text:
//; (function($) {
$.extend($.fn, {
    initJerichoTab: function(setting) {
        var opts = $.fn.extend({
            //the container of jerichotab(is required,  a jQuery format selector String as '.container' or '#container')
            renderTo: null,
            //the unique id of jerichotab(is required and unique, not null)
            uniqueId: null,
            //format your tab data like this: [{title:'',iconImg:'',closeable:true},{title:'',iconImg:'',closeable:true}]
            //it's an Array...
            tabs: [],
            //when the jerichotab has been loaded, the tab you'ld like to display first(start at 0, and 0 as default)
            activeTabIndex: 0,
            //the style sheet of tab content
            contentCss: {
                'height': '500px'
            },
            //if you set this property as true, the data'll be loaded only at the first time when users click the tab
            //in other times jerichotab only swich it's css(display property) from 'none' to 'block'
            loadOnce: true,
            //the tab width (150 as default)
            tabWidth: 110,
            //set an ajaxload effect, jerichotab has provided two choices: 'usebg' | 'righttag'
            //'usebg': control if set a big loading gif in the contentholder
            //'righttag': this will set a small loading gif in the right top of contentholder
            loader: 'righttag',
            //两边滑块宽度
            slidersWidth: 19,
            //标题高度
            titleHeight: 26
        }, setting);
        //initialize the jerichotab
        function createJerichoTab() {
            //make sure that a container and uniqueId were provided
            if (opts.renderTo == null) { alert('you must set the \'renderTo\' property\r\t--JeirchoTab'); return; }
            if (opts.uniqueId == null) { alert('you must set the \'uniqueId\' property\r\t--JeirchoTab'); return; }
            if ($('#' + opts.uniqueId).length > 0) { alert('you must set the \'uniqueId\' property as unique\r\t--JeirchoTab'); return; }
            //the jerichotab html tree:
            /*

 ###tabpages here

 ###tabcontents here

            */
            var jerichotab = $('

')
                                            .appendTo($(opts.renderTo));

            //apply contentcss to the contentholder
            $('.tab_content>.content', jerichotab).css(opts.contentCss);

            //fill data
            $.fn.jerichoTab = {
                master: jerichotab,
                tabWidth: opts.tabWidth,
                tabPageWidth: $('.tab_pages', jerichotab).width(),
                slidersWidth: opts.slidersWidth,
                loader: opts.loader,
                loadOnce: opts.loadOnce,
                tabpage: $('.tab_pages>.tabs>ul', jerichotab),
                addTab: function(tabsetting) {
                    //set as the unique tab id and tabFirer tag
                    tagGuid = (typeof tagGuid == 'undefined' ? 0 : tagGuid + 1);
                    var curIndex = tagGuid;
                    //this function will be open to all users for them to add tab at any time
                    var ps = $.fn.extend({
                        //if there is a DOM that cause the tab to be added to tabpages,
                        //you should pass it to jerichotab, in which way tab'll only be activated when
                        //user click the DOM next time
                        tabFirer: null,
                        title: '新增页签'+(curIndex+1),
                        //the dataType and dataLink were suited as:
                        //1.formtag:
                        //   dataType:'formtag',
                        //                  --use the html tags in this page
                        //   dataLink:'#example'
                        //                  --id of the tag you'ld like to display in this tab
                        //2.iframe:
                        //   dataType:'iframe',
                        //                  --use the iframe to load another page
                        //   dataLink:''
                        //                  --such as 'iframetemplates/iframe.htm', set
                        //                  --the relative url of the page u'ld like to display in this tab,
                        //                  --and jerichoTab will use an iframe to load it
                        //3.html:
                        //   dataType:'html',
                        //                  --load html tags from a url
                        //   dataLink:''
                        //                  --the relative url of your html page
                        //4.ajax:
                        //   dataType:'ajax',
                        //                  --use the ajax to load datas with asynchronous operations
                        //    dataLink:''
                        //                  --yes,u can write down your ajax handler url and jerichotab'll make a callback,
                        //                  --so the responseText will be displayed in the content holder(u can use html tags in your server callback datas)
                        data: { dataType: '', dataLink: '' },
                        //set the tab icon of each(relative to...)
                        iconImg: '',
                        //whether this tab can be closed(ture as default)
                        closeable: true,
                        //this function will be fired after all data has been loaded
                        onLoadCompleted: null,
                        // the tab's name
                        name:''
                    }, tabsetting);
                    //window.console && console.log('%o', tabsetting);
                    //check whether the tabFirer exists or not, and that it has an attribute['jerichotabindex'], then set the tab that tabFirer was connected activated
                    //otherwise attach the jerichotabindex' attribute
                    if (ps.tabFirer != null) {
                        var jerichotabindex = ps.tabFirer.attr('jerichotabindex');
                        if (typeof jerichotabindex != 'undefined' && $('#jerichotab_' + jerichotabindex).length > 0)
                            return $.fn.setTabActive(jerichotabindex).adaptSlider().loadData();
                        ps.tabFirer.attr('jerichotabindex', curIndex);
                    }
                    // set name
                    if(ps.name == ''){
                    	ps.name = ps.title;
                    }
                    //newTab html tree:
                    /*

JerichoTab

                    */
                    /*var newTab = $('
' +
	                                    '
' +
	                                        (ps.iconImg == '' ? '' : '

') +
	                                        '
' + ps.title.cut(opts.tabWidth / 10 - 1) + '
  ' +
	                                        '
' + (ps.closeable ? ' ' : '') + '
' +
	                                    '
' +
	                                    '

' +
	                                '
')*/
                    var newTab = $('
' +
                            '
' +
                                (ps.iconImg == '' ? '' : '

') +
                                '
' + ps.title.cut(opts.tabWidth / 10 - 1) + '
  ' +
                                '
' + (ps.closeable ? ' ' : '') + '
' +
                            '
' +
                            '

' +
                        '
').appendTo($.fn.jerichoTab.tabpage).css('opacity', '0').applyHover()
	                          .applyCloseEvent().animate({ 'opacity': '1', width: opts.tabWidth }, 100, function() {
	                    $.fn.setTabActive(curIndex);
	                });
                    //use an Array named "tabHash" to restore the tab information
                    tabHash = (typeof tabHash == 'undefined' ? [] : tabHash);
                    tabHash.push({
                        index: curIndex,
                        tabFirer: ps.tabFirer,
                        tabId: 'jerichotab_' + curIndex,
                        holderId: 'jerichotabholder_' + curIndex,
                        iframeId: 'jerichotabiframe_' + curIndex,
                        onCompleted: ps.onLoadCompleted
                    });
                    return newTab.applySlider();
                },
                closeCurrentTab: function(tabsetting) {
                	$('.tab_selected .tab_close>a').click();
                    /*var ps = $.fn.extend({
                        name:'',
                        activeTabName:'',
                        isReaload: false
                    }, tabsetting);

                    $.fn.jerichoTab.tabpage.children('li[name='+ps.name+']').remove();

                    var isLoad = 0;
                    if(ps.activeTabName != ''){
                    	var lis = $.fn.jerichoTab.tabpage.children('li');
                    	for(var i=0;i<lis.size();i++){
                    		if(lis.eq(i).attr('name')==ps.activeTabName){
                    			$.fn.setTabActive(i).loadData(ps.isReaload);
                    			isLoad = 1;
                    			break;
                    		}
                    	}
                    }
                    if(isLoad==0){
                    	$.fn.setTabActive(0).loadData(ps.isReaload);
                    }*/

                },
            };
            $.each(opts.tabs, function(i, n) {
                $.fn.jerichoTab.addTab(n);
            });
            try{
                if (tabHash.length == 0)
                    jerichotab.css({ 'display': 'none' });
            }catch(e){ }
        }
        createJerichoTab();
        $.fn.setTabActive(opts.activeTabIndex).loadData();
        $.fn.jerichoTab.resize = function() {
        	$.fn.jerichoTab.tabPageWidth = $(".tab_pages", $.fn.jerichoTab.master).width() - (($(".jericho_slider").length > 0) ? ($.fn.jerichoTab.slidersWidth * 2) : 0);
            $(".tabs", $.fn.jerichoTab.master).width($.fn.jerichoTab.tabPageWidth).applySlider().adaptSlider();
            var fixHeight = -2;
            //if (Metronic.isIE8()){
            //	fixHeight = 25;
            //}
            $('#jerichotab_contentholder').height($(opts.renderTo).height() - opts.titleHeight - 5 - fixHeight);
            $(".jericho_tab iframe").height($(".jericho_tab").parent().height() - opts.titleHeight - fixHeight);
        };
        $(window).resize(function() {
            $.fn.jerichoTab.resize();
        })
        //window.console && console.log('width :' + $.fn.jerichoTab.tabpage.width());
    },
    //activate the tag(orderkey is the tab order, start at 1)
    setTabActiveByOrder: function(orderKey) {
        var lastTab = $.fn.jerichoTab.tabpage.children('li').filter('.tab_selected');
        if (lastTab.length > 0) lastTab.swapTabEnable();
        return $('#jericho_tabs').filter(':nth-child(' + orderKey + ')').swapTabEnable();
    },
    //activate the tag(orderKey is the tagGuid of each tab)
    setTabActive: function(orderKey) {
        var lastTab = $.fn.jerichoTab.tabpage.children('li').filter('.tab_selected');
        if (lastTab.length > 0) lastTab.swapTabEnable();
        return $('#jerichotab_' + orderKey).swapTabEnable();
    },
    addEvent: function(e, h) {
        var target = this.get(0);
        if (target.addEventListener) {
            target.addEventListener(e, h, false);
        } else if (target.attachEvent) {
            target.attachEvent('on' + e, h);
        }
    },
    //create an iframe in the contentholder to load pages
    buildIFrame: function(src) {
        return this.each(function() {
            var onComleted = null, jerichotabiframe = '';
            for (var tab in tabHash) {
                if (tabHash[tab].holderId == $(this).attr('id')) {
                    onComleted = tabHash[tab].onCompleted;
                    jerichotabiframe = tabHash[tab].iframeId;
                    break;
                }
            }
            src += (src.indexOf('?') == -1 ? '?' : '&') + 'tabPageId=' + jerichotabiframe;
            var iframe = $('')
							.css({ width: '100%', height: $(this).parent().height(), border: 0 }).appendTo($(this));
            //add a listener to the load event
            $('#' + jerichotabiframe).addEvent('load', function() {
                //if onComlete(Function) is not null, then release it
                !!onComleted ? onComleted(arguments[1]) : true;
                $.fn.removeLoader();
            });
        });
    },
    //load data from dataLink
    //use the following function after each tab was activated
    loadData: function(flag) {
        return this.each(function() {
        	$('.jericho_tab .tab_selected').css('background-color', $('body').css('background-color'));
            //show ajaxloader first
            $('#jerichotab_contentholder').showLoader();
            var onComleted = null, holderId = '', tabId = '';
            //search information in tabHash
            for (var tab in tabHash) {
                if (tabHash[tab].tabId == $(this).attr('id')) {
                    onComleted = tabHash[tab].onCompleted;
                    holderId = '#' + tabHash[tab].holderId;
                    tabId = '#' + tabHash[tab].tabId;
                    break;
                }
            }
            var dataType = $(this).attr('dataType');
            var dataLink = $(this).attr('dataLink');
            //if dataType was undefined, nothing will be done
            if (typeof dataType == 'undefined' || dataType == '' || dataType == 'undefined') { removeLoading(); return; }
            //hide the rest contentholders
            $('#jerichotab_contentholder').children('div[class=curholder]').attr('class', 'holder').css({ 'display': 'none' });
            var holder = $(holderId);
            if (holder.length == 0) {
                //if contentholder DOM hasn't been created, create it immediately
                holder = $('
').appendTo($('#jerichotab_contentholder'));
                //load data into holder
                load(holder);
            }
            else {
                holder.attr('class', 'curholder').css({ 'display': 'block' });
                if ($.fn.jerichoTab.loadOnce && !flag){
                    removeLoading();
                } else {
                    holder.html('');
                    load(holder);
                }
            }

            function load(c) {
                switch (dataType) {
                    case 'formtag':
                        //clone html DOM elements in the page
                        $(dataLink).css('display', 'none');
                        var clone = $(dataLink).clone(true).appendTo(c).css('display', 'block');
                        removeLoading(holder);
                        break;
                    case 'html':
                        //load HTML from page
                        holder.load(dataLink + '?t=' + Math.floor(Math.random()), function() {
                            removeLoading(holder);
                        });
                        break;
                    case 'iframe':
                        //use iframe to load a website
                        holder.buildIFrame(dataLink, holder);
                        break;
                    case 'ajax':
                        //load a remote page using an HTTP request
                        $.ajax({
                            url: dataLink,
                            data: { t: Math.floor(Math.random()) },
                            error: function(r) {
                                holder.html('数据加载失败!');
                                removeLoading(holder);
                            },
                            success: function(r) {
                                holder.html(r);
                                removeLoading(holder);
                            }
                        });
                        break;
                }
            }
            function removeLoading(h) {
                !!onComleted ? onComleted(h) : true;
                $.fn.removeLoader();
            }
        });
    },
    //attach the slider event to every tab,
    //so users can slide the tabs when there are too much tabs
    attachSliderEvent: function() {
        return this.each(function() {
            var me = this;
            $(me).hover(function() {
                $(me).swapClass('jericho_slider' + $(me).attr('pos') + '_enable', 'jericho_slider' + $(me).attr('pos') + '_hover');
            }, function() {
                $(me).swapClass('jericho_slider' + $(me).attr('pos') + '_hover', 'jericho_slider' + $(me).attr('pos') + '_enable');
            }).mouseup(function() {
                //filter the sliders in order to prevent users from sliding`
                if ($(me).is('[slide=no]')) return;
                //get the css(left) of tabpage(ul elements)
                var offLeft = parseInt($.fn.jerichoTab.tabpage.css('left'));
                //the max css(left) of tabpage
                var maxLeft = tabHash.length * $.fn.jerichoTab.tabWidth - $.fn.jerichoTab.tabPageWidth + ($.fn.jerichoTab.slidersWidth * 2);
                switch ($(me).attr('pos')) {
                    case 'left':
                        //slide to the left side
                        if (offLeft + $.fn.jerichoTab.tabWidth < 0)
                            $.fn.jerichoTab.tabpage.animate({ left: offLeft + $.fn.jerichoTab.tabWidth }, 100);
                        else
                            $.fn.jerichoTab.tabpage.animate({ left: 0 }, 100, function() {
                                $(me).attr({ 'slide': 'no', 'class': 'jericho_sliders jericho_sliderleft_disable' });
                            });
                        $('.jericho_sliders[pos=right]').attr({ 'slide': 'yes', 'class': 'jericho_sliders jericho_sliderright_enable' });
                        break;
                    case 'right':
                        //slide to the right side
                        if (offLeft - $.fn.jerichoTab.tabWidth > -maxLeft)
                            $.fn.jerichoTab.tabpage.animate({ left: offLeft - $.fn.jerichoTab.tabWidth }, 100);
                        else
                            $.fn.jerichoTab.tabpage.animate({ left: -maxLeft }, 100, function() {
                                $(me).attr({ 'slide': 'no', 'class': 'jericho_sliders jericho_sliderright_disable' });
                            });
                        $('.jericho_sliders[pos=left]').attr({ 'slide': 'yes', 'class': 'jericho_sliders jericho_sliderleft_enable' });
                        break;
                }
            });
        });
    },
    //create or activate the slider to tabpage
    applySlider: function() {
        return this.each(function() {
            if (typeof tabHash == 'undefined' || tabHash.length == 0) return;
            //get the offwidth of tabpage
            var offWidth = tabHash.length * $.fn.jerichoTab.tabWidth - $.fn.jerichoTab.tabPageWidth + ($.fn.jerichoTab.slidersWidth * 2);
            if (tabHash.length > 0 && offWidth > 0) {
                //make sure that the parent Div of tabpage was fixed(position:relative)
                //so jerichotab can control the display position of tabpage by using 'left'
                $.fn.jerichoTab.tabpage.parent().css({ width: $.fn.jerichoTab.tabPageWidth - ($.fn.jerichoTab.slidersWidth * 2) });
                //auto grow the tabpage(ul) width and reset 'left'
                $.fn.jerichoTab.tabpage.css({ width: offWidth + $.fn.jerichoTab.tabPageWidth - ($.fn.jerichoTab.slidersWidth * 2) })
                		.animate({ left: -offWidth }, 0, function() {
                    //append 'jerichosliders' to the tabpageholder if 'jerichoslider' has't been added
                    if ($('.jericho_sliders').length <= 0) {
                    	var s = 'onclick="if(document.selection && document.selection.empty) {document.selection.empty();}else if(window.getSelection) {var sel = window.getSelection();sel.removeAllRanges();}"';
                        $.fn.jerichoTab.tabpage.parent()
                            .before($('

'));
                        $.fn.jerichoTab.tabpage.parent()
                            .after($('

'));
                        $('.jericho_sliders').attachSliderEvent();
                    }
                    //$('.jericho_sliders').adaptSlider();
                });
            }
            else if (tabHash.length > 0 && offWidth <= 0) {
                //remove 'jerichosliders' whether the tabs were not go beyond the capacity of tabpageholder
                $('.jericho_sliders').remove();
                $.fn.jerichoTab.tabpage.parent().css({ width: $.fn.jerichoTab.tabPageWidth });
                $.fn.jerichoTab.tabpage.css({ width: -offWidth + $.fn.jerichoTab.tabPageWidth })
                	.animate({ left: 0 }, 0);
            }
        });
    },
    //make sure that the slider will be adjusted quickly to the tabpage after tab 'clicking' or tab 'initializing'
    adaptSlider: function() {
        return this.each(function() {
            if ($('.jericho_sliders').length > 0) {
                var offLeft = parseInt($.fn.jerichoTab.tabpage.css('left'));
                var curtag = '#', index = 0;
                for (var t in tabHash) {
                    if (tabHash[t].tabId == $(this).attr('id')) {
                        curtag += tabHash[t].tabId;
                        index = parseInt(t);
                        break;
                    }
                }
                //set the tabpage width
                var tabWidth = $.fn.jerichoTab.tabPageWidth - ($.fn.jerichoTab.slidersWidth * 2);
                //calculate the distance from the left side of tabpage
                var space_l = $.fn.jerichoTab.tabWidth * index + offLeft;
                //calculate the distance from the right side of tabpage
                var space_r = $.fn.jerichoTab.tabWidth * (index + 1) + offLeft;
                //window.console && console.log(space_l + '||' + space_r);
                function setSlider(pos, enable) {
                    $('.jericho_sliders[pos=' + pos + ']').attr({ 'slide': (enable ? 'yes' : 'no'), 'class': 'jericho_sliders jericho_slider' + pos + '_' + (enable ? 'enable' : 'disable') });
                }
                //slider to right to check whether it's a tab nearby left slider
                if ((space_l < 0 && space_l > -$.fn.jerichoTab.tabWidth) && (space_r > 0 && space_r < $.fn.jerichoTab.tabWidth)) {
                    //left
                    $.fn.jerichoTab.tabpage.animate({ left: -$.fn.jerichoTab.tabWidth * index }, 0, function() {
                        if (index == 0) setSlider('left', false);
                        else setSlider('left', true);
                        setSlider('right', true);
                    });
                }
                //slider to left to check whether it's a tab nearby right slider
                if ((space_l < tabWidth && space_l > tabWidth - $.fn.jerichoTab.tabWidth) && (space_r > tabWidth && space_r < tabWidth + $.fn.jerichoTab.tabWidth)) {
                    //right
                    $.fn.jerichoTab.tabpage.animate({ left: -$.fn.jerichoTab.tabWidth * (index + 1) + tabWidth }, 0, function() {
                        if (index == tabHash.length - 1) setSlider('right', false);
                        else setSlider('left', true);
                        setSlider('left', true);
                    });
                }
            }
        });
    },
    //apply event to the close anchor
    applyCloseEvent: function() {
        return this.each(function() {
            var me = this;
            $('.tab_close>a', this).click(function(e) {
                //prevents further propagation of the current event.
                e.stopPropagation();
                if ($(this).length == 0) return;
                //remove tab from tabpageholder
                $(me).animate({ 'opacity': '0', width: '0px' }, 100, function() {
                    //make the previous tab selected whether the removed tab was selected
                    var lastTab = $.fn.jerichoTab.tabpage.children('li').filter('.tab_selected');
                    if (lastTab.attr('id') == $(this).attr('id')) {
                    	if($(this).prev().text() != ''){
                            $(this).prev().swapTabEnable().loadData();
                    	}else{
                    		$(this).next().swapTabEnable().loadData();
                    	}
                    }
                    //clear the information of the removed tab from tabHash
                    for (var t in tabHash) {
                        if (tabHash[t].tabId == $(me).attr('id')) {
                            if (tabHash[t].tabFirer != null)
                                tabHash[t].tabFirer.removeAttr('jerichotabindex');
                            tabHash.splice(t, 1);
                        }
                    }
                    //adapt slider
                    $(me).applySlider().remove();
                    //remove contentholder
                    $('#jerichotabholder_' + $(me).attr('id').replace('jerichotab_', '')).remove();
                })
            });
            $(this).RightMenu('jerichotabmenu',{menuList:[
                {menuName:"刷新当前",clickEvent:"$('.tab_selected').loadData(true);"},
                {menuName:"关闭其它",clickEvent:"$('.tab_unselect .tab_close>a').click();"
                	+"setTimeout('$.fn.jerichoTab.resize();setTimeout(\\\'$.fn.jerichoTab.resize();"
                	+"setTimeout(\\\\\\'$.fn.jerichoTab.resize();\\\\\\',1000);\\\',500);',500);"}
        	]});
        });
    },
    //apply the "hover" effect and "onSelect" event
    applyHover: function() {
        return this.each(function() {
            $(this).hover(function() {
                if ($(this).hasClass('tab_unselect')) $(this).addClass('tab_unselect_h');
            }, function() {
                if ($(this).hasClass('tab_unselect_h')) $(this).removeClass('tab_unselect_h');
            }).mouseup(function() {
                if ($(this).hasClass('tab_selected')) return;
                //select this tab and hide the last selected tab
                var lastTab = $.fn.jerichoTab.tabpage.children('li').filter('.tab_selected');
                lastTab.attr('class', 'jericho_tabs tab_unselect');
                $('#jerichotabholder_' + lastTab.attr('id').replace('jerichotab_', '')).css({ 'display': 'none' });
                $(this).attr('class', 'jericho_tabs tab_selected').loadData().adaptSlider();
            });
        });
    },
    //switch the tab between the selected mode and the unselected mode, or v.v...
    swapTabEnable: function() {
        return this.each(function() {
            if ($(this).hasClass('tab_selected'))
                $(this).swapClass('tab_selected', 'tab_unselect');
            else if ($(this).hasClass('tab_unselect'))
                $(this).swapClass('tab_unselect', 'tab_selected');
        });
    },
    //change class from css1 to css2 of DOM
    swapClass: function(css1, css2) {
        return this.each(function() {
            $(this).removeClass(css1).addClass(css2);
        })
    },
    //if it takes a long time to load the data, show a loader to ui
    showLoader: function() {
        return this.each(function() {
            switch ($.fn.jerichoTab.loader) {
                case 'usebg':
                    //add a circular loading gif picture to the background of contentholder
                    $(this).addClass('loading');
                    break;
                case 'righttag':
                    //add a small loading gif picture and a banner to the right top corner of contentholder
                    if ($('#jerichotab_contentholder>.righttag').length == 0)
                        $('
正在加载...
').appendTo($(this));
                    else
                        $('#jerichotab_contentholder>.righttag').css({ display: 'block' });
                    break;
            }
        });
    },
    //remove the loader
    removeLoader: function() {
        switch ($.fn.jerichoTab.loader) {
            case 'usebg':
                $('#jerichotab_contentholder').removeClass('loading');
                break;
            case 'righttag':
                $('#jerichotab_contentholder>.righttag').css({ display: 'none' });
                break;
        }
    }
});
//})(jQuery);

String.prototype.cut = function(len) {
    var position = 0;
    var result = [];
    var tale = '';
    for (var i = 0; i < this.length; i++) {
        if (position >= len) {
            tale = '...';
            break;
        }
        if (this.charCodeAt(i) > 255) {
            position += 2;
            result.push(this.substr(i, 1));
        }
        else {
            position++;
            result.push(this.substr(i, 1));
        }
    }
    return result.join("") + tale;
}

/*
 * 右键菜单,示例:$(this).RightMenu('myMenu2',{menuList:[{menuName:"菜单1",menuclass:"1",clickEvent:"divClick(1)"}]});
 */
$(function(){
	document.oncontextmenu=function(){return false;}//屏蔽右键
	document.onmousemove=mouseMove;//记录鼠标位置
});
var mx=0,my=0;
function mouseMove(ev){Ev=ev||window.event;var mousePos=mouseCoords(Ev);mx=mousePos.x;my=mousePos.y;}
function mouseCoords(ev){
	if(ev.pageX||ev.pageY){return{x:ev.pageX,y:ev.pageY};}
	return{x:ev.clientX,y:ev.clientY+$(document).scrollTop()};
}
$.fn.extend({RightMenu: function(id,options){
	options = $.extend({menuList:[]},options);
	var menuCount=options.menuList.length;
	if (!$("#"+id)[0]){
		var divMenuList="

";
		for(var i=0;i<menuCount;i++){
			divMenuList+="
"+options.menuList[i].menuName+"
";
		}
		divMenuList += "

";
		$("body").append(divMenuList).find("#"+id).hide().find("li")
				.bind("mouseover",function(){$(this).addClass("RM_mouseover");})
				.bind("mouseout",function(){$(this).removeClass("RM_mouseover");});
		$(document).click(function(){$("#"+id).hide();});
	}
	return this.each(function(){
		this.oncontextmenu=function(){
			var mw=$('body').width(),mhh=$('html').height(),mbh=$('body').height(),
				w=$('#'+id).width(),h=$('#'+id).height(),
				mh=(mhh>mbh)?mhh:mbh;//最大高度 比较html与body的高度
			if(mh<h+my){my=mh-h;}//超 高
			if(mw<w+mx){mx=mw-w;}//超 宽
			$("#"+id).hide().css({top:my,left:mx}).show();
			$.fn.jerichoTab.resize(); // 修正弹出菜单时tab滚动被挤下去的问题
		}
	});
}});


text:
namespace ngraph
{
    namespace onnx_import
    {
        namespace op
        {
            namespace set_1
            {
                inline OutputVector min(const Node& node)
                {
                    return variadic::make_ng_variadic_op<default_opset::Minimum>(
                        node, ngraph::op::AutoBroadcastSpec::NONE);
                }
            }

            namespace set_8
            {
                inline OutputVector min(const Node& node)
                {
                    return variadic::make_ng_variadic_op<default_opset::Minimum>(node);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace peloton {
namespace benchmark {
namespace sdbench {

std::unique_ptr<storage::DataTable> sdbench_table;

void CreateTable() {
  const oid_t col_count = state.attribute_count + 1;
  const bool is_inlined = true;

  // Create schema first
  std::vector<catalog::Column> columns;

  for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
    auto column =
        catalog::Column(type::Type::INTEGER, type::Type::GetTypeSize(type::Type::INTEGER),
                        "" + std::to_string(col_itr), is_inlined);

    columns.push_back(column);
  }

  catalog::Schema *table_schema = new catalog::Schema(columns);
  std::string table_name("SDBENCHTABLE");

  /////////////////////////////////////////////////////////
  // Create table.
  /////////////////////////////////////////////////////////

  bool own_schema = true;
  bool adapt_table = true;
  sdbench_table.reset(storage::TableFactory::GetDataTable(
      INVALID_OID, INVALID_OID, table_schema, table_name,
      state.tuples_per_tilegroup, own_schema, adapt_table));
}

void LoadTable() {
  const oid_t col_count = state.attribute_count + 1;
  const int tuple_count = state.scale_factor * state.tuples_per_tilegroup;

  auto table_schema = sdbench_table->GetSchema();

  /////////////////////////////////////////////////////////
  // Load in the data
  /////////////////////////////////////////////////////////

  // Insert tuples into tile_group.
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  const bool allocate = true;
  auto txn = txn_manager.BeginTransaction();
  std::unique_ptr<type::AbstractPool> pool(new type::EphemeralPool());

  int rowid;
  for (rowid = 0; rowid < tuple_count; rowid++) {
    int populate_value = rowid;

    storage::Tuple tuple(table_schema, allocate);

    for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
      auto value = type::ValueFactory::GetIntegerValue(populate_value);
      tuple.SetValue(col_itr, value, pool.get());
    }

    ItemPointer tuple_slot_id = sdbench_table->InsertTuple(&tuple);
    PL_ASSERT(tuple_slot_id.block != INVALID_OID);
    PL_ASSERT(tuple_slot_id.offset != INVALID_OID);
    txn->RecordInsert(tuple_slot_id);
  }

  auto result = txn_manager.CommitTransaction(txn);

  if (result == Result::RESULT_SUCCESS) {
    LOG_TRACE("commit successfully");
  } else {
    LOG_TRACE("commit failed");
  }

}

void CreateAndLoadTable(LayoutType layout_type) {
  // Initialize settings
  peloton_layout_mode = layout_type;

  CreateTable();

  LoadTable();
}

void DropIndexes() {
  // Drop index
  sdbench_table->DropIndexWithOid(0);
}

}  // namespace sdbench
}  // namespace benchmark
}  // namespace peloton


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation = "horizontal">

    <!-- Emoticon image -->

    <ImageView
        android:id="@+id/emoticon"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <!-- Username and social situation -->
    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/emoticon"
        android:textSize="12sp"
        android:textAlignment="viewStart" />

    <!-- Location and date -->
    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/emoticon"
        android:textSize="12sp" />

    <!-- Mood Reason -->
    <TextView
        android:id="@+id/reason"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_toRightOf="@id/emoticon"
        android:textSize="20sp" />

    <!--  -->
    <ImageView
        android:id="@+id/picture"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true" />

</RelativeLayout>


text:
package org.junit.rules;

import org.junit.internal.AssumptionViolatedException;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

/**
 * TestWatchman is a base class for Rules that take note of the testing
 * action, without modifying it. For example, this class will keep a log of each
 * passing and failing test:
 *
 * <pre>
 * public static class WatchmanTest {
 *  private static String watchedLog;
 *
 *  @Rule
 *  public MethodRule watchman= new TestWatchman() {
 *      @Override
 *      public void failed(Throwable e, FrameworkMethod method) {
 *          watchedLog+= method.getName() + " " + e.getClass().getSimpleName()
 *                  + "\n";
 *         }
 *
 *      @Override
 *      public void succeeded(FrameworkMethod method) {
 *          watchedLog+= method.getName() + " " + "success!\n";
 *         }
 *     };
 *
 *  @Test
 *  public void fails() {
 *      fail();
 *     }
 *
 *  @Test
 *  public void succeeds() {
 *     }
 * }
 * </pre>
 *
 * @since 4.7
 * @deprecated Use {@link TestWatcher} (which implements {@link TestRule}) instead.
 */
@Deprecated
public class TestWatchman implements MethodRule {
    public Statement apply(final Statement base, final FrameworkMethod method,
            Object target) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                starting(method);
                try {
                    base.evaluate();
                    succeeded(method);
                } catch (AssumptionViolatedException e) {
                    throw e;
                } catch (Throwable t) {
                    failed(t, method);
                    throw t;
                } finally {
                    finished(method);
                }
            }
        };
    }

    /**
     * Invoked when a test method succeeds
     */
    public void succeeded(FrameworkMethod method) {
    }

    /**
     * Invoked when a test method fails
     */
    public void failed(Throwable e, FrameworkMethod method) {
    }

    /**
     * Invoked when a test method is about to start
     */
    public void starting(FrameworkMethod method) {
    }

    /**
     * Invoked when a test method finishes (whether passing or failing)
     */
    public void finished(FrameworkMethod method) {
    }
}


text:
<?php
/* @var $this AppsController */
/* @var $model Apps */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'apps-form',
	'htmlOptions'=>array("class"=>"","role"=>"form"),
	'enableAjaxValidation'=>true,
    'clientOptions'=>array('validateOnSubmit'=>true),
)); ?>
	<?php echo $form->errorSummary($model,null,null,array('class'=>'alert alert-danger')); ?>

		<?php echo CHtml::submitButton($model->isNewRecord ? Yii::t('app','Create') : Yii::t('app','Save'),array('class'=>'btn btn-primary btn-large')); ?>
		<?php echo CHtml::link(Yii::t('app','Back'),array('admin'),array('class'=>'btn btn-large btn-default'))?>

		<?php echo $form->labelEx($model,'name',array('class'=>'control-label')); ?>
		<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>255,'class'=>'form-control')); ?>
		<?php echo $form->error($model,'name',array('class'=>'help-block')); ?>

		<?php echo $form->labelEx($model,'redirect_uri',array('class'=>'control-label')); ?>
		<?php echo $form->textField($model,'redirect_uri',array('size'=>60,'maxlength'=>255,'class'=>'form-control')); ?>
		<?php echo $form->error($model,'redirect_uri',array('class'=>'help-block')); ?>

   	<?php /*

		<?php echo $form->labelEx($model,'scopes',array('class'=>'control-label')); ?>

		<?php $selected_keys = array_keys(CHtml::listData( $model->scopesapp, 'name' , 'name')); ?>
		<?php echo CHtml::checkBoxList('Apps[scopes][]',$selected_keys,UsersAuthitem::listData(),array('class'=>'form-control')); ?>
		<?php echo $form->error($model,'scopes',array('class'=>'help-block')); ?>

   	*/ ?>

		<?php echo CHtml::submitButton($model->isNewRecord ? Yii::t('app','Create') : Yii::t('app','Save'),array('class'=>'btn btn-primary btn-large')); ?>
		<?php echo CHtml::link(Yii::t('app','Back'),array('admin'),array('class'=>'btn btn-large btn-default'))?>

<?php $this->endWidget(); ?>


text:
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace ConvertToConditionalCS
{
    internal class ReturnConditionalAnalyzer : ConditionalAnalyzer
    {
        private ReturnConditionalAnalyzer(IfStatementSyntax ifStatement, SemanticModel semanticModel)
            : base(ifStatement, semanticModel)
        {
        }

        public static bool TryGetNewReturnStatement(IfStatementSyntax ifStatement, SemanticModel semanticModel, out ReturnStatementSyntax returnStatement)
        {
            returnStatement = null;

            var conditional = new ReturnConditionalAnalyzer(ifStatement, semanticModel).CreateConditional();
            if (conditional == null)
            {
                return false;
            }

            returnStatement = SyntaxFactory.ReturnStatement(conditional);

            return true;
        }

        protected override ExpressionSyntax CreateConditional()
        {
            ReturnStatementSyntax whenTrueStatement;
            ReturnStatementSyntax whenFalseStatement;
            if (!TryGetReturnStatements(IfStatement, out whenTrueStatement, out whenFalseStatement))
            {
                return null;
            }

            var whenTrue = whenTrueStatement.Expression;
            var whenFalse = whenFalseStatement.Expression;
            if (whenTrue == null || whenFalse == null)
            {
                return null;
            }

            var parentMember = IfStatement.FirstAncestorOrSelf<MemberDeclarationSyntax>();
            var memberSymbol = SemanticModel.GetDeclaredSymbol(parentMember);
            switch (memberSymbol.Kind)
            {
                case SymbolKind.Method:
                    var methodSymbol = (IMethodSymbol)memberSymbol;
                    return !methodSymbol.ReturnsVoid
                        ? CreateConditional(whenTrue, whenFalse, methodSymbol.ReturnType)
                        : null;

                default:
                    return null;
            }
        }

        private static bool TryGetReturnStatements(IfStatementSyntax ifStatement, out ReturnStatementSyntax whenTrueStatement, out ReturnStatementSyntax whenFalseStatement)
        {
            Debug.Assert(ifStatement != null);
            Debug.Assert(ifStatement.Else != null);

            whenTrueStatement = null;
            whenFalseStatement = null;

            var statement = ifStatement.Statement.SingleStatementOrSelf() as ReturnStatementSyntax;
            if (statement == null)
            {
                return false;
            }

            var elseStatement = ifStatement.Else.Statement.SingleStatementOrSelf() as ReturnStatementSyntax;
            if (elseStatement == null)
            {
                return false;
            }

            whenTrueStatement = statement;
            whenFalseStatement = elseStatement;
            return true;
        }
    }
}


text: <select data-ng-options="item as item for item in ItemArray" data-ng-model="selectedOption" ng-change="update()"></select>


text:
import { setQuarter } from 'date-fns'
export default setQuarter


text:
// ==UserScript==
// @name Main
// @include http://*.youneedabudget.com/*
// @include https://*.youneedabudget.com/*
// @require res/features/allSettings.js
// ==/UserScript==

function injectCSS(path) {
  var link = document.createElement('link');
  link.setAttribute('rel', 'stylesheet');
  link.setAttribute('type', 'text/css');
  link.setAttribute('href', kango.io.getResourceUrl(path));

  document.getElementsByTagName('head')[0].appendChild(link);
}

var previouslyInjectedScripts = [];

function injectScript(path) {
  if (previouslyInjectedScripts.indexOf(path) < 0) {
    previouslyInjectedScripts.push(path);

    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', kango.io.getResourceUrl(path));

    document.getElementsByTagName('head')[0].appendChild(script);
  }
}

function injectJSString(js) {
  var script = document.createElement('script');
  script.text = js;

  document.getElementsByTagName('head')[0].appendChild(script);
}

function applySettingsToDom() {
  ynabToolKit.settings.forEach(function (setting) {
    getKangoSetting(setting.name).then(function (data) {
      // Check for specific upgrade path where a boolean setting gets
      // changed to a select. Previous value will be 'true' but
      // that should map to '1' in select land.
      // eslint-disable-next-line eqeqeq
      if (data == 'true' &&
          '1' in setting.actions &&
          !('true' in setting.actions)) {
        data = '1';
      }

      if (data in setting.actions) {
        var selectedActions = setting.actions[data.toString()];
        for (var i = 0; i < selectedActions.length; i += 2) {
          var action = selectedActions[i];
          var target = selectedActions[i + 1];

          if (action === 'injectCSS') {
            injectCSS(target);
          } else if (action === 'injectScript') {
            injectScript(target);
          } else if (action === 'injectJSString') {
            injectJSString(target);
          } else {
            var error = "Invalid action '" + action + "'. Only injectCSS, injectScript and injectJSString are currently supported.";
            throw error;
          }
        }
      }
    });
  });
}

/* Init ynabToolKit object and import options from Kango  */
var options = {};

function pushOption(setting) {
  return getKangoSetting(setting.name).then(function (data) {
    options[setting.name] = data;
  });
}

var optionsPromises = [];

ynabToolKit.settings.forEach(function (setting) {
  optionsPromises.push(pushOption(setting));
});

Promise.all(optionsPromises).then(function () {
  let version = getKangoExtensionInfo().version;

  injectJSString('window.ynabToolKit = { version: \'' + version + '\'}; ynabToolKit.options = ' + JSON.stringify(options) + '; Object.freeze(ynabToolKit.options); Object.seal(ynabToolKit.options);');

  /* Load this to setup shared utility functions */
  injectScript('res/features/shared/main.js');

  /* Global toolkit css. */
  injectCSS('res/features/shared/main.css');

  /* This script to be built automatically by the python script */
  injectScript('res/features/act-on-change/feedChanges.js');

  /* Load this to setup behaviors when the DOM updates and shared functions */
  injectScript('res/features/act-on-change/main.js');

  ensureDefaultsAreSet().then(applySettingsToDom);
});


text:
GLint getUniLoc(const GLuint program, const GLchar *name);
void  printShaderInfoLog(GLuint obj);
void  printProgramInfoLog(GLuint obj);

const std::string GetShaderSourceFromFile(
    const char* filename,
    const std::string path=std::string("../shaders/"));
const GLchar* GetShaderSourceFromTable(const char* filename);
const std::string GetShaderSource(const char* filename);
GLuint loadShaderFile(const char* filename, const unsigned long Type);

///@todo Audit these terrible variable names
GLuint makeShaderFromSource(
    const char* vertSrc,
    const char* fragSrc,
    const char* geomSrc=NULL);
GLuint makeShaderByName(const char* name);


text:
$(document).ready(function () {
$('table.table-sort tbody').sortable({
    items: "> tr",
    handle: '.sort-row',
    axis: 'y',
    update: function (event, ui) {
        var orderDirection = 'desc';
        if ($('table.table-sort a[href$="[order]"]').attr('data-method') === 'orderAsc') {
            orderDirection = 'asc';
        }
        $.post($('table.table-sort').attr('data-sort-url'), {
                order: orderDirection,
                value: $(this).sortable('toArray', {attribute: "data-id"})
            },
            function (result) {
                if (result) {
                    alert(result);
                }
            });
    }
});
$('table.table-sort tbody').disableSelection();
});


text:
package org.apache.harmony.luni.internal.locale;
public class Currency_fr_FR extends java.util.ListResourceBundle {
protected Object[][] getContents() {
	Object[][] contents = {
		{"FRF","F",},
	};
return contents;
}
}


text:
namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace wkb {

template <typename T>
struct value_parser
{
    typedef T value_type;

    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, T& value, byte_order_type::enum_t order)
    {
        // Very basic pre-conditions check on stream of bytes passed in
        BOOST_STATIC_ASSERT((
            boost::is_integral<typename std::iterator_traits<Iterator>::value_type>::value
        ));
        BOOST_STATIC_ASSERT((sizeof(boost::uint8_t) ==
            sizeof(typename std::iterator_traits<Iterator>::value_type)
        ));

        typedef typename std::iterator_traits<Iterator>::difference_type diff_type;
        diff_type const required_size = sizeof(T);
        if (it != end && std::distance(it, end) >= required_size)
        {
            typedef endian::endian_value<T> parsed_value_type;
            parsed_value_type parsed_value;

            // Decide on direcion of endianness translation, detault to native
            if (byte_order_type::xdr == order)
            {
                parsed_value.template load<endian::big_endian_tag>(it);
            }
            else if (byte_order_type::ndr == order)
            {
                parsed_value.template load<endian::little_endian_tag>(it);
            }
            else
            {
                parsed_value.template load<endian::native_endian_tag>(it);
            }

            value = parsed_value;
            std::advance(it, required_size);
            return true;
        }

        return false;
    }
};

struct byte_order_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, byte_order_type::enum_t& order)
    {
        boost::uint8_t value;
        if (value_parser<boost::uint8_t>::parse(it, end, value, byte_order_type::unknown))
        {
            if (byte_order_type::unknown > value)
            {
                order = byte_order_type::enum_t(value);
            }
            return true;
        }
        return false;
    }
};

struct geometry_type_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, geometry_type::enum_t& type,
        byte_order_type::enum_t order)
    {
        boost::uint32_t value;
        if (value_parser<boost::uint32_t>::parse(it, end, value, order))
        {
            // TODO: Refine the test when multi* geometries are supported

            boost::uint32_t id = value & 0xff;
            if (geometry_type::polygon >= id)
            {
                type = geometry_type::enum_t(id);
                return true;
            }
        }
        return false;
    }
};

template <typename P, int I, int N>
struct parsing_assigner
{
    template <typename Iterator>
    static void run(Iterator& it, Iterator end, P& point, byte_order_type::enum_t order)
    {
        typedef typename coordinate_type<P>::type coordinate_type;

        // coordinate type in WKB is always double
        double value(0);
        if (value_parser<double>::parse(it, end, value, order))
        {
            // actual coordinate type of point may be different
            set<I>(point, static_cast<coordinate_type>(value));
        }
        else
        {
            // TODO: mloskot - Report premature termination at coordinate level
            //throw failed to read coordinate value

            // default initialized value as fallback
            set<I>(point, coordinate_type());
        }
        parsing_assigner<P, I+1, N>::run(it, end, point, order);
    }
};

template <typename P, int N>
struct parsing_assigner<P, N, N>
{
    template <typename Iterator>
    static void run(Iterator& it, Iterator end, P& point, byte_order_type::enum_t order)
    {
        // terminate
    }
};

template <typename P>
struct point_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, P& point, byte_order_type::enum_t order)
    {
        // TODO: mloskot - Add assert on point dimension, 2d only

        geometry_type::enum_t type;
        if (geometry_type_parser::parse(it, end, type, order))
        {
            if (geometry_type::point == type && it != end)
            {
                parsing_assigner<P, 0, dimension<P>::value>::run(it, end, point, order);
            }
            return true;
        }
        return false;
    }
};

template <typename C>
struct point_container_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, C& container, byte_order_type::enum_t order)
    {
        typedef typename point_type<C>::type point_type;

        boost::uint32_t num_points(0);
        if (!value_parser<boost::uint32_t>::parse(it, end, num_points, order))
        {
            return false;
        }

        typedef typename std::iterator_traits<Iterator>::difference_type size_type;
        assert(num_points <= boost::uint32_t( (std::numeric_limits<size_type>::max)() ) );

        size_type const container_size = static_cast<size_type>(num_points);
        size_type const point_size = dimension<point_type>::value * sizeof(double);

        if (std::distance(it, end) >= (container_size * point_size))
        {
            point_type point_buffer;
            std::back_insert_iterator<C> output(std::back_inserter(container));

            // Read coordinates into point and append point to line (ring)
            size_type points_parsed = 0;
            while (points_parsed < container_size && it != end)
            {
                parsing_assigner<point_type, 0, dimension<point_type>::value>::run(it, end, point_buffer, order);
                output = point_buffer;
                ++output;
                ++points_parsed;
            }

            if (container_size != points_parsed)
            {
                return false;
            }
        }

        return true;
    }
};

template <typename L>
struct linestring_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, L& linestring, byte_order_type::enum_t order)
    {
        typedef typename point_type<L>::type point_type;

        geometry_type::enum_t type;
        if (!geometry_type_parser::parse(it, end, type, order))
        {
            return false;
        }

        if (geometry_type::linestring != type)
        {
            return false;
        }

        assert(it != end);
        return point_container_parser<L>::parse(it, end, linestring, order);
    }
};

template <typename Polygon>
struct polygon_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, Polygon& polygon, byte_order_type::enum_t order)
    {
        geometry_type::enum_t type;
        if (!geometry_type_parser::parse(it, end, type, order))
        {
            return false;
        }

        boost::uint32_t num_rings(0);
        if (geometry_type::polygon != type ||
            !value_parser<boost::uint32_t>::parse(it, end, num_rings, order))
        {
            return false;
        }

        typedef typename ring_type<Polygon>::type ring_type;

        std::size_t rings_parsed = 0;
        while (rings_parsed < num_rings && it != end) //while (rings_parsed < num_rings && it != end)
        {
            if (0 == rings_parsed)
            {
                ring_type& ring0 = exterior_ring(polygon);
                if (!point_container_parser<ring_type>::parse(it, end, ring0, order))
                {
                    return false;
                }
            }
            else
            {
                interior_rings(polygon).resize(rings_parsed);
                ring_type& ringN = interior_rings(polygon).back();
                if (!point_container_parser<ring_type>::parse(it, end, ringN, order))
                {
                    return false;
                }
            }
            ++rings_parsed;
        }

        if (num_rings != rings_parsed)
        {
            return false;
        }

        return true;
    }
};

}} // namespace detail::wkb
#endif // DOXYGEN_NO_IMPL

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_IO_WKB_DETAIL_PARSER_HPP


text:
layout: page
title: Weiss 55th Anniversary
date: 2016-05-24
author: Carol Holloway
tags: weekly links, java
status: published
summary: Phasellus laoreet leo non turpis iaculis, id mattis.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 05/17/2019
  endDate: 05/18/2019
  ctyhocn: SPLNJHX
  groupCode: W5A
published: true
---
Praesent vulputate vitae quam sit amet volutpat. Sed eget porta nisl, sed fermentum dui. Ut ultrices elit eu vestibulum luctus. Aenean efficitur a ante vitae feugiat. Pellentesque sodales in neque consectetur feugiat. Praesent sit amet iaculis diam. Duis condimentum odio tortor, sed pulvinar ante lobortis non. Duis tempor risus eu odio vehicula, eu blandit eros semper. Ut congue molestie ante, non efficitur tortor interdum a. Nulla in augue sit amet urna eleifend dapibus. Nam in malesuada libero.

* Vestibulum quis nulla ut massa eleifend porttitor non sed enim
* Etiam tempus magna eu sodales facilisis
* Etiam vitae enim tincidunt, facilisis ipsum sagittis, porttitor justo
* Vivamus mollis risus nec odio ultricies sagittis.

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam auctor et magna et fermentum. Duis eros dui, suscipit cursus tempus vitae, accumsan iaculis ligula. Morbi eu iaculis sem, vitae dapibus augue. Nulla facilisi. Sed porttitor non erat sit amet blandit. Quisque eu sodales sapien. Sed porta sit amet sem vel bibendum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.


text:
#import <Foundation/Foundation.h>
#import "CloudResponse.h"

/*!
 * @brief The delegate to receive the data from the cloud for asynchronous request.
 */
@interface HttpResponseDelegatee : NSObject

+(id) sharedInstance;

@property (atomic,copy) void (^readResponse)(CloudResponse *);
- (id) init __attribute__((unavailable("Must create singleton using \"sharedInstance\" method")));
@end


text:
Fast binding for vcgencmd.

## Install
    npm install vcgencmd

## Usage
```javascript
var vcgencmd = require('vcgencmd');
console.log(vcgencmd.codecEnabled('H264'));
console.log(vcgencmd.measureClock('core'));
```

## API
[See elinux for details](http://elinux.org/RPI_vcgencmd_usage).

Note that case matters.

### `measureClock(string clock) → number`
`clock` can be one of **arm, core, h264, isp, v3d, uart, pwm, emmc, pixel, vec, hdmi, dpi**.

### `measureVolts(string id) → number`
`id` can be one of **core, sdram_c, sdram_i, sdram_p**.

### `measureTemp() → number`

### `codecEnabled(string codec) → boolean`
`codec` can be one of **H264, MPG2, WVC1, MPG4, MJPG, WMV9**.

### `getConfig(string config) → Object|number|string`
`config` is specific option (for example, **arm_freq**), **int** or **str**. if `config` is **int** or **str** then return map of numbers or strings respectively.

### `getCamera() → {boolean supported, boolean detected}`

### `getMem(string mem) → number`
`mem` can be **arm** or **gpu**.

### `getLCDInfo() → {number width, number height, number depth}`

### `cacheFlush() → void`

## Changelog
### v0.3.0
* Add >0.12 compatibility of native add-on. Thanks to [Mark Plomer](https://github.com/not-implemented).

### v0.2.5
* `getLCDInfo` and `cacheFlush`

### v0.2.0
* `measureVolts`
* TS definition

### v0.1.0
* `measureClock`, `measureTemp`, `codecEnabled`, `getConfig`, `getCamera` and `getMem`


text:
layout: default
title: Outreach
permalink: /outreach/
---

I am co-founder of [Astronomy on Tap](http://astronomyontap.org/) (AoT) in [Seattle](https://www.facebook.com/AoTSeattle), a free monthly outreach event featuring astronomy-themed talks and trivia at a local brewery. AoT Seattle has been holding events since March 2015, and now regularly draws crowds of over 200 astro-enthusiasts each month. All events are now live-streamed, as well as recorded on our [YouTube channel](https://www.youtube.com/channel/UCXT72Io5VlTXXJrpPezFj0A/videos). From 2015-2017 I also served as the coordinator for the [University of Washington Planetarium](http://depts.washington.edu/astron/outreach/uw-planetarium/). Please feel free to [contact](../../) me with inquiries related to astronomy outreach and education!

Astronomy on Tap Seattle crowd at Peddler Brewing Company, August 2016.


text:
/**
 * Populate DB with sample data on server start
 * to disable, edit config/environment/index.js, and set `seedDB: false`
 */

'use strict';

var beaconService = require('../service/beacon.service.js');
var beaconDetectionService = require('../service/beacon-detection.service.js');
var agentService = require('../service/agent.service.js');

var userService = require('../service/user.service.js');
var beaconDao = require('../dao/beacon.dao.js');
var agentDao = require('../dao/agent.dao.js');
var beaconDetectionDao = require('../dao/beacon-detection.dao.js');

var seedData = require('./seedData.js');

module.exports = function (complete) {

    var savedAgents;
    var savedBeacons;

    // delete users
    userService.deleteAllUsers()
        // then populate users
        .then(function () {
            var createPromise = userService.createUsers(seedData.users);

            createPromise.then(function() {
                console.log('finished populating users');
            });

            return createPromise;
        })
        // then delete beacons
        .then(function () {
            return beaconDao.deleteAllBeacons();
        })
        // then populate beacons
        .then(function () {
            var createPromise = beaconService.createBeacons(seedData.beacons);
            createPromise.then(function (beacons) {
                savedBeacons = beacons;
                console.log('finished populating beacons');
            });
            return createPromise;
        })
        // then delete agents
        .then(function () {
            return agentDao.deleteAllAgents();
        })
        // then populate agents
        .then(function () {
            var createPromise = agentService.createAgents(seedData.agents);
            createPromise.then(function (agents) {
                savedAgents = agents;
                console.log('finished populating agents');
            });
            return createPromise;
        })
        // then delete detections
//        .then(function () {
//            return beaconDetectionDao.deleteAllDetections();
//        })
        // then populate detections
        .then(function () {
            var createPromise = beaconDetectionService.createDetections([
                {
                    time: Date.now(),
                    uuid: savedBeacons[0].uuid,
                    major: 11111,
                    minor: 22222,
                    tx: 3,
                    rssi: 1,
                    proximity: 1.2,
                    agentId: savedAgents[0].customId
                },
                {
                    time: Date.now(),
                    uuid: savedBeacons[0].uuid,
                    major: 11112,
                    minor: 22223,
                    tx: 4,
                    rssi: 2,
                    proximity: 2.2,
                    agentId: savedAgents[1].customId
                },
                {
                    time: Date.now(),
                    uuid: savedBeacons[1].uuid,
                    major: 1,
                    minor: 1,
                    tx: -65,
                    rssi: -75,
                    proximity: 3.7,
                    agentId: savedAgents[2].customId
                }
            ]);

            createPromise.then(function () {
                console.log('finished populating beacon detections');
            });
            return createPromise;
        }
    )
        .then(function () {
            console.log('Seed data complete!');
            complete();
        }, function (err) {
            console.log('Error loading seed data: ' + err);
        });
}


text:
package mf.org.w3c.dom.html;

import mf.org.w3c.dom.*;

import mf.org.w3c.dom.html.HTMLElement;

/**
 * Regroups the COL and COLGROUP elements. See the
 * COL element definition in HTML 4.0.
 */
public interface HTMLTableColElement extends HTMLElement {
  /**
   * Horizontal alignment of cell data in column. See the align attribute
   * definition in HTML 4.0.
   */
  public String             getAlign();
  public void               setAlign(String align);
  /**
   * Alignment character for cells in a column. See the char attribute
   * definition in HTML 4.0.
   */
  public String             getCh();
  public void               setCh(String ch);
  /**
   * Offset of alignment character. See the charoff attribute definition in
   * HTML 4.0.
   */
  public String             getChOff();
  public void               setChOff(String chOff);
  /**
   * Indicates the number of columns in a group or affected by a grouping. See
   * the span attribute definition in HTML 4.0.
   */
  public int                getSpan();
  public void               setSpan(int span);
  /**
   * Vertical alignment of cell data in column. See the valign attribute
   * definition in HTML 4.0.
   */
  public String             getVAlign();
  public void               setVAlign(String vAlign);
  /**
   * Default column width. See the width attribute definition in HTML 4.0.
   */
  public String             getWidth();
  public void               setWidth(String width);
}


text:
cHangingEntity::cHangingEntity(eEntityType a_EntityType, eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z)
	:	cEntity(a_EntityType, a_X, a_Y, a_Z, 0.8, 0.8)
	, m_BlockFace(a_BlockFace)
{
	SetMaxHealth(1);
	SetHealth(1);
}

void cHangingEntity::SpawnOn(cClientHandle & a_ClientHandle)
{
	int Dir = 0;

	// The client uses different values for item frame directions and block faces. Our constants are for the block faces, so we convert them here to item frame faces
	switch (m_BlockFace)
	{
		case BLOCK_FACE_ZP: break; // Initialised to zero
		case BLOCK_FACE_ZM: Dir = 2; break;
		case BLOCK_FACE_XM: Dir = 1; break;
		case BLOCK_FACE_XP: Dir = 3; break;
		default: ASSERT(!"Unhandled block face when trying to spawn item frame!"); return;
	}

	if ((Dir == 0) || (Dir == 2)) // Probably a client bug, but two directions are flipped and contrary to the norm, so we do -180
	{
		SetYaw((Dir * 90) - 180);
	}
	else
	{
		SetYaw(Dir * 90);
	}

	a_ClientHandle.SendSpawnObject(*this, 71, Dir, (Byte)GetYaw(), (Byte)GetPitch());
	a_ClientHandle.SendEntityMetadata(*this);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.codehaus.mojo.exec.it</groupId>
  <artifactId>mexec-70</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>@project.version@</version>
        <executions>
          <execution>
            <phase>process-classes</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>java</executable>
              <arguments>
                <argument>-classpath</argument>
                <classpath />
                <argument>Main</argument>
              </arguments>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
Ext.provide('Phlexible.messages.subscription.MainPanel');

Ext.require('Phlexible.messages.model.Subscription');

Phlexible.messages.subscription.MainPanel = Ext.extend(Ext.Panel, {
    title: Phlexible.messages.Strings.subscriptions,
    strings: Phlexible.messages.Strings,
    iconCls: 'p-message-subscription-icon',
    layout: 'fit',

    initComponent: function () {

        // Create RowActions Plugin
        var actions = new Ext.ux.grid.RowActions({
            header: this.strings.actions,
            width: 40,
            actions: [
                {
                    iconCls: 'p-message-delete-icon',
                    tooltip: this.strings["delete"],
                    callback: this.deleteSubscription.createDelegate(this),
                    scope: this
                }
            ]
        });

        this.items = [
            {
                xtype: 'grid',
                region: 'center',
                loadMask: true,
                viewConfig: {
                    emptyText: this.strings.no_subscriptions,
                    deferEmptyText: false
                },
                store: new Ext.data.JsonStore({
                    url: Phlexible.Router.generate('messages_subscriptions'),
                    fields: Phlexible.messages.model.Subscription,
                    id: 'id',
                    autoLoad: true
                }),
                columns: [
                    {
                        header: this.strings.id,
                        dataIndex: 'id',
                        width: 200,
                        hidden: true
                    },
                    {
                        header: this.strings.filter,
                        width: 200,
                        dataIndex: 'filter'
                    },
                    {
                        header: this.strings.handler,
                        width: 200,
                        dataIndex: 'handler'
                    },
                    actions
                ],
                plugins: [actions]
            }
        ];

        this.tbar = [
            {
                xtype: 'combo',
                emptyText: this.strings.filter,
                store: new Ext.data.JsonStore({
                    url: Phlexible.Router.generate('messages_filters'),
                    id: 'id',
                    fields: Phlexible.messages.model.Filter
                }),
                displayField: 'title',
                valueField: 'id',
                mode: 'remote',
                editable: false,
                allowBlank: false,
                triggerAction: 'all'
            },
            ' ',
            {
                xtype: 'iconcombo',
                emptyText: this.strings.handler,
                store: new Ext.data.SimpleStore({
                    fields: ['id', 'name', 'iconCls'],
                    data: Phlexible.messages.Handlers
                }),
                displayField: 'name',
                valueField: 'id',
                iconClsField: 'iconCls',
                mode: 'local',
                editable: false,
                allowBlank: false,
                triggerAction: 'all'
            },
            ' ',
            {
                xtype: 'button',
                text: this.strings.subscribe,
                iconCls: 'p-message-subscription-icon',
                handler: function () {
                    var filter = this.getTopToolbar().items.items[0].getValue(),
                        handler = this.getTopToolbar().items.items[2].getValue();

                    Ext.Ajax.request({
                        url: Phlexible.Router.generate('messages_subscription_create'),
                        params: {
                            filter: filter,
                            handler: handler
                        },
                        success: function (response) {
                            var result = Ext.decode(response.responseText);

                            if (result.success) {
                                this.getComponent(0).getStore().reload();
                                Phlexible.success(result.msg);
                            } else {
                                Phlexible.failure(result.msg);
                            }
                        },
                        scope: this
                    });
                },
                scope: this
            }
        ];

        Phlexible.messages.subscription.MainPanel.superclass.initComponent.call(this);
    },

    reloadSubscriptions: function () {
        this.getComponent(0).getStore().reload();
    },

    deleteSubscription: function (grid, record) {
        Ext.Ajax.request({
            url: Phlexible.Router.generate('messages_subscription_delete', {id: record.data.id}),
            success: function (response) {
                var result = Ext.decode(response.responseText);

                if (result.success) {
                    this.getComponent(0).getStore().reload();
                    Phlexible.success(result.msg);
                } else {
                    Phlexible.failure(result.msg);
                }
            },
            scope: this
        })
    }
});

Ext.reg('messages-subscription-mainpanel', Phlexible.messages.subscription.MainPanel);


text:
SOFTWARE to install

Specifies the software products you want to install.

Note: You do not need to have a licence password to install a
product, but the software may not run after it is installed without
one.


text:
/*
 * Phone.com API
 * This is a Phone.com api Swagger definition
 *
 * OpenAPI spec version: 1.0.0
 * Contact: apisupport@phone.com
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package io.swagger.client;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

public class JSON {
    private ApiClient apiClient;
    private Gson gson;

    /**
     * JSON constructor.
     *
     * @param apiClient An instance of ApiClient
     */
    public JSON(ApiClient apiClient) {
        this.apiClient = apiClient;
        gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateAdapter(apiClient))
            .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
            .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
            .create();
    }

    /**
     * Get Gson.
     *
     * @return Gson
     */
    public Gson getGson() {
        return gson;
    }

    /**
     * Set Gson.
     *
     * @param gson Gson
     */
    public void setGson(Gson gson) {
        this.gson = gson;
    }

    /**
     * Serialize the given Java object into JSON string.
     *
     * @param obj Object
     * @return String representation of the JSON
     */
    public String serialize(Object obj) {
        return gson.toJson(obj);
    }

    /**
     * Deserialize the given JSON string to Java object.
     *
     * @param <T> Type
     * @param body The JSON string
     * @param returnType The type to deserialize into
     * @return The deserialized Java object
     */
    @SuppressWarnings("unchecked")
    public <T> T deserialize(String body, Type returnType) {
        try {
            if (apiClient.isLenientOnJson()) {
                JsonReader jsonReader = new JsonReader(new StringReader(body));
                // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
                jsonReader.setLenient(true);
                return gson.fromJson(jsonReader, returnType);
            } else {
                return gson.fromJson(body, returnType);
            }
        } catch (JsonParseException e) {
            // Fallback processing when failed to parse JSON form response body:
            //   return the response body string directly for the String return type;
            //   parse response body into date or datetime for the Date return type.
            if (returnType.equals(String.class))
                return (T) body;
            else if (returnType.equals(Date.class))
                return (T) apiClient.parseDateOrDatetime(body);
            else throw(e);
        }
    }
}

class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
    private final ApiClient apiClient;

    /**
     * Constructor for DateAdapter
     *
     * @param apiClient Api client
     */
    public DateAdapter(ApiClient apiClient) {
        super();
        this.apiClient = apiClient;
    }

    /**
     * Serialize
     *
     * @param src Date
     * @param typeOfSrc Type
     * @param context Json Serialization Context
     * @return Json Element
     */
    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        if (src == null) {
            return JsonNull.INSTANCE;
        } else {
            return new JsonPrimitive(apiClient.formatDatetime(src));
        }
    }

    /**
     * Deserialize
     *
     * @param json Json element
     * @param date Type
     * @param context Json Serialization Context
     * @return Date
     * @throws JsonParseException if fail to parse
     */
    @Override
    public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException {
        String str = json.getAsJsonPrimitive().getAsString();
        try {
            return apiClient.parseDateOrDatetime(str);
        } catch (RuntimeException e) {
            throw new JsonParseException(e);
        }
    }
}

/**
 * Gson TypeAdapter for Joda DateTime type
 */
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {

    private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser();
    private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime();

    @Override
    public void write(JsonWriter out, DateTime date) throws IOException {
        if (date == null) {
            out.nullValue();
        } else {
            out.value(printFormatter.print(date));
        }
    }

    @Override
    public DateTime read(JsonReader in) throws IOException {
        switch (in.peek()) {
            case NULL:
                in.nextNull();
                return null;
            default:
                String date = in.nextString();
                return parseFormatter.parseDateTime(date);
        }
    }
}

/**
 * Gson TypeAdapter for Joda LocalDate type
 */
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {

    private final DateTimeFormatter formatter = ISODateTimeFormat.date();

    @Override
    public void write(JsonWriter out, LocalDate date) throws IOException {
        if (date == null) {
            out.nullValue();
        } else {
            out.value(formatter.print(date));
        }
    }

    @Override
    public LocalDate read(JsonReader in) throws IOException {
        switch (in.peek()) {
            case NULL:
                in.nextNull();
                return null;
            default:
                String date = in.nextString();
                return formatter.parseLocalDate(date);
        }
    }
}


text:
While using import statements, prefer to use relative pathing instead of parentURL pathing.

We should prefer (example in kondike.js):
```
import "./board.js";
import "./game.js";
```
over
```
import "klondike/board.js";
import "klondike/game.js";
```
## SystemJS baseURL Config

Load the application, check the `System.baseURL` from console, by default this url points at wherever
the application is launched from (index.htm). For this application, it is "http://127.0.0.1:8080/app/".
SystemJS figure use the parent URL of index.html (after all, system.js is loaded from index.htm) as the default value for `System.baseURL`.
This baseURL comes into play when normalizing(resolving) module names, i.e., from angular to a complete url where angular module can be loaded.
When the browser request app.js, app.js is appended to the end of `System.baseURL`.

It can be overriden by `baseURL` property in SystemJS config file if we do need to resolve modules from unconventional places.

## jspm init

Questions asked by `jspm init`, answer options and implications:

1. Would you like jspm to prefix the jspm package.json properties under jspm? [yes]
Create a `jspm` property in package.json file for jspm configuration.
Among other things, this jspm property will keep track of dependencies you have installed with `jspm install` command.

1. Enter server baseURL (public folder path) [.]
For this project's set up, we run the web server (see `npm start` script) from where package.json resides,
our application (app.js and index.html and the rest of the modules) lives in the `app` folder. Setting the
server baseURL to `app` tells jspm to look for the application files in this `app` folder. `jspm` command
should be run from there directory where package.json file resides, because jspm's configuration is a
subsection (by answer to the first question above) in package.json file.

1. Enter jspm packages folder [app/jspm_packages]
It will default to whatever the server baseURL concatenated with `/jspm_packages`.

1. Enter config file path [app/config.js]
It will default to the server baseURL concatenated with `/config.js`.
If you leave it as default, there will be no visible configuration items for it in the jspm section in package.json file.

1. Configuration file config.js doesn't exist, create it? [yes]
Say yes.

1. Enter client baseURL (public folder URL) [/]:

1. Which ES6 transpiler would you like to use, Traceur or Babel? [babel]:
Say yes.

The init process will pull down babel-core, babel-runtime and core-js
JSPM works out-of-the-box with NPM and github repositories to download packages.

### paths in config.js

`paths` is a different way of configuring resolution of modules.
https://github.com/systemjs/systemjs/blob/master/docs/config-api.md#paths

It provides alias for packages imported from external package management systems: NPM, github.

## Production workflows

### Only use NPM package (not using JSPM registry)
My choice would be not to use jspm's registry, which is its proprietary package repository, intead I
think it is best to use only one package management system, which is NPM.

### jspm install
This way to make it work is to use jspm's ability to install a package from NPM
into its local jspm_package directory. An example would be `jspm install angular npm:angular=@angular`,whereas `@angular` is the package name in NPM,
`angular` is the alias to bring into jspm local registry, also the name to use in import statements in source code.

This command download package from NPM into local `jspm_packages` diretory and managed it the jspm way.

There is a way to get away with jspm registry and `jspm install` altogether by using just `npm install` and systemjs and jspm's depcache function.
[See the example here](https://github.com/yilinglu/Angular2-GettingStarted/blob/master/APM%20-%20Final%20Updated/systemjs.config.js)
The key is the put the systemjs config file (config.js) and package.json file in the same directory. Then we can use the `packages` property
in systemjs' config file to resolve and load packages directly from npm local dir (node_modules).

#### jspm install from github

Example as follows. Either will work, each will download and install to fit a different purpose.

`jspm install ngDraggable=github:fatlinesofcode/ngDraggable` (alias to ngDraggable in jspm registry)
`jspm install github:fatlinesofcode/ngDraggable` (use fatlinesofcode/ngDraggable as name to import, it is also the name in jspm local registry)
`jspm install github:fatlinesofcode/ngDraggable@0.1.8` (download a specific version)

### Bundle up with jspm

1. `jspm bundle app.js app/app.bundle.js`
1. `jspm bundle app.js app/app.bundle.js --inject` will save adding a script
tag for the bundle file. Intead, jspm will modify the config.js file during the bundling process
by adding a `bundle` property to config.js to tell SystemJS that if any of the files in the
bundles are request, just request and get the entire bundle file. This is possible because
config.js file in included as a script tag in index.html

This is an entirely uninstrusive process to run in CI environment and for production build.
Whilst the development environment can work with unbundled source code that is transpiled in real time on the browser side.

With SystemJS, we can develope without anything bundled. Bundling is only a production concern.

### SystemJS bundle arithmetic

[Use systemJS bundle arithmetic](https://github.com/systemjs/builder) capability for elaborate bundling requirements.
Looks like we need to create separate scripts to deal with complex bundling scenario.

### SystemJS CSP version

If we are bundling our application, we no longer need the full-blown version of system.js, we could use the
`system-csp-production.js` - [a lightweight systemJS version](https://github.com/systemjs/systemjs/blob/master/docs/production-workflows.md).
The reason this works is because AMD module and the System.register formatted module can be loaded with a script tag. With this modules, they
can be loaded with a sript tag instead of via XHR request.
Once we bundle our application with SystemJS, all our applications are bundled with System.register format, which is safe to be loaded with
a script tag. Thus we can use this light weight csp version of systemjs.

### depCache

Runing `jspm depcache app.js` will inject a depCache property into config.js file (without extra command line options like bundle's `--inject`) .
This could be the best option for production environment.
1. All source files are not bundled and loaded on demand only when needed.
1. When a source file is loaded, all of its dependencies are loaded in parallel.
1. No bundling is needed. When the browser supports HTTP/2, the dependencies loading can take advantage of
the protocol level optimization automatically without any work on our part. We have future proof our application.

### SystemJS meta property

Use [meta property](https://github.com/systemjs/systemjs/blob/master/docs/config-api.md#meta) to shim dependencies
of a third party lib, for install, when that lib misses dependencies declaration in its package.json file.

An example is the ngDraggable lib in this example (ngDraggable misses angular in its dependencies section in its package.json).
1. Use `jspm install ngdraggable=npm:ngdraggable` to download to jspm_packages
1. In config.js, add the following to map object:
```
    "ngDraggable": "npm:ngdraggable@0.1.10",
```
1. Add this to meta to make up for its missing angular dependency declaration
```
  meta: {
    "jspm_packages/npm/ngdraggable@0.1.10/ngDraggable.js": {
      "deps": [
        "angular"
      ]
    }
  },
```

# Lessions learned

1. Put jspm_packages, node_modules, package.json, karma.conf.js and index.html in the same top level directory.
This will save/avoid trick url resolution problems.


text:
import os
import platform

from datetime import datetime
from fabric import Connection
from fabric import task
from glob import glob
from invoke import run as local

# global connections
# (until I figure out how the context variable works...)
# TODO: look into adding host info to .ssh/config - that seems to be the official way to handle this

connect_kwargs = {}
if platform.system() == 'Windows':
    # this requires SSH key to be loaded into pageant
    connect_kwargs = {
        "key_filename": "c:/users/keith/.ssh/id_rsa",
    }

c = Connection(
    host='kdechant.com',
    user='ubuntu',
    connect_kwargs=connect_kwargs
)
server_python = '/var/www/vhosts/eamon/.venv/bin/python'
server_root = '/var/www/vhosts/eamon'

# utility functions

def _get_db_pw():
    raw = c.run("awk '/PASSWORD/ {{print $2}}' {}/eamon/local_settings.py".format(server_root), hide='out')
    return raw.stdout[1:-3]

def _get_local_db_pw():
    raw = local("awk '/PASSWORD/ {{print $2}}' {}/eamon/local_settings.py".format(os.getcwd()), hide='out')
    return raw.stdout[1:-3]

def _db_pull(tables=None):
    pw = _get_db_pw()
    tables = "".join(tables) if tables is not None else ""
    t = datetime.now()
    fn = 'eamon-{0.year}-{0.month:0>2}-{0.day:0>2}-{0.hour:0>2}-{0.minute:0>2}-{0.second:0>2}.sql'.format(t)
    print('exporting DB on server...')
    c.run('mysqldump eamon -u eamon -p{} {} | gzip > {}.gz'.format(pw, tables, fn))
    print('downloading DB...')
    c.get("{}.gz".format(fn))
    print('importing DB locally...')
    if platform.system() == 'Windows':
        local('7z.exe e ./{}.gz -y'.format(fn), hide='out')
    else:
        local('gunzip {}'.format(fn))

    # We can sniff out the local PW on *nix but Windows should just use an empty PW.
    if platform.system() == 'Windows':
        local_pw = ""
    else:
        local_pw = _get_local_db_pw()

    if local_pw != "":
        local('mysql -u root -p{} eamon -e "source {}"'.format(local_pw, fn))
    else:
        local('mysql -u root eamon -e "source {}"'.format(fn))

def _db_push(prefix="eamon", tables=None):
    pw = _get_db_pw()
    tables = " ".join(tables) if tables is not None else ""
    t = datetime.now()
    fn = '{0}-{1.year}-{1.month:0>2}-{1.day:0>2}-{1.hour:0>2}-{1.minute:0>2}-{1.second:0>2}.sql'.format(prefix, t)
    print('exporting DB locally...')
    local_pw = _get_local_db_pw()
    if local_pw != "":
        local('mysqldump eamon -u root -p{} -r {} {}'.format(local_pw, fn, tables))
    else:
        local('mysqldump eamon -u root -r {} {}'.format(fn, tables))
    if platform.system() == 'Windows':
        local('7z.exe a {0}.gz {0} -y'.format(fn), hide='out')
    else:
        local('gzip {}'.format(fn))
    print('uploading DB...')
    c.put("{}.gz".format(fn))
    _db_backup()
    print('importing DB on server...')
    c.run('gunzip {}.gz'.format(fn))
    c.run('mysql eamon -u eamon -p{} < {}'.format(pw, fn))
    print('cleaning up...')
    c.run('rm {}'.format(fn))

def _db_migrate():
    print('running DB migrations on server...')
    c.run('{} {}/manage.py migrate'.format(server_python, server_root))

def _db_backup():
    print('backing up DB on server...')
    pw = _get_db_pw()
    t = datetime.now()
    fn = 'eamon-{0.year}-{0.month:0>2}-{0.day:0>2}-{0.hour:0>2}-{0.minute:0>2}-{0.second:0>2}.sql'.format(t)
    c.run('mysqldump eamon -u eamon -p{} | gzip > {}/db/{}.gz'.format(pw, server_root, fn))

# tasks
@task
def disk_space(context):
    c.run('df -h')

@task
def dbpull(context):
    """download DB from remote to local"""
    _db_pull()

@task
def dbpull_player(context):
    """download DB from remote to local - player data only"""
    tables = ['adventure_activitylog', 'adventure_player', 'adventure_playerartifact', 'adventure_playerprofile',
              'player_rating', 'player_savedgame']
    _db_pull(tables)

@task
def dbpush_adventure(context):
    """push DB from local to remote - non-player adventure tables only"""
    tables = ['adventure_adventure', 'adventure_artifact', 'adventure_author', 'adventure_adventure_authors',
              'adventure_effect', 'adventure_hint', 'adventure_hintanswer', 'adventure_monster', 'adventure_room',
              'adventure_roomexit', 'taggit_tag', 'taggit_taggeditem']
    _db_push('eamon-adventure', tables)

@task
def dbpush_news(context):
    """push DB from local to remote - news tables only"""
    tables = ['news_article']
    _db_push('eamon-news', tables)

@task
def migrate(context):
    """runs db migrations remotely"""
    print('running DB migrations on server...')
    _db_migrate()

@task
def build_js(context):
    """builds js and css for production deploy"""
    print('-- building JS and CSS locally...')
    local('git stash save "pre-deployment"')
    local('cd client && npm run build')
    local('git stash pop --quiet')

@task
def deploy(context):
    """full deployment - python and js/css"""
    build_js(context)
    deploy_python(context)
    deploy_js(context)

@task
def deploy_python(context):
    _db_backup()
    print('-- pulling new code...')
    # with cd() is not in fabric 2 yet
    c.run('cd {} && git pull'.format(server_root))
    print('-- installing python packages...')
    c.run('cd {} && pipenv install'.format(server_root))
    _db_migrate()

@task
def deploy_js(context):
    build_js(context)
    print('-- uploading JS and CSS files...')
    remote_static = '{}/client/build/static/'.format(server_root)
    files = glob('client/build/static/*.js')
    for file in files:
        c.put(file, remote=remote_static)
    files = glob('client/build/static/**/*.js')
    for file in files:
        c.put(file, remote='{}/adventures/'.format(remote_static))
    c.put('client/build/static/css/style.css', remote='{}/css/'.format(remote_static))
    print('-- collecting static...')
    c.run('{} {}/manage.py collectstatic --no-input'.format(server_python, server_root))
    print('-- restarting server...')
    c.run('sudo apachectl graceful')
    print('-- Done!')

@task
def build_sqlite_db(context):
    """Creates the committable SQLite DB from the MySQL DB

    This requires both the MySQL ("default") and SQLite ("sqlite")
    DB connections to be configured in your local_settings.py file.
    """
    # print('-- Exporting data from the master DB...')
    # local("python -Xutf8 manage.py dumpdata --indent 2 --database default --exclude=contenttypes --exclude=auth --exclude=admin --exclude=sessions --output db/dumpdata.json")
    print('-- Running Migrations on SQLite DB...')
    local("python manage.py migrate --database sqlite")
    print('-- Importing data...')
    local("python -Xutf8 manage.py loaddata --database sqlite db/dumpdata.json")
    print('-- Creating distributable copy...')
    if platform.system() == 'Windows':
        local("del db\eamon.sqlite3.dist.old")
        local("move db\eamon.sqlite3.dist db\eamon.sqlite3.dist.old")
        local("copy db\eamon.sqlite3 db\eamon.sqlite3.dist")
    else:
        local("rm db/eamon.sqlite3.dist.old")
        local("mv db/eamon.sqlite3.dist db/eamon/sqlite3.dist.old")
        local("cp db/eamon.sqlite3 db/eamon.sqlite3.dist")
    print('-- Done!')


text:
struct wjhu_list
{
	struct wjhu_list* next;

	void* data;
};

struct wjhu_list* wjhu_list_create(void* data);
void wjhu_list_add(struct wjhu_list* list, void* data);
void* wjhu_list_find(struct wjhu_list* list, void* data);
void wjhu_list_destroy(struct wjhu_list* list);

struct wjhu_list* wjhu_list_create(void* data)
{
	struct wjhu_list* ret = malloc(sizeof(struct wjhu_list));
	ret->data = data;
	ret->next = NULL;

	return ret;
}

// Must be called on the head node if you want the whole list to be freed,
// Otherwise it will only be freed from the point passed.
// We know nothing about any prior nodes.
void wjhu_list_destroy(struct wjhu_list* list)
{
	if(list->next != NULL)
	{
		wjhu_list_destroy(list->next);
		free(list->next);
	}

	list->next = NULL;
}

// Can be passed any element in the list, will keep iterating until it finds
// the tail.
// Takes ownership of data!
void wjhu_list_add(struct wjhu_list* list, void* data)
{
	while(list->next != NULL)
		list = list->next;

	list->next = malloc(sizeof(struct wjhu_list));
	list->next->data = data;
}

// Pass the node of the list where the search should begin.
void* wjhu_list_find(struct wjhu_list* list, void* data)
{
	while(list->data != data)
	{
		if(list->next != NULL)
		{
			list = list->next;
		}
		else
		{
			return NULL;
		}
	}

	return list->data;
}

#endif


text:
.claro .dojoxTitleGroup .dijitTitlePaneContentOuter {
    border-bottom:none;
}
.claro .dojoxTitleGroup .dijitTitlePaneContentOuter .dijitTitlePaneContentOuter,
.claro .dojoxTitleGroup {
    border-bottom:1px solid #B5BCC7;
}
.soria .dojoxTitleGroup .dijitTitlePaneContentOuter {
    border-bottom:none;
}
.soria .dojoxTitleGroup .dijitTitlePaneContentOuter .dijitTitlePaneContentOuter,
.soria .dojoxTitleGroup {
    border-bottom:1px solid #BFBFBF;
}
.nihilo .dojoxTitleGroup .dijitTitlePaneContentOuter {
    border-bottom:none;
}
.nihilo .dojoxTitleGroup .dijitTitlePaneContentOuter .dijitTitlePaneContentOuter,
.nihilo .dojoxTitleGroup {
    border-bottom:1px solid #BFBFBF;
}