<commit_before>(function (window, leggo, $, undefined) {

  var longitude = null;
  var latitude = null;
  var locationRefreshHandle = null;
  var timeRefreshHandle = null;
  var timeSetHandle = null;
  var activityRefreshHandle = null;

  var currId;
  var activitySelected=false;
  var activityData = {};

  var isMouseDown = false;

  var currTime;
  var endTime;

  var hoursArray = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

  var anyTime = true;
  var millisecsAvailable = 0;

  leggo.initializePage = function () {
    // $('#help-button').popover();
    // pure JS
    var elem = document.getElementById('slider');
    window.mySwipe = Swipe(elem, {
      startSlide: 0,
      speed: 300,
      auto: 0,
      continuous: false,
      disableScroll: false,
      stopPropagation: false,
      callback: function(index, elem) {
        if (index==5 && activitySelected!=true){
        mySwipe.prev();
      }
      },
      transitionEnd: function(index, elem) {}
    });

    // with jQuery
    // window.mySwipe = $('ß#mySwipe').Swipe().data('Swipe');

    $('#help-button').popover(); // does this work?
    getLocation();
    locationRefreshHandle = setInterval(getLocation, 30000);

    //set up slightly less fancy time filter
    var myScrollMinutes = new IScroll('#minutes-wrapper', { probeType: 3, mouseWheel: false, bounce: false, startY: 0 });
    myScrollMinutes.scrolling = false;
    myScrollMinutes.selectedIndex = 1;
    myScrollMinutes.on('scrollStart', startTimeScroll);
    myScrollMinutes.on('scroll', updateSelectedTime);
    myScrollMinutes.on('scrollEnd', endTimeScroll);

    //make each scroll element clickable
    var lastSelectedIdx = myScrollMinutes.selectedIndex;
    $('#minutes-scroller ul').children().on('click', function (e) {
      e.preventDefault();
      myScrollMinutes.scrollToElement($(this)[0], null, null, true);
    }).mousedown(mouseDownScroll).click(mouseUpScroll);
      // .bind('touchdown', mouseDownScroll)
      // .mousedown(mouseDownScroll)
      // .bind('touchup', mouseUpScroll)
      // .click(mouseUpScroll);

    function mouseDownScroll (e) {
      e.preventDefault();
      lastSelectedIdx = myScrollMinutes.selectedIndex;
    }

    function mouseUpScroll (e) {
      e.preventDefault();
      if (lastSelectedIdx === myScrollMinutes.selectedIndex) {
        myScrollMinutes.scrollToElement($(this)[0], null, null, true);
      }
    }

    function setDisplayedTime(date) {

    }

    function updateSelectedTime () {
      this.scrolling = true;
      var yDiff = this.y - 10;
      var idx = Math.floor(-1*yDiff/40) + 1;
      if (this.selectedIndex === undefined || this.selectedIndex !== idx) {
        this.selectedIndex = idx;
        var options = $($(this.scroller).children('ul')[0]).children();
        $(options).removeClass('selected-time');
        $(options[idx]).addClass('selected-time');
      }
    }

    function startTimeScroll () {
      this.scrolling = true;
      // $(document).bind('touchmove', function (e) { e.preventDefault(); });
      console.log('start');
    }

    function endTimeScroll () {
      updateSelectedTime();
      //15 minutes = 900000 millisecs. Yes this shouldn't be hardcoded
      //Yes I could have fixed that in the time it took to write this comment
      var millisecsAvailable = myScrollMinutes.selectedIndex * 900000;
      if (myScrollMinutes.selectedIndex === 1) {
        millisecsAvailable = 0;
      }
      this.scrolling = false;
      // $(document).unbind('touchmove');
      console.log('end');
    }

    function checkAndSetTime () {

    }

    //enable filter buttons
    $('.image-checkbox').each(function (i, n) {
      $(this).click( function (e) {
        console.log('hi!');
        e.preventDefault();
        var button = $(this);
        if (button.hasClass('image-checkbox-checked')) {
          button.removeClass('image-checkbox-checked');
          button.addClass('image-checkbox');
          deselectButton(button);
        } else {
          button.removeClass('image-checkbox');
          console.log(button.siblings('.image-checkbox-checked'));
          button.siblings('.image-checkbox-checked').removeClass('image-checkbox-checked').addClass('image-checkbox')
            .each( function () {
              deselectButton(this);
            });
          button.addClass('image-checkbox-checked');
          selectButton(button);
        }
        leggo.findActivities();
        setTimeout(function () { leggo.changeFilter(true); }, 500);
      });
    });

    //deselects all the filter options on the current filter
    $('.surprise-button').each(function (i, n) {
      $(this).click( function (e) {
        e.preventDefault();
        var buttons = $(this).parent().parent().find('.icons').children().removeClass('image-checkbox-checked').addClass('image-checkbox')
          .each( function () {
            deselectButton(this);
          });
        setTimeout(function () { leggo.changeFilter(true); }, 500);
      });
    });
    $('#time-surprise').unbind('click').click( function (e) {
      e.preventDefault();
      myScrollMinutes.scrollToElement($('#minutes-scroller ul').children()[1], null, null, true);
      setTimeout(function () { leggo.changeFilter(true); }, 500);
    });

    //enable refresh button. gets new activities
    $('#refresh-button').click( function (e) {
      e.preventDefault();
      leggo.findActivities();
    });

    var derp = setTimeout(leggo.findActivities, 2000);
    activityRefreshHandle = setInterval(leggo.findActivities, 300000);

  }

  //These next two functions switch the img src of a button with the appropriate selected/unselected image
  function deselectButton (button) {
    var newURL = $(button).attr('src');
    if (newURL !== undefined) {
      newURL = newURL.split('_')[0];
      newURL = newURL + '_unsel.png';
      $(button).attr('src', newURL);
    }
  }
  function selectButton (button) {
    var newURL = $(button).attr('src');
    if (newURL !== undefined) {
      newURL = newURL.split('_')[0];
      newURL = newURL + '_selected.png';
      $(button).attr('src', newURL);
    }
  }

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(storePosition);
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  }

  function toClockString (date) {
    var isPM = date.getHours() >= 12;
    //return ((isPM) ? date.getHours() - 12 : date.getHours()) + ':' + (((date.getMinutes() < 10) ? '0' : '') + currTime.getMinutes()) + ((isPM) ? 'PM' : 'AM');
    return ((date.getHours() >= 12) ? hoursArray[date.getHours() - 12] : hoursArray[date.getHours()]) + ':' + ( (date.getMinutes()<10?'0':'') + date.getMinutes() ) + ' ' + ((isPM) ? 'PM' : 'AM');
  }

  function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
  }

  //adds "amount" minutes to the end time filter
  leggo.changeEndTime = function changeEndTime(amount) {
    endTime = addMinutes(endTime, amount);
    if ( endTime.getTime() < currTime.getTime() ) {
      currTimeStr = toClockString(currTime);//((currTime.getHours() > 12) ? currTime.getHours() - 12 : currTime.getHours()) + ':' + ( (currTime.getMinutes()<10?'0':'') + currTime.getMinutes() );
      $('#time-display').text(currTimeStr);
      $('#time-display').attr('filterValue', currTime.toDateString() + ' ' + currTime.toTimeString());
    } else {
      endTimeStr = toClockString(endTime);
      $('#time-display').text(endTimeStr);
      $('#time-display').attr('filterValue', endTime.toDateString() + ' ' + endTime.toTimeString());
    }
  }

  leggo.setActivityID = function setActivityID(id){
    currId= id;
    console.log("Curr id is now" + id);
  }

  leggo.activityClicked= function activityClicked(isNext,id){
    activitySelected=true;
    leggo.setActivityID(id);
    $.get('../data.json', getProject);
    leggo.changeFilter(true);
  }
  var result;

  function getProject(result)
  {
    activities= result;
    // console.log(result);
    // console.log(currId);
    // console.log(result['activities'][currId-1]);
    $("#img-detail").attr('src', result['activities'][currId-1]['imageURL']);
    $("#descrip-detail").text(result['activities'][currId-1]['description']);
    $("#needs-detail").text(result['activities'][currId-1]['thingslist']);
    $("#cost-detail").text("$" + result['activities'][currId-1]['moneyupperlimit']);
  }

  leggo.testingfunction = function testingfunction(){
    // console.log(currId);
    window.location.replace("/finalactivity/"+currId);
  }

function callbackFunc(){

  console.log("performed");
}

  function storePosition(position) {
    longitude = position.coords.longitude;
    latitude = position.coords.latitude;
    console.log('position stored: ');
    // leggo.findActivities();
  }

  //swipes the current filter forward if isNext is true, backward if not
  leggo.changeFilter = function changeFilter (isNext) {
    var currPos = mySwipe.getPos();
    // console.log(currPos);

    var children = $('.nav-dots').children()[0].children;
    $(children[currPos]).removeClass('selected');

    if (isNext) {
        mySwipe.next();
    } else {
        mySwipe.prev();
    }

    currPos = mySwipe.getPos();
    $(children[currPos]).addClass('selected');
  }

  //aggregates the currently set filters and returns a list of activities that pass said filters
  leggo.findActivities = function (noFilter) {
    currTime = new Date();
    var startStr = currTime.getTime();
    var endStr = currTime.getTime() + millisecsAvailable;

    // console.log('start: ' + startStr);
    // console.log('end : ' + endStr);
    var filterData = {
      'nofilter': ((noFilter === undefined) ? false : true),
      'coords': [ latitude, longitude ],
/*
      'starttime':currTime.toDateString() + ' ' + currTime.toTimeString()
*/
      'starttime': startStr,
      'endtime' : endStr
    };

    //note that I am pushing filter values to arrays. I'll leave it for now in case we return to non-exclusive buttons
    $('.image-checkbox-checked').each(function (i, n) {
      filterData[$(this).attr('filter')] = filterData[$(this).attr('filter')] || [];
      filterData[$(this).attr('filter')].push($(this).attr('filtervalue'));
      // console.log('filter: ' + $(this).attr('filter') + ' value: ' + $(this).attr('filtervalue'));
    });
    $.post('/findactivities', filterData, function (data) {
      activityData = data['activities'];
      populateActivities(activityData);

      console.log(data);
    });
  }

  //adds activities to the activities page
  function populateActivities (activities) {
    if (activities.length == 0) {
      $('#activities-intro').text('We couldn\'t find anything matching your filters, so here\'s a random selection...');
      leggo.findActivities(true);
      return;
    }

    var count = 0;
    $('#activities').children().each( function () {
      var newActivity = activities[count] || false;

      var activityAnchor = $(this).find('a');
      var activityImage = $(this).find('img');

      var activityID = $(activityAnchor).attr('activityid');
      activityAnchor.unbind('click');
      if (newActivity) {
        $(this).show();
        activityAnchor.click( function (e) {
          e.preventDefault();
          leggo.activityClicked(true, newActivity['id']);
        });
        $(activityImage).attr('src', newActivity['imageURL']);
      } else {
        $(this).hide();
      }

      count++;
    });
  }

})(this, window.leggo = window.leggo || {}, jQuery);<commit_msg>clickiness fix maybe<commit_after>(function (window, leggo, $, undefined) {

  var longitude = null;
  var latitude = null;
  var locationRefreshHandle = null;
  var timeRefreshHandle = null;
  var timeSetHandle = null;
  var activityRefreshHandle = null;

  var currId;
  var activitySelected=false;
  var activityData = {};

  var isMouseDown = false;

  var currTime;
  var endTime;

  var hoursArray = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

  var anyTime = true;
  var millisecsAvailable = 0;

  leggo.initializePage = function () {
    // $('#help-button').popover();
    // pure JS
    var elem = document.getElementById('slider');
    window.mySwipe = Swipe(elem, {
      startSlide: 0,
      speed: 300,
      auto: 0,
      continuous: false,
      disableScroll: false,
      stopPropagation: false,
      callback: function(index, elem) {
        if (index==5 && activitySelected!=true){
        mySwipe.prev();
      }
      },
      transitionEnd: function(index, elem) {}
    });

    // with jQuery
    // window.mySwipe = $('ß#mySwipe').Swipe().data('Swipe');

    $('#help-button').popover(); // does this work?
    getLocation();
    locationRefreshHandle = setInterval(getLocation, 30000);

    //set up slightly less fancy time filter
    var myScrollMinutes = new IScroll('#minutes-wrapper', { probeType: 3, mouseWheel: false, bounce: false, startY: 0 });
    myScrollMinutes.scrolling = false;
    myScrollMinutes.selectedIndex = 1;
    myScrollMinutes.on('scrollStart', startTimeScroll);
    myScrollMinutes.on('scroll', updateSelectedTime);
    myScrollMinutes.on('scrollEnd', endTimeScroll);

    //make each scroll element clickable
    var lastSelectedIdx = myScrollMinutes.selectedIndex;
    // $('#minutes-scroller ul').children().on('tap', function (e) {
      // e.preventDefault();
      // myScrollMinutes.scrollToElement($(this)[0], null, null, true);
    // }).mousedown(mouseDownScroll).click(mouseUpScroll);
    $('#minutes-scroller ul').children().bind('touchstart', mouseDownScroll)
      .mousedown(mouseDownScroll)
      .bind('touchend', mouseUpScroll)
      .click(mouseUpScroll);

    function mouseDownScroll (e) {
      e.preventDefault();
      lastSelectedIdx = myScrollMinutes.selectedIndex;
    }

    function mouseUpScroll (e) {
      e.preventDefault();
      if (lastSelectedIdx === myScrollMinutes.selectedIndex) {
        myScrollMinutes.scrollToElement($(this)[0], null, null, true);
      }
    }

    function setDisplayedTime(date) {

    }

    function updateSelectedTime () {
      this.scrolling = true;
      var yDiff = this.y - 10;
      var idx = Math.floor(-1*yDiff/40) + 1;
      if (this.selectedIndex === undefined || this.selectedIndex !== idx) {
        this.selectedIndex = idx;
        var options = $($(this.scroller).children('ul')[0]).children();
        $(options).removeClass('selected-time');
        $(options[idx]).addClass('selected-time');
      }
    }

    function startTimeScroll () {
      this.scrolling = true;
      // $(document).bind('touchmove', function (e) { e.preventDefault(); });
      console.log('start');
    }

    function endTimeScroll () {
      updateSelectedTime();
      //15 minutes = 900000 millisecs. Yes this shouldn't be hardcoded
      //Yes I could have fixed that in the time it took to write this comment
      var millisecsAvailable = myScrollMinutes.selectedIndex * 900000;
      if (myScrollMinutes.selectedIndex === 1) {
        millisecsAvailable = 0;
      }
      this.scrolling = false;
      // $(document).unbind('touchmove');
      console.log('end');
    }

    function checkAndSetTime () {

    }

    //enable filter buttons
    $('.image-checkbox').each(function (i, n) {
      $(this).click( function (e) {
        console.log('hi!');
        e.preventDefault();
        var button = $(this);
        if (button.hasClass('image-checkbox-checked')) {
          button.removeClass('image-checkbox-checked');
          button.addClass('image-checkbox');
          deselectButton(button);
        } else {
          button.removeClass('image-checkbox');
          console.log(button.siblings('.image-checkbox-checked'));
          button.siblings('.image-checkbox-checked').removeClass('image-checkbox-checked').addClass('image-checkbox')
            .each( function () {
              deselectButton(this);
            });
          button.addClass('image-checkbox-checked');
          selectButton(button);
        }
        leggo.findActivities();
        setTimeout(function () { leggo.changeFilter(true); }, 500);
      });
    });

    //deselects all the filter options on the current filter
    $('.surprise-button').each(function (i, n) {
      $(this).click( function (e) {
        e.preventDefault();
        var buttons = $(this).parent().parent().find('.icons').children().removeClass('image-checkbox-checked').addClass('image-checkbox')
          .each( function () {
            deselectButton(this);
          });
        setTimeout(function () { leggo.changeFilter(true); }, 500);
      });
    });
    $('#time-surprise').unbind('click').click( function (e) {
      e.preventDefault();
      myScrollMinutes.scrollToElement($('#minutes-scroller ul').children()[1], null, null, true);
      setTimeout(function () { leggo.changeFilter(true); }, 500);
    });

    //enable refresh button. gets new activities
    $('#refresh-button').click( function (e) {
      e.preventDefault();
      leggo.findActivities();
    });

    var derp = setTimeout(leggo.findActivities, 2000);
    activityRefreshHandle = setInterval(leggo.findActivities, 300000);

  }

  //These next two functions switch the img src of a button with the appropriate selected/unselected image
  function deselectButton (button) {
    var newURL = $(button).attr('src');
    if (newURL !== undefined) {
      newURL = newURL.split('_')[0];
      newURL = newURL + '_unsel.png';
      $(button).attr('src', newURL);
    }
  }
  function selectButton (button) {
    var newURL = $(button).attr('src');
    if (newURL !== undefined) {
      newURL = newURL.split('_')[0];
      newURL = newURL + '_selected.png';
      $(button).attr('src', newURL);
    }
  }

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(storePosition);
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  }

  function toClockString (date) {
    var isPM = date.getHours() >= 12;
    //return ((isPM) ? date.getHours() - 12 : date.getHours()) + ':' + (((date.getMinutes() < 10) ? '0' : '') + currTime.getMinutes()) + ((isPM) ? 'PM' : 'AM');
    return ((date.getHours() >= 12) ? hoursArray[date.getHours() - 12] : hoursArray[date.getHours()]) + ':' + ( (date.getMinutes()<10?'0':'') + date.getMinutes() ) + ' ' + ((isPM) ? 'PM' : 'AM');
  }

  function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
  }

  //adds "amount" minutes to the end time filter
  leggo.changeEndTime = function changeEndTime(amount) {
    endTime = addMinutes(endTime, amount);
    if ( endTime.getTime() < currTime.getTime() ) {
      currTimeStr = toClockString(currTime);//((currTime.getHours() > 12) ? currTime.getHours() - 12 : currTime.getHours()) + ':' + ( (currTime.getMinutes()<10?'0':'') + currTime.getMinutes() );
      $('#time-display').text(currTimeStr);
      $('#time-display').attr('filterValue', currTime.toDateString() + ' ' + currTime.toTimeString());
    } else {
      endTimeStr = toClockString(endTime);
      $('#time-display').text(endTimeStr);
      $('#time-display').attr('filterValue', endTime.toDateString() + ' ' + endTime.toTimeString());
    }
  }

  leggo.setActivityID = function setActivityID(id){
    currId= id;
    console.log("Curr id is now" + id);
  }

  leggo.activityClicked= function activityClicked(isNext,id){
    activitySelected=true;
    leggo.setActivityID(id);
    $.get('../data.json', getProject);
    leggo.changeFilter(true);
  }
  var result;

  function getProject(result)
  {
    activities= result;
    // console.log(result);
    // console.log(currId);
    // console.log(result['activities'][currId-1]);
    $("#img-detail").attr('src', result['activities'][currId-1]['imageURL']);
    $("#descrip-detail").text(result['activities'][currId-1]['description']);
    $("#needs-detail").text(result['activities'][currId-1]['thingslist']);
    $("#cost-detail").text("$" + result['activities'][currId-1]['moneyupperlimit']);
  }

  leggo.testingfunction = function testingfunction(){
    // console.log(currId);
    window.location.replace("/finalactivity/"+currId);
  }

function callbackFunc(){

  console.log("performed");
}

  function storePosition(position) {
    longitude = position.coords.longitude;
    latitude = position.coords.latitude;
    console.log('position stored: ');
    // leggo.findActivities();
  }

  //swipes the current filter forward if isNext is true, backward if not
  leggo.changeFilter = function changeFilter (isNext) {
    var currPos = mySwipe.getPos();
    // console.log(currPos);

    var children = $('.nav-dots').children()[0].children;
    $(children[currPos]).removeClass('selected');

    if (isNext) {
        mySwipe.next();
    } else {
        mySwipe.prev();
    }

    currPos = mySwipe.getPos();
    $(children[currPos]).addClass('selected');
  }

  //aggregates the currently set filters and returns a list of activities that pass said filters
  leggo.findActivities = function (noFilter) {
    currTime = new Date();
    var startStr = currTime.getTime();
    var endStr = currTime.getTime() + millisecsAvailable;

    // console.log('start: ' + startStr);
    // console.log('end : ' + endStr);
    var filterData = {
      'nofilter': ((noFilter === undefined) ? false : true),
      'coords': [ latitude, longitude ],
/*
      'starttime':currTime.toDateString() + ' ' + currTime.toTimeString()
*/
      'starttime': startStr,
      'endtime' : endStr
    };

    //note that I am pushing filter values to arrays. I'll leave it for now in case we return to non-exclusive buttons
    $('.image-checkbox-checked').each(function (i, n) {
      filterData[$(this).attr('filter')] = filterData[$(this).attr('filter')] || [];
      filterData[$(this).attr('filter')].push($(this).attr('filtervalue'));
      // console.log('filter: ' + $(this).attr('filter') + ' value: ' + $(this).attr('filtervalue'));
    });
    $.post('/findactivities', filterData, function (data) {
      activityData = data['activities'];
      populateActivities(activityData);

      console.log(data);
    });
  }

  //adds activities to the activities page
  function populateActivities (activities) {
    if (activities.length == 0) {
      $('#activities-intro').text('We couldn\'t find anything matching your filters, so here\'s a random selection...');
      leggo.findActivities(true);
      return;
    }

    var count = 0;
    $('#activities').children().each( function () {
      var newActivity = activities[count] || false;

      var activityAnchor = $(this).find('a');
      var activityImage = $(this).find('img');

      var activityID = $(activityAnchor).attr('activityid');
      activityAnchor.unbind('click');
      if (newActivity) {
        $(this).show();
        activityAnchor.click( function (e) {
          e.preventDefault();
          leggo.activityClicked(true, newActivity['id']);
        });
        $(activityImage).attr('src', newActivity['imageURL']);
      } else {
        $(this).hide();
      }

      count++;
    });
  }

})(this, window.leggo = window.leggo || {}, jQuery);<|endoftext|>


<commit_before>//================================================================================
// 1 start the game
// 2 computer selects the color
// 3 user turn begins
// 4 user selects a color
// 5 match the user's color with computer's color
// 6a if it is match repeat step 2
// 6b if it doesnt match show the message 'you lost'
//================================================================================
// ================================= declare global vars =========================
var on
var off
var audio
var yellowButton
var greenButton
var redButton
var blueButton
var start
on = document.getElementsByClassName('switch-on')[0];
off = document.getElementsByClassName('switch-off')[0];
score = document.getElementsByClassName('score-text')[0];
yellowButton = document.getElementsByClassName('yellow')[0];
greenButton = document.getElementsByClassName('green')[0];
redButton = document.getElementsByClassName('red')[0];
blueButton = document.getElementsByClassName('blue')[0];
start = document.getElementsByClassName('start-button')[0];

//================================ onload ========================================
document.addEventListener('DOMContentLoaded',function(event) {
  event.preventDefault()

  //================================ Turn the game on/off ==========================
  on.addEventListener('click', toggleOn);
  off.addEventListener('click', toggleOff);
})

//=========================== Turn Game On =====================================
var toggleOn = function(event) {
  if(on.style.display !== 'none') {
    event.target.style.display = 'none';
    off.style.display = 'block';
    score.style.color = '#dc0d29'
  }
}

//========================= Turn Game Off ===========================================
var toggleOff = function(event) {
  if(off.style.display == 'block') {
    off.style.display = 'none';
    on.style.display = 'block'
    score.style.color = '#32050c'
    // *** pop off anything in the gamesPattern Array ***
  }
}
//===================== Store Patterns ==============================
var playersPattern = [];
var gamesPattern = [];
//====================== Game Buttons ===============================
sounds = {
  yellow : function(player) {
    console.log('PLAYERS PATTERN', playersPattern.length);
    console.log('GAMES PATTERN', gamesPattern.length);
    console.log('arguments::', arguments);

    if(off.style.display == 'block'){
      var audio = new Audio('../sounds/simonSoundYellow.mp3');
      audio.play();
      audio.addEventListener('ended',() => {
        yellowButton.style.backgroundColor = "#cba60c"
      })
      yellowButton.style.backgroundColor = "#F9D339"
    }
    if(player) {
      playersPattern.push('yellow')//*trying this*
      processPlayersTurn()
    }
  },

  green: function(player) {
    console.log('PLAYERS PATTERN', playersPattern.length);
    console.log('GAMES PATTERN', gamesPattern.length);
    console.log('arguments::', arguments);

    if(off.style.display == 'block') {
      var audio = new Audio('../sounds/simonSound2.mp3');
      audio.play();
      audio.addEventListener('ended', () => {
        greenButton.style.backgroundColor = "#03a64b"
      })
      greenButton.style.backgroundColor = "#03C65B"
    }
    if(player) {
      playersPattern.push('green')//*trying this*
      processPlayersTurn()
    }
  },

  red: function(player) {
    console.log('PLAYERS PATTERN', playersPattern.length);
    console.log('GAMES PATTERN', gamesPattern.length);
    console.log('arguments::', arguments);
    console.log('')

    if(off.style.display == 'block') {
      var audio = new Audio('../sounds/simonSound3.mp3');
      audio.play();
      audio.addEventListener('ended', () => {
        redButton.style.backgroundColor = "#9c121c"
      })
      redButton.style.backgroundColor = "#DB1A27"
    }
    if(player) {
      playersPattern.push('red')//*trying this*
      processPlayersTurn()
    }
  },

  blue: function(player) {
    console.log('PLAYERS PATTERN', playersPattern.length);
    console.log('GAMES PATTERN', gamesPattern.length);
    console.log('arguments::', arguments);

    if(off.style.display == 'block') {
      var audio = new Audio('../sounds/simonSound4.mp3');
      audio.play();
      audio.addEventListener('ended', () => {
        blueButton.style.backgroundColor = "#1d8cff"
      })
      blueButton.style.backgroundColor = "#72B6FF"
    }
    if(player) {
      playersPattern.push('blue')//*trying this*
      processPlayersTurn()
    }
  }
}

//============================= Start the Game ==================================

var gamesTurn = function() {
  if(off.style.display == 'block') {
    computerPicksColor()
    for(let i = 0; i < gamesPattern.length; i++) {
      let colors = gamesPattern[i]
      let soundFunction = functionLookUp[colors]
      setTimeout( soundFunction.bind(null, gamesPattern), i*500 );
    }
  }
}
//================================ Game Picks ===============================================

var functionLookUp = {
  yellow: function() {console.log("RUNNING YELLOW", Date.now());return sounds.yellow()},
  blue: function() {console.log("RUNNING BLUE", Date.now());return sounds.blue()},
  green: function() {console.log("RUNNING GREEN", Date.now());return sounds.green()},
  red: function() {console.log("RUNNING RED");return sounds.red()}
}

var gamesPattern = [];
var colors = ['red', 'yellow', 'green', 'blue'];
var isGameComplete = false

var computerPicksColor = function() {
  var result = colors[Math.floor(Math.random() * colors.length)];
  gamesPattern.push(result)
}

//================================= Did the Player Win or Lose ===============================
var processPlayersTurn = function() {
  for(let i=0; i < playersPattern.length; i++) {
    if(playersPattern[i] !== gamesPattern[i]) {
      gamesPattern = []
      playersPattern = []
      return false
    }
  }

  if(playersPattern.length >= gamesPattern.length) {
    setTimeout( function() {
      playersPattern = []
      gamesTurn()
    }, 1000 )
  }
}

// var compareIndexPatterns = function() {
//   if(playersPattern.length > 0) {
//     for( let i = 0; i < gamesPattern.length; i++ ) {
//       if( gamesPattern[i] !== playersPattern[i] ) {
//         return false
//       }
//     }
//     return true
//   }
// }
//
// var compareLength = function() {
//   if( playersPattern.length > 0 ) {
//     for( let i = 0; i < gamesPattern.length; i++ ) {
//       if(compareIndexPatterns() && playersPattern.length == gamesPattern.length) {
//         gamesTurn()
//       }
//     }
//   }
// }

//when strict is clicked
  // ++ to a variable that tracks no match when players turn and games turn don't match.
  //if no match is greater than 0
  //if they don't match flash !! in the score 3 times
  //then flash - - 3 times
  //reset score variable to 0
  //dump game's play arr
  //execute games turn with one randomized function from sounds
<commit_msg>add score and player messaging<commit_after>//================================================================================
// 1 start the game
// 2 computer selects the color
// 3 user turn begins
// 4 user selects a color
// 5 match the user's color with computer's color
// 6a if it is match repeat step 2
// 6b if it doesnt match show the message 'you lost'
//================================================================================
// ================================= declare global vars =========================
var on
var off
var audio
var yellowButton
var greenButton
var redButton
var blueButton
var start
on = document.getElementsByClassName('switch-on')[0];
off = document.getElementsByClassName('switch-off')[0];
score = document.getElementsByClassName('score-text')[0];
yellowButton = document.getElementsByClassName('yellow')[0];
greenButton = document.getElementsByClassName('green')[0];
redButton = document.getElementsByClassName('red')[0];
blueButton = document.getElementsByClassName('blue')[0];
start = document.getElementsByClassName('start-button')[0];

//================================ onload ========================================
document.addEventListener('DOMContentLoaded',function(event) {
  event.preventDefault()

  //================================ Turn the game on/off ==========================
  on.addEventListener('click', toggleOn);
  off.addEventListener('click', toggleOff);
})

//=========================== Turn Game On =====================================
var toggleOn = function(event) {
  if(on.style.display !== 'none') {
    event.target.style.display = 'none';
    off.style.display = 'block';
    score.style.color = '#dc0d29'
  }
}

//========================= Turn Game Off ===========================================
var toggleOff = function(event) {
  if(off.style.display == 'block') {
    off.style.display = 'none';
    on.style.display = 'block'
    score.style.color = '#32050c'
    // *** pop off anything in the gamesPattern Array ***
  }
}
//===================== Store Patterns & Score ==============================
var playersPattern = [];
var gamesPattern = [];
var playersScore = 0
//====================== Game Buttons ===============================
sounds = {
  yellow : function(player) {
    console.log('PLAYERS PATTERN', playersPattern.length);
    console.log('GAMES PATTERN', gamesPattern.length);
    console.log('arguments::', arguments);

    if(off.style.display == 'block'){
      var audio = new Audio('../sounds/simonSoundYellow.mp3');
      audio.play();
      audio.addEventListener('ended',() => {
        yellowButton.style.backgroundColor = "#cba60c"
      })
      yellowButton.style.backgroundColor = "#F9D339"
    }
    if(player) {
      playersPattern.push('yellow')//*trying this*
      processPlayersTurn()
    }
  },

  green: function(player) {
    console.log('PLAYERS PATTERN', playersPattern.length);
    console.log('GAMES PATTERN', gamesPattern.length);
    console.log('arguments::', arguments);

    if(off.style.display == 'block') {
      var audio = new Audio('../sounds/simonSound2.mp3');
      audio.play();
      audio.addEventListener('ended', () => {
        greenButton.style.backgroundColor = "#03a64b"
      })
      greenButton.style.backgroundColor = "#03C65B"
    }
    if(player) {
      playersPattern.push('green')//*trying this*
      processPlayersTurn()
    }
  },

  red: function(player) {
    console.log('PLAYERS PATTERN', playersPattern.length);
    console.log('GAMES PATTERN', gamesPattern.length);
    console.log('arguments::', arguments);
    console.log('')

    if(off.style.display == 'block') {
      var audio = new Audio('../sounds/simonSound3.mp3');
      audio.play();
      audio.addEventListener('ended', () => {
        redButton.style.backgroundColor = "#9c121c"
      })
      redButton.style.backgroundColor = "#DB1A27"
    }
    if(player) {
      playersPattern.push('red')//*trying this*
      processPlayersTurn()
    }
  },

  blue: function(player) {
    console.log('PLAYERS PATTERN', playersPattern.length);
    console.log('GAMES PATTERN', gamesPattern.length);
    console.log('arguments::', arguments);

    if(off.style.display == 'block') {
      var audio = new Audio('../sounds/simonSound4.mp3');
      audio.play();
      audio.addEventListener('ended', () => {
        blueButton.style.backgroundColor = "#1d8cff"
      })
      blueButton.style.backgroundColor = "#72B6FF"
    }
    if(player) {
      playersPattern.push('blue')//*trying this*
      processPlayersTurn()
    }
  }
}

//============================= Start the Game ==================================

var gamesTurn = function() {
  if(off.style.display == 'block') {
    computerPicksColor()
    for(let i = 0; i < gamesPattern.length; i++) {
      // document.getElementsByClassName("score-text")[0].innerHTML = "- -"
      let colors = gamesPattern[i]
      let soundFunction = functionLookUp[colors]
      setTimeout( soundFunction.bind(null, gamesPattern), i*500 );
    }
  }
}
//================================ Game Picks ===============================================

var functionLookUp = {
  yellow: function() {console.log("RUNNING YELLOW", Date.now());return sounds.yellow()},
  blue: function() {console.log("RUNNING BLUE", Date.now());return sounds.blue()},
  green: function() {console.log("RUNNING GREEN", Date.now());return sounds.green()},
  red: function() {console.log("RUNNING RED");return sounds.red()}
}

var gamesPattern = [];
var colors = ['red', 'yellow', 'green', 'blue'];
var isGameComplete = false

var computerPicksColor = function() {
  var result = colors[Math.floor(Math.random() * colors.length)];
  gamesPattern.push(result)
}

//================================= Did the Player Win or Lose ===============================
var processPlayersTurn = function() {
  for(let i=0; i < playersPattern.length; i++) {
    if(playersPattern[i] !== gamesPattern[i]) {
      document.getElementsByClassName("score-text")[0].innerHTML = " ! ! "
      gamesPattern = []
      playersPattern = []
      playersScore = 0
      document.getElementsByClassName("score-text")[0].innerHTML = "- -"
      setTimeout( function() {
        alert("╭∩╮(-_-)╭∩╮ Simon Says You Suck.... Click start button to play a new game")
      }, 1000 )

      return false
    }
  }

  if(playersPattern.length >= gamesPattern.length) {
    playersScore++
    document.getElementsByClassName("score-text")[0].innerHTML = playersScore
    setTimeout( function() {
      playersPattern = []
      gamesTurn()
    }, 1000 )
  }
}

//================================= Did the Player Win or Lose ===============================

//when strict is clicked
  // ++ to a variable that tracks no match when players turn and games turn don't match.
  //if no match is greater than 0
  //if they don't match flash !! in the score 3 times
  //then flash - - 3 times
  //reset score variable to 0
  //dump game's play arr
  //execute games turn with one randomized function from sounds
<|endoftext|>


<commit_before>'use strict';

var textarea = document.getElementById('code');
var button = document.getElementById('run-code');
var iframe = document.getElementById('iframe');
var htmlTempl = document.getElementById('template');
var alert = document.getElementById('alert');
var limit = 116;

function hideError() {
  alert.style.display = 'none';
}

function showError(source, error) {
  alert.style.display = 'block';
  alert.innerHTML = '' + source + ': ' + error;
}

function updateStatus() {
  var code = textarea.value;
  textarea.style.background = (code.length > limit) ? '#d9534f' : 'none';
  button.innerText = 'Run code (' + (limit - code.length) + ')';
}

function render() {
  var code = textarea.value;
  var doc = iframe.contentWindow.document;
  try {
    var es5 = compile(code);
  } catch(e) {
    showError('Babel Compile Error', e);
    return;
  }
  hideError();
  doc.open();
  doc.write(
    '<link rel="stylesheet" href="base.css">' +
    '' +
    '' +
    '' +
    '');
  doc.close();
}

function compile(code) {
  // Compile es6 -> es5
  return Babel.transform(code, { presets: ['es2015', 'stage-2'] }).code;
}

textarea.addEventListener('input', updateStatus);
button.addEventListener('click',  render);
hideError();
render();
updateStatus();
<commit_msg>Allow trailing comments in playground Fixes #20<commit_after>'use strict';

var textarea = document.getElementById('code');
var button = document.getElementById('run-code');
var iframe = document.getElementById('iframe');
var htmlTempl = document.getElementById('template');
var alert = document.getElementById('alert');
var limit = 116;

function hideError() {
  alert.style.display = 'none';
}

function showError(source, error) {
  alert.style.display = 'block';
  alert.innerHTML = '' + source + ': ' + error;
}

function updateStatus() {
  var code = textarea.value;
  textarea.style.background = (code.length > limit) ? '#d9534f' : 'none';
  button.innerText = 'Run code (' + (limit - code.length) + ')';
}

function render() {
  var code = textarea.value;
  var doc = iframe.contentWindow.document;
  try {
    var es5 = compile(code);
  } catch(e) {
    showError('Babel Compile Error', e);
    return;
  }
  hideError();
  doc.open();
  doc.write(
    '<link rel="stylesheet" href="base.css">' +
    '' +
    '' +
    '' +
    '');
  doc.close();
}

function compile(code) {
  // Compile es6 -> es5
  return Babel.transform(code, { presets: ['es2015', 'stage-2'] }).code;
}

textarea.addEventListener('input', updateStatus);
button.addEventListener('click',  render);
hideError();
render();
updateStatus();
<|endoftext|>


<commit_before>define(['jquery', 'inheritance', 'sprintf', 'bind', 'domReady!'], function($, inheritance) {

    var instance = null;

    var Ws = Class.extend({
        init: function () {
            if (instance !== null) {
                throw Error('Only one instance of Ws allowed!');
            }

            var that = this;

            that.events = {};

            if (!opmuseGlobals.authenticated) {
                return;
            }

            var host = null;

            if (opmuseGlobals.ws_port !== null) {
                host = sprintf("%s:%d", document.location.hostname, opmuseGlobals.ws_port);
            } else {
                host = document.location.host;
            }

            var scheme = null;

            if (document.location.protocol == 'https:') {
                scheme = 'wss';
            } else {
                scheme = 'ws';
            }

            that.unloaded = false;

            that.url = scheme + '://' + host + '/ws';

            that.internalInit();
        },
        internalInit: function () {
            var that = this;

            that.socket = new WebSocket(that.url);

            that.socket.onmessage = function (event) {
                var data = JSON.parse(event.data);

                if (data.event in that.events) {
                    for (var index in that.events[data.event]) {
                        var callback = that.events[data.event][index];
                        callback.apply(that, data.args);
                    }
                }
            };

            that.socket.onopen = function() {
                $(that).trigger('open');
            };

            $(window).bind('beforeunload', function (event) {
                that.unloaded = true;
                that.socket.close();
            });

            that.socket.onclose = function() {
                if (!that.unloaded) {
                    // TODO implement exponential backoff algo
                    setTimeout(function () {
                        that.internalInit();
                    }, 2000);
                }
            };
        },
        emit: function (event) {
            var that = this;

            var args = [].splice.call(arguments, 1);

            that.socket.send(JSON.stringify({
                'event': event,
                'args': args
            }));
        },
        on: function (event, callback) {
            var that = this;

            if (!(event in that.events)) {
                that.events[event] = [];
            }

            that.events[event].push(callback);
        }
    });

    return (function() {
        if (instance === null) {
            instance = new Ws();
        }

        return instance;
    })();
});
<commit_msg>reconnect ws every 6s instead of 2s<commit_after>define(['jquery', 'inheritance', 'sprintf', 'bind', 'domReady!'], function($, inheritance) {

    var instance = null;

    var Ws = Class.extend({
        init: function () {
            if (instance !== null) {
                throw Error('Only one instance of Ws allowed!');
            }

            var that = this;

            that.events = {};

            if (!opmuseGlobals.authenticated) {
                return;
            }

            var host = null;

            if (opmuseGlobals.ws_port !== null) {
                host = sprintf("%s:%d", document.location.hostname, opmuseGlobals.ws_port);
            } else {
                host = document.location.host;
            }

            var scheme = null;

            if (document.location.protocol == 'https:') {
                scheme = 'wss';
            } else {
                scheme = 'ws';
            }

            that.unloaded = false;

            that.url = scheme + '://' + host + '/ws';

            that.internalInit();
        },
        internalInit: function () {
            var that = this;

            that.socket = new WebSocket(that.url);

            that.socket.onmessage = function (event) {
                var data = JSON.parse(event.data);

                if (data.event in that.events) {
                    for (var index in that.events[data.event]) {
                        var callback = that.events[data.event][index];
                        callback.apply(that, data.args);
                    }
                }
            };

            that.socket.onopen = function() {
                $(that).trigger('open');
            };

            $(window).bind('beforeunload', function (event) {
                that.unloaded = true;
                that.socket.close();
            });

            that.socket.onclose = function() {
                if (!that.unloaded) {
                    // TODO implement exponential backoff algo
                    setTimeout(function () {
                        that.internalInit();
                    }, 6000);
                }
            };
        },
        emit: function (event) {
            var that = this;

            var args = [].splice.call(arguments, 1);

            that.socket.send(JSON.stringify({
                'event': event,
                'args': args
            }));
        },
        on: function (event, callback) {
            var that = this;

            if (!(event in that.events)) {
                that.events[event] = [];
            }

            that.events[event].push(callback);
        }
    });

    return (function() {
        if (instance === null) {
            instance = new Ws();
        }

        return instance;
    })();
});
<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";
var assert = require("power-assert");
var checker = require("../").checker;
describe("checker-test", function () {
    var pkg = {};
    describe("validateScopedPackage", function () {
        context("when package name start with @", function () {
            beforeEach(function () {
                pkg = {
                    name: "@private/module"
                };
            });
            it("should return true", function () {
                assert(checker.validateScopedPackage(pkg));
            });
        });
    });
});<commit_msg>test: add checker tests<commit_after>// LICENSE : MIT
"use strict";
var assert = require("power-assert");
var checker = require("../").checker;
describe("checker-test", function () {
    var pkg = {};
    describe("validateScopedPackage", function () {
        context("when package name start with @", function () {
            beforeEach(function () {
                pkg = {
                    name: "@private/module"
                };
            });
            it("should return empty array - No Error!", function () {
                var errors = checker.validateScopedPackage(pkg);
                assert(errors.length === 0);
            });
        });
        context("when package name is undefined", function () {
            beforeEach(function () {
                pkg = {};
            });
            it("should return [error] - has package.name error", function () {
                var errors = checker.validateScopedPackage(pkg);
                assert(errors.length >= 1);// will other errors contain
            });
        });
        context("when package name is not start with @", function () {
            beforeEach(function () {
                pkg = {
                    name: "normal-package"
                };
            });
            it("should return [error] - has package.name error", function () {
                var errors = checker.validateScopedPackage(pkg);
                assert(errors.length === 1);
            });
        });
    });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var sinon = require('sinon');
var circuit = require('../circuit.js');

describe('.prop', function() {
  it('getter/setter', function() {
    var o = {};
    var a = circuit.prop(null);
    assert.equal(a(), null);
    a(o);
    assert.equal(a(), o);
  });

  it('no argument', function() {
    var a = circuit.prop();
    assert(typeof a() === 'undefined');
  });

  it('function as argument', function() {
    var f = sinon.spy();
    var a = circuit.prop(f);
    a(1);
    assert(f.calledWith(1));
  });
});

describe('.event', function() {
  it('wrap function', function() {
    var f = sinon.spy();
    var a = circuit.event(f)
    a();
    assert(f.called);
  });

  it('no argument', function() {
    var a = circuit.event();
    assert.doesNotThrow(function() {
      a();
    });
  });
});

describe('.bind', function() {
  it('prop', function() {
    var o0 = {};
    var a = circuit.prop(o0);
    var b = circuit.prop();
    var c = circuit.prop();
    var d = circuit.prop();
    circuit.bind(a, b);
    circuit.bind(b, c);
    circuit.bind(c, d);
    assert.equal(d(), o0);
    var o1 = {};
    a(o1);
    assert.equal(d(), o1);
  });

  it('event', function(done) {
    var fa = sinon.spy();
    var a = circuit.event(fa);
    var fb = sinon.spy();
    var b = circuit.event(fb);
    circuit.bind(a, b);
    setTimeout(function() {
      assert(!fa.called);
      a();
      setTimeout(function() {
        assert(fb.called);
        done();
      }, 0);
    }, 0);
  });

  it('different type', function() {
    var a = circuit.prop();
    var b = circuit.event();
    assert.throws(function() {
      circuit.bind(a, b);
    });
  });

  it('no argument', function() {
    assert.throws(function() {
      circuit.bind();
    });
  });

  it('only 1 argument', function() {
    var a = circuit.prop();
    assert.throws(function() {
      circuit.bind(a);
    });
    assert.throws(function() {
      circuit.connect(null, a);
    });
    assert.throws(function() {
      circuit.connect(undefined, a);
    });
  });

  it('bind same prop', function() {
    var a = circuit.prop(0);
    circuit.bind(a, a);
    a(1);
    assert.equal(a(), 1);
  });

  it('bind same prop with function', function(done) {
    var a = circuit.prop(function(x) {
      return x + 1;
    });
    circuit.bind(a, a);
    a(1);
    assert.equal(a(), 2);
    setTimeout(function() {
      assert.equal(a(), 3);
      setTimeout(function() {
        assert.equal(a(), 4);
        done();
      });
    });
  });

  it('should not update binding prop immediately', function() {
    var a = circuit.prop(1);
    var f = sinon.spy();
    var b = circuit.prop(f);
    circuit.bind(a, b);
    a(2);
    assert(!f.called);
  });

  it('shoud update binding prop when the call stack has cleared', function(done) {
    var a = circuit.prop(1);
    var f = sinon.spy();
    var b = circuit.prop(f);
    circuit.bind(a, b);
    a(2);
    setTimeout(function() {
      assert(f.called);
      done();
    }, 0);
  });

  it('bind prop with setting function as argument', function() {
    var a = circuit.prop(function(value) {
      return value;
    });
    var b = circuit.prop();
    circuit.bind(a, b);
    var o = {};
    a(o);
    assert.equal(b(), o);
  });

  it('bind prop more than once', function() {
    var a = circuit.prop(0);
    var b = circuit.prop(1);
    var c = circuit.prop(function(x, y) {
      return x + y;
    });
    circuit.bind(a, c);
    circuit.bind(b, c);
    a(1);
    assert.equal(c(), 2);
  });

  it('bind same prop more than once', function() {
    var a = circuit.prop(1);
    var b = circuit.prop(function(x, y) {
      assert.equal(x, 1);
      assert.equal(y, 1);
    });
    circuit.bind(a, b);
    circuit.bind(a, b);
    b();
  });

  it('update prop values at the same time', function() {
    var a = circuit.prop(1);
    var b = circuit.prop(1);
    var f = sinon.spy();
    var c = circuit.prop(f);
    circuit.bind(a, c);
    circuit.bind(b, c);
    a(2);
    c();
    assert(f.calledOnce);
  });

  it('bind prop each other', function() {
    var a = circuit.prop(0);
    var b = circuit.prop(0);
    circuit.bind(a, b);
    circuit.bind(b, a);
    b(1);
    assert.equal(a(), 1);
    a(2);
    assert.equal(b(), 2);
  });

  it('bind prop in circle chain', function() {
    var a = circuit.prop(0);
    var b = circuit.prop(1);
    var c = circuit.prop(2);
    circuit.bind(a, b);
    circuit.bind(b, c);
    circuit.bind(c, a);
    a(1);
    assert.equal(a(), 1);
    assert.equal(b(), 1);
    assert.equal(c(), 1);
  });

  it('cancel event', function(done) {
    var a = circuit.event(function(event) {
      event.cancel();
    });
    var f = sinon.spy();
    var b = circuit.event(f);
    circuit.bind(a, b);
    a();
    setTimeout(function() {
      assert(!f.called);
      done();
    }, 0);
  });

  it('dispatch event', function(done) {
    var a = circuit.event(function(event) {
      event.cancel();
      event.dispatch();
    });
    var f = sinon.spy();
    var b = circuit.event(f);
    circuit.bind(a, b);
    a();
    setTimeout(function() {
      assert(f.called);
      done();
    }, 0);
  });

  it('Does not relay argument of the dispatch function as event context', function(done) {
    var a = circuit.event(function(event) {
      event.cancel();
      event.context(1);
      event.dispatch(2);
    });
    var b = circuit.event(function(event) {
      var value = event.context();
      assert.equal(value, 1);
      done();
    });
    circuit.bind(a, b);
    a();
  });

  it('event context', function(done) {
    var a = circuit.event(function(event) {
      var context = event.context;
      assert.equal(context(), 1);
      context(context() + 1);
    });
    var b = circuit.event(function(event) {
      assert.equal(event.context(), 2);
      done();
    });
    circuit.bind(a, b);
    a(1);
  });

  it('assignment to event context', function(done) {
    var a = circuit.event(function(event) {
      event.context = 1;
    });
    var b = circuit.event(function(event) {
      assert.doesNotThrow(function() {
        event.context();
      });
      done();
    });
    circuit.bind(a, b);
    a();
  });
});

describe('unbind', function() {
  it('prop', function() {
    var a = circuit.prop();
    var b = circuit.prop();
    circuit.bind(a, b);
    circuit.unbind(a, b);
    var o = {};
    a(o);
    assert.notEqual(b(), o);
  });

  it('event', function(done) {
    var a = circuit.event();
    var f = sinon.spy();
    var b = circuit.event(f);
    circuit.bind(a, b);
    circuit.unbind(a, b);
    a();
    setTimeout(function() {
      assert(!f.called);
      done();
    }, 0);
  });

  it('no argument', function() {
    assert.throws(function() {
      circuit.unbind();
    });
  });

  it('should not unbind same pair many times', function() {
    var a = circuit.prop();
    var b = circuit.prop();
    circuit.bind(a, b);
    circuit.unbind(a, b);
    assert.throws(function() {
      circuit.unbind(a, b);
    });
  });

  it('update prop cache', function() {
    var a = circuit.prop(0);
    var b = circuit.prop(0);
    circuit.bind(a, b);
    a(1);
    circuit.unbind(a, b);
    assert.equal(b(), 1);
  });
});<commit_msg>Fix test title<commit_after>var assert = require('assert');
var sinon = require('sinon');
var circuit = require('../circuit.js');

describe('.prop', function() {
  it('getter/setter', function() {
    var o = {};
    var a = circuit.prop(null);
    assert.equal(a(), null);
    a(o);
    assert.equal(a(), o);
  });

  it('no argument', function() {
    var a = circuit.prop();
    assert(typeof a() === 'undefined');
  });

  it('function as argument', function() {
    var f = sinon.spy();
    var a = circuit.prop(f);
    a(1);
    assert(f.calledWith(1));
  });
});

describe('.event', function() {
  it('wrap function', function() {
    var f = sinon.spy();
    var a = circuit.event(f)
    a();
    assert(f.called);
  });

  it('no argument', function() {
    var a = circuit.event();
    assert.doesNotThrow(function() {
      a();
    });
  });
});

describe('.bind', function() {
  it('prop', function() {
    var o0 = {};
    var a = circuit.prop(o0);
    var b = circuit.prop();
    var c = circuit.prop();
    var d = circuit.prop();
    circuit.bind(a, b);
    circuit.bind(b, c);
    circuit.bind(c, d);
    assert.equal(d(), o0);
    var o1 = {};
    a(o1);
    assert.equal(d(), o1);
  });

  it('event', function(done) {
    var fa = sinon.spy();
    var a = circuit.event(fa);
    var fb = sinon.spy();
    var b = circuit.event(fb);
    circuit.bind(a, b);
    setTimeout(function() {
      assert(!fa.called);
      a();
      setTimeout(function() {
        assert(fb.called);
        done();
      }, 0);
    }, 0);
  });

  it('different type', function() {
    var a = circuit.prop();
    var b = circuit.event();
    assert.throws(function() {
      circuit.bind(a, b);
    });
  });

  it('no argument', function() {
    assert.throws(function() {
      circuit.bind();
    });
  });

  it('only 1 argument', function() {
    var a = circuit.prop();
    assert.throws(function() {
      circuit.bind(a);
    });
    assert.throws(function() {
      circuit.connect(null, a);
    });
    assert.throws(function() {
      circuit.connect(undefined, a);
    });
  });

  it('bind same prop', function() {
    var a = circuit.prop(0);
    circuit.bind(a, a);
    a(1);
    assert.equal(a(), 1);
  });

  it('bind same prop with function', function(done) {
    var a = circuit.prop(function(x) {
      return x + 1;
    });
    circuit.bind(a, a);
    a(1);
    assert.equal(a(), 2);
    setTimeout(function() {
      assert.equal(a(), 3);
      setTimeout(function() {
        assert.equal(a(), 4);
        done();
      });
    });
  });

  it('should not update binding prop immediately', function() {
    var a = circuit.prop(1);
    var f = sinon.spy();
    var b = circuit.prop(f);
    circuit.bind(a, b);
    a(2);
    assert(!f.called);
  });

  it('shoud update binding prop when the call stack has cleared', function(done) {
    var a = circuit.prop(1);
    var f = sinon.spy();
    var b = circuit.prop(f);
    circuit.bind(a, b);
    a(2);
    setTimeout(function() {
      assert(f.called);
      done();
    }, 0);
  });

  it('bind prop with setting function as argument', function() {
    var a = circuit.prop(function(value) {
      return value;
    });
    var b = circuit.prop();
    circuit.bind(a, b);
    var o = {};
    a(o);
    assert.equal(b(), o);
  });

  it('bind prop more than once', function() {
    var a = circuit.prop(0);
    var b = circuit.prop(1);
    var c = circuit.prop(function(x, y) {
      return x + y;
    });
    circuit.bind(a, c);
    circuit.bind(b, c);
    a(1);
    assert.equal(c(), 2);
  });

  it('bind same prop more than once', function() {
    var a = circuit.prop(1);
    var b = circuit.prop(function(x, y) {
      assert.equal(x, 1);
      assert.equal(y, 1);
    });
    circuit.bind(a, b);
    circuit.bind(a, b);
    b();
  });

  it('update prop values at the same time', function() {
    var a = circuit.prop(1);
    var b = circuit.prop(1);
    var f = sinon.spy();
    var c = circuit.prop(f);
    circuit.bind(a, c);
    circuit.bind(b, c);
    a(2);
    c();
    assert(f.calledOnce);
  });

  it('bind prop each other', function() {
    var a = circuit.prop(0);
    var b = circuit.prop(0);
    circuit.bind(a, b);
    circuit.bind(b, a);
    b(1);
    assert.equal(a(), 1);
    a(2);
    assert.equal(b(), 2);
  });

  it('bind prop in circle chain', function() {
    var a = circuit.prop(0);
    var b = circuit.prop(1);
    var c = circuit.prop(2);
    circuit.bind(a, b);
    circuit.bind(b, c);
    circuit.bind(c, a);
    a(1);
    assert.equal(a(), 1);
    assert.equal(b(), 1);
    assert.equal(c(), 1);
  });

  it('cancel event', function(done) {
    var a = circuit.event(function(event) {
      event.cancel();
    });
    var f = sinon.spy();
    var b = circuit.event(f);
    circuit.bind(a, b);
    a();
    setTimeout(function() {
      assert(!f.called);
      done();
    }, 0);
  });

  it('dispatch event', function(done) {
    var a = circuit.event(function(event) {
      event.cancel();
      event.dispatch();
    });
    var f = sinon.spy();
    var b = circuit.event(f);
    circuit.bind(a, b);
    a();
    setTimeout(function() {
      assert(f.called);
      done();
    }, 0);
  });

  it('should not relay argument of the dispatch function as event context', function(done) {
    var a = circuit.event(function(event) {
      event.cancel();
      event.context(1);
      event.dispatch(2);
    });
    var b = circuit.event(function(event) {
      var value = event.context();
      assert.equal(value, 1);
      done();
    });
    circuit.bind(a, b);
    a();
  });

  it('event context', function(done) {
    var a = circuit.event(function(event) {
      var context = event.context;
      assert.equal(context(), 1);
      context(context() + 1);
    });
    var b = circuit.event(function(event) {
      assert.equal(event.context(), 2);
      done();
    });
    circuit.bind(a, b);
    a(1);
  });

  it('assignment to event context', function(done) {
    var a = circuit.event(function(event) {
      event.context = 1;
    });
    var b = circuit.event(function(event) {
      assert.doesNotThrow(function() {
        event.context();
      });
      done();
    });
    circuit.bind(a, b);
    a();
  });
});

describe('unbind', function() {
  it('prop', function() {
    var a = circuit.prop();
    var b = circuit.prop();
    circuit.bind(a, b);
    circuit.unbind(a, b);
    var o = {};
    a(o);
    assert.notEqual(b(), o);
  });

  it('event', function(done) {
    var a = circuit.event();
    var f = sinon.spy();
    var b = circuit.event(f);
    circuit.bind(a, b);
    circuit.unbind(a, b);
    a();
    setTimeout(function() {
      assert(!f.called);
      done();
    }, 0);
  });

  it('no argument', function() {
    assert.throws(function() {
      circuit.unbind();
    });
  });

  it('should not unbind same pair many times', function() {
    var a = circuit.prop();
    var b = circuit.prop();
    circuit.bind(a, b);
    circuit.unbind(a, b);
    assert.throws(function() {
      circuit.unbind(a, b);
    });
  });

  it('update prop cache', function() {
    var a = circuit.prop(0);
    var b = circuit.prop(0);
    circuit.bind(a, b);
    a(1);
    circuit.unbind(a, b);
    assert.equal(b(), 1);
  });
});<|endoftext|>


<commit_before>'use strict';

module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    return this.addBowerPackagesToProject([
        {
          name: 'bootstrap',
          target: '~3.3'
        },
        {
          name: 'bower-webfontloader',
          target: '~1.5.13'
        }
      ]);
  }
};
<commit_msg>Remove webfontloader from blueprint<commit_after>'use strict';

module.exports = {
  normalizeEntityName() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall() {
    return this.addBowerPackagesToProject([
      {
        name: 'bootstrap',
        target: '~3.3'
      }
    ]);
  }
};
<|endoftext|>


<commit_before>import { logger } from '../util/logger';

import fs from 'fs';
import workflowFactory from '../util/workflow';
import mongoose from 'mongoose';

const pageApi = {

  createPage(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('validatePage', function () {
      const page = req.body;

      if (!page.name) {
        workflow.outcome.errfor.name = 'Required';
      }

      if (!page.addr) {
        workflow.outcome.errfor.addr = 'Required';
      }

      if (workflow.hasErrors()) {
        return workflow.emit('response');
      }

      workflow.emit('createPage');
    });

    workflow.on('createPage', function () {
      mongoose.model('Page').create({
        name: req.body.name,
        address: req.body.addr,
        owner: req.user
      }, function (err, doc) {
        if (err) {
          logger.instance.error('Error while saving page', err);
          workflow.outcome.errors.push('Cannot create page');
          return workflow.emit('response');
        }
        workflow.outcome.result = doc;
        return workflow.emit('response');
      });
    });

    workflow.emit('validatePage');
  },

  getPages(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('getPages', function () {
      mongoose.model('Page').find({ owner: req.user }, function (err, doc) {
        if (err) {
          logger.instance.error('Error while fetching pages', err);
          workflow.outcome.errors.push('Cannot fetch pages');
          return workflow.emit('response');
        }

        workflow.outcome.result = doc;
        return workflow.emit('response');
      });
    });

    workflow.emit('getPages');
  },

  findPage(req, res, next) {
    const workflow = workflowFactory(req, res);
    const self = this;

    workflow.on('findPage', function () {
      pageApi._findPage(req.params.nameslug, logger.instance, function (err, doc) {
        if (err) {
          workflow.outcome.errors.push(err);
          return workflow.emit('response');
        }

        workflow.outcome.result = doc;
        return workflow.emit('response');
      });
    });

    workflow.emit('findPage');
  },

  _findPage(nameslug, logger, cb) {
    mongoose.model('Page').findOne({ nameslug }, function (err, doc) {
      if (err) {
        logger.error('Error while fetching pages', err);
        return cb('Cannot fetch pages', null);
      }

      return cb(null, doc);
    });
  },

  getPhotos(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('pageLookup', function () {
      mongoose.model('Page').findOne({
        nameslug: req.params.nameslug
      }, '_id', function (err, page) {
        if (err) {
          logger.instance.error('Cannot get photos', err);
        }
        if (!page) {
          workflow.outcome.errors.push('Page doesn\'t exist');
          workflow.emit('response');
        } else {
          workflow.page = page;
          workflow.emit('imageLookup');
        }
      });
    });

    workflow.on('imageLookup', function () {
      mongoose.model('Photo').find({
        page: workflow.page._id
      }, function (err, photos) {
        workflow.outcome.result = photos;
        return workflow.emit('response');
      });
    });

    workflow.emit('pageLookup');
  },

  uploadPhoto(req, res, next) {
    const workflow = workflowFactory(req, res);
    const file = req.file;

    workflow.on('validate', function () {
      if (file.size / 1000000 > 1) {
        workflow.outcome.errors.push('Maximum file size is 1MB');
        return workflow.emit('response');
      }

      mongoose.model('Page').findOne({
        owner: req.user,
        nameslug: req.params.nameslug
      }, function (err, page) {
        if (err) throw err;
        if (!page) {
          workflow.outcome.errors.push('Page doesn\t exist');
          return workflow.emit('response');
        }
        workflow.page = page;
        workflow.emit('upload');
      });
    });

    workflow.on('upload', function () {
      fs.readFile(file.path, function (err, data) {
        if (err) {
          return workflow.emit('exception', err);
        }

        mongoose.model('Photo').create({
          size: file.size,
          name: file.originalname,
          filename: file.filename,
          contentType: file.mimetype,
          originalFilename: file.originalname,
          page: workflow.page._id
        }, function (err, doc) {
          if (err) {
            logger.instance.error('Error while saving image', err);
            workflow.outcome.errors.push('Cannot save image');
            return workflow.emit('response');
          }
          workflow.outcome.result = 'Uploaded';
          return workflow.emit('response');
        });
      });
    });

    workflow.emit('validate');
  },

  deletePhoto(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('deletePicture', function () {
      let query = {
        $pull: {
          photos: {
            _id: req.params.photoid
          }
        }
      };

      mongoose.model('Page').findOneAndUpdate({
        owner: req.user,
        nameslug: req.params.nameslug
      }, query, function (err, doc) {
        if (err) {
          logger.instance.error('Error while removing photo', err);
          workflow.outcome.errors.push('Cannot delete photo');
          return workflow.emit('response');
        }
        workflow.outcome.result = 'Deleted';
        return workflow.emit('response');
      });
    });

    workflow.emit('deletePicture');
  },

  updatePhoto(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('validate', function () {
      mongoose.model('Page').findOne({
        owner: req.user,
        nameslug: req.params.nameslug
      }, function (err, page) {
        if (err) {
          logger.instance.error('Page doesn\'t exist', err);
          workflow.outcome.errors.push('An error occurred');
          return workflow.emit('response');
        }

        workflow.outcome.page = page;
        return workflow.emit('updatePhoto');
      });
    });

    workflow.on('updatePhoto', function () {
      const query = {
        name: req.body.name,
        tags: req.body.tags
      };
      mongoose.model('Photo').findByIdAndUpdate(
        req.params.photoid,
        query,
        function (err, doc) {
          if (err) {
            logger.instance.error('Error while updating photo', err);
            workflow.outcome.errors.push('Cannot delete photo');
            return workflow.emit('response');
          }

          workflow.outcome.result = 'Updated';
          return workflow.emit('response');
        });
    });

    workflow.emit('validate');
  }
};

export { pageApi };
<commit_msg>populate createdBy field<commit_after>import { logger } from '../util/logger';

import fs from 'fs';
import workflowFactory from '../util/workflow';
import mongoose from 'mongoose';

const pageApi = {

  createPage(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('validatePage', function () {
      const page = req.body;

      if (!page.name) {
        workflow.outcome.errfor.name = 'Required';
      }

      if (!page.addr) {
        workflow.outcome.errfor.addr = 'Required';
      }

      if (workflow.hasErrors()) {
        return workflow.emit('response');
      }

      workflow.emit('createPage');
    });

    workflow.on('createPage', function () {
      mongoose.model('Page').create({
        name: req.body.name,
        address: req.body.addr,
        owner: req.user
      }, function (err, doc) {
        if (err) {
          logger.instance.error('Error while saving page', err);
          workflow.outcome.errors.push('Cannot create page');
          return workflow.emit('response');
        }
        workflow.outcome.result = doc;
        return workflow.emit('response');
      });
    });

    workflow.emit('validatePage');
  },

  getPages(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('getPages', function () {
      mongoose.model('Page').find({ owner: req.user }, function (err, doc) {
        if (err) {
          logger.instance.error('Error while fetching pages', err);
          workflow.outcome.errors.push('Cannot fetch pages');
          return workflow.emit('response');
        }

        workflow.outcome.result = doc;
        return workflow.emit('response');
      });
    });

    workflow.emit('getPages');
  },

  findPage(req, res, next) {
    const workflow = workflowFactory(req, res);
    const self = this;

    workflow.on('findPage', function () {
      pageApi._findPage(req.params.nameslug, logger.instance, function (err, doc) {
        if (err) {
          workflow.outcome.errors.push(err);
          return workflow.emit('response');
        }

        workflow.outcome.result = doc;
        return workflow.emit('response');
      });
    });

    workflow.emit('findPage');
  },

  _findPage(nameslug, logger, cb) {
    mongoose.model('Page').findOne({ nameslug }, function (err, doc) {
      if (err) {
        logger.error('Error while fetching pages', err);
        return cb('Cannot fetch pages', null);
      }

      return cb(null, doc);
    });
  },

  getPhotos(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('pageLookup', function () {
      mongoose.model('Page').findOne({
        nameslug: req.params.nameslug
      }, '_id', function (err, page) {
        if (err) {
          logger.instance.error('Cannot get photos', err);
        }
        if (!page) {
          workflow.outcome.errors.push('Page doesn\'t exist');
          workflow.emit('response');
        } else {
          workflow.page = page;
          workflow.emit('imageLookup');
        }
      });
    });

    workflow.on('imageLookup', function () {
      mongoose.model('Photo').find({
        page: workflow.page._id
      }, function (err, photos) {
        workflow.outcome.result = photos;
        return workflow.emit('response');
      });
    });

    workflow.emit('pageLookup');
  },

  uploadPhoto(req, res, next) {
    const workflow = workflowFactory(req, res);
    const file = req.file;

    workflow.on('validate', function () {
      if (file.size / 1000000 > 1) {
        workflow.outcome.errors.push('Maximum file size is 1MB');
        return workflow.emit('response');
      }

      mongoose.model('Page').findOne({
        owner: req.user,
        nameslug: req.params.nameslug
      }, function (err, page) {
        if (err) throw err;
        if (!page) {
          workflow.outcome.errors.push('Page doesn\t exist');
          return workflow.emit('response');
        }
        workflow.page = page;
        workflow.emit('upload');
      });
    });

    workflow.on('upload', function () {
      fs.readFile(file.path, function (err, data) {
        if (err) {
          return workflow.emit('exception', err);
        }

        mongoose.model('Photo').create({
          size: file.size,
          name: file.originalname,
          filename: file.filename,
          contentType: file.mimetype,
          originalFilename: file.originalname,
          page: workflow.page._id,
          createdBy: req.user
        }, function (err, doc) {
          if (err) {
            logger.instance.error('Error while saving image', err);
            workflow.outcome.errors.push('Cannot save image');
            return workflow.emit('response');
          }
          workflow.outcome.result = 'Uploaded';
          return workflow.emit('response');
        });
      });
    });

    workflow.emit('validate');
  },

  deletePhoto(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('deletePicture', function () {
      let query = {
        $pull: {
          photos: {
            _id: req.params.photoid
          }
        }
      };

      mongoose.model('Page').findOneAndUpdate({
        owner: req.user,
        nameslug: req.params.nameslug
      }, query, function (err, doc) {
        if (err) {
          logger.instance.error('Error while removing photo', err);
          workflow.outcome.errors.push('Cannot delete photo');
          return workflow.emit('response');
        }
        workflow.outcome.result = 'Deleted';
        return workflow.emit('response');
      });
    });

    workflow.emit('deletePicture');
  },

  updatePhoto(req, res, next) {
    const workflow = workflowFactory(req, res);

    workflow.on('validate', function () {
      mongoose.model('Page').findOne({
        owner: req.user,
        nameslug: req.params.nameslug
      }, function (err, page) {
        if (err) {
          logger.instance.error('Page doesn\'t exist', err);
          workflow.outcome.errors.push('An error occurred');
          return workflow.emit('response');
        }

        workflow.outcome.page = page;
        return workflow.emit('updatePhoto');
      });
    });

    workflow.on('updatePhoto', function () {
      const query = {
        name: req.body.name,
        tags: req.body.tags
      };
      mongoose.model('Photo').findByIdAndUpdate(
        req.params.photoid,
        query,
        function (err, doc) {
          if (err) {
            logger.instance.error('Error while updating photo', err);
            workflow.outcome.errors.push('Cannot delete photo');
            return workflow.emit('response');
          }

          workflow.outcome.result = 'Updated';
          return workflow.emit('response');
        });
    });

    workflow.emit('validate');
  }
};

export { pageApi };
<|endoftext|>


<commit_before>var assert = window.chai.assert;
var htmlCases = require('../cases/html');
var serverParser = require('../../dist/htmlparser2').parseDOM;
var clientParser = require('../../lib/html-to-dom-client');
var helpers = require('../helpers');

describe('client parser', function () {
  helpers.throwsError(clientParser, assert);
  helpers.runTests(htmlCases, clientParser, serverParser, assert);

  it.skip('performance', function () {
    var html = '
test
';
    var start = performance.now();
    var times = 1000;
    while (--times) {
      clientParser(html);
    }
    var end = performance.now();
    console.log('performance: ' + (end - start) + ' milliseconds'); // eslint-disable-line no-console
  });
});
<commit_msg>test(client): enable performance test for client parser<commit_after>var assert = window.chai.assert;
var htmlCases = require('../cases/html');
var serverParser = require('../../dist/htmlparser2').parseDOM;
var clientParser = require('../../lib/html-to-dom-client');
var helpers = require('../helpers');

describe('client parser', function () {
  helpers.throwsError(clientParser, assert);
  helpers.runTests(htmlCases, clientParser, serverParser, assert);

  describe('performance', function () {
    it('executes 1000 times in less than 50ms', function () {
      var times = 1000;
      var start = performance.now();
      while (--times) {
        clientParser('
test
');
      }
      var end = performance.now();
      var elapsed = end - start;
      assert.isBelow(elapsed, 50);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var assert = require('assert');
var cp = require('child_process');

// Sets directory to output coverage data to
// Incremented every time getRunner() is called.
var covCount = 1;
var isIstanbul = process.env.running_under_istanbul;

/**
 * Gets an array containing the routine to run the jade CLI. If this file is
 * being processed with istanbul then this function will return a routine
 * asking istanbul to store coverage data to a unique directory
 * (cov-pt<covCount>/).
 */
function getRunner() {
  var jadeExe = __dirname + '/../bin/jade.js';

  if (!isIstanbul) return ['node', jadeExe];
  else {
    return ['istanbul', 'cover',
            '--print',  'none',
            '--root',   process.cwd(),
            '--dir',    process.cwd() + '/cov-pt' + (covCount++),
            jadeExe,
            '--'];
  }
}

function run(args, stdin, callback) {
  if (arguments.length === 2) {
    callback = stdin;
    stdin    = null;
  }
  var runner = getRunner().join(' ');
  cp.exec((stdin || '') + runner + ' ' + args, {
    cwd: __dirname + '/temp'
  }, callback);
}

try {
  fs.mkdirSync(__dirname + '/temp');
} catch (ex) {
  if (ex.code !== 'EEXIST') {
    throw ex;
  }
}

describe('command line with HTML output', function () {
  if (isIstanbul) {
    this.timeout(6000);
    this.slow(4500);
  } else {
    this.slow(250);
  }
  it('jade --no-debug input.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input.html', '
output not written
');
    run('--no-debug input.jade', function (err) {
      if (err) return done(err);
      var html = fs.readFileSync(__dirname + '/temp/input.html', 'utf8');
      assert(html === '
bar
');
      done();
    });
  });
  it('jade --no-debug --obj "{\'loc\':\'str\'}" input.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo= loc');
    fs.writeFileSync(__dirname + '/temp/input.html', '
output not written
');
    run('--no-debug --obj "{\'loc\':\'str\'}" input.jade', function (err) {
      if (err) return done(err);
      var html = fs.readFileSync(__dirname + '/temp/input.html', 'utf8');
      assert(html === '
str
');
      done();
    });
  });
  it('cat input.jade | jade --no-debug', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    run('--no-debug', 'cat input.jade | ', function (err, stdout, stderr) {
      if (err) return done(err);
      assert(stdout === '
bar
');
      done();
    });
  });
});

describe('command line with client JS output', function () {
  if (isIstanbul) {
    this.timeout(6000);
    this.slow(4500);
  } else {
    this.slow(250);
  }
  it('jade --no-debug --client --name myTemplate input.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input.js', 'throw new Error("output not written");');
    run('--no-debug --client --name myTemplate input.jade', function (err) {
      if (err) return done(err);
      var template = Function('', fs.readFileSync(__dirname + '/temp/input.js', 'utf8') + ';return myTemplate;')();
      assert(template() === '
bar
');
      done();
    });
  });
  it('cat input.jade | jade --no-debug --client --name myTemplate', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input.js', 'throw new Error("output not written");');
    run('--no-debug --client --name myTemplate', 'cat input.jade | ', function (err, stdout) {
      if (err) return done(err);
      var template = Function('', stdout + ';return myTemplate;')();
      assert(template() === '
bar
');
      done();
    });
  });
  it('jade --no-debug --client --name-after-file input-file.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input-file.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input-file.js', 'throw new Error("output not written");');
    run('--no-debug --client --name-after-file input-file.jade', function (err, stdout, stderr) {
      if (err) return done(err);
      var template = Function('', fs.readFileSync(__dirname + '/temp/input-file.js', 'utf8') + ';return inputFileTemplate;')();
      assert(template() === '
bar
');
      return done();
    });
  });
  it('jade --no-debug --client --name-after-file _InPuTwIthWEiRdNaMME.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/_InPuTwIthWEiRdNaMME.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/_InPuTwIthWEiRdNaMME.js', 'throw new Error("output not written");');
    run('--no-debug --client --name-after-file _InPuTwIthWEiRdNaMME.jade', function (err, stdout, stderr) {
      if (err) return done(err);
      var template = Function('', fs.readFileSync(__dirname + '/temp/_InPuTwIthWEiRdNaMME.js', 'utf8') + ';return InputwithweirdnammeTemplate;')();
      assert(template() === '
bar
');
      return done();
    });
  });
});

describe('command line watch mode', function () {
  var watchProc;
  var stdout = '';
  after(function() {
    watchProc.kill('SIGINT');
  });
  it('jade --no-debug --client --name-after-file --watch input-file.jade (pass 1)', function (done) {
    if (isIstanbul) {
      this.timeout(6000);
      this.slow(4500);
    } else {
      this.slow(300);
    }
    fs.writeFileSync(__dirname + '/temp/input-file.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input-file.js', 'throw new Error("output not written (pass 1)");');
    var cmd = getRunner();
    cmd.push.apply(cmd,
      ['--no-debug', '--client', '--name-after-file', '--watch', 'input-file.jade']);
    watchProc = cp.spawn(cmd[0], cmd.slice(1),  {
      cwd: __dirname + '/temp'
    });

    watchProc.stdout.setEncoding('utf8');
    watchProc
      .on('error', done)
      .stdout.on('data', function(buf) {
        stdout += buf;
        if (/.*rendered.*/.test(stdout)) {
          stdout = '';
          var template = Function('', fs.readFileSync(__dirname + '/temp/input-file.js', 'utf8') + ';return inputFileTemplate;')();
          assert(template() === '
bar
');

          watchProc.stdout.removeAllListeners('data');
          watchProc.removeAllListeners('error');
          return done();
        }
      });
  });
  it('jade --no-debug --client --name-after-file --watch input-file.jade (pass 2)', function (done) {
    fs.writeFileSync(__dirname + '/temp/input-file.js', 'throw new Error("output not written (pass 2)");');
    fs.writeFileSync(__dirname + '/temp/input-file.jade', '.foo baz');

    watchProc
      .on('error', done)
      .stdout.on('data', function(buf) {
        stdout += buf;
        if (/.*rendered.*/.test(stdout)) {
          stdout = '';
          var template = Function('', fs.readFileSync(__dirname + '/temp/input-file.js', 'utf8') + ';return inputFileTemplate;')();
          assert(template() === '
baz
');

          watchProc.stdout.removeAllListeners('data');
          watchProc.removeAllListeners('error');
          return done();
        }
      });
  });
});
<commit_msg>Add file extension output test<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var assert = require('assert');
var cp = require('child_process');

// Sets directory to output coverage data to
// Incremented every time getRunner() is called.
var covCount = 1;
var isIstanbul = process.env.running_under_istanbul;

/**
 * Gets an array containing the routine to run the jade CLI. If this file is
 * being processed with istanbul then this function will return a routine
 * asking istanbul to store coverage data to a unique directory
 * (cov-pt<covCount>/).
 */
function getRunner() {
  var jadeExe = __dirname + '/../bin/jade.js';

  if (!isIstanbul) return ['node', jadeExe];
  else {
    return ['istanbul', 'cover',
            '--print',  'none',
            '--root',   process.cwd(),
            '--dir',    process.cwd() + '/cov-pt' + (covCount++),
            jadeExe,
            '--'];
  }
}

function run(args, stdin, callback) {
  if (arguments.length === 2) {
    callback = stdin;
    stdin    = null;
  }
  var runner = getRunner().join(' ');
  cp.exec((stdin || '') + runner + ' ' + args, {
    cwd: __dirname + '/temp'
  }, callback);
}

try {
  fs.mkdirSync(__dirname + '/temp');
} catch (ex) {
  if (ex.code !== 'EEXIST') {
    throw ex;
  }
}

describe('command line with HTML output', function () {
  if (isIstanbul) {
    this.timeout(6000);
    this.slow(4500);
  } else {
    this.slow(250);
  }
  it('jade --no-debug input.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input.html', '
output not written
');
    run('--no-debug input.jade', function (err) {
      if (err) return done(err);
      var html = fs.readFileSync(__dirname + '/temp/input.html', 'utf8');
      assert(html === '
bar
');
      done();
    });
  });
  it('jade --no-debug -E special-html input.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input.special-html', '
output not written
');
    run('--no-debug -E special-html input.jade', function (err) {
      if (err) return done(err);
      var html = fs.readFileSync(__dirname + '/temp/input.special-html', 'utf8');
      assert(html === '
bar
');
      done();
    });
  });
  it('jade --no-debug --obj "{\'loc\':\'str\'}" input.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo= loc');
    fs.writeFileSync(__dirname + '/temp/input.html', '
output not written
');
    run('--no-debug --obj "{\'loc\':\'str\'}" input.jade', function (err) {
      if (err) return done(err);
      var html = fs.readFileSync(__dirname + '/temp/input.html', 'utf8');
      assert(html === '
str
');
      done();
    });
  });
  it('cat input.jade | jade --no-debug', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    run('--no-debug', 'cat input.jade | ', function (err, stdout, stderr) {
      if (err) return done(err);
      assert(stdout === '
bar
');
      done();
    });
  });
});

describe('command line with client JS output', function () {
  if (isIstanbul) {
    this.timeout(6000);
    this.slow(4500);
  } else {
    this.slow(250);
  }
  it('jade --no-debug --client --name myTemplate input.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input.js', 'throw new Error("output not written");');
    run('--no-debug --client --name myTemplate input.jade', function (err) {
      if (err) return done(err);
      var template = Function('', fs.readFileSync(__dirname + '/temp/input.js', 'utf8') + ';return myTemplate;')();
      assert(template() === '
bar
');
      done();
    });
  });
  it('jade --no-debug --client -E special-js --name myTemplate input.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input.special-js', 'throw new Error("output not written");');
    run('--no-debug --client -E special-js --name myTemplate input.jade', function (err) {
      if (err) return done(err);
      var template = Function('', fs.readFileSync(__dirname + '/temp/input.special-js', 'utf8') + ';return myTemplate;')();
      assert(template() === '
bar
');
      done();
    });
  });
  it('cat input.jade | jade --no-debug --client --name myTemplate', function (done) {
    fs.writeFileSync(__dirname + '/temp/input.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input.js', 'throw new Error("output not written");');
    run('--no-debug --client --name myTemplate', 'cat input.jade | ', function (err, stdout) {
      if (err) return done(err);
      var template = Function('', stdout + ';return myTemplate;')();
      assert(template() === '
bar
');
      done();
    });
  });
  it('jade --no-debug --client --name-after-file input-file.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/input-file.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input-file.js', 'throw new Error("output not written");');
    run('--no-debug --client --name-after-file input-file.jade', function (err, stdout, stderr) {
      if (err) return done(err);
      var template = Function('', fs.readFileSync(__dirname + '/temp/input-file.js', 'utf8') + ';return inputFileTemplate;')();
      assert(template() === '
bar
');
      return done();
    });
  });
  it('jade --no-debug --client --name-after-file _InPuTwIthWEiRdNaMME.jade', function (done) {
    fs.writeFileSync(__dirname + '/temp/_InPuTwIthWEiRdNaMME.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/_InPuTwIthWEiRdNaMME.js', 'throw new Error("output not written");');
    run('--no-debug --client --name-after-file _InPuTwIthWEiRdNaMME.jade', function (err, stdout, stderr) {
      if (err) return done(err);
      var template = Function('', fs.readFileSync(__dirname + '/temp/_InPuTwIthWEiRdNaMME.js', 'utf8') + ';return InputwithweirdnammeTemplate;')();
      assert(template() === '
bar
');
      return done();
    });
  });
});

describe('command line watch mode', function () {
  var watchProc;
  var stdout = '';
  after(function() {
    watchProc.kill('SIGINT');
  });
  it('jade --no-debug --client --name-after-file --watch input-file.jade (pass 1)', function (done) {
    if (isIstanbul) {
      this.timeout(6000);
      this.slow(4500);
    } else {
      this.slow(300);
    }
    fs.writeFileSync(__dirname + '/temp/input-file.jade', '.foo bar');
    fs.writeFileSync(__dirname + '/temp/input-file.js', 'throw new Error("output not written (pass 1)");');
    var cmd = getRunner();
    cmd.push.apply(cmd,
      ['--no-debug', '--client', '--name-after-file', '--watch', 'input-file.jade']);
    watchProc = cp.spawn(cmd[0], cmd.slice(1),  {
      cwd: __dirname + '/temp'
    });

    watchProc.stdout.setEncoding('utf8');
    watchProc
      .on('error', done)
      .stdout.on('data', function(buf) {
        stdout += buf;
        if (/.*rendered.*/.test(stdout)) {
          stdout = '';
          var template = Function('', fs.readFileSync(__dirname + '/temp/input-file.js', 'utf8') + ';return inputFileTemplate;')();
          assert(template() === '
bar
');

          watchProc.stdout.removeAllListeners('data');
          watchProc.removeAllListeners('error');
          return done();
        }
      });
  });
  it('jade --no-debug --client --name-after-file --watch input-file.jade (pass 2)', function (done) {
    fs.writeFileSync(__dirname + '/temp/input-file.js', 'throw new Error("output not written (pass 2)");');
    fs.writeFileSync(__dirname + '/temp/input-file.jade', '.foo baz');

    watchProc
      .on('error', done)
      .stdout.on('data', function(buf) {
        stdout += buf;
        if (/.*rendered.*/.test(stdout)) {
          stdout = '';
          var template = Function('', fs.readFileSync(__dirname + '/temp/input-file.js', 'utf8') + ';return inputFileTemplate;')();
          assert(template() === '
baz
');

          watchProc.stdout.removeAllListeners('data');
          watchProc.removeAllListeners('error');
          return done();
        }
      });
  });
});
<|endoftext|>