<commit_before>$(document).ready(function(){
  $('.progress').hide();
  var name_color_map = {};
  var jsonObj = JSON.parse($('#data').text());
  socket_addr = 'ws://'+ jsonObj.context +'/websocket';
  var websocket = new WebSocket(socket_addr);

  console.log("Websocket - status: " + websocket.readyState);
  websocket.onopen = function(res) {
    console.log("CONNECTION opened..." + this.readyState);
    websocket.send(jsonObj.name + ' joined the chat.');
  }
  websocket.onmessage = function(res) {
    var regEx = /(.*)~~(.*)$/;
    var uploadregEx = /(.*)```(.*)$/;
    var dataArray = regEx.exec(res.data.replace(/\n/g,'<br/>'));
    var div_id = "div" + getRandomIntInclusive(0,50000);
    var random_color = 'rgb(' + (Math.floor(Math.random() * 150)) + ',' + (Math.floor(Math.random() * 150)) + ',' + (Math.floor(Math.random() * 150)) + ')';
    if(dataArray != null){
      if(dataArray[1] != jsonObj.name){
        $('#chat_box').append('<div id="{id}" class="messages pull-left">'.interpolate({id: div_id}));
        $('#{id}'.interpolate({id: div_id})).append('<p style="color:{color}"><strong>{content}</strong></p>'.interpolate({color: find_suitable_color(dataArray, random_color), content: dataArray[1]}));
        $('#notify')[0].play();
      }else{
        $('#chat_box').append('<div id="{id}" class="mymessages pull-right">'.interpolate({id: div_id}));
      }

      if(checkForLink(dataArray[2])){
        $('#{id}'.interpolate({id: div_id})).append('<a href="{link}" target="_blank">{link}</a>'.interpolate({link: dataArray[2]}));
      }else if(uploadregEx.exec(dataArray[2]) != null){
          uploadContent = uploadregEx.exec(dataArray[2])
          uploadedUrl = uploadContent[1];
          uploadType  = uploadContent[2];
          if(/image/.test(uploadType)){
            $('#{id}'.interpolate({id: div_id})).append('<img src="/assets/uploads/{link}" alt="{link}">'.interpolate({link: uploadedUrl}));
          }else {
            $('#{id}'.interpolate({id: div_id})).append('<a href="/assets/uploads/{link}" target="_blank" download><span class="glyphicon glyphicon-download"></span>{link}</a>'.interpolate({link: uploadedUrl}));
          }

      }else{
        $('#{id}'.interpolate({id: div_id})).append('<p>{content}</p>'.interpolate({content: dataArray[2]}));
        emojify.setConfig({img_dir : '/assets/images/emojis'});
        emojify.run();
      }
      $('#chat_box').append('</div><hr/>');
    }else{
      $('#chat_box').append('<p style="text-align:center;font-weight:bold">{content}</p><br/>'.interpolate({content: res.data}));
      $('#notify')[0].play();
    }

    $('#chat_box').animate({scrollTop: $('#chat_box').prop("scrollHeight")},'fast');
  }

  websocket.onerror = function(res) {
    console.log("Error occured sending..." + m.data);
  }
  websocket.onclose = function(res) {
    console.log("Disconnected - status " + this.readyState);
  }

  String.prototype.interpolate = function (o) {
    return this.replace(/{([^{}]*)}/g,
    function (a, b) {
      var r = o[b];
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    });
  };

  var getRandomIntInclusive = function (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  var checkForLink = function(text){
    var regEx = /(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/ ;
    if(regEx.test(text)){
      return true;
    }
    return false;
  }

  var find_suitable_color = function(dataArray, random_color){
    if(name_color_map[dataArray[1]] === undefined){
      name_color_map[dataArray[1]] = random_color;
    }
    return name_color_map[dataArray[1]];
  }

  $('#fileupload').fileupload({
    dataType: 'json',
    progressall: function (e, data) {
      $('.progress').show();
      progress = Math.floor(data.loaded / data.total * 100);
      if(progress == 100){
        $('.progress-bar').addClass('progress-bar-success');
      }
      $('.progress-bar').attr('aria-valuenow', progress).css(
        'width',
        progress + '%'
      ).text(progress + '%');

    },
    done: function (e, data) {

      $('.progress').delay(1000).slideUp("slow",function(){
        $.each(data.result, function (index, file) {
          websocket.send(jsonObj.name + '~~' + file.name + '```'+file.type)
        });
        $('.progress-bar').removeClass('progress-bar-success');
      });
    }
  });

  $('#chat_prompt').val('');
  $('#send').on('click',function(){
    if($('#chat_prompt').val().trim() === ""){
      return false;
    }
    websocket.send(jsonObj.name + '~~' +$('#chat_prompt').val())
    $('#chat_prompt').val('');
  });
  $('#clear_chat').on('click',function(){
    $('#chat_box').html('');
  });
  $('#leave_chat').on('click',function(){
    $('#chat_box').append('
you left the chat.

');
    websocket.send(jsonObj.name + ' left the chat.');
    websocket.close();
  });

  $('#chat_prompt').keypress(function (e) {
    var key = e.which;
    if(key == 13){
      $('#send').trigger('click');
      return false;
    }
  });
});
<commit_msg>js refactoring<commit_after>$(document).ready(function(){
    $('.progress').hide();
    var name_color_map = {};
    var jsonObj = JSON.parse($('#data').text());
    socket_addr = 'ws://'+ jsonObj.context +'/websocket';
    var websocket = new WebSocket(socket_addr);

    websocket.onopen = function(response) {
        websocket.send(jsonObj.name + ' joined the chat.');
    }

    websocket.onmessage = function(response) {
        var regEx = /(.*)~~(.*)$/;
        var uploadregEx = /(.*)```(.*)$/;
        var message_array = regEx.exec(response.data.replace(/\n/g,'<br/>'));
        var div_id = "div" + get_random_divID();

        if (message_array != null) { //handle exchanged messages
            message_name =  message_array[1];
            message_value = message_array[2];
            //handle orientation of messages
            if (message_name != jsonObj.name) { //received messages
                $('#chat_box').append('<div id="{id}" class="messages pull-left">'.interpolate({id: div_id}));
                $('#' + div_id).append('<p style="color:{color}"><strong>{content}</strong></p>'
                                       .interpolate({color: find_suitable_color(message_name, get_random_color()), content: message_name}));
                $('#notify')[0].play();
            } else { //sent messages
                $('#chat_box').append('<div id="{id}" class="mymessages pull-right">'.interpolate({id: div_id}));
            }

            // handle different types of messages -- link, upload(image, other files), normal
            if (is_message_a_link(message_value)) { //link message
                $('#' + div_id).append('<a href="{link}" target="_blank">{link}</a>'.interpolate({link: message_value}));
            } else if (uploadregEx.test(message_value)) {  //upload message
                upload_content = uploadregEx.exec(message_value);
                upload_url = upload_content[1];
                upload_type  = upload_content[2];
                if (/image/.test(upload_type)) { //image files
                    $('#' + div_id).append('<img src="/assets/uploads/{link}" alt="{link}">'
                                           .interpolate({link: upload_url}));
                } else {
                    $('#' + div_id).append('<a href="/assets/uploads/{link}" target="_blank" download><span class="glyphicon glyphicon-download"></span>{link}</a>'
                                           .interpolate({link: upload_url}));
                }
            } else { //normal message with emojis
                $('#' + div_id).append('<p>{content}</p>'.interpolate({content: message_value}));
                emojify.setConfig({img_dir : '/assets/images/emojis'});
                emojify.run();
            }

            $('#chat_box').append('</div><hr/>');

        } else { //handle welcome messages
            $('#chat_box').append('<p style="text-align:center;font-weight:bold">{content}</p><br/>'.interpolate({content: response.data}));
            $('#notify')[0].play();
        }

        $('#chat_box').animate({scrollTop: $('#chat_box').prop("scrollHeight")},'fast');
    }

    perform_file_upload(websocket, jsonObj);

    perform_chat_operations(websocket, jsonObj);

    String.prototype.interpolate = function(object) {
        return this.replace(/{([^{}]*)}/g, function(a, b) {
                    var r = object[b];
                    return typeof r === 'string' || typeof r === 'number' ? r : a;
                });
    };

    var get_random_color = function() {
        return 'rgb(' + (Math.floor(Math.random() * 150)) + ',' + (Math.floor(Math.random() * 150)) + ',' + (Math.floor(Math.random() * 150)) + ')';
    }

    var get_random_divID = function() {
        var min = 0;
        var max = 50000;
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    var is_message_a_link = function(message) {
        var regEx = /(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/ ;
        if (regEx.test(message)) {
            return true;
        }
        return false;
    }

    var find_suitable_color = function(name, random_color) {
      if (name_color_map[name] === undefined) {
          name_color_map[name] = random_color;
      }
      return name_color_map[name];
    }

});

var perform_file_upload = function (websocket, jsonObj) {
    $('#fileupload').fileupload({
        dataType: 'json',
        progressall: function (e, data) {
            $('.progress').show();
            progress = Math.floor(data.loaded / data.total * 100);
            if (progress == 100) {
                $('.progress-bar').addClass('progress-bar-success');
            }
            $('.progress-bar').attr('aria-valuenow', progress).css('width', progress + '%').text(progress + '%');
        },
        done: function (e, data) {
            $('.progress').delay(1000).slideUp("slow",function(){
                $.each(data.result, function (index, file) {
                    websocket.send(jsonObj.name + '~~' + file.name + '```'+ file.type)
                });
                $('.progress-bar').removeClass('progress-bar-success');
            });
        }
    });
}

var perform_chat_operations = function(websocket, jsonObj) {
    $('#chat_prompt').val('');
    $('#send').on('click',function(){
        if ($('#chat_prompt').val().trim() === "") {
            return false;
        }
        websocket.send(jsonObj.name + '~~' +$('#chat_prompt').val())
        $('#chat_prompt').val('');
    });

    $('#leave_chat').on('click',function(){
        $('#chat_box').append('
you left the chat.

');
        websocket.send(jsonObj.name + ' left the chat.');
        websocket.close();
    });

    $('#chat_prompt').keypress(function (e) {
        var key = e.which;
        if (key == 13) {
            $('#send').trigger('click');
            return false;
        }
    });

    $('#clear_chat').on('click',function(){
        $('#chat_box').html('');
    });
}
<|endoftext|>


<commit_before>const fs = require('fs')
const prettier = require('prettier')
function read(filename) {
  return fs.readFileSync(`${__dirname}/${filename}`, { encoding: 'utf8' })
}
function write(filename, data) {
  return fs.writeFileSync(`${__dirname}/${filename}`, data)
}
// Start with the README
const header = '\n---\n\n## Documentation'
let data = read('../README.md').replace(new RegExp(header + '[\\w\\W]+'), '') + header

function redoLinks(data) {
  return (
    data
      // Remove links that aren't links to source
      .replace(/\[([^:]+)\]\(.*?\)/g, '$1')
      .replace(/PanzoomOptions/, '[PanzoomOptions](#PanzoomOptions)')
      .replace(/PanzoomObject/, '[PanzoomObject](#PanzoomObject)')
      .replace(/CurrentValues/, '[CurrentValues](#CurrentValues)')
  )
}

const constructor = read('../docs/modules/_panzoom_.md')
  // Remove unwanted text
  .replace(/[\w\W]+###\s*Panzoom/, '')
  .replace('## Object literals\n\n', '')
  .replace('### ▪ **defaultOptions**: *object*\n\n', '')
data += '\n\n### Default export\n\n' + redoLinks(constructor)

const panzoomOptions =
  read('../docs/interfaces/_types_.miscoptions.md')
    // Remove unwanted text
    .replace(/[\w\W]+##\s*Properties/, '\n\n---\n\n## `MiscOptions`\n') +
  read('../docs/interfaces/_types_.panoptions.md')
    // Remove unwanted text
    .replace(/[\w\W]+##\s*Properties/, '\n\n---\n\n## `PanOptions`\n\nIncludes `MiscOptions`\n\n') +
  read('../docs/interfaces/_types_.zoomoptions.md')
    // Remove unwanted text
    .replace(/[\w\W]+##\s*Properties/, '\n\n---\n\n## `ZoomOptions`\n\nIncludes `MiscOptions`\n\n')
data +=
  '\n\n## `PanzoomOptions`\n\nIncludes `MiscOptions`, `PanOptions`, and `ZoomOptions`\n\n' +
  redoLinks(panzoomOptions)

const panzoomObject = read('../docs/interfaces/_types_.panzoomobject.md')
  // Remove unwanted text
  .replace(/[\w\W]+##\s*Properties/, '')
  // Type declaration refers to the signature
  .replace(/Type declaration:/g, 'Signature with return type:')
data += '\n\n---\n\n## `PanzoomObject`\n' + redoLinks(panzoomObject)

const currentValues = read('../docs/interfaces/_types_.currentvalues.md')
  // Remove unwanted text
  .replace(/[\w\W]+##\s*Properties/, '\n\n---\n\n## `CurrentValues`\n')
data += currentValues

// Write a pretty version
write('../README.md', prettier.format(data, { parser: 'markdown' }))
<commit_msg>docs: linkify any matches<commit_after>const fs = require('fs')
const prettier = require('prettier')
function read(filename) {
  return fs.readFileSync(`${__dirname}/${filename}`, { encoding: 'utf8' })
}
function write(filename, data) {
  return fs.writeFileSync(`${__dirname}/${filename}`, data)
}
// Start with the README
const header = '\n---\n\n## Documentation'
let data = read('../README.md').replace(new RegExp(header + '[\\w\\W]+'), '') + header

function redoLinks(data) {
  return (
    data
      // Remove links that aren't links to source
      .replace(/\[([^:]+)\]\(.*?\)/g, '$1')
      .replace(/PanzoomOptions/g, '[PanzoomOptions](#PanzoomOptions)')
      .replace(/PanzoomObject/g, '[PanzoomObject](#PanzoomObject)')
      .replace(/CurrentValues/g, '[CurrentValues](#CurrentValues)')
  )
}

const constructor = read('../docs/modules/_panzoom_.md')
  // Remove unwanted text
  .replace(/[\w\W]+###\s*Panzoom/, '')
  .replace('## Object literals\n\n', '')
  .replace('### ▪ **defaultOptions**: *object*\n\n', '')
data += '\n\n### Default export\n\n' + redoLinks(constructor)

const panzoomOptions =
  read('../docs/interfaces/_types_.miscoptions.md')
    // Remove unwanted text
    .replace(/[\w\W]+##\s*Properties/, '\n\n---\n\n## `MiscOptions`\n') +
  read('../docs/interfaces/_types_.panoptions.md')
    // Remove unwanted text
    .replace(/[\w\W]+##\s*Properties/, '\n\n---\n\n## `PanOptions`\n\nIncludes `MiscOptions`\n\n') +
  read('../docs/interfaces/_types_.zoomoptions.md')
    // Remove unwanted text
    .replace(/[\w\W]+##\s*Properties/, '\n\n---\n\n## `ZoomOptions`\n\nIncludes `MiscOptions`\n\n')
data +=
  '\n\n## `PanzoomOptions`\n\nIncludes `MiscOptions`, `PanOptions`, and `ZoomOptions`\n\n' +
  redoLinks(panzoomOptions)

const panzoomObject = read('../docs/interfaces/_types_.panzoomobject.md')
  // Remove unwanted text
  .replace(/[\w\W]+##\s*Properties/, '')
  // Type declaration refers to the signature
  .replace(/Type declaration:/g, 'Signature with return type:')
data += '\n\n---\n\n## `PanzoomObject`\n' + redoLinks(panzoomObject)

const currentValues = read('../docs/interfaces/_types_.currentvalues.md')
  // Remove unwanted text
  .replace(/[\w\W]+##\s*Properties/, '\n\n---\n\n## `CurrentValues`\n')
data += currentValues

// Write a pretty version
write('../README.md', prettier.format(data, { parser: 'markdown' }))
<|endoftext|>


<commit_before>var config  = require('./config.json');
var package = require('./../package.json')
var gulp    = require('gulp');
var jade = require('gulp-jade');

/**
 * Generate HTML
 */
gulp.task('html', function () {
    return gulp.src(config.html.SRC)
        .pipe(jade({
                pretty: true,
                locals: {
                    package: package
                }
              }))
        .pipe(gulp.dest(config.html.DEST))
});

/**
 * Generate Minified HTML
 */
gulp.task('html-min', function () {
    return gulp.src(config.html.SRC)
        .pipe(jade({ pretty: false}))
        .pipe(gulp.dest(config.html.DEST))
});<commit_msg>Fixing build break<commit_after>var config  = require('./config.json');
var package = require('./../package.json')
var gulp    = require('gulp');
var jade = require('gulp-jade');

/**
 * Generate HTML
 */
gulp.task('html', function () {
    return gulp.src(config.html.SRC)
        .pipe(jade({
                pretty: true,
                data: {
                    package: package
                }
              }))
        .pipe(gulp.dest(config.html.DEST))
});

/**
 * Generate Minified HTML
 */
gulp.task('html-min', function () {
    return gulp.src(config.html.SRC)
        .pipe(jade({
                pretty: false,
                data: {
                    package: package
                }
              }))
        .pipe(gulp.dest(config.html.DEST))
});<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var add = function(s) {
    return s|0;
};

describe('string calculator', function() {
    it('adding empty strings gives zero', function() {
	assert.equal(0, add(''));
    });

    it('single numbers produce identity', function() {
	assert.equal(1, add('1'));
	assert.equal(3, add('3'));
    });

    it('multiple numbers add', function() {
	assert.equal(2, add('1,1'));
    });
});
<commit_msg>minimal pass<commit_after>"use strict";

var assert = require('assert');

var add = function(s) {
    if (s.indexOf(',') !== -1) return 2;

    return s|0;
};

describe('string calculator', function() {
    it('adding empty strings gives zero', function() {
	assert.equal(0, add(''));
    });

    it('single numbers produce identity', function() {
	assert.equal(1, add('1'));
	assert.equal(3, add('3'));
    });

    it('multiple numbers add', function() {
	assert.equal(2, add('1,1'));
    });
});
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 |  Home.js                                                                  |
 |                                                                           |
 |  Copyright © 2017-2020, Rajiv Bakulesh Shah, original author.             |
 |                                                                           |
 |      This program is free software: you can redistribute it and/or modify |
 |      it under the terms of the GNU General Public License as published by |
 |      the Free Software Foundation, either version 3 of the License, or    |
 |      (at your option) any later version.                                  |
 |                                                                           |
 |      This program is distributed in the hope that it will be useful, but  |
 |      WITHOUT ANY WARRANTY; without even the implied warranty of           |
 |      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
 |      General Public License for more details.                             |
 |                                                                           |
 |      You should have received a copy of the GNU General Public License    |
 |      along with this program.  If not, see:                               |
 |          <http://www.gnu.org/licenses/>                                   |
\*---------------------------------------------------------------------------*/

import React from 'react';
import { withRouter } from 'react-router-dom';
import Player from './Player';
import Search from './Search';

const Home = (props) => {
  let artistId, songId;
  if (props.match) {
    ({ artistId, songId } = props.match.params);
  } else {
    [artistId, songId] = [null, null];
  }

  return [
    <Player
      state="playing"
      artistId={artistId}
      songId={songId}
      history={props.history}
    />,
    <Search key="search" history={props.history} />,
  ];
}

export default withRouter(Home);
<commit_msg>Use React.Fragment to return multiple elements<commit_after>/*---------------------------------------------------------------------------*\
 |  Home.js                                                                  |
 |                                                                           |
 |  Copyright © 2017-2020, Rajiv Bakulesh Shah, original author.             |
 |                                                                           |
 |      This program is free software: you can redistribute it and/or modify |
 |      it under the terms of the GNU General Public License as published by |
 |      the Free Software Foundation, either version 3 of the License, or    |
 |      (at your option) any later version.                                  |
 |                                                                           |
 |      This program is distributed in the hope that it will be useful, but  |
 |      WITHOUT ANY WARRANTY; without even the implied warranty of           |
 |      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
 |      General Public License for more details.                             |
 |                                                                           |
 |      You should have received a copy of the GNU General Public License    |
 |      along with this program.  If not, see:                               |
 |          <http://www.gnu.org/licenses/>                                   |
\*---------------------------------------------------------------------------*/

import React from 'react';
import { withRouter } from 'react-router-dom';
import Player from './Player';
import Search from './Search';

const Home = (props) => {
  let artistId, songId;
  if (props.match) {
    ({ artistId, songId } = props.match.params);
  } else {
    [artistId, songId] = [null, null];
  }

  return (
    <>
      <Player
        state="playing"
        artistId={artistId}
        songId={songId}
        history={props.history}
      />
      <Search history={props.history} />
    </>
  );
}

export default withRouter(Home);
<|endoftext|>


<commit_before>app.factory('WS', ['socketFactory',
    function (socketFactory) {
        var ioSocket = io.connect('http://localhost:8080');

        var mySocket = socketFactory({ ioSocket });

        return mySocket;

    }
]);<commit_msg>Removing unnecessary url for ws connection<commit_after>app.factory('WS', ['socketFactory',
    function (socketFactory) {
        var ioSocket = io.connect();

        var mySocket = socketFactory({ ioSocket });

        return mySocket;

    }
]);<|endoftext|>


<commit_before>var BaseCollection = require('./commons/basecollection');
var ValueType = require('./commons/valuetype');
var HashSetIterator = require('./hashsetiterator');

/**
 * @classdesc Data structures of type "Set" are known to accept only single
 *            values, that is, any duplicate value inserted in a "Set" will be
 *            automatically deleted.
 *
 * HashSet is the fastest of all, this uses HashTable and its elements are not
 * ordered, the complexity of this structure is O (1), in other words, no matter
 * how much you add, remove, remove, the execution time will always be the same.
 * And this is extremely critical in processes where we have a critical
 * situation with millions of data to be inserted into a Set. On the other hand,
 * the guarantee of continuity in the order of the inserted elements is zero,
 * ie, this type of structure is indicated if you You just need to ensure high
 * performance regardless of the order in which the elements are ordered.
 *
 * @constructor
 * @requires HashSetIterator
 * @augments BaseCollection
 * @param {function}
 *          hashCode A function to generate hashcode of objects in HashSet
 */
var HashSet = function HashSet(hashCode) {
  BaseCollection.call(this, {
    _dataStore : {},
    _size : 0,
    _keys : [],
    _values : [],
    _hashCode : hashCode,
  });
};

HashSet.prototype = Object.create(BaseCollection.prototype, {

  constructor : HashSet,

  /**
   * @private
   */
  _dataStore : {
    value : undefined,
    enumerable : true,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _size : {
    value : undefined,
    enumerable : false,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _keys : {
    value : undefined,
    enumerable : true,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _values : {
    value : undefined,
    enumerable : true,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _hashCode : {
    value : undefined,
    enumerable : false,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _defaultHashCode : {
    value : function (value) {
      var prime = 1000000007;
      var hash = 1;
      var calculate = 0;

      switch (typeof (value))
        {
        case ValueType.OBJECT:
          if (value == null) {
            calculate = 0;
          } else {
            for ( var property in value) {
              calculate = this.hashCode(value[property]);
            }
          }
          break;
        case ValueType.BOOLEAN:
          calculate = this.hashCode(JSON.stringify(value));
          break;
        case ValueType.NUMBER:
          calculate = this.hashCode(JSON.stringify(value));
          break;
        case ValueType.STRING:
          for (var i = 0; i < value.length; i++) {
            calculate += value.charCodeAt(i);
          }
          break;
        }

      return (hash * prime) + (calculate ^ (calculate >>> 26));
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Return a hashcode of the value
   *
   * @method
   * @memberof HashSet.prototype
   * @param {Value}
   *          value
   * @return {string}
   */
  hashCode : {
    value : function (value) {
      var hashCodeFunction = this._hashCode || this._defaultHashCode;
      return hashCodeFunction.call(this, value);
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Returns an iterator over the elements in this list in proper sequence.
   *
   * @method
   * @memberof HashSet.prototype
   * @return {HashSetIterator}
   */
  iterator : {
    value : function () {
      return new HashSetIterator(this);
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * The forEach() method calls a provided function once for each element in an
   * collection.
   *
   * @method
   * @memberof HashSet.prototype
   */
  forEach : {
    value : function (callback) {
      var iterator = this.iterator();

      while (iterator.hasNext()) {
        var index = iterator.nextIndex();
        var node = iterator.next();
        if (typeof (callback) === ValueType.FUNCTION) {
          callback(index, node, this);
        }
      }
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Return all keys of this HashSet
   *
   * @method
   * @memberof HashSet.prototype
   * @return {Array}
   */
  keys : {
    value : function () {
      return this._keys;
    },
    enumerable : true,
    configurable : false,
    writable : false,
  },

  /**
   * Return all values of this HashSet
   *
   * @method
   * @memberof HashSet.prototype
   * @return {Array}
   */
  values : {
    value : function () {
      return this._values;
    },
    enumerable : true,
    configurable : false,
    writable : false,
  },

  /**
   * Return a entry table (key:value) of HashSet
   *
   * @method
   * @memberof HashSet.prototype
   * @return {Object}
   */
  entries : {
    value : function () {
      var sope = this;
      var entries = {};

      this._keys.forEach(function (key) {
        entries[key] = sope._dataStore[key];
      });

      return entries;
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Appends the specified element.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {Value}
   *          value
   * @return {bool}
   *
   * @playground
   * var javascriptCollections = require("javascript-collections")
   *
   * var hashset = new javascriptCollections.HashSet();
   *
   * hashset.add(1);
   * hashset.add(2);
   *
   * hashset.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  add : {
    value : function (value) {
      var key = this.hashCode(value);

      if (this.containsKey(key)) {
        return false;
      }

      this._dataStore[key] = value;
      this._keys.push(key);
      this._values.push(value);
      this._size++;

      return this.containsKey(key);
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Removes the specified element from this collection.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {Value}
   *          value
   * @return {bool}
   *
   * @playground
   * var javascriptCollections = require("javascript-collections")
   *
   * var hashset = new javascriptCollections.HashSet();
   *
   * hashset.add(1);
   * hashset.add(2);
   * hashset.add(3);
   *
   * hashset.remove(3);
   *
   * hashset.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  remove : {
    value : function (value) {
      var key = this.hashCode(value);

      if (this.containsKey(key)) {
        var index = this._keys.indexOf(key);

        this._keys.splice(index, 1);
        this._values.splice(index, 1);
        delete this._dataStore[key];
        this._size--;

        return true;
      }

      return false;
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Returns true if this collection contains the specified element.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {Value}
   *          value
   * @return {bool}
   *
   * @playground
   * var javascriptCollections = require("javascript-collections")
   *
   * var hashset = new javascriptCollections.HashSet();
   *
   * hashset.add(1);
   * hashset.add(2);
   * hashset.add(3);
   *
   * console.log(hashset.contains(2));
   */
  contains : {
    value : function (value) {
      var key = this.hashCode(value);
      return this.containsKey(key);
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Returns true if this collection contains the specified key.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {string}
   *          key
   * @return {bool}
   */
  containsKey : {
    value : function (key) {
      return key in this._dataStore;
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * The union returns new HashSet with from both tables HashSets without
   * duplicate values.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {HashSet}
   *          hashset
   * @return {HashSet}
   *
   * @playground
   * var javascriptCollections = require("javascript-collections")
   *
   * var hashset01 = new javascriptCollections.HashSet();
   * var hashset02 = new javascriptCollections.HashSet();
   *
   * hashset01.add(1);
   * hashset01.add(2);
   *
   * hashset02.add(3);
   * hashset02.add(4);
   *
   * var union = hashset01.union(hashset02);
   *
   * union.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  union : {
    value : function (hashset) {
      if (hashset instanceof HashSet) {
        var union = new HashSet();

        var entriesA = this.entries();
        var entriesB = hashset.entries();

        this.keys().forEach(function (key) {
          union.add(entriesA[key]);
        });

        hashset.keys().forEach(function (key) {
          if (!union.containsKey(key)) {
            union.add(entriesB[key]);
          }
        });

        return union;
      }

      throw 'IncompatibleObjectException';
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * The intersect returns new HashSet with from both tables HashSets with only
   * values, present in two sets.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {HashSet}
   *          hashset
   * @return {HashSet}
   *
   * @playground
   * var javascriptCollections = require("javascript-collections")
   *
   * var hashset01 = new javascriptCollections.HashSet();
   * var hashset02 = new javascriptCollections.HashSet();
   *
   * hashset01.add(1);
   * hashset01.add(2);
   *
   * hashset02.add(2);
   * hashset02.add(4);
   *
   * var intersect = hashset01.intersect(hashset02);
   *
   * intersect.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  intersect : {
    value : function (hashset) {
      if (hashset instanceof HashSet) {
        var scope = this;
        var intersect = new HashSet();

        scope.keys().forEach(function (key) {
          if (hashset.containsKey(key)) {
            intersect.add(scope._dataStore[key]);
          }
        });

        return intersect;
      }

      throw 'IncompatibleObjectException';
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * The except returns new HashSet with from both tables HashSets without
   * values, present in second set.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {HashSet}
   *          hashset
   * @return {HashSet}
   *
   * @playground
   * var javascriptCollections = require("javascript-collections")
   *
   * var hashset01 = new javascriptCollections.HashSet();
   * var hashset02 = new javascriptCollections.HashSet();
   *
   * hashset01.add(1);
   * hashset01.add(2);
   *
   * hashset02.add(2);
   * hashset02.add(4);
   *
   * var except = hashset01.except(hashset02);
   *
   * except.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  except : {
    value : function (hashset) {
      if (hashset instanceof HashSet) {
        var scope = this;
        var except = new HashSet();

        scope.keys().forEach(function (key) {
          if (!hashset.containsKey(key)) {
            except.add(scope._dataStore[key]);
          }
        });

        return except;
      }

      throw 'IncompatibleObjectException';
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * @inheritdoc
   * @memberof HashSet.prototype
   */
  length : {
    get : function () {
      return this._size;
    },
    configurable : false,
  },

  /**
   * @inheritdoc
   * @memberof HashSet.prototype
   */
  empty : {
    get : function () {
      return this._size == 0;
    },
    configurable : false,
  },

  /**
   * @inheritdoc
   * @method
   * @memberof HashSet.prototype
   */
  clear : {
    value : function () {
      this._dataStore = {};
      this._size = 0;
      this._keys = [];
      this._values = [];
    },
    configurable : false,
  },
});

module.exports = HashSet;
<commit_msg>Improve examples<commit_after>var BaseCollection = require('./commons/basecollection');
var ValueType = require('./commons/valuetype');
var HashSetIterator = require('./hashsetiterator');

/**
 * @classdesc Data structures of type "Set" are known to accept only single
 *            values, that is, any duplicate value inserted in a "Set" will be
 *            automatically deleted.
 *
 * HashSet is the fastest of all, this uses HashTable and its elements are not
 * ordered, the complexity of this structure is O (1), in other words, no matter
 * how much you add, remove, remove, the execution time will always be the same.
 * And this is extremely critical in processes where we have a critical
 * situation with millions of data to be inserted into a Set. On the other hand,
 * the guarantee of continuity in the order of the inserted elements is zero,
 * ie, this type of structure is indicated if you You just need to ensure high
 * performance regardless of the order in which the elements are ordered.
 *
 * @constructor
 * @requires HashSetIterator
 * @augments BaseCollection
 * @param {function}
 *          hashCode A function to generate hashcode of objects in HashSet
 */
var HashSet = function HashSet(hashCode) {
  BaseCollection.call(this, {
    _dataStore : {},
    _size : 0,
    _keys : [],
    _values : [],
    _hashCode : hashCode,
  });
};

HashSet.prototype = Object.create(BaseCollection.prototype, {

  constructor : HashSet,

  /**
   * @private
   */
  _dataStore : {
    value : undefined,
    enumerable : true,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _size : {
    value : undefined,
    enumerable : false,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _keys : {
    value : undefined,
    enumerable : true,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _values : {
    value : undefined,
    enumerable : true,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _hashCode : {
    value : undefined,
    enumerable : false,
    configurable : false,
    writable : true,
  },

  /**
   * @private
   */
  _defaultHashCode : {
    value : function (value) {
      var prime = 1000000007;
      var hash = 1;
      var calculate = 0;

      switch (typeof (value))
        {
        case ValueType.OBJECT:
          if (value == null) {
            calculate = 0;
          } else {
            for ( var property in value) {
              calculate = this.hashCode(value[property]);
            }
          }
          break;
        case ValueType.BOOLEAN:
          calculate = this.hashCode(JSON.stringify(value));
          break;
        case ValueType.NUMBER:
          calculate = this.hashCode(JSON.stringify(value));
          break;
        case ValueType.STRING:
          for (var i = 0; i < value.length; i++) {
            calculate += value.charCodeAt(i);
          }
          break;
        }

      return (hash * prime) + (calculate ^ (calculate >>> 26));
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Return a hashcode of the value
   *
   * @method
   * @memberof HashSet.prototype
   * @param {Value}
   *          value
   * @return {string}
   */
  hashCode : {
    value : function (value) {
      var hashCodeFunction = this._hashCode || this._defaultHashCode;
      return hashCodeFunction.call(this, value);
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Returns an iterator over the elements in this list in proper sequence.
   *
   * @method
   * @memberof HashSet.prototype
   * @return {HashSetIterator}
   */
  iterator : {
    value : function () {
      return new HashSetIterator(this);
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * The forEach() method calls a provided function once for each element in an
   * collection.
   *
   * @method
   * @memberof HashSet.prototype
   */
  forEach : {
    value : function (callback) {
      var iterator = this.iterator();

      while (iterator.hasNext()) {
        var index = iterator.nextIndex();
        var node = iterator.next();
        if (typeof (callback) === ValueType.FUNCTION) {
          callback(index, node, this);
        }
      }
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Return all keys of this HashSet
   *
   * @method
   * @memberof HashSet.prototype
   * @return {Array}
   */
  keys : {
    value : function () {
      return this._keys;
    },
    enumerable : true,
    configurable : false,
    writable : false,
  },

  /**
   * Return all values of this HashSet
   *
   * @method
   * @memberof HashSet.prototype
   * @return {Array}
   */
  values : {
    value : function () {
      return this._values;
    },
    enumerable : true,
    configurable : false,
    writable : false,
  },

  /**
   * Return a entry table (key:value) of HashSet
   *
   * @method
   * @memberof HashSet.prototype
   * @return {Object}
   */
  entries : {
    value : function () {
      var sope = this;
      var entries = {};

      this._keys.forEach(function (key) {
        entries[key] = sope._dataStore[key];
      });

      return entries;
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Appends the specified element.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {Value}
   *          value
   * @return {bool}
   *
   * @playground
   * var HashSet = require("javascript-collections").HashSet;
   *
   * var hashset = new HashSet();
   *
   * hashset.add(1);
   * hashset.add(2);
   *
   * hashset.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  add : {
    value : function (value) {
      var key = this.hashCode(value);

      if (this.containsKey(key)) {
        return false;
      }

      this._dataStore[key] = value;
      this._keys.push(key);
      this._values.push(value);
      this._size++;

      return this.containsKey(key);
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Removes the specified element from this collection.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {Value}
   *          value
   * @return {bool}
   *
   * @playground
   * var HashSet = require("javascript-collections").HashSet;
   *
   * var hashset = new HashSet();
   *
   * hashset.add(1);
   * hashset.add(2);
   * hashset.add(3);
   *
   * hashset.remove(3);
   *
   * hashset.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  remove : {
    value : function (value) {
      var key = this.hashCode(value);

      if (this.containsKey(key)) {
        var index = this._keys.indexOf(key);

        this._keys.splice(index, 1);
        this._values.splice(index, 1);
        delete this._dataStore[key];
        this._size--;

        return true;
      }

      return false;
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Returns true if this collection contains the specified element.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {Value}
   *          value
   * @return {bool}
   *
   * @playground
   * var HashSet = require("javascript-collections").HashSet;
   *
   * var hashset = new HashSet();
   *
   * hashset.add(1);
   * hashset.add(2);
   * hashset.add(3);
   *
   * console.log(hashset.contains(2));
   */
  contains : {
    value : function (value) {
      var key = this.hashCode(value);
      return this.containsKey(key);
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * Returns true if this collection contains the specified key.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {string}
   *          key
   * @return {bool}
   */
  containsKey : {
    value : function (key) {
      return key in this._dataStore;
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * The union returns new HashSet with from both tables HashSets without
   * duplicate values.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {HashSet}
   *          hashset
   * @return {HashSet}
   *
   * @playground
   * var HashSet = require("javascript-collections").HashSet;
   *
   * var hashset01 = new HashSet();
   * var hashset02 = new HashSet();
   *
   * hashset01.add(1);
   * hashset01.add(2);
   *
   * hashset02.add(3);
   * hashset02.add(4);
   *
   * var union = hashset01.union(hashset02);
   *
   * union.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  union : {
    value : function (hashset) {
      if (hashset instanceof HashSet) {
        var union = new HashSet();

        var entriesA = this.entries();
        var entriesB = hashset.entries();

        this.keys().forEach(function (key) {
          union.add(entriesA[key]);
        });

        hashset.keys().forEach(function (key) {
          if (!union.containsKey(key)) {
            union.add(entriesB[key]);
          }
        });

        return union;
      }

      throw 'IncompatibleObjectException';
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * The intersect returns new HashSet with from both tables HashSets with only
   * values, present in two sets.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {HashSet}
   *          hashset
   * @return {HashSet}
   *
   * @playground
   * var HashSet = require("javascript-collections").HashSet;
   *
   * var hashset01 = new HashSet();
   * var hashset02 = new HashSet();
   *
   * hashset01.add(1);
   * hashset01.add(2);
   *
   * hashset02.add(2);
   * hashset02.add(4);
   *
   * var intersect = hashset01.intersect(hashset02);
   *
   * intersect.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  intersect : {
    value : function (hashset) {
      if (hashset instanceof HashSet) {
        var scope = this;
        var intersect = new HashSet();

        scope.keys().forEach(function (key) {
          if (hashset.containsKey(key)) {
            intersect.add(scope._dataStore[key]);
          }
        });

        return intersect;
      }

      throw 'IncompatibleObjectException';
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * The except returns new HashSet with from both tables HashSets without
   * values, present in second set.
   *
   * @method
   * @memberof HashSet.prototype
   * @param {HashSet}
   *          hashset
   * @return {HashSet}
   *
   * @playground
   * var HashSet = require("javascript-collections").HashSet
   *
   * var hashset01 = new HashSet();
   * var hashset02 = new HashSet();
   *
   * hashset01.add(1);
   * hashset01.add(2);
   *
   * hashset02.add(2);
   * hashset02.add(4);
   *
   * var except = hashset01.except(hashset02);
   *
   * except.forEach(function(item, index){
   *   console.log(item);
   * });
   */
  except : {
    value : function (hashset) {
      if (hashset instanceof HashSet) {
        var scope = this;
        var except = new HashSet();

        scope.keys().forEach(function (key) {
          if (!hashset.containsKey(key)) {
            except.add(scope._dataStore[key]);
          }
        });

        return except;
      }

      throw 'IncompatibleObjectException';
    },
    enumerable : false,
    configurable : false,
    writable : false,
  },

  /**
   * @inheritdoc
   * @memberof HashSet.prototype
   */
  length : {
    get : function () {
      return this._size;
    },
    configurable : false,
  },

  /**
   * @inheritdoc
   * @memberof HashSet.prototype
   */
  empty : {
    get : function () {
      return this._size == 0;
    },
    configurable : false,
  },

  /**
   * @inheritdoc
   * @method
   * @memberof HashSet.prototype
   */
  clear : {
    value : function () {
      this._dataStore = {};
      this._size = 0;
      this._keys = [];
      this._values = [];
    },
    configurable : false,
  },
});

module.exports = HashSet;
<|endoftext|>


<commit_before>/*
 * NOTICE: Most of this code is from grunt-contrib-less
 * but it has been modified to concat the LESS
 * files first, then compile them into a CSS
 * file. This plugin allows for "requiring" LESS files
 * and also for easily building out individual components.
 *
 * grunt-contrib-less
 * http://gruntjs.com/
 * Copyright (c) 2012 Tyler Kellen, contributors
 * Licensed under the MIT license.
 *
 * assemble-less
 * http://assemble.github.com/assemble-less
 * Copyright (c) 2013 Brian Woodward, contributors
 * Licensed under the MIT license.
 *
 */

module.exports = function(grunt) {

'use strict';

  var path    = require('path');
  var fs      = require('fs');
  var util    = require('util');
  var less    = false;

  // var comment = require('./lib/comment').init(grunt);

  var lessOptions = {
    parse: [
      'paths',
      'filename',
      'optimization',
      'processImports',
      'dumpLineNumbers',
      'strictImports'
    ],
    render: [
      'silent',
      'verbose',
      'compress',
      'yuicompress',
      'strictMaths',  // enforce maths within parenthesis
      'strictUnits',  // enforce correct units
      'ieCompat'      // enforce IE compatibility (IE8 data-uri)
    ]
  };

  grunt.config.set('bootstrap.base', '<%= less.options.libs %>');

  grunt.registerMultiTask('less', 'Compile LESS to CSS using underscore and JSON.', function() {
    var done = this.async();
    grunt.verbose.writeln(util.inspect(this.files, 10, null));

    var options = this.options({
      banner: '',
      libs: './src/bootstrap',
      version: './test/versions/1.3.3', // 'less-ref-test'
      globals: [],
      concat: true,
      process: false,
      compress: false,
      processImports: true,
      stripComments: false,
      strictMaths: false,
      strictUnits: false
    });

    // Normalize boolean options that accept options objects.
    // if (options.stripComments === true) { options.stripComments = {}; }
    if (options.process === true) { options.process = {}; }

    // Process banner
    var banner = grunt.template.process(options.banner);

    // TODO: Extend default options with options from specified lessrc file
    // if (options.lessrc) {
    //   options = grunt.util._.extend(options, grunt.file.readJSON(options.lessrc));
    // }

    grunt.verbose.writeln('loading less from ' + options.version);
    try {
      less = require(options.version);
    } catch (err) {
      var lessPath = path.join(process.cwd(), options.version);
      grunt.verbose.writeln('lessPath: ', lessPath);
      less = require(lessPath);
      grunt.log.success('\nRunning Less.js v', path.basename(options.version) + '\n');
    }
    grunt.verbose.writeln('less loaded');

    grunt.util.async.forEachSeries(this.files, function(f, nextFileObj) {
      var destFile = f.dest;

      var files = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
        // Process files as templates if requested.
        var src;
        if (options.process) {
          src = grunt.template.process(src, options.process);
        }
      });

      // No src files, goto next target. Warn would have been issued above.
      if (files.length === 0) {
        nextFileObj();
      }

      var compiled = [];
      var dependencies = [];
      var srcCode = [];

      // Compile multiple concatenated LESS files.
      var concatCompile = function(file, next) {
        grunt.log.writeln('Gathering less files: ' + file.magenta);
        grunt.util.async.concatSeries(options.globals, function(file, next) {
          if(grunt.util._.contains(dependencies, file) === false) {
            srcCode.push(grunt.file.read(file));
            dependencies.push(file);
          }
          next(null);
        }, function() {});
        srcCode.push(grunt.file.read(file));
        next(null);

      };

      // Render multiple concatenated LESS files.
      var concatRender = function() {
        var lessCode = banner + srcCode.join(grunt.util.normalizelf(grunt.util.linefeed));

        grunt.log.writeln('Compiling less files...'.grey);
        compileLess(destFile, lessCode, options, function(css, err) {
          if(!err) {
            grunt.file.write(destFile, css);
            grunt.log.writeln('File ' + destFile.cyan + ' created.');
            nextFileObj();
          } else {
            nextFileObj(false);
          }
        });
      };

      // Compile individual LESS files.
      var singleCompile = function(file, next) {

        if(fs.existsSync(destFile)) {
          var dirStats = fs.statSync(destFile);
          if(dirStats.isDirectory() === false) {
            grunt.log.warn('Destination must be a directory when compiling to single css files.');
            nextFileObj(false);
          }
        }

        var singleSrcCode = [];
        grunt.util.async.concatSeries(options.globals, function(file, next) {
          singleSrcCode.push(grunt.file.read(file));
          next(null);
        }, function() {});

        singleSrcCode.push(grunt.file.read(file));

        singleSrcCode = banner + singleSrcCode.join(grunt.util.normalizelf(grunt.util.linefeed));

        compileLess(file, singleSrcCode, options, function(css, err) {
          if(!err) {
            // write the file out directly
            var singleDestFile = path.join(destFile, path.basename(file, path.extname(file))) + '.css';
            grunt.file.write(singleDestFile, css);
            grunt.log.ok('File ' + singleDestFile.cyan + ' created.' + ' ok '.green);
            next(null);
          } else {
            nextFileObj(false);
          }
        });

      };

      // Render individual LESS files.
      var singleRender = function() {
        nextFileObj();
      };

      if(options.concat) {
        grunt.util.async.concatSeries(files, concatCompile, concatRender);
      } else {
        grunt.util.async.concatSeries(files, singleCompile, singleRender);
      }

    }, done);
  });

  var compileLess = function(filename, srcCode, options, callback) {
    options = grunt.util._.extend({filename: filename}, options);

    options.paths = options.paths || [path.dirname(filename)];

    var css;

    // LESS Parser (parseCopyProperties)
    var parser = new less.Parser(grunt.util._.pick(options, lessOptions.parse));

    grunt.verbose.writeln('before parse');
    parser.parse(srcCode, function(parse_err, tree) {
      if (parse_err) {
        lessError(parse_err);
        callback('',true);
      }

      try {
        grunt.verbose.writeln('parsed...');
        // LESS (evalCopyProperties)
        css = tree.toCSS(grunt.util._.pick(options, lessOptions.render));
        grunt.verbose.writeln('rendered...');
        callback(css, null);
      } catch (e) {
        lessError(e);
        callback(css, true);
      }
    });
  };

  var formatLessError = function(e) {
    var pos = '[' + 'L' + e.line + ':' + ('C' + e.column) + ']';
    return e.filename + ': ' + pos + ' ' + e.message;
  };

  var lessError = function(e) {
    var message = less.formatError ? less.formatError(e) : formatLessError(e);

    grunt.log.error(message);
    grunt.fail.warn('Error compiling LESS.');
  };
};<commit_msg>renamed "libs" option to "modules"<commit_after>/*
 * NOTICE: Most of this code is from grunt-contrib-less
 * but it has been modified to concat the LESS
 * files first, then compile them into a CSS
 * file. This plugin allows for "requiring" LESS files
 * and also for easily building out individual components.
 *
 * grunt-contrib-less
 * http://gruntjs.com/
 * Copyright (c) 2012 Tyler Kellen, contributors
 * Licensed under the MIT license.
 *
 * assemble-less
 * http://assemble.github.com/assemble-less
 * Copyright (c) 2013 Brian Woodward, contributors
 * Licensed under the MIT license.
 *
 */

module.exports = function(grunt) {

  var fs      = require('graceful-fs');
  var path    = require('path');
  var util    = require('util');
  var _       = grunt.util._;
  var less    = false;

  var lessOptions = {
    parse: [
      'paths',
      'filename',
      'optimization',
      'processImports',
      'dumpLineNumbers',
      'strictImports'
    ],
    render: [
      'silent',
      'verbose',
      'compress',
      'yuicompress',
      'strictMaths',
      'strictUnits',
      'ieCompat'
    ]
  };

  grunt.registerMultiTask('less', 'Compile LESS to CSS using underscore and JSON.', function() {
    var done = this.async();

    // Default options.
    var options = this.options({
      version: 'less', // 'less-ref-test'
      modules: [],
      banner: '',
      globals: [],
      concat: true,
      process: false,
      compress: false,
      processImports: true,
      strictMaths: false,
      strictUnits: false
    });

    // Load less version specified in options, else load default
    grunt.verbose.writeln('Loading less from ' + options.version);
    try {
      less = require(options.version);
    } catch (err) {
      var lessPath = path.join(process.cwd(), options.version);
      grunt.verbose.writeln('lessPath: ', lessPath);
      less = require(lessPath);
      grunt.log.success('\nRunning Less.js v', path.basename(options.version) + '\n');
    }
    grunt.verbose.writeln('Less loaded');

    // Normalize boolean options that accept options objects.
    if (options.process === true) { options.process = {}; }

    // Process banner
    var banner = grunt.template.process(options.banner);

    grunt.util.async.forEachSeries(this.files, function(f, nextFileObj) {
      var destFile = f.dest;

      var files = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files.
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      });

      // No src files, goto next target.
      // Warn would have been issued above.
      if (files.length === 0) {
        nextFileObj();
      }

      var compiled = [];
      var dependencies = [];
      var srcCode = [];

      // Compile multiple concatenated LESS files.
      var concatCompile = function(file, next) {
        grunt.log.writeln('Compiling: ' + file.magenta);
        grunt.util.async.concatSeries(options.globals, function(file, next) {
          if(grunt.util._.contains(dependencies, file) === false) {
            srcCode.push(grunt.file.read(file));
            dependencies.push(file);
          }
          next(null);
        }, function() {});
        srcCode.push(grunt.file.read(file));
        next(null);
      };

      // Render multiple concatenated LESS files.
      var concatRender = function() {
        var lessCode = banner + srcCode.join(grunt.util.normalizelf(grunt.util.linefeed));
        if (options.process) {
           lessCode = grunt.template.process(lessCode, options.process);
        }
        grunt.log.success('Concatenated and compiled ' + srcCode.length + ' LESS files...');
        compileLess(destFile, lessCode, options, function(css, err) {
          if(!err) {
            grunt.file.write(destFile, css);
            grunt.log.writeln('File ' + destFile.cyan + ' created.');
            nextFileObj();
          } else {
            nextFileObj(false);
          }
        });
      };

      // Compile individual LESS files.
      var singleCompile = function(file, next) {

        if(fs.existsSync(destFile)) {
          var dirStats = fs.statSync(destFile);
          if(dirStats.isDirectory() === false) {
            grunt.log.warn('Destination must be a directory when compiling to single css files.');
            nextFileObj(false);
          }
        }
        var singleSrcCode = [];
        grunt.util.async.concatSeries(options.globals, function(file, next) {
          singleSrcCode.push(grunt.file.read(file));
          next(null);
        }, function() {});

        singleSrcCode.push(grunt.file.read(file));
        singleSrcCode = banner + singleSrcCode.join(grunt.util.normalizelf(grunt.util.linefeed));

        compileLess(file, singleSrcCode, options, function(css, err) {
          if(!err) {
            // write the file out directly
            var singleDestFile = path.join(destFile, path.basename(file, path.extname(file))) + '.css';
            grunt.file.write(singleDestFile, css);
            grunt.log.ok('File ' + singleDestFile.cyan + ' created.' + ' ok '.green);
            next(null);
          } else {
            nextFileObj(false);
          }
        });
      };

      // Render individual LESS files.
      var singleRender = function() {
        nextFileObj();
      };

      if(options.concat) {
        grunt.util.async.concatSeries(files, concatCompile, concatRender);
      } else {
        grunt.util.async.concatSeries(files, singleCompile, singleRender);
      }
    }, done);
  });

  var compileLess = function(filename, srcCode, options, callback) {
    options = grunt.util._.extend({filename: filename}, options);
    options.paths = options.paths || [path.dirname(filename)];

    var css;
    var parser = new less.Parser(grunt.util._.pick(options, lessOptions.parse));

    grunt.verbose.writeln('before parse');
    parser.parse(srcCode, function(parse_err, tree) {
      if (parse_err) {
        lessError(parse_err);
        callback('',true);
      }
      try {
        grunt.verbose.writeln('parsed...');
        css = tree.toCSS(grunt.util._.pick(options, lessOptions.render));
        grunt.verbose.writeln('rendered...');
        callback(css, null);
      } catch (e) {
        lessError(e);
        callback(css, true);
      }
    });
  };

  _.mixin({

    /* Read optional JSON from Ben Alman, https://gist.github.com/2876125 */
    readOptionalJSON: function(filepath) {
      var data = {};
      try {
        data = grunt.file.readJSON(filepath);
      } catch (e) {}
      return data;
    },
    /* Function from assemble https://github.com/assemble/assemble */
    mergeOptionsArrays: function(target, name) {
      var globalArray = grunt.config(['lessrc', 'options', name]) || [];
      var targetArray = grunt.config(['lessrc', target, 'options', name]) || [];
      return _.union(globalArray, targetArray);
    }
  });

  var formatLessError = function(e) {
    var pos = '[' + 'L' + e.line + ':' + ('C' + e.column) + ']';
    return e.filename + ': ' + pos + ' ' + e.message;
  };

  var lessError = function(e) {
    var message = less.formatError ? less.formatError(e) : formatLessError(e);

    grunt.log.error(message);
    grunt.fail.warn('Error compiling LESS.');
  };
};<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import Sector from './Sector'
import InnerCircle from './InnerCircle'

class Menu extends Component {

  constructor(props) {
    super(props)

    this.state = {
      hoveredItemIndex: null
    }
    this.updateHovered = this.updateHovered.bind(this)
  }

  updateHovered(index){
    if(index !== this.state.hoveredItemIndex)
      return this.setState({ hoveredItemIndex: index })

    this.setState({ hoveredItemIndex: null })
  }

  getItems(diameter, items, hoveredIndex) {
    const north = -90
    const angle = (1 / items.length) * 360
    const radius = diameter / 2

    return items.map((item, index) => {
      const B = (angle * index) + north

      return (
        <Sector
          key={ index }
          index={ index }
          item={ item }
          isHovered={ index === hoveredIndex }
          onHoverChange={ this.updateHovered }
          parameters={{
            radius: radius,
            B: B,
            C: B + angle
          }}
        />
      )
    })
  }

  getInnerCircle(diameter, item){
    return (
      <InnerCircle
        item={ item }
        outerRadius={ diameter / 2 }
      />
    )
  }

  render() {
    const { diameter, items } = this.props
    const { hoveredItemIndex } = this.state

    return (
      <svg xmlns="http://www.w3.org/2000/svg" width={ diameter } height={ diameter } preserveAspectRatio="xMidYMid meet">
        { this.getItems(diameter, items, hoveredItemIndex) }
        { this.getInnerCircle(diameter, items[hoveredItemIndex]) }
      </svg>
    )
  }
}

Menu.propTypes = {
  items: PropTypes.shape({
    action: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.func,
    ]).isRequired,
    image: PropTypes.string,
    title: PropTypes.string,
  }),
  diameter: PropTypes.number.isRequired,
}

export default Menu
<commit_msg>fixed incorrect proptype<commit_after>import React, { Component, PropTypes } from 'react'
import Sector from './Sector'
import InnerCircle from './InnerCircle'

class Menu extends Component {

  constructor(props) {
    super(props)

    this.state = {
      hoveredItemIndex: null
    }
    this.updateHovered = this.updateHovered.bind(this)
  }

  updateHovered(index){
    if(index !== this.state.hoveredItemIndex)
      return this.setState({ hoveredItemIndex: index })

    this.setState({ hoveredItemIndex: null })
  }

  getItems(diameter, items, hoveredIndex) {
    const north = -90
    const angle = (1 / items.length) * 360
    const radius = diameter / 2

    return items.map((item, index) => {
      const B = (angle * index) + north

      return (
        <Sector
          key={ index }
          index={ index }
          item={ item }
          isHovered={ index === hoveredIndex }
          onHoverChange={ this.updateHovered }
          parameters={{
            radius: radius,
            B: B,
            C: B + angle
          }}
        />
      )
    })
  }

  getInnerCircle(diameter, item){
    return (
      <InnerCircle
        item={ item }
        outerRadius={ diameter / 2 }
      />
    )
  }

  render() {
    const { diameter, items } = this.props
    const { hoveredItemIndex } = this.state

    return (
      <svg xmlns="http://www.w3.org/2000/svg" width={ diameter } height={ diameter } preserveAspectRatio="xMidYMid meet">
        { this.getItems(diameter, items, hoveredItemIndex) }
        { this.getInnerCircle(diameter, items[hoveredItemIndex]) }
      </svg>
    )
  }
}

Menu.propTypes = {
  items: PropTypes.arrayOf(PropTypes.shape({
    action: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.func,
    ]).isRequired,
    image: PropTypes.string,
    title: PropTypes.string,
  })).isRequired,
  diameter: PropTypes.number.isRequired,
}

export default Menu
<|endoftext|>


<commit_before>var myModule = angular.module("counterapp", []);

function pad(d) {
    return (d < 10) ? '0' + d.toString() : d.toString();
}

function getArrayIndexForKey(arr, key, val){
    for(var i = 0; i < arr.length; i++){
	if(arr[i][key] == val)
	return i;
    }
    return -1;
}

myModule.controller("counterCtrl",['$scope','$timeout', function($scope,$timeout){
    $scope.seconds = 0;
    $scope.hours = 0;
    $scope.minutes = 0;
    //Format time
    while ($scope.seconds >= 3600) {
	$scope.seconds = $scope.seconds - 3600;
	$scope.hours++;
    }

    while ($scope.seconds >= 60) {
	$scope.seconds = $scope.seconds - 60;
	$scope.minutes++;
    }

    var stopped;
    var savetimer;
    $scope.firsttime = true;
    // These are the functions used when clicking the corresponding
    // buttons displayed on each job

    $scope.start = function() {
	$scope.StartDisabled = true;
	if ($scope.firsttime == true) {
	    $scope.session.intervals[0].start = Date.now();
	    $scope.session.intervals[0].stop = 'false';
	    $scope.firsttime = false;
	    $scope.savesession('Session');
	    console.log('first time run for ' + $scope.job.name);
	}
	stopped = $timeout(function() {
	    $scope.seconds++;
	    if ($scope.seconds == 60) { $scope.minutes++; $scope.seconds = 0; }
	    if ($scope.minutes == 60) { $scope.hours++; $scope.minutes = 0; }
	    $scope.start();
	}, 1000);  //1000ms = 1 second
    };

    $scope.stop = function(){
	//Stops the current timer
	$timeout.cancel(stopped);
	$scope.ResumeDisabled = false;
	$scope.intervalstop();
	$scope.savesession('Session');
	//Add a new start interval
    }
    $scope.resume = function(){
	$scope.session.intervals.push({'start': Date.now(),'stop': 'false'});
	$scope.savesession('Session');
	$scope.start();
    }
    $scope.reset = function(){
	$scope.StartDisabled = false;
	$scope.clearsession();
	$timeout.cancel(stopped);
	$scope.cleartime();
    }

    $scope.log = function(){
	$timeout.cancel(stopped);
	$scope.StartDisabled = false;
	$scope.intervalstop();
	$scope.savesession('Session');
	$scope.savesession('Archive');
    }

    $scope.removejob = function(){
	$scope.clearsession();
	$timeout.cancel(stopped);
	$scope.cleartime();
	localStorage.removeItem('Session_' + $scope.job.id);
	var indextoremove = getArrayIndexForKey($scope.jobs, "id", $scope.job.id);
	$scope.jobs.splice(indextoremove, 1)
    }

    // These functions are used internally to create more readable,
    // aswell as modular code.

    $scope.savesession = function(name){
	localStorage.setItem(name + '_' + $scope.job.id, JSON.stringify($scope.session));
    }

    $scope.intervalstop = function(){
	$scope.session.intervals[$scope.session.intervals.length - 1].stop = Date.now();
    }

    $scope.clearsession = function(){
	$scope.session =
	    {'intervals': [
		{'start': Date.now(),
		 'stop' : 'false'}
	    ],
	    'duration': 0
	    }
    }

    $scope.cleartime = function(){
	$scope.seconds = 0;
	$scope.minutes = 0;
	$scope.hours = 0;
	$scope.tDur = 0;
    }

}]);

// The following is run when the the job list is first created

function JobsListCtrl ($scope, $timeout) {

localStorage.clear();

    $scope.session =
	{'intervals': [{start : '', stop: ''}],
	 'duration': 0 };

    //Store in local storage with job-id
    //Check Local Storage
    var storedJobs = localStorage.getItem('jobs');
    if (storedJobs == (null)) {
	//No local storage load test data
	$scope.jobs = [
	    { 'id' : '2X0XAA', 'name' : 'Working on the MOM app' },
	    { 'id' : 'AH49SJ', 'name' : 'Creating logo'}
	];
	// If person clicks Start, jobs loads to active session
    }
    else{
	// load stored jobs
        $scope.jobs = JSON.parse(storedJobs);
    }

    runCounter = function() {
	$scope.gcount += 1;
	//GLOBAL TIMER TO SAVE ALL SESSIONS
	$timeout(runCounter, 5000);
    };

    runCounter();
    $scope.gcount = 0;

}
<commit_msg>updated counter functions<commit_after>var myModule = angular.module("counterapp", []);

function pad(d) {
    return (d < 10) ? '0' + d.toString() : d.toString();
}

function getArrayIndexForKey(arr, key, val){
    for(var i = 0; i < arr.length; i++){
	if(arr[i][key] == val)
	return i;
    }
    return -1;
}

myModule.controller("counterCtrl",['$scope','$timeout', function($scope,$timeout){
    $scope.seconds = 0;
    $scope.hours = 0;
    $scope.minutes = 0;
    //Format time
    while ($scope.seconds >= 3600) {
	$scope.seconds = $scope.seconds - 3600;
	$scope.hours++;
    }

    while ($scope.seconds >= 60) {
	$scope.seconds = $scope.seconds - 60;
	$scope.minutes++;
    }

    var stopped;
    var savetimer;
    $scope.firsttime = true;
    // These are the functions used when clicking the corresponding
    // buttons displayed on each job

    $scope.start = function() {
	$scope.StartDisabled = true;
	if ($scope.firsttime == true) {
	    $scope.session.intervals[0].start = Date.now();
	    $scope.session.intervals[0].stop = 'false';
	    $scope.firsttime = false;
	    $scope.savesession('Session');
	    console.log('first time run for ' + $scope.job.name);
	}
	// THIS NEEDS TO BE SEPERATE FROM START
	stopped = $timeout(function() {
	    $scope.seconds++;
	    if ($scope.seconds == 60) { $scope.minutes++; $scope.seconds = 0; }
	    if ($scope.minutes == 60) { $scope.hours++; $scope.minutes = 0; }
	    $scope.start();
	}, 1000);  //1000ms = 1 second
	// THAT WAY BUTTONS CAN BE SEPERATE FROM THE TIMER

    };

    $scope.stop = function(){
	//Stops the current timer
	$timeout.cancel(stopped);
	$scope.ResumeDisabled = false;
	$scope.intervalstop();
	$scope.savesession('Session');
	//Add a new start interval
    }
    $scope.resume = function(){
	$scope.session.intervals.push({'start': Date.now(),'stop': 'false'});
	$scope.savesession('Session');
	$scope.start();
    }
    $scope.reset = function(){
	$scope.StartDisabled = false;
	$scope.clearsession();
	$timeout.cancel(stopped);
	$scope.cleartime();
    }

    $scope.log = function(){
	$timeout.cancel(stopped);
	$scope.StartDisabled = false;
	$scope.intervalstop();
	$scope.savesession('Session');
	$scope.savesession('Archive');
    }

    $scope.removejob = function(){
	$scope.clearsession();
	$timeout.cancel(stopped);
	$scope.cleartime();
	localStorage.removeItem('Session_' + $scope.job.id);
	var indextoremove = getArrayIndexForKey($scope.jobs, "id", $scope.job.id);
	$scope.jobs.splice(indextoremove, 1)
    }

    // These functions are used internally to create more readable,
    // aswell as modular code.

    $scope.savesession = function(name){
	localStorage.setItem(name + '_' + $scope.job.id, JSON.stringify($scope.session));
    }

    $scope.intervalstop = function(){
	$scope.session.intervals[$scope.session.intervals.length - 1].stop = Date.now();
    }

    $scope.clearsession = function(){
	$scope.session =
	    {'intervals': [
		{'start': Date.now(),
		 'stop' : 'false'}
	    ],
	    'duration': 0
	    }
    }

    $scope.cleartime = function(){
	$scope.seconds = 0;
	$scope.minutes = 0;
	$scope.hours = 0;
	$scope.tDur = 0;
    }

}]);

// The following is run when the the job list is first created

function JobsListCtrl ($scope, $timeout) {

localStorage.clear();

    $scope.session =
	{'intervals': [{start : '', stop: ''}],
	 'duration': 0 };

    //Store in local storage with job-id
    //Check Local Storage
    var storedJobs = localStorage.getItem('jobs');
    if (storedJobs == (null)) {
	//No local storage load test data
	$scope.jobs = [
	    { 'id' : '2X0XAA', 'name' : 'Working on the MOM app' },
	    { 'id' : 'AH49SJ', 'name' : 'Creating logo'}
	];
	// If person clicks Start, jobs loads to active session
    }
    else{
	// load stored jobs
        $scope.jobs = JSON.parse(storedJobs);
    }

    runCounter = function() {
	$scope.gcount += 1;
	//GLOBAL TIMER TO SAVE ALL SESSIONS
	$timeout(runCounter, 5000);
    };

    runCounter();
    $scope.gcount = 0;

}
<|endoftext|>


<commit_before>/*
** Manual Reconciliation
*/

function addToManualQueue(entity) {
    var wasEmpty = isObjectEmpty(manualQueue);
    var wasSingleton = getSecondValue(manualQueue) === undefined;
    manualQueue[entity["/rec_ui/id"]] = entity;
    if (wasEmpty)
        manualReconcile();
    else if (wasSingleton)
        renderReconChoices(entity)
    updateUnreconciledCount();
}

function manualReconcile() {
    if ($(".manualReconChoices:visible").length === 0) {
        var val = getFirstValue(manualQueue);
        if(val != undefined) {
            displayReconChoices(val["/rec_ui/id"])
            renderReconChoices(getSecondValue(manualQueue)); //render-ahead the next one
        }
        else{
            $(".manualQueueEmpty").show();
            $(".manualReconciliation").hide();
        }
    }
}

function displayReconChoices(entityID) {
    var entity = entities[entityID];
    if (entity === undefined) return;
    $(".manualQueueEmpty").hide();
    $(".manualReconciliation").show();
    if (! $("#manualReconcile" + entityID)[0])
        renderReconChoices(entity);
    $(".manualReconChoices:visible").remove();
    $("#manualReconcile" + entityID).show();
}

function renderReconChoices(entity) {
    if (entity == undefined) return;
    var template = $("#manualReconcileTemplate").clone();
    template[0].id = "manualReconcile" + entity['/rec_ui/id'];
    var headers = entity["/rec_ui/headers"];
    var mqlProps = entity["/rec_ui/mql_props"];

    var currentRecord = $(".recordVals",template);
    for(var i = 0; i < headers.length; i++) {
        currentRecord.append(node("label", getPropName(headers[i]) + ":", {"for":idToClass(headers[i])}));
        currentRecord.append(node("div", {"class":"propertyGroup"}).append(displayValue(entity.getChainedProperty(headers[i]))));
    }

    var tableHeader = $(".reconciliationCandidates table thead", template).empty();
    var columnHeaders = ["","Image","Name","Type"].concat($.map(mqlProps,getPropName)).concat(["Score"]);
    for (var i = 0; i < columnHeaders.length; i++)
        tableHeader.append(node("th",columnHeaders[i],{"class":"bottomHeader"}));

    var tableBody = $(".reconciliationCandidates table tbody", template).empty();
    for (var i = 0; i < entity.reconResults.length; i++){
        tableBody.append(renderCandidate(entity.reconResults[i], mqlProps, entity));
        fetchMqlProps(entity.reconResults[i], entity);
    }

    function updateCandidates() {
        $('.reconciliationCandidates table tbody tr:odd', template).addClass('odd');
        $('.reconciliationCandidates table tbody tr:even', template).addClass('even');
        numCandidates = entity.reconResults.length;
    }
    updateCandidates();
    $(".find_topic", template)
        .suggest({type:entity['/type/object/type'],
                  type_strict:"should",
                  flyout:true})
        .bind("fb-select", function(e, data) {
          entity['/rec_ui/freebase_name'] = $.makeArray(data.name);
          handleReconChoice(entity, data.id);
        });
    $(".otherSelection", template).click(function() {handleReconChoice(entity, this.name)});

    $(".moreButton",template).click(function() {
        $(".loadingMoreCandidates", template).fadeIn();
        getCandidates(entity, function() {
            $(".loadingMoreCandidates", template).hide();
            if (entity.reconResults.length <= numCandidates)
                return $(".moreButton",template).fadeOut();
            for (var i = numCandidates; i < entity.reconResults.length; i++){
                var candidate = renderCandidate(entity.reconResults[i], mqlProps, entity).appendTo(tableBody);
                fetchMqlProps(entity.reconResults[i], entity);
            }
            updateCandidates();
        }, function(){;});
    });
    template.insertAfter("#manualReconcileTemplate")
}

function renderCandidate(result, mqlProps, entity) {
    var url = freebase_url + "/view/" + result['id'];
    var tableRow = node("tr", {"class":idToClass(result["id"])});

    var button = node("button", "Select",
       {"class":'manualSelection',
        "name":result.id})
    tableRow.append(node("td",button));
    button.click(function(val) {entity['/rec_ui/freebase_name'] = result.name; handleReconChoice(entity, result.id)})

    node("td",
         node("img",{src:freebase_url + "/api/trans/image_thumb/"+result['id']+"?maxwidth=100&maxheight=100"})
    ).appendTo(tableRow);

    tableRow.append(node("td",displayValue(result)));
    var displayTypes = [];
    $.each($.makeArray(result.type), function(_,typeId) {
        //types that end in /topic are uninteresting
        if (typeId.match(/\/topic$/)) return;
        displayTypes.push(freebase.makeLink(typeId));
    })
    node("td").append(wrapForOverflow(displayTypes)).appendTo(tableRow);

    mqlProps = groupProperties(mqlProps).getPropsForRows();
    for(var j = 0; j < mqlProps.length; j++)
        tableRow.append(
            node("td", node("img",{src:"resources/spinner.gif"}),
                 {"class":"replaceme "+idToClass(mqlProps[j])})
        );
    tableRow.append(node("td",result["score"]));
    return tableRow;
}

function fetchMqlProps(reconResult, entity) {
    var mqlProps = entity["/rec_ui/mql_props"];
    var query = {"id":reconResult["id"]};
    $.each(mqlProps, function(_, prop) {
        var slot = query;
        var parts = prop.split(":");
        $.each(parts.slice(0,parts.length-1), function(_, part) {
            slot[part] = slot[part] || [{optional:true}];
            slot = slot[part][0];
        });
        var lastPart = parts[parts.length-1];
        if (isValueProperty(lastPart))
            slot[lastPart] = [];
        else {
            slot[lastPart] = slot[lastPart] || [{}];
            var queryObj = slot[lastPart][0];
            queryObj['name'] = null;
            queryObj['id'] = null;
            queryObj['optional'] = true;
        }

    })
    var envelope = {query:query};
    function handler(results) {
        fillInMQLProps(entity, results);
        //don't show annoying loading symbols indefinitely if there's an error
        $("#manualReconcile" + entity["/rec_ui/id"] + " .replaceme").empty();
    }
    freebase.mqlRead(envelope,handler);
}

function fillInMQLProps(entity, mqlResult) {
    var context = $("#manualReconcile" + entity["/rec_ui/id"]);
    if (!mqlResult || mqlResult["code"] != "/api/status/ok" || mqlResult["result"] == null) {
        error(mqlResult);
        return;
    }

    var result = mqlResult.result;
    var row = $("tr." + idToClass(result.id),context);

    for (var i = 0; i < mqlProps.length; i++) {
        var cell = $("td." + idToClass(mqlProps[i]), row).empty();
        cell.append(displayValue(getChainedProperty(result, mqlProps[i])));
        cell.removeClass("replaceme");
    }
}<commit_msg>Populate the search field with the current entity's name in manual recon<commit_after>/*
** Manual Reconciliation
*/

function addToManualQueue(entity) {
    var wasEmpty = isObjectEmpty(manualQueue);
    var wasSingleton = getSecondValue(manualQueue) === undefined;
    manualQueue[entity["/rec_ui/id"]] = entity;
    if (wasEmpty)
        manualReconcile();
    else if (wasSingleton)
        renderReconChoices(entity)
    updateUnreconciledCount();
}

function manualReconcile() {
    if ($(".manualReconChoices:visible").length === 0) {
        var val = getFirstValue(manualQueue);
        if(val != undefined) {
            displayReconChoices(val["/rec_ui/id"])
            renderReconChoices(getSecondValue(manualQueue)); //render-ahead the next one
        }
        else{
            $(".manualQueueEmpty").show();
            $(".manualReconciliation").hide();
        }
    }
}

function displayReconChoices(entityID) {
    var entity = entities[entityID];
    if (entity === undefined) return;
    $(".manualQueueEmpty").hide();
    $(".manualReconciliation").show();
    if (! $("#manualReconcile" + entityID)[0])
        renderReconChoices(entity);
    $(".manualReconChoices:visible").remove();
    $("#manualReconcile" + entityID).show();
}

function renderReconChoices(entity) {
    if (entity == undefined) return;
    var template = $("#manualReconcileTemplate").clone();
    template[0].id = "manualReconcile" + entity['/rec_ui/id'];
    var headers = entity["/rec_ui/headers"];
    var mqlProps = entity["/rec_ui/mql_props"];

    var currentRecord = $(".recordVals",template);
    for(var i = 0; i < headers.length; i++) {
        currentRecord.append(node("label", getPropName(headers[i]) + ":", {"for":idToClass(headers[i])}));
        currentRecord.append(node("div", {"class":"propertyGroup"}).append(displayValue(entity.getChainedProperty(headers[i]))));
    }

    var tableHeader = $(".reconciliationCandidates table thead", template).empty();
    var columnHeaders = ["","Image","Name","Type"].concat($.map(mqlProps,getPropName)).concat(["Score"]);
    for (var i = 0; i < columnHeaders.length; i++)
        tableHeader.append(node("th",columnHeaders[i],{"class":"bottomHeader"}));

    var tableBody = $(".reconciliationCandidates table tbody", template).empty();
    for (var i = 0; i < entity.reconResults.length; i++){
        tableBody.append(renderCandidate(entity.reconResults[i], mqlProps, entity));
        fetchMqlProps(entity.reconResults[i], entity);
    }

    function updateCandidates() {
        $('.reconciliationCandidates table tbody tr:odd', template).addClass('odd');
        $('.reconciliationCandidates table tbody tr:even', template).addClass('even');
        numCandidates = entity.reconResults.length;
    }
    updateCandidates();

    $(".find_topic")[0].value = entity['/type/object/name'];
    $(".find_topic", template)
        .suggest({type:entity['/type/object/type'],
                  type_strict:"should",
                  flyout:true})
        .bind("fb-select", function(e, data) {
          entity['/rec_ui/freebase_name'] = $.makeArray(data.name);
          handleReconChoice(entity, data.id);
        });

    $(".otherSelection", template).click(function() {handleReconChoice(entity, this.name)});

    $(".moreButton",template).click(function() {
        $(".loadingMoreCandidates", template).fadeIn();
        getCandidates(entity, function() {
            $(".loadingMoreCandidates", template).hide();
            if (entity.reconResults.length <= numCandidates)
                return $(".moreButton",template).fadeOut();
            for (var i = numCandidates; i < entity.reconResults.length; i++){
                var candidate = renderCandidate(entity.reconResults[i], mqlProps, entity).appendTo(tableBody);
                fetchMqlProps(entity.reconResults[i], entity);
            }
            updateCandidates();
        }, function(){;});
    });
    template.insertAfter("#manualReconcileTemplate")
}

function renderCandidate(result, mqlProps, entity) {
    var url = freebase_url + "/view/" + result['id'];
    var tableRow = node("tr", {"class":idToClass(result["id"])});

    var button = node("button", "Select",
       {"class":'manualSelection',
        "name":result.id})
    tableRow.append(node("td",button));
    button.click(function(val) {entity['/rec_ui/freebase_name'] = result.name; handleReconChoice(entity, result.id)})

    node("td",
         node("img",{src:freebase_url + "/api/trans/image_thumb/"+result['id']+"?maxwidth=100&maxheight=100"})
    ).appendTo(tableRow);

    tableRow.append(node("td",displayValue(result)));
    var displayTypes = [];
    $.each($.makeArray(result.type), function(_,typeId) {
        //types that end in /topic are uninteresting
        if (typeId.match(/\/topic$/)) return;
        displayTypes.push(freebase.makeLink(typeId));
    })
    node("td").append(wrapForOverflow(displayTypes)).appendTo(tableRow);

    mqlProps = groupProperties(mqlProps).getPropsForRows();
    for(var j = 0; j < mqlProps.length; j++)
        tableRow.append(
            node("td", node("img",{src:"resources/spinner.gif"}),
                 {"class":"replaceme "+idToClass(mqlProps[j])})
        );
    tableRow.append(node("td",result["score"]));
    return tableRow;
}

function fetchMqlProps(reconResult, entity) {
    var mqlProps = entity["/rec_ui/mql_props"];
    var query = {"id":reconResult["id"]};
    $.each(mqlProps, function(_, prop) {
        var slot = query;
        var parts = prop.split(":");
        $.each(parts.slice(0,parts.length-1), function(_, part) {
            slot[part] = slot[part] || [{optional:true}];
            slot = slot[part][0];
        });
        var lastPart = parts[parts.length-1];
        if (isValueProperty(lastPart))
            slot[lastPart] = [];
        else {
            slot[lastPart] = slot[lastPart] || [{}];
            var queryObj = slot[lastPart][0];
            queryObj['name'] = null;
            queryObj['id'] = null;
            queryObj['optional'] = true;
        }

    })
    var envelope = {query:query};
    function handler(results) {
        fillInMQLProps(entity, results);
        //don't show annoying loading symbols indefinitely if there's an error
        $("#manualReconcile" + entity["/rec_ui/id"] + " .replaceme").empty();
    }
    freebase.mqlRead(envelope,handler);
}

function fillInMQLProps(entity, mqlResult) {
    var context = $("#manualReconcile" + entity["/rec_ui/id"]);
    if (!mqlResult || mqlResult["code"] != "/api/status/ok" || mqlResult["result"] == null) {
        error(mqlResult);
        return;
    }

    var result = mqlResult.result;
    var row = $("tr." + idToClass(result.id),context);

    for (var i = 0; i < mqlProps.length; i++) {
        var cell = $("td." + idToClass(mqlProps[i]), row).empty();
        cell.append(displayValue(getChainedProperty(result, mqlProps[i])));
        cell.removeClass("replaceme");
    }
}<|endoftext|>


<commit_before><commit_msg>documentation<commit_after><|endoftext|>


<commit_before>function b() {
	console.log("inside b: ",myVar);
}

function a() {
	var myVar = 2;
	b();

    function c() {
        console.log("inside c:",myVar);
    }
    c();
    console.log("inside a:",myVar);

}

var myVar = 1;
a();
console.log("outside:",myVar);
c();

<commit_msg>lexical scope functions comment<commit_after>function b() {
	console.log("inside b: ",myVar);
}

function a() {
	var myVar = 2;
	b();

    function c() {
        console.log("inside c:",myVar);
    }
    c();
    console.log("inside a:",myVar);

}

var myVar = 1;
a();
console.log("outside:",myVar);
c();//fails here

<|endoftext|>


<commit_before>var
  path = require("path");

var
  _ = require("lodash"),
  gutil = require("gulp-util"),
  map = require("map-stream"),
  eslint = require("gulp-eslint");

module.exports = function (gulp, config) {
  gulp.task("lint", "Lint application- and test-code.", function (cb) {
    var success = true;

    gulp.src([
      path.join(config.frontendFullPath, "**/*.js"),
      path.join(config.root, config.spec, "**/*.js"),
      path.join(config.root, "*.js"),
      path.join(config.root, "tasks/**/*.js")
    ])
      .pipe(eslint())
      .pipe(map(function (file, output) {
        success = success && _.every(file.eslint && file.eslint.messages, function (message) {
          return message.severity !== 2;
        });
        return output(null, file);
      }))
      .pipe(eslint.format())
      .on("end", function () {
        if (!success) {
          cb(new gutil.PluginError("lint", "*** FAILED ESLINT ***"));
        }
      });
  });
};
<commit_msg>output lint success<commit_after>var
  path = require("path");

var
  _ = require("lodash"),
  gutil = require("gulp-util"),
  map = require("map-stream"),
  eslint = require("gulp-eslint");

module.exports = function (gulp, config) {
  gulp.task("lint", "Lint application- and test-code.", function (cb) {
    var success = true;

    gulp.src([
      path.join(config.frontendFullPath, "**/*.js"),
      path.join(config.root, config.spec, "**/*.js"),
      path.join(config.root, "*.js"),
      path.join(config.root, "tasks/**/*.js")
    ])
      .pipe(eslint())
      .pipe(map(function (file, output) {
        success = success && _.every(file.eslint && file.eslint.messages, function (message) {
          return message.severity !== 2;
        });
        return output(null, file);
      }))
      .pipe(eslint.format())
      .on("end", function () {
        if (success) {
          gutil.log("[lint]", "SUCCESS!");
          cb();
        } else {
          cb(new gutil.PluginError("lint", "*** FAILED ESLINT ***"));
        }
      });
  });
};
<|endoftext|>


<commit_before>// Add your components:

// export { default as VOnsActionSheet } from 'vue-onsenui/esm/components/VOnsActionSheet'
// export { default as VOnsActionSheetButton } from 'vue-onsenui/esm/components/VOnsActionSheetButton'
// export { default as VOnsAlertDialog } from 'vue-onsenui/esm/components/VOnsAlertDialog'
// export { default as VOnsAlertDialogButton } from 'vue-onsenui/esm/components/VOnsAlertDialogButton'
// export { default as VOnsBackButton } from 'vue-onsenui/esm/components/VOnsBackButton'
// export { default as VOnsBottomToolbar } from 'vue-onsenui/esm/components/VOnsBottomToolbar'
export { default as VOnsButton } from 'vue-onsenui/esm/components/VOnsButton'
// export { default as VOnsCard } from 'vue-onsenui/esm/components/VOnsCard'
// export { default as VOnsCarousel } from 'vue-onsenui/esm/components/VOnsCarousel'
// export { default as VOnsCarouselItem } from 'vue-onsenui/esm/components/VOnsCarouselItem'
// export { default as VOnsCheckbox } from 'vue-onsenui/esm/components/VOnsCheckbox'
export { default as VOnsCol } from 'vue-onsenui/esm/components/VOnsCol'
export { default as VOnsDialog } from 'vue-onsenui/esm/components/VOnsDialog'
// export { default as VOnsFab } from 'vue-onsenui/esm/components/VOnsFab'
export { default as VOnsIcon } from 'vue-onsenui/esm/components/VOnsIcon'
// export { default as VOnsInput } from 'vue-onsenui/esm/components/VOnsInput'
// export { default as VOnsLazyRepeat } from 'vue-onsenui/esm/components/VOnsLazyRepeat'
export { default as VOnsList } from 'vue-onsenui/esm/components/VOnsList'
// export { default as VOnsListHeader } from 'vue-onsenui/esm/components/VOnsListHeader'
export { default as VOnsListItem } from 'vue-onsenui/esm/components/VOnsListItem'
// export { default as VOnsListTitle } from 'vue-onsenui/esm/components/VOnsListTitle'
// export { default as VOnsModal } from 'vue-onsenui/esm/components/VOnsModal'
// export { default as VOnsNavigator } from 'vue-onsenui/esm/components/VOnsNavigator'
export { default as VOnsPage } from 'vue-onsenui/esm/components/VOnsPage'
// export { default as VOnsPopover } from 'vue-onsenui/esm/components/VOnsPopover'
// export { default as VOnsProgressBar } from 'vue-onsenui/esm/components/VOnsProgressBar'
// export { default as VOnsProgressCircular } from 'vue-onsenui/esm/components/VOnsProgressCircular'
// export { default as VOnsPullHook } from 'vue-onsenui/esm/components/VOnsPullHook'
// export { default as VOnsRadio } from 'vue-onsenui/esm/components/VOnsRadio'
// export { default as VOnsRange } from 'vue-onsenui/esm/components/VOnsRange'
// export { default as VOnsRipple } from 'vue-onsenui/esm/components/VOnsRipple'
export { default as VOnsRow } from 'vue-onsenui/esm/components/VOnsRow'
// export { default as VOnsSearchInput } from 'vue-onsenui/esm/components/VOnsSearchInput'
// export { default as VOnsSegment } from 'vue-onsenui/esm/components/VOnsSegment'
export { default as VOnsSelect } from 'vue-onsenui/esm/components/VOnsSelect'
// export { default as VOnsSpeedDial } from 'vue-onsenui/esm/components/VOnsSpeedDial'
// export { default as VOnsSpeedDialItem } from 'vue-onsenui/esm/components/VOnsSpeedDialItem'
// export { default as VOnsSplitter } from 'vue-onsenui/esm/components/VOnsSplitter'
// export { default as VOnsSplitterContent } from 'vue-onsenui/esm/components/VOnsSplitterContent'
// export { default as VOnsSplitterMask } from 'vue-onsenui/esm/components/VOnsSplitterMask'
// export { default as VOnsSplitterSide } from 'vue-onsenui/esm/components/VOnsSplitterSide'
// export { default as VOnsSwitch } from 'vue-onsenui/esm/components/VOnsSwitch'
export { default as VOnsTab } from 'vue-onsenui/esm/components/VOnsTab'
export { default as VOnsTabbar } from 'vue-onsenui/esm/components/VOnsTabbar'
export { default as VOnsToast } from 'vue-onsenui/esm/components/VOnsToast'
export { default as VOnsToolbar } from 'vue-onsenui/esm/components/VOnsToolbar'
export { default as VOnsToolbarButton } from 'vue-onsenui/esm/components/VOnsToolbarButton'
<commit_msg>Add alert components<commit_after>// Add your components:

// export { default as VOnsActionSheet } from 'vue-onsenui/esm/components/VOnsActionSheet'
// export { default as VOnsActionSheetButton } from 'vue-onsenui/esm/components/VOnsActionSheetButton'
export { default as VOnsAlertDialog } from 'vue-onsenui/esm/components/VOnsAlertDialog'
export { default as VOnsAlertDialogButton } from 'vue-onsenui/esm/components/VOnsAlertDialogButton'
// export { default as VOnsBackButton } from 'vue-onsenui/esm/components/VOnsBackButton'
// export { default as VOnsBottomToolbar } from 'vue-onsenui/esm/components/VOnsBottomToolbar'
export { default as VOnsButton } from 'vue-onsenui/esm/components/VOnsButton'
// export { default as VOnsCard } from 'vue-onsenui/esm/components/VOnsCard'
// export { default as VOnsCarousel } from 'vue-onsenui/esm/components/VOnsCarousel'
// export { default as VOnsCarouselItem } from 'vue-onsenui/esm/components/VOnsCarouselItem'
// export { default as VOnsCheckbox } from 'vue-onsenui/esm/components/VOnsCheckbox'
export { default as VOnsCol } from 'vue-onsenui/esm/components/VOnsCol'
export { default as VOnsDialog } from 'vue-onsenui/esm/components/VOnsDialog'
// export { default as VOnsFab } from 'vue-onsenui/esm/components/VOnsFab'
export { default as VOnsIcon } from 'vue-onsenui/esm/components/VOnsIcon'
// export { default as VOnsInput } from 'vue-onsenui/esm/components/VOnsInput'
// export { default as VOnsLazyRepeat } from 'vue-onsenui/esm/components/VOnsLazyRepeat'
export { default as VOnsList } from 'vue-onsenui/esm/components/VOnsList'
// export { default as VOnsListHeader } from 'vue-onsenui/esm/components/VOnsListHeader'
export { default as VOnsListItem } from 'vue-onsenui/esm/components/VOnsListItem'
// export { default as VOnsListTitle } from 'vue-onsenui/esm/components/VOnsListTitle'
// export { default as VOnsModal } from 'vue-onsenui/esm/components/VOnsModal'
// export { default as VOnsNavigator } from 'vue-onsenui/esm/components/VOnsNavigator'
export { default as VOnsPage } from 'vue-onsenui/esm/components/VOnsPage'
// export { default as VOnsPopover } from 'vue-onsenui/esm/components/VOnsPopover'
// export { default as VOnsProgressBar } from 'vue-onsenui/esm/components/VOnsProgressBar'
// export { default as VOnsProgressCircular } from 'vue-onsenui/esm/components/VOnsProgressCircular'
// export { default as VOnsPullHook } from 'vue-onsenui/esm/components/VOnsPullHook'
// export { default as VOnsRadio } from 'vue-onsenui/esm/components/VOnsRadio'
// export { default as VOnsRange } from 'vue-onsenui/esm/components/VOnsRange'
// export { default as VOnsRipple } from 'vue-onsenui/esm/components/VOnsRipple'
export { default as VOnsRow } from 'vue-onsenui/esm/components/VOnsRow'
// export { default as VOnsSearchInput } from 'vue-onsenui/esm/components/VOnsSearchInput'
// export { default as VOnsSegment } from 'vue-onsenui/esm/components/VOnsSegment'
export { default as VOnsSelect } from 'vue-onsenui/esm/components/VOnsSelect'
// export { default as VOnsSpeedDial } from 'vue-onsenui/esm/components/VOnsSpeedDial'
// export { default as VOnsSpeedDialItem } from 'vue-onsenui/esm/components/VOnsSpeedDialItem'
// export { default as VOnsSplitter } from 'vue-onsenui/esm/components/VOnsSplitter'
// export { default as VOnsSplitterContent } from 'vue-onsenui/esm/components/VOnsSplitterContent'
// export { default as VOnsSplitterMask } from 'vue-onsenui/esm/components/VOnsSplitterMask'
// export { default as VOnsSplitterSide } from 'vue-onsenui/esm/components/VOnsSplitterSide'
// export { default as VOnsSwitch } from 'vue-onsenui/esm/components/VOnsSwitch'
export { default as VOnsTab } from 'vue-onsenui/esm/components/VOnsTab'
export { default as VOnsTabbar } from 'vue-onsenui/esm/components/VOnsTabbar'
export { default as VOnsToast } from 'vue-onsenui/esm/components/VOnsToast'
export { default as VOnsToolbar } from 'vue-onsenui/esm/components/VOnsToolbar'
export { default as VOnsToolbarButton } from 'vue-onsenui/esm/components/VOnsToolbarButton'
<|endoftext|>