<commit_before>$(document).ready(function() {

  /*
   * LOVELY INITIATIVES
   */

  // Initialize a temp array
  var tempfarray = [];

  // ID of the Google Spreadsheet
  var spreadsheetID = "13-ozrkaBha3CQIwP9J_FuEF3hnQpXYrKzVxNqS0Hzoo";

  // Make sure it is public or set to Anyone with link can view
  var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json";

  // Create Modal
  function getModal(itemid) {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      var n = itemid;
      var ititle = entry[n].gsx$title.$t;
      var icategory = entry[n].gsx$category.$t;
      var idescription = entry[n].gsx$description.$t;
      var iwebsite = entry[n].gsx$website.$t;
      var iimage = entry[n].gsx$image.$t;
      var istatus = entry[n].gsx$status.$t;
      var iregion = entry[n].gsx$region.$t;
      var ifellow = entry[n].gsx$fellow.$t;
      var ischool = entry[n].gsx$school.$t;
      var istate = entry[n].gsx$state.$t;
      var istakeholders = entry[n].gsx$stakeholders.$t;
      var iresources = entry[n].gsx$resources.$t;
      var iactivity = entry[n].gsx$activity.$t;
      var idesiredoutcome = entry[n].gsx$desiredoutcome.$t;
      var iimpactachieved = entry[n].gsx$impactachieved.$t;

      // Refreshes the Modal
      $('#myModalLabel').empty();
      $('#modal-body-1').empty();
      $('#modal-body-2').empty();
      $('.modal-footer').empty();

      $('#myModalLabel').append(ititle + '

' + iwebsite + '
');
      $('#modal-body-1').append('

Fellow(s):
' + ifellow + '

Status:
' + istatus + '

School and State:
' + ischool + ', ' + istate + '

Region:
' + iregion + '

Stakeholders:
' + istakeholders + '

Resources:
' + iresources);
      $('#modal-body-2').append('

Description:
' + idescription + '

Activity:
' + iactivity + '

Desired Outcome:
' + idesiredoutcome + '

Impact Achieved:
' + iimpactachieved + '

Challenges faced and Plans to overcome:');

      $('#myModal').modal("show");

    });
  }

  // Append Data
  function appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow) {
    $('.list').append('
' + ititle + ' ' + inum + '
 ' + 'by ' + ifellow + '
Categories: ' + icategory + '

' + idescription + '

');
  }

  // Get the Data from the spreadsheet using JSON
  function getData() {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;

        appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);

      };
    });
  }

  // Filters data
  function filterData() {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;

        // Filters the cateogries
        function iscorrectcategory(kategori, nombor) {
          for (var l = 0; l < tempfarray.length; l++) {
            if (kategori.indexOf(tempfarray[l]) < 0) {
              return false;
              break;
            } else if (l == tempfarray.length - 1) {
              appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
              break;
            }
          }
        };

        iscorrectcategory(icategory, i);

      };
    });
  }

  // Individual Filter Buttons
  function idvfilterData(filteredword, type) {
    $('input[class=filtercheckbox]').attr('checked', false);
    tempfarray = [];

    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;

        if (type == "region") {
          if (iregion.indexOf(filteredword) >= 0) {
            appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
          }
        } else if (type = "status") {
          if (filteredword == istatus) {
            appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
          }
        };
      };
    });
  }

  // Search Query
  function searchedData(searchword) {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var ischool = entry[i].gsx$school.$t;
        var istate = entry[i].gsx$state.$t;
        var istakeholders = entry[i].gsx$stakeholders.$t;
        var iresources = entry[i].gsx$resources.$t;
        var iactivity = entry[i].gsx$activity.$t;
        var idesiredoutcome = entry[i].gsx$desiredoutcome.$t;
        var iimpactachieved = entry[i].gsx$impactachieved.$t;

        // Set to lower case for m
        searchword = searchword.toLowerCase();
        var ltitle = ititle.toLowerCase();
        var lcategory = icategory.toLowerCase();
        var ldescription = idescription.toLowerCase();
        var lstatus = istatus.toLowerCase();
        var lregion = iregion.toLowerCase();
        var lfellow = ifellow.toLowerCase();
        var lschool = ischool.toLowerCase();
        var lstate = istate.toLowerCase();
        var lstakeholders = istakeholders.toLowerCase();
        var lresources = iresources.toLowerCase();
        var lactivity = iactivity.toLowerCase();
        var ldesiredoutcome = idesiredoutcome.toLowerCase();
        var limpactachieved = iimpactachieved.toLowerCase();

        if (ltitle.indexOf(searchword) >= 0 || ldescription.indexOf(searchword) >= 0 || lcategory.indexOf(searchword) >= 0 || lstatus.indexOf(searchword) >= 0 || lregion.indexOf(searchword) >= 0 || lfellow.indexOf(searchword) >= 0 || lschool.indexOf(searchword) >= 0 || lstate.indexOf(searchword) >= 0 || lstakeholders.indexOf(searchword) >= 0 || lresources.indexOf(searchword) >= 0 || lactivity.indexOf(searchword) >= 0 || ldesiredoutcome.indexOf(searchword) >= 0 || limpactachieved.indexOf(searchword) >= 0) {
          appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
        };
      };
    });
  }

  // Generate the Initial Data
  getData();

  // Links the title of the Iniative to its profile page
  $(".list").delegate(".name", "click", function() {
    var id = $(this).attr("id");
    getModal(id);
  });

  // These are the buttons function
  // Always Lucky - Random list generator
  $('#filter-random').click(function() {
    $.getJSON(url, function(data) {
      $('input[class=filtercheckbox]').attr('checked', false);
      tempfarray = [];

      var entry = data.feed.entry;
      var max = entry.length;
      var min = 0;

      $(".list").empty();

      // Generate random item
      var rn = Math.floor(Math.random() * (max + min)) + min;

      // Append the random item unto the database
      var ititle = entry[rn].gsx$title.$t;
      var icategory = entry[rn].gsx$category.$t;
      var idescription = entry[rn].gsx$description.$t;
      var iwebsite = entry[rn].gsx$website.$t;
      var iimage = entry[rn].gsx$image.$t;
      var istatus = entry[rn].gsx$status.$t;
      var iregion = entry[rn].gsx$region.$t;
      var ifellow = entry[rn].gsx$fellow.$t;

      appendData(ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
    });
  });

  // Search Button
  $("#search_button").click(function() {
    var user_input = $(".searched").val();
    searchedData(user_input);
  });

  // Search Keypress
  $(".searched").keypress(function(event) {
    if (event.which == 13) {
      var user_input = $(".searched").val();
      searchedData(user_input);
    }
  });

  // Pushes or removes an element from the array that needs to be filtered
  function checkboxfilter(categoryp, id) {
    if (document.getElementById(id).checked) {
      tempfarray.push(categoryp);
      filterData();
    } else {
      var ssindex = tempfarray.indexOf(categoryp);
      if (ssindex > -1) {
        tempfarray.splice(ssindex, 1);
      }
      if (tempfarray.length <= 0) {
        getData();
      } else {
        filterData();
      }
    }
  }

  // Subject Specific
  $('#filter-subject-specific').click(function() {
    checkboxfilter("Subject Specific", "filter-subject-specific");
  });

  // Teaching Quality
  $('#filter-teaching-quality').click(function() {
    checkboxfilter("Teaching Quality", "filter-teaching-quality");
  });

  // Personal Development
  $('#filter-development').click(function() {
    checkboxfilter("Development", "filter-development");
  });

  // English Oral Profiency
  $('#filter-english-oral-fluency').click(function() {
    checkboxfilter("English Oral Fluency", "filter-english-oral-fluency");
  });

  // Literacy
  $('#filter-literacy').click(function() {
    checkboxfilter("Literacy", "filter-literacy");
  });

  // Numeracy
  $("#filter-numeracy").click(function() {
    checkboxfilter("Numeracy", "filter-numeracy");
  });

  // Tertiary Education
  $("#filter-tertiary-education").click(function() {
    checkboxfilter("Tertiary Education", "filter-tertiary-education");
  });

  // Learning Environment
  $("#filter-learning-environment").click(function() {
    checkboxfilter("Learning Environment", "filter-learning-environment");
  });

  // Participation
  $("#filter-participation").click(function() {
    checkboxfilter("Participation", "filter-participation");
  });

  // North
  $("#filter-north").click(function() {
    idvfilterData("North", "region");
  });

  // South
  $("#filter-east").click(function() {
    idvfilterData("East", "region");
  });

  // West
  $("#filter-west").click(function() {
    idvfilterData("West", "region");
  });

  // South
  $("#filter-south").click(function() {
    idvfilterData("South", "region");
  });

  // Active
  $("#filter-active").click(function() {
    idvfilterData("Active", "status");
  });

  // Inactive
  $("#filter-inactive").click(function() {
    idvfilterData("Inactive", "status");
  });

  // wat
  $("#filter-notwat").click(function() {
    getModal(1);
  });

  // Show all
  $('#filter-none').click(function() {
    $('input[class=filtercheckbox]').attr('checked', false);
    tempfarray = [];
    getData();
  });
});
<commit_msg>Update index.js<commit_after>$(document).ready(function() {

  /*
   * LOVELY INITIATIVES
   */

  // Initialize a temp array
  var tempfarray = [];

  // ID of the Google Spreadsheet
  var spreadsheetID = "13-ozrkaBha3CQIwP9J_FuEF3hnQpXYrKzVxNqS0Hzoo";

  // Make sure it is public or set to Anyone with link can view
  var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json";

  // Create Modal
  function getModal(itemid) {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      var n = itemid;
      var ititle = entry[n].gsx$title.$t;
      var icategory = entry[n].gsx$category.$t;
      var idescription = entry[n].gsx$description.$t;
      var iwebsite = entry[n].gsx$website.$t;
      var iimage = entry[n].gsx$image.$t;
      var istatus = entry[n].gsx$status.$t;
      var iregion = entry[n].gsx$region.$t;
      var ifellow = entry[n].gsx$fellow.$t;
      var ischool = entry[n].gsx$school.$t;
      var istate = entry[n].gsx$state.$t;
      var istakeholders = entry[n].gsx$stakeholders.$t;
      var iresources = entry[n].gsx$resources.$t;
      var iactivity = entry[n].gsx$activity.$t;
      var idesiredoutcome = entry[n].gsx$desiredoutcome.$t;
      var iimpactachieved = entry[n].gsx$impactachieved.$t;

      // Refreshes the Modal
      $('#myModalLabel').empty();
      $('#modal-body-1').empty();
      $('#modal-body-2').empty();
      $('.modal-footer').empty();

      $('#myModalLabel').append(ititle + '

' + iwebsite + '
');
      $('#modal-body-1').append('

Fellow(s):
' + ifellow + '

Status:
' + istatus + '

School and State:
' + ischool + ', ' + istate + '

Region:
' + iregion + '

Stakeholders:
' + istakeholders + '

Resources:
' + iresources);
      $('#modal-body-2').append('

Description:
' + idescription + '

Activity:
' + iactivity + '

Desired Outcome:
' + idesiredoutcome + '

Impact Achieved:
' + iimpactachieved + '

Challenges faced and Plans to overcome:');

      $('#myModal').modal("show");

    });
  }

  // Append Data
  function appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow) {
    $('.list').append('
' + ititle + ' ' + inum + '
 ' + 'by ' + ifellow + '
Categories: ' + icategory + '

' + idescription + '

');
  }

  // Get the Data from the spreadsheet using JSON
  function getData() {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;

        appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);

      };
    });
  }

  // Filters data
  function filterData() {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;

        // Filters the cateogries
        function iscorrectcategory(kategori, nombor) {
          for (var l = 0; l < tempfarray.length; l++) {
            if (kategori.indexOf(tempfarray[l]) < 0) {
              return false;
              break;
            } else if (l == tempfarray.length - 1) {
              appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
              break;
            }
          }
        };

        iscorrectcategory(icategory, i);

      };
    });
  }

  // Individual Filter Buttons
  function idvfilterData(filteredword, type) {
    $('input[class=filtercheckbox]').attr('checked', false);
    tempfarray = [];

    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;

        if (type == "region") {
          if (iregion.indexOf(filteredword) >= 0) {
            appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
          }
        } else if (type = "status") {
          if (filteredword == istatus) {
            appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
          }
        };
      };
    });
  }

  // Search Query
  function searchedData(searchword) {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var ischool = entry[i].gsx$school.$t;
        var istate = entry[i].gsx$state.$t;
        var istakeholders = entry[i].gsx$stakeholders.$t;
        var iresources = entry[i].gsx$resources.$t;
        var iactivity = entry[i].gsx$activity.$t;
        var idesiredoutcome = entry[i].gsx$desiredoutcome.$t;
        var iimpactachieved = entry[i].gsx$impactachieved.$t;

        // Set to lower case
        searchword = searchword.toLowerCase();
        var ltitle = ititle.toLowerCase();
        var lcategory = icategory.toLowerCase();
        var ldescription = idescription.toLowerCase();
        var lstatus = istatus.toLowerCase();
        var lregion = iregion.toLowerCase();
        var lfellow = ifellow.toLowerCase();
        var lschool = ischool.toLowerCase();
        var lstate = istate.toLowerCase();
        var lstakeholders = istakeholders.toLowerCase();
        var lresources = iresources.toLowerCase();
        var lactivity = iactivity.toLowerCase();
        var ldesiredoutcome = idesiredoutcome.toLowerCase();
        var limpactachieved = iimpactachieved.toLowerCase();

        if (ltitle.indexOf(searchword) >= 0 || ldescription.indexOf(searchword) >= 0 || lcategory.indexOf(searchword) >= 0 || lstatus.indexOf(searchword) >= 0 || lregion.indexOf(searchword) >= 0 || lfellow.indexOf(searchword) >= 0 || lschool.indexOf(searchword) >= 0 || lstate.indexOf(searchword) >= 0 || lstakeholders.indexOf(searchword) >= 0 || lresources.indexOf(searchword) >= 0 || lactivity.indexOf(searchword) >= 0 || ldesiredoutcome.indexOf(searchword) >= 0 || limpactachieved.indexOf(searchword) >= 0) {
          appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
        };
      };
    });
  }

  // Generate the Initial Data
  getData();

  // Links the title of the Iniative to its profile page
  $(".list").delegate(".name", "click", function() {
    var id = $(this).attr("id");
    getModal(id);
  });

  // These are the buttons function
  // Always Lucky - Random list generator
  $('#filter-random').click(function() {
    $.getJSON(url, function(data) {
      $('input[class=filtercheckbox]').attr('checked', false);
      tempfarray = [];

      var entry = data.feed.entry;
      var max = entry.length;
      var min = 0;

      $(".list").empty();

      // Generate random item
      var rn = Math.floor(Math.random() * (max + min)) + min;

      // Append the random item unto the database
      var inum = rn;
      var ititle = entry[rn].gsx$title.$t;
      var icategory = entry[rn].gsx$category.$t;
      var idescription = entry[rn].gsx$description.$t;
      var iwebsite = entry[rn].gsx$website.$t;
      var iimage = entry[rn].gsx$image.$t;
      var istatus = entry[rn].gsx$status.$t;
      var iregion = entry[rn].gsx$region.$t;
      var ifellow = entry[rn].gsx$fellow.$t;

      appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow);
    });
  });

  // Search Button
  $("#search_button").click(function() {
    var user_input = $(".searched").val();
    searchedData(user_input);
  });

  // Search Keypress
  $(".searched").keypress(function(event) {
    if (event.which == 13) {
      var user_input = $(".searched").val();
      searchedData(user_input);
    }
  });

  // Pushes or removes an element from the array that needs to be filtered
  function checkboxfilter(categoryp, id) {
    if (document.getElementById(id).checked) {
      tempfarray.push(categoryp);
      filterData();
    } else {
      var ssindex = tempfarray.indexOf(categoryp);
      if (ssindex > -1) {
        tempfarray.splice(ssindex, 1);
      }
      if (tempfarray.length <= 0) {
        getData();
      } else {
        filterData();
      }
    }
  }

  // Subject Specific
  $('#filter-subject-specific').click(function() {
    checkboxfilter("Subject Specific", "filter-subject-specific");
  });

  // Teaching Quality
  $('#filter-teaching-quality').click(function() {
    checkboxfilter("Teaching Quality", "filter-teaching-quality");
  });

  // Personal Development
  $('#filter-development').click(function() {
    checkboxfilter("Development", "filter-development");
  });

  // English Oral Profiency
  $('#filter-english-oral-fluency').click(function() {
    checkboxfilter("English Oral Fluency", "filter-english-oral-fluency");
  });

  // Literacy
  $('#filter-literacy').click(function() {
    checkboxfilter("Literacy", "filter-literacy");
  });

  // Numeracy
  $("#filter-numeracy").click(function() {
    checkboxfilter("Numeracy", "filter-numeracy");
  });

  // Tertiary Education
  $("#filter-tertiary-education").click(function() {
    checkboxfilter("Tertiary Education", "filter-tertiary-education");
  });

  // Learning Environment
  $("#filter-learning-environment").click(function() {
    checkboxfilter("Learning Environment", "filter-learning-environment");
  });

  // Participation
  $("#filter-participation").click(function() {
    checkboxfilter("Participation", "filter-participation");
  });

  // North
  $("#filter-north").click(function() {
    idvfilterData("North", "region");
  });

  // South
  $("#filter-east").click(function() {
    idvfilterData("East", "region");
  });

  // West
  $("#filter-west").click(function() {
    idvfilterData("West", "region");
  });

  // South
  $("#filter-south").click(function() {
    idvfilterData("South", "region");
  });

  // Active
  $("#filter-active").click(function() {
    idvfilterData("Active", "status");
  });

  // Inactive
  $("#filter-inactive").click(function() {
    idvfilterData("Inactive", "status");
  });

  // wat
  $("#filter-notwat").click(function() {
    getModal(1);
  });

  // Show all
  $('#filter-none').click(function() {
    $('input[class=filtercheckbox]').attr('checked', false);
    tempfarray = [];
    getData();
  });
});
<|endoftext|>


<commit_before>const rootVm = new Vue({
    el: '#app-sudoku',
    template: `

 event.target.focus()"
    >

                        {{ cell.value }}
                        {{ cell.value }}

 set ? i + 1 : ''))">
                            {{ n }}

        <historical-event :event="command" :key="index" :active="history.commands.length - index === history.current"
        v-for="(command, index) in Array.from(history.commands).reverse()" />

initial

`,
    components: {
        'historical-event': {
            props: { event: Object, active: Boolean, },
            template: '
{{ where + " " + what }}
',
            computed: {
                where: function() {
                    const where = this.event.where;
                    return '(' + (~~(where / 9) + 1) + ',' + (where % 9 + 1) + ')';
                },
                what: function() {
                    switch(this.event.type) {
                    case 'erase': return 'erase';
                    default: return this.event.type + ' ' + this.event.value;
                    }
                },
            },
        }
    },
    computed: {
        affectedIndices: function() { return this.affectedIndicesBy(this.pointed); },
        boxes: function() {
            return this.chunksOf(9, this.indices.box.map(index => this.cells[index]));
        },
        cells: function() {
            /* manage each number cell by the object: {
                {Boolean} given, -- true if the number is given for clue, otherwise false.
                {Number} value, -- a number between 0 to 9.
                {Array} memo, -- array of Boolean, each element represent the number those of which can be placed, user considers.
            } */
            return this.history.commands.slice(0, this.history.current).reduce((cells, command) => {
                switch(command.type) {
                case 'place':
                case 'erase':
                    cells[command.where].value = command.value;
                    break;
                case 'remark':
                case 'unmark':
                    cells[command.where].memo[command.value - 1] = command.type[0] === 'r';
                    break;
                case 'flush':
                    this.affectedIndicesBy(command.where).forEach(index => cells[index].memo[command.value - 1] = false);
                    break;
                }
                return cells;
            }, Array.from( // initial cells
                '060003001200500600007090500000400090800000006010005000002010700004009003700200040' // 朝日新聞beパズル 2017/10/07 掲載分
            ).map(Number).map(n => new Object({given: n !== 0, value: n, memo: Array(9), })));
        },
        missPlacedIndices: function() {
            const unique = (value, index, array) => array.indexOf(value) === index;
            const indices = [this.indices.row, this.indices.col, this.indices.box].reduce((a, b) => a.concat(b));
            const dupOrNot = this.chunksOf(9, indices.map(index => this.cells[index].value)) // for each 9...
            .map(vs => vs.map((v, i, self) => v && self.slice(0, i).concat(self.slice(i+1)).some(x => x === v))) // flag non-zero and duplicates
            .reduce((a, b) => a.concat(b));
            return dupOrNot.map((v, i) => v ? indices[i] : NaN).filter(unique); // NaN will be removed by unique.
        },
        indices: (() => {
            const colNr = index => index % 9;
            const boxNr = index => 3 * ~~(index / 27) + ~~((index % 9) / 3);
            const row = Array.from({length: 81, }).map((_, index) => index);
            const col = Array.from(row).sort((a, b) => colNr(a) - colNr(b));
            const box = Array.from(row).sort((a, b) => boxNr(a) - boxNr(b));
            const indices = { row: row, col: col, box: box, };
            return () => indices;
        })(),
        pointedCell: function() { return this.cells[this.pointed] || {given: true, }; },
    },
    data: () => new Object({
        pointed: -1,
        /* user operations. this backs undo/redo up.
        `current` points `commands` array index where new command to be inserted into. */
        history: {commands: [], current: 0, },
    }),
    methods: {
        chunksOf: (n, array) => Array.from({
            [Symbol.iterator]: () => {
                var i = 0;
                return { next: () => new Object({done: i >= array.length, value: array.slice(i, i += n), }), };
            },
        }),
        affectedIndicesBy: function(cellIndex) {
            const get = array => {
                const index = array.findIndex(x => x === cellIndex);
                const start = 9 * ~~(index / 9);
                return array.slice(start, start + (index !== -1 ? 9 : 0));
            };
            return [get(this.indices.row), get(this.indices.col), get(this.indices.box)]
            .reduce((a, b) => a.concat(b)) // flatten array
            .filter(value => value !== cellIndex) // remove cellIndex itself
            .filter((value, index, array) => array.indexOf(value) === index); // remove duplicates
        },
        onKey: function(event) {
            const ALT = event.altKey;
            const SHIFT = event.shiftKey;
            const NUMBER = Number((/^Digit([1-9])$/.exec(event.code) || [])[1]);
            const UNDO = event.code === 'KeyZ' && ALT && !SHIFT;
            const REDO = (event.code === 'KeyZ' && ALT && SHIFT) || (event.code === 'KeyY' && ALT && !SHIFT);
            if (ALT && NUMBER && this.pointed !== -1) {
                this.mark(NUMBER, !SHIFT);
            } else if (!ALT && NUMBER && !this.pointedCell.given) {
                this.place(NUMBER);
            } else if (['Digit0', 'Backspace'].includes(event.code) && !this.pointedCell.given) {
                this.erase();
            } else if (UNDO && this.history.current !== 0) {
                this.history.current -= 1;
            } else if (REDO && this.history.current != this.history.commands.length) {
                this.history.current += 1;
            }
        },
        place: function(number) {
            this.push({value: number, type: 'place', });
        },
        erase: function() {
            this.push({value: 0, type: 'erase', });
        },
        mark: function(number, mark) {
            this.push({value: number, type: mark ? 'remark' : 'unmark', });
        },
        flush: function() {
            this.push({value: this.pointedCell.value, type: 'flush', });
        },
        push: function(command) {
            this.history.commands.splice(this.history.current ++, Infinity,
                Object.assign({when: new Date(), where: this.pointed, }, command));
        },
    },
});
<commit_msg>Remove `affectedIndices` computed.<commit_after>const rootVm = new Vue({
    el: '#app-sudoku',
    template: `

 event.target.focus()"
    >

                        {{ cell.value }}
                        {{ cell.value }}

 set ? i + 1 : ''))">
                            {{ n }}

        <historical-event :event="command" :key="index" :active="history.commands.length - index === history.current"
        v-for="(command, index) in Array.from(history.commands).reverse()" />

initial

`,
    components: {
        'historical-event': {
            props: { event: Object, active: Boolean, },
            template: '
{{ where + " " + what }}
',
            computed: {
                where: function() {
                    const where = this.event.where;
                    return '(' + (~~(where / 9) + 1) + ',' + (where % 9 + 1) + ')';
                },
                what: function() {
                    switch(this.event.type) {
                    case 'erase': return 'erase';
                    default: return this.event.type + ' ' + this.event.value;
                    }
                },
            },
        }
    },
    computed: {
        boxes: function() {
            return this.chunksOf(9, this.indices.box.map(index => this.cells[index]));
        },
        cells: function() {
            /* manage each number cell by the object: {
                {Boolean} given, -- true if the number is given for clue, otherwise false.
                {Number} value, -- a number between 0 to 9.
                {Array} memo, -- array of Boolean, each element represent the number those of which can be placed, user considers.
            } */
            return this.history.commands.slice(0, this.history.current).reduce((cells, command) => {
                switch(command.type) {
                case 'place':
                case 'erase':
                    cells[command.where].value = command.value;
                    break;
                case 'remark':
                case 'unmark':
                    cells[command.where].memo[command.value - 1] = command.type[0] === 'r';
                    break;
                case 'flush':
                    this.affectedIndicesBy(command.where).forEach(index => cells[index].memo[command.value - 1] = false);
                    break;
                }
                return cells;
            }, Array.from( // initial cells
                '060003001200500600007090500000400090800000006010005000002010700004009003700200040' // 朝日新聞beパズル 2017/10/07 掲載分
            ).map(Number).map(n => new Object({given: n !== 0, value: n, memo: Array(9), })));
        },
        missPlacedIndices: function() {
            const unique = (value, index, array) => array.indexOf(value) === index;
            const indices = [this.indices.row, this.indices.col, this.indices.box].reduce((a, b) => a.concat(b));
            const dupOrNot = this.chunksOf(9, indices.map(index => this.cells[index].value)) // for each 9...
            .map(vs => vs.map((v, i, self) => v && self.slice(0, i).concat(self.slice(i+1)).some(x => x === v))) // flag non-zero and duplicates
            .reduce((a, b) => a.concat(b));
            return dupOrNot.map((v, i) => v ? indices[i] : NaN).filter(unique); // NaN will be removed by unique.
        },
        indices: (() => {
            const colNr = index => index % 9;
            const boxNr = index => 3 * ~~(index / 27) + ~~((index % 9) / 3);
            const row = Array.from({length: 81, }).map((_, index) => index);
            const col = Array.from(row).sort((a, b) => colNr(a) - colNr(b));
            const box = Array.from(row).sort((a, b) => boxNr(a) - boxNr(b));
            const indices = { row: row, col: col, box: box, };
            return () => indices;
        })(),
        pointedCell: function() { return this.cells[this.pointed] || {given: true, }; },
    },
    data: () => new Object({
        pointed: -1,
        /* user operations. this backs undo/redo up.
        `current` points `commands` array index where new command to be inserted into. */
        history: {commands: [], current: 0, },
    }),
    methods: {
        chunksOf: (n, array) => Array.from({
            [Symbol.iterator]: () => {
                var i = 0;
                return { next: () => new Object({done: i >= array.length, value: array.slice(i, i += n), }), };
            },
        }),
        affectedIndicesBy: function(cellIndex) {
            const get = array => {
                const index = array.findIndex(x => x === cellIndex);
                const start = 9 * ~~(index / 9);
                return array.slice(start, start + (index !== -1 ? 9 : 0));
            };
            return [get(this.indices.row), get(this.indices.col), get(this.indices.box)]
            .reduce((a, b) => a.concat(b)) // flatten array
            .filter(value => value !== cellIndex) // remove cellIndex itself
            .filter((value, index, array) => array.indexOf(value) === index); // remove duplicates
        },
        onKey: function(event) {
            const ALT = event.altKey;
            const SHIFT = event.shiftKey;
            const NUMBER = Number((/^Digit([1-9])$/.exec(event.code) || [])[1]);
            const UNDO = event.code === 'KeyZ' && ALT && !SHIFT;
            const REDO = (event.code === 'KeyZ' && ALT && SHIFT) || (event.code === 'KeyY' && ALT && !SHIFT);
            if (ALT && NUMBER && this.pointed !== -1) {
                this.mark(NUMBER, !SHIFT);
            } else if (!ALT && NUMBER && !this.pointedCell.given) {
                this.place(NUMBER);
            } else if (['Digit0', 'Backspace'].includes(event.code) && !this.pointedCell.given) {
                this.erase();
            } else if (UNDO && this.history.current !== 0) {
                this.history.current -= 1;
            } else if (REDO && this.history.current != this.history.commands.length) {
                this.history.current += 1;
            }
        },
        place: function(number) {
            this.push({value: number, type: 'place', });
        },
        erase: function() {
            this.push({value: 0, type: 'erase', });
        },
        mark: function(number, mark) {
            this.push({value: number, type: mark ? 'remark' : 'unmark', });
        },
        flush: function() {
            this.push({value: this.pointedCell.value, type: 'flush', });
        },
        push: function(command) {
            this.history.commands.splice(this.history.current ++, Infinity,
                Object.assign({when: new Date(), where: this.pointed, }, command));
        },
    },
});
<|endoftext|>


<commit_before>var tipbox=document.querySelector('.tip');
tipbox.addEventListener('click', function(){
  $(".tip").hide();
});
var count = 0;
var hoursCount = 0;
var firstTime=false;
var first= false;
var addH = document.querySelector('.check');
addH.innerHTML = "You will See Here Your Statistics"
var main = document.getElementById("main");
var isChecked = false;
var divOld = document.getElementById("div")

function minutesUp(){
  count+= 5;
    addH.innerHTML = "You Walked: "+count+" minutes out of "+hoursCount + " Minutes";
    if (count >= 10) {
  $(".walking").css({opacity: "0.3"});
}
  if (count >= 20) {
  $(".walking").css({opacity: "0.7"});
}
  if (count >= 30) {
  $(".walking").css({opacity: "1"});
}
}

function checkTime() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
  if(m < 10) {
    m = "0" + m;
  }
  if(s < 10) {
    s = "0" + s;
  }

  console.log("its been 30 Minutes! Start Walking!!!");

      var div = document.createElement('div');
  div.innerHTML = "
 " + h + ':' + m + ':' + s + "

Time to Walk!
Did you Walk 5 Minutes?
<form action='#'><input type='radio' name='walk' value='yes' onclick='minutesUp()'>Yes
<input type='radio'  name='walk' value='no' >No
</form>";
div.className = 'box';

      hoursCount+= 10;

  addH.innerHTML = "You Walked: "+count+" minutes out of "+hoursCount + " Minutes";

  if (isChecked === true) {
    $( "#main" ).prepend( div );
    // div.insertBefore(div);
    console.log("true");

} else {
  console.log("First Time!");
  $( "#main" ).prepend( div );
  isChecked = true;
}

  console.log(h + ':' + m + ':' + s);

}

checkTime();
setInterval(checkTime, 1800000);

// function checkTime() {
// var date = new Date();
// var h = date.getHours();
// var m = date.getMinutes();
// var s = date.getSeconds();

// var shoot = new Audio("https://raw.githubusercontent.com/yurinkab/game-boxhit/master/lose.wav");

// if(m % 30 === 0) {

//   console.log("its been 30 Minutes! Start Walking!!!");
//   console.log(h + ':' + m + ':' + s);
//   shoot.play();
// }

// }

// setInterval(checkTime, 1000);
<commit_msg>Update index.js<commit_after>var tipbox=document.querySelector('.tip');
tipbox.addEventListener('click', function(){
  $(".tip").hide();
});
var count = 0;
var hoursCount = 0;
var firstTime=false;
var first= false;
var addH = document.querySelector('.check');
addH.innerHTML = "You will See Here Your Statistics"
var main = document.getElementById("main");
var isChecked = false;
var divOld = document.getElementById("div")

function minutesUp(){
  count+= 5;
    addH.innerHTML = "You Walked: "+count+" minutes out of "+hoursCount + " Minutes";
    if (count >= 10) {
  $(".walking").css({opacity: "0.3"});
}
  if (count >= 20) {
  $(".walking").css({opacity: "0.7"});
}
  if (count >= 30) {
  $(".walking").css({opacity: "1"});
}
}

function checkTime() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
  if(m < 10) {
    m = "0" + m;
  }
  if(s < 10) {
    s = "0" + s;
  }

  console.log("its been 30 Minutes! Start Walking!!!");

      var div = document.createElement('div');
  div.innerHTML = "
 " + h + ':' + m + ':' + s + "

Time to Walk!
Did you Walk 5 Minutes?
<form action='#'><input type='radio' name='walk' value='yes' onclick='minutesUp()'>Yes
<input type='radio'  name='walk' value='no' >No
</form>";
div.className = 'box';

      hoursCount+= 30;

  addH.innerHTML = "You Walked: "+count+" minutes out of "+hoursCount + " Minutes";

  if (isChecked === true) {
    $( "#main" ).prepend( div );
    // div.insertBefore(div);
    console.log("true");

} else {
  console.log("First Time!");
  $( "#main" ).prepend( div );
  isChecked = true;
}

  console.log(h + ':' + m + ':' + s);

}

checkTime();
setInterval(checkTime, 1800000);

// function checkTime() {
// var date = new Date();
// var h = date.getHours();
// var m = date.getMinutes();
// var s = date.getSeconds();

// var shoot = new Audio("https://raw.githubusercontent.com/yurinkab/game-boxhit/master/lose.wav");

// if(m % 30 === 0) {

//   console.log("its been 30 Minutes! Start Walking!!!");
//   console.log(h + ':' + m + ':' + s);
//   shoot.play();
// }

// }

// setInterval(checkTime, 1000);
<|endoftext|>


<commit_before>/*
 * This is the main entry point.
 *
 * You can import other modules here, including external packages. When bundling using rollup you can mark those modules as external and have them excluded or, if they have a jsnext:main entry in their package.json (like this package does), let rollup bundle them into your dist file.
 *
 * IMPORTANT NOTE: If you are ultimately creating an iife/self executing bundle for the browser, be sure to:
 *  import 'babel-polyfill'
 *
 * at your application entry point.  This is necessary for browsers that do not yet support some ES2015 runtime necessities such as Symbol.  We do this in `index-iife.js` for our iife rollup bundle.
 */
import 'babel-polyfill'

// Bootstrap components
import 'bootstrap/dist/js/bootstrap'

// invalidComponentMatches is currently disabled due to https://github.com/rollup/rollup/issues/428#issuecomment-170066452
import './checkbox'
import './checkboxInline'
import './collapseInline'
import './file'
import './radio'
import './radioInline'
import './select'
import './switch'
import './text'
import './textarea'

import './drawer'

import './ripples'
import './autofill'
import './bootstrapMaterialDesign'
<commit_msg>import BS sources<commit_after>/*
 * This is the main entry point.
 *
 * You can import other modules here, including external packages. When bundling using rollup you can mark those modules as external and have them excluded or, if they have a jsnext:main entry in their package.json (like this package does), let rollup bundle them into your dist file.
 *
 * IMPORTANT NOTE: If you are ultimately creating an iife/self executing bundle for the browser, be sure to:
 *  import 'babel-polyfill'
 *
 * at your application entry point.  This is necessary for browsers that do not yet support some ES2015 runtime necessities such as Symbol.  We do this in `index-iife.js` for our iife rollup bundle.
 */
import 'babel-polyfill'

// Bootstrap components
import 'bootstrap/js/src/alert'
import 'bootstrap/js/src/button'
import 'bootstrap/js/src/carousel'
import 'bootstrap/js/src/collapse'
import 'bootstrap/js/src/dropdown'
import 'bootstrap/js/src/modal'
import 'bootstrap/js/src/popover'
import 'bootstrap/js/src/scrollspy'
import 'bootstrap/js/src/tab'
import 'bootstrap/js/src/tooltip'
import 'bootstrap/js/src/util'

// invalidComponentMatches is currently disabled due to https://github.com/rollup/rollup/issues/428#issuecomment-170066452
import './checkbox'
import './checkboxInline'
import './collapseInline'
import './file'
import './radio'
import './radioInline'
import './select'
import './switch'
import './text'
import './textarea'

import './drawer'

import './ripples'
import './autofill'
import './bootstrapMaterialDesign'
<|endoftext|>


<commit_before>var totalPercents = {};

var setMainProg = function() {
    var res = 0;
    var num = 0;
    $.each(totalPercents, function(i) { res += totalPercents[i]; num++; });
    var amt = res/num;
    $(".overview.progfill").css("background-color", getCol(amt));
    $(".overview.proglab").text(amt.toString() + "%");
    if (amt > 100) {
        amt = 100;
    }
    $(".overview.progfill").css("width", amt.toString() + "%");
    console.log(amt);
};

var setProg = function(elemClass, progAmt, descUp) {
    var bar = $(elemClass + ".progfill");
    var label = $(elemClass + ".proglab");
    var desc = $(elemClass + ".progdesc");
    bar.css("background-color", getCol(progAmt));
    label.text(progAmt.toString() + "%");
    totalPercents[elemClass] = progAmt;
    if (progAmt > 100) {
        progAmt = 100;
    }
    bar.css("width", progAmt.toString() + "%");
    desc.text(descUp);
    setMainProg();
};

var getCol = function(progAmt) {
    return (progAmt < 50) ? "#F75E5E" : (progAmt < 80) ? "#F2EF4B" : "#5EE66E";
};

$(".progfill").hover(function() {
    var cur = $(this);
    cur.css("height", parseFloat(cur.css("height")) * 1.25);
}, function() {
    var cur = $(this);
    cur.css("height", parseFloat(cur.css("height")) * 0.75);
    });

<commit_msg>Stuff.<commit_after>var totalPercents = {};

var setMainProg = function() {
    var res = 0;
    var num = 0;
    $.each(totalPercents, function(i) { res += totalPercents[i]; num++; });
    var amt = res/num;
    $(".overview.progfill").css("background-color", getCol(amt));
    $(".overview.proglab").text(amt.toString() + "%");
    if (amt > 100) {
        amt = 100;
    }
    $(".overview.progfill").css("width", amt.toString() + "%");
    console.log(amt);
};

var setProg = function(elemClass, progAmt, descUp) {
    var bar = $(elemClass + ".progfill");
    var label = $(elemClass + ".proglab");
    var desc = $(elemClass + ".progdesc");
    bar.css("background-color", getCol(progAmt));
    label.text(progAmt.toString() + "%");
    totalPercents[elemClass] = progAmt;
    if (progAmt > 100) {
        progAmt = 100;
    }
    bar.css("width", progAmt.toString() + "%");
    desc.text(descUp);
    setMainProg();
};

var getCol = function(progAmt) {
    return (progAmt < 50) ? "#F75E5E" : (progAmt < 80) ? "#F2EF4B" : "#5EE66E";
};

$(".progfill").hover(function() {
    var cur = $(this);
    cur.css("height", parseFloat(cur.css("height")) * 1.25);
}, function() {
    var cur = $(this);
    cur.css("height", parseFloat(cur.css("height")) * 0.80);
    });

<|endoftext|>


<commit_before>/**
Funcao de inicialização da página
*/
function init() {

	var mapOptions = {
		center: new google.maps.LatLng(-16.6825443,-49.2538256),
		zoom: 13,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map(document.getElementById("map"),
		mapOptions);

}

/** adiciona os marcadores ao mapa */
function addPlaces() {
	var points = getPoints();
	points.forEach(function (point) {
		plotPoint(map, point);
	});

}

/** adiciona visualmente os marcadores */
/* icon: http://www.iconarchive.com/show/simpsons-icons-by-jonathan-rey/Bart-Simpson-02-Skate-icon.html */
function plotPoint(map, point) {
	var marker = new google.maps.Marker({
		position: point,
		map: window.map,
		title:"Local",
		icon: "img/icon/bart-skate-map.png"
	});
}

/** Retorna os pontos com os picos */
function getPoints() {
	return [
		new google.maps.LatLng(-16.658371, -49.266528),
		new google.maps.LatLng(-16.668238, -49.265670),
		new google.maps.LatLng(-16.684189, -49.303264),
		new google.maps.LatLng(-16.699974, -49.244556),
		new google.maps.LatLng(-16.683695, -49.253482)
	];

}

$(document).ready(function() {
	init();
	addPlaces();
});

<commit_msg>zoom on marker<commit_after>/**
Funcao de inicialização da página
*/
function init() {

	var mapOptions = {
		center: new google.maps.LatLng(-16.6825443,-49.2538256),
		zoom: 13,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map(document.getElementById("map"),
		mapOptions);

	map.markers = [];

}

/** adiciona os marcadores ao mapa */
function addPlaces() {
	var points = getPoints();
	points.forEach(function (point) {
		plotPoint(map, point);
	});

}

/** adiciona visualmente os marcadores */
/* icon: http://www.iconarchive.com/show/simpsons-icons-by-jonathan-rey/Bart-Simpson-02-Skate-icon.html */
function plotPoint(map, point) {
	var marker = new google.maps.Marker({
		position: point,
		map: window.map,
		title:"Local",
		icon: "img/icon/bart-skate-map.png"
	});

	/* adiciona evento */
	google.maps.event.addListener(marker, 'click', function(event) {
			zoomOnMarker(event, marker);
			addButtons();
		}
	);

	/** adiciona ao array do mapa, para controle */
	map.markers.push(marker);

}

/* centraliza e da zoom em um marcador */
function zoomOnMarker (event, marker) {
	var center =  new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
	map.setCenter(center);
	map.setZoom(16);
}

function addButtons() {
	var nav = $("<button value='navegar até aqui>'");
	$(".buttons");
}

/** Retorna os pontos com os picos */
function getPoints() {
	return [
		new google.maps.LatLng(-16.658371, -49.266528),
		new google.maps.LatLng(-16.668238, -49.265670),
		new google.maps.LatLng(-16.684189, -49.303264),
		new google.maps.LatLng(-16.699974, -49.244556),
		new google.maps.LatLng(-16.683695, -49.253482)
	];

}

$(document).ready(function() {
	init();
	addPlaces();
});

<|endoftext|>


<commit_before>// All images taken from PEXELS.COM - free stock images
"use strict";
document.addEventListener("DOMContentLoaded", function(event) {
    // Navigation bar buttons
    (function() {
        var nodes = {};
        (function() {
            nodes.navigation = document.body.querySelector("#navigation");
            nodes.about = nodes.navigation.querySelector("#navAbout");
            nodes.services = nodes.navigation.querySelector("#navServices");
            nodes.courses = nodes.navigation.querySelector("#navCourses");
            nodes.contact = nodes.navigation.querySelector("#navContact");
            nodes.formName = document.body.querySelector("#formName");
            nodes.formEmail = document.body.querySelector("#formEmail");
            nodes.formMessage = document.body.querySelector("#formMessage");
            nodes.aboutRow = document.body.querySelector("#aboutRow");
            nodes.serviceRow = document.body.querySelector("#servicesRow");
            nodes.coursesInfo = document.body.querySelector("#coursesInfo");
            nodes.phoneContact = document.body.querySelector("#phoneContact");
            nodes.aboutRow = document.body.querySelector("#aboutRow");
            nodes.bannerBtn = document.body.querySelector("#bannerBtn");
        })();

        var test = function(node, selector) {
            node.addEventListener("click", function() {
                selector.scrollIntoView();
                window.scrollBy(0, -50);
            });
        };
        test(nodes.about, nodes.aboutRow);
        test(nodes.services, nodes.serviceRow);
        test(nodes.courses, nodes.coursesInfo);
        test(nodes.contact, nodes.phoneContact);
        // Learn more jumbotron button jump to about div
        test(nodes.bannerBtn, nodes.aboutRow);

        // Clear input on click in the form
        nodes.formName.addEventListener("click", function() {
            nodes.formName.value = "";
        });
        nodes.formEmail.addEventListener("click", function() {
            nodes.formEmail.value = "";
        });
        nodes.formMessage.addEventListener("click", function() {
            nodes.formMessage.value = "";
        });
    })();
});
<commit_msg>shortcuts fixed<commit_after>// All images taken from PEXELS.COM - free stock images
"use strict";
document.addEventListener("DOMContentLoaded", function(event) {
    // Navigation bar buttons
    (function() {
        var nodes = {};
        (function() {
            nodes.navigation = document.body.querySelector("#navigation");
            nodes.about = nodes.navigation.querySelector("#navAbout");
            nodes.services = nodes.navigation.querySelector("#navServices");
            nodes.courses = nodes.navigation.querySelector("#navCourses");
            nodes.contact = nodes.navigation.querySelector("#navContact");
            nodes.formName = document.body.querySelector("#name");
            nodes.formEmail = document.body.querySelector("#email");
            nodes.formMessage = document.body.querySelector("#message");
            nodes.aboutRow = document.body.querySelector("#aboutRow");
            nodes.serviceRow = document.body.querySelector("#servicesRow");
            nodes.coursesInfo = document.body.querySelector("#coursesInfo");
            nodes.phoneContact = document.body.querySelector("#phoneContact");
            nodes.aboutRow = document.body.querySelector("#aboutRow");
            nodes.bannerBtn = document.body.querySelector("#bannerBtn");
        })();

        var navigationShortcut = function(node, selector) {
            node.addEventListener("click", function() {
                selector.scrollIntoView();
                window.scrollBy(0, -50);
            });
        };
        navigationShortcut(nodes.about, nodes.aboutRow);
        navigationShortcut(nodes.services, nodes.serviceRow);
        navigationShortcut(nodes.courses, nodes.coursesInfo);
        navigationShortcut(nodes.contact, nodes.phoneContact);
        // Learn more jumbotron button jump to about div
        navigationShortcut(nodes.bannerBtn, nodes.aboutRow);

        // Clear input on click in the form
        nodes.formName.addEventListener("click", function() {
            nodes.formName.value = "";
        });
        nodes.formEmail.addEventListener("click", function() {
            nodes.formEmail.value = "";
        });
        nodes.formMessage.addEventListener("click", function() {
            nodes.formMessage.value = "";
        });
    })();
});
<|endoftext|>


<commit_before>function setup(){
  canvas = createCanvas(windowWidth, windowHeight-10);

  setupControls();
  placeEnemies();
  spaceship = placeSpaceShip();
  gameObjects.push(spaceship);
}

function draw(){
  background(0);
  if(!gameOver){
    updatePositions();
    drawObjects();
  }
  else{
    if(!refreshed){
      setTimeout(resetEverything, 3000 );
      refreshed = true;
    }
    fill(255);
    gameOverTextSize = constrain(gameOverTextSize,0,50);
    textSize(gameOverTextSize);
    rectMode(CENTER);
    text("Game Over", windowWidth*(1/4 + 1/8), windowHeight/2);
    if(score == numEnemies){
      text("You Won!", windowWidth*(1/4 + 1/7), windowHeight/2 + 100);
    }
    gameOverTextSize += 2;
  }
  textSize(20);
  text('Score:' + score, windowWidth - 100, 50);
}
<commit_msg>Chingu chuzzled<commit_after>function setup(){
  canvas = createCanvas(windowWidth, windowHeight-10);

  setupControls();
  placeEnemies();
  spaceship = placeSpaceShip();
  gameObjects.push(spaceship);
}

function draw(){
  background(0);
  if(!gameOver){
    updatePositions();
    drawObjects();
  }
  else{
    if(!refreshed){
      setTimeout(resetEverything, 7000 );
      refreshed = true;
    }
    fill(255);
    gameOverTextSize = constrain(gameOverTextSize,0,50);
    textSize(gameOverTextSize);
    rectMode(CENTER);
    text("Game Over", windowWidth*(1/4 + 1/8), windowHeight/2);
    if(score == numEnemies){
      text("You Won! Code is: MediumOfRiddles", windowWidth*(1/4 + 1/7), windowHeight/2 + 100);
    }
    gameOverTextSize += 2;
  }
  textSize(20);
  text('Score:' + score, windowWidth - 100, 50);
}
<|endoftext|>


<commit_before>const path = require('path');
const select = require('unist-util-select');

const isInternal = url => !url.includes(':') && !url.startsWith('//');

module.exports = ({ markdownNode, markdownAST, getNode, files }) => {
  if (!markdownNode.fileAbsolutePath) {
    return;
  }

  const filteredFiles = files.filter(x => x && x.relativePath);

  const parentNode = getNode(markdownNode.parent);
  const parentNodeAbsoluteDir = parentNode.dir + '/';
  const parentNodeRelativeDir = path.posix.dirname(parentNode.relativePath) + '/';

  const fixUrl = url => {
    if (isInternal(url)) {
      const relativePath = path.posix.resolve('/', parentNodeRelativeDir, url);
      const rootlessRelativePath = relativePath.substr(1);

      const fileNode = filteredFiles.find(x => x.relativePath === rootlessRelativePath);

      if (fileNode) {
        const relativePath = path.posix.relative(parentNodeAbsoluteDir, fileNode.absolutePath);

        return relativePath;
      }
    }

    return url;
  };

  select(markdownAST, 'image').forEach(node => {
    node.url = fixUrl(node.url);
  });

  select(markdownAST, 'link').forEach(node => {
    node.url = fixUrl(node.url);
  });

  const frontmatterImage = markdownNode.frontmatter && markdownNode.frontmatter.image;

  if (frontmatterImage) {
    markdownNode.frontmatter.image = fixUrl(frontmatterImage);
  }
};
<commit_msg>Replaces "select" with "visit" on gatsby-remark-fix-urls.js<commit_after>const path = require('path');
const visit = require('unist-util-visit');

const isInternal = url => !url.includes(':') && !url.startsWith('//');

module.exports = ({ markdownNode, markdownAST, getNode, files }) => {
  if (!markdownNode.fileAbsolutePath) {
    return;
  }

  const filteredFiles = files.filter(x => x && x.relativePath);

  const parentNode = getNode(markdownNode.parent);
  const parentNodeAbsoluteDir = parentNode.dir + '/';
  const parentNodeRelativeDir = path.posix.dirname(parentNode.relativePath) + '/';

  const fixUrl = url => {
    if (isInternal(url)) {
      const relativePath = path.posix.resolve('/', parentNodeRelativeDir, url);
      const rootlessRelativePath = relativePath.substr(1);

      const fileNode = filteredFiles.find(x => x.relativePath === rootlessRelativePath);

      if (fileNode) {
        const relativePath = path.posix.relative(parentNodeAbsoluteDir, fileNode.absolutePath);

        return relativePath;
      }
    }

    return url;
  };

  visit(markdownAST, 'image', node => {
    node.url = fixUrl(node.url);
  });

  visit(markdownAST, 'link', node => {
    node.url = fixUrl(node.url);
  });

  const frontmatterImage = markdownNode.frontmatter && markdownNode.frontmatter.image;

  if (frontmatterImage) {
    markdownNode.frontmatter.image = fixUrl(frontmatterImage);
  }
};
<|endoftext|>


<commit_before>console.clear();

/*
   Any suggestions about how the colour blast on click doesn't make the page scroll down if it overflows?
*/

setTimeout(function(){permitted = true;}, 500);

var clip = new Clipboard('.colours >*');
var clipr = new Clipboard('.individual .red');
var clipg = new Clipboard('.individual .green');
var clipb = new Clipboard('.individual .blue');
var permitted = false;
var selection = 0;
var r, g, b, a = 255;

clip.on('error', error());
clipr.on('error', error());
clipg.on('error', error());
clipb.on('error', error());

function error() {
   if(permitted) {
      console.error("Clip");
      $(".error").addClass("shown");
   }
}
$(".catchment, .close").click(function(){
   $(".error").removeClass("shown")
});

$(".dropdown .options div").click(function(){
   $(".dropdown .selection").text($(this).text());
   $(".dropdown .options div").removeClass("selected");
   $(this).addClass("selected");
   selection = $(this).index();
   if (selection == 14) {
      $(".individual").css("display", "flex");
   } else {
      $(".individual").css("display", "none");
   }
});

$(".sign").mousedown(function(e){
   var val = $(this).attr("color");
   $(this).parent().parent().append('

');
   remove("#" + ts);
});
$(".colours >*").mousedown(function(e){
   var val = $(this).attr("color"), val2 = "";
   $('body').css('background-color','#' + val);
   var ts = Math.floor(e.timeStamp);
   $(this).parent().parent().append('

');
   remove("#" + ts);
   if (selection >= 2) {
      r = $.baseConvert(val.substr(0,2), 16, 10);
      g = $.baseConvert(val.substr(2,2), 16, 10);
      b = $.baseConvert(val.substr(4,2), 16, 10);
      $(".individual .red").css("background-color", "rgb(" + r + ",0,0)");
      $(".individual .green").css("background-color", "rgb(0," + g + ",0)");
      $(".individual .blue").css("background-color", "rgb(0,0," + b + ")");
   }
   if(selection >= 2 && selection <=5) {
      /*C0 -> BB not CC*/
      var r2 = Math.round(r/17) + "";
      val2 += $.baseConvert(r2, 10, 16);
      /*I may have forgotten that jQuery already supports base 16-10 conversions absolutely fine*/
      if(selection >= 4) {
         val2 += $.baseConvert(r2, 10, 16);
      }
      var g2 = Math.round(g/17) + "";
      val2 += $.baseConvert(g2, 10, 16);
      if(selection >= 4) {
         val2 += $.baseConvert(g2, 10, 16);
      }
      var b2 = Math.round(b/17) + "";
      val2 += $.baseConvert(b2, 10, 16);
      if(selection >= 4) {
         val2 += $.baseConvert(b2, 10, 16);
      }
      val = val2;
   }
   if(selection >= 6 && selection <=7) {
      val += "FF";
   }
   switch(selection) {
      case 0:case 2:case 4:case 6:
         $(".colourvalue").val("#" + val);
         $(".errorcode").val("#" + val);
         break;
      case 1:case 3:case 5:case 7:
         $(".colourvalue").val(val);
         $(".errorcode").val(val);
         break;
      case 8:
         $(".colourvalue").val("(" + r + "," + g + "," + b + ")");
         $(".errorcode").val("(" + r + "," + g + "," + b + ")");
         break;
      case 10:
         $(".colourvalue").val("(" + r + "," + g + "," + b + ",1)");
         $(".errorcode").val("(" + r + "," + g + "," + b + ",1)");
         break;
      case 12:
         $(".colourvalue").val("(" + r + "," + g + "," + b + ",255)");
         $(".errorcode").val("(" + r + "," + g + "," + b + ",255)");
         break;
      case 9:
         $(".colourvalue").val("rgb(" + r + "," + g + "," + b + ")");
         $(".errorcode").val("rgb(" + r + "," + g + "," + b + ")");
         break;
      case 11:
         $(".colourvalue").val("rgba(" + r + "," + g + "," + b + ",1)");
         $(".errorcode").val("rgba(" + r + "," + g + "," + b + ",1)");
         break;
      case 13:
         $(".colourvalue").val("rgba(" + r + "," + g + "," + b + ",255)");
         $(".errorcode").val("rgba(" + r + "," + g + "," + b + ",255)");
         break;
      case 15:case 16:
          /*http://www.javascripter.net/faq/hex2cmyk.htm*/
          var C = 1 - (r/255);
          var M = 1 - (g/255);
          var Y = 1 - (b/255);
          var K = 0;
          var minCMY = Math.min(C,Math.min(M,Y));
          C = (C - minCMY) / (1 - minCMY) ;
          M = (M - minCMY) / (1 - minCMY) ;
          Y = (Y - minCMY) / (1 - minCMY) ;
          K = minCMY;
         if(selection == 15) {
            $(".colourvalue").val("cymk(" + C + "," + Y + "," + M + "," + K + ")");
            $(".errorcode").val("cymk(" + C + "," + Y + "," + M + "," + K + ")");
         } else {
            $(".colourvalue").val("cymk(" + C*100 + "," + Y*100 + "," + M*100 + "," + K*100 + ")");
            $(".errorcode").val("cymk(" + C*100 + "," + Y*100 + "," + M*100 + "," + K*100 + ")");
         }
         break;
   }
});

$(".individual .red").mousedown(function(){
   var ts = Math.floor(e.timeStamp);
   $(this).append('

');
   remove("#" + ts);
   $(".colourvalue").val(r);
});

$(".individual .green").mousedown(function(){
   var ts = Math.floor(e.timeStamp);
   $(this).append('

');
   remove("#" + ts);
   $(".colourvalue").val(g);
});

$(".individual .blue").mousedown(function(){
   var ts = Math.floor(e.timeStamp);
   $(this).append('

');
   remove("#" + ts);
   $(".colourvalue").val(b);
});

function remove(id) {
   setTimeout(function(){$(id).remove();},1200);
}

/*https://github.com/koya-io/baseConvert.js*/
$.baseConvert=function(n,i,t){var r="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(36>=i&&(n=n.toUpperCase()),i>64||2>t||t>64||2>i?r="Error, selector out of bounds.":n.replace(/[^0-9a-zA-Z+\/]/g,"").length!=n.length?r="Error, invalid character.":$.each((n+"").split(""),function(n,t){i>=63?63==i&&"/"==t&&(r="Error, invalid character."):o.indexOf(t)>=i&&(r="Error, invalid character.")}),""==r){var a=bigInt(0),g="";for(n+="",i+="",t+="",$.each(n.split(""),function(t,r){if(i>=63){var g=bigInt(n.length).minus(t).minus(1),l=bigInt(i).pow(g),d=bigInt(o.indexOf(r)).multiply(l);a=bigInt(a).add(d)}else{var g=bigInt(n.length).minus(t).minus(1),l=bigInt(i).pow(g),d=bigInt(o.indexOf(r)).multiply(l);a=bigInt(a).add(d)}});a>0;){g=t>=63?e[bigInt(a).mod(t)]+""+g:o[bigInt(a).mod(t)]+""+g;var l=bigInt(a).mod(t);bigInt(a).minus(l),a=bigInt(a).divide(t)}return g}return r};<commit_msg>updated rgb individual event listeners to pass event<commit_after>console.clear();

/*
   Any suggestions about how the colour blast on click doesn't make the page scroll down if it overflows?
*/

setTimeout(function(){permitted = true;}, 500);

var clip = new Clipboard('.colours >*');
var clipr = new Clipboard('.individual .red');
var clipg = new Clipboard('.individual .green');
var clipb = new Clipboard('.individual .blue');
var permitted = false;
var selection = 0;
var r, g, b, a = 255;

clip.on('error', error());
clipr.on('error', error());
clipg.on('error', error());
clipb.on('error', error());

function error() {
   if(permitted) {
      console.error("Clip");
      $(".error").addClass("shown");
   }
}
$(".catchment, .close").click(function(){
   $(".error").removeClass("shown")
});

$(".dropdown .options div").click(function(){
   $(".dropdown .selection").text($(this).text());
   $(".dropdown .options div").removeClass("selected");
   $(this).addClass("selected");
   selection = $(this).index();
   if (selection == 14) {
      $(".individual").css("display", "flex");
   } else {
      $(".individual").css("display", "none");
   }
});

$(".sign").mousedown(function(e){
   var val = $(this).attr("color");
   $(this).parent().parent().append('

');
   remove("#" + ts);
});
$(".colours >*").mousedown(function(e){
   var val = $(this).attr("color"), val2 = "";
   $('body').css('background-color','#' + val);
   var ts = Math.floor(e.timeStamp);
   $(this).parent().parent().append('

');
   remove("#" + ts);
   if (selection >= 2) {
      r = $.baseConvert(val.substr(0,2), 16, 10);
      g = $.baseConvert(val.substr(2,2), 16, 10);
      b = $.baseConvert(val.substr(4,2), 16, 10);
      $(".individual .red").css("background-color", "rgb(" + r + ",0,0)");
      $(".individual .green").css("background-color", "rgb(0," + g + ",0)");
      $(".individual .blue").css("background-color", "rgb(0,0," + b + ")");
   }
   if(selection >= 2 && selection <=5) {
      /*C0 -> BB not CC*/
      var r2 = Math.round(r/17) + "";
      val2 += $.baseConvert(r2, 10, 16);
      /*I may have forgotten that jQuery already supports base 16-10 conversions absolutely fine*/
      if(selection >= 4) {
         val2 += $.baseConvert(r2, 10, 16);
      }
      var g2 = Math.round(g/17) + "";
      val2 += $.baseConvert(g2, 10, 16);
      if(selection >= 4) {
         val2 += $.baseConvert(g2, 10, 16);
      }
      var b2 = Math.round(b/17) + "";
      val2 += $.baseConvert(b2, 10, 16);
      if(selection >= 4) {
         val2 += $.baseConvert(b2, 10, 16);
      }
      val = val2;
   }
   if(selection >= 6 && selection <=7) {
      val += "FF";
   }
   switch(selection) {
      case 0:case 2:case 4:case 6:
         $(".colourvalue").val("#" + val);
         $(".errorcode").val("#" + val);
         break;
      case 1:case 3:case 5:case 7:
         $(".colourvalue").val(val);
         $(".errorcode").val(val);
         break;
      case 8:
         $(".colourvalue").val("(" + r + "," + g + "," + b + ")");
         $(".errorcode").val("(" + r + "," + g + "," + b + ")");
         break;
      case 10:
         $(".colourvalue").val("(" + r + "," + g + "," + b + ",1)");
         $(".errorcode").val("(" + r + "," + g + "," + b + ",1)");
         break;
      case 12:
         $(".colourvalue").val("(" + r + "," + g + "," + b + ",255)");
         $(".errorcode").val("(" + r + "," + g + "," + b + ",255)");
         break;
      case 9:
         $(".colourvalue").val("rgb(" + r + "," + g + "," + b + ")");
         $(".errorcode").val("rgb(" + r + "," + g + "," + b + ")");
         break;
      case 11:
         $(".colourvalue").val("rgba(" + r + "," + g + "," + b + ",1)");
         $(".errorcode").val("rgba(" + r + "," + g + "," + b + ",1)");
         break;
      case 13:
         $(".colourvalue").val("rgba(" + r + "," + g + "," + b + ",255)");
         $(".errorcode").val("rgba(" + r + "," + g + "," + b + ",255)");
         break;
      case 15:case 16:
          /*http://www.javascripter.net/faq/hex2cmyk.htm*/
          var C = 1 - (r/255);
          var M = 1 - (g/255);
          var Y = 1 - (b/255);
          var K = 0;
          var minCMY = Math.min(C,Math.min(M,Y));
          C = (C - minCMY) / (1 - minCMY) ;
          M = (M - minCMY) / (1 - minCMY) ;
          Y = (Y - minCMY) / (1 - minCMY) ;
          K = minCMY;
         if(selection == 15) {
            $(".colourvalue").val("cymk(" + C + "," + Y + "," + M + "," + K + ")");
            $(".errorcode").val("cymk(" + C + "," + Y + "," + M + "," + K + ")");
         } else {
            $(".colourvalue").val("cymk(" + C*100 + "," + Y*100 + "," + M*100 + "," + K*100 + ")");
            $(".errorcode").val("cymk(" + C*100 + "," + Y*100 + "," + M*100 + "," + K*100 + ")");
         }
         break;
   }
});

$(".individual .red").mousedown(function(e){
   var ts = Math.floor(e.timeStamp);
   $(this).append('

');
   remove("#" + ts);
   $(".colourvalue").val(r);
});

$(".individual .green").mousedown(function(e){
   var ts = Math.floor(e.timeStamp);
   $(this).append('

');
   remove("#" + ts);
   $(".colourvalue").val(g);
});

$(".individual .blue").mousedown(function(e){
   var ts = Math.floor(e.timeStamp);
   $(this).append('

');
   remove("#" + ts);
   $(".colourvalue").val(b);
});

function remove(id) {
   setTimeout(function(){$(id).remove();},1200);
}

/*https://github.com/koya-io/baseConvert.js*/
$.baseConvert=function(n,i,t){var r="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(36>=i&&(n=n.toUpperCase()),i>64||2>t||t>64||2>i?r="Error, selector out of bounds.":n.replace(/[^0-9a-zA-Z+\/]/g,"").length!=n.length?r="Error, invalid character.":$.each((n+"").split(""),function(n,t){i>=63?63==i&&"/"==t&&(r="Error, invalid character."):o.indexOf(t)>=i&&(r="Error, invalid character.")}),""==r){var a=bigInt(0),g="";for(n+="",i+="",t+="",$.each(n.split(""),function(t,r){if(i>=63){var g=bigInt(n.length).minus(t).minus(1),l=bigInt(i).pow(g),d=bigInt(o.indexOf(r)).multiply(l);a=bigInt(a).add(d)}else{var g=bigInt(n.length).minus(t).minus(1),l=bigInt(i).pow(g),d=bigInt(o.indexOf(r)).multiply(l);a=bigInt(a).add(d)}});a>0;){g=t>=63?e[bigInt(a).mod(t)]+""+g:o[bigInt(a).mod(t)]+""+g;var l=bigInt(a).mod(t);bigInt(a).minus(l),a=bigInt(a).divide(t)}return g}return r};<|endoftext|>


<commit_before>import { Bullet, Gun, Painter, Summary, Target } from './core';
import { Alfred } from './ai';

const default_speed = 0.8; //pixels per millisecond
const dom_node_id = "#canvas";
const interval = 15;

let store = {
    gun: null,
    target: null,
    painter: null,
    alfred: null,
    summary: null,
};

function initializeListeners() {
    $(dom_node_id).on("mousemove", e => {
        if(!store.summary.autoplay) store.gun.adjustOrientation(e.clientX, e.clientY);
    });

    $(dom_node_id).on("click", e => {
        if(!store.summary.active) initializeActors();
        else if(e.clientX < 300 && e.clientY < 300) store.summary.toggleAutoplay();
        else if(!store.summary.autoplay) store.gun.shoot();
    });

}

function initializeActors() {
    let gun_height = Math.round(window.innerHeight/2),
        gun = new Gun(0, 30, gun_height, "gun_1", default_speed);

    store.gun = gun;

    store.target = new Target(window.innerWidth - 60, 30, 20, 60, 90, default_speed);

    store.painter = new Painter(dom_node_id);

    store.alfred = new Alfred();

    store.summary = new Summary();
}

$(document).ready(() => {

    initializeActors();

    initializeListeners();

    window.setInterval(() => {

        store.painter.draw(store.gun, store.target, store.summary);

        store.summary.update(store.gun, store.target);

        let target_move = store.alfred.decideTargetMove(store.gun, store.target);

        store.target.setActiveMove(target_move);

    }, interval);

    window.setInterval(() => {

        if(store.summary.autoplay) {
            const move = store.alfred.decideGunMove(store.gun, store.target);
            store.gun.adjustOrientation(move.gun_x_pos, move.gun_y_pos);
            if(move.is_shoot) store.gun.shoot();
        }

    }, interval * 40);
});

<commit_msg>Resolved #6: set a 2 second timeout once the game is over and the user clicks on the screen<commit_after>import { Bullet, Gun, Painter, Summary, Target } from './core';
import { Alfred } from './ai';

const default_speed = 0.8; //pixels per millisecond
const dom_node_id = "#canvas";
const interval = 15;

let store = {
    gun: null,
    target: null,
    painter: null,
    alfred: null,
    summary: null,
};

function initializeListeners() {
    $(dom_node_id).on("mousemove", e => {
        if(!store.summary.autoplay) store.gun.adjustOrientation(e.clientX, e.clientY);
    });

    $(dom_node_id).on("click", e => {
        if(!store.summary.active) window.setTimeout(() => initializeActors(), 2000);
        else if(e.clientX < 300 && e.clientY < 300) store.summary.toggleAutoplay();
        else if(!store.summary.autoplay) store.gun.shoot();
    });

}

function initializeActors() {
    let gun_height = Math.round(window.innerHeight/2),
        gun = new Gun(0, 30, gun_height, "gun_1", default_speed);

    store.gun = gun;

    store.target = new Target(window.innerWidth - 60, 30, 20, 60, 90, default_speed);

    store.painter = new Painter(dom_node_id);

    store.alfred = new Alfred();

    store.summary = new Summary();
}

$(document).ready(() => {

    initializeActors();

    initializeListeners();

    window.setInterval(() => {

        store.painter.draw(store.gun, store.target, store.summary);

        store.summary.update(store.gun, store.target);

        let target_move = store.alfred.decideTargetMove(store.gun, store.target);

        store.target.setActiveMove(target_move);

    }, interval);

    window.setInterval(() => {

        if(store.summary.autoplay) {
            const move = store.alfred.decideGunMove(store.gun, store.target);
            store.gun.adjustOrientation(move.gun_x_pos, move.gun_y_pos);
            if(move.is_shoot) store.gun.shoot();
        }

    }, interval * 40);
});

<|endoftext|>


<commit_before>
var SITE_ROOT = "";

var Promise = require("bluebird");
Promise.longStackTraces();
var $ = require("jquery");
var Backbone = require("backbone");
Backbone.$ = $;

var request = require("./request");
var Panes = require("./Panes");
var Editor = require("./Editor");
var Preview = require("./Preview");
var Toolbar = require("./Toolbar");
var Dropdown = require("./Dropdown");
var SelectMenu = require("./SelectMenu");
var TitleForm = require("./TitleForm");
var Content = require("./Content");

function fetchPages() {
    return request.get(SITE_ROOT + "/pages.json");
}

function picoUrl(format) {
    return window.location.pathname + "?show=" + format;
}

var toolbar = new Toolbar();
toolbar.render();
$("body").append(toolbar.el);

var content = new Content();
var panes = new Panes();

var editor = new Editor({
    model: content
});

var preview = new Preview({
    previewUrl: picoUrl("preview")
});

panes.setView(".left-pane", editor);
panes.setView(".right-pane", preview);
panes.render();

content.initialized.then(function() {
    panes.setPos(500);
    content.savePreview(editor.getContent());
});

$("body").append(panes.el);

content.on("savePreview savePublic", function(p) {
    p.then(function() {
        return preview.refresh();
    });
});

content.fetch();

toolbar.on("preview", function() {
    content.savePreview(editor.getContent());
});

toolbar.on("publish", function() {
    content.savePublic(editor.getContent());
});

toolbar.on("new", function(e) {
    var d = new Dropdown({
        target: e.target
    });

    var tf = new TitleForm();
    d.setContent(tf);
    d.render();

    tf.getTitle().then(function(t) {
        window.localStorage.presetTitle = t.title;
        window.location = SITE_ROOT + t.slug + "?show=editor";
    });

});

editor.listenTo(toolbar, "all", function(eventName) {
    editor.trigger(eventName);
});

toolbar.on("open", function(e) {
    var d = new Dropdown({
        target: e.target
    });

    var s = new SelectMenu({
        title: "Pages",
    });

    d.setContent(s);

    d.render();

    s.selectFrom(fetchPages()).then(function(page) {
        console.log("TO", page);
        window.location = SITE_ROOT + page.url + "?show=editor";
    }).catch(Promise.CancellationError, function() {
        console.log("cancel");
    });

});

// function save(type) {
//     return $.post(window.location.pathname, {
//         type: type,
//         value: editor.getValue()
//     }).then(function(res) {
//         console.log(res);
//         previewPage();
//     }, function(err) {
//         console.error("Saving failed:", arguments);
//         renderNotification("Failed to save!");
//     });
// }

// $(".bold-action").on("click", function(e) {
//     var c = editor.getCursor();
//     console.log(c);
//
//     if (editor.somethingSelected()) {
//         var text = editor.getSelection();
//         editor.replaceSelection("***" + text + "***");
//     }
//     else {
//         editor.replaceRange("**Bold Text**", c, c);
//         editor.setSelection({
//             line: c.line,
//             ch: c.ch + 2
//         }, {
//             line: c.line,
//             ch: c.ch + 11
//         });
//     }
//
//     editor.focus();
// });
//
//
// $(".preview-action").on("click", function(e) {
//     e.preventDefault();
//     save("preview");
// });
//
// $(".publish-action").on("click", function(e) {
//     e.preventDefault();
//     save("publish");
// });
//
// editor.on("change", _.debounce(function() {
//     save("preview");
// }, 2000));
//
// $(window).on("blur", _.debounce(function() {
//     save("preview");
// }, 500));
//
// $.get(picoUrl("json")).then(function(res) {
//     editor.setValue(res.preview  || res.public);
//     save("preview");
// }, function(err) {
//     console.error("Failed to load current page", err.responseText, err);
//     renderNotification("Failed to load page");
// });

<commit_msg>remove old code<commit_after>
var SITE_ROOT = "";

var Promise = require("bluebird");
Promise.longStackTraces();
var $ = require("jquery");
var Backbone = require("backbone");
Backbone.$ = $;

var request = require("./request");
var Panes = require("./Panes");
var Editor = require("./Editor");
var Preview = require("./Preview");
var Toolbar = require("./Toolbar");
var Dropdown = require("./Dropdown");
var SelectMenu = require("./SelectMenu");
var TitleForm = require("./TitleForm");
var Content = require("./Content");

function fetchPages() {
    return request.get(SITE_ROOT + "/pages.json");
}

function picoUrl(format) {
    return window.location.pathname + "?show=" + format;
}

var toolbar = new Toolbar();
toolbar.render();
$("body").append(toolbar.el);

var content = new Content();
var panes = new Panes();

var editor = new Editor({
    model: content
});

var preview = new Preview({
    previewUrl: picoUrl("preview")
});

panes.setView(".left-pane", editor);
panes.setView(".right-pane", preview);
panes.render();

content.initialized.then(function() {
    panes.setPos(500);
    content.savePreview(editor.getContent());
});

$("body").append(panes.el);

content.on("savePreview savePublic", function(p) {
    p.then(function() {
        return preview.refresh();
    });
});

content.fetch();

toolbar.on("preview", function() {
    content.savePreview(editor.getContent());
});

toolbar.on("publish", function() {
    content.savePublic(editor.getContent());
});

toolbar.on("new", function(e) {
    var d = new Dropdown({
        target: e.target
    });

    var tf = new TitleForm();
    d.setContent(tf);
    d.render();

    tf.getTitle().then(function(t) {
        window.localStorage.presetTitle = t.title;
        window.location = SITE_ROOT + t.slug + "?show=editor";
    });

});

editor.listenTo(toolbar, "all", function(eventName) {
    editor.trigger(eventName);
});

toolbar.on("open", function(e) {
    var d = new Dropdown({
        target: e.target
    });

    var s = new SelectMenu({
        title: "Pages",
    });

    d.setContent(s);

    d.render();

    s.selectFrom(fetchPages()).then(function(page) {
        console.log("TO", page);
        window.location = SITE_ROOT + page.url + "?show=editor";
    }).catch(Promise.CancellationError, function() {
        console.log("cancel");
    });

});

<|endoftext|>


<commit_before>(function ( $ ) {
  $.fn.responsify = function() {
    return this.each(function() {
      var owdith, oheight,
          twidth, theight,
          fx1, fy1, fx2, fy2,
          width, height, top, left;

      owidth = $('img', this).width();
      oheight = $('img', this).height();
      twidth = $(this).width();
      theight = $(this).height();
      fx1 = Number($('img', this).attr('data-focus-left'));
      fy1 = Number($('img', this).attr('data-focus-top'));
      fx2 = Number($('img', this).attr('data-focus-right'));
      fy2 = Number($('img', this).attr('data-focus-bottom'));
      if( owidth/oheight > twidth/theight ) {
        var fwidth = (fx2-fx1) * owidth;
        if ( fwidth/oheight > twidth/theight ) {
          height = oheight*twidth/fwidth;
          width = owidth*twidth/fwidth;
          left = -fx1*width;
          top = (theight-height)/2;
        } else {
          height = theight;
          width = theight*owidth/oheight;
          left = twidth/2 - (fx1 + fx2)*width/2;
          // if left > 0, it will leave blank on the left, so set it to 0;
          left = left>0?0:left;
          top = 0;
        }
      }
      else {
        var fheight = (fy2-fy1) * oheight;
        if ( fheight/owidth > theight/twidth ) {
          width = owidth*theight/fheight;
          height = oheight*theight/fheight;
          top = -fy1*height;
          // console.log(top);
          left = (twidth-width)/2;
        } else {
          width = twidth;
          height = twidth*oheight/owidth;
          top = theight/2 - (fy1 + fy2)*height/2;
          // if top > 0, it will leave blank on the top, so set it to 0;
          top = top>0?0:top;
          left = 0;
        }
      }
      $(this).css({
        "overflow": "hidden"
      })
      $('img', this).css({
        "position": "relative",
        "height": height,
        "width": width,
        "left": left,
        "top": top
      })
  });
  };
}( jQuery ));

$('.wrapper').responsify();
$(window).resize(function(){
  $('.wrapper').responsify();
})<commit_msg>fix bottom and right blank<commit_after>(function ( $ ) {
  $.fn.responsify = function() {
    return this.each(function() {
      var owdith, oheight,
          twidth, theight,
          fx1, fy1, fx2, fy2,
          width, height, top, left;

      owidth = $('img', this).width();
      oheight = $('img', this).height();
      twidth = $(this).width();
      theight = $(this).height();
      fx1 = Number($('img', this).attr('data-focus-left'));
      fy1 = Number($('img', this).attr('data-focus-top'));
      fx2 = Number($('img', this).attr('data-focus-right'));
      fy2 = Number($('img', this).attr('data-focus-bottom'));
      if( owidth/oheight > twidth/theight ) {
        var fwidth = (fx2-fx1) * owidth;
        if ( fwidth/oheight > twidth/theight ) {
          height = oheight*twidth/fwidth;
          width = owidth*twidth/fwidth;
          left = -fx1*width;
          top = (theight-height)/2;
        } else {
          height = theight;
          width = theight*owidth/oheight;
          left = twidth/2 - (fx1 + fx2)*width/2;
          // if left > 0, it will leave blank on the left, so set it to 0;
          left = left>0?0:left;
          // if width - left < twidth, it will leave blank on the right, so set left = width - twidth
          left = (twidth - left - width)>0?(twidth-width):left
          top = 0;
        }
      }
      else {
        var fheight = (fy2-fy1) * oheight;
        if ( fheight/owidth > theight/twidth ) {
          width = owidth*theight/fheight;
          height = oheight*theight/fheight;
          top = -fy1*height;
          // console.log(top);
          left = (twidth-width)/2;
        } else {
          width = twidth;
          height = twidth*oheight/owidth;
          top = theight/2 - (fy1 + fy2)*height/2;
          // if top > 0, it will leave blank on the top, so set it to 0;
          top = top>0?0:top;
          // if height - top < theight, it will leave blank on the bottom, so set top = height - theight
          top = (theight - top - height)>0?(theight-height):top
          left = 0;
        }
      }
      $(this).css({
        "overflow": "hidden"
      })
      $('img', this).css({
        "position": "relative",
        "height": height,
        "width": width,
        "left": left,
        "top": top
      })
  });
  };
}( jQuery ));

$('.wrapper').responsify();
$(window).resize(function(){
  $('.wrapper').responsify();
})
<|endoftext|>


<commit_before>
var bitcore = require('bitcore-lib');

var rerun = function() {
	// Initialize.
	$('#result-text').val('');
	$('#result-text-error').hide();
	$('#result-hex').val('');
	$('#result-error').hide();
	$('#result-steps tbody *').remove();
	// Read input.
	var input = $('#input').val().trim();
	var chunks = input.split(/\s+/);
	try {
		var script = bitcore.Script.fromString(chunks.join(' '));
	} catch(e) {
		$('#result-text-error').show();
		return;
	}
	$('#result-text').val(script.toString());
	$('#result-hex').val('0x'+script.toHex());
	$('#result-url').val(location.href.split(/[?#]/)[0]+'?input='+encodeURIComponent(script.toString()));
	var interpreter = new bitcore.Script.Interpreter();
	interpreter.set({script: script});
	var err = '';
	var result = true;
	for(; interpreter.pc<interpreter.script.chunks.length;) {
		result = interpreter.step();
		var stack = interpreter.stack.map(function(item) {return item.toString('hex');}).reverse().join('
');
		var executed = (new bitcore.Script()).set({chunks: interpreter.script.chunks.slice(interpreter.pc-1, interpreter.pc)}).toString();
		var remaining = (new bitcore.Script()).set({chunks: interpreter.script.chunks.slice(interpreter.pc)}).toString();
		$('#result-steps tbody').append('
' + [interpreter.pc, stack, executed, remaining].join('	') + '
');
		if(!result) break;
	}
	if(!result) {
		err += 'Script ended with error.';
	} else {
		if(interpreter.stack.length == 0) {
			result = false;
			err += 'The resulting stack is empty.';
		} else {
			var ret = interpreter.stack.pop();
			if(!bitcore.Script.Interpreter.castToBool(ret)) {
				result = false;
				err += 'The resulting top stack item is FALSE.';
			}
		}
	}
	if(!result) {
		$('#result-error').text(err);
		$('#result-error').show();
	}
	$('#result').removeClass('label-success');
	$('#result').removeClass('label-danger');
	$('#result').addClass(result ? 'label-success' : 'label-danger');
	$('#result').text('Result: ' + (result ? 'OK' : 'NG'));
}

var parseQuery = function() {
	var query = {};
	var tmp = location.search.substring(1).split('&');
	for(var data in tmp) {
		var t = tmp[data].split('=', 2);
		query[t[0]] = decodeURIComponent(t[1]);
	}
	return query;
}

$(document).ready(function() {
	var query = parseQuery();
	if(query.input) {
		$('#input').val(query.input);
	}
	rerun();
});

<commit_msg>chagnge bg color and select automatically for readonly textareas.<commit_after>
var bitcore = require('bitcore-lib');

var rerun = function() {
	// Initialize.
	$('#result-text').val('');
	$('#result-text-error').hide();
	$('#result-hex').val('');
	$('#result-error').hide();
	$('#result-steps tbody *').remove();
	// Read input.
	var input = $('#input').val().trim();
	var chunks = input.split(/\s+/);
	try {
		var script = bitcore.Script.fromString(chunks.join(' '));
	} catch(e) {
		$('#result-text-error').show();
		return;
	}
	$('#result-text').val(script.toString());
	$('#result-hex').val('0x'+script.toHex());
	$('#result-url').val(location.href.split(/[?#]/)[0]+'?input='+encodeURIComponent(script.toString()));
	var interpreter = new bitcore.Script.Interpreter();
	interpreter.set({script: script});
	var err = '';
	var result = true;
	for(; interpreter.pc<interpreter.script.chunks.length;) {
		result = interpreter.step();
		var stack = interpreter.stack.map(function(item) {return item.toString('hex');}).reverse().join('
');
		var executed = (new bitcore.Script()).set({chunks: interpreter.script.chunks.slice(interpreter.pc-1, interpreter.pc)}).toString();
		var remaining = (new bitcore.Script()).set({chunks: interpreter.script.chunks.slice(interpreter.pc)}).toString();
		$('#result-steps tbody').append('
' + [interpreter.pc, stack, executed, remaining].join('	') + '
');
		if(!result) break;
	}
	if(!result) {
		err += 'Script ended with error.';
	} else {
		if(interpreter.stack.length == 0) {
			result = false;
			err += 'The resulting stack is empty.';
		} else {
			var ret = interpreter.stack.pop();
			if(!bitcore.Script.Interpreter.castToBool(ret)) {
				result = false;
				err += 'The resulting top stack item is FALSE.';
			}
		}
	}
	if(!result) {
		$('#result-error').text(err);
		$('#result-error').show();
	}
	$('#result').removeClass('label-success');
	$('#result').removeClass('label-danger');
	$('#result').addClass(result ? 'label-success' : 'label-danger');
	$('#result').text('Result: ' + (result ? 'OK' : 'NG'));
}

var parseQuery = function() {
	var query = {};
	var tmp = location.search.substring(1).split('&');
	for(var data in tmp) {
		var t = tmp[data].split('=', 2);
		query[t[0]] = decodeURIComponent(t[1]);
	}
	return query;
}

$(document).ready(function() {
	$('[readonly]').css('background-color', '#ddd');
	$('[readonly]').on('click', function() {this.select()});
	var query = parseQuery();
	if(query.input) {
		$('#input').val(query.input);
	}
	rerun();
});

<|endoftext|>


<commit_before>$(document).ready(function() {
  $('.toggleMore').on('click', function() {
    $(this).closest('.slot').toggleClass('active');
    $(this).next('.slot-more').slideToggle('fast');
  });

  $('#header .header-inner').css({'min-height': $(window).height()});
});

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(2016, 8, 3, 17);
initializeClock('countdown', deadline);
<commit_msg>Fix hour<commit_after>$(document).ready(function() {
  $('.toggleMore').on('click', function() {
    $(this).closest('.slot').toggleClass('active');
    $(this).next('.slot-more').slideToggle('fast');
  });

  $('#header .header-inner').css({'min-height': $(window).height()});
});

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(2016, 8, 3, 16);
initializeClock('countdown', deadline);
<|endoftext|>