<commit_before>/*
 * Copyright (C) 2014 TopCoder Inc., All Rights Reserved.
 */

'use strict';

var angular = require('angular');
require('jquery-knob');

module.exports = angular.module('broker.directives', [])
  // custom select control
  .directive('dropDown', [function() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        $(element).click(function() {

          var dropDownActiveEl = $(".drop-down-active");

          dropDownActiveEl.removeClass("drop-down-active");
          $(this).next().addClass("drop-down-active");
          $(".drop-down-box:not(.drop-down-active)").hide();
          dropDownActiveEl.toggle();
          if (attrs.fixArrow) {
            var w = $(element).width() - 16;
            $('.drop-down-active .icon-arrow').css({left: w + "px"});
          }
          return false;
        });
      }
    };
  }])
  // expand menu item in left sidebar
  .directive('expandArrow', [function() {
    return {
      restrict: 'A',
      link: function(scope, element) {
        var $ele = $(element);
        $ele.find(".arrows").click(function() {
          $ele.toggleClass("current");
          if ($ele.hasClass("current")) {
            $(this).removeClass("arrow-right").addClass("arrow-down");
          } else {
            $(this).removeClass("arrow-down").addClass("arrow-right");
          }
        });
      }
    };
  }])
  // fix left sidebar height
  .directive('fixSidebar', ["fixSidebar", function(fixSidebar) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        scope.$watch(function() {
          return $(element).height();
        }, function(newValue, oldValue) {
          if (newValue !== oldValue) {
            fixSidebar();
          }
        });
        element.ready(function() {
          fixSidebar();
        });
      }
    };
  }])
  // set proper class to main content if sidebar is expanded or collapsed
  .directive('setWidth', ["$rootScope", function($rootScope) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        var checkClass = function() {
          if ($rootScope.sideBarExpanded) {
            $(element).addClass("left-184").removeClass("left-74");
          } else {
            $(element).removeClass("left-184").addClass("left-74");
          }
        };
        checkClass();
        $rootScope.$watch("sideBarExpanded", function(oldVal, newVal) {
          if (oldVal !== newVal) {
            checkClass();
          }
        });
      }
    };
  }])
  // expand or collapse left sidebar after arrow click
  .directive('toggleSidebar', ["$rootScope", function($rootScope) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        var $ele = $(element);
        $ele.find(".side-arrow").click(function() {
          $ele.toggleClass('absolute-nav');
          if ($ele.hasClass("absolute-nav")) {
            $ele.find("ul li").removeClass("current");
            $ele.find("ul li a.li-links span.arrow-down")
              .removeClass("arrow-down")
              .addClass("arrow-right");
            $rootScope.sideBarExpanded = false;
          } else {
            $rootScope.sideBarExpanded = true;
          }
          $rootScope.$apply();
        });
      }
    };
  }])
  // iterate through all boxes and fix height
  .directive('fixBoxesHeight', [function() {
    return {
      restrict: 'A',
      link: function(scope, element) {
        element.ready(function() {
          var maxHeight = 0,
            $boxes = $(element).find('.boxes');
          $boxes.each(function() {
            maxHeight = Math.max(maxHeight, $(this).height());
          });
          $boxes.height(maxHeight);
        });
      }
    };
  }])
  // display table with project orders
  .directive('ordersTable', [function($templateCache) {
    return {
      restrict: 'E',
      scope: {
        orders: "="
      },
      templateUrl: '/partials/common/orders-table.html'
    };
  }])
  // display box with service details
  .directive('serviceBox', [function($templateCache) {
    return {
      restrict: 'E',
      scope: {
        service: "="
      },
      templateUrl: '/partials/common/service-box.html'
    };
  }])
  // show grid or list view
  .directive('switchViewButtons', ["fixSidebar", function(fixSidebar) {
    return {
      restrict: 'E',
      template: [
        '',
        '',
        '',
        ''
      ].join(""),
      scope: {
        gridView: "=",
        listView: "="
      },
      link: function(scope, element) {
        scope.showList = function() {
          $(scope.gridView).hide();
          $(scope.listView).show();
          $(element).find(".js-list-btn").addClass('btn-active');
          $(element).find(".js-grid-btn").removeClass('btn-active');
          fixSidebar();
        };
        scope.showGrid = function() {
          $(scope.gridView).show();
          $(scope.listView).hide();
          $(element).find(".js-grid-btn").addClass('btn-active');
          $(element).find(".js-list-btn").removeClass('btn-active');
          fixSidebar();
        };
      }
    };
  }])
  // show category (blue print, webservices, applications) in marketplace view
  .directive('marketplaceItems', [function($templateCache) {
    return {
      restrict: 'E',
      templateUrl: '/partials/common/marketplace-items.html',
      transclude: true,
      scope: {
        items: "="
      },
      link: function(scope) {
        scope.tab = "featured";
      }
    };
  }])
  // popup with X icon for dashboard
  .directive('alertPopup', ["fixSidebar", function(fixSidebar) {
    return {
      restrict: 'E',
      scope: {
        msg: "="
      },
      transclude: true,
      template: '

',
      link: function(scope, element) {
        $(element).find('.close').click(function() {
          $(element).remove();
          fixSidebar();
        });
      }
    };
  }])
  // animate graphs
  .directive('animateKnob', ["$interval", function($interval) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        element.ready(function() {
          var $element = $(element);
          var intervalId = null;
          var animate = function() {
            var targetValue = parseInt($element.attr("data-target-value"));
            if (!targetValue) {
              return;
            }
            $element.knob({
              'draw': function() {
                var $this = $(this.i);
                $this.val(this.cv + '%');
                $this.css({
                  "font-family": "SourceSansPro_Regular",
                  "font-size": "42px",
                  "color": "#0a4684",
                  "font-weight": "normal",
                  "display": "inline-block"
                });
                $this.on("focus", function() {
                  $this.parent().click();
                });
              }
            });
            if (intervalId) {
              $interval.cancel(intervalId);
              intervalId = null;
            }
            var currentValue = 0;
            intervalId = $interval(function() {
              currentValue += 1;
              $element.val(currentValue).trigger('change');
              if (currentValue === targetValue) {
                $interval.cancel(intervalId);
                intervalId = null;
              }
              if (currentValue === 100) {
                $element.css({
                  "width": "101px",
                  "margin-left": "-127px"
                });
              }
            }, 10);
          };
          animate();
          scope.$watch("selectedStatistic", function(newValue, oldValue) {
            if (newValue !== oldValue) {
              animate();
            }
          });
        });
      }
    };
  }]);<commit_msg>Switch to watch for assignments to animate<commit_after>/*
 * Copyright (C) 2014 TopCoder Inc., All Rights Reserved.
 */

'use strict';

var angular = require('angular');
require('jquery-knob');

module.exports = angular.module('broker.directives', [])
  // custom select control
  .directive('dropDown', [function() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        $(element).click(function() {

          var dropDownActiveEl = $(".drop-down-active");

          dropDownActiveEl.removeClass("drop-down-active");
          $(this).next().addClass("drop-down-active");
          $(".drop-down-box:not(.drop-down-active)").hide();
          dropDownActiveEl.toggle();
          if (attrs.fixArrow) {
            var w = $(element).width() - 16;
            $('.drop-down-active .icon-arrow').css({left: w + "px"});
          }
          return false;
        });
      }
    };
  }])
  // expand menu item in left sidebar
  .directive('expandArrow', [function() {
    return {
      restrict: 'A',
      link: function(scope, element) {
        var $ele = $(element);
        $ele.find(".arrows").click(function() {
          $ele.toggleClass("current");
          if ($ele.hasClass("current")) {
            $(this).removeClass("arrow-right").addClass("arrow-down");
          } else {
            $(this).removeClass("arrow-down").addClass("arrow-right");
          }
        });
      }
    };
  }])
  // fix left sidebar height
  .directive('fixSidebar', ["fixSidebar", function(fixSidebar) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        scope.$watch(function() {
          return $(element).height();
        }, function(newValue, oldValue) {
          if (newValue !== oldValue) {
            fixSidebar();
          }
        });
        element.ready(function() {
          fixSidebar();
        });
      }
    };
  }])
  // set proper class to main content if sidebar is expanded or collapsed
  .directive('setWidth', ["$rootScope", function($rootScope) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        var checkClass = function() {
          if ($rootScope.sideBarExpanded) {
            $(element).addClass("left-184").removeClass("left-74");
          } else {
            $(element).removeClass("left-184").addClass("left-74");
          }
        };
        checkClass();
        $rootScope.$watch("sideBarExpanded", function(oldVal, newVal) {
          if (oldVal !== newVal) {
            checkClass();
          }
        });
      }
    };
  }])
  // expand or collapse left sidebar after arrow click
  .directive('toggleSidebar', ["$rootScope", function($rootScope) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        var $ele = $(element);
        $ele.find(".side-arrow").click(function() {
          $ele.toggleClass('absolute-nav');
          if ($ele.hasClass("absolute-nav")) {
            $ele.find("ul li").removeClass("current");
            $ele.find("ul li a.li-links span.arrow-down")
              .removeClass("arrow-down")
              .addClass("arrow-right");
            $rootScope.sideBarExpanded = false;
          } else {
            $rootScope.sideBarExpanded = true;
          }
          $rootScope.$apply();
        });
      }
    };
  }])
  // iterate through all boxes and fix height
  .directive('fixBoxesHeight', [function() {
    return {
      restrict: 'A',
      link: function(scope, element) {
        element.ready(function() {
          var maxHeight = 0,
            $boxes = $(element).find('.boxes');
          $boxes.each(function() {
            maxHeight = Math.max(maxHeight, $(this).height());
          });
          $boxes.height(maxHeight);
        });
      }
    };
  }])
  // display table with project orders
  .directive('ordersTable', [function($templateCache) {
    return {
      restrict: 'E',
      scope: {
        orders: "="
      },
      templateUrl: '/partials/common/orders-table.html'
    };
  }])
  // display box with service details
  .directive('serviceBox', [function($templateCache) {
    return {
      restrict: 'E',
      scope: {
        service: "="
      },
      templateUrl: '/partials/common/service-box.html'
    };
  }])
  // show grid or list view
  .directive('switchViewButtons', ["fixSidebar", function(fixSidebar) {
    return {
      restrict: 'E',
      template: [
        '',
        '',
        '',
        ''
      ].join(""),
      scope: {
        gridView: "=",
        listView: "="
      },
      link: function(scope, element) {
        scope.showList = function() {
          $(scope.gridView).hide();
          $(scope.listView).show();
          $(element).find(".js-list-btn").addClass('btn-active');
          $(element).find(".js-grid-btn").removeClass('btn-active');
          fixSidebar();
        };
        scope.showGrid = function() {
          $(scope.gridView).show();
          $(scope.listView).hide();
          $(element).find(".js-grid-btn").addClass('btn-active');
          $(element).find(".js-list-btn").removeClass('btn-active');
          fixSidebar();
        };
      }
    };
  }])
  // show category (blue print, webservices, applications) in marketplace view
  .directive('marketplaceItems', [function($templateCache) {
    return {
      restrict: 'E',
      templateUrl: '/partials/common/marketplace-items.html',
      transclude: true,
      scope: {
        items: "="
      },
      link: function(scope) {
        scope.tab = "featured";
      }
    };
  }])
  // popup with X icon for dashboard
  .directive('alertPopup', ["fixSidebar", function(fixSidebar) {
    return {
      restrict: 'E',
      scope: {
        msg: "="
      },
      transclude: true,
      template: '

',
      link: function(scope, element) {
        $(element).find('.close').click(function() {
          $(element).remove();
          fixSidebar();
        });
      }
    };
  }])
  // animate graphs
  .directive('animateKnob', ["$interval", function($interval) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        element.ready(function() {
          var $element = $(element);
          var intervalId = null;
          var animate = function() {
            var targetValue = parseInt($element.attr("data-target-value"));
            if (!targetValue) {
              return;
            }
            $element.knob({
              'draw': function() {
                var $this = $(this.i);
                $this.val(this.cv + '%');
                $this.css({
                  "font-family": "SourceSansPro_Regular",
                  "font-size": "42px",
                  "color": "#0a4684",
                  "font-weight": "normal",
                  "display": "inline-block"
                });
                $this.on("focus", function() {
                  $this.parent().click();
                });
              }
            });
            if (intervalId) {
              $interval.cancel(intervalId);
              intervalId = null;
            }
            var currentValue = 0;
            intervalId = $interval(function() {
              currentValue += 1;
              $element.val(currentValue).trigger('change');
              if (currentValue === targetValue) {
                $interval.cancel(intervalId);
                intervalId = null;
              }
              if (currentValue === 100) {
                $element.css({
                  "width": "101px",
                  "margin-left": "-127px"
                });
              }
            }, 10);
          };
          scope.$watch("selectedStatistic", function(newValue, oldValue) {
            if (newValue !== oldValue) {
              animate();
            }
          });
          scope.$watch("assignments", function() {
            animate();
          });

        });
      }
    };
  }]);<|endoftext|>


<commit_before>// Module includes
var http = require("http");
var restify = require("restify");
var Slack = require("node-slack");
var npmPackage = require("../package");

// Function forward declarations
var stripCommand, makeQuery, constructError, constructResponse;

// App config
var domain = process.env.DOMAIN;
var token = process.env.TOKEN;
var port = process.env.PORT;

// List of webhook enabled commands (setup from Slack)
var commands = {};

// Create the slack instance to send/receive messages
var slack = new Slack(domain, token);

// Create the http server
var server = restify.createServer({
	name: npmPackage.name,
	version: npmPackage.version
});
server.use(restify.bodyParser());

// Listen for all of the command hooks
server.post("/:command", function(req, res, next) {
	var command = req.params.command;

	console.log("Handling command: '%s'.", command);

	slack.respond(req.params, function(hook) {
		console.log("Hook details: %j", hook);

		// Callback once a response has been constructed
		var cb = function(reply) {
			console.log("Sending reply: %j", reply);
			res.send(reply);
		};

		// Try to find an appropriate command handler for the request
		var handler = commands[command];

		if (handler) {
			console.log("Found handler for command '%s'.", command);
			hook.text = stripCommand(command, hook.text);
			handler(hook, cb);
		} else {
			console.warn("No handler found for command: '%s'", command);
			cb(constructError(hook, "Command not found: '%s'.", command));
		}
	});
});

server.listen(port, function() {
	console.log("Server started on port %d.", port);
});

// Command handlers

commands["wiki"] = function(hook, cb) {
	makeQuery("opensearch", {
		search: hook.text,
		limit: 1,
		redirects: "resolve",
		format: "json"
	}, function(error, res) {
		if (error) {
			cb(constructError(hook, error));
		} else {
			if (res.length > 0 && res[0].length > 0) {
				cb(constructResponse(res, 0));
			} else {
				cb(constructError(hook, "Could not find any results for: '%s'.", hook.text));
			}
		}
	});
};

// Functions

stripCommand = function(command, text) {
	return text.substr(command.length);
};

makeQuery = function(action, params, cb) {
	// Construct the API query string
	var query = "http://en.wikipedia.org/w/api.php?action=" + action;
	for (var key in params) {
		query += "&" + key + "=" + encodeURIComponent(params[key]);
	}

	console.log("Making API call to wikipedia: %s", query);

	// Make the http request
	http.get(query, function(res) {
		cb(null, res);
	}).on("error", function(e) {
		console.error("Error making wikipedia request: '%s' %j", action, params);
		console.error(e);
		cb("Error making HTTP request: %d - %s.", res.statusCode, e.message);
	});
};

constructError = function(hook, message) {
	return {
		text: "Sorry, " + hook.hook._user_name + ", I can't process that request because of this error: " + message
	};
};

constructResponse = function(res, idx) {
	return {
		text: util.format("%s - \"%s\"... %s", res[0][idx], res[1][idx], res[2][idx])
	};
};
<commit_msg>Misspelled user_name property<commit_after>// Module includes
var http = require("http");
var restify = require("restify");
var Slack = require("node-slack");
var npmPackage = require("../package");

// Function forward declarations
var stripCommand, makeQuery, constructError, constructResponse;

// App config
var domain = process.env.DOMAIN;
var token = process.env.TOKEN;
var port = process.env.PORT;

// List of webhook enabled commands (setup from Slack)
var commands = {};

// Create the slack instance to send/receive messages
var slack = new Slack(domain, token);

// Create the http server
var server = restify.createServer({
	name: npmPackage.name,
	version: npmPackage.version
});
server.use(restify.bodyParser());

// Listen for all of the command hooks
server.post("/:command", function(req, res, next) {
	var command = req.params.command;

	console.log("Handling command: '%s'.", command);

	slack.respond(req.params, function(hook) {
		console.log("Hook details: %j", hook);

		// Callback once a response has been constructed
		var cb = function(reply) {
			console.log("Sending reply: %j", reply);
			res.send(reply);
		};

		// Try to find an appropriate command handler for the request
		var handler = commands[command];

		if (handler) {
			console.log("Found handler for command '%s'.", command);
			hook.text = stripCommand(command, hook.text);
			handler(hook, cb);
		} else {
			console.warn("No handler found for command: '%s'", command);
			cb(constructError(hook, "Command not found: '%s'.", command));
		}
	});
});

server.listen(port, function() {
	console.log("Server started on port %d.", port);
});

// Command handlers

commands["wiki"] = function(hook, cb) {
	makeQuery("opensearch", {
		search: hook.text,
		limit: 1,
		redirects: "resolve",
		format: "json"
	}, function(error, res) {
		if (error) {
			cb(constructError(hook, error));
		} else {
			if (res.length > 0 && res[0].length > 0) {
				cb(constructResponse(res, 0));
			} else {
				cb(constructError(hook, "Could not find any results for: '%s'.", hook.text));
			}
		}
	});
};

// Functions

stripCommand = function(command, text) {
	return text.substr(command.length);
};

makeQuery = function(action, params, cb) {
	// Construct the API query string
	var query = "http://en.wikipedia.org/w/api.php?action=" + action;
	for (var key in params) {
		query += "&" + key + "=" + encodeURIComponent(params[key]);
	}

	console.log("Making API call to wikipedia: %s", query);

	// Make the http request
	http.get(query, function(res) {
		cb(null, res);
	}).on("error", function(e) {
		console.error("Error making wikipedia request: '%s' %j", action, params);
		console.error(e);
		cb("Error making HTTP request: %d - %s.", res.statusCode, e.message);
	});
};

constructError = function(hook, message) {
	return {
		text: "Sorry, " + hook.hook.user_name + ", I can't process that request because of this error: " + message
	};
};

constructResponse = function(res, idx) {
	return {
		text: util.format("%s - \"%s\"... %s", res[0][idx], res[1][idx], res[2][idx])
	};
};
<|endoftext|>


<commit_before>/**
 * Hoodie plugin chat
 * Lightweight and easy chat
 */

/* global Hoodie */

Hoodie.extend(function (hoodie) {
  'use strict';
  var _talks = {};

  var genFake = function (profile, talks) {
    if (profile.id !== hoodie.id()) {
      talks['fake-' + profile.id] = {
        profile: profile
      };
    }
  };

  var cleanFake = function (talk, talks) {
    talk.exclusive.map(function (userId) {
      if (userId !== hoodie.id()) {
        talk.profile = talk.profiles[userId];
        talks[talk.id] = talk;
        delete talks['fake-' + userId];
      }
    });
  };

  hoodie.store.on('profile:add', function (profile) {
    genFake(profile, _talks);
    hoodie.trigger('ontalk', _talks);
  });

  hoodie.store.on('talk:add', function (talk) {
    cleanFake(talk, _talks);
    hoodie.trigger('ontalk', _talks);
  });

  hoodie.store.on('message:add', function (message) {
    if (!!_talks && _talks[message.talkId]) {
      _talks[message.talkId].messages = _talks[message.talkId].messages || [];
      _talks[message.talkId].messages.push(message);
    }
    if (message.talkId === hoodie.chat.currentTalk.id)
      hoodie.trigger('onmessage', message);
  });

  hoodie.chat = {

    currentTalk: null,
    pubsubtypes: ['talk', 'message'],

    getProfile: function (userId) {
      var defer = window.jQuery.Deferred();
      defer.notify('getProfile', arguments, false);
      hoodie.profile.get(userId)
        .then(defer.resolve)
        .fail(defer.reject);
      return defer.promise();
    },
    setCurrentTalk: function (talk) {
      var defer = window.jQuery.Deferred();
      defer.notify('getProfile', arguments, false);
      hoodie.chat.currentTalk = talk;
      defer.resolve(talk);
      return defer.promise();
    },

    talk: function (userId) {
      var defer = window.jQuery.Deferred();
      defer.notify('talk', arguments, false);

      hoodie.remote.sync();
      var participants = [ userId, hoodie.id() ];
      hoodie.profile.getAsObjects(participants)
        .then(function (profiles) {
          var chat = {
            userId: hoodie.id(),
            exclusive: participants,
            profiles: profiles
          };

          hoodie.pubsub.bidirectional(userId, hoodie.chat.pubsubtypes)
            .then(function () {
              hoodie.store.add('talk', chat)
                .then(function (talk) {
                  hoodie.chat.currentTalk = talk;
                  defer.resolve(talk);
                })
                .fail(defer.reject);
            })
            .fail(function (err) {
              if (err.err !== 'You already subscribed.')
                defer.reject(err);
              else
                hoodie.chat.getTalkByUserId(userId)
                .then(function (talk) {
                  hoodie.chat.currentTalk = talk;
                  defer.resolve(talk);
                })
                .fail(defer.reject);
            });
        })
        .fail(defer.reject);

      return defer.promise();
    },
    deleteTalk: function (id) {
      var defer = window.jQuery.Deferred();
      defer.notify('deleteTalk', arguments, false);
      if (!id) {
        hoodie.store.removeAll('talk')
          .then(defer.resolve)
          .fail(defer.reject);
      } else {
        hoodie.store.remove('talk', id)
          .then(defer.resolve)
          .fail(defer.reject);
      }
      return defer.promise();
    },
    feed: function () {
      var defer = window.jQuery.Deferred();
      defer.notify('feed', arguments, false);
      var result = {};
      hoodie.store.findAll('profile')
        .then(function (profiles) {
          profiles.map(function (profile) {
            genFake(profile, result);
          });
          return hoodie.store.findAll('talk');
        })
        .then(function (talks) {
          talks.map(function (_talk) {
            cleanFake(_talk, result);
          });
          defer.resolve(result);
        })
        .fail(defer.reject);

      return defer.promise();
    },
    message: function (talkObject, messageObject) {
      var defer = window.jQuery.Deferred();
      defer.notify('message', arguments, false);

      messageObject.talkId = talkObject.id;
      messageObject.exclusive = talkObject.exclusive;
      messageObject.userId = hoodie.id();

      hoodie.store.add('message', messageObject)
        .then(defer.resolve)
        .fail(defer.reject);
      return defer.promise();
    },
    setMessages: function (talkId, talk) {
      var defer = window.jQuery.Deferred();
      defer.notify('setMessages', arguments, false);
      hoodie.chat.getMessages(talkId)
        .then(function (messages) {
          talk.messages = messages;
          defer.resolve(talk);
        })
        .fail(defer.reject);
      return defer.promise();
    },
    getMessages: function (talkId) {
      var defer = window.jQuery.Deferred();
      defer.notify('getMessages', arguments, false);
      hoodie.store.findAll('message')
        .then(function (messages) {
          var filteredMessages = messages.filter(function (message) {
            return (message.talkId === talkId);
          })
          .reverse();
          defer.resolve(filteredMessages);
        })
        .fail(function () {
          defer.resolve([]);
        });
      return defer.promise();
    },
    getTalk: function (talkId) {
      var defer = window.jQuery.Deferred();
      defer.notify('getTalk', arguments, false);
      hoodie.store.find('talk', talkId)
        .then(function (talk) {
          return hoodie.chat.setMessages(talkId, talk);
        })
        .then(function (talk) {
          hoodie.chat.currentTalk = talk;
          defer.resolve(talk);
        })
        .fail(defer.reject);
      return defer.promise();
    },
    getTalkByUserId: function (userId) {
      var defer = window.jQuery.Deferred();
      defer.notify('getTalkByUserId', arguments, false);
      var find = false;
      hoodie.store.findAll('talk')
        .then(function (talks) {
          var talk = talks.filter(function (_talk) {

            return _talk.exclusive
              .map(function (v) {
                return (v === userId);
              })
              .reduce(function (b, c) {
                return b || c;
              }, false);

          });
          if (talk.length > 0) {
            hoodie.chat.setMessages(talk.id, talk)
              .then(function (talk) {
                hoodie.chat.currentTalk = talk;
                defer.resolve(talk);
              })
              .fail(defer.reject);
          } else {
            defer.reject('chat not found');
          }
        })
        .fail(defer.reject);
      return defer.promise();
    },
    onTalk: function (cb) {
      hoodie.on('ontalk', cb);
    },
    onMessage: function (cb) {
      hoodie.on('onmessage', cb);
    }
  };

  // var debugPromisseGstart = function (text) {
  //   var defer = window.jQuery.Deferred();
  //   (window.debug === 'chat') && console.groupCollapsed(text);
  //   defer.resolve({});
  //   return defer.promise();
  // };

  // var debugPromisseGend = function () {
  //   var defer = window.jQuery.Deferred();
  //   (window.debug === 'chat') && console.groupEnd();
  //   defer.resolve({});
  //   return defer.promise();
  // };

  function out(name, obj, task) {
    if (window.debug === 'chat') {
      var group = (task) ? 'task: ' + task + '(' + name + ')': 'method: ' + name;

      console.groupCollapsed(group);
      if (!!obj)
        console.table(obj);
      console.groupEnd();
    }
  }

  if (window.debug === 'chat') {
    hoodie.task.on('start', function () {
      out('start', arguments[0], arguments[0].type);
    });

    // task aborted
    hoodie.task.on('abort', function () {
      out('abort', arguments[0], arguments[0].type);
    });

    // task could not be completed
    hoodie.task.on('error', function () {
      out('error', arguments, arguments[1].type);
    });

    // task completed successfully
    hoodie.task.on('success', function () {
      out('success', arguments[0], arguments[0].type);
    });
  }
});
<commit_msg>treat object<commit_after>/**
 * Hoodie plugin chat
 * Lightweight and easy chat
 */

/* global Hoodie */

Hoodie.extend(function (hoodie) {
  'use strict';
  var _talks = {};

  var genFake = function (profile, talks) {
    if (profile.id !== hoodie.id()) {
      talks['fake-' + profile.id] = {
        profile: profile
      };
    }
  };

  var cleanFake = function (talk, talks) {
    talk.exclusive.map(function (userId) {
      if (userId !== hoodie.id()) {
        talk.profile = talk.profiles[userId];
        talks[talk.id] = talk;
        delete talks['fake-' + userId];
      }
    });
  };

  hoodie.store.on('profile:add', function (profile) {
    genFake(profile, _talks);
    hoodie.trigger('ontalk', _talks);
  });

  hoodie.store.on('talk:add', function (talk) {
    cleanFake(talk, _talks);
    hoodie.trigger('ontalk', _talks);
  });

  hoodie.store.on('message:add', function (message) {
    if (!!_talks && _talks[message.talkId]) {
      _talks[message.talkId].messages = _talks[message.talkId].messages || [];
      _talks[message.talkId].messages.push(message);
    }
    if (hoodie.chat.currentTalk && message.talkId === hoodie.chat.currentTalk.id)
      hoodie.trigger('onmessage', message);
  });

  hoodie.chat = {

    currentTalk: null,
    pubsubtypes: ['talk', 'message'],

    getProfile: function (userId) {
      var defer = window.jQuery.Deferred();
      defer.notify('getProfile', arguments, false);
      hoodie.profile.get(userId)
        .then(defer.resolve)
        .fail(defer.reject);
      return defer.promise();
    },
    setCurrentTalk: function (talk) {
      var defer = window.jQuery.Deferred();
      defer.notify('getProfile', arguments, false);
      hoodie.chat.currentTalk = talk;
      defer.resolve(talk);
      return defer.promise();
    },

    talk: function (userId) {
      var defer = window.jQuery.Deferred();
      defer.notify('talk', arguments, false);

      hoodie.remote.sync();
      var participants = [ userId, hoodie.id() ];
      hoodie.profile.getAsObjects(participants)
        .then(function (profiles) {
          var chat = {
            userId: hoodie.id(),
            exclusive: participants,
            profiles: profiles
          };

          hoodie.pubsub.bidirectional(userId, hoodie.chat.pubsubtypes)
            .then(function () {
              hoodie.store.add('talk', chat)
                .then(function (talk) {
                  hoodie.chat.currentTalk = talk;
                  defer.resolve(talk);
                })
                .fail(defer.reject);
            })
            .fail(function (err) {
              if (err.err !== 'You already subscribed.')
                defer.reject(err);
              else
                hoodie.chat.getTalkByUserId(userId)
                .then(function (talk) {
                  hoodie.chat.currentTalk = talk;
                  defer.resolve(talk);
                })
                .fail(defer.reject);
            });
        })
        .fail(defer.reject);

      return defer.promise();
    },
    deleteTalk: function (id) {
      var defer = window.jQuery.Deferred();
      defer.notify('deleteTalk', arguments, false);
      if (!id) {
        hoodie.store.removeAll('talk')
          .then(defer.resolve)
          .fail(defer.reject);
      } else {
        hoodie.store.remove('talk', id)
          .then(defer.resolve)
          .fail(defer.reject);
      }
      return defer.promise();
    },
    feed: function () {
      var defer = window.jQuery.Deferred();
      defer.notify('feed', arguments, false);
      var result = {};
      hoodie.store.findAll('profile')
        .then(function (profiles) {
          profiles.map(function (profile) {
            genFake(profile, result);
          });
          return hoodie.store.findAll('talk');
        })
        .then(function (talks) {
          talks.map(function (_talk) {
            cleanFake(_talk, result);
          });
          defer.resolve(result);
        })
        .fail(defer.reject);

      return defer.promise();
    },
    message: function (talkObject, messageObject) {
      var defer = window.jQuery.Deferred();
      defer.notify('message', arguments, false);

      messageObject.talkId = talkObject.id;
      messageObject.exclusive = talkObject.exclusive;
      messageObject.userId = hoodie.id();

      hoodie.store.add('message', messageObject)
        .then(defer.resolve)
        .fail(defer.reject);
      return defer.promise();
    },
    setMessages: function (talkId, talk) {
      var defer = window.jQuery.Deferred();
      defer.notify('setMessages', arguments, false);
      hoodie.chat.getMessages(talkId)
        .then(function (messages) {
          talk.messages = messages;
          defer.resolve(talk);
        })
        .fail(defer.reject);
      return defer.promise();
    },
    getMessages: function (talkId) {
      var defer = window.jQuery.Deferred();
      defer.notify('getMessages', arguments, false);
      hoodie.store.findAll('message')
        .then(function (messages) {
          var filteredMessages = messages.filter(function (message) {
            return (message.talkId === talkId);
          })
          .reverse();
          defer.resolve(filteredMessages);
        })
        .fail(function () {
          defer.resolve([]);
        });
      return defer.promise();
    },
    getTalk: function (talkId) {
      var defer = window.jQuery.Deferred();
      defer.notify('getTalk', arguments, false);
      hoodie.store.find('talk', talkId)
        .then(function (talk) {
          return hoodie.chat.setMessages(talkId, talk);
        })
        .then(function (talk) {
          hoodie.chat.currentTalk = talk;
          defer.resolve(talk);
        })
        .fail(defer.reject);
      return defer.promise();
    },
    getTalkByUserId: function (userId) {
      var defer = window.jQuery.Deferred();
      defer.notify('getTalkByUserId', arguments, false);
      var find = false;
      hoodie.store.findAll('talk')
        .then(function (talks) {
          var talk = talks.filter(function (_talk) {

            return _talk.exclusive
              .map(function (v) {
                return (v === userId);
              })
              .reduce(function (b, c) {
                return b || c;
              }, false);

          });
          if (talk.length > 0) {
            hoodie.chat.setMessages(talk.id, talk)
              .then(function (talk) {
                hoodie.chat.currentTalk = talk;
                defer.resolve(talk);
              })
              .fail(defer.reject);
          } else {
            defer.reject('chat not found');
          }
        })
        .fail(defer.reject);
      return defer.promise();
    },
    onTalk: function (cb) {
      hoodie.on('ontalk', cb);
    },
    onMessage: function (cb) {
      hoodie.on('onmessage', cb);
    }
  };

  // var debugPromisseGstart = function (text) {
  //   var defer = window.jQuery.Deferred();
  //   (window.debug === 'chat') && console.groupCollapsed(text);
  //   defer.resolve({});
  //   return defer.promise();
  // };

  // var debugPromisseGend = function () {
  //   var defer = window.jQuery.Deferred();
  //   (window.debug === 'chat') && console.groupEnd();
  //   defer.resolve({});
  //   return defer.promise();
  // };

  function out(name, obj, task) {
    if (window.debug === 'chat') {
      var group = (task) ? 'task: ' + task + '(' + name + ')': 'method: ' + name;

      console.groupCollapsed(group);
      if (!!obj)
        console.table(obj);
      console.groupEnd();
    }
  }

  if (window.debug === 'chat') {
    hoodie.task.on('start', function () {
      out('start', arguments[0], arguments[0].type);
    });

    // task aborted
    hoodie.task.on('abort', function () {
      out('abort', arguments[0], arguments[0].type);
    });

    // task could not be completed
    hoodie.task.on('error', function () {
      out('error', arguments, arguments[1].type);
    });

    // task completed successfully
    hoodie.task.on('success', function () {
      out('success', arguments[0], arguments[0].type);
    });
  }
});
<|endoftext|>


<commit_before>var source = './src/',
    assets = 'assets/',
    components = './../components-development-submodule/',
    build = './build/',
    bowerFiles = './bower_components/',
    npmFiles = './node_modules',
    compile = './compile/',
    index = 'index.html',
    root = __dirname,
    gulp_dir = './gulp/',
    fs = require('fs');

module.exports = {
    bowerFiles: bowerFiles,
    npmFiles: npmFiles,
    src: source,
    build: build,
    compile: compile,
    assets: assets,
    appCss: assets + 'styles/',
    appFonts: assets + 'fonts/',
    appImages: assets + 'images',
    root: root,
    gulp: gulp_dir,
    index: source + index,
    styles: [
        source + '**/*.css',
        source + '**/*.less'
    ],
    templates: [
        '!' + source + index,
        source + 'app/**/*.html'
    ],
    scripts: [
        source + 'app/**/*.js',
        '!' + source + '**/*.spec.js',
        '!' + source + '**/*.test.js'
    ],
    components: {
        dir: components,
        scripts: [
            components + '**/*.js',
            '!' + components + '**/*.spec.js',
            '!' + components + '**/*.test.js'
        ],
        templates: components + '**/*.html',
        styles: {
            less: components + '**/*.less',
            css: components + '**/*.css'
        }
    },
    appFiles: [
        build + '**/app.js',
        build + '**/*.js',
        build + '**/*.css',
        source + '**/*.css'
    ],
    wrapper: {
        header: '(function() {\n"use strict";\n',
        footer: '}());'
    },
    templateCacheSettings: {
        standalone: false,
        moduleSystem: 'IIFE',
        module: 'orderCloud'
    },
    ngConstantSettings: {
        name: 'orderCloud',
        deps: false,
        constants: getConstants()
    },
    autoprefixerSettings: {
        browsers: ['last 2 versions'],
        cascade: true
    },
    jsCache: 'jsscripts',
    indentSize: 4
};

function getConstants() {
    var result = {};
    var constants = JSON.parse(fs.readFileSync(source + 'app/app.config.json'));
    var environment = process.env.environment || constants.environment;
    switch (environment) {
        case 'local':
            result.authurl = 'http://core.four51.com:11629/oauth/token';
            result.apiurl = 'http://core.four51.com:9002';
            break;
        case 'test':
            result.authurl = 'https://testauth.ordercloud.io/oauth/token';
            result.apiurl = 'https://testapi.ordercloud.io';
            break;
        case 'qa':
            result.authurl = 'https://qaauth.ordercloud.io/oauth/token';
            result.apiurl = 'https://qaapi.ordercloud.io';
            break;
        default:
            result.authurl = 'https://auth.ordercloud.io/oauth/token';
            result.apiurl = 'https://api.ordercloud.io';
            break;
    }
    if (process.env.apiurl && process.env.authurl) {
        result.authurl = process.env.authurl;
        result.apiurl = process.env.apiurl;
    }
    else if (!environment && !process.env.apiurl && !process.env.authurl) {
        result.authurl = 'https://auth.ordercloud.io/oauth/token';
        result.apiurl = 'https://api.ordercloud.io';
    }
    if (process.env.clientid) result.clientid = process.env.clientid;
    if (process.env.appname) result.appname = process.env.appname;
    if (process.env.ocscope) result.ocscope = process.env.ocscope;
    if (process.env.buyerid) result.buyerid = process.env.buyerid;
    return result;
}
<commit_msg>image updates<commit_after>var source = './src/',
    assets = 'assets/',
    components = './../components-development-submodule/',
    build = './build/',
    bowerFiles = './bower_components/',
    npmFiles = './node_modules',
    compile = './compile/',
    index = 'index.html',
    root = __dirname,
    gulp_dir = './gulp/',
    fs = require('fs');

module.exports = {
    bowerFiles: bowerFiles,
    npmFiles: npmFiles,
    src: source,
    build: build,
    compile: compile,
    assets: assets,
    appCss: assets + 'styles/',
    appFonts: assets + 'fonts/',
    appImages: assets + 'images/',
    root: root,
    gulp: gulp_dir,
    index: source + index,
    styles: [
        source + '**/*.css',
        source + '**/*.less'
    ],
    templates: [
        '!' + source + index,
        source + 'app/**/*.html'
    ],
    scripts: [
        source + 'app/**/*.js',
        '!' + source + '**/*.spec.js',
        '!' + source + '**/*.test.js'
    ],
    components: {
        dir: components,
        scripts: [
            components + '**/*.js',
            '!' + components + '**/*.spec.js',
            '!' + components + '**/*.test.js'
        ],
        templates: components + '**/*.html',
        styles: {
            less: components + '**/*.less',
            css: components + '**/*.css'
        }
    },
    appFiles: [
        build + '**/app.js',
        build + '**/*.js',
        build + '**/*.css',
        source + '**/*.css'
    ],
    wrapper: {
        header: '(function() {\n"use strict";\n',
        footer: '}());'
    },
    templateCacheSettings: {
        standalone: false,
        moduleSystem: 'IIFE',
        module: 'orderCloud'
    },
    ngConstantSettings: {
        name: 'orderCloud',
        deps: false,
        constants: getConstants()
    },
    autoprefixerSettings: {
        browsers: ['last 2 versions'],
        cascade: true
    },
    jsCache: 'jsscripts',
    indentSize: 4
};

function getConstants() {
    var result = {};
    var constants = JSON.parse(fs.readFileSync(source + 'app/app.config.json'));
    var environment = process.env.environment || constants.environment;
    switch (environment) {
        case 'local':
            result.authurl = 'http://core.four51.com:11629/oauth/token';
            result.apiurl = 'http://core.four51.com:9002';
            break;
        case 'test':
            result.authurl = 'https://testauth.ordercloud.io/oauth/token';
            result.apiurl = 'https://testapi.ordercloud.io';
            break;
        case 'qa':
            result.authurl = 'https://qaauth.ordercloud.io/oauth/token';
            result.apiurl = 'https://qaapi.ordercloud.io';
            break;
        default:
            result.authurl = 'https://auth.ordercloud.io/oauth/token';
            result.apiurl = 'https://api.ordercloud.io';
            break;
    }
    if (process.env.apiurl && process.env.authurl) {
        result.authurl = process.env.authurl;
        result.apiurl = process.env.apiurl;
    }
    else if (!environment && !process.env.apiurl && !process.env.authurl) {
        result.authurl = 'https://auth.ordercloud.io/oauth/token';
        result.apiurl = 'https://api.ordercloud.io';
    }
    if (process.env.clientid) result.clientid = process.env.clientid;
    if (process.env.appname) result.appname = process.env.appname;
    if (process.env.ocscope) result.ocscope = process.env.ocscope;
    if (process.env.buyerid) result.buyerid = process.env.buyerid;
    return result;
}
<|endoftext|>


<commit_before>/*
	(c) 2014, 2016 Digital Humanities Lab, Utrecht University
	Author: Julian Gonggrijp, j.gonggrijp@uu.nl

	Automated word-in-context scraper for text corpora:
	http://corpus.rae.es/cordenet.html
	http://corpus.rae.es/creanet.html
	http://corpus.byu.edu/
	http://web.frl.es/CORPES/view/inicioExterno.view
	http://web.frl.es/CREA/view/inicioExterno.view
	http://web.frl.es/CNDHE/view/inicioExterno.view
*/

(function() {
	'use strict';

	var target,          // frame or window containing first page of results
	    parser = new DOMParser(),
	    data = [],       // will contain the extracted data in subarrays
	    progressSteps,   // number of requests to complete (including jQuery)
	    progress = 0,    // number of requests completed so far
	    csvSpecial = /[,; "'\t\n\r]/;  // used in sanitize()

	// Produces an object with domain-specific code, if available.
	// Refer to the Readme for a discussion of the purpose of each function.
	var domains = {
		'corpus.byu.edu': {
			columns: [
				'number', 'century', 'text',
				'contextLeft', 'sample', 'contextRight',
			],
			init: function() {
				target = frames[6];
				this.rowsPerPage = frames[2].document.querySelector('#kh').value;
				var navtable = target.document.querySelectorAll('#zabba table')[1];
				if (navtable) {
					var navrow = navtable.querySelectorAll('td')[2];
					progressSteps = Number(navrow.childNodes[4].nodeValue.split('/')[1]);
				} else progressSteps = 1;
			},
			getNext: function(doc) {
				var navtable = doc.querySelectorAll('#zabba table')[1];
				if (!navtable) return;
				var navrow = navtable.querySelectorAll('td')[2],
				    anchor = navrow.querySelectorAll('a')[2],
				    currentState = navrow.childNodes[4].nodeValue.split('/');
				if (anchor && Number(currentState[0]) < Number(currentState[1])) {
					return anchor.getAttribute('href');
				}
				// else return undefined
			},
			scrape1page: function(doc) {
				var row, anchors, field, fieldparts, fieldmiddle, rowdata,
				    i, j, l;
				for (i = 1; i <= this.rowsPerPage; ++i) {
					row = doc.querySelector('#t' + i);
					if (!row) continue;
					anchors = row.querySelectorAll('a');
					field = row.querySelector('#texto_' + i);
					rowdata = [];
					if (!anchors || !field || !field.value) continue;
					for (j = 0; j < 3; ++j) {
						rowdata.push(anchors[j].childNodes[0].nodeValue);
					}
					fieldparts = field.value.split(/<b><u>|<\/u><\/b>/);
					fieldmiddle = [];
					for (l = fieldparts.length, j = 1; j < l - 1; ++j) {
						fieldmiddle.push(fieldparts[j]);
					}
					rowdata.push(   fieldparts[0],
					                fieldmiddle.join(''),
					                fieldparts[j]           );
					data.push(rowdata);
				}
			}
		},
		'corpus.rae.es': {
			columns: [
				'number', 'century', 'text',
				'contextLeft', 'sample', 'contextRight',
			],
			init: function() {
				target = window;
				var navnode = document.querySelector('td.texto[align="center"]');
				progressSteps = Number(navnode.textContent.split(/[^0,1-9]+/)[2]);
			},
			getNext: function(doc) {
				var anchor = doc.querySelector('td > a');
				if (!anchor || anchor.textContent !== 'Siguiente') return;
				return anchor.getAttribute('href');
			},
			translateHeader: function(columnHeader) {
				switch (columnHeader) {
				// \xBA might be replaced by \ufffd on encoding mismatch.
				case 'N\ufffd':
				case 'N\xBA':
					return 'number';
				case 'A\xD1O':
					return 'date';
				case 'T\xCDTULO':
					return 'text';
				case 'CONCORDANCIA':
					return 'contextLeft';
				default:
					return null;
				}
			},
			columnPositions: function(section, titleLine) {
				var firstMatch = section.innerHTML.split('\n')[1],
				    columnHeads = titleLine.split(/(\s+)/),
				    anchorParts = firstMatch.split(/<a.+?">|<\/a>/),
				    columns = {},
				    currentHeader,
				    range,
				    index = 0,
				    l, i;
				for (l = columnHeads.length, i = 0; i < l; i += 2) {
					currentHeader = this.translateHeader(columnHeads[i]);
					range = [index];
					index += columnHeads[i].length;
					if (i + 1 < l) index += columnHeads[i + 1].length;
					if (currentHeader) {
						range.push(index);
						columns[currentHeader] = range;
					}
				}
				// Split the "CONCORDANCIA" column into context and sample.
				range = [
					anchorParts[0].length,
					anchorParts[0].length + anchorParts[1].length
				];
				columns.sample = range;
				// Substract 5 to remove the asterisks and trailing space.
				columns.contextRight = [range[1], columns.contextLeft[1] - 5];
				columns.contextLeft[1] = range[0];
				return columns;
			},
			// bind scrape1line to an object with `.columns` and `.minLength`
			scrape1line: function(line) {
				if (line.length < this.minLength) return;
				data.push([
					line.slice.apply(line, this.columns.number),
					line.slice.apply(line, this.columns.date),
					line.slice.apply(line, this.columns.text),
					line.slice.apply(line, this.columns.contextLeft),
					line.slice.apply(line, this.columns.sample),
					line.slice.apply(line, this.columns.contextRight),
				]);
			},
			scrape1page: function(doc) {
				var section = doc.querySelector('tt');
				if (!section) {
					console.log('Error: page', progress, 'does not contain data in the expected format.');
					return;
				}
				var lines = section.textContent.split('\n'),
				    firstLine = lines.shift(),
				    columns = this.columnPositions(section, firstLine);
				lines.forEach(this.scrape1line, {
					columns: columns,
					minLength: columns.text[1],
				});
			},
		},
		'web.frl.es': {
			columns: [
				'number', 'date', 'source', 'author', 'published', 'country',
				'contextLeft', 'sample', 'contextRight', 'sampleAnalysis',
			],
			init: function() {
				var stepNode = document.getElementById('jsf:import:CNDHEForm:importResultadoConcorView:CNDHEForm:selecTable:htmlOutputText49');
				if (stepNode) {
					progressSteps = Number(stepNode.textContent);
				} else {
					progressSteps = 1;
				}
				target = window;
				this.pagingObject = CAF.model('jsf:import:CNDHEForm:importResultadoConcorView:CNDHEForm:selecTable:comandoAlante');
				this.pagingEventName = 'CAF.Command.actionCompleteListener.#' + this.pagingObject.id;
			},
			fetchNextPage: function(callback) {
				var self = this;
				var handler = function() {
					Event.Custom.removeListener(self.pagingEventName, handler);
					callback(document);
				};
				Event.Custom.addListener(self.pagingEventName, handler);
				self.pagingObject.element.setAttribute('caf:async', true);
				self.pagingObject.go();
			},
			getNext: function() {
				return this.fetchNextPage.bind(this);
			},
			scrape1row: function(row) {
				console.log('scrape1row', row);
				console.log(row.childNodes);
				console.log(row.childElements);
				console.log(row.childElements().length);
				console.log(row.childElements().item);
				var cells = row.childNodes,
				    number = cells[0].textContent,
				    meta = cells[1].querySelectorAll('.datos_cabecera'),
				    date = meta[0].textContent,
				    source = meta[2].textContent,
				    author = meta[1].textContent,
				    published = meta[4].textContent.replace(/\[|\]/g, ''),
				    country = meta[3].textContent.replace(/\[|\]/g, ''),
				    content = cells[3].querySelectorAll('div span span'),
				    contextLeft = content[1].textContent,
				    sample = content[2].textContent,
				    contextRight = content[3].textContent,
				    sampleAnalysis = content[0].textContent;
				return [
					number, date, source, author, published, country,
					contextLeft, sample, contextRight, sampleAnalysis,
				];
			},
			scrape1page: function(doc) {
				var rows = doc.getElementById(
				    	'jsf:import:CNDHEForm:importResultadoConcorView:CNDHEForm:selecTable'
				    ).querySelectorAll('.caf-primary-row'),
				    l, i,
				    data = [];
				for (l = rows.length, i = 0; i < l; ++i) {
					data.push(this.scrape1row(rows[i]));
				}
				return data;
			},
		},
	};
	domains['www.corpusdelespanol.org'] = domains['corpus.byu.edu'];
	domains['www.corpusdoportugues.org'] = domains['corpus.byu.edu'];
	domains['googlebooks.byu.edu'] = domains['corpus.byu.edu'];

	var domain = domains[window.location.hostname];

	if (!domain) return;

	/* Add jQuery to `window`. When ready, call `continuation`. */
	function insertJQueryThen(continuation) {
		var scriptnode = document.createElement('script');
		scriptnode.setAttribute('src', '//code.jquery.com/jquery-2.1.1.min.js');
		document.head.appendChild(scriptnode);
		scriptnode.addEventListener('load', continuation);
	}

	/* Draw an empty status bar on `target.document`. */
	function createStatusbar() {
		var statuswidget = document.createElement('div'),
		    outerBar = document.createElement('div'),
		    innerBar = document.createElement('div');
		statuswidget.setAttribute('style', 'background: #fff; padding: 20px; border-radius: 10px; z-index: 10; position: fixed; top: 50px; right: 50px;');
		outerBar.setAttribute('style', 'width: 100px; height: 10px; border: 2px solid black;');
		innerBar.setAttribute('id', 'progress-fill');
		innerBar.setAttribute('style', 'width: 0%; height: 100%; background: #d10');
		outerBar.appendChild(innerBar);
		statuswidget.appendChild(outerBar);
		target.document.body.appendChild(statuswidget);
	}

	/* Increment `progress` and fill the status bar accordingly. */
	function updateStatusbar() {
		var percentage = ++progress / progressSteps * 100;
		target.document.querySelector('#progress-fill').style.width = percentage + '%';
	}

	function retrieveAndProceed(href, continuation) {
		window.jQuery.get(href, function(data) {
			var docElem = parser.parseFromString(data, 'text/html');
			continuation(docElem);
		});
	}

	function sanitize(csvValue) {
		if (typeof csvValue !== 'string') return csvValue;
		var sanitized = csvValue.trim().split('"').join('""');
		if (sanitized.match(csvSpecial)) return '"' + sanitized + '"';
		return sanitized;
	}

	function serialize(csvRow) {
		if (csvRow.length !== domain.columns.length) {
			console.log('Error: subarray of incorrect length.\n', csvRow);
		}
		return csvRow.map(sanitize).join(';');
	}

	/* Encode the extracted data as CSV and present it to the user. */
	function exportCSV() {
		console.log(data);
		// filter below removes mysterious undefined elements that
		// creep into the array
		var rows = data.filter(function(elem) { return elem; }).map(serialize),
		    $ = window.jQuery,
		    body = $(document.body);
		body.empty().text(
			'Scraping complete. Please copy the contents below ' +
			'into a plaintext document and give it a .csv extension.'
		).append('<br>');
		$('<textarea>').css({width: '50ex', height: '10em'}).text(
			domain.columns.join(';') + '\n' +
			rows.join('\n')
		).appendTo(body).focus().select();
	}

	/*
		A "lazy loop": scrape pages until there are no more.
		Looks like recursion but isn't, because of the JavaScript event model.
	*/
	function scrape(doc) {
		console.log(doc);
		var start = new Date(),
		    next = domain.getNext(doc),
		    wait;
		domain.scrape1page(doc);
		updateStatusbar();
		wait = Math.max(0, 500 - (new Date() - start));
		switch (typeof next) {
		case 'string':
			window.setTimeout(retrieveAndProceed, wait, next, scrape);
			break;
		case 'function':
			window.setTimeout(next, wait, scrape);
			break;
		default:
			exportCSV();
		}
	}

	domain.init();
	createStatusbar();
	insertJQueryThen(function() { scrape(target.document); });
}());
<commit_msg>Improve jQuery insertion<commit_after>/*
	(c) 2014, 2016, 2017 Digital Humanities Lab, Utrecht University
	Author: Julian Gonggrijp, j.gonggrijp@uu.nl

	Automated word-in-context scraper for text corpora:
	http://corpus.rae.es/cordenet.html
	http://corpus.rae.es/creanet.html
	http://corpus.byu.edu/
	http://web.frl.es/CORPES/view/inicioExterno.view
	http://web.frl.es/CREA/view/inicioExterno.view
	http://web.frl.es/CNDHE/view/inicioExterno.view
*/

(function() {
	'use strict';

	var target,          // frame or window containing first page of results
	    parser = new DOMParser(),
	    data = [],       // will contain the extracted data in subarrays
	    progressSteps,   // number of requests to complete (including jQuery)
	    progress = 0,    // number of requests completed so far
	    csvSpecial = /[,; "'\t\n\r]/;  // used in sanitize()

	// Produces an object with domain-specific code, if available.
	// Refer to the Readme for a discussion of the purpose of each function.
	var domains = {
		'corpus.byu.edu': {
			columns: [
				'number', 'century', 'text',
				'contextLeft', 'sample', 'contextRight',
			],
			init: function() {
				target = frames[6];
				this.rowsPerPage = frames[2].document.querySelector('#kh').value;
				var navtable = target.document.querySelectorAll('#zabba table')[1];
				if (navtable) {
					var navrow = navtable.querySelectorAll('td')[2];
					progressSteps = Number(navrow.childNodes[4].nodeValue.split('/')[1]);
				} else progressSteps = 1;
			},
			getNext: function(doc) {
				var navtable = doc.querySelectorAll('#zabba table')[1];
				if (!navtable) return;
				var navrow = navtable.querySelectorAll('td')[2],
				    anchor = navrow.querySelectorAll('a')[2],
				    currentState = navrow.childNodes[4].nodeValue.split('/');
				if (anchor && Number(currentState[0]) < Number(currentState[1])) {
					return anchor.getAttribute('href');
				}
				// else return undefined
			},
			scrape1page: function(doc) {
				var row, anchors, field, fieldparts, fieldmiddle, rowdata,
				    i, j, l;
				for (i = 1; i <= this.rowsPerPage; ++i) {
					row = doc.querySelector('#t' + i);
					if (!row) continue;
					anchors = row.querySelectorAll('a');
					field = row.querySelector('#texto_' + i);
					rowdata = [];
					if (!anchors || !field || !field.value) continue;
					for (j = 0; j < 3; ++j) {
						rowdata.push(anchors[j].childNodes[0].nodeValue);
					}
					fieldparts = field.value.split(/<b><u>|<\/u><\/b>/);
					fieldmiddle = [];
					for (l = fieldparts.length, j = 1; j < l - 1; ++j) {
						fieldmiddle.push(fieldparts[j]);
					}
					rowdata.push(   fieldparts[0],
					                fieldmiddle.join(''),
					                fieldparts[j]           );
					data.push(rowdata);
				}
			}
		},
		'corpus.rae.es': {
			columns: [
				'number', 'century', 'text',
				'contextLeft', 'sample', 'contextRight',
			],
			init: function() {
				target = window;
				var navnode = document.querySelector('td.texto[align="center"]');
				progressSteps = Number(navnode.textContent.split(/[^0,1-9]+/)[2]);
			},
			getNext: function(doc) {
				var anchor = doc.querySelector('td > a');
				if (!anchor || anchor.textContent !== 'Siguiente') return;
				return anchor.getAttribute('href');
			},
			translateHeader: function(columnHeader) {
				switch (columnHeader) {
				// \xBA might be replaced by \ufffd on encoding mismatch.
				case 'N\ufffd':
				case 'N\xBA':
					return 'number';
				case 'A\xD1O':
					return 'date';
				case 'T\xCDTULO':
					return 'text';
				case 'CONCORDANCIA':
					return 'contextLeft';
				default:
					return null;
				}
			},
			columnPositions: function(section, titleLine) {
				var firstMatch = section.innerHTML.split('\n')[1],
				    columnHeads = titleLine.split(/(\s+)/),
				    anchorParts = firstMatch.split(/<a.+?">|<\/a>/),
				    columns = {},
				    currentHeader,
				    range,
				    index = 0,
				    l, i;
				for (l = columnHeads.length, i = 0; i < l; i += 2) {
					currentHeader = this.translateHeader(columnHeads[i]);
					range = [index];
					index += columnHeads[i].length;
					if (i + 1 < l) index += columnHeads[i + 1].length;
					if (currentHeader) {
						range.push(index);
						columns[currentHeader] = range;
					}
				}
				// Split the "CONCORDANCIA" column into context and sample.
				range = [
					anchorParts[0].length,
					anchorParts[0].length + anchorParts[1].length
				];
				columns.sample = range;
				// Substract 5 to remove the asterisks and trailing space.
				columns.contextRight = [range[1], columns.contextLeft[1] - 5];
				columns.contextLeft[1] = range[0];
				return columns;
			},
			// bind scrape1line to an object with `.columns` and `.minLength`
			scrape1line: function(line) {
				if (line.length < this.minLength) return;
				data.push([
					line.slice.apply(line, this.columns.number),
					line.slice.apply(line, this.columns.date),
					line.slice.apply(line, this.columns.text),
					line.slice.apply(line, this.columns.contextLeft),
					line.slice.apply(line, this.columns.sample),
					line.slice.apply(line, this.columns.contextRight),
				]);
			},
			scrape1page: function(doc) {
				var section = doc.querySelector('tt');
				if (!section) {
					console.log('Error: page', progress, 'does not contain data in the expected format.');
					return;
				}
				var lines = section.textContent.split('\n'),
				    firstLine = lines.shift(),
				    columns = this.columnPositions(section, firstLine);
				lines.forEach(this.scrape1line, {
					columns: columns,
					minLength: columns.text[1],
				});
			},
		},
		'web.frl.es': {
			columns: [
				'number', 'date', 'source', 'author', 'published', 'country',
				'contextLeft', 'sample', 'contextRight', 'sampleAnalysis',
			],
			init: function() {
				var stepNode = document.getElementById('jsf:import:CNDHEForm:importResultadoConcorView:CNDHEForm:selecTable:htmlOutputText49');
				if (stepNode) {
					progressSteps = Number(stepNode.textContent);
				} else {
					progressSteps = 1;
				}
				target = window;
				this.pagingObject = CAF.model('jsf:import:CNDHEForm:importResultadoConcorView:CNDHEForm:selecTable:comandoAlante');
				this.pagingEventName = 'CAF.Command.actionCompleteListener.#' + this.pagingObject.id;
			},
			fetchNextPage: function(callback) {
				console.log('fetchNextPage', callback, this.pagingObject);
				var self = this;
				var handler = function() {
					Event.Custom.removeListener(self.pagingEventName, handler);
					console.log('handling CAF actionComplete');
					callback(document);
				};
				Event.Custom.addListener(self.pagingEventName, handler);
				self.pagingObject.element.setAttribute('caf:async', true);
				self.pagingObject.go();
			},
			getNext: function() {
				return this.fetchNextPage.bind(this);
			},
			scrape1row: function(row) {
				// console.log('scrape1row', row);
				// console.log(row.childNodes);
				// console.log(row.childElements);
				// console.log(row.childElements().length);
				// console.log(row.childElements().item);
				var cells = row.childNodes,
				    number = cells[0].textContent,
				    meta = cells[1].querySelectorAll('.datos_cabecera'),
				    date = meta[0].textContent,
				    source = meta[2].textContent,
				    author = meta[1].textContent,
				    published = meta[4].textContent.replace(/\[|\]/g, ''),
				    country = meta[3].textContent.replace(/\[|\]/g, ''),
				    content = cells[3].querySelectorAll('div span span'),
				    contextLeft = content[1].textContent,
				    sample = content[2].textContent,
				    contextRight = content[3].textContent,
				    sampleAnalysis = content[0].textContent;
				return [
					number, date, source, author, published, country,
					contextLeft, sample, contextRight, sampleAnalysis,
				];
			},
			scrape1page: function(doc) {
				var rows = doc.getElementById(
				    	'jsf:import:CNDHEForm:importResultadoConcorView:CNDHEForm:selecTable'
				    ).querySelectorAll('.caf-primary-row'),
				    l, i,
				    data = [];
				for (l = rows.length, i = 0; i < l; ++i) {
					data.push(this.scrape1row(rows[i]));
				}
				console.log('scrape1page', data);
				return data;
			},
		},
	};
	domains['www.corpusdelespanol.org'] = domains['corpus.byu.edu'];
	domains['www.corpusdoportugues.org'] = domains['corpus.byu.edu'];
	domains['googlebooks.byu.edu'] = domains['corpus.byu.edu'];

	var domain = domains[window.location.hostname];

	if (!domain) return;

	/* Add jQuery to `window`. When ready, call `continuation`. */
	function insertJQueryThen(continuation) {
		if (window.jQuery) return continuation();
		var scriptnode = document.createElement('script');
		scriptnode.setAttribute('src', '//code.jquery.com/jquery-2.1.1.min.js');
		document.head.appendChild(scriptnode);
		scriptnode.addEventListener('load', function() {
			jQuery.noConflict();  // In case the `$` variable is already used
			continuation();
		});
	}

	/* Draw an empty status bar on `target.document`. */
	function createStatusbar() {
		var statuswidget = document.createElement('div'),
		    outerBar = document.createElement('div'),
		    innerBar = document.createElement('div');
		statuswidget.setAttribute('style', 'background: #fff; padding: 20px; border-radius: 10px; z-index: 10; position: fixed; top: 50px; right: 50px;');
		outerBar.setAttribute('style', 'width: 100px; height: 10px; border: 2px solid black;');
		innerBar.setAttribute('id', 'progress-fill');
		innerBar.setAttribute('style', 'width: 0%; height: 100%; background: #d10');
		outerBar.appendChild(innerBar);
		statuswidget.appendChild(outerBar);
		target.document.body.appendChild(statuswidget);
	}

	/* Increment `progress` and fill the status bar accordingly. */
	function updateStatusbar() {
		var percentage = ++progress / progressSteps * 100;
		target.document.querySelector('#progress-fill').style.width = percentage + '%';
	}

	function retrieveAndProceed(href, continuation) {
		window.jQuery.get(href, function(data) {
			var docElem = parser.parseFromString(data, 'text/html');
			continuation(docElem);
		});
	}

	function sanitize(csvValue) {
		if (typeof csvValue !== 'string') return csvValue;
		var sanitized = csvValue.trim().split('"').join('""');
		if (sanitized.match(csvSpecial)) return '"' + sanitized + '"';
		return sanitized;
	}

	function serialize(csvRow) {
		if (csvRow.length !== domain.columns.length) {
			console.log('Error: subarray of incorrect length.\n', csvRow);
		}
		return csvRow.map(sanitize).join(';');
	}

	/* Encode the extracted data as CSV and present it to the user. */
	function exportCSV() {
		console.log(data);
		// filter below removes mysterious undefined elements that
		// creep into the array
		var rows = data.filter(function(elem) { return elem; }).map(serialize),
		    $ = window.jQuery,
		    body = $(document.body);
		body.empty().text(
			'Scraping complete. Please copy the contents below ' +
			'into a plaintext document and give it a .csv extension.'
		).append('<br>');
		$('<textarea>').css({width: '50ex', height: '10em'}).text(
			domain.columns.join(';') + '\n' +
			rows.join('\n')
		).appendTo(body).focus().select();
	}

	/*
		A "lazy loop": scrape pages until there are no more.
		Looks like recursion but isn't, because of the JavaScript event model.
	*/
	function scrape(doc) {
		console.log(doc);
		var start = new Date(),
		    next = domain.getNext(doc),
		    wait;
		domain.scrape1page(doc);
		updateStatusbar();
		wait = Math.max(0, 500 - (new Date() - start));
		switch (typeof next) {
		case 'string':
			window.setTimeout(retrieveAndProceed, wait, next, scrape);
			break;
		case 'function':
			window.setTimeout(next, wait, scrape);
			break;
		default:
			exportCSV();
		}
	}

	domain.init();
	createStatusbar();
	insertJQueryThen(function() { scrape(target.document); });
}());
<|endoftext|>


<commit_before>var Parsimmon = require('parsimmon');

var join = require('./lib/join.js');
var builtinTypes = require('./builtin-types.js')

var builtinType = Parsimmon.alt.apply(null,
    builtinTypes.map(function (str) {
        return Parsimmon.string(str)
    })
).map(function (type) {
    return {
        type: 'typeLiteral',
        builtin: true,
        name: type
    };
})

var customType = Parsimmon.regex(/[a-z]+/i)
    .map(function (type) {
        return {
            type: 'typeLiteral',
            builtin: false,
            name: type
        };
    })

var typeLiteral = Parsimmon.alt(
    builtinType,
    customType
)

var genericArgs = Parsimmon.lazy(function () {
    return join(
        typeDefinition,
        Parsimmon.optWhitespace
            .then(Parsimmon.string(','))
            .then(Parsimmon.optWhitespace)
    );
})

var genericExpression = Parsimmon.string('<')
    .then(genericArgs)
    .skip(Parsimmon.string('>'))

var genericLiteral = Parsimmon.seq(
    typeLiteral,
    genericExpression.times(0, 1)
).map(function (list) {
    if (list[1].length === 0) {
        return list[0]
    }

    return {
        type: 'genericLiteral',
        value: list[0],
        generics: list[1][0]
    }
})

module.exports = genericLiteral

var typeDefinition = require('./type-definition.js');
<commit_msg>refactor type-literal to use ast<commit_after>var Parsimmon = require('parsimmon');

var AST = require('../ast.js');
var join = require('./lib/join.js');
var builtinTypes = require('./builtin-types.js')

var builtinType = Parsimmon.alt.apply(null,
    builtinTypes.map(function (str) {
        return Parsimmon.string(str)
    })
).map(function (type) {
    return AST.literal(type, true);
})

var customType = Parsimmon.regex(/[a-z]+/i)
    .map(function (type) {
        return AST.literal(type, false);
    })

var typeLiteral = Parsimmon.alt(
    builtinType,
    customType
)

var genericArgs = Parsimmon.lazy(function () {
    return join(
        typeDefinition,
        Parsimmon.optWhitespace
            .then(Parsimmon.string(','))
            .then(Parsimmon.optWhitespace)
    );
})

var genericExpression = Parsimmon.string('<')
    .then(genericArgs)
    .skip(Parsimmon.string('>'))

var genericLiteral = Parsimmon.seq(
    typeLiteral,
    genericExpression.times(0, 1)
).map(function (list) {
    if (list[1].length === 0) {
        return list[0]
    }

    return AST.generic(list[0], list[1][0])
})

module.exports = genericLiteral

var typeDefinition = require('./type-definition.js');
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Apple, Inc. and contributors.
// License:   Licened under MIT license (see license.js)
// ==========================================================================
/*globals module ok equals same test MyApp */

var MyApp;
module("SC.Record core methods", {
  setup: function() {
    MyApp = SC.Object.create({
      store: SC.Store.create()
    })  ;

    MyApp.Foo = SC.Record.extend({});
    MyApp.json = {
      foo: "bar",
      number: 123,
      bool: YES,
      array: [1,2,3]
    };

    MyApp.foo = MyApp.store.createRecord(MyApp.Foo, MyApp.json);

  }
});

test("statusToString", function() {
  var status = MyApp.store.readStatus(MyApp.foo);
  equals(SC.Record.statusToString(status), 'EMPTY', 'status string should be EMPTY');
});<commit_msg>Fix SC.Record statusString unit test<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Apple, Inc. and contributors.
// License:   Licened under MIT license (see license.js)
// ==========================================================================
/*globals module ok equals same test MyApp */

var MyApp;
module("SC.Record core methods", {
  setup: function() {
    MyApp = SC.Object.create({
      store: SC.Store.create()
    })  ;

    MyApp.Foo = SC.Record.extend({});
    MyApp.json = {
      foo: "bar",
      number: 123,
      bool: YES,
      array: [1,2,3]
    };

    MyApp.foo = MyApp.store.createRecord(MyApp.Foo, MyApp.json);

  }
});

test("statusString", function() {
  equals(MyApp.foo.statusString(), 'READY_NEW', 'status string should be READY_NEW');
});<|endoftext|>


<commit_before>/* This caused a valgrind error at some point.
 *
 * This might actually be a libc/valgrind issue?  The following example
 * will also cause similar valgrind complaints:
 *
 *   #include <stdio.h>
 *   #include <string.h>
 *
 *   int main(int argc, char *argv[]) {
 *   	double d = 0.0;
 *   	char buf[256];
 *
 *   	memset(buf, 0, sizeof(buf));
 *   	sprintf(buf, "%s", "NaN");
 *   	sscanf(buf, "%lg", &d);
 *   	printf("%lg\n", d);
 *   }
 */

/*===
===*/

var x;

x = "NaN" >>> 0;

<commit_msg>fix ecmascript testcase for ToNumber() valgrind issue: print something at the end to ensure we reach the end (empty expect string is a bad idea)<commit_after>/* This caused a valgrind error at some point.
 *
 * This might actually be a libc/valgrind issue?  The following example
 * will also cause similar valgrind complaints:
 *
 *   #include <stdio.h>
 *   #include <string.h>
 *
 *   int main(int argc, char *argv[]) {
 *   	double d = 0.0;
 *   	char buf[256];
 *
 *   	memset(buf, 0, sizeof(buf));
 *   	sprintf(buf, "%s", "NaN");
 *   	sscanf(buf, "%lg", &d);
 *   	printf("%lg\n", d);
 *   }
 */

/*===
still here
===*/

var x;

x = "NaN" >>> 0;
print('still here');
<|endoftext|>


<commit_before>(function(sc) {
    'use strict';
    // Helper functions
    sc.chart.navChart = function() {
        var dispatch = d3.dispatch('viewChange');

        var navTimeSeries = fc.chart.linearTimeSeries()
            .yTicks(0);

        var area = fc.series.area()
            .yValue(function(d) { return d.open; });

        var line = fc.series.line()
            .yValue(function(d) { return d.open; });

        var brush = d3.svg.brush();

        var navMulti = fc.series.multi().series([area, line, brush]);

        var viewScale = fc.scale.dateTime();

        function navChart(selection) {
            var data = selection.datum().data;
            var viewDomain = selection.datum().viewDomain;

            viewScale.domain(viewDomain)
                .range([0, selection.attr('width')]);

            var yExtent = fc.util.extent(sc.util.filterDataInDateRange(data,
                fc.util.extent(data, 'date')), ['low', 'high']);

            navTimeSeries = fc.chart.linearTimeSeries()
                .xDomain(fc.util.extent(data, 'date'))
                .yDomain(yExtent);

            brush.on('brush', function() {
                if (brush.extent()[0][0] - brush.extent()[1][0] !== 0) {
                    // Control the shared view scale's domain
                    dispatch.viewChange([brush.extent()[0][0], brush.extent()[1][0]]);
                }
            });

            // Allow to zoom using mouse, but disable panning
            var zoom = d3.behavior.zoom();
            zoom.x(viewScale)
                .on('zoom', function() {
                    if (zoom.scale() === 1) {
                        zoom.translate([0, 0]);
                    } else {
                        // Usual behavior
                        sc.util.zoomControl(zoom, selection, data, viewScale);
                        dispatch.viewChange(viewScale.domain());
                    }
                });
            selection.call(zoom);

            navMulti.mapping(function(series) {
                if (series === brush) {
                    brush.extent([
                        [viewScale.domain()[0], navTimeSeries.yDomain()[0]],
                        [viewScale.domain()[1], navTimeSeries.yDomain()[1]]
                    ]);
                }
                return data;
            });

            navTimeSeries.plotArea(navMulti);
            selection.call(navTimeSeries);
        }

        d3.rebind(navChart, dispatch, 'on');

        return navChart;
    };

})(sc);<commit_msg>Deleted reinitialisation<commit_after>(function(sc) {
    'use strict';
    // Helper functions
    sc.chart.navChart = function() {
        var dispatch = d3.dispatch('viewChange');

        var navTimeSeries = fc.chart.linearTimeSeries()
            .yTicks(0);

        var area = fc.series.area()
            .yValue(function(d) { return d.open; });

        var line = fc.series.line()
            .yValue(function(d) { return d.open; });

        var brush = d3.svg.brush();

        var navMulti = fc.series.multi().series([area, line, brush]);

        var viewScale = fc.scale.dateTime();

        function navChart(selection) {
            var data = selection.datum().data;
            var viewDomain = selection.datum().viewDomain;

            viewScale.domain(viewDomain)
                .range([0, selection.attr('width')]);

            var yExtent = fc.util.extent(sc.util.filterDataInDateRange(data,
                fc.util.extent(data, 'date')), ['low', 'high']);

            navTimeSeries.xDomain(fc.util.extent(data, 'date'))
                .yDomain(yExtent);

            brush.on('brush', function() {
                if (brush.extent()[0][0] - brush.extent()[1][0] !== 0) {
                    // Control the shared view scale's domain
                    dispatch.viewChange([brush.extent()[0][0], brush.extent()[1][0]]);
                }
            });

            // Allow to zoom using mouse, but disable panning
            var zoom = d3.behavior.zoom();
            zoom.x(viewScale)
                .on('zoom', function() {
                    if (zoom.scale() === 1) {
                        zoom.translate([0, 0]);
                    } else {
                        // Usual behavior
                        sc.util.zoomControl(zoom, selection, data, viewScale);
                        dispatch.viewChange(viewScale.domain());
                    }
                });
            selection.call(zoom);

            navMulti.mapping(function(series) {
                if (series === brush) {
                    brush.extent([
                        [viewScale.domain()[0], navTimeSeries.yDomain()[0]],
                        [viewScale.domain()[1], navTimeSeries.yDomain()[1]]
                    ]);
                }
                return data;
            });

            navTimeSeries.plotArea(navMulti);
            selection.call(navTimeSeries);
        }

        d3.rebind(navChart, dispatch, 'on');

        return navChart;
    };

})(sc);<|endoftext|>


<commit_before><commit_msg>[ts] Typecheck SourceCodeDiff.js<commit_after><|endoftext|>


<commit_before>Function.prototype.bind||(Function.prototype.bind=function(a){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var b=Array.prototype.slice.call(arguments,1),c=this,d=function(){},e=function(){return c.apply(this instanceof d?this:a,b.concat(Array.prototype.slice.call(arguments)))};return this.prototype&&(d.prototype=this.prototype),e.prototype=new d,e}),define(["dojo/_base/declare","dijit/_Widget","dijit/_TemplatedMixin","dijit/_WidgetsInTemplateMixin","esri/dijit/Search","dojo/dom-construct","dijit/layout/ContentPane","dijit/TitlePane","dojox/widget/TitleGroup","dojo/on","dojo/Deferred","dojo/query","dojo/NodeList-data"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m=function(a){return void 0===a||null===a||""===a},n=function(a,b){var c=f.toDom(""+a+"");return l(c).data("result",b),c},o=function(a,b){return!m(a)&&a.length>0&&b?""+a.length+"":""},p=function(a,b,c){var d=0,e=0,f=new i,j=a.Addresses;for(d=0,e=j.length;e>d;d+=1)f.addChild(new g({content:["",n(j[d].address,j[d])]}));b.addChild(new h({title:a.Description+o(j,c),content:f,open:!1}))},q=function(a,b){var c,d,e=0,f=0,h=new i;if(!m(a.Addresses)&&a.Addresses.length>1){for(c=a.Addresses,e=0,f=c.length;f>e;e++)!m(c[e].Addresses)&&c[e].Addresses.length>1?p(c[e],h,b):(d=m(c[e].address)?n(c[e].Addresses[0].address,c[e].Addresses[0]):n(c[e].address,c[e]),h.addChild(new g({content:["",d]})));h.startup()}else m(a.Addresses[0].address)?!m(a.Addresses[0].Addresses)&&a.Addresses[0].Addresses.length>0&&p(a.Addresses[0],h):h=new g({content:n(a.Addresses[0].address,a.Addresses[0])});return h},r=function(a,b){this.get("contentSet")===!1&&(this.set("content",q(a,b)),this.set("contentSet",!0))};return a([b,c,d,e],{baseClass:"drilldown",widgetsInTemplate:!0,resultsElement:null,_titleGroups:[],showCounts:!1,constructor:function(b){a.safeMixin(this,b)},destroy:function(){this._clearPicklist(),this.inherited(arguments)},search:function(){var a=this,b=new k;return this.inherited(arguments).then(function(c){a._buildPickListUi(c),b.resolve()}),b.promise},clear:function(){this._clearPicklist(),this.inherited(arguments)},_hydrateResults:function(a){return a.PickListItems?a:this.inherited(arguments)},_formatResults:function(a,b,c){var d={activeSourceIndex:b,value:c,numResults:0,numErrors:0,errors:null,results:null},e={},f={},g=0;if(a){if(b===this._allIndex){for(g=0;g0){for(a=0,b=this._titleGroups.length;b>a;a++)this._titleGroups[a].destroy();this._titleGroups=[]}},_showNoResults:function(){this._noResults(this.value),this._showNoResultsMenu()},_isSingleResult:function(a){var b,c,d,e=0;for(d in a)a.hasOwnProperty(d)&&(e++,c=d);if(1===e){if(b=a[c].PickListItems,1===b.length&&1===b[0].Addresses.length){if(m(b[0].Addresses[0].Addresses))return!0;if(!m(b[0].Addresses[0].Addresses)&&1===b[0].Addresses[0].Addresses.length)return!0}return!1}return!1},_buildPickListUi:function(a){var b,c,d,e,g,n,p=this,s=0,t=0,u=!1,v=new k;if(this._clearPicklist(),f.destroy(this.resultsElement),this.resultsElement=f.create("div",{"class":"arcgisSearch searchGroup picklistResults"},this.domNode,"last"),p.activeSourceIndex!==this._allIndex&&this._isSingleResult(a))e=this._hydrateResult(a[p.activeSourceIndex].PickListItems[0].Addresses[0],p.activeSourceIndex,!1),this.select(e);else{if(!m(a)){for(d in a)if(a.hasOwnProperty(d))if(m(a[d])||m(a[d].PickListItems))u=!0;else if(b=a[d].PickListItems,t=b.length,t>0)for(g=f.create("div",{id:d},this.resultsElement,"last"),c=new i(null,g),this._titleGroups.push(c),s=0;t>s;s+=1)n=new h({title:b[s].Description+o(b[s].Addresses,this.showCounts),open:!1,contentSet:!1}),1===t?(n.set("open",!0),n.set("contentSet",!0),n.set("content",q(b[s],this.showCounts))):n.own(n.on("click",r.bind(n,b[s],this.showCounts))),c.addChild(n),u=!1;else u=!0;v.resolve()}u&&this._showNoResults(),m(this.resultsElement)||j(this.resultsElement,".drilldownResult:click",function(){var a=l(this).data()[0],b=p._hydrateResult(a.result,p.activeSourceIndex,!1);p.select(b),p._clearPicklist()})}return v.promise}})});<commit_msg>Update from travis build of arcgis-dijit-drilldown<commit_after>Function.prototype.bind||(Function.prototype.bind=function(a){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var b=Array.prototype.slice.call(arguments,1),c=this,d=function(){},e=function(){return c.apply(this instanceof d?this:a,b.concat(Array.prototype.slice.call(arguments)))};return this.prototype&&(d.prototype=this.prototype),e.prototype=new d,e}),define(["dojo/_base/declare","dijit/_Widget","dijit/_TemplatedMixin","dijit/_WidgetsInTemplateMixin","esri/dijit/Search","dojo/dom-construct","dijit/layout/ContentPane","dijit/TitlePane","dojox/widget/TitleGroup","dojo/on","dojo/Deferred","dojo/query","dojo/NodeList-data"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m=function(a){return void 0===a||null===a||""===a},n=function(a,b){var c=f.toDom(""+a+"");return l(c).data("result",b),c},o=function(a,b){return!m(a)&&a.length>0&&b?""+a.length+"":""},p=function(a,b,c){var d=0,e=0,f=new i,j=a.Addresses;for(d=0,e=j.length;e>d;d+=1)f.addChild(new g({content:["",n(j[d].address,j[d])]}));b.addChild(new h({title:""+a.Description+""+o(j,c),content:f,open:!1}))},q=function(a,b){var c,d,e=0,f=0,h=new i;if(!m(a.Addresses)&&a.Addresses.length>1){for(c=a.Addresses,e=0,f=c.length;f>e;e++)!m(c[e].Addresses)&&c[e].Addresses.length>1?p(c[e],h,b):(d=m(c[e].address)?n(c[e].Addresses[0].address,c[e].Addresses[0]):n(c[e].address,c[e]),h.addChild(new g({content:["",d]})));h.startup()}else m(a.Addresses[0].address)?!m(a.Addresses[0].Addresses)&&a.Addresses[0].Addresses.length>0&&p(a.Addresses[0],h):h=new g({content:n(a.Addresses[0].address,a.Addresses[0])});return h},r=function(a,b){this.get("contentSet")===!1&&(this.set("content",q(a,b)),this.set("contentSet",!0))};return a([b,c,d,e],{baseClass:"drilldown",widgetsInTemplate:!0,resultsElement:null,_titleGroups:[],showCounts:!1,constructor:function(b){a.safeMixin(this,b)},destroy:function(){this._clearPicklist(),this.inherited(arguments)},search:function(){var a=this,b=new k;return this.inherited(arguments).then(function(c){a._buildPickListUi(c),b.resolve()}),b.promise},clear:function(){this._clearPicklist(),this.inherited(arguments)},_hydrateResults:function(a){return a.PickListItems?a:this.inherited(arguments)},_formatResults:function(a,b,c){var d={activeSourceIndex:b,value:c,numResults:0,numErrors:0,errors:null,results:null},e={},f={},g=0;if(a){if(b===this._allIndex){for(g=0;g0){for(a=0,b=this._titleGroups.length;b>a;a++)this._titleGroups[a].destroy();this._titleGroups=[]}},_showNoResults:function(){this._noResults(this.value),this._showNoResultsMenu()},_isSingleResult:function(a){var b,c,d,e=0;for(d in a)a.hasOwnProperty(d)&&(e++,c=d);if(1===e){if(b=a[c].PickListItems,1===b.length&&1===b[0].Addresses.length){if(m(b[0].Addresses[0].Addresses))return!0;if(!m(b[0].Addresses[0].Addresses)&&1===b[0].Addresses[0].Addresses.length)return!0}return!1}return!1},_buildPickListUi:function(a){var b,c,d,e,g,n,p=this,s=0,t=0,u=!1,v=new k;if(this._clearPicklist(),f.destroy(this.resultsElement),this.resultsElement=f.create("div",{"class":"arcgisSearch searchGroup picklistResults"},this.domNode,"last"),p.activeSourceIndex!==this._allIndex&&this._isSingleResult(a))e=this._hydrateResult(a[p.activeSourceIndex].PickListItems[0].Addresses[0],p.activeSourceIndex,!1),this.select(e);else{if(!m(a)){for(d in a)if(a.hasOwnProperty(d))if(m(a[d])||m(a[d].PickListItems))u=!0;else if(b=a[d].PickListItems,t=b.length,t>0)for(g=f.create("div",{id:d},this.resultsElement,"last"),c=new i(null,g),this._titleGroups.push(c),s=0;t>s;s+=1)n=new h({title:""+b[s].Description+""+o(b[s].Addresses,this.showCounts),open:!1,contentSet:!1}),1===t?(n.set("open",!0),n.set("contentSet",!0),n.set("content",q(b[s],this.showCounts))):n.own(n.on("click",r.bind(n,b[s],this.showCounts))),c.addChild(n),u=!1;else u=!0;v.resolve()}u&&this._showNoResults(),m(this.resultsElement)||j(this.resultsElement,".drilldownResult:click",function(){var a=l(this).data()[0],b=p._hydrateResult(a.result,p.activeSourceIndex,!1);p.select(b),p._clearPicklist()})}return v.promise}})});<|endoftext|>


<commit_before>const config = require('../config');

let sentry = '';
if (config.sentry_id) {
  //eslint-disable-next-line node/no-missing-require
  const version = require('../../dist/version.json');
  sentry = `
var RAVEN_CONFIG = {
  release: '${version.version}',
  tags: {
    commit: '${version.commit}'
  },
  dataCallback: function (data) {
    var hash = window.location.hash;
    if (hash) {
      return JSON.parse(JSON.stringify(data).replace(new RegExp(hash.slice(1), 'g'), ''));
    }
    return data;
  }
}
var SENTRY_ID = '${config.sentry_id}';
`;
}

let ga = '';
if (config.analytics_id) {
  ga = `var GOOGLE_ANALYTICS_ID = ${config.analytics_id};`;
}

/* eslint-disable no-useless-escape */
const jsconfig = `
var isIE = /trident\\\/7\.|msie/i.test(navigator.userAgent);
var isUnsupportedPage = /\\\/unsupported/.test(location.pathname);
if (isIE && !isUnsupportedPage) {
  window.location.replace('/unsupported/ie');
}
var MAXFILESIZE = ${config.max_file_size};
var EXPIRE_SECONDS = ${config.expire_seconds};
${ga}
${sentry}
`;

module.exports = function(req, res) {
  res.set('Content-Type', 'application/javascript');
  res.send(jsconfig);
};
<commit_msg>fixed GA var in jsconfig<commit_after>const config = require('../config');

let sentry = '';
if (config.sentry_id) {
  //eslint-disable-next-line node/no-missing-require
  const version = require('../../dist/version.json');
  sentry = `
var RAVEN_CONFIG = {
  release: '${version.version}',
  tags: {
    commit: '${version.commit}'
  },
  dataCallback: function (data) {
    var hash = window.location.hash;
    if (hash) {
      return JSON.parse(JSON.stringify(data).replace(new RegExp(hash.slice(1), 'g'), ''));
    }
    return data;
  }
}
var SENTRY_ID = '${config.sentry_id}';
`;
}

let ga = '';
if (config.analytics_id) {
  ga = `var GOOGLE_ANALYTICS_ID = '${config.analytics_id}';`;
}

/* eslint-disable no-useless-escape */
const jsconfig = `
var isIE = /trident\\\/7\.|msie/i.test(navigator.userAgent);
var isUnsupportedPage = /\\\/unsupported/.test(location.pathname);
if (isIE && !isUnsupportedPage) {
  window.location.replace('/unsupported/ie');
}
var MAXFILESIZE = ${config.max_file_size};
var EXPIRE_SECONDS = ${config.expire_seconds};
${ga}
${sentry}
`;

module.exports = function(req, res) {
  res.set('Content-Type', 'application/javascript');
  res.send(jsconfig);
};
<|endoftext|>


<commit_before>/**
 * Application Main Class
 */
var app = {
  pages: {},
  appBoard: $('#appMain'),
  header: $('#appHeader'),
  pageBoard: $('#appBody'),
  mainMenuAsGoBack: false,
  currentPageMgr: undefined,
  pageViewStack: [],
  wannaExit: false,

  begin: function() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    document.addEventListener('pause', this.onPause, false);
    document.addEventListener('resume', this.onResume, false);
    document.addEventListener('backbutton', this.onBackKeyDown, false);
    document.addEventListener('menubutton', this.onMenuKeyDown, false);
  },

  onDeviceReady: function() {
    console.log('device is ready to use on ' + device.platform + '. language: ' + navigator.language);

    app.initialize();
  },

  initialize: function() {
    runningOnBrowser = !isValid(device) || device.platform == 'browser';

    $(window).off('resize').on('resize', function(){ app.adjustLayout(); });

    // set up Language Pack
    R.setLocale(navigator.language);

    // main menu icon
    app.header.find('li:nth-child(1)').off('click').on('click', app.clickMainMenu);

    // application title
    app.header.find('li:nth-child(2)').html('' + R.text('appTitle') + '');

    app.addPages( [pageMain, studyMgr, testMgr, reviewMgr, contentsMgr, testingMgr] );

    RT.load('data/sample.json', function(){ app.showPage(pageMain); });
  },

  // returns height of ad's
  getAdHeight: function() {
    return isRunningOnBrowser() ? 0 : 50;
  },

  getHeaderHeight: function() {
    return 50;
  },

  adjustLayout: function() {
    var appHeaderHeight = app.getHeaderHeight();

    var w = $(window).width();
    var h = $(window).height();

    // TODO iOS: consider status bar height. adjust header top padding, header height.

    place(app.appBoard, undefined, undefined, w, h);
    place(app.header, undefined, undefined, w, appHeaderHeight);
    place(app.pageBoard, undefined, undefined, w, h - appHeaderHeight - app.getAdHeight());
    // place(app.pageBoard.find('.x-main-view'), undefined, undefined, w, h - appHeaderHeight);

    app.pageBoard.css({'position':'relative', 'top':appHeaderHeight + cUnit});

    for(var x in app.pages) {
      if( app.pages[x].adjustLayout ) {
        app.pages[x].adjustLayout(w, h);
      }
    }
  },

  onPause: function(event) {
    //
  },

  onResume: function(event) {
    app.adjustLayout();
    setTimeout(function() { admob.showADBanner(); }, 20);
  },

  onBackKeyDown: function(event) {
    if( app.wannaExit ) { navigator.app.exitApp(); }

    if( !app.goBack() ) {
      app.wannaExit = true;
      showToast(R.text('backExit'));
      setTimeout(function() { app.wannaExit = false; }, 2900);
    }
  },

  onMenuKeyDown: function(event) {
    //
  },

  clickMainMenu: function() {
    if( app.mainMenuAsGoBack ) {
      app.onBackKeyDown();
    } else {
      // TODO
    }
  },

  addPage: function(pageMgr) {
    if( app.pages[pageMgr.getPageID()] ) {
      throw 'already defined page.';
    }

    app.pages[pageMgr.getPageID()] = pageMgr;

    var board = $('

').addClass('x-main-view').attr('id', pageMgr.getPageID()).hide();
    app.pageBoard.append(board);
    pageMgr.initialize(board);
  },

  addPages: function(pages) {
    for(var i = 0; i < pages.length; ++i)
      app.addPage(pages[i]);
  },

  showPage: function(pageMrg, options) {
    var pageID = pageMrg.getPageID();
    var newMgr = app.pages[pageID];

    if( newMgr == undefined ) {
      console.log('unregistered page manager: ' + pageID);
      return;
    }

    newMgr.onActivated(app.currentPageMgr, options);

    app.switchHeader(newMgr);

    if( app.currentPageMgr && app.currentPageMgr != newMgr ) {
      app.currentPageMgr.onDeactivated(newMgr);
    }

    app.pageBoard.find('.x-main-view').hide();
    app.pageBoard.find('#' + pageID).show();

    if( app.currentPageMgr && checkCall(app.currentPageMgr['isHistoric'], true) ) {
      app.pageViewStack.push(app.currentPageMgr);
    }

    app.currentPageMgr = newMgr;
    app.adjustLayout();

    setTimeout(function() { admob.showADBanner(); }, 20);
  },

  switchHeader: function(pageMgr) {
    var hi = pageMgr.getHeaderInfo();

    if( hi['mainButton'] == 'back' ) {
      app.header.find('li:nth-child(1)').html('').off('click').on('click', app.clickMainMenu);
      app.mainMenuAsGoBack = true;
    } else {
      app.header.find('li:nth-child(1)').html('').off('click').on('click', app.clickMainMenu);
      app.mainMenuAsGoBack = false;
    }

    app.header.find('li:nth-child(2)').html('' + hi['title'] + '');
  },

  goBack: function() {
    if( app.currentPageMgr && !checkCall(app.currentPageMgr['isPossibleToGoBack'], true) ) {
      return true;
    }

    if( app.pageViewStack.length < 1 ) { return false; }
    app.showPage(app.pageViewStack.pop());

    return true;
  }
};

app.begin();
<commit_msg>working<commit_after>/**
 * Application Main Class
 */
var app = {
  pages: {},
  appBoard: $('#appMain'),
  header: $('#appHeader'),
  pageBoard: $('#appBody'),
  mainMenuAsGoBack: false,
  currentPageMgr: undefined,
  pageViewStack: [],
  wannaExit: false,

  begin: function() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    document.addEventListener('pause', this.onPause, false);
    document.addEventListener('resume', this.onResume, false);
    document.addEventListener('backbutton', this.onBackKeyDown, false);
    document.addEventListener('menubutton', this.onMenuKeyDown, false);
  },

  onDeviceReady: function() {
    console.log('device is ready to use on ' + device.platform + '. language: ' + navigator.language);

    app.initialize();
  },

  initialize: function() {
    runningOnBrowser = !isValid(device) || device.platform == 'browser';

    $(window).off('resize').on('resize', function(){ app.adjustLayout(); });

    // set up Language Pack
    R.setLocale(navigator.language);

    // main menu icon
    app.header.find('li:nth-child(1)').off('click').on('click', app.clickMainMenu);

    // application title
    app.header.find('li:nth-child(2)').html('' + R.text('appTitle') + '');

    app.addPages( [pageMain, studyMgr, testMgr, reviewMgr, contentsMgr, testingMgr] );

    RT.load('data/sample.json', function(){ app.showPage(pageMain); });
  },

  // returns height of ad's
  getAdHeight: function() {
    return isRunningOnBrowser() ? 0 : 50;
  },

  getHeaderHeight: function() {
    return 50;
  },

  adjustLayout: function() {
    var appHeaderHeight = app.getHeaderHeight();

    var w = $(window).width();
    var h = $(window).height();

    // TODO iOS: consider status bar height. adjust header top padding, header height.

    place(app.appBoard, undefined, undefined, w, h);
    place(app.header, undefined, undefined, w, appHeaderHeight);
    place(app.pageBoard, undefined, undefined, w, h - appHeaderHeight - app.getAdHeight());
    // place(app.pageBoard.find('.x-main-view'), undefined, undefined, w, h - appHeaderHeight);

    app.pageBoard.css({'position':'relative', 'top':appHeaderHeight + cUnit});

    for(var x in app.pages) {
      if( app.pages[x].adjustLayout ) {
        app.pages[x].adjustLayout(w, h);
      }
    }
  },

  onPause: function(event) {
    //
  },

  onResume: function(event) {
    app.adjustLayout();
    setTimeout(function() { admob.showADBanner(); }, 20);
  },

  onBackKeyDown: function(event) {
    if( app.wannaExit ) { navigator.app.exitApp(); }

    if( !app.goBack() ) {
      app.wannaExit = true;
      showToast(R.text('backExit'));
      setTimeout(function() { app.wannaExit = false; }, 2900);
    }
  },

  onMenuKeyDown: function(event) {
    //
  },

  clickMainMenu: function() {
    if( app.mainMenuAsGoBack ) {
      app.onBackKeyDown();
    } else {
      // TODO
    }
  },

  addPage: function(pageMgr) {
    if( app.pages[pageMgr.getPageID()] ) {
      throw 'already defined page.';
    }

    app.pages[pageMgr.getPageID()] = pageMgr;

    var board = $('

').addClass('x-main-view').attr('id', pageMgr.getPageID()).hide();
    app.pageBoard.append(board);
    pageMgr.initialize(board);
  },

  addPages: function(pages) {
    for(var i = 0; i < pages.length; ++i)
      app.addPage(pages[i]);
  },

  showPage: function(pageMrg, options, fromBack) {
    var pageID = pageMrg.getPageID();
    var newMgr = app.pages[pageID];

    if( newMgr == undefined ) {
      console.log('unregistered page manager: ' + pageID);
      return;
    }

    newMgr.onActivated(app.currentPageMgr, options);

    app.switchHeader(newMgr);

    if( app.currentPageMgr && app.currentPageMgr != newMgr ) {
      app.currentPageMgr.onDeactivated(newMgr);
    }

    app.pageBoard.find('.x-main-view').hide();
    app.pageBoard.find('#' + pageID).show();

    if( !fromBack && app.currentPageMgr && checkCall(app.currentPageMgr['isHistoric'], true) ) {
      app.pageViewStack.push(app.currentPageMgr);
    }

    app.currentPageMgr = newMgr;
    app.adjustLayout();

    setTimeout(function() { admob.showADBanner(); }, 20);
  },

  switchHeader: function(pageMgr) {
    var hi = pageMgr.getHeaderInfo();

    if( hi['mainButton'] == 'back' ) {
      app.header.find('li:nth-child(1)').html('').off('click').on('click', app.clickMainMenu);
      app.mainMenuAsGoBack = true;
    } else {
      app.header.find('li:nth-child(1)').html('').off('click').on('click', app.clickMainMenu);
      app.mainMenuAsGoBack = false;
    }

    app.header.find('li:nth-child(2)').html('' + hi['title'] + '');
  },

  goBack: function() {
    if( app.currentPageMgr && !checkCall(app.currentPageMgr['isPossibleToGoBack'], true) ) {
      return true;
    }

    if( app.pageViewStack.length < 1 ) { return false; }
    app.showPage(app.pageViewStack.pop(), undefined, true);

    return true;
  }
};

app.begin();
<|endoftext|>