<commit_before>/* This notice must be untouched at all times.

wz_tooltip.js    v. 3.3

The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de

Copyright (c) 2002-2004 Walter Zorn. All rights reserved.
Created 1. 12. 2002 by Walter Zorn (Web: http://www.walterzorn.com )
Last modified: 27. 4. 2005

Cross-browser tooltips working even in Opera 5 and 6,
as well as in NN 4, Gecko-Browsers, IE4+, Opera 7 and Konqueror.
No onmouseouts required.
Appearance of tooltips can be individually configured
via commands within the onmouseovers.

LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/

////////////////  GLOBAL TOOPTIP CONFIGURATION  /////////////////////
var ttBgColor      = "#e6ecff";
var ttBgImg        = "";           // path to background image;
var ttBorderColor  = "#003399";
var ttBorderWidth  = 1;
var ttDelay        = 500;          // time span until tooltip shows up [milliseconds]
var ttFontColor    = "#000066";
var ttFontFace     = "arial,helvetica,sans-serif";
var ttFontSize     = "11px";
var ttFontWeight   = "normal";     // alternative is "bold";
var ttOffsetX      = 12;            // horizontal offset of left-top corner from mousepointer
var ttOffsetY      = 15;           // vertical offset                   "
var ttOpacity      = 100;          // opacity of tooltip in percent (must be integer between 0 and 100)
var ttPadding      = 3;            // spacing between border and content
var ttShadowColor  = "";
var ttShadowWidth  = 0;
var ttTemp         = 0;            // time span after which the tooltip disappears; 0 (zero) means "infinite timespan"
var ttTextAlign    = "left";
var ttTitleColor   = "#ffffff";    // color of caption text
var ttWidth        = 300;
////////////////////  END OF TOOLTIP CONFIG  ////////////////////////

//////////////  TAGS WITH TOOLTIP FUNCTIONALITY  ////////////////////
// List may be extended or shortened:
var tt_tags = new Array("a","area","b","big","caption","center","code","dd","div","dl","dt","em","h1","h2","h3","h4","h5","h6","i","img","input","li","map","ol","p","pre","s","small","span","strike","strong","sub","sup","table","td","th","tr","tt","u","var","ul","layer");
/////////////////////////////////////////////////////////////////////

///////// DON'T CHANGE ANYTHING BELOW THIS LINE /////////////////////
var tt_obj,                // current tooltip
tt_objW = 0, tt_objH = 0,  // width and height of tt_obj
tt_objX = 0, tt_objY = 0,
tt_offX = 0, tt_offY = 0,
xlim = 0, ylim = 0,        // right and bottom borders of visible client area
tt_sup = false,            // true if T_ABOVE cmd
tt_sticky = false,         // tt_obj sticky?
tt_wait = false,
tt_act = false,            // tooltip visibility flag
tt_sub = false,            // true while tooltip below mousepointer
tt_u = "undefined",
tt_mf,                     // stores previous mousemove evthandler
tt_inputs = new Array(),   // drop-down-boxes to be hidden in IE
// Opera: disable href when hovering
tt_tag = null;             // stores hovered dom node, href and previous statusbar txt

var tt_db,
tt_n = navigator.userAgent.toLowerCase();

function tt_init() {
    tt_db = (document.compatMode && document.compatMode != "BackCompat") ?
        document.documentElement : document.body? document.body : null;
    // Browser flags
    tt_op = !!(window.opera && document.getElementById),
    tt_op6 = tt_op && !document.defaultView,
    tt_op7 = tt_op && !tt_op6,
    tt_ie = tt_n.indexOf("msie") != -1 && document.all && tt_db && !tt_op,
    tt_n4 = (document.layers && typeof document.classes != tt_u) ? true : false,
    tt_n6 = (!tt_op && document.defaultView && typeof document.defaultView.getComputedStyle != tt_u),
    tt_w3c = !tt_ie && !tt_n6 && !tt_op && document.getElementById;
}

function tt_Int(t_x)
{
	var t_y;
	return isNaN(t_y = parseInt(t_x))? 0 : t_y;
}

function wzReplace(t_x, t_y)
{
	var t_ret = "",
	t_str = this,
	t_xI;
	while((t_xI = t_str.indexOf(t_x)) != -1)
	{
		t_ret += t_str.substring(0, t_xI) + t_y;
		t_str = t_str.substring(t_xI + t_x.length);
	}
	return t_ret+t_str;
}
String.prototype.wzReplace = wzReplace;

function tt_N4Tags(tagtyp, t_d, t_y)
{
	t_d = t_d || document;
	t_y = t_y || new Array();
	var t_x = (tagtyp=="a")? t_d.links : t_d.layers;
	for(var z = t_x.length; z--;) t_y[t_y.length] = t_x[z];
	for(z = t_d.layers.length; z--;) t_y = tt_N4Tags(tagtyp, t_d.layers[z].document, t_y);
	return t_y;
}

function tt_GetSelects()
{
	if (!tt_op6 && !tt_ie) return;
	var t_i, t_s = tt_op6? "input" : "select";
	if (document.all)
	{
		t_i = document.all.tags(t_s).length; while(t_i--)
			tt_inputs[t_i] = document.all.tags(t_s)[t_i];
	}
	else if (document.getElementsByTagName)
	{
		t_i = document.getElementsByTagName(t_s).length; while(t_i--)
			tt_inputs[t_i] = document.getElementsByTagName(t_s)[t_i];
	}
	t_i = tt_inputs.length; while(t_i--)
	{
		tt_inputs[t_i].vis = '';
		tt_inputs[t_i].x = 0;
		tt_inputs[t_i].y = 0;
		var t_o = tt_inputs[t_i];
		while(t_o)
		{
			tt_inputs[t_i].x += t_o.offsetLeft || 0;
			tt_inputs[t_i].y += t_o.offsetTop|| 0;
			t_o = t_o.offsetParent;
		}
	}
}

function tt_Htm(tt, t_id, txt)
{
	var t_bgc = (typeof tt.T_BGCOLOR != tt_u)? tt.T_BGCOLOR : ttBgColor,
	t_bgimg   = (typeof tt.T_BGIMG != tt_u)? tt.T_BGIMG : ttBgImg,
	t_bc      = (typeof tt.T_BORDERCOLOR != tt_u)? tt.T_BORDERCOLOR : ttBorderColor,
	t_bw      = (typeof tt.T_BORDERWIDTH != tt_u)? tt.T_BORDERWIDTH : ttBorderWidth,
	t_ff      = (typeof tt.T_FONTFACE != tt_u)? tt.T_FONTFACE : ttFontFace,
	t_fc      = (typeof tt.T_FONTCOLOR != tt_u)? tt.T_FONTCOLOR : ttFontColor,
	t_fsz     = (typeof tt.T_FONTSIZE != tt_u)? tt.T_FONTSIZE : ttFontSize,
	t_fwght   = (typeof tt.T_FONTWEIGHT != tt_u)? tt.T_FONTWEIGHT : ttFontWeight,
	t_opa     = (typeof tt.T_OPACITY != tt_u)? tt.T_OPACITY : ttOpacity,
	t_padd    = (typeof tt.T_PADDING != tt_u)? tt.T_PADDING : ttPadding,
	t_shc     = (typeof tt.T_SHADOWCOLOR != tt_u)? tt.T_SHADOWCOLOR : (ttShadowColor || 0),
	t_shw     = (typeof tt.T_SHADOWWIDTH != tt_u)? tt.T_SHADOWWIDTH : (ttShadowWidth || 0),
	t_algn    = (typeof tt.T_TEXTALIGN != tt_u)? tt.T_TEXTALIGN : ttTextAlign,
	t_tit     = (typeof tt.T_TITLE != tt_u)? tt.T_TITLE : "",
	t_titc    = (typeof tt.T_TITLECOLOR != tt_u)? tt.T_TITLECOLOR : ttTitleColor,
	t_w       = (typeof tt.T_WIDTH != tt_u)? tt.T_WIDTH  : ttWidth;
	if (t_shc || t_shw)
	{
		t_shc = t_shc || "#cccccc";
		t_shw = t_shw || 5;
	}
	if (tt_n4 && (t_fsz == "10px" || t_fsz == "11px")) t_fsz = "12px";

	var t_optx = (tt_n4? '' : tt_n6? ('-moz-opacity:'+(t_opa/100.0)) : tt_ie? ('filter:Alpha(opacity='+t_opa+')') : ('opacity:'+(t_opa/100.0))) + ';';
	var t_y = '
' +
		'
';
	if (t_tit)
	{
		t_y += '
' +
			(tt_n4? ' ' : '')+t_tit+'<\/b><\/font><\/td><\/tr>';
	}
	t_y += '

' +
		'
';
	if (t_fwght == 'bold') t_y += '';
	t_y += txt;
	if (t_fwght == 'bold') t_y += '<\/b>';
	t_y += '<\/font><\/td><\/tr><\/table><\/td><\/tr><\/table>';
	if (t_shw)
	{
		var t_spct = Math.round(t_shw*1.3);
		if (tt_n4)
		{
			t_y += '<layer bgcolor="'+t_shc+'" left="'+t_w+'" top="'+t_spct+'" width="'+t_shw+'" height="0"><\/layer>' +
				'<layer bgcolor="'+t_shc+'" left="'+t_spct+'" align="bottom" width="'+(t_w-t_spct)+'" height="'+t_shw+'"><\/layer>';
		}
		else
		{
			t_optx = tt_n6? '-moz-opacity:0.85;' : tt_ie? 'filter:Alpha(opacity=85);' : 'opacity:0.85;';
			t_y += '
<\/div>' +
				'
<\/div>';
		}
	}
	return t_y+'<\/div>';
}

function tt_EvX(t_e)
{
	var t_y = tt_Int(t_e.pageX || t_e.clientX || 0) +
		tt_Int(tt_ie? tt_db.scrollLeft : 0) +
		tt_offX;
	if (t_y > xlim) t_y = xlim;
	var t_scr = tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0);
	if (t_y < t_scr) t_y = t_scr;
	return t_y;
}

function tt_EvY(t_e)
{
    var t_y = tt_Int(t_e.pageY || t_e.clientY || 0) +
		tt_Int(tt_ie? tt_db.scrollTop : 0);
	if (tt_sup) t_y -= (tt_objH + tt_offY - 15);
	else if (t_y > ylim || !tt_sub && t_y > ylim-24)
	{
		t_y -= (tt_objH + 5);
		tt_sub = false;
	}
	else
	{
		t_y += tt_offY;
		tt_sub = true;
	}
	return t_y;
}

function tt_ReleasMov()
{
	if (document.onmousemove == tt_Move)
	{
		if (!tt_mf && document.releaseEvents) document.releaseEvents(Event.MOUSEMOVE);
		document.onmousemove = tt_mf;
	}
}

function tt_HideInput()
{
	if (!(tt_ie || tt_op6) || !tt_inputs) return;
    var t_o;
	var t_i = tt_inputs.length; while(t_i--)
	{
		t_o = tt_inputs[t_i];
		if (tt_act && !t_o.vis && tt_objX+tt_objW > t_o.x && tt_objX < t_o.x+t_o.offsetWidth && tt_objY+tt_objH > t_o.y && tt_objY < t_o.y+t_o.offsetHeight)
		{
            t_o.vis = t_o.currentStyle? t_o.currentStyle.visibility : t_o.style.visibility;
			t_o.style.visibility = 'hidden';
		}
		else if (t_o.vis)
		{
			t_o.style.visibility = t_o.vis;
			t_o.vis = '';
		}
	}
}

function tt_GetDiv(t_id)
{
	return(
		tt_n4? (document.layers[t_id] || null)
		: tt_ie? (document.all[t_id] || null)
		: (document.getElementById(t_id) || null)
	);
}

function tt_GetDivW()
{
	return tt_Int(
		tt_n4? tt_obj.clip.width
		: (tt_obj.style.pixelWidth || tt_obj.offsetWidth)
	);
}

function tt_GetDivH()
{
	return tt_Int(
		tt_n4? tt_obj.clip.height
		: (tt_obj.style.pixelHeight || tt_obj.offsetHeight)
	);
}

// Compat with DragDrop Lib: Ensure that z-index of tooltip is lifted beyond toplevel dragdrop element
function tt_SetDivZ()
{
	var t_i = tt_obj.style || tt_obj;
	if (window.dd && dd.z)
		t_i.zIndex = Math.max(dd.z+1, t_i.zIndex);
}

function tt_SetDivPos(t_x, t_y)
{
	var t_i = tt_obj.style || tt_obj;
	var t_px = (tt_op6 || tt_n4)? '' : 'px';
    t_i.left =(tt_objX = t_x) + t_px;
    t_i.top = (tt_objY = t_y) + t_px;
    //tt_HideInput(); // avernet: Removed this as it creates flickering on IE
}

function tt_ShowDiv(t_x)
{
	if (tt_n4) tt_obj.visibility = t_x? 'show' : 'hide';
	else tt_obj.style.visibility = t_x? 'visible' : 'hidden';
	tt_act = t_x;
	tt_HideInput();
}

function tt_OpDeHref(t_e)
{
	if (t_e && t_e.target.hasAttribute("href"))
	{
		tt_tag = t_e.target;
		tt_tag.t_href = tt_tag.getAttribute("href");
		tt_tag.removeAttribute("href");
		tt_tag.style.cursor = "hand";
		tt_tag.onmousedown = tt_OpReHref;
		tt_tag.stats = window.status;
		window.status = tt_tag.t_href;
	}
}

function tt_OpReHref()
{
	if (tt_tag)
	{
		tt_tag.setAttribute("href", tt_tag.t_href);
		window.status = tt_tag.stats;
		tt_tag = null;
	}
}

function tt_Show(t_e, t_id, t_sup, t_delay, t_fix, t_left, t_offx, t_offy, t_static, t_sticky, t_temp)
{
	if (tt_obj) tt_Hide();
	tt_mf = document.onmousemove || null;
	if (window.dd && (window.DRAG && tt_mf == DRAG || window.RESIZE && tt_mf == RESIZE)) return;
	var t_uf = document.onmouseup || null;
	if (tt_mf && t_uf) t_uf(t_e);

	tt_obj = tt_GetDiv(t_id);
	if (tt_obj)
	{
		t_e = t_e || window.event;
		tt_sub = !(tt_sup = t_sup);
		tt_sticky = t_sticky;
		tt_objW = tt_GetDivW();
		tt_objH = tt_GetDivH();
		tt_offX = t_left? -(tt_objW+t_offx) : t_offx;
		tt_offY = t_offy;
		if (tt_op7) tt_OpDeHref(t_e);
		if (tt_n4)
		{
			if (tt_obj.document.layers.length)
			{
				var t_sh = tt_obj.document.layers[0];
				t_sh.clip.height = tt_objH - Math.round(t_sh.clip.width*1.3);
			}
		}
		else
		{
			var t_sh = tt_GetDiv(t_id+'R');
			if (t_sh)
			{
				var t_h = tt_objH - tt_Int(t_sh.style.pixelTop || t_sh.style.top || 0);
				if (typeof t_sh.style.pixelHeight != tt_u) t_sh.style.pixelHeight = t_h;
				else t_sh.style.height = t_h+'px';
			}
		}

		tt_GetSelects();

		xlim = tt_Int((tt_db && tt_db.clientWidth)? tt_db.clientWidth : window.innerWidth) +
			tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0) -
			tt_objW -
			(tt_n4? 21 : 0);
		ylim = tt_Int(window.innerHeight || tt_db.clientHeight) +
			tt_Int(window.pageYOffset || (tt_db? tt_db.scrollTop : 0) || 0) -
			tt_objH - tt_offY;

        tt_SetDivZ();
        if (t_fix) tt_SetDivPos(tt_Int((t_fix = t_fix.split(','))[0]), tt_Int(t_fix[1]));
		else tt_SetDivPos(tt_EvX(t_e), tt_EvY(t_e));

		var t_txt = 'tt_ShowDiv(\'true\');';
		if (t_sticky) t_txt += '{'+
				'tt_ReleasMov();'+
				'window.tt_upFunc = document.onmouseup || null;'+
				'if (document.captureEvents) document.captureEvents(Event.MOUSEUP);'+
				'document.onmouseup = new Function("window.setTimeout(\'tt_Hide();\', 10);");'+
			'}';
		else if (t_static) t_txt += 'tt_ReleasMov();';
		if (t_temp > 0) t_txt += 'window.tt_rtm = window.setTimeout(\'tt_sticky = false; tt_Hide();\','+t_temp+');';
		window.tt_rdl = window.setTimeout(t_txt, t_delay);

		if (!t_fix)
		{
			if (document.captureEvents) document.captureEvents(Event.MOUSEMOVE);
			document.onmousemove = tt_Move;
		}
	}
}

var tt_area = false;
function tt_Move(t_ev)
{
	if (!tt_obj) return;
	if (tt_n6 || tt_w3c)
	{
		if (tt_wait) return;
		tt_wait = true;
		setTimeout('tt_wait = false;', 5);
	}
	var t_e = t_ev || window.event;
    tt_SetDivPos(tt_EvX(t_e), tt_EvY(t_e));
	if (tt_op6)
	{
		if (tt_area && t_e.target.tagName != 'AREA') tt_Hide();
		else if (t_e.target.tagName == 'AREA') tt_area = true;
	}
}

function tt_Hide()
{
	if (window.tt_obj)
	{
		if (window.tt_rdl) window.clearTimeout(tt_rdl);
		if (!tt_sticky || !tt_act)
		{
			if (window.tt_rtm) window.clearTimeout(tt_rtm);
			tt_ShowDiv(false);
			tt_SetDivPos(-tt_objW, -tt_objH);
			tt_obj = null;
			if (typeof window.tt_upFunc != tt_u) document.onmouseup = window.tt_upFunc;
		}
		tt_sticky = false;
		if (tt_op6 && tt_area) tt_area = false;
		tt_ReleasMov();
		if (tt_op7) tt_OpReHref();
		tt_HideInput();
	}
}

function tt_Init()
{
	if (!(tt_op || tt_n4 || tt_n6 || tt_ie || tt_w3c)) return;

	var htm = tt_n4? '
<\/div>' : '',
	tags,
	t_tj,
	over,
	esc = 'return escape(';
	var i = tt_tags.length; while(i--)
	{
		tags = tt_ie? (document.all.tags(tt_tags[i]) || 1)
			: document.getElementsByTagName? (document.getElementsByTagName(tt_tags[i]) || 1)
			: (!tt_n4 && tt_tags[i]=="a")? document.links
			: 1;
		if (tt_n4 && (tt_tags[i] == "a" || tt_tags[i] == "layer")) tags = tt_N4Tags(tt_tags[i]);
		var j = tags.length; while(j--)
		{
			if (typeof (t_tj = tags[j]).onmouseover == "function" && t_tj.onmouseover.toString().indexOf(esc) != -1 && !tt_n6 || tt_n6 && (over = t_tj.getAttribute("onmouseover")) && over.indexOf(esc) != -1)
			{
				if (over) t_tj.onmouseover = new Function(over);
				var txt = unescape(t_tj.onmouseover());
				htm += tt_Htm(
					t_tj,
					"tOoLtIp"+i+""+j,
					txt.wzReplace("& ","&")
				);

				t_tj.onmouseover = new Function('e',
					'tt_Show(e,'+
					'"tOoLtIp' +i+''+j+ '",'+
					(typeof t_tj.T_ABOVE != tt_u)+','+
					((typeof t_tj.T_DELAY != tt_u)? t_tj.T_DELAY : ttDelay)+','+
					((typeof t_tj.T_FIX != tt_u)? '"'+t_tj.T_FIX+'"' : '""')+','+
					(typeof t_tj.T_LEFT != tt_u)+','+
					((typeof t_tj.T_OFFSETX != tt_u)? t_tj.T_OFFSETX : ttOffsetX)+','+
					((typeof t_tj.T_OFFSETY != tt_u)? t_tj.T_OFFSETY : ttOffsetY)+','+
					(typeof t_tj.T_STATIC != tt_u)+','+
					(typeof t_tj.T_STICKY != tt_u)+','+
					((typeof t_tj.T_TEMP != tt_u)? t_tj.T_TEMP : ttTemp)+
					');'
				);
				t_tj.onmouseout = tt_Hide;
				if (t_tj.alt) t_tj.alt = "";
				if (t_tj.title) t_tj.title = "";
			}
		}
	}
	document.write(htm);
}

//tt_Init();
<commit_msg>Fix [ #306018 ] Tool tip showing partly off-screen<commit_after><|endoftext|>


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

    angular
        .module('fedramp.components')
        .component('gridSort', {
            templateUrl: 'src/fedramp.components/grid-sort.html',
            require: {
                gridController: '^grid'
            },
            controller: GridSort,
            controllerAs: 'controller',
            bindings: {
                name: '@',
                property: '@',
                caseSensitive: '@',
                header: '@',
                default: '@'
            }
        });

    GridSort.$inject = ['$log', '$parse', '$element'];

    /**
     * @constructor
     * @memberof Components
     * @example <grid-sort property="provider" header="Provider"></grid-sort>
     */
    function GridSort($log, $parse, $element){
        var self = this;
        self.activated = null;

        self.asc = true;

        self.$onInit = $onInit;
        self.sort = sort;
        self.highlight = highlight;
        self.toggleSort = toggleSort;
        self.clear = clear;

        function $onInit(){
            if(!self.name){
                throw 'Name must be specified for sort filter';
            }
            if(self.property){
                self.sortFunc = sortFunc;
            }
            restoreState();
            self.gridController.addSort(self);
        }

        /**
         * Stores the sort information to the grid state.
         *
         * @public
         * @memberof Components.GridSort
         */
        function saveState(){
            // Merge any existing parameters
            var existingParams =
                angular.extend(
                    self.gridController.state,{
                        'sort': (self.asc ? '' : '-') + self.name
                    });

            // Update url
            self.gridController.stateUpdate(existingParams);
        }

        /**
         * Restores the latest saved sort.
         *
         * @public
         * @memberof Components.GridSort
         */
        function restoreState(){
            var sortParam = self.gridController.state.sort;
            if(!sortParam){
                loadDefaultSort();
                return;
            }

            var m = sortParam.match(/(-)?(.*)/);
            if(m[2] !== self.name){
                return;
            }

            self.asc = (m[1] === undefined);
            self.activated = true;
            self.sort(self.asc);
        }

        /**
         * Loads a specified default sort. This is to ensure a grid applies a sort when first loaded.
         *
         * @public
         * @memberof Components.GridSort
         */
        function loadDefaultSort(){
            if(self.default){
                // Parse if default should be in asc/desc
                self.asc = self.default.split('-').reduce(function(p, c){
                    return false;
                });
                self.sort(self.asc);
            }
        }

        /**
         * Sorts a list of items in the grid controller by the property for this particular
         * grid sort.
         *
         * @public
         * @memberof Components.GridSort
         * @param {boolean} doAscending
         * Sort direction to use
         */
        function sort(doAscending){
            self.activated = angular.isDefined(doAscending);
            self.asc = doAscending;
            self.gridController.defaultSort = self;
            self.gridController.items.sort(self.sortFunc);
            $element.addClass('sort-selected');
            // Update state of all sorts
            self.gridController.updateSort();
            saveState();

        }

        /**
         * Toggles the sort. To maintain a consistent interaction, we always set the toggle to ascending
         * if the sort is not activated. This case would be hit when the user has clicked on the sort for the
         * first time or after another sort.
         *
         * @public
         * @memberof Components.GridSort
         */
        function toggleSort(){
            if(!self.activated){
                self.sort(true);
                return;
            }
            self.sort(!self.asc);
        }

        /**
         * Performs a generic sort.
         *
         * @public
         * @memberof Components.GridSort
         */
        function sortFunc(_a, _b) {
            // Enables to sort on multiple properties for a specific grid sort.
            var props = self.property.split(',');

            for(var x = 0; x < props.length; x++){
                var a = $parse(props[x])(_a);
                var b = $parse(props[x])(_b);

                // If we're dealing with numbers, delegate to number sort func
                if(angular.isNumber(a)){
                    return numberSortFunc(a, b);
                }

                // Normalize everything and make it all lowercase for fair comparison
                a = a.toLowerCase();
                b = b.toLowerCase();

                if(a < b){
                    return self.asc ? -1 : 1;
                }
                if(a > b) {
                    return self.asc ? 1 : -1;
                }
            }
            return 0;
        }

        /**
         * Handles generic numerical sort.
         */
        function numberSortFunc(a, b){
            if(self.asc){
                return a - b;
            }
            return b - a;
        }

        /**
         * Determines whether to highlight sort selected option.
         */
        function highlight(asc){
            if(!self.activated){
                return false;
            }
            if(self !== self.gridController.defaultSort){
                return false;
            }
            if(self.asc === asc){
                return true;
            }
            return false;
        }

        /**
         * Clears the sorting.
         *
         * @public
         * @memberof Components.GridSort
         */
        function clear(){
            self.activated = false;
            $element.removeClass('sort-selected');
        }
    }

})();
<commit_msg>Fixed sorting on service models<commit_after>(function () {
    'use strict';

    angular
        .module('fedramp.components')
        .component('gridSort', {
            templateUrl: 'src/fedramp.components/grid-sort.html',
            require: {
                gridController: '^grid'
            },
            controller: GridSort,
            controllerAs: 'controller',
            bindings: {
                name: '@',
                property: '@',
                caseSensitive: '@',
                header: '@',
                default: '@'
            }
        });

    GridSort.$inject = ['$log', '$parse', '$element'];

    /**
     * @constructor
     * @memberof Components
     * @example <grid-sort property="provider" header="Provider"></grid-sort>
     */
    function GridSort($log, $parse, $element){
        var self = this;
        self.activated = null;

        self.asc = true;

        self.$onInit = $onInit;
        self.sort = sort;
        self.highlight = highlight;
        self.toggleSort = toggleSort;
        self.clear = clear;

        function $onInit(){
            if(!self.name){
                throw 'Name must be specified for sort filter';
            }
            if(self.property){
                self.sortFunc = sortFunc;
            }
            restoreState();
            self.gridController.addSort(self);
        }

        /**
         * Stores the sort information to the grid state.
         *
         * @public
         * @memberof Components.GridSort
         */
        function saveState(){
            // Merge any existing parameters
            var existingParams =
                angular.extend(
                    self.gridController.state,{
                        'sort': (self.asc ? '' : '-') + self.name
                    });

            // Update url
            self.gridController.stateUpdate(existingParams);
        }

        /**
         * Restores the latest saved sort.
         *
         * @public
         * @memberof Components.GridSort
         */
        function restoreState(){
            var sortParam = self.gridController.state.sort;
            if(!sortParam){
                loadDefaultSort();
                return;
            }

            var m = sortParam.match(/(-)?(.*)/);
            if(m[2] !== self.name){
                return;
            }

            self.asc = (m[1] === undefined);
            self.activated = true;
            self.sort(self.asc);
        }

        /**
         * Loads a specified default sort. This is to ensure a grid applies a sort when first loaded.
         *
         * @public
         * @memberof Components.GridSort
         */
        function loadDefaultSort(){
            if(self.default){
                // Parse if default should be in asc/desc
                self.asc = self.default.split('-').reduce(function(p, c){
                    return false;
                });
                self.sort(self.asc);
            }
        }

        /**
         * Sorts a list of items in the grid controller by the property for this particular
         * grid sort.
         *
         * @public
         * @memberof Components.GridSort
         * @param {boolean} doAscending
         * Sort direction to use
         */
        function sort(doAscending){
            self.activated = angular.isDefined(doAscending);
            self.asc = doAscending;
            self.gridController.defaultSort = self;
            self.gridController.items.sort(self.sortFunc);
            $element.addClass('sort-selected');
            // Update state of all sorts
            self.gridController.updateSort();
            saveState();

        }

        /**
         * Toggles the sort. To maintain a consistent interaction, we always set the toggle to ascending
         * if the sort is not activated. This case would be hit when the user has clicked on the sort for the
         * first time or after another sort.
         *
         * @public
         * @memberof Components.GridSort
         */
        function toggleSort(){
            if(!self.activated){
                self.sort(true);
                return;
            }
            self.sort(!self.asc);
        }

        /**
         * Performs a generic sort.
         *
         * @public
         * @memberof Components.GridSort
         */
        function sortFunc(_a, _b) {
            // Enables to sort on multiple properties for a specific grid sort.
            var props = self.property.split(',');

            for(var x = 0; x < props.length; x++){
                var a = $parse(props[x])(_a);
                var b = $parse(props[x])(_b);

                // If we're dealing with numbers, delegate to number sort func
                if(angular.isNumber(a)){
                    return numberSortFunc(a, b);
                }
                if(angular.isArray(a)){
                    a = a.join(',');
                    b = b.join(',');
                }
                // Normalize everything and make it all lowercase for fair comparison
                a = a.toLowerCase();
                b = b.toLowerCase();

                if(a < b){
                    return self.asc ? -1 : 1;
                }
                if(a > b) {
                    return self.asc ? 1 : -1;
                }
            }
            return 0;
        }

        /**
         * Handles generic numerical sort.
         */
        function numberSortFunc(a, b){
            if(self.asc){
                return a - b;
            }
            return b - a;
        }

        /**
         * Determines whether to highlight sort selected option.
         */
        function highlight(asc){
            if(!self.activated){
                return false;
            }
            if(self !== self.gridController.defaultSort){
                return false;
            }
            if(self.asc === asc){
                return true;
            }
            return false;
        }

        /**
         * Clears the sorting.
         *
         * @public
         * @memberof Components.GridSort
         */
        function clear(){
            self.activated = false;
            $element.removeClass('sort-selected');
        }
    }

})();
<|endoftext|>


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

(function ($) {
  // Leer
  fs.readFile('bd/products.json', function (err, products) {
    if (err) throw err;
    var myObject = eval('(' + products + ')');
    var total = 0;

    $('#form1').on('submit', function (event) {

      $("#alertAddedSuccessful").hide();
      $("#alertAddedWarning").hide();
      $("#alertAddedDanger").hide();

      event.preventDefault();
      var data_table = $("#tblDatos");
      var code_product = $("#code_product").val();
      var resp = false;

      for (var cont = 0; cont < myObject.length; cont++) {
        if (code_product == myObject[cont].code) {

          data_table.append("
"+myObject[cont].code+"	"+myObject[cont].name+"	"+1+"	"+myObject[cont].price+"	<button onclick="+"fnselect("+myObject[cont].code + ")"+">"+"x"+"</button>
");

            myObject[cont].amount = myObject[cont].amount - 1;
          total = total + parseInt(myObject[cont].price);
          $("#total").text(total);
          $("#alertAddedSuccessful").show();
          if (myObject[cont].amount <= 0){
            $('#myWarningModal').modal('show');
            $("#alertAddedSuccessful").hide();
            $("#alertAddedWarning").show();
          }
          resp = true;
          break;
        }
      }
      if (resp == false) {
        $('#myDangerModal').modal('show');
        $("#alertAddedSuccessful").hide();
        $("#alertAddedWarning").hide();
        $("#alertAddedDanger").show();
      }
    });

    $("#btn_confirm").click(function () {
      var products_number = $("#tblDatos tr").length;

      if (products_number > 1) {

        fs.readFile('bd/sales.json', function (err, sales) {
          if (err) throw err;

          var mySales = eval('(' + sales + ')');
          var date = new Date();
          var size = mySales.length;

          mySales.push({ "id": size + 1, "date": date, "total": total });
          fs.writeFileSync("bd/sales.json", JSON.stringify(mySales), 'utf8');

        });

        fs.writeFileSync("bd/products.json", JSON.stringify(myObject), 'utf8');
        alert("Exito en la venta");
        location.reload();
      } else {
        alert("Error, no existen productos en la linea de venta.");
      };
    });

  });

})(jQuery);
function fnselect(value){

    var element = document.getElementById(value);
    element.remove();

}
<commit_msg>cambiar total, quitar producto<commit_after>var fs = require('fs');
var total = 0;

(function ($) {
  // Leer
  fs.readFile('bd/products.json', function (err, products) {
    if (err) throw err;
    var myObject = eval('(' + products + ')');

    $('#form1').on('submit', function (event) {

      $("#alertAddedSuccessful").hide();
      $("#alertAddedWarning").hide();
      $("#alertAddedDanger").hide();

      event.preventDefault();
      var data_table = $("#tblDatos");
      var code_product = $("#code_product").val();
      var resp = false;

      for (var cont = 0; cont < myObject.length; cont++) {
        if (code_product == myObject[cont].code) {

          data_table.append("
"+myObject[cont].code+"	"+myObject[cont].name+"	"+1+"	"+myObject[cont].price+"	<button onclick="+"fnselect("+myObject[cont].code + ")"+">"+"x"+"</button>
");

            myObject[cont].amount = myObject[cont].amount - 1;
          total = total + parseInt(myObject[cont].price);
          $("#total").text(total);
          $("#alertAddedSuccessful").show();
          if (myObject[cont].amount <= 0){
            $('#myWarningModal').modal('show');
            $("#alertAddedSuccessful").hide();
            $("#alertAddedWarning").show();
          }
          resp = true;
          break;
        }
      }
      if (resp == false) {
        $('#myDangerModal').modal('show');
        $("#alertAddedSuccessful").hide();
        $("#alertAddedWarning").hide();
        $("#alertAddedDanger").show();
      }
    });

    $("#btn_confirm").click(function () {
      var products_number = $("#tblDatos tr").length;

      if (products_number > 1) {

        fs.readFile('bd/sales.json', function (err, sales) {
          if (err) throw err;

          var mySales = eval('(' + sales + ')');
          var date = new Date();
          var size = mySales.length;

          mySales.push({ "id": size + 1, "date": date, "total": total });
          fs.writeFileSync("bd/sales.json", JSON.stringify(mySales), 'utf8');

        });

        fs.writeFileSync("bd/products.json", JSON.stringify(myObject), 'utf8');
        alert("Exito en la venta");
        location.reload();
      } else {
        alert("Error, no existen productos en la linea de venta.");
      };
    });

  });

})(jQuery);

function fnselect(value){
  var fs = require('fs');
   fs.readFile('bd/products.json', function (err, products) {
      if (err)
       throw err;
        var myObject = eval('(' + products + ')');
         for (var cont = 0; cont < myObject.length; cont++) {
            if (value == myObject[cont].code)
            {
              myObject[cont].amount = myObject[cont].amount + 1;
               total = total - parseInt(myObject[cont].price);
               $("#total").text(total);
             }
            }

       });
       var element = document.getElementById(value);
        element.remove();
       }
<|endoftext|>


<commit_before>var $ = require('jquery-browserify'),
    Vector = require('./Vector'),
    AABB = require('./AABB'),
    World = require('./World'),
    Solid = require('./Solid'),
    Player = require('./Player');

module.exports = Asymmetry;

function Asymmetry() {
    var self = this;

    this.socket = io.connect('http://localhost:9966');
    this.width  = $('#canvainer').width(),
    this.height = $('#canvainer').height(),
    this.renderer = this.createRenderer();
    this.world = this.initWorld();

    this.TILE_SIZE = 40;
    this.MAZE_BORDER = 2;
    this.maze = this.generateMaze();

    this.player = new Player(100, 100);
    window.player = this.player;
};

Asymmetry.prototype.createRenderer = function() {
    htmlCanvas = "<canvas width=" + "\"" + this.width + "\"" + "height=" + "\"" + this.height + "\"" + "></canvas>";

    $('#canvainer').append(htmlCanvas);

    return $('canvas').get(0).getContext('2d');
}

Asymmetry.prototype.resizeRenderer = function(w, h) {
    this.renderer.width = w;
    this.renderer.height = h;
}

Asymmetry.prototype.initWorld = function() {
    // Define world
    var worldBounds = new AABB(0, 0, this.width, this.height);

    var world = new World({
        bounds: worldBounds
    });

    var goal = new Solid(this.TILE_SIZE, this.TILE_SIZE, this.width / 2, this.height / 2);
    world.goal = goal;

    return world;
}

Asymmetry.prototype.updateWorld = function(dt) {
    this.world.update(dt);
    this.player.update(dt);
    this.socket.emit('player pos', this.player.pos);

    if(this.world.complete()) {
        this.world.solids = [new Solid(this.width, this.height, 0, 0)];
        this.renderer.fillStyle = 'green';
    }
}

Asymmetry.prototype.drawWorld = function() {
    var self = this;

    this.renderer.clearRect(0, 0, this.width, this.height);

    // Draw solids
    for (var i = 0; i < this.world.solids.length; i++) {
        var s = this.world.solids[i];

        this.renderer.fillRect(s.pos.x, s.pos.y, s.w, s.h);
    };

    // Draw maze
    var m = this.maze;
    for (var x = 0; x < m.length; x++) {
        for (var y = 0; y < m[x].length; y++) {
            var screenPos = new Vector(x*this.TILE_SIZE, y*this.TILE_SIZE),
                c = m[x][y];

            if(c.N) this.renderer.fillRect(screenPos.x, screenPos.y, this.TILE_SIZE, this.MAZE_BORDER);
            if(c.E) this.renderer.fillRect(screenPos.x + this.TILE_SIZE, screenPos.y, this.MAZE_BORDER, this.TILE_SIZE);
            if(c.S) this.renderer.fillRect(screenPos.x, screenPos.y + this.TILE_SIZE, this.TILE_SIZE, this.MAZE_BORDER);
            if(c.W) this.renderer.fillRect(screenPos.x, screenPos.y, this.MAZE_BORDER, this.TILE_SIZE);
        };
    };

    // Draw goal
    var g = this.world.goal;

    this.renderer.fillRect(g.pos.x, g.pos.y, g.w, g.h);

    // Draw the player
    var p = this.player;
    this.renderer.fillRect(p.pos.x, p.pos.y, p.w, p.h);
}

Asymmetry.prototype.spawnSolid = function(x, y, w, h) {
    var s = new Solid(w, h, x, y);
    this.world.pushSolid(s);
}

Asymmetry.prototype.generateMaze = function() {
    var cells = [],
        w = Math.floor(this.width / this.TILE_SIZE),
        h = Math.floor(this.height / this.TILE_SIZE),
        totalCells = w * h;

    for (var x = 0; x < w; x++) {
        cells[x] = [];
        for (var y = 0; y < h; y++) {
            cells[x][y] = new Cell(x, y);
        };
    };

    var currentCellCoords = new Vector(Math.round(Math.random() * w), Math.round(Math.random() * h)),
        currentCell = cells[currentCellCoords.x][currentCellCoords.y],
        cellStack = [];
        visitedCells = 1;

    function getRandNeighbor(cell) {
        var randNeighborCoords,
            validNeighbors = [];

       function validateNeighbor(coords) {
           //Check if the cell is legit
            if(coords.x < w && coords.x >= 0 && coords.y < h && coords.y >= 0) {
                var randNeighbor = cells[coords.x][coords.y];

                if(randNeighbor.N && randNeighbor.E && randNeighbor.S && randNeighbor.W) {
                    validNeighbors.push(randNeighbor);
                }
            }
        }

        for (var i = 0; i <= 3; i++) {
            switch(i) {
                case 0:
                    randNeighborCoords = new Vector(cell.x, cell.y + 1);
                    validateNeighbor(randNeighborCoords);
                    break;
                case 1:
                    randNeighborCoords = new Vector(cell.x + 1, cell.y);
                    validateNeighbor(randNeighborCoords);
                    break;
                case 2:
                    randNeighborCoords = new Vector(cell.x, cell.y - 1);
                    validateNeighbor(randNeighborCoords);
                    break;
                case 3:
                    randNeighborCoords = new Vector(cell.x - 1, cell.y);
                    validateNeighbor(randNeighborCoords);
                    break;
                default:
                    console.log('huh? ' + i);
                    break;
            };
        };

        if(validNeighbors.length > 0) {
            var rn = Math.round(Math.random() * (validNeighbors.length - 1));

            return validNeighbors[rn];
        } else {
            return null;
        }
    }

    while(visitedCells < totalCells) {
        var randNeighbor = getRandNeighbor(currentCell);
        console.log('current');
        console.dir(currentCell);
        console.log('rand');
        console.dir(randNeighbor);

        if(randNeighbor !== null) {
            if(randNeighbor.x > currentCell.x) {
                currentCell.E = false;
                randNeighbor.W = false;
            } else if (randNeighbor.x < currentCell.x) {
                currentCell.W = false;
                randNeighbor.E = false;
            } else if (randNeighbor.y < currentCell.y) {
                currentCell.N = false;
                randNeighbor.S = false;
            } else if (randNeighbor.y > currentCell.y) {
                currentCell.S = false;
                randNeighbor.N = false;
            } else {
                console.log('huh...')
            }

            cellStack.push(currentCell);
            currentCell = randNeighbor;
            visitedCells++;
        } else {
            currentCell = cellStack.pop()
        }

    }

    return cells;
}

function Cell(x, y) {
    this.x = x;
    this.y = y;
    this.N = true;
    this.E = true;
    this.S = true;
    this.W = true;
}
<commit_msg>Implemented dodgy goal<commit_after>var $ = require('jquery-browserify'),
    Vector = require('./Vector'),
    AABB = require('./AABB'),
    World = require('./World'),
    Solid = require('./Solid'),
    Player = require('./Player');

module.exports = Asymmetry;

function Asymmetry() {
    var self = this;
    this.TILE_SIZE = 40;
    this.MAZE_BORDER = 2;

    this.socket = io.connect('http://localhost:9966');
    this.width  = $('#canvainer').width(),
    this.height = $('#canvainer').height(),
    this.renderer = this.createRenderer();
    this.world = this.initWorld();

    this.maze = this.generateMaze();
    this.solidifyMaze();

    this.player = new Player(100, 100);
    window.player = this.player;
};

Asymmetry.prototype.createRenderer = function() {
    htmlCanvas = "<canvas width=" + "\"" + this.width + "\"" + "height=" + "\"" + this.height + "\"" + "></canvas>";

    $('#canvainer').append(htmlCanvas);

    return $('canvas').get(0).getContext('2d');
}

Asymmetry.prototype.resizeRenderer = function(w, h) {
    this.renderer.width = w;
    this.renderer.height = h;
}

Asymmetry.prototype.initWorld = function() {
    // Define world
    var worldBounds = new AABB(0, 0, this.width, this.height);

    var world = new World({
        bounds: worldBounds
    });

    return world;
}

Asymmetry.prototype.updateWorld = function(dt) {
    this.world.update(dt);
    this.player.update(dt);
    this.socket.emit('player pos', this.player.pos);

    if(this.world.complete()) {
        this.world.solids = [new Solid(this.width, this.height, 0, 0)];
        this.renderer.fillStyle = 'green';
    }
}

Asymmetry.prototype.drawWorld = function() {
    var self = this;

    this.renderer.clearRect(0, 0, this.width, this.height);

    // Draw solids
    for (var i = 0; i < this.world.solids.length; i++) {
        var s = this.world.solids[i];

        this.renderer.fillRect(s.pos.x, s.pos.y, s.w, s.h);
    };

    // Draw goal
    var g = this.world.goal;
    this.renderer.fillRect(g.pos.x, g.pos.y, g.w, g.h);

    // Draw the player
    var p = this.player;
    this.renderer.fillRect(p.pos.x, p.pos.y, p.w, p.h);
}

Asymmetry.prototype.spawnSolid = function(x, y, w, h) {
    var s = new Solid(w, h, x, y);
    this.world.pushSolid(s);
}

Asymmetry.prototype.generateMaze = function() {
    var cells = [],
        w = Math.floor(this.width / this.TILE_SIZE),
        h = Math.floor(this.height / this.TILE_SIZE),
        totalCells = w * h;

    for (var x = 0; x < w; x++) {
        cells[x] = [];
        for (var y = 0; y < h; y++) {
            cells[x][y] = new Cell(x, y);
        };
    };

    var currentCellCoords = new Vector(Math.round(Math.random() * w), Math.round(Math.random() * h)),
        currentCell = cells[currentCellCoords.x][currentCellCoords.y],
        cellStack = [];
        visitedCells = 1;

    function getRandNeighbor(cell) {
        var randNeighborCoords,
            validNeighbors = [];

       function validateNeighbor(coords) {
           //Check if the cell is legit
            if(coords.x < w && coords.x >= 0 && coords.y < h && coords.y >= 0) {
                var randNeighbor = cells[coords.x][coords.y];

                if(randNeighbor.N && randNeighbor.E && randNeighbor.S && randNeighbor.W) {
                    validNeighbors.push(randNeighbor);
                }
            }
        }

        for (var i = 0; i <= 3; i++) {
            switch(i) {
                case 0:
                    randNeighborCoords = new Vector(cell.x, cell.y + 1);
                    validateNeighbor(randNeighborCoords);
                    break;
                case 1:
                    randNeighborCoords = new Vector(cell.x + 1, cell.y);
                    validateNeighbor(randNeighborCoords);
                    break;
                case 2:
                    randNeighborCoords = new Vector(cell.x, cell.y - 1);
                    validateNeighbor(randNeighborCoords);
                    break;
                case 3:
                    randNeighborCoords = new Vector(cell.x - 1, cell.y);
                    validateNeighbor(randNeighborCoords);
                    break;
                default:
                    console.log('huh? ' + i);
                    break;
            };
        };

        if(validNeighbors.length > 0) {
            var rn = Math.round(Math.random() * (validNeighbors.length - 1));

            return validNeighbors[rn];
        } else {
            return null;
        }
    }

    while(visitedCells < totalCells) {
        var randNeighbor = getRandNeighbor(currentCell);

        if(randNeighbor !== null) {
            if(randNeighbor.x > currentCell.x) {
                currentCell.E = false;
                randNeighbor.W = false;
            } else if (randNeighbor.x < currentCell.x) {
                currentCell.W = false;
                randNeighbor.E = false;
            } else if (randNeighbor.y < currentCell.y) {
                currentCell.N = false;
                randNeighbor.S = false;
            } else if (randNeighbor.y > currentCell.y) {
                currentCell.S = false;
                randNeighbor.N = false;
            } else {
                console.log('huh...')
            }

            cellStack.push(currentCell);
            currentCell = randNeighbor;
            visitedCells++;
        } else {
            currentCell = cellStack.pop()
        }

    }

    this.world.goal = new Solid(this.TILE_SIZE, this.TILE_SIZE, cells[w - 1][h - 1].x * this.TILE_SIZE, cells[w - 1][h - 1].y * this.TILE_SIZE);

    return cells;
}

Asymmetry.prototype.solidifyMaze = function() {
    var m = this.maze;
    for (var x = 0; x < m.length; x++) {
        for (var y = 0; y < m[x].length; y++) {
            var screenPos = new Vector(x*this.TILE_SIZE, y*this.TILE_SIZE),
                c = m[x][y];

            if(c.N) this.world.pushSolid(new Solid(this.TILE_SIZE, this.MAZE_BORDER, screenPos.x, screenPos.y));
            if(c.E) this.world.pushSolid(new Solid(this.MAZE_BORDER, this.TILE_SIZE, screenPos.x + this.TILE_SIZE, screenPos.y));
            if(c.S) this.world.pushSolid(new Solid(this.TILE_SIZE, this.MAZE_BORDER, screenPos.x, screenPos.y + this.TILE_SIZE));
            if(c.W) this.world.pushSolid(new Solid(this.MAZE_BORDER, this.TILE_SIZE, screenPos.x, screenPos.y));
        };
    };
}

function Cell(x, y) {
    this.x = x;
    this.y = y;
    this.N = true;
    this.E = true;
    this.S = true;
    this.W = true;
}
<|endoftext|>


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

'use strict';

function main(
  projectId = process.env.GCLOUD_PROJECT,
  cloudRegion = 'us-central1',
  datasetId,
  fhirStoreId,
  resourceType,
) {
  // [START healthcare_create_fhir_resource]
  const {google} = require('googleapis');
  const healthcare = google.healthcare('v1');

  async function createFhirResource() {
    const auth = await google.auth.getClient({
      scopes: ['https://www.googleapis.com/auth/cloud-platform'],
    });

    // Replace the following body with the data for the resource you want to
    // create.
    const body = {
        "name": [{"use": "official", "family": "Smith", "given": ["Darcy"]}],
        "gender": "female",
        "birthDate": "1970-01-01",
        "resourceType": "Patient",
    };

    google.options({auth, headers: {'Content-Type': 'application/fhir+json'}});

    // TODO(developer): uncomment these lines before running the sample
    // const cloudRegion = 'us-central1';
    // const projectId = 'adjective-noun-123';
    // const datasetId = 'my-dataset';
    // const fhirStoreId = 'my-fhir-store';
    // const resourceType = 'Patient';
    const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;

    const request = {parent, type: resourceType, requestBody: body};
    const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.create(
      request
    );
    console.log(`Created FHIR resource with ID ${resource.data.id}`);
    console.log(resource.data);
  }

  createFhirResource();
  // [END healthcare_create_fhir_resource]
}

// node createFhirResource.js <projectId> <cloudRegion> <datasetId> <fhirStoreId> <resourceType>
main(...process.argv.slice(2));
<commit_msg>healthcare API: fix create FHIR resource region tag (#1869)<commit_after>/**
 * Copyright 2020, Google, LLC
 * Licensed under the Apache License, Version 2.0 (the `License`);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an `AS IS` BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

function main(
  projectId = process.env.GCLOUD_PROJECT,
  cloudRegion = 'us-central1',
  datasetId,
  fhirStoreId,
  resourceType,
) {
  // [START healthcare_create_resource]
  const {google} = require('googleapis');
  const healthcare = google.healthcare('v1');

  async function createFhirResource() {
    const auth = await google.auth.getClient({
      scopes: ['https://www.googleapis.com/auth/cloud-platform'],
    });

    // Replace the following body with the data for the resource you want to
    // create.
    const body = {
        "name": [{"use": "official", "family": "Smith", "given": ["Darcy"]}],
        "gender": "female",
        "birthDate": "1970-01-01",
        "resourceType": "Patient",
    };

    google.options({auth, headers: {'Content-Type': 'application/fhir+json'}});

    // TODO(developer): uncomment these lines before running the sample
    // const cloudRegion = 'us-central1';
    // const projectId = 'adjective-noun-123';
    // const datasetId = 'my-dataset';
    // const fhirStoreId = 'my-fhir-store';
    // const resourceType = 'Patient';
    const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;

    const request = {parent, type: resourceType, requestBody: body};
    const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.create(
      request
    );
    console.log(`Created FHIR resource with ID ${resource.data.id}`);
    console.log(resource.data);
  }

  createFhirResource();
  // [END healthcare_create_resource]
}

// node createFhirResource.js <projectId> <cloudRegion> <datasetId> <fhirStoreId> <resourceType>
main(...process.argv.slice(2));
<|endoftext|>


<commit_before>
(function() {

if(typeof(L) == "undefined")
  return;

L.CartoDBGroupLayerBase = L.TileLayer.extend({

  interactionClass: wax.leaf.interaction,

  includes: [
    cdb.geo.LeafLetLayerView.prototype,
    //LayerDefinition.prototype,
    CartoDBLayerCommon.prototype
  ],

  options: {
    opacity:        0.99,
    attribution:    "CartoDB",
    debug:          false,
    visible:        true,
    added:          false,
    tiler_domain:   "cartodb.com",
    tiler_port:     "80",
    tiler_protocol: "http",
    sql_api_domain:     "cartodb.com",
    sql_api_port:       "80",
    sql_api_protocol:   "http",
    maxZoom: 30, // default leaflet zoom level for a layers is 18, raise it
    extra_params:   {
    },
    cdn_url:        null,
    subdomains:     null
  },

  initialize: function (options) {
    options = options || {};
    // Set options
    L.Util.setOptions(this, options);

    // Some checks
    if (!options.layer_definition && !options.sublayers) {
        throw new Error('cartodb-leaflet needs at least the layer_definition or sublayer list');
    }

    if(!options.layer_definition) {
      this.options.layer_definition = LayerDefinition.layerDefFromSubLayers(options.sublayers);
    }

    LayerDefinition.call(this, this.options.layer_definition, this.options);

    this.fire = this.trigger;

    CartoDBLayerCommon.call(this);
    L.TileLayer.prototype.initialize.call(this);
    this.interaction = [];
    this.addProfiling();
  },

  addProfiling: function() {
    this.bind('tileloadstart', function(e) {
      var s = this.tileStats || (this.tileStats = {});
      s[e.tile.src] = cartodb.core.Profiler.metric('cartodb-js.tile.png.load.time').start();
    });
    var finish = function(e) {
      var s = this.tileStats && this.tileStats[e.tile.src];
      s && s.end();
    };
    this.bind('tileload', finish);
    this.bind('tileerror', function(e) {
      cartodb.core.Profiler.metric('cartodb-js.tile.png.error').inc();
      finish(e);
    });
  },

  // overwrite getTileUrl in order to
  // support different tiles subdomains in tilejson way
  getTileUrl: function (tilePoint) {
    var EMPTY_GIF = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
    this._adjustTilePoint(tilePoint);

    var tiles = [EMPTY_GIF];
    if(this.tilejson) {
      tiles = this.tilejson.tiles;
    }

    var index = (tilePoint.x + tilePoint.y) % tiles.length;

    return L.Util.template(tiles[index], L.Util.extend({
      z: this._getZoomForUrl(),
      x: tilePoint.x,
      y: tilePoint.y
    }, this.options));
  },

  /**
   * Change opacity of the layer
   * @params {Integer} New opacity
   */
  setOpacity: function(opacity) {

    if (isNaN(opacity) || opacity>1 || opacity<0) {
      throw new Error(opacity + ' is not a valid value');
    }

    // Leaflet only accepts 0-0.99... Weird!
    this.options.opacity = Math.min(opacity, 0.99);

    if (this.options.visible) {
      L.TileLayer.prototype.setOpacity.call(this, this.options.opacity);
      this.fire('updated');
    }
  },

  /**
   * When Leaflet adds the layer... go!
   * @params {map}
   */
  onAdd: function(map) {
    var self = this;
    this.options.map = map;

    // Add cartodb logo
    if (this.options.cartodb_logo != false)
      cdb.geo.common.CartoDBLogo.addWadus({ left:8, bottom:8 }, 0, map._container);

    this.__update(function() {
      // if while the layer was processed in the server is removed
      // it should not be added to the map
      var id = L.stamp(self);
      if (!map._layers[id]) {
        return;
      }

      L.TileLayer.prototype.onAdd.call(self, map);
      self.fire('added');
      self.options.added = true;
    });
  },

  /**
   * When removes the layer, destroy interactivity if exist
   */
  onRemove: function(map) {
    if(this.options.added) {
      this.options.added = false;
      L.TileLayer.prototype.onRemove.call(this, map);
    }
  },

  /**
   * Update CartoDB layer
   * generates a new url for tiles and refresh leaflet layer
   * do not collide with leaflet _update
   */
  __update: function(done) {
    var self = this;
    this.fire('updated');
    this.fire('loading');
    var map = this.options.map;

    this.getTiles(function(urls, err) {
      if(urls) {
        self.tilejson = urls;
        self.setUrl(self.tilejson.tiles[0]);
        // manage interaction
        self._reloadInteraction();
        self.ok && self.ok();
        done && done();
      } else {
        self.error && self.error(err);
        done && done();
      }
    });
  },

  _checkLayer: function() {
    if (!this.options.added) {
      throw new Error('the layer is not still added to the map');
    }
  },

  /**
   * Set a new layer attribution
   * @params {String} New attribution string
   */
  setAttribution: function(attribution) {
    this._checkLayer();

    // Remove old one
    this.map.attributionControl.removeAttribution(this.options.attribution);

    // Set new attribution in the options
    this.options.attribution = attribution;

    // Change text
    this.map.attributionControl.addAttribution(this.options.attribution);

    // Change in the layer
    this.options.attribution = this.options.attribution;
    this.tilejson.attribution = this.options.attribution;

    this.fire('updated');
  },

  /**
   * Bind events for wax interaction
   * @param {Object} Layer map object
   * @param {Event} Wax event
   */
  _manageOnEvents: function(map, o) {
    var layer_point = this._findPos(map,o);

    if (!layer_point || isNaN(layer_point.x) || isNaN(layer_point.y)) {
      // If layer_point doesn't contain x and y,
      // we can't calculate event map position
      return;
    }

    var latlng = map.layerPointToLatLng(layer_point);
    var event_type = o.e.type.toLowerCase();
    var screenPos = map.layerPointToContainerPoint(layer_point);

    switch (event_type) {
      case 'mousemove':
        if (this.options.featureOver) {
          return this.options.featureOver(o.e,latlng, screenPos, o.data, o.layer);
        }
        break;

      case 'click':
      case 'touchend':
      case 'mspointerup':
      case 'pointerup':
      case 'pointermove':
        if (this.options.featureClick) {
          this.options.featureClick(o.e,latlng, screenPos, o.data, o.layer);
        }
        break;
      default:
        break;
    }
  },

  /**
   * Bind off event for wax interaction
   */
  _manageOffEvents: function(map, o) {
    if (this.options.featureOut) {
      return this.options.featureOut && this.options.featureOut(o.e, o.layer);
    }
  },

  /**
   * Get the Leaflet Point of the event
   * @params {Object} Map object
   * @params {Object} Wax event object
   */
  _findPos: function (map,o) {
    var curleft = 0, curtop = 0;
    var obj = map.getContainer();

    var x, y;
    if (o.e.changedTouches && o.e.changedTouches.length > 0) {
      x = o.e.changedTouches[0].clientX + window.scrollX;
      y = o.e.changedTouches[0].clientY + window.scrollY;
    } else {
      x = o.e.clientX;
      y = o.e.clientY;
    }

    if (obj.offsetParent) {
      // Modern browsers
      do {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
      return map.containerPointToLayerPoint(new L.Point(x - curleft, y - curtop));
    } else {
      var rect = obj.getBoundingClientRect();
      var p = new L.Point(
            o.e.clientX - rect.left - obj.clientLeft - window.scrollX,
            o.e.clientY - rect.top - obj.clientTop - window.scrollY);
      return map.containerPointToLayerPoint(p);
    }
  }

});

L.CartoDBGroupLayer = L.CartoDBGroupLayerBase.extend({
  includes: [
    LayerDefinition.prototype,
  ]
});

function layerView(base) {
  var layerViewClass = base.extend({

    includes: [
      cdb.geo.LeafLetLayerView.prototype,
      Backbone.Events
    ],

    initialize: function(layerModel, leafletMap) {
      var self = this;
      var hovers = [];

      // CartoDB new attribution,
      // also we have the logo
      layerModel.attributes.attribution = cdb.config.get('cartodb_attributions');

      var opts = _.clone(layerModel.attributes);

      opts.map =  leafletMap;

      var // preserve the user's callbacks
      _featureOver  = opts.featureOver,
      _featureOut   = opts.featureOut,
      _featureClick = opts.featureClick;

      var previousEvent;
      var eventTimeout = -1;

      opts.featureOver  = function(e, latlon, pxPos, data, layer) {
        if (!hovers[layer]) {
          self.trigger('layerenter', e, latlon, pxPos, data, layer);
        }
        hovers[layer] = 1;
        _featureOver  && _featureOver.apply(this, arguments);
        self.featureOver  && self.featureOver.apply(self, arguments);
        // if the event is the same than before just cancel the event
        // firing because there is a layer on top of it
        if (e.timeStamp === previousEvent) {
          clearTimeout(eventTimeout);
        }
        eventTimeout = setTimeout(function() {
          self.trigger('mouseover', e, latlon, pxPos, data, layer);
          self.trigger('layermouseover', e, latlon, pxPos, data, layer);
        }, 0);
        previousEvent = e.timeStamp;

      };

      opts.featureOut  = function(m, layer) {
        if (hovers[layer]) {
          self.trigger('layermouseout', layer);
        }
        hovers[layer] = 0;
        if(!_.any(hovers)) {
          self.trigger('mouseout');
        }
        _featureOut  && _featureOut.apply(this, arguments);
        self.featureOut  && self.featureOut.apply(self, arguments);
      };

      opts.featureClick  = _.debounce(function() {
        _featureClick  && _featureClick.apply(self, arguments);
        self.featureClick  && self.featureClick.apply(self, arguments);
      }, 10);

      base.prototype.initialize.call(this, opts);
      cdb.geo.LeafLetLayerView.call(this, layerModel, this, leafletMap);

    },

    featureOver: function(e, latlon, pixelPos, data, layer) {
      // dont pass leaflet lat/lon
      this.trigger('featureOver', e, [latlon.lat, latlon.lng], pixelPos, data, layer);
    },

    featureOut: function(e, layer) {
      this.trigger('featureOut', e, layer);
    },

    featureClick: function(e, latlon, pixelPos, data, layer) {
      // dont pass leaflet lat/lon
      this.trigger('featureClick', e, [latlon.lat, latlon.lng], pixelPos, data, layer);
    },

    error: function(e) {
      this.trigger('error', e ? e.errors : 'unknown error');
      this.model.trigger('error', e?e.errors:'unknown error');
    },

    ok: function(e) {
      this.model.trigger('tileOk');
    },

    onLayerDefinitionUpdated: function() {
      this.__update();
    }

  });

  return layerViewClass;
}

L.NamedMap = L.CartoDBGroupLayerBase.extend({
  includes: [
    cdb.geo.LeafLetLayerView.prototype,
    NamedMap.prototype,
    CartoDBLayerCommon.prototype
  ],

  initialize: function (options) {
    options = options || {};
    // Set options
    L.Util.setOptions(this, options);

    // Some checks
    if (!options.named_map && !options.sublayers) {
        throw new Error('cartodb-leaflet needs at least the named_map');
    }

    /*if(!options.layer_definition) {
      this.options.layer_definition = LayerDefinition.layerDefFromSubLayers(options.sublayers);
    }*/

    NamedMap.call(this, this.options.named_map, this.options);

    this.fire = this.trigger;

    CartoDBLayerCommon.call(this);
    L.TileLayer.prototype.initialize.call(this);
    this.interaction = [];
    this.addProfiling();
  }
});

cdb.geo.LeafLetCartoDBLayerGroupView = layerView(L.CartoDBGroupLayer);
cdb.geo.LeafLetCartoDBNamedMapView = layerView(L.NamedMap);

})();
<commit_msg>Added return false when map pos is not valid<commit_after>
(function() {

if(typeof(L) == "undefined")
  return;

L.CartoDBGroupLayerBase = L.TileLayer.extend({

  interactionClass: wax.leaf.interaction,

  includes: [
    cdb.geo.LeafLetLayerView.prototype,
    //LayerDefinition.prototype,
    CartoDBLayerCommon.prototype
  ],

  options: {
    opacity:        0.99,
    attribution:    "CartoDB",
    debug:          false,
    visible:        true,
    added:          false,
    tiler_domain:   "cartodb.com",
    tiler_port:     "80",
    tiler_protocol: "http",
    sql_api_domain:     "cartodb.com",
    sql_api_port:       "80",
    sql_api_protocol:   "http",
    maxZoom: 30, // default leaflet zoom level for a layers is 18, raise it
    extra_params:   {
    },
    cdn_url:        null,
    subdomains:     null
  },

  initialize: function (options) {
    options = options || {};
    // Set options
    L.Util.setOptions(this, options);

    // Some checks
    if (!options.layer_definition && !options.sublayers) {
        throw new Error('cartodb-leaflet needs at least the layer_definition or sublayer list');
    }

    if(!options.layer_definition) {
      this.options.layer_definition = LayerDefinition.layerDefFromSubLayers(options.sublayers);
    }

    LayerDefinition.call(this, this.options.layer_definition, this.options);

    this.fire = this.trigger;

    CartoDBLayerCommon.call(this);
    L.TileLayer.prototype.initialize.call(this);
    this.interaction = [];
    this.addProfiling();
  },

  addProfiling: function() {
    this.bind('tileloadstart', function(e) {
      var s = this.tileStats || (this.tileStats = {});
      s[e.tile.src] = cartodb.core.Profiler.metric('cartodb-js.tile.png.load.time').start();
    });
    var finish = function(e) {
      var s = this.tileStats && this.tileStats[e.tile.src];
      s && s.end();
    };
    this.bind('tileload', finish);
    this.bind('tileerror', function(e) {
      cartodb.core.Profiler.metric('cartodb-js.tile.png.error').inc();
      finish(e);
    });
  },

  // overwrite getTileUrl in order to
  // support different tiles subdomains in tilejson way
  getTileUrl: function (tilePoint) {
    var EMPTY_GIF = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
    this._adjustTilePoint(tilePoint);

    var tiles = [EMPTY_GIF];
    if(this.tilejson) {
      tiles = this.tilejson.tiles;
    }

    var index = (tilePoint.x + tilePoint.y) % tiles.length;

    return L.Util.template(tiles[index], L.Util.extend({
      z: this._getZoomForUrl(),
      x: tilePoint.x,
      y: tilePoint.y
    }, this.options));
  },

  /**
   * Change opacity of the layer
   * @params {Integer} New opacity
   */
  setOpacity: function(opacity) {

    if (isNaN(opacity) || opacity>1 || opacity<0) {
      throw new Error(opacity + ' is not a valid value');
    }

    // Leaflet only accepts 0-0.99... Weird!
    this.options.opacity = Math.min(opacity, 0.99);

    if (this.options.visible) {
      L.TileLayer.prototype.setOpacity.call(this, this.options.opacity);
      this.fire('updated');
    }
  },

  /**
   * When Leaflet adds the layer... go!
   * @params {map}
   */
  onAdd: function(map) {
    var self = this;
    this.options.map = map;

    // Add cartodb logo
    if (this.options.cartodb_logo != false)
      cdb.geo.common.CartoDBLogo.addWadus({ left:8, bottom:8 }, 0, map._container);

    this.__update(function() {
      // if while the layer was processed in the server is removed
      // it should not be added to the map
      var id = L.stamp(self);
      if (!map._layers[id]) {
        return;
      }

      L.TileLayer.prototype.onAdd.call(self, map);
      self.fire('added');
      self.options.added = true;
    });
  },

  /**
   * When removes the layer, destroy interactivity if exist
   */
  onRemove: function(map) {
    if(this.options.added) {
      this.options.added = false;
      L.TileLayer.prototype.onRemove.call(this, map);
    }
  },

  /**
   * Update CartoDB layer
   * generates a new url for tiles and refresh leaflet layer
   * do not collide with leaflet _update
   */
  __update: function(done) {
    var self = this;
    this.fire('updated');
    this.fire('loading');
    var map = this.options.map;

    this.getTiles(function(urls, err) {
      if(urls) {
        self.tilejson = urls;
        self.setUrl(self.tilejson.tiles[0]);
        // manage interaction
        self._reloadInteraction();
        self.ok && self.ok();
        done && done();
      } else {
        self.error && self.error(err);
        done && done();
      }
    });
  },

  _checkLayer: function() {
    if (!this.options.added) {
      throw new Error('the layer is not still added to the map');
    }
  },

  /**
   * Set a new layer attribution
   * @params {String} New attribution string
   */
  setAttribution: function(attribution) {
    this._checkLayer();

    // Remove old one
    this.map.attributionControl.removeAttribution(this.options.attribution);

    // Set new attribution in the options
    this.options.attribution = attribution;

    // Change text
    this.map.attributionControl.addAttribution(this.options.attribution);

    // Change in the layer
    this.options.attribution = this.options.attribution;
    this.tilejson.attribution = this.options.attribution;

    this.fire('updated');
  },

  /**
   * Bind events for wax interaction
   * @param {Object} Layer map object
   * @param {Event} Wax event
   */
  _manageOnEvents: function(map, o) {
    var layer_point = this._findPos(map,o);

    if (!layer_point || isNaN(layer_point.x) || isNaN(layer_point.y)) {
      // If layer_point doesn't contain x and y,
      // we can't calculate event map position
      return false;
    }

    var latlng = map.layerPointToLatLng(layer_point);
    var event_type = o.e.type.toLowerCase();
    var screenPos = map.layerPointToContainerPoint(layer_point);

    switch (event_type) {
      case 'mousemove':
        if (this.options.featureOver) {
          return this.options.featureOver(o.e,latlng, screenPos, o.data, o.layer);
        }
        break;

      case 'click':
      case 'touchend':
      case 'mspointerup':
      case 'pointerup':
      case 'pointermove':
        if (this.options.featureClick) {
          this.options.featureClick(o.e,latlng, screenPos, o.data, o.layer);
        }
        break;
      default:
        break;
    }
  },

  /**
   * Bind off event for wax interaction
   */
  _manageOffEvents: function(map, o) {
    if (this.options.featureOut) {
      return this.options.featureOut && this.options.featureOut(o.e, o.layer);
    }
  },

  /**
   * Get the Leaflet Point of the event
   * @params {Object} Map object
   * @params {Object} Wax event object
   */
  _findPos: function (map,o) {
    var curleft = 0, curtop = 0;
    var obj = map.getContainer();

    var x, y;
    if (o.e.changedTouches && o.e.changedTouches.length > 0) {
      x = o.e.changedTouches[0].clientX + window.scrollX;
      y = o.e.changedTouches[0].clientY + window.scrollY;
    } else {
      x = o.e.clientX;
      y = o.e.clientY;
    }

    if (obj.offsetParent) {
      // Modern browsers
      do {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
      return map.containerPointToLayerPoint(new L.Point(x - curleft, y - curtop));
    } else {
      var rect = obj.getBoundingClientRect();
      var p = new L.Point(
            o.e.clientX - rect.left - obj.clientLeft - window.scrollX,
            o.e.clientY - rect.top - obj.clientTop - window.scrollY);
      return map.containerPointToLayerPoint(p);
    }
  }

});

L.CartoDBGroupLayer = L.CartoDBGroupLayerBase.extend({
  includes: [
    LayerDefinition.prototype,
  ]
});

function layerView(base) {
  var layerViewClass = base.extend({

    includes: [
      cdb.geo.LeafLetLayerView.prototype,
      Backbone.Events
    ],

    initialize: function(layerModel, leafletMap) {
      var self = this;
      var hovers = [];

      // CartoDB new attribution,
      // also we have the logo
      layerModel.attributes.attribution = cdb.config.get('cartodb_attributions');

      var opts = _.clone(layerModel.attributes);

      opts.map =  leafletMap;

      var // preserve the user's callbacks
      _featureOver  = opts.featureOver,
      _featureOut   = opts.featureOut,
      _featureClick = opts.featureClick;

      var previousEvent;
      var eventTimeout = -1;

      opts.featureOver  = function(e, latlon, pxPos, data, layer) {
        if (!hovers[layer]) {
          self.trigger('layerenter', e, latlon, pxPos, data, layer);
        }
        hovers[layer] = 1;
        _featureOver  && _featureOver.apply(this, arguments);
        self.featureOver  && self.featureOver.apply(self, arguments);
        // if the event is the same than before just cancel the event
        // firing because there is a layer on top of it
        if (e.timeStamp === previousEvent) {
          clearTimeout(eventTimeout);
        }
        eventTimeout = setTimeout(function() {
          self.trigger('mouseover', e, latlon, pxPos, data, layer);
          self.trigger('layermouseover', e, latlon, pxPos, data, layer);
        }, 0);
        previousEvent = e.timeStamp;

      };

      opts.featureOut  = function(m, layer) {
        if (hovers[layer]) {
          self.trigger('layermouseout', layer);
        }
        hovers[layer] = 0;
        if(!_.any(hovers)) {
          self.trigger('mouseout');
        }
        _featureOut  && _featureOut.apply(this, arguments);
        self.featureOut  && self.featureOut.apply(self, arguments);
      };

      opts.featureClick  = _.debounce(function() {
        _featureClick  && _featureClick.apply(self, arguments);
        self.featureClick  && self.featureClick.apply(self, arguments);
      }, 10);

      base.prototype.initialize.call(this, opts);
      cdb.geo.LeafLetLayerView.call(this, layerModel, this, leafletMap);

    },

    featureOver: function(e, latlon, pixelPos, data, layer) {
      // dont pass leaflet lat/lon
      this.trigger('featureOver', e, [latlon.lat, latlon.lng], pixelPos, data, layer);
    },

    featureOut: function(e, layer) {
      this.trigger('featureOut', e, layer);
    },

    featureClick: function(e, latlon, pixelPos, data, layer) {
      // dont pass leaflet lat/lon
      this.trigger('featureClick', e, [latlon.lat, latlon.lng], pixelPos, data, layer);
    },

    error: function(e) {
      this.trigger('error', e ? e.errors : 'unknown error');
      this.model.trigger('error', e?e.errors:'unknown error');
    },

    ok: function(e) {
      this.model.trigger('tileOk');
    },

    onLayerDefinitionUpdated: function() {
      this.__update();
    }

  });

  return layerViewClass;
}

L.NamedMap = L.CartoDBGroupLayerBase.extend({
  includes: [
    cdb.geo.LeafLetLayerView.prototype,
    NamedMap.prototype,
    CartoDBLayerCommon.prototype
  ],

  initialize: function (options) {
    options = options || {};
    // Set options
    L.Util.setOptions(this, options);

    // Some checks
    if (!options.named_map && !options.sublayers) {
        throw new Error('cartodb-leaflet needs at least the named_map');
    }

    /*if(!options.layer_definition) {
      this.options.layer_definition = LayerDefinition.layerDefFromSubLayers(options.sublayers);
    }*/

    NamedMap.call(this, this.options.named_map, this.options);

    this.fire = this.trigger;

    CartoDBLayerCommon.call(this);
    L.TileLayer.prototype.initialize.call(this);
    this.interaction = [];
    this.addProfiling();
  }
});

cdb.geo.LeafLetCartoDBLayerGroupView = layerView(L.CartoDBGroupLayer);
cdb.geo.LeafLetCartoDBNamedMapView = layerView(L.NamedMap);

})();
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var utils = require('./utils.js');
var slug = require('slug');

/**
 * Defines a set of filters available in swig templates
 * @param  {Object}   swig        Swig engine to add filters to
 */
module.exports.init = function (swig) {

  var upper = function(input) {
    return input.toUpperCase();
  };

  var slice = function(input, offset, limit) {
    if(Array.isArray(input))
    {
      return input.slice(offset || 0, offset + limit)
    }

    return utils.sliceDictionary(input, limit, offset);
  };

  var sort = function(input, property) {
    return _.sortBy(input, property)
  };

  var reverse = function(input, reverse) {
    return _(input).reverse();
  };

  var slug = function(input) {
    return slug(input).toLowerCase();
  }

  this.imageSize = function(input, width, height) {
    if(width && !height)
    {
      return input + '?width=' + width;
    } else if (height && !width) {
      return input + '?height=' + height;
    }

    return input + '?width=' + width + '&height=' + height;
  };

  swig.setFilter('upper', upper);
  swig.setFilter('slice', slice);
  swig.setFilter('sort', sort);
  swig.setFilter('reverse', reverse);
  swig.setFilter('imageSize', reverse);
  swig.setFilter('slug', slug);
};<commit_msg>avoid recurse<commit_after>'use strict';

var _ = require('lodash');
var utils = require('./utils.js');
var slug = require('slug');

/**
 * Defines a set of filters available in swig templates
 * @param  {Object}   swig        Swig engine to add filters to
 */
module.exports.init = function (swig) {

  var upper = function(input) {
    return input.toUpperCase();
  };

  var slice = function(input, offset, limit) {
    if(Array.isArray(input))
    {
      return input.slice(offset || 0, offset + limit)
    }

    return utils.sliceDictionary(input, limit, offset);
  };

  var sort = function(input, property) {
    return _.sortBy(input, property)
  };

  var reverse = function(input, reverse) {
    return _(input).reverse();
  };

  var makeSlug = function(input) {
    return slug(input).toLowerCase();
  }

  this.imageSize = function(input, width, height) {
    if(width && !height)
    {
      return input + '?width=' + width;
    } else if (height && !width) {
      return input + '?height=' + height;
    }

    return input + '?width=' + width + '&height=' + height;
  };

  swig.setFilter('upper', upper);
  swig.setFilter('slice', slice);
  swig.setFilter('sort', sort);
  swig.setFilter('reverse', reverse);
  swig.setFilter('imageSize', reverse);
  swig.setFilter('slug', makeSlug);
};<|endoftext|>