<commit_before>/*
Copyright (C) 2013 Sanjay Agravat <sanjay.agravat@emory.edu>, Ashish Sharma <ashish.sharma@emory.edu>

This file is a zoom and pan handler for OpenSeadragon and annotools.js to support resizing annotations on certain mouse events.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

var AnnotoolsOpenSeadragonHandler = new Class({

    initialize: function (viewer, options) {
        this.viewer = viewer;
        this.state = 'none';
        this.stateTarget = null;
        this.stateOrigin = null;
        this.scale = options.ratio || 1.3;
        this.lastCenter = {x: 0, y: 0};
        this.objectCenterPts = {};
        this.originalCoords = [];
        this.originalDivCoords = [];
        this.zoom = viewer.viewport.getZoom();
        this.zoomBase = viewer.viewport.getZoom();
        this.zooming = false;
        this.panning = false;
        this.animateWaitTime = options.animateWaitTime || 300;

        this._setupOpenSeadragonButtonHandlers();

        // global object reference used when the "this" object is referring to the window
        window.annotationHandler = this;
    },

    /*
        Redefines the button handlers from the OpenSeadragon button bar
        for the onRelease event. Handles Zoom in, Zoom out, and Home
        buttons.
    */
    _setupOpenSeadragonButtonHandlers: function() {

        for (var i = 0; i < this.viewer.buttons.buttons.length; i++) {
            var button = this.viewer.buttons.buttons[i];
            if (button.tooltip.toLowerCase() == "zoom in") {
                var onZoomInRelease = button.onRelease;
                var zoomIn = this.handleZoomIn;
                button.onRelease = function(args){

                    $$('svg')[0].setStyle('opacity', 1);
                    onZoomInRelease(args);
                    setTimeout(function() {
                        //zoomIn();
                        $$('svg')[0].setStyle('opacity', 1);
                    }, annotationHandler.animateWaitTime);
                };

            }
            else if (button.tooltip.toLowerCase() == "zoom out") {
                var onZoomOutRelease = button.onRelease;
                var zoomOut = this.handleZoomOut;
                button.onRelease = function(args){

                    $$('svg')[0].setStyle('opacity', 0);
                    onZoomOutRelease(args);
                    setTimeout(function() {
                        //zoomOut();
                        $$('svg')[0].setStyle('opacity', 1);
                    }, annotationHandler.animateWaitTime);
                };

            }

        }

    }.protect(),

    goHome: function(annot) {

        annot.getAnnot();
    },

    handleZoomIn: function(annot) {
          zooming = true;
          console.log("handleZoomIn");
      var center = viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5));
          if (annotationHandler.lastCenter.x != center.x || annotationHandler.lastCenter.y != center.y) {
              scale  = 1.3;
              annotationHandler.zoom++;
              var centerPt =
                  viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5));
              $('originpt').setProperty('cx',centerPt.x);
              $('originpt').setProperty('cy',centerPt.y);

              for (var i = 0; i < $('viewport').getChildren().length; i++) {

                  var object = $('viewport').getChildren()[i];
                  //var centerPt = $('center')[0];
                  var bbox = object.getBBox();

                  var newLocation = viewer.viewport.pixelFromPoint(annotationHandler.objectCenterPts[i]);

                  var distance = newLocation.distanceTo(center);
                  if (object.tagName == "ellipse") {

                      object.setAttribute("rx", (bbox.width/2)*scale);
                      object.setAttribute("ry", (bbox.height/2)*scale);
                      object.setAttribute("cx", newLocation.x);
                      object.setAttribute("cy", newLocation.y);

                  }
                  else if (object.tagName == "rect") {

                      object.setAttribute("width", (bbox.width)*scale);
                      object.setAttribute("height", (bbox.height)*scale);
                      object.setAttribute("x", newLocation.x-(bbox.width/2)*scale);
                      object.setAttribute("y", newLocation.y-(bbox.height/2)*scale);

                  }
                  else {

                      var points = String.split(object.getAttribute("points").trim(), ' ');
                      var newLocationRelPt = viewer.viewport.pointFromPixel(newLocation);
                      var distances = annotationHandler.originalCoords[i].distances;
                      var pointsStr = "";
                      for (var j = 0; j < distances.length-1; j++) {
                          var pointPair = distances[j].plus(newLocationRelPt);
                          var pixelPoint = viewer.viewport.pixelFromPoint(pointPair);
                          pointsStr += pixelPoint.x + "," + pixelPoint.y + " ";

                      }
                      object.setAttribute("points", pointsStr);

                  }

                  var div    = $$('div.annotcontainer')[i];
                  div.style.left   = newLocation.x-(bbox.width/2)*scale + "px";
                  div.style.top    = newLocation.y-(bbox.height/2)*scale + "px";
                  div.style.width  = (bbox.width)*scale + "px";
                  div.style.height = (bbox.height)*scale + "px";

              }
          }

          annotationHandler.lastCenter = center;
    zooming = false;
    },

    handleZoomOut: function() {
    zooming = true;
          var center = viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5));
          console.log("handleZoomOut");
          if (annotationHandler.lastCenter.x != center.x || annotationHandler.lastCenter.y != center.y) {
              scale  = 1/1.3;
              annotationHandler.zoom--;

              var centerPt =
                  viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5));
              $('originpt').setProperty('cx',centerPt.x);
              $('originpt').setProperty('cy',centerPt.y);

              for (var i = 0; i < $('viewport').getChildren().length; i++) {

                  var object = $('viewport').getChildren()[i];
                  var bbox = object.getBBox();

                  var newLocation = viewer.viewport.pixelFromPoint(annotationHandler.objectCenterPts[i]);

                  if (object.tagName == "ellipse") {

                      object.setAttribute("rx", (bbox.width/2)*scale);
                      object.setAttribute("ry", (bbox.height/2)*scale);
                      object.setAttribute("cx", newLocation.x);
                      object.setAttribute("cy", newLocation.y);

                  }
                  else if (object.tagName == "rect") {

                      object.setAttribute("width", (bbox.width)*scale);
                      object.setAttribute("height", (bbox.height)*scale);
                      object.setAttribute("x", newLocation.x-(bbox.width/2)*scale);
                      object.setAttribute("y", newLocation.y-(bbox.height/2)*scale);

                  }
                  else {

                      var points = String.split(object.getAttribute("points").trim(), ' ');
                      var newLocationRelPt = viewer.viewport.pointFromPixel(newLocation);
                      var distances = annotationHandler.originalCoords[i].distances;
                      var pointsStr = "";
                      for (var j = 0; j < distances.length-1; j++) {
                          var pointPair = distances[j].plus(newLocationRelPt);
                          var pixelPoint = viewer.viewport.pixelFromPoint(pointPair);
                          pointsStr += pixelPoint.x + "," + pixelPoint.y + " ";

                      }
                      object.setAttribute("points", pointsStr);

                  }
                  var div    = $$('div.annotcontainer')[i];
                  div.style.left   = newLocation.x-(bbox.width/2)*scale + "px";
                  div.style.top    = newLocation.y-(bbox.height/2)*scale + "px";
                  div.style.width  = (bbox.width)*scale + "px";
                  div.style.height = (bbox.height)*scale + "px";

              }

          }

          annotationHandler.lastCenter = center;
          zooming = false;
    },

    handleMouseMove: function(evt) {
      //console.log("..");
      if(evt.preventDefault){
          //console.log("frozen");
          evt.preventDefault();
      }
      if (this.state == 'pan') {
          //$('svg')[0].hide();
          $$('svg')[0].setStyle('opacity', 0);
          var pixel = OpenSeadragon.getMousePosition(evt).minus
              (OpenSeadragon.getElementPosition(viewer.element));
          var point = viewer.viewport.pointFromPixel(pixel);
      }

    },

    handleMouseUp: function(evt) {

      //if (evt.target.tagName.toLowerCase() == "button" || evt.target.tagName.toLowerCase() == "div") {
      if (evt.target.tagName.toLowerCase() == "button") {

        console.log("handleMouseUp: " + evt.target.tagName);
        return;

      }
          if(evt.preventDefault)
              evt.preventDefault();

          if (this.state == 'pan') {
              this.state = 'up';
              var pixel =
                  OpenSeadragon.getMousePosition(evt).minus
                      (OpenSeadragon.getElementPosition(viewer.element));

              var diff = pixel.minus(this.stateOrigin);

              // handles a mouse click (zoom and pan to)
              // otherwise we will handle the pan event
              if (diff.x == 0 && diff.y == 0) {

                 // setTimeout(function() {
                         //annotationHandler.handleZoomIn();
                        $$('svg')[0].setStyle('opacity', 1);
                    // }, annotationHandler.animateWaitTime);

              }
              else {

                $('originpt').setProperty('cx',
                        viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5)).x);
                $('originpt').setProperty('cy',
                        viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5)).y);

                //$('svg')[0].show();
                $$('svg')[0].setStyle('opacity', 1);
                for (var i = 0; i < $('viewport').getChildren().length; i++) {

                    var object = $('viewport').getChildren()[i];
                    //object.setAttribute("style", style="fill:none;stroke:lime;stroke-width:2");
                    var bbox = object.getBBox();
                    if (object.tagName == "ellipse") {

                        var currX = bbox.x+bbox.width/2;
                        var currY = bbox.y+bbox.height/2;
                        object.setAttribute("cx", currX + diff.x);
                        object.setAttribute("cy", currY + diff.y);

                    }
                    else if (object.tagName == "rect") {

                        object.setAttribute("x", bbox.x + diff.x);
                        object.setAttribute("y", bbox.y + diff.y);

                    }
                    else {

                        var points = String.split(object.getAttribute("points").trim(), ' ');
                        var pointsStr = "";
                        for (var j = 0; j < points.length; j++) {
                            var pointPair = String.split(points[j], ",");
                            pointsStr += (parseFloat(pointPair[0])+diff.x) +
                                            "," +
                                        (parseFloat(pointPair[1])+diff.y) + " ";

                        }
                        object.setAttribute("points", pointsStr);

                    }

                    var div    = $$('div.annotcontainer')[i];

                    div.style.left   = (bbox.x + diff.x) + "px";
                    div.style.top    = (bbox.y  + diff.y)+ "px";
                }
          }

        }

    },

    handleMouseDown: function(evt) {

      if (evt.target.tagName.toLowerCase() == "button") {
        console.log("handleMouseDown: " + evt.target.tagName);
        return;
      }
      if(evt.preventDefault)
          evt.preventDefault();
      this.state = 'pan';
      var pixel = OpenSeadragon.getMousePosition(evt).minus
          (OpenSeadragon.getElementPosition(viewer.element));

      $$('svg')[0].setStyle('opacity', 0);
      this.stateOrigin = pixel;

    },

    handleMouseWheel: function(evt) {
     if(evt.preventDefault)
          evt.preventDefault();

     $$('svg')[0].setStyle('opacity', 0);
    }
});

<commit_msg>disable zoom on mousedown on form elements to allow users to fill forms instead of zooming in osd<commit_after>/*
Copyright (C) 2013 Sanjay Agravat <sanjay.agravat@emory.edu>, Ashish Sharma <ashish.sharma@emory.edu>

This file is a zoom and pan handler for OpenSeadragon and annotools.js to support resizing annotations on certain mouse events.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

var AnnotoolsOpenSeadragonHandler = new Class({

    initialize: function (viewer, options) {
        this.viewer = viewer;
        this.state = 'none';
        this.stateTarget = null;
        this.stateOrigin = null;
        this.scale = options.ratio || 1.3;
        this.lastCenter = {x: 0, y: 0};
        this.objectCenterPts = {};
        this.originalCoords = [];
        this.originalDivCoords = [];
        this.zoom = viewer.viewport.getZoom();
        this.zoomBase = viewer.viewport.getZoom();
        this.zooming = false;
        this.panning = false;
        this.animateWaitTime = options.animateWaitTime || 300;

        this._setupOpenSeadragonButtonHandlers();

        // global object reference used when the "this" object is referring to the window
        window.annotationHandler = this;
    },

    /*
        Redefines the button handlers from the OpenSeadragon button bar
        for the onRelease event. Handles Zoom in, Zoom out, and Home
        buttons.
    */
    _setupOpenSeadragonButtonHandlers: function() {

        for (var i = 0; i < this.viewer.buttons.buttons.length; i++) {
            var button = this.viewer.buttons.buttons[i];
            if (button.tooltip.toLowerCase() == "zoom in") {
                var onZoomInRelease = button.onRelease;
                var zoomIn = this.handleZoomIn;
                button.onRelease = function(args){

                    $$('svg')[0].setStyle('opacity', 1);
                    onZoomInRelease(args);
                    setTimeout(function() {
                        //zoomIn();
                        $$('svg')[0].setStyle('opacity', 1);
                    }, annotationHandler.animateWaitTime);
                };

            }
            else if (button.tooltip.toLowerCase() == "zoom out") {
                var onZoomOutRelease = button.onRelease;
                var zoomOut = this.handleZoomOut;
                button.onRelease = function(args){

                    $$('svg')[0].setStyle('opacity', 0);
                    onZoomOutRelease(args);
                    setTimeout(function() {
                        //zoomOut();
                        $$('svg')[0].setStyle('opacity', 1);
                    }, annotationHandler.animateWaitTime);
                };

            }

        }

    }.protect(),

    goHome: function(annot) {

        annot.getAnnot();
    },

    handleZoomIn: function(annot) {
          zooming = true;
          console.log("handleZoomIn");
      var center = viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5));
          if (annotationHandler.lastCenter.x != center.x || annotationHandler.lastCenter.y != center.y) {
              scale  = 1.3;
              annotationHandler.zoom++;
              var centerPt =
                  viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5));
              $('originpt').setProperty('cx',centerPt.x);
              $('originpt').setProperty('cy',centerPt.y);

              for (var i = 0; i < $('viewport').getChildren().length; i++) {

                  var object = $('viewport').getChildren()[i];
                  //var centerPt = $('center')[0];
                  var bbox = object.getBBox();

                  var newLocation = viewer.viewport.pixelFromPoint(annotationHandler.objectCenterPts[i]);

                  var distance = newLocation.distanceTo(center);
                  if (object.tagName == "ellipse") {

                      object.setAttribute("rx", (bbox.width/2)*scale);
                      object.setAttribute("ry", (bbox.height/2)*scale);
                      object.setAttribute("cx", newLocation.x);
                      object.setAttribute("cy", newLocation.y);

                  }
                  else if (object.tagName == "rect") {

                      object.setAttribute("width", (bbox.width)*scale);
                      object.setAttribute("height", (bbox.height)*scale);
                      object.setAttribute("x", newLocation.x-(bbox.width/2)*scale);
                      object.setAttribute("y", newLocation.y-(bbox.height/2)*scale);

                  }
                  else {

                      var points = String.split(object.getAttribute("points").trim(), ' ');
                      var newLocationRelPt = viewer.viewport.pointFromPixel(newLocation);
                      var distances = annotationHandler.originalCoords[i].distances;
                      var pointsStr = "";
                      for (var j = 0; j < distances.length-1; j++) {
                          var pointPair = distances[j].plus(newLocationRelPt);
                          var pixelPoint = viewer.viewport.pixelFromPoint(pointPair);
                          pointsStr += pixelPoint.x + "," + pixelPoint.y + " ";

                      }
                      object.setAttribute("points", pointsStr);

                  }

                  var div    = $$('div.annotcontainer')[i];
                  div.style.left   = newLocation.x-(bbox.width/2)*scale + "px";
                  div.style.top    = newLocation.y-(bbox.height/2)*scale + "px";
                  div.style.width  = (bbox.width)*scale + "px";
                  div.style.height = (bbox.height)*scale + "px";

              }
          }

          annotationHandler.lastCenter = center;
    zooming = false;
    },

    handleZoomOut: function() {
    zooming = true;
          var center = viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5));
          console.log("handleZoomOut");
          if (annotationHandler.lastCenter.x != center.x || annotationHandler.lastCenter.y != center.y) {
              scale  = 1/1.3;
              annotationHandler.zoom--;

              var centerPt =
                  viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5));
              $('originpt').setProperty('cx',centerPt.x);
              $('originpt').setProperty('cy',centerPt.y);

              for (var i = 0; i < $('viewport').getChildren().length; i++) {

                  var object = $('viewport').getChildren()[i];
                  var bbox = object.getBBox();

                  var newLocation = viewer.viewport.pixelFromPoint(annotationHandler.objectCenterPts[i]);

                  if (object.tagName == "ellipse") {

                      object.setAttribute("rx", (bbox.width/2)*scale);
                      object.setAttribute("ry", (bbox.height/2)*scale);
                      object.setAttribute("cx", newLocation.x);
                      object.setAttribute("cy", newLocation.y);

                  }
                  else if (object.tagName == "rect") {

                      object.setAttribute("width", (bbox.width)*scale);
                      object.setAttribute("height", (bbox.height)*scale);
                      object.setAttribute("x", newLocation.x-(bbox.width/2)*scale);
                      object.setAttribute("y", newLocation.y-(bbox.height/2)*scale);

                  }
                  else {

                      var points = String.split(object.getAttribute("points").trim(), ' ');
                      var newLocationRelPt = viewer.viewport.pointFromPixel(newLocation);
                      var distances = annotationHandler.originalCoords[i].distances;
                      var pointsStr = "";
                      for (var j = 0; j < distances.length-1; j++) {
                          var pointPair = distances[j].plus(newLocationRelPt);
                          var pixelPoint = viewer.viewport.pixelFromPoint(pointPair);
                          pointsStr += pixelPoint.x + "," + pixelPoint.y + " ";

                      }
                      object.setAttribute("points", pointsStr);

                  }
                  var div    = $$('div.annotcontainer')[i];
                  div.style.left   = newLocation.x-(bbox.width/2)*scale + "px";
                  div.style.top    = newLocation.y-(bbox.height/2)*scale + "px";
                  div.style.width  = (bbox.width)*scale + "px";
                  div.style.height = (bbox.height)*scale + "px";

              }

          }

          annotationHandler.lastCenter = center;
          zooming = false;
    },

    handleMouseMove: function(evt) {
      //console.log("..");
      if(evt.preventDefault){
          //console.log("frozen");
          evt.preventDefault();
      }
      if (this.state == 'pan') {
          //$('svg')[0].hide();
          $$('svg')[0].setStyle('opacity', 0);
          var pixel = OpenSeadragon.getMousePosition(evt).minus
              (OpenSeadragon.getElementPosition(viewer.element));
          var point = viewer.viewport.pointFromPixel(pixel);
      }

    },

    handleMouseUp: function(evt) {
      //console.log("mouse up");
      //if (evt.target.tagName.toLowerCase() == "button" || evt.target.tagName.toLowerCase() == "div") {
      if (evt.target.tagName.toLowerCase() == "button" || evt.target.tagName.toLowerCase() == "input") {
        //console.log("here");
        //console.log("handleMouseUp: " + evt.target.tagName);
        return;

      }

          if(evt.preventDefault)
              evt.preventDefault();

          if (this.state == 'pan') {
              this.state = 'up';
              var pixel =
                  OpenSeadragon.getMousePosition(evt).minus
                      (OpenSeadragon.getElementPosition(viewer.element));

              var diff = pixel.minus(this.stateOrigin);

              // handles a mouse click (zoom and pan to)
              // otherwise we will handle the pan event
              if (diff.x == 0 && diff.y == 0) {

                 // setTimeout(function() {
                         //annotationHandler.handleZoomIn();
                        $$('svg')[0].setStyle('opacity', 1);
                    // }, annotationHandler.animateWaitTime);

              }
              else {

                $$('originpt').setProperty('cx',
                        viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5)).x);
                $$('originpt').setProperty('cy',
                        viewer.viewport.pixelFromPoint(new OpenSeadragon.Point(.5,.5)).y);

                //$('svg')[0].show();
                $$('svg')[0].setStyle('opacity', 1);
                for (var i = 0; i < $$('viewport').getChildren().length; i++) {

                    var object = $('viewport').getChildren()[i];
                    //object.setAttribute("style", style="fill:none;stroke:lime;stroke-width:2");
                    var bbox = object.getBBox();
                    if (object.tagName == "ellipse") {

                        var currX = bbox.x+bbox.width/2;
                        var currY = bbox.y+bbox.height/2;
                        object.setAttribute("cx", currX + diff.x);
                        object.setAttribute("cy", currY + diff.y);

                    }
                    else if (object.tagName == "rect") {

                        object.setAttribute("x", bbox.x + diff.x);
                        object.setAttribute("y", bbox.y + diff.y);

                    }
                    else {

                        var points = String.split(object.getAttribute("points").trim(), ' ');
                        var pointsStr = "";
                        for (var j = 0; j < points.length; j++) {
                            var pointPair = String.split(points[j], ",");
                            pointsStr += (parseFloat(pointPair[0])+diff.x) +
                                            "," +
                                        (parseFloat(pointPair[1])+diff.y) + " ";

                        }
                        object.setAttribute("points", pointsStr);

                    }

                    var div    = $$('div.annotcontainer')[i];

                    div.style.left   = (bbox.x + diff.x) + "px";
                    div.style.top    = (bbox.y  + diff.y)+ "px";
                }
          }

        }

    },

    handleMouseDown: function(evt) {

        //Allow interactions on the annotation creation form elements
      if (evt.target.tagName.toLowerCase() == "button" || evt.target.tagName.toLowerCase() == "input" || evt.target.tagName.toLowerCase() == "select") {

        return;
      }
      if(evt.preventDefault)
          evt.preventDefault();
      this.state = 'pan';
      var pixel = OpenSeadragon.getMousePosition(evt).minus
          (OpenSeadragon.getElementPosition(viewer.element));

      $$('svg')[0].setStyle('opacity', 0);
      this.stateOrigin = pixel;

    },

    handleMouseWheel: function(evt) {
     if(evt.preventDefault)
          evt.preventDefault();

     $$('svg')[0].setStyle('opacity', 0);
    }
});

<|endoftext|>


<commit_before>'use strict';
$(document).ready(() => {
  console.log('Hi kids Do You Like Violence?')

  $('#myInput').val('')

  const $items = $('.your-class');

  function catFunction() {
    let cat = $('#dropdown').val()

    $.getJSON('/items')
      .done((items) => {

        $('.your-class').children().remove()
        $('.your-class').removeClass('slick-initialized slick-slider')

        for (const item of items) {
          console.log(item.cat)
          if (cat === 'All') {
            //add all items
            let $card = createCard(item)
            $items.append($card)
          }
          if (item.cat == cat) {
            //add item
            let $card = createCard(item)
            $items.append($card)
          }
        }
      })
      .fail(() => {
        Materialize.toast('Unable to retrieve items', 3000);
      })
  }

  $('#dropdown').change(function(event) {

      catFunction()

  })

  // var i = 0;
  const slick = function () {
    $.getJSON('/items')
      .done((items) => {

        for (const item of items) {
        const title = item.title

          // const $anchor = $('')
          //   .attr({
          //     href: `/item.html?id=${item.id}`,
          //     'data-delay': '50',
          //     'data-tooltip': item.title
          //   })
          //   .tooltip();
          //
          //   let color = "red"
          //   const $card = $('
').addClass('card col s4 m4 l4 ');
          //   $card.attr('style', `background-color:${color};`)
          //   const $cardimage = $('
').addClass('card-image')
          //   $cardimage.attr('style', 'padding-bottom: 30px;')
          //   const $cardContent = $('
').addClass('card-content black-text')
          //   const $span = $('').addClass('card-title')
          //   $span.text(item.title)
          //   const $pPrice = $('
')
          //   $pPrice.text("Price: $" + item.daily_price + " a day.")
          //   const $p = $('
')
          //   $p.text('Desc: ' + item.desc)
          //   const $img = $('').attr({ src: item.img_url, alt: item.title, height: 200, width: 200, style: 'object-fit: contain;' });
          //
          //   $card.append($anchor);
          //   $card.append($cardimage);
          //   $cardContent.append($span)
          //   $cardContent.append($pPrice)
          //   $cardContent.append($p)
          //   $card.append($cardContent)
          //   $items.append($card)

          // const green = "#4FCCB2"
          // const blue = "#42BADF"
          // const orange = "#F3AA4E"
          // const red = "#EF7858"
          // const colorPalet = [ green, red, blue, orange ]

          // var color
          // var color = colorPalet[i]
          // i += 1
          // if(i == 5) {
          //   var color = colorPalet[4]
          //   i = 0
          // }

          $items.append(`<a href= item.html?id=${item.id}>` +
                          "
" +
                            "
" +
                              "
" +
                              "" + item.title + "" +
                              "
" +
                              "
" +
                              `<img id = pic src = ${item.img_url} alt = ${item.title}>` +
                              "
" +
                              "
" +
                              "
" + item.desc + "
" +
                              "
 Daily Price: $" + item.daily_price + "
" +
                              "
" +
                            "
" +
                          "
" +
                        "")
          // $(".card").attr("style", `background-color: ${colorPalet[i]};`)

          $(".card").click(function() {
            window.location.href = `item.html?id=${item.id}`;
          })

          // i++
        }

        $('.your-class').slick({
          slidesToShow: 3,
          slidesToScroll: 1,
          autoplay: true,
          autoplaySpeed: 3000,
        });
      })
      .fail(() => {
        Materialize.toast('Unable to retrieve items', 3000);
      });
  }

  function createCard(item) {
    const $anchor = $('')
      .attr({
        href: `/item.html?id=${item.id}`,
        'data-delay': '50',
        'data-tooltip': item.title
      })
      .tooltip();

    const $card = $('
').addClass('card col s4 m4 l4 ');
    $card.attr('style', 'padding: 0px; width:371px;')
    const $cardimage = $('
').addClass('card-image')
    // $cardimage.attr('style', 'padding-bottom: 30px;')
    const $cardContent = $('
').addClass('card-content black-text')
    const $span = $('').addClass('card-title')
    $span.text(item.title)
    const $pPrice = $('
')
    $pPrice.text("Price: $" + item.daily_price + " a day.")
    const $p = $('
')
    $p.text('Desc: ' + item.desc)
    const $img = $('').attr({ src: item.img_url, alt: item.title, height: 200, width: 200, style: 'object-fit: contain;' });

    $card.append($anchor);
    $cardimage.append($img)
    $card.append($cardimage);
    $cardContent.append($span)
    $cardContent.append($pPrice)
    $cardContent.append($p)
    $card.append($cardContent)

    $card.click(function() {
      window.location.href = `item.html?id=${item.id}`;
    })

    return $card
  }
  $('#myInput').keydown(function (e) {
    e.stopPropagation();
    if (e.keyCode === 40) {
        e.preventDefault();
        console.log(40);
    } else if (e.keyCode === 38) {
        e.preventDefault();
        console.log(38);
    }
  })

  let searches = 0

  $('#myInput').keyup(function (e) {

    if (searches === 0) {
      $('.your-class').children().remove()
      $('.your-class').removeClass('slick-initialized slick-slider')
    }

    searches++

    let input = $('#myInput').val()

    let cat = $('#dropdown').val()

    if (input === '') {

      //check for cat selection
      if (cat != null) {
        searches = 0;
        $('.your-class').empty()
        $('.your-class').removeClass('slick-initialized slick-slider')
        return catFunction()
      }

      searches = 0;
      $('.your-class').empty()
      $('.your-class').removeClass('slick-initialized slick-slider')
      slick()
      return
    }

    let length = input.length

    const $items = $('.your-class');
      $.getJSON('/items')
        .done((items) => {
          console.log(cat)
            for (const item of items) {
              let title = item.title
              let newarr = title.split(" ")

              for (const word of newarr) {
                if (word.slice(0, length).toLowerCase() === input.toLowerCase()) {
                  let card = createCard(item)

                  let alreadyin = false;
                  $items.children().each(function() {
                    const $div = this
                    if ($($div).find('img')[0] === undefined) {
                      console.log('undefined yo')
                      alreadyin = false
                    } else {
                      let name = $($div).find('img')[0].alt
                      if (item.title === name) {
                        console.log('item already in search')
                        alreadyin = true
                      }
                    }
                  })

                  if (alreadyin === true) {

                  } else {

                    //check if matches cat
                    console.log('test' + item.cat)
                    if (cat === 'All' || cat === null) {
                      $items.append(card)
                      break
                    } else {
                      if (cat === item.cat) {
                        $items.append(card)
                        break
                      }
                    }

                  }

                } else {
                  let card = createCard(item)
                  if (word.indexOf(input) !== -1 && input.length !== 1) {

                    let alreadyin = false;
                    console.log($items.children())
                    $items.children().each(function() {
                      const $div = this
                      if ($($div).find('img')[0] === undefined) {
                        console.log('undefined yo')
                      } else {
                        let name = $($div).find('img')[0].alt
                        if (item.title === name) {
                          console.log('item already in search')
                          alreadyin = true
                        }
                      }
                    })

                    if (alreadyin === true) {

                    } else {
                      //check if matches cat
                      console.log(item.cat)
                      if (cat === 'All' || cat === null) {
                        $items.append(card)
                        break
                      } else {
                        if (cat === item.cat) {
                          $items.append(card)
                          break
                        }
                      }
                    }
                  }
                  else {

                  }

                }
              }

            }
        })
        .fail(() => {
          Materialize.toast('Unable to retrieve items', 3000);
        });
  })

    $('.parallax').parallax();

    slick()

});
<commit_msg>card css done<commit_after>'use strict';
$(document).ready(() => {
  console.log('Hi kids Do You Like Violence?')

  $('#myInput').val('')

  const $items = $('.your-class');

  function catFunction() {
    let cat = $('#dropdown').val()

    $.getJSON('/items')
      .done((items) => {

        $('.your-class').children().remove()
        $('.your-class').removeClass('slick-initialized slick-slider')

        for (const item of items) {
          console.log(item.cat)
          if (cat === 'All') {
            //add all items
            let $card = createCard(item)
            $items.append($card)
          }
          if (item.cat == cat) {
            //add item
            let $card = createCard(item)
            $items.append($card)
          }
        }
      })
      .fail(() => {
        Materialize.toast('Unable to retrieve items', 3000);
      })
  }

  $('#dropdown').change(function(event) {

      catFunction()

  })

  var i = 0;
  const slick = function () {
    $.getJSON('/items')
      .done((items) => {

        for (const item of items) {
        const title = item.title

          // const $anchor =w $('')
          //   .attr({
          //     href: `/item.html?id=${item.id}`,
          //     'data-delay': '50',
          //     'data-tooltip': item.title
          //   })
          //   .tooltip();
          //
          //   let color = "red"
          //   const $card = $('
').addClass('card col s4 m4 l4 ');
          //   $card.attr('style', `background-color:${color};`)
          //   const $cardimage = $('
').addClass('card-image')
          //   $cardimage.attr('style', 'padding-bottom: 30px;')
          //   const $cardContent = $('
').addClass('card-content black-text')
          //   const $span = $('').addClass('card-title')
          //   $span.text(item.title)
          //   const $pPrice = $('
')
          //   $pPrice.text("Price: $" + item.daily_price + " a day.")
          //   const $p = $('
')
          //   $p.text('Desc: ' + item.desc)
          //   const $img = $('').attr({ src: item.img_url, alt: item.title, height: 200, width: 200, style: 'object-fit: contain;' });
          //
          //   $card.append($anchor);
          //   $card.append($cardimage);
          //   $cardContent.append($span)
          //   $cardContent.append($pPrice)
          //   $cardContent.append($p)
          //   $card.append($cardContent)
          //   $items.append($card)

          const green = "#4FCCB2"
          const blue = "#42BADF"
          const orange = "#F3AA4E"
          const red = "#EF7858"
          const colorPalet = [ green, red, blue, orange ]

          var color = colorPalet[i]
          i += 1
          if(i == 5) {
            var color = colorPalet[0]
            i = 1
          }

          const $card = (`<a href= item.html?id=${item.id}>` +
                          "
" +
                            `<div style = background-color:${color}; class = card>` +
                              "
" +
                              "" + item.title + "" +
                              "
" +
                              "
" +
                              `<img id = pic src = ${item.img_url} alt = ${item.title}>` +
                              "
" +
                              "
" +
                              "
" + item.desc + "
" +
                              "
 Daily Price: $" + item.daily_price + "
" +
                              "
" +
                            "
" +
                          "
" +
                        "")

          $items.append($card)
          // i++
        }

        $('.your-class').slick({
          slidesToShow: 3,
          slidesToScroll: 1,
          autoplay: true,
          autoplaySpeed: 3000,
        });
      })
      .fail(() => {
        Materialize.toast('Unable to retrieve items', 3000);
      });
  }

  function createCard(item) {
    // const $anchor = $('')
    //   .attr({
    //     href: `/item.html?id=${item.id}`,
    //     'data-delay': '50',
    //     'data-tooltip': item.title
    //   })
    //   .tooltip();
    //
    // const $card = $('
').addClass('card col s4 m4 l4 ');
    // $card.attr('style', 'padding: 0px; width:371px;')
    // const $cardimage = $('
').addClass('card-image')
    // // $cardimage.attr('style', 'padding-bottom: 30px;')
    // const $cardContent = $('
').addClass('card-content black-text')
    // const $span = $('').addClass('card-title')
    // $span.text(item.title)
    // const $pPrice = $('
')
    // $pPrice.text("Price: $" + item.daily_price + " a day.")
    // const $p = $('
')
    // $p.text('Desc: ' + item.desc)
    // const $img = $('').attr({ src: item.img_url, alt: item.title, height: 200, width: 200, style: 'object-fit: contain;' });
    //
    // $card.append($anchor);
    // $cardimage.append($img)
    // $card.append($cardimage);
    // $cardContent.append($span)
    // $cardContent.append($pPrice)
    // $cardContent.append($p)
    // $card.append($cardContent)
    const $card = (`<a href= item.html?id=${item.id}>` +
                    "
" +
                      "
" +

                        "
" +
                        "" + item.title + "" +
                        "
" +

                        "
" +
                        `<img id = pic src = ${item.img_url} alt = ${item.title}>` +
                        "
" +

                        "
" +
                        "
" + item.desc + "
" +
                        "
 Daily Price: $" + item.daily_price + "
" +
                        "
" +

                      "
" +
                    "
" +
                  "")

    return $card
  }
  $('#myInput').keydown(function (e) {
    e.stopPropagation();
    if (e.keyCode === 40) {
        e.preventDefault();
        console.log(40);
    } else if (e.keyCode === 38) {
        e.preventDefault();
        console.log(38);
    }
  })

  let searches = 0

  $('#myInput').keyup(function (e) {

    if (searches === 0) {
      $('.your-class').children().remove()
      $('.your-class').removeClass('slick-initialized slick-slider')
    }

    searches++

    let input = $('#myInput').val()

    let cat = $('#dropdown').val()

    if (input === '') {

      //check for cat selection
      if (cat != null) {
        searches = 0;
        $('.your-class').empty()
        $('.your-class').removeClass('slick-initialized slick-slider')
        return catFunction()
      }

      searches = 0;
      $('.your-class').empty()
      $('.your-class').removeClass('slick-initialized slick-slider')
      slick()
      return
    }

    let length = input.length

    const $items = $('.your-class');
      $.getJSON('/items')
        .done((items) => {
          console.log(cat)
            for (const item of items) {
              let title = item.title
              let newarr = title.split(" ")

              for (const word of newarr) {
                if (word.slice(0, length).toLowerCase() === input.toLowerCase()) {
                  let card = createCard(item)

                  let alreadyin = false;
                  $items.children().each(function() {
                    const $div = this
                    if ($($div).find('img')[0] === undefined) {
                      console.log('undefined yo')
                      alreadyin = false
                    } else {
                      let name = $($div).find('img')[0].alt
                      if (item.title === name) {
                        console.log('item already in search')
                        alreadyin = true
                      }
                    }
                  })

                  if (alreadyin === true) {

                  } else {

                    //check if matches cat
                    console.log('test' + item.cat)
                    if (cat === 'All' || cat === null) {
                      $items.append(card)
                      break
                    } else {
                      if (cat === item.cat) {
                        $items.append(card)
                        break
                      }
                    }

                  }

                } else {
                  let card = createCard(item)
                  if (word.indexOf(input) !== -1 && input.length !== 1) {

                    let alreadyin = false;
                    console.log($items.children())
                    $items.children().each(function() {
                      const $div = this
                      if ($($div).find('img')[0] === undefined) {
                        console.log('undefined yo')
                      } else {
                        let name = $($div).find('img')[0].alt
                        console.log(name)
                        if (item.title === name) {
                          console.log('item already in search')
                          alreadyin = true
                        }
                      }
                    })

                    if (alreadyin === true) {

                    } else {
                      //check if matches cat
                      console.log(item.cat)
                      if (cat === 'All' || cat === null) {
                        $items.append(card)
                        break
                      } else {
                        if (cat === item.cat) {
                          $items.append(card)
                          break
                        }
                      }
                    }
                  }
                  else {

                  }

                }
              }

            }
        })
        .fail(() => {
          Materialize.toast('Unable to retrieve items', 3000);
        });
  })

    $('.parallax').parallax();

    slick()

});
<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var buster = require("buster-core");

var colorOpt = {
    "none": { color: false, bright: false },
    "dim": { color: true, bright: false },
    "bright": { color: true, bright: true }
};

module.exports = buster.extend(buster.create(require("buster-cli")), {
    missionStatement: "Run Buster.JS tests on node, in browsers, or both",
    usage: "buster-test [options] [filters]",
    description:
        "\nOptionally provide a test name filter to run a selection of tests:\n" +
        "`buster-test configuration` runs all contexts/tests with the word\n" +
        "'configuration' in their name.",
    environmentVariable: "BUSTER_TEST_OPT",

    onRun: function () {
        var options = buster.extend({
            reporter: this.reporter.value,
            filters: this.filters.value,
            cwd: process.cwd(),
            server: this.serverConfig(),
            cacheResources: !this.reset.isSet,
            warnings: this.warnings.value,
            failOn: this.failOn.value,
            captureConsole: this.captureConsole.isSet,
            staticResourcePath: this.staticResourcePath.isSet
        }, colorOpt[this.color.value]);

        this.onConfig(function (err, config) {
            if (err) {
                this.logger.e(err.message);
                if (err.stack) this.logger.e(err.stack);
            } else {
                this.runConfig(config.groups || [], options);
            }
        }.bind(this));
    },

    runConfig: function (groups, options) {
        var runs;
        var runGroup = function (err, results) {
            if (!runs) {
                runs = [];
            } else {
                runs.push({ error: err, results: results });
            }
            var group = groups.shift();
            if (!group) { return process.exit(exitCode(runs)); }
            this.logger.info("Running tests:", group.name);
            this.logger.info("Loading:", "\n  " + files(group).join("\n  "));
            var runner = this.loadRunner(group.environment);
            if (runner) { runner.run(group, options, runGroup); }
        }.bind(this);
        runGroup();
    },

    loadOptions: function () {
        this.addConfigOption();

        this.reporter = this.opt("-r", "--reporter", "Test output reporter", {
            defaultValue: "dots",
            validators: { "reporter": "No such reporter '${1}'" }
        });

        this.color = this.opt("-C", "--color", "Output color scheme", {
            values: ["dim", "bright", "none"],
            defaultValue: "bright"
        });

        this.server = this.opt("-s", "--server", "Hostname and port to a running buster-server instance (for browser tests)", {
            defaultValue: "http://localhost:1111"
        });

        this.reset = this.opt("-R", "--reset",
                              "Don't use cached resources on the server.");

        this.warnings = this.opt("-W", "--warnings", "Warnings to print", {
            values: ["fatal", "error", "warning", "all", "none"],
            defaultValue: "all"
        });

        this.failOn = this.opt("-F", "--fail-on", "Fail on warnings at this level", {
            values: ["fatal", "error", "warning"],
            defaultValue: "fatal"
        });

        this.captureConsole = this.opt(
            "-a",
            "--capture-console",
            "Capture log messages from console.log and friends. Replaces the " +
                "global console object with the buster.console object");

        this.staticResourcePath = this.opt(
            "-p",
            "--static-paths",
            "Serve files over a static URL on the server. Reusing paths "+
                "across test runs makes it possible to use breakpoints, " +
                "but increases the risk of stale resources due to over-eaher " +
                "browser caching");

        this.args.addShorthand("--node", ["-e", "node"]);

        this.filters = this.args.createOperand();
        this.filters.greedy = true;
    },

    serverConfig: function () {
        var server = this.server.value;
        server = (/^:/.test(server) ? "127.0.0.1" : "") + server;
        return (!/^http\:\/\//.test(server) ? "http://" : "") + server;
    },

    loadRunner: function (env, config) {
        var module = "./runners/" + env + "-runner";
        if (!moduleExists(module)) {
            return this.err("Unknown environment '" + env + "'. Try one of:\n" +
                            availableRunners().join(", "));
        }

        var runner = Object.create(require("./runners/" + env + "-runner"));
        runner.logger = this.logger;
        return runner;
    }
});

var EX_SOFTWARE = 70;

function exitCode(runs) {
    for (var i = 0, l = runs.length; i < l; ++i) {
        if (runs[i].error) { return runs[i].error.code || EX_SOFTWARE; }
        if (!runs[i].results.ok) { return 1; }
    }
    return 0;
}

function moduleExists(module) {
    try {
        return fs.statSync(path.join(__dirname, module + ".js")).isFile();
    } catch (e) {
        return false;
    }
}

function availableRunners() {
    return fs.readdirSync(path.join(__dirname, "runners"));
}

module.exports.helpTopics = {};
Object.defineProperty(module.exports.helpTopics, "reporters", {
    enumerable: true,
    get: function () {
        var testReporters = require("buster-test").reporters
        var reporters = Object.keys(testReporters).filter(function (r) {
            return typeof testReporters[r] == "object";
        });

        return "Buster.JS ships with a set of built-in reporters. These can be used by\n" +
"providing the name to the -r/--reporter option:\n" +
"buster-test -r dots\n\n" +
"The dots reporter is the default reporter. Built-in reporters\n" +
"include:\n" + reporters.join("\n") + "\n\n" +
"Custom reporters\n" +
"Buster.JS can use custom reporters that are reachable through the node\n" +
"module system. Assume you have a reporter that looks like:\n\n" +
"module.exports = {\n" +
"    create: function (options) {\n" +
"        // ...\n" +
"    },\n\n" +
"    listen: function (runner) {\n" +
"        // ...\n" +
"    },\n\n" +
"    // ...\n" +
"};\n\n" +
"When this reporter is available on the node load path, say in the\n" +
"my-reporter module, you can use it the following way:\n" +
"`buster-test -r my-reporter`\n\n" +
"If your module is not the main export from the module, you can provide the\n" +
"'path' to the correct object using the following syntax: \n" +
"`buster-test -r my-reporters#console.fancy`\n\n" +
"This will cause Buster to load the `my-reporters' module, and try to use\n" +
"the `console.fancy' object exported from it.\n\n" +
"The BUSTER_REPORTER environment variable\n" +
"If you want a different reporter, but don't want to specify it for each\n" +
"run, you can specify the BUSTER_REPORTER environment variable in e.g. ,\n" +
".bashrc and Buster will use this reporter as long as another one is not\n" +
"specified with the -r option.\n\n" +
"For information on implementing custom reporters, refer to the online docs\n" +
"at http://busterjs.org/docs/buster-test/reporters/";
    }
});

require("buster-args").validators.reporter = function (errMsg) {
    return function (arg, promise) {
        try {
            require("buster-test").reporters.load(arg.value);
            promise.resolve();
        } catch (e) {
            promise.reject(
                arg.signature + ": " + errMsg.replace("${1}", arg.value) +
                    "\n" + e.message + "\nLearn more about reporters with " +
                    "`buster-test -h reporters`");
        }
    };
};

function files(config) {
    return config.resourceSet && config.resourceSet.load || [];
}
<commit_msg>Add --browser option<commit_after>var fs = require("fs");
var path = require("path");
var buster = require("buster-core");

var colorOpt = {
    "none": { color: false, bright: false },
    "dim": { color: true, bright: false },
    "bright": { color: true, bright: true }
};

module.exports = buster.extend(buster.create(require("buster-cli")), {
    missionStatement: "Run Buster.JS tests on node, in browsers, or both",
    usage: "buster-test [options] [filters]",
    description:
        "\nOptionally provide a test name filter to run a selection of tests:\n" +
        "`buster-test configuration` runs all contexts/tests with the word\n" +
        "'configuration' in their name.",
    environmentVariable: "BUSTER_TEST_OPT",

    onRun: function () {
        var options = buster.extend({
            reporter: this.reporter.value,
            filters: this.filters.value,
            cwd: process.cwd(),
            server: this.serverConfig(),
            cacheResources: !this.reset.isSet,
            warnings: this.warnings.value,
            failOn: this.failOn.value,
            captureConsole: this.captureConsole.isSet,
            staticResourcePath: this.staticResourcePath.isSet
        }, colorOpt[this.color.value]);

        this.onConfig(function (err, config) {
            if (err) {
                this.logger.e(err.message);
                if (err.stack) this.logger.e(err.stack);
            } else {
                this.runConfig(config.groups || [], options);
            }
        }.bind(this));
    },

    runConfig: function (groups, options) {
        var runs;
        var runGroup = function (err, results) {
            if (!runs) {
                runs = [];
            } else {
                runs.push({ error: err, results: results });
            }
            var group = groups.shift();
            if (!group) { return process.exit(exitCode(runs)); }
            this.logger.info("Running tests:", group.name);
            this.logger.info("Loading:", "\n  " + files(group).join("\n  "));
            var runner = this.loadRunner(group.environment);
            if (runner) { runner.run(group, options, runGroup); }
        }.bind(this);
        runGroup();
    },

    loadOptions: function () {
        this.addConfigOption();

        this.reporter = this.opt("-r", "--reporter", "Test output reporter", {
            defaultValue: "dots",
            validators: { "reporter": "No such reporter '${1}'" }
        });

        this.color = this.opt("-C", "--color", "Output color scheme", {
            values: ["dim", "bright", "none"],
            defaultValue: "bright"
        });

        this.server = this.opt("-s", "--server", "Hostname and port to a running buster-server instance (for browser tests)", {
            defaultValue: "http://localhost:1111"
        });

        this.reset = this.opt("-R", "--reset",
                              "Don't use cached resources on the server.");

        this.warnings = this.opt("-W", "--warnings", "Warnings to print", {
            values: ["fatal", "error", "warning", "all", "none"],
            defaultValue: "all"
        });

        this.failOn = this.opt("-F", "--fail-on", "Fail on warnings at this level", {
            values: ["fatal", "error", "warning"],
            defaultValue: "fatal"
        });

        this.captureConsole = this.opt(
            "-a",
            "--capture-console",
            "Capture log messages from console.log and friends. Replaces the " +
                "global console object with the buster.console object");

        this.staticResourcePath = this.opt(
            "-p",
            "--static-paths",
            "Serve files over a static URL on the server. Reusing paths "+
                "across test runs makes it possible to use breakpoints, " +
                "but increases the risk of stale resources due to over-eaher " +
                "browser caching");

        this.args.addShorthand("--node", ["-e", "node"]);
        this.args.addShorthand("--browser", ["-e", "browser"]);

        this.filters = this.args.createOperand();
        this.filters.greedy = true;
    },

    serverConfig: function () {
        var server = this.server.value;
        server = (/^:/.test(server) ? "127.0.0.1" : "") + server;
        return (!/^http\:\/\//.test(server) ? "http://" : "") + server;
    },

    loadRunner: function (env, config) {
        var module = "./runners/" + env + "-runner";
        if (!moduleExists(module)) {
            return this.err("Unknown environment '" + env + "'. Try one of:\n" +
                            availableRunners().join(", "));
        }

        var runner = Object.create(require("./runners/" + env + "-runner"));
        runner.logger = this.logger;
        return runner;
    }
});

var EX_SOFTWARE = 70;

function exitCode(runs) {
    for (var i = 0, l = runs.length; i < l; ++i) {
        if (runs[i].error) { return runs[i].error.code || EX_SOFTWARE; }
        if (!runs[i].results.ok) { return 1; }
    }
    return 0;
}

function moduleExists(module) {
    try {
        return fs.statSync(path.join(__dirname, module + ".js")).isFile();
    } catch (e) {
        return false;
    }
}

function availableRunners() {
    return fs.readdirSync(path.join(__dirname, "runners"));
}

module.exports.helpTopics = {};
Object.defineProperty(module.exports.helpTopics, "reporters", {
    enumerable: true,
    get: function () {
        var testReporters = require("buster-test").reporters
        var reporters = Object.keys(testReporters).filter(function (r) {
            return typeof testReporters[r] == "object";
        });

        return "Buster.JS ships with a set of built-in reporters. These can be used by\n" +
"providing the name to the -r/--reporter option:\n" +
"buster-test -r dots\n\n" +
"The dots reporter is the default reporter. Built-in reporters\n" +
"include:\n" + reporters.join("\n") + "\n\n" +
"Custom reporters\n" +
"Buster.JS can use custom reporters that are reachable through the node\n" +
"module system. Assume you have a reporter that looks like:\n\n" +
"module.exports = {\n" +
"    create: function (options) {\n" +
"        // ...\n" +
"    },\n\n" +
"    listen: function (runner) {\n" +
"        // ...\n" +
"    },\n\n" +
"    // ...\n" +
"};\n\n" +
"When this reporter is available on the node load path, say in the\n" +
"my-reporter module, you can use it the following way:\n" +
"`buster-test -r my-reporter`\n\n" +
"If your module is not the main export from the module, you can provide the\n" +
"'path' to the correct object using the following syntax: \n" +
"`buster-test -r my-reporters#console.fancy`\n\n" +
"This will cause Buster to load the `my-reporters' module, and try to use\n" +
"the `console.fancy' object exported from it.\n\n" +
"The BUSTER_REPORTER environment variable\n" +
"If you want a different reporter, but don't want to specify it for each\n" +
"run, you can specify the BUSTER_REPORTER environment variable in e.g. ,\n" +
".bashrc and Buster will use this reporter as long as another one is not\n" +
"specified with the -r option.\n\n" +
"For information on implementing custom reporters, refer to the online docs\n" +
"at http://busterjs.org/docs/buster-test/reporters/";
    }
});

require("buster-args").validators.reporter = function (errMsg) {
    return function (arg, promise) {
        try {
            require("buster-test").reporters.load(arg.value);
            promise.resolve();
        } catch (e) {
            promise.reject(
                arg.signature + ": " + errMsg.replace("${1}", arg.value) +
                    "\n" + e.message + "\nLearn more about reporters with " +
                    "`buster-test -h reporters`");
        }
    };
};

function files(config) {
    return config.resourceSet && config.resourceSet.load || [];
}
<|endoftext|>


<commit_before>import * as d3 from 'd3';
import _ from 'lodash';

export default class D3ForceLayout {
  constructor({ renderCallback }) {
    const forceSimulation = d3.forceSimulation();
    this.forceSimulation = forceSimulation;

    const forceManyBody = d3.forceManyBody();
    forceManyBody.strength(-140);
    forceManyBody.distanceMin(70);
    this.forceManyBody = forceManyBody;

    const forceCenter = d3.forceCenter();
    this.forceCenter = forceCenter;

    const forceLink = d3.forceLink();
    forceLink.id(d => d.id);
    forceLink.strength((link) => {
      switch (link.type) {
        case 'contain':
          return 0.12;
        case 'depend':
          return 0.10;
        default:
          return 0;
      }
    });
    this.forceLink = forceLink;

    // Connect Forces
    forceSimulation.force('forceManyBody', forceManyBody);
    forceSimulation.force('forceLink', forceLink);
    forceSimulation.force('forceCenter', forceCenter);

    // setter
    this.renderCallback = renderCallback;
  }

  get nodes() {
    return this.forceSimulation.nodes();
  }

  get links() {
    return this.forceLink.links();
  }

  addNodes(newNodes) {
    const nodes = this.forceSimulation.nodes();
    nodes.push(...newNodes);
    this.forceSimulation.nodes(nodes);
  }

  updateNodes(changedNodes) {
    const oldNodes = this.nodes;

    changedNodes.forEach((newNode) => {
      const oldNode = _.find(oldNodes, (n) => n.id === newNode.id);
      if (oldNode) {
        Object.assign(oldNode, newNode);
      } else {
        throw new Error(`node ${newNode} is changed but coudln't find it`);
      }
    });
  }

  addLinks(newLinks) {
    const links = this.forceLink.links();
    links.push(...newLinks);
    this.forceLink.links(links);
  }

  static EVENTS = {
    NODE_CLICK: 'node.click',
  };

  set containerDOM(containerDOM) {
    this._containerDOM = containerDOM;

    this._bindEventToContainerDom();
  }

  get containerDOM() {
    return this._containerDOM;
  }

  _bindEventToContainerDom() {
    d3.select(this.containerDOM)
      .call(
        d3.drag()
          .container(this.containerDOM)
          .subject(() =>
            this.forceSimulation.find(
              d3.event.x,
              d3.event.y
            )
          )
          .on('start', () => {
            if (!d3.event.active) this.forceSimulation.alphaTarget(0.3).restart();
            d3.event.subject.fx = d3.event.subject.x;
            d3.event.subject.fy = d3.event.subject.y;
          })
          .on('drag', () => {
            d3.event.subject.fx = d3.event.x;
            d3.event.subject.fy = d3.event.y;
          })
          .on('end', () => {
            if (!d3.event.active) this.forceSimulation.alphaTarget(0);
            d3.event.subject.fx = null;
            d3.event.subject.fy = null;
          })
      );
  }

  set forceSimulationSize(size) {
    this._forceSimulationSize = size;

    // Update Force Center
    this.forceCenter.x(size.width * 0.5);
    this.forceCenter.y(size.height * 0.5);

    // Update Bounding Box
    this.forceSimulation.on('tick.boundsForce', () => {
      this.nodes.forEach((node) => {
        const padding = 50;
        Object.assign(node, {
          x: Math.max(padding, Math.min(size.width - padding, node.x)),
          y: Math.max(padding, Math.min(size.height - padding, node.y)),
        });
      });

      this.renderCallback();
    });

    // Restart
    this.forceSimulation.restart();
  }

  get forceSimulationSize() {
    return this._forceSimulationSize;
  }
}
<commit_msg>change force layout<commit_after>import * as d3 from 'd3';
import _ from 'lodash';

export default class D3ForceLayout {
  constructor({ renderCallback }) {
    const forceSimulation = d3.forceSimulation();
    this.forceSimulation = forceSimulation;

    const forceManyBody = d3.forceManyBody();
    forceManyBody.strength(-140);
    forceManyBody.distanceMin(70);
    forceManyBody.distanceMax(140);
    this.forceManyBody = forceManyBody;

    const forceCenter = d3.forceCenter();
    this.forceCenter = forceCenter;

    const forceLink = d3.forceLink();
    forceLink.id(d => d.id);
    forceLink.strength((link) => {
      switch (link.type) {
        case 'contain':
          return 0.12;
        case 'depend':
          return 0.10;
        default:
          return 0;
      }
    });
    this.forceLink = forceLink;

    // Connect Forces
    forceSimulation.force('forceManyBody', forceManyBody);
    forceSimulation.force('forceLink', forceLink);
    forceSimulation.force('forceCenter', forceCenter);

    // setter
    this.renderCallback = renderCallback;
  }

  get nodes() {
    return this.forceSimulation.nodes();
  }

  get links() {
    return this.forceLink.links();
  }

  addNodes(newNodes) {
    const nodes = this.forceSimulation.nodes();
    nodes.push(...newNodes);
    this.forceSimulation.nodes(nodes);
  }

  updateNodes(changedNodes) {
    const oldNodes = this.nodes;

    changedNodes.forEach((newNode) => {
      const oldNode = _.find(oldNodes, (n) => n.id === newNode.id);
      if (oldNode) {
        Object.assign(oldNode, newNode);
      } else {
        throw new Error(`node ${newNode} is changed but coudln't find it`);
      }
    });
  }

  addLinks(newLinks) {
    const links = this.forceLink.links();
    links.push(...newLinks);
    this.forceLink.links(links);
  }

  static EVENTS = {
    NODE_CLICK: 'node.click',
  };

  set containerDOM(containerDOM) {
    this._containerDOM = containerDOM;

    this._bindEventToContainerDom();
  }

  get containerDOM() {
    return this._containerDOM;
  }

  _bindEventToContainerDom() {
    d3.select(this.containerDOM)
      .call(
        d3.drag()
          .container(this.containerDOM)
          .subject(() =>
            this.forceSimulation.find(
              d3.event.x,
              d3.event.y
            )
          )
          .on('start', () => {
            if (!d3.event.active) this.forceSimulation.alphaTarget(0.3).restart();
            d3.event.subject.fx = d3.event.subject.x;
            d3.event.subject.fy = d3.event.subject.y;
          })
          .on('drag', () => {
            d3.event.subject.fx = d3.event.x;
            d3.event.subject.fy = d3.event.y;
          })
          .on('end', () => {
            if (!d3.event.active) this.forceSimulation.alphaTarget(0);
            d3.event.subject.fx = null;
            d3.event.subject.fy = null;
          })
      );
  }

  set forceSimulationSize(size) {
    this._forceSimulationSize = size;

    // Update Force Center
    this.forceCenter.x(size.width * 0.5);
    this.forceCenter.y(size.height * 0.5);

    // Update Bounding Box
    this.forceSimulation.on('tick.boundsForce', () => {
      this.nodes.forEach((node) => {
        const padding = 50;
        Object.assign(node, {
          x: Math.max(padding, Math.min(size.width - padding, node.x)),
          y: Math.max(padding, Math.min(size.height - padding, node.y)),
        });
      });

      this.renderCallback();
    });

    // Restart
    this.forceSimulation.restart();
  }

  get forceSimulationSize() {
    return this._forceSimulationSize;
  }
}
<|endoftext|>


<commit_before>/* jshint strict: false, sub: true */
/* global print */
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / DISCLAIMER
// /
// / Copyright 2016 ArangoDB GmbH, Cologne, Germany
// / Copyright 2014 triagens GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is ArangoDB GmbH, Cologne, Germany
// /
// / @author Max Neunhoeffer
// //////////////////////////////////////////////////////////////////////////////

const functionsDocumentation = {
  'recovery': 'run recovery tests'
};
const optionsDocumentation = [
];

const fs = require('fs');
const pu = require('@arangodb/process-utils');
const tu = require('@arangodb/test-utils');
const _ = require('lodash');

const toArgv = require('internal').toArgv;

const RED = require('internal').COLORS.COLOR_RED;
const RESET = require('internal').COLORS.COLOR_RESET;
const BLUE = require('internal').COLORS.COLOR_BLUE;

const testPaths = {
  'recovery': [tu.pathForTesting('server/recovery')]
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief TEST: recovery
// //////////////////////////////////////////////////////////////////////////////

function runArangodRecovery (params) {
  let argv = [];

  if (params.setup) {
    params.options.disableMonitor = true;
    params.testDir = fs.join(params.tempDir, `${params.count}`);
    pu.cleanupDBDirectoriesAppend(params.testDir);
    let dataDir = fs.join(params.testDir, 'data');
    let appDir = fs.join(params.testDir, 'app');
    let tmpDir = fs.join(params.testDir, 'tmp');
    fs.makeDirectoryRecursive(params.testDir);
    fs.makeDirectoryRecursive(dataDir);
    fs.makeDirectoryRecursive(tmpDir);
    fs.makeDirectoryRecursive(appDir);

    let args = pu.makeArgs.arangod(params.options, appDir, '', tmpDir);
    // enable development debugging if extremeVerbosity is set
    if (params.options.extremeVerbosity === true) {
      args['log.level'] = 'development=info';
    }
    args = Object.assign(args, params.options.extraArgs);
    args = Object.assign(args, {
      'wal.reserve-logfiles': 1,
      'rocksdb.wal-file-timeout-initial': 10,
      'database.directory': fs.join(dataDir + 'db'),
      'server.rest-server': 'false',
      'replication.auto-start': 'true',
      'javascript.script': params.script
    });
    params.args = args;

    argv = toArgv(
      Object.assign(params.args,
                    {
                      'javascript.script-parameter': 'setup'
                    }
                   )
    );
  } else {
    argv = toArgv(
      Object.assign(params.args,
                    {
                      'wal.ignore-logfile-errors': 'true',
                      'javascript.script-parameter': 'recovery'
                    }
                   )
    );
  }
  params.instanceInfo.pid = pu.executeAndWait(
    pu.ARANGOD_BIN,
    argv,
    params.options,
    'recovery',
    params.instanceInfo.rootDir,
    params.setup,
    !params.setup && params.options.coreCheck);
}

function recovery (options) {
  if (!global.ARANGODB_CLIENT_VERSION(true)['failure-tests'] ||
      global.ARANGODB_CLIENT_VERSION(true)['failure-tests'] === 'false') {
    return {
      recovery: {
        status: false,
        message: 'failure-tests not enabled. please recompile with -DUSE_FAILURE_TESTS=On'
      },
      status: false
    };
  }

  let results = {
    status: true
  };

  let recoveryTests = tu.scanTestPaths(testPaths.recovery);

  recoveryTests = tu.splitBuckets(options, recoveryTests);

  let count = 0;
  let orgTmp = process.env.TMPDIR;
  let tempDir = fs.join(fs.getTempPath(), 'crashtmp');
  fs.makeDirectoryRecursive(tempDir);
  process.env.TMPDIR = tempDir;
  pu.cleanupDBDirectoriesAppend(tempDir);

  for (let i = 0; i < recoveryTests.length; ++i) {
    let test = recoveryTests[i];
    let filtered = {};

    if (tu.filterTestcaseByOptions(test, options, filtered)) {
      count += 1;
      ////////////////////////////////////////////////////////////////////////
      print(BLUE + "running setup of test " + count + " - " + test + RESET);
      let params = {
        tempDir: tempDir,
        instanceInfo: {
          rootDir: pu.UNITTESTS_DIR
        },
        options: _.cloneDeep(options),
        script: test,
        setup: true,
        count: count,
        testDir: ""
      };
      runArangodRecovery(params);

      ////////////////////////////////////////////////////////////////////////
      print(BLUE + "running recovery of test " + count + " - " + test + RESET);
      params.options.disableMonitor = options.disableMonitor;
      params.setup = false;
      runArangodRecovery(params);

      results[test] = tu.readTestResult(
        params.args['temp.path'],
        {
          status: false
        }
      );
      if (!results[test].status) {
        print("Not cleaning up " + params.testDir);
        results.status = false;
      }
      else {
        options.cleanup = false;
        pu.cleanupLastDirectory(params.options);
      }
    } else {
      if (options.extremeVerbosity) {
        print('Skipped ' + test + ' because of ' + filtered.filter);
      }
    }
  }
  process.env.TMPDIR = orgTmp;
  if (count === 0) {
    print(RED + 'No testcase matched the filter.' + RESET);
    return {
      ALLTESTS: {
        status: false,
        skipped: true
      },
      status: false
    };
  }

  return results;
}

exports.setup = function (testFns, defaultFns, opts, fnDocs, optionsDoc, allTestPaths) {
  Object.assign(allTestPaths, testPaths);
  testFns['recovery'] = recovery;
  for (var attrname in functionsDocumentation) { fnDocs[attrname] = functionsDocumentation[attrname]; }
  for (var i = 0; i < optionsDocumentation.length; i++) { optionsDoc.push(optionsDocumentation[i]); }
};
<commit_msg>fix test status (#7456)<commit_after>/* jshint strict: false, sub: true */
/* global print */
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / DISCLAIMER
// /
// / Copyright 2016 ArangoDB GmbH, Cologne, Germany
// / Copyright 2014 triagens GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is ArangoDB GmbH, Cologne, Germany
// /
// / @author Max Neunhoeffer
// //////////////////////////////////////////////////////////////////////////////

const functionsDocumentation = {
  'recovery': 'run recovery tests'
};
const optionsDocumentation = [
];

const fs = require('fs');
const pu = require('@arangodb/process-utils');
const tu = require('@arangodb/test-utils');
const _ = require('lodash');

const toArgv = require('internal').toArgv;

const RED = require('internal').COLORS.COLOR_RED;
const RESET = require('internal').COLORS.COLOR_RESET;
const BLUE = require('internal').COLORS.COLOR_BLUE;

const testPaths = {
  'recovery': [tu.pathForTesting('server/recovery')]
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief TEST: recovery
// //////////////////////////////////////////////////////////////////////////////

function runArangodRecovery (params) {
  let argv = [];

  if (params.setup) {
    params.options.disableMonitor = true;
    params.testDir = fs.join(params.tempDir, `${params.count}`);
    pu.cleanupDBDirectoriesAppend(params.testDir);
    let dataDir = fs.join(params.testDir, 'data');
    let appDir = fs.join(params.testDir, 'app');
    let tmpDir = fs.join(params.testDir, 'tmp');
    fs.makeDirectoryRecursive(params.testDir);
    fs.makeDirectoryRecursive(dataDir);
    fs.makeDirectoryRecursive(tmpDir);
    fs.makeDirectoryRecursive(appDir);

    let args = pu.makeArgs.arangod(params.options, appDir, '', tmpDir);
    // enable development debugging if extremeVerbosity is set
    if (params.options.extremeVerbosity === true) {
      args['log.level'] = 'development=info';
    }
    args = Object.assign(args, params.options.extraArgs);
    args = Object.assign(args, {
      'wal.reserve-logfiles': 1,
      'rocksdb.wal-file-timeout-initial': 10,
      'database.directory': fs.join(dataDir + 'db'),
      'server.rest-server': 'false',
      'replication.auto-start': 'true',
      'javascript.script': params.script
    });
    params.args = args;

    argv = toArgv(
      Object.assign(params.args,
                    {
                      'javascript.script-parameter': 'setup'
                    }
                   )
    );
  } else {
    argv = toArgv(
      Object.assign(params.args,
                    {
                      'wal.ignore-logfile-errors': 'true',
                      'javascript.script-parameter': 'recovery'
                    }
                   )
    );
  }
  params.instanceInfo.pid = pu.executeAndWait(
    pu.ARANGOD_BIN,
    argv,
    params.options,
    'recovery',
    params.instanceInfo.rootDir,
    params.setup,
    !params.setup && params.options.coreCheck);
}

function recovery (options) {
  if (!global.ARANGODB_CLIENT_VERSION(true)['failure-tests'] ||
      global.ARANGODB_CLIENT_VERSION(true)['failure-tests'] === 'false') {
    return {
      recovery: {
        status: false,
        message: 'failure-tests not enabled. please recompile with -DUSE_FAILURE_TESTS=On'
      },
      status: false
    };
  }

  let results = {
    status: true
  };

  let recoveryTests = tu.scanTestPaths(testPaths.recovery);

  recoveryTests = tu.splitBuckets(options, recoveryTests);

  let count = 0;
  let orgTmp = process.env.TMPDIR;
  let tempDir = fs.join(fs.getTempPath(), 'crashtmp');
  fs.makeDirectoryRecursive(tempDir);
  process.env.TMPDIR = tempDir;
  pu.cleanupDBDirectoriesAppend(tempDir);

  for (let i = 0; i < recoveryTests.length; ++i) {
    let test = recoveryTests[i];
    let filtered = {};

    if (tu.filterTestcaseByOptions(test, options, filtered)) {
      count += 1;
      ////////////////////////////////////////////////////////////////////////
      print(BLUE + "running setup of test " + count + " - " + test + RESET);
      let params = {
        tempDir: tempDir,
        instanceInfo: {
          rootDir: pu.UNITTESTS_DIR
        },
        options: _.cloneDeep(options),
        script: test,
        setup: true,
        count: count,
        testDir: ""
      };
      runArangodRecovery(params);

      ////////////////////////////////////////////////////////////////////////
      print(BLUE + "running recovery of test " + count + " - " + test + RESET);
      params.options.disableMonitor = options.disableMonitor;
      params.setup = false;
      runArangodRecovery(params);

      results[test] = tu.readTestResult(
        params.args['temp.path'],
        {
          status: false
        }
      );
      if (!results[test].status) {
        print("Not cleaning up " + params.testDir);
        results.status = false;
      }
      else {
        pu.cleanupLastDirectory(params.options);
      }
    } else {
      if (options.extremeVerbosity) {
        print('Skipped ' + test + ' because of ' + filtered.filter);
      }
    }
  }
  process.env.TMPDIR = orgTmp;
  if (count === 0) {
    print(RED + 'No testcase matched the filter.' + RESET);
    return {
      ALLTESTS: {
        status: false,
        skipped: true
      },
      status: false
    };
  }

  return results;
}

exports.setup = function (testFns, defaultFns, opts, fnDocs, optionsDoc, allTestPaths) {
  Object.assign(allTestPaths, testPaths);
  testFns['recovery'] = recovery;
  for (var attrname in functionsDocumentation) { fnDocs[attrname] = functionsDocumentation[attrname]; }
  for (var i = 0; i < optionsDocumentation.length; i++) { optionsDoc.push(optionsDocumentation[i]); }
};
<|endoftext|>


<commit_before>var MovableWindow = function(width,height,titleText,id) {

	width = width || 300;
	height = height || 200;
	titleText = titleText || '';

	var container = $(	'
' +
							'
' +
								'' + titleText + '' +
								'' +
							'
' +
							'

' +
						'
')
							.appendTo( $(document.body) )
							.hide(),
		header = container.find('.movable-header'),
		title = container.find('.movable-header-title'),
		body = container.find('.movable-body'),
		close = container.find('.close-button'),
		win = $(window),
		doc = $(document),

		startWindowPosition = null,
		startMousePosition = null;

	header.on('mousedown', function(e) {
		doc
			.on('mousemove', move)
			.on('mouseup', mouseup);

		startWindowPosition = container.offset();
		startMousePosition = {x:e.clientX, y:e.clientY};
	});

	function mouseup() {
		doc
			.off('mousemove', move)
			.off('mouseup', mouseup);
	}

	function move(e) {
		// handle move
		//console.log(e);

		container.css({
			top: startWindowPosition.top - (startMousePosition.y - e.clientY),
			left: startWindowPosition.left - (startMousePosition.x - e.clientX)
		});
	}

	close.on('click', hide);

	function size(width, height) {

		body.width(width);
		body.height(height);

		return ext;
	}
	size(width, height);
	center();

	function show() {
		container.show();
		return ext;
	}
	function hide() {
		container.hide();
		return ext;
	}
	function center() {
		var
			infoWidth = container.outerWidth(),
			infoHeight = container.outerHeight();

		container.css({
			top: win.height()/2 - infoHeight/2,
			left: win.width()/2 - infoWidth/2
		});

		return ext;
	}

	var ext = {
		show: show,
		hide: hide,
		size: size,
		container: container,
		body: body,
		title: title,
		center: center
	};

	return ext;

};<commit_msg>ensure it doesn't go -x<commit_after>var MovableWindow = function(width,height,titleText,id) {

	width = width || 300;
	height = height || 200;
	titleText = titleText || '';

	var container = $(	'
' +
							'
' +
								'' + titleText + '' +
								'' +
							'
' +
							'

' +
						'
')
							.appendTo( $(document.body) )
							.hide(),
		header = container.find('.movable-header'),
		title = container.find('.movable-header-title'),
		body = container.find('.movable-body'),
		close = container.find('.close-button'),
		win = $(window),
		doc = $(document),

		startWindowPosition = null,
		startMousePosition = null;

	header.on('mousedown', function(e) {
		doc
			.on('mousemove', move)
			.on('mouseup', mouseup);

		startWindowPosition = container.offset();
		startMousePosition = {x:e.clientX, y:e.clientY};
	});

	function mouseup() {
		doc
			.off('mousemove', move)
			.off('mouseup', mouseup);
	}

	function move(e) {
		// handle move
		//console.log(e);

		container.css({
			top: startWindowPosition.top - (startMousePosition.y - e.clientY),
			left: startWindowPosition.left - (startMousePosition.x - e.clientX)
		});
	}

	close.on('click', hide);

	function size(width, height) {

		body.width(width);
		body.height(height);

		return ext;
	}
	size(width, height);
	center();

	function show() {
		container.show();
		return ext;
	}
	function hide() {
		container.hide();
		return ext;
	}
	function center() {
		var
			infoWidth = container.outerWidth(),
			infoHeight = container.outerHeight(),
			top = win.height()/2 - infoHeight/2,
			left = win.width()/2 - infoWidth/2;

		if (top < 0) {
			top = 0;
		}
		if (left < 0) {
			left = 0;
		}

		container.css({
			top: top,
			left: left
		});

		return ext;
	}

	var ext = {
		show: show,
		hide: hide,
		size: size,
		container: container,
		body: body,
		title: title,
		center: center
	};

	return ext;

};<|endoftext|>


<commit_before>describe("sap.m.SemanticPage", function() {

	var fnClickThenCompare = function (sId, sImageName, sTestMessage) {
		it(sTestMessage, function () {
			element(by.id(sId)).click();
			expect(takeScreenshot()).toLookAs(sImageName);
		});
	}

	it("Should load test page",function(){
		expect(takeScreenshot()).toLookAs("semantic-initial");
	});

	//messages indicator
	fnClickThenCompare("addMessagesBtn", "semantic-messages-indicator", "should show a messages indicator");
	fnClickThenCompare("clearMessagesBtn", "semantic-messages-cleared", "should not show a messages indicator");

	//draft indicator
	fnClickThenCompare("showDraftSavedBtn", "semantic-saved-draft", "should show a label for draft saved");
	fnClickThenCompare("clearDraftStateBtn", "semantic-draft-cleared", "should not show a draft label");

	//footer show/hide
	fnClickThenCompare("showHideFooterBtn", "semantic-no-footer", "should not show a page footer");
	fnClickThenCompare("showHideFooterBtn", "semantic-with-footer", "should show a page footer");

	//multiselect on/off databinding
	fnClickThenCompare("toggleMultiselectPressedBtn", "semantic-multiselect-by-databinding-on", "should show a multiselect-cancel button");
	fnClickThenCompare("toggleMultiselectPressedBtn", "semantic-multiselect-by-databinding-off", "should show a multiselect button");

	//multiselect enable/disable
	fnClickThenCompare("toggleMultiselectEnabledBtn", "semantic-multiselect-disabled", "should show a disabled multiselect button");
	fnClickThenCompare("toggleMultiselectEnabledBtn", "semantic-multiselect-enabled", "should show an enabled multiselect button");

	//multiselect on/off
	fnClickThenCompare("multiselectAction-toggleButton", "semantic-multiselect-on", "should show a multiselect-cancel button");
	fnClickThenCompare("multiselectAction-toggleButton", "semantic-multiselect-off", "should show a multiselect button");

	//favorite on/off
	fnClickThenCompare("favoriteAction-toggleButton", "semantic-favorite-on", "should show a favorite emphasized button");
	fnClickThenCompare("favoriteAction-toggleButton", "semantic-favorite-off", "should show a favorite non-emphasized button");

	//flag on/off
	fnClickThenCompare("flagAction-toggleButton", "semantic-flag-on", "should show a flag emphasized button");
	fnClickThenCompare("flagAction-toggleButton", "semantic-flag-off", "should show a flag non-emphasized button");

	//sort select on/off
	fnClickThenCompare("sortSelect-select", "semantic-sort-select-options", "should open select options");
	fnClickThenCompare("sortSelect-select", "semantic-sort-select-no-options", "should hide select options");

	//stateless actions
	fnClickThenCompare("addAction-button", "semantic-add-action", "should trigger add action");
	fnClickThenCompare("filterAction-button", "semantic-filter-action", "should trigger filter action");
	fnClickThenCompare("groupAction-button", "semantic-group-action", "should trigger group action");
	fnClickThenCompare("mainAction-button", "semantic-main-action", "should trigger main action");
	fnClickThenCompare("editAction-button", "semantic-edit-action", "should trigger edit action");
	fnClickThenCompare("saveAction-button", "semantic-save-action", "should trigger save action");
	fnClickThenCompare("deleteAction-button", "semantic-delete-action", "should trigger delete action");
	fnClickThenCompare("positiveAction-button", "semantic-positive-action", "should trigger positive action");
	fnClickThenCompare("negativeAction-button", "semantic-negative-action", "should trigger negative action");
	fnClickThenCompare("cancelAction-button", "semantic-cancel-action", "should trigger cancel action");
	fnClickThenCompare("forwardAction-button", "semantic-forward-action", "should trigger forward action");

	//share menu
	fnClickThenCompare("detail-shareButton", "semantic-share-menu-expanded", "should expand the share menu");

});
<commit_msg>[INTERNAL] sap.m.semantic.SemanticPage: Made visual test independent on resolution<commit_after>describe("sap.m.SemanticPage", function() {

	var fnClickThenCompare = function (sId, sImageName, sTestMessage, bEnsureOverflowVisible) {
		it(sTestMessage, function () {

			if (bEnsureOverflowVisible) {
				fnEnsureOverflowVisible();
			}
			element(by.id(sId)).click();
			expect(takeScreenshot()).toLookAs(sImageName);
		});
	}

	var fnEnsureOverflowVisible = function() {
		var overflowBtn = element(by.id("detail-footer-overflowButton"));
		overflowBtn.isPresent().then(function(isPresent) {
			if(isPresent) {
				overflowBtn.click(); // we ensure that any buttons in overflow are also visible
			}
		})

	}

	it("Should load test page",function(){
		expect(takeScreenshot()).toLookAs("semantic-initial");
	});

	//messages indicator
	fnClickThenCompare("addMessagesBtn", "semantic-messages-indicator", "should show a messages indicator");
	fnClickThenCompare("clearMessagesBtn", "semantic-messages-cleared", "should not show a messages indicator");

	//draft indicator
	fnClickThenCompare("showDraftSavedBtn", "semantic-saved-draft", "should show a label for draft saved");
	fnClickThenCompare("clearDraftStateBtn", "semantic-draft-cleared", "should not show a draft label");

	//footer show/hide
	fnClickThenCompare("showHideFooterBtn", "semantic-no-footer", "should not show a page footer");
	fnClickThenCompare("showHideFooterBtn", "semantic-with-footer", "should show a page footer");

	//multiselect on/off databinding
	fnClickThenCompare("toggleMultiselectPressedBtn", "semantic-multiselect-by-databinding-on", "should show a multiselect-cancel button");
	fnClickThenCompare("toggleMultiselectPressedBtn", "semantic-multiselect-by-databinding-off", "should show a multiselect button");

	//multiselect enable/disable
	fnClickThenCompare("toggleMultiselectEnabledBtn", "semantic-multiselect-disabled", "should show a disabled multiselect button");
	fnClickThenCompare("toggleMultiselectEnabledBtn", "semantic-multiselect-enabled", "should show an enabled multiselect button");

	//multiselect on/off
	fnClickThenCompare("multiselectAction-toggleButton", "semantic-multiselect-on", "should show a multiselect-cancel button");
	fnClickThenCompare("multiselectAction-toggleButton", "semantic-multiselect-off", "should show a multiselect button");

	 //favorite on/off
	 fnClickThenCompare("favoriteAction-toggleButton", "semantic-favorite-on", "should show a favorite emphasized button", true);
	 fnClickThenCompare("favoriteAction-toggleButton", "semantic-favorite-off", "should show a favorite non-emphasized button", true);

	//flag on/off
	fnClickThenCompare("flagAction-toggleButton", "semantic-flag-on", "should show a flag emphasized button", true);
	fnClickThenCompare("flagAction-toggleButton", "semantic-flag-off", "should show a flag non-emphasized button", true);

	//sort select on/off
	fnClickThenCompare("sortSelect-select", "semantic-sort-select-options", "should open select options");
	fnClickThenCompare("sortSelect-select", "semantic-sort-select-no-options", "should hide select options");

	//stateless actions
	fnClickThenCompare("addAction-button", "semantic-add-action", "should trigger add action");
	fnClickThenCompare("filterAction-button", "semantic-filter-action", "should trigger filter action");
	fnClickThenCompare("groupAction-button", "semantic-group-action", "should trigger group action");
	fnClickThenCompare("mainAction-button", "semantic-main-action", "should trigger main action");
	fnClickThenCompare("editAction-button", "semantic-edit-action", "should trigger edit action");
	fnClickThenCompare("saveAction-button", "semantic-save-action", "should trigger save action");
	fnClickThenCompare("deleteAction-button", "semantic-delete-action", "should trigger delete action");
	fnClickThenCompare("positiveAction-button", "semantic-positive-action", "should trigger positive action");
	fnClickThenCompare("negativeAction-button", "semantic-negative-action", "should trigger negative action");
	fnClickThenCompare("cancelAction-button", "semantic-cancel-action", "should trigger cancel action", true);
	fnClickThenCompare("forwardAction-button", "semantic-forward-action", "should trigger forward action", true);

	//share menu
	fnClickThenCompare("detail-shareButton", "semantic-share-menu-expanded", "should expand the share menu");

});
<|endoftext|>


<commit_before>var elasticsearch = require('elasticsearch');

exports.query = function(config, req, res, query, sort) {
   var client = new elasticsearch.Client({
       host: config.url
   });

   // Execute ES Query
   client.search({
       index: config.index,
       type: config.type,
       body: {
           query: {
               query_string: {
                   query: query
               }
           }
       },
       size: 100,
       sort: sort
   }).then(function(resp) {
       // Parse ES response and send result back
       parseResponse(resp, res);

       // Release client resources
       client.close();
   }, function(err) {
       res.status(400).send(err.message);

       // Release client resources
       client.close();
   });
};

/**
* Parses an ES response, formats it and sends data on the HTTP response.
*/
function parseResponse(resp, res) {
   var hits = resp.hits.hits;
   var results = [];
   for (var x = 0; x < hits.length; x++) {
       results.push(hits[x]._source);
   }

   // Write response direct back to client
   res.send({
       "rows": results,
       "total": results.length
   });
}<commit_msg>Added elasticsearch service<commit_after>var elasticsearch = require('elasticsearch');

exports.query = function(config, req, res, query, handler) {
   var client = new elasticsearch.Client({
       host: config.url
   });

   // Execute ES Query
   client.search({
       index: config.index,
       type: config.type,
       body: {
           query: {
               query_string: {
                   query: query
               }
           }
       }
       // sort: sort
   }).then(function(resp) {
       // Parse ES response and send result back
       var hits = module.exports.parseResponse(resp, res);

       if (handler) {
          handler(res, hits);
       }
       else {
          module.exports.defaultHandler(res, hits);
       }

       // Release client resources
       client.close();
   }, function(err) {
       res.status(400).send(err.message);

       // Release client resources
       client.close();
   });
};

/**
* Parses an ES response, formats it and sends data on the HTTP response.
*/
exports.parseResponse = function(resp, res) {
    return resp.hits.hits.map(function(hit) { return hit._source; });
}

exports.defaultHandler = function(res, hits) {
    res.json(hits);
}<|endoftext|>


<commit_before>define([ 'jquery', 'underscore' ], function($, _) {
  'use strict';

  function DataSource(options) {
    this.collection = options.collection;
    this.columnsData = options.columns;
    this.comparators = {
      'races' : function(model) {
        return parseInt(model.get('races'), 10);
      },
      'total_odo' : function(model) {
        return parseFloat(model.get('total_odo'));
      },
      'avg_speed' : function(model) {
        return parseFloat(model.get('avg_speed'));
      }
    };
  }

  DataSource.prototype = {

    columns : function() {
      return this.columnsData;
    },

    data : function(options, callback) {
      var data = this.collection.toJSON();
      var count = this.collection.size();
      var startIndex = options.pageIndex * options.pageSize;
      var start = startIndex + 1;
      var endIndex = startIndex + options.pageSize;
      var end = count < endIndex ? count : endIndex;
      var pages = Math.ceil(count / options.pageSize);
      var page = options.pageIndex + 1;

      if (options.search) {
        data = _.filter(data, function(item) {
          for ( var prop in item) {
            if (!item.hasOwnProperty(prop)) {
              continue;
            }
            if (item[prop].toString().toLowerCase().indexOf(options.search.toLowerCase())) {
              return true;
            }
          }
          return false;
        });
      }

      if (options.filter) {
        data = _.filter(data, function(item) {
          switch (options.filter.value) {
            case 'lt5m':
              if (item.population < 5000000) {
                return true;
              }
              break;
            case 'gte5m':
              if (item.population >= 5000000) {
                return true;
              }
              break;
            default:
              return true;
          }
        });
      }

      if (options.sortProperty && this.comparators[options.sortProperty] !== undefined) {
        this.collection.comparator = this.comparators[options.sortProperty];
        this.collection.sort();
      }
      data = this.collection.toJSON();
      if (options.sortDirection === 'desc') {
        data.reverse();
      }
      data = data.slice(startIndex, end);
      callback({
        data : data,
        start : start,
        end : end,
        count : count,
        pages : pages,
        page : page
      });
    }
  };

  return DataSource;
});
<commit_msg>Remove sample code for search and filter options.<commit_after>define([ 'jquery', 'underscore' ], function($, _) {
  'use strict';

  function DataSource(options) {
    this.collection = options.collection;
    this.columnsData = options.columns;
    this.comparators = {
      'races' : function(model) {
        return parseInt(model.get('races'), 10);
      },
      'total_odo' : function(model) {
        return parseFloat(model.get('total_odo'));
      },
      'avg_speed' : function(model) {
        return parseFloat(model.get('avg_speed'));
      }
    };
  }

  DataSource.prototype = {

    columns : function() {
      return this.columnsData;
    },

    data : function(options, callback) {
      var data = this.collection.toJSON();
      var count = this.collection.size();
      var startIndex = options.pageIndex * options.pageSize;
      var start = startIndex + 1;
      var endIndex = startIndex + options.pageSize;
      var end = count < endIndex ? count : endIndex;
      var pages = Math.ceil(count / options.pageSize);
      var page = options.pageIndex + 1;

      if (options.search) {
      }

      if (options.filter) {
      }

      if (options.sortProperty && this.comparators[options.sortProperty] !== undefined) {
        this.collection.comparator = this.comparators[options.sortProperty];
        this.collection.sort();
      }
      data = this.collection.toJSON();
      if (options.sortDirection === 'desc') {
        data.reverse();
      }
      data = data.slice(startIndex, end);
      callback({
        data : data,
        start : start,
        end : end,
        count : count,
        pages : pages,
        page : page
      });
    }
  };

  return DataSource;
});
<|endoftext|>