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

	KC3StrategyTabs.aircraft = new KC3StrategyTab("aircraft");

	KC3StrategyTabs.aircraft.definition = {
		tabSelf: KC3StrategyTabs.aircraft,

		squadNames: {},
		_items: {},
		_holders: {},
		_slotNums: {},

		/* INIT
		Prepares all data needed
		---------------------------------*/
		init :function(){
			var self = this;

			// Get squad names
			if(typeof localStorage.planes == "undefined"){ localStorage.planes = "{}"; }
			this.squadNames = JSON.parse(localStorage.planes);

			// Compile equipment holders
			var ctr, ThisItem, MasterItem, ThisShip, MasterShip;
			for(ctr in KC3ShipManager.list){
				this.checkShipSlotForItemHolder(0, KC3ShipManager.list[ctr]);
				this.checkShipSlotForItemHolder(1, KC3ShipManager.list[ctr]);
				this.checkShipSlotForItemHolder(2, KC3ShipManager.list[ctr]);
				this.checkShipSlotForItemHolder(3, KC3ShipManager.list[ctr]);
			}

			// Compile ships on Index
			var thisType, thisSlotitem, thisGearInstance;

			function GetMyHolder(){ return self._holders["s"+this.itemId]; }
			function NoHolder(){ return false; }

			for(ctr in KC3GearManager.list){
				ThisItem = KC3GearManager.list[ctr];
				MasterItem = ThisItem.master();
				if(!MasterItem) continue;
				if([6,7,8,9,10,21,22,33].indexOf(MasterItem.api_type[3]) == -1) continue;

				// Add holder to the item object temporarily via function return
				if(typeof this._holders["s"+ThisItem.itemId] != "undefined"){
					ThisItem.MyHolder = GetMyHolder;
				}else{
					ThisItem.MyHolder = NoHolder;
				}

				// Check if slotitem_type is filled
				if(typeof this._items["t"+MasterItem.api_type[3]] == "undefined"){
					this._items["t"+MasterItem.api_type[3]] = [];
				}
				thisType = this._items["t"+MasterItem.api_type[3]];

				// Check if slotitem_id is filled
				if(typeof this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] == "undefined"){
					this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] = {
						id: ThisItem.masterId,
						english: ThisItem.name(),
						japanese: MasterItem.api_name,
						stats: {
							fp: MasterItem.api_houg,
							tp: MasterItem.api_raig,
							aa: MasterItem.api_tyku,
							ar: MasterItem.api_souk,
							as: MasterItem.api_tais,
							ev: MasterItem.api_houk,
							ls: MasterItem.api_saku,
							dv: MasterItem.api_baku,
							ht: MasterItem.api_houm,
							rn: MasterItem.api_leng
						},
						instances: []
					};
				}
				thisSlotitem = 	this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id];

				thisSlotitem.instances.push(ThisItem);
			}

			// sort this_items
			for( var i in this._items ){

				// make elements in this._items true Array
				for( var j in this._items[i] ){
					// sort item by ace
					this._items[i][j].instances.sort(function(a,b){
						return b.ace - a.ace;
					});
					this._items[i].push( this._items[i][j] );
					delete this._items[i][j];
				}

				// sort MasterItem by stat
				this._items[i].sort(function(a, b){
					var attr;
					switch( i ){
						case 't6': case 6:
							attr = 'aa'; break;
						case 't7': case 7:
							attr = 'dv'; break;
						case 't8': case 8:
							attr = 'tp'; break;
						case 't9': case 9:
							attr = 'ls'; break;
						case 't10': case 10:
							attr = 'dv'; break;
						default:
							attr = 'aa'; break;
					}
					if( b.stats[attr] == a.stats[attr] )
						return b.stats.ht - a.stats.ht;
					return b.stats[attr] - a.stats[attr];
				});
			}
		},

		/* Check a ship's equipment slot of an item is equipped
		--------------------------------------------*/
		checkShipSlotForItemHolder :function(slot, ThisShip){
			if(ThisShip.items[slot] > -1){
				this._holders["s"+ThisShip.items[slot]] = ThisShip;
				this._slotNums["s"+ThisShip.items[slot]] = slot;
			}
		},

		/* EXECUTE
		Places data onto the interface
		---------------------------------*/
		execute :function(){
			var self = this;

			$(".tab_aircraft .item_type").on("click", function(){
				$(".tab_aircraft .item_type").removeClass("active");
				$(this).addClass("active");
				self.showType($(this).data("type"));
			});

			$(".tab_aircraft .item_list").on("change", ".instance_name input", function(){
				self.squadNames["p"+$(this).attr("data-gearId")] = $(this).val();
				localStorage.planes = JSON.stringify(self.squadNames);
			});

			$(".tab_aircraft .item_type").first().trigger("click");
		},

		/* Show slotitem type
		--------------------------------------------*/
		showType :function(type_id){
			$(".tab_aircraft .item_list").html("");

			var ctr, ThisType, ItemElem, ThisSlotitem;
			for(ctr in this._items["t"+type_id]){
				ThisSlotitem = this._items["t"+type_id][ctr];

				ItemElem = $(".tab_aircraft .factory .slotitem").clone().appendTo(".tab_aircraft .item_list");
				$(".icon img", ItemElem).attr("src", "../../assets/img/items/"+type_id+".png");
				$(".english", ItemElem).text(ThisSlotitem.english);
				$(".japanese", ItemElem).text(ThisSlotitem.japanese);

				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "fp");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "tp");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "aa");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "ar");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "as");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "ev");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "ls");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "dv");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "ht");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "rn");

				var PlaneCtr, ThisPlane, PlaneBox, rankLines, ThisCapacity;
				for(PlaneCtr in ThisSlotitem.instances){
					ThisPlane = ThisSlotitem.instances[PlaneCtr];

					PlaneBox = $(".tab_aircraft .factory .instance").clone();
					$(".instances", ItemElem).append(PlaneBox);

					$(".instance_icon img", PlaneBox).attr("src", "../../assets/img/items/"+type_id+".png");

					if(ThisPlane.ace > 0){
						$(".instance_chev img", PlaneBox).attr("src", "../../assets/img/client/achev/"+ThisPlane.ace+".png");
					}else{
						$(".instance_chev img", PlaneBox).hide();
					}

					$(".instance_name input", PlaneBox).attr("data-gearId", ThisPlane.itemId);

					if(typeof this.squadNames["p"+ThisPlane.itemId] != "undefined"){
						$(".instance_name input", PlaneBox).val( this.squadNames["p"+ThisPlane.itemId] );
					}

					if(ThisPlane.MyHolder()){
						$(".holder_pic img", PlaneBox).attr("src", KC3Meta.shipIcon(ThisPlane.MyHolder().masterId) );
						$(".holder_name", PlaneBox).text( ThisPlane.MyHolder().name() );
						$(".holder_level", PlaneBox).text("Lv."+ThisPlane.MyHolder().level);

						// Compute for veteranized fighter power
						ThisCapacity = ThisPlane.MyHolder().slots[ this._slotNums["s"+ThisPlane.itemId] ];
						$(".instance_aaval", PlaneBox).addClass("activeSquad");
						$(".instance_aaval", PlaneBox).text( Math.floor(ThisPlane.fighterPower(ThisCapacity)) );
					}else{
						$(".holder_pic", PlaneBox).hide();
						$(".holder_name", PlaneBox).hide();
						$(".holder_level", PlaneBox).hide();
						$(".instance_aaval", PlaneBox).addClass("reserveSquad");
						$(".instance_aaval", PlaneBox).text( ThisSlotitem.stats.aa );
					}
				}

			}

		},

		/* Determine if an item has a specific stat
		--------------------------------------------*/
		slotitem_stat :function(ItemElem, stats, stat_name){
			if(stats[stat_name] !== 0){
				$(".stats .item_"+stat_name+" span", ItemElem).text(stats[stat_name]);
			}else{
				$(".stats .item_"+stat_name, ItemElem).hide();
			}
		}

	};

})();
<commit_msg>even more fix<commit_after>(function(){
	"use strict";

	KC3StrategyTabs.aircraft = new KC3StrategyTab("aircraft");

	KC3StrategyTabs.aircraft.definition = {
		tabSelf: KC3StrategyTabs.aircraft,

		squadNames: {},
		_items: {},
		_holders: {},
		_slotNums: {},

		/* INIT
		Prepares all data needed
		---------------------------------*/
		init :function(){
			var self = this;

			// Get squad names
			if(typeof localStorage.planes == "undefined"){ localStorage.planes = "{}"; }
			this.squadNames = JSON.parse(localStorage.planes);

			// Compile equipment holders
			var ctr, ThisItem, MasterItem, ThisShip, MasterShip;
			for(ctr in KC3ShipManager.list){
				this.checkShipSlotForItemHolder(0, KC3ShipManager.list[ctr]);
				this.checkShipSlotForItemHolder(1, KC3ShipManager.list[ctr]);
				this.checkShipSlotForItemHolder(2, KC3ShipManager.list[ctr]);
				this.checkShipSlotForItemHolder(3, KC3ShipManager.list[ctr]);
			}

			// Compile ships on Index
			var thisType, thisSlotitem, thisGearInstance;

			function GetMyHolder(){ return self._holders["s"+this.itemId]; }
			function NoHolder(){ return false; }

			for(ctr in KC3GearManager.list){
				ThisItem = KC3GearManager.list[ctr];
				MasterItem = ThisItem.master();
				if(!MasterItem) continue;
				if([6,7,8,9,10,21,22,33].indexOf(MasterItem.api_type[3]) == -1) continue;

				// Add holder to the item object temporarily via function return
				if(typeof this._holders["s"+ThisItem.itemId] != "undefined"){
					ThisItem.MyHolder = GetMyHolder;
				}else{
					ThisItem.MyHolder = NoHolder;
				}

				// Check if slotitem_type is filled
				if(typeof this._items["t"+MasterItem.api_type[3]] == "undefined"){
					this._items["t"+MasterItem.api_type[3]] = [];
				}
				thisType = this._items["t"+MasterItem.api_type[3]];

				// Check if slotitem_id is filled
				if(typeof this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] == "undefined"){
					this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] = {
						id: ThisItem.masterId,
						english: ThisItem.name(),
						japanese: MasterItem.api_name,
						stats: {
							fp: MasterItem.api_houg,
							tp: MasterItem.api_raig,
							aa: MasterItem.api_tyku,
							ar: MasterItem.api_souk,
							as: MasterItem.api_tais,
							ev: MasterItem.api_houk,
							ls: MasterItem.api_saku,
							dv: MasterItem.api_baku,
							ht: MasterItem.api_houm,
							rn: MasterItem.api_leng
						},
						instances: []
					};
				}
				thisSlotitem = 	this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id];

				thisSlotitem.instances.push(ThisItem);
			}

			// sort this_items
			var sortMasterItem = function(a, b){
				var attr;
				switch( i ){
					case 't6': case 6:
						attr = 'aa'; break;
					case 't7': case 7:
						attr = 'dv'; break;
					case 't8': case 8:
						attr = 'tp'; break;
					case 't9': case 9:
						attr = 'ls'; break;
					case 't10': case 10:
						attr = 'dv'; break;
					default:
						attr = 'aa'; break;
				}
				if( b.stats[attr] == a.stats[attr] )
					return b.stats.ht - a.stats.ht;
				return b.stats[attr] - a.stats[attr];
			};
			var sortSlotItem = function(a,b){
				return b.ace - a.ace
			}
			for( var i in this._items ){

				// make elements in this._items true Array
				for( var j in this._items[i] ){
					// sort item by ace
					this._items[i][j].instances.sort(sortSlotItem);
					this._items[i].push( this._items[i][j] );
					delete this._items[i][j];
				}

				// sort MasterItem by stat
				this._items[i].sort(sortMasterItem);
			}
		},

		/* Check a ship's equipment slot of an item is equipped
		--------------------------------------------*/
		checkShipSlotForItemHolder :function(slot, ThisShip){
			if(ThisShip.items[slot] > -1){
				this._holders["s"+ThisShip.items[slot]] = ThisShip;
				this._slotNums["s"+ThisShip.items[slot]] = slot;
			}
		},

		/* EXECUTE
		Places data onto the interface
		---------------------------------*/
		execute :function(){
			var self = this;

			$(".tab_aircraft .item_type").on("click", function(){
				$(".tab_aircraft .item_type").removeClass("active");
				$(this).addClass("active");
				self.showType($(this).data("type"));
			});

			$(".tab_aircraft .item_list").on("change", ".instance_name input", function(){
				self.squadNames["p"+$(this).attr("data-gearId")] = $(this).val();
				localStorage.planes = JSON.stringify(self.squadNames);
			});

			$(".tab_aircraft .item_type").first().trigger("click");
		},

		/* Show slotitem type
		--------------------------------------------*/
		showType :function(type_id){
			$(".tab_aircraft .item_list").html("");

			var ctr, ThisType, ItemElem, ThisSlotitem;
			for(ctr in this._items["t"+type_id]){
				ThisSlotitem = this._items["t"+type_id][ctr];

				ItemElem = $(".tab_aircraft .factory .slotitem").clone().appendTo(".tab_aircraft .item_list");
				$(".icon img", ItemElem).attr("src", "../../assets/img/items/"+type_id+".png");
				$(".english", ItemElem).text(ThisSlotitem.english);
				$(".japanese", ItemElem).text(ThisSlotitem.japanese);

				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "fp");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "tp");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "aa");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "ar");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "as");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "ev");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "ls");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "dv");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "ht");
				this.slotitem_stat(ItemElem, ThisSlotitem.stats, "rn");

				var PlaneCtr, ThisPlane, PlaneBox, rankLines, ThisCapacity;
				for(PlaneCtr in ThisSlotitem.instances){
					ThisPlane = ThisSlotitem.instances[PlaneCtr];

					PlaneBox = $(".tab_aircraft .factory .instance").clone();
					$(".instances", ItemElem).append(PlaneBox);

					$(".instance_icon img", PlaneBox).attr("src", "../../assets/img/items/"+type_id+".png");

					if(ThisPlane.ace > 0){
						$(".instance_chev img", PlaneBox).attr("src", "../../assets/img/client/achev/"+ThisPlane.ace+".png");
					}else{
						$(".instance_chev img", PlaneBox).hide();
					}

					$(".instance_name input", PlaneBox).attr("data-gearId", ThisPlane.itemId);

					if(typeof this.squadNames["p"+ThisPlane.itemId] != "undefined"){
						$(".instance_name input", PlaneBox).val( this.squadNames["p"+ThisPlane.itemId] );
					}

					if(ThisPlane.MyHolder()){
						$(".holder_pic img", PlaneBox).attr("src", KC3Meta.shipIcon(ThisPlane.MyHolder().masterId) );
						$(".holder_name", PlaneBox).text( ThisPlane.MyHolder().name() );
						$(".holder_level", PlaneBox).text("Lv."+ThisPlane.MyHolder().level);

						// Compute for veteranized fighter power
						ThisCapacity = ThisPlane.MyHolder().slots[ this._slotNums["s"+ThisPlane.itemId] ];
						$(".instance_aaval", PlaneBox).addClass("activeSquad");
						$(".instance_aaval", PlaneBox).text( Math.floor(ThisPlane.fighterPower(ThisCapacity)) );
					}else{
						$(".holder_pic", PlaneBox).hide();
						$(".holder_name", PlaneBox).hide();
						$(".holder_level", PlaneBox).hide();
						$(".instance_aaval", PlaneBox).addClass("reserveSquad");
						$(".instance_aaval", PlaneBox).text( ThisSlotitem.stats.aa );
					}
				}

			}

		},

		/* Determine if an item has a specific stat
		--------------------------------------------*/
		slotitem_stat :function(ItemElem, stats, stat_name){
			if(stats[stat_name] !== 0){
				$(".stats .item_"+stat_name+" span", ItemElem).text(stats[stat_name]);
			}else{
				$(".stats .item_"+stat_name, ItemElem).hide();
			}
		}

	};

})();
<|endoftext|>


<commit_before>var api = require('digio-api')
, print = require('../print')
, tools = require('../tools')

var domains = function (cmd, _config) {
  api = new api(tools.get_active_key(_config))

  cmd.register(
    'domains',
    'list',
    [],
    'List all domains',
    function () {
      api.domains.list(function (err, data) {
        if (err) return print.error(err.message)
        console.log('\nTotal domains: ' + data.meta.total + '\n')
        data.domains.forEach(function (dom) {
          console.log('- Domain:        ' + dom.name)
          console.log('    TTL:         ' + dom.ttl)
          console.log('    Zone File:   ' + dom.zone_file + '\n')
        })
      })
    }
  )

  cmd.register(
    'domains',
    'create',
    ['<domain>', '<ip>'],
    'Create a new domain',
    function (domain, ip_address) {
      api.domains.create(domain, ip_address, function (err, data) {
        if (err) return print.error(err.message)
        print.success(domain + ' (' + ip_address + ') created')
      })
    }
  )

  cmd.register(
    'domains',
    'delete',
    ['<id>'],
    'Delete a domain with a specific ID',
    function (domain) {
      api.domains.delete(domain, function (err, data) {
        if (err) return print.error(err.message)
        print.success('Deleted domain "' + domain + '"')
      })
    }
  )

  cmd.register(
    'domains',
    'get',
    ['<domain>'],
    'Get details of a specific domain',
    function (domain) {
      api.domains.get(domain, function (err, data) {
        console.log('\n- Domain:        ' + data.domain.name)
        console.log('    TTL:         ' + data.domain.ttl)
        console.log('    Zone File:   ' + data.domain.zone_file + '\n')
      })
    }
  )

}

module.exports = domains
<commit_msg>Add commands for list, get, create, delete and update domain records<commit_after>var api = require('digio-api')
, print = require('../print')
, tools = require('../tools')

var domains = function (cmd, _config) {
  api = new api(tools.get_active_key(_config))

  cmd.register(
    'domains',
    'list',
    [],
    'List all domains',
    function () {
      api.domains.list(function (err, data) {
        if (err) return print.error(err.message)
        console.log('\nTotal domains: ' + data.meta.total + '\n')
        data.domains.forEach(function (dom) {
          console.log('- Domain:        ' + dom.name)
          console.log('    TTL:         ' + dom.ttl)
          console.log('    Zone File:   ' + dom.zone_file + '\n')
        })
      })
    }
  )

  cmd.register(
    'domains',
    'create',
    ['<domain>', '<ip>'],
    'Create a new domain',
    function (domain, ip_address) {
      api.domains.create(domain, ip_address, function (err, data) {
        if (err) return print.error(err.message)
        print.success(domain + ' (' + ip_address + ') created')
      })
    }
  )

  cmd.register(
    'domains',
    'delete',
    ['<id>'],
    'Delete a domain with a specific ID',
    function (domain) {
      api.domains.delete(domain, function (err, data) {
        if (err) return print.error(err.message)
        print.success('Deleted domain "' + domain + '"')
      })
    }
  )

  cmd.register(
    'domains',
    'get',
    ['<domain>'],
    'Get details of a specific domain',
    function (domain) {
      api.domains.get(domain, function (err, data) {
        if (err) return print.error(err.message)
        console.log('\n- Domain:        ' + data.domain.name)
        console.log('    TTL:         ' + data.domain.ttl)
        console.log('    Zone File:   ' + data.domain.zone_file + '\n')
      })
    }
  )

  cmd.register(
    'domains',
    'listrecords',
    ['<domain>'],
    'List records for a specific domain',
    function (domain) {
      api.domains.list_records(domain, function (err, data) {
        if (err) return print.error(err.message)
        console.log('\nTotal records: ' + data.meta.total + '\n')
        data.domain_records.forEach(function (record) {
          console.log('- Name:          ' + record.name)
          console.log('    ID:          ' + record.id)
          console.log('    Type:        ' + record.type)
          console.log('    Data:        ' + record.data)
          console.log('    Priority:    ' + record.priority)
          console.log('    Port:        ' + record.port)
          console.log('    Weight:      ' + record.weight)
          console.log('')
        })
      })
    }
  )

  cmd.register(
    'domains',
    'getrecord',
    ['<domain>', '<record_id>'],
    'Get details of a domain record',
    function (domain, record) {
      api.domains.get_record(domain, record, function (err, data) {
        if (err) return print.error(err.message)
        console.log('')
        console.log('- Name:          ' + data.domain_record.name)
        console.log('    ID:          ' + data.domain_record.id)
        console.log('    Type:        ' + data.domain_record.type)
        console.log('    Data:        ' + data.domain_record.data)
        console.log('    Priority:    ' + data.domain_record.priority)
        console.log('    Port:        ' + data.domain_record.port)
        console.log('    Weight:      ' + data.domain_record.weight)
        console.log('')
      })
    }
  )

  cmd.register(
    'domains',
    'deleterecord',
    ['<domain>', '<record_id>'],
    'Delete a domain record',
    function (domain, record_id) {
      api.delete_record(domain, record_id, function (err, data) {
        if (err) return print.error(err.message)
        print.success('Deleted record ' + record_id + ' on domain ' + domain)
      })
    }
  )

  cmd.register(
    'domains',
    'updaterecord',
    ['<domain>', '<record_id>', '<name>'],
    'Change the name of a domain record',
    function (domain, record_id, name) {
      api.update_record(domain, record_id, function (err, data) {
        if (err) return print.error(err.message)
        print.success('Domain record name on record ' + record_id + ' (' + domain + ') changed to ' + name)
      })
    }
  )

  cmd.register(
    'domains',
    'createrecord',
    ['<domain>', '<type>', '<name>', '<data>', '<priority>', '<port>', '<weight>'],
    'Create a new domain record for a specific domain',
    function (domain, type, name, data, priority, port, weight) {
      var types = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'SRV', 'NS']
      if (types.indexOf(type) === -1)
        return print.error('Invalid type. See DigitalOcean API documentation for details.')
      if (name === 'null' && (type !== 'NS' && type !== 'MX'))
        return print.error('You must specify a name with A, AAAA, CNAME, TXT & SRV records.')
      if (data === 'null')
        return print.error('Data argument must be specified.')
      if ((type === 'MX' || type === 'SRV') && priority === 'null')
        return print.error('Priority must be specified for MX and SRV records.')
      if (type === 'SRV' && port === 'null')
        return print.error('Port must be specified in SRV records.')
      if (type === 'SRV' && weight === 'null')
        return print.error('Weight must be specified in SRV records.')

      if (name === 'null') name = null
      if (priority === 'null') priority = null
      if (port === 'null') port = null
      if (weight === 'null') weight = null

      api.create_record(domain, type, name, data, priority, port, weight, function (err, data) {
        if (err) return print.error(err.message)
        print.success('Domain record created.')
      })
    }
  )
}

module.exports = domains
<|endoftext|>


<commit_before>/* jshint node:true */

var GitRepo = require('../utils/git');
var fs      = require('fs');
var path    = require('path');
var merge   = require('merge');
var chalk   = require('chalk');
var RSVP    = require('rsvp');

var resolve = RSVP.resolve;
var resolveAll = RSVP.all;

module.exports = {
  name: 'release',
  description: 'Create a new git tag at HEAD',
  works: 'insideProject',

  strategies: {
    semver: require('../strategies/semver'),
    date: require('../strategies/date')
  },

  availableOptions: [
    {
      name: 'local',
      type: Boolean,
      aliases: [ 'l' ],
      default: false,
      description: "whether release commit and tags are locally or not (not pushed to a remote)"
    },
    {
      name: 'remote',
      type: String,
      aliases: [ 'r' ],
      default: 'origin',
      description: "the git origin to push tags to, ignored if the '--local' option is true"
    },
    {
      name: 'tag',
      type: String,
      aliases: [ 't' ],
      description: "the name of the git tag to create"
    },
    {
      name: 'annotation',
      type: String,
      aliases: [ 'a' ],
      description: "a message passed to the `--message` option of `git tag`, indicating that to the tag should be created with the `--annotated` option (defualt is lightweight), the string '%@' is replaced with the tag name"
    },
    {
      name: 'message',
      type: String,
      aliases: [ 'm' ],
      default: 'Released %@',
      description: "a message passed to the `--message` option of `git commit`, the string '%@' is replaced with the tag name"
    },
    {
      name: 'build',
      type: Boolean,
      aliases: [ 'b' ],
      default: false,
      description: "whether to run `ember build` or not"
    },
    {
      name: 'publish',
      type: Boolean,
      aliases: [ 'p' ],
      default: false,
      description: "whether to run `npm publish` post-tagging or not"
    },
    {
      name: 'yes',
      type: Boolean,
      aliases: [ 'y' ],
      default: false,
      description: "whether to skip confirmation prompts or not (answer 'yes' to all questions)"
    },
    {
      name: 'strategy',
      type: String,
      aliases: [ 's' ],
      default: 'semver',
      description: "strategy for auto-generating the tag name, either 'semver' or 'date', ignored if the 'name' option is specified"
    },
    {
      name: 'major',
      type: Boolean,
      aliases: [ 'j' ],
      description: "when strategy is 'semver', specifies that the major version number should be incremented"
    },
    {
      name: 'minor',
      type: Boolean,
      aliases: [ 'i' ],
      description: "when strategy is 'semver', specifies that the minor version number should be incremented, ignored if '--major' option is true"
    },
    {
      name: 'format',
      type: String,
      aliases: [ 'f' ],
      default: 'YYYY.MM.DD',
      description: "when strategy is 'date', the format used to generate the tag"
    },
    {
      name: 'timezone',
      type: String,
      aliases: [ 'z' ],
      default: 'UTC',
      description: "when strategy is 'date', the timezone to consider the current date in"
    }
  ],

  run: function(cliOptions) {
    var SilentError = this.project.require('ember-cli/lib/errors/silent');
    var command = this;
    var ui = this.ui;
    var repo = this.git();
    var strategies = this.strategies;
    var defaultOptions = this.availableOptions.map(function(option) {
      return option.default;
    });
    var options = {};
    var pushQueue = [];

    if (fs.existsSync(path.join(this.project.root, 'config/release'))) {
      options = this.project.require('config/release');
    }

    options = merge(options, removeDefaults(cliOptions, defaultOptions));

    function proceedPrompt(ui, message) {
      if (options.yes) {
        return resolve();
      }

      return ui.prompt({
        type: 'confirm',
        name: 'proceed',
        message: chalk.yellow(message + ", proceed?"),
        choices: [
          { key: 'y', value: true },
          { key: 'n', value: false }
        ]
      }).then(function(response) {
        if (!response.proceed) {
          throw new SilentError("Aborted.");
        }
      });
    }

    function getVersioningStrategy() {
      var strategyName = options.strategy;

      if (!(strategyName in strategies)) {
        throw new SilentError("Unknown versioning strategy: '" + strategyName + "'");
      }

      return strategies[strategyName];
    }

    function abortIfAtTag() {
      return repo.currentTag().then(function(currentTag) {
        if (currentTag) {
          throw new SilentError("Skipped tagging, HEAD already at tag: " + currentTag);
        }
      });
    }

    function propmtIfWorkingTreeDirty() {
      return repo.status().then(function(status) {
        if (status) {
          return proceedPrompt(ui, "Your working tree contains modifications that will be added to the release commit");
        }
      });
    }

    function getNextTag() {
      if (options.tag) {
        // Use tag name if specified
        return {
          next: options.tag
        };
      } else {
        // Otherwise fetch all tags to pass to the versioning strategy
        return repo.tags().then(function(tags) {
          var versioningStrategy = getVersioningStrategy();
          var tagNames = tags.map(function(tag) {
            return tag.name;
          });

          return versioningStrategy(tagNames, options);
        });
      }
    }

    function printLatestVersion(latestVersion) {
      if (latestVersion) {
        ui.writeLine(chalk.green('Latest version: ' + latestVersion));
      }
    }

    function replaceVersionsInManifests(nextVersion) {
      [ 'package.json', 'bower.json' ].forEach(function(file) {
        command.replaceVersionInFile(file, nextVersion);
      });
    }

    function createCommit(nextVersion) {
      return repo.status().then(function(status) {
        // Don't bother committing if for some reason the working tree is clean
        if (status) {
          return repo.currentBranch().then(function(branchName) {
            if (!branchName) {
              throw new SilentError("Must have a branch checked out to commit to");
            }

            // Allow the name to be in the message
            var message = options.message.replace(/%@/g, nextVersion);

            return repo.commitAll(message).then(function() {
              pushQueue.push(branchName);
            }).then(function() {
              ui.writeLine(chalk.green("Succesfully committed changes '" + message + "' locally."));
            });
          });
        }
      });
    }

    function promptToCreateTag(nextVersion) {
      return proceedPrompt(ui, "About to create tag '" + nextVersion + "'" + (options.local ? "" : " and push to remote '" + options.remote + "'"));
    }

    function createTag(tagName) {
      var message = null;

      if (options.annotation) {
        // Allow the tag name to be in the message
        message = options.annotation.replace(/%@/g, tagName);
      }

      return repo.createTag(tagName, message).then(function() {
        pushQueue.push(tagName);
      }).then(function() {
        ui.writeLine(chalk.green("Succesfully created git tag '" + tagName + "' locally."));
      });
    }

    function pushChanges() {
      if (options.local || !pushQueue.length) { return; }

      resolveAll(pushQueue.map(function(treeish) {
        return repo.push(options.remote, treeish).then(function() {
          ui.writeLine(chalk.green("Succesfully pushed '" + treeish + "' to remote '" + options.remote + "'."));
        });
      }));
    }

    return resolve()
      .then(abortIfAtTag)
      .then(propmtIfWorkingTreeDirty)
      .then(getNextTag)
      .then(function(versions) {
        printLatestVersion(versions.latest);

        replaceVersionsInManifests(versions.next);

        return createCommit(versions.next)
          .then(function() {
            return promptToCreateTag(versions.next);
          })
          .then(function() {
            return createTag(versions.next);
          });
      })
      .then(pushChanges);
  },

  git: function() {
    if (this._repo) {
      return this._repo;
    }

    return this._repo = new GitRepo(this.project.root);
  },

  replaceVersionInFile: function(file, version) {
    var filepath = path.join(this.project.root, file);

    if (fs.existsSync(filepath)) {
      var pkg = JSON.parse(fs.readFileSync(filepath, {
        encoding: 'utf8'
      }));

      // Skip replace if 'version' key does not exist
      if (pkg.version) {
        pkg.version = version;

        var contents = JSON.stringify(pkg, null, 2);

        fs.writeFileSync(filepath, contents, {
          encoding: 'utf8'
        });
      }
    }
  },

};

function removeDefaults(obj, defaults) {
  return Object.keys(obj).reduce(function(result, key) {
    if (obj[key] !== defaults[key]) {
      result[key] = obj[key];
    }

    return result;
  }, {});
}
<commit_msg>Refactored version replacement method for consistency<commit_after>/* jshint node:true */

var GitRepo = require('../utils/git');
var fs      = require('fs');
var path    = require('path');
var merge   = require('merge');
var chalk   = require('chalk');
var RSVP    = require('rsvp');

var resolve = RSVP.resolve;
var resolveAll = RSVP.all;

var manifestFiles = [
  'package.json',
  'bower.json'
];

module.exports = {
  name: 'release',
  description: 'Create a new git tag at HEAD',
  works: 'insideProject',

  strategies: {
    semver: require('../strategies/semver'),
    date: require('../strategies/date')
  },

  availableOptions: [
    {
      name: 'local',
      type: Boolean,
      aliases: [ 'l' ],
      default: false,
      description: "whether release commit and tags are locally or not (not pushed to a remote)"
    },
    {
      name: 'remote',
      type: String,
      aliases: [ 'r' ],
      default: 'origin',
      description: "the git origin to push tags to, ignored if the '--local' option is true"
    },
    {
      name: 'tag',
      type: String,
      aliases: [ 't' ],
      description: "the name of the git tag to create"
    },
    {
      name: 'annotation',
      type: String,
      aliases: [ 'a' ],
      description: "a message passed to the `--message` option of `git tag`, indicating that to the tag should be created with the `--annotated` option (defualt is lightweight), the string '%@' is replaced with the tag name"
    },
    {
      name: 'message',
      type: String,
      aliases: [ 'm' ],
      default: 'Released %@',
      description: "a message passed to the `--message` option of `git commit`, the string '%@' is replaced with the tag name"
    },
    {
      name: 'build',
      type: Boolean,
      aliases: [ 'b' ],
      default: false,
      description: "whether to run `ember build` or not"
    },
    {
      name: 'publish',
      type: Boolean,
      aliases: [ 'p' ],
      default: false,
      description: "whether to run `npm publish` post-tagging or not"
    },
    {
      name: 'yes',
      type: Boolean,
      aliases: [ 'y' ],
      default: false,
      description: "whether to skip confirmation prompts or not (answer 'yes' to all questions)"
    },
    {
      name: 'strategy',
      type: String,
      aliases: [ 's' ],
      default: 'semver',
      description: "strategy for auto-generating the tag name, either 'semver' or 'date', ignored if the 'name' option is specified"
    },
    {
      name: 'major',
      type: Boolean,
      aliases: [ 'j' ],
      description: "when strategy is 'semver', specifies that the major version number should be incremented"
    },
    {
      name: 'minor',
      type: Boolean,
      aliases: [ 'i' ],
      description: "when strategy is 'semver', specifies that the minor version number should be incremented, ignored if '--major' option is true"
    },
    {
      name: 'format',
      type: String,
      aliases: [ 'f' ],
      default: 'YYYY.MM.DD',
      description: "when strategy is 'date', the format used to generate the tag"
    },
    {
      name: 'timezone',
      type: String,
      aliases: [ 'z' ],
      default: 'UTC',
      description: "when strategy is 'date', the timezone to consider the current date in"
    }
  ],

  run: function(cliOptions) {
    var SilentError = this.project.require('ember-cli/lib/errors/silent');
    var ui = this.ui;
    var projectRoot = this.project.root;
    var repo = this.git();
    var strategies = this.strategies;
    var defaultOptions = this.availableOptions.map(function(option) {
      return option.default;
    });
    var options = {};
    var pushQueue = [];

    if (fs.existsSync(path.join(this.project.root, 'config/release'))) {
      options = this.project.require('config/release');
    }

    options = merge(options, removeDefaults(cliOptions, defaultOptions));

    function proceedPrompt(ui, message) {
      if (options.yes) {
        return resolve();
      }

      return ui.prompt({
        type: 'confirm',
        name: 'proceed',
        message: chalk.yellow(message + ", proceed?"),
        choices: [
          { key: 'y', value: true },
          { key: 'n', value: false }
        ]
      }).then(function(response) {
        if (!response.proceed) {
          throw new SilentError("Aborted.");
        }
      });
    }

    function getVersioningStrategy() {
      var strategyName = options.strategy;

      if (!(strategyName in strategies)) {
        throw new SilentError("Unknown versioning strategy: '" + strategyName + "'");
      }

      return strategies[strategyName];
    }

    function abortIfAtTag() {
      return repo.currentTag().then(function(currentTag) {
        if (currentTag) {
          throw new SilentError("Skipped tagging, HEAD already at tag: " + currentTag);
        }
      });
    }

    function propmtIfWorkingTreeDirty() {
      return repo.status().then(function(status) {
        if (status) {
          return proceedPrompt(ui, "Your working tree contains modifications that will be added to the release commit");
        }
      });
    }

    function getNextTag() {
      if (options.tag) {
        // Use tag name if specified
        return {
          next: options.tag
        };
      } else {
        // Otherwise fetch all tags to pass to the versioning strategy
        return repo.tags().then(function(tags) {
          var versioningStrategy = getVersioningStrategy();
          var tagNames = tags.map(function(tag) {
            return tag.name;
          });

          return versioningStrategy(tagNames, options);
        });
      }
    }

    function printLatestVersion(latestVersion) {
      if (latestVersion) {
        ui.writeLine(chalk.green('Latest version: ' + latestVersion));
      }
    }

    function replaceVersionsInManifests(nextVersion) {
      manifestFiles.forEach(function(file) {
        var filepath = path.join(projectRoot, file);

        if (fs.existsSync(filepath)) {
          var pkg = JSON.parse(fs.readFileSync(filepath, {
            encoding: 'utf8'
          }));

          // Skip replace if 'version' key does not exist
          if (pkg.version) {
            pkg.version = nextVersion;

            var contents = JSON.stringify(pkg, null, 2);

            fs.writeFileSync(filepath, contents, {
              encoding: 'utf8'
            });
          }
        }
      });
    }

    function createCommit(nextVersion) {
      return repo.status().then(function(status) {
        // Don't bother committing if for some reason the working tree is clean
        if (status) {
          return repo.currentBranch().then(function(branchName) {
            if (!branchName) {
              throw new SilentError("Must have a branch checked out to commit to");
            }

            // Allow the name to be in the message
            var message = options.message.replace(/%@/g, nextVersion);

            return repo.commitAll(message).then(function() {
              pushQueue.push(branchName);
            }).then(function() {
              ui.writeLine(chalk.green("Succesfully committed changes '" + message + "' locally."));
            });
          });
        }
      });
    }

    function promptToCreateTag(nextVersion) {
      return proceedPrompt(ui, "About to create tag '" + nextVersion + "'" + (options.local ? "" : " and push to remote '" + options.remote + "'"));
    }

    function createTag(tagName) {
      var message = null;

      if (options.annotation) {
        // Allow the tag name to be in the message
        message = options.annotation.replace(/%@/g, tagName);
      }

      return repo.createTag(tagName, message).then(function() {
        pushQueue.push(tagName);
      }).then(function() {
        ui.writeLine(chalk.green("Succesfully created git tag '" + tagName + "' locally."));
      });
    }

    function pushChanges() {
      if (options.local || !pushQueue.length) { return; }

      resolveAll(pushQueue.map(function(treeish) {
        return repo.push(options.remote, treeish).then(function() {
          ui.writeLine(chalk.green("Succesfully pushed '" + treeish + "' to remote '" + options.remote + "'."));
        });
      }));
    }

    return resolve()
      .then(abortIfAtTag)
      .then(propmtIfWorkingTreeDirty)
      .then(getNextTag)
      .then(function(versions) {
        printLatestVersion(versions.latest);

        replaceVersionsInManifests(versions.next);

        return createCommit(versions.next)
          .then(function() {
            return promptToCreateTag(versions.next);
          })
          .then(function() {
            return createTag(versions.next);
          });
      })
      .then(pushChanges);
  },

  git: function() {
    if (this._repo) {
      return this._repo;
    }

    return this._repo = new GitRepo(this.project.root);
  }
};

function removeDefaults(obj, defaults) {
  return Object.keys(obj).reduce(function(result, key) {
    if (obj[key] !== defaults[key]) {
      result[key] = obj[key];
    }

    return result;
  }, {});
}
<|endoftext|>


<commit_before>/* eslint no-unused-vars: 0 */

/*********************************/
/** UI Columns Performance Once **/
/*********************************/
gridState.processors['ui-columns-performance-once'] = {
    watches: ['sort', 'columns', 'space'],
    init: function(model){
        model.processors['ui-columns-performance-once-runner'] = [];
    },
    runs: function (options) {
        if (!options.model.space || !options.model.space.width) {
            return;
        }
        var runOnce = [];
        if (!options.model.vm.columns || !options.model.vm.columns())
        {
            console.log("Running vm-update-bindings-columns once");
            runOnce.push('vm-update-bindings-columns');
        }
        if (!options.model.vm.hb_columns || !options.model.vm.hb_columns())
        {
            console.log("Running vm-handlebars-columns once");
            runOnce.push('vm-handlebars-columns');
        }
        options.model.processors['ui-columns-performance-once-runner'] = runOnce;
    }
};
<commit_msg>Run columns once wasn't detecting if the length was incorrect<commit_after>/* eslint no-unused-vars: 0 */

/*********************************/
/** UI Columns Performance Once **/
/*********************************/
gridState.processors['ui-columns-performance-once'] = {
    watches: ['sort', 'columns', 'space'],
    init: function(model){
        model.processors['ui-columns-performance-once-runner'] = [];
    },
    runs: function (options) {
        if (!options.model.space || !options.model.space.width) {
            return;
        }
        var runOnce = [];
        if (!options.model.vm.columns || !options.model.vm.columns() || options.model.vm.columns().length !== options.model.columns.length)
        {
            console.log("Running vm-update-bindings-columns once");
            runOnce.push('vm-update-bindings-columns');
        }
        if (!options.model.vm.hb_columns || !options.model.vm.hb_columns())
        {
            console.log("Running vm-handlebars-columns once");
            runOnce.push('vm-handlebars-columns');
        }
        options.model.processors['ui-columns-performance-once-runner'] = runOnce;
    }
};
<|endoftext|>


<commit_before>"use strict";

let objects = require("../utils/objects");

/* Simple AST node visitor builder. */
let visitor = {
  build: function(functions) {
    function visit(node) {
      return functions[node.type].apply(null, arguments);
    }

    function visitNop() { }

    function visitExpression(node) {
      let extraArgs = Array.prototype.slice.call(arguments, 1);

      visit.apply(null, [node.expression].concat(extraArgs));
    }

    function visitChildren(property) {
      return function(node) {
        let extraArgs = Array.prototype.slice.call(arguments, 1);

        node[property].forEach(child => {
          visit.apply(null, [child].concat(extraArgs));
        });
      };
    }

    const DEFAULT_FUNCTIONS = {
          grammar: function(node) {
            let extraArgs = Array.prototype.slice.call(arguments, 1);

            if (node.initializer) {
              visit.apply(null, [node.initializer].concat(extraArgs));
            }

            node.rules.forEach(rule => {
              visit.apply(null, [rule].concat(extraArgs));
            });
          },

          initializer:  visitNop,
          rule:         visitExpression,
          named:        visitExpression,
          choice:       visitChildren("alternatives"),
          action:       visitExpression,
          sequence:     visitChildren("elements"),
          labeled:      visitExpression,
          text:         visitExpression,
          simple_and:   visitExpression,
          simple_not:   visitExpression,
          optional:     visitExpression,
          zero_or_more: visitExpression,
          one_or_more:  visitExpression,
          group:        visitExpression,
          semantic_and: visitNop,
          semantic_not: visitNop,
          rule_ref:     visitNop,
          literal:      visitNop,
          "class":      visitNop,
          any:          visitNop
        };

    objects.defaults(functions, DEFAULT_FUNCTIONS);

    return visit;
  }
};

module.exports = visitor;
<commit_msg>Don't use "objects" in lib/compiler/visitor.js<commit_after>"use strict";

/* Simple AST node visitor builder. */
let visitor = {
  build: function(functions) {
    function visit(node) {
      return functions[node.type].apply(null, arguments);
    }

    function visitNop() { }

    function visitExpression(node) {
      let extraArgs = Array.prototype.slice.call(arguments, 1);

      visit.apply(null, [node.expression].concat(extraArgs));
    }

    function visitChildren(property) {
      return function(node) {
        let extraArgs = Array.prototype.slice.call(arguments, 1);

        node[property].forEach(child => {
          visit.apply(null, [child].concat(extraArgs));
        });
      };
    }

    const DEFAULT_FUNCTIONS = {
          grammar: function(node) {
            let extraArgs = Array.prototype.slice.call(arguments, 1);

            if (node.initializer) {
              visit.apply(null, [node.initializer].concat(extraArgs));
            }

            node.rules.forEach(rule => {
              visit.apply(null, [rule].concat(extraArgs));
            });
          },

          initializer:  visitNop,
          rule:         visitExpression,
          named:        visitExpression,
          choice:       visitChildren("alternatives"),
          action:       visitExpression,
          sequence:     visitChildren("elements"),
          labeled:      visitExpression,
          text:         visitExpression,
          simple_and:   visitExpression,
          simple_not:   visitExpression,
          optional:     visitExpression,
          zero_or_more: visitExpression,
          one_or_more:  visitExpression,
          group:        visitExpression,
          semantic_and: visitNop,
          semantic_not: visitNop,
          rule_ref:     visitNop,
          literal:      visitNop,
          "class":      visitNop,
          any:          visitNop
        };

    Object.keys(DEFAULT_FUNCTIONS).forEach(type => {
      if (!functions.hasOwnProperty(type)) {
        functions[type] = DEFAULT_FUNCTIONS[type];
      }
    });

    return visit;
  }
};

module.exports = visitor;
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import { doCloseModal } from 'redux/actions/app';
import { doNavigate } from 'redux/actions/navigation';
import { doSetClientSetting } from 'redux/actions/settings';
import { selectUserIsRewardApproved } from 'redux/selectors/user';
import { selectBalance } from 'redux/selectors/wallet';
import {
  makeSelectHasClaimedReward,
  makeSelectRewardByType,
  selectUnclaimedRewardValue,
} from 'redux/selectors/rewards';
import * as settings from 'constants/settings';
import ModalCreditIntro from './view';

const select = (state, props) => {
  const selectHasClaimed = makeSelectHasClaimedReward(),
    selectReward = makeSelectRewardByType();

  return {
    currentBalance: selectBalance(state),
    isRewardApproved: selectUserIsRewardApproved(state),
    totalRewardValue: selectUnclaimedRewardValue(state),
  };
};

const perform = dispatch => () => ({
  addBalance: () => {
    dispatch(doSetClientSetting(settings.CREDIT_REQUIRED_ACKNOWLEDGED, true));
    dispatch(doNavigate('/getcredits'));
    dispatch(doCloseModal());
  },
  closeModal: () => {
    dispatch(doSetClientSetting(settings.CREDIT_REQUIRED_ACKNOWLEDGED, true));
    dispatch(doCloseModal());
  },
});

export default connect(select, perform)(ModalCreditIntro);
<commit_msg>Fixed error caused by using deprecated selector<commit_after>import { connect } from 'react-redux';
import { doCloseModal } from 'redux/actions/app';
import { doNavigate } from 'redux/actions/navigation';
import { doSetClientSetting } from 'redux/actions/settings';
import { selectUserIsRewardApproved } from 'redux/selectors/user';
import { selectBalance } from 'redux/selectors/wallet';
import { selectUnclaimedRewardValue } from 'redux/selectors/rewards';
import * as settings from 'constants/settings';
import ModalCreditIntro from './view';

const select = state => ({
  currentBalance: selectBalance(state),
  isRewardApproved: selectUserIsRewardApproved(state),
  totalRewardValue: selectUnclaimedRewardValue(state),
});

const perform = dispatch => () => ({
  addBalance: () => {
    dispatch(doSetClientSetting(settings.CREDIT_REQUIRED_ACKNOWLEDGED, true));
    dispatch(doNavigate('/getcredits'));
    dispatch(doCloseModal());
  },
  closeModal: () => {
    dispatch(doSetClientSetting(settings.CREDIT_REQUIRED_ACKNOWLEDGED, true));
    dispatch(doCloseModal());
  },
});

export default connect(select, perform)(ModalCreditIntro);
<|endoftext|>


<commit_before>// Copyright 2013 Stuart P. Bentley.
// This work may be used freely as long as this notice is included.
// The work is provided "as is" without warranty, express or implied.

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

var filters;
var allFilterRegexp;

function loadFilters(){
  filters = localStorage.getItem('filters');
  allFilterRegexp = new RegExp('('
    + filters.keys
      .filter(function(fil){return fil.enabled})
      .sort(function(m,n){
        return m.length == n.length ? m < n : m.length > n.length})
      .map(function(fil){return fil.inword})
      .map(escapeRegExp)
      .join('|')
    + ')','gi');
}

function caseMatchSpan(source,base,output) {
  return base == base.toLowerCase ?
  // If the span is expected to be all lower-case
    source != source.toLowerCase && source == source.toUpperCase ?
      output.toUpperCase : output
    // Only capitalize the output if the source is entirely upper-case
    : base == base.toUpperCase ?
    // If the span is expected to be all upper-case
      source != source.toUpperCase && source == source.toLowerCase ?
        output.toLowerCase : output
      // Only lowercase the output if the source is entirely lower-case
    // Otherwise, if the input matches either full-case push,
    // push the output to that case
    : source != source.toLowerCase && source == source.toUpperCase ?
      output.toUpperCase
    : source != source.toUpperCase && source == source.toLowerCase ?
      output.toLowerCase
    : output;
}

// Slice against, for arrays or strings.
function sliceAgainst(i, ars, other) {
  return ars.slice(
    Math.floor(i/other.length*ars.length),
    Math.floor((i+1)/other.length*ars.length));
}

function caseMatchWords(source, base, output) {
  //special case the first letter
  var result = caseMatchSpan(source[0],base[0],output[0]);

  var sRest = source.slice(1);
  var bRest = base.slice(1);
  var oRest = output.slice(1);

  for(var i = 0; i < Math.min(bRest.length,oRest.length); i++){
    result += caseMatchSpan(
      sliceAgainst(i, sRest, oRest),
      sliceAgainst(i, bRest, oRest),
      sliceAgainst(i, oRest, bRest));
  }
}

function replacement(match) {
  var filter = filters[match.toLowerCase()];

  var inWords = filter.inword.split(' ');
  var outWords = filter.outword.split(' ');
  var matchWords = match.split(' ');

  var iwl = inWords.length;
  var owl = outWords.length;

  var replacementWords = [];

  for(var i = 0; i < Math.min(iwl,owl); i++){
    replacementWords[i] = caseMatchWords(
      sliceAgainst(i,matchWords,outWords),
      sliceAgainst(i,inWords,outWords),
      sliceAgainst(i,outWords,inWords));
  }

  return replacementWords.join(' ');
}

function performSubstitutions(str) {
  return str.replace(allFilterRegexp, replacement);
}

// define the nodeType value for TEXT_NODEs (the kind we want to replace)
// Some browsers may fail to make this value available - it's 3
var TEXT_NODE = Node.TEXT_NODE || 3;

// Semaphore to signal that we're replacing text, so that our changes don't
// trigger recursive substitutions
var replacingContent = false;

function replaceTextContent(node) {
  if (~node.textContent.search(allFilterRegexp)) {
    //flag that content is being replaced so the event it generates
    //won't trigger another replacement
    replacingContent = true;
    node.textContent = performSubstitutions(node.textContent);
    replacingContent = false;
  }
}

function changeTextNodes(node) {
  var length, childNodes;
  //If this is a text node, attempt substitutions on it
  if (node.nodeType == TEXT_NODE) {
    replaceTextContent(node);
  //If this is anything other than a text node, recurse any children
  } else {
    childNodes = node.childNodes;
    length = childNodes.length;
    for(var i = 0; i < length; ++i){
      changeTextNodes(childNodes[i]);
    }
  }
}

function insertion_listener(event) {
  //change any new text nodes in a node that is added to the body
  changeTextNodes(event.target);
}

function cdm_listener(event) {
  //avoid infinite loop by ignoring events triggered by replacement
  if(!replacingContent){
    replaceTextContent(event.target);
  }
}

loadFilters();
changeTextNodes(document.body);
document.title = performSubstitutions(document.title);
document.body.addEventListener("DOMNodeInserted", insertion_listener, false);
document.body.addEventListener("DOMCharacterDataModified", cdm_listener, false);
<commit_msg>Fix sequences being split into more parts than possible<commit_after>// Copyright 2013 Stuart P. Bentley.
// This work may be used freely as long as this notice is included.
// The work is provided "as is" without warranty, express or implied.

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

var filters;
var allFilterRegexp;

function loadFilters(){
  filters = localStorage.getItem('filters');
  allFilterRegexp = new RegExp('('
    + filters.keys
      .filter(function(fil){return fil.enabled})
      .sort(function(m,n){
        return m.length == n.length ? m < n : m.length > n.length})
      .map(function(fil){return fil.inword})
      .map(escapeRegExp)
      .join('|')
    + ')','gi');
}

function caseMatchSpan(source,base,output) {
  // When the span has an entire case that doesn't match the entire case of
  // the expected text, transform it to match
  return source == source.toLowerCase() && source != source.toUpperCase() ?
      base == base.toLowerCase() && base != base.toUpperCase() ? output :
      output.toLowerCase()
    : source == source.toUpperCase() && source != source.toLowerCase() ?
      base == base.toUpperCase() && base != base.toLowerCase() ? output :
      output.toUpperCase()
    : output;
}

// Slice against, for arrays or strings.
function sliceOf(ars, i, parts) {
  return ars.slice(
    Math.floor(i/parts*ars.length),
    Math.floor((i+1)/parts*ars.length));
}

// NOTE: This function takes in strings of "words", which is wrong.
// It's supposed to apply for each word in the output, according to the nearest
// word in the input.
// That said, it's good enough right now.
function caseMatchWords(source, base, output) {
  //special case the first letter
  var result = caseMatchSpan(source[0],base[0],output[0]);

  var sRest = source.slice(1);
  var bRest = base.slice(1);
  var oRest = output.slice(1);

  var parts = Math.min(bRest.length,oRest.length);

  for(var i = 0; i < parts; i++){
    result += caseMatchSpan(
      sliceOf(sRest, i, parts),
      sliceOf(bRest, i, parts),
      sliceOf(oRest, i, parts));
  }

  return result;
}

function replacement(match) {
  var filter = filters[match.toLowerCase()];

  var inWords = filter.inword.split(' ');
  var outWords = filter.outword.split(' ');
  var matchWords = match.split(' ');

  var replacementWords = [];

  var parts = Math.min(inWords.length,outWords.length);

  for(var i = 0; i < parts; i++){
    replacementWords[i] = caseMatchWords(
      sliceOf(matchWords, i, parts).join(' '),
      sliceOf(inWords, i, parts).join(' '),
      sliceOf(outWords, i, parts).join(' '));
  }

  return replacementWords.join(' ');
}

function performSubstitutions(str) {
  return str.replace(allFilterRegexp, replacement);
}

// define the nodeType value for TEXT_NODEs (the kind we want to replace)
// Some browsers may fail to make this value available - it's 3
var TEXT_NODE = Node.TEXT_NODE || 3;

// Semaphore to signal that we're replacing text, so that our changes don't
// trigger recursive substitutions
var replacingContent = false;

function replaceTextContent(node) {
  if (~node.textContent.search(allFilterRegexp)) {
    //flag that content is being replaced so the event it generates
    //won't trigger another replacement
    replacingContent = true;
    node.textContent = performSubstitutions(node.textContent);
    replacingContent = false;
  }
}

function changeTextNodes(node) {
  var length, childNodes;
  //If this is a text node, attempt substitutions on it
  if (node.nodeType == TEXT_NODE) {
    replaceTextContent(node);
  //If this is anything other than a text node, recurse any children
  } else {
    childNodes = node.childNodes;
    length = childNodes.length;
    for(var i = 0; i < length; ++i){
      changeTextNodes(childNodes[i]);
    }
  }
}

function insertion_listener(event) {
  //change any new text nodes in a node that is added to the body
  changeTextNodes(event.target);
}

function cdm_listener(event) {
  //avoid infinite loop by ignoring events triggered by replacement
  if(!replacingContent){
    replaceTextContent(event.target);
  }
}

loadFilters();
changeTextNodes(document.body);
document.title = performSubstitutions(document.title);
document.body.addEventListener("DOMNodeInserted", insertion_listener, false);
document.body.addEventListener("DOMCharacterDataModified", cdm_listener, false);
<|endoftext|>


<commit_before>// Copyright (c) 2016, Matt Godbolt & Rubén Rincón
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

const BaseCompiler = require('../base-compiler'),
    _ = require('underscore-node');

class GolangCompiler extends BaseCompiler {
    convertNewGoL(code) {
        const re = /^\s+(0[xX]?[0-9A-Za-z]+)?\s?[0-9]+\s*\(([^:]+):([0-9]+)\)\s*([A-Z]+)(.*)/;
        const reUnknown = /^\s+(0[xX]?[0-9A-Za-z]+)?\s?[0-9]+\s*\(<unknown line number>)\s*([A-Z]+)(.*)/;
        let prevLine = null;
        let file = null;
        let fileCount = 0;
        return _.compact(code.map(obj => {
            const line = obj.text;
            let match = line.match(re);
            if (match) {
                let res = "";
                if (file !== match[2]) {
                    fileCount++;
                    res += "\t.file " + fileCount + ' "' + match[2] + '"\n';
                    file = match[2];
                }
                if (prevLine !== match[3]) {
                    res += "\t.loc " + fileCount + " " + match[3] + " 0\n";
                    prevLine = match[3];
                }
                return res + "\t" + match[4].toLowerCase() + match[5];
            } else {
                match = line.match(reUnknown);
                if (match) {
                    return "\t" + match[2].toLowerCase() + match[3];
                } else {
                    return null;
                }
            }

        })).join("\n");
    }

    postProcess(result) {
        result.asm = this.convertNewGoL(result.stdout);
        result.stdout = [];
        return Promise.resolve(result);
    }

    optionsForFilter(filters, outputFilename) {
        // If we're dealing with an older version...
        if (this.compiler.id === '6g141') {
            return ['tool', '6g', '-g', '-o', outputFilename, '-S'];
        }
        return ['tool', 'compile', '-o', outputFilename, '-S'];
    }

    getDefaultExecOptions() {
        const execOptions = super.getDefaultExecOptions();
        const goroot = this.compilerProps("compiler." + this.compiler.id + ".goroot");
        if (goroot) {
            execOptions.env.GOROOT = goroot;
        }
        return execOptions;
    }
}

module.exports = GolangCompiler;
<commit_msg>missed a slash<commit_after>// Copyright (c) 2016, Matt Godbolt & Rubén Rincón
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

const BaseCompiler = require('../base-compiler'),
    _ = require('underscore-node');

class GolangCompiler extends BaseCompiler {
    convertNewGoL(code) {
        const re = /^\s+(0[xX]?[0-9A-Za-z]+)?\s?[0-9]+\s*\(([^:]+):([0-9]+)\)\s*([A-Z]+)(.*)/;
        const reUnknown = /^\s+(0[xX]?[0-9A-Za-z]+)?\s?[0-9]+\s*\(<unknown line number>\)\s*([A-Z]+)(.*)/;
        let prevLine = null;
        let file = null;
        let fileCount = 0;
        return _.compact(code.map(obj => {
            const line = obj.text;
            let match = line.match(re);
            if (match) {
                let res = "";
                if (file !== match[2]) {
                    fileCount++;
                    res += "\t.file " + fileCount + ' "' + match[2] + '"\n';
                    file = match[2];
                }
                if (prevLine !== match[3]) {
                    res += "\t.loc " + fileCount + " " + match[3] + " 0\n";
                    prevLine = match[3];
                }
                return res + "\t" + match[4].toLowerCase() + match[5];
            } else {
                match = line.match(reUnknown);
                if (match) {
                    return "\t" + match[2].toLowerCase() + match[3];
                } else {
                    return null;
                }
            }

        })).join("\n");
    }

    postProcess(result) {
        result.asm = this.convertNewGoL(result.stdout);
        result.stdout = [];
        return Promise.resolve(result);
    }

    optionsForFilter(filters, outputFilename) {
        // If we're dealing with an older version...
        if (this.compiler.id === '6g141') {
            return ['tool', '6g', '-g', '-o', outputFilename, '-S'];
        }
        return ['tool', 'compile', '-o', outputFilename, '-S'];
    }

    getDefaultExecOptions() {
        const execOptions = super.getDefaultExecOptions();
        const goroot = this.compilerProps("compiler." + this.compiler.id + ".goroot");
        if (goroot) {
            execOptions.env.GOROOT = goroot;
        }
        return execOptions;
    }
}

module.exports = GolangCompiler;
<|endoftext|>


<commit_before>var React = require('react');
var ReactDOM = require('react-dom');
var ExecutionEnvironment = require('exenv');
var ModalPortal = React.createFactory(require('./ModalPortal'));
var ariaAppHider = require('../helpers/ariaAppHider');
var elementClass = require('element-class');
var renderSubtreeIntoContainer = require("react-dom").unstable_renderSubtreeIntoContainer;
var Assign = require('lodash.assign');

var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};
var AppElement = ExecutionEnvironment.canUseDOM ? document.body : {appendChild: function() {}};

function getParentElement(parentSelector) {
  return parentSelector();
}

var Modal = React.createClass({

  displayName: 'Modal',
  statics: {
    setAppElement: function(element) {
        AppElement = ariaAppHider.setElement(element);
    },
    injectCSS: function() {
      "production" !== process.env.NODE_ENV
        && console.warn('React-Modal: injectCSS has been deprecated ' +
                        'and no longer has any effect. It will be removed in a later version');
    }
  },

  propTypes: {
    isOpen: React.PropTypes.bool.isRequired,
    style: React.PropTypes.shape({
      content: React.PropTypes.object,
      overlay: React.PropTypes.object
    }),
    portalClassName: React.PropTypes.string,
    appElement: React.PropTypes.instanceOf(SafeHTMLElement),
    onAfterOpen: React.PropTypes.func,
    onRequestClose: React.PropTypes.func,
    closeTimeoutMS: React.PropTypes.number,
    ariaHideApp: React.PropTypes.bool,
    shouldCloseOnOverlayClick: React.PropTypes.bool,
    parentSelector: React.PropTypes.func,
    role: React.PropTypes.string,
    contentLabel: React.PropTypes.string.isRequired
  },

  getDefaultProps: function () {
    return {
      isOpen: false,
      portalClassName: 'ReactModalPortal',
      ariaHideApp: true,
      closeTimeoutMS: 0,
      shouldCloseOnOverlayClick: true,
      parentSelector: function () { return document.body; }
    };
  },

  componentDidMount: function() {
    this.node = document.createElement('div');
    this.node.className = this.props.portalClassName;

    var parent = getParentElement(this.props.parentSelector);
    parent.appendChild(this.node);
    this.renderPortal(this.props);
  },

  componentWillReceiveProps: function(newProps) {
    var currentParent = getParentElement(this.props.parentSelector);
    var newParent = getParentElement(newProps.parentSelector);

    if(newParent !== currentParent) {
      currentParent.removeChild(this.node);
      newParent.appendChild(this.node);
    }

    this.renderPortal(newProps);
  },

  componentWillUnmount: function() {
    if (this.props.ariaHideApp) {
      ariaAppHider.show(this.props.appElement);
    }

    var state = this.portal.state;
    var now = Date.now();
    var closesAt = state.isOpen && this.props.closeTimeoutMS
      && (state.closesAt
        || now + this.props.closeTimeoutMS);

    if (closesAt) {
      if (!state.beforeClose) {
        this.portal.closeWithTimeout();
      }

      setTimeout(function() { this.removePortal(); }, closesAt - now);
    } else {
      this.removePortal();
    }
  },

  removePortal: function() {
    ReactDOM.unmountComponentAtNode(this.node);
    var parent = getParentElement(this.props.parentSelector);
    parent.removeChild(this.node);
    elementClass(document.body).remove('ReactModal__Body--open');
  },

  renderPortal: function(props) {
    if (props.isOpen) {
      elementClass(document.body).add('ReactModal__Body--open');
    } else {
      elementClass(document.body).remove('ReactModal__Body--open');
    }

    if (props.ariaHideApp) {
      ariaAppHider.toggle(props.isOpen, props.appElement);
    }

    this.portal = renderSubtreeIntoContainer(this, ModalPortal(Assign({}, props, {defaultStyles: Modal.defaultStyles})), this.node);
  },

  render: function () {
    return React.DOM.noscript();
  }
});

Modal.defaultStyles = {
  overlay: {
    position        : 'fixed',
    top             : 0,
    left            : 0,
    right           : 0,
    bottom          : 0,
    backgroundColor : 'rgba(255, 255, 255, 0.75)'
  },
  content: {
    position                : 'absolute',
    top                     : '40px',
    left                    : '40px',
    right                   : '40px',
    bottom                  : '40px',
    border                  : '1px solid #ccc',
    background              : '#fff',
    overflow                : 'auto',
    WebkitOverflowScrolling : 'touch',
    borderRadius            : '4px',
    outline                 : 'none',
    padding                 : '20px'
  }
}

module.exports = Modal
<commit_msg>[fixed] remove portal context in timeout (#353)<commit_after>var React = require('react');
var ReactDOM = require('react-dom');
var ExecutionEnvironment = require('exenv');
var ModalPortal = React.createFactory(require('./ModalPortal'));
var ariaAppHider = require('../helpers/ariaAppHider');
var elementClass = require('element-class');
var renderSubtreeIntoContainer = require("react-dom").unstable_renderSubtreeIntoContainer;
var Assign = require('lodash.assign');

var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};
var AppElement = ExecutionEnvironment.canUseDOM ? document.body : {appendChild: function() {}};

function getParentElement(parentSelector) {
  return parentSelector();
}

var Modal = React.createClass({

  displayName: 'Modal',
  statics: {
    setAppElement: function(element) {
        AppElement = ariaAppHider.setElement(element);
    },
    injectCSS: function() {
      "production" !== process.env.NODE_ENV
        && console.warn('React-Modal: injectCSS has been deprecated ' +
                        'and no longer has any effect. It will be removed in a later version');
    }
  },

  propTypes: {
    isOpen: React.PropTypes.bool.isRequired,
    style: React.PropTypes.shape({
      content: React.PropTypes.object,
      overlay: React.PropTypes.object
    }),
    portalClassName: React.PropTypes.string,
    appElement: React.PropTypes.instanceOf(SafeHTMLElement),
    onAfterOpen: React.PropTypes.func,
    onRequestClose: React.PropTypes.func,
    closeTimeoutMS: React.PropTypes.number,
    ariaHideApp: React.PropTypes.bool,
    shouldCloseOnOverlayClick: React.PropTypes.bool,
    parentSelector: React.PropTypes.func,
    role: React.PropTypes.string,
    contentLabel: React.PropTypes.string.isRequired
  },

  getDefaultProps: function () {
    return {
      isOpen: false,
      portalClassName: 'ReactModalPortal',
      ariaHideApp: true,
      closeTimeoutMS: 0,
      shouldCloseOnOverlayClick: true,
      parentSelector: function () { return document.body; }
    };
  },

  componentDidMount: function() {
    this.node = document.createElement('div');
    this.node.className = this.props.portalClassName;

    var parent = getParentElement(this.props.parentSelector);
    parent.appendChild(this.node);
    this.renderPortal(this.props);
  },

  componentWillReceiveProps: function(newProps) {
    var currentParent = getParentElement(this.props.parentSelector);
    var newParent = getParentElement(newProps.parentSelector);

    if(newParent !== currentParent) {
      currentParent.removeChild(this.node);
      newParent.appendChild(this.node);
    }

    this.renderPortal(newProps);
  },

  componentWillUnmount: function() {
    if (this.props.ariaHideApp) {
      ariaAppHider.show(this.props.appElement);
    }

    var state = this.portal.state;
    var now = Date.now();
    var closesAt = state.isOpen && this.props.closeTimeoutMS
      && (state.closesAt
        || now + this.props.closeTimeoutMS);

    if (closesAt) {
      if (!state.beforeClose) {
        this.portal.closeWithTimeout();
      }

      var that = this;
      setTimeout(function() { that.removePortal(); }, closesAt - now);
    } else {
      this.removePortal();
    }
  },

  removePortal: function() {
    ReactDOM.unmountComponentAtNode(this.node);
    var parent = getParentElement(this.props.parentSelector);
    parent.removeChild(this.node);
    elementClass(document.body).remove('ReactModal__Body--open');
  },

  renderPortal: function(props) {
    if (props.isOpen) {
      elementClass(document.body).add('ReactModal__Body--open');
    } else {
      elementClass(document.body).remove('ReactModal__Body--open');
    }

    if (props.ariaHideApp) {
      ariaAppHider.toggle(props.isOpen, props.appElement);
    }

    this.portal = renderSubtreeIntoContainer(this, ModalPortal(Assign({}, props, {defaultStyles: Modal.defaultStyles})), this.node);
  },

  render: function () {
    return React.DOM.noscript();
  }
});

Modal.defaultStyles = {
  overlay: {
    position        : 'fixed',
    top             : 0,
    left            : 0,
    right           : 0,
    bottom          : 0,
    backgroundColor : 'rgba(255, 255, 255, 0.75)'
  },
  content: {
    position                : 'absolute',
    top                     : '40px',
    left                    : '40px',
    right                   : '40px',
    bottom                  : '40px',
    border                  : '1px solid #ccc',
    background              : '#fff',
    overflow                : 'auto',
    WebkitOverflowScrolling : 'touch',
    borderRadius            : '4px',
    outline                 : 'none',
    padding                 : '20px'
  }
}

module.exports = Modal
<|endoftext|>


<commit_before>/*!
 * node-minify
 * Copyright(c) 2011-2016 Rodolphe Stoclin
 * MIT Licensed
 */

'use strict';

/**
 * Module dependencies.
 */

var Promise = require('bluebird');
var csso = require('csso');
var utils = require('../utils');

/**
 * Expose `compressCSSO()`.
 */

module.exports = compressCSSO;

/**
 * Run csso.
 *
 * @param {Object} settings
 * @param {String} content
 */

function compressCSSO(settings, content) {
  return new Promise(function(resolve) {
    var contentMinified = csso.minify(content, settings.options.restructureOff);
    utils.writeFile(settings.output, contentMinified);
    resolve(contentMinified);
  });
}
<commit_msg>Fix CSSO compressor output due to package upgrade<commit_after>/*!
 * node-minify
 * Copyright(c) 2011-2016 Rodolphe Stoclin
 * MIT Licensed
 */

'use strict';

/**
 * Module dependencies.
 */

var Promise = require('bluebird');
var csso = require('csso');
var utils = require('../utils');

/**
 * Expose `compressCSSO()`.
 */

module.exports = compressCSSO;

/**
 * Run csso.
 *
 * @param {Object} settings
 * @param {String} content
 */

function compressCSSO(settings, content) {
  return new Promise(function(resolve) {
    var contentMinified = csso.minify(content, settings.options.restructureOff);
    utils.writeFile(settings.output, contentMinified.css);
    resolve(contentMinified.css);
  });
}
<|endoftext|>


<commit_before>"use strict";

const Bluebird = require('bluebird');

const defaultFlagMap = [
    { match: String, make: String, guess: s => s!==null },
    { match: Number, make: Number, guess: s => s!==null && !isNaN(s) },
    { match: Boolean, make: s => s === 'true', guess: s => (s === 'true' || s === 'false') },
    { match: Date, make: s=> new Date(s), guess: function(s) {
        if ( !s ) return false;
        if ( !s.match(/[0-9]{4}.*([0-9]{2}:[0-9]{2})?/)) return false;
        var t=new Date(s).getTime();
        if ( t===0 || isNaN(t) || t>=9999999999999 ) return false;
        return true;
    }}
];

const defaultOptions = {
    mapTypes: true,
    guessTypes: false,
    typeMapFlags: defaultFlagMap,
    defaultType: defaultFlagMap[0],
    concurrency: 10
};

function consulKvObjectForge(kvSync, userOptions) {
    if (!(kvSync && ['get', 'set', 'del'].every(k => kvSync[k] instanceof Function))) {
        throw new Error('constructing consul-kv-object requires consul.kv as argument');
    }
    const kv = Bluebird.promisifyAll(kvSync);

    const consulObjectOptions = Object.keys(defaultOptions)
        .reduce(
            function (options, defaultKey) {
                if (options[defaultKey] === undefined) {
                    options[defaultKey] = defaultOptions[defaultKey];
                }
                return options;
            }, userOptions || {});

    function wrapCosnsulOptions(param, key, value, flags, recurse) {
        var ret;
        if (param instanceof Object) {
            ret = param;
        } else {
            ret = {
                key: param
            };
        }
        if (key !== undefined) {
            ret.key = key;
        }
        if (value !== undefined) {
            ret.value = value;
        }
        if (flags !== undefined) {
            ret.flags = flags;
        }
        if (recurse !== undefined) {
            ret.recurse = true;
        }
        return ret;
    }
    function createValue(consulKey) {
        //
        // Creates javascript value based on consulObjectOptions, consul flags and flagMap
        //
        if (consulKey.Value === null) return null;

        if (consulObjectOptions.typeMapFlags && consulObjectOptions.mapTypes) {
            let type;
            if (consulKey.Flags === 0 && consulObjectOptions.guessTypes) {
                type = consulObjectOptions.typeMapFlags.filter(tmf => tmf.guess && tmf.guess(consulKey.Value)).pop().make;
            } else {
                type = (consulObjectOptions.typeMapFlags[consulKey.Flags] || consulObjectOptions.defaultType || {}).make;
            }
            let value = type(consulKey.Value);
            return value;
        } else {
            return consulKey.Value;
        }
    }
    function createKey(value, prefix) {
        var flag = 0;
        if (consulObjectOptions.typeMapFlags && consulObjectOptions.mapTypes) {

            if ( value !== null ) {
                flag = consulObjectOptions.typeMapFlags
                    .map(m => m.match)
                    .indexOf(value.constructor);
            }
        }

        return { key: prefix, value: value === null ? null : value.toString(), flag: flag };
    }

    function objectToKeyList(object, prefix, target) {
        target = target || [];
        var key;
        if (object !== null && object.constructor === Object) {
            for( key in object )
            {
                 if ( object.hasOwnProperty(key) ) {
                     objectToKeyList(object[key], (prefix ? prefix + "/" : "") + key, target );
                 }
            }

        } else {
            target.push(createKey(object, prefix));
        }
        return target;
    }

    function consulResponseToObject(err, res, prefix, callback) {
        //
        // Converts consul response into object
        //
        const prefixLen = (prefix.substr(-1) === '/' ?
              prefix.length - 1
            : prefix.length);

        if (err) {
            callback(err, null);
        }
        else {
            if (res === undefined) {
                callback(null, undefined);
                return;
            }
            var response = res.reduce(function reducePathToObject(assembly, consulKey) {
                var keyPath = consulKey.Key.substr(prefixLen).split('/');
                var key = keyPath.pop();

                var at = keyPath
                    .filter(key => !!key)
                    .reduce(function (at, key) {
                        if (at[key] === undefined) {
                            at[key] = {};
                        }
                        return at[key];
                    }, assembly);
                if (key !== "") {
                    at[key] = createValue(consulKey);
                }
                if (key === "" && keyPath.length === 0) {
                    return createValue(consulKey);
                }
                return assembly;
            }, {});
            callback(null, response);
        }
    }

    function get(keyOptions, callback) {
        const consulRequestOptions = wrapCosnsulOptions(keyOptions, undefined, undefined, undefined, true);
        return kv.get(consulRequestOptions, function (err, res) {
            consulResponseToObject(err, res, consulRequestOptions.key, callback);
        });
    }

    function set(keyOptions, values, callback) {
        const consulRequestOptions = wrapCosnsulOptions(keyOptions);
        const keyList = objectToKeyList(values, consulRequestOptions.key);
        const promisedSet =
            Bluebird.map( keyList,
                function (o) {
                    const options = wrapCosnsulOptions({}, o.key, o.value, o.flag);
                    return kv.setAsync(options);
                }, {
                concurrency: consulObjectOptions.concurrency
            });

        if (callback) {
            return Bluebird.all(promisedSet).then((data) => callback(null, data));
        }
    }
    function del(keyOptions, callback) {
        const consulRequestOptions = wrapCosnsulOptions(keyOptions, undefined, undefined, undefined, true);
        return kv.del(consulRequestOptions, callback || (() => { }));
    }

    var cko = {
        "get": get,
        "set": set,
        "del": del
    };
    return cko;
}

module.exports = consulKvObjectForge; <commit_msg>.all wrapper is no longer required<commit_after>"use strict";

const Bluebird = require('bluebird');

const defaultFlagMap = [
    { match: String, make: String, guess: s => s!==null },
    { match: Number, make: Number, guess: s => s!==null && !isNaN(s) },
    { match: Boolean, make: s => s === 'true', guess: s => (s === 'true' || s === 'false') },
    { match: Date, make: s=> new Date(s), guess: function(s) {
        if ( !s ) return false;
        if ( !s.match(/[0-9]{4}.*([0-9]{2}:[0-9]{2})?/)) return false;
        var t=new Date(s).getTime();
        if ( t===0 || isNaN(t) || t>=9999999999999 ) return false;
        return true;
    }}
];

const defaultOptions = {
    mapTypes: true,
    guessTypes: false,
    typeMapFlags: defaultFlagMap,
    defaultType: defaultFlagMap[0],
    concurrency: 10
};

function consulKvObjectForge(kvSync, userOptions) {
    if (!(kvSync && ['get', 'set', 'del'].every(k => kvSync[k] instanceof Function))) {
        throw new Error('constructing consul-kv-object requires consul.kv as argument');
    }
    const kv = Bluebird.promisifyAll(kvSync);

    const consulObjectOptions = Object.keys(defaultOptions)
        .reduce(
            function (options, defaultKey) {
                if (options[defaultKey] === undefined) {
                    options[defaultKey] = defaultOptions[defaultKey];
                }
                return options;
            }, userOptions || {});

    function wrapCosnsulOptions(param, key, value, flags, recurse) {
        var ret;
        if (param instanceof Object) {
            ret = param;
        } else {
            ret = {
                key: param
            };
        }
        if (key !== undefined) {
            ret.key = key;
        }
        if (value !== undefined) {
            ret.value = value;
        }
        if (flags !== undefined) {
            ret.flags = flags;
        }
        if (recurse !== undefined) {
            ret.recurse = true;
        }
        return ret;
    }
    function createValue(consulKey) {
        //
        // Creates javascript value based on consulObjectOptions, consul flags and flagMap
        //
        if (consulKey.Value === null) return null;

        if (consulObjectOptions.typeMapFlags && consulObjectOptions.mapTypes) {
            let type;
            if (consulKey.Flags === 0 && consulObjectOptions.guessTypes) {
                type = consulObjectOptions.typeMapFlags.filter(tmf => tmf.guess && tmf.guess(consulKey.Value)).pop().make;
            } else {
                type = (consulObjectOptions.typeMapFlags[consulKey.Flags] || consulObjectOptions.defaultType || {}).make;
            }
            let value = type(consulKey.Value);
            return value;
        } else {
            return consulKey.Value;
        }
    }
    function createKey(value, prefix) {
        var flag = 0;
        if (consulObjectOptions.typeMapFlags && consulObjectOptions.mapTypes) {

            if ( value !== null ) {
                flag = consulObjectOptions.typeMapFlags
                    .map(m => m.match)
                    .indexOf(value.constructor);
            }
        }

        return { key: prefix, value: value === null ? null : value.toString(), flag: flag };
    }

    function objectToKeyList(object, prefix, target) {
        target = target || [];
        var key;
        if (object !== null && object.constructor === Object) {
            for( key in object )
            {
                 if ( object.hasOwnProperty(key) ) {
                     objectToKeyList(object[key], (prefix ? prefix + "/" : "") + key, target );
                 }
            }

        } else {
            target.push(createKey(object, prefix));
        }
        return target;
    }

    function consulResponseToObject(err, res, prefix, callback) {
        //
        // Converts consul response into object
        //
        const prefixLen = (prefix.substr(-1) === '/' ?
              prefix.length - 1
            : prefix.length);

        if (err) {
            callback(err, null);
        }
        else {
            if (res === undefined) {
                callback(null, undefined);
                return;
            }
            var response = res.reduce(function reducePathToObject(assembly, consulKey) {
                var keyPath = consulKey.Key.substr(prefixLen).split('/');
                var key = keyPath.pop();

                var at = keyPath
                    .filter(key => !!key)
                    .reduce(function (at, key) {
                        if (at[key] === undefined) {
                            at[key] = {};
                        }
                        return at[key];
                    }, assembly);
                if (key !== "") {
                    at[key] = createValue(consulKey);
                }
                if (key === "" && keyPath.length === 0) {
                    return createValue(consulKey);
                }
                return assembly;
            }, {});
            callback(null, response);
        }
    }

    function get(keyOptions, callback) {
        const consulRequestOptions = wrapCosnsulOptions(keyOptions, undefined, undefined, undefined, true);
        return kv.get(consulRequestOptions, function (err, res) {
            consulResponseToObject(err, res, consulRequestOptions.key, callback);
        });
    }

    function set(keyOptions, values, callback) {
        const consulRequestOptions = wrapCosnsulOptions(keyOptions);
        const keyList = objectToKeyList(values, consulRequestOptions.key);
        const promisedSet =
            Bluebird.map( keyList,
                function (o) {
                    const options = wrapCosnsulOptions({}, o.key, o.value, o.flag);
                    return kv.setAsync(options);
                }, {
                concurrency: consulObjectOptions.concurrency
            });

        if (callback) {
            return promisedSet.then((data) => callback(null, data));
        }
    }
    function del(keyOptions, callback) {
        const consulRequestOptions = wrapCosnsulOptions(keyOptions, undefined, undefined, undefined, true);
        return kv.del(consulRequestOptions, callback || (() => { }));
    }

    var cko = {
        "get": get,
        "set": set,
        "del": del
    };
    return cko;
}

module.exports = consulKvObjectForge; <|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

// Provides class sap.ui.core.util.File
sap.ui.define(['jquery.sap.global', 'sap/ui/Device'],
	function(jQuery, Device) {
	'use strict';

	/**
	 * Utility class to handle files.
	 *
	 * @class Utility class to handle files
	 * @author SAP SE
	 * @version ${version}
	 * @static
	 *
	 * @public
	 * @since 1.22.0
	 * @alias sap.ui.core.util.File
	 */
	var File = {

		/**
		 *
Triggers a download / save action of the given file.

		 *
		 *
There are limitations for this feature in some browsers:

		 *
		 *
Internet Explorer 8 / 9

		 * Some file extensions on some operating systems are not working due to a bug in IE.
		 * Therefore 'txt' will be used as file extension if the problem is occurring.

		 *
		 *
Safari 6 / 7 (OS X)

		 * A new window/tab will be opened. The user has to manually save the file (CMD + S), choose "page source" and specify a filename.

		 *
		 *
Mobile Safari (iOS)

		 * Not supported

		 *
		 *
Android Browser

		 * Not supported

		 *
		 * @param {string} sData file content
		 * @param {string} sFileName file name
		 * @param {string} sFileExtension file extension
		 * @param {string} sMimeType file mime-type
		 * @param {string} sCharset file charset
		 *
		 * @public
		 */
		save: function(sData, sFileName, sFileExtension, sMimeType, sCharset) {
			var sFullFileName = sFileName + '.' + sFileExtension;

			// prepend utf-8 byte-order-mark (BOM) to prevent encoding issues in .csv files
			if (sCharset === 'utf-8' && sFileExtension === 'csv') {
				sData = '\ufeff' + sData;
			}

			if (window.Blob) {
				var sType = 'data:' + sMimeType;
				if (sCharset) {
					sType += ';charset=' + sCharset;
				}
				var oBlob = new window.Blob([ sData ], { type: sType });

				// IE 10+ (native saveAs FileAPI)
				if (window.navigator.msSaveOrOpenBlob) {
					window.navigator.msSaveOrOpenBlob(oBlob, sFullFileName);
				} else {
					var oURL = window.URL || window.webkitURL;
					var sBlobUrl = oURL.createObjectURL(oBlob);

					var oLink = window.document.createElement('a');
					if ('download' in oLink) {
						// use an anchor link with download attribute for download
						var $body = jQuery(document.body);
						var $link = jQuery(oLink).attr({
							download: sFullFileName,
							href: sBlobUrl,
							style: 'display:none'
						});
						$body.append($link);
						$link.get(0).click();

						$link.remove();
					} else {
						// remove utf-8 byte-order-mark (BOM) again to prevent an exception when using btoa
						if (sData && sCharset === 'utf-8' && sFileExtension === 'csv') {
							sData = sData.substr(1);
						}
						// Safari (user has to save the file manually)
						window.open(sType + ";base64," + window.btoa(sData));
					}
				}
			} else if (Device.browser.internet_explorer && Device.browser.version <= 9) {
				// iframe fallback for IE 8/9
				var $body = jQuery(document.body);
				var $iframe = jQuery('', {
					style: 'display:none'
				});
				$body.append($iframe);
				var oDocument = $iframe.get(0).contentWindow.document;
				// open the document to be able to modify it
				oDocument.open(sMimeType, 'replace');
				// set charset (e.g. utf-8) if given
				if (sCharset) {
					oDocument.charset = sCharset;
				}
				// write content to iframe
				oDocument.write(sData);
				oDocument.close();

				// open the file-save dialog
				// measure the time that the execCommand takes to detect an
				// IE bug with some file extensions on some OS (e.g. Windows Server 2008 E2 Enterprise SP1) in all IE versions:
				// http://stackoverflow.com/questions/2515791/execcommandsaveas-null-file-csv-is-not-working-in-ie8
				var oTime = new Date();
				var bSuccess = oDocument.execCommand('SaveAs', false, sFullFileName);
				if (!bSuccess && new Date() - oTime < 10) {
					// execCommand returns false either when the user clicks on cancel or
					// when the bug mentioned above is occurring, so the time is measured
					// to detect the cancel action

					// .txt as file extension will work on all systems
					oDocument.execCommand('SaveAs', false, sFullFileName + '.txt');
				}

				// cleanup
				$iframe.remove();
			}
		}
	};

	return File;
}, /* bExport= */ true);
<commit_msg>[FIX] sap.ui.core.util.File: Throw error when window was blocked (Safari 9)<commit_after>/*!
 * ${copyright}
 */

// Provides class sap.ui.core.util.File
sap.ui.define(['jquery.sap.global', 'sap/ui/Device'],
	function(jQuery, Device) {
	'use strict';

	/**
	 * Utility class to handle files.
	 *
	 * @class Utility class to handle files
	 * @author SAP SE
	 * @version ${version}
	 * @static
	 *
	 * @public
	 * @since 1.22.0
	 * @alias sap.ui.core.util.File
	 */
	var File = {

		/**
		 *
Triggers a download / save action of the given file.

		 *
		 *
There are limitations for this feature in some browsers:

		 *
		 *
Internet Explorer 8 / 9

		 * Some file extensions on some operating systems are not working due to a bug in IE.
		 * Therefore 'txt' will be used as file extension if the problem is occurring.

		 *
		 *
Safari (OS X / iOS)

		 * A new window/tab will be opened. In OS X the user has to manually save the file (CMD + S), choose "page source" and specify a filename.
		 * In iOS the content can be opened in another app (Mail, Notes, ...) or copied to the clipboard.
		 * In case the popup blocker prevents this action, an error will be thrown which can be used to notify the user to disable it.

		 *
		 *
Android Browser

		 * Not supported

		 *
		 * @param {string} sData file content
		 * @param {string} sFileName file name
		 * @param {string} sFileExtension file extension
		 * @param {string} sMimeType file mime-type
		 * @param {string} sCharset file charset
		 *
		 * @public
		 */
		save: function(sData, sFileName, sFileExtension, sMimeType, sCharset) {
			var sFullFileName = sFileName + '.' + sFileExtension;

			// prepend utf-8 byte-order-mark (BOM) to prevent encoding issues in .csv files
			if (sCharset === 'utf-8' && sFileExtension === 'csv') {
				sData = '\ufeff' + sData;
			}

			if (window.Blob) {
				var sType = 'data:' + sMimeType;
				if (sCharset) {
					sType += ';charset=' + sCharset;
				}
				var oBlob = new window.Blob([ sData ], { type: sType });

				// IE 10+ (native saveAs FileAPI)
				if (window.navigator.msSaveOrOpenBlob) {
					window.navigator.msSaveOrOpenBlob(oBlob, sFullFileName);
				} else {
					var oURL = window.URL || window.webkitURL;
					var sBlobUrl = oURL.createObjectURL(oBlob);

					var oLink = window.document.createElement('a');
					if ('download' in oLink) {
						// use an anchor link with download attribute for download
						var $body = jQuery(document.body);
						var $link = jQuery(oLink).attr({
							download: sFullFileName,
							href: sBlobUrl,
							style: 'display:none'
						});
						$body.append($link);
						$link.get(0).click();

						$link.remove();
					} else {
						// remove utf-8 byte-order-mark (BOM) again to prevent an exception when using btoa
						if (sData && sCharset === 'utf-8' && sFileExtension === 'csv') {
							sData = sData.substr(1);
						}
						// Safari (user has to save the file manually)
						var oWindow = window.open(sType + ";base64," + window.btoa(sData));
						if (!oWindow) {
							throw new Error("Could not download file. A popup blocker might be active.");
						}
					}
				}
			} else if (Device.browser.internet_explorer && Device.browser.version <= 9) {
				// iframe fallback for IE 8/9
				var $body = jQuery(document.body);
				var $iframe = jQuery('', {
					style: 'display:none'
				});
				$body.append($iframe);
				var oDocument = $iframe.get(0).contentWindow.document;
				// open the document to be able to modify it
				oDocument.open(sMimeType, 'replace');
				// set charset (e.g. utf-8) if given
				if (sCharset) {
					oDocument.charset = sCharset;
				}
				// write content to iframe
				oDocument.write(sData);
				oDocument.close();

				// open the file-save dialog
				// measure the time that the execCommand takes to detect an
				// IE bug with some file extensions on some OS (e.g. Windows Server 2008 E2 Enterprise SP1) in all IE versions:
				// http://stackoverflow.com/questions/2515791/execcommandsaveas-null-file-csv-is-not-working-in-ie8
				var oTime = new Date();
				var bSuccess = oDocument.execCommand('SaveAs', false, sFullFileName);
				if (!bSuccess && new Date() - oTime < 10) {
					// execCommand returns false either when the user clicks on cancel or
					// when the bug mentioned above is occurring, so the time is measured
					// to detect the cancel action

					// .txt as file extension will work on all systems
					oDocument.execCommand('SaveAs', false, sFullFileName + '.txt');
				}

				// cleanup
				$iframe.remove();
			}
		}
	};

	return File;
}, /* bExport= */ true);
<|endoftext|>


<commit_before>/**
 * TrackMania Callbacks
 */
'use strict';

/**
 * Run the registers.
 *
 * @param {CallbackManager} manager
 * @param {function} manager.register
 */
export default function (manager) {

  manager.register({
    callback: 'TrackMania.PlayerCheckpoint',
    event: 'trackmania.player.checkpoint',
    parameters: {
      playerId: 0,
      login: 1,
      timeOrScore: 2,
      curLap: 3,
      checkpoint: 4
    }
  });

  manager.register({
    callback: 'TrackMania.PlayerFinishCheckpoint',
    event: 'trackmania.player.finish',
    parameters: {
      playerId: 0,
      login: 1,
      timeOrScore: 2
    }
  });

  manager.register({
    callback: 'TrackMania.PlayerIncoherence',
    event: 'trackmania.player.incoherence',
    parameters: {
      playerId: 0,
      login: 1
    }
  });
}
<commit_msg>Fixing wrong callback name.<commit_after>/**
 * TrackMania Callbacks
 */
'use strict';

/**
 * Run the registers.
 *
 * @param {CallbackManager} manager
 * @param {function} manager.register
 */
export default function (manager) {

  manager.register({
    callback: 'TrackMania.PlayerCheckpoint',
    event: 'trackmania.player.checkpoint',
    parameters: {
      playerId: 0,
      login: 1,
      timeOrScore: 2,
      curLap: 3,
      checkpoint: 4
    }
  });

  manager.register({
    callback: 'TrackMania.PlayerFinish',
    event: 'trackmania.player.finish',
    parameters: {
      playerId: 0,
      login: 1,
      timeOrScore: 2
    }
  });

  manager.register({
    callback: 'TrackMania.PlayerIncoherence',
    event: 'trackmania.player.incoherence',
    parameters: {
      playerId: 0,
      login: 1
    }
  });
}
<|endoftext|>