<commit_before>'use strict';

(function() {
  var xhr = new XMLHttpRequest();

  xhr.open('GET', '/api/posts');
  xhr.send(null);

  xhr.onreadystatechange = function() {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    var post, posts, i;

    if (xhr.readyState === DONE) {
      if (xhr.status === OK) {

        posts = JSON.parse(xhr.responseText);
        console.log(posts);

        for (i = 0; i < posts.length; i++) {
          var card        = document.createElement("div");
          var cardContent = document.createElement("div");
          var cardAction  = document.createElement("div");
          var link        = document.createElement("a");
          var button      = document.createElement("button");
          var title       = document.createElement("span");
          var titleText   = document.createTextNode(posts[i].title);
          var content     = document.createElement("p");
          var contentText = document.createTextNode(posts[i].content);
          var element     = document.getElementById("posts-container");

          card.appendChild(cardContent);
          card.className += "card grey lighten-2";

          cardContent.appendChild(title)
          cardContent.className += "card-content black-text";
          cardContent.appendChild(content)
          cardContent.appendChild(cardAction);

          cardAction.className += "card-action";
          cardAction.appendChild(link);

          button.innerHTML = "Click to Read";
          button.className += "btn waves-effect red darken-1";

          link.setAttribute("href", "#");
          link.appendChild(button)
          link.className += "";

          title.appendChild(titleText);
          title.className += "card-title";

          content.appendChild(contentText);

          element.appendChild(card);
        }
      }
    }
  };
})();
<commit_msg>remove console.log<commit_after>'use strict';

(function() {
  var xhr = new XMLHttpRequest();

  xhr.open('GET', '/api/posts');
  xhr.send(null);

  xhr.onreadystatechange = function() {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    var post, posts, i;

    if (xhr.readyState === DONE) {
      if (xhr.status === OK) {

        posts = JSON.parse(xhr.responseText);

        for (i = 0; i < posts.length; i++) {
          var card        = document.createElement("div");
          var cardContent = document.createElement("div");
          var cardAction  = document.createElement("div");
          var link        = document.createElement("a");
          var button      = document.createElement("button");
          var title       = document.createElement("span");
          var titleText   = document.createTextNode(posts[i].title);
          var content     = document.createElement("p");
          var contentText = document.createTextNode(posts[i].content);
          var element     = document.getElementById("posts-container");

          card.appendChild(cardContent);
          card.className += "card grey lighten-2";

          cardContent.appendChild(title)
          cardContent.className += "card-content black-text";
          cardContent.appendChild(content)
          cardContent.appendChild(cardAction);

          cardAction.className += "card-action";
          cardAction.appendChild(link);

          button.innerHTML = "Click to Read";
          button.className += "btn waves-effect blue";

          link.setAttribute("href", "#");
          link.appendChild(button)
          link.className += "";

          title.appendChild(titleText);
          title.className += "card-title";

          content.appendChild(contentText);

          element.appendChild(card);
        }
      }
    }
  };
})();
<|endoftext|>


<commit_before>function prepareHighlight() {
  $('#log').addClass("highlight");
  $("#log div.highlight").removeClass("highlight");
  $('#clear_selection').addClass("active");
}

function clearHighlight() {
  $('#log').removeClass("highlight");
  $("#log div.highlight").removeClass("highlight");
  $('#clear_selection').removeClass("active");
}

function highlightLines(range) {
  prepareHighlight();

  range = range.sort();

  var first = range[0];
  var last  = range[1] || range[0];

  $("#log .timestamp").each(function() {
    var $entry = $(this).parent();

    if (this.id >= first && this.id <= last)
      $entry.addClass("highlight");
    else
      $entry.removeClass("highlight");
  })
}

function highlightChain(id) {
  prepareHighlight();

  while(true) {
    var elems = $("#log [data-group='" + id + "']");
    elems.addClass("highlight");

    var attr = elems[0].attributes.getNamedItem('data-previous_group');
    if(!attr) return elems[0];
    id = attr.value;
  }
}

function filterJoinPart() {
  if($('#show_noise').is(':checked')) {
    $("#log").removeClass('without-noise');
  } else {
    $("#log").addClass('without-noise');
  }
}

function filterLines(query) {
  if(query == null || query == "") {
    $("#clear_filter").hide();
    $("#log div").show();
  } else {
    $("#clear_filter").show();

    query = query.toLowerCase();
    $("#log div").each(function() {
      if(this.textContent.toLowerCase().indexOf(query) != -1) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  }
}

function update(initial) {
  var current = window.location.hash.substring(1).split(";");
  var selection = current[0], filter = current[1];

  if(selection != null) {
    if(selection == "") {
      clearHighlight();
    } else {
      prepareHighlight();

      var anchors = selection.split("-");
      if(anchors[1] == 'chain') {
        var elem = highlightChain($("[id='" + anchors[0] + "']:last").parent()[0].attributes.getNamedItem('data-group').value);
      } else {
        if(anchors && anchors.length > 0)
          var elem = $("#" + anchors[0])[0];
        highlightLines(anchors);
      }

      if(elem && initial)
        elem.scrollIntoView();
    }
  }

  if(initial)
    $('#filter').val(filter);

  filterLines(filter);

  if(anchors)
    return anchors[0];
}

function setHash(selection, filter) {
  var current = window.location.hash.substring(1).split(";");
  var currentSelection = current[0], currentFilter = current[1];

  if(selection != null) currentSelection = selection;
  if(filter != null)    currentFilter = filter;

  var newHash = (currentSelection || '') + ';' + (currentFilter || '');

  var elems = $("[id='" + newHash + "']");
  elems.attr('id', '');
  window.location.hash = '#' + newHash;
  elems.attr('id', currentSelection);
}

$(window).hashchange(function() {
  update();
});

$(document).ready(function() {
  update(true);

  var shift = false;

  $("a.timestamp").click(function() {
    prepareHighlight();

    if(shift) {
      var from = update();
      var to = this.id;

      setHash(from + "-" + to);
    } else {
      setHash(this.id);
    }

    return false;
  });

  $(document).keydown(function(e) {
    if(e.keyCode == 16) shift = true;
  });

  $(document).keyup(function(e) {
    if(e.keyCode == 16) shift = false;
  });

  $("#clear_selection").click(function() {
    setHash("");
    clearHighlight();

    return false;
  });

  var filterTimeout = null;
  $("#filter").keyup(function() {
    var $this = this;

    clearTimeout(filterTimeout);
    filterTimeout = setTimeout(function() {
      setHash(null, $this.value);
    }, 500);
  });

  $("#clear_filter").click(function() {
    var highlightedElem = $("#log div.highlight:first")[0];

    setHash(null, "");
    $("#filter").val("");

    if(highlightedElem) {
      setTimeout(function() {
        highlightedElem.scrollIntoView();
      }, 200);
    }
  });

  $("#show_noise").change(function() {
    filterJoinPart();
  });

  $(".chain").click(function() {
     setHash($(this).parent().find('.timestamp')[0].id + "-chain");
  });
});
<commit_msg>Allow clearing selection by clicking anywhere in the log.<commit_after>function prepareHighlight() {
  $('#log').addClass("highlight");
  $("#log div.highlight").removeClass("highlight");
  $('#clear_selection').addClass("active");
}

function clearHighlight() {
  $('#log').removeClass("highlight");
  $("#log div.highlight").removeClass("highlight");
  $('#clear_selection').removeClass("active");
}

function highlightLines(range) {
  prepareHighlight();

  range = range.sort();

  var first = range[0];
  var last  = range[1] || range[0];

  $("#log .timestamp").each(function() {
    var $entry = $(this).parent();

    if (this.id >= first && this.id <= last)
      $entry.addClass("highlight");
    else
      $entry.removeClass("highlight");
  })
}

function highlightChain(id) {
  prepareHighlight();

  while(true) {
    var elems = $("#log [data-group='" + id + "']");
    elems.addClass("highlight");

    var attr = elems[0].attributes.getNamedItem('data-previous_group');
    if(!attr) return elems[0];
    id = attr.value;
  }
}

function filterJoinPart() {
  if($('#show_noise').is(':checked')) {
    $("#log").removeClass('without-noise');
  } else {
    $("#log").addClass('without-noise');
  }
}

function filterLines(query) {
  if(query == null || query == "") {
    $("#clear_filter").hide();
    $("#log div").show();
  } else {
    $("#clear_filter").show();

    query = query.toLowerCase();
    $("#log div").each(function() {
      if(this.textContent.toLowerCase().indexOf(query) != -1) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  }
}

function update(initial) {
  var current = window.location.hash.substring(1).split(";");
  var selection = current[0], filter = current[1];

  if(selection != null) {
    if(selection == "") {
      clearHighlight();
    } else {
      prepareHighlight();

      var anchors = selection.split("-");
      if(anchors[1] == 'chain') {
        var elem = highlightChain($("[id='" + anchors[0] + "']:last").parent()[0].attributes.getNamedItem('data-group').value);
      } else {
        if(anchors && anchors.length > 0)
          var elem = $("#" + anchors[0])[0];
        highlightLines(anchors);
      }

      if(elem && initial)
        elem.scrollIntoView();
    }
  }

  if(initial)
    $('#filter').val(filter);

  filterLines(filter);

  if(anchors)
    return anchors[0];
}

function setHash(selection, filter) {
  var current = window.location.hash.substring(1).split(";");
  var currentSelection = current[0], currentFilter = current[1];

  if(selection != null) currentSelection = selection;
  if(filter != null)    currentFilter = filter;

  var newHash = (currentSelection || '') + ';' + (currentFilter || '');

  var elems = $("[id='" + newHash + "']");
  elems.attr('id', '');
  window.location.hash = '#' + newHash;
  elems.attr('id', currentSelection);
}

$(window).hashchange(function() {
  update();
});

$(document).ready(function() {
  update(true);

  var shift = false;

  $("a.timestamp").click(function() {
    prepareHighlight();

    if(shift) {
      var from = update();
      var to = this.id;

      setHash(from + "-" + to);
    } else {
      setHash(this.id);
    }

    return false;
  });

  $(document).keydown(function(e) {
    if(e.keyCode == 16) shift = true;
  });

  $(document).keyup(function(e) {
    if(e.keyCode == 16) shift = false;
  });

  $("#log, #clear_selection").click(function() {
    setHash("");
    clearHighlight();

    return false;
  });

  var filterTimeout = null;
  $("#filter").keyup(function() {
    var $this = this;

    clearTimeout(filterTimeout);
    filterTimeout = setTimeout(function() {
      setHash(null, $this.value);
    }, 500);
  });

  $("#clear_filter").click(function() {
    var highlightedElem = $("#log div.highlight:first")[0];

    setHash(null, "");
    $("#filter").val("");

    if(highlightedElem) {
      setTimeout(function() {
        highlightedElem.scrollIntoView();
      }, 200);
    }
  });

  $("#show_noise").change(function() {
    filterJoinPart();
  });

  $(".chain").click(function() {
     setHash($(this).parent().find('.timestamp')[0].id + "-chain");

     return false;
  });
});
<|endoftext|>


<commit_before>//form variables
var city = '';
var checkin = '';
var checkout = '';
var id = '';

//when the search cities nav link is clicked, the cities are loaded
$('#cities').click(function(){

    $('#searchbox').hide();
    $('#contactus').hide();
    $('#location').show();

    //charlottesville, nyc, chicago
    //change to an object {charlottesville: picture, chicago: picture, nyc: picture }
    cityPics = ['http://az616578.vo.msecnd.net/files/2016/03/19/635939924999229260-1043665980_1400-charlottesville-va-downtown.imgcache.rev1409086909867.web.jpg', 'http://www.nationalgeographic.com/new-york-city-skyline-tallest-midtown-manhattan/assets/img/articleImg/01nyskyline1536.jpg','http://chicagoraffaello.com/wp-content/uploads/2013/08/chicago-skyline.jpg'];

    function whatPic(city){
        switch(city) {
            case 'charlottesville':
                return cityPics[0];
                break;
            case 'newyork':
                return cityPics[1];
                break;
            case 'chicago':
                return cityPics[2];
                break;
            default:
                return cityPics[0];
                break;
      }
    }

    //container for a location object
    var LocationModel = Backbone.Model.extend({});

    //basic view rendering a single location
    var LocationView = Backbone.View.extend({
        tagName: 'div',
        className: 'loc',
        render: function(){
            //just render the location name and region code of this object
            $(this.el).html(
                '
' + this.model.get("name") + ', ' + this.model.get("region_code") + '
' +
                ''
                );
            return this;
        }
    });

    //a collection holding many locations and responsible for performing the search that fetches them
    var LocationsCollection = Backbone.Collection.extend({
        model: LocationModel,
        url: 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/'

    });

    //rendering of a collection of locations
    var LocationsView = Backbone.View.extend({
        el: '#location',
        initialize: function(options){
            //Bind on initialize rather than rendering. reason we are binding versus rendering is because
            //we only want to bind to 'add' once.
            this.collection.bind("add", function(model){
                var locationView = new LocationView({
                    model: model
                });
            $(this.el).prepend(locationView.render().el);
            }, this);
        },
        render: function(){
            return this;
        }
    });

    //create a new assembly language repo collection
    var assemblyLocs = new LocationsCollection([], {
        language: "assembly"
    });

    //create a view that will contain the locations
    var assemblyLocsView = new LocationsView({
        collection: assemblyLocs
    });

    //Render the view regardless of the fact that it has not been fetched. This might need to change.
    $('#location').html(assemblyLocsView.render().el);

    //fetch the data from the server
    assemblyLocs.fetch();

});

//add MVC for hotels when a search is run
//regex /\d{4}-\d{2}-\d{2}/
//how to i get the ID from the bulk of hotels to call pickHotel??????

function hotelSearch(){

    var hotelsUrl = 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/' + city + '/hotels?checkin=' + checkin + '&checkout=' + checkout;
    var hotelsTemplate = $('#hotelsTemplate');
    var divClassName = 'hotels';

    /*
    else if (task == 'pickHotel'){
        var hotelsUrl = 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/' + id + '/hotels?checkin=' + checkin + '&checkout=' + checkout;
        var hotelsTemplate = $('#oneHotelTemplate');
        var divClassName = 'hotel';
    }
    */

    //hide the home title
    $('#hometitle').hide();

    //container for hotel model
    var HotelModel = Backbone.Model.extend({});

    //basic view for a single hotel
    var HotelView = Backbone.View.extend({
        tagName: "div",
        className: divClassName,
        template: hotelsTemplate.html(),
        render: function(){
            var tmpl = _.template(this.template);
            $(this.el).html(tmpl(this.model.toJSON()));

            return this;
        }
    });

    //a collection holding many hotels and responsible for performing the search that fetches them
    var HotelsCollection = Backbone.Collection.extend({
        model: HotelModel,
        url: hotelsUrl
    });

    //rendering of a collection of hotels
    var HotelsView = Backbone.View.extend({
        el: "#hotels",
        initialize: function(options){
            //Bind on initialize rather than rendering. reason we are binding versus rendering is because
            //we only want to bind to 'add' once.
            this.collection.bind("add", function(model){
                var hotelView = new HotelView({
                    model: model
                });
            $(this.el).prepend(hotelView.render().el);
            }, this);
        },
        render: function(){
            return this;
        }
    });

    var assemblyHotels = new HotelsCollection([],{
        language: "assembly"
    });

    var assemblyHotelsView = new HotelsView({
        collection: assemblyHotels
    });

    $('#hotels').html(assemblyHotelsView.render().el);

    //fetch the data from the server
    assemblyHotels.fetch();

}

function hotelInfo(){

    $('#hotels').empty();

    var hotelsUrl = 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/' + city + '/hotels/' + id + '?checkin=' + checkin + '&checkout=' + checkout;
    var hotelsTemplate = $('#oneHotelTemplate');
    var divClassName = 'hotel';

//container for hotel model
    var HotelModel = Backbone.Model.extend({
        url: 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/'
    });

    //basic view for a single hotel
    var HotelView = Backbone.View.extend({
        el: '#hotels',
        template: hotelsTemplate.html(),
        url: hotelsUrl,
        render: function(){
            var tmpl = _.template(this.template);
            $(this.el).html(tmpl(this.model.toJSON()));

            return this;
        }
    });

    var hotel = new HotelModel({ id: city + '/hotels/' + id + '?checkin=' + checkin + '&checkout=' + checkout});

    hotel.fetch();

}

//when user clicks search hotels in nav bar, everything is hidden except searchbox
$('#search').click(function(){
    $('#location').hide();
    $('#contactus').hide();
    $('#searchbox').show();

});

//when user clicks contact us in nav bar, everything is hidden except contact us form
$('#contact').click(function(){
    $('#location').hide();
    $('#searchbox').hide();
    $('#contactus').show();
});

//on submit button click, input values stored in variables, dates are validated, if valid hotelSearch function is called
//need to make the checkin checkout and city variables global
$('#submit').click(searchingHotel);

function searchingHotel(e){
    checkin = $('#checkin').val();
    checkout = $('#checkout').val();
    city = $('#selloc').val();

    if (!validateDate(checkin, checkout)){
        e.preventDefault();
    }
    else {

        $('select[name="location"]').val(city);
        $('input[name="checkin"]').val(checkin);
        $('input[name="checkout"]').val(checkout);
        hotelSearch('searchHotels');
    }
}

//function to validate the check in and out dates entered by user to make sure they are the correct format and the
//check out date is after the check in date
function validateDate(x, y) {
    //regex /\d{4}-\d{2}-\d{2}/
    //x is checkin
    //y is checkout
    var regex = /\d{4}-\d{2}-\d{2}/;

    var xYear = x.slice(0,4);
    var xMonth = x.slice(5,7);
    var xDay = x.slice(8,10);

    var yYear = y.slice(0,4);
    var yMonth = y.slice(5,7);
    var yDay = y.slice(8,10);

    if (!regex.test(x)) {
        alert('Invalid Date');
        return false;
    }
    if (!regex.test(y)) {
        alert('Invalid Date');
        return false;
    }
    if (yYear > xYear) {
        return true;
    }
    else {
        if (yMonth > xMonth){
            return true;
        }
        else {
            if (yDay > xDay){
                return true;
            }
            else {
                alert("Invalid Date Range");
                return false;
            }
        }
    }

}

function storeId(hotelId){
    id = hotelId;
    hotelInfo();

}<commit_msg>single hotel works<commit_after>//form variables
var city = '';
var checkin = '';
var checkout = '';
var id = '';

//when the search cities nav link is clicked, the cities are loaded
$('#cities').click(function(){

    $('#searchbox').hide();
    $('#contactus').hide();
    $('#location').show();

    //charlottesville, nyc, chicago
    //change to an object {charlottesville: picture, chicago: picture, nyc: picture }
    cityPics = ['http://az616578.vo.msecnd.net/files/2016/03/19/635939924999229260-1043665980_1400-charlottesville-va-downtown.imgcache.rev1409086909867.web.jpg', 'http://www.nationalgeographic.com/new-york-city-skyline-tallest-midtown-manhattan/assets/img/articleImg/01nyskyline1536.jpg','http://chicagoraffaello.com/wp-content/uploads/2013/08/chicago-skyline.jpg'];

    function whatPic(city){
        switch(city) {
            case 'charlottesville':
                return cityPics[0];
                break;
            case 'newyork':
                return cityPics[1];
                break;
            case 'chicago':
                return cityPics[2];
                break;
            default:
                return cityPics[0];
                break;
      }
    }

    //container for a location object
    var LocationModel = Backbone.Model.extend({});

    //basic view rendering a single location
    var LocationView = Backbone.View.extend({
        tagName: 'div',
        className: 'loc',
        render: function(){
            //just render the location name and region code of this object
            $(this.el).html(
                '
' + this.model.get("name") + ', ' + this.model.get("region_code") + '
' +
                ''
                );
            return this;
        }
    });

    //a collection holding many locations and responsible for performing the search that fetches them
    var LocationsCollection = Backbone.Collection.extend({
        model: LocationModel,
        url: 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/'

    });

    //rendering of a collection of locations
    var LocationsView = Backbone.View.extend({
        el: '#location',
        initialize: function(options){
            //Bind on initialize rather than rendering. reason we are binding versus rendering is because
            //we only want to bind to 'add' once.
            this.collection.bind("add", function(model){
                var locationView = new LocationView({
                    model: model
                });
            $(this.el).prepend(locationView.render().el);
            }, this);
        },
        render: function(){
            return this;
        }
    });

    //create a new assembly language repo collection
    var assemblyLocs = new LocationsCollection([], {
        language: "assembly"
    });

    //create a view that will contain the locations
    var assemblyLocsView = new LocationsView({
        collection: assemblyLocs
    });

    //Render the view regardless of the fact that it has not been fetched. This might need to change.
    $('#location').html(assemblyLocsView.render().el);

    //fetch the data from the server
    assemblyLocs.fetch();

});

//add MVC for hotels when a search is run
//regex /\d{4}-\d{2}-\d{2}/
//how to i get the ID from the bulk of hotels to call pickHotel??????

function hotelSearch(){

    var hotelsUrl = 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/' + city + '/hotels?checkin=' + checkin + '&checkout=' + checkout;
    var hotelsTemplate = $('#hotelsTemplate');
    var divClassName = 'hotels';

    /*
    else if (task == 'pickHotel'){
        var hotelsUrl = 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/' + id + '/hotels?checkin=' + checkin + '&checkout=' + checkout;
        var hotelsTemplate = $('#oneHotelTemplate');
        var divClassName = 'hotel';
    }
    */

    //hide the home title
    $('#hometitle').hide();

    //container for hotel model
    var HotelModel = Backbone.Model.extend({});

    //basic view for a single hotel
    var HotelView = Backbone.View.extend({
        tagName: "div",
        className: divClassName,
        template: hotelsTemplate.html(),
        render: function(){
            var tmpl = _.template(this.template);
            $(this.el).html(tmpl(this.model.toJSON()));

            return this;
        }
    });

    //a collection holding many hotels and responsible for performing the search that fetches them
    var HotelsCollection = Backbone.Collection.extend({
        model: HotelModel,
        url: hotelsUrl
    });

    //rendering of a collection of hotels
    var HotelsView = Backbone.View.extend({
        el: "#hotels",
        initialize: function(options){
            //Bind on initialize rather than rendering. reason we are binding versus rendering is because
            //we only want to bind to 'add' once.
            this.collection.bind("add", function(model){
                var hotelView = new HotelView({
                    model: model
                });
            $(this.el).prepend(hotelView.render().el);
            }, this);
        },
        render: function(){
            return this;
        }
    });

    var assemblyHotels = new HotelsCollection([],{
        language: "assembly"
    });

    var assemblyHotelsView = new HotelsView({
        collection: assemblyHotels
    });

    $('#hotels').html(assemblyHotelsView.render().el);

    //fetch the data from the server
    assemblyHotels.fetch();

}

function hotelInfo(){

    $('#hotels').empty();

    var hotelsUrl = 'https://roomkey-frontend-project-ajboyle.c9users.io/api/locations/' + city + '/hotels/' + id + '?checkin=' + checkin + '&checkout=' + checkout;
    var hotelsTemplate = $('#oneHotelTemplate');
    var divClassName = 'hotel';

    //container for hotel model
    var HotelModel = Backbone.Model.extend({});

    //basic view for a single hotel
    var HotelView = Backbone.View.extend({
        tagName: "div",
        className: divClassName,
        template: hotelsTemplate.html(),
        render: function(){
            var tmpl = _.template(this.template);
            $(this.el).html(tmpl(this.model.toJSON()));

            return this;
        }
    });

    //a collection holding many hotels and responsible for performing the search that fetches them
    var HotelsCollection = Backbone.Collection.extend({
        model: HotelModel,
        url: hotelsUrl
    });

    //rendering of a collection of hotels
    var HotelsView = Backbone.View.extend({
        el: "#hotels",
        initialize: function(options){
            //Bind on initialize rather than rendering. reason we are binding versus rendering is because
            //we only want to bind to 'add' once.
            this.collection.bind("add", function(model){
                var hotelView = new HotelView({
                    model: model
                });
            $(this.el).prepend(hotelView.render().el);
            }, this);
        },
        render: function(){
            return this;
        }
    });

    var assemblyHotels = new HotelsCollection([],{
        language: "assembly"
    });

    var assemblyHotelsView = new HotelsView({
        collection: assemblyHotels
    });

    $('#hotels').html(assemblyHotelsView.render().el);

    //fetch the data from the server
    assemblyHotels.fetch();

}

//when user clicks search hotels in nav bar, everything is hidden except searchbox
$('#search').click(function(){
    $('#location').hide();
    $('#contactus').hide();
    $('#searchbox').show();

});

//when user clicks contact us in nav bar, everything is hidden except contact us form
$('#contact').click(function(){
    $('#location').hide();
    $('#searchbox').hide();
    $('#contactus').show();
});

//on submit button click, input values stored in variables, dates are validated, if valid hotelSearch function is called
//need to make the checkin checkout and city variables global
$('#submit').click(searchingHotel);

function searchingHotel(e){
    checkin = $('#checkin').val();
    checkout = $('#checkout').val();
    city = $('#selloc').val();

    if (!validateDate(checkin, checkout)){
        e.preventDefault();
    }
    else {

        $('select[name="location"]').val(city);
        $('input[name="checkin"]').val(checkin);
        $('input[name="checkout"]').val(checkout);
        hotelSearch('searchHotels');
    }
}

//function to validate the check in and out dates entered by user to make sure they are the correct format and the
//check out date is after the check in date
function validateDate(x, y) {
    //regex /\d{4}-\d{2}-\d{2}/
    //x is checkin
    //y is checkout
    var regex = /\d{4}-\d{2}-\d{2}/;

    var xYear = x.slice(0,4);
    var xMonth = x.slice(5,7);
    var xDay = x.slice(8,10);

    var yYear = y.slice(0,4);
    var yMonth = y.slice(5,7);
    var yDay = y.slice(8,10);

    if (!regex.test(x)) {
        alert('Invalid Date');
        return false;
    }
    if (!regex.test(y)) {
        alert('Invalid Date');
        return false;
    }
    if (yYear > xYear) {
        return true;
    }
    else {
        if (yMonth > xMonth){
            return true;
        }
        else {
            if (yDay > xDay){
                return true;
            }
            else {
                alert("Invalid Date Range");
                return false;
            }
        }
    }

}

function storeId(hotelId){
    id = hotelId;
    hotelInfo();

}<|endoftext|>


<commit_before>scoreGame = function (game) {
  //most cards
  //most coins
  //seven of coins
  //primera
  //scopa

  game.players[game.lastScorer].pile.push.apply(game.players[game.lastScorer].pile, game.table);
  game.table = []  ;
  game.inProgress = false;
  game.finished = new Date();

  var mostCards = ['x', -1],
      mostCoins = ['x', -1],
      highestPrimera = ['x', -1];

  Object.keys(game.players).forEach(function (id) {
    var cardCount = game.players[id].pile.length;
    if (cardCount > mostCards[1]) {
      mostCards = [id, cardCount];
    } else if (cardCount === mostCards[1]) {
      mostCards = false;
    }

    if(hasSetteBello(pile)) {
      game.players[id].score.SetteBello = 1;
    }

    var primera = getPrimera(pile);
    if (primera > highestPrimera[1]) {
      highestPrimera = [id, primera];
    } else if (primera === highestPrimera[1]) {
      highestPrimera = false;
    }

  });

  if (mostCards) game.players[mostCards[0]].score.mostCards = 1;
  if (mostCoins) game.players[mostCoins[0]].score.mostCoins = 1;
  if (highestPrimera) game.players[highestPrimera[0]].score.primera = 1;

  var highest = ['x', -1];

  Object.keys(game.players).forEach(function (id) {
    var s = game.players[id].score;

    game.players[id].score.total = s.mostCards + s.mostCoins + s.primera + s.setteBello + s.scopa;

    if ( game.players[id].score.total > highest [1]) {
      highest = [id, game.players[id].score.total];
    } else if (game.players[id].score.total === highest[1]) {
      highest = false;
    }
  });

  game.winner = highest ? highest[0] : "tie";
};

var primeraPoints = {
 '7': 21,
 '6': 18,
 '1': 16,
 '5': 15,
 '4': 14,
 '3': 13,
 '2': 12,
 '10': 10,
 '8': 0,
 '9': 0
};

function getPrimera(set){
  var cards = [suit('Coins', set), suit('Cups', set), suit("Clubs", set), suit('Swords', set)];

  return cards.map(function (suit) {
    return suit.map( function (card) {
      return primeraPoints[card.value];
    }).sort(function (a, b) { return b - a; })[0];
  }).reduce(function (a, b) {
    return a + b;
  });
}

function hasSetteBello(set) {
  return _.some(set, function (card) {
    return card.suit === 'Coins' && card.value === 7;
  });
}

function suit(suit, cards) {
  return cards.filter(function (card) {
    return card.suit === suit;
  });
} <commit_msg>Minor fix and refactor gameScoring.js<commit_after>scoreGame = function (game) {
  //most cards
  //most coins
  //seven of coins
  //primera
  //scopa

  game.players[game.lastScorer].pile.push.apply(game.players[game.lastScorer].pile, game.table);
  game.table = [];
  game.inProgress = false;
  game.finished = new Date();

  var mostCards = ['x', -1],
      mostCoins = ['x', -1],
      highestPrimera = ['x', -1];

  Object.keys(game.players).forEach(function (id) {
    var pile = game.players[id].pile

    var cardCount = pile.length;
    if (cardCount > mostCards[1]) {
      mostCards = [id, cardCount];
    } else if (cardCount === mostCards[1]) {
      mostCards = false;
    }

    if(hasSetteBello(pile)) {
      game.players[id].score.SetteBello = 1;
    }

    var primera = getPrimera(pile);
    if (primera > highestPrimera[1]) {
      highestPrimera = [id, primera];
    } else if (primera === highestPrimera[1]) {
      highestPrimera = false;
    }

  });

  if (mostCards) game.players[mostCards[0]].score.mostCards = 1;
  if (mostCoins) game.players[mostCoins[0]].score.mostCoins = 1;
  if (highestPrimera) game.players[highestPrimera[0]].score.primera = 1;

  var highest = ['x', -1];

  Object.keys(game.players).forEach(function (id) {
    var s = game.players[id].score;

    game.players[id].score.total = s.mostCards + s.mostCoins + s.primera + s.setteBello + s.scopa;

    if ( game.players[id].score.total > highest [1]) {
      highest = [id, game.players[id].score.total];
    } else if (game.players[id].score.total === highest[1]) {
      highest = false;
    }
  });

  game.winner = highest ? highest[0] : "tie";
};

var primeraPoints = {
 '7': 21,
 '6': 18,
 '1': 16,
 '5': 15,
 '4': 14,
 '3': 13,
 '2': 12,
 '10': 10,
 '8': 0,
 '9': 0
};

function getPrimera(set){
  var cards = [suit('Coins', set), suit('Cups', set), suit("Clubs", set), suit('Swords', set)];

  return cards.map(function (suit) {
    return suit.map( function (card) {
      return primeraPoints[card.value];
    }).sort(function (a, b) { return b - a; })[0];
  }).reduce(function (a, b) {
    return a + b;
  });
}

function hasSetteBello(set) {
  return _.some(set, function (card) {
    return card.suit === 'Coins' && card.value === 7;
  });
}

function suit(suit, cards) {
  return cards.filter(function (card) {
    return card.suit === suit;
  });
} <|endoftext|>


<commit_before>const _ = require('lodash')

// graphql function returns a promise so we can use this little promise helper to have a nice result/error state
const wrapper = promise =>
  promise
    .then(result => {
      if (result.errors) {
        throw result.errors
      }
      return { result, error: null }
    })
    .catch(error => ({ error, result: null }))

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  let slug
  // Only use MDX nodes
  if (node.internal.type === 'Mdx') {
    const fileNode = getNode(node.parent)
    // If the frontmatter contains a "slug", use it
    if (
      Object.prototype.hasOwnProperty.call(node, 'frontmatter') &&
      Object.prototype.hasOwnProperty.call(node.frontmatter, 'slug')
    ) {
      slug = `/${_.kebabCase(node.frontmatter.slug)}`
    }
    // Otherwise use the title for the slug
    if (
      Object.prototype.hasOwnProperty.call(node, 'frontmatter') &&
      Object.prototype.hasOwnProperty.call(node.frontmatter, 'title')
    ) {
      slug = `/${_.kebabCase(node.frontmatter.title)}`
    }
    createNodeField({ node, name: 'slug', value: slug })
    // Adds the name of "gatsby-source-filesystem" as field (in this case "projects" or "pages")
    createNodeField({ node, name: 'sourceInstanceName', value: fileNode.sourceInstanceName })
  }
}

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  // Our templates for projects and files inside /pages/*.mdx
  const projectPage = require.resolve('./src/templates/project.jsx')
  const singlePage = require.resolve('./src/templates/single.jsx')

  const { error, result } = await wrapper(
    graphql(`
      {
        projects: allMdx(filter: { fields: { sourceInstanceName: { eq: "projects" } } }) {
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
        single: allMdx(filter: { fields: { sourceInstanceName: { eq: "pages" } } }) {
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
      }
    `)
  )

  if (!error) {
    result.data.projects.edges.forEach(edge => {
      createPage({
        path: edge.node.fields.slug,
        component: projectPage,
        context: {
          // Pass "slug" through context so we can reference it in our query like "$slug: String!"
          slug: edge.node.fields.slug,
        },
      })
    })
    result.data.single.edges.forEach(edge => {
      createPage({
        path: edge.node.fields.slug,
        component: singlePage,
        context: {
          slug: edge.node.fields.slug,
        },
      })
    })
    return
  }

  console.log(error)
}

// Necessary changes to get gatsby-mdx and Cypress working
exports.onCreateWebpackConfig = ({ stage, actions, loaders, getConfig }) => {
  const config = getConfig()

  config.module.rules = [
    ...config.module.rules.filter(rule => String(rule.test) !== String(/\.jsx?$/)),
    {
      ...loaders.js(),
      test: /\.jsx?$/,
      exclude: modulePath => /node_modules/.test(modulePath) && !/node_modules\/gatsby-mdx/.test(modulePath),
    },
  ]

  actions.replaceWebpackConfig(config)
}
<commit_msg>use simplified promise wrapper<commit_after>const _ = require('lodash')

// graphql function doesn't throw an error so we have to check to check for the result.errors to throw manually
const wrapper = promise =>
  promise.then(result => {
    if (result.errors) {
      throw result.errors
    }
    return result
  })

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  let slug
  // Only use MDX nodes
  if (node.internal.type === 'Mdx') {
    const fileNode = getNode(node.parent)
    // If the frontmatter contains a "slug", use it
    if (
      Object.prototype.hasOwnProperty.call(node, 'frontmatter') &&
      Object.prototype.hasOwnProperty.call(node.frontmatter, 'slug')
    ) {
      slug = `/${_.kebabCase(node.frontmatter.slug)}`
    }
    // Otherwise use the title for the slug
    if (
      Object.prototype.hasOwnProperty.call(node, 'frontmatter') &&
      Object.prototype.hasOwnProperty.call(node.frontmatter, 'title')
    ) {
      slug = `/${_.kebabCase(node.frontmatter.title)}`
    }
    createNodeField({ node, name: 'slug', value: slug })
    // Adds the name of "gatsby-source-filesystem" as field (in this case "projects" or "pages")
    createNodeField({ node, name: 'sourceInstanceName', value: fileNode.sourceInstanceName })
  }
}

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  // Our templates for projects and files inside /pages/*.mdx
  const projectPage = require.resolve('./src/templates/project.jsx')
  const singlePage = require.resolve('./src/templates/single.jsx')

  const result = await wrapper(
    graphql(`
      {
        projects: allMdx(filter: { fields: { sourceInstanceName: { eq: "projects" } } }) {
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
        single: allMdx(filter: { fields: { sourceInstanceName: { eq: "pages" } } }) {
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
      }
    `)
  )

  result.data.projects.edges.forEach(edge => {
    createPage({
      path: edge.node.fields.slug,
      component: projectPage,
      context: {
        // Pass "slug" through context so we can reference it in our query like "$slug: String!"
        slug: edge.node.fields.slug,
      },
    })
  })
  result.data.single.edges.forEach(edge => {
    createPage({
      path: edge.node.fields.slug,
      component: singlePage,
      context: {
        slug: edge.node.fields.slug,
      },
    })
  })
}

// Necessary changes to get gatsby-mdx and Cypress working
exports.onCreateWebpackConfig = ({ stage, actions, loaders, getConfig }) => {
  const config = getConfig()

  config.module.rules = [
    ...config.module.rules.filter(rule => String(rule.test) !== String(/\.jsx?$/)),
    {
      ...loaders.js(),
      test: /\.jsx?$/,
      exclude: modulePath => /node_modules/.test(modulePath) && !/node_modules\/gatsby-mdx/.test(modulePath),
    },
  ]

  actions.replaceWebpackConfig(config)
}
<|endoftext|>


<commit_before>var stage = new createjs.Stage("trafficCanvas");

function getAnimatorSelfInstance(currentThis) {
  var self = undefined;

  if (currentThis.animator != undefined) {
    self = currentThis.animator; // currentThis references Window object
  } else {
    self = currentThis; // currentThis is the animator instance as needed
  }

  return self;
}

function Animator() {
  var self = getAnimatorSelfInstance(this);

  self.TOPOLOGY_RADIUS = 200;
  self.TOPOLOGY_CENTER_X = 470;
  self.TOPOLOGY_CENTER_Y = 250;
  self.TOPOLOGY_WIDTH = 940;
  self.TOPOLOGY_HEIGHT = 500;
  self.REDRAW_FREQUENCY = 1000;

  self._nodesClassC = new Array();
  self._nodesExternal = new Array();
  self._redrawInterval = 0;

  createjs.Ticker.setFPS(60);
  createjs.Ticker.addEventListener("tick", stage);

  self._drawRouter();

  if( self._redrawInterval > 0 ) clearInterval(self._redrawInterval);
  self._redrawInterval = setInterval(self._redrawNodes, self.REDRAW_FREQUENCY);
}

Animator.prototype.addNode = function(ip) {
  var self = getAnimatorSelfInstance(this);

  if (self._isClassC(ip) && !(ip in self._nodesClassC)) {
    var circle = new createjs.Shape();
    circle.graphics.beginFill("DeepSkyBlue").drawCircle(0, 0, 25);
    stage.addChild(circle);
    self._nodesClassC[ip] = {graphic: circle, x: 0, y: 0};
    self._redrawNodes();
  } else {
    self._nodesExternal[ip] = ip;
  }
};

Animator.prototype.update = function() {
  var self = getAnimatorSelfInstance(this);
  var arg = arguments[0];

  // If arg.add is present, we are being notified of a new network node
  //   we should add to our canvas.
  // If arg.traffic is present, we are being notified to visualize traffic.
  if (arg.add != undefined) {
    var node = arg.add;
    self.addNode(node.getIP());
  } else if (arg.traffic != undefined) {
    var traffic = arg.traffic;
    self.displayTraffic(traffic.getSourceIP(), traffic.getDestinationIP());
  }
};

Animator.prototype.displayTraffic = function(sourceAddr, destAddr) {
  var self = getAnimatorSelfInstance(this);
  var originX = 0, originY = 0;
  var destX = 0, destY = 0;

  /* Calculate origin and destination x,y coordinates */
  if (sourceAddr in self._nodesClassC) {
    originX = self._nodesClassC[sourceAddr].x;
    originY = self._nodesClassC[sourceAddr].y;
    console.log("From: ", originX, originY);
  } else {
    originX = self.TOPOLOGY_WIDTH / 2;
    originY = self.TOPOLOGY_HEIGHT / 2;
  }

  if (destAddr in self._nodesClassC) {
    destX = self._nodesClassC[destAddr].x;
    destY = self._nodesClassC[destAddr].y;
    console.log("To: ", destX, destY);
  } else {
    destX = self.TOPOLOGY_WIDTH / 2;
    destY = self.TOPOLOGY_HEIGHT / 2;;
  }

  /* Draw laser */
  var beam = new createjs.Shape();
  beam.graphics.beginFill("red");
  beam.graphics.moveTo(0, 1.5).lineTo(70, 0).lineTo(70, 3).closePath();
  beam.x = originX;
  beam.y = originY;
  beam.setBounds(0,0,70,3);
  beam.rotation = self._getTrafficRotation(originX, destX, originY, destY);

  stage.addChildAt(beam, 0);

  createjs.Tween.get(beam, {loop: false, onChange: self._beamUpdate})
    .to({x: destX, y: destY, alpha: 0.25}, 1500, createjs.Ease.linear)
    .call(self._beamComplete);
};

Animator.prototype._beamUpdate = function(e) {
  var self = getAnimatorSelfInstance(this);
  var beam = e.currentTarget.target;
  var targetX = e.currentTarget._curQueueProps.x;

  // Make the beam grow smaller when target reached
  // * Needs updated
  /*if( targetX - beam.x < beam.getBounds().width ) {
    //beam.scaleX = (targetX - beam.x) / targetX;
  } else {
    //beam.scaleX = 1;
  }*/
};

Animator.prototype._beamComplete = function(e) {
  var self = getAnimatorSelfInstance(this);
  var beam = e.target;
  stage.removeChild(beam);
};

Animator.prototype._findSlope = function(x1, x2, y1, y2) {
  if (x1 == x2) {
    return 0;
  } else {
    return (y2 - y1) / (x2 - x1);
  }
};

Animator.prototype._slopeToDegrees = function(slope) {
  // slope to angle to degrees
  return Math.atan(slope) * (180/Math.PI);
};

Animator.prototype._isClassC = function(ip) {
  var firstOctet = Number(ip.substring(0,3));

  if (firstOctet >= 192 && firstOctet <= 223) {
    return true;
  } else {
    return false;
  }
};

Animator.prototype._redrawNodes = function() {
  var self = getAnimatorSelfInstance(this);
  var totalNodes = Object.keys(self._nodesClassC).length;
  var current = 0;
  var step = (Math.PI * 2) / totalNodes;

  for ( var node in self._nodesClassC ) {
    nodeGraphic = self._nodesClassC[node].graphic;
    var newX = self.TOPOLOGY_CENTER_X + self.TOPOLOGY_RADIUS * Math.cos(current);
    var newY = self.TOPOLOGY_CENTER_Y + self.TOPOLOGY_RADIUS * Math.sin(current);
    createjs.Tween.get(nodeGraphic, {loop: false})
      .to({x: newX, y: newY}, 500, createjs.Ease.linear);

    self._nodesClassC[node].x = newX;
    self._nodesClassC[node].y = newY;
    current += step;
  }
};

Animator.prototype._drawRouter = function() {
  var self = getAnimatorSelfInstance(this);
  var router = new createjs.Shape();
  router.graphics.beginFill("Black")
    .drawCircle(self.TOPOLOGY_CENTER_X, self.TOPOLOGY_CENTER_Y, 12);
  stage.addChild(router);
};

Animator.prototype._getTrafficRotation = function(originX, destX, originY, destY) {
  var self = getAnimatorSelfInstance(this);
  var rotation = self._slopeToDegrees(
    self._findSlope(originX, destX, originY, destY)
  );

  if (destX < originX) {
    rotation += 180;
  } else if (destX == originX) {
    if (destY < originY) {
      rotation -= 90;
    } else {
      rotation += 90;
    }
  }

  return rotation;
}
<commit_msg>* Removed unnecessary logs.<commit_after>var stage = new createjs.Stage("trafficCanvas");

function getAnimatorSelfInstance(currentThis) {
  var self = undefined;

  if (currentThis.animator != undefined) {
    self = currentThis.animator; // currentThis references Window object
  } else {
    self = currentThis; // currentThis is the animator instance as needed
  }

  return self;
}

function Animator() {
  var self = getAnimatorSelfInstance(this);

  self.TOPOLOGY_RADIUS = 200;
  self.TOPOLOGY_CENTER_X = 470;
  self.TOPOLOGY_CENTER_Y = 250;
  self.TOPOLOGY_WIDTH = 940;
  self.TOPOLOGY_HEIGHT = 500;
  self.REDRAW_FREQUENCY = 1000;

  self._nodesClassC = new Array();
  self._nodesExternal = new Array();
  self._redrawInterval = 0;

  createjs.Ticker.setFPS(60);
  createjs.Ticker.addEventListener("tick", stage);

  self._drawRouter();

  if( self._redrawInterval > 0 ) clearInterval(self._redrawInterval);
  self._redrawInterval = setInterval(self._redrawNodes, self.REDRAW_FREQUENCY);
}

Animator.prototype.addNode = function(ip) {
  var self = getAnimatorSelfInstance(this);

  if (self._isClassC(ip) && !(ip in self._nodesClassC)) {
    var circle = new createjs.Shape();
    circle.graphics.beginFill("DeepSkyBlue").drawCircle(0, 0, 25);
    stage.addChild(circle);
    self._nodesClassC[ip] = {graphic: circle, x: 0, y: 0};
    self._redrawNodes();
  } else {
    self._nodesExternal[ip] = ip;
  }
};

Animator.prototype.update = function() {
  var self = getAnimatorSelfInstance(this);
  var arg = arguments[0];

  // If arg.add is present, we are being notified of a new network node
  //   we should add to our canvas.
  // If arg.traffic is present, we are being notified to visualize traffic.
  if (arg.add != undefined) {
    var node = arg.add;
    self.addNode(node.getIP());
  } else if (arg.traffic != undefined) {
    var traffic = arg.traffic;
    self.displayTraffic(traffic.getSourceIP(), traffic.getDestinationIP());
  }
};

Animator.prototype.displayTraffic = function(sourceAddr, destAddr) {
  var self = getAnimatorSelfInstance(this);
  var originX = 0, originY = 0;
  var destX = 0, destY = 0;

  /* Calculate origin and destination x,y coordinates */
  if (sourceAddr in self._nodesClassC) {
    originX = self._nodesClassC[sourceAddr].x;
    originY = self._nodesClassC[sourceAddr].y;
  } else {
    originX = self.TOPOLOGY_WIDTH / 2;
    originY = self.TOPOLOGY_HEIGHT / 2;
  }

  if (destAddr in self._nodesClassC) {
    destX = self._nodesClassC[destAddr].x;
    destY = self._nodesClassC[destAddr].y;
  } else {
    destX = self.TOPOLOGY_WIDTH / 2;
    destY = self.TOPOLOGY_HEIGHT / 2;;
  }

  /* Draw laser */
  var beam = new createjs.Shape();
  beam.graphics.beginFill("red");
  beam.graphics.moveTo(0, 1.5).lineTo(70, 0).lineTo(70, 3).closePath();
  beam.x = originX;
  beam.y = originY;
  beam.setBounds(0,0,70,3);
  beam.rotation = self._getTrafficRotation(originX, destX, originY, destY);

  stage.addChildAt(beam, 0);

  createjs.Tween.get(beam, {loop: false, onChange: self._beamUpdate})
    .to({x: destX, y: destY, alpha: 0.25}, 1500, createjs.Ease.linear)
    .call(self._beamComplete);
};

Animator.prototype._beamUpdate = function(e) {
  var self = getAnimatorSelfInstance(this);
  var beam = e.currentTarget.target;
  var targetX = e.currentTarget._curQueueProps.x;

  // Make the beam grow smaller when target reached
  // * Needs updated
  /*if( targetX - beam.x < beam.getBounds().width ) {
    //beam.scaleX = (targetX - beam.x) / targetX;
  } else {
    //beam.scaleX = 1;
  }*/
};

Animator.prototype._beamComplete = function(e) {
  var self = getAnimatorSelfInstance(this);
  var beam = e.target;
  stage.removeChild(beam);
};

Animator.prototype._findSlope = function(x1, x2, y1, y2) {
  if (x1 == x2) {
    return 0;
  } else {
    return (y2 - y1) / (x2 - x1);
  }
};

Animator.prototype._slopeToDegrees = function(slope) {
  // slope to angle to degrees
  return Math.atan(slope) * (180/Math.PI);
};

Animator.prototype._isClassC = function(ip) {
  var firstOctet = Number(ip.substring(0,3));

  if (firstOctet >= 192 && firstOctet <= 223) {
    return true;
  } else {
    return false;
  }
};

Animator.prototype._redrawNodes = function() {
  var self = getAnimatorSelfInstance(this);
  var totalNodes = Object.keys(self._nodesClassC).length;
  var current = 0;
  var step = (Math.PI * 2) / totalNodes;

  for ( var node in self._nodesClassC ) {
    nodeGraphic = self._nodesClassC[node].graphic;
    var newX = self.TOPOLOGY_CENTER_X + self.TOPOLOGY_RADIUS * Math.cos(current);
    var newY = self.TOPOLOGY_CENTER_Y + self.TOPOLOGY_RADIUS * Math.sin(current);
    createjs.Tween.get(nodeGraphic, {loop: false})
      .to({x: newX, y: newY}, 500, createjs.Ease.linear);

    self._nodesClassC[node].x = newX;
    self._nodesClassC[node].y = newY;
    current += step;
  }
};

Animator.prototype._drawRouter = function() {
  var self = getAnimatorSelfInstance(this);
  var router = new createjs.Shape();
  router.graphics.beginFill("Black")
    .drawCircle(self.TOPOLOGY_CENTER_X, self.TOPOLOGY_CENTER_Y, 12);
  stage.addChild(router);
};

Animator.prototype._getTrafficRotation = function(originX, destX, originY, destY) {
  var self = getAnimatorSelfInstance(this);
  var rotation = self._slopeToDegrees(
    self._findSlope(originX, destX, originY, destY)
  );

  if (destX < originX) {
    rotation += 180;
  } else if (destX == originX) {
    if (destY < originY) {
      rotation -= 90;
    } else {
      rotation += 90;
    }
  }

  return rotation;
}
<|endoftext|>


<commit_before>function parseData(data) {
    var result = $.parseJSON(data.file_data);
    return generateDataArray(result.results);
}

function parseDate(str) {
    var year = str.substr(0,4),
        month = str.substr(4,2) - 1,
        day = str.substr(6,2);
    var date = Date.UTC(year,month,day);
    return date;
}

function dateArray(resultObj) {
    return _.map(resultObj, function(item) {
        return parseDate(item.time);
    });
}

function valueArray(resultObj) {
    return _.map(resultObj, function(item) {
        return item.count;
    });
}

function generateDataArray(resultObj) {
    var dates = dateArray(resultObj);
    var counts = valueArray(resultObj);
    return _.zip(dates, counts);
}

function addSeries(dataArray, query, visibility) {
    var chart = $('#container').highcharts();

    chart.addSeries({
        name: query,
        data: dataArray,
        visible: visibility
    });

    if (visibility) {
        if (chart.title) {
            chart.setTitle({text: chart.title.textStr + " vs. " + query});
        } else {
            chart.setTitle({text: "FDA Recalls: " + query});
        }
    }
}

function clearGraph() {
    var chart = $('#container').highcharts();
    while( chart.series.length > 0 ) {
        chart.series[0].remove( false );
    }
    chart.setTitle({text: ''});
    chart.redraw();
}

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

function leastSquaresRegression(dataArray) {
    var yValues = _.map(dataArray, function(item) { return item[1] } );
    var xValues =  _.map(dataArray, function(item) { return item[0] } );
    var length = yValues.length;
    var xIndices = _.range(1, length+1);

    var sumX = _.reduce(xIndices, function(sum, num){ return sum + num; }, 0);
    var sumY = _.reduce(yValues, function(sum, num){ return sum + num; }, 0);
    var sumXY = _.reduce([xIndices, yValues], function(sum, pair){ return sum + (pair[0]*pair[1]); }, 0);
    var sumX2 = _.reduce(xIndices, function(sum, num){ return sum + (num*num); }, 0);

    // y = mx + b
    var slope = ((length * sumXY) - (sumX * sumY)) / ((length * sumX2) - (sumX * sumX));
    var intercept = (sumY / length) - ((slope * sumX) / length);

    var initialY = (slope*_.first(xIndices)) + intercept;
    var finalY = (slope*_.last(xIndices)) + intercept;

    return [[_.first(xValues), finalY], [_.last(xValues), initialY]];
}

function graph(dataArray, query, startDate) {
    $(function () {
        $('#container').highcharts({
            chart: {
                zoomType: 'x'
            },
            xAxis: {
                type: 'datetime',
                minRange: 30 * 24 * 3600000,

                title: {
                    text: 'Date'
                }
            },
            yAxis: {
                title: {
                    text: 'Number of Recalls'
                },
                min: 0
            },
            title: {
                text: "FDA Recalls: " + query
            },
            tooltip: {
                headerFormat: '{series.name}
',
                pointFormat: '{point.x:%e %b %y}: {point.y:.2f}'
            },
            plotOptions: {
                series: {
                    marker: {
                        radius: 3
                    }
                }
            },
            series: [{
                name: query,
                data: dataArray
            }]
        });
    });
}

<commit_msg>deployment config<commit_after>function parseData(data) {
    var result = $.parseJSON(data.results);
    return generateDataArray(result.results);
}

function parseDate(str) {
    var year = str.substr(0,4),
        month = str.substr(4,2) - 1,
        day = str.substr(6,2);
    var date = Date.UTC(year,month,day);
    return date;
}

function dateArray(resultObj) {
    return _.map(resultObj, function(item) {
        return parseDate(item.time);
    });
}

function valueArray(resultObj) {
    return _.map(resultObj, function(item) {
        return item.count;
    });
}

function generateDataArray(resultObj) {
    var dates = dateArray(resultObj);
    var counts = valueArray(resultObj);
    return _.zip(dates, counts);
}

function addSeries(dataArray, query, visibility) {
    var chart = $('#container').highcharts();

    chart.addSeries({
        name: query,
        data: dataArray,
        visible: visibility
    });

    if (visibility) {
        if (chart.title) {
            chart.setTitle({text: chart.title.textStr + " vs. " + query});
        } else {
            chart.setTitle({text: "FDA Recalls: " + query});
        }
    }
}

function clearGraph() {
    var chart = $('#container').highcharts();
    while( chart.series.length > 0 ) {
        chart.series[0].remove( false );
    }
    chart.setTitle({text: ''});
    chart.redraw();
}

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

function leastSquaresRegression(dataArray) {
    var yValues = _.map(dataArray, function(item) { return item[1] } );
    var xValues =  _.map(dataArray, function(item) { return item[0] } );
    var length = yValues.length;
    var xIndices = _.range(1, length+1);

    var sumX = _.reduce(xIndices, function(sum, num){ return sum + num; }, 0);
    var sumY = _.reduce(yValues, function(sum, num){ return sum + num; }, 0);
    var sumXY = _.reduce([xIndices, yValues], function(sum, pair){ return sum + (pair[0]*pair[1]); }, 0);
    var sumX2 = _.reduce(xIndices, function(sum, num){ return sum + (num*num); }, 0);

    // y = mx + b
    var slope = ((length * sumXY) - (sumX * sumY)) / ((length * sumX2) - (sumX * sumX));
    var intercept = (sumY / length) - ((slope * sumX) / length);

    var initialY = (slope*_.first(xIndices)) + intercept;
    var finalY = (slope*_.last(xIndices)) + intercept;

    return [[_.first(xValues), finalY], [_.last(xValues), initialY]];
}

function graph(dataArray, query, startDate) {
    $(function () {
        $('#container').highcharts({
            chart: {
                zoomType: 'x'
            },
            xAxis: {
                type: 'datetime',
                minRange: 30 * 24 * 3600000,

                title: {
                    text: 'Date'
                }
            },
            yAxis: {
                title: {
                    text: 'Number of Recalls'
                },
                min: 0
            },
            title: {
                text: "FDA Recalls: " + query
            },
            tooltip: {
                headerFormat: '{series.name}
',
                pointFormat: '{point.x:%e %b %y}: {point.y:.2f}'
            },
            plotOptions: {
                series: {
                    marker: {
                        radius: 3
                    }
                }
            },
            series: [{
                name: query,
                data: dataArray
            }]
        });
    });
}

<|endoftext|>


<commit_before>jQuery(document).ready(function($){
    var headerOffset = $('.header').offset().top;
    $(window).scroll(function(){
        var header = $('.header'),
            scroll = $(window).scrollTop();
        if (scroll > headerOffset){
            header.addClass('fixed');
        }else {
            header.removeClass('fixed');
        }
    });
		/* show message */
    function isEmpty( el ){
      return !$.trim(el.html())
    }
    if (!isEmpty($('#messages'))) {
        $("#messages").addClass("show");
    }
    setTimeout(function() {
        $("#messages").removeClass("show");
        setTimeout(function(){
            $("#messages").empty();
        }, 500);
      }, 4000);
    /* end show message */
});<commit_msg>update js<commit_after>jQuery(document).ready(function($){
    var headerOffset = $('.header').offset().top;
    $(window).scroll(function(){
        var header = $('.header'),
            scroll = $(window).scrollTop();
        if (scroll > headerOffset){
            header.addClass('fixed');
        }else {
            header.removeClass('fixed');
        }
    });
		/* show message */
    function isEmpty( el ){
      return !$.trim(el.html())
    }
    if (!isEmpty($('#messages'))) {
        $("#messages").addClass("show");
    }
    setTimeout(function() {
        $("#messages").removeClass("show");
        setTimeout(function(){
            $("#messages").empty();
        }, 500);
      }, 4000);
    /* end show message */
		 $(".investment-list li").on('click', function(){
      $(".investment-list li").removeClass('active');
      $(this).addClass('active');
      $(this).find('input[type="radio"]').prop('checked', true);
    });
});<|endoftext|>


<commit_before>(function ($) {

    function setupTooltip () {
        $('[data-toggle="tooltip"]').tooltip({
            'placement': 'top',
            'container': 'body',
            'html': 'true',
            'white-space': 'nowrap'
        });
    }

    function initialize (selector) {
        var selectorId = $(selector).attr('id');

        // FIXME: SS should create the container and pass id of the
        // container to graphit.
        var container = $("
");
        container.append("
");
        container.append("<button type='button' data-parent-query="+ selectorId +
                         " class='btn btn-link more'>" +
                         " View more</button>");
        container.append("<button type='button' data-parent-query="+ selectorId +
                         " class='btn btn-link less'>" +
                         " View less</button>");

        $(selector).children().eq(1).children().eq(0).after(container);
    }

    function graphControls (pId, isInit) {
        // Show/Hide view more or less buttons according to the number of
        // hits already drawn, and yet to be drawn.
        var initButtons = function (pId) {
            var lessButton = $('.less'),
                moreButton = $('.more'),
                totalHits = $(pId).data().hitCount,
                shownHits = $(pId).find('.ghit > g').length;

                if (shownHits < 20) {
                    lessButton.hide();
                    moreButton.hide();
                }
                else if (shownHits === totalHits) {
                    moreButton.hide();
                    lessButton.show();
                }
                else if (shownHits === 20) {
                    lessButton.hide();
                    moreButton.show();
                }
                else {
                    lessButton.show();
                    moreButton.show();
                }
        }

        // To check if drawing for first time, then run initButtons to
        // hide/show accordingly, or otherwise buttons may require a click
        // to show desired behavior.
        if (isInit === true) {
            initButtons(pId);
        }

        // Minimum number of hits in graphical overview that we always
        // want to retain.
        var MIN_HITS_TO_SHOW = 20;

        $('.more').on('click', function (e) {
            var pId = '#'+$(this).data().parentQuery;
            var shownHits = $(pId).find('.ghit > g').length;
            $.graphIt(pId, shownHits, MIN_HITS_TO_SHOW);
            initButtons(pId);
            setupTooltip();
            e.stopPropagation();
        });

        $('.less').on('click', function (e) {
            var pId = '#'+$(this).data().parentQuery;
            var shownHits = $(pId).find('.ghit > g').length;
            var diff = shownHits - MIN_HITS_TO_SHOW;

            // We are drawing less hits than currently shown, and hence
            // negative value has to be passed to graphIt.
            if (diff >= MIN_HITS_TO_SHOW) {
                $.graphIt(pId, shownHits, -MIN_HITS_TO_SHOW);
                initButtons(pId);
            }
            else if (diff !== 0) { // Don't show less than MIN_HITS_TO_SHOW hits.
                $.graphIt(pId, shownHits, MIN_HITS_TO_SHOW - shownHits);
                initButtons(pId);
            }
            setupTooltip();
            e.stopPropagation();
        });
    }

    // Returns an array of all the hits within the given selector
    // element, where the hit data is obtained from the data-attribs.
    // HSPs class name is indicated in data-graphit-target in the
    // selector element.
    function toD3 (selector, index, howMany) {
        var hits = []
        hitPanels = $(selector).find('.hitn').slice(0, index + howMany);
        hitPanels.map(function () {
            _hsps = [];
            $(this).find('.hsps').each(function () {
                __hsps = [];
                __hsps = $(this).data();
                __hsps.hspId = $(this).attr('id');
                _hsps.push(__hsps);
            });
            _hsps.hitId = $(this).attr('id');
            _hsps.hitDef = $(this).data().hitDef;
            _hsps.hitEvalue = $(this).data().hitEvalue;
            hits.push(_hsps);
        });
        return hits;
    }

    function drawLegend (svg, options, width, height) {
        var svg_legend = svg.append('g')
                .attr('transform',
                    'translate(0,'+(height-options.margin-options.legend*1.25)+')');

        svg_legend.append('rect')
                .attr('x', 7*(width-2*options.margin)/10)
                .attr('width', 2*(width-4*options.margin)/10)
                .attr('height', options.legend)
                .attr('fill', 'url(#legend-grad)');

        svg_legend.append('text')
                .attr('transform', 'translate(0, '+options.legend+')')
                .attr('x', 6*(width-2*options.margin)/10 - options.margin/2)
                .text("Weaker hits");
        svg_legend.append('text')
                .attr('transform', 'translate(0, '+options.legend+')')
                .attr('x', 9*(width-2*options.margin)/10 + options.margin/2)
                .text("Stronger hits");

        svg.append('linearGradient')
            .attr('id', 'legend-grad')
          .selectAll('stop')
            .data([
                {offset: "0%", color: "#ccc"},
                {offset: '50%', color: '#888'},
                {offset: "100%", color: "#000"}
                ])
          .enter().append('stop')
            .attr('offset', function (d) { return d.offset })
            .attr('stop-color', function (d) { return d.color });
    }

    $.extend({
        graphIt: function (selector, index, howMany, opts) {
            // barHeight: Height of each hit track.
            // barPadding: Padding around each hit track.
            // legend: Height reserved for the overview legend.
            // margin: Margin around the svg element.
            var defaults = {
                barHeight: 4,
                barPadding: 5,
                legend: 10,
                margin: 20
            }, options = $.extend(defaults, opts),
               hits = toD3(selector, index, howMany);

            // Don't draw anything when no hits are obtained.
            if (hits.length < 1) return false;

            if (index == 0) {
                initialize(selector);
            }
            else {
                // Currently, we have no good way to extend pre-existing graph
                // and hence, are removing the old one and redrawing.
                d3.select($(selector).find('.graph')[0])
                .selectAll('svg')
                .remove();
            }

            var queryLen = $(selector).data().queryLen;
            var q_i = $(selector).attr('id');

            var width = $('.graph', selector).width();
            var height = hits.length*(options.barHeight + options.barPadding)
                + 5*options.margin + options.legend*3;

            var svg = d3.select($(selector).find('.graph')[0])
                .selectAll('svg')
                .data([hits]).enter()
                .append('svg')
                .attr('width', width)
                .attr('height', height)
                .append('g')
                .attr('transform', 'translate('+options.margin/4+', '+options.margin/4+')');

            var x = d3.scale.linear().range([0, width-options.margin])
            x.domain([1, queryLen]);

            var _tValues = x.ticks(11);
            _tValues.pop();

            var xAxis = d3.svg.axis()
                .scale(x)
                .orient('top')
                .tickValues(_tValues.concat([1, queryLen]));

            // Attach the axis to DOM (<svg> element)
            var scale = svg.append('g')
                        .attr('transform', 'translate(0, '+options.margin+')')
                        .append('g').attr('class', 'x axis')
                        .call(xAxis);

            var y = d3.scale.ordinal()
                .rangeBands([0,height-3*options.margin-2*options.legend], .3);

            y.domain(hits.map(function (d, i) {
                return d.hitId;
            }));

            var gradScale = d3.scale.log()
                .domain([d3.min([1e-5, d3.min(hits.map(function (d) {
                    return d.hitEvalue;
                }))]), d3.max(hits.map(function (d) {
                    return d.hitEvalue;
                }))])
                .range([40,150]);

            svg.append('g')
                .attr('class', 'ghit')
                .attr('transform', 'translate(0, '+(2*options.margin-options.legend)+')')
                .selectAll('.hits')
                .data(hits)
                .enter()
                .append('g')
                .attr('data-toggle', 'tooltip')
                .attr('title', function(d) {
                    // Pretty print evalue in tooltip.
                    var regex = /(\d*\.\d*)e?([+-]\d*)?/;
                    var parsedVal = regex.exec(d.hitEvalue);
                    var prettyEvalue = +parseFloat(parsedVal[1]).toFixed(3)
                    var returnString = d.hitDef + '
Evalue: ' + prettyEvalue;
                    if (parsedVal[2] != undefined) {
                        returnString +=  ' x 10' + parsedVal[2] + '';
                    }
                    return returnString;
                })
                .each(function (d,i) {
                    // Cached parameters to be used later. Perhaps, can be avoided.
                    var h_i = i+1;
                    var p_hsp = d;
                    var p_id = d.hitId;
                    var p_count = d.length;

                    d3.select(this)
                        .selectAll('.hsps')
                        .data(d).enter()
                        .append('a')
                        .each(function (pd, j) {
                            // Drawing the HSPs connector line using the same
                            // color as that of the hit track (using lookahead).
                            var y_hspline = y(p_id)+options.barHeight/2;
                            var hspline_color = d3.rgb(gradScale(p_hsp.hitEvalue),
                                gradScale(p_hsp.hitEvalue),gradScale(p_hsp.hitEvalue));

                            if (j+1 < p_count) {
                                if (p_hsp[j].hspEnd <= p_hsp[j+1].hspStart) {
                                    d3.select(this.parentNode).append('line')
                                        .attr('x1', x(p_hsp[j].hspEnd))
                                        .attr('y1', y_hspline)
                                        .attr('x2', x(p_hsp[j+1].hspStart))
                                        .attr('y2', y_hspline)
                                        .attr('stroke', hspline_color);
                                }
                                else if (p_hsp[j].hspStart > p_hsp[j+1].hspEnd) {
                                    d3.select(this.parentNode).append('line')
                                        .attr('x1', x(p_hsp[j+1].hspEnd))
                                        .attr('y1', y_hspline)
                                        .attr('x2', x(p_hsp[j].hspStart))
                                        .attr('y2', y_hspline)
                                        .attr('stroke', hspline_color);
                                };
                            };

                            // Draw the rectangular hit tracks itself.
                            d3.select(this)
                            .attr('xlink:href', function (d,i) {return '#'+q_i+'_hit_'+(h_i);})
                            .append('rect')
                            .attr('x', function (d) {
                                    return x(d.hspStart);
                            })
                            .attr('y', y(p_id))
                            .attr('width', function (d) {
                                    return x(d.hspEnd - d.hspStart + 1);
                            })
                            .attr('height', options.barHeight)
                            .attr('fill', d3.rgb(hspline_color));
                    });
                });

                // Draw legend only when more than one hit present
                if (hits.length > 1) {
                    drawLegend(svg, options, width, height);
                }
                // Bind listener events once all the graphical elements have
                // been drawn for first time.
                if (index === 0) {
                    graphControls(selector, true);
                }
                // Refresh tooltip each time graph is redrawn.
                setupTooltip();
        }
    });
}(jQuery));
<commit_msg>t.js: Switch from function defintion to function expression , minor style changes<commit_after>(function ($) {

    var setupTooltip = function () {
        $('[data-toggle="tooltip"]').tooltip({
            'placement': 'top',
            'container': 'body',
            'html': 'true',
            'white-space': 'nowrap'
        });
    }

    var initialize = function (selector) {
        var selectorId = $(selector).attr('id');

        // FIXME: SS should create the container and pass id of the
        // container to graphit.
        var container = $("
");
        container.append("
");
        container.append("<button type='button' data-parent-query="+ selectorId +
                         " class='btn btn-link more'>" +
                         " View more</button>");
        container.append("<button type='button' data-parent-query="+ selectorId +
                         " class='btn btn-link less'>" +
                         " View less</button>");

        $(selector).children().eq(1).children().eq(0).after(container);
    }

    var graphControls = function (pId, isInit) {
        // Show/Hide view more or less buttons according to the number of
        // hits already drawn, and yet to be drawn.
        var initButtons = function (pId) {
            var lessButton = $('.less'),
                moreButton = $('.more'),
                totalHits = $(pId).data().hitCount,
                shownHits = $(pId).find('.ghit > g').length;

                if (shownHits < 20) {
                    lessButton.hide();
                    moreButton.hide();
                }
                else if (shownHits === totalHits) {
                    moreButton.hide();
                    lessButton.show();
                }
                else if (shownHits === 20) {
                    lessButton.hide();
                    moreButton.show();
                }
                else {
                    lessButton.show();
                    moreButton.show();
                }
        }

        // To check if drawing for first time, then run initButtons to
        // hide/show accordingly, or otherwise buttons may require a click
        // to show desired behavior.
        if (isInit === true) {
            initButtons(pId);
        }

        // Minimum number of hits in graphical overview that we always
        // want to retain.
        var MIN_HITS_TO_SHOW = 20;

        $('.more').on('click', function (e) {
            var pId = '#'+$(this).data().parentQuery;
            var shownHits = $(pId).find('.ghit > g').length;
            $.graphIt(pId, shownHits, MIN_HITS_TO_SHOW);
            initButtons(pId);
            setupTooltip();
            e.stopPropagation();
        });

        $('.less').on('click', function (e) {
            var pId = '#'+$(this).data().parentQuery;
            var shownHits = $(pId).find('.ghit > g').length;
            var diff = shownHits - MIN_HITS_TO_SHOW;

            // We are drawing less hits than currently shown, and hence
            // negative value has to be passed to graphIt.
            if (diff >= MIN_HITS_TO_SHOW) {
                $.graphIt(pId, shownHits, -MIN_HITS_TO_SHOW);
                initButtons(pId);
            }
            else if (diff !== 0) { // Don't show less than MIN_HITS_TO_SHOW hits.
                $.graphIt(pId, shownHits, MIN_HITS_TO_SHOW - shownHits);
                initButtons(pId);
            }
            setupTooltip();
            e.stopPropagation();
        });
    }

    // Returns an array of all the hits within the given selector
    // element, where the hit data is obtained from the data-attribs.
    // HSPs class name is indicated in data-graphit-target in the
    // selector element.
    var toD3 = function (selector, index, howMany) {
        var hits = []
        hitPanels = $(selector).find('.hitn').slice(0, index + howMany);
        hitPanels.map(function () {
            _hsps = [];
            $(this).find('.hsps').each(function () {
                __hsps = [];
                __hsps = $(this).data();
                __hsps.hspId = $(this).attr('id');
                _hsps.push(__hsps);
            });
            _hsps.hitId = $(this).attr('id');
            _hsps.hitDef = $(this).data().hitDef;
            _hsps.hitEvalue = $(this).data().hitEvalue;
            hits.push(_hsps);
        });
        return hits;
    }

    var drawLegend = function (svg, options, width, height) {
        var svg_legend = svg.append('g')
                .attr('transform',
                    'translate(0,'+(height-options.margin-options.legend*1.25)+')');

        svg_legend.append('rect')
                .attr('x', 7*(width-2*options.margin)/10)
                .attr('width', 2*(width-4*options.margin)/10)
                .attr('height', options.legend)
                .attr('fill', 'url(#legend-grad)');

        svg_legend.append('text')
                .attr('transform', 'translate(0, '+options.legend+')')
                .attr('x', 6*(width-2*options.margin)/10 - options.margin/2)
                .text("Weaker hits");
        svg_legend.append('text')
                .attr('transform', 'translate(0, '+options.legend+')')
                .attr('x', 9*(width-2*options.margin)/10 + options.margin/2)
                .text("Stronger hits");

        svg.append('linearGradient')
            .attr('id', 'legend-grad')
          .selectAll('stop')
            .data([
                {offset: "0%", color: "#ccc"},
                {offset: '50%', color: '#888'},
                {offset: "100%", color: "#000"}
                ])
          .enter().append('stop')
            .attr('offset', function (d) { return d.offset })
            .attr('stop-color', function (d) { return d.color });
    }

    $.extend({
        graphIt: function (selector, index, howMany, opts) {
            // barHeight: Height of each hit track.
            // barPadding: Padding around each hit track.
            // legend: Height reserved for the overview legend.
            // margin: Margin around the svg element.
            var defaults = {
                barHeight: 4,
                barPadding: 5,
                legend: 10,
                margin: 20
            }, options = $.extend(defaults, opts),
               hits = toD3(selector, index, howMany);

            // Don't draw anything when no hits are obtained.
            if (hits.length < 1) return false;

            if (index == 0) {
                initialize(selector);
            }
            else {
                // Currently, we have no good way to extend pre-existing graph
                // and hence, are removing the old one and redrawing.
                d3.select($(selector).find('.graph')[0])
                .selectAll('svg')
                .remove();
            }

            var queryLen = $(selector).data().queryLen;
            var q_i = $(selector).attr('id');

            var width = $('.graph', selector).width();
            var height = hits.length*(options.barHeight + options.barPadding)
                + 5*options.margin + options.legend*3;

            var svg = d3.select($(selector).find('.graph')[0])
                .selectAll('svg')
                .data([hits]).enter()
                .append('svg')
                .attr('width', width)
                .attr('height', height)
                .append('g')
                .attr('transform', 'translate('+options.margin/4+', '+options.margin/4+')');

            var x = d3.scale.linear().range([0, width-options.margin])
            x.domain([1, queryLen]);

            var _tValues = x.ticks(11);
            _tValues.pop();

            var xAxis = d3.svg.axis()
                .scale(x)
                .orient('top')
                .tickValues(_tValues.concat([1, queryLen]));

            // Attach the axis to DOM (<svg> element)
            var scale = svg.append('g')
                        .attr('transform', 'translate(0, '+options.margin+')')
                        .append('g').attr('class', 'x axis')
                        .call(xAxis);

            var y = d3.scale.ordinal()
                .rangeBands([0,height-3*options.margin-2*options.legend], .3);

            y.domain(hits.map(function (d, i) {
                return d.hitId;
            }));

            var gradScale = d3.scale.log()
                .domain([d3.min([1e-5, d3.min(hits.map(function (d) {
                    return d.hitEvalue;
                }))]), d3.max(hits.map(function (d) {
                    return d.hitEvalue;
                }))])
                .range([40,150]);

            svg.append('g')
                .attr('class', 'ghit')
                .attr('transform', 'translate(0, '+(2*options.margin-options.legend)+')')
                .selectAll('.hits')
                .data(hits)
                .enter()
                .append('g')
                .attr('data-toggle', 'tooltip')
                .attr('title', function(d) {
                    // Pretty print evalue in tooltip.
                    var regex = /(\d*\.\d*)e?([+-]\d*)?/;
                    var parsedVal = regex.exec(d.hitEvalue);
                    var prettyEvalue = +parseFloat(parsedVal[1]).toFixed(3)
                    var returnString = d.hitDef + '
Evalue: ' + prettyEvalue;
                    if (parsedVal[2] != undefined) {
                        returnString +=  ' x 10' + parsedVal[2] + '';
                    }
                    return returnString;
                })
                .each(function (d,i) {
                    // Cached parameters to be used later. Perhaps, can be avoided.
                    var h_i = i+1;
                    var p_hsp = d;
                    var p_id = d.hitId;
                    var p_count = d.length;

                    d3.select(this)
                        .selectAll('.hsps')
                        .data(d).enter()
                        .append('a')
                        .each(function (pd, j) {
                            // Drawing the HSPs connector line using the same
                            // color as that of the hit track (using lookahead).
                            var yHspline = y(p_id)+options.barHeight/2;
                            var hsplineColor = d3.rgb(gradScale(p_hsp.hitEvalue),
                                gradScale(p_hsp.hitEvalue),gradScale(p_hsp.hitEvalue));

                            if (j+1 < p_count) {
                                if (p_hsp[j].hspEnd <= p_hsp[j+1].hspStart) {
                                    d3.select(this.parentNode).append('line')
                                        .attr('x1', x(p_hsp[j].hspEnd))
                                        .attr('y1', yHspline)
                                        .attr('x2', x(p_hsp[j+1].hspStart))
                                        .attr('y2', yHspline)
                                        .attr('stroke', hsplineColor);
                                }
                                else if (p_hsp[j].hspStart > p_hsp[j+1].hspEnd) {
                                    d3.select(this.parentNode).append('line')
                                        .attr('x1', x(p_hsp[j+1].hspEnd))
                                        .attr('y1', yHspline)
                                        .attr('x2', x(p_hsp[j].hspStart))
                                        .attr('y2', yHspline)
                                        .attr('stroke', hsplineColor);
                                };
                            };

                            // Draw the rectangular hit tracks itself.
                            d3.select(this)
                            .attr('xlink:href', function (d,i) {return '#'+q_i+'_hit_'+(h_i);})
                            .append('rect')
                            .attr('x', function (d) {
                                    return x(d.hspStart);
                            })
                            .attr('y', y(p_id))
                            .attr('width', function (d) {
                                    return x(d.hspEnd - d.hspStart + 1);
                            })
                            .attr('height', options.barHeight)
                            .attr('fill', d3.rgb(hsplineColor));
                    });
                });

                // Draw legend only when more than one hit present
                if (hits.length > 1) {
                    drawLegend(svg, options, width, height);
                }
                // Bind listener events once all the graphical elements have
                // been drawn for first time.
                if (index === 0) {
                    graphControls(selector, true);
                }
                // Refresh tooltip each time graph is redrawn.
                setupTooltip();
        }
    });
}(jQuery));
<|endoftext|>


<commit_before>var scene, camera, brush, plane, projector, renderer, controls,
    objectHovered;

init();
animate();

function init() {
    // Scene
    scene = new THREE.Scene();

    // Camera
    var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
    var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
    camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
    scene.add(camera);
    camera.lookAt(scene.position);
    //camera.position.set(0,150,300);
    camera.position.set(-104,331,263);

    // Brush
    brush = new THREE.Mesh( new THREE.CubeGeometry( 50, 1, 50 ),
                            new THREE.MeshLambertMaterial( { color: 0x303030, wireframe: false, opacity:1 } ) );
    brush.position.set(0,1/2,0);
    brush.name = "brush";
    scene.add( brush );

    // Plane
    var planeW = 3;
    var planeH = 5;
    plane = new THREE.Mesh( new THREE.PlaneGeometry( planeW*50, planeH*50, planeW, planeH ),
                            new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, opacity:.5 } ) );
    plane.rotation.x = -Math.PI/2;
    plane.position.set(0,0,0 );
    plane.name = "plane";
    scene.add(plane);

    // Projector
    projector = new THREE.Projector();

    // Lights
    var ambientLight = new THREE.AmbientLight( 0x404040 );
    scene.add( ambientLight );

    var directionalLight = new THREE.DirectionalLight( 0xffffff );
    directionalLight.position.x = 1;
    directionalLight.position.y = 1;
    directionalLight.position.z = .75;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    var directionalLight = new THREE.DirectionalLight( 0x808080 );
    directionalLight.position.x = -1;
    directionalLight.position.y = 1;
    directionalLight.position.z = -0.75;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    var directionalLight = new THREE.DirectionalLight( 0xfffff );
    directionalLight.position.x = 1;
    directionalLight.position.y = 800;
    directionalLight.position.z = .75;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    // Renderer
    if ( Detector.webgl )
        renderer = new THREE.WebGLRenderer( {antialias:true} );
    else
        renderer = new THREE.CanvasRenderer();

    renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    document.body.appendChild( renderer.domElement );

    // Controls
    controls = new THREE.OrbitControls( camera, renderer.domElement );

    // Events
    THREEx.WindowResize(renderer, camera);
    document.addEventListener( 'mousemove', onDocumentMouseMove, false );
    document.addEventListener( 'mouseup', onDocumentMouseUp, false );

}

function onDocumentMouseMove( event ) {
    event.preventDefault();

    // Find mouse position mapped to the 3D scene
    var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
    projector.unprojectVector( vector, camera );
    var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

    // Create an array containing all objects in the scene with which the ray intersects
    intersects = raycaster.intersectObjects( scene.children );

    if ( objectHovered ) {
        objectHovered.material.opacity = 1;
        objectHovered = null;
    }

    // if there is one (or more) intersections
    if ( intersects.length > 0 ) {
        intersect = intersects[ 0 ].object == brush ? intersects[ 1 ] : intersects[ 0 ];
        if (intersect) {
            brush.visible = true;
            brush.position.x = Math.floor( (intersects[0].point.x + 25) / 50 ) * 50;
            brush.position.z = Math.floor( (intersects[0].point.z + 25) / 50 ) * 50;

            if ( intersect.object != plane ) {
                objectHovered = intersect.object;
                objectHovered.material.opacity = 1;
                brush.visible = false;
            }
        }
    } else {
        brush.visible = false;
    }
}

function onDocumentMouseUp( event ) {
    if ( objectHovered ) {
        if (Math.round(objectHovered.scale.y * 10) / 10 == 0.1) {
            var tween = new TWEEN.Tween( { y: .1, pin: objectHovered} )
               .to( { y: 1 }, 250 )
               .easing( TWEEN.Easing.Cubic.InOut )
               .onUpdate( function () {
                    this.pin.scale.y = this.y;
                    this.pin.position.y = 25*this.y;
                    this.pin.material.ambient.r = 1 - this.y;
                    this.pin.material.ambient.g = 1 - this.y;
                    this.pin.material.ambient.b = 1 - this.y;
                })
                .onComplete( function() {
                }).start();
        } else {
            var tween = new TWEEN.Tween( { y: 1, pin: objectHovered} )
               .to( { y: .1 }, 250 )
               .easing( TWEEN.Easing.Cubic.InOut )
               .onUpdate( function () {
                    this.pin.scale.y = this.y;
                    this.pin.position.y = 25*this.y;
                    this.pin.material.ambient.r = 1 - this.y;
                    this.pin.material.ambient.g = 1 - this.y;
                    this.pin.material.ambient.b = 1 - this.y;
                })
                .onComplete( function() {
                }).start();
        }
    }
}

function animate() {
    requestAnimationFrame( animate );
    controls.update();
    renderer.render( scene, camera );
    TWEEN.update();
}<commit_msg>Adding a link back to the repo<commit_after>// PinThing - https://github.com/pinthing/pinthing.com
var scene, camera, brush, plane, projector, renderer, controls,
    objectHovered;

init();
animate();

function init() {
    // Scene
    scene = new THREE.Scene();

    // Camera
    var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
    var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
    camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
    scene.add(camera);
    camera.lookAt(scene.position);
    //camera.position.set(0,150,300);
    camera.position.set(-104,331,263);

    // Brush
    brush = new THREE.Mesh( new THREE.CubeGeometry( 50, 1, 50 ),
                            new THREE.MeshLambertMaterial( { color: 0x303030, wireframe: false, opacity:1 } ) );
    brush.position.set(0,1/2,0);
    brush.name = "brush";
    scene.add( brush );

    // Plane
    var planeW = 3;
    var planeH = 5;
    plane = new THREE.Mesh( new THREE.PlaneGeometry( planeW*50, planeH*50, planeW, planeH ),
                            new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, opacity:.5 } ) );
    plane.rotation.x = -Math.PI/2;
    plane.position.set(0,0,0 );
    plane.name = "plane";
    scene.add(plane);

    // Projector
    projector = new THREE.Projector();

    // Lights
    var ambientLight = new THREE.AmbientLight( 0x404040 );
    scene.add( ambientLight );

    var directionalLight = new THREE.DirectionalLight( 0xffffff );
    directionalLight.position.x = 1;
    directionalLight.position.y = 1;
    directionalLight.position.z = .75;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    var directionalLight = new THREE.DirectionalLight( 0x808080 );
    directionalLight.position.x = -1;
    directionalLight.position.y = 1;
    directionalLight.position.z = -0.75;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    var directionalLight = new THREE.DirectionalLight( 0xfffff );
    directionalLight.position.x = 1;
    directionalLight.position.y = 800;
    directionalLight.position.z = .75;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    // Renderer
    if ( Detector.webgl )
        renderer = new THREE.WebGLRenderer( {antialias:true} );
    else
        renderer = new THREE.CanvasRenderer();

    renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    document.body.appendChild( renderer.domElement );

    // Controls
    controls = new THREE.OrbitControls( camera, renderer.domElement );

    // Events
    THREEx.WindowResize(renderer, camera);
    document.addEventListener( 'mousemove', onDocumentMouseMove, false );
    document.addEventListener( 'mouseup', onDocumentMouseUp, false );

}

function onDocumentMouseMove( event ) {
    event.preventDefault();

    // Find mouse position mapped to the 3D scene
    var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
    projector.unprojectVector( vector, camera );
    var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

    // Create an array containing all objects in the scene with which the ray intersects
    intersects = raycaster.intersectObjects( scene.children );

    if ( objectHovered ) {
        objectHovered.material.opacity = 1;
        objectHovered = null;
    }

    // if there is one (or more) intersections
    if ( intersects.length > 0 ) {
        intersect = intersects[ 0 ].object == brush ? intersects[ 1 ] : intersects[ 0 ];
        if (intersect) {
            brush.visible = true;
            brush.position.x = Math.floor( (intersects[0].point.x + 25) / 50 ) * 50;
            brush.position.z = Math.floor( (intersects[0].point.z + 25) / 50 ) * 50;

            if ( intersect.object != plane ) {
                objectHovered = intersect.object;
                objectHovered.material.opacity = 1;
                brush.visible = false;
            }
        }
    } else {
        brush.visible = false;
    }
}

function onDocumentMouseUp( event ) {
    if ( objectHovered ) {
        if (Math.round(objectHovered.scale.y * 10) / 10 == 0.1) {
            var tween = new TWEEN.Tween( { y: .1, pin: objectHovered} )
               .to( { y: 1 }, 250 )
               .easing( TWEEN.Easing.Cubic.InOut )
               .onUpdate( function () {
                    this.pin.scale.y = this.y;
                    this.pin.position.y = 25*this.y;
                    this.pin.material.ambient.r = 1 - this.y;
                    this.pin.material.ambient.g = 1 - this.y;
                    this.pin.material.ambient.b = 1 - this.y;
                })
                .onComplete( function() {
                }).start();
        } else {
            var tween = new TWEEN.Tween( { y: 1, pin: objectHovered} )
               .to( { y: .1 }, 250 )
               .easing( TWEEN.Easing.Cubic.InOut )
               .onUpdate( function () {
                    this.pin.scale.y = this.y;
                    this.pin.position.y = 25*this.y;
                    this.pin.material.ambient.r = 1 - this.y;
                    this.pin.material.ambient.g = 1 - this.y;
                    this.pin.material.ambient.b = 1 - this.y;
                })
                .onComplete( function() {
                }).start();
        }
    }
}

function animate() {
    requestAnimationFrame( animate );
    controls.update();
    renderer.render( scene, camera );
    TWEEN.update();
}<|endoftext|>