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

	window.KC3Translation = {
		/* EXECUTE
		Triggers translations into current page
		-----------------------------------------*/
		execute :function(){
			this.applyWords();
			this.applyHTML();
		},

		/* APPLY WORDS
		Change words inside visible DOM elements
		-----------------------------------------*/
		applyWords :function(){
			// Interchange element contents with translations
			$(".i18n").each(function(){
				$(this).html( KC3Meta.term( $(this).text() ) );
				$(this).css("visibility", "visible");
			});
			// Update title attribute with translations
			$(".i18n_title").each(function(){
				$(this).attr("title", KC3Meta.term( $(this).attr("title") ) );
			});
		},

		/* APPLY HTML
		Specialized Language HTML adjustments
		-----------------------------------------*/
		applyHTML :function(){
			// Specialized fonts
			var fontFamily = false;
			switch(ConfigManager.language){

				case "scn": fontFamily = '"HelveticaNeue-Light","Helvetica Neue Light","Helvetica Neue",Helvetica,"Nimbus Sans L",Arial,"Lucida Grande","Liberation Sans","Microsoft YaHei UI","Microsoft YaHei","Hiragino Sans GB","Wenquanyi Micro Hei","WenQuanYi Zen Hei","ST Heiti",SimHei,"WenQuanYi Zen Hei Sharp",sans-serif'; break;

				case "jp": fontFamily = '"Helvetica Neue", "Tahoma", Helvetica, Arial, "ヒラギノ角ゴ Pro W3", "Hiragino Kaku Gothic Pro", Osaka, "メイリオ", "Meiryo", "Yu Gothic UI Semibold", "ＭＳ Ｐゴシック", "MS PGothic", sans-serif'; break;

				default: break;
			}

			if(fontFamily){ $("body").css("font-family", fontFamily); }

			// Apply HTML language code
			$("html").attr("lang", ConfigManager.language);
		},

		/* GET JSON
		Used by KC3Meta.js to load json files
		-----------------------------------------*/
		getJSON :function(repo, filename, extendEnglish){
			if (filename === "quotes") {
				console.log("warning: using KC3Translation.getQuotes to get quotes");
				return this.getQuotes(repo);
			}

			// Check if desired to extend english files
			if(typeof extendEnglish=="undefined"){ extendEnglish=false; }

			var language = ConfigManager.language;
			// Japanese special case where ships and items sources are already in JP
			if(
				(["jp", "tcn"].indexOf(language) > -1)
				&& (filename==="ships" || filename==="items")
			){
				extendEnglish = false;
			}
			// make ships.json and items.json an option to be always in specified one
			if (!!ConfigManager.info_force_ship_lang
				&& (filename==="ships" || filename==="items")){
				extendEnglish = false;
				language = ConfigManager.info_force_ship_lang;
			}
			// make "stype.json" an option:
			if (filename === "stype" && ConfigManager.info_eng_stype){
				language = "en";
			}

			var translationBase = {}, enJSON;
			if(extendEnglish && language!="en"){
				// Load english file
				enJSON = JSON.parse($.ajax({
					url : repo+'lang/data/en/' + filename + '.json',
					async: false
				}).responseText);

				// Make is as the translation base
				translationBase = enJSON;
			}

			// if we can't fetch this file, the English
			// version will be used instead
			var translation;
			try {
				translation = JSON.parse($.ajax({
					url : repo+'lang/data/' +language+ '/' + filename + '.json',
					async: false
				}).responseText);
			} catch (e) {
				if (e instanceof SyntaxError && extendEnglish && language!="en"){
					console.warn(e.stack);
					translation = null;
				} else {
					throw e;
				}
			}
			return $.extend(true, translationBase, translation);
		},

		getQuotes: function(repo) {
			// we always use English version quotes as the base,
			// assuming all quotes are complete so there
			// is no need to extend the table by considering pre-remodel ship quotes.
			var	enJSON = {};
			var language = ConfigManager.language;
			try {
				enJSON = JSON.parse($.ajax({
					url : repo+'lang/data/en/quotes.json',
					async: false
				}).responseText);
			} catch(e) {
				if (e instanceof SyntaxError){
					console.warn(e.stack);
					translation = null;
				} else {
					throw e;
				}
			}

			// if it's already English the we are done.
			if (language === "en") return enJSON;

			// load language specific quotes.json
			var langJSON;
			try {
				langJSON = JSON.parse($.ajax({
					url : repo+'lang/data/' +language+ '/quotes.json',
					async: false
				}).responseText);
			} catch (e) {
				console.warn("failed to retrieve language specific quotes.");
				if (e instanceof SyntaxError){
					console.warn(e.stack);
					console.log("falling back to eng version");
					return enJSON;
				} else {
					throw e;
				}
			}

			// extend quotes by reusing ship's pre-remodels
			// 1st pass: extend langJSON by considering pre-models
            if (typeof RemodelDb !== "undefined" && typeof RemodelDb._db !== "undefined") {
			    $.each(RemodelDb._db.remodelGroups, function(orgShipIdStr,groupInfo) {
				    // a group of ship ids that consider as "same ship"
				    // sorted by remodels
				    var group = groupInfo.group;

				    var i,curShipId;
				    // accumulate quotes
				    var curQuotes = {};
                    var q;
				    for (i=0; i<group.length; ++i) {
					    curShipId = group[i];
					    // implicit casting index from num to str
					    q = langJSON[curShipId] || {};
					    // accumulate to curQuotes
					    curQuotes = $.extend(true, {}, curQuotes, q);
					    // note that curQuotes now refers to a different obj
					    // and we haven't done any modification on curQuotes
					    // so it's safe to be assigned to a table
					    langJSON[curShipId] = curQuotes;
				    }
			    });
            } else {
                console.warn("Translation: failed to load RemodelDb, " +
                             "please make sureit's been initialized properly");
            }

			// 2nd pass: extend langJSON using enJSON to fill in any missing parts
			langJSON = $.extend(true, {}, enJSON, langJSON);

			return langJSON;
		}

	};

})();
<commit_msg>impl descriptive key<commit_after>(function(){
	"use strict";

	window.KC3Translation = {
		/* EXECUTE
		Triggers translations into current page
		-----------------------------------------*/
		execute :function(){
			this.applyWords();
			this.applyHTML();
		},

		/* APPLY WORDS
		Change words inside visible DOM elements
		-----------------------------------------*/
		applyWords :function(){
			// Interchange element contents with translations
			$(".i18n").each(function(){
				$(this).html( KC3Meta.term( $(this).text() ) );
				$(this).css("visibility", "visible");
			});
			// Update title attribute with translations
			$(".i18n_title").each(function(){
				$(this).attr("title", KC3Meta.term( $(this).attr("title") ) );
			});
		},

		/* APPLY HTML
		Specialized Language HTML adjustments
		-----------------------------------------*/
		applyHTML :function(){
			// Specialized fonts
			var fontFamily = false;
			switch(ConfigManager.language){

				case "scn": fontFamily = '"HelveticaNeue-Light","Helvetica Neue Light","Helvetica Neue",Helvetica,"Nimbus Sans L",Arial,"Lucida Grande","Liberation Sans","Microsoft YaHei UI","Microsoft YaHei","Hiragino Sans GB","Wenquanyi Micro Hei","WenQuanYi Zen Hei","ST Heiti",SimHei,"WenQuanYi Zen Hei Sharp",sans-serif'; break;

				case "jp": fontFamily = '"Helvetica Neue", "Tahoma", Helvetica, Arial, "ヒラギノ角ゴ Pro W3", "Hiragino Kaku Gothic Pro", Osaka, "メイリオ", "Meiryo", "Yu Gothic UI Semibold", "ＭＳ Ｐゴシック", "MS PGothic", sans-serif'; break;

				default: break;
			}

			if(fontFamily){ $("body").css("font-family", fontFamily); }

			// Apply HTML language code
			$("html").attr("lang", ConfigManager.language);
		},

		/* GET JSON
		Used by KC3Meta.js to load json files
		-----------------------------------------*/
		getJSON :function(repo, filename, extendEnglish){
			if (filename === "quotes") {
				console.log("warning: using KC3Translation.getQuotes to get quotes");
				return this.getQuotes(repo);
			}

			// Check if desired to extend english files
			if(typeof extendEnglish=="undefined"){ extendEnglish=false; }

			var language = ConfigManager.language;
			// Japanese special case where ships and items sources are already in JP
			if(
				(["jp", "tcn"].indexOf(language) > -1)
				&& (filename==="ships" || filename==="items")
			){
				extendEnglish = false;
			}
			// make ships.json and items.json an option to be always in specified one
			if (!!ConfigManager.info_force_ship_lang
				&& (filename==="ships" || filename==="items")){
				extendEnglish = false;
				language = ConfigManager.info_force_ship_lang;
			}
			// make "stype.json" an option:
			if (filename === "stype" && ConfigManager.info_eng_stype){
				language = "en";
			}

			var translationBase = {}, enJSON;
			if(extendEnglish && language!="en"){
				// Load english file
				enJSON = JSON.parse($.ajax({
					url : repo+'lang/data/en/' + filename + '.json',
					async: false
				}).responseText);

				// Make is as the translation base
				translationBase = enJSON;
			}

			// if we can't fetch this file, the English
			// version will be used instead
			var translation;
			try {
				translation = JSON.parse($.ajax({
					url : repo+'lang/data/' +language+ '/' + filename + '.json',
					async: false
				}).responseText);
			} catch (e) {
				if (e instanceof SyntaxError && extendEnglish && language!="en"){
					console.warn(e.stack);
					translation = null;
				} else {
					throw e;
				}
			}
			return $.extend(true, translationBase, translation);
		},

		// insert quote id as key if descriptive key is used.
		transformQuotes: function(quotes) {
			function isIntStr(s) {
				return parseInt(s,10).toString() === s;
			}

			var descToId = {
				"Intro" : 1,
				"Library" : 25,
				"Poke(1)" : 2,
				"Poke(2)" : 3,
				"Poke(3)" : 4,
				"Married" : 28,
				"Wedding" : 24,
				"Ranking" : 8,
				"Join" : 13,
				"Equip(1)" : 9,
				"Equip(2)" : 10,
				"Equip(3)" : 26,
				"Supply" : 27,
				"Docking(1)" : 11,
				"Docking(2)" : 12,
				"Construction" : 5,
				"Return" : 7,
				"Sortie" : 14,
				"Battle" : 15,
				"Attack" : 16,
				"Yasen(1)" : 18,
				"Yasen(2)" : 17,
				"MVP" : 23,
				"Damaged(1)" : 19,
				"Damaged(2)" : 20,
				"Damaged(3)" : 21,
				"Sunk" : 22,
				"Idle" : 29,
				"Repair" : 6,

				"H0000":30, "H0100":31, "H0200":32, "H0300":33,
				"H0400":34, "H0500":35, "H0600":36, "H0700":37,
				"H0800":38, "H0900":39, "H1000":40, "H1100":41,
				"H1200":42, "H1300":43, "H1400":44, "H1500":45,
				"H1600":46, "H1700":47, "H1800":48, "H1900":49,
				"H2000":50, "H2100":51, "H2200":52, "H2300":53
			};
			$.each( quotes, function(k,v) {
				if (! isIntStr(k) )
					return;
				// transforming "v" object

				// get an immutable list of keys for further operation
				var subKeys = Object.keys(v);
				$.each(subKeys, function(i,subKey) {
					var subId = descToId[subKey];
					if (subId) {
						// force overwriting regardless of original content
						v[subId] = v[subKey];
					} else {
						if (! isIntStr(subKey) ) {
							// neither a descriptive key nor a normal number
							console.warn( "Unrecognized subtitle key: " + subKey
										  + " (masterId=" + k + ")");
						}
					}
				});

			});
			return quotes;
		},

		// get quotes without Descriptive Key Transformation
		// internal use only, please use "getQuotes"
		getQuotesWithoutDKT: function(repo) {
			// we always use English version quotes as the base,
			// assuming all quotes are complete so there
			// is no need to extend the table by considering pre-remodel ship quotes.
			var	enJSON = {};
			var language = ConfigManager.language;
			try {
				enJSON = JSON.parse($.ajax({
					url : repo+'lang/data/en/quotes.json',
					async: false
				}).responseText);
			} catch(e) {
				if (e instanceof SyntaxError){
					console.warn(e.stack);
					translation = null;
				} else {
					throw e;
				}
			}

			// if it's already English the we are done.
			if (language === "en") return enJSON;

			// load language specific quotes.json
			var langJSON;
			try {
				langJSON = JSON.parse($.ajax({
					url : repo+'lang/data/' +language+ '/quotes.json',
					async: false
				}).responseText);
			} catch (e) {
				console.warn("failed to retrieve language specific quotes.");
				if (e instanceof SyntaxError){
					console.warn(e.stack);
					console.log("falling back to eng version");
					return enJSON;
				} else {
					throw e;
				}
			}

			// extend quotes by reusing ship's pre-remodels
			// 1st pass: extend langJSON by considering pre-models
            if (typeof RemodelDb !== "undefined" && typeof RemodelDb._db !== "undefined") {
			    $.each(RemodelDb._db.remodelGroups, function(orgShipIdStr,groupInfo) {
				    // a group of ship ids that consider as "same ship"
				    // sorted by remodels
				    var group = groupInfo.group;

				    var i,curShipId;
				    // accumulate quotes
				    var curQuotes = {};
                    var q;
				    for (i=0; i<group.length; ++i) {
					    curShipId = group[i];
					    // implicit casting index from num to str
					    q = langJSON[curShipId] || {};
					    // accumulate to curQuotes
					    curQuotes = $.extend(true, {}, curQuotes, q);
					    // note that curQuotes now refers to a different obj
					    // and we haven't done any modification on curQuotes
					    // so it's safe to be assigned to a table
					    langJSON[curShipId] = curQuotes;
				    }
			    });
            } else {
                console.warn("Translation: failed to load RemodelDb, " +
                             "please make sureit's been initialized properly");
            }

			// 2nd pass: extend langJSON using enJSON to fill in any missing parts
			langJSON = $.extend(true, {}, enJSON, langJSON);

			return langJSON;
		},

		getQuotes: function(repo) {
			return this.transformQuotes(
				this.getQuotesWithoutDKT(repo));
		}

	};

})();
<|endoftext|>


<commit_before>var SubscriptionDefinition = function(exchange, topic, callback) {
    this.exchange = exchange;
    this.topic = topic;
    this.callback = callback;
    this.priority = DEFAULT_PRIORITY;
    this.constraints = [];
    this.maxCalls = DEFAULT_DISPOSEAFTER;
    this.onHandled = NO_OP;
    this.context = null;

    postal.publish(SYSTEM_EXCHANGE, "subscription.created",
        {
            event: "subscription.created",
            exchange: exchange,
            topic: topic
        });
};

SubscriptionDefinition.prototype = {
    unsubscribe: function() {
        postal.configuration.bus.unsubscribe(this);
        postal.publish(SYSTEM_EXCHANGE, "subscription.removed",
            {
                event: "subscription.removed",
                exchange: this.exchange,
                topic: this.topic
            });
    },

    defer: function() {
        var fn = this.callback;
        this.callback = function(data) {
            setTimeout(fn,0,data);
        };
        return this;
    },

    disposeAfter: function(maxCalls) {
        if(_.isNaN(maxCalls) || maxCalls <= 0) {
            throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero.";
        }

        var fn = this.onHandled;
        var dispose = _.after(maxCalls, _.bind(function() {
                this.unsubscribe(this);
            }, this));

        this.onHandled = function() {
            fn.apply(this.context, arguments);
            dispose();
        };
        return this;
    },

    ignoreDuplicates: function() {
        this.withConstraint(new DistinctPredicate());
        return this;
    },

    whenHandledThenExecute: function(callback) {
        if(! _.isFunction(callback)) {
            throw "Value provided to 'whenHandledThenExecute' must be a function";
        }
        this.onHandled = callback;
        return this;
    },

    withConstraint: function(predicate) {
        if(! _.isFunction(predicate)) {
            throw "Predicate constraint must be a function";
        }
        this.constraints.push(predicate);
        return this;
    },

    withConstraints: function(predicates) {
        var self = this;
        if(_.isArray(predicates)) {
            _.each(predicates, function(predicate) { self.withConstraint(predicate); } );
        }
        return self;
    },

    withContext: function(context) {
        this.context = context;
        return this;
    },

    withDebounce: function(milliseconds) {
        if(_.isNaN(milliseconds)) {
            throw "Milliseconds must be a number";
        }
        var fn = this.callback;
        this.callback = _.debounce(fn, milliseconds);
        return this;
    },

    withDelay: function(milliseconds) {
        if(_.isNaN(milliseconds)) {
            throw "Milliseconds must be a number";
        }
        var fn = this.callback;
        this.callback = function(data) {
            setTimeout(fn, milliseconds, data);
        };
        return this;
    },

    withPriority: function(priority) {
        if(_.isNaN(priority)) {
            throw "Priority must be a number";
        }
        this.priority = priority;
        return this;
    },

    withThrottle: function(milliseconds) {
        if(_.isNaN(milliseconds)) {
            throw "Milliseconds must be a number";
        }
        var fn = this.callback;
        this.callback = _.throttle(fn, milliseconds);
        return this;
    }
};
<commit_msg>temporarily deferring s subscription.created event message<commit_after>var SubscriptionDefinition = function(exchange, topic, callback) {
    this.exchange = exchange;
    this.topic = topic;
    this.callback = callback;
    this.priority = DEFAULT_PRIORITY;
    this.constraints = [];
    this.maxCalls = DEFAULT_DISPOSEAFTER;
    this.onHandled = NO_OP;
    this.context = null;

    _.defer(function() {
	    postal.publish(SYSTEM_EXCHANGE, "subscription.created",
		    {
			    event: "subscription.created",
			    exchange: exchange,
			    topic: topic
		    })
    });
};

SubscriptionDefinition.prototype = {
    unsubscribe: function() {
        postal.configuration.bus.unsubscribe(this);
        postal.publish(SYSTEM_EXCHANGE, "subscription.removed",
            {
                event: "subscription.removed",
                exchange: this.exchange,
                topic: this.topic
            });
    },

    defer: function() {
        var fn = this.callback;
        this.callback = function(data) {
            setTimeout(fn,0,data);
        };
        return this;
    },

    disposeAfter: function(maxCalls) {
        if(_.isNaN(maxCalls) || maxCalls <= 0) {
            throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero.";
        }

        var fn = this.onHandled;
        var dispose = _.after(maxCalls, _.bind(function() {
                this.unsubscribe(this);
            }, this));

        this.onHandled = function() {
            fn.apply(this.context, arguments);
            dispose();
        };
        return this;
    },

    ignoreDuplicates: function() {
        this.withConstraint(new DistinctPredicate());
        return this;
    },

    whenHandledThenExecute: function(callback) {
        if(! _.isFunction(callback)) {
            throw "Value provided to 'whenHandledThenExecute' must be a function";
        }
        this.onHandled = callback;
        return this;
    },

    withConstraint: function(predicate) {
        if(! _.isFunction(predicate)) {
            throw "Predicate constraint must be a function";
        }
        this.constraints.push(predicate);
        return this;
    },

    withConstraints: function(predicates) {
        var self = this;
        if(_.isArray(predicates)) {
            _.each(predicates, function(predicate) { self.withConstraint(predicate); } );
        }
        return self;
    },

    withContext: function(context) {
        this.context = context;
        return this;
    },

    withDebounce: function(milliseconds) {
        if(_.isNaN(milliseconds)) {
            throw "Milliseconds must be a number";
        }
        var fn = this.callback;
        this.callback = _.debounce(fn, milliseconds);
        return this;
    },

    withDelay: function(milliseconds) {
        if(_.isNaN(milliseconds)) {
            throw "Milliseconds must be a number";
        }
        var fn = this.callback;
        this.callback = function(data) {
            setTimeout(fn, milliseconds, data);
        };
        return this;
    },

    withPriority: function(priority) {
        if(_.isNaN(priority)) {
            throw "Priority must be a number";
        }
        this.priority = priority;
        return this;
    },

    withThrottle: function(milliseconds) {
        if(_.isNaN(milliseconds)) {
            throw "Milliseconds must be a number";
        }
        var fn = this.callback;
        this.callback = _.throttle(fn, milliseconds);
        return this;
    }
};
<|endoftext|>


<commit_before>export const API_URL = {
  JSON_SCHEMA: '/api/dev/docs/jsonschema',
  USER_TIMECARD: (yearMonth) => `/api/v1/timecards/${yearMonth}`,
}
export const ROUTES = {
  USER_TIMECARD: (yearMonth) => `/timecards/${yearMonth}`,
  API_SPEC: '/dev/docs/api',
  MOCK_SETTING: '/dev/mock/setting'
}

export const HTTP_METHOD = {
  GET: 'GET',
  POST: 'POST'
}<commit_msg>記述順序変更<commit_after>export const ROUTES = {
  USER_TIMECARD: (yearMonth) => `/timecards/${yearMonth}`,
  API_SPEC: '/dev/docs/api',
  MOCK_SETTING: '/dev/mock/setting'
}

export const API_URL = {
  JSON_SCHEMA: '/api/dev/docs/jsonschema',
  USER_TIMECARD: (yearMonth) => `/api/v1/timecards/${yearMonth}`,
}

export const HTTP_METHOD = {
  GET: 'GET',
  POST: 'POST'
}<|endoftext|>


<commit_before>
// a list of names we pick from when generating data
var firstnames = ['Sophia','Emma','Olivia','Isabella','Mia','Ava','Lily','Zoe','Emily','Chloe','Layla','Madison','Madelyn','Abigail','Aubrey','Charlotte','Amelia','Ella','Kaylee','Avery','Aaliyah','Hailey','Hannah','Addison','Riley','Harper','Aria','Arianna','Mackenzie','Lila','Evelyn','Adalyn','Grace','Brooklyn','Ellie','Anna','Kaitlyn','Isabelle','Sophie','Scarlett','Natalie','Leah','Sarah','Nora','Mila','Elizabeth','Lillian','Kylie','Audrey','Lucy','Maya'];
var lastnames = ['Smith','Jones','Williams','Taylor','Brown','Davies','Evans','Wilson','Thomas','Johnson'];

var images = ['niall','sean','alberto','statue','horse'];

// each call gets a unique id, nothing to do with the grid, just help make the sample
// data more realistic
var callIdSequence = 555;

var rowData = createRowData();

// method creates all the data, both the top level grid and the lower level grids
function createRowData() {
    var rowData = [];

    for (var i = 0; i < 20; i++) {
        var firstName = firstnames[Math.floor(Math.random()*firstnames.length)];
        var lastName = lastnames[Math.floor(Math.random()*lastnames.length)];

        var image = images[i % images.length];

        var totalDuration = 0;

        var callRecords = [];
        // call count is random number between 20 and 120
        var callCount = Math.floor(Math.random() * 100) + 20;
        for (var j = 0; j<callCount; j++) {
            // duration is random number between 20 and 120
            var callDuration = Math.floor(Math.random() * 100) + 20;
            var callRecord = {
                callId: callIdSequence++,
                duration: callDuration,
                switchCode: 'SW' + Math.floor(Math.random() * 10),
                // 50% chance of in vs out
                direction: (Math.random()>.5) ? 'In' : 'Out',
                // made up number
                number:  '(0' + Math.floor(Math.random() * 10) + ') ' + Math.floor(Math.random() * 100000000)
            };
            callRecords.push(callRecord);
            totalDuration += callDuration;
        }

        var record = {
            name: firstName + ' ' + lastName,
            account: i + 177000,
            totalCalls: callCount,
            image: image,
            // convert from seconds to minutes
            totalMinutes: totalDuration / 60,
            callRecords: callRecords
        };
        rowData.push(record);
    }

    return rowData;
}

// create 200 data records

var minuteCellFormatter = function(params) {
    return params.value.toLocaleString() + 'm';
};

var secondCellFormatter = function(params) {
    return params.value.toLocaleString() + 's';
};

var masterColumnDefs = [
    {headerName: 'Name', field: 'name',
        // left column is going to act as group column, with the expand / contract controls
        cellRenderer: 'group',
        // we don't want the child count - it would be one each time anyway as each parent
        // not has exactly one child node
        cellRendererParams: { suppressCount: true }
    },
    {headerName: 'Account', field: 'account'},
    {headerName: 'Calls', field: 'totalCalls'},
    {headerName: 'Minutes', field: 'totalMinutes', cellFormatter: minuteCellFormatter}
];

var detailColumnDefs = [
    {headerName: 'Call ID', field: 'callId', cellClass: 'call-record-cell'},
    {headerName: 'Direction', field: 'direction', cellClass: 'call-record-cell'},
    {headerName: 'Number', field: 'number', cellClass: 'call-record-cell'},
    {headerName: 'Duration', field: 'duration', cellClass: 'call-record-cell', cellFormatter: secondCellFormatter},
    {headerName: 'Switch', field: 'switchCode', cellClass: 'call-record-cell'}
];

function DetailPanelCellRenderer() {}

DetailPanelCellRenderer.prototype.init = function(params) {
    // trick to convert string of html into dom object
    var eTemp = document.createElement('div');
    eTemp.innerHTML = this.getTemplate(params);
    this.eGui = eTemp.firstElementChild;

    this.setupDetailGrid(params.data);
    this.consumeMouseWheelOnDetailGrid();
    this.addSeachFeature();
    this.addButtonListeners();
};

DetailPanelCellRenderer.prototype.setupDetailGrid = function(callRecords) {

    this.detailGridOptions = {
        enableSorting: true,
        enableFilter: true,
        enableColResize: true,
        rowData: callRecords,
        columnDefs: detailColumnDefs,
        onGridReady: function(params) {
            setTimeout( function() { params.api.sizeColumnsToFit(); }, 0);
        }
    };

    var eDetailGrid = this.eGui.querySelector('.full-width-grid');
    new agGrid.Grid(eDetailGrid, this.detailGridOptions);
};

DetailPanelCellRenderer.prototype.getTemplate = function(params) {

    var parentRecord = params.node.parent.data;

    var template =
        '
' +
        '
' +
        '

' +
        '
Name: '+parentRecord.name+'
' +
        '
Account: '+parentRecord.account+'
' +
        '
'+
        '

' +
        '
' +
        '       ' +
        '       <button></button>' +
        '       <button></button>' +
        '       <button></button>' +
        '       <input class="full-width-search" placeholder="Search..."/>' +
        '
'+
        '
';

    return template;
};

DetailPanelCellRenderer.prototype.getGui = function() {
    return this.eGui;
};

DetailPanelCellRenderer.prototype.destroy = function() {
    this.detailGridOptions.api.destroy();
};

DetailPanelCellRenderer.prototype.addSeachFeature = function() {
    var tfSearch = this.eGui.querySelector('.full-width-search');
    var gridApi = this.detailGridOptions.api;

    var searchListener = function() {
        var filterText = tfSearch.value;
        gridApi.setQuickFilter(filterText);
    };

    tfSearch.addEventListener('input', searchListener);
};

DetailPanelCellRenderer.prototype.addButtonListeners = function() {
    var eButtons = this.eGui.querySelectorAll('.full-width-grid-toolbar button');

    for (var i = 0;  i<eButtons.length; i++) {
        eButtons[i].addEventListener('click', function() {
            window.alert('Sample button pressed!!');
        });
    }
};

// if we don't do this, then the mouse wheel will be picked up by the main
// grid and scroll the main grid and not this component. this ensures that
// the wheel move is only picked up by the text field
DetailPanelCellRenderer.prototype.consumeMouseWheelOnDetailGrid = function() {
    var eDetailGrid = this.eGui.querySelector('.full-width-grid');

    var mouseWheelListener = function(event) {
        event.stopPropagation();
    };

    // event is 'mousewheel' for IE9, Chrome, Safari, Opera
    eDetailGrid.addEventListener('mousewheel', mouseWheelListener);
    // event is 'DOMMouseScroll' Firefox
    eDetailGrid.addEventListener('DOMMouseScroll', mouseWheelListener);
};

var masterGridOptions = {
    columnDefs: masterColumnDefs,
    rowData: rowData,
    enableSorting: true,
    enableColResize: true,
    enableFilter: true,
    isFullWidthCell: function(rowNode) {
        return rowNode.level === 1;
    },
    onGridReady: function(params) {
        params.api.sizeColumnsToFit();
    },
    // see ag-Grid docs cellRenderer for details on how to build cellRenderers
    fullWidthCellRenderer: DetailPanelCellRenderer,
    getRowHeight: function(params) {
        var rowIsDetailRow = params.node.level===1;
        // return 100 when detail row, otherwise return 25
        return rowIsDetailRow ? 200 : 25;
    },
    getNodeChildDetails: function(record) {
        if (record.callRecords) {
            return {
                group: true,
                // the key is used by the default group cellRenderer
                key: record.name,
                // provide ag-Grid with the children of this group
                children: [record.callRecords],
                // for demo, expand the third row by default
                expanded: record.account === 177005
            };
        } else {
            return null;
        }
    }
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
    var gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, masterGridOptions);
});
<commit_msg>removed filtering from master/detail example cos it didn't work<commit_after>
// a list of names we pick from when generating data
var firstnames = ['Sophia','Emma','Olivia','Isabella','Mia','Ava','Lily','Zoe','Emily','Chloe','Layla','Madison','Madelyn','Abigail','Aubrey','Charlotte','Amelia','Ella','Kaylee','Avery','Aaliyah','Hailey','Hannah','Addison','Riley','Harper','Aria','Arianna','Mackenzie','Lila','Evelyn','Adalyn','Grace','Brooklyn','Ellie','Anna','Kaitlyn','Isabelle','Sophie','Scarlett','Natalie','Leah','Sarah','Nora','Mila','Elizabeth','Lillian','Kylie','Audrey','Lucy','Maya'];
var lastnames = ['Smith','Jones','Williams','Taylor','Brown','Davies','Evans','Wilson','Thomas','Johnson'];

var images = ['niall','sean','alberto','statue','horse'];

// each call gets a unique id, nothing to do with the grid, just help make the sample
// data more realistic
var callIdSequence = 555;

var rowData = createRowData();

// method creates all the data, both the top level grid and the lower level grids
function createRowData() {
    var rowData = [];

    for (var i = 0; i < 20; i++) {
        var firstName = firstnames[Math.floor(Math.random()*firstnames.length)];
        var lastName = lastnames[Math.floor(Math.random()*lastnames.length)];

        var image = images[i % images.length];

        var totalDuration = 0;

        var callRecords = [];
        // call count is random number between 20 and 120
        var callCount = Math.floor(Math.random() * 100) + 20;
        for (var j = 0; j<callCount; j++) {
            // duration is random number between 20 and 120
            var callDuration = Math.floor(Math.random() * 100) + 20;
            var callRecord = {
                callId: callIdSequence++,
                duration: callDuration,
                switchCode: 'SW' + Math.floor(Math.random() * 10),
                // 50% chance of in vs out
                direction: (Math.random()>.5) ? 'In' : 'Out',
                // made up number
                number:  '(0' + Math.floor(Math.random() * 10) + ') ' + Math.floor(Math.random() * 100000000)
            };
            callRecords.push(callRecord);
            totalDuration += callDuration;
        }

        var record = {
            name: firstName + ' ' + lastName,
            account: i + 177000,
            totalCalls: callCount,
            image: image,
            // convert from seconds to minutes
            totalMinutes: totalDuration / 60,
            callRecords: callRecords
        };
        rowData.push(record);
    }

    return rowData;
}

// create 200 data records

var minuteCellFormatter = function(params) {
    return params.value.toLocaleString() + 'm';
};

var secondCellFormatter = function(params) {
    return params.value.toLocaleString() + 's';
};

var masterColumnDefs = [
    {headerName: 'Name', field: 'name',
        // left column is going to act as group column, with the expand / contract controls
        cellRenderer: 'group',
        // we don't want the child count - it would be one each time anyway as each parent
        // not has exactly one child node
        cellRendererParams: { suppressCount: true }
    },
    {headerName: 'Account', field: 'account'},
    {headerName: 'Calls', field: 'totalCalls'},
    {headerName: 'Minutes', field: 'totalMinutes', cellFormatter: minuteCellFormatter}
];

var detailColumnDefs = [
    {headerName: 'Call ID', field: 'callId', cellClass: 'call-record-cell'},
    {headerName: 'Direction', field: 'direction', cellClass: 'call-record-cell'},
    {headerName: 'Number', field: 'number', cellClass: 'call-record-cell'},
    {headerName: 'Duration', field: 'duration', cellClass: 'call-record-cell', cellFormatter: secondCellFormatter},
    {headerName: 'Switch', field: 'switchCode', cellClass: 'call-record-cell'}
];

function DetailPanelCellRenderer() {}

DetailPanelCellRenderer.prototype.init = function(params) {
    // trick to convert string of html into dom object
    var eTemp = document.createElement('div');
    eTemp.innerHTML = this.getTemplate(params);
    this.eGui = eTemp.firstElementChild;

    this.setupDetailGrid(params.data);
    this.consumeMouseWheelOnDetailGrid();
    this.addSeachFeature();
    this.addButtonListeners();
};

DetailPanelCellRenderer.prototype.setupDetailGrid = function(callRecords) {

    this.detailGridOptions = {
        enableSorting: true,
        enableFilter: true,
        enableColResize: true,
        rowData: callRecords,
        columnDefs: detailColumnDefs,
        onGridReady: function(params) {
            setTimeout( function() { params.api.sizeColumnsToFit(); }, 0);
        }
    };

    var eDetailGrid = this.eGui.querySelector('.full-width-grid');
    new agGrid.Grid(eDetailGrid, this.detailGridOptions);
};

DetailPanelCellRenderer.prototype.getTemplate = function(params) {

    var parentRecord = params.node.parent.data;

    var template =
        '
' +
        '
' +
        '

' +
        '
Name: '+parentRecord.name+'
' +
        '
Account: '+parentRecord.account+'
' +
        '
'+
        '

' +
        '
' +
        '       ' +
        '       <button></button>' +
        '       <button></button>' +
        '       <button></button>' +
        '       <input class="full-width-search" placeholder="Search..."/>' +
        '
'+
        '
';

    return template;
};

DetailPanelCellRenderer.prototype.getGui = function() {
    return this.eGui;
};

DetailPanelCellRenderer.prototype.destroy = function() {
    this.detailGridOptions.api.destroy();
};

DetailPanelCellRenderer.prototype.addSeachFeature = function() {
    var tfSearch = this.eGui.querySelector('.full-width-search');
    var gridApi = this.detailGridOptions.api;

    var searchListener = function() {
        var filterText = tfSearch.value;
        gridApi.setQuickFilter(filterText);
    };

    tfSearch.addEventListener('input', searchListener);
};

DetailPanelCellRenderer.prototype.addButtonListeners = function() {
    var eButtons = this.eGui.querySelectorAll('.full-width-grid-toolbar button');

    for (var i = 0;  i<eButtons.length; i++) {
        eButtons[i].addEventListener('click', function() {
            window.alert('Sample button pressed!!');
        });
    }
};

// if we don't do this, then the mouse wheel will be picked up by the main
// grid and scroll the main grid and not this component. this ensures that
// the wheel move is only picked up by the text field
DetailPanelCellRenderer.prototype.consumeMouseWheelOnDetailGrid = function() {
    var eDetailGrid = this.eGui.querySelector('.full-width-grid');

    var mouseWheelListener = function(event) {
        event.stopPropagation();
    };

    // event is 'mousewheel' for IE9, Chrome, Safari, Opera
    eDetailGrid.addEventListener('mousewheel', mouseWheelListener);
    // event is 'DOMMouseScroll' Firefox
    eDetailGrid.addEventListener('DOMMouseScroll', mouseWheelListener);
};

var masterGridOptions = {
    columnDefs: masterColumnDefs,
    rowData: rowData,
    enableSorting: true,
    enableColResize: true,
    // we cannot filter on the groups, as filters work on the child nodes, and in this example
    // the child nodes are not aggregations of the parent.
    suppressMenuFilterPanel: true,
    isFullWidthCell: function(rowNode) {
        return rowNode.level === 1;
    },
    onGridReady: function(params) {
        params.api.sizeColumnsToFit();
    },
    // see ag-Grid docs cellRenderer for details on how to build cellRenderers
    fullWidthCellRenderer: DetailPanelCellRenderer,
    getRowHeight: function(params) {
        var rowIsDetailRow = params.node.level===1;
        // return 100 when detail row, otherwise return 25
        return rowIsDetailRow ? 200 : 25;
    },
    getNodeChildDetails: function(record) {
        if (record.callRecords) {
            return {
                group: true,
                // the key is used by the default group cellRenderer
                key: record.name,
                // provide ag-Grid with the children of this group
                children: [record.callRecords],
                // for demo, expand the third row by default
                expanded: record.account === 177005
            };
        } else {
            return null;
        }
    }
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
    var gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, masterGridOptions);
});
<|endoftext|>


<commit_before>var ViewPopupUI = (function() {
    var _container = null;
    var _diff_end_start_time = 300; // we show point markers if end time start time difference is <= than this (5 minutes default)
    return {
        _init: function () {
            _container = null;
        },
        container: function (refresh) {
            if (refresh) {
                if (this._container) {
                    this._container.remove();
                }
                this._container = null;
            }
            if (!this._container) {
                var that = this;
                var con = $('
x

');
                con.hide();
                var _on_close = function () {
                    that.cleanup(true);
                };
                con.find('a.close').on('click', function () { _on_close(); } );
                $(document).on('keydown', function(e) {
                     if (e.which === 27) _on_close();
                });
                this._container = con;
            }
            return this._container;
        },
        cleanup: function () {
            this.forget_streams();
            this.clear_timer();
            this.close_container();
            this._init();
        },
        forget_streams: function() {
            while(window.stream_ids && window.stream_ids.length > 0) {
                var id = window.stream_ids.pop();
                if(id && id.length > 0) {
                    BinarySocket.send({"forget": id});
                }
            }
        },
        clear_timer: function() {
            if(window.ViewPopupTimerInterval) {
                clearInterval(window.ViewPopupTimerInterval);
                window.ViewPopupTimerInterval = undefined;
            }
        },
        close_container: function () {
            if (live_chart && typeof live_chart !== "undefined") {
                live_chart.close_chart();
            }
            if (this._container) {
                this._container.hide().remove();
                $('.popup_page_overlay').hide().remove();
                this._container = null;
            }
        },
        server_data: function () {
            var data = {};
            var field = $('#sell_extra_info_data');
            if (field) {
                data['barrier']             = field.attr('barrier');
                data['barrier2']            = field.attr('barrier2');
                data['is_immediate']        = field.attr('is_immediate');
                data['is_negative']         = field.attr('is_negative');
                data['is_forward_starting'] = field.attr('is_forward_starting');
                data['trade_feed_delay']    = field.attr('trade_feed_delay');
                data['currency']            = field.attr('currency');
                data['purchase_price']      = field.attr('purchase_price');
                data['shortcode']           = field.attr('shortcode');
                data['payout']              = field.attr('payout');
                data['contract_id']         = field.attr('contract_id');
            }
            return data;
        },
        disable_button: function (button) {
            button.attr('disabled', 'disabled');
            button.fadeTo(0, 0.5);
        },
        enable_button: function (button) {
            button.removeAttr('disabled');
            button.fadeTo(0, 1);
        },
        show_inpage_popup: function (data, containerClass, dragHandle) {
            var that = this;
            var con = this.container(true);
            if(containerClass) {
                con.addClass(containerClass);
            }
            if (data) {
                $('.inpage_popup_content', con).html(data);
            }
            var body = $(document.body);
            con.css('position', 'fixed').css('z-index', get_highest_zindex() + 100);
            body.append(con);
            con.show();
            $(document.body).append($('
', {class: 'popup_page_overlay'}));
            $('.popup_page_overlay').click(function(){that.cleanup();});
            con.draggable({
                stop: function() {
                    that.reposition_confirmation_ondrag();
                },
                handle: dragHandle,
                scroll: false,
            });
            $(dragHandle).disableSelection();
            this.reposition_confirmation();
            return con;
        },
        reposition_confirmation_ondrag: function () {
            var con    = this.container();
            var offset = con.offset();
            var win_   = $(window);
            // top
            if(offset.top < win_.scrollTop()) {con.offset({top: win_.scrollTop()});}
            // left
            if(offset.left < 0) {con.offset({left: 0});}
            // right
            if(offset.left > win_.width() - con.width()) {con.offset({left: win_.width() - con.width()});}
        },
        reposition_confirmation: function (x, y) {
            var con = this.container();
            var win_ = $(window);
            var x_min = 50;
            var y_min = 500;
            if(win_.width() < 767) { //To be responsive, on mobiles and phablets we show popup as full screen.
                x_min = 0;
                y_min = 0;
            }
            if (x === undefined) {
                x = Math.max(Math.floor((win_.width() - win_.scrollLeft() - con.width()) / 2), x_min) + win_.scrollLeft();
            }
            if (y === undefined) {
                y = Math.min(Math.floor((win_.height() - con.height()) / 2), y_min) + win_.scrollTop();
                if(y < win_.scrollTop()) {y = win_.scrollTop();}
            }
            con.offset({left: x, top: y});
        },
        show_chart: function (con, symbol) {
            var that = this;
            var server_data = that.server_data();
            var liveChartConfig = new LiveChartConfig({ renderTo: 'analysis_live_chart', symbol: symbol, with_trades: 0, shift: 0});
            var time_obj = that.get_time_interval();
            if(time_obj['is_live'] && time_obj['is_live'] === 1) {
                 liveChartConfig.update( {
                     live: '10min'
                 });
            } else {
                var from_date, to_date;
                if (server_data.is_forward_starting > 0) {
                    if(server_data.trade_feed_delay > 0) {
                        from_date = that.get_date_from_seconds(time_obj['from_time'] - parseInt(server_data.trade_feed_delay));
                        to_date = that.get_date_from_seconds(time_obj['to_time'] + parseInt(server_data.trade_feed_delay));
                    }
                } else {
                    from_date = that.get_date_from_seconds(time_obj['from_time'] - 5);
                    to_date = that.get_date_from_seconds(time_obj['to_time']);
                }

                var display_marker = false;
                if(time_obj['to_time'] - time_obj['from_time'] <= _diff_end_start_time) {
                    display_marker = true;
                }

                if(time_obj['force_tick']) {
                    liveChartConfig.update({
                        force_tick: true,
                    });
                }

                liveChartConfig.update({
                    interval: {
                        from: from_date,
                        to: to_date
                    },
                    with_markers: display_marker,
                });
            }
            configure_livechart();
            updateLiveChart(liveChartConfig);
            var barrier,
                purchase_time = $('#trade_details_purchase_date').attr('epoch_time');
            if (!purchase_time) { // dont add barrier if its forward starting
                if(server_data.barrier && server_data.barrier2) {
                    if (liveChartConfig.has_indicator('high')) {
                        live_chart.remove_indicator('high');
                    }
                    barrier = new LiveChartIndicator.Barrier({ name: "high", value: server_data.barrier, color: 'green', label: text.localize('High Barrier')});
                    live_chart.add_indicator(barrier);

                    if (liveChartConfig.has_indicator('low')) {
                        live_chart.remove_indicator('low');
                    }
                    barrier = new LiveChartIndicator.Barrier({ name: "low", value: server_data.barrier2, color: 'red', label: text.localize('Low Barrier')});
                    live_chart.add_indicator(barrier);

                } else {
                    if (liveChartConfig.has_indicator('barrier')) {
                        live_chart.remove_indicator('barrier');
                    }
                    barrier = new LiveChartIndicator.Barrier({ name: "barrier", value: server_data.barrier, color: 'green', label: text.localize('Barrier')});
                    live_chart.add_indicator(barrier);
                }
            }
            that.add_time_indicators(liveChartConfig);
            that.reposition_confirmation();
        },
        get_date_from_seconds: function(seconds) {
            var date = new Date(seconds*1000);
            return date;
        },
        get_epoch: function(elementID) {
            return $('#' + elementID).attr('epoch_time');
        },
        get_time_interval: function() {
            var time_obj = {};
            var start_time    = this.get_epoch('trade_details_start_date');
            var purchase_time = this.get_epoch('trade_details_purchase_date');
            var now_time      = this.get_epoch('trade_details_now_date');
            var end_time      = this.get_epoch('trade_details_end_date');
            if(purchase_time) { // forward starting
                time_obj['from_time'] = parseInt(purchase_time);
                time_obj['to_time'] = parseInt(start_time);
            } else if(start_time && now_time) {
                if (now_time > start_time) {
                    if (((parseInt(end_time) - parseInt(start_time)) > 3600) && ((parseInt(now_time) - parseInt(start_time)) < 3600)) {
                        // check if end date is more than 1 hours and now time - start time is less than 1 hours
                        // in this case we switch back to tick chart rather than ohlc
                        time_obj['from_time'] = parseInt(start_time);
                        time_obj['to_time'] = parseInt(start_time) + 3595;
                    } else if ((parseInt(end_time) - parseInt(start_time)) === 3600) {
                        time_obj['from_time'] = parseInt(start_time);
                        time_obj['to_time'] = parseInt(end_time);
                        time_obj['force_tick'] = 1;
                    } else {
                        time_obj['from_time'] = parseInt(start_time);
                        time_obj['to_time'] = parseInt(end_time);
                    }
                }
            } else if (!now_time && start_time && end_time) { // bet has expired
                time_obj['from_time'] = parseInt(start_time);
                time_obj['to_time'] = parseInt(end_time);
            } else {
                time_obj['is_live'] = 1;
            }
            return time_obj;
        },
        add_time_indicators: function(liveChartConfig) {
            var that = this,
                indicator;
            var start_time      = that.get_epoch('trade_details_start_date');
            var purchase_time   = that.get_epoch('trade_details_purchase_date');
            var sold_time       = that.get_epoch('trade_details_sold_date');
            var end_time        = that.get_epoch('trade_details_end_date');
            var entry_spot_time = that.get_epoch('trade_details_entry_spot_time');
            if(purchase_time) {
                if (liveChartConfig.has_indicator('purchase_time')) {
                    live_chart.remove_indicator('purchase_time');
                }
                indicator = new LiveChartIndicator.Barrier({ name: "purchase_time", label: 'Purchase Time', value: that.get_date_from_seconds(parseInt(purchase_time)), color: '#e98024', axis: 'x'});
                live_chart.add_indicator(indicator);
            }

            if(start_time) {
                if (liveChartConfig.has_indicator('start_time')) {
                    live_chart.remove_indicator('start_time');
                }
                indicator = new LiveChartIndicator.Barrier({ name: "start_time", label: 'Start Time', value: that.get_date_from_seconds(parseInt(start_time)), color: '#e98024', axis: 'x'});
                live_chart.add_indicator(indicator);
            }

            if(entry_spot_time && entry_spot_time != start_time) {
                if (liveChartConfig.has_indicator('entry_spot_time')) {
                    live_chart.remove_indicator('entry_spot_time');
                }

                if (start_time && entry_spot_time < start_time) {
                    indicator = new LiveChartIndicator.Barrier({ name: "entry_spot_time", label: 'Entry Spot', value: that.get_date_from_seconds(parseInt(entry_spot_time)), color: '#e98024', axis: 'x'});
                } else {
                    indicator = new LiveChartIndicator.Barrier({ name: "entry_spot_time", label: 'Entry Spot', value: that.get_date_from_seconds(parseInt(entry_spot_time)), color: '#e98024', axis: 'x', nomargin: true});
                }
                live_chart.add_indicator(indicator);
            }

            if(end_time) {
                if (liveChartConfig.has_indicator('end_time')) {
                    live_chart.remove_indicator('end_time');
                }

                indicator = new LiveChartIndicator.Barrier({ name: "end_time", label: 'End Time', value: that.get_date_from_seconds(parseInt(end_time)), color: '#e98024', axis: 'x'});
                live_chart.add_indicator(indicator);
            }
            if(sold_time) {
                if (liveChartConfig.has_indicator('sold_time')) {
                    live_chart.remove_indicator('sold_time');
                }

                indicator = new LiveChartIndicator.Barrier({ name: "sold_time", label: 'Sell Time', value: that.get_date_from_seconds(parseInt(sold_time)), color: '#e98024', axis: 'x'});
                live_chart.add_indicator(indicator);
            }
        },
    };
}());
<commit_msg>Remove livecharts codes from view popup<commit_after>var ViewPopupUI = (function() {
    var _container = null;
    return {
        _init: function () {
            _container = null;
        },
        container: function (refresh) {
            if (refresh) {
                if (this._container) {
                    this._container.remove();
                }
                this._container = null;
            }
            if (!this._container) {
                var that = this;
                var con = $('
x

');
                con.hide();
                var _on_close = function () {
                    that.cleanup(true);
                };
                con.find('a.close').on('click', function () { _on_close(); } );
                $(document).on('keydown', function(e) {
                     if (e.which === 27) _on_close();
                });
                this._container = con;
            }
            return this._container;
        },
        cleanup: function () {
            this.forget_streams();
            this.clear_timer();
            this.close_container();
            this._init();
        },
        forget_streams: function() {
            while(window.stream_ids && window.stream_ids.length > 0) {
                var id = window.stream_ids.pop();
                if(id && id.length > 0) {
                    BinarySocket.send({"forget": id});
                }
            }
        },
        clear_timer: function() {
            if(window.ViewPopupTimerInterval) {
                clearInterval(window.ViewPopupTimerInterval);
                window.ViewPopupTimerInterval = undefined;
            }
        },
        close_container: function () {
            if (this._container) {
                this._container.hide().remove();
                $('.popup_page_overlay').hide().remove();
                this._container = null;
            }
        },
        disable_button: function (button) {
            button.attr('disabled', 'disabled');
            button.fadeTo(0, 0.5);
        },
        enable_button: function (button) {
            button.removeAttr('disabled');
            button.fadeTo(0, 1);
        },
        show_inpage_popup: function (data, containerClass, dragHandle) {
            var that = this;
            var con = this.container(true);
            if(containerClass) {
                con.addClass(containerClass);
            }
            if (data) {
                $('.inpage_popup_content', con).html(data);
            }
            var body = $(document.body);
            con.css('position', 'fixed').css('z-index', get_highest_zindex() + 100);
            body.append(con);
            con.show();
            $(document.body).append($('
', {class: 'popup_page_overlay'}));
            $('.popup_page_overlay').click(function(){that.cleanup();});
            con.draggable({
                stop: function() {
                    that.reposition_confirmation_ondrag();
                },
                handle: dragHandle,
                scroll: false,
            });
            $(dragHandle).disableSelection();
            this.reposition_confirmation();
            return con;
        },
        reposition_confirmation_ondrag: function () {
            var con    = this.container();
            var offset = con.offset();
            var win_   = $(window);
            // top
            if(offset.top < win_.scrollTop()) {con.offset({top: win_.scrollTop()});}
            // left
            if(offset.left < 0) {con.offset({left: 0});}
            // right
            if(offset.left > win_.width() - con.width()) {con.offset({left: win_.width() - con.width()});}
        },
        reposition_confirmation: function (x, y) {
            var con = this.container();
            var win_ = $(window);
            var x_min = 50;
            var y_min = 500;
            if(win_.width() < 767) { //To be responsive, on mobiles and phablets we show popup as full screen.
                x_min = 0;
                y_min = 0;
            }
            if (x === undefined) {
                x = Math.max(Math.floor((win_.width() - win_.scrollLeft() - con.width()) / 2), x_min) + win_.scrollLeft();
            }
            if (y === undefined) {
                y = Math.min(Math.floor((win_.height() - con.height()) / 2), y_min) + win_.scrollTop();
                if(y < win_.scrollTop()) {y = win_.scrollTop();}
            }
            con.offset({left: x, top: y});
        },
    };
}());
<|endoftext|>


<commit_before>var traceur = Npm.require('traceur');
var os = Npm.require('os');

Plugin.registerSourceHandler("next.js", function (compileStep) {
  var oldPath = compileStep.inputPath;
  var newPath = oldPath.replace(/\.next\.js$/, '.now.js');

  var options = {
    filename: oldPath,
    sourceMap: true
  };
  var content = compileStep.read().toString('utf8');
  var output = traceur.compile(content, options);

  if (output.errors.length) {
    throw new Error(output.errors.join(os.EOL));
  }

  compileStep.addJavaScript({
    sourcePath: oldPath,
    path: newPath,
    data: output.js,
    sourceMap: output.sourceMap
  });
});
<commit_msg>Use preferred error handling from Traceur docs<commit_after>var traceur = Npm.require('traceur');

Plugin.registerSourceHandler("next.js", function (compileStep) {
  var oldPath = compileStep.inputPath;
  var newPath = oldPath.replace(/\.next\.js$/, '.now.js');

  var options = {
    filename: oldPath,
    sourceMap: true
  };
  var content = compileStep.read().toString('utf8');
  var output = traceur.compile(content, options);

  if (output.error) {
    throw new Error(output.error);
  }

  compileStep.addJavaScript({
    sourcePath: oldPath,
    path: newPath,
    data: output.js,
    sourceMap: output.sourceMap
  });
});
<|endoftext|>


<commit_before>;!function(mu){
	var config = {
		name:'check',
		files:['/assets/vendor/iCheck/skins/purple.css','/assets/vendor/iCheck/icheck.min.js']
	}

	mu.iCheck = function(callback){
		mu.queue(callback,config);
	}

	function plugin(){
		var element = this.element;

		//初始化icheck,设置状态 check||uncheck||toggle||disable||enable||indeterminate||determinate||update||destroy
		this.check = function(state,fn,fn2){
			if(typeof(state) == 'string' && state == 'value'){
				var glue = typeof(fn) == 'string'? fn : ',';
				var value = '';
				element.each(function(index, el) {
					if($(this).prop('checked'))
					value += (value != ''?',':'') + $(this).val();
				});
				return value;

			}
			mu.iCheck(function(){
				if(typeof(state) == 'string'){
					if(state == 'bind'){
						$(fn).on('ifChanged',function(){
							element.prop('checked',$(fn).prop('checked'));
							element.iCheck('update');
						})
					}else{
						if(typeof(fn) == 'string'){
							var values = fn.split(',');
							var filters = '';
							for (var i = 0; i < values.length; i++) {
								filters += (filters == ''?'':',') + '[value='+values[i]+']';
							};

							element.filter(filters).iCheck(state,fn2);
						}else{
							element.iCheck(state,fn);
						}
					}
				}else{
					element.iCheck({checkboxClass: 'icheckbox_square-purple',radioClass: 'iradio_square-purple'});
				}
			})
		};
	}

	mu.plugin(config.name,plugin);
}(mu)<commit_msg>icheck插件<commit_after>//icheck插件
;!function(mu){
	var config = {
		name:'check',
		files:['/assets/vendor/iCheck/skins/purple.css','/assets/vendor/iCheck/icheck.min.js']
	}

	mu.iCheck = function(callback){
		mu.queue(callback,config);
	}

	function plugin(){
		var element = this.element;

		//初始化icheck,设置状态 check||uncheck||toggle||disable||enable||indeterminate||determinate||update||destroy
		this.check = function(state,fn,fn2){
			if(typeof(state) == 'string' && state == 'value'){
				var glue = typeof(fn) == 'string'? fn : ',';
				var value = '';
				element.each(function(index, el) {
					if($(this).prop('checked'))
					value += (value != ''?',':'') + $(this).val();
				});
				return value;

			}
			mu.iCheck(function(){
				if(typeof(state) == 'string'){
					if(state == 'bind'){
						$(fn).on('ifChanged',function(){
							element.prop('checked',$(fn).prop('checked'));
							element.iCheck('update');
						})
					}else{
						if(typeof(fn) == 'string'){
							var values = fn.split(',');
							var filters = '';
							for (var i = 0; i < values.length; i++) {
								filters += (filters == ''?'':',') + '[value='+values[i]+']';
							};

							element.filter(filters).iCheck(state,fn2);
						}else{
							element.iCheck(state,fn);
						}
					}
				}else{
					element.iCheck({checkboxClass: 'icheckbox_square-purple',radioClass: 'iradio_square-purple'});
				}
			})
		};
	}

	mu.plugin(config.name,plugin);
}(mu)<|endoftext|>


<commit_before>const { api, _, Action } = require("../../")
const Remote = require("icebreaker-rpc/lib/remote.js")
const utils = require("icebreaker-network/lib/util.js")
const flat = require("flat")
const Util = require('muxrpc/util')
const rr = require('rr')
const Defer = require('pull-defer')
const distance = require('k-bucket').distance
const unset = require('unset-value');

module.exports = () => {

  let spec = {}

  api.actions.lb = {}
  api.lb = api.actions.lb
  let lb = api.lb

  const robin = {}

  api.actions.call = {

    promise: Action({
      type: "promise",
      input: ["string", "string", "array"],
      desc: "This run a promise action on peerID",
      run: async function (peerID, path, args) {
        for (let k in api.connections) {
          let c = api.connections[k]
          if (c.peerID === peerID && c.peer) {
            const f = flat.flatten(c.peer)
            if (!f[path]) throw new Error("Action " + path + " not found on " + peerID)
            if (f[path].type !== "promise") throw new Error("Action " + path + " type is not a promise on " + peerID)
            return await f[path](...args)
          }

        }
        throw new Error("No Peer with id" + peerID + " found on " + api.id)
      }
    }),
    source: Action({
      type: "source",
      input: ["string", "string", "array"],
      desc: "This run a source stream on peerID",
      run: (peerID, path, args) => {
        for (let k in api.connections) {
          let c = api.connections[k]
          if (c.peerID === peerID && c.peer) {
            const f = flat.flatten(c.peer)
            if (!f[path]) return _.error(new Error("Action " + path + " not found on " + peerID))
            if (f[path].type !== "source") return _.error(new Error("Action " + path + " type is not a source on " + peerID))
            return f[path](...args)
          }
        }
        return _.error(new Error("No Peer with id" + peerID + " found on " + api.id))
      }
    }),
    duplex: Action({
      type: "source",
      input: ["string", "string", "array"],
      desc: "This run a duplex stream on peerID",
      run: (peerID, path, args) => {
        const error = (err) => {
          return {
            source: _.error(err),
            sink: (read) => {
              read(err || true, (_err) => { })
            }
          }
        }

        for (let k in api.connections) {
          let c = api.connections[k]
          if (c.peerID === peerID && c.peer) {
            const f = flat.flatten(c.peer)
            if (!f[path]) return error(new Error("Action " + path + " not found on " + peerID))
            if (f[path].type !== "source") return error(new Error("Action " + path + " type is not a source on " + peerID))
            return f[path](...args)
          }
        }
        return error(new Error("No Peer with id" + peerID + " found on " + api.id))
      }
    }),
    sink: Action({
      type: "sink",
      input: ["string", "string", "array"],
      desc: "This run a sink stream on peerID",
      run: (peerID, path, args, cb) => {
        args.push(cb)

        const error = (err) => {
          return (read) => {
            read(err || true, (_err) => { cb(err || _err) })
          }
        }

        for (let k in api.connections) {
          let c = api.connections[k]
          if (c.peerID === peerID && c.peer) {
            const f = flat.flatten(c.peer)
            if (!f[path]) return error(new Error("Action " + path + " not found on " + peerID))
            if (f[path].type !== "sink") return error(new Error("Action " + path + " type is not a sink on " + peerID))
            return f[path](...args)
          }
        }

        return error(new Error("No Peer with id" + peerID + " found on " + api.id))
      }
    })

  }

  api.actions.call.async= api.actions.call.sync = Action({
    type: "async",
    input: ["string", "string", "array"],
    desc: "This run a async or sync action on peerID",
    run: (peerID, path, args, cb) => {
      for (let k in api.connections) {
        let c = api.connections[k]
        if (c.peerID === peerID && c.peer) {
          const f = flat.flatten(c.peer)
          if (!f[path]) return cb(new Error("Action " + path + " not found on " + peerID))
          if (f[path].type !== "sync" && f[path].type !== "async") return cb(new Error("Action " + path + " type is not sync or async on " + peerID))
          return f[path](...args)
        }
      }

      return cb(new Error("No Peer with id" + peerID + " found on " + api.id))
    }
  })

  function error(type, error, cb, defer) {
    if (type === "promise") {
      if (defer) return defer.reject(error)

      return new Promise((resolve, reject) => {
        reject(error)
      });
    }

    if (!cb) cb = _.isFunction(cb) ? cb : (err) => {
      if (type == "duplex") return
      if (err) throw new Error(err || 'callback not provided')
    }
    if (defer) defer.resolve(Util.errorAsStreamOrCb(type, error, cb))

    return Util.errorAsStreamOrCb(type, error, cb)
  }

  function remoteCall(type, path, args) {

    const cb = _.isFunction(args[args.length - 1]) ? args[args.length - 1] : null
    if (cb) args.pop()

    try {
      if (!spec[path]) return error(type, new Error("function " + path + " unarivable"), cb)
      const addrs = spec[path]
      const keys = Object.keys(addrs)
      if (keys.length === 0) return error(type, new Error("No address found for action " + path), cb)
      keys._rr  = robin[path]=robin[path] || 0
      const key = rr(keys)
      robin[path] = keys._rr++
      const address = Object.keys(spec[path][key])
      if (address.length === 0) return error(type, new Error("No address found for action " + path), cb)
      const connect = (_cb, resolve, reject) => {
        let defer
        if (type == "source" || type == "sink" || type == "duplex") defer = Defer[type]()
        if (type == "promise") defer = { reject: reject, resolve: resolve }
        api.connect(address, (err, e) => {
          if (err) return error(type, err, cb, defer)
          _cb(e, cb, defer)
        })
        return defer
      }

      if (!address[0].includes("//" + key + "@")) {

        const subCall = (resolve, reject) => {
          return connect((e, cb, defer) => {
            try {
              if (!(e.peer.call && e.peer.call[type]))
                return error(type, new Error("Type " + type + " not supported on " + e.peerID), cb, defer)
              if (defer) {
                if (type == "sink")
                  return defer.resolve(e.peer.call[type](key, path, args, cb))

                return defer.resolve(e.peer.call[type](key, path, args))
              }

              return e.peer.call[type](key, path, args, cb)
            }
            catch (err) {
              if (err) return error(type, err, cb, defer)
            }
            return defer

          }, resolve, reject)
        }

        if (type === "promise") return new Promise(subCall)
        return subCall()
      }

      const call = (resolve, reject) => {
          return  connect((e, cb, defer) => {
          const f = flat.flatten(e.peer)
          if (!f[path]) return error(type, new Error("Action " + path + " not found on " + e.peerID), cb, defer)
            if (defer) return defer.resolve(f[path](...args))
            return f[path].call(null, ...args, cb)
        }, resolve, reject)
      }

      if (type === "promise") return new Promise(call)
      return call()
    }
    catch (err) {
      return error(type, err, cb)
    }
  }

  _(
    api.addrs({live:true,old:true}),
    _.drain((data) => {
      const url = utils.parseUrl(data.key)

      if (!spec[data.action]) spec[data.action] = {}
      if (!spec[data.action][url.auth]) spec[data.action][url.auth] = {}
      const u = utils.parseUrl(data.key)
       u.pathname = null
       const address = u.format()
       const apiId = api.config.keys.publicKey

      if (data.gw != null) {
        data.gw.sort(function (a, b) {
          const aId = utils.parseUrl(a).auth
          const bId = utils.parseUrl(b).auth
          distance(utils.decode(aId, api.config.encoding), apiId) - distance(utils.decode(bId, api.config.encoding), apiId)
        })

        data.gw.forEach(addr => {
          addr = addr.replace("/" + api.config.appKey, "")
          if (spec[data.action][url.auth][addr] == null || spec[data.action][url.auth][addr] < data.ts)
            spec[data.action][url.auth][addr] = data.ts
        })
      }
      else if (spec[data.action][url.auth][address] == null || spec[data.action][url.auth][address] < data.ts)
        spec[data.action][url.auth][address] = data.ts

      let keys = Object.keys(spec[data.action])
      .sort((a, b) => distance(utils.decode(a, api.config.encoding), apiId) - distance(utils.decode(b, api.config.encoding), apiId))

      const sorted = {}
      for (let k of keys) sorted[k] = spec[data.action][k]
      spec[data.action] = sorted

      const action = {}
      delete data.ts
      delete data.key
      delete data.gw
      action[data.action] = data

      Object.assign(lb, Remote(flat.unflatten(action), remoteCall))
      const f = flat.flatten(lb)
      const ts = Date.now() - api.config.connectionTimeout

      Object.keys(f).forEach((k) => {
        if (spec[k]) {
          Object.keys(spec[k]).forEach((k2) => {
            if (spec[k][k2]) {
              Object.keys(spec[k][k2]).forEach((addr) => {
                if (spec[k][k2][addr] < ts) {
                  delete spec[k][k2][addr]
                }
                if (Object.keys(spec[k][k2]).length === 0) delete spec[k][k2]
                if (Object.keys(spec[k]).length === 0) {
                  delete spec[k]
                  delete robin[k]
                  unset(lb, k)
                }

              })

            }
          })
        }
      })
    }, () => {

    }))

}
<commit_msg>fix for lb<commit_after>const { api, _, Action } = require("../../")
const Remote = require("icebreaker-rpc/lib/remote.js")
const utils = require("icebreaker-network/lib/util.js")
const flat = require("flat")
const Util = require('muxrpc/util')
const rr = require('rr')
const Defer = require('pull-defer')
const distance = require('k-bucket').distance
const unset = require('unset-value');
const assign = require('assign-deep');

module.exports = () => {

  let spec = {}

  api.actions.lb = {}
  api.lb = api.actions.lb
  let lb = api.lb

  const robin = {}

  api.actions.call = {

    promise: Action({
      type: "promise",
      input: ["string", "string", "array"],
      desc: "This run a promise action on peerID",
      run: async function (peerID, path, args) {
        for (let k in api.connections) {
          let c = api.connections[k]
          if (c.peerID === peerID && c.peer) {
            const f = flat.flatten(c.peer)
            if (!f[path]) throw new Error("Action " + path + " not found on " + peerID)
            if (f[path].type !== "promise") throw new Error("Action " + path + " type is not a promise on " + peerID)
            return await f[path](...args)
          }

        }
        throw new Error("No Peer with id" + peerID + " found on " + api.id)
      }
    }),
    source: Action({
      type: "source",
      input: ["string", "string", "array"],
      desc: "This run a source stream on peerID",
      run: (peerID, path, args) => {
        for (let k in api.connections) {
          let c = api.connections[k]
          if (c.peerID === peerID && c.peer) {
            const f = flat.flatten(c.peer)
            if (!f[path]) return _.error(new Error("Action " + path + " not found on " + peerID))
            if (f[path].type !== "source") return _.error(new Error("Action " + path + " type is not a source on " + peerID))
            return f[path](...args)
          }
        }
        return _.error(new Error("No Peer with id" + peerID + " found on " + api.id))
      }
    }),
    duplex: Action({
      type: "source",
      input: ["string", "string", "array"],
      desc: "This run a duplex stream on peerID",
      run: (peerID, path, args) => {
        const error = (err) => {
          return {
            source: _.error(err),
            sink: (read) => {
              read(err || true, (_err) => { })
            }
          }
        }

        for (let k in api.connections) {
          let c = api.connections[k]
          if (c.peerID === peerID && c.peer) {
            const f = flat.flatten(c.peer)
            if (!f[path]) return error(new Error("Action " + path + " not found on " + peerID))
            if (f[path].type !== "source") return error(new Error("Action " + path + " type is not a source on " + peerID))
            return f[path](...args)
          }
        }
        return error(new Error("No Peer with id" + peerID + " found on " + api.id))
      }
    }),
    sink: Action({
      type: "sink",
      input: ["string", "string", "array"],
      desc: "This run a sink stream on peerID",
      run: (peerID, path, args, cb) => {
        args.push(cb)

        const error = (err) => {
          return (read) => {
            read(err || true, (_err) => { cb(err || _err) })
          }
        }

        for (let k in api.connections) {
          let c = api.connections[k]
          if (c.peerID === peerID && c.peer) {
            const f = flat.flatten(c.peer)
            if (!f[path]) return error(new Error("Action " + path + " not found on " + peerID))
            if (f[path].type !== "sink") return error(new Error("Action " + path + " type is not a sink on " + peerID))
            return f[path](...args)
          }
        }

        return error(new Error("No Peer with id" + peerID + " found on " + api.id))
      }
    })

  }

  api.actions.call.async= api.actions.call.sync = Action({
    type: "async",
    input: ["string", "string", "array"],
    desc: "This run a async or sync action on peerID",
    run: (peerID, path, args, cb) => {
      for (let k in api.connections) {
        let c = api.connections[k]
        if (c.peerID === peerID && c.peer) {
          const f = flat.flatten(c.peer)
          if (!f[path]) return cb(new Error("Action " + path + " not found on " + peerID))
          if (f[path].type !== "sync" && f[path].type !== "async") return cb(new Error("Action " + path + " type is not sync or async on " + peerID))
          return f[path](...args)
        }
      }

      return cb(new Error("No Peer with id" + peerID + " found on " + api.id))
    }
  })

  function error(type, error, cb, defer) {
    if (type === "promise") {
      if (defer) return defer.reject(error)

      return new Promise((resolve, reject) => {
        reject(error)
      });
    }

    if (!cb) cb = _.isFunction(cb) ? cb : (err) => {
      if (type == "duplex") return
      if (err) throw new Error(err || 'callback not provided')
    }
    if (defer) defer.resolve(Util.errorAsStreamOrCb(type, error, cb))

    return Util.errorAsStreamOrCb(type, error, cb)
  }

  function remoteCall(type, path, args) {

    const cb = _.isFunction(args[args.length - 1]) ? args[args.length - 1] : null
    if (cb) args.pop()

    try {
      if (!spec[path]) return error(type, new Error("function " + path + " unarivable"), cb)
      const addrs = spec[path]
      const keys = Object.keys(addrs)
      if (keys.length === 0) return error(type, new Error("No address found for action " + path), cb)
      keys._rr  = robin[path]=robin[path] || 0
      const key = rr(keys)
      robin[path] = keys._rr++
      const address = Object.keys(spec[path][key])
      if (address.length === 0) return error(type, new Error("No address found for action " + path), cb)
      const connect = (_cb, resolve, reject) => {
        let defer
        if (type == "source" || type == "sink" || type == "duplex") defer = Defer[type]()
        if (type == "promise") defer = { reject: reject, resolve: resolve }
        api.connect(address, (err, e) => {
          if (err) return error(type, err, cb, defer)
          _cb(e, cb, defer)
        })
        return defer
      }

      if (!address[0].includes("//" + key + "@")) {

        const subCall = (resolve, reject) => {
          return connect((e, cb, defer) => {
            try {
              if (!(e.peer.call && e.peer.call[type]))
                return error(type, new Error("Type " + type + " not supported on " + e.peerID), cb, defer)
              if (defer) {
                if (type == "sink")
                  return defer.resolve(e.peer.call[type](key, path, args, cb))

                return defer.resolve(e.peer.call[type](key, path, args))
              }

              return e.peer.call[type](key, path, args, cb)
            }
            catch (err) {
              if (err) return error(type, err, cb, defer)
            }
            return defer

          }, resolve, reject)
        }

        if (type === "promise") return new Promise(subCall)
        return subCall()
      }

      const call = (resolve, reject) => {
          return  connect((e, cb, defer) => {
          const f = flat.flatten(e.peer)
          if (!f[path]) return error(type, new Error("Action " + path + " not found on " + e.peerID), cb, defer)
            if (defer) return defer.resolve(f[path](...args))
            return f[path].call(null, ...args, cb)
        }, resolve, reject)
      }

      if (type === "promise") return new Promise(call)
      return call()
    }
    catch (err) {
      return error(type, err, cb)
    }
  }

  _(
    api.addrs({live:true,old:true}),
    _.drain((data) => {
      const url = utils.parseUrl(data.key)

      if (!spec[data.action]) spec[data.action] = {}
      if (!spec[data.action][url.auth]) spec[data.action][url.auth] = {}
      const u = utils.parseUrl(data.key)
       u.pathname = null
       const address = u.format()
       const apiId = api.config.keys.publicKey

      if (data.gw != null) {
        data.gw.sort(function (a, b) {
          const aId = utils.parseUrl(a).auth
          const bId = utils.parseUrl(b).auth
          distance(utils.decode(aId, api.config.encoding), apiId) - distance(utils.decode(bId, api.config.encoding), apiId)
        })

        data.gw.forEach(addr => {
          addr = addr.replace("/" + api.config.appKey, "")
          if (spec[data.action][url.auth][addr] == null || spec[data.action][url.auth][addr] < data.ts)
            spec[data.action][url.auth][addr] = data.ts
        })
      }
      else if (spec[data.action][url.auth][address] == null || spec[data.action][url.auth][address] < data.ts)
        spec[data.action][url.auth][address] = data.ts

      let keys = Object.keys(spec[data.action])
      .sort((a, b) => distance(utils.decode(a, api.config.encoding), apiId) - distance(utils.decode(b, api.config.encoding), apiId))

      const sorted = {}
      for (let k of keys) sorted[k] = spec[data.action][k]
      spec[data.action] = sorted

      const action = {}
      delete data.ts
      delete data.key
      delete data.gw
      action[data.action] = data
      assign(lb, Remote(flat.unflatten(action), remoteCall))
      const f = flat.flatten(lb)
      console.log(Remote(flat.unflatten(action)))
      const ts = Date.now() - api.config.connectionTimeout

      Object.keys(f).forEach((k) => {
        if (spec[k]) {
          Object.keys(spec[k]).forEach((k2) => {
            if (spec[k][k2]) {
              Object.keys(spec[k][k2]).forEach((addr) => {
                if (spec[k][k2][addr] < ts) {
                  delete spec[k][k2][addr]
                }
                if (Object.keys(spec[k][k2]).length === 0) delete spec[k][k2]
                if (Object.keys(spec[k]).length === 0) {
                  delete spec[k]
                  delete robin[k]
                  unset(lb, k)
                }

              })

            }
          })
        }
      })
    }, () => {

    }))

}
<|endoftext|>


<commit_before>// Copyright (c) 2010 Romain Vallet
// Licensed under the MIT license, read license.txt

var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push( {
	name: 'Default',
	version: '0.4',
	prepareImgLinks: function(callback) {
		var res = [];
		$('a[href]').filter(function() {
			return this.href.match(/\.(?:jpe?g|gif|png|svg|bmp|ico|xbm)(?:[\?#].*)?$/i);
		}).each(function() {
			var _this = $(this);
			if (!_this.data('hoverZoomSrc')) {
				_this.data('hoverZoomSrc', [this.href]);
				res.push(_this);
			}
		});
		callback($(res));
	}
});<commit_msg>Default plugin now excludes file names with a colon (:) (fixes issue 49).<commit_after>// Copyright (c) 2011 Romain Vallet <romain.vallet@gmail.com>
// Licensed under the MIT license, read license.txt

var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push( {
	name: 'Default',
	version: '0.5',
	prepareImgLinks: function(callback) {
		var res = [];
		$('a[href]').filter(function() {
			return this.href.match(/\/[^:]+\.(?:jpe?g|gif|png|svg|bmp|ico|xbm)(?:[\?#].*)?$/i);
		}).each(function() {
			var _this = $(this);
			if (!_this.data('hoverZoomSrc')) {
				_this.data('hoverZoomSrc', [this.href]);
				res.push(_this);
			}
		});
		callback($(res));
	}
});<|endoftext|>


<commit_before>var deps = require('get-deps')
var addDeps = require('add-deps')
var rebuild = require('npmd-rebuild')
var bin = require('npmd-bin')
var path = require('path')

exports.commands = function (db, cache, config) {

  if(!cache.get) throw new Error('must have cache')
  var install = require('npmd-install')(cache)

  db.commands.push(function (db, cache, config, cb) {
    var args = config._.slice()
    if('install' !== args.shift()) return

    var _args = args.slice()

    db.resolve(args.slice(), config, function (err, tree) {
      if(err) return cb(err)
      install(tree, config, function (err, installed) {
        if(err) return cb(err)
        return console.log(installed)
        if(config.save || config.saveDev)
          addDeps(config.path || process.cwd(), installed, config, next)
        else next()

        function next () {

          rebuild(_args[0], config, function (err) {

            _args = _args.map(function (e) {
              e = e.split('@').shift()
              if(/^[./]/.test(e)) return e
              return config.global
                ? path.join(config.prefix, 'lib', 'node_modules', e)
                : path.join(process.cwd(), 'node_modules', e)
            })

            bin.all(_args, config.bin, config, cb)

          })

        }
      })
    })
    return true
  })
}

<commit_msg>helpful output<commit_after>var deps = require('get-deps')
var addDeps = require('add-deps')
var rebuild = require('npmd-rebuild')
var bin = require('npmd-bin')
var path = require('path')

exports.commands = function (db, cache, config) {

  if(!cache.get) throw new Error('must have cache')
  var install = require('npmd-install')(cache)

  db.commands.push(function (db, cache, config, cb) {
    var args = config._.slice()
    if('install' !== args.shift()) return

    var _args = args.slice()

    db.resolve(args.slice(), config, function (err, tree) {
      if(err) return cb(err)
      install(tree, config, function (err, installed) {
        if(err) return cb(err)

        if(config.save || config.saveDev)
          addDeps(config.path || process.cwd(), installed, config, next)
        else next()

        function next () {

          rebuild(_args[0], config, function (err) {

            _args = _args.map(function (e) {
              e = e.split('@').shift()
              if(/^[./]/.test(e)) return e
              return config.global
                ? path.join(config.prefix, 'lib', 'node_modules', e)
                : path.join(process.cwd(), 'node_modules', e)
            })

            bin.all(_args, config.bin, config, function (err) {
              cb(err, installed)
            })

          })

        }
      })
    })
    return true
  })
}

<|endoftext|>


<commit_before>// History
// Uses AMD or browser globals for jQuery.
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as a module.
        define('pnotify.history', ['jquery', 'pnotify'], factory);
    } else {
        // Browser globals
        factory(jQuery, PNotify);
    }
}(function($, PNotify){
	var history_menu,
		history_handle_top;
	$(function(){
		$("body").on("pnotify.history-all", function(){
			// Display all notices. (Disregarding non-history notices.)
			$.each(PNotify.notices, function(){
				if (this.modules.history.inHistory) {
					if (this.elem.is(":visible")) {
						// The hide variable controls whether the history pull down should
						// queue a removal timer.
						if (this.options.hide)
							this.queueRemove();
					} else if (this.open)
						this.open();
				}
			});
		}).on("pnotify.history-last", function(){
			var pushTop = (PNotify.prototype.options.stack.push === "top");

			// Look up the last history notice, and display it.
			var i = (pushTop ? 0 : -1);

			var notice;
			do {
				if (i === -1)
					notice = PNotify.notices.slice(i);
				else
					notice = PNotify.notices.slice(i, i+1);
				if (!notice[0])
					return false;

				i = (pushTop ? i + 1 : i - 1);
			} while (!notice[0].modules.history.inHistory || notice[0].elem.is(":visible"));
			if (notice[0].open)
				notice[0].open();
		});
	});
	PNotify.prototype.options.history = {
		// Place the notice in the history.
		history: true,
		// Display a pull down menu to redisplay previous notices.
		menu: false,
		// Make the pull down menu fixed to the top of the viewport.
		fixed: true,
		// Maximum number of notifications to have onscreen.
		maxonscreen: Infinity,
		// The various displayed text, helps facilitating internationalization.
		labels: {
			redisplay: "Redisplay",
			all: "All",
			last: "Last"
		}
	};
	PNotify.prototype.modules.history = {
		// The history variable controls whether the notice gets redisplayed
		// by the history pull down.
		inHistory: false,

		init: function(notice, options){
			// Make sure that no notices get destroyed.
			notice.options.destroy = false;

			this.inHistory = options.history;

			if (options.menu) {
				// If there isn't a history pull down, create one.
				if (typeof history_menu === "undefined") {
					history_menu = $("<div />", {
						"class": "ui-pnotify-history-container "+notice.styles.hi_menu,
						"mouseleave": function(){
							history_menu.animate({top: "-"+history_handle_top+"px"}, {duration: 100, queue: false});
						}
					})
					.append($("<div />", {"class": "ui-pnotify-history-header", "text": options.labels.redisplay}))
					.append($("<button />", {
							"class": "ui-pnotify-history-all "+notice.styles.hi_btn,
							"text": options.labels.all,
							"mouseenter": function(){
								$(this).addClass(notice.styles.hi_btnhov);
							},
							"mouseleave": function(){
								$(this).removeClass(notice.styles.hi_btnhov);
							},
							"click": function(){
								$(this).trigger("pnotify.history-all");
								return false;
							}
					}))
					.append($("<button />", {
							"class": "ui-pnotify-history-last "+notice.styles.hi_btn,
							"text": options.labels.last,
							"mouseenter": function(){
								$(this).addClass(notice.styles.hi_btnhov);
							},
							"mouseleave": function(){
								$(this).removeClass(notice.styles.hi_btnhov);
							},
							"click": function(){
								$(this).trigger("pnotify.history-last");
								return false;
							}
					}))
					.appendTo("body");

					// Make a handle so the user can pull down the history tab.
					var handle = $("<span />", {
						"class": "ui-pnotify-history-pulldown "+notice.styles.hi_hnd,
						"mouseenter": function(){
							history_menu.animate({top: "0"}, {duration: 100, queue: false});
						}
					})
					.appendTo(history_menu);

					// Get the top of the handle.
					console.log(handle.offset());
					history_handle_top = handle.offset().top + 2;
					// Hide the history pull down up to the top of the handle.
					history_menu.css({top: "-"+history_handle_top+"px"});

					// Apply the fixed styling.
					if (options.fixed) {
						history_menu.addClass('ui-pnotify-history-fixed');
					}
				}
			}
		},
		update: function(notice, options){
			// Update values for history menu access.
			this.inHistory = options.history;
			if (options.fixed && history_menu) {
				history_menu.addClass('ui-pnotify-history-fixed');
			} else if (history_menu) {
				history_menu.removeClass('ui-pnotify-history-fixed');
			}
		},
		beforeOpen: function(notice, options){
			// Remove oldest notifications leaving only options.maxonscreen on screen
			if (PNotify.notices && (PNotify.notices.length > options.maxonscreen)) {
				// Oldest are normally in front of array, or if stack.push=="top" then
				// they are at the end of the array! (issue #98)
				var el;
				if (notice.options.stack.push !== "top")
					el = PNotify.notices.slice(0, PNotify.notices.length - options.maxonscreen);
				else
					el = PNotify.notices.slice(options.maxonscreen, PNotify.notices.length);

				$.each(el, function(){
					if (this.remove)
						this.remove();
				});
			}
		}
	};
	$.extend(PNotify.styling.jqueryui, {
		hi_menu: "ui-state-default ui-corner-bottom",
		hi_btn: "ui-state-default ui-corner-all",
		hi_btnhov: "ui-state-hover",
		hi_hnd: "ui-icon ui-icon-grip-dotted-horizontal"
	});
	$.extend(PNotify.styling.bootstrap2, {
		hi_menu: "well",
		hi_btn: "btn",
		hi_btnhov: "",
		hi_hnd: "icon-chevron-down"
	});
	$.extend(PNotify.styling.bootstrap3, {
		hi_menu: "well",
		hi_btn: "btn btn-default",
		hi_btnhov: "",
		hi_hnd: "glyphicon glyphicon-chevron-down"
	});
	$.extend(PNotify.styling.fontawesome, {
		hi_menu: "well",
		hi_btn: "btn btn-default",
		hi_btnhov: "",
		hi_hnd: "fa fa-chevron-down"
	});
}));
<commit_msg>fixes <IE9 bug when console isn't open<commit_after>// History
// Uses AMD or browser globals for jQuery.
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as a module.
        define('pnotify.history', ['jquery', 'pnotify'], factory);
    } else {
        // Browser globals
        factory(jQuery, PNotify);
    }
}(function($, PNotify){
	var history_menu,
		history_handle_top;
	$(function(){
		$("body").on("pnotify.history-all", function(){
			// Display all notices. (Disregarding non-history notices.)
			$.each(PNotify.notices, function(){
				if (this.modules.history.inHistory) {
					if (this.elem.is(":visible")) {
						// The hide variable controls whether the history pull down should
						// queue a removal timer.
						if (this.options.hide)
							this.queueRemove();
					} else if (this.open)
						this.open();
				}
			});
		}).on("pnotify.history-last", function(){
			var pushTop = (PNotify.prototype.options.stack.push === "top");

			// Look up the last history notice, and display it.
			var i = (pushTop ? 0 : -1);

			var notice;
			do {
				if (i === -1)
					notice = PNotify.notices.slice(i);
				else
					notice = PNotify.notices.slice(i, i+1);
				if (!notice[0])
					return false;

				i = (pushTop ? i + 1 : i - 1);
			} while (!notice[0].modules.history.inHistory || notice[0].elem.is(":visible"));
			if (notice[0].open)
				notice[0].open();
		});
	});
	PNotify.prototype.options.history = {
		// Place the notice in the history.
		history: true,
		// Display a pull down menu to redisplay previous notices.
		menu: false,
		// Make the pull down menu fixed to the top of the viewport.
		fixed: true,
		// Maximum number of notifications to have onscreen.
		maxonscreen: Infinity,
		// The various displayed text, helps facilitating internationalization.
		labels: {
			redisplay: "Redisplay",
			all: "All",
			last: "Last"
		}
	};
	PNotify.prototype.modules.history = {
		// The history variable controls whether the notice gets redisplayed
		// by the history pull down.
		inHistory: false,

		init: function(notice, options){
			// Make sure that no notices get destroyed.
			notice.options.destroy = false;

			this.inHistory = options.history;

			if (options.menu) {
				// If there isn't a history pull down, create one.
				if (typeof history_menu === "undefined") {
					history_menu = $("<div />", {
						"class": "ui-pnotify-history-container "+notice.styles.hi_menu,
						"mouseleave": function(){
							history_menu.animate({top: "-"+history_handle_top+"px"}, {duration: 100, queue: false});
						}
					})
					.append($("<div />", {"class": "ui-pnotify-history-header", "text": options.labels.redisplay}))
					.append($("<button />", {
							"class": "ui-pnotify-history-all "+notice.styles.hi_btn,
							"text": options.labels.all,
							"mouseenter": function(){
								$(this).addClass(notice.styles.hi_btnhov);
							},
							"mouseleave": function(){
								$(this).removeClass(notice.styles.hi_btnhov);
							},
							"click": function(){
								$(this).trigger("pnotify.history-all");
								return false;
							}
					}))
					.append($("<button />", {
							"class": "ui-pnotify-history-last "+notice.styles.hi_btn,
							"text": options.labels.last,
							"mouseenter": function(){
								$(this).addClass(notice.styles.hi_btnhov);
							},
							"mouseleave": function(){
								$(this).removeClass(notice.styles.hi_btnhov);
							},
							"click": function(){
								$(this).trigger("pnotify.history-last");
								return false;
							}
					}))
					.appendTo("body");

					// Make a handle so the user can pull down the history tab.
					var handle = $("<span />", {
						"class": "ui-pnotify-history-pulldown "+notice.styles.hi_hnd,
						"mouseenter": function(){
							history_menu.animate({top: "0"}, {duration: 100, queue: false});
						}
					})
					.appendTo(history_menu);

					// Get the top of the handle.
					history_handle_top = handle.offset().top + 2;
					// Hide the history pull down up to the top of the handle.
					history_menu.css({top: "-"+history_handle_top+"px"});

					// Apply the fixed styling.
					if (options.fixed) {
						history_menu.addClass('ui-pnotify-history-fixed');
					}
				}
			}
		},
		update: function(notice, options){
			// Update values for history menu access.
			this.inHistory = options.history;
			if (options.fixed && history_menu) {
				history_menu.addClass('ui-pnotify-history-fixed');
			} else if (history_menu) {
				history_menu.removeClass('ui-pnotify-history-fixed');
			}
		},
		beforeOpen: function(notice, options){
			// Remove oldest notifications leaving only options.maxonscreen on screen
			if (PNotify.notices && (PNotify.notices.length > options.maxonscreen)) {
				// Oldest are normally in front of array, or if stack.push=="top" then
				// they are at the end of the array! (issue #98)
				var el;
				if (notice.options.stack.push !== "top")
					el = PNotify.notices.slice(0, PNotify.notices.length - options.maxonscreen);
				else
					el = PNotify.notices.slice(options.maxonscreen, PNotify.notices.length);

				$.each(el, function(){
					if (this.remove)
						this.remove();
				});
			}
		}
	};
	$.extend(PNotify.styling.jqueryui, {
		hi_menu: "ui-state-default ui-corner-bottom",
		hi_btn: "ui-state-default ui-corner-all",
		hi_btnhov: "ui-state-hover",
		hi_hnd: "ui-icon ui-icon-grip-dotted-horizontal"
	});
	$.extend(PNotify.styling.bootstrap2, {
		hi_menu: "well",
		hi_btn: "btn",
		hi_btnhov: "",
		hi_hnd: "icon-chevron-down"
	});
	$.extend(PNotify.styling.bootstrap3, {
		hi_menu: "well",
		hi_btn: "btn btn-default",
		hi_btnhov: "",
		hi_hnd: "glyphicon glyphicon-chevron-down"
	});
	$.extend(PNotify.styling.fontawesome, {
		hi_menu: "well",
		hi_btn: "btn btn-default",
		hi_btnhov: "",
		hi_hnd: "fa fa-chevron-down"
	});
}));
<|endoftext|>