<commit_before>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global require */

(function () {
  'use strict';
  var Foxx = require('org/arangodb/foxx'),
    _ = require('underscore'),
    extend = require('org/arangodb/extend').extend,
    // ArangoError = require('internal').ArangoError,
    BaseTransition = require('./base_transition').BaseTransition,
    BaseState = require('./state').State,
    // VertexNotFound = require('./graph').VertexNotFound,
    RepositoryWithGraph = require('./repository_with_graph').RepositoryWithGraph,
    Transition,
    State,
    Model,
    Repository;

  var Strategy = function () {};

  _.extend(Strategy.prototype, {
    executable: function(semantics, from, to, relation) {
      return semantics === this.semantics && from === this.from && to === this.to && relation === this.relation;
    }
  });

  Strategy.extend = extend;

  var AddEntityToRepository = Strategy.extend({
    semantics: 'link',
    from: 'repository',
    to: 'entity',
    relation: 'one-to-one',

    execute: function(controller, graph, relation, repositoryState, entityState) {
      var nameOfRootElement = entityState.name,
        repository = repositoryState.repository,
        BodyParam = Foxx.Model.extend({ schema: relation.parameters }),
        href = repositoryState.urlTemplate,
        name = relation.name,
        method = 'POST',
        fields,
        title = relation.description;

      fields = _.map(relation.parameters, function (joi, name) {
        var fieldDescription = { name: name, type: joi._type };

        if (!_.isNull(joi._description)) {
          fieldDescription.description = joi._description;
        }

        if (!_.isUndefined(joi._flags.default)) {
          fieldDescription.value = joi._flags.default;
        }

        return fieldDescription;
      });

      repositoryState.addAction(name, method, href, title, fields);

      controller.post(href, function (req, res) {
        var data = {},
          model = req.params(nameOfRootElement);

        data[nameOfRootElement] = repository.save(model).forClient();
        res.status(201);
        res.json(data);
      }).bodyParam(nameOfRootElement, 'TODO', BodyParam)
        .summary(relation.description)
        .notes('TODO');
    }
  });

  var Link = Strategy.extend({
    semantics: 'follow',
    from: 'start',
    to: 'repository',
    relation: 'one-to-one',

    execute: function (controller, graph, relation, from, to) {
      var rel = relation.name,
        href = to.urlTemplate,
        title = relation.description;

      from.addLink([rel], href, title);

      controller.get(href, function (req, res) {
        res.json({
          properties: {},
          links: to.links,
          actions: to.actions
        });
      });
    }
  });

  var strategies = [
    new AddEntityToRepository(),
    new Link()
  ];

  var Context = function (semantics, from, to, relation) {
    this.strategy = _.find(strategies, function (maybeStrategy) {
      return maybeStrategy.executable(semantics, from, to, relation);
    });

    if (_.isUndefined(this.strategy)) {
      require('console').log("Couldn't find %s strategy for semantic %s from %s to %s", relation, semantics, from, to);
      throw 'Could not find strategy';
    }
  };

  _.extend(Context.prototype, {
    execute: function (controller, graph, relation, from, to) {
      this.strategy.execute(controller, graph, relation, from, to);
    }
  });

  Repository = RepositoryWithGraph.extend({
  });

  Model = Foxx.Model.extend({
  });

  State = BaseState.extend({
    addRepository: function (Repository, states) {
      this.type = 'repository';
      var elementRelation = this.findTransitionBySemantics('link'),
        ModelForRepo = states[elementRelation.to].model;

      this.collection = this.graph.addVertexCollection(this.name);
      this.collectionName = this.collection.name();

      this.repository = new Repository(this.collection, {
        model: ModelForRepo,
        graph: this.graph
      });
    },

    setAsStart: function (controller) {
      var that = this;

      controller.get('/', function (req, res) {
        res.json({
          properties: {},
          links: that.links,
          actions: that.actions
        });
      }).summary('Billboard URL')
        .notes('TODO');
      this.type = 'start';
    },

    addLink: function (rel, href, title) {
      this.links.push({
        rel: rel,
        href: href,
        title: title
      });
    },

    addAction: function (name, method, href, title, fields) {
      this.actions.push({
        name: name,
        // class: ?,
        method: method,
        href: href,
        title: title,
        type: 'application/json',
        fields: fields
      });
    }
  });

  Transition = BaseTransition.extend({
    addRoutesForOneRelation: function (controller, graph, relation, from, to) {
      var context = new Context(this.semantics, from.type, to.type, 'one-to-one');
      context.execute(controller, graph, relation, from, to);
    },

    addRoutesForManyRelation: function (controller, graph, relation, from, to) {
      var context = new Context(this.semantics, from.type, to.type, 'one-to-many');
      context.execute(controller, graph, relation, from, to);
    }
  });

  exports.mediaType = {
    Model: Model,
    Repository: Repository,
    Transition: Transition,
    State: State,
    transitions: []
  };
}());
<commit_msg>Return entities for repositories<commit_after>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global require */

(function () {
  'use strict';
  var Foxx = require('org/arangodb/foxx'),
    _ = require('underscore'),
    extend = require('org/arangodb/extend').extend,
    // ArangoError = require('internal').ArangoError,
    BaseTransition = require('./base_transition').BaseTransition,
    BaseState = require('./state').State,
    // VertexNotFound = require('./graph').VertexNotFound,
    RepositoryWithGraph = require('./repository_with_graph').RepositoryWithGraph,
    Transition,
    State,
    Model,
    Repository;

  var forClient = function (model) {
    return model.forClient();
  };

  var Strategy = function () {};

  _.extend(Strategy.prototype, {
    executable: function(semantics, from, to, relation) {
      return semantics === this.semantics && from === this.from && to === this.to && relation === this.relation;
    }
  });

  Strategy.extend = extend;

  var AddEntityToRepository = Strategy.extend({
    semantics: 'link',
    from: 'repository',
    to: 'entity',
    relation: 'one-to-one',

    execute: function(controller, graph, relation, repositoryState, entityState) {
      var nameOfRootElement = entityState.name,
        repository = repositoryState.repository,
        BodyParam = Foxx.Model.extend({ schema: relation.parameters }),
        href = repositoryState.urlTemplate,
        name = relation.name,
        method = 'POST',
        fields,
        title = relation.description;

      fields = _.map(relation.parameters, function (joi, name) {
        var fieldDescription = { name: name, type: joi._type };

        if (!_.isNull(joi._description)) {
          fieldDescription.description = joi._description;
        }

        if (!_.isUndefined(joi._flags.default)) {
          fieldDescription.value = joi._flags.default;
        }

        return fieldDescription;
      });

      repositoryState.addAction(name, method, href, title, fields);

      controller.post(href, function (req, res) {
        var data = {},
          model = req.params(nameOfRootElement);

        data[nameOfRootElement] = repository.save(model).forClient();
        res.status(201);
        res.json(data);
      }).bodyParam(nameOfRootElement, 'TODO', BodyParam)
        .summary(relation.description)
        .notes('TODO');
    }
  });

  var Link = Strategy.extend({
    semantics: 'follow',
    from: 'start',
    to: 'repository',
    relation: 'one-to-one',

    execute: function (controller, graph, relation, from, to) {
      var rel = relation.name,
        href = to.urlTemplate,
        title = relation.description;

      from.addLink([rel], href, title);

      controller.get(href, function (req, res) {
        res.json({
          properties: to.properties(),
          entities: to.entities(),
          links: to.links,
          actions: to.actions
        });
      }).summary(relation.description)
        .notes('TODO');
    }
  });

  var strategies = [
    new AddEntityToRepository(),
    new Link()
  ];

  var Context = function (semantics, from, to, relation) {
    this.strategy = _.find(strategies, function (maybeStrategy) {
      return maybeStrategy.executable(semantics, from, to, relation);
    });

    if (_.isUndefined(this.strategy)) {
      require('console').log("Couldn't find %s strategy for semantic %s from %s to %s", relation, semantics, from, to);
      throw 'Could not find strategy';
    }
  };

  _.extend(Context.prototype, {
    execute: function (controller, graph, relation, from, to) {
      this.strategy.execute(controller, graph, relation, from, to);
    }
  });

  Repository = RepositoryWithGraph.extend({
  });

  Model = Foxx.Model.extend({
    forClient: function () {
      var properties = Foxx.Model.prototype.forClient.call(this);

      return {
        properties: properties
      };
    }
  });

  State = BaseState.extend({
    addRepository: function (Repository, states) {
      this.type = 'repository';
      var elementRelation = this.findTransitionBySemantics('link'),
        ModelForRepo = states[elementRelation.to].model;

      this.collection = this.graph.addVertexCollection(this.name);
      this.collectionName = this.collection.name();

      this.repository = new Repository(this.collection, {
        model: ModelForRepo,
        graph: this.graph
      });
    },

    setAsStart: function (controller) {
      var that = this;

      controller.get('/', function (req, res) {
        res.json({
          properties: {},
          links: that.links,
          actions: that.actions
        });
      }).summary('Billboard URL')
        .notes('TODO');
      this.type = 'start';
    },

    properties: function () {
      return {};
    },

    entities: function () {
      var entities = [];

      if (this.type === 'repository') {
        entities = _.map(this.repository.all(), forClient);
      }

      return entities;
    },

    addLink: function (rel, href, title) {
      this.links.push({
        rel: rel,
        href: href,
        title: title
      });
    },

    addAction: function (name, method, href, title, fields) {
      this.actions.push({
        name: name,
        // class: ?,
        method: method,
        href: href,
        title: title,
        type: 'application/json',
        fields: fields
      });
    }
  });

  Transition = BaseTransition.extend({
    addRoutesForOneRelation: function (controller, graph, relation, from, to) {
      var context = new Context(this.semantics, from.type, to.type, 'one-to-one');
      context.execute(controller, graph, relation, from, to);
    },

    addRoutesForManyRelation: function (controller, graph, relation, from, to) {
      var context = new Context(this.semantics, from.type, to.type, 'one-to-many');
      context.execute(controller, graph, relation, from, to);
    }
  });

  exports.mediaType = {
    Model: Model,
    Repository: Repository,
    Transition: Transition,
    State: State,
    transitions: []
  };
}());
<|endoftext|>


<commit_before>/* eslint-disable no-console */
/* eslint-disable no-fallthrough */

(function() {

	mw.loader.using(['mediawiki.util']).done(function() {
		/* mediawiki.util */

		console.log("using User:Xiplus/global.js");

		/* 反importScript */
		var whitelist = ["Xiplus", "A2093064-test", "A2093064-bot"];
		if (whitelist.indexOf(mw.config.get('wgUserName')) === -1) {
			alert("請勿importScript User:Xiplus/global.js！可能有未預期的危害發生。");
			return;
		}

		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/APIedit.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/APIedit.js&action=raw&ctype=text/javascript');
		mw.loader.using(['mediawiki.util']).done(function() {
			mw.loader.load('https://en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-ShowMessageNames.js&oldid=554722666&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		});
		// [[File:Krinkle_CVNSimpleOverlay_wiki.js]]
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Krinkle/Scripts/CVNSimpleOverlay_wiki.js&oldid=18174822&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		mw.loader.load("https://zh.wikipedia.org/w/index.php?title=User:Bluedeck/serve/edit-count.js&oldid=49623399&action=raw&ctype=text/javascript"); // 08:46, 5 August 2018 (UTC)

		/* wikiplus */
		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/w.js');
		mw.loader.load('https://wikiplus-app.com/Main.min.js');
		(function() {
			function wikiplusSettingdefaultSummary(w) {
				if (w.sectionNumber == -1) {
					return ' ';
				}
				if (w.sectionNumber == 0) {
					return '/* 首段 */ ';
				}
				return '/* ' + w.sectionName + ' */ ';
			}
			var wikiplusSetting = {
				"defaultSummary": wikiplusSettingdefaultSummary.toString().replace(/\s+/g, " "),
				"documatation": "http://zh.moegirl.org/User:%E5%A6%B9%E7%A9%BA%E9%85%B1/Wikiplus/%E8%AE%BE%E7%BD%AE%E8%AF%B4%E6%98%8E"
			};
			localStorage.setItem("Wikiplus_Settings", JSON.stringify(wikiplusSetting));
		})();

		/* XTools */
		mw.loader.load('https://www.mediawiki.org/w/index.php?title=XTools/ArticleInfo.js&oldid=2625658&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)

		/* FakeRollback */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/FakeRollback.js&oldid=18757250&action=raw&ctype=text/javascript'); // 11:25, 4 January 2019 (UTC)
		}

		/* AutoUndo */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/AutoUndo.js&action=raw&ctype=text/javascript'); // 08:47, 5 August 2018 (UTC)
		}

		/* cvn-smart */
		// mw.loader.load('https://xiplus.ddns.net/wikipedia_rc/gadget.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/cvn-smart-gadget.js&action=raw&ctype=text/javascript');

		/* history-merge */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) !== -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/history-merge.js&action=raw&ctype=text/javascript');
		}

		/* list-user-last-active */
		switch (mw.config.get('wgDBname')) {
			case 'zhwiki':
				break;
			default:
				mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/list-user-last-active.js&action=raw&ctype=text/javascript');
				break;
		}

		/* get-translatewiki-link */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/get-translatewiki-link.js&action=raw&ctype=text/javascript');

		/* LinkToWikidata */
		if (mw.config.get('wgDBname').match(/^zhwik|enwiki/) && mw.config.get('wgDBname') != 'zhwiki') {
			mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/LinkToWikidata.js');
		}

		/* UTC clock */
		mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript');

		/* 頂欄 */
		document.all["pt-betafeatures"].hidden = true;
		document.all["pt-logout"].hidden = true;

		/* CentralAuth */
		function showCentralAuth(username) {
			if (username.match('^\\d+\\.\\d+\\.\\d+\\.\\d+$') !== null || username.match('^[0-9a-fA-F]+:[0-9a-fA-F:]+$')) {
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/meta/stalktoy/' + username,
					'全域封禁'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://whatismyipaddress.com/ip/' + username,
					'地理位置'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'http://whois.tanet.edu.tw/showWhoisPublic.php?queryString=' + username,
					'TANet'
				);
			} else {
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:CentralAuth') + '?target=' + encodeURIComponent(username),
					'全域帳號'
				);
			}
			mw.util.addPortletLink(
				'p-cactions',
				'https://tools.wmflabs.org/guc/?by=date&user=' + username,
				'全域貢獻'
			);
		}
		if (mw.config.get('wgNamespaceNumber') === 2 || mw.config.get('wgNamespaceNumber') === 3) {
			showCentralAuth(mw.config.get('wgTitle').replace(/^([^/]+).*$/, '$1'));
		} else if (mw.config.get('wgRelevantUserName') !== null) {
			showCentralAuth(mw.config.get('wgRelevantUserName'));
		}

		/* Admin list */
		switch (mw.config.get('wgDBname')) {
			// case 'zh_classicalwiki':
			// case 'zh_yuewiki':
			case 'zhwiki':
				// case 'zhwikibooks':
				// case 'zhwikinews':
				// case 'zhwikiquote':
				// case 'zhwikisource':
				// case 'zhwikivoyage':
				// case 'zhwiktionary':
				break;
			default:
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:Userlist') + '?group=sysop',
					'管理員列表'
				);
		}

		/* Twinkle */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			// case 'simplewiki':
			case 'zh_classicalwiki':
			case 'zhwiki':
			case 'zhwikibooks':
			// case 'zhwikinews':
			case 'zhwikiquote':
			// case 'zhwikisource':
			case 'zhwikiversity':
			case 'zhwikivoyage':
			case 'zhwiktionary':
				break;
			default:
				console.log("載入 Gadget-site-lib.js");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-site-lib.js&action=raw&ctype=text/javascript');
				console.log("測試版Twinkle");
				mw.loader.using(['mediawiki.user', 'mediawiki.util', 'mediawiki.RegExp', 'mediawiki.Title', 'jquery.ui.dialog', 'jquery.tipsy']).done(function() {
					console.log("Loading");
					mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:Xiplus/Twinkle-dev.js&action=raw&ctype=text/javascript');
				});
				break;
		}

		/* Popup */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'zhwiki':
				break;
			default:
				console.log("載入 A2569875Popup");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopupsSetting_zh-hant.js&action=raw&ctype=text/javascript');
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopups.css&action=raw&ctype=text/css', 'text/css');
				break;
		}

		/* 側欄 */
		mw.util.addPortletLink(
			'p-tb',
			'/wiki/Special:PrefixIndex/' + mw.config.get('wgPageName'),
			'前綴索引',
			't-prefixindex',
			'',
			'',
			$('#t-specialpages')
		);

		mw.util.addPortletLink(
			'p-tb',
			'/wiki/?curid=' + mw.config.get('wgArticleId'),
			'短網址',
			't-shorturl',
			'',
			'',
			$('#t-info')
		);

		if (mw.config.get("wgNamespaceNumber") == 8) {
			mw.util.addPortletLink(
				'p-cactions',
				'https://translatewiki.net/wiki/' + mw.config.get("wgPageName").split("/")[0] + '/zh-hant?action=edit',
				'translatewiki'
			);
		}

		mw.loader.using(['mediawiki.api']).done(function() {
			new mw.Api().get({
				action: "query",
				format: "json",
				list: "logevents",
				leprop: "comment|type",
				letype: "delete",
				letitle: mw.config.get('wgPageName')
			}).then(function(data) {
				for (var i = 0; i < data.query.logevents.length; i++) {
					var comment = data.query.logevents[i].comment;
					console.log(comment);
				}
			});
		});

		/* mediawiki.util */
	});

	console.log("global.js end");

})();
<commit_msg>interface-global: Update ip tools<commit_after>/* eslint-disable no-console */
/* eslint-disable no-fallthrough */

(function() {

	mw.loader.using(['mediawiki.util']).done(function() {
		/* mediawiki.util */

		console.log("using User:Xiplus/global.js");

		/* 反importScript */
		var whitelist = ["Xiplus", "A2093064-test", "A2093064-bot"];
		if (whitelist.indexOf(mw.config.get('wgUserName')) === -1) {
			alert("請勿importScript User:Xiplus/global.js！可能有未預期的危害發生。");
			return;
		}

		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/APIedit.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/APIedit.js&action=raw&ctype=text/javascript');
		mw.loader.using(['mediawiki.util']).done(function() {
			mw.loader.load('https://en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-ShowMessageNames.js&oldid=554722666&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		});
		// [[File:Krinkle_CVNSimpleOverlay_wiki.js]]
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Krinkle/Scripts/CVNSimpleOverlay_wiki.js&oldid=18174822&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		mw.loader.load("https://zh.wikipedia.org/w/index.php?title=User:Bluedeck/serve/edit-count.js&oldid=49623399&action=raw&ctype=text/javascript"); // 08:46, 5 August 2018 (UTC)

		/* wikiplus */
		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/w.js');
		mw.loader.load('https://wikiplus-app.com/Main.min.js');
		(function() {
			function wikiplusSettingdefaultSummary(w) {
				if (w.sectionNumber == -1) {
					return ' ';
				}
				if (w.sectionNumber == 0) {
					return '/* 首段 */ ';
				}
				return '/* ' + w.sectionName + ' */ ';
			}
			var wikiplusSetting = {
				"defaultSummary": wikiplusSettingdefaultSummary.toString().replace(/\s+/g, " "),
				"documatation": "http://zh.moegirl.org/User:%E5%A6%B9%E7%A9%BA%E9%85%B1/Wikiplus/%E8%AE%BE%E7%BD%AE%E8%AF%B4%E6%98%8E"
			};
			localStorage.setItem("Wikiplus_Settings", JSON.stringify(wikiplusSetting));
		})();

		/* XTools */
		mw.loader.load('https://www.mediawiki.org/w/index.php?title=XTools/ArticleInfo.js&oldid=2625658&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)

		/* FakeRollback */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/FakeRollback.js&oldid=18757250&action=raw&ctype=text/javascript'); // 11:25, 4 January 2019 (UTC)
		}

		/* AutoUndo */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/AutoUndo.js&action=raw&ctype=text/javascript'); // 08:47, 5 August 2018 (UTC)
		}

		/* cvn-smart */
		// mw.loader.load('https://xiplus.ddns.net/wikipedia_rc/gadget.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/cvn-smart-gadget.js&action=raw&ctype=text/javascript');

		/* history-merge */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) !== -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/history-merge.js&action=raw&ctype=text/javascript');
		}

		/* list-user-last-active */
		switch (mw.config.get('wgDBname')) {
			case 'zhwiki':
				break;
			default:
				mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/list-user-last-active.js&action=raw&ctype=text/javascript');
				break;
		}

		/* get-translatewiki-link */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/get-translatewiki-link.js&action=raw&ctype=text/javascript');

		/* LinkToWikidata */
		if (mw.config.get('wgDBname').match(/^zhwik|enwiki/) && mw.config.get('wgDBname') != 'zhwiki') {
			mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/LinkToWikidata.js');
		}

		/* UTC clock */
		mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript');

		/* 頂欄 */
		document.all["pt-betafeatures"].hidden = true;
		document.all["pt-logout"].hidden = true;

		/* CentralAuth */
		function showCentralAuth(username) {
			if (username === undefined) {
				return;
			}
			if (mw.util.isIPAddress(username, true)) {
				username = username.replace(/\/\d+$/, '');
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/meta/stalktoy/' + username,
					'全域封禁'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://whatismyipaddress.com/ip/' + username,
					'地理位置'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'http://whois.tanet.edu.tw/showWhoisPublic.php?queryString=' + username,
					'TANet'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/ipcheck/index.php?ip=' + username,
					'Proxy Checker'
				);
			} else {
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:CentralAuth') + '?target=' + encodeURIComponent(username),
					'全域帳號'
				);
			}
			mw.util.addPortletLink(
				'p-cactions',
				'https://tools.wmflabs.org/guc/?by=date&user=' + username,
				'全域貢獻'
			);
		}
		if (mw.config.get('wgNamespaceNumber') === 2 || mw.config.get('wgNamespaceNumber') === 3) {
			showCentralAuth(mw.config.get('wgTitle').replace(/^([^/]+).*$/, '$1'));
		} else if (mw.config.get('wgRelevantUserName') !== null) {
			showCentralAuth(mw.config.get('wgRelevantUserName'));
		} else if (mw.config.get('wgCanonicalSpecialPageName') === 'Contributions') {
			showCentralAuth($('[name="target"]').val());
		}

		/* Admin list */
		switch (mw.config.get('wgDBname')) {
			// case 'zh_classicalwiki':
			// case 'zh_yuewiki':
			case 'zhwiki':
				// case 'zhwikibooks':
				// case 'zhwikinews':
				// case 'zhwikiquote':
				// case 'zhwikisource':
				// case 'zhwikivoyage':
				// case 'zhwiktionary':
				break;
			default:
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:Userlist') + '?group=sysop',
					'管理員列表'
				);
		}

		/* Twinkle */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			// case 'simplewiki':
			case 'zh_classicalwiki':
			case 'zhwiki':
			case 'zhwikibooks':
			// case 'zhwikinews':
			case 'zhwikiquote':
			// case 'zhwikisource':
			case 'zhwikiversity':
			case 'zhwikivoyage':
			case 'zhwiktionary':
				break;
			default:
				console.log("載入 Gadget-site-lib.js");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-site-lib.js&action=raw&ctype=text/javascript');
				console.log("測試版Twinkle");
				mw.loader.using(['mediawiki.user', 'mediawiki.util', 'mediawiki.RegExp', 'mediawiki.Title', 'jquery.ui.dialog', 'jquery.tipsy']).done(function() {
					console.log("Loading");
					mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:Xiplus/Twinkle-dev.js&action=raw&ctype=text/javascript');
				});
				break;
		}

		/* Popup */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'zhwiki':
				break;
			default:
				console.log("載入 A2569875Popup");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopupsSetting_zh-hant.js&action=raw&ctype=text/javascript');
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopups.css&action=raw&ctype=text/css', 'text/css');
				break;
		}

		/* 側欄 */
		mw.util.addPortletLink(
			'p-tb',
			'/wiki/Special:PrefixIndex/' + mw.config.get('wgPageName'),
			'前綴索引',
			't-prefixindex',
			'',
			'',
			$('#t-specialpages')
		);

		mw.util.addPortletLink(
			'p-tb',
			'/wiki/?curid=' + mw.config.get('wgArticleId'),
			'短網址',
			't-shorturl',
			'',
			'',
			$('#t-info')
		);

		if (mw.config.get("wgNamespaceNumber") == 8) {
			mw.util.addPortletLink(
				'p-cactions',
				'https://translatewiki.net/wiki/' + mw.config.get("wgPageName").split("/")[0] + '/zh-hant?action=edit',
				'translatewiki'
			);
		}

		mw.loader.using(['mediawiki.api']).done(function() {
			new mw.Api().get({
				action: "query",
				format: "json",
				list: "logevents",
				leprop: "comment|type",
				letype: "delete",
				letitle: mw.config.get('wgPageName')
			}).then(function(data) {
				for (var i = 0; i < data.query.logevents.length; i++) {
					var comment = data.query.logevents[i].comment;
					console.log(comment);
				}
			});
		});

		/* mediawiki.util */
	});

	console.log("global.js end");

})();
<|endoftext|>


<commit_before>exports.log = jsio.__env.log;
exports.GLOBAL = jsio.__env.global;

var SLICE = Array.prototype.slice;

exports.isArray = function(obj) {
	return Object.prototype.toString.call(obj) === '[object Array]';
}

exports.bind = function(context, method /*, VARGS*/) {
	if(arguments.length > 2) {
		var args = SLICE.call(arguments, 2);
		return typeof method == 'string'
			? function __bound() {
				if (context[method]) {
					return context[method].apply(context, args.concat(SLICE.call(arguments, 0)));
				} else {
					throw logger.error('No method:', method, 'for context', context);
				}
			}
			: function __bound() { return method.apply(context, args.concat(SLICE.call(arguments, 0))); }
	} else {
		return typeof method == 'string'
			? function __bound() {
				if (context[method]) {
					return context[method].apply(context, arguments);
				} else {
					throw logger.error('No method:', method, 'for context', context);
				}
			}
			: function __bound() { return method.apply(context, arguments); }
	}
}

exports.Class = function(parent, proto) {
	if (typeof parent == 'string') {
		var name = arguments[0],
			parent = arguments[1],
			proto = arguments[2],
			logger = exports.logging.get(name);
	}

	if (!parent) { throw new Error('parent or prototype not provided'); }
	if (!proto) { proto = parent; parent = null; }
	else if (exports.isArray(parent)) { // multiple inheritance, use at your own risk =)
		proto.prototype = {};
		for(var i = 0, p; p = parent[i]; ++i) {
			if (p == Error && ErrorParentClass) { p = ErrorParentClass; }
			for (var item in p.prototype) {
				if (!(item in proto.prototype)) {
					proto.prototype[item] = p.prototype[item];
				}
			}
		}
		parent = parent[0];
	} else {
		if (parent == Error && ErrorParentClass) { parent = ErrorParentClass; }
		proto.prototype = parent.prototype;
	}

	var cls = function() { if (this.init) { return this.init.apply(this, arguments); }},
		supr = parent ? function(context, method, args) {
			var f = parent.prototype[method];
			if (!f) { throw new Error('method ' + method + ' does not exist'); }
			return f.apply(context, args || []);
		} : null;

	cls.prototype = new proto(logger || supr, logger && supr);
	cls.prototype.constructor = cls;
	cls.prototype.__parentClass__ = parent;
	if (name) { cls.prototype.__class__ = name; }
	return cls;
}

var ErrorParentClass = exports.Class(Error, function() {
	this.init = function() {
		var err = Error.prototype.constructor.apply(this, arguments);
		for (var prop in err) {
			if (err.hasOwnProperty(prop)) {
				this[prop] = err[prop];
			}
		}
	}
});

exports.Class.defaults =
exports.merge = function(base, extra) {
	base = base || {};

	for (var i = 1, len = arguments.length; i < len; ++i) {
		var copyFrom = arguments[i];
		for (var key in copyFrom) {
			if (copyFrom.hasOwnProperty(key) && !base.hasOwnProperty(key)) {
				base[key] = copyFrom[key];
			}
		}
	}

	return base;
}

exports.Class.ctor = function(proto, supr, defaults, post) {
	if (!supr) {
		supr = function(ctx, method, args) {
			ctx._opts = args[0];
		}
	}

	if (post) {
		proto.init = function(opts) {
			supr(this, 'init', [opts = exports.merge(opts, defaults)]);
			post.apply(this, [opts].concat(SLICE.call(arguments, 1)));
		}
	} else {
		proto.init = function(opts) {
			supr(this, 'init', [exports.merge(opts, defaults)]);
		}
	}
}

// keep logging local variables out of other closures in this file!
exports.logging = (function() {

	// logging namespace, this is what is exported
	var logging = {
			DEBUG: 1,
			LOG: 2,
			INFO: 3,
			WARN: 4,
			ERROR: 5
		},
		loggers = {}, // effectively globals - all loggers and a global production state
		production = false;
	var gPrefix = '';
	logging.setPrefix = function(prefix) { gPrefix = prefix + ' '; }
	logging.setProduction = function(prod) { production = !!prod; }
	logging.get = function(name) {
		return loggers.hasOwnProperty(name) ? loggers[name]
			: (loggers[name] = new Logger(name));
	}
	logging.set = function(name, _logger) {
		loggers[name] = _logger;
	}

	logging.getAll = function() { return loggers; }

	logging.__create = function(pkg, ctx) { ctx.logger = logging.get(pkg); }

	var Logger = exports.Class(function() {
		this.init = function(name, level) {
			this._name = name;
			this._level = level || logging.LOG;
			this._listener = exports.log;
		}

		this.setLevel = function(level) { this._level = level; }

		function makeLogFunction(level, type) {
			return function() {
				if (!production && level >= this._level) {
					var prefix = type + ' ' + gPrefix + this._name;
					if (this._listener) {
						return this._listener.apply(this._listener, [prefix].concat(SLICE.call(arguments)));
					} else {
						return function() {}
					}
				}
				return arguments[0];
			}
		}

		this.setListener = function(listener) { this._listener = listener; }
		this.debug = makeLogFunction(logging.DEBUG, "DEBUG");
		this.log = makeLogFunction(logging.LOG, "LOG");
		this.info = makeLogFunction(logging.INFO, "INFO");
		this.warn = makeLogFunction(logging.WARN, "WARN");
		this.error = makeLogFunction(logging.ERROR, "ERROR");
	});

	return logging;
})();

var logger = exports.logging.get('jsiocore');
<commit_msg>Use the overriden log function<commit_after>exports.log = jsio.__env.log;
exports.GLOBAL = jsio.__env.global;

var SLICE = Array.prototype.slice;

exports.isArray = function(obj) {
	return Object.prototype.toString.call(obj) === '[object Array]';
}

exports.bind = function(context, method /*, VARGS*/) {
	if(arguments.length > 2) {
		var args = SLICE.call(arguments, 2);
		return typeof method == 'string'
			? function __bound() {
				if (context[method]) {
					return context[method].apply(context, args.concat(SLICE.call(arguments, 0)));
				} else {
					throw logger.error('No method:', method, 'for context', context);
				}
			}
			: function __bound() { return method.apply(context, args.concat(SLICE.call(arguments, 0))); }
	} else {
		return typeof method == 'string'
			? function __bound() {
				if (context[method]) {
					return context[method].apply(context, arguments);
				} else {
					throw logger.error('No method:', method, 'for context', context);
				}
			}
			: function __bound() { return method.apply(context, arguments); }
	}
}

exports.Class = function(parent, proto) {
	if (typeof parent == 'string') {
		var name = arguments[0],
			parent = arguments[1],
			proto = arguments[2],
			logger = exports.logging.get(name);
	}

	if (!parent) { throw new Error('parent or prototype not provided'); }
	if (!proto) { proto = parent; parent = null; }
	else if (exports.isArray(parent)) { // multiple inheritance, use at your own risk =)
		proto.prototype = {};
		for(var i = 0, p; p = parent[i]; ++i) {
			if (p == Error && ErrorParentClass) { p = ErrorParentClass; }
			for (var item in p.prototype) {
				if (!(item in proto.prototype)) {
					proto.prototype[item] = p.prototype[item];
				}
			}
		}
		parent = parent[0];
	} else {
		if (parent == Error && ErrorParentClass) { parent = ErrorParentClass; }
		proto.prototype = parent.prototype;
	}

	var cls = function() { if (this.init) { return this.init.apply(this, arguments); }},
		supr = parent ? function(context, method, args) {
			var f = parent.prototype[method];
			if (!f) { throw new Error('method ' + method + ' does not exist'); }
			return f.apply(context, args || []);
		} : null;

	cls.prototype = new proto(logger || supr, logger && supr);
	cls.prototype.constructor = cls;
	cls.prototype.__parentClass__ = parent;
	if (name) { cls.prototype.__class__ = name; }
	return cls;
}

var ErrorParentClass = exports.Class(Error, function() {
	this.init = function() {
		var err = Error.prototype.constructor.apply(this, arguments);
		for (var prop in err) {
			if (err.hasOwnProperty(prop)) {
				this[prop] = err[prop];
			}
		}
	}
});

exports.Class.defaults =
exports.merge = function(base, extra) {
	base = base || {};

	for (var i = 1, len = arguments.length; i < len; ++i) {
		var copyFrom = arguments[i];
		for (var key in copyFrom) {
			if (copyFrom.hasOwnProperty(key) && !base.hasOwnProperty(key)) {
				base[key] = copyFrom[key];
			}
		}
	}

	return base;
}

exports.Class.ctor = function(proto, supr, defaults, post) {
	if (!supr) {
		supr = function(ctx, method, args) {
			ctx._opts = args[0];
		}
	}

	if (post) {
		proto.init = function(opts) {
			supr(this, 'init', [opts = exports.merge(opts, defaults)]);
			post.apply(this, [opts].concat(SLICE.call(arguments, 1)));
		}
	} else {
		proto.init = function(opts) {
			supr(this, 'init', [exports.merge(opts, defaults)]);
		}
	}
}

// keep logging local variables out of other closures in this file!
exports.logging = (function() {

	// logging namespace, this is what is exported
	var logging = {
			DEBUG: 1,
			LOG: 2,
			INFO: 3,
			WARN: 4,
			ERROR: 5
		},
		loggers = {}, // effectively globals - all loggers and a global production state
		production = false;
	var gPrefix = '';
	logging.setPrefix = function(prefix) { gPrefix = prefix + ' '; }
	logging.setProduction = function(prod) { production = !!prod; }
	logging.get = function(name) {
		return loggers.hasOwnProperty(name) ? loggers[name]
			: (loggers[name] = new Logger(name));
	}
	logging.set = function(name, _logger) {
		loggers[name] = _logger;
	}

	logging.getAll = function() { return loggers; }

	logging.__create = function(pkg, ctx) { ctx.logger = logging.get(pkg); }

	var Logger = exports.Class(function() {
		this.init = function(name, level) {
			this._name = name;
			this._level = level || logging.LOG;
			this._listener = exports.log;
		}

		this.setLevel = function(level) { this._level = level; }

		function makeLogFunction(level, type) {
			return function() {
				if (!production && level >= this._level) {
					var prefix = type + ' ' + gPrefix + this._name;
					if (this._listener) {
						return exports.log.apply(this._listener, [prefix].concat(SLICE.call(arguments)));
					} else {
						return function() {}
					}
				}
				return arguments[0];
			}
		}

		this.setListener = function(listener) { this._listener = listener; }
		this.debug = makeLogFunction(logging.DEBUG, "DEBUG");
		this.log = makeLogFunction(logging.LOG, "LOG");
		this.info = makeLogFunction(logging.INFO, "INFO");
		this.warn = makeLogFunction(logging.WARN, "WARN");
		this.error = makeLogFunction(logging.ERROR, "ERROR");
	});

	return logging;
})();

var logger = exports.logging.get('jsiocore');
<|endoftext|>


<commit_before><commit_msg>add content check guard to library page<commit_after><|endoftext|>


<commit_before>var data = [],
    lang = document.documentElement.lang,
    dataset = $("#radar").attr("dataset"),
    polygon = $("#radar").attr("polygon"),
    label = $("#radar").attr("label"),
    value = $("#radar").attr("value"),
    filters = $("#radar").attr("filters"),
    url = "http://api.staging.dataviva.info/" +
        dataset + "/year/" + polygon + "/" + label + ( filters ? "?" + filters : '');

var pageTitle = window.parent.document.querySelector('h1').childNodes[0].textContent.replace(/\s+/g,' ').trim();
var title;

if(lang == 'en')
    title = 'Economic Activity in ' + pageTitle + ' by gender';
else
    title = 'Atividade Econômica em ' + pageTitle + ' por gênero';

$('#title').html(title);

var loading = dataviva.ui.loading('.loading');
if (lang == "en") {
    loading.text('loading' + "...");
} else {
    loading.text('carregando' + "...");
}

var compare = function(a, b){
    if(a.year < b.year)
        return -1;
    if(a.year > b.year)
        return 1;

    if(a[label] < b[label])
        return -1;
    if(a[label] > b[label])
        return 1;

    return 0;
}

$(document).ready(function(){
    ajaxQueue([
        url,
        "http://api.staging.dataviva.info/metadata/" + polygon,
        "http://api.staging.dataviva.info/metadata/" + label
    ],

    function(responses){
        var json = responses[0],
            polygon_metadata = responses[1],
            label_metadata = responses[2];

        json.data.forEach(function(item, index){
            var dataItem = {};

            dataItem["year"] = item[0]
            dataItem[polygon] = item[1]
            dataItem[label] = item[2]
            dataItem["average_monthly_wage"] = +item[5]
            dataItem["jobs"] = item[6]

            data.push(dataItem);
        });

        data.map(function(item){
            item["name"] = label_metadata[item[label]]["name_" + lang];
            item[polygon] = polygon_metadata[item[polygon]]["name_" + lang];
        });

        data.sort(compare);
        loading.hide();

        var visualization = d3plus.viz()
            .container("#radar")
            .type("radar")
            .data(data)
            .id([polygon, "name"])
            .color({
                "value": polygon,
                "tooltip": "name"
            })
            .size(value)
            .time({
                "value": "year",
                "solo": []
            })
            .background("transparent")
            .format({
                "number": function(number, params) {
                    var formatted = d3plus.number.format(number, params);
                    if (params.key === "average_monthly_wage") {
                        return "$" + formatted + " USD";
                    }
                    else {
                        return formatted;
                    }
                },
                "text": function(text, params) {
                    if (text === "average_monthly_wage") {
                        return lang == 'en' ? 'Average monthly wage' : 'Salário médio mensal';
                    }
                    else if(text === "jobs") {
                        return lang == 'en' ? 'Jobs' : 'Empregos';
                    }

                    else {
                        return d3plus.string.title(text, params);
                    }

                }
            })
            .draw();
    });
});
<commit_msg>Update radar title<commit_after>var data = [],
    lang = document.documentElement.lang,
    dataset = $("#radar").attr("dataset"),
    polygon = $("#radar").attr("polygon"),
    label = $("#radar").attr("label"),
    value = $("#radar").attr("value"),
    filters = $("#radar").attr("filters"),
    url = "http://api.staging.dataviva.info/" +
        dataset + "/year/" + polygon + "/" + label + ( filters ? "?" + filters : '');

var titleHelper = {
    'jobs': {
        'en': 'Jobs in ',
        'pt': 'Empregos em '
    },
    'average_monthly_wage': {
        'en': 'Average Monthly Wage in ',
        'pt': 'Salário Médio Mensal em '
    },
    'gender': {
        'en': ' by gender',
        'pt': ' por gênero'
    },
    'pageTitle': window.parent.document.querySelector('h1').childNodes[0].textContent.replace(/\s+/g,' ').trim()
}

var title = titleHelper[value][lang] + titleHelper.pageTitle + titleHelper.gender[lang];

$('#title').html(title);

var loading = dataviva.ui.loading('.loading');
if (lang == "en") {
    loading.text('loading' + "...");
} else {
    loading.text('carregando' + "...");
}

var compare = function(a, b){
    if(a.year < b.year)
        return -1;
    if(a.year > b.year)
        return 1;

    if(a[label] < b[label])
        return -1;
    if(a[label] > b[label])
        return 1;

    return 0;
}

$(document).ready(function(){
    ajaxQueue([
        url,
        "http://api.staging.dataviva.info/metadata/" + polygon,
        "http://api.staging.dataviva.info/metadata/" + label
    ],

    function(responses){
        var json = responses[0],
            polygon_metadata = responses[1],
            label_metadata = responses[2];

        json.data.forEach(function(item, index){
            var dataItem = {};

            dataItem["year"] = item[0]
            dataItem[polygon] = item[1]
            dataItem[label] = item[2]
            dataItem["average_monthly_wage"] = +item[5]
            dataItem["jobs"] = item[6]

            data.push(dataItem);
        });

        data.map(function(item){
            item["name"] = label_metadata[item[label]]["name_" + lang];
            item[polygon] = polygon_metadata[item[polygon]]["name_" + lang];
        });

        data.sort(compare);
        loading.hide();

        var visualization = d3plus.viz()
            .container("#radar")
            .type("radar")
            .data(data)
            .id([polygon, "name"])
            .color({
                "value": polygon,
                "tooltip": "name"
            })
            .size(value)
            .time({
                "value": "year",
                "solo": []
            })
            .background("transparent")
            .format({
                "number": function(number, params) {
                    var formatted = d3plus.number.format(number, params);
                    if (params.key === "average_monthly_wage") {
                        return "$" + formatted + " USD";
                    }
                    else {
                        return formatted;
                    }
                },
                "text": function(text, params) {
                    if (text === "average_monthly_wage") {
                        return lang == 'en' ? 'Average Monthly Wage' : 'Salário Médio Mensal';
                    }
                    else if(text === "jobs") {
                        return lang == 'en' ? 'Jobs' : 'Empregos';
                    }

                    else {
                        return d3plus.string.title(text, params);
                    }

                }
            })
            .draw();
    });
});
<|endoftext|>


<commit_before>define(function(){

	/**
	 * Escape quotes, i.e. replace single quotes ' with \'.
	 *
	 * @param {String} str
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @function
	 * @memberOf StringUtils
	 */
	var escapeQuotes = function(str) {
		if (str = this.toString()) {
			return str.replaceAll('\'', '\\\'', false);
		} else if(str == ''){
			return str;
		}
		throw new Error('Error in StringUtils.escapeQuotes: This is not a string: '+ (typeof this));
	};

	/**
	 * Escape double quotes, i.e. replace quotes " with \".
	 *
	 * @param {String} str
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @memberOf StringUtils
	 */
	var escapeDoubleQuotes = function(str) {
		var str;
		if (str = this.toString()) {
			return str.replaceAll('"', '\\"', false);
		} else if(str == ''){
			return str;
		}
		throw new Error('Error in StringUtils.escapeDoubleQuotes: This is not a string: '+ (typeof this));
	};

	/**
	 * Un-escape quotes, i.e. replace escaped single quotes \' with '.
	 *
	 * @param {String} str
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @memberOf StringUtils
	 */
	var unescapeQuotes = function(str) {
		var str;
		if (str = this.toString()) {
			return str.replaceAll('\\\'', '\'', false);
		} else if(str == ''){
			return str;
		}
		throw new Error('Error in StringUtils.unescapeQuotes: This is not a string: '+ (typeof this));
	};

	/**
	 * Un-escape double quotes, i.e. replace escaped quotes \" with ".
	 *
	 * @param {String} str
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @memberOf StringUtils
	 */
	var unescapeDoubleQuotes = function () {
		var str;
		if (str = this.toString()) {
			return str.replaceAll('\\"', '"', false);
		} else if(str == ''){
			return str;
		}
		throw new Error('Error in String.unescapeDoubleQuotes: This is not a string: '+ (typeof this));
	};

	/**
	 * Custom implementation for trim():
	 * removes whitespaces from beginning and end of a String.
	 *
	 * @param {String} str
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @memberOf StringUtils
	 */
	var trim = function(str){
		return str
				.replace(/^\s\s*/, '') //remove whitespace at start...
				.replace(/\s\s*$/, '');//... and whitespaces at the end of the String
	};

	return {
		trim: trim,
		escapeQuotes: escapeQuotes,
		unescapeQuotes: unescapeQuotes,
		escapeDoubleQuotes: escapeDoubleQuotes,
		unescapeDoubleQuotes: unescapeDoubleQuotes
	};

});
<commit_msg>BUGFIX replaced use of replaceAll() by RegExpr<commit_after>define(function(){

	/**
	 * Escape quotes, i.e. replace single quotes ' with \'.
	 *
	 * @param {String} inputStr
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @function
	 * @memberOf StringUtils
	 */
	var escapeQuotes = function(inputStr) {
		if (str = inputStr.toString()) {
			return str.replace(/'/gm, '\\\'');
		} else if(str == ''){
			return str;
		}
		throw new Error('Error in StringUtils.escapeQuotes: This is not a string: '+ (typeof this));
	};

	/**
	 * Escape double quotes, i.e. replace quotes " with \".
	 *
	 * @param {String} inputStr
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @memberOf StringUtils
	 */
	var escapeDoubleQuotes = function(inputStr) {
		var str;
		if (str = inputStr.toString()) {
			return str.replace(/"/gm, '\\"');
		} else if(str == ''){
			return str;
		}
		throw new Error('Error in StringUtils.escapeDoubleQuotes: This is not a string: '+ (typeof this));
	};

	/**
	 * Un-escape quotes, i.e. replace escaped single quotes \' with '.
	 *
	 * @param {String} inputStr
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @memberOf StringUtils
	 */
	var unescapeQuotes = function(inputStr) {
		var str;
		if (str = inputStr.toString()) {
			return str.replace(/\\'/gm, '\'');
		} else if(str == ''){
			return str;
		}
		throw new Error('Error in StringUtils.unescapeQuotes: This is not a string: '+ (typeof this));
	};

	/**
	 * Un-escape double quotes, i.e. replace escaped quotes \" with ".
	 *
	 * @param {String} inputStr
	 * 			the String that will be modified
	 * @returns {String}
	 * 			the modified String
	 *
	 * @memberOf StringUtils
	 */
	var unescapeDoubleQuotes = function(inputStr) {
		var str;
		if (str = inputStr.toString()) {
			return str.replace(/\\"/gm, '"');
		} else if(str == ''){
			return str;
		}
		throw new Error('Error in String.unescapeDoubleQuotes: This is not a string: '+ (typeof this));
	};

	/**
	 * HTML-Encode the supplied input
	 *
	 * Parameters:
	 *
	 * @param {string} source
	 *                     The text to be encoded.
	 *
	 * @param {boolean} [display]
	 *                     (optional)
	 *                     The output is intended for display.
	 *
	 *                     If true (or undefined):
	 *                     * Tabs will be expanded to the number of spaces
	 *                       indicated by the 'tabs' argument.
	 *                     * Line breaks will be converted to
.
	 *
	 *                     If false:
	 *                     * Tabs and linebreaks get turned into &#____;
	 *                       entities just like all other control characters.
	 *
	 * @param {number} [tabs]
	 *                     (optional)
	 *                     The number of spaces to expand tabs to.
	 *                     (Ignored if the 'display' parameter evaluates to false
	 *                      or if tabs is not >= 0.)
	 *
	 *                     Default: undefined (do not replace tabs with spaces)
	 *
	 * version 2010-11-08 (modified: 2012-12-20)
	 *
	 * @memberOf StringUtils
	 */
	var htmlEncode = function (source, display, tabs) {
		var i, s, ch, peek, line, result,
		next, endline, push,
		spaces;

		//'parse' parameters
		if(typeof display === 'number'){
			//use as tabs-parameter
			tabs = display;
			display = true;
		} else if(typeof display === 'undefined'){
			display = true;
		}
		if(typeof tabs === 'string'){
			tabs = parseInt(tabs,10);
		} else if(typeof tabs === 'number'){
			tabs = Math.floor(tabs);
		} else {
			tabs = -1;
		}

		// Stash the next character and advance the pointer
		next = function () {
			peek = source.charAt(i);
			i += 1;
		};

		// Start a new "line" of output, to be joined later by

		endline = function () {
			line = line.join('');
			if (display) {
				// If a line starts or ends with a space, it evaporates in html
				// unless it's an nbsp.
				line = line.replace(/(^ )|( $)/g, ' ');
			}
			result.push(line);
			line = [];
		};

		// Push a character or its entity onto the current line
		push = function () {
			if (ch < ' ' || ch > '~') {
				line.push('&#' + ch.charCodeAt(0) + ';');
			} else {
				line.push(ch);
			}
		};

		result = [];
		line = [];

		i = 0;
		next();
		while (i <= source.length) { // less than or equal, because i is always one ahead
			ch = peek;
			next();

			// HTML special chars.
			switch (ch) {
			case '<':
				line.push('<');
				break;
			case '>':
				line.push('>');
				break;
			case '&':
				line.push('&');
				break;
			case '"':
				line.push('"');
				break;
			case "'":
				line.push(''');
				break;
			default:
				// If the output is intended for display,
				// then end lines on newlines, and replace tabs with spaces.
				if (display) {
					switch (ch) {
					case '\r':
						// If this \r is the beginning of a \r\n, skip over the \n part.
						if (peek === '\n') {
							next();
						}
						endline();
						break;
					case '\n':
						endline();
						break;
					case '\t':
						// expand tabs?
						if(tabs >= 0){
							spaces = tabs - (line.length % tabs);
							for (s = 0; s < spaces; s += 1) {
								line.push(' ');
							}
						} else{
							//otherwise: preserve tabs
							push('	');
						}
						break;
					default:
						// All other characters can be dealt with generically.
						push();
					}
				} else {
					// If the output is not for display,
					// then none of the characters need special treatment.
					push();
				}
			}
		}
		endline();

		// If you can't beat 'em, join 'em.
		result = result.join('
');

		if (display) {
			// Break up contiguous blocks of spaces with non-breaking spaces
			result = result.replace(/ {2}/g, '  ');
		}

		// tada!
		return result;
	};

	return {
		htmlEncode: htmlEncode,
		escapeQuotes: escapeQuotes,
		unescapeQuotes: unescapeQuotes,
		escapeDoubleQuotes: escapeDoubleQuotes,
		unescapeDoubleQuotes: unescapeDoubleQuotes
	};

});
<|endoftext|>


<commit_before>//bind pager controls to our addon grids
$('.island .listing-grid').bind('grid.init', function(e, data) {
    var $grid = data.self,
        numPages = data.maxPage;

    if (numPages > 0) {
        var $nav = $('');
        $nav.append('«');
        for (var i=0; i<=numPages; i++) {
            $nav.append('');
        }
        $nav.append('»');
        $grid.parent().prepend($nav);
        $nav.delegate('a', 'click', function(e) {
            e.preventDefault();
            var $tgt = $(this);
            if ($tgt.hasClass('dot')) {
                $grid.go($tgt.index() - 1);
            } else if ($tgt.hasClass('prev')){
                $grid.prevPage();
            } else if ($tgt.hasClass('next')){
                $grid.nextPage();
            }
        });
        $grid.bind('grid.update', function(e, data) {
            $nav.find('.dot').removeClass('selected')
                .eq(data.current).addClass('selected');
        });
    }
});

z.visitor = z.Storage('visitor');
z.currentVisit = z.SessionStorage('current-visit');
(function() {
    // Show the bad-browser message if it has not been dismissed
    if (!z.visitor.get('seen_badbrowser_warning') && $('body').hasClass('badbrowser')) {
        $('#site-nonfx').show();
    }
})();

function hoverTruncate(grid) {
    var $grid = $(grid);
    if ($grid.hasClass('hovercard')) {
        $grid = $grid.parent();
    }
    $grid.find('.hovercard h3').truncate();
    $grid.delegate('.hovercard', 'mouseover', function() {
        var $el = $(this);
        setTimeout(function() {
            $el.find('h3').untruncate();
        }, 100);
    }).delegate('.hovercard', 'mouseout', function() {
        var $el = $(this);
        setTimeout(function() {
            $el.find('h3').truncate();
        }, 100);
    });
}

function listing_grid() {
    var $grid = $(this),
        $pages = $grid.find('section'),
        current = 0,
        maxPage = $pages.length-1;
    $grid.trigger("grid.init", {self: $grid, current: current, maxPage: maxPage});
    $grid.go = function(n) {
        if (n != current) {
            n = n < 0 ? 0 : (n > maxPage ? maxPage : n);
            current = n;
            $pages.hide().eq(n).show().find('.hovercard h3').truncate();
            $grid.trigger("grid.update", {self: $grid, current: current, maxPage: maxPage});
        }
    };
    $grid.prevPage = function() {
        $grid.go(current-1);
    };
    $grid.nextPage = function() {
        $grid.go(current+1);
    };
    hoverTruncate(this);
    $grid.css({
        'width': $grid.width() + 'px',
        'height': $grid.height() + 'px'
    });
    return $grid;
}

$(function() {
    "use strict";

    initBanners();

    // Paginate listing grids.
    $('.listing-grid').each(listing_grid);

    // Truncate titles on single hovercards.
    $('.hovercard').each(function() {
        hoverTruncate(this);
    });

    // load deferred images.
    $('img[data-defer-src]').each(function() {
        var $img = $(this);
        $img.attr('src', $img.attr('data-defer-src'));
    });

    // Email obfuscation.
    $('span.emaillink').each(function() {
        var $this = $(this);
        $this.find('.i').remove();
        var em = $this.text().split('').reverse().join('');
        $this.prev('a').attr('href', 'mailto:' + em);
        // Allows the email to be selected and pasted in webmails, see #919160.
        $this.text(em).css('direction', 'ltr');
    });

    $('#page').delegate('.expando .toggle', 'click', _pd(function() {
        $(this).closest('.expando').toggleClass('expanded');
    }));

    if (window.location.hash) {
        // If the page URL is pointing directly to an expando section (e.g.
        // external link to that section), make sure the contents are visible.
        var $target = $(window.location.hash);
        if ($target.hasClass('expando'))
            $target.addClass('expanded');
    }

    $('#page').delegate('.scrollto', 'click', function(e) {
        e.preventDefault();
        var href = $(this).attr('href'),
            $target = $(href.match(/#.*$/)[0]);
        if ($target.hasClass('expando')) {
            $target.addClass('expanded');
        }
        var top = $target.offset().top - 15;
        $(document.documentElement).animate({ scrollTop: top }, 500);
    });

    contributions.init();

    $("select[name='rating']").ratingwidget();
});

function initBanners(delegate) {
    var $delegate = $(delegate || document.body);

    // Show the first visit banner.
    if (!z.visitor.get('seen_impala_first_visit')) {
        $('body').addClass('firstvisit');
        z.visitor.set('seen_impala_first_visit', 1);
    }
    // Show the FxA migration banner (potentially).
    if (!z.currentVisit.get('seen_fxa_migration_banner')) {
        $('body').addClass('show-fxa-migration-banner');
    }

    // Show the ACR pitch if it has not been dismissed.
    if (!z.visitor.get('seen_acr_pitch') && $('body').hasClass('acr-pitch')) {
        $delegate.find('#acr-pitch').show();
    }

    // Allow dismissal of site-balloons.
    $delegate.delegate('.site-balloon .close, .site-tip .close', 'click', _pd(function() {
        var $parent = $(this).closest('.site-balloon, .site-tip');
        $parent.fadeOut();
        if ($parent.is('#site-nonfx')) {
            z.visitor.set('seen_badbrowser_warning', 1);
        } else if ($parent.is('#acr-pitch')) {
            z.visitor.set('seen_acr_pitch', 1);
        } else if ($parent.is('#appruntime-pitch')) {
            z.visitor.set('seen_appruntime_pitch', 1);
        } else if ($parent.is('#fxa-migration-banner')) {
            z.currentVisit.set('seen_fxa_migration_banner', 1);
        }
    }));
}

// AJAX form submit

$(function() {
  $('form.ajax-submit, .ajax-submit form').live('submit', function() {
      var $form = $(this),
          $parent = $form.is('.ajax-submit') ? $form : $form.closest('.ajax-submit'),
          params = $form.serializeArray();

      $form.find('.submit, button[type=submit], submit').attr('disabled', true).addClass('loading-submit');
      $.post($form.attr('action'), params, function(d) {
          var $replacement = $(d);
          $parent.replaceWith($replacement);
          $replacement.trigger('ajax-submit-loaded');
          $replacement.find('.ajax-submit').trigger('ajax-submit-loaded');
      });
      return false;
  });
});

$(function() {
    "use strict";

    $(document).ready(function() {
        stick.basic();
    });
});
<commit_msg>Remove the offending stick<commit_after>//bind pager controls to our addon grids
$('.island .listing-grid').bind('grid.init', function(e, data) {
    var $grid = data.self,
        numPages = data.maxPage;

    if (numPages > 0) {
        var $nav = $('');
        $nav.append('«');
        for (var i=0; i<=numPages; i++) {
            $nav.append('');
        }
        $nav.append('»');
        $grid.parent().prepend($nav);
        $nav.delegate('a', 'click', function(e) {
            e.preventDefault();
            var $tgt = $(this);
            if ($tgt.hasClass('dot')) {
                $grid.go($tgt.index() - 1);
            } else if ($tgt.hasClass('prev')){
                $grid.prevPage();
            } else if ($tgt.hasClass('next')){
                $grid.nextPage();
            }
        });
        $grid.bind('grid.update', function(e, data) {
            $nav.find('.dot').removeClass('selected')
                .eq(data.current).addClass('selected');
        });
    }
});

z.visitor = z.Storage('visitor');
z.currentVisit = z.SessionStorage('current-visit');
(function() {
    // Show the bad-browser message if it has not been dismissed
    if (!z.visitor.get('seen_badbrowser_warning') && $('body').hasClass('badbrowser')) {
        $('#site-nonfx').show();
    }
})();

function hoverTruncate(grid) {
    var $grid = $(grid);
    if ($grid.hasClass('hovercard')) {
        $grid = $grid.parent();
    }
    $grid.find('.hovercard h3').truncate();
    $grid.delegate('.hovercard', 'mouseover', function() {
        var $el = $(this);
        setTimeout(function() {
            $el.find('h3').untruncate();
        }, 100);
    }).delegate('.hovercard', 'mouseout', function() {
        var $el = $(this);
        setTimeout(function() {
            $el.find('h3').truncate();
        }, 100);
    });
}

function listing_grid() {
    var $grid = $(this),
        $pages = $grid.find('section'),
        current = 0,
        maxPage = $pages.length-1;
    $grid.trigger("grid.init", {self: $grid, current: current, maxPage: maxPage});
    $grid.go = function(n) {
        if (n != current) {
            n = n < 0 ? 0 : (n > maxPage ? maxPage : n);
            current = n;
            $pages.hide().eq(n).show().find('.hovercard h3').truncate();
            $grid.trigger("grid.update", {self: $grid, current: current, maxPage: maxPage});
        }
    };
    $grid.prevPage = function() {
        $grid.go(current-1);
    };
    $grid.nextPage = function() {
        $grid.go(current+1);
    };
    hoverTruncate(this);
    $grid.css({
        'width': $grid.width() + 'px',
        'height': $grid.height() + 'px'
    });
    return $grid;
}

$(function() {
    "use strict";

    initBanners();

    // Paginate listing grids.
    $('.listing-grid').each(listing_grid);

    // Truncate titles on single hovercards.
    $('.hovercard').each(function() {
        hoverTruncate(this);
    });

    // load deferred images.
    $('img[data-defer-src]').each(function() {
        var $img = $(this);
        $img.attr('src', $img.attr('data-defer-src'));
    });

    // Email obfuscation.
    $('span.emaillink').each(function() {
        var $this = $(this);
        $this.find('.i').remove();
        var em = $this.text().split('').reverse().join('');
        $this.prev('a').attr('href', 'mailto:' + em);
        // Allows the email to be selected and pasted in webmails, see #919160.
        $this.text(em).css('direction', 'ltr');
    });

    $('#page').delegate('.expando .toggle', 'click', _pd(function() {
        $(this).closest('.expando').toggleClass('expanded');
    }));

    if (window.location.hash) {
        // If the page URL is pointing directly to an expando section (e.g.
        // external link to that section), make sure the contents are visible.
        var $target = $(window.location.hash);
        if ($target.hasClass('expando'))
            $target.addClass('expanded');
    }

    $('#page').delegate('.scrollto', 'click', function(e) {
        e.preventDefault();
        var href = $(this).attr('href'),
            $target = $(href.match(/#.*$/)[0]);
        if ($target.hasClass('expando')) {
            $target.addClass('expanded');
        }
        var top = $target.offset().top - 15;
        $(document.documentElement).animate({ scrollTop: top }, 500);
    });

    contributions.init();

    $("select[name='rating']").ratingwidget();
});

function initBanners(delegate) {
    var $delegate = $(delegate || document.body);

    // Show the first visit banner.
    if (!z.visitor.get('seen_impala_first_visit')) {
        $('body').addClass('firstvisit');
        z.visitor.set('seen_impala_first_visit', 1);
    }
    // Show the FxA migration banner (potentially).
    if (!z.currentVisit.get('seen_fxa_migration_banner')) {
        $('body').addClass('show-fxa-migration-banner');
    }

    // Show the ACR pitch if it has not been dismissed.
    if (!z.visitor.get('seen_acr_pitch') && $('body').hasClass('acr-pitch')) {
        $delegate.find('#acr-pitch').show();
    }

    // Allow dismissal of site-balloons.
    $delegate.delegate('.site-balloon .close, .site-tip .close', 'click', _pd(function() {
        var $parent = $(this).closest('.site-balloon, .site-tip');
        $parent.fadeOut();
        if ($parent.is('#site-nonfx')) {
            z.visitor.set('seen_badbrowser_warning', 1);
        } else if ($parent.is('#acr-pitch')) {
            z.visitor.set('seen_acr_pitch', 1);
        } else if ($parent.is('#appruntime-pitch')) {
            z.visitor.set('seen_appruntime_pitch', 1);
        } else if ($parent.is('#fxa-migration-banner')) {
            z.currentVisit.set('seen_fxa_migration_banner', 1);
        }
    }));
}

// AJAX form submit

$(function() {
  $('form.ajax-submit, .ajax-submit form').live('submit', function() {
      var $form = $(this),
          $parent = $form.is('.ajax-submit') ? $form : $form.closest('.ajax-submit'),
          params = $form.serializeArray();

      $form.find('.submit, button[type=submit], submit').attr('disabled', true).addClass('loading-submit');
      $.post($form.attr('action'), params, function(d) {
          var $replacement = $(d);
          $parent.replaceWith($replacement);
          $replacement.trigger('ajax-submit-loaded');
          $replacement.find('.ajax-submit').trigger('ajax-submit-loaded');
      });
      return false;
  });
});
<|endoftext|>


<commit_before>'use strict'

const os = require('os')
const fs = require('fs')
const path = require('path')
const SimplyImitatedSQS = require('../simply_imitated_sqs')

/* global describe, test, expect, beforeEach, afterEach */
describe('simply_imitated_sqs', () => {
  let sqs = null
  beforeEach(() => {
    sqs = new SimplyImitatedSQS()
  })
  afterEach(() => sqs.clear())

  test('sqs is instanceOf SimplyImitatedSQS', () => {
    expect(sqs).toBeInstanceOf(SimplyImitatedSQS)
  })

  describe('defaultDbFile()', () => {
    test('File path including pid', () => {
      expect(sqs.defaultDbFile())
      .toMatch(/SimplyImitatedSQS-\d{1,}\.json/)
    })
  })

  describe('sqs.dbFile variable', () => {
    test('File path including pid', () => {
      expect(sqs.dbFile)
      .toMatch(/SimplyImitatedSQS-\d{1,}\.json/)
    })

    test('Specify file path at instance creation', () => {
      const filePath = path.join(os.tmpdir(), 'SimplyImitatedSQS-test.json')
      sqs = new SimplyImitatedSQS(filePath)
      expect(sqs.dbFile).toBe(filePath)
    })
  })

  describe('reload() and clear()', () => {
    test('Remove the file with clear and delete vsq. Recreate with reload', () => {
      const dbFile = sqs.dbFile
      expect(fs.existsSync(dbFile)).toBeTruthy()

      sqs.clear()
      expect(fs.existsSync(dbFile)).toBeFalsy()
      expect(sqs.vsq).toBeUndefined()

      sqs.reload()
      expect(fs.existsSync(dbFile)).toBeTruthy()
      expect(sqs.vsq).toBeDefined()
    })

    test('Exceptions do not occur even if clear() is executed continuously', () => {
      const func = () => {
        sqs.clear()
        sqs.clear()
        return true
      }
      expect(func()).toBeTruthy()
    })
  })

  describe('md5_(str)', () => {
    test('value of md5', () => {
      expect(sqs.md5_('hoge')).toBe('ea703e7aa1efda0064eaa507d9e8ab7e')
    })
  })

  describe('eventEmitter_(err, data)', () => {
    test('EventEmitter', () => {
      const eventEmitter = sqs.eventEmitter_()
      eventEmitter.on('test', (value) => {
        expect(value).toBe('piyo')
      })
      eventEmitter.emit('test', 'piyo')
    })

    test('promise()', () => {
      const eventEmitter = sqs.eventEmitter_(null, 'piyo')
      return eventEmitter.promise().then(data => {
        expect(data).toBe('piyo')
      })
    })
  })

  describe('sendMessage()', () => {
    const params = {
      QueueUrl: 'QueueUrl',
      MessageBody: 'hoge'
    }

    const expected = {
      ResponseMetadata: {
        RequestId: 'SimplyImitatedSQS-RequestId'
      },
      MD5OfMessageBody: 'ea703e7aa1efda0064eaa507d9e8ab7e',
      MessageId: 'SimplyImitatedSQS-MessageId'
    }

    test('Return value', () => {
      sqs.sendMessage(params, (err, data) => {
        expect(err).toBeNull()
        expect(data).toEqual(expected)
      })
    })

    test('Return value (promise)', () => {
      return sqs.sendMessage(params).promise().then(data => {
        expect(data).toEqual(expected)
      }).catch((err) => {
        // When entering here is abnormal
        expect(err).toBeNull()
      })
    })
  })

  describe('sendMessageBatch()', () => {
    const params = {
      QueueUrl: 'QueueUrl',
      Entries: [{
        MessageBody: '1',
        Id: 'a'
      }, {
        MessageBody: '2',
        Id: 'b'
      }]
    }

    const expected = {
      ResponseMetadata: {
        RequestId: 'SimplyImitatedSQS-RequestId'
      },
      Successful: [{
        Id: 'a',
        MessageId: 'SimplyImitatedSQS-MessageId-0',
        MD5OfMessageBody: 'c4ca4238a0b923820dcc509a6f75849b'
      }, {
        Id: 'b',
        MessageId: 'SimplyImitatedSQS-MessageId-1',
        MD5OfMessageBody: 'c81e728d9d4c2f636f067f89cc14862c'
      }],
      Failed: []
    }

    test('Return value', () => {
      sqs.sendMessageBatch(params, (err, data) => {
        expect(err).toBeNull()
        expect(data).toEqual(expected)
      })
    })

    test('Return value (promise)', () => {
      return sqs.sendMessageBatch(params).promise().then(data => {
        expect(data).toEqual(expected)
      }).catch((err) => {
        // When entering here is abnormal
        expect(err).toBeNull()
      })
    })
  })

  describe('receiveMessage()', () => {
    const sendMessageParams = {
      QueueUrl: 'QueueUrl',
      MessageBody: 'hoge'
    }
    const receiveMessageParams = {QueueUrl: 'QueueUrl'}

    const expected = (receiptHandle) => {
      return {
        ResponseMetadata: {
          RequestId: 'SimplyImitatedSQS-RequestId'
        },
        Messages: [{
          MessageId: 'SimplyImitatedSQS-MessageId',
          ReceiptHandle: receiptHandle,
          MD5OfBody: 'ea703e7aa1efda0064eaa507d9e8ab7e',
          Body: 'hoge'
        }]
      }
    }

    test('Return value', () => {
      sqs.sendMessage(sendMessageParams, (err, data) => {
        expect(err).toBeNull()
        expect(data).toBeDefined()

        sqs.receiveMessage(receiveMessageParams, (err, data) => {
          const receiptHandle = Object.keys(sqs.vsq.data.value)[0]
          expect(err).toBeNull()
          expect(data).toEqual(expected(receiptHandle))
        })
      })
    })

    test('Return value (promise)', () => {
      return sqs.sendMessage(sendMessageParams).promise().then(data => {
        expect(data).toBeDefined()
        return data
      }).then(data => {
        return sqs.receiveMessage(receiveMessageParams).promise().then(data => {
          const receiptHandle = Object.keys(sqs.vsq.data.value)[0]
          expect(data).toEqual(expected(receiptHandle))
        })
      }).catch((err) => {
        // When entering here is abnormal
        expect(err).toBeNull()
      })
    })
  })

  describe('deleteMessage()', () => {
    const sendMessageParams = {
      QueueUrl: 'QueueUrl',
      MessageBody: 'hoge'
    }
    const deleteMessageParams = (receiptHandle) => {
      return {
        QueueUrl: 'QueueUrl',
        ReceiptHandle: receiptHandle
      }
    }

    const expected = {
      ResponseMetadata: {
        RequestId: 'SimplyImitatedSQS-RequestId'
      }
    }

    test('Return value', () => {
      sqs.sendMessage(sendMessageParams, (err, data) => {
        expect(err).toBeNull()
        expect(data).toBeDefined()

        const receiptHandle = Object.keys(sqs.vsq.data.value)[0]
        sqs.deleteMessage(deleteMessageParams(receiptHandle), (err, data) => {
          expect(err).toBeNull()
          expect(data).toEqual(expected)
        })
      })
    })

    test('Return value (promise)', () => {
      return sqs.sendMessage(sendMessageParams).promise().then(data => {
        expect(data).toBeDefined()
        return data
      }).then(data => {
        const receiptHandle = Object.keys(sqs.vsq.data.value)[0]
        return sqs.deleteMessage(deleteMessageParams(receiptHandle))
          .promise()
          .then(data => {
            expect(data).toEqual(expected)
          })
      }).catch((err) => {
        // When entering here is abnormal
        expect(err).toBeNull()
      })
    })
  })
})
<commit_msg>Fix a bug that the DB file used in the test remained<commit_after>'use strict'

const os = require('os')
const fs = require('fs')
const path = require('path')
const SimplyImitatedSQS = require('../simply_imitated_sqs')

/* global describe, test, expect, beforeEach, afterEach */
describe('simply_imitated_sqs', () => {
  let sqs = null
  beforeEach(() => {
    sqs = new SimplyImitatedSQS()
  })
  afterEach(() => sqs.clear())

  test('sqs is instanceOf SimplyImitatedSQS', () => {
    expect(sqs).toBeInstanceOf(SimplyImitatedSQS)
  })

  describe('defaultDbFile()', () => {
    test('File path including pid', () => {
      expect(sqs.defaultDbFile())
      .toMatch(/SimplyImitatedSQS-\d{1,}\.json/)
    })
  })

  describe('sqs.dbFile variable', () => {
    test('File path including pid', () => {
      expect(sqs.dbFile)
      .toMatch(/SimplyImitatedSQS-\d{1,}\.json/)
    })

    test('Specify file path at instance creation', () => {
      const filePath = path.join(os.tmpdir(), 'SimplyImitatedSQS-test.json')
      const _sqs = new SimplyImitatedSQS(filePath)
      expect(_sqs.dbFile).toBe(filePath)
      _sqs.clear()
    })
  })

  describe('reload() and clear()', () => {
    test('Remove the file with clear and delete vsq. Recreate with reload', () => {
      const dbFile = sqs.dbFile
      expect(fs.existsSync(dbFile)).toBeTruthy()

      sqs.clear()
      expect(fs.existsSync(dbFile)).toBeFalsy()
      expect(sqs.vsq).toBeUndefined()

      sqs.reload()
      expect(fs.existsSync(dbFile)).toBeTruthy()
      expect(sqs.vsq).toBeDefined()
    })

    test('Exceptions do not occur even if clear() is executed continuously', () => {
      const func = () => {
        sqs.clear()
        sqs.clear()
        return true
      }
      expect(func()).toBeTruthy()
    })
  })

  describe('md5_(str)', () => {
    test('value of md5', () => {
      expect(sqs.md5_('hoge')).toBe('ea703e7aa1efda0064eaa507d9e8ab7e')
    })
  })

  describe('eventEmitter_(err, data)', () => {
    test('EventEmitter', () => {
      const eventEmitter = sqs.eventEmitter_()
      eventEmitter.on('test', (value) => {
        expect(value).toBe('piyo')
      })
      eventEmitter.emit('test', 'piyo')
    })

    test('promise()', () => {
      const eventEmitter = sqs.eventEmitter_(null, 'piyo')
      return eventEmitter.promise().then(data => {
        expect(data).toBe('piyo')
      })
    })
  })

  describe('sendMessage()', () => {
    const params = {
      QueueUrl: 'QueueUrl',
      MessageBody: 'hoge'
    }

    const expected = {
      ResponseMetadata: {
        RequestId: 'SimplyImitatedSQS-RequestId'
      },
      MD5OfMessageBody: 'ea703e7aa1efda0064eaa507d9e8ab7e',
      MessageId: 'SimplyImitatedSQS-MessageId'
    }

    test('Return value', () => {
      sqs.sendMessage(params, (err, data) => {
        expect(err).toBeNull()
        expect(data).toEqual(expected)
      })
    })

    test('Return value (promise)', () => {
      return sqs.sendMessage(params).promise().then(data => {
        expect(data).toEqual(expected)
      }).catch((err) => {
        // When entering here is abnormal
        expect(err).toBeNull()
      })
    })
  })

  describe('sendMessageBatch()', () => {
    const params = {
      QueueUrl: 'QueueUrl',
      Entries: [{
        MessageBody: '1',
        Id: 'a'
      }, {
        MessageBody: '2',
        Id: 'b'
      }]
    }

    const expected = {
      ResponseMetadata: {
        RequestId: 'SimplyImitatedSQS-RequestId'
      },
      Successful: [{
        Id: 'a',
        MessageId: 'SimplyImitatedSQS-MessageId-0',
        MD5OfMessageBody: 'c4ca4238a0b923820dcc509a6f75849b'
      }, {
        Id: 'b',
        MessageId: 'SimplyImitatedSQS-MessageId-1',
        MD5OfMessageBody: 'c81e728d9d4c2f636f067f89cc14862c'
      }],
      Failed: []
    }

    test('Return value', () => {
      sqs.sendMessageBatch(params, (err, data) => {
        expect(err).toBeNull()
        expect(data).toEqual(expected)
      })
    })

    test('Return value (promise)', () => {
      return sqs.sendMessageBatch(params).promise().then(data => {
        expect(data).toEqual(expected)
      }).catch((err) => {
        // When entering here is abnormal
        expect(err).toBeNull()
      })
    })
  })

  describe('receiveMessage()', () => {
    const sendMessageParams = {
      QueueUrl: 'QueueUrl',
      MessageBody: 'hoge'
    }
    const receiveMessageParams = {QueueUrl: 'QueueUrl'}

    const expected = (receiptHandle) => {
      return {
        ResponseMetadata: {
          RequestId: 'SimplyImitatedSQS-RequestId'
        },
        Messages: [{
          MessageId: 'SimplyImitatedSQS-MessageId',
          ReceiptHandle: receiptHandle,
          MD5OfBody: 'ea703e7aa1efda0064eaa507d9e8ab7e',
          Body: 'hoge'
        }]
      }
    }

    test('Return value', () => {
      sqs.sendMessage(sendMessageParams, (err, data) => {
        expect(err).toBeNull()
        expect(data).toBeDefined()

        sqs.receiveMessage(receiveMessageParams, (err, data) => {
          const receiptHandle = Object.keys(sqs.vsq.data.value)[0]
          expect(err).toBeNull()
          expect(data).toEqual(expected(receiptHandle))
        })
      })
    })

    test('Return value (promise)', () => {
      return sqs.sendMessage(sendMessageParams).promise().then(data => {
        expect(data).toBeDefined()
        return data
      }).then(data => {
        return sqs.receiveMessage(receiveMessageParams).promise().then(data => {
          const receiptHandle = Object.keys(sqs.vsq.data.value)[0]
          expect(data).toEqual(expected(receiptHandle))
        })
      }).catch((err) => {
        // When entering here is abnormal
        expect(err).toBeNull()
      })
    })
  })

  describe('deleteMessage()', () => {
    const sendMessageParams = {
      QueueUrl: 'QueueUrl',
      MessageBody: 'hoge'
    }
    const deleteMessageParams = (receiptHandle) => {
      return {
        QueueUrl: 'QueueUrl',
        ReceiptHandle: receiptHandle
      }
    }

    const expected = {
      ResponseMetadata: {
        RequestId: 'SimplyImitatedSQS-RequestId'
      }
    }

    test('Return value', () => {
      sqs.sendMessage(sendMessageParams, (err, data) => {
        expect(err).toBeNull()
        expect(data).toBeDefined()

        const receiptHandle = Object.keys(sqs.vsq.data.value)[0]
        sqs.deleteMessage(deleteMessageParams(receiptHandle), (err, data) => {
          expect(err).toBeNull()
          expect(data).toEqual(expected)
        })
      })
    })

    test('Return value (promise)', () => {
      return sqs.sendMessage(sendMessageParams).promise().then(data => {
        expect(data).toBeDefined()
        return data
      }).then(data => {
        const receiptHandle = Object.keys(sqs.vsq.data.value)[0]
        return sqs.deleteMessage(deleteMessageParams(receiptHandle))
          .promise()
          .then(data => {
            expect(data).toEqual(expected)
          })
      }).catch((err) => {
        // When entering here is abnormal
        expect(err).toBeNull()
      })
    })
  })
})
<|endoftext|>


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

  let RegExpTokenizer = function() { };
  let prototype = RegExpTokenizer.prototype;

  RegExpTokenizer.ESCAPE_CHAR_TYPES = [
    "ControlEscape",
    "ControlLetterEscape",
    "HexEscapeSequence",
    "UnicodeEscapeSequence",
    "IdentityEscape",
    "CharacterClassEscape"
  ];

  RegExpTokenizer.ESCAPE_CHARS = {
    "f": 0,
    "n": 0,
    "r": 0,
    "t": 0,
    "v": 0,
    "c": 1,
    "x": 2,
    "u": 3,
    "d": 5,
    "D": 5,
    "s": 5,
    "S": 5,
    "w": 5,
    "W": 5
  };

  RegExpTokenizer.ESCACPE_CHAR_CODES = {
    "0" : 0,
    "t" : 9,
    "n" : 10,
    "v" : 11,
    "f" : 12,
    "r" : 13
  };

  prototype.token = null;
  prototype.capturingGroups = [];

  prototype.tokenize = function(str) {
    function token(type, start, end, additionalProps) {
      this.type = type;
      if (additionalProps) {
        let self = this;
        Object.getOwnPropertyNames(additionalProps).forEach(function mapPropNames(name) {
          self[name] = additionalProps[name];
        });
      }
      this.loc = {
        start: start,
        end: end || start + 1
      }
    }

    let length = str.length;
    let i = 0;
    let ast = new token("RegularExpression", i, length, {body: []});
    let parent = ast.body;
    let currentToken = null;
    while (i < length) {
      let char = str.charAt(i);
      let addToParent = true;

      if (char === "\\") {
        currentToken = new token("", i);
        this.parseEscapeSequence(str, currentToken);
      } else {
        if (currentToken && currentToken.type === "Literal") {
          currentToken.value += char;
          currentToken.loc.end++;
          addToParent = false;
        } else {
          currentToken = new token("Literal", i, null, {value: char});
        }
      }

      if (addToParent) {
        if (Array.isArray(parent)) {
          parent.push(currentToken);
        } else {
          parent = currentToken;
        }
      }

      i = currentToken.loc.end;
    }

    this.token = ast;

    return ast;
  };

  prototype.parseEscapeSequence = function(str, token) {
    let escapeCharType = RegExpTokenizer.ESCAPE_CHARS[str[token.loc.end]];
    if (escapeCharType === undefined)
      escapeCharType = 4;
    token.type = RegExpTokenizer.ESCAPE_CHAR_TYPES[escapeCharType];
    switch (token.type) {
      case "ControlEscape":
      case "IdentityEscape":
      case "CharacterClassEscape":
        token.char = str[token.loc.end];
        if (token.type == "ControlEscape") {
          token.value = RegExpTokenizer.ESCACPE_CHAR_CODES[token.char];
        }
        token.loc.end++;
        break;

      case "ControlLetterEscape":
        token.char = str[token.loc.end + 1];
        token.value = token.char.charCodeAt(0) - 64;
        token.loc.end += 2;
        break;

      case "HexEscapeSequence":
        token.sequence = str.substr(token.loc.end + 1, 2);
        token.loc.end += 3;
        break;

      case "UnicodeEscapeSequence":
        token.sequence = str.substr(token.loc.end + 1, 4);
        token.loc.end += 5;
        break;
    }

    return;
  };

  window.RegExpTokenizer = RegExpTokenizer;
})();<commit_msg>Added parsing of 'any character' dot<commit_after>(function () {
  "use strict";

  let RegExpTokenizer = function() { };
  let prototype = RegExpTokenizer.prototype;

  RegExpTokenizer.ESCAPE_CHAR_TYPES = [
    "ControlEscape",
    "ControlLetterEscape",
    "HexEscapeSequence",
    "UnicodeEscapeSequence",
    "IdentityEscape",
    "CharacterClassEscape"
  ];

  RegExpTokenizer.ESCAPE_CHARS = {
    "f": 0,
    "n": 0,
    "r": 0,
    "t": 0,
    "v": 0,
    "c": 1,
    "x": 2,
    "u": 3,
    "d": 5,
    "D": 5,
    "s": 5,
    "S": 5,
    "w": 5,
    "W": 5
  };

  RegExpTokenizer.ESCACPE_CHAR_CODES = {
    "0" : 0,
    "t" : 9,
    "n" : 10,
    "v" : 11,
    "f" : 12,
    "r" : 13
  };

  prototype.token = null;
  prototype.capturingGroups = [];

  prototype.tokenize = function(str) {
    function token(type, start, end, additionalProps) {
      this.type = type;
      if (additionalProps) {
        let self = this;
        Object.getOwnPropertyNames(additionalProps).forEach(function mapPropNames(name) {
          self[name] = additionalProps[name];
        });
      }
      this.loc = {
        start: start,
        end: end || start + 1
      }
    }

    let length = str.length;
    let i = 0;
    let ast = new token("RegularExpression", i, length, {body: []});
    let parent = ast.body;
    let currentToken = null;
    while (i < length) {
      let char = str.charAt(i);
      let addToParent = true;

      if (char === "\\") {
        currentToken = new token("", i);
        this.parseEscapeSequence(str, currentToken);
      } else if (char === ".") {
        currentToken = new token("AnyCharacter", i);
      } else {
        if (currentToken && currentToken.type === "Literal") {
          currentToken.value += char;
          currentToken.loc.end++;
          addToParent = false;
        } else {
          currentToken = new token("Literal", i, null, {value: char});
        }
      }

      if (addToParent) {
        if (Array.isArray(parent)) {
          parent.push(currentToken);
        } else {
          parent = currentToken;
        }
      }

      i = currentToken.loc.end;
    }

    this.token = ast;

    return ast;
  };

  prototype.parseEscapeSequence = function(str, token) {
    let escapeCharType = RegExpTokenizer.ESCAPE_CHARS[str[token.loc.end]];
    if (escapeCharType === undefined)
      escapeCharType = 4;
    token.type = RegExpTokenizer.ESCAPE_CHAR_TYPES[escapeCharType];
    switch (token.type) {
      case "ControlEscape":
      case "IdentityEscape":
      case "CharacterClassEscape":
        token.char = str[token.loc.end];
        if (token.type == "ControlEscape") {
          token.value = RegExpTokenizer.ESCACPE_CHAR_CODES[token.char];
        }
        token.loc.end++;
        break;

      case "ControlLetterEscape":
        token.char = str[token.loc.end + 1];
        token.value = token.char.charCodeAt(0) - 64;
        token.loc.end += 2;
        break;

      case "HexEscapeSequence":
        token.sequence = str.substr(token.loc.end + 1, 2);
        token.loc.end += 3;
        break;

      case "UnicodeEscapeSequence":
        token.sequence = str.substr(token.loc.end + 1, 4);
        token.loc.end += 5;
        break;
    }

    return;
  };

  window.RegExpTokenizer = RegExpTokenizer;
})();<|endoftext|>


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

module.exports = {
    extends: [
        'eslint:recommended',
        'prettier',
        'plugin:@typescript-eslint/eslint-recommended',
        'plugin:@typescript-eslint/recommended'
    ],
    plugins: [
        'react',
        'import',
        '@typescript-eslint'
    ],
    env: {
        browser: true
    },
    parserOptions: {
        project: path.join(__dirname, "tsconfig.json")
    },
    rules: {
        'arrow-parens': [2, 'as-needed'],
        'comma-dangle': [2, 'never'],
        'no-constant-condition': 0,
        'no-prototype-builtins': 0,
        'no-unused-expressions': 2,
        'no-unused-vars': 0,
        'prefer-arrow-callback': 2,
        'quote-props': [2, 'as-needed'],
        'quotes': [2, 'single', { 'avoidEscape': true }],
        '@typescript-eslint/ban-types': 0,
        '@typescript-eslint/explicit-module-boundary-types': 0,
        '@typescript-eslint/array-type': 0,
        '@typescript-eslint/eofline': 0,
        '@typescript-eslint/max-classes-per-file': 0,
        '@typescript-eslint/max-line-length': 0,
        '@typescript-eslint/member-access': 0,
        '@typescript-eslint/member-ordering': 0,
        '@typescript-eslint/no-conditional-assignment': 0,
        '@typescript-eslint/no-empty': 0,
        '@typescript-eslint/no-empty-function': 0,
        '@typescript-eslint/no-empty-interface': 0,
        '@typescript-eslint/no-explicit-any': 0,
        '@typescript-eslint/no-unused-vars': [2, { 'argsIgnorePattern': '_' }],
        '@typescript-eslint/no-var-requires': 0,
        '@typescript-eslint/object-literal-sort-keys': 0,
        '@typescript-eslint/object-literal-shorthand': 0,
        '@typescript-eslint/ordered-imports': 0,
        '@typescript-eslint/prefer-const': 0,
        '@typescript-eslint/prefer-for-of': 0,
        '@typescript-eslint/space-before-function-paren': [0, 'always'],
        '@typescript-eslint/unified-signatures': 0,
        '@typescript-eslint/variable-name': 0
    }
};
<commit_msg>Add no-console eslint rule to renderer.<commit_after>var path = require('path');

module.exports = {
    extends: [
        'eslint:recommended',
        'prettier',
        'plugin:@typescript-eslint/eslint-recommended',
        'plugin:@typescript-eslint/recommended'
    ],
    plugins: [
        'react',
        'import',
        '@typescript-eslint'
    ],
    env: {
        browser: true
    },
    parserOptions: {
        project: path.join(__dirname, "tsconfig.json")
    },
    rules: {
        'arrow-parens': [2, 'as-needed'],
        'comma-dangle': [2, 'never'],
        'no-constant-condition': 0,
        'no-prototype-builtins': 0,
        'no-unused-expressions': 2,
        'no-unused-vars': 0,
        'prefer-arrow-callback': 2,
        'quote-props': [2, 'as-needed'],
        'quotes': [2, 'single', { 'avoidEscape': true }],
        'no-console': 2,
        '@typescript-eslint/ban-types': 0,
        '@typescript-eslint/explicit-module-boundary-types': 0,
        '@typescript-eslint/array-type': 0,
        '@typescript-eslint/eofline': 0,
        '@typescript-eslint/max-classes-per-file': 0,
        '@typescript-eslint/max-line-length': 0,
        '@typescript-eslint/member-access': 0,
        '@typescript-eslint/member-ordering': 0,
        '@typescript-eslint/no-conditional-assignment': 0,
        '@typescript-eslint/no-empty': 0,
        '@typescript-eslint/no-empty-function': 0,
        '@typescript-eslint/no-empty-interface': 0,
        '@typescript-eslint/no-explicit-any': 0,
        '@typescript-eslint/no-unused-vars': [2, { 'argsIgnorePattern': '_' }],
        '@typescript-eslint/no-var-requires': 0,
        '@typescript-eslint/object-literal-sort-keys': 0,
        '@typescript-eslint/object-literal-shorthand': 0,
        '@typescript-eslint/ordered-imports': 0,
        '@typescript-eslint/prefer-const': 0,
        '@typescript-eslint/prefer-for-of': 0,
        '@typescript-eslint/space-before-function-paren': [0, 'always'],
        '@typescript-eslint/unified-signatures': 0,
        '@typescript-eslint/variable-name': 0
    }
};
<|endoftext|>


<commit_before>/**
 * @fileoverview The super model representing any model that contains a path for
 * drawing and a fill color.
 *
 * @author joseph@cs.utexas.edu (Joe Tessler)
 */

goog.provide('cn.model.PathModel');

goog.require('goog.color');
goog.require('goog.graphics.Path');
goog.require('goog.graphics.SolidFill');

/**
 * @param {string} color The model's fill color.
 * @constructor
 */
cn.model.PathModel = function(color) {
  if (!goog.color.isValidColor(color)) {
    throw Error(color + ' is not a valid color');
  }
  this.path = new goog.graphics.Path();
  this.fill = new goog.graphics.SolidFill(color);
};

/**
 * The model's path representation.
 * @type {!goog.graphics.Path}
 */
cn.model.PathModel.prototype.path;

/**
 * The cargo box's color
 * @type {!goog.graphics.Fill}
 */
cn.model.PathModel.prototype.fill;
<commit_msg>Added getX/Y functions.<commit_after>/**
 * @fileoverview The super model representing any model that contains a path for
 * drawing and a fill color.
 *
 * @author joseph@cs.utexas.edu (Joe Tessler)
 */

goog.provide('cn.model.PathModel');

goog.require('goog.color');
goog.require('goog.graphics.Path');
goog.require('goog.graphics.SolidFill');

/**
 * @param {string} color The model's fill color.
 * @constructor
 */
cn.model.PathModel = function(color) {
  if (!goog.color.isValidColor(color)) {
    throw Error(color + ' is not a valid color');
  }
  this.path = new goog.graphics.Path();
  this.fill = new goog.graphics.SolidFill(color);
};

/**
 * The model's path representation.
 * @type {!goog.graphics.Path}
 */
cn.model.PathModel.prototype.path;

/**
 * The model's color
 * @type {!goog.graphics.Fill}
 */
cn.model.PathModel.prototype.fill;

/**
 * @return {number} The model's top left x-coordinate.
 */
cn.model.PathModel.prototype.getX = function() {
  return this.path.getCurrentPoint()[0];
};

/**
 * @return {number} The model's top left y-coordinate.
 */
cn.model.PathModel.prototype.getY = function() {
  return this.path.getCurrentPoint()[1];
};
<|endoftext|>


<commit_before>var app = angular.module('ngRouteAnimationManager', ['ngAnimate']);

app.run(['$rootScope', 'RouteAnimationManager', function($rootScope, RouteAnimationManager) {
  $rootScope.$on('$routeChangeStart', function(scope, next, current) {
    RouteAnimationManager.setAnimationClass(current, next );
  });

  $rootScope.RouteAnimationManager = {
    animationClass : RouteAnimationManager.animationClass
  };
}]);

app.provider('RouteAnimationManager', function()  {

  //private vars
  var _defaultAnimation = '';
  var _animationClass = { name:''};

  //configurable function
  this.setDefaultAnimation = function(animation) {
    _defaultAnimation = animation;
  };

  //return factory instance
  this.$get = function() {
    return new RouteAnimationManager();
  };

  //define factory instance
  function RouteAnimationManager() {
    function AnimationRouteData(route) {
      if (!route || !route.originalPath) return undefined;
      this.conf = route.data.animationConf;
      this.name = route.originalPath.substring(1) || 'root'; //root refers to the '/' route
    }

    this.setAnimationClass =  function(currentRoute, nextRoute) {
      var animation;
      var currentRouteData = currentRoute && new AnimationRouteData(currentRoute);
      var nextRouteData = nextRoute && new AnimationRouteData(nextRoute);

      if (!nextRouteData.name) {return;} //not navigating, probably bootstrapping

      if (nextRouteData.conf[currentRouteData.name]) {//get animation for a specific navigation condition
        animation = nextRouteData.conf[currentRouteData.name];
      }
      else if (nextRouteData.conf.default) {//get default animation for this view
        animation = nextRouteData.conf.default;
      }
      else {//get the default global animation
        animation = _defaultAnimation;
      }

      _animationClass.name = animation;
    };

    this.animationClass = _animationClass;
  };
});
<commit_msg>refactored logic<commit_after>var app = angular.module('ngRouteAnimationManager', ['ngAnimate']);

app.run(['$rootScope', 'RouteAnimationManager', function($rootScope, RouteAnimationManager) {
  $rootScope.$on('$routeChangeStart', function(scope, next, current) {
    RouteAnimationManager.setAnimationClass(current, next );
  });

  $rootScope.RouteAnimationManager = {
    animationClass : RouteAnimationManager.animationClass
  };
}]);

app.provider('RouteAnimationManager', function()  {

  //private vars
  var _defaultAnimation = '';
  var _animationClass = { name:''};

  //configurable function
  this.setDefaultAnimation = function(animation) {
    _defaultAnimation = animation;
  };

  //return factory instance
  this.$get = function() {
    return new RouteAnimationManager();
  };

  //define factory instance
  function RouteAnimationManager() {
    function AnimationRouteData(route) {
      if (!route || !route.originalPath) return undefined;
      this.conf = route.data.animationConf;
      this.name = route.originalPath.substring(1) || 'root'; //root refers to the '/' route
    }

    this.setAnimationClass =  function(currentRoute, nextRoute) {
      var animation;
      var currentRouteData = currentRoute && new AnimationRouteData(currentRoute);
      var nextRouteData = nextRoute && new AnimationRouteData(nextRoute);

      if (!nextRouteData.name) {return;} //not navigating, probably bootstrapping

     _animationClass.name = nextRouteData.conf[currentRouteData.name] ||  nextRouteData.conf.default || _defaultAnimation;

    };

    this.animationClass = _animationClass;
  };
});
<|endoftext|>