<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

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

var BlendMode = {
	process: function(blendMode, sourceContext, destContext, opacity, offset) {
		var sourceCanvas = sourceContext.canvas,
			dstData = destContext.getImageData(offset.x, offset.y,
					sourceCanvas.width, sourceCanvas.height),
			dst  = dstData.data,
			src  = sourceContext.getImageData(0, 0,
					sourceCanvas.width, sourceCanvas.height).data,
			min = Math.min,
			sA, dA, rA, sM, dM, rM, sRA, sGA, sBA, dRA, dGA, dBA;

		// TODO: Some blend modes seem broken at the moment, e.g. dodge, burn
		var modes = {
			normal: function(i) {
				dst[i]     = (sRA + dRA - dRA * sA) * rM;
				dst[i + 1] = (sGA + dGA - dGA * sA) * rM;
				dst[i + 2] = (sBA + dBA - dBA * sA) * rM;
			},

			multiply: function(i) {
				dst[i]     = (sRA * dRA + sRA * (1 - dA) + dRA * (1 - sA)) * rM;
				dst[i + 1] = (sGA * dGA + sGA * (1 - dA) + dGA * (1 - sA)) * rM;
				dst[i + 2] = (sBA * dBA + sBA * (1 - dA) + dBA * (1 - sA)) * rM;
			},

			screen: function(i) {
				dst[i]     = (sRA + dRA - sRA * dRA) * rM;
				dst[i + 1] = (sGA + dGA - sGA * dGA) * rM;
				dst[i + 2] = (sBA + dBA - sBA * dBA) * rM;
			},

			overlay: function(i) {
				// Correct for 100% opacity case; colors get clipped as opacity falls
				dst[i]     = dRA <= 0.5 ? (2 * src[i]     * dRA / dA) : 255 - (2 - 2 * dRA / dA) * (255 - src[i]);
				dst[i + 1] = dGA <= 0.5 ? (2 * src[i + 1] * dGA / dA) : 255 - (2 - 2 * dGA / dA) * (255 - src[i + 1]);
				dst[i + 2] = dBA <= 0.5 ? (2 * src[i + 2] * dBA / dA) : 255 - (2 - 2 * dBA / dA) * (255 - src[i + 2]);
			},

			// TODO: Missing: soft-light

			'hard-light': function(i) {
				dst[i]     = sRA <= 0.5 ? (2 * dst[i]     * sRA / dA) : 255 - (2 - 2 * sRA / sA) * (255 - dst[i]);
				dst[i + 1] = sGA <= 0.5 ? (2 * dst[i + 1] * sGA / dA) : 255 - (2 - 2 * sGA / sA) * (255 - dst[i + 1]);
				dst[i + 2] = sBA <= 0.5 ? (2 * dst[i + 2] * sBA / dA) : 255 - (2 - 2 * sBA / sA) * (255 - dst[i + 2]);
			},

			'color-dodge': function(i) {
				dst[i]     = src[i]     == 255 && dRA == 0 ? 255 : min(255, dst[i]     / (255 - src[i]    )) * rM;
				dst[i + 1] = src[i + 1] == 255 && dGA == 0 ? 255 : min(255, dst[i + 1] / (255 - src[i + 1])) * rM;
				dst[i + 2] = src[i + 2] == 255 && dBA == 0 ? 255 : min(255, dst[i + 2] / (255 - src[i + 2])) * rM;
			},

			'color-burn': function(i) {
				dst[i]     = src[i]     == 0 && dRA == 0 ? 0 : (1 - min(1, (1 - dRA) / sRA)) * rM;
				dst[i + 1] = src[i + 1] == 0 && dGA == 0 ? 0 : (1 - min(1, (1 - dGA) / sGA)) * rM;
				dst[i + 2] = src[i + 2] == 0 && dBA == 0 ? 0 : (1 - min(1, (1 - dBA) / sBA)) * rM;
			},

			darken: function(i) {
				dst[i]     = (sRA > dRA ? dRA : sRA) * rM;
				dst[i + 1] = (sGA > dGA ? dGA : sGA) * rM;
				dst[i + 2] = (sBA > dBA ? dBA : sBA) * rM;
			},

			lighten: function(i) {
				dst[i]     = (sRA < dRA ? dRA : sRA) * rM;
				dst[i + 1] = (sGA < dGA ? dGA : sGA) * rM;
				dst[i + 2] = (sBA < dBA ? dBA : sBA) * rM;
			},

			difference: function(i) {
				dst[i]     = (sRA + dRA - 2 * min(sRA * dA, dRA * sA)) * rM;
				dst[i + 1] = (sGA + dGA - 2 * min(sGA * dA, dGA * sA)) * rM;
				dst[i + 2] = (sBA + dBA - 2 * min(sBA * dA, dBA * sA)) * rM;
			},

			exclusion: function(i) {
				dst[i]     = (dRA + sRA - 2 * dRA * sRA) * rM;
				dst[i + 1] = (dGA + sGA - 2 * dGA * sGA) * rM;
				dst[i + 2] = (dBA + sBA - 2 * dBA * sBA) * rM;
			},

			// TODO: Missing: hue, saturation, color, luminosity

			// Not in Illustrator:

			'src-in': function(i) {
				// Only differs from Photoshop in low - opacity areas
				rA = sA * dA;
				rM = 255 / rA;
				dst[i]     = sRA * dA * rM;
				dst[i + 1] = sGA * dA * rM;
				dst[i + 2] = sBA * dA * rM;
			},

			add: function(i) {
				// Photoshop doesn't simply add the alpha channels,
				// this might be correct wrt SVG 1.2
				rA = min(1, sA + dA);
				rM = 255 / rA;
				dst[i]     = min(sRA + dRA, 1) * rM;
				dst[i + 1] = min(sGA + dGA, 1) * rM;
				dst[i + 2] = min(sBA + dBA, 1) * rM;
			}
		};

		var process = modes[blendMode];
		if (!process)
			return;
		opacity /= 255;
		for (var i = 0, l = dst.length; i < l; i += 4) {
			sA  = src[i + 3] * opacity;
			dA  = dst[i + 3] / 255;
			rA = sA + dA - sA * dA;
			sM = sA / 255;
			dM = dA / 255;
			sRA = src[i] * sM;
			dRA = dst[i] * dM;
			sGA = src[i + 1] * sM;
			dGA = dst[i + 1] * dM;
			sBA = src[i + 2] * sM;
			dBA = dst[i + 2] * dM;
			rM = 255 / rA;
			process(i);
			dst[i + 3] = rA * 255;
		}
		destContext.putImageData(dstData, offset.x, offset.y);
	}
};
<commit_msg>Use min() / max() in darken / lighten for shorter code.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

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

var BlendMode = {
	process: function(blendMode, sourceContext, destContext, opacity, offset) {
		var sourceCanvas = sourceContext.canvas,
			dstData = destContext.getImageData(offset.x, offset.y,
					sourceCanvas.width, sourceCanvas.height),
			dst  = dstData.data,
			src  = sourceContext.getImageData(0, 0,
					sourceCanvas.width, sourceCanvas.height).data,
			min = Math.min,
			max = Math.max,
			sA, dA, rA, sM, dM, rM, sRA, sGA, sBA, dRA, dGA, dBA;

		// TODO: Some blend modes seem broken at the moment, e.g. dodge, burn
		var modes = {
			normal: function(i) {
				dst[i]     = (sRA + dRA - dRA * sA) * rM;
				dst[i + 1] = (sGA + dGA - dGA * sA) * rM;
				dst[i + 2] = (sBA + dBA - dBA * sA) * rM;
			},

			multiply: function(i) {
				dst[i]     = (sRA * dRA + sRA * (1 - dA) + dRA * (1 - sA)) * rM;
				dst[i + 1] = (sGA * dGA + sGA * (1 - dA) + dGA * (1 - sA)) * rM;
				dst[i + 2] = (sBA * dBA + sBA * (1 - dA) + dBA * (1 - sA)) * rM;
			},

			screen: function(i) {
				dst[i]     = (sRA + dRA - sRA * dRA) * rM;
				dst[i + 1] = (sGA + dGA - sGA * dGA) * rM;
				dst[i + 2] = (sBA + dBA - sBA * dBA) * rM;
			},

			overlay: function(i) {
				// Correct for 100% opacity case; colors get clipped as opacity falls
				dst[i]     = dRA <= 0.5 ? (2 * src[i]     * dRA / dA) : 255 - (2 - 2 * dRA / dA) * (255 - src[i]);
				dst[i + 1] = dGA <= 0.5 ? (2 * src[i + 1] * dGA / dA) : 255 - (2 - 2 * dGA / dA) * (255 - src[i + 1]);
				dst[i + 2] = dBA <= 0.5 ? (2 * src[i + 2] * dBA / dA) : 255 - (2 - 2 * dBA / dA) * (255 - src[i + 2]);
			},

			// TODO: Missing: soft-light

			'hard-light': function(i) {
				dst[i]     = sRA <= 0.5 ? (2 * dst[i]     * sRA / dA) : 255 - (2 - 2 * sRA / sA) * (255 - dst[i]);
				dst[i + 1] = sGA <= 0.5 ? (2 * dst[i + 1] * sGA / dA) : 255 - (2 - 2 * sGA / sA) * (255 - dst[i + 1]);
				dst[i + 2] = sBA <= 0.5 ? (2 * dst[i + 2] * sBA / dA) : 255 - (2 - 2 * sBA / sA) * (255 - dst[i + 2]);
			},

			'color-dodge': function(i) {
				dst[i]     = src[i]     == 255 && dRA == 0 ? 255 : min(255, dst[i]     / (255 - src[i]    )) * rM;
				dst[i + 1] = src[i + 1] == 255 && dGA == 0 ? 255 : min(255, dst[i + 1] / (255 - src[i + 1])) * rM;
				dst[i + 2] = src[i + 2] == 255 && dBA == 0 ? 255 : min(255, dst[i + 2] / (255 - src[i + 2])) * rM;
			},

			'color-burn': function(i) {
				dst[i]     = src[i]     == 0 && dRA == 0 ? 0 : (1 - min(1, (1 - dRA) / sRA)) * rM;
				dst[i + 1] = src[i + 1] == 0 && dGA == 0 ? 0 : (1 - min(1, (1 - dGA) / sGA)) * rM;
				dst[i + 2] = src[i + 2] == 0 && dBA == 0 ? 0 : (1 - min(1, (1 - dBA) / sBA)) * rM;
			},

			darken: function(i) {
				dst[i]     = min(sRA, dRA) * rM;
				dst[i + 1] = min(sGA, dGA) * rM;
				dst[i + 2] = min(sBA, dBA) * rM;
			},

			lighten: function(i) {
				dst[i]     = max(sRA, dRA) * rM;
				dst[i + 1] = max(sGA, dGA) * rM;
				dst[i + 2] = max(sBA, dBA) * rM;
			},

			difference: function(i) {
				dst[i]     = (sRA + dRA - 2 * min(sRA * dA, dRA * sA)) * rM;
				dst[i + 1] = (sGA + dGA - 2 * min(sGA * dA, dGA * sA)) * rM;
				dst[i + 2] = (sBA + dBA - 2 * min(sBA * dA, dBA * sA)) * rM;
			},

			exclusion: function(i) {
				dst[i]     = (dRA + sRA - 2 * dRA * sRA) * rM;
				dst[i + 1] = (dGA + sGA - 2 * dGA * sGA) * rM;
				dst[i + 2] = (dBA + sBA - 2 * dBA * sBA) * rM;
			},

			// TODO: Missing: hue, saturation, color, luminosity

			// Not in Illustrator:

			'src-in': function(i) {
				// Only differs from Photoshop in low - opacity areas
				rA = sA * dA;
				rM = 255 / rA;
				dst[i]     = sRA * dA * rM;
				dst[i + 1] = sGA * dA * rM;
				dst[i + 2] = sBA * dA * rM;
			},

			add: function(i) {
				// Photoshop doesn't simply add the alpha channels,
				// this might be correct wrt SVG 1.2
				rA = min(1, sA + dA);
				rM = 255 / rA;
				dst[i]     = min(sRA + dRA, 1) * rM;
				dst[i + 1] = min(sGA + dGA, 1) * rM;
				dst[i + 2] = min(sBA + dBA, 1) * rM;
			}
		};

		var process = modes[blendMode];
		if (!process)
			return;
		opacity /= 255;
		for (var i = 0, l = dst.length; i < l; i += 4) {
			sA  = src[i + 3] * opacity;
			dA  = dst[i + 3] / 255;
			rA = sA + dA - sA * dA;
			sM = sA / 255;
			dM = dA / 255;
			sRA = src[i] * sM;
			dRA = dst[i] * dM;
			sGA = src[i + 1] * sM;
			dGA = dst[i + 1] * dM;
			sBA = src[i + 2] * sM;
			dBA = dst[i + 2] * dM;
			rM = 255 / rA;
			process(i);
			dst[i + 3] = rA * 255;
		}
		destContext.putImageData(dstData, offset.x, offset.y);
	}
};
<|endoftext|>


<commit_before>// JSON-P Twitter fetcher for Octopress
// (c) Brandon Mathis // MIT Lisence
function getTwitterFeed(user, count, replies) {
  feed = new jXHR();
  feed.onerror = function (msg,url) {
    $('#tweets li.loading').addClass('error').text("Twitter's busted");
  }
  feed.onreadystatechange = function(data){
    if (feed.readyState === 4) {
      var tweets = new Array();
      for (i in data){
        if(tweets.length < count){
          if(replies || data[i].in_reply_to_user_id == null){
            tweets.push(data[i]);
          }
        }
      }
      showTwitterFeed(tweets, user);
    }
  };
  feed.open("GET","http://twitter.com/statuses/user_timeline/"+user+".json?trim_user=true&count="+(parseInt(count)+60)+"&callback=?");
  feed.send();
}

function showTwitterFeed(tweets, twitter_user){
  var timeline = document.getElementById('tweets');
  timeline.innerHTML='';
  for (t in tweets){
    timeline.innerHTML+='
'+'
'+''+prettyDate(tweets[t].created_at)+''+linkifyTweet(tweets[t].text.replace(/\n/g, '
'))+'
'+'
';
  }
}
function linkifyTweet(text){
  return text.replace(/(https?:\/\/)([\w\-:;?&=+.%#\/]+)/gi, '$2')
    .replace(/(^|\W)@(\w+)/g, '$1@$2')
    .replace(/(^|\W)#(\w+)/g, '$1#$2');
}

// jXHR.js (JSON-P XHR) | v0.1 (c) Kyle Simpson | MIT License | http://mulletxhr.com/
// uncompressed version available in source/javascripts/libs/jXHR.js
(function(c){var b=c.setTimeout,d=c.document,a=0;c.jXHR=function(){var e,g,n,h,m=null;function l(){try{h.parentNode.removeChild(h)}catch(o){}}function k(){g=false;e="";l();h=null;i(0)}function f(p){try{m.onerror.call(m,p,e)}catch(o){throw new Error(p)}}function j(){if((this.readyState&&this.readyState!=="complete"&&this.readyState!=="loaded")||g){return}this.onload=this.onreadystatechange=null;g=true;if(m.readyState!==4){f("Script failed to load ["+e+"].")}l()}function i(o,p){p=p||[];m.readyState=o;if(typeof m.onreadystatechange==="function"){m.onreadystatechange.apply(m,p)}}m={onerror:null,onreadystatechange:null,readyState:0,open:function(p,o){k();internal_callback="cb"+(a++);(function(q){c.jXHR[q]=function(){try{i.call(m,4,arguments)}catch(r){m.readyState=-1;f("Script failed to run ["+e+"].")}c.jXHR[q]=null}})(internal_callback);e=o.replace(/=\?/,"=jXHR."+internal_callback);i(1)},send:function(){b(function(){h=d.createElement("script");h.setAttribute("type","text/javascript");h.onload=h.onreadystatechange=function(){j.call(h)};h.setAttribute("src",e);d.getElementsByTagName("head")[0].appendChild(h)},0);i(2)},setRequestHeader:function(){},getResponseHeader:function(){return""},getAllResponseHeaders:function(){return[]}};k();return m}})(window);

/* Sky Slavin, Ludopoli. MIT license.  * based on JavaScript Pretty Date * Copyright (c) 2008 John Resig (jquery.com) * Licensed under the MIT license.  */

function prettyDate(time) {
  if (navigator.appName == 'Microsoft Internet Explorer') {
    return "∞"; // because IE date parsing isn't fun.
  };

  var say = {};
  say.just_now = " now",
  say.minute_ago = "1m",
  say.minutes_ago = "m",
  say.hour_ago = "1h",
  say.hours_ago = "h",
  say.yesterday = "1d",
  say.days_ago = "d",
  say.weeks_ago = "w"

  var current_date = new Date();
  current_date_time = current_date.getTime();
  current_date_full = current_date_time + (1 * 60000);
  var date = new Date(time);
  var diff = ((current_date_full - date.getTime()) / 1000);
  var day_diff = Math.floor(diff / 86400);

  if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) return;

  return day_diff == 0 && (
    diff < 60 && say.just_now ||
    diff < 120 && say.minute_ago ||
    diff < 3600 && Math.floor(diff / 60) + say.minutes_ago ||
    diff < 7200 && say.hour_ago ||
    diff < 86400 && Math.floor(diff / 3600) + say.hours_ago) ||
    day_diff == 1 && say.yesterday ||
    day_diff < 7 && day_diff + say.days_ago ||
    day_diff < 31 && Math.ceil(day_diff / 7) + say.weeks_ago;
}
<commit_msg>correctly scope locals<commit_after>// JSON-P Twitter fetcher for Octopress
// (c) Brandon Mathis // MIT Lisence
function getTwitterFeed(user, count, replies) {
  var feed = new jXHR();

  feed.onerror = function (msg,url) {
    $('#tweets li.loading').addClass('error').text("Twitter's busted");
  }
  feed.onreadystatechange = function(data){
    if (feed.readyState === 4) {
      var tweets = new Array();
      var i = 0;
      for (i in data){
        if(tweets.length < count){
          if(replies || data[i].in_reply_to_user_id == null){
            tweets.push(data[i]);
          }
        }
      }
      showTwitterFeed(tweets, user);
    }
  };
  feed.open("GET","http://twitter.com/statuses/user_timeline/"+user+".json?trim_user=true&count="+(parseInt(count)+60)+"&callback=?");
  feed.send();
}

function showTwitterFeed(tweets, twitter_user){
  var timeline = document.getElementById('tweets');
  timeline.innerHTML='';
  for (t in tweets){
    timeline.innerHTML+='
'+'
'+''+prettyDate(tweets[t].created_at)+''+linkifyTweet(tweets[t].text.replace(/\n/g, '
'))+'
'+'
';
  }
}
function linkifyTweet(text){
  return text.replace(/(https?:\/\/)([\w\-:;?&=+.%#\/]+)/gi, '$2')
    .replace(/(^|\W)@(\w+)/g, '$1@$2')
    .replace(/(^|\W)#(\w+)/g, '$1#$2');
}

// jXHR.js (JSON-P XHR) | v0.1 (c) Kyle Simpson | MIT License | http://mulletxhr.com/
// uncompressed version available in source/javascripts/libs/jXHR.js
(function(c){var b=c.setTimeout,d=c.document,a=0;c.jXHR=function(){var e,g,n,h,m=null;function l(){try{h.parentNode.removeChild(h)}catch(o){}}function k(){g=false;e="";l();h=null;i(0)}function f(p){try{m.onerror.call(m,p,e)}catch(o){throw new Error(p)}}function j(){if((this.readyState&&this.readyState!=="complete"&&this.readyState!=="loaded")||g){return}this.onload=this.onreadystatechange=null;g=true;if(m.readyState!==4){f("Script failed to load ["+e+"].")}l()}function i(o,p){p=p||[];m.readyState=o;if(typeof m.onreadystatechange==="function"){m.onreadystatechange.apply(m,p)}}m={onerror:null,onreadystatechange:null,readyState:0,open:function(p,o){k();internal_callback="cb"+(a++);(function(q){c.jXHR[q]=function(){try{i.call(m,4,arguments)}catch(r){m.readyState=-1;f("Script failed to run ["+e+"].")}c.jXHR[q]=null}})(internal_callback);e=o.replace(/=\?/,"=jXHR."+internal_callback);i(1)},send:function(){b(function(){h=d.createElement("script");h.setAttribute("type","text/javascript");h.onload=h.onreadystatechange=function(){j.call(h)};h.setAttribute("src",e);d.getElementsByTagName("head")[0].appendChild(h)},0);i(2)},setRequestHeader:function(){},getResponseHeader:function(){return""},getAllResponseHeaders:function(){return[]}};k();return m}})(window);

/* Sky Slavin, Ludopoli. MIT license.  * based on JavaScript Pretty Date * Copyright (c) 2008 John Resig (jquery.com) * Licensed under the MIT license.  */

function prettyDate(time) {
  if (navigator.appName == 'Microsoft Internet Explorer') {
    return "∞"; // because IE date parsing isn't fun.
  };

  var say = {};
  say.just_now = " now",
  say.minute_ago = "1m",
  say.minutes_ago = "m",
  say.hour_ago = "1h",
  say.hours_ago = "h",
  say.yesterday = "1d",
  say.days_ago = "d",
  say.weeks_ago = "w"

  var current_date = new Date();
  current_date_time = current_date.getTime();
  current_date_full = current_date_time + (1 * 60000);
  var date = new Date(time);
  var diff = ((current_date_full - date.getTime()) / 1000);
  var day_diff = Math.floor(diff / 86400);

  if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) return;

  return day_diff == 0 && (
    diff < 60 && say.just_now ||
    diff < 120 && say.minute_ago ||
    diff < 3600 && Math.floor(diff / 60) + say.minutes_ago ||
    diff < 7200 && say.hour_ago ||
    diff < 86400 && Math.floor(diff / 3600) + say.hours_ago) ||
    day_diff == 1 && say.yesterday ||
    day_diff < 7 && day_diff + say.days_ago ||
    day_diff < 31 && Math.ceil(day_diff / 7) + say.weeks_ago;
}
<|endoftext|>


<commit_before>myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, inventoryService) {
    $scope.inventories = inventoryService.loadInventories();
    $scope.inventory = inventoryService.getInventory($routeParams.id);
    $scope.headerIcon = $scope.inventory ? "arrow_back" : "";
    console.log("Path: " + $location.path());

    $scope.goBack = function() {
        $window.history.go(-1);
    };

    $scope.newInventory = function() {
        var inventory = inventoryService.newInventory();
        $location.path(`/new/${inventory.id}`);
    };

    $scope.editInventory = function(inv) {
        $location.path(`/edit/${inv.id}`);
    };

    $scope.addInventory = function() {
        var id = $routeParams.id;
        $scope.inventories[id] = $scope.inventory;
        inventoryService.storeInventories();
        $location.path(`/view/${id}`);
    };

    $scope.newItem = function() {
        var id = $scope.inventory.id;
        var item = inventoryService.newItem();
        $location.path(`/edit/${id}/item/new/${item.id}`);
    };

    $scope.addItem = function() {
        var { id, itemId } = $routeParams;
        var inventory = $scope.inventories[id];

        inventory.items[itemId] = $scope.item;
        inventoryService.storeInventories();
        $location.path(`/view/${id}`);
    };

    $scope.removeItem = function() {
    };
});
<commit_msg>Log current route<commit_after>myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, inventoryService) {
    $scope.inventories = inventoryService.loadInventories();
    $scope.inventory = inventoryService.getInventory($routeParams.id);
    $scope.headerIcon = $scope.inventory ? "arrow_back" : "";
    console.log("Path: " + $location.path(), $route.current);

    $scope.goBack = function() {
        $window.history.go(-1);
    };

    $scope.newInventory = function() {
        var inventory = inventoryService.newInventory();
        $location.path(`/new/${inventory.id}`);
    };

    $scope.editInventory = function(inv) {
        $location.path(`/edit/${inv.id}`);
    };

    $scope.addInventory = function() {
        var id = $routeParams.id;
        $scope.inventories[id] = $scope.inventory;
        inventoryService.storeInventories();
        $location.path(`/view/${id}`);
    };

    $scope.newItem = function() {
        var id = $scope.inventory.id;
        var item = inventoryService.newItem();
        $location.path(`/edit/${id}/item/new/${item.id}`);
    };

    $scope.addItem = function() {
        var { id, itemId } = $routeParams;
        var inventory = $scope.inventories[id];

        inventory.items[itemId] = $scope.item;
        inventoryService.storeInventories();
        $location.path(`/view/${id}`);
    };

    $scope.removeItem = function() {
    };
});
<|endoftext|>


<commit_before>var scontext = require('search-context');
var searchIndexLogger = require('../logger/searchIndexLogger');
var stopwords = require('natural').stopwords;
var totalDocs = 0;

var sortOnValueDesc = function(a,b) {
  if (a.value  b.value) return -1; return 0;
}
var sortOnValueAsc = function(a,b) {
  if (a.value  b.value) return 1; return 0;
}
var sortOnKeyDesc = function(a,b) {
  if (a.key  b.key) return -1; return 0;
}
var sortOnKeyAsc = function(a,b) {
  if (a.key  b.key) return 1; return 0;
}

//used on startup
exports.setTotalDocs = function (td) {
  totalDocs = td;
}

var getFacetSets = function(facetks, facetsSoFar, indexes, filterks, counter, q, callback) {
  var thisFacetCat = facetks[counter].split('~')[3];
  indexes.createReadStream({
    valueEncoding: 'json',
    limit: -1,
    start: facetks[counter],
    end: facetks[counter] + '~'})
    .on('data', function (data) {
      var thisFacetName = data.key.split('~')[4];

      var filteredFacetSet = data.value; //its actually unfiltered at this point
      //handle intersections for filters
      for (var i = 0; i < filterks.length; i++) {
        var filters = filterks[i].slice(0);
        filteredFacetSet = intersectionDestructive(filteredFacetSet, filters);
      }
      if (!facetsSoFar[thisFacetCat][thisFacetName]) {
        if (filteredFacetSet.length > 0)
          facetsSoFar[thisFacetCat][thisFacetName] = filteredFacetSet;
      }
      else {
        //handle intersections for multiword queries
        var intersection = intersectionDestructive(facetsSoFar[thisFacetCat][thisFacetName], filteredFacetSet);
        if (intersection.length > 0)
          facetsSoFar[thisFacetCat][thisFacetName] = intersection;
        else
          delete facetsSoFar[thisFacetCat][thisFacetName];
      }
    })
    .on('end', function () {
      if (++counter < facetks.length) {getFacetSets(facetKeySet, facetsSoFar, indexes, filterks, counter, q);}
      else {
        //flatten sets to counts
        var finalFacets = {};
        for (k in facetsSoFar) {
          finalFacets[k] = [];
          for (kk in facetsSoFar[k]) {

            //if facet is active add flag
            var thisFacetEntry = {'key':kk,'value':facetsSoFar[k][kk].length};
            if (q['filter']) if (q['filter'][k]) if (q['filter'][k].indexOf(kk) != -1)
              thisFacetEntry['active'] = true;

            finalFacets[k].push(thisFacetEntry);
          }
          if (q.facetSort) {
            if (q.facetSort == 'keyAsc') finalFacets[k].sort(sortOnKeyAsc);
            else if (q.facetSort == 'keyDesc') finalFacets[k].sort(sortOnKeyDesc);
            else if (q.facetSort == 'valueAsc') finalFacets[k].sort(sortOnValueAsc);
            else if (q.facetSort == 'valueDesc') finalFacets[k].sort(sortOnValueDesc);
          }
          else {
            finalFacets[k].sort(sortOnValueDesc);
          }
          var facetLength = q.facetLength || 10;
          finalFacets[k] = finalFacets[k].slice(0, facetLength);
        }
        //finished!
        callback(finalFacets);
      }
    });
}

var getDocumentFreqencies = function(indexesMultiply, keySet, callback) {
  //Check document frequencies
  var err = false;
  var docFreqs = {};
  var tfsets = [];
  var totalHits = 0;
  indexesMultiply.get(keySet, function(err, data) {
    for (k in data) {
      if (data[k] == null) {
        //return a zero result
        docFreqs[keySet[i]] = 0;
        searchIndexLogger.debug('KEY ' + k + ' NOT FOUND IN DICTIONARY');
      }
      else {
        //    totalHits = data[k].length;
        docFreqs[k] = data[k].length;
        tfsets.push(data[k]);
      }
    }
    var intersection = tfsets[0];
    for (var i = 1; i < tfsets.length; i++) {
      intersection = intersectionDestructive(intersection, tfsets[i]);
    }

    if(intersection === undefined)
      err = true;
    else
      totalHits = intersection.length;
    callback(err, {docFreqs:docFreqs, allDocsIDsInResultSet:intersection});
  });
};

exports.search = function (indexes, indexesMultiply, q, callback) {
  var cleanQuery = {};
  var canSearch = true;
  var keySet = [];

  var getFacets = function(q, indexes, callback) {
    //if no facet request callback and return
    if (!q.facets){callback({});return;}
    var facetKeySet = [];
    var filterKeySet = [];
    for (var searchField in q.query) {
      for (var h = 0; h < q.query[searchField].length; h++) {
        var queryToken = q.query[searchField][h];
        for (var i = 0; i < q.facets.length; i++) {
          var facetName = q.facets[i];
          facetKeySet.push('TF~'
                           + searchField + '~'
                           + queryToken + '~'
                           + facetName + '~');
          if (q.filter) {
            if (q.filter[facetName]) {
              thisFilterValues = q.filter[facetName];
              for (var l = 0; l < thisFilterValues.length; l++) {
                filterKeySet.push('TF~'
                                  + searchField + '~'
                                  + queryToken + '~'
                                  + facetName + '~' + thisFilterValues[l]);
              }
            }
          }
        }
      }
    }

    var facetsSoFar = {};
    for (var i = 0; i < q.facets.length; i++)
      facetsSoFar[q.facets[i]] = {};
    //could be speeded up by always taking the least frequent keys first?
    indexesMultiply.get(filterKeySet, function (err, data) {
      var filters = [];
      for (var i in data)
        filters.push(data[i]);
      getFacetSets(facetKeySet, facetsSoFar, indexes, filters, 0, q, function(msg){
        callback(msg);
      });
    });
  };

  //remove stopwords
  cleanQuery['query'] = {};
  for (var searchField in q['query']) {
    var cleanQueryFieldToken = searchField;
    cleanQuery['query'][cleanQueryFieldToken] = [];
    for (var k = 0; k < q['query'][searchField].length; k++) {
      cleanQuery['query'][cleanQueryFieldToken].push(q['query'][searchField][k]);
    }
    //TODO: does this make sense?
    if (cleanQuery['query'][cleanQueryFieldToken].length == 0) {
      canSearch = false;
    }
  }

  if (q.weight) {
    cleanQuery['weight'] = q.weight;
  }

  var filterKeySet = [];
  for (k in q.filter) {
    for (var i = 0; i < q.filter[k].length; i++) {
      filterKeySet.push(k + '~' + q.filter[k][i]);
    }
  }

  //generate keyset
//  var RIKeySet = [];
  for (var queryField in cleanQuery.query) {
    for (var j = 0; j < cleanQuery.query[queryField].length; j++) {
      if (q.filter) {
        for (k in q.filter) {
          for (var i = 0; i < q.filter[k].length; i++) {
            keySet.push('TF~' + queryField + '~' + cleanQuery.query[queryField][j] + '~'
                        + k + '~' + q.filter[k][i]);
          }
        }
      }
      else {
        keySet.push('TF~' + queryField + '~' + cleanQuery.query[queryField][j] + '~~');
//        RIKeySet.push('RI~' + queryField + '~' + cleanQuery.query[queryField][j] + '~~');
      }
    }
  }

  var getEmptyResultSet = function() {
    var resultSet = {};
    resultSet['hits'] = [];
    return resultSet;
  }

  getDocumentFreqencies(indexesMultiply, keySet, function(err, frequencies) {
    if (err) return callback(getEmptyResultSet());
    getFacets(q, indexes, function(facets) {
      var response = {};
      response['totalDocs'] = frequencies.allDocsIDsInResultSet.length;
      response['facets'] = facets;
      response['hits'] = [];
      //Key an RIKeyset in descending order of document frequency
      var RIKeySet = [];
      for (var k in frequencies.docFreqs)
        RIKeySet.push(k.replace(/^TF~/,'RI~'));
      var unsortedHits = {};
      indexesMultiply.get(RIKeySet, function(err, data) {
        //preserve the order of frequency (least frequent first)
        for (var j = 0; j < RIKeySet.length; j++) {
          var thisKey = RIKeySet[j];
          if (!data[thisKey]) return callback(getEmptyResultSet());
          var firstPass = false;
          if (j == 0) firstPass = true;
          var lastPass = false;
          if (j == (RIKeySet.length - 1)) lastPass = true;
          //account for weighting
          var fieldWeight = 1;
          var fieldName = thisKey.split('~')[1];
          if (q.weight)
            if (q.weight[fieldName])
              fieldWeight = q.weight[fieldName];

          //How far down the frequency set you want to look.
          //Bigger == more accurate, smaller == faster.
          var seekCutOff = 500;

          //if there is only one key in the set, and only one query term
          //set cutoff to be the same length as the page
          if (RIKeySet.length == 1) seekCutOff = (q.pageSize + q.offset);

          var thisSeekCounter = 0;
          for (var i = 0; ((i < data[thisKey].length) && (thisSeekCounter < seekCutOff)); i++) {
            //insert all of this stuff into a sorted array so that
            //subsequent passes can
            var docID = data[thisKey][i][1];
            if (frequencies.allDocsIDsInResultSet.indexOf(docID) != -1) {
              thisSeekCounter++;
              var tuple = [thisKey, (fieldWeight*data[thisKey][i][0])];
              if (firstPass) {
                unsortedHits[docID] = [tuple];
              }
              else {
                if (unsortedHits[docID]) {
                  if (unsortedHits[docID].length == j)
                    unsortedHits[docID].push(tuple);
                  else
                    delete unsortedHits[docID];
                }
              }
            }
//            if ((lastPass) && (Object.keys(unsortedHits).length > maxUnsortedHits)) break;
          }
        }
        //Iterate through object, calculating scores, account for weighting
        var sortedHits = [];
        for (var k in unsortedHits) {
          var score = 0;
          for (var i = 0; i < unsortedHits[k].length; i++)
            score += unsortedHits[k][i][1];
          sortedHits.push([k, score]);
        }
        sortedHits = sortedHits.sort(function(a,b) {
          if (a[1]  b[1])
            return -1;
          return 0;
        });

        //set offset and pagesize
        var offset = 0;
        if (q.offset) offset = q.offset;
        var pageSize = 100;
        if (q.pageSize) pageSize = q.pageSize;
        sortedHits = sortedHits.slice(offset, (offset + pageSize));

        var IDsToBeGlued = [];
        var IDsToBeGluedWithScores = {};
        //get ids of results to glue
        for (var i = 0; i < sortedHits.length; i++) {
          IDsToBeGlued.push('DOCUMENT~' + sortedHits[i][0] + '~');
          IDsToBeGluedWithScores['DOCUMENT~' + sortedHits[i][0] + '~'] = sortedHits[i][1];
        }

        //Glue docs to IDs and send resultset

        indexesMultiply.get(IDsToBeGlued, function(err, data) {
          for (var k in data) {
            var hit = {};
            hit['id'] = k.split('~')[1];
            hit['score'] = IDsToBeGluedWithScores[k];
            hit['document'] = JSON.parse(data[k]);
            var terms = q['query']['*'];
            if (q['query'][q.teaser])
              terms = q['query'][q.teaser];
            if (q.teaser && hit.document[q.teaser]) {
              try {
                hit.document['teaser'] =
                  scontext(hit.document[q.teaser],
                           terms, 400,
                           function hi (string) {
                             return '' + string + ''
                           });
              } catch (e) {
                searchIndexLogger.error('error with teaser generation: ' + e)
              }
            }
            delete hit['document']['*'];
            response["hits"].push(hit);
          }

          response['hits'] = response.hits.sort(function(a,b) {
            if (a.score  b.score)
              return -1;
            return 0;
          });
          response['totalHits'] = frequencies.allDocsIDsInResultSet.length;
          response['query'] = q;

          callback(response);

        });
      });
    });
  });
};

function intersectionDestructive(a, b) {
  var result = new Array();
  while( a.length > 0 && b.length > 0 ) {
     if      (a[0]  b[0]){ b.shift(); }
     else /* they're equal */ {
       result.push(a.shift());
       b.shift();
     }
  }
  return result;
}
<commit_msg>fix and tidy up<commit_after>var scontext = require('search-context');
var searchIndexLogger = require('../logger/searchIndexLogger');
var stopwords = require('natural').stopwords;
var totalDocs = 0;

//used on startup
exports.setTotalDocs = function (td) {
  totalDocs = td;
}

exports.search = function (indexes, indexesMultiply, q, callback) {

  var cleanQuery = getCleanQuery(q);
  var filterKeySet = getFilterKeySet(q);
  var keySet = getKeySet(q, cleanQuery);

  var getFacets = function(q, indexes, callback) {
    //if no facet request callback and return
    if (!q.facets){callback({});return;}

    var facetLength = 10;
    if (q.facetLength) facetLength = q.facetLength;

    var sortOnValueDesc = function(a,b) {if (a.value  b.value) return -1; return 0;}
    var sortOnValueAsc = function(a,b) {if (a.value  b.value) return 1; return 0;}
    var sortOnKeyDesc = function(a,b) {if (a.key  b.key) return -1; return 0;}
    var sortOnKeyAsc = function(a,b) {if (a.key  b.key) return 1; return 0;}

    var facetKeySet = [];
    var filterKeySet = [];
    for (var searchField in q.query) {
      for (var h = 0; h < q.query[searchField].length; h++) {
        var queryToken = q.query[searchField][h];
        for (var i = 0; i < q.facets.length; i++) {
          var facetName = q.facets[i];
          facetKeySet.push('TF~'
                           + searchField + '~'
                           + queryToken + '~'
                           + facetName + '~');
          if (q.filter) {
            if (q.filter[facetName]) {
              thisFilterValues = q.filter[facetName];
              for (var l = 0; l < thisFilterValues.length; l++) {
                filterKeySet.push('TF~'
                                  + searchField + '~'
                                  + queryToken + '~'
                                  + facetName + '~' + thisFilterValues[l]);
              }
            }
          }
        }
      }
    }

    var facetsSoFar = {};
    for (var i = 0; i < q.facets.length; i++)
      facetsSoFar[q.facets[i]] = {};

    //could be speeded up by always taking the least frequent keys first?
    var getFacetSets = function(facetks, filterks, counter) {
      var thisFacetCat = facetks[counter].split('~')[3];
      indexes.createReadStream({
        valueEncoding: 'json',
        limit: -1,
        start: facetks[counter],
        end: facetks[counter] + '~'})
        .on('data', function (data) {
          var thisFacetName = data.key.split('~')[4];

          var filteredFacetSet = data.value; //its actually unfiltered at this point
          //handle intersections for filters
          for (var i = 0; i < filterks.length; i++) {
            var filters = filterks[i].slice(0);
            filteredFacetSet = intersectionDestructive(filteredFacetSet, filters);
          }
          if (!facetsSoFar[thisFacetCat][thisFacetName]) {
            if (filteredFacetSet.length > 0)
              facetsSoFar[thisFacetCat][thisFacetName] = filteredFacetSet;
          }
          else {
            //handle intersections for multiword queries
            var intersection = intersectionDestructive(facetsSoFar[thisFacetCat][thisFacetName], filteredFacetSet);
            if (intersection.length > 0)
              facetsSoFar[thisFacetCat][thisFacetName] = intersection;
            else
              delete facetsSoFar[thisFacetCat][thisFacetName];
          }
        })
        .on('end', function () {
          if (++counter < facetks.length) {getFacetSets(facetKeySet, filterks, counter);}
          else {
            //flatten sets to counts
            var finalFacets = {};
            for (k in facetsSoFar) {
              finalFacets[k] = [];
              for (kk in facetsSoFar[k]) {

                //if facet is active add flag
                var thisFacetEntry = {'key':kk,'value':facetsSoFar[k][kk].length};
                if (q['filter']) if (q['filter'][k]) if (q['filter'][k].indexOf(kk) != -1)
                  thisFacetEntry['active'] = true;

                finalFacets[k].push(thisFacetEntry);
              }
              if (q.facetSort) {
                if (q.facetSort == 'keyAsc') finalFacets[k].sort(sortOnKeyAsc);
                else if (q.facetSort == 'keyDesc') finalFacets[k].sort(sortOnKeyDesc);
                else if (q.facetSort == 'valueAsc') finalFacets[k].sort(sortOnValueAsc);
                else if (q.facetSort == 'valueDesc') finalFacets[k].sort(sortOnValueDesc);
              }
              else {
                finalFacets[k].sort(sortOnValueDesc);
              }
              finalFacets[k] = finalFacets[k].slice(0, facetLength);
            }
            //finished!
            callback(finalFacets);
          }
        });
    }

    indexesMultiply.get(filterKeySet, function (err, data) {
      var filters = [];
      for (var i in data)
        filters.push(data[i]);
      getFacetSets(facetKeySet, filters, 0);
    });

  };

  getDocumentFreqencies(indexesMultiply, q, keySet, function(err, frequencies) {
    if (err) return callback(getEmptyResultSet());
    getFacets(q, indexes, function(facets) {
      var response = {};
      response['totalDocs'] = frequencies.allDocsIDsInResultSet.length;
      response['facets'] = facets;
      response['hits'] = [];
      //Key an RIKeyset in descending order of document frequency
      var RIKeySet = [];
      for (var k in frequencies.docFreqs)
        RIKeySet.push(k.replace(/^TF~/,'RI~'));
      var unsortedHits = {};
      indexesMultiply.get(RIKeySet, function(err, data) {
        //preserve the order of frequency (least frequent first)
        for (var j = 0; j < RIKeySet.length; j++) {
          var thisKey = RIKeySet[j];
          if (!data[thisKey]) return callback(getEmptyResultSet());
          var firstPass = false;
          if (j == 0) firstPass = true;
          var lastPass = false;
          if (j == (RIKeySet.length - 1)) lastPass = true;
          //account for weighting
          var fieldWeight = 1;
          var fieldName = thisKey.split('~')[1];
          if (q.weight)
            if (q.weight[fieldName])
              fieldWeight = q.weight[fieldName];

          //How far down the frequency set you want to look.
          //Bigger == more accurate, smaller == faster.
          var seekCutOff = 500;

          //if there is only one key in the set, and only one query term
          //set cutoff to be the same length as the page
          if (RIKeySet.length == 1) seekCutOff = (q.pageSize + q.offset);

          var thisSeekCounter = 0;
          for (var i = 0; ((i < data[thisKey].length) && (thisSeekCounter < seekCutOff)); i++) {
            //insert all of this stuff into a sorted array so that
            //subsequent passes can
            var docID = data[thisKey][i][1];
            if (frequencies.allDocsIDsInResultSet.indexOf(docID) != -1) {
              thisSeekCounter++;
              var tuple = [thisKey, (fieldWeight*data[thisKey][i][0])];
              if (firstPass) {
                unsortedHits[docID] = [tuple];
              }
              else {
                if (unsortedHits[docID]) {
                  if (unsortedHits[docID].length == j)
                    unsortedHits[docID].push(tuple);
                  else
                    delete unsortedHits[docID];
                }
              }
            }
//            if ((lastPass) && (Object.keys(unsortedHits).length > maxUnsortedHits)) break;
          }
        }
        //Iterate through object, calculating scores, account for weighting
        var sortedHits = [];
        for (var k in unsortedHits) {
          var score = 0;
          for (var i = 0; i < unsortedHits[k].length; i++)
            score += unsortedHits[k][i][1];
          sortedHits.push([k, score]);
        }
        sortedHits = sortedHits.sort(function(a,b) {
          if (a[1]  b[1])
            return -1;
          return 0;
        });

        //set offset and pagesize
        var offset = 0;
        if (q.offset) offset = q.offset;
        var pageSize = 100;
        if (q.pageSize) pageSize = q.pageSize;
        sortedHits = sortedHits.slice(offset, (offset + pageSize));

        var IDsToBeGlued = [];
        var IDsToBeGluedWithScores = {};
        //get ids of results to glue
        for (var i = 0; i < sortedHits.length; i++) {
          IDsToBeGlued.push('DOCUMENT~' + sortedHits[i][0] + '~');
          IDsToBeGluedWithScores['DOCUMENT~' + sortedHits[i][0] + '~'] = sortedHits[i][1];
        }

        //Glue docs to IDs and send resultset

        indexesMultiply.get(IDsToBeGlued, function(err, data) {
          for (var k in data) {
            var hit = {};
            hit['id'] = k.split('~')[1];
            hit['score'] = IDsToBeGluedWithScores[k];
            hit['document'] = JSON.parse(data[k]);
            var terms = q['query']['*'];
            if (q['query'][q.teaser])
              terms = q['query'][q.teaser];
            if (q.teaser && hit.document[q.teaser]) {
              try {
                hit.document['teaser'] =
                  scontext(hit.document[q.teaser],
                           terms, 400,
                           function hi (string) {
                             return '' + string + ''
                           });
              } catch (e) {
                searchIndexLogger.error('error with teaser generation: ' + e)
              }
            }
            delete hit['document']['*'];
            response["hits"].push(hit);
          }

          response['hits'] = response.hits.sort(function(a,b) {
            if (a.score  b.score)
              return -1;
            return 0;
          });
          response['totalHits'] = frequencies.allDocsIDsInResultSet.length;
          response['query'] = q;

          callback(response);

        });
      });
    });
  });
};

function intersectionDestructive(a, b) {
  var result = new Array();
  while( a.length > 0 && b.length > 0 ) {
     if      (a[0]  b[0]){ b.shift(); }
     else /* they're equal */ {
       result.push(a.shift());
       b.shift();
     }
  }
  return result;
}

var getCleanQuery = function(q) {
  var cleanQuery = {};
  //remove stopwords
  cleanQuery['query'] = {};
  for (var searchField in q['query']) {
    var cleanQueryFieldToken = searchField;
    cleanQuery['query'][cleanQueryFieldToken] = [];
    for (var k = 0; k < q['query'][searchField].length; k++) {
      cleanQuery['query'][cleanQueryFieldToken].push(q['query'][searchField][k]);
    }
  }
  if (q.weight) {
    cleanQuery['weight'] = q.weight;
  }
  return cleanQuery;
}

var getFilterKeySet = function(q) {
  var filterKeySet = [];
  for (k in q.filter) {
    for (var i = 0; i < q.filter[k].length; i++) {
      filterKeySet.push(k + '~' + q.filter[k][i]);
    }
  }
  return filterKeySet;
}

var getKeySet = function(q, cleanQuery) {
  //generate keyset
  var keySet = [];
  for (var queryField in cleanQuery.query) {
    for (var j = 0; j < cleanQuery.query[queryField].length; j++) {
      if (q.filter) {
        for (k in q.filter) {
          for (var i = 0; i < q.filter[k].length; i++) {
            keySet.push('TF~' + queryField + '~' + cleanQuery.query[queryField][j] + '~'
                        + k + '~' + q.filter[k][i]);
          }
        }
      }
      else {
        keySet.push('TF~' + queryField + '~' + cleanQuery.query[queryField][j] + '~~');
      }
    }
  }
  return keySet;
}

var getEmptyResultSet = function() {
  var resultSet = {};
  resultSet['hits'] = [];
  return resultSet;
}

var getDocumentFreqencies = function(indexesMultiply, q, keySet, callback) {
  //Check document frequencies
  var err = false;
  var docFreqs = {};
  var tfsets = [];
  var totalHits = 0;
  if (!q.pageSize)
    q.pageSize = 100; //default
  if (!q.offset)
    q.offset = 0;     //default
  indexesMultiply.get(keySet, function(err, data) {
    for (k in data) {
      if (data[k] == null) {
        //return a zero result
        docFreqs[keySet[i]] = 0;
        searchIndexLogger.debug('KEY ' + k + ' NOT FOUND IN DICTIONARY');
      }
      else {
        //    totalHits = data[k].length;
        docFreqs[k] = data[k].length;
        tfsets.push(data[k]);
      }
    }
    var intersection = tfsets[0];
    for (var i = 1; i < tfsets.length; i++) {
      intersection = intersectionDestructive(intersection, tfsets[i]);
    }

    if(intersection === undefined)
      err = true;
    else
      totalHits = intersection.length;
    callback(err, {docFreqs:docFreqs, allDocsIDsInResultSet:intersection});
  });
};
<|endoftext|>


<commit_before>var $ = require('jquery');

function createCgi(url, settings) {
  var self = this;
  if (typeof url == 'string') {
    url = {url: url};
  }
  settings = $.extend({dataType: 'json'}, settings, url);
  url = url.url;
  var queue = [];
  var jqXhr;

  function cgiFn(data, callback, options) {
    var opts = {url: typeof url == 'function' ? url() : url};
    if (typeof data == 'function') {
      options = callback;
      callback = data;
      data = null;
    } else {
      opts.data = data;
    }

    options = $.extend(true, {}, settings, options, opts);
    if (jqXhr) {
      var mode = options.mode;
      if (mode == 'ignore') {
        return;
      }
      if (mode == 'cancel') {
        jqXhr.abort();
      } else if (mode == 'chain') {
        return queue.push([data, callback, options]);
      }
    }

    var execCallback = function(data, xhr) {
      jqXhr = null;
      callback && callback.call(this, data, xhr);
      var args = queue.shift();
      args && cgiFn.apply(self, args);
    };
    options.success = function(data, statusText, xhr) {
      execCallback.call(this, data, xhr);
    };
    options.error = function(xhr, em) {
      execCallback.call(this, false, xhr, em);
    };

    return (jqXhr = $.ajax(options));
  }

  return cgiFn;
}

function create(obj, settings) {
  var cgi = {};
  Object.keys(obj).forEach(function(name) {
    cgi[name] = createCgi(obj[name], settings);
  });
  return cgi;
}

module.exports = create;
<commit_msg>refactor: Composer<commit_after>var $ = require('jquery');

function createCgi(url, settings) {
  var self = this;
  if (typeof url == 'string') {
    url = {url: url};
  }
  settings = $.extend({dataType: 'json'}, settings, url);
  url = url.url;
  var queue = [];
  var jqXhr;

  function cgiFn(data, callback, options) {
    var opts = {url: typeof url == 'function' ? url() : url};
    if (typeof data == 'function') {
      options = callback;
      callback = data;
      data = null;
    } else {
      opts.data = data;
    }

    options = $.extend(true, {}, settings, options, opts);
    if (jqXhr) {
      var mode = options.mode;
      if (mode == 'ignore') {
        return;
      }
      if (mode == 'cancel') {
        jqXhr.abort();
      } else if (mode == 'chain') {
        return queue.push([data, callback, options]);
      }
    }

    var execCallback = function(data, xhr, em) {
      jqXhr = null;
      callback && callback.call(this, data, xhr, em);
      var args = queue.shift();
      args && cgiFn.apply(self, args);
    };
    options.success = function(data, statusText, xhr) {
      execCallback.call(this, data, xhr);
    };
    options.error = function(xhr, em) {
      execCallback.call(this, false, xhr, em);
    };

    return (jqXhr = $.ajax(options));
  }

  return cgiFn;
}

function create(obj, settings) {
  var cgi = {};
  Object.keys(obj).forEach(function(name) {
    cgi[name] = createCgi(obj[name], settings);
  });
  return cgi;
}

module.exports = create;
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    var move;
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
        return move || 'getInput()';
    }

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    var move;
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || 'randomPlay';
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Unit 4 homework - created function to retur 'player' 'computer' or 'tie' as winner<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    var move;
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
        return move || 'getInput()';
    }

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    var move;
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || 'randomPlay';
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (playerMove = 'rock') {
        if computerMove = 'rock' {
            winner = 'tie';
        };
        else if computerMove = 'paper' {
            winner = 'computer';
        };
        else if computerMove = 'scissors' {
            winner = 'player';
        };
        };

    else if (playerMove = 'paper') {
        if computerMove = 'rock' {
            winner = 'player';
        };
        else if computerMove = 'paper' {
            winner = 'tie';
        };
        else if computerMove = 'scissors' {
            winner = 'computer';
        };
    };
    else if (playerMove = 'scissors') {
        if computerMove = 'rock' {
            winner = 'computer';
        };
        else if computerMove = 'paper' {
            winner = 'player';
        };
        else if computerMove = 'scissors' {
            winner = 'tie';
        };
    };
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/

'use strict';

togglbutton.render('.content .page-title:not(.toggl)', {observe: true}, function (elem) {
  var link,  description,
    numElem = $('.page-title'),
    titleElem = $(".issue-box .title"),
    projectElem = $('.project_name').firstChild;

  description = titleElem.textContent;
  description = numElem.firstChild.textContent + " " + description;

  link = togglbutton.createTimerLink({
    className: 'gitlab',
    description: description,
    projectName: projectElem.textContent.split(' / ').pop()
  });

  $('.content .page-title').appendChild(link);
});
<commit_msg>Fix GitLab content script<commit_after>/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/

'use strict';

togglbutton.render('.content .page-title:not(.toggl)', {observe: true}, function (elem) {
  var link,  description,
    numElem = $('.page-title'),
    titleElem = $(".issue-box .title"),
    projectElem = $('.title').firstChild;

  description = titleElem.textContent;
  description = numElem.firstChild.textContent + " " + description;

  link = togglbutton.createTimerLink({
    className: 'gitlab',
    description: description,
    projectName: projectElem.textContent.split(' / ').pop()
  });

  $('.content .page-title').appendChild(link);
});
<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * A rectangular push button that draws gradients and such in order to create
 * a somewhat 3D look.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // Includes
  var AbstractPushButton = require( 'SUN/experimental/buttons/AbstractPushButton' );
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LinearGradient = require( 'SCENERY/util/LinearGradient' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var Shape = require( 'KITE/Shape' );
  var Vector2 = require( 'DOT/Vector2' );

  // Constants
  var HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var SHADE_GRADIENT_LENGTH = 3; // In screen coords, which are roughly pixels.

  /**
   * @param {Node} content - Node to put on surface of button, could be text, icon, or whatever
   * @param {Object} options
   * @constructor
   */
  function RectangularPushButton( content, options ) {

    var thisButton = this;

    options = _.extend( {
      // Default values.
      cursor: 'pointer',
      cornerRounding: 4,
      baseColor: new Color( 153, 206, 255 ),
      disabledBaseColor: new Color( 220, 220, 220 ),
      xPadding: 5,
      yPadding: 5,
      listener: null,
      fireOnDown: false,
      touchExpansionX: 5,
      touchExpansionY: 5,
      stroke: null, // No outline stroke by default
      lineWidth: 1 // Only meaningful if stroke is non-null
    }, options );

    AbstractPushButton.call( thisButton, { listener: options.listener, fireOnDown: options.fireOnDown } );

    var buttonWidth = content.width + options.xPadding * 2;
    var buttonHeight = content.height + options.yPadding * 2;
    var upCenter = new Vector2( buttonWidth / 2, buttonHeight / 2 );
    var downCenter = upCenter.plus( new Vector2( 0.0, 0.0 ) ); // TODO: Set to zero on 3/36/2014 because text was moving inconsistently.  Decide whether to eliminate completely.
    var verticalHighlightStop = HIGHLIGHT_GRADIENT_LENGTH / buttonHeight;
    var verticalShadowStop = 1 - SHADE_GRADIENT_LENGTH / buttonHeight;
    var horizontalHighlightStop = HIGHLIGHT_GRADIENT_LENGTH / buttonWidth;
    var horizontalShadowStop = 1 - SHADE_GRADIENT_LENGTH / buttonWidth;
    var baseColor = options.baseColor;
    var disabledBaseColor = options.disabledBaseColor;
    var transparentBaseColor = new Color( baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), 0 );
    var transparentDisabledBaseColor = new Color( disabledBaseColor.getRed(), disabledBaseColor.getGreen(), disabledBaseColor.getBlue(), 0 );
    var lightenedStroke = null;
    if ( options.stroke ) {
      lightenedStroke = options.stroke instanceof Color ? options.stroke.colorUtilsBrighter( 0.5 ) : new Color( options.stroke ).colorUtilsBrighter( 0.5 );
    }

    // Create the gradient fills used for various button states
    var upFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor )
      .addColorStop( verticalShadowStop, baseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var upFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var downFill = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop * 0.67, baseColor.colorUtilsDarker( 0.3 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.2 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentDisabledBaseColor )
      .addColorStop( horizontalShadowStop, transparentDisabledBaseColor )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    // Create the basic button shape.
    var background = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRounding, options.cornerRounding,
      {
        fill: options.baseColor,
        lineWidth: options.lineWidth
      } );
    this.addChild( background );

    // Create the overlay that is used to add horizontal shading.
    var overlayForHorizGradient = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRounding, options.cornerRounding,
      {
        fill: options.baseColor,
        stroke: options.stroke,
        lineWidth: options.lineWidth
      } );
    this.addChild( overlayForHorizGradient );

    content.center = upCenter;
    thisButton.addChild( content );

    // Hook up the function that will modify button appearance as the state changes.
    this.buttonModel.interactionState.link( function( interactionState ) {

      switch( interactionState ) {

        case 'idle':
          content.center = upCenter;
          content.opacity = 1;
          background.fill = upFillVertical;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = upFillHorizontal;
          thisButton.cursor = 'pointer';
          break;

        case 'over':
          content.center = upCenter;
          content.opacity = 1;
          background.fill = overFillVertical;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = overFillHorizontal;
          thisButton.cursor = 'pointer';
          break;

        case 'pressed':
          content.center = downCenter;
          content.opacity = 1;
          background.fill = downFill;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = overFillHorizontal;
          thisButton.cursor = 'pointer';
          break;

        case 'disabled':
          content.center = upCenter;
          content.opacity = 0.3;
          background.fill = disabledFillVertical;
          background.stroke = lightenedStroke;
          overlayForHorizGradient.stroke = lightenedStroke;
          overlayForHorizGradient.fill = disabledFillHorizontal;
          thisButton.cursor = null;
          break;
      }
    } );

    // Add explicit mouse and touch areas so that the child nodes can all be non-pickable.
    this.mouseArea = Shape.rectangle( 0, 0, buttonWidth, buttonHeight );
    this.touchArea = Shape.rectangle( -options.touchExpansionX, -options.touchExpansionY, buttonWidth + options.touchExpansionX * 2, buttonHeight + options.touchExpansionY * 2 );

    // Mutate with the options after the layout is complete so that
    // width-dependent fields like centerX will work.
    thisButton.mutate( options );
  }

  return inherit( AbstractPushButton, RectangularPushButton );
} );<commit_msg>Improved horizontal gradient.<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * A rectangular push button that draws gradients and such in order to create
 * a somewhat 3D look.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // Includes
  var AbstractPushButton = require( 'SUN/experimental/buttons/AbstractPushButton' );
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LinearGradient = require( 'SCENERY/util/LinearGradient' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var Shape = require( 'KITE/Shape' );
  var Vector2 = require( 'DOT/Vector2' );

  // Constants
  var VERTICAL_HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var HORIZONTAL_HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var SHADE_GRADIENT_LENGTH = 3; // In screen coords, which are roughly pixels.

  /**
   * @param {Node} content - Node to put on surface of button, could be text, icon, or whatever
   * @param {Object} options
   * @constructor
   */
  function RectangularPushButton( content, options ) {

    var thisButton = this;

    options = _.extend( {
      // Default values.
      cursor: 'pointer',
      cornerRounding: 4,
      baseColor: new Color( 153, 206, 255 ),
      disabledBaseColor: new Color( 220, 220, 220 ),
      xPadding: 5,
      yPadding: 5,
      listener: null,
      fireOnDown: false,
      touchExpansionX: 5,
      touchExpansionY: 5,
      stroke: null, // No outline stroke by default
      lineWidth: 1 // Only meaningful if stroke is non-null
    }, options );

    AbstractPushButton.call( thisButton, { listener: options.listener, fireOnDown: options.fireOnDown } );

    var buttonWidth = content.width + options.xPadding * 2;
    var buttonHeight = content.height + options.yPadding * 2;
    var upCenter = new Vector2( buttonWidth / 2, buttonHeight / 2 );
    var downCenter = upCenter.plus( new Vector2( 0.0, 0.0 ) ); // TODO: Set to zero on 3/36/2014 because text was moving inconsistently.  Decide whether to eliminate completely.
    var verticalHighlightStop = VERTICAL_HIGHLIGHT_GRADIENT_LENGTH / buttonHeight;
    var verticalShadowStop = 1 - SHADE_GRADIENT_LENGTH / buttonHeight;
    var horizontalHighlightStop = HORIZONTAL_HIGHLIGHT_GRADIENT_LENGTH / buttonWidth;
    var horizontalShadowStop = 1 - SHADE_GRADIENT_LENGTH / buttonWidth;
    var baseColor = options.baseColor;
    var disabledBaseColor = options.disabledBaseColor;
    var transparentBaseColor = new Color( baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), 0 );
    var transparentDisabledBaseColor = new Color( disabledBaseColor.getRed(), disabledBaseColor.getGreen(), disabledBaseColor.getBlue(), 0 );
    var lightenedStroke = null;
    if ( options.stroke ) {
      lightenedStroke = options.stroke instanceof Color ? options.stroke.colorUtilsBrighter( 0.5 ) : new Color( options.stroke ).colorUtilsBrighter( 0.5 );
    }
    var transparentWhite = new Color( 256, 256, 256, 0.7 );

    // Create the gradient fills used for various button states
    var upFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor )
      .addColorStop( verticalShadowStop, baseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var upFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, transparentWhite )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

//    var overFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
//      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.9 ) )
//      .addColorStop( horizontalHighlightStop * 2, transparentBaseColor )
//      .addColorStop( horizontalShadowStop, transparentBaseColor )
//      .addColorStop( 1, baseColor.colorUtilsDarker( 0.3 ) );
//    var overFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
//      .addColorStop( 0, black.colorUtilsBrighter( 0.9 ) )
//      .addColorStop( horizontalHighlightStop * 2, new Color( 0, 0, 0, 0 ) )
//      .addColorStop( horizontalShadowStop, transparentBaseColor )
//      .addColorStop( 1, baseColor.colorUtilsDarker( 0.3 ) );
    var overFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, transparentWhite )
      .addColorStop( horizontalHighlightStop / 2, new Color( 256, 256, 256, 0 ) )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.3 ) );

    var downFill = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop * 0.67, baseColor.colorUtilsDarker( 0.3 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.2 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentDisabledBaseColor )
      .addColorStop( horizontalShadowStop, transparentDisabledBaseColor )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    // Create the basic button shape.
    var background = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRounding, options.cornerRounding,
      {
        fill: options.baseColor,
        lineWidth: options.lineWidth
      } );
    this.addChild( background );

    // Create the overlay that is used to add horizontal shading.
    var overlayForHorizGradient = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRounding, options.cornerRounding,
      {
        fill: options.baseColor,
        stroke: options.stroke,
        lineWidth: options.lineWidth
      } );
    this.addChild( overlayForHorizGradient );

    content.center = upCenter;
    thisButton.addChild( content );

    // Hook up the function that will modify button appearance as the state changes.
    this.buttonModel.interactionState.link( function( interactionState ) {

      switch( interactionState ) {

        case 'idle':
          content.center = upCenter;
          content.opacity = 1;
          background.fill = upFillVertical;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = upFillHorizontal;
          thisButton.cursor = 'pointer';
          break;

        case 'over':
          content.center = upCenter;
          content.opacity = 1;
          background.fill = overFillVertical;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = overFillHorizontal;
          thisButton.cursor = 'pointer';
          break;

        case 'pressed':
          content.center = downCenter;
          content.opacity = 1;
          background.fill = downFill;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = overFillHorizontal;
          thisButton.cursor = 'pointer';
          break;

        case 'disabled':
          content.center = upCenter;
          content.opacity = 0.3;
          background.fill = disabledFillVertical;
          background.stroke = lightenedStroke;
          overlayForHorizGradient.stroke = lightenedStroke;
          overlayForHorizGradient.fill = disabledFillHorizontal;
          thisButton.cursor = null;
          break;
      }
    } );

    // Add explicit mouse and touch areas so that the child nodes can all be non-pickable.
    this.mouseArea = Shape.rectangle( 0, 0, buttonWidth, buttonHeight );
    this.touchArea = Shape.rectangle( -options.touchExpansionX, -options.touchExpansionY, buttonWidth + options.touchExpansionX * 2, buttonHeight + options.touchExpansionY * 2 );

    // Mutate with the options after the layout is complete so that
    // width-dependent fields like centerX will work.
    thisButton.mutate( options );
  }

  return inherit( AbstractPushButton, RectangularPushButton );
} );<|endoftext|>


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

    angular
        .module('atlasSearchResults')
        .constant('SEARCH_CONFIG', {
            QUERY_ENDPOINTS: [
                {
                    slug: 'adres',
                    label_singular: 'Adres',
                    label_plural: 'Adressen',
                    uri: 'atlas/search/adres/'
                }, {
                    slug: 'subject',
                    label_singular: 'Kadastraal subject',
                    label_plural: 'Kadastrale subjecten',
                    uri: 'atlas/search/kadastraalsubject/'
                }, {
                    slug: 'object',
                    label_singular: 'Kadastraal object',
                    label_plural: 'Kadastrale objecten',
                    uri: 'atlas/search/kadastraalobject/'
                }, {
                    slug: 'openbareruimte',
                    label_singular: 'Openbare ruimte',
                    label_plural: 'Openbare ruimtes',
                    uri: 'atlas/search/openbareruimte/'
                }, {
                    slug: 'meetbouten',
                    label_singular: 'Meetbout',
                    label_plural: 'Meetbouten',
                    uri: 'meetbouten/search/'
                }, {
                    slug: 'bouwblokken',
                    label_singular: 'Bouwblok',
                    label_plural: 'Bouwblokken',
                    uri: 'atlas/search/bouwblok/'
                }
            ],
            COORDINATES_ENDPOINTS: [
                {
                    uri: 'geosearch/nap/',
                    radius: 25
                }, {
                    uri: 'geosearch/atlas/',
                    radius: null
                }
            ],
            COORDINATES_HIERARCHY: [
                {
                    //The slug variable is used to indentify this category in geosearch.factory.js
                    slug: 'pand',
                    label_singular: 'Pand',
                    label_plural: 'Panden',
                    features: ['bag/pand']
                }, {
                    label_singular: 'Standplaats',
                    label_plural: 'Standplaatsen',
                    features: ['bag/standplaats']
                }, {
                    label_singular: 'Ligplaats',
                    label_plural: 'Ligplaatsen',
                    features: ['bag/ligplaats']
                }, {
                    label_singular: 'Openbare ruimte',
                    label_plural: 'Openbare ruimtes',
                    features: ['bag/openbareruimte']
                }, {
                    label_singular: 'Kadastraal object',
                    label_plural: 'Kadastrale objecten',
                    features: ['kadaster/kadastraal_object']
                }, {
                    label_singular: 'Gebied',
                    label_plural: 'Gebieden',
                    features: [
                        'gebieden/stadsdeel',
                        'gebieden/gebiedsgerichtwerken',
                        'gebieden/grootstedelijkgebied',
                        'gebieden/buurtcombinatie',
                        'gebieden/buurt',
                        'gebieden/bouwblok',
                        'gebieden/unesco'
                    ]
                }, {
                    label_singular: 'Gemeentelijke beperking',
                    label_plural: 'Gemeentelijke beperkingen',
                    features: ['wkpb/beperking']
                }, {
                    label_singular: 'Meetbout',
                    label_plural: 'Meetbouten',
                    features: ['meetbouten/meetbout']
                }, {
                    label_singular: 'NAP Peilmerk',
                    label_plural: 'NAP Peilmerken',
                    features: ['nap/peilmerk']
                }
            ]
        });
})();<commit_msg>changes the order of search result categories<commit_after>(function () {
    'use strict';

    angular
        .module('atlasSearchResults')
        .constant('SEARCH_CONFIG', {
            QUERY_ENDPOINTS: [
                {
                    slug: 'openbareruimte',
                    label_singular: 'Openbare ruimte',
                    label_plural: 'Openbare ruimtes',
                    uri: 'atlas/search/openbareruimte/'
                }, {
                    slug: 'adres',
                    label_singular: 'Adres',
                    label_plural: 'Adressen',
                    uri: 'atlas/search/adres/'
                }, {
                    slug: 'object',
                    label_singular: 'Kadastraal object',
                    label_plural: 'Kadastrale objecten',
                    uri: 'atlas/search/kadastraalobject/'
                }, {
                    slug: 'subject',
                    label_singular: 'Kadastraal subject',
                    label_plural: 'Kadastrale subjecten',
                    uri: 'atlas/search/kadastraalsubject/'
                }, {
                    slug: 'bouwblokken',
                    label_singular: 'Bouwblok',
                    label_plural: 'Bouwblokken',
                    uri: 'atlas/search/bouwblok/'
                }, {
                    slug: 'meetbouten',
                    label_singular: 'Meetbout',
                    label_plural: 'Meetbouten',
                    uri: 'meetbouten/search/'
                }
            ],
            COORDINATES_ENDPOINTS: [
                {
                    uri: 'geosearch/nap/',
                    radius: 25
                }, {
                    uri: 'geosearch/atlas/',
                    radius: null
                }
            ],
            COORDINATES_HIERARCHY: [
                {
                    label_singular: 'Openbare ruimte',
                    label_plural: 'Openbare ruimtes',
                    features: ['bag/openbareruimte']
                }, {
                    //The slug variable is used to indentify this category in geosearch.factory.js
                    slug: 'pand',
                    label_singular: 'Pand',
                    label_plural: 'Panden',
                    features: ['bag/pand']
                }, {
                    label_singular: 'Standplaats',
                    label_plural: 'Standplaatsen',
                    features: ['bag/standplaats']
                }, {
                    label_singular: 'Ligplaats',
                    label_plural: 'Ligplaatsen',
                    features: ['bag/ligplaats']
                }, {
                    label_singular: 'Kadastraal object',
                    label_plural: 'Kadastrale objecten',
                    features: ['kadaster/kadastraal_object']
                }, {
                    label_singular: 'Gemeentelijke beperking',
                    label_plural: 'Gemeentelijke beperkingen',
                    features: ['wkpb/beperking']
                }, {
                    label_singular: 'Gebied',
                    label_plural: 'Gebieden',
                    features: [
                        'gebieden/stadsdeel',
                        'gebieden/gebiedsgerichtwerken',
                        'gebieden/grootstedelijkgebied',
                        'gebieden/unesco',
                        'gebieden/buurtcombinatie',
                        'gebieden/buurt',
                        'gebieden/bouwblok'
                    ]
                }, {
                    label_singular: 'Meetbout',
                    label_plural: 'Meetbouten',
                    features: ['meetbouten/meetbout']
                }, {
                    label_singular: 'NAP Peilmerk',
                    label_plural: 'NAP Peilmerken',
                    features: ['nap/peilmerk']
                }
            ]
        });
})();<|endoftext|>