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

const barChart = {};
const margin = 60;
// data looks like this
// { emotion: emotion, data: object[emotion], index: i }
barChart.create = (el, props, data) => {
  console.log(el, 'svg inside create');
  // functions to grab specific parts of the data
  const emotion = d => d.emotion;
  // const yAxisMargin = {'margin-top': '25%'};
  const emotionsData = d => d.data;
  // const index = (d) => d.index;
  let svg = d3.select(el)
    .append('svg')
    .style('padding-top', '20%')
    .attr('id', 'barChart')
    .attr('width', props.width)
    .attr('height', props.height);
  // both x and y axes don't currently render

  let xScale = d3.scale.ordinal()
    .domain(data.map(d => d.emotion))
    .rangeRoundBands([100, 450], 0.1); // magic #40, width is a %
  /* [height, width], distance <> bars */
  //
  let yScale = d3.scale.linear()
    .domain([0, d3.max(data, emotionsData)]) // ?
    .range([400 - margin, 0]); // height - margin, 300
  let xAxis = d3.svg.axis().scale(xScale);
  let yAxis = d3.svg.axis().scale(yScale).orient('left');

  d3.select('svg')
    .append('g')
    .attr('class', 'x-axis')
    .attr('transform', `translate(-5, ${400 - margin})`)
    .call(xAxis);
  d3.select('svg')
    .append('g')
    .attr('class', 'y-axis')
    .attr('transform', `translate(${margin + 41}, 0)`)
    .call(yAxis);
  svg.selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('x', d => xScale(d.emotion))
    .attr('y', d => yScale(d.data))
    .attr('width', xScale.rangeBand())
    .attr('height', (d) => (yScale(0) - yScale(d.data)))
    .attr('fill', 'green');

  svg.selectAll('text')
    .data(data)
    .enter()
    .append('text')
    .text((d) => d.emotion)
    .attr('text-anchor', 'middle')
    .attr('x', (d, i) => (xScale(i) + xScale.rangeBand() / 2))
    .attr('y', (d) => yScale(d.data))
    .attr('font-family', 'sans-serif')
    .attr('font-size', '11px')
    .attr('fill', 'black');
};

barChart.update = (el, props, data) => {
  const emotionsData = d => d.data;
  let xScale = d3.scale.ordinal()
    .domain(data.map(d => d.emotion))
    .rangeRoundBands([100, 450], 0.1); // magic #40, width is a %
      /* [height, width], distance <> bars */
  let yScale = d3.scale.linear()
    .domain([0, d3.max(data, emotionsData)]) // ?
    .range([400 - margin, 0]); // height - margin, 300
  let xAxis = d3.svg.axis().scale(xScale);
  let yAxis = d3.svg.axis().scale(yScale).orient('left');

  let svg = d3.select('#barChart');
  console.log(data);
  svg.selectAll('rect')
    .data(data)
    .transition()
    .duration(500)
    .attr('x', d => xScale(d.emotion))
    .attr('height', (d) => (yScale(0) - yScale(d.data)))
    .attr('y', d => yScale(d.data))
    .attr('width', xScale.rangeBand())
    // .attr('text-anchor', 'middle')
    // .attr('fill', 'green')

};

export default barChart;
<commit_msg>reabase<commit_after>import d3 from 'd3';
import _ from 'lodash';

const barChart = {};
const margin = 60;
// data looks like this
// { emotion: emotion, data: object[emotion], index: i }
barChart.create = (el, props, data) => {
  console.log(el, 'svg inside create');
  // functions to grab specific parts of the data
  const emotion = d => d.emotion;
  // const yAxisMargin = {'margin-top': '25%'};
  const emotionsData = d => d.data;
  // const index = (d) => d.index;
  const svg = d3.select(el)
    .append('svg')
    .style('padding-top', '20%')
    .attr('id', 'barChart')
    .attr('width', props.width)
    .attr('height', props.height);
  // both x and y axes don't currently render

  const xScale = d3.scale.ordinal()
    .domain(data.map(d => d.emotion))
    .rangeRoundBands([100, 450], 0.1); // magic #40, width is a %
  /* [height, width], distance <> bars */
  //
  const yScale = d3.scale.linear()
    .domain([0, d3.max(data, emotionsData)]) // ?
    .range([400 - margin, 0]); // height - margin, 300
  const xAxis = d3.svg.axis().scale(xScale);
  const yAxis = d3.svg.axis().scale(yScale).orient('left');

  d3.select('svg')
    .append('g')
    .attr('class', 'x-axis')
    .attr('transform', `translate(-5, ${400 - margin})`)
    .call(xAxis);
  d3.select('svg')
    .append('g')
    .attr('class', 'y-axis')
    .attr('transform', `translate(${margin + 41}, 0)`)
    .call(yAxis);
  svg.selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('x', d => xScale(d.emotion))
    .attr('y', d => yScale(d.data))
    .attr('width', xScale.rangeBand())
    .attr('height', (d) => (yScale(0) - yScale(d.data)))
    .attr('fill', 'green');

  svg.selectAll('text')
    .data(data)
    .enter()
    .append('text')
    .text((d) => d.emotion)
    .attr('text-anchor', 'middle')
    .attr('x', (d, i) => (xScale(i) + xScale.rangeBand() / 2))
    .attr('y', (d) => yScale(d.data))
    .attr('font-family', 'sans-serif')
    .attr('font-size', '11px')
    .attr('fill', 'black');
};

barChart.update = (el, props, data) => {
  const emotionsData = d => d.data;
  const xScale = d3.scale.ordinal()
    .domain(data.map(d => d.emotion))
    .rangeRoundBands([100, 450], 0.1); // magic #40, width is a %
      /* [height, width], distance <> bars */
  const yScale = d3.scale.linear()
    .domain([0, d3.max(data, emotionsData)]) // ?
    .range([400 - margin, 0]); // height - margin, 300
  const xAxis = d3.svg.axis().scale(xScale);
  const yAxis = d3.svg.axis().scale(yScale).orient('left');

  const svg = d3.select('#barChart');
  console.log(data);
  svg.selectAll('rect')
    .data(data)
    .transition()
    .duration(500)
    .attr('x', d => xScale(d.emotion))
    .attr('height', (d) => (yScale(0) - yScale(d.data)))
    .attr('y', d => yScale(d.data))
    .attr('width', xScale.rangeBand())
    // .attr('text-anchor', 'middle')
    // .attr('fill', 'green')

};

export default barChart;
<|endoftext|>


<commit_before>/*
*  Chat.js
*
*  Manages all things related to the chat on all pages
*
*/

var $form = $('[name=\'chatbox_form\']');
var $submit = $('[name=\'chat_submit\']');
var $chat_text = $('#chat_text');
var $file = $('[name=\'attachment\']');

var refreshIntervalId = setInterval(function() {
    refreshChat()
},5000);

function refreshChat() {
    var chatHistory = [];
    var sumResponse = [];
    console.log('Trying to refresh the chat.')
    jQuery.get('scripts/auto_refresh_home.php',function(response1){
        response1 = JSON.parse(response1);
        sumResponse = response1;
        jQuery.getJSON('api/chat_messages.php',function(response2){
            sumResponse[2] = response2;
            onSumResponse2(JSON.stringify(sumResponse));
        });
    });
}

function disableForm() {
    console.log('Disabled HTML chat form');
    $submit.attr('type','button');
    $form.changeElementType('div');
}

function enableForm() {
    console.log('Enabled HTML chat form');
    $submit.attr('type','submit');
    $form.changeElementType('form');
}

function sendChatMessage() {

    //If there is NO file attached
    if($file[0].files.length === 0) {
        console.log('No files detected to be attached. Using jQuery to post chat.');
        jQuery.post('scripts/chat_post.php', {
            "chat_text": $chat_text.val()
        }, function(res){
            console.log('Done');
            $chat_text[0].value = '';
            refreshChat();
        });

    }
    else {
        //If there is, do it the old fashion way.
        enableForm();
        $submit.trigger('click');
    }

}

if(window.location.pathname === '/home.php') {
    disableForm();
    $submit.on('click',function(event) {
        //Recursion preventative from manual $.trigger() above
        if(event.originalEvent) {
            sendChatMessage();
        }
    });
    $chat_text.on('keyup', function(event){
        if(event.keyCode === 13) {
            console.log(event.keyCode);
            sendChatMessage();
        }
    });

    var refreshButton = document.createElement('span');
    refreshButton.setAttribute('id','refresh_button');
    refreshButton.setAttribute('title','Refresh the chat');
    refreshButton.innerHTML = '@';
    $('[name=\'chat_submit\']').after(refreshButton);
    $('#refresh_button').on('click',refreshChat);

}
<commit_msg>Removed manual refresh button, there's no need<commit_after>/*
*  Chat.js
*
*  Manages all things related to the chat on all pages
*
*/

var $form = $('[name=\'chatbox_form\']');
var $submit = $('[name=\'chat_submit\']');
var $chat_text = $('#chat_text');
var $file = $('[name=\'attachment\']');

var refreshIntervalId = setInterval(function() {
    refreshChat()
},5000);

function refreshChat() {
    var chatHistory = [];
    var sumResponse = [];
    console.log('Trying to refresh the chat.')
    jQuery.get('scripts/auto_refresh_home.php',function(response1){
        response1 = JSON.parse(response1);
        sumResponse = response1;
        jQuery.getJSON('api/chat_messages.php',function(response2){
            sumResponse[2] = response2;
            onSumResponse2(JSON.stringify(sumResponse));
        });
    });
}

function disableForm() {
    console.log('Disabled HTML chat form');
    $submit.attr('type','button');
    $form.changeElementType('div');
}

function enableForm() {
    console.log('Enabled HTML chat form');
    $submit.attr('type','submit');
    $form.changeElementType('form');
}

function sendChatMessage() {

    //If there is NO file attached
    if($file[0].files.length === 0) {
        console.log('No files detected to be attached. Using jQuery to post chat.');
        jQuery.post('scripts/chat_post.php', {
            "chat_text": $chat_text.val()
        }, function(res){
            console.log('Done');
            $chat_text[0].value = '';
            refreshChat();
        });

    }
    else {
        //If there is, do it the old fashion way.
        enableForm();
        $submit.trigger('click');
    }

}

if(window.location.pathname === '/home.php') {
    disableForm();
    $submit.on('click',function(event) {
        //Recursion preventative from manual $.trigger() above
        if(event.originalEvent) {
            sendChatMessage();
        }
    });
    $chat_text.on('keyup', function(event){
        if(event.keyCode === 13) {
            console.log(event.keyCode);
            sendChatMessage();
        }
    });

}
<|endoftext|>


<commit_before>(function() {
    'use strict';

    describe('angular-queue', function() {

        var $queue,
            $timeout,
            myQueue,
            result,
            myCallback = function(item) {
                result.push(item);
            };

        beforeEach(function() {
            result = [];
            module('ngQueue');
            inject(function($injector) {
                $queue = $injector.get('$queue');
                $timeout = $injector.get('$timeout');
                myQueue = $queue.queue(myCallback);
            });
        });

        describe('Constructor', function() {
            it('Should throw exception when no callback is specified',
                function() {
                    expect($queue.queue).toThrow();
                }
            );

            it('Should make a new Queue', function() {
                var aQueue = $queue.queue(myCallback);
                expect(aQueue).toBeDefined();
                expect(aQueue.queue).toBeDefined();
            });
        });

        describe('#pause', function() {
            it('Should pause the queue', function() {
                myQueue.pause();
                expect(myQueue.paused).toBeTruthy();
            });
        });

        describe('#start', function() {
            it('Should unpause the queue', function() {
                myQueue.pause();
                expect(myQueue.paused).toBeTruthy();
                myQueue.start();
                expect(myQueue.paused).toBeFalsy();
            });
        });

        describe('#add', function() {
            it('Should add an item to the queue', function() {
                myQueue.pause();
                expect(myQueue.queue.length).toEqual(0);
                expect(myQueue.add('item')).toEqual(1);
                expect(myQueue.queue.length).toEqual(1);
                expect(myQueue.queue[0]).toEqual('item');
            });
        });

        describe('#size', function() {
            it('Should return the number of items in the queue', function() {
                myQueue.pause();
                expect(myQueue.size()).toEqual(0);
                myQueue.add('an item');
                expect(myQueue.size()).toEqual(1);
                myQueue.add('another item');
                expect(myQueue.size()).toEqual(2);
            });
        });

        describe('#addEach', function() {
            it('Should add an array of items to the queue', function() {
                myQueue.pause();
                myQueue.addEach(['tom', 'joe', 'mike']);
                expect(myQueue.size()).toEqual(3);
                expect(myQueue.queue[1]).toEqual('joe');
            });
        });

        describe('#clear', function() {
            it('Should clear the queue', function() {
                myQueue.pause();
                myQueue.add('item');
                myQueue.clear();
                expect(myQueue.size()).toEqual(0);
            });
        });

        describe('Queue processing', function() {
            it('Should process items via the provided callback', function() {
                expect(result.length).toEqual(0);
                var names = ['james', 'tom', 'joe', 'mike', 'ryan'];
                myQueue.addEach(names);
                for (var i = 0; i < names.length; i++) {
                    //Must call flush once per delay
                    $timeout.flush();
                    //Result is pushed items via myCallback
                    expect(result[i]).toEqual(names[i]);
                }
            });

            it('Should call the complete callback when finished', function() {

                var hasCompleted = false,
                    onComplete = function() {
                        hasCompleted = true;
                    },
                    aQueue = $queue.queue(myCallback, {complete: onComplete});

                aQueue.add('item');
                $timeout.flush();
                expect(hasCompleted).toBeTruthy();
            });
        });

    });
})();<commit_msg>Test for indexOf<commit_after>(function() {
    'use strict';

    describe('angular-queue', function() {

        var $queue,
            $timeout,
            myQueue,
            result,
            myCallback = function(item) {
                result.push(item);
            };

        beforeEach(function() {
            result = [];
            module('ngQueue');
            inject(function($injector) {
                $queue = $injector.get('$queue');
                $timeout = $injector.get('$timeout');
                myQueue = $queue.queue(myCallback);
            });
        });

        describe('Constructor', function() {
            it('Should throw exception when no callback is specified',
                function() {
                    expect($queue.queue).toThrow();
                }
            );

            it('Should make a new Queue', function() {
                var aQueue = $queue.queue(myCallback);
                expect(aQueue).toBeDefined();
                expect(aQueue.queue).toBeDefined();
            });
        });

        describe('#pause', function() {
            it('Should pause the queue', function() {
                myQueue.pause();
                expect(myQueue.paused).toBeTruthy();
            });
        });

        describe('#start', function() {
            it('Should unpause the queue', function() {
                myQueue.pause();
                expect(myQueue.paused).toBeTruthy();
                myQueue.start();
                expect(myQueue.paused).toBeFalsy();
            });
        });

        describe('#add', function() {
            it('Should add an item to the queue', function() {
                myQueue.pause();
                expect(myQueue.queue.length).toEqual(0);
                expect(myQueue.add('item')).toEqual(1);
                expect(myQueue.queue.length).toEqual(1);
                expect(myQueue.queue[0]).toEqual('item');
            });
        });

        describe('#size', function() {
            it('Should return the number of items in the queue', function() {
                myQueue.pause();
                expect(myQueue.size()).toEqual(0);
                myQueue.add('an item');
                expect(myQueue.size()).toEqual(1);
                myQueue.add('another item');
                expect(myQueue.size()).toEqual(2);
            });
        });

        describe('#addEach', function() {
            it('Should add an array of items to the queue', function() {
                myQueue.pause();
                myQueue.addEach(['tom', 'joe', 'mike']);
                expect(myQueue.size()).toEqual(3);
                expect(myQueue.queue[1]).toEqual('joe');
            });
        });

        describe('#clear', function() {
            it('Should clear the queue', function() {
                myQueue.pause();
                myQueue.add('item');
                myQueue.clear();
                expect(myQueue.size()).toEqual(0);
            });
        });

        describe('#instanceOf', function() {
            it('Should return the index of the item in the queue', function() {
                myQueue.pause();
                myQueue.addEach(['tom', 'joe', 'mike']);
                expect(myQueue.indexOf('tom')).toEqual(0);
                expect(myQueue.indexOf('joe')).toEqual(1);
                expect(myQueue.indexOf('mike')).toEqual(2);
                expect(myQueue.indexOf('invalid')).toEqual(-1);
            });
        });

        describe('Queue processing', function() {
            it('Should process items via the provided callback', function() {
                expect(result.length).toEqual(0);
                var names = ['james', 'tom', 'joe', 'mike', 'ryan'];
                myQueue.addEach(names);
                for (var i = 0; i < names.length; i++) {
                    //Must call flush once per delay
                    $timeout.flush();
                    //Result is pushed items via myCallback
                    expect(result[i]).toEqual(names[i]);
                }
            });

            it('Should call the complete callback when finished', function() {

                var hasCompleted = false,
                    onComplete = function() {
                        hasCompleted = true;
                    },
                    aQueue = $queue.queue(myCallback, {complete: onComplete});

                aQueue.add('item');
                $timeout.flush();
                expect(hasCompleted).toBeTruthy();
            });
        });

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


<commit_before>var viewer;

// Many thanks to Dan Wellman (@danwellman). Not only did he write
// the excellent post that formed the basis for this application's
// Steampunk UI, he provided the artwork to help build a custom
// version...
// http://www.dmxzone.com/go/18220/an-image-viewer-with-the-dmxzone-universal-css-transforms-library/

function initialize() {

  // Get our access token from the internal web-service API

  $.get("http://" + window.location.host + '/api/token',
    function (accessToken) {

      var options = {};
      options.env = "AutodeskProduction";
      options.accessToken = accessToken;
      options.document =
        "urn:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6c3RlYW1idWNrL1NwTTNXNy5mM2Q=";

      // Create and initialize our 3D viewer

      var elem = document.getElementById('viewer3d');
      viewer = new Autodesk.Viewing.Viewer3D(elem, {});
      viewer.initialize();

      // Go with the "Riverbank" lighting and background effect

      viewer.impl.setLightPreset(8);

      // We have a heavy model, so let's save some work during
      // navigation

      viewer.setOptimizeNavigation(true);

      // Let's zoom in and out of the pivot - the screen
      // real estate is fairly limited - and reverse the
      // zoom direction

      viewer.navigation.setZoomTowardsPivot(true);
      viewer.navigation.setReverseZoomDirection(true);

      Autodesk.Viewing.Initializer(options, function () {
        loadDocument(viewer, options.document);
      });
    }
  );

  // Set up some UI elements for the Steampunk UI

  $("#ui").find("div").attr("id", "over");
  $("#window").wrapInner("
");

  // Store positions

  var overPositions =
        {
          entirety: 0, engine: 75, body: 152,
          interior: 230, wheels: 310
        },
      cogPositions =
        {
          entirety: 5, engine: 80, body: 154,
          interior: 235, wheels: 310
        },
      previousCogPosition = 0;

  // Animation function

  function animator(pointer, callback) {

    // Move cog

    $("#cog").animate({
      "translateY": parseInt(cogPositions[pointer]),
      "rotate":
        (parseInt(cogPositions[pointer]) < previousCogPosition) ?
        "-=365" : "+=365"
    }, function () {
      previousCogPosition = cogPositions[pointer];
    });

    // Move over

    $("#over").animate({
      "translateY": parseInt(overPositions[pointer])
    });

    // Add a delay so the camera changes after the cog has stopped
    // whirring

    if (callback) {
      setTimeout(function () { callback(); }, 400);
    }
  }

  // Is there a hash?

  if (window.location.hash) {

    // Store the hash

    var hash = window.location.hash.split("#")[1];

    // Position over

    animator(hash);
  }

  // Add transitions

  $("#ui a").click(function (e) {
    e.preventDefault();

    // Store new pointer

    var pointer = $(this).attr("href").split("#")[1];

    // Call animation function

    animator(pointer, function () {
      if (pointer === "entirety") {
        zoomEntirety();
      } else if (pointer === "engine") {
        zoomEngine();
      } else if (pointer === "body") {
        zoomBody();
      } else if (pointer === "interior") {
        zoomInterior();
      } else if (pointer === "wheels") {
        zoomWheels();
      }
    });
  });
}

// Helper functions to zoom into a specific part of the model

function zoomEntirety() {
  zoom(-48722.5, -54872, 44704.8, 10467.3, 1751.8, 1462.8);
}
function zoomEngine() {
  zoom(-17484, -364, 4568, 12927, 173, 1952);
}
function zoomBody() {
  zoom(53143, -7200, 5824, 12870, -327.5, 1674);
}
function zoomInterior() {
  zoom(20459, -19227, 19172.5, 13845, 1228.6, 2906);
}
function zoomWheels() {
  zoom(260.3, 26327, 954, 371.5, 134, 2242.7);
}

// Set the camera based on a position and target location

function zoom(px, py, pz, tx, ty, tz) {

  // Make sure our up vector is correct for this model

  viewer.navigation.setWorldUpVector(new THREE.Vector3(0, 0, 1));

  // This performs a smooth view transition (we might also use
  // setView() to get there more directly)

  viewer.navigation.setRequestTransition(
    true,
    new THREE.Vector3(px, py, pz), new THREE.Vector3(tx, ty, tz),
    viewer.getFOV()
  );
}

// Progress listener to set the view once the data has started
// loading properly (we get a 5% notification early on that we
// need to ignore - it comes too soon)

function progressListener(param) {

  if (param.percent > 0.1 && param.percent < 5) {

    // Remove the listener once called - one-time operation

    viewer.removeEventListener("progress", progressListener);

    // Iterate the materials to change any red ones to grey

    for (var p in viewer.impl.materials) {
      var m = viewer.impl.materials[p];
      if (m.color.r >= 0.5 && m.color.g == 0 && m.color.b == 0) {
        m.color.r = m.color.g = m.color.b = 0.5;
        m.needsUpdate = true;
      }
    }

    // Zoom to the overall view initially

    zoomEntirety();
  }
}

function loadDocument(viewer, docId) {

  var path = VIEWING_URL + '/' + docId.substr(4);

  Autodesk.Viewing.Document.load(path,
    function (document) {
      var geometryItems = [];

      if (geometryItems.length == 0) {
        geometryItems =
          Autodesk.Viewing.Document.getSubItemsWithProperties(
            document.getRootItem(),
            { 'type': 'geometry', 'role': '3d' },
            true
          );
      }
      if (geometryItems.length > 0) {
        viewer.load(document.getViewablePath(geometryItems[0]));
      }

      viewer.addEventListener("progress", progressListener);
    },
    function (errorMsg, httpErrorCode) {
      var container = document.getElementById('viewer3d');
      if (container) {
        alert("Load error " + errorMsg);
      }
    }
  );
}
<commit_msg>Partial change to support new viewer release<commit_after>var viewer;

// Many thanks to Dan Wellman (@danwellman). Not only did he write
// the excellent post that formed the basis for this application's
// Steampunk UI, he provided the artwork to help build a custom
// version...
// http://www.dmxzone.com/go/18220/an-image-viewer-with-the-dmxzone-universal-css-transforms-library/

function initialize() {

  // Get our access token from the internal web-service API

  $.get("http://" + window.location.host + '/api/token',
    function (accessToken) {

      var options = {};
      options.env = "AutodeskProduction";
      options.accessToken = accessToken;
      options.document =
        "dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6c3RlYW1idWNrL1NwTTNXNy5mM2Q=";

      // Create and initialize our 3D viewer

      var elem = document.getElementById('viewer3d');
      viewer = new Autodesk.Viewing.Viewer3D(elem, {});

      Autodesk.Viewing.Initializer(options, function () {

        viewer.initialize();

        // Go with the "Riverbank" lighting and background effect

        viewer.impl.setLightPreset(8);

        // We have a heavy model, so let's save some work during
        // navigation

        viewer.setOptimizeNavigation(true);

        // Let's zoom in and out of the pivot - the screen
        // real estate is fairly limited - and reverse the
        // zoom direction

        viewer.navigation.setZoomTowardsPivot(true);
        viewer.navigation.setReverseZoomDirection(true);

        loadDocument(viewer, options.document);
      });
    }
  );

  // Set up some UI elements for the Steampunk UI

  $("#ui").find("div").attr("id", "over");
  $("#window").wrapInner("
");

  // Store positions

  var overPositions =
        {
          entirety: 0, engine: 75, body: 152,
          interior: 230, wheels: 310
        },
      cogPositions =
        {
          entirety: 5, engine: 80, body: 154,
          interior: 235, wheels: 310
        },
      previousCogPosition = 0;

  // Animation function

  function animator(pointer, callback) {

    // Move cog

    $("#cog").animate({
      "translateY": parseInt(cogPositions[pointer]),
      "rotate":
        (parseInt(cogPositions[pointer]) < previousCogPosition) ?
        "-=365" : "+=365"
    }, function () {
      previousCogPosition = cogPositions[pointer];
    });

    // Move over

    $("#over").animate({
      "translateY": parseInt(overPositions[pointer])
    });

    // Add a delay so the camera changes after the cog has stopped
    // whirring

    if (callback) {
      setTimeout(function () { callback(); }, 400);
    }
  }

  // Is there a hash?

  if (window.location.hash) {

    // Store the hash

    var hash = window.location.hash.split("#")[1];

    // Position over

    animator(hash);
  }

  // Add transitions

  $("#ui a").click(function (e) {
    e.preventDefault();

    // Store new pointer

    var pointer = $(this).attr("href").split("#")[1];

    // Call animation function

    animator(pointer, function () {
      if (pointer === "entirety") {
        zoomEntirety();
      } else if (pointer === "engine") {
        zoomEngine();
      } else if (pointer === "body") {
        zoomBody();
      } else if (pointer === "interior") {
        zoomInterior();
      } else if (pointer === "wheels") {
        zoomWheels();
      }
    });
  });
}

// Helper functions to zoom into a specific part of the model

function zoomEntirety() {
  zoom(-48722.5, -54872, 44704.8, 10467.3, 1751.8, 1462.8);
}
function zoomEngine() {
  zoom(-17484, -364, 4568, 12927, 173, 1952);
}
function zoomBody() {
  zoom(53143, -7200, 5824, 12870, -327.5, 1674);
}
function zoomInterior() {
  zoom(20459, -19227, 19172.5, 13845, 1228.6, 2906);
}
function zoomWheels() {
  zoom(260.3, 26327, 954, 371.5, 134, 2242.7);
}

// Set the camera based on a position and target location

function zoom(px, py, pz, tx, ty, tz) {

  // Make sure our up vector is correct for this model

  viewer.navigation.setWorldUpVector(new THREE.Vector3(1, 0, 0));
  viewer.navigation.setWorldUpVector(new THREE.Vector3(0, 0, 1));

  // This performs a smooth view transition (we might also use
  // setView() to get there more directly)

  viewer.navigation.setRequestTransition(
    true,
    new THREE.Vector3(px, py, pz), new THREE.Vector3(tx, ty, tz),
    viewer.getFOV()
  );
}

// Progress listener to set the view once the data has started
// loading properly (we get a 5% notification early on that we
// need to ignore - it comes too soon)

function progressListener(param) {

  if (param.percent > 0.1 && param.percent < 5) {

    // Remove the listener once called - one-time operation

    viewer.removeEventListener("progress", progressListener);

    // Iterate the materials to change any red ones to grey

    for (var p in viewer.model.myData.materials.materials) {
      var m = viewer.model.myData.materials.materials[p];
      var c =
        m.materials[0].properties.colors.generic_diffuse.values[0];
      if (c.r >= 0.5 && c.g == 0 && c.b == 0) {
        c.r = c.g = c.b = 0.5;
        //m.needsUpdate = true;
      }
    }

    // Zoom to the overal view initially

    zoomEntirety();
  }
}

function loadDocument(viewer, docId) {

  if (docId.substring(0, 4) !== 'urn:')
    docId = 'urn:' + docId;

  Autodesk.Viewing.Document.load(docId,
    function (document) {
      var geometryItems = [];

      if (geometryItems.length == 0) {
        geometryItems =
          Autodesk.Viewing.Document.getSubItemsWithProperties(
            document.getRootItem(),
            { 'type': 'geometry', 'role': '3d' },
            true
          );
      }
      if (geometryItems.length > 0) {
        viewer.load(document.getViewablePath(geometryItems[0]));
      }

      viewer.addEventListener("progress", progressListener);
    },
    function (errorMsg, httpErrorCode) {
      var container = document.getElementById('viewer3d');
      if (container) {
        alert("Load error " + errorMsg);
      }
    }
  );
}
<|endoftext|>


<commit_before>// alerts

$(document).ready(function(){
  var alerts = $('.alert-message');

  setTimeout(function(){
    alerts.fadeOut(400);
  }, 3000);

  alerts.on('click', function(){
      alerts.fadeOut(400);
  });
})
<commit_msg>Increasing the time fadeOut in setTimeout<commit_after>// alerts

$(function(){
  var alerts = $('.alert-message');

  setTimeout(function() {
    alerts.fadeOut(400);
  }, 4000);

  alerts.click(function() {
    alerts.fadeOut(400);
  });
})
<|endoftext|>


<commit_before>'use strict';

var localstorage = localstorage || {};

localstorage.dataPoints = [];

function DataPoint (date, prescription, dosage, tLevel, eLevel, logEntry){
  this.date = date;
  this.prescription = prescription;
  this.dosage = dosage;
  this.tLevel = tLevel;
  this.eLevel = eLevel;
  this.logEntry = logEntry;
  localstorage.dataPoints.push(this);
};

DataPoint.prototype.toHtml = function (){
   //manipulate template strings here so that the dom renders them to #log section

};

$('#submit-button').on('click', function(e){
  e.preventDefault();
  var obj = new DataPoint($('#date').val(), $('#prescription').val(), parseInt($('#dosage').val()), parseInt($('#tLevel').val()), parseInt($('#eLevel').val()), $('#entry-form').val());
  $.post('/submit', obj)
    .then(console.log('post complete'))
    .catch(console.error);
});
<commit_msg>further reducing lines of code!<commit_after>'use strict';

var localstorage = localstorage || {};

localstorage.dataPoints = [];

function DataPoint (date, prescription, dosage, tLevel, eLevel, logEntry){
  this.date = date;
  this.prescription = prescription;
  this.dosage = dosage;
  this.tLevel = tLevel;
  this.eLevel = eLevel;
  this.logEntry = logEntry;
  localstorage.dataPoints.push(this);
};

DataPoint.prototype.toHtml = function (){
   //manipulate template strings here so that the dom renders them to #log section

};

$('#submit-button').on('click', function(e){
  e.preventDefault();
  var obj = new DataPoint($('#date').val(), $('#prescription').val(), parseInt($('#dosage').val()), parseInt($('#tLevel').val()), parseInt($('#eLevel').val()), $('#entry-form').val());
  $.post('/submit', obj).then(console.log('post complete')).catch(console.error);
});
<|endoftext|>


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

var fs = require('fs');
var path = require('path');
var Immutable = require('immutable');
var LocalFile = require('../../lib/models/localFile');
var RepositoryState = require('../../lib/models/repositoryState');

var repofs = require('../..');
var LocalUtils = repofs.LocalUtils;

var REPO_DIR = '.tmp/repo/';

module.exports = function (driver) {
    if (process.env.REPOFS_DRIVER !== 'uhub') return;

    return describe('LocalUtils', testLocal.bind(this, driver));
};

function testLocal(driver) {
    describe('.status', function() {

        before(function () {
            this.initialReadme = fs.readFileSync(path.join(REPO_DIR, 'README.md'), 'utf8');
            fs.writeFileSync(path.join(REPO_DIR, 'README.md'), 'New content');
            fs.writeFileSync(path.join(REPO_DIR, 'readme2.md'), 'New content');
        });

        after(function () {
            fs.writeFileSync(path.join(REPO_DIR, 'README.md'), this.initialReadme);
            fs.unlinkSync(path.join(REPO_DIR, 'readme2.md'));
        });

        it('should return list of changed files', function(done) {
            var repoState = new RepositoryState({
                currentBranchName: 'master'
            });

            LocalUtils.status(repoState, driver)
                .then(function (localFiles) {
                    // is an immutable list
                    localFiles.should.be.instanceof(Immutable.List);

                    // size equals 2
                    localFiles.size.should.be.equal(2);

                    // instance of file are LocalFile
                    localFiles.get(0).should.be.instanceof(LocalFile);
                    localFiles.get(1).should.be.instanceof(LocalFile);

                    // Content should be consistant
                    localFiles.get(1).should.eql(LocalFile.create({
                        sha: '0000000000000000000000000000000000000000',
                        filename: 'readme2.md',
                        status: 'untracked',
                        additions: 0,
                        deletions: 0,
                        changes: 0,
                        patch: ''
                    }));

                    localFiles.get(0).get('filename').should.equal('README.md');
                    localFiles.get(0).get('status').should.equal('modified');
                    localFiles.get(0).get('additions').should.equal(1);
                    localFiles.get(0).get('deletions').should.equal(1);
                    localFiles.get(0).get('changes').should.equal(2);
                    localFiles.get(0).get('patch').should.equal('@@ -1 +1 @@\n-# \\n\n+New content\n\\ No newline at end of file\n');
                })
                .then(done)
                .catch(done);
        });
    });
};
<commit_msg>Fix local status test<commit_after>var fs = require('fs');
var path = require('path');
var Immutable = require('immutable');
var LocalFile = require('../../lib/models/localFile');
var RepositoryState = require('../../lib/models/repositoryState');

var repofs = require('../..');
var LocalUtils = repofs.LocalUtils;

var REPO_DIR = '.tmp/repo/';

module.exports = function (driver) {
    if (process.env.REPOFS_DRIVER !== 'uhub') return;

    return describe('LocalUtils', testLocal.bind(this, driver));
};

function testLocal(driver) {
    describe('.status', function() {

        before(function () {
            this.initialReadme = fs.readFileSync(path.join(REPO_DIR, 'README.md'), 'utf8');
            fs.writeFileSync(path.join(REPO_DIR, 'README.md'), 'New content');
            fs.writeFileSync(path.join(REPO_DIR, 'readme2.md'), 'New content');
        });

        after(function () {
            fs.writeFileSync(path.join(REPO_DIR, 'README.md'), this.initialReadme);
            fs.unlinkSync(path.join(REPO_DIR, 'readme2.md'));
        });

        it('should return list of changed files', function(done) {
            var repoState = new RepositoryState({
                currentBranchName: 'master'
            });

            LocalUtils.status(repoState, driver)
                .then(function (localFiles) {
                    // is an immutable list
                    localFiles.should.be.instanceof(Immutable.List);

                    // size equals 2
                    localFiles.size.should.be.equal(2);

                    // instance of file are LocalFile
                    localFiles.get(0).should.be.instanceof(LocalFile);
                    localFiles.get(1).should.be.instanceof(LocalFile);

                    // Content should be consistant
                    localFiles.get(1).should.eql(LocalFile.create({
                        sha: '0000000000000000000000000000000000000000',
                        filename: 'readme2.md',
                        status: 'untracked',
                        additions: 0,
                        deletions: 0,
                        changes: 0,
                        patch: ''
                    }));

                    localFiles.get(0).get('filename').should.equal('README.md');
                    localFiles.get(0).get('status').should.equal('modified');
                    localFiles.get(0).get('additions').should.equal(1);
                    localFiles.get(0).get('deletions').should.equal(1);
                    localFiles.get(0).get('changes').should.equal(2);
                    localFiles.get(0).get('patch').should.equal('@@ -1 +1 @@\n-# Uhub test repository\\n\n+New content\n\\ No newline at end of file\n');
                })
                .then(done)
                .catch(done);
        });
    });
}
<|endoftext|>


<commit_before>var JSC          = require("jscheck");
var assert       = require("chai").assert;
var _            = require("lodash");
var getTestUtils = require("../TestUtils.js");

function generateArrayOfStrings() {
  return JSC.array()().map(function() { return JSC.string()(); });
}

function argumentsToArray(theArguments) {
  return Array.prototype.slice.call(theArguments);
}

function dropKeysPredicate(keys) {
  return function (value, key) {
    return _.includes(keys, key);
  }
}

module.exports = function(config) {
  var Immutable = config.implementation;
  var TestUtils = getTestUtils(Immutable);
  var check     = TestUtils.check;

  describe("#without", function() {

    function checkImmutableWithKeys(keysSpecifier, callback/*function(immutable, keys)*/) {
      var runs = 100;

      function checkMultiple(callback) {
        // keysSpecifier = array of generators
        check(runs, keysSpecifier, function(singleArrayOrFirstKey) {

          var useVarArgs = !(singleArrayOrFirstKey instanceof Array);

          var keys;
          if (arguments.length > 1) {
            keys = Array.prototype.slice.call(arguments);
          } else if (singleArrayOrFirstKey instanceof Array) {
            keys = singleArrayOrFirstKey;
          } else {
            keys = [singleArrayOrFirstKey];
          }

          assert.notStrictEqual(keys.length, 0, "Can't usefully check without() with no objects");

          // Make an object that at LEAST contains the specified keys.
          var immutable = Immutable(keys).asObject(function(key) {
            return [key, JSC.any()()];
          }).merge(TestUtils.ComplexObjectSpecifier()());

          callback(immutable, keys, useVarArgs);
        })
      }

      checkMultiple(callback);
    }

    function generateWithoutTestsFor(firstSpecifier) {

      var keysSpecifier = (firstSpecifier === generateArrayOfStrings) ?
        [firstSpecifier] : argumentsToArray(arguments);

      checkImmutableWithKeys(keysSpecifier, function(immutable, keys, useVarArgs) {

        it("returns the same result as a corresponding without(predicate)", function() {
          var expected = immutable.without(dropKeysPredicate(keys));
          var actual   = useVarArgs ?
            immutable.without.apply(immutable, keys) :
            immutable.without(keys);
          TestUtils.assertJsonEqual(actual, expected);
        });

        it("drops the keys", function() {
          var expectedKeys = _.difference(_.keys(immutable), keys);
          var result = immutable.without(keys);

          TestUtils.assertJsonEqual(_.keys(result), expectedKeys);
        });
      });
    }

    // Sanity check to make sure our QuickCheck logic isn't off the rails.
    it("passes a basic sanity check on canned input", function() {
      var expected = Immutable({cat: "meow", dog: "woof"});
      var actual   = Immutable({cat: "meow", dog: "woof", fox: "???"}).without("fox");

      TestUtils.assertJsonEqual(actual, expected);
    });

    it("is a no-op when passed nothing", function() {
      check(100, [TestUtils.ComplexObjectSpecifier()], function(obj) {
        var expected = Immutable(obj);
        var actual   = expected.without();

        TestUtils.assertJsonEqual(actual, expected);
      });
    });

    it("preserves prototypes after call to without", function() {
      function TestClass(o) { _.extend(this, o); };
      var data = new TestClass({a: 1, b: 2});

      var immutable = Immutable(data, {prototype: TestClass.prototype});
      var result = immutable.without('b');

      TestUtils.assertJsonEqual(result, _.omit(data, 'b'));
      TestUtils.assertHasPrototype(result, TestClass.prototype);
    });

    describe("when passed a single key", function() {
      generateWithoutTestsFor(JSC.string());
    });

    describe("when passed multiple keys", function() {
      generateWithoutTestsFor(JSC.string(), JSC.string(), JSC.string());
    });

    describe("when passed an array of keys", function() {
      generateWithoutTestsFor(generateArrayOfStrings);
    });

    describe("when passed a predicate", function() {
      checkImmutableWithKeys([generateArrayOfStrings], function(immutable, keys) {

        it("drops the keys satisfying the predicate", function() {
          var expectedKeys = _.difference(_.keys(immutable), keys);
          var result = immutable.without(dropKeysPredicate(keys));

          assert.deepEqual(_.keys(result), expectedKeys);

          // Make sure the remaining keys still point to the same values
          _.each(_.keys(result), function(key) {
            TestUtils.assertJsonEqual(immutable[key], result[key]);;
          });
        });

        it("returns an Immutable Object", function() {
          var result = immutable.without(dropKeysPredicate(keys));
          assert.instanceOf(result, Object);
          TestUtils.assertIsDeeplyImmutable(result);
        });

        it("drops keys whose values satisfy the predicate", function() {
          var valuesToDrop = _.chain(immutable).pick(keys).values();
          // We might have dropped more keys as more keys might have the same value
          var expectedKeys = _.chain(immutable)
            .omit(function (value) {
              return _.includes(valuesToDrop, value);
            })
            .keys()
            .value();
          var result = immutable.without(function (value, key) {
            return _.includes(valuesToDrop, value);
          });

          assert.deepEqual(_.keys(result), expectedKeys);
        });

      });

    });
  });
};
<commit_msg>Use TestUtils.assertJsonEqual over assert.deepEqual<commit_after>var JSC          = require("jscheck");
var assert       = require("chai").assert;
var _            = require("lodash");
var getTestUtils = require("../TestUtils.js");

function generateArrayOfStrings() {
  return JSC.array()().map(function() { return JSC.string()(); });
}

function argumentsToArray(theArguments) {
  return Array.prototype.slice.call(theArguments);
}

function dropKeysPredicate(keys) {
  return function (value, key) {
    return _.includes(keys, key);
  }
}

module.exports = function(config) {
  var Immutable = config.implementation;
  var TestUtils = getTestUtils(Immutable);
  var check     = TestUtils.check;

  describe("#without", function() {

    function checkImmutableWithKeys(keysSpecifier, callback/*function(immutable, keys)*/) {
      var runs = 100;

      function checkMultiple(callback) {
        // keysSpecifier = array of generators
        check(runs, keysSpecifier, function(singleArrayOrFirstKey) {

          var useVarArgs = !(singleArrayOrFirstKey instanceof Array);

          var keys;
          if (arguments.length > 1) {
            keys = Array.prototype.slice.call(arguments);
          } else if (singleArrayOrFirstKey instanceof Array) {
            keys = singleArrayOrFirstKey;
          } else {
            keys = [singleArrayOrFirstKey];
          }

          assert.notStrictEqual(keys.length, 0, "Can't usefully check without() with no objects");

          // Make an object that at LEAST contains the specified keys.
          var immutable = Immutable(keys).asObject(function(key) {
            return [key, JSC.any()()];
          }).merge(TestUtils.ComplexObjectSpecifier()());

          callback(immutable, keys, useVarArgs);
        })
      }

      checkMultiple(callback);
    }

    function generateWithoutTestsFor(firstSpecifier) {

      var keysSpecifier = (firstSpecifier === generateArrayOfStrings) ?
        [firstSpecifier] : argumentsToArray(arguments);

      checkImmutableWithKeys(keysSpecifier, function(immutable, keys, useVarArgs) {

        it("returns the same result as a corresponding without(predicate)", function() {
          var expected = immutable.without(dropKeysPredicate(keys));
          var actual   = useVarArgs ?
            immutable.without.apply(immutable, keys) :
            immutable.without(keys);
          TestUtils.assertJsonEqual(actual, expected);
        });

        it("drops the keys", function() {
          var expectedKeys = _.difference(_.keys(immutable), keys);
          var result = immutable.without(keys);

          TestUtils.assertJsonEqual(_.keys(result), expectedKeys);
        });
      });
    }

    // Sanity check to make sure our QuickCheck logic isn't off the rails.
    it("passes a basic sanity check on canned input", function() {
      var expected = Immutable({cat: "meow", dog: "woof"});
      var actual   = Immutable({cat: "meow", dog: "woof", fox: "???"}).without("fox");

      TestUtils.assertJsonEqual(actual, expected);
    });

    it("is a no-op when passed nothing", function() {
      check(100, [TestUtils.ComplexObjectSpecifier()], function(obj) {
        var expected = Immutable(obj);
        var actual   = expected.without();

        TestUtils.assertJsonEqual(actual, expected);
      });
    });

    it("preserves prototypes after call to without", function() {
      function TestClass(o) { _.extend(this, o); };
      var data = new TestClass({a: 1, b: 2});

      var immutable = Immutable(data, {prototype: TestClass.prototype});
      var result = immutable.without('b');

      TestUtils.assertJsonEqual(result, _.omit(data, 'b'));
      TestUtils.assertHasPrototype(result, TestClass.prototype);
    });

    describe("when passed a single key", function() {
      generateWithoutTestsFor(JSC.string());
    });

    describe("when passed multiple keys", function() {
      generateWithoutTestsFor(JSC.string(), JSC.string(), JSC.string());
    });

    describe("when passed an array of keys", function() {
      generateWithoutTestsFor(generateArrayOfStrings);
    });

    describe("when passed a predicate", function() {
      checkImmutableWithKeys([generateArrayOfStrings], function(immutable, keys) {

        it("drops the keys satisfying the predicate", function() {
          var expectedKeys = _.difference(_.keys(immutable), keys);
          var result = immutable.without(dropKeysPredicate(keys));

          assert.deepEqual(_.keys(result), expectedKeys);

          // Make sure the remaining keys still point to the same values
          _.each(_.keys(result), function(key) {
            TestUtils.assertJsonEqual(immutable[key], result[key]);;
          });
        });

        it("returns an Immutable Object", function() {
          var result = immutable.without(dropKeysPredicate(keys));
          assert.instanceOf(result, Object);
          TestUtils.assertIsDeeplyImmutable(result);
        });

        it("drops keys whose values satisfy the predicate", function() {
          var valuesToDrop = _.chain(immutable).pick(keys).values();
          // We might have dropped more keys as more keys might have the same value
          var expectedKeys = _.chain(immutable)
            .omit(function (value) {
              return _.includes(valuesToDrop, value);
            })
            .keys()
            .value();
          var result = immutable.without(function (value, key) {
            return _.includes(valuesToDrop, value);
          });

          TestUtils.assertJsonEqual(_.keys(result), expectedKeys);
        });

      });

    });
  });
};
<|endoftext|>


<commit_before>var EventBridge;
var WebChannel;
$(document).ready(function(){
    document.addEventListener("contextmenu", function(event) {
        event.preventDefault();
    }, false);
    WebChannel = new QWebChannel(qt.webChannelTransport, function (channel) {
        EventBridge = WebChannel.objects.eventBridgeWrapper.eventBridge;
        webEventBridgeCallback(EventBridge);
    });
});

function webEventBridgeCallback(eb){
    if (EventBridge !== undefined) {
        EventBridge.scriptEventReceived.connect(scriptEvent);
        loadData();
    }
}

function getRepos()
{
    repositories = {};
    for(var i = 0; i < repoUrls.length; i++){
        var url = repoUrls[i];
        var repository = {};
        repository["categories"] = {};
        repository["packages"] = {};
        $.ajax({
            url: url,
            success: function(response){
                data = JSON.parse(response);
                repositories[url] = data;
            },
            async: false
        });
    }
    debug(repositories);
    webEvent({command:"setRepositories",value:repositories});
}

function renderRepositories(){
    var cats = "";
    var repos = "";
    var count = 0;
    var repoCount = 0;
    for(var k in repositories){
        var repo = repositories[k];
        repos += renderRepo(repo,repoCount++,k);
        for(var l in repo.categories){
            if(count == 0){
                cats += '
';
            }
            cats += '
';
            var category = repo.categories[l];
            cats += renderCategory(l,category,repo.packages,repo.meta,k);
            cats += "
";
            ++count;
            if(count == 2){
                cats += "
";
                count = 0;
            }
        }
    }
    if(count != 0){
        cats += "
";
    }

    $("#debugtext").html("
" + cats.replace("<","<").replace(">",">") + "
");

    $("div#categorieslist").html(cats);
    $("div#repolist").html(repos);
}

function renderCategory(cat,category,packages,repo,repoKey){
    var html = '

' +
        category.name + '
Active <input type="checkbox" ' +
        (isActiveCategory(repoKey,cat) ? ' checked="checked" ' : "") +
        'data-repo="' +  repoKey + '" data-cat="' + cat + '" class="catcheck"/>
' +
        '

' + category.description +
        '

' +
        '' + repo.name +
        '

';
    return html;
}

function renderRepo(repo,c,repoKey){
    var html = '

' +
        repo.meta.name + '
Active ' +
        '<input type="checkbox" onchange="checkAllPkg(this,' + c + ');" ' +
        (isActivePkg(repoKey,"") ? 'checked="checked" ' : "") + 'class="repocheck" data-repo="' + repoKey + '" />
' +
        '

';

        //$(this).parent().siblings('.panel-body').eq(0).children('.pkgcheck').prop("checked",true)
    html += renderPackages(repo.packages, c,repoKey);

    html += '

' +
        '' + repo.meta.name +
        '

';
    return html;
}
function renderPackages(pkgs, c, repoKey){
    var html = "

";
    for(var k in pkgs){
        html += renderPackage(pkgs[k],k,c,repoKey);
    }
    return html + "

";
}

function renderPackage(pkg,k,c,repoKey){
    return '
<input type="checkbox" data-pkg="' + k + '" ' +
        (isActivePkg(repoKey,k) ? 'checked="checked" ' : "") +
        'data-repo="' + repoKey + '" ' +
        'class="pkgcheck pkgcheck-' + c + '" />	' + pkg.name + "
";
}

function post(val){
    alert(JSON.stringify(val));
}

function checkAllPkg(elem,c){
    $(".pkgcheck-" + c).each(function(index){
        $(this).prop("checked",$(elem).prop("checked"));
    });
}

function applyScripts(){
    var scripts = [];
    $("input.repocheck").each(function(i){
        if($(this).prop("checked")){
            scripts.push($(this).data("repo"));
        }
    });
    $("input.pkgcheck").each(function(i){
        if($(this).prop("checked")){
            var repo = $(this).data("repo");
            if(scripts.indexOf(repo) < 0){
                scripts.push(repo + ">" + $(this).data("pkg"));
            }
        }
    });
    var categories = [];
    $("input.catcheck").each(function(i){
        if($(this).prop("checked")){
            categories.push($(this).data("repo") + ">" + $(this).data("cat"));
        }
    });
    webEvent({command:"setActiveScripts",value:{scripts:scripts,categories:categories}});
}

var repoUrls = [];

function command(typ){
    return {command:typ};
}

function loadData()
{
    repoUrls = [];
    webEvent([command("getRepoUrls"),command("getActiveScripts"),command("getRepositories"),command("getRunningScripts")]);
}

function webEvent(val){
    if(EventBridge !== undefined){
        EventBridge.emitWebEvent(JSON.stringify(val));
    }
}

function debug(data){
    //alert(JSON.stringify(data));
    $("#debugtext").html(JSON.stringify(data));
}

function removeRepo(repo){
    webEvent({command:"removeRepoUrl",value:repo});
}

function addRepo(){
    var newrepo = $("input#newrepo").val();
    $("input#newrepo").val("");
    webEvent({command:"addRepoUrl",value:newrepo});
}
var activeScripts = null;

function isActivePkg(repo,pkg){
    if(activeScripts == null) return false;
    return (activeScripts.scripts.indexOf(repo + ">" + pkg) >= 0 || activeScripts.scripts.indexOf(repo) >= 0);
}

function isActiveCategory(repo,cat){
    if(activeScripts == null) return false;
    return (activeScripts.categories.indexOf(repo + ">" + cat) >= 0);
}

function getRunningScripts(){
    webEvent({command:"getRunningScripts"});
}

function stopScript(scr){
    webEvent({command:"stopScript",value:scr});
}

function refreshScript(scr){
    webEvent({command:"refreshScript",value:scr})
}

function reset(){
    webEvent(command("reset"));
}

function scriptEvent(scriptEventData){
    //alert(scriptEventData);
    scriptEventData = JSON.parse(scriptEventData);
    if(!(scriptEventData instanceof Array)){
        scriptEventData = [scriptEventData];
    }
    for(var i = 0;i < scriptEventData.length; i++){
        data = scriptEventData[i];
        if(!data.hasOwnProperty("command"))continue;
        if(!data.hasOwnProperty("value"))continue;
        switch (data.command) {
            case "getRepoUrls":
                if(data.value instanceof Array){
                    var html = "";
                    for(var i = 0;i < data.value.length; i++){
                        html += '
' + data.value[i] + '
';
                    }
                    $("tbody#activerepolist").html(html);
                    repoUrls = data.value;
                    getRepos();
                }
                break;
            case "getRunningScripts":
                var html = "";
                for(var i in data.value){
                    var run = data.value[i];
                    html += '
' + run.name + '
';
                }
                $("tbody#runningscripts").html(html);
                break;
            case "getRepositories":
                    repositories = data.value;
                    renderRepositories();
                break;
            case "getActiveScripts":
                    activeScripts = data.value;
                    renderRepositories();
                break;

        }
    }
}
<commit_msg>Added tagging and search suppurt to the ui<commit_after>var EventBridge;
var WebChannel;
$(document).ready(function(){
    document.addEventListener("contextmenu", function(event) {
        event.preventDefault();
    }, false);
    WebChannel = new QWebChannel(qt.webChannelTransport, function (channel) {
        EventBridge = WebChannel.objects.eventBridgeWrapper.eventBridge;
        webEventBridgeCallback(EventBridge);
    });
    $('input.searchbox').on('keyup paste change',function(){filterSearch(this)});
});

function webEventBridgeCallback(eb){
    if (EventBridge !== undefined) {
        EventBridge.scriptEventReceived.connect(scriptEvent);
        loadData();
    }
}

function getRepos()
{
    repositories = {};
    for(var i = 0; i < repoUrls.length; i++){
        var url = repoUrls[i];
        var repository = {};
        repository["categories"] = {};
        repository["packages"] = {};
        $.ajax({
            url: url,
            success: function(response){
                data = JSON.parse(response);
                repositories[url] = data;
            },
            async: false
        });
    }
    debug(repositories);
    webEvent({command:"setRepositories",value:repositories});
}

function renderRepositories(){
    var cats = "";
    var repos = "";
    var count = 0;
    var repoCount = 0;
    for(var k in repositories){
        var repo = repositories[k];
        repos += renderRepo(repo,repoCount++,k);
        for(var l in repo.categories){
            if(count == 0){
                cats += '
';
            }
            cats += '
';
            var category = repo.categories[l];
            cats += renderCategory(l,category,repo.packages,repo.meta,k);
            cats += "
";
            ++count;
            if(count == 2){
                cats += "
";
                count = 0;
            }
        }
    }
    if(count != 0){
        cats += "
";
    }

    $("#debugtext").html("
" + cats.replace("<","<").replace(">",">") + "
");

    $("div#categorieslist").html(cats);
    $("div#repolist").html(repos);
}

function renderCategory(cat,category,packages,repo,repoKey){
    var html = '

' +
        category.name + '
Active <input type="checkbox" ' +
        (isActiveCategory(repoKey,cat) ? ' checked="checked" ' : "") +
        'data-repo="' +  repoKey + '" data-cat="' + cat + '" class="catcheck"/>
' +
        '

' + category.description +
        '

' +
        '' + repo.name +
        '

';
    return html;
}

function filterSearch(elem){
    var search = "." + $(elem).data("search");
    var filter = $(elem).val();
    if(filter.length < 1){
        $(search).show();
        $(search + "-hide").show();
        return;
    }
    $(search + "-hide").hide();
    $(search).hide();
    $(search + '[data-tags*="' + filter + '"]').show();

}

function renderRepo(repo,c,repoKey){

    var tags = [];
    for(var k in repo.packages){
        var tgs = repo.packages[k].tags;
        for(var t in tgs){
            if(tags.indexOf(tgs[t]) < 0){
                tags.push(tgs[t]);
            }
        }
    }

    var html = '

' +
        repo.meta.name + '
Active ' +
        '<input type="checkbox" onchange="checkAllPkg(this,' + c + ');" ' +
        (isActivePkg(repoKey,"") ? 'checked="checked" ' : "") + 'class="repocheck" data-repo="' + repoKey + '" />
' +
        '

';

        //$(this).parent().siblings('.panel-body').eq(0).children('.pkgcheck').prop("checked",true)
    html += renderPackages(repo.packages, c,repoKey);

    html += '

' +
        '' + repo.meta.name +
        '

';
    return html;
}
function renderPackages(pkgs, c, repoKey){
    var html = "

";
    for(var k in pkgs){
        html += renderPackage(pkgs[k],k,c,repoKey);
    }
    return html + "

";
}

function renderPackage(pkg,k,c,repoKey){
    return '
<input type="checkbox" data-pkg="' + k + '" ' +
        (isActivePkg(repoKey,k) ? 'checked="checked" ' : "") +
        'data-repo="' + repoKey + '" ' +
        'class="pkgcheck pkgcheck-' + c + '" />	' + pkg.name + "
";
}

function post(val){
    alert(JSON.stringify(val));
}

function checkAllPkg(elem,c){
    $(".pkgcheck-" + c).each(function(index){
        $(this).prop("checked",$(elem).prop("checked"));
    });
}

function applyScripts(){
    var scripts = [];
    $("input.repocheck").each(function(i){
        if($(this).prop("checked")){
            scripts.push($(this).data("repo"));
        }
    });
    $("input.pkgcheck").each(function(i){
        if($(this).prop("checked")){
            var repo = $(this).data("repo");
            if(scripts.indexOf(repo) < 0){
                scripts.push(repo + ">" + $(this).data("pkg"));
            }
        }
    });
    var categories = [];
    $("input.catcheck").each(function(i){
        if($(this).prop("checked")){
            categories.push($(this).data("repo") + ">" + $(this).data("cat"));
        }
    });
    webEvent({command:"setActiveScripts",value:{scripts:scripts,categories:categories}});
}

var repoUrls = [];

function command(typ){
    return {command:typ};
}

function loadData()
{
    repoUrls = [];
    webEvent([command("getRepoUrls"),command("getActiveScripts"),command("getRepositories"),command("getRunningScripts")]);
}

function webEvent(val){
    if(EventBridge !== undefined){
        EventBridge.emitWebEvent(JSON.stringify(val));
    }
}

function debug(data){
    //alert(JSON.stringify(data));
    $("#debugtext").html(JSON.stringify(data));
}

function removeRepo(repo){
    webEvent({command:"removeRepoUrl",value:repo});
}

function addRepo(){
    var newrepo = $("input#newrepo").val();
    $("input#newrepo").val("");
    webEvent({command:"addRepoUrl",value:newrepo});
}
var activeScripts = null;

function isActivePkg(repo,pkg){
    if(activeScripts == null) return false;
    return (activeScripts.scripts.indexOf(repo + ">" + pkg) >= 0 || activeScripts.scripts.indexOf(repo) >= 0);
}

function isActiveCategory(repo,cat){
    if(activeScripts == null) return false;
    return (activeScripts.categories.indexOf(repo + ">" + cat) >= 0);
}

function getRunningScripts(){
    webEvent({command:"getRunningScripts"});
}

function stopScript(scr){
    webEvent({command:"stopScript",value:scr});
}

function refreshScript(scr){
    webEvent({command:"refreshScript",value:scr})
}

function reset(){
    webEvent(command("reset"));
}

function scriptEvent(scriptEventData){
    //alert(scriptEventData);
    scriptEventData = JSON.parse(scriptEventData);
    if(!(scriptEventData instanceof Array)){
        scriptEventData = [scriptEventData];
    }
    for(var i = 0;i < scriptEventData.length; i++){
        data = scriptEventData[i];
        if(!data.hasOwnProperty("command"))continue;
        if(!data.hasOwnProperty("value"))continue;
        switch (data.command) {
            case "getRepoUrls":
                if(data.value instanceof Array){
                    var html = "";
                    for(var i = 0;i < data.value.length; i++){
                        html += '
' + data.value[i] + '
';
                    }
                    $("tbody#activerepolist").html(html);
                    repoUrls = data.value;
                    getRepos();
                }
                break;
            case "getRunningScripts":
                var html = "";
                for(var i in data.value){
                    var run = data.value[i];
                    html += '
' + run.name + '
';
                }
                $("tbody#runningscripts").html(html);
                break;
            case "getRepositories":
                    repositories = data.value;
                    renderRepositories();
                break;
            case "getActiveScripts":
                    activeScripts = data.value;
                    renderRepositories();
                break;

        }
    }
}
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery.gridster
//= require jquery.knob
//= require jquery.leanModal.min
//= require jquery.timeago
//= require moment.min
//= require rickshaw-1.5.1.min
//= require batman
//= require batman.jquery
//= require d3-3.2.8.min
//= require es5-shim
//= require dashing-src
<commit_msg>change order<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery.gridster
//= require jquery.knob
//= require jquery.leanModal.min
//= require jquery.timeago
//= require moment.min
//= require d3-3.2.8.min
//= require rickshaw-1.5.1.min
//= require batman
//= require batman.jquery
//= require es5-shim
//= require dashing-src
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*
 * HOWDO:
 *
 * This test tests argstream by exhaustive search.
 *
 * For speed concerns, it's set to only run the integration test which is
 * sufficient to catch regressions.
 *
 * However, since you're reading this, you'll probably want to instead change
 * it to run the unit tests to help understand which side the failure is on.
 *
 * If you doubt the exhaustive or correct nature of the search, you may be
 * served by running the sanity test to iterate on the searcher itself.
 */

var test = require('tape');
var util = require('util');

var TestSearch = require('./lib/test_search');
var argstream = require('../argstream');

/* jshint camelcase:false */

// Useful for verifying the searcher
test.skip('setup sanity', argSearchTest(function t(state, assert) {
    var frames = state.frames;
    var args = state.args;

    // should only combine to 3 args
    assert.equal(args.length, 3);

    // shouldn't have any duplicate letters
    var counts = chrCounts(frames.map(function each(frame) {
        return frame.join('');
    }).join(''));
    var ks = Object.keys(counts);
    for (var i = 0; i < ks.length; i++) {
        if (counts[ks[i]] > 1) {
            assert.fail(util.format('bad test state', state));
            break;
        }
    }

    assert.end();
}));

test('argstream', function t(assert) {
    var verbose = true;
    if (module === require.main) {
        var argv = require('minimist', {
            boolean: {
                verbose: true
            },
            default: {
                verbose: verbose
            }
        })(process.argv.slice(2));
        verbose = argv.verbose;
    }

    assert.test('unit test OutArgStream', {skip: !verbose}, argSearchTest(function t(state, assert) {
        var frames = state.frames;
        var expect = realFrames(frames);
        var gotI = 0;
        var s = new argstream.OutArgStream();
        s.on('frame', function onFrame(tup) {
            var parts = tup[0];
            var expected = expect[gotI++];
            if (!expected) {
                assert.fail(util.format('unexpected frame %s: ', gotI, parts));
            } else {
                assert.deepEqual(parts, expected.map(function(part) {
                    return new Buffer(part);
                }), 'expected frame ' + gotI);
            }
        });
        s.on('finish', function onFinish() {
            assert.equal(gotI, expect.length, 'got all expected frames');
        });
        writeFrames(frames, s, assert.end);
    }));

    assert.test('unit test InArgStream', {skip: !verbose}, argSearchTest(function t(state, assert) {
        var frames = state.frames;
        var args = state.args;
        var s = new argstream.InArgStream();
        hookupEnd(s, finish);
        realFrames(frames).forEach(function eachFrame(parts) {
            s.handleFrame(parts);
        });
        s.handleFrame(null);
        function finish(err) {
            assert.ifError(err, 'no end error');
            assert.equal(getArg(s.arg1), args[0] || null, 'expected arg1');
            assert.equal(getArg(s.arg2), args[1] || null, 'expected arg2');
            assert.equal(getArg(s.arg3), args[2] || null, 'expected arg3');
            assert.end();
        }
    }));

    assert.test('integration test {Out -> In}ArgStream', {skip: verbose}, argSearchTest(function t(state, assert) {
        var frames = state.frames;
        var args = state.args;
        var o = new argstream.OutArgStream();
        var i = new argstream.InArgStream();
        o.on('frame', function onFrame(tup) {
            var parts = tup[0];
            i.handleFrame(parts);
        });
        writeFrames(frames, o, finish);
        function finish(err) {
            assert.ifError(err, 'no end error');
            i.handleFrame(null);
            assert.equal(getArg(i.arg1), args[0] || null, 'expected arg1');
            assert.equal(getArg(i.arg2), args[1] || null, 'expected arg2');
            assert.equal(getArg(i.arg3), args[2] || null, 'expected arg3');
            assert.end();
        }
    }));
});

function argSearchTest(testFunc) {
    var search = TestSearch({
        describeState: function describe(state) {
            return state.frames.map(function each(frame) {
                return frame.join('.');
            }).join('_');
        },

        init: function init() {
            var self = this;
            self.frontier.push({
                frames: [['', '', '']]
            });
        },

        test: function test(state, assert) {
            var self = this;
            var frames = state.frames;

            var args = state.args = [];
            var i = 0;
            args[i] = '';
            for (var j = 0; j < frames.length; j++) {
                var frame = frames[j];
                for (var k = 0; k < frame.length; k++) {
                    if (k > 0) args[++i] = '';
                    args[i] += frame[k];
                }
            }

            testFunc.call(self, state, assert);
        },

        next: function next(state, _emit) {
            var layers = [
                addPauses,
                addContent,
            ];
            gen(state.frames, 0, emit);

            function gen(frames, i, emit) {
                if (i < layers.length) {
                    layers[i](frames, function(frames) {
                        if (filter(frames)) {
                            gen(frames, i+1, emit);
                        }
                    });
                } else if (filter(frames)) {
                    emit(frames);
                }
            }

            function emit(frames) {
                _emit({frames: relabel(frames)});
            }
        }
    });
    return search.run.bind(search);
}

function realFrames(frames) {
    return frames.filter(function(frame) {
        if (!frame.length) return false;
        if (frame.length === 1 && !frame[0].length) return false;
        return true;
    });
}

function writeFrames(frames, s, callback) {
    hookupEnd(s, callback);
    var writingArg = 1;
    eachFrame(0);
    function eachFrame(i) {
        var stream = s['arg' + writingArg];
        if (i >= frames.length) {
            if (stream) stream.end();
            return;
        }
        var frame = frames[i];
        if (!stream) return callback(new Error('ran out of arg streams'));
        for (var j = 0; j < frame.length; j++) {
            if (j > 0) {
                stream.end();
                stream = s['arg' + (++writingArg)];
                if (!stream) return callback(new Error('ran out of arg streams'));
            }
            if (j === frame.length - 1 && i === frames.length - 1) {
                stream.end(frame[j]);
                writingArg++;
            } else {
                stream.write(frame[j]);
            }
        }
        setImmediate(eachFrame, i+1);
    }
}

function chrCounts(s) {
    var counts = {};
    s.split('').forEach(function(chr) {
        counts[chr] = (counts[chr] || 0) + 1;
    });
    return counts;
}

function addPauses(frames, emit) {
    for (var i = 0; i<frames.length; i++) {
        var head = frames.slice(0, i);
        var tail = frames.slice(i + 1);
        var frame = frames[i];
        for (var j = 0; j<frame.length; j++) {
            var a = frame.slice(0, j);
            var b = frame.slice(j);
            if (a.length && b.length) {
                emit(head.concat([a.concat(['']), b]).concat(tail));
                emit(head.concat([a, [''].concat(b)]).concat(tail));
            } else if (a.length || b.length) {
                emit(head.concat([a, b]).concat(tail));
            }
        }
    }
}

function addContent(frames, emit) {
    var chr = greatestChr(frames);
    for (var i = 0; i < frames.length; i++) {
        var head = frames.slice(0, i);
        var tail = frames.slice(i + 1);
        var frame = frames[i];
        for (var j = 0; j < frame.length; j++) {
            if (!frame[j].length) {
                var part = frame.slice(0, j)
                    .concat([String.fromCharCode(chr)])
                    .concat(frame.slice(j+1));
                emit(head.concat([part]).concat(tail));
            }
        }
    }
}

function greatestChr(frames) {
    var chr = 0x41;
    for (var i = 0; i<frames.length; i++) {
        var frame = frames[i];
        for (var j = 0; j<frame.length; j++) {
            if (frame[j].length) {
                chr = Math.max(chr, frame[j].charCodeAt(0) + 1);
            }
        }
    }
    return chr;
}

function relabel(frames) {
    var chr = 0x41;
    var ret = new Array(frames.length);
    for (var i = 0; i < frames.length; i++) {
        var frame = frames[i];
        ret[i] = new Array(frame.length);
        for (var j = 0; j < frame.length; j++) {
            ret[i][j] = frame[j].length ? String.fromCharCode(chr++) : '';
        }
    }
    return ret;
}

function filter(frames) {
    var i;
    var ends = 0;
    for (i = 0; i < frames.length; i++) {
        if (frames[i].length > 1) ends++;
    }
    if (ends > 3) return false;
    var run = 0;
    for (i = 1; i < frames.length; i++) {
        if (run || frames[i-1].length === 1) {
            if (frames[i].length === 1) {
                if (++run > 2) return false;
            } else if (frames[i].length > 1 && run) {
                return false;
            } else {
                run = 0;
            }
        }
    }
    simplify(frames);
    return true;
}

function simplify(frames) {
    var i = 1;
    while (i < frames.length) {
        var a = frames[i-1];
        var b = frames[i];
        if (!b.length) {
            if (!a.length) {
                frames.splice(i-1, 2, []);
            } else {
                frames.splice(i, 1);
            }
        } else if (b.length === 1 && b[0] === '') {
            if (a.length === 1 && a[0] === '') {
                frames.splice(i-1, 2, ['']);
            } else {
                frames.splice(i, 1);
            }
        } else {
            i++;
        }
    }
}

function hookupEnd(stream, callback) {
    stream.on('finish', onFinish);
    stream.on('error', onError);
    function onError(err) {
        stream.removeListener('finish', onFinish);
        stream.removeListener('error', onError);
        callback(err);
    }
    function onFinish() {
        stream.removeListener('finish', onFinish);
        stream.removeListener('error', onError);
        callback();
    }
}

function getArg(arg) {
    var val = arg.read();
    if (val !== null) {
        return val.toString();
    } else {
        return val;
    }
}
<commit_msg>test/argstream: take options to search test<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*
 * HOWDO:
 *
 * This test tests argstream by exhaustive search.
 *
 * For speed concerns, it's set to only run the integration test which is
 * sufficient to catch regressions.
 *
 * However, since you're reading this, you'll probably want to instead change
 * it to run the unit tests to help understand which side the failure is on.
 *
 * If you doubt the exhaustive or correct nature of the search, you may be
 * served by running the sanity test to iterate on the searcher itself.
 */

var extend = require('xtend');
var test = require('tape');
var util = require('util');

var TestSearch = require('./lib/test_search');
var argstream = require('../argstream');

/* jshint camelcase:false */

// Useful for verifying the searcher
test.skip('setup sanity', argSearchTest(function t(state, assert) {
    var frames = state.frames;
    var args = state.args;

    // should only combine to 3 args
    assert.equal(args.length, 3);

    // shouldn't have any duplicate letters
    var counts = chrCounts(frames.map(function each(frame) {
        return frame.join('');
    }).join(''));
    var ks = Object.keys(counts);
    for (var i = 0; i < ks.length; i++) {
        if (counts[ks[i]] > 1) {
            assert.fail(util.format('bad test state', state));
            break;
        }
    }

    assert.end();
}));

test('argstream', function t(assert) {
    var verbose = true;
    if (module === require.main) {
        var argv = require('minimist', {
            boolean: {
                verbose: true
            },
            default: {
                verbose: verbose
            }
        })(process.argv.slice(2));
        verbose = argv.verbose;
    }

    assert.test('unit test OutArgStream', {skip: !verbose}, argSearchTest(function t(state, assert) {
        var frames = state.frames;
        var expect = realFrames(frames);
        var gotI = 0;
        var s = new argstream.OutArgStream();
        s.on('frame', function onFrame(tup) {
            var parts = tup[0];
            var expected = expect[gotI++];
            if (!expected) {
                assert.fail(util.format('unexpected frame %s: ', gotI, parts));
            } else {
                assert.deepEqual(parts, expected.map(function(part) {
                    return new Buffer(part);
                }), 'expected frame ' + gotI);
            }
        });
        s.on('finish', function onFinish() {
            assert.equal(gotI, expect.length, 'got all expected frames');
        });
        writeFrames(frames, s, assert.end);
    }));

    assert.test('unit test InArgStream', {skip: !verbose}, argSearchTest(function t(state, assert) {
        var frames = state.frames;
        var args = state.args;
        var s = new argstream.InArgStream();
        hookupEnd(s, finish);
        realFrames(frames).forEach(function eachFrame(parts) {
            s.handleFrame(parts);
        });
        s.handleFrame(null);
        function finish(err) {
            assert.ifError(err, 'no end error');
            assert.equal(getArg(s.arg1), args[0] || null, 'expected arg1');
            assert.equal(getArg(s.arg2), args[1] || null, 'expected arg2');
            assert.equal(getArg(s.arg3), args[2] || null, 'expected arg3');
            assert.end();
        }
    }));

    assert.test('integration test {Out -> In}ArgStream', {skip: verbose}, argSearchTest(function t(state, assert) {
        var frames = state.frames;
        var args = state.args;
        var o = new argstream.OutArgStream();
        var i = new argstream.InArgStream();
        o.on('frame', function onFrame(tup) {
            var parts = tup[0];
            i.handleFrame(parts);
        });
        writeFrames(frames, o, finish);
        function finish(err) {
            assert.ifError(err, 'no end error');
            i.handleFrame(null);
            assert.equal(getArg(i.arg1), args[0] || null, 'expected arg1');
            assert.equal(getArg(i.arg2), args[1] || null, 'expected arg2');
            assert.equal(getArg(i.arg3), args[2] || null, 'expected arg3');
            assert.end();
        }
    }));
});

function argSearchTest(options, testFunc) {
    if (typeof options === 'function') {
        testFunc = options;
        options = {};
    }

    var search = TestSearch(extend(options, {
        describeState: function describe(state) {
            return state.frames.map(function each(frame) {
                return frame.join('.');
            }).join('_');
        },

        init: function init() {
            var self = this;
            self.frontier.push({
                frames: [['', '', '']]
            });
        },

        test: function test(state, assert) {
            var self = this;
            var frames = state.frames;

            var args = state.args = [];
            var i = 0;
            args[i] = '';
            for (var j = 0; j < frames.length; j++) {
                var frame = frames[j];
                for (var k = 0; k < frame.length; k++) {
                    if (k > 0) args[++i] = '';
                    args[i] += frame[k];
                }
            }

            testFunc.call(self, state, assert);
        },

        next: function next(state, _emit) {
            var layers = [
                addPauses,
                addContent,
            ];
            gen(state.frames, 0, emit);

            function gen(frames, i, emit) {
                if (i < layers.length) {
                    layers[i](frames, function(frames) {
                        if (filter(frames)) {
                            gen(frames, i+1, emit);
                        }
                    });
                } else if (filter(frames)) {
                    emit(frames);
                }
            }

            function emit(frames) {
                _emit({frames: relabel(frames)});
            }
        }
    }));
    return search.run.bind(search);
}

function realFrames(frames) {
    return frames.filter(function(frame) {
        if (!frame.length) return false;
        if (frame.length === 1 && !frame[0].length) return false;
        return true;
    });
}

function writeFrames(frames, s, callback) {
    hookupEnd(s, callback);
    var writingArg = 1;
    eachFrame(0);
    function eachFrame(i) {
        var stream = s['arg' + writingArg];
        if (i >= frames.length) {
            if (stream) stream.end();
            return;
        }
        var frame = frames[i];
        if (!stream) return callback(new Error('ran out of arg streams'));
        for (var j = 0; j < frame.length; j++) {
            if (j > 0) {
                stream.end();
                stream = s['arg' + (++writingArg)];
                if (!stream) return callback(new Error('ran out of arg streams'));
            }
            if (j === frame.length - 1 && i === frames.length - 1) {
                stream.end(frame[j]);
                writingArg++;
            } else {
                stream.write(frame[j]);
            }
        }
        setImmediate(eachFrame, i+1);
    }
}

function chrCounts(s) {
    var counts = {};
    s.split('').forEach(function(chr) {
        counts[chr] = (counts[chr] || 0) + 1;
    });
    return counts;
}

function addPauses(frames, emit) {
    for (var i = 0; i<frames.length; i++) {
        var head = frames.slice(0, i);
        var tail = frames.slice(i + 1);
        var frame = frames[i];
        for (var j = 0; j<frame.length; j++) {
            var a = frame.slice(0, j);
            var b = frame.slice(j);
            if (a.length && b.length) {
                emit(head.concat([a.concat(['']), b]).concat(tail));
                emit(head.concat([a, [''].concat(b)]).concat(tail));
            } else if (a.length || b.length) {
                emit(head.concat([a, b]).concat(tail));
            }
        }
    }
}

function addContent(frames, emit) {
    var chr = greatestChr(frames);
    for (var i = 0; i < frames.length; i++) {
        var head = frames.slice(0, i);
        var tail = frames.slice(i + 1);
        var frame = frames[i];
        for (var j = 0; j < frame.length; j++) {
            if (!frame[j].length) {
                var part = frame.slice(0, j)
                    .concat([String.fromCharCode(chr)])
                    .concat(frame.slice(j+1));
                emit(head.concat([part]).concat(tail));
            }
        }
    }
}

function greatestChr(frames) {
    var chr = 0x41;
    for (var i = 0; i<frames.length; i++) {
        var frame = frames[i];
        for (var j = 0; j<frame.length; j++) {
            if (frame[j].length) {
                chr = Math.max(chr, frame[j].charCodeAt(0) + 1);
            }
        }
    }
    return chr;
}

function relabel(frames) {
    var chr = 0x41;
    var ret = new Array(frames.length);
    for (var i = 0; i < frames.length; i++) {
        var frame = frames[i];
        ret[i] = new Array(frame.length);
        for (var j = 0; j < frame.length; j++) {
            ret[i][j] = frame[j].length ? String.fromCharCode(chr++) : '';
        }
    }
    return ret;
}

function filter(frames) {
    var i;
    var ends = 0;
    for (i = 0; i < frames.length; i++) {
        if (frames[i].length > 1) ends++;
    }
    if (ends > 3) return false;
    var run = 0;
    for (i = 1; i < frames.length; i++) {
        if (run || frames[i-1].length === 1) {
            if (frames[i].length === 1) {
                if (++run > 2) return false;
            } else if (frames[i].length > 1 && run) {
                return false;
            } else {
                run = 0;
            }
        }
    }
    simplify(frames);
    return true;
}

function simplify(frames) {
    var i = 1;
    while (i < frames.length) {
        var a = frames[i-1];
        var b = frames[i];
        if (!b.length) {
            if (!a.length) {
                frames.splice(i-1, 2, []);
            } else {
                frames.splice(i, 1);
            }
        } else if (b.length === 1 && b[0] === '') {
            if (a.length === 1 && a[0] === '') {
                frames.splice(i-1, 2, ['']);
            } else {
                frames.splice(i, 1);
            }
        } else {
            i++;
        }
    }
}

function hookupEnd(stream, callback) {
    stream.on('finish', onFinish);
    stream.on('error', onError);
    function onError(err) {
        stream.removeListener('finish', onFinish);
        stream.removeListener('error', onError);
        callback(err);
    }
    function onFinish() {
        stream.removeListener('finish', onFinish);
        stream.removeListener('error', onError);
        callback();
    }
}

function getArg(arg) {
    var val = arg.read();
    if (val !== null) {
        return val.toString();
    } else {
        return val;
    }
}
<|endoftext|>