<commit_before>$(function ()
{

	//populates the game types dropdowns
	$.getJSON( "game_types", function(json)
	{
		var values = [];

		values.push('<option value="" disabled selected>Select game type...</option>');

	  	json.forEach(function (item)
	  	{
	  		values.push('<option value="' + item.id + '">' + item.name + '</option>');
	  	});

	  	var html = values.join("");

	  	$("#game_type").html(html);
	  	$("#game_type_leader").html(html);

	  	console.log( "game_type load success" );
	})

	.fail( function ()
	{
		console.log( "game_types failed to load" );
	});

	// populates the players dropdowns
	$.getJSON( "players", function(json)
	{
		var values = [];

		values.push('<option value="" disabled selected>Select player...</option>');

	  	json.forEach(function (item)
	  	{
	  		values.push('<option value="' + item.id + '">' + item.first_name + ' \"' + item.nickname + '\" ' + item.last_name + '</option>');
	  	});

	  	var html = values.join("");

	  	$("#player1").html(html);
	  	$("#player2").html(html);

	  	renderRankTable();

	  	console.log( "players load success" );
	})

	.fail( function ()
	{
		console.log( "players failed to load" );
	});

	//create a new game in the DB
	$("#new_game_form").submit( function(event)
	{
		event.preventDefault();

		var game_form = $(this);

		var a = [];
		var type = $("#game_type").val();

		var p1 = new Object();
		p1.score = $("#part1_score").val();
		p1.players = [$("#player1").val()]; //TODO: will eventually need to change to add multiple
		a.push(p1);

		var p2 = new Object();
		p2.score = $("#part2_score").val();
		p2.players = [$("#player2").val()]; //TODO: will eventually need to change to add multiple players
		a.push(p2);

		var pars = JSON.stringify(a);

		if ($("#player1").val() == $("#player2").val())
		{
			$('#same_id').show();
		}
		else
		{
			$.post(game_form.attr("action"), {game_type: type, participants: pars}, function ()
			{
				//TODO: update rankings based on new game
				$("#match_confirmation").show();

				$('.ok').on('click', function ()
				{
					$('#match_confirmation').hide();
				});

				renderRankTable();
				game_form[0].reset();

				console.log( "game created" );

				var dLeft = (window.innerWidth - $('#game_confirmation').outerWidth()) / 2.0;
				$('#game_confirmation').css("left", dLeft + "px");
				$('#game_confirmation').fadeIn(2500, function()
				{
					window.setTimeout(function() {$('#game_confirmation').fadeOut(2500)},4000);
				});
			})

			.fail( function ()
			{
				alert("Game not created.  Required fields missing.");
			});
		}
	});

	//create a new player in the DB
	$("#new_player_form").submit( function(event)
	{
		event.preventDefault();

		var player_form = $(this);

		$.post(player_form.attr("action"), {first_name: $("#first_name").val(), nickname: $("#nickname").val(), last_name: $("#last_name").val()}, function (json)
		{
			//TODO: get full list of names (even if some have been removed)

			//Adds new player to selects
			$('#player1').append('<option value="' + json.id + '">' + json.first_name + ' \"' + json.nickname + '\" ' + json.last_name + '</option>');
			$('#player2').append('<option value="' + json.id + '">' + json.first_name + ' \"' + json.nickname + '\" ' + json.last_name + '</option>');

			$('#add_player_model').hide();

			$("#player_confirmation").show();
			$('.ok').on('click', function ()
			{
				$('#player_confirmation').hide();
			});

			console.log( "player created" );

			var dLeft = (window.innerWidth - $('#player_confirmation').outerWidth()) / 2.0;
			$('#player_confirmation').css("left", dLeft + "px");
			$('#player_confirmation').fadeIn(2500, function()
			{
				window.setTimeout(function() {$('#player_confirmation').fadeOut(2500)},4000);
			});
		})

		.fail( function ()
		{
			alert("Player not created, required fields missing.");
		});
	});

	$("#game_reset").on('click', function()
	{
		$("#same_id").hide();
	});

	// hide the same_id error message
	$("#player1").on("change", function() {
		$("#same_id").hide();
	});

	// hide the same_id error message
	$("#player2").on("change", function() {
		$("#same_id").hide();
	});

	$('#game_type_leader').on('change', renderRankTable);

	function renderRankTable() {

		$.getJSON('players', function(data) {
			var gameType = $('#game_type_leader').val(),
				ranks = data.map(function(datum) {
					var rankToDisplay;
					datum.ranks.forEach(function(rank) {
						if (rank.game_type == gameType) { rankToDisplay = rank.rank; }
					});
					return {
						fullName: datum.first_name + ' "' + datum.nickname + '" ' + datum.last_name,
						rank: rankToDisplay
					};
				}).sort(function(a, b) { return b.rank - a.rank; });
			$('#leaderboard').empty();
			ranks.forEach(function(rank, idx) {
				$('#leaderboard').append(
					$('<tr>')
						.append($('<td>').text(idx + 1))
						.append($('<td>').text(rank.fullName))
						.append($('<td>').text(rank.rank))
				);
			});
		});

	}

	// set up initial state of rank table
	renderRankTable();

});
<commit_msg>Done.<commit_after>$(function ()
{

	//populates the game types dropdowns
	$.getJSON( "game_types", function(json)
	{
		var values = [];

	  	json.forEach(function (item)
	  	{
	  		values.push('<option value="' + item.id + '">' + item.name + '</option>');
	  	});

	  	var html = values.join("");

	  	$("#game_type").html(html);
	  	$("#game_type").prepend('<option value="" disabled selected>Select game type...</option>');
	  	$("#game_type_leader").html(html);

	  	console.log( "game_type load success" );
	})

	.fail( function ()
	{
		console.log( "game_types failed to load" );
	});

	// populates the players dropdowns
	$.getJSON( "players", function(json)
	{
		var values = [];

		values.push('<option value="" disabled selected>Select player...</option>');

	  	json.forEach(function (item)
	  	{
	  		values.push('<option value="' + item.id + '">' + item.first_name + ' \"' + item.nickname + '\" ' + item.last_name + '</option>');
	  	});

	  	var html = values.join("");

	  	$("#player1").html(html);
	  	$("#player2").html(html);

	  	renderRankTable();

	  	console.log( "players load success" );
	})

	.fail( function ()
	{
		console.log( "players failed to load" );
	});

	//create a new game in the DB
	$("#new_game_form").submit( function(event)
	{
		event.preventDefault();

		var game_form = $(this);

		var a = [];
		var type = $("#game_type").val();

		var p1 = new Object();
		p1.score = $("#part1_score").val();
		p1.players = [$("#player1").val()]; //TODO: will eventually need to change to add multiple
		a.push(p1);

		var p2 = new Object();
		p2.score = $("#part2_score").val();
		p2.players = [$("#player2").val()]; //TODO: will eventually need to change to add multiple players
		a.push(p2);

		var pars = JSON.stringify(a);

		if ($("#player1").val() == $("#player2").val())
		{
			$('#same_id').show();
		}
		else
		{
			$.post(game_form.attr("action"), {game_type: type, participants: pars}, function ()
			{
				//TODO: update rankings based on new game
				$("#match_confirmation").show();

				$('.ok').on('click', function ()
				{
					$('#match_confirmation').hide();
				});

				renderRankTable();
				game_form[0].reset();

				console.log( "game created" );

				var dLeft = (window.innerWidth - $('#game_confirmation').outerWidth()) / 2.0;
				$('#game_confirmation').css("left", dLeft + "px");
				$('#game_confirmation').fadeIn(2500, function()
				{
					window.setTimeout(function() {$('#game_confirmation').fadeOut(2500)},4000);
				});
			})

			.fail( function ()
			{
				alert("Game not created.  Required fields missing.");
			});
		}
	});

	//create a new player in the DB
	$("#new_player_form").submit( function(event)
	{
		event.preventDefault();

		var player_form = $(this);

		$.post(player_form.attr("action"), {first_name: $("#first_name").val(), nickname: $("#nickname").val(), last_name: $("#last_name").val()}, function (json)
		{
			//TODO: get full list of names (even if some have been removed)

			//Adds new player to selects
			$('#player1').append('<option value="' + json.id + '">' + json.first_name + ' \"' + json.nickname + '\" ' + json.last_name + '</option>');
			$('#player2').append('<option value="' + json.id + '">' + json.first_name + ' \"' + json.nickname + '\" ' + json.last_name + '</option>');

			$('#add_player_model').hide();

			$("#player_confirmation").show();
			$('.ok').on('click', function ()
			{
				$('#player_confirmation').hide();
			});

			$("#add_player_modal").hide();
			$("#new_player_form")[0].reset();

			console.log( "player created" );

			var dLeft = (window.innerWidth - $('#player_confirmation').outerWidth()) / 2.0;
			$('#player_confirmation').css("left", dLeft + "px");
			$('#player_confirmation').fadeIn(2500, function()
			{
				window.setTimeout(function() {$('#player_confirmation').fadeOut(2500)},4000);
			});
		})

		.fail( function ()
		{
			alert("Player not created, required fields missing.");
		});
	});

	$("#game_reset").on('click', function()
	{
		$("#same_id").hide();
	});

	// hide the same_id error message
	$("#player1").on("change", function() {
		$("#same_id").hide();
	});

	// hide the same_id error message
	$("#player2").on("change", function() {
		$("#same_id").hide();
	});

	$('#game_type_leader').on('change', renderRankTable);

	function renderRankTable() {

		$.getJSON('players', function(data) {
			var gameType = $('#game_type_leader').val(),
				ranks = data.map(function(datum) {
					var rankToDisplay;
					datum.ranks.forEach(function(rank) {
						if (rank.game_type == gameType) { rankToDisplay = rank.rank; }
					});
					return {
						fullName: datum.first_name + ' "' + datum.nickname + '" ' + datum.last_name,
						rank: rankToDisplay
					};
				}).sort(function(a, b) { return b.rank - a.rank; });
			$('#leaderboard').empty();
			ranks.forEach(function(rank, idx) {
				$('#leaderboard').append(
					$('<tr>')
						.append($('<td>').text(idx + 1))
						.append($('<td>').text(rank.fullName))
						.append($('<td>').text(rank.rank))
				);
			});
		});

	}

	// set up initial state of rank table
	renderRankTable();

});
<|endoftext|>


<commit_before>(function (Scheduler, $, undefined) {
    Scheduler.Bar = function (bar_number, time_signature, bar_objects, bar_start) {
        this.bar_number = bar_number || 0;
        this.bar_objects = bar_objects || [];
        this.time_signature = time_signature || {value: 4, count: 4};
        this.bar_start = bar_start || performance.now();
        return this;
    };

    Scheduler.Bar.prototype.toString = function () {
        return "".concat(this.bar_objects);
    };

    Scheduler.Bar.initializeStartTime = function() {
        this.bar_start = performance.now();
    }

    Scheduler.currentTempo = 120;
    var bps = Scheduler.currentTempo / 60.0;
    var time_signature = {value: 4, count: 4};
    var beat_offset = 0; // This is the number of beats away from start of current bar
    Scheduler.quantization_interval_denominator = 2; // quantizes to this fraction of a beat
    Scheduler.refreshMultiplier = 8;
    Scheduler.interval = ((1.0 / bps) / Scheduler.quantization_interval_denominator * 1000);
    Scheduler.currentBar = 1;
    var bars = [new Scheduler.Bar(0, time_signature, []), new Scheduler.Bar(0, time_signature, []),
        new Scheduler.Bar(0, time_signature, []), new Scheduler.Bar(0, time_signature, []),
        new Scheduler.Bar(0, time_signature, []), new Scheduler.Bar(0, time_signature, [])];

    var bar = bars[Scheduler.currentBar];

    var quantizeBar = function (bar) {
        // bar should be an array of objects with note, timeOn, timeOff. If noteOff time is not
        // available, assume performance.now()
        // returns an array of objects with the MIDI data, and the quantized beats. Those with the same beat length
        // should be grouped together
        // values returned are relative to the beginning of the bar
        var quantized_bar = new Scheduler.Bar(0, time_signature, []);
        var bar_start = bar.bar_start;
        quantized_bar.bar_objects = bar.bar_objects.map(function (note) {
            var startBeatLocation = quantize(getBeatLocation(note.timeOn, bar_start));
            var endBeatLocation = quantize(getBeatLocation(note.timeOff, bar_start));
            return new Palette.BarObject(false,
                endBeatLocation > time_signature.count ? time_signature.count : (endBeatLocation > startBeatLocation ?
                    endBeatLocation : endBeatLocation + 1 / Scheduler.quantization_interval_denominator),
                startBeatLocation % time_signature.count,
                note.note);
        });
        return quantized_bar;
    };

    var getCurrentBar = function () {
        return Math.floor(beat_offset / time_signature.count);
    };

    Scheduler.eventLoop = function () {
        // run every tick
        // update beat offset
        beat_offset = (beat_offset + (1 / Scheduler.quantization_interval_denominator) / Scheduler.refreshMultiplier) % time_signature.count;
        if (beat_offset == 0) {
            bars.splice(0, 1);
            bars.push(new Scheduler.Bar(0, time_signature, []));
            bars[Scheduler.currentBar] = new Scheduler.Bar(0, time_signature, []);
            bar = bars[Scheduler.currentBar];
        }

        // pass bars to painter to draw
        anticipatoryMusicProducer.Painter.show("", bars.map(quantizeBar), beat_offset / time_signature.count);
    };
    /**
     * A callback that adds a given note to be drawn on the canvas
     * @param {number} note The MIDI value of the note
     * @param {number} time DOMHighResTimeStamp representing time on
     */
    Scheduler.onNoteOn = function (note, time) {
        bar.bar_objects.push(
            {
                note   : new Palette.Note(note),
                timeOn : time,
                timeOff: performance.now(),
                tempo  : Scheduler.currentTempo
            });
        //quantizeBar(bar);
    };

    /**
     * A callback that removes a given note from the canvas
     * @param {number} note The MIDI value of the note
     * @param {number} time DOMHighResTimeStamp representing time off
     */
    Scheduler.onNoteOff = function (note, time) {
        var releasedNote = bar.bar_objects.filter(function (noteObj) {
            return (noteObj.note.number == note);
        })[0];
        if (releasedNote) {
            releasedNote.timeOff = time;
        }
    };

    /**
     * quantizes a fractional beat count to the quantization interval, eg. 2.27321 => 2.25
     * @param beat_count
     * @returns {number}
     */
    var quantize = function (beat_count) {
        return Math.round((beat_count * Scheduler.quantization_interval_denominator)) / Scheduler.quantization_interval_denominator;
    };

    // Calculate elapsed beats since play start timestamp
    var getBeatLocation = function (note_start_timestamp, bar_start_timestamp) {
        var elapsed_seconds = (note_start_timestamp - bar_start_timestamp) / 1000.0;
        return elapsed_seconds * bps;
    };

})(window.anticipatoryMusicProducer.Scheduler =
    window.anticipatoryMusicProducer.Scheduler || {}, jQuery);
<commit_msg>Implemented dynamic updating of note drawing (holding a note will regularly update instead of waiting for note release)<commit_after>(function (Scheduler, $, undefined) {
    Scheduler.Bar = function (bar_number, time_signature, bar_objects, bar_start) {
        this.bar_number = bar_number || 0;
        this.bar_objects = bar_objects || [];
        this.time_signature = time_signature || {value: 4, count: 4};
        this.bar_start = bar_start || performance.now();
        return this;
    };

    Scheduler.Bar.prototype.toString = function () {
        return "".concat(this.bar_objects);
    };

    Scheduler.Bar.initializeStartTime = function() {
        this.bar_start = performance.now();
    }

    Scheduler.currentTempo = 120;
    var bps = Scheduler.currentTempo / 60.0;
    var time_signature = {value: 4, count: 4};
    var beat_offset = 0; // This is the number of beats away from start of current bar
    Scheduler.quantization_interval_denominator = 16; // quantizes to this fraction of a beat
    Scheduler.refreshMultiplier = 1;
    Scheduler.interval = ((1.0 / bps) / Scheduler.quantization_interval_denominator * 1000);
    Scheduler.currentBar = 1;
    var bars = [new Scheduler.Bar(0, time_signature, []), new Scheduler.Bar(0, time_signature, []),
        new Scheduler.Bar(0, time_signature, []), new Scheduler.Bar(0, time_signature, []),
        new Scheduler.Bar(0, time_signature, []), new Scheduler.Bar(0, time_signature, [])];

    var bar = bars[Scheduler.currentBar];

    var quantizeBar = function (bar) {
        // bar should be an array of objects with note, timeOn, timeOff. If noteOff time is not
        // available, assume performance.now()
        // returns an array of objects with the MIDI data, and the quantized beats. Those with the same beat length
        // should be grouped together
        // values returned are relative to the beginning of the bar
        var quantized_bar = new Scheduler.Bar(0, time_signature, []);
        var bar_start = bar.bar_start;
        quantized_bar.bar_objects = bar.bar_objects.map(function (note) {
            var startBeatLocation = quantize(getBeatLocation(note.timeOn, bar_start));
            var endBeatLocation = quantize(getBeatLocation(note.timeOff, bar_start));
            return new Palette.BarObject(false,
                endBeatLocation > time_signature.count ? time_signature.count : (endBeatLocation > startBeatLocation ?
                    endBeatLocation : endBeatLocation + 1 / Scheduler.quantization_interval_denominator),
                startBeatLocation % time_signature.count,
                note.note);
        });
        return quantized_bar;
    };

    var getCurrentBar = function () {
        return Math.floor(beat_offset / time_signature.count);
    };

    Scheduler.eventLoop = function () {
        // run every tick
        // update beat offset
        beat_offset = (beat_offset + (1 / Scheduler.quantization_interval_denominator) / Scheduler.refreshMultiplier) % time_signature.count;
        if (beat_offset == 0) {
            bars.splice(0, 1);
            bars.push(new Scheduler.Bar(0, time_signature, []));
            bars[Scheduler.currentBar] = new Scheduler.Bar(0, time_signature, []);
            bar = bars[Scheduler.currentBar];
        }

        // Dynamically updates the note depending on how long you hold it
        var activeNotes = bar.bar_objects.filter(function (noteObj) {
            return (noteObj.done == false);
        });
        console.log(activeNotes.length);
        activeNotes.forEach(function(noteObj) {
            noteObj.timeOff = performance.now();
        });

        // pass bars to painter to draw
        anticipatoryMusicProducer.Painter.show("", bars.map(quantizeBar), beat_offset / time_signature.count);
    };
    /**
     * A callback that adds a given note to be drawn on the canvas
     * @param {number} note The MIDI value of the note
     * @param {number} time DOMHighResTimeStamp representing time on
     */
    Scheduler.onNoteOn = function (note, time) {
        bar.bar_objects.push(
            {
                note   : new Palette.Note(note),
                done   : false,
                timeOn : time,
                timeOff: -1,
                tempo  : Scheduler.currentTempo
            });
        //quantizeBar(bar);
    };

    /**
     * A callback that removes a given note from the canvas
     * @param {number} note The MIDI value of the note
     * @param {number} time DOMHighResTimeStamp representing time off
     */
    Scheduler.onNoteOff = function (note, time) {
        var releasedNote = bar.bar_objects.filter(function (noteObj) {
            return (noteObj.note.number == note);
        })[0];
        if (releasedNote) {
            releasedNote.timeOff = time;
            releasedNote.done = true;
        }
    };

    /**
     * quantizes a fractional beat count to the quantization interval, eg. 2.27321 => 2.25
     * @param beat_count
     * @returns {number}
     */
    var quantize = function (beat_count) {
        return Math.round((beat_count * Scheduler.quantization_interval_denominator)) / Scheduler.quantization_interval_denominator;
    };

    // Calculate elapsed beats since play start timestamp
    var getBeatLocation = function (note_start_timestamp, bar_start_timestamp) {
        var elapsed_seconds = (note_start_timestamp - bar_start_timestamp) / 1000.0;
        return elapsed_seconds * bps;
    };

})(window.anticipatoryMusicProducer.Scheduler =
    window.anticipatoryMusicProducer.Scheduler || {}, jQuery);
<|endoftext|>


<commit_before>'use strict'
import 'lodash/lodash'
import 'popper.js/dist/popper'
import 'bootstrap/dist/js/bootstrap'
import OwnedPluginForm from './owned_plugin_form'

$(document).ready(() => {
  new Vue({
    el: '#in-tail-parse',
    props: [
      "targetFile",
      "parseType",
    ],
    data: () => {
      return {
        highlightedLines: null
      }
    },
    computed: {
      token: function() {
        return Rails.csrfToken()
      }
    },
    components: {
      'owned-plugin-form': OwnedPluginForm
    },
    watch: {
      'parse.expression': function() {
        console.log('parse.expression')
        this.preview()
      },
      'parse.timeFormat': function() {
        console.log('parse.timeFormat')
        this.preview()
      },
      'parseType': function() {
        this.preview()
      },
    },
    mounted: function() {
      this.parse = {}
    },
    methods: {
      onChangePluginName: function(name) {
        console.log("onChangePluginName")
        this.parseType = name
      },
      onChangeParseConfig: function(data) {
        console.log("onChangeParseConfig")
        _.merge(this.parse, data)
        this.preview()
      },
      updateHighlightedLines: function(matches) {
        if (!matches) {
          this.highlightedLines = null
          return
        }

        let $container = $('
')
        _.each(matches, (match) => {
          const colors = ["#ff9", "#cff", "#fcf", "#dfd"]
          const whole = match.whole
          let html = ""
          let _matches = []
          let lastPos = 0

          _.each(match.matches, (m) => {
            let matched = m.matched
            if (!matched) {
              return
            }
            // Ignore empty matched with "foobar".match(/foo(.*?)bar/)[1] #=> ""
            if (matched.length === 0) {
              return
            }
            // rotate color
            let currentColor = colors.shift()
            colors.push(currentColor)

            // create highlighted range HTML
            let $highlighted = $("").text(matched)
            $highlighted.attr({
              "class": "regexp-preview",
              "data-toggle": "tooltip",
              "data-placement": "top",
              "title": match.key,
              'style': 'background-color:' + currentColor
            })
            let highlightedHtml = $highlighted.wrap("
").parent().html()

            let pos = {
              start: match.pos[0],
              end: match.pos[1]
            }
            if (pos.start > 0) {
              html += _.escape(whole.substring(lastPos, pos.start))
            }
            html += highlightedHtml
            lastPos = pos.end
          })
          html += whole.substring(lastPos)

          $container.append(html)
          $container.append("
")
        })

        this.highlightedLines = $container.html()
      },

      preview: function() {
        console.log("preview!!!!")
        if (this.previewAjax) {
          this.previewAjax.abort()
        }

        this.previewAjax = $.ajax({
          method: "POST",
          url: "/api/regexp_preview",
          headers: {
            'X-CSRF-Token': this.token
          },
          data: {
            expression: this.parse.expression,
            time_format: this.parse.timeFormat,
            parse_type: _.isEmpty(this.parseType) ? "regexp" : this.parseType,
            file: this.targetFile
          }
        }).then(
          (result) => {
            this.params = _merge(this.params, result.params)
            this.updateHighlightedLines(result.matches)
          },
          (error) => {
            if (error.stack) {
              console.error(error.stack)
            }
          })
      }
    }
  })
})
<commit_msg>Use function instead of arrow function<commit_after>'use strict'
import 'lodash/lodash'
import 'popper.js/dist/popper'
import 'bootstrap/dist/js/bootstrap'
import OwnedPluginForm from './owned_plugin_form'

$(document).ready(() => {
  new Vue({
    el: '#in-tail-parse',
    props: [
      "targetFile",
      "parseType",
    ],
    data: function() {
      return {
        highlightedLines: null
      }
    },
    computed: {
      token: function() {
        return Rails.csrfToken()
      }
    },
    components: {
      'owned-plugin-form': OwnedPluginForm
    },
    watch: {
      'parse.expression': function() {
        console.log('parse.expression')
        this.preview()
      },
      'parse.timeFormat': function() {
        console.log('parse.timeFormat')
        this.preview()
      },
      'parseType': function() {
        this.preview()
      },
    },
    mounted: function() {
      this.parse = {}
    },
    methods: {
      onChangePluginName: function(name) {
        console.log("onChangePluginName")
        this.parseType = name
      },
      onChangeParseConfig: function(data) {
        console.log("onChangeParseConfig")
        _.merge(this.parse, data)
        this.preview()
      },
      updateHighlightedLines: function(matches) {
        if (!matches) {
          this.highlightedLines = null
          return
        }

        let $container = $('
')
        _.each(matches, (match) => {
          const colors = ["#ff9", "#cff", "#fcf", "#dfd"]
          const whole = match.whole
          let html = ""
          let _matches = []
          let lastPos = 0

          _.each(match.matches, (m) => {
            let matched = m.matched
            if (!matched) {
              return
            }
            // Ignore empty matched with "foobar".match(/foo(.*?)bar/)[1] #=> ""
            if (matched.length === 0) {
              return
            }
            // rotate color
            let currentColor = colors.shift()
            colors.push(currentColor)

            // create highlighted range HTML
            let $highlighted = $("").text(matched)
            $highlighted.attr({
              "class": "regexp-preview",
              "data-toggle": "tooltip",
              "data-placement": "top",
              "title": match.key,
              'style': 'background-color:' + currentColor
            })
            let highlightedHtml = $highlighted.wrap("
").parent().html()

            let pos = {
              start: match.pos[0],
              end: match.pos[1]
            }
            if (pos.start > 0) {
              html += _.escape(whole.substring(lastPos, pos.start))
            }
            html += highlightedHtml
            lastPos = pos.end
          })
          html += whole.substring(lastPos)

          $container.append(html)
          $container.append("
")
        })

        this.highlightedLines = $container.html()
      },

      preview: function() {
        console.log("preview!!!!")
        if (this.previewAjax) {
          this.previewAjax.abort()
        }

        this.previewAjax = $.ajax({
          method: "POST",
          url: "/api/regexp_preview",
          headers: {
            'X-CSRF-Token': this.token
          },
          data: {
            expression: this.parse.expression,
            time_format: this.parse.timeFormat,
            parse_type: _.isEmpty(this.parseType) ? "regexp" : this.parseType,
            file: this.targetFile
          }
        }).then(
          (result) => {
            this.params = _merge(this.params, result.params)
            this.updateHighlightedLines(result.matches)
          },
          (error) => {
            if (error.stack) {
              console.error(error.stack)
            }
          })
      }
    }
  })
})
<|endoftext|>


<commit_before>/**
 * @copyright Devexperts
 *
 * @requires DX
 * @requires DX.Dom
 * @requires DX.Bem
 * @requires DX.Event
 * @requires DropDown
 * @namespace
 */

var Selectbox = (function(DX, window, document, undefined) {
	'use strict';

	var CN_SELECTBOX = 'selectBox',
		CN_INNER = CN_SELECTBOX + '--inner',
		CN_LABEL = CN_SELECTBOX + '--label',
		CN_ARROW = CN_SELECTBOX + '--arrow',
		TN_OPTGROUP = 'optgroup',
		KEY_UP_CODE = 38,
		KEY_DOWN_CODE = 40,
		ENTER_KEY_CODE = 13,
		M_ACTIVE = 'active',
		M_FOCUSED = 'focused',
		UPDATE_DELAY = 100,
		tmpl = [
			'
',
			'',
			'',
			'
'
		].join(''),
		emptyOption = {
			value: '',
			label: '',
			textContent: '',
			className: ''
		};

	function map(collection, callback) {
		return Array.prototype.map.call(collection, callback);
	}

	function createDataObj(select) {
		return map(select.children, function(element) {
			return (element.tagName.toLowerCase() === TN_OPTGROUP) ? parseOptgroup(element) : parseOption(element);
		});
	}

	function parseOptgroup(optgroup) {
		return {
			title: optgroup.label,
			options: map(optgroup.children, function(option) {
				return parseOption(option);
			})
		};
	}

	function parseOption(option) {
		return {
			value: option.value,
			text: option.label || option.innerHTML,
			modifiers: splitClassName(option),
			data: DX.Dom.getData(option)
		};
	}

	function splitClassName(element) {
		return element ? element.className.split(' ') : [];
	}

	/**
	 * Creates new selectbox component
	 * @constructor Selectbox
	 * @param {HTMLSelectElement} select
	 */
	return function Selectbox(select) {
		var block,
			label,
			dropDown,
			hasFocus,
			updateDelay,
			currentOption,
			permanentBlockClassNames,
			selectId;

		/**
		 * Triggers when electbox is created
		 *
		 * @event selectbox:created
		 */
		function init() {
			var dropDownClassName = splitClassName(select);

			permanentBlockClassNames = select.className;
			select.className = '';

			selectId = select.id || DX.String.createRandomId();
			select.id = '';

			dropDownClassName.push(CN_SELECTBOX);

			initAppearance();
			dropDown = new DropDown(block, {
				modifiers: dropDownClassName
			});
			updateData();
			initListeners();

			DX.Event.trigger(select, Selectbox.E_CREATED, {
				detail: {
					eventTarget: select,
					block: block,
					dropDown: dropDown.getBlock()
				}
			});
		}

		function initAppearance() {
			var parent = DX.Dom.getParent(select),
				selectedIndex = select.selectedIndex;

			block = createBlock();
			label = block.querySelector('.' + CN_LABEL);

			parent.insertBefore(block, select);
			block.appendChild(select);
			select.selectedIndex = selectedIndex;
		}

		function createBlock() {
			return DX.Dom.createElement('div', {
				id: selectId,
				innerHTML: tmpl
			});
		}

		function updateData() {
			var data = createDataObj(select);

			dropDown.setDataList(data);
			setIndexBySelectedIndex();
		}

		function updateBlockClassNames() {
			var classNames = [permanentBlockClassNames, DX.Bem.createModifiedClassName(CN_SELECTBOX, splitClassName(currentOption))];

			if (hasFocus) {
				classNames.push(DX.Bem.createModifiedClassName(CN_SELECTBOX, splitClassName(M_FOCUSED)));
			}

			block.className = classNames.join(' ');
		}

		/**
		 * Triggers when selectbox is changed
		 *
		 * @event selectbox:changed
		 */
		function initListeners() {
			var dropDownBlock = dropDown.getBlock();

			select.addEventListener('focus', function() {
				setFocusState();
				hasFocus = true;
			});

			select.addEventListener('blur', function() {
				removeFocusState();
				hasFocus = false;
			});

			select.addEventListener('change', function(e) {
				setIndexBySelectedIndex();
			});

			block.addEventListener('touchend', function(e) {
				toggleDropdown();

				e.preventDefault();
			}, true);

			block.addEventListener('click', function(e) {
				toggleDropdown();
			}, true);

			dropDownBlock.addEventListener(DropDown.E_CHANGED, function() {
				var index = dropDown.getSelectedIndex();

				select.selectedIndex = index;
				setSelectedByIndex(index);
				DX.Event.trigger(select, Selectbox.E_CHANGED);
			}, true);

			dropDownBlock.addEventListener(DropDown.E_SHOWN, setActiveState);
			dropDownBlock.addEventListener(DropDown.E_HIDDEN, removeActiveState);
			select.addEventListener(Selectbox.E_CHANGE_VALUE, function() {
				setIndexBySelectedIndex();
			}, true);
			select.addEventListener('DOMNodeInserted', optionListModificationHandler);
			select.addEventListener('DOMNodeRemoved', optionListModificationHandler);
		}
		/**
		 * Show dropdown
		 * @method showDropDown
		 */
		function showDropdown() {
			if (!isDisabled()) {
				dropDown.show();
			}
		}
		/**
		 * Hide dropdown
		 * @method hideDropDown
		 */
		function hideDropdown() {
			dropDown.hide();
		}

		function keyDownHandler(e) {
			var key;

			if (dropDown.isShown()) {

				key = e.key || e.which;
				var newIndex = dropDown.getHoveredIndex();

				if (key === KEY_UP_CODE || key === 'Up') {
					newIndex--;
					dropDown.setHoveredIndex(newIndex);
				} else if (key === KEY_DOWN_CODE || key === 'Down') {
					newIndex++;
					dropDown.setHoveredIndex(newIndex);
				} else if (key === ENTER_KEY_CODE || key === 'Enter') {
					var triggerChangeEvent = true;
					dropDown.hide();
					dropDown.setSelectedIndex(newIndex, triggerChangeEvent);
				}

			}
		}
		function toggleDropdown() {
			if (isActiveState()) {
				hideDropdown();
			} else {
				showDropdown();
			}
		}

		function isDisabled() {
			return select.disabled;
		}

		function setActiveState() {
			DX.Bem.addModifier(block, M_ACTIVE);
			document.addEventListener(DX.Event.KEY_DOWN, keyDownHandler);
		}

		function setFocusState() {
			DX.Bem.addModifier(block, M_FOCUSED);
		}

		function removeFocusState() {
			DX.Bem.removeModifier(block, M_FOCUSED);
		}

		function removeActiveState() {
			DX.Bem.removeModifier(block, M_ACTIVE);
			document.removeEventListener(DX.Event.KEY_DOWN, keyDownHandler);
		}

		function isActiveState() {
			return DX.Bem.hasModifier(block, M_ACTIVE);
		}

		function optionListModificationHandler() {
			window.clearTimeout(updateDelay);

			updateDelay = window.setTimeout(updateData, UPDATE_DELAY);
		}
		/**
		 * Should be fired after external select index change
		 *
		 * @event selectbox:changevalue
		 */
		function setIndexBySelectedIndex() {
			var index = select.selectedIndex;

			setSelectedByIndex(index);
			dropDown.setSelectedIndex(index);
		}

		function setSelectedByIndex(index) {
			var option = select.options[index];

			if (option) {
				currentOption = option;
			} else {
				currentOption = emptyOption;
			}

			setLabel(currentOption.label || currentOption.textContent);
			updateBlockClassNames();

			if (isDisabled()) {
				Selectbox.disable(select);
			} else {
				Selectbox.enable(select);
			}
		}

		function setLabel(str) {
			label.textContent  = str;
		}
		/**
		 * Get current label
		 * @method getText
		 * @returns {String}
		 */
		function getText() {
			return currentOption.label || currentOption.textContent;
		}
		/**
		 * Get current value
		 * @method getValue
		 * @returns {Number|String}
		 */
		function getValue() {
			return currentOption.value || currentOption.textContent;
		}

		this.getValue = getValue;
		this.getText = getText;
		this.showDropdown = showDropdown;
		this.hideDropdown = hideDropdown;
		/**
		 * Get HTMLNode containing selectbox
		 * @method getBlock
		 * @returns {Node}
		 */
		this.getBlock = function() {
			return block;
		};
		/**
		 * Get element which listens to events
		 * @method getEventTarget
		 * @returns {Node}
		 */
		this.getEventTarget = function() {
			return select;
		};

		init();
	};
})(DX, window, document);

/** @constant
 * @type {string}
 * @default
 * @memberof Selectbox
 */
Selectbox.E_CREATED = 'selectbox:created';
/** @constant
 * @type {string}
 * @default
 * @memberof Selectbox
 */
Selectbox.E_CHANGED = 'selectbox:changed';
/** @constant
 * @type {string}
 * @default
 * @memberof Selectbox
 */
Selectbox.E_CHANGE_VALUE = 'selectbox:changevalue';

/**
 * Disable selectbox
 * @method disable
 * @static
 * @memberof Selectbox
 * @param {Node} HTMLNode containing select block
 */
Selectbox.disable = function disableSelectbox(select) {
	'use strict';

	var block = DX.Dom.getParent(select);

	DX.Bem.addModifier(block, 'disabled');
	select.disabled = true;
};
/**
 * Enable selectbox
 * @method enable
 * @static
 * @memberof Selectbox
 * @param {Node} HTMLNode containing select block
 */
Selectbox.enable = function enableSelectbox(select) {
	'use strict';

	var block = DX.Dom.getParent(select);

	DX.Bem.removeModifier(block, 'disabled');
	select.disabled = false;
};<commit_msg>removed unnecessary variables<commit_after>/**
 * @copyright Devexperts
 *
 * @requires DX
 * @requires DX.Dom
 * @requires DX.Bem
 * @requires DX.Event
 * @requires DropDown
 * @namespace
 */

var Selectbox = (function(DX, window, document, undefined) {
	'use strict';

	var CN_SELECTBOX = 'selectBox',
		CN_INNER = CN_SELECTBOX + '--inner',
		CN_LABEL = CN_SELECTBOX + '--label',
		CN_ARROW = CN_SELECTBOX + '--arrow',
		TN_OPTGROUP = 'optgroup',
		KEY_UP_CODE = 38,
		KEY_DOWN_CODE = 40,
		ENTER_KEY_CODE = 13,
		M_ACTIVE = 'active',
		M_FOCUSED = 'focused',
		UPDATE_DELAY = 100,
		tmpl = [
			'
',
			'',
			'',
			'
'
		].join(''),
		emptyOption = {
			value: '',
			label: '',
			textContent: '',
			className: ''
		};

	function map(collection, callback) {
		return Array.prototype.map.call(collection, callback);
	}

	function createDataObj(select) {
		return map(select.children, function(element) {
			return (element.tagName.toLowerCase() === TN_OPTGROUP) ? parseOptgroup(element) : parseOption(element);
		});
	}

	function parseOptgroup(optgroup) {
		return {
			title: optgroup.label,
			options: map(optgroup.children, function(option) {
				return parseOption(option);
			})
		};
	}

	function parseOption(option) {
		return {
			value: option.value,
			text: option.label || option.innerHTML,
			modifiers: splitClassName(option),
			data: DX.Dom.getData(option)
		};
	}

	function splitClassName(element) {
		return element ? element.className.split(' ') : [];
	}

	/**
	 * Creates new selectbox component
	 * @constructor Selectbox
	 * @param {HTMLSelectElement} select
	 */
	return function Selectbox(select) {
		var block,
			label,
			dropDown,
			updateDelay,
			currentOption,
			permanentBlockClassNames,
			selectId;

		/**
		 * Triggers when electbox is created
		 *
		 * @event selectbox:created
		 */
		function init() {
			var dropDownClassName = splitClassName(select);

			permanentBlockClassNames = select.className;
			select.className = '';

			selectId = select.id || DX.String.createRandomId();
			select.id = '';

			dropDownClassName.push(CN_SELECTBOX);

			initAppearance();
			dropDown = new DropDown(block, {
				modifiers: dropDownClassName
			});
			updateData();
			initListeners();

			DX.Event.trigger(select, Selectbox.E_CREATED, {
				detail: {
					eventTarget: select,
					block: block,
					dropDown: dropDown.getBlock()
				}
			});
		}

		function initAppearance() {
			var parent = DX.Dom.getParent(select),
				selectedIndex = select.selectedIndex;

			block = createBlock();
			label = block.querySelector('.' + CN_LABEL);

			parent.insertBefore(block, select);
			block.appendChild(select);
			select.selectedIndex = selectedIndex;
		}

		function createBlock() {
			return DX.Dom.createElement('div', {
				id: selectId,
				innerHTML: tmpl
			});
		}

		function updateData() {
			var data = createDataObj(select);

			dropDown.setDataList(data);
			setIndexBySelectedIndex();
		}

		function updateBlockClassNames() {
			var classNames = [permanentBlockClassNames, DX.Bem.createModifiedClassName(CN_SELECTBOX, splitClassName(currentOption))];

			if (DX.Bem.hasModifier(block, M_FOCUSED)) {
				classNames.push(DX.Bem.createModifiedClassName(CN_SELECTBOX, [M_FOCUSED]));
			}

			block.className = classNames.join(' ');
		}

		/**
		 * Triggers when selectbox is changed
		 *
		 * @event selectbox:changed
		 */
		function initListeners() {
			var dropDownBlock = dropDown.getBlock();

			select.addEventListener('focus', setFocusState);

			select.addEventListener('blur', removeFocusState);

			select.addEventListener('change', function(e) {
				setIndexBySelectedIndex();
			});

			block.addEventListener('touchend', function(e) {
				toggleDropdown();

				e.preventDefault();
			}, true);

			block.addEventListener('click', function(e) {
				toggleDropdown();
			}, true);

			dropDownBlock.addEventListener(DropDown.E_CHANGED, function() {
				var index = dropDown.getSelectedIndex();

				select.selectedIndex = index;
				setSelectedByIndex(index);
				DX.Event.trigger(select, Selectbox.E_CHANGED);
			}, true);

			dropDownBlock.addEventListener(DropDown.E_SHOWN, setActiveState);
			dropDownBlock.addEventListener(DropDown.E_HIDDEN, removeActiveState);
			select.addEventListener(Selectbox.E_CHANGE_VALUE, function() {
				setIndexBySelectedIndex();
			}, true);
			select.addEventListener('DOMNodeInserted', optionListModificationHandler);
			select.addEventListener('DOMNodeRemoved', optionListModificationHandler);
		}
		/**
		 * Show dropdown
		 * @method showDropDown
		 */
		function showDropdown() {
			if (!isDisabled()) {
				dropDown.show();
			}
		}
		/**
		 * Hide dropdown
		 * @method hideDropDown
		 */
		function hideDropdown() {
			dropDown.hide();
		}

		function keyDownHandler(e) {
			var key;

			if (dropDown.isShown()) {

				key = e.key || e.which;
				var newIndex = dropDown.getHoveredIndex();

				if (key === KEY_UP_CODE || key === 'Up') {
					newIndex--;
					dropDown.setHoveredIndex(newIndex);
				} else if (key === KEY_DOWN_CODE || key === 'Down') {
					newIndex++;
					dropDown.setHoveredIndex(newIndex);
				} else if (key === ENTER_KEY_CODE || key === 'Enter') {
					var triggerChangeEvent = true;
					dropDown.hide();
					dropDown.setSelectedIndex(newIndex, triggerChangeEvent);
				}

			}
		}
		function toggleDropdown() {
			if (isActiveState()) {
				hideDropdown();
			} else {
				showDropdown();
			}
		}

		function isDisabled() {
			return select.disabled;
		}

		function setActiveState() {
			DX.Bem.addModifier(block, M_ACTIVE);
			document.addEventListener(DX.Event.KEY_DOWN, keyDownHandler);
		}

		function setFocusState() {
			DX.Bem.addModifier(block, M_FOCUSED);
		}

		function removeFocusState() {
			DX.Bem.removeModifier(block, M_FOCUSED);
		}

		function removeActiveState() {
			DX.Bem.removeModifier(block, M_ACTIVE);
			document.removeEventListener(DX.Event.KEY_DOWN, keyDownHandler);
		}

		function isActiveState() {
			return DX.Bem.hasModifier(block, M_ACTIVE);
		}

		function optionListModificationHandler() {
			window.clearTimeout(updateDelay);

			updateDelay = window.setTimeout(updateData, UPDATE_DELAY);
		}
		/**
		 * Should be fired after external select index change
		 *
		 * @event selectbox:changevalue
		 */
		function setIndexBySelectedIndex() {
			var index = select.selectedIndex;

			setSelectedByIndex(index);
			dropDown.setSelectedIndex(index);
		}

		function setSelectedByIndex(index) {
			var option = select.options[index];

			if (option) {
				currentOption = option;
			} else {
				currentOption = emptyOption;
			}

			setLabel(currentOption.label || currentOption.textContent);
			updateBlockClassNames();

			if (isDisabled()) {
				Selectbox.disable(select);
			} else {
				Selectbox.enable(select);
			}
		}

		function setLabel(str) {
			label.textContent  = str;
		}
		/**
		 * Get current label
		 * @method getText
		 * @returns {String}
		 */
		function getText() {
			return currentOption.label || currentOption.textContent;
		}
		/**
		 * Get current value
		 * @method getValue
		 * @returns {Number|String}
		 */
		function getValue() {
			return currentOption.value || currentOption.textContent;
		}

		this.getValue = getValue;
		this.getText = getText;
		this.showDropdown = showDropdown;
		this.hideDropdown = hideDropdown;
		/**
		 * Get HTMLNode containing selectbox
		 * @method getBlock
		 * @returns {Node}
		 */
		this.getBlock = function() {
			return block;
		};
		/**
		 * Get element which listens to events
		 * @method getEventTarget
		 * @returns {Node}
		 */
		this.getEventTarget = function() {
			return select;
		};

		init();
	};
})(DX, window, document);

/** @constant
 * @type {string}
 * @default
 * @memberof Selectbox
 */
Selectbox.E_CREATED = 'selectbox:created';
/** @constant
 * @type {string}
 * @default
 * @memberof Selectbox
 */
Selectbox.E_CHANGED = 'selectbox:changed';
/** @constant
 * @type {string}
 * @default
 * @memberof Selectbox
 */
Selectbox.E_CHANGE_VALUE = 'selectbox:changevalue';

/**
 * Disable selectbox
 * @method disable
 * @static
 * @memberof Selectbox
 * @param {Node} HTMLNode containing select block
 */
Selectbox.disable = function disableSelectbox(select) {
	'use strict';

	var block = DX.Dom.getParent(select);

	DX.Bem.addModifier(block, 'disabled');
	select.disabled = true;
};
/**
 * Enable selectbox
 * @method enable
 * @static
 * @memberof Selectbox
 * @param {Node} HTMLNode containing select block
 */
Selectbox.enable = function enableSelectbox(select) {
	'use strict';

	var block = DX.Dom.getParent(select);

	DX.Bem.removeModifier(block, 'disabled');
	select.disabled = false;
};<|endoftext|>


<commit_before>/*===========================
Template7 Template engine
===========================*/
window.Template7 = (function () {
    'use strict';
    function isArray(arr) {
        return Object.prototype.toString.apply(arr) === '[object Array]';
    }
    function isObject(obj) {
        return obj instanceof Object;
    }
    function isFunction(func) {
        return typeof func === 'function';
    }
    var cache = {};
    function helperToSlices(string) {
        var helperParts = string.replace(/[{}#}]/g, '').split(' ');
        var slices = [];
        var shiftIndex, i, j;
        for (i = 0; i < helperParts.length; i++) {
            var part = helperParts[i];
            if (i === 0) slices.push(part);
            else {
                if (part.indexOf('"') === 0) {
                    // Plain String
                    if (part.match(/"/g).length === 2) {
                        // One word string
                        slices.push(part);
                    }
                    else {
                        // Find closed Index
                        shiftIndex = 0;
                        for (j = i + 1; j < helperParts.length; j++) {
                            part += ' ' + helperParts[j];
                            if (helperParts[j].indexOf('"') >= 0) {
                                shiftIndex = j;
                                slices.push(part);
                                break;
                            }
                        }
                        if (shiftIndex) i = shiftIndex;
                    }
                }
                else {
                    if (part.indexOf('=') > 0) {
                        // Hash
                        var hashParts = part.split('=');
                        var hashName = hashParts[0];
                        var hashContent = hashParts[1];
                        if (hashContent.match(/"/g).length !== 2) {
                            shiftIndex = 0;
                            for (j = i + 1; j < helperParts.length; j++) {
                                hashContent += ' ' + helperParts[j];
                                if (helperParts[j].indexOf('"') >= 0) {
                                    shiftIndex = j;
                                    break;
                                }
                            }
                            if (shiftIndex) i = shiftIndex;
                        }
                        var hash = [hashName, hashContent.replace(/"/g,'')];
                        slices.push(hash);
                    }
                    else {
                        // Plain variable
                        slices.push(part);
                    }
                }
            }
        }
        return slices;
    }
    function stringToBlocks(string) {
        var blocks = [], i, j, k;
        if (!string) return [];
        var _blocks = string.split(/({{[^{^}]*}})/);
        for (i = 0; i < _blocks.length; i++) {
            var block = _blocks[i];
            if (block === '') continue;
            if (block.indexOf('{{') < 0) {
                blocks.push({
                    type: 'plain',
                    content: block
                });
            }
            else {
                if (block.indexOf('{/') >= 0) {
                    continue;
                }
                if (block.indexOf('{#') < 0 && block.indexOf(' ') < 0 && block.indexOf('else') < 0) {
                    // Simple variable
                    blocks.push({
                        type: 'variable',
                        contextName: block.replace(/[{}]/g, '')
                    });
                    continue;
                }
                // Helpers
                var helperSlices = helperToSlices(block);
                var helperName = helperSlices[0];
                var helperContext = [];
                var helperHash = {};
                for (j = 1; j < helperSlices.length; j++) {
                    var slice = helperSlices[j];
                    if (isArray(slice)) {
                        // Hash
                        helperHash[slice[0]] = slice[1] === 'false' ? false : slice[1];
                    }
                    else {
                        helperContext.push(slice);
                    }
                }

                if (block.indexOf('{#') >= 0) {
                    // Condition/Helper
                    var helperStartIndex = i;
                    var helperContent = '';
                    var elseContent = '';
                    var toSkip = 0;
                    var shiftIndex;
                    var foundClosed = false, foundElse = false, foundClosedElse = false, depth = 0;
                    for (j = i + 1; j < _blocks.length; j++) {
                        if (_blocks[j].indexOf('{{#') >= 0) {
                            depth ++;
                        }
                        if (_blocks[j].indexOf('{{/') >= 0) {
                            depth --;
                        }
                        if (_blocks[j].indexOf('{{#' + helperName) >= 0) {
                            helperContent += _blocks[j];
                            if (foundElse) elseContent += _blocks[j];
                            toSkip ++;
                        }
                        else if (_blocks[j].indexOf('{{/' + helperName) >= 0) {
                            if (toSkip > 0) {
                                toSkip--;
                                helperContent += _blocks[j];
                                if (foundElse) elseContent += _blocks[j];
                            }
                            else {
                                shiftIndex = j;
                                foundClosed = true;
                                break;
                            }
                        }
                        else if (_blocks[j].indexOf('else') >= 0 && depth === 0) {
                            foundElse = true;
                        }
                        else {
                            if (!foundElse) helperContent += _blocks[j];
                            if (foundElse) elseContent += _blocks[j];
                        }

                    }
                    if (foundClosed) {
                        if (shiftIndex) i = shiftIndex;
                        blocks.push({
                            type: 'helper',
                            helperName: helperName,
                            contextName: helperContext,
                            content: helperContent,
                            inverseContent: elseContent,
                            hash: helperHash
                        });
                    }
                }
                else if (block.indexOf(' ') > 0) {
                    blocks.push({
                        type: 'helper',
                        helperName: helperName,
                        contextName: helperContext,
                        hash: helperHash
                    });
                }
            }
        }
        return blocks;
    }
    var Template7 = function (template, data) {
        var t = this;
        t.template = template;
        t.context = data;

        function getCompileFn(block, depth) {
            if (block.content) return compile(block.content, depth);
            else return function () {return ''; };
        }
        function getCompileInverse(block, depth) {
            if (block.inverseContent) return compile(block.inverseContent, depth);
            else return function () {return ''; };
        }
        function getCompileVar(name, ctx) {
            var parents, variable, context;

            if (name.indexOf('.') > 0) {
                if (name.indexOf('this') === 0) variable = name.replace('this', ctx);
                else variable = ctx + '.' + name;
            }
            else if (name.indexOf('../') === 0) {
                var levelUp = name.split('../').length - 1;
                var newName = name.split('../')[name.split('../').length - 1];
                var newDepth = ctx.split('_')[1] - levelUp;
                variable = 'ctx_' + (newDepth >= 1 ? newDepth : 1) + '.' + newName;
            }
            else {
                variable = name === 'this' ? ctx : ctx + '.' + name;
            }
            if (name && name.indexOf('@') >= 0) {
                variable = '(data && data.' + name.replace('@', '') + ')';
            }

            return variable;
        }
        function getCompiledArguments(contextArray, ctx) {
            var arr = [];
            for (var i = 0; i < contextArray.length; i++) {
                if (contextArray[i].indexOf('"') === 0) arr.push(contextArray[i]);
                else {
                    arr.push(getCompileVar(contextArray[i], ctx));
                }
            }
            return arr.join(', ');
        }
        function compile(template, depth) {
            depth = depth || 1;
            template = template || t.template;
            if (typeof template !== 'string') {
                throw new Error('Template7: Template must be a string');
            }
            var blocks = stringToBlocks(template);

            if (blocks.length === 0) {
                return function () { return ''; };
            }
            var ctx = 'ctx_' + depth;
            var resultString = '(function (' + ctx + ', data) {\n';
            if (depth === 1) {
                resultString += 'function isArray(arr){return Object.prototype.toString.apply(arr) === \'[object Array]\';}\n';
                resultString += 'function isFunction(func){return (typeof func === \'function\');}\n';
                resultString += 'function c(val, ctx) {if (typeof val !== "undefined") {if (isFunction(val)) {return val.call(ctx);} else return val;} else return "";}\n';
            }
            resultString += 'var r = \'\';\n';
            var i, j, context;
            for (i = 0; i < blocks.length; i++) {
                var block = blocks[i];
                // Plain block
                if (block.type === 'plain') {
                    resultString += 'r +=\'' + (block.content).replace(/\n/g, '\\n').replace(/'/g, '\\' + '\'') + '\';';
                    continue;
                }
                var variable, compiledArguments;
                // Variable block
                if (block.type === 'variable') {
                    variable = getCompileVar(block.contextName, ctx);
                    resultString += 'r += c(' + variable + ', ' + ctx + ');';
                }
                // Helpers block
                if (block.type === 'helper') {
                    if (block.helperName in t.helpers) {
                        compiledArguments = getCompiledArguments(block.contextName, ctx);
                        resultString += 'r += (Template7.helpers.' + block.helperName + ').call(' + ctx + ', ' + compiledArguments + ', {hash:' + JSON.stringify(block.hash) + ', data: data || {}, fn: ' + getCompileFn(block, depth+1) + ', inverse: ' + getCompileInverse(block, depth+1) + '});';
                    }
                    else {
                        if (block.contextName.length > 0) {
                            throw new Error('Template7: Missing helper: "' + block.helperName + '"');
                        }
                        else {
                            variable = getCompileVar(block.helperName, ctx);
                            resultString += 'if (' + variable + ') {';
                            resultString += 'if (isArray(' + variable + ')) {';
                            resultString += 'r += (Template7.helpers.each).call(' + ctx + ', ' + variable + ', {hash:' + JSON.stringify(block.hash) + ', data: data || {}, fn: ' + getCompileFn(block, depth+1) + ', inverse: ' + getCompileInverse(block, depth+1) + '});';
                            resultString += '}else {';
                            resultString += 'r += (Template7.helpers.with).call(' + ctx + ', ' + variable + ', {hash:' + JSON.stringify(block.hash) + ', data: data || {}, fn: ' + getCompileFn(block, depth+1) + ', inverse: ' + getCompileInverse(block, depth+1) + '});';
                            resultString += '}}';
                        }
                    }
                }
            }
            resultString += '\nreturn r;})';
            return eval.call(window, resultString);
        }
        t.compile = function (template) {
            if (!t.compiled) {
                t.compiled = compile(template);
            }
            return t.compiled;
        };
    };
    Template7.prototype = {
        options: {
            // cache: false
        },
        helpers: {
            'if': function (context, options) {
                if (isFunction(context)) { context = context.call(this); }
                if (context) {
                    return options.fn(this, options.data);
                }
                else {
                    return options.inverse(this, options.data);
                }
            },
            'unless': function (context, options) {
                if (isFunction(context)) { context = context.call(this); }
                if (!context) {
                    return options.fn(this, options.data);
                }
                else {
                    return options.inverse(this, options.data);
                }
            },
            'each': function (context, options) {
                var ret = '', i = 0;
                if (isFunction(context)) { context = context.call(this); }
                if (isArray(context)) {
                    if (options.hash.reverse) {
                        context = context.reverse();
                    }
                    for (i = 0; i < context.length; i++) {
                        ret += options.fn(context[i], {first: i === 0, last: i === context.length - 1, index: i});
                    }
                    if (options.hash.reverse) {
                        context = context.reverse();
                    }
                }
                else {
                    for (var key in context) {
                        i++;
                        ret += options.fn(context[key], {key: key});
                    }
                }
                if (i > 0) return ret;
                else return options.inverse(this);
            },
            'with': function (context, options) {
                if (isFunction(context)) { context = context.call(this); }
                return options.fn(context);
            },
            'join': function (context, options) {
                if (isFunction(context)) { context = context.call(this); }
                return context.join(options.hash.delimeter);
            }
        }
    };
    var t7 = function (template, data) {
        if (arguments.length === 2) {
            var instance = new Template7(template);
            var rendered = instance.compile()(data);
            instance = null;
            return (rendered);
        }
        else return new Template7(template);
    };
    t7.registerHelper = function (name, fn) {
        Template7.prototype.helpers[name] = fn;
    };

    t7.compile = function (template) {
        var instance = new Template7(template);
        return instance.compile();
    };

    t7.options = Template7.prototype.options;
    t7.helpers = Template7.prototype.helpers;
    return t7;
})();<commit_msg>Update Template7<commit_after>/*===========================
Template7 Template engine
===========================*/
window.Template7 = (function () {
    'use strict';
    function isArray(arr) {
        return Object.prototype.toString.apply(arr) === '[object Array]';
    }
    function isObject(obj) {
        return obj instanceof Object;
    }
    function isFunction(func) {
        return typeof func === 'function';
    }
    var cache = {};
    function helperToSlices(string) {
        var helperParts = string.replace(/[{}#}]/g, '').split(' ');
        var slices = [];
        var shiftIndex, i, j;
        for (i = 0; i < helperParts.length; i++) {
            var part = helperParts[i];
            if (i === 0) slices.push(part);
            else {
                if (part.indexOf('"') === 0) {
                    // Plain String
                    if (part.match(/"/g).length === 2) {
                        // One word string
                        slices.push(part);
                    }
                    else {
                        // Find closed Index
                        shiftIndex = 0;
                        for (j = i + 1; j < helperParts.length; j++) {
                            part += ' ' + helperParts[j];
                            if (helperParts[j].indexOf('"') >= 0) {
                                shiftIndex = j;
                                slices.push(part);
                                break;
                            }
                        }
                        if (shiftIndex) i = shiftIndex;
                    }
                }
                else {
                    if (part.indexOf('=') > 0) {
                        // Hash
                        var hashParts = part.split('=');
                        var hashName = hashParts[0];
                        var hashContent = hashParts[1];
                        if (hashContent.match(/"/g).length !== 2) {
                            shiftIndex = 0;
                            for (j = i + 1; j < helperParts.length; j++) {
                                hashContent += ' ' + helperParts[j];
                                if (helperParts[j].indexOf('"') >= 0) {
                                    shiftIndex = j;
                                    break;
                                }
                            }
                            if (shiftIndex) i = shiftIndex;
                        }
                        var hash = [hashName, hashContent.replace(/"/g,'')];
                        slices.push(hash);
                    }
                    else {
                        // Plain variable
                        slices.push(part);
                    }
                }
            }
        }
        return slices;
    }
    function stringToBlocks(string) {
        var blocks = [], i, j, k;
        if (!string) return [];
        var _blocks = string.split(/({{[^{^}]*}})/);
        for (i = 0; i < _blocks.length; i++) {
            var block = _blocks[i];
            if (block === '') continue;
            if (block.indexOf('{{') < 0) {
                blocks.push({
                    type: 'plain',
                    content: block
                });
            }
            else {
                if (block.indexOf('{/') >= 0) {
                    continue;
                }
                if (block.indexOf('{#') < 0 && block.indexOf(' ') < 0 && block.indexOf('else') < 0) {
                    // Simple variable
                    blocks.push({
                        type: 'variable',
                        contextName: block.replace(/[{}]/g, '')
                    });
                    continue;
                }
                // Helpers
                var helperSlices = helperToSlices(block);
                var helperName = helperSlices[0];
                var helperContext = [];
                var helperHash = {};
                for (j = 1; j < helperSlices.length; j++) {
                    var slice = helperSlices[j];
                    if (isArray(slice)) {
                        // Hash
                        helperHash[slice[0]] = slice[1] === 'false' ? false : slice[1];
                    }
                    else {
                        helperContext.push(slice);
                    }
                }

                if (block.indexOf('{#') >= 0) {
                    // Condition/Helper
                    var helperStartIndex = i;
                    var helperContent = '';
                    var elseContent = '';
                    var toSkip = 0;
                    var shiftIndex;
                    var foundClosed = false, foundElse = false, foundClosedElse = false, depth = 0;
                    for (j = i + 1; j < _blocks.length; j++) {
                        if (_blocks[j].indexOf('{{#') >= 0) {
                            depth ++;
                        }
                        if (_blocks[j].indexOf('{{/') >= 0) {
                            depth --;
                        }
                        if (_blocks[j].indexOf('{{#' + helperName) >= 0) {
                            helperContent += _blocks[j];
                            if (foundElse) elseContent += _blocks[j];
                            toSkip ++;
                        }
                        else if (_blocks[j].indexOf('{{/' + helperName) >= 0) {
                            if (toSkip > 0) {
                                toSkip--;
                                helperContent += _blocks[j];
                                if (foundElse) elseContent += _blocks[j];
                            }
                            else {
                                shiftIndex = j;
                                foundClosed = true;
                                break;
                            }
                        }
                        else if (_blocks[j].indexOf('else') >= 0 && depth === 0) {
                            foundElse = true;
                        }
                        else {
                            if (!foundElse) helperContent += _blocks[j];
                            if (foundElse) elseContent += _blocks[j];
                        }

                    }
                    if (foundClosed) {
                        if (shiftIndex) i = shiftIndex;
                        blocks.push({
                            type: 'helper',
                            helperName: helperName,
                            contextName: helperContext,
                            content: helperContent,
                            inverseContent: elseContent,
                            hash: helperHash
                        });
                    }
                }
                else if (block.indexOf(' ') > 0) {
                    blocks.push({
                        type: 'helper',
                        helperName: helperName,
                        contextName: helperContext,
                        hash: helperHash
                    });
                }
            }
        }
        return blocks;
    }
    var Template7 = function (template) {
        var t = this;
        t.template = template;

        function getCompileFn(block, depth) {
            if (block.content) return compile(block.content, depth);
            else return function () {return ''; };
        }
        function getCompileInverse(block, depth) {
            if (block.inverseContent) return compile(block.inverseContent, depth);
            else return function () {return ''; };
        }
        function getCompileVar(name, ctx) {
            var parents, variable, context;

            if (name.indexOf('.') > 0) {
                if (name.indexOf('this') === 0) variable = name.replace('this', ctx);
                else variable = ctx + '.' + name;
            }
            else if (name.indexOf('../') === 0) {
                var levelUp = name.split('../').length - 1;
                var newName = name.split('../')[name.split('../').length - 1];
                var newDepth = ctx.split('_')[1] - levelUp;
                variable = 'ctx_' + (newDepth >= 1 ? newDepth : 1) + '.' + newName;
            }
            else {
                variable = name === 'this' ? ctx : ctx + '.' + name;
            }
            if (name && name.indexOf('@') >= 0) {
                variable = '(data && data.' + name.replace('@', '') + ')';
            }

            return variable;
        }
        function getCompiledArguments(contextArray, ctx) {
            var arr = [];
            for (var i = 0; i < contextArray.length; i++) {
                if (contextArray[i].indexOf('"') === 0) arr.push(contextArray[i]);
                else {
                    arr.push(getCompileVar(contextArray[i], ctx));
                }
            }
            return arr.join(', ');
        }
        function compile(template, depth) {
            depth = depth || 1;
            template = template || t.template;
            if (typeof template !== 'string') {
                throw new Error('Template7: Template must be a string');
            }
            var blocks = stringToBlocks(template);

            if (blocks.length === 0) {
                return function () { return ''; };
            }
            var ctx = 'ctx_' + depth;
            var resultString = '(function (' + ctx + ', data) {\n';
            if (depth === 1) {
                resultString += 'function isArray(arr){return Object.prototype.toString.apply(arr) === \'[object Array]\';}\n';
                resultString += 'function isFunction(func){return (typeof func === \'function\');}\n';
                resultString += 'function c(val, ctx) {if (typeof val !== "undefined") {if (isFunction(val)) {return val.call(ctx);} else return val;} else return "";}\n';
            }
            resultString += 'var r = \'\';\n';
            var i, j, context;
            for (i = 0; i < blocks.length; i++) {
                var block = blocks[i];
                // Plain block
                if (block.type === 'plain') {
                    resultString += 'r +=\'' + (block.content).replace(/\r/g, '\\r').replace(/\n/g, '\\n').replace(/'/g, '\\' + '\'') + '\';';
                    continue;
                }
                var variable, compiledArguments;
                // Variable block
                if (block.type === 'variable') {
                    variable = getCompileVar(block.contextName, ctx);
                    resultString += 'r += c(' + variable + ', ' + ctx + ');';
                }
                // Helpers block
                if (block.type === 'helper') {
                    if (block.helperName in t.helpers) {
                        compiledArguments = getCompiledArguments(block.contextName, ctx);
                        resultString += 'r += (Template7.helpers.' + block.helperName + ').call(' + ctx + ', ' + (compiledArguments && (compiledArguments + ',')) +'{hash:' + JSON.stringify(block.hash) + ', data: data || {}, fn: ' + getCompileFn(block, depth+1) + ', inverse: ' + getCompileInverse(block, depth+1) + '});';
                    }
                    else {
                        if (block.contextName.length > 0) {
                            throw new Error('Template7: Missing helper: "' + block.helperName + '"');
                        }
                        else {
                            variable = getCompileVar(block.helperName, ctx);
                            resultString += 'if (' + variable + ') {';
                            resultString += 'if (isArray(' + variable + ')) {';
                            resultString += 'r += (Template7.helpers.each).call(' + ctx + ', ' + variable + ', {hash:' + JSON.stringify(block.hash) + ', data: data || {}, fn: ' + getCompileFn(block, depth+1) + ', inverse: ' + getCompileInverse(block, depth+1) + '});';
                            resultString += '}else {';
                            resultString += 'r += (Template7.helpers.with).call(' + ctx + ', ' + variable + ', {hash:' + JSON.stringify(block.hash) + ', data: data || {}, fn: ' + getCompileFn(block, depth+1) + ', inverse: ' + getCompileInverse(block, depth+1) + '});';
                            resultString += '}}';
                        }
                    }
                }
            }
            resultString += '\nreturn r;})';
            return eval.call(window, resultString);
        }
        t.compile = function (template) {
            if (!t.compiled) {
                t.compiled = compile(template);
            }
            return t.compiled;
        };
    };
    Template7.prototype = {
        options: {},
        helpers: {
            'if': function (context, options) {
                if (isFunction(context)) { context = context.call(this); }
                if (context) {
                    return options.fn(this, options.data);
                }
                else {
                    return options.inverse(this, options.data);
                }
            },
            'unless': function (context, options) {
                if (isFunction(context)) { context = context.call(this); }
                if (!context) {
                    return options.fn(this, options.data);
                }
                else {
                    return options.inverse(this, options.data);
                }
            },
            'each': function (context, options) {
                var ret = '', i = 0;
                if (isFunction(context)) { context = context.call(this); }
                if (isArray(context)) {
                    if (options.hash.reverse) {
                        context = context.reverse();
                    }
                    for (i = 0; i < context.length; i++) {
                        ret += options.fn(context[i], {first: i === 0, last: i === context.length - 1, index: i});
                    }
                    if (options.hash.reverse) {
                        context = context.reverse();
                    }
                }
                else {
                    for (var key in context) {
                        i++;
                        ret += options.fn(context[key], {key: key});
                    }
                }
                if (i > 0) return ret;
                else return options.inverse(this);
            },
            'with': function (context, options) {
                if (isFunction(context)) { context = context.call(this); }
                return options.fn(context);
            },
            'join': function (context, options) {
                if (isFunction(context)) { context = context.call(this); }
                return context.join(options.hash.delimeter);
            }
        }
    };
    var t7 = function (template, data) {
        if (arguments.length === 2) {
            var instance = new Template7(template);
            var rendered = instance.compile()(data);
            instance = null;
            return (rendered);
        }
        else return new Template7(template);
    };
    t7.registerHelper = function (name, fn) {
        Template7.prototype.helpers[name] = fn;
    };
    t7.deregisterHelper = function (name) {
        Template7.prototype.helpers[name] = undefined;
        delete Template7.prototype.helpers[name];
    };

    t7.compile = function (template, options) {
        var instance = new Template7(template, options);
        return instance.compile();
    };

    t7.options = Template7.prototype.options;
    t7.helpers = Template7.prototype.helpers;
    return t7;
})();<|endoftext|>


<commit_before>var neighbourMap = neighbourMap || {};

(function(o) {
  'use strict';
  o.viewModel = o.viewModel || {};

  // Define Place
  var Place = function(data) {
    this.name = ko.observable(data.name);
    this.location = data.location;
    this.visible = ko.observable(true);
  };

  var ViewModel = function() {
    var self = this;

    // List view. Not visible to start with
    self.listVisible = ko.observable(false);

    // Populate am observable array with all the places defined in the model
    self.placeList = ko.observableArray();
    neighbourMap.model.initialPlaces.forEach(function(place) {
      self.placeList.push(new Place(place));
    });

    // Sort array of places by place name
    self.placeList.sort(function(l, r) {
      return l.name().localeCompare(r.name());
    });

    // Function called when hamburger icon clicked
    self.toggleListVisible = function() {
      self.listVisible() ?
        self.listVisible(false) :
        self.listVisible(true);
    };

    // Initialize text in filter input
    self.filterText = ko.observable('');

    // Function called whenever anything is typed into Filter field
    // Sets visibility of list items and map markers
    // Closes infoWindow if it's marker is removed
    self.filterPlaceList = function() {
      self.placeList().forEach(function(place) {
        if (place.name().search(self.filterText()) > -1) {
          place.visible(true);
          place.marker.setVisible(true);
        } else {
          place.visible(false);
          place.marker.setVisible(false);
          // Check to see if the marker is currently associated with the infoWindow
          // Close the infoWindow if it is
          if (place.marker === neighbourMap.viewMap.infoWindowMarker) {
            neighbourMap.viewMap.infoWindow.close();
            neighbourMap.viewMap.infoWindowMarker = null;
          }
        }
      });
    };

    // Function called when a place name in the list is clicked
    // Results in data being displayed on map. Same as if the marker had been clicked
    self.selectPlace = function(clickedPlace) {
      neighbourMap.viewMap.getData(clickedPlace);
    };
  };

  o.viewModel.ViewModel = new ViewModel();
  ko.applyBindings(o.viewModel.ViewModel);

})(neighbourMap);
<commit_msg>Update selectPlace so that list is no longer visible<commit_after>var neighbourMap = neighbourMap || {};

(function(o) {
  'use strict';
  o.viewModel = o.viewModel || {};

  // Define Place
  var Place = function(data) {
    this.name = ko.observable(data.name);
    this.location = data.location;
    this.visible = ko.observable(true);
  };

  var ViewModel = function() {
    var self = this;

    // List view. Not visible to start with
    self.listVisible = ko.observable(false);

    // Populate am observable array with all the places defined in the model
    self.placeList = ko.observableArray();
    neighbourMap.model.initialPlaces.forEach(function(place) {
      self.placeList.push(new Place(place));
    });

    // Sort array of places by place name
    self.placeList.sort(function(l, r) {
      return l.name().localeCompare(r.name());
    });

    // Function called when hamburger icon clicked
    self.toggleListVisible = function() {
      self.listVisible() ?
        self.listVisible(false) :
        self.listVisible(true);
    };

    // Initialize text in filter input
    self.filterText = ko.observable('');

    // Function called whenever anything is typed into Filter field
    // Sets visibility of list items and map markers
    // Closes infoWindow if it's marker is removed
    self.filterPlaceList = function() {
      self.placeList().forEach(function(place) {
        if (place.name().search(self.filterText()) > -1) {
          place.visible(true);
          place.marker.setVisible(true);
        } else {
          place.visible(false);
          place.marker.setVisible(false);
          // Check to see if the marker is currently associated with the infoWindow
          // Close the infoWindow if it is
          if (place.marker === neighbourMap.viewMap.infoWindowMarker) {
            neighbourMap.viewMap.infoWindow.close();
            neighbourMap.viewMap.infoWindowMarker = null;
          }
        }
      });
    };

    // Function called when a place name in the list is clicked
    // Results in data being displayed on map. Same as if the marker had been clicked
    self.selectPlace = function(clickedPlace) {
      neighbourMap.viewMap.getData(clickedPlace);
      // Remove the list so that it doesn't obstruct view of InfoWindow
      self.listVisible(false);
    };
  };

  o.viewModel.ViewModel = new ViewModel();
  ko.applyBindings(o.viewModel.ViewModel);

})(neighbourMap);
<|endoftext|>


<commit_before>import content from './content'

console.log('content')
content()
<commit_msg>🐍 remove cosole<commit_after>import content from './content'

content()
<|endoftext|>


<commit_before>'use strict';
/* A newable factory to handle xml files using the Perseus Treebank Schema
 *
 * The constructor functions takes a configuration object (that typically
 * contains a resource object for this service).
 *
 */
angular.module('arethusa').factory('TreebankRetriever', [
  'configurator',
  'documentStore',
  'retrieverHelper',
  'idHandler',
  function (configurator, documentStore, retrieverHelper, idHandler) {
    function xmlTokenToState(docId, token, sentenceId, artificials) {
      // One could formalize this to real rules that are configurable...
      //
      // Remember that attributes of the converted xml are prefixed with underscore
      var obj = aC.token(token._form, sentenceId);

      obj.morphology = {
        lemma: token._lemma,
        postag: token._postag
      };

      obj.relation = {};

      var relation = token._relation;
      obj.relation.label = (relation && relation !== 'nil') ? relation : '';

      var gloss = token._gloss;
      if (gloss) {
        obj.morphology.gloss = gloss;
      }

      var sg = token._sg;
      if (sg && !sg.match(/^\s*$/)) {
        obj.sg = { ancestors: sg.split(' ') };
      }

      if (token._artificial) {
        obj.artificial = true;
        obj.type = token._artificial;
      }

      if (aU.isTerminatingPunctuation(obj.string)) {
        obj.terminator = true;
      }

      var intId = xmlTokenId(token, sentenceId);
      retrieverHelper.generateId(obj, intId, token._id, docId);
      createHead(obj, token, artificials);

      return obj;
    }

    function createHead(stateToken, xmlToken, artificials) {
      var head = xmlToken._head;
      if (angular.isDefined(head)) {
        var newHead = {};
        var artHead = artificials[head];
        newHead.id = artHead ? artHead : idHandler.getId(head, stateToken.sentenceId);
        stateToken.head = newHead;
      }
    }

    function xmlTokenId(token, sId) {
      return token._artificial ? token._insertion_id : idHandler.getId(token._id, sId);
    }

    // This is for backwards compatibility - we still might encounter documents, which
    // stored the insertion id without the sentence id. This is a little hacky but a
    // must have.
    function padWithSentenceId(token, sId) {
      var iId = token._insertion_id;
      if (iId.match(/-/)) {
        token._insertion_id = idHandler.padIdWithSId(iId, sId);
      }
    }

    function extractArtificial(memo, token, i, sId) {
      if (token._artificial) {
        padWithSentenceId(token, sId);
        memo[token._id] = token._insertion_id;
      }
    }

    function xmlSentenceToState(docId, words, id, cite) {
      var tokens = {};
      var artificials = arethusaUtil.inject({}, words, function(memo, token, i) {
        extractArtificial(memo, token, i, id);
      });
      angular.forEach(words, function (xmlToken, i) {
        var token = xmlTokenToState(docId, xmlToken, id, artificials);
        tokens[token.id] = token;
      });

      return aC.sentence(id, tokens, cite);
    }

    function parseDocument(json, docId) {
      var sentences = arethusaUtil.toAry(json.treebank.sentence);
      return arethusaUtil.inject([], sentences, function (memo, sentence, k) {
        var cite = extractCiteInfo(sentence);
        memo.push(xmlSentenceToState(docId, sentence.word, sentence._id, cite));
      });
    }

    // Try to support the new as well as the old schema for now
    function extractCiteInfo(sentence) {
      var cite = sentence._cite;
      if (cite) {
        return cite;
      } else {

        var docId = sentence._document_id;
        var subdoc = sentence._subdoc;
        if (subdoc) {
          return docId + ':' + subdoc;
        } else {
          return docId;
        }
      }
    }

    function findAdditionalConfInfo(json) {
      var linkInfo = json.treebank.link;
      var links =  linkInfo ? arethusaUtil.toAry(linkInfo) : [];
      var confs = arethusaUtil.inject({}, links, function(memo, link) {
        memo[link._title] = link._href;
      });
      var format = json.treebank._format;
      if (format) {
        // For backwards compatibility to older days
        if (format == 'aldt') {
          format = 'aldt2' + json.treebank['_xml:lang'];
        }
        confs.fullFile = format;
      }
      return confs;
    }

    return function (conf) {
      var self = this;
      var resource = configurator.provideResource(conf.resource);
      var docId = conf.docIdentifier;

      this.preselections = retrieverHelper.getPreselections(conf);

      this.get = function (callback) {
        resource.get().then(function (res) {
          var xml = res.data;
          var json = arethusaUtil.xml2json(res.data);
          var moreConf = findAdditionalConfInfo(json);

          documentStore.addDocument(docId, new aC.doc(xml, json, moreConf));
          callback(parseDocument(json, docId));
        });
      };
    };
  }
]);
<commit_msg>Fix faulty logic in sentence id padding<commit_after>'use strict';
/* A newable factory to handle xml files using the Perseus Treebank Schema
 *
 * The constructor functions takes a configuration object (that typically
 * contains a resource object for this service).
 *
 */
angular.module('arethusa').factory('TreebankRetriever', [
  'configurator',
  'documentStore',
  'retrieverHelper',
  'idHandler',
  function (configurator, documentStore, retrieverHelper, idHandler) {
    function xmlTokenToState(docId, token, sentenceId, artificials) {
      // One could formalize this to real rules that are configurable...
      //
      // Remember that attributes of the converted xml are prefixed with underscore
      var obj = aC.token(token._form, sentenceId);

      obj.morphology = {
        lemma: token._lemma,
        postag: token._postag
      };

      obj.relation = {};

      var relation = token._relation;
      obj.relation.label = (relation && relation !== 'nil') ? relation : '';

      var gloss = token._gloss;
      if (gloss) {
        obj.morphology.gloss = gloss;
      }

      var sg = token._sg;
      if (sg && !sg.match(/^\s*$/)) {
        obj.sg = { ancestors: sg.split(' ') };
      }

      if (token._artificial) {
        obj.artificial = true;
        obj.type = token._artificial;
      }

      if (aU.isTerminatingPunctuation(obj.string)) {
        obj.terminator = true;
      }

      var intId = xmlTokenId(token, sentenceId);
      retrieverHelper.generateId(obj, intId, token._id, docId);
      createHead(obj, token, artificials);

      return obj;
    }

    function createHead(stateToken, xmlToken, artificials) {
      var head = xmlToken._head;
      if (angular.isDefined(head)) {
        var newHead = {};
        var artHead = artificials[head];
        newHead.id = artHead ? artHead : idHandler.getId(head, stateToken.sentenceId);
        stateToken.head = newHead;
      }
    }

    function xmlTokenId(token, sId) {
      return token._artificial ? token._insertion_id : idHandler.getId(token._id, sId);
    }

    // This is for backwards compatibility - we still might encounter documents, which
    // stored the insertion id without the sentence id. This is a little hacky but a
    // must have.
    function padWithSentenceId(token, sId) {
      var iId = token._insertion_id;
      if (!iId.match(/-/)) {
        token._insertion_id = idHandler.padIdWithSId(iId, sId);
      }
    }

    function extractArtificial(memo, token, i, sId) {
      if (token._artificial) {
        padWithSentenceId(token, sId);
        memo[token._id] = token._insertion_id;
      }
    }

    function xmlSentenceToState(docId, words, id, cite) {
      var tokens = {};
      var artificials = arethusaUtil.inject({}, words, function(memo, token, i) {
        extractArtificial(memo, token, i, id);
      });
      angular.forEach(words, function (xmlToken, i) {
        var token = xmlTokenToState(docId, xmlToken, id, artificials);
        tokens[token.id] = token;
      });

      return aC.sentence(id, tokens, cite);
    }

    function parseDocument(json, docId) {
      var sentences = arethusaUtil.toAry(json.treebank.sentence);
      return arethusaUtil.inject([], sentences, function (memo, sentence, k) {
        var cite = extractCiteInfo(sentence);
        memo.push(xmlSentenceToState(docId, sentence.word, sentence._id, cite));
      });
    }

    // Try to support the new as well as the old schema for now
    function extractCiteInfo(sentence) {
      var cite = sentence._cite;
      if (cite) {
        return cite;
      } else {

        var docId = sentence._document_id;
        var subdoc = sentence._subdoc;
        if (subdoc) {
          return docId + ':' + subdoc;
        } else {
          return docId;
        }
      }
    }

    function findAdditionalConfInfo(json) {
      var linkInfo = json.treebank.link;
      var links =  linkInfo ? arethusaUtil.toAry(linkInfo) : [];
      var confs = arethusaUtil.inject({}, links, function(memo, link) {
        memo[link._title] = link._href;
      });
      var format = json.treebank._format;
      if (format) {
        // For backwards compatibility to older days
        if (format == 'aldt') {
          format = 'aldt2' + json.treebank['_xml:lang'];
        }
        confs.fullFile = format;
      }
      return confs;
    }

    return function (conf) {
      var self = this;
      var resource = configurator.provideResource(conf.resource);
      var docId = conf.docIdentifier;

      this.preselections = retrieverHelper.getPreselections(conf);

      this.get = function (callback) {
        resource.get().then(function (res) {
          var xml = res.data;
          var json = arethusaUtil.xml2json(res.data);
          var moreConf = findAdditionalConfInfo(json);

          documentStore.addDocument(docId, new aC.doc(xml, json, moreConf));
          callback(parseDocument(json, docId));
        });
      };
    };
  }
]);
<|endoftext|>


<commit_before>import isNumeric from './isnumeric';

function sum(arr) {
    let sum = arr.reduce(function(sum, x) {
        return sum + x;
    }, 0);
    if (arr.length === 0) { sum = '--'; }
    return sum;
}

function mean(arr) {
    return sum(arr) / arr.length;
}

function weighted(arr, weight) {
    let sumR = sum(arr);
    let sumW = sum(weight);
    return sumR / sumW;
}

function valsToArray(data, years, keys) {
    let arr = [];
    for (let y = 0; y < years.length; y++) {
        for (var i = 0; i < keys.length; i++) {
            if (isNumeric(data[keys[i]][`y_${years[y]}`])) {
                arr.push(data[keys[i]][`y_${years[y]}`]);
            }
        }
    }
    return arr;
}

function wValsToArray(data, weight, years, keys) {
    let arr = [];
    for (let y = 0; y < years.length; y++) {
        for (var i = 0; i < keys.length; i++) {
            if (isNumeric(data[keys[i]][`y_${years[y]}`]) && isNumeric(weight[keys[i]][`y_${years[y]}`])) {
                arr.push(data[keys[i]][`y_${years[y]}`] * weight[keys[i]][`y_${years[y]}`]);
            }
        }
    }
    return arr;
}

function calcValue(data, calcType = sum, year, keys) {
    if (calcType === 'sum') {
        let dataArray = valsToArray(data.map, [year], keys);
        return sum(dataArray);
    }
    if (calcType === 'mean') {
        let dataArray = valsToArray(data.map, [year], keys);
        return mean(dataArray);
    }
    if (calcType === 'weighted') {
        let dataArray = wValsToArray(data.map, data.w, [year], keys);
        let wArray = valsToArray(data.w, [year], keys);
        return weighted(dataArray, wArray);
    }
    return false;
}

export {sum, mean, weighted, valsToArray, wValsToArray, calcValue};
<commit_msg>Added median calculation<commit_after>import isNumeric from './isnumeric';

function sum(arr) {
    let sum = arr.reduce(function(sum, x) {
        return sum + x;
    }, 0);
    if (arr.length === 0) { sum = '--'; }
    return sum;
}

function mean(arr) {
    return sum(arr) / arr.length;
}

function weighted(arr, weight) {
    let sumR = sum(arr);
    let sumW = sum(weight);
    return sumR / sumW;
}

function median(arr) {
    arr.sort( function(a,b) {return a - b;} );
    let half = Math.floor(arr.length/2);

    if (arr.length % 2) {
        return arr[half];
    }
    else {
        return (arr[half-1] + arr[half]) / 2.0;
    }
}

function valsToArray(data, years, keys) {
    let arr = [];
    for (let y = 0; y < years.length; y++) {
        for (var i = 0; i < keys.length; i++) {
            if (isNumeric(data[keys[i]][`y_${years[y]}`])) {
                arr.push(data[keys[i]][`y_${years[y]}`]);
            }
        }
    }
    return arr;
}

function wValsToArray(data, weight, years, keys) {
    let arr = [];
    for (let y = 0; y < years.length; y++) {
        for (var i = 0; i < keys.length; i++) {
            if (isNumeric(data[keys[i]][`y_${years[y]}`]) && isNumeric(weight[keys[i]][`y_${years[y]}`])) {
                arr.push(data[keys[i]][`y_${years[y]}`] * weight[keys[i]][`y_${years[y]}`]);
            }
        }
    }
    return arr;
}

function calcValue(data, calcType = sum, year, keys) {
    if (calcType === 'sum') {
        let dataArray = valsToArray(data.map, [year], keys);
        return sum(dataArray);
    }
    if (calcType === 'mean') {
        let dataArray = valsToArray(data.map, [year], keys);
        return mean(dataArray);
    }
    if (calcType === 'weighted') {
        let dataArray = wValsToArray(data.map, data.w, [year], keys);
        let wArray = valsToArray(data.w, [year], keys);
        return weighted(dataArray, wArray);
    }
    return false;
}

export {sum, mean, weighted, median, valsToArray, wValsToArray, calcValue};
<|endoftext|>