<commit_before>(function () {
  angular.module('mnBucketsDetailsService', [
    'mnPoolDefault',
    'mnTasksDetails',
    'mnCompaction'
  ]).factory('mnBucketsDetailsService', mnBucketsDetailsServiceFcatory);

  function mnBucketsDetailsServiceFcatory($q, $http, mnTasksDetails, mnPoolDefault, mnCompaction) {
    var mnBucketsDetailsService = {
      getBucketRamGuageConfig: getBucketRamGuageConfig,
      deleteBucket: deleteBucket,
      flushBucket: flushBucket,
      doGetDetails: doGetDetails,
      getWarmUpTasks: getWarmUpTasks,
      getGuageConfig: getGuageConfig,
      getCompactionTask: getCompactionTask
    };

    var bucketRamGuageConfig = {};
    var guageConfig = {};

    return mnBucketsDetailsService;

    function getWarmUpTasks(bucket) {
      return $q.all([
        mnTasksDetails.get(),
        mnPoolDefault.get()
      ]).then(function (resp) {
        var tasks = resp[0];
        var poolDefault = resp[0];

        return _.filter(tasks.tasks, function (task) {
          var isNeeded = task.type === 'warming_up' && task.status === 'running' && task.bucket === bucket.name;
          if (isNeeded) {
            task.hostname = _.find(poolDefault.nodes, function (node) {
              return node.otpNode === task.node;
            }).hostname;
          }
          return isNeeded;
        });
      });
    }

    function getCompactionTask(bucket) {
      return mnTasksDetails.get().then(function (tasks) {
        var rv = {};
        rv.thisBucketCompactionTask = _.find(tasks.tasks, function (task) {
          return task.type === 'bucket_compaction' && task.bucket === bucket.name;
        });
        if (rv.thisBucketCompactionTask && !!rv.thisBucketCompactionTask.cancelURI) {
          rv.disableCancel = !!mnCompaction.getStartedCompactions()[rv.thisBucketCompactionTask.cancelURI];
        } else {
          rv.disableCompact = !!(mnCompaction.getStartedCompactions()[bucket.controllers.compactAll] || rv.thisBucketCompactionTask);
        }
        return rv
      });
    }

    function getBucketRamGuageConfig(ramSummary) {
      if (!ramSummary) {
        return;
      }
      bucketRamGuageConfig.topRight = {
        name: 'Cluster quota',
        value: ramSummary.total
      };
      bucketRamGuageConfig.items = [{
        name: 'Other Buckets',
        value: ramSummary.otherBuckets,
        itemStyle: {'background-color': '#00BCE9', 'z-index': '2'},
        labelStyle: {'color': '#1878a2', 'text-align': 'left'}
      }, {
        name: 'This Bucket',
        value: ramSummary.thisAlloc,
        itemStyle: {'background-color': '#7EDB49', 'z-index': '1'},
        labelStyle: {'color': '#409f05', 'text-align': 'center'}
      }, {
        name: 'Free',
        value: ramSummary.total - ramSummary.otherBuckets - ramSummary.thisAlloc,
        itemStyle: {'background-color': '#E1E2E3'},
        labelStyle: {'color': '#444245', 'text-align': 'right'}
      }];
      bucketRamGuageConfig.markers = [];

      if (bucketRamGuageConfig.items[2].value < 0) {
        bucketRamGuageConfig.items[1].value = ramSummary.total - ramSummary.otherBuckets;
        bucketRamGuageConfig.items[2] = {
          name: 'Overcommitted',
          value: ramSummary.otherBuckets + ramSummary.thisAlloc - ramSummary.total,
          itemStyle: {'background-color': '#F40015'},
          labelStyle: {'color': '#e43a1b'}
        };
        bucketRamGuageConfig.markers.push({
          value: ramSummary.total,
          itemStyle: {'background-color': '#444245'}
        });
        bucketRamGuageConfig.markers.push({
          value: ramSummary.otherBuckets + ramSummary.thisAlloc,
          itemStyle: {'background-color': 'red'}
        });
        bucketRamGuageConfig.topLeft = {
          name: 'Total Allocated',
          value: ramSummary.otherBuckets + ramSummary.thisAlloc,
          itemStyle: {'color': '#e43a1b'}
        };
      }
      return bucketRamGuageConfig;
    }

    function getGuageConfig(total, thisBucket, otherBuckets, otherData) {
      var free = total - otherData - thisBucket - otherBuckets;

      guageConfig.topLeft = {
        name: 'Other Data',
        value: otherData
      };
      guageConfig.topRight = {
        name: 'Total Cluster Storage',
        value: total
      };
      guageConfig.items = [{
        name: null,
        value: otherData,
        itemStyle: {'background-color':'#FDC90D', 'z-index': '3'},
        labelStyle: {}
      }, {
        name: 'Other Buckets',
        value: otherBuckets,
        itemStyle: {'background-color':'#00BCE9', 'z-index': '2'},
        labelStyle: {'color':'#1878a2', 'text-align': 'left'}
      }, {
        name: 'This Bucket',
        value: thisBucket,
        itemStyle: {'background-color':'#7EDB49', 'z-index': '1'},
        labelStyle: {'color':'#409f05', 'text-align': 'center'}
      }, {
        name: 'Free',
        value: free,
        itemStyle: {'background-color':'#E1E2E3'},
        labelStyle: {'color':'#444245', 'text-align': 'right'}
      }];

      return guageConfig;
    }

    function deleteBucket(bucket) {
      return $http({
        method: 'DELETE',
        url: bucket.uri
      });
    }
    function flushBucket(bucket) {
      return $http({
        method: 'POST',
        url: bucket.controllers.flush
      });
    }
    function doGetDetails(bucket) {
      return $http({
        method: 'GET',
        url: bucket.uri + "&basic_stats=true&skipMap=true"
      }).then(function (resp) {
        return resp.data;
      });
    }
  }
})();
<commit_msg>correct poolDefault index in getWarmUpTasks response<commit_after>(function () {
  angular.module('mnBucketsDetailsService', [
    'mnPoolDefault',
    'mnTasksDetails',
    'mnCompaction'
  ]).factory('mnBucketsDetailsService', mnBucketsDetailsServiceFcatory);

  function mnBucketsDetailsServiceFcatory($q, $http, mnTasksDetails, mnPoolDefault, mnCompaction) {
    var mnBucketsDetailsService = {
      getBucketRamGuageConfig: getBucketRamGuageConfig,
      deleteBucket: deleteBucket,
      flushBucket: flushBucket,
      doGetDetails: doGetDetails,
      getWarmUpTasks: getWarmUpTasks,
      getGuageConfig: getGuageConfig,
      getCompactionTask: getCompactionTask
    };

    var bucketRamGuageConfig = {};
    var guageConfig = {};

    return mnBucketsDetailsService;

    function getWarmUpTasks(bucket) {
      return $q.all([
        mnTasksDetails.get(),
        mnPoolDefault.get()
      ]).then(function (resp) {
        var tasks = resp[0];
        var poolDefault = resp[1];

        return _.filter(tasks.tasks, function (task) {
          var isNeeded = task.type === 'warming_up' && task.status === 'running' && task.bucket === bucket.name;
          if (isNeeded) {
            task.hostname = _.find(poolDefault.nodes, function (node) {
              return node.otpNode === task.node;
            }).hostname;
          }
          return isNeeded;
        });
      });
    }

    function getCompactionTask(bucket) {
      return mnTasksDetails.get().then(function (tasks) {
        var rv = {};
        rv.thisBucketCompactionTask = _.find(tasks.tasks, function (task) {
          return task.type === 'bucket_compaction' && task.bucket === bucket.name;
        });
        if (rv.thisBucketCompactionTask && !!rv.thisBucketCompactionTask.cancelURI) {
          rv.disableCancel = !!mnCompaction.getStartedCompactions()[rv.thisBucketCompactionTask.cancelURI];
        } else {
          rv.disableCompact = !!(mnCompaction.getStartedCompactions()[bucket.controllers.compactAll] || rv.thisBucketCompactionTask);
        }
        return rv
      });
    }

    function getBucketRamGuageConfig(ramSummary) {
      if (!ramSummary) {
        return;
      }
      bucketRamGuageConfig.topRight = {
        name: 'Cluster quota',
        value: ramSummary.total
      };
      bucketRamGuageConfig.items = [{
        name: 'Other Buckets',
        value: ramSummary.otherBuckets,
        itemStyle: {'background-color': '#00BCE9', 'z-index': '2'},
        labelStyle: {'color': '#1878a2', 'text-align': 'left'}
      }, {
        name: 'This Bucket',
        value: ramSummary.thisAlloc,
        itemStyle: {'background-color': '#7EDB49', 'z-index': '1'},
        labelStyle: {'color': '#409f05', 'text-align': 'center'}
      }, {
        name: 'Free',
        value: ramSummary.total - ramSummary.otherBuckets - ramSummary.thisAlloc,
        itemStyle: {'background-color': '#E1E2E3'},
        labelStyle: {'color': '#444245', 'text-align': 'right'}
      }];
      bucketRamGuageConfig.markers = [];

      if (bucketRamGuageConfig.items[2].value < 0) {
        bucketRamGuageConfig.items[1].value = ramSummary.total - ramSummary.otherBuckets;
        bucketRamGuageConfig.items[2] = {
          name: 'Overcommitted',
          value: ramSummary.otherBuckets + ramSummary.thisAlloc - ramSummary.total,
          itemStyle: {'background-color': '#F40015'},
          labelStyle: {'color': '#e43a1b'}
        };
        bucketRamGuageConfig.markers.push({
          value: ramSummary.total,
          itemStyle: {'background-color': '#444245'}
        });
        bucketRamGuageConfig.markers.push({
          value: ramSummary.otherBuckets + ramSummary.thisAlloc,
          itemStyle: {'background-color': 'red'}
        });
        bucketRamGuageConfig.topLeft = {
          name: 'Total Allocated',
          value: ramSummary.otherBuckets + ramSummary.thisAlloc,
          itemStyle: {'color': '#e43a1b'}
        };
      }
      return bucketRamGuageConfig;
    }

    function getGuageConfig(total, thisBucket, otherBuckets, otherData) {
      var free = total - otherData - thisBucket - otherBuckets;

      guageConfig.topLeft = {
        name: 'Other Data',
        value: otherData
      };
      guageConfig.topRight = {
        name: 'Total Cluster Storage',
        value: total
      };
      guageConfig.items = [{
        name: null,
        value: otherData,
        itemStyle: {'background-color':'#FDC90D', 'z-index': '3'},
        labelStyle: {}
      }, {
        name: 'Other Buckets',
        value: otherBuckets,
        itemStyle: {'background-color':'#00BCE9', 'z-index': '2'},
        labelStyle: {'color':'#1878a2', 'text-align': 'left'}
      }, {
        name: 'This Bucket',
        value: thisBucket,
        itemStyle: {'background-color':'#7EDB49', 'z-index': '1'},
        labelStyle: {'color':'#409f05', 'text-align': 'center'}
      }, {
        name: 'Free',
        value: free,
        itemStyle: {'background-color':'#E1E2E3'},
        labelStyle: {'color':'#444245', 'text-align': 'right'}
      }];

      return guageConfig;
    }

    function deleteBucket(bucket) {
      return $http({
        method: 'DELETE',
        url: bucket.uri
      });
    }
    function flushBucket(bucket) {
      return $http({
        method: 'POST',
        url: bucket.controllers.flush
      });
    }
    function doGetDetails(bucket) {
      return $http({
        method: 'GET',
        url: bucket.uri + "&basic_stats=true&skipMap=true"
      }).then(function (resp) {
        return resp.data;
      });
    }
  }
})();
<|endoftext|>


<commit_before>/**
 * Custom tap event for jQuery
 * https://github.com/mattmccloskey/tap.jquery
 * Released under the MIT license
 */
(function($)
{
	// Tap event
	$.event.special.tap = {
		enabled: true,
		setup: function()
		{
			var startEvent = {},
				endEvent = {},
				buffer = 5,	// How far the finger has to move before it's no longer a tap
				touchStarted = false,
				touchMoved = false,
				wasTouched = false;
			$(this).on({
				'touchstart.tapevents': function(e)
				{
					touchStarted = true;
					touchMoved = false;
					wasTouched = true;
					startEvent.x = e.originalEvent.touches[0].pageX;
					startEvent.y = e.originalEvent.touches[0].pageY;
				},
				'touchmove.tapevents': function(e)
				{
					endEvent.x = e.originalEvent.touches[0].pageX;
					endEvent.y = e.originalEvent.touches[0].pageY;
					if(Math.abs(startEvent.x - endEvent.x) > buffer || Math.abs(startEvent.y - endEvent.y) > buffer)
					{
						touchMoved = true
					}
				},
				'touchend.tapevents': function(e)
				{
					if(touchStarted && ! touchMoved)
					{
						$(e.target).trigger('tap', e);
					}
					else
					{
						/* It was a drag or mistake, not a tap */

						// Reset wasTouched, since click won't be fired in this case
						wasTouched = false;
					}

					// reset touchStarted
					touchStarted = false;
				}
				,
				'click.tapevents.notaps': function(e) {
					// Check to see if there was a touch. If not, and we have touch, then we need to fire click.
					if(wasTouched === false && ('ontouchstart' in window || 'msmaxtouchpoints' in window.navigator))
					{
						$(e.target).trigger('tap', e);
					}

					// Reset wasTouched
					wasTouched = false;
				}
			});
		},

		teardown: function()
		{
			return $(this).off('.tapevents');
		}
	};

	// Convert clicks to taps
	var isTouch = 'ontouchstart' in window || 'msmaxtouchpoints' in window.navigator;

	if(isTouch && (typeof convertClicksToTaps == "undefined" || convertClicksToTaps !== false))
	{
		var onFunc = $.fn.on,
			offFunc = $.fn.off,
			replaceClickWithTap = function()
			{
				if(typeof arguments[0] === 'string' && arguments[0].slice(0, 5) === 'click' && arguments[0].indexOf('notaps') == -1)
				{
					arguments[0] = arguments[0].replace('click', 'tap');
				}
				return arguments;
			};

		$.fn.on = function()
		{
			// Since we're replacing click with tap, click will still fire by default, causing href="#" to modify the URL bar.
			// To prevent this, add preventDefault on click event.
			if(typeof arguments[0] === 'string' && arguments[0].slice(0, 5) === 'click' && arguments[0].indexOf('notaps') == -1)
			{
				var args = Array.prototype.slice.call(arguments);
					i = 0, l = args.length;
				for (i; i < l; i++)
				{
					if(typeof args[i] === "function")
					{
						args[i] = function(e)
						{
							if(e.currentTarget.tagName.toLowerCase() === 'a' && e.currentTarget.getAttribute('href'))
							{
								e.preventDefault();
							}
						};
						break;
					}
				}
				args[0] = 'click.tapreplaced';
				onFunc.apply(this, args);
			}
			return onFunc.apply(this, replaceClickWithTap.apply(this, arguments));
		};

		$.fn.off = function()
		{
			return offFunc.apply(this, replaceClickWithTap.apply(this, arguments));
		};
	}

})(jQuery);
<commit_msg>Update comments and var names<commit_after>/**
 * Custom tap event for jQuery
 * https://github.com/mattmccloskey/tap.jquery
 * Released under the MIT license
 */
(function($)
{
	// Convert clicks to taps
	var hasTouch = 'ontouchstart' in window || 'msmaxtouchpoints' in window.navigator;

	// Tap event
	$.event.special.tap = {
		enabled: true,
		setup: function()
		{
			var startEvent = {},
				endEvent = {},
				buffer = 5,	// How far the finger has to move before it's no longer a tap
				touchStarted = false,
				touchMoved = false,
				wasTouched = false;
			$(this).on({
				'touchstart.tapevents': function(e)
				{
					touchStarted = true;
					touchMoved = false;
					wasTouched = true;
					startEvent.x = e.originalEvent.touches[0].pageX;
					startEvent.y = e.originalEvent.touches[0].pageY;
				},
				'touchmove.tapevents': function(e)
				{
					endEvent.x = e.originalEvent.touches[0].pageX;
					endEvent.y = e.originalEvent.touches[0].pageY;
					if(Math.abs(startEvent.x - endEvent.x) > buffer || Math.abs(startEvent.y - endEvent.y) > buffer)
					{
						touchMoved = true
					}
				},
				'touchend.tapevents': function(e)
				{
					if(touchStarted && ! touchMoved)
					{
						$(e.target).trigger('tap', e);
					}
					else
					{
						/* It was a drag or mistake, not a tap */

						// Reset wasTouched, since click won't be fired in this case
						wasTouched = false;
					}

					// reset touchStarted
					touchStarted = false;
				}
				,
				'click.tapevents.notaps': function(e) {
					// Check to see if there was a touch.
					// If there wasn't a touch, but we have touch ability, there must be mouse input too so we need to fire on click
					if(wasTouched === false && hasTouch)
					{
						$(e.target).trigger('tap', e);
					}

					// Reset wasTouched
					wasTouched = false;
				}
			});
		},

		teardown: function()
		{
			return $(this).off('.tapevents');
		}
	};

	if(hasTouch && (typeof convertClicksToTaps == "undefined" || convertClicksToTaps !== false))
	{
		var onFunc = $.fn.on,
			offFunc = $.fn.off,
			replaceClickWithTap = function()
			{
				if(typeof arguments[0] === 'string' && arguments[0].slice(0, 5) === 'click' && arguments[0].indexOf('notaps') == -1)
				{
					arguments[0] = arguments[0].replace('click', 'tap');
				}
				return arguments;
			};

		$.fn.on = function()
		{
			// Since we're replacing click with tap, click will still fire by default, causing href="#" to modify the URL bar.
			// To prevent this, add preventDefault on click event.
			if(typeof arguments[0] === 'string' && arguments[0].slice(0, 5) === 'click' && arguments[0].indexOf('notaps') == -1)
			{
				var args = Array.prototype.slice.call(arguments);
					i = 0, l = args.length;
				for (i; i < l; i++)
				{
					if(typeof args[i] === "function")
					{
						args[i] = function(e)
						{
							if(e.currentTarget.tagName.toLowerCase() === 'a' && e.currentTarget.getAttribute('href'))
							{
								e.preventDefault();
							}
						};
						break;
					}
				}
				args[0] = 'click.tapreplaced';
				onFunc.apply(this, args);
			}
			return onFunc.apply(this, replaceClickWithTap.apply(this, arguments));
		};

		$.fn.off = function()
		{
			return offFunc.apply(this, replaceClickWithTap.apply(this, arguments));
		};
	}

})(jQuery);
<|endoftext|>


<commit_before>'use strict';
/**
 * [schema defines validation schemas for Mongo documents being inserted into db:ibu collection:ibuerrors]
 *
 *
 */
 // Mongoose connection to MongoDB
const mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ibuErrorSchema = new Schema({
  filename: {
    type: String,
    trim: true,
    unique: true
  },
  filePathXML: {
    type: String,
    unique: true
  },
  filePathIMG: {
    type: String,
    unique: true
  },
  digitalcollection: {
    type: String
  },
  IMGerrors: {
    type: Array
  },
  XMLerrors: {
    type: Array
  },
  created: {
    type: Date , default: Date.now
  }
});
//,
// validate: {
//   validator: function(v){
//     return /^[^.]+$/.test(v);

var ibuErrorDoc = mongoose.model('ibuErrorDoc', ibuErrorSchema);
// exports.default = new ibuErrorDoc();
module.exports = ibuErrorDoc;

// Some test's to show schema validator working
//testobj.filename = 'testdoc.xml';
//
//testobj.save(function(err){
//  console.log(err.errors.filename);
//});
//
//console.log(testobj);
<commit_msg>Lint Code<commit_after>
/**
 * [schema defines validation schemas for Mongo
 * documents being inserted into db:ibu collection:ibuerrors]
 *
 */
 // Mongoose connection to MongoDB
const mongoose = require('mongoose');
let Schema = mongoose.Schema;

let ibuErrorSchema = new Schema({
  filename: {
    type: String,
    trim: true,
    unique: true,
  },
  filePathXML: {
    type: String,
    unique: true,
  },
  filePathIMG: {
    type: String,
    unique: true,
  },
  digitalcollection: {
    type: String,
  },
  IMGerrors: {
    type: Array,
  },
  XMLerrors: {
    type: Array,
  },
  created: {
    type: Date, default: Date.now,
  },
});
/*,
* validate: {
*   validator: function(v){
*     return /^[^.]+$/.test(v);
*/

let ibuErrorDoc = mongoose.model('ibuErrorDoc', ibuErrorSchema);
// exports.default = new ibuErrorDoc();
module.exports = ibuErrorDoc;

// Some test's to show schema validator working
// testobj.filename = 'testdoc.xml';
//
// testobj.save(function(err){
//  console.log(err.errors.filename);
// });
//
// console.log(testobj);
<|endoftext|>


<commit_before>'use strict';
/**
 * [schema defines validation schemas for Mongo documents being inserted into db:ibu collection:ibuerrors]
 *
 *
 */
 // Mongoose connection to MongoDB
const mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ibuErrorSchema = new Schema({
  filename: {
    type: String,
    trim: true
  },
  filePathXML: {
    type: String,
    unique: true
  },
  filePathIMG: {
    type: String,
    unique: true
  },
  digitalcollection: {
    type: String
  },
  IMGerrors: {
    type: Array
  },
  XMLerrors: {
    type: Array
  },
  created: {
    type: Date , default: Date.now
  }
});
//,
// validate: {
//   validator: function(v){
//     return /^[^.]+$/.test(v);

var ibuErrorDoc = mongoose.model('ibuErrorDoc', ibuErrorSchema);
// exports.default = new ibuErrorDoc();
module.exports = ibuErrorDoc;

// Some test's to show schema validator working
//testobj.filename = 'testdoc.xml';
//
//testobj.save(function(err){
//  console.log(err.errors.filename);
//});
//
//console.log(testobj);
<commit_msg>Set filename to unique<commit_after>'use strict';
/**
 * [schema defines validation schemas for Mongo documents being inserted into db:ibu collection:ibuerrors]
 *
 *
 */
 // Mongoose connection to MongoDB
const mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ibuErrorSchema = new Schema({
  filename: {
    type: String,
    trim: true,
    unique: true
  },
  filePathXML: {
    type: String,
    unique: true
  },
  filePathIMG: {
    type: String,
    unique: true
  },
  digitalcollection: {
    type: String
  },
  IMGerrors: {
    type: Array
  },
  XMLerrors: {
    type: Array
  },
  created: {
    type: Date , default: Date.now
  }
});
//,
// validate: {
//   validator: function(v){
//     return /^[^.]+$/.test(v);

var ibuErrorDoc = mongoose.model('ibuErrorDoc', ibuErrorSchema);
// exports.default = new ibuErrorDoc();
module.exports = ibuErrorDoc;

// Some test's to show schema validator working
//testobj.filename = 'testdoc.xml';
//
//testobj.save(function(err){
//  console.log(err.errors.filename);
//});
//
//console.log(testobj);
<|endoftext|>


<commit_before>var spawn = require('child_process').spawn;

module.exports = pdc;

// pdc(src, from, to[, opt], cb)
function pdc(src, from, to, opt, cb) {
  if (typeof cb == 'undefined')
    cb = opt;

  var args = [ '-f', from, '-t', to ];

  if (typeof opt == 'object')
    args = args.concat(opt);

  var pandoc = spawn('pandoc', args);

  var result = '';
  var error = '';

  pandoc.stdout.on('data', function (data) {
    result += data;
  });
  pandoc.stderr.on('data', function (data) {
    error += data;
  });

  pandoc.on('exit', function (code) {
    if (code != 0)
      return cb(new Error('pandoc exited with code '+code+'.'));
    if (error)
      return cb(new Error(error));

    cb(null, result);
  });

  pandoc.stdin.end(src, 'utf8');
}
<commit_msg>show error instead of exit code if error info available - re: issue #1<commit_after>var spawn = require('child_process').spawn;

module.exports = pdc;

// pdc(src, from, to[, opt], cb)
function pdc(src, from, to, opt, cb) {
  if (typeof cb == 'undefined')
    cb = opt;

  var args = [ '-f', from, '-t', to ];

  if (typeof opt == 'object')
    args = args.concat(opt);

  var pandoc = spawn('pandoc', args);

  var result = '';
  var error = '';

  pandoc.stdout.on('data', function (data) {
    result += data;
  });
  pandoc.stderr.on('data', function (data) {
    error += data;
  });

  pandoc.on('exit', function (code) {
    if (code != 0 && !err)
      return cb(new Error('pandoc exited with code '+code+'.'));
    if (error)
      return cb(new Error(error));

    cb(null, result);
  });

  pandoc.stdin.end(src, 'utf8');
}
<|endoftext|>


<commit_before>/*jshint node: true */

'use strict';

var test = require('tape');

var MetaInfo = require('../index.js');

var fs = require('fs');

var path = require('path');

test("Single File MetaInfo",function(t){
  var raw = fs.readFileSync(path.join(__dirname,'test.torrent'));
  var info = MetaInfo.parse(raw);
  var torrent = info.asTorrent();

  t.test('should have values', function(t) {
    t.assert(torrent.info, 'has an info dictionary');

    t.equal(524288,torrent.info["piece length"], "info has a piece length");

    t.deepEqual(new Buffer('ubuntu-12.04-server-amd64.iso'), torrent.info.name, 'info has a name');

    t.equal(27380,torrent.info.pieces.length, 'info has pieces');

    t.equal(717533184,torrent.info.length, 'info has a length');

    t.deepEqual(new Buffer('http://torrent.ubuntu.com:6969/announce'), torrent.announce, 'has an announce');

    var announceList = [
      [new Buffer('http://torrent.ubuntu.com:6969/announce') ],
      [new Buffer('http://ipv6.torrent.ubuntu.com:6969/announce') ]
    ];
    t.deepEquals(announceList, torrent['announce-list'], 'has an announce-list');

    t.equal(1335433839,torrent['creation date'],'has a creation date');

    t.deepEqual(new Buffer('Ubuntu CD releases.ubuntu.com'), torrent.comment, "has a comment");

    t.end();
  });

  t.test('should produce the same bencoded value for test.torrent', function(t) {
    t.plan(1);
    t.deepEqual(raw, torrent.bencoded);
  });

  t.test('should produce the sha1 hash for test.torrent', function(t) {
    t.plan(1);
    t.deepEqual(new Buffer('1uzfWLWnV8Z2Xok4Eyw1TY0pb5Y=','base64'),torrent.sha1sum);
  });
});

test("Multi File MetaInfo",function(t){
  var raw = fs.readFileSync(path.join(__dirname,'multifile.torrent'));
  var info = MetaInfo.parse(raw);
  var torrent = info.asTorrent();

  t.test('should produce the same bencoded value for multifile.torrent', function(t) {
    t.plan(1);
    t.deepEqual(raw, torrent.bencoded);
  });

  t.test('should produce the sha1 hash for multifile.torrent', function(t) {
    t.plan(1);
    t.deepEqual(new Buffer('Zmlm9Z8RcPL2nWUqCIix2niugtM=','base64'),torrent.sha1sum);
  });
});<commit_msg>updated test for info hash<commit_after>/*jshint node: true */

'use strict';

var test = require('tape');

var MetaInfo = require('../index.js');

var fs = require('fs');

var path = require('path');

test("Single File MetaInfo",function(t){
  var raw = fs.readFileSync(path.join(__dirname,'test.torrent'));
  var info = MetaInfo.parse(raw);
  var torrent = info.asTorrent();

  t.test('should have values', function(t) {
    t.assert(torrent.info, 'has an info dictionary');

    t.equal(524288,torrent.info["piece length"], "info has a piece length");

    t.deepEqual(new Buffer('ubuntu-12.04-server-amd64.iso'), torrent.info.name, 'info has a name');

    t.equal(27380,torrent.info.pieces.length, 'info has pieces');

    t.equal(717533184,torrent.info.length, 'info has a length');

    t.deepEqual(new Buffer('http://torrent.ubuntu.com:6969/announce'), torrent.announce, 'has an announce');

    var announceList = [
      [new Buffer('http://torrent.ubuntu.com:6969/announce') ],
      [new Buffer('http://ipv6.torrent.ubuntu.com:6969/announce') ]
    ];
    t.deepEquals(announceList, torrent['announce-list'], 'has an announce-list');

    t.equal(1335433839,torrent['creation date'],'has a creation date');

    t.deepEqual(new Buffer('Ubuntu CD releases.ubuntu.com'), torrent.comment, "has a comment");

    t.end();
  });

  t.test('should produce the same bencoded value for test.torrent', function(t) {
    t.plan(1);
    t.deepEqual(raw, torrent.bencoded);
  });

  t.test('should produce the sha1 hash for test.torrent', function(t) {
    t.plan(1);
    t.deepEqual(new Buffer('1uzfWLWnV8Z2Xok4Eyw1TY0pb5Y=','base64'),torrent.sha1sum);
  });

  t.test('should produce the info hash for test.torrent', function(t) {
    t.plan(1);
    t.deepEqual(new Buffer('S19qPlBJSa/hB1gKZ4RDftCb5So=','base64'),torrent.infoHash);
  });
});

test("Multi File MetaInfo",function(t){
  var raw = fs.readFileSync(path.join(__dirname,'multifile.torrent'));
  var info = MetaInfo.parse(raw);
  var torrent = info.asTorrent();

  t.test('should produce the same bencoded value for multifile.torrent', function(t) {
    t.plan(1);
    t.deepEqual(raw, torrent.bencoded);
  });

  t.test('should produce the sha1 hash for multifile.torrent', function(t) {
    t.plan(1);
    t.deepEqual(new Buffer('Zmlm9Z8RcPL2nWUqCIix2niugtM=','base64'),torrent.sha1sum);
  });
});<|endoftext|>


<commit_before>import {Subject, of} from 'rxjs'
import {compose} from 'compose'
import {getAllVisualizations} from '../ccdc/ccdcRecipe'
import {getAvailableBands} from 'sources'
import {map, switchMap, takeUntil} from 'rxjs/operators'
import {msg} from 'translate'
import {recipeAccess} from '../../recipeAccess'
import {selectFrom} from 'stateUtils'
import {toVisualizations} from 'app/home/map/imageLayerSource/assetVisualizationParser'
import {withRecipe} from '../../recipeContext'
import Notifications from 'widget/notifications'
import React from 'react'
import _ from 'lodash'
import api from 'api'

const baseBandPattern = /(.*)_(coefs|intercept|slope|phase_\d|amplitude_\d|rmse|magnitude)$/

const mapRecipeToProps = (recipe, ownProps) => {
    return {
        ...ownProps,
        source: selectFrom(recipe, 'model.source') || {}
    }
}

class _SourceSync extends React.Component {
    cancel$ = new Subject()

    render() {
        return null
    }

    componentDidMount() {
        this.initSource()
    }

    componentDidUpdate(prevProps) {
        const {source: prevSource} = prevProps
        const {source} = this.props
        if (source.id !== prevSource.id
            || selectFrom(source, 'classification.id') !== selectFrom(prevSource, 'classification.id')) {
            this.cancel$.next()
        }
        this.initSource(prevSource)
    }

    initSource(prevSource) {
        const {source} = this.props
        if (!source.id) {
            return
        }
        source.type === 'RECIPE_REF'
            ? this.initRecipe()
            : this.initAsset(prevSource)
    }

    initAsset(prevSource = {}) {
        const {stream, source = {}} = this.props
        if (source.id && source.id === prevSource.id || stream('LOAD').active) {
            return
        }
        stream('LOAD',
            api.gee.imageMetadata$({asset: source.id}).pipe(
                takeUntil(this.cancel$)
            ),
            metadata => this.updateAssetSource(source.id, metadata),
            error => Notifications.error({message: msg('process.ccdcSlice.source.asset.loadError'), error})
        )
    }

    initRecipe() {
        const {stream, source, loadedRecipes} = this.props
        const ccdcRecipe = loadedRecipes[source.id]
        if (ccdcRecipe) {
            const classificationId = selectFrom(ccdcRecipe, 'model.sources.classification')
            const classificationRecipe = classificationId && loadedRecipes[classificationId]
            if (classificationId && !classificationRecipe) {
                this.loadClassificationRecipe({ccdcRecipe, classificationId})
            } else {
                this.updateRecipeSource({ccdcRecipe, classificationRecipe})
            }
        } else if (!stream('LOAD').active) {
            this.loadCcdcRecipe(source.id)
        }
    }

    loadCcdcRecipe(recipeId) {
        const {stream, loadRecipe$} = this.props
        stream('LOAD',
            loadRecipe$(recipeId).pipe(
                switchMap(ccdcRecipe => ccdcRecipe.model.sources.classification
                    ? loadRecipe$(ccdcRecipe.model.sources.classification).pipe(
                        map(classificationRecipe => ({ccdcRecipe, classificationRecipe}))
                    )
                    : of({ccdcRecipe})
                ),
                takeUntil(this.cancel$)
            ),
            ({ccdcRecipe, classificationRecipe}) => {
                this.updateRecipeSource({ccdcRecipe, classificationRecipe})
            },
            error => Notifications.error({message: msg('process.ccdcSlice.source.recipe.loadError'), error})
        )
    }

    loadClassificationRecipe({ccdcRecipe, classificationId}) {
        const {stream, loadRecipe$} = this.props
        if (!stream('LOAD').active) {
            stream('LOAD',
                loadRecipe$(classificationId).pipe(
                    takeUntil(this.cancel$)
                ),
                classificationRecipe => {
                    this.updateRecipeSource({ccdcRecipe, classificationRecipe})
                },
                error => Notifications.error({message: msg('process.ccdcSlice.source.recipe.loadError'), error})
            )
        }
    }

    updateAssetSource(id, metadata) {
        const {recipeActionBuilder} = this.props
        const bands = metadata.bands
        const bandAndType = _.chain(bands)
            .map(sourceBand => sourceBand.match(baseBandPattern))
            .filter(match => match)
            .map(([_, name, bandType]) => bandType === 'coefs'
                ? ['value', 'intercept', 'slope', 'phase_1', 'amplitude_1', 'phase_2', 'amplitude_2', 'phase_3', 'amplitude_3']
                    .map(bandType => ({name, bandType}))
                : [{name, bandType}]
            )
            .flatten()
            .value()
        const bandByName = _.groupBy(bandAndType, ({name}) => name)
        const baseBands = _.chain(bandAndType)
            .map(({name}) => name)
            .uniq()
            .map(name => ({name, bandTypes: bandByName[name].map(({bandType}) => bandType)}))
            .value()
        const segmentBands = bands
            .filter(name => ['tStart', 'tEnd', 'tBreak', 'numObs', 'changeProb'].includes(name))
            .map(name => ({name}))
        const sourceDetails = {
            type: 'ASSET',
            id,
            bands,
            baseBands,
            segmentBands,
            dateFormat: metadata.properties.dateFormat,
            startDate: metadata.properties.startDate,
            endDate: metadata.properties.endDate,
            visualizations: toVisualizations(metadata.properties, bands)
        }
        recipeActionBuilder('UPDATE_SOURCE', {sourceDetails})
            .set('model.source', sourceDetails)
            .dispatch()
    }

    updateRecipeSource({ccdcRecipe, classificationRecipe}) {
        const {source, recipeActionBuilder} = this.props
        const nextSource = this.recipeSource({ccdcRecipe, classificationRecipe})
        if (!_.isEqual(source, nextSource)) {
            recipeActionBuilder('UPDATE_SOURCE', {source})
                .set('model.source', nextSource)
                .dispatch()
        }
    }

    recipeSource({ccdcRecipe, classificationRecipe}) {
        const corrections = ccdcRecipe.model.options.corrections
        const baseBands = getAvailableBands({
            dataSets: ccdcRecipe.model.sources.dataSets,
            corrections,
            classification: classificationRecipe
                ? {
                    id: classificationRecipe.id,
                    classifierType: classificationRecipe.model.classifier.type,
                    classificationLegend: classificationRecipe.model.legend,
                    include: ['regression', 'probabilities']
                }
                : {}
        }).map(name => ({
            name,
            bandTypes: ['value', 'rmse', 'magnitude', 'intercept', 'slope',
                'phase_1', 'amplitude_1', 'phase_2', 'amplitude_2', 'phase_3', 'amplitude_3']
        }))
        const segmentBands = [{name: 'tStart'}, {name: 'tEnd'}, {name: 'tBreak'}, {name: 'numObs'}, {name: 'changeProb'}]
        const bands = [
            ...baseBands.map(({name, bandTypes}) => bandTypes.map(bandType => `${name}_${bandType === 'value' ? 'coefs' : bandType}`)),
            segmentBands.map(({name}) => name)
        ].flat()
        return {
            type: 'RECIPE_REF',
            id: ccdcRecipe.id,
            bands,
            baseBands,
            segmentBands,
            dateFormat: ccdcRecipe.model.ccdcOptions.dateFormat,
            startDate: ccdcRecipe.model.dates.startDate,
            endDate: ccdcRecipe.model.dates.endDate,
            visualizations: getAllVisualizations(ccdcRecipe)
        }
    }
}

export const SourceSync = compose(
    _SourceSync,
    withRecipe(mapRecipeToProps),
    recipeAccess()
)
<commit_msg>Assigned visualization ids for visualizations from CCDC assets.<commit_after>import {Subject, of} from 'rxjs'
import {compose} from 'compose'
import {getAllVisualizations} from '../ccdc/ccdcRecipe'
import {getAvailableBands} from 'sources'
import {map, switchMap, takeUntil} from 'rxjs/operators'
import {msg} from 'translate'
import {recipeAccess} from '../../recipeAccess'
import {selectFrom} from 'stateUtils'
import {toVisualizations} from 'app/home/map/imageLayerSource/assetVisualizationParser'
import {withRecipe} from '../../recipeContext'
import Notifications from 'widget/notifications'
import React from 'react'
import _ from 'lodash'
import api from 'api'
import guid from 'guid'

const baseBandPattern = /(.*)_(coefs|intercept|slope|phase_\d|amplitude_\d|rmse|magnitude)$/

const mapRecipeToProps = (recipe, ownProps) => {
    return {
        ...ownProps,
        source: selectFrom(recipe, 'model.source') || {}
    }
}

class _SourceSync extends React.Component {
    cancel$ = new Subject()

    render() {
        return null
    }

    componentDidMount() {
        this.initSource()
    }

    componentDidUpdate(prevProps) {
        const {source: prevSource} = prevProps
        const {source} = this.props
        if (source.id !== prevSource.id
            || selectFrom(source, 'classification.id') !== selectFrom(prevSource, 'classification.id')) {
            this.cancel$.next()
        }
        this.initSource(prevSource)
    }

    initSource(prevSource) {
        const {source} = this.props
        if (!source.id) {
            return
        }
        source.type === 'RECIPE_REF'
            ? this.initRecipe()
            : this.initAsset(prevSource)
    }

    initAsset(prevSource = {}) {
        const {stream, source = {}} = this.props
        if (source.id && source.id === prevSource.id || stream('LOAD').active) {
            return
        }
        stream('LOAD',
            api.gee.imageMetadata$({asset: source.id}).pipe(
                takeUntil(this.cancel$)
            ),
            metadata => this.updateAssetSource(source.id, metadata),
            error => Notifications.error({message: msg('process.ccdcSlice.source.asset.loadError'), error})
        )
    }

    initRecipe() {
        const {stream, source, loadedRecipes} = this.props
        const ccdcRecipe = loadedRecipes[source.id]
        if (ccdcRecipe) {
            const classificationId = selectFrom(ccdcRecipe, 'model.sources.classification')
            const classificationRecipe = classificationId && loadedRecipes[classificationId]
            if (classificationId && !classificationRecipe) {
                this.loadClassificationRecipe({ccdcRecipe, classificationId})
            } else {
                this.updateRecipeSource({ccdcRecipe, classificationRecipe})
            }
        } else if (!stream('LOAD').active) {
            this.loadCcdcRecipe(source.id)
        }
    }

    loadCcdcRecipe(recipeId) {
        const {stream, loadRecipe$} = this.props
        stream('LOAD',
            loadRecipe$(recipeId).pipe(
                switchMap(ccdcRecipe => ccdcRecipe.model.sources.classification
                    ? loadRecipe$(ccdcRecipe.model.sources.classification).pipe(
                        map(classificationRecipe => ({ccdcRecipe, classificationRecipe}))
                    )
                    : of({ccdcRecipe})
                ),
                takeUntil(this.cancel$)
            ),
            ({ccdcRecipe, classificationRecipe}) => {
                this.updateRecipeSource({ccdcRecipe, classificationRecipe})
            },
            error => Notifications.error({message: msg('process.ccdcSlice.source.recipe.loadError'), error})
        )
    }

    loadClassificationRecipe({ccdcRecipe, classificationId}) {
        const {stream, loadRecipe$} = this.props
        if (!stream('LOAD').active) {
            stream('LOAD',
                loadRecipe$(classificationId).pipe(
                    takeUntil(this.cancel$)
                ),
                classificationRecipe => {
                    this.updateRecipeSource({ccdcRecipe, classificationRecipe})
                },
                error => Notifications.error({message: msg('process.ccdcSlice.source.recipe.loadError'), error})
            )
        }
    }

    updateAssetSource(id, metadata) {
        const {recipeActionBuilder} = this.props
        const bands = metadata.bands
        const bandAndType = _.chain(bands)
            .map(sourceBand => sourceBand.match(baseBandPattern))
            .filter(match => match)
            .map(([_, name, bandType]) => bandType === 'coefs'
                ? ['value', 'intercept', 'slope', 'phase_1', 'amplitude_1', 'phase_2', 'amplitude_2', 'phase_3', 'amplitude_3']
                    .map(bandType => ({name, bandType}))
                : [{name, bandType}]
            )
            .flatten()
            .value()
        const bandByName = _.groupBy(bandAndType, ({name}) => name)
        const baseBands = _.chain(bandAndType)
            .map(({name}) => name)
            .uniq()
            .map(name => ({name, bandTypes: bandByName[name].map(({bandType}) => bandType)}))
            .value()
        const segmentBands = bands
            .filter(name => ['tStart', 'tEnd', 'tBreak', 'numObs', 'changeProb'].includes(name))
            .map(name => ({name}))
        const sourceDetails = {
            type: 'ASSET',
            id,
            bands,
            baseBands,
            segmentBands,
            dateFormat: metadata.properties.dateFormat,
            startDate: metadata.properties.startDate,
            endDate: metadata.properties.endDate,
            visualizations: toVisualizations(metadata.properties, bands)
                .map(visualization => ({...visualization, id: guid()}))
        }
        recipeActionBuilder('UPDATE_SOURCE', {sourceDetails})
            .set('model.source', sourceDetails)
            .dispatch()
    }

    updateRecipeSource({ccdcRecipe, classificationRecipe}) {
        const {source, recipeActionBuilder} = this.props
        const nextSource = this.recipeSource({ccdcRecipe, classificationRecipe})
        if (!_.isEqual(source, nextSource)) {
            recipeActionBuilder('UPDATE_SOURCE', {source})
                .set('model.source', nextSource)
                .dispatch()
        }
    }

    recipeSource({ccdcRecipe, classificationRecipe}) {
        const corrections = ccdcRecipe.model.options.corrections
        const baseBands = getAvailableBands({
            dataSets: ccdcRecipe.model.sources.dataSets,
            corrections,
            classification: classificationRecipe
                ? {
                    id: classificationRecipe.id,
                    classifierType: classificationRecipe.model.classifier.type,
                    classificationLegend: classificationRecipe.model.legend,
                    include: ['regression', 'probabilities']
                }
                : {}
        }).map(name => ({
            name,
            bandTypes: ['value', 'rmse', 'magnitude', 'intercept', 'slope',
                'phase_1', 'amplitude_1', 'phase_2', 'amplitude_2', 'phase_3', 'amplitude_3']
        }))
        const segmentBands = [{name: 'tStart'}, {name: 'tEnd'}, {name: 'tBreak'}, {name: 'numObs'}, {name: 'changeProb'}]
        const bands = [
            ...baseBands.map(({name, bandTypes}) => bandTypes.map(bandType => `${name}_${bandType === 'value' ? 'coefs' : bandType}`)),
            segmentBands.map(({name}) => name)
        ].flat()
        return {
            type: 'RECIPE_REF',
            id: ccdcRecipe.id,
            bands,
            baseBands,
            segmentBands,
            dateFormat: ccdcRecipe.model.ccdcOptions.dateFormat,
            startDate: ccdcRecipe.model.dates.startDate,
            endDate: ccdcRecipe.model.dates.endDate,
            visualizations: getAllVisualizations(ccdcRecipe)
        }
    }
}

export const SourceSync = compose(
    _SourceSync,
    withRecipe(mapRecipeToProps),
    recipeAccess()
)
<|endoftext|>


<commit_before>var testCase = require('nodeunit').testCase,
    filters = require('../lib/filters');

exports.lower = function (test) {
    var input = 'BaR';
    test.strictEqual('bar', eval(filters.wrap('input', ['lower'])));
    input = 345;
    test.strictEqual('345', eval(filters.wrap('input', ['lower'])));
    test.done();
};

exports.upper = function (test) {
    var input = 'bar';
    test.strictEqual('BAR', eval(filters.wrap('input', ['upper'])));
    input = 345;
    test.strictEqual('345', eval(filters.wrap('input', ['upper'])));
    test.done();
};

exports.capitalize = function (test) {
    var input = 'awesome sauce.';
    test.strictEqual('Awesome sauce.', eval(filters.wrap('input', ['capitalize'])));
    input = 345;
    test.strictEqual('345', eval(filters.wrap('input', ['capitalize'])));
    test.done();
};

exports.title = function (test) {
    var input = 'this is title case';
    test.strictEqual('This Is Title Case', eval(filters.wrap('input', ['title'])));
    test.done();
};

exports.join = function (test) {
    var input = [1, 2, 3];
    test.strictEqual('1+2+3', eval(filters.wrap('input', ['join(\'+\')'])));
    test.strictEqual('1 * 2 * 3', eval(filters.wrap('input', ['join(\' * \')'])));
    input = 'asdf';
    test.strictEqual('asdf', eval(filters.wrap('input', ['join(\'-\')'])), 'Non-array input is not joined.');
    test.done();
};

exports.length = function (test) {
    var input = [1, 2, 3];
    test.strictEqual(3, eval(filters.wrap('input', ['length'])));
    input = 'foobar';
    test.strictEqual(6, eval(filters.wrap('input', ['length'])));
    test.done();
};

exports.url_encode = function (test) {
    var input = "param=1&anotherParam=2";
    test.strictEqual("param%3D1%26anotherParam%3D2", eval(filters.wrap('input', ['url_encode'])));
    test.done();
};

exports.url_decode = function (test) {
    var input = "param%3D1%26anotherParam%3D2";
    test.strictEqual("param=1&anotherParam=2", eval(filters.wrap('input', ['url_decode'])));
    test.done();
};

exports.json_encode = function (test) {
    var input = { foo: 'bar', baz: [1, 2, 3] };
    test.strictEqual('{"foo":"bar","baz":[1,2,3]}', eval(filters.wrap('input', ['json_encode'])));
    test.done();
};

exports.striptags = function (test) {
    var input = '
foo

hi
';
    test.strictEqual('foo hi', eval(filters.wrap('input', ['striptags'])));
    test.done();
};

exports.multiple = function (test) {
    var input = ['aWEsoMe', 'sAuCe'];
    test.strictEqual('Awesome Sauce', eval(filters.wrap('input', ['join(\' \')', 'title'])));
    test.done();
};
<commit_msg>not using nodeunit testcases in filters tests. removing requires.<commit_after>var filters = require('../lib/filters');

exports.lower = function (test) {
    var input = 'BaR';
    test.strictEqual('bar', eval(filters.wrap('input', ['lower'])));
    input = 345;
    test.strictEqual('345', eval(filters.wrap('input', ['lower'])));
    test.done();
};

exports.upper = function (test) {
    var input = 'bar';
    test.strictEqual('BAR', eval(filters.wrap('input', ['upper'])));
    input = 345;
    test.strictEqual('345', eval(filters.wrap('input', ['upper'])));
    test.done();
};

exports.capitalize = function (test) {
    var input = 'awesome sauce.';
    test.strictEqual('Awesome sauce.', eval(filters.wrap('input', ['capitalize'])));
    input = 345;
    test.strictEqual('345', eval(filters.wrap('input', ['capitalize'])));
    test.done();
};

exports.title = function (test) {
    var input = 'this is title case';
    test.strictEqual('This Is Title Case', eval(filters.wrap('input', ['title'])));
    test.done();
};

exports.join = function (test) {
    var input = [1, 2, 3];
    test.strictEqual('1+2+3', eval(filters.wrap('input', ['join(\'+\')'])));
    test.strictEqual('1 * 2 * 3', eval(filters.wrap('input', ['join(\' * \')'])));
    input = 'asdf';
    test.strictEqual('asdf', eval(filters.wrap('input', ['join(\'-\')'])), 'Non-array input is not joined.');
    test.done();
};

exports.length = function (test) {
    var input = [1, 2, 3];
    test.strictEqual(3, eval(filters.wrap('input', ['length'])));
    input = 'foobar';
    test.strictEqual(6, eval(filters.wrap('input', ['length'])));
    test.done();
};

exports.url_encode = function (test) {
    var input = "param=1&anotherParam=2";
    test.strictEqual("param%3D1%26anotherParam%3D2", eval(filters.wrap('input', ['url_encode'])));
    test.done();
};

exports.url_decode = function (test) {
    var input = "param%3D1%26anotherParam%3D2";
    test.strictEqual("param=1&anotherParam=2", eval(filters.wrap('input', ['url_decode'])));
    test.done();
};

exports.json_encode = function (test) {
    var input = { foo: 'bar', baz: [1, 2, 3] };
    test.strictEqual('{"foo":"bar","baz":[1,2,3]}', eval(filters.wrap('input', ['json_encode'])));
    test.done();
};

exports.striptags = function (test) {
    var input = '
foo

hi
';
    test.strictEqual('foo hi', eval(filters.wrap('input', ['striptags'])));
    test.done();
};

exports.multiple = function (test) {
    var input = ['aWEsoMe', 'sAuCe'];
    test.strictEqual('Awesome Sauce', eval(filters.wrap('input', ['join(\' \')', 'title'])));
    test.done();
};
<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

function main(storageUri) {
  // [START speech_transcribe_sync]
  // Provides "hints" to the speech recognizer to favor
  // specific classes of words in the results.

  // Imports the Google Cloud client library
  const speech = require('@google-cloud/speech');

  // Creates a client
  const client = new speech.SpeechClient();

  async function transcribeContextClasses() {
    // storageUri = 'gs://YOUR_BUCKET_ID/path/to/your/file.wav'
    const audio = {
      uri: storageUri,
    };

    // SpeechContext: to configure your speech_context see:
    // https://cloud.google.com/speech-to-text/docs/reference/rpc/google.cloud.speech.v1#speechcontext
    // Full list of supported phrases(class tokens) here:
    // https://cloud.google.com/speech-to-text/docs/class-tokens
    const speechContext = {
      phrases: ['$TIME'],
    };

    // RecognitionConfig: to configure your encoding and sample_rate_hertz, see:
    // https://cloud.google.com/speech-to-text/docs/reference/rpc/google.cloud.speech.v1#recognitionconfig
    const config = {
      encoding: 'LINEAR16',
      sampleRateHertz: 8000,
      languageCode: 'en-US',
      speechContexts: [speechContext],
    };

    const request = {
      config: config,
      audio: audio,
    };

    // Detects speech in the audio file.
    const [response] = await client.recognize(request);
    response.results.forEach((result, index) => {
      const transcript = result.alternatives[0].transcript;
      console.log('-'.repeat(20));
      console.log(`First alternative of result ${index}`);
      console.log(`Transcript: ${transcript}`);
    });
  }

  transcribeContextClasses();
  // [END speech_transcribe_sync]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});

main(...process.argv.slice(2));
<commit_msg>docs: add additional context to samples (#672)<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// sample-metadata:
//   title: Transcribe Context Classes
//   description: Provides "hints" to the speech recognizer to favor specific words and phrases in the results.
//   usage: node samples/transcribeContextClasses.js <storageUri>

function main(storageUri) {
  // [START speech_transcribe_sync]
  // Provides "hints" to the speech recognizer to favor
  // specific classes of words in the results.

  // Imports the Google Cloud client library
  const speech = require('@google-cloud/speech');

  // Creates a client
  const client = new speech.SpeechClient();

  async function transcribeContextClasses() {
    // storageUri = 'gs://YOUR_BUCKET_ID/path/to/your/file.wav'
    const audio = {
      uri: storageUri,
    };

    // SpeechContext: to configure your speech_context see:
    // https://cloud.google.com/speech-to-text/docs/reference/rpc/google.cloud.speech.v1#speechcontext
    // Full list of supported phrases(class tokens) here:
    // https://cloud.google.com/speech-to-text/docs/class-tokens
    const speechContext = {
      phrases: ['$TIME'],
    };

    // RecognitionConfig: to configure your encoding and sample_rate_hertz, see:
    // https://cloud.google.com/speech-to-text/docs/reference/rpc/google.cloud.speech.v1#recognitionconfig
    const config = {
      encoding: 'LINEAR16',
      sampleRateHertz: 8000,
      languageCode: 'en-US',
      speechContexts: [speechContext],
    };

    const request = {
      config: config,
      audio: audio,
    };

    // Detects speech in the audio file.
    const [response] = await client.recognize(request);
    response.results.forEach((result, index) => {
      const transcript = result.alternatives[0].transcript;
      console.log('-'.repeat(20));
      console.log(`First alternative of result ${index}`);
      console.log(`Transcript: ${transcript}`);
    });
  }

  transcribeContextClasses();
  // [END speech_transcribe_sync]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});

main(...process.argv.slice(2));
<|endoftext|>


<commit_before>var Urhola = {

	SelectBox: function(userDefinedSettings) {

		var wrapper = undefined;
		var container = undefined;
		var selector = undefined;
		var valueContainer = undefined;
		var selectedValue = undefined;
		var selectedLabel = undefined;
		var optionsContainer = undefined;
		var valueContainerText = undefined;
		var arrow = undefined;
		var self = this;

		// Allowed settings which can be overriden by the user
		var settings = {
			options: [],
			wrapperClass: undefined,
			parentElement: undefined,
			defaultValue: undefined,
			orientation: "right",
			onChange: undefined,
			optionLimit: 5
		};

		init();

		function init() {
			settings = Urhola.Utils.mergeSettings(userDefinedSettings, settings);
			Urhola.SelectBox.validateSettings(settings);
			wrapper = createWrapper();
			container = createContainer();
			selector = createSelector();
			valueContainer = createValueContainer();
			optionsContainer = createOptionsContainer();
		}

		this.setOptions = function(options) {
			Urhola.SelectBox.validateOptionList(options);
			settings.options = options;
			addOptionsToContainer(optionsContainer);
			updateValueContainerText();
		}

		this.setOptionLimit = function(limit) {
			self.closeOptionList();
			settings.optionLimit = limit;
			self.openOptionList();
		}

		this.setOrientation = function(orientation) {
			settings.orientation = orientation;
			self.render();
		}

		this.getOptions = function() {
			return getOptions();
		}

		this.closeOptionList = function() {
			Urhola.Dom.addStyleToElement(optionsContainer, "display", "none");
			Urhola.Dom.addClassToElement(arrow, "arrow arrowDown");
		}

		this.openOptionList = function() {
			Urhola.Dom.addStyleToElement(optionsContainer, "display", "block");
			Urhola.Dom.addClassToElement(arrow, "arrow arrowUp");
			var height = optionsContainer.firstChild.offsetHeight;
			adjustOptionsContainerHeight(height);
			adjustOptionsContainerWidth();
		}

		this.getSelectedValue = function() {
			return selectedValue;
		}

		this.getSelectedLabel = function() {
			return selectedLabel;
		}

		this.hide = function() {
			wrapper.addStyleToElement("display", "none");
			return this;
		}

		this.show = function() {
			wrapper.addStyleToElement("display", "block");
			return this;
		}

		this.render = function() {
			var rootElement = getParentElement();
			rootElement.innerHTML = "";
			Urhola.Dom.appendChildToElement(wrapper, rootElement);
			Urhola.Dom.appendChildToElement(container, wrapper);
			var orientation = getOrientation();
			if (orientation === "right") {
				Urhola.Dom.appendChildToElement(valueContainer, container);
				Urhola.Dom.appendChildToElement(selector, container);
			}
			else {
				Urhola.Dom.appendChildToElement(selector, container);
				Urhola.Dom.appendChildToElement(valueContainer, container);
			}
			Urhola.Dom.appendChildToElement(optionsContainer, wrapper);
			addOptionsToContainer(optionsContainer);
			return this;
		}

		function setDefaultOption() {
			var defaultValue = getDefaultValue();
			var option = getOptionByValue(defaultValue);
			setSelectedOption(option);
		}

		function setSelectedOption(option) {
			selectedLabel = option.label;
			selectedValue = option.value;
			valueContainerText.innerHTML = "";
			Urhola.Dom.appendTextToElement(selectedLabel, valueContainerText);
		}

		function updateValueContainerText() {
			var option = getOptionByValue(selectedValue);
			setSelectedOption(option);
		}

		function addOptionsToContainer(parent) {
			parent.innerHTML = "";
			var options = getOptions();
			for (var i = 0; i < options.length; i++) {
				var label = options[i].label;
				var value = options[i].value;
				var li = Urhola.Dom.createElement("li");
				Urhola.Dom.addPropertyToElement(li, "label", label);
				Urhola.Dom.addPropertyToElement(li, "value", value);
				Urhola.Dom.appendTextToElement(label, li);
				li.addEventListener("click", optionClicked);
				Urhola.Dom.appendChildToElement(li, parent);
			}
			return parent;
		}

		function adjustOptionsContainerWidth() {
			var width =  wrapper.offsetWidth + "px";
			Urhola.Dom.addStyleToElement(optionsContainer, "width", width);
		}

		function adjustOptionsContainerHeight(listItemOffsetHeight) {
			var limit = getOptionLimit();
			var height = limit * listItemOffsetHeight;
			height += "px"
			Urhola.Dom.addStyleToElement(optionsContainer, "height", height);
		}

		function getOptionByValue(value) {
			var options = getOptions();
			for (var i = 0; i < options.length; i++) {
				if (options[i].value === value)
					return options[i];
			}
			return options[0];
		}

		function optionClicked(e) {
			var target = e.target;
			var onChange = getOnChange();
			selectedValue = Urhola.Dom.getElementAttribute(target, "value");
			selectedLabel = Urhola.Dom.getElementAttribute(target, "label");
			valueContainerText.innerHTML = selectedLabel;
			if (typeof onChange === "function")
				onChange(selectedLabel, selectedValue, self);
		}

		function createValueContainerText(text) {
			var textNode = Urhola.Dom.createTextNode(text);
			return textNode;
		}

		function createOptionsContainer() {
			var className = "optionsContainer";
			var container = Urhola.Dom.createElement("ul");
			Urhola.Dom.addClassToElement(container, className);
			return container;
		}

		function createValueContainer() {
			var className = "valueContainer";
			var valueContainer = Urhola.Dom.createElement("li");
			valueContainerText = Urhola.Dom.createElement("span");
			Urhola.Dom.appendChildToElement(valueContainerText, valueContainer);
			Urhola.Dom.addClassToElement(valueContainer, className);
			setDefaultOption();
			return valueContainer;
		}

		function createSelector() {
			var className = "selector";
			var selector = Urhola.Dom.createElement("li");
			Urhola.Dom.addClassToElement(selector, className);
			arrow = Urhola.Dom.createElement("div");
			Urhola.Dom.addClassToElement(arrow, "arrow arrowDown");
			Urhola.Dom.appendChildToElement(arrow, selector);
			return selector;
		}

		function toggleOptionList(e) {
			var optionsContainerDisplayValue = Urhola.Dom.getElementStyleValue(optionsContainer, "display");
			if (optionsContainerDisplayValue === "block")
				self.closeOptionList();
			else
				self.openOptionList();
		}

		function createWrapper() {
			var className = getWrapperClass();
			var wrapper = Urhola.Dom.createElement("div");
			wrapper.addEventListener("click", toggleOptionList);
			wrapper.addEventListener("mouseleave", mouseLeave);
			Urhola.Dom.addClassToElement(wrapper, className);
			return wrapper;
		}

		function mouseLeave(e) {
			self.closeOptionList();
		}

		function createContainer() {
			var className = "container";
			var container = Urhola.Dom.createElement("ul");
			Urhola.Dom.addClassToElement(container, className);
			return container;
		}

		function getOrientation() {
			return settings.orientation;
		}

		function getOptionLimit() {
			return settings.optionLimit;
		}

		function getOptions() {
			return settings.options;
		}

		function getWrapperClass() {
			return settings.wrapperClass;
		}

		function getParentElement() {
			return settings.parentElement;
		}

		function getDefaultValue() {
			return settings.defaultValue;
		}

		function getOnChange() {
			return settings.onChange;
		}
	},

	Dom: {

		getElementById: function(id) {
			return document.getElementById(id);
		},

		createElement: function(tagName, id, classNames) {
			var elem = document.createElement(tagName);
			if (id !== undefined)
				elem.id = id;
			if (Urhola.Utils.isArray(classNames)) {
				for (var i = 0; i < classNames.length; i++)
					elem.className = classNames[i];
			}
			else if (typeof classNames === "string")
				elem.className = className;
			return elem;
		},

		addIdToElement: function(elem, id) {
			elem.id = id;
			return elem;
		},

		addClassToElement: function(elem, className) {
			elem.className = className;
			return elem;
		},

		addStyleToElement: function(elem, name, value) {
			elem.style[name] = value;
			return elem;
		},

		getElementStyleValue: function(elem, name) {
			return elem.style[name];
		},

		getElementAttribute: function(elem, name) {
			return elem.getAttribute(name);
		},

		addPropertyToElement: function(elem, name, value) {
			elem.setAttribute(name, value);
			return elem;
		},

		appendChildToElement: function(child, elem) {
			elem.appendChild(child);
			return parent;
		},

		createTextNode: function(text) {
			return document.createTextNode(text);
		},

		appendTextToElement: function(text, elem) {
			var node = Urhola.Dom.createTextNode(text);
			Urhola.Dom.appendChildToElement(node, elem);
			return node;
		}
	},

	Utils: {
		mergeSettings: function(a, b) {
			for (var key in b) {
				if (a[key] !== undefined)
					b[key] = a[key];
			}
			return b;
		},

		isArray: function(arr) {
			if (Array.isArray)
				return Array.isArray(arr);
			return false;
		}
	}
}

Urhola.SelectBox.validateOptionList = function(options) {
	if (Object.prototype.toString.call(options) !== '[object Array]')
		throw new Error("Options must be an object array! Each array object must contain label and value attributes!");
}

Urhola.SelectBox.validateElement = function(parentElement) {
	if (typeof parentElement !== "object")
		throw new Error("Parent element must be an element!");
}

Urhola.SelectBox.validateSettings = function(settings) {
	Urhola.SelectBox.validateOptionList(settings.options);
	Urhola.SelectBox.validateElement(settings.parentElement);
}<commit_msg>enabled sorting<commit_after>var Urhola = {

	SelectBox: function(userDefinedSettings) {

		var wrapper = undefined;
		var container = undefined;
		var selector = undefined;
		var valueContainer = undefined;
		var selectedValue = undefined;
		var selectedLabel = undefined;
		var optionsContainer = undefined;
		var valueContainerText = undefined;
		var arrow = undefined;
		var self = this;

		// Allowed settings which can be overriden by the user
		var settings = {
			options: [],
			wrapperClass: undefined,
			parentElement: undefined,
			defaultValue: undefined,
			orientation: "right",
			onChange: undefined,
			optionLimit: 5,
			sort: "desc"
		};

		init();

		function init() {
			settings = Urhola.Utils.mergeSettings(userDefinedSettings, settings);
			Urhola.SelectBox.validateSettings(settings);
			wrapper = createWrapper();
			container = createContainer();
			selector = createSelector();
			valueContainer = createValueContainer();
			optionsContainer = createOptionsContainer();
		}

		this.setOptions = function(options) {
			Urhola.SelectBox.validateOptionList(options);
			settings.options = options;
			addOptionsToContainer(optionsContainer);
			updateValueContainerText();
		}

		this.setOptionLimit = function(limit) {
			self.closeOptionList();
			settings.optionLimit = limit;
			self.openOptionList();
		}

		this.setOrientation = function(orientation) {
			settings.orientation = orientation;
			self.render();
		}

		this.getOptions = function() {
			return getOptions();
		}

		this.closeOptionList = function() {
			Urhola.Dom.addStyleToElement(optionsContainer, "display", "none");
			Urhola.Dom.addClassToElement(arrow, "arrow arrowDown");
		}

		this.openOptionList = function() {
			Urhola.Dom.addStyleToElement(optionsContainer, "display", "block");
			Urhola.Dom.addClassToElement(arrow, "arrow arrowUp");
			var height = optionsContainer.firstChild.offsetHeight;
			adjustOptionsContainerHeight(height);
			adjustOptionsContainerWidth();
		}

		this.getSelectedValue = function() {
			return selectedValue;
		}

		this.getSelectedLabel = function() {
			return selectedLabel;
		}

		this.hide = function() {
			wrapper.addStyleToElement("display", "none");
			return this;
		}

		this.show = function() {
			wrapper.addStyleToElement("display", "block");
			return this;
		}

		this.render = function() {
			var rootElement = getParentElement();
			rootElement.innerHTML = "";
			Urhola.Dom.appendChildToElement(wrapper, rootElement);
			Urhola.Dom.appendChildToElement(container, wrapper);
			var orientation = getOrientation();
			if (orientation === "right") {
				Urhola.Dom.appendChildToElement(valueContainer, container);
				Urhola.Dom.appendChildToElement(selector, container);
			}
			else {
				Urhola.Dom.appendChildToElement(selector, container);
				Urhola.Dom.appendChildToElement(valueContainer, container);
			}
			Urhola.Dom.appendChildToElement(optionsContainer, wrapper);
			addOptionsToContainer(optionsContainer);
			return this;
		}

		function setDefaultOption() {
			var defaultValue = getDefaultValue();
			var option = getOptionByValue(defaultValue);
			setSelectedOption(option);
		}

		function setSelectedOption(option) {
			selectedLabel = option.label;
			selectedValue = option.value;
			valueContainerText.innerHTML = "";
			Urhola.Dom.appendTextToElement(selectedLabel, valueContainerText);
		}

		function updateValueContainerText() {
			var option = getOptionByValue(selectedValue);
			setSelectedOption(option);
		}

		function addOptionsToContainer(parent) {
			parent.innerHTML = "";
			var options = getOptions();
			var sort = getSort();
			switch(sort) {
				case "desc":
					options.sort(sortByDesc);
					break;
				case "asc":
					options.sort(sortByAsc);
					break;
				default:
					throw Error("Unsupported sort type \"" + sort + "\"");
			}
			for (var i = 0; i < options.length; i++) {
				var label = options[i].label;
				var value = options[i].value;
				var li = Urhola.Dom.createElement("li");
				Urhola.Dom.addPropertyToElement(li, "label", label);
				Urhola.Dom.addPropertyToElement(li, "value", value);
				Urhola.Dom.appendTextToElement(label, li);
				li.addEventListener("click", optionClicked);
				Urhola.Dom.appendChildToElement(li, parent);
			}
			return parent;
		}

		function sortByDesc(optionA, optionB) {
			var a = optionA.label;
			var b = optionB.label;
			if (a > b)
				return 1;
			if (a < b)
				return -1;
			return 0;
		}

		function sortByAsc(optionA, optionB) {
			var a = optionA.label;
			var b = optionB.label;
			if (a > b)
				return -1;
			if (a < b)
				return 1;
			return 0;
		}

		function adjustOptionsContainerWidth() {
			var width =  wrapper.offsetWidth + "px";
			Urhola.Dom.addStyleToElement(optionsContainer, "width", width);
		}

		function adjustOptionsContainerHeight(listItemOffsetHeight) {
			var limit = getOptionLimit();
			var height = limit * listItemOffsetHeight;
			height += "px"
			Urhola.Dom.addStyleToElement(optionsContainer, "height", height);
		}

		function getOptionByValue(value) {
			var options = getOptions();
			for (var i = 0; i < options.length; i++) {
				if (options[i].value === value)
					return options[i];
			}
			return options[0];
		}

		function optionClicked(e) {
			var target = e.target;
			var onChange = getOnChange();
			selectedValue = Urhola.Dom.getElementAttribute(target, "value");
			selectedLabel = Urhola.Dom.getElementAttribute(target, "label");
			valueContainerText.innerHTML = selectedLabel;
			if (typeof onChange === "function")
				onChange(selectedLabel, selectedValue, self);
		}

		function createValueContainerText(text) {
			var textNode = Urhola.Dom.createTextNode(text);
			return textNode;
		}

		function createOptionsContainer() {
			var className = "optionsContainer";
			var container = Urhola.Dom.createElement("ul");
			Urhola.Dom.addClassToElement(container, className);
			return container;
		}

		function createValueContainer() {
			var className = "valueContainer";
			var valueContainer = Urhola.Dom.createElement("li");
			valueContainerText = Urhola.Dom.createElement("span");
			Urhola.Dom.appendChildToElement(valueContainerText, valueContainer);
			Urhola.Dom.addClassToElement(valueContainer, className);
			setDefaultOption();
			return valueContainer;
		}

		function createSelector() {
			var className = "selector";
			var selector = Urhola.Dom.createElement("li");
			Urhola.Dom.addClassToElement(selector, className);
			arrow = Urhola.Dom.createElement("div");
			Urhola.Dom.addClassToElement(arrow, "arrow arrowDown");
			Urhola.Dom.appendChildToElement(arrow, selector);
			return selector;
		}

		function toggleOptionList(e) {
			var optionsContainerDisplayValue = Urhola.Dom.getElementStyleValue(optionsContainer, "display");
			if (optionsContainerDisplayValue === "block")
				self.closeOptionList();
			else
				self.openOptionList();
		}

		function createWrapper() {
			var className = getWrapperClass();
			var wrapper = Urhola.Dom.createElement("div");
			wrapper.addEventListener("click", toggleOptionList);
			wrapper.addEventListener("mouseleave", mouseLeave);
			Urhola.Dom.addClassToElement(wrapper, className);
			return wrapper;
		}

		function mouseLeave(e) {
			self.closeOptionList();
		}

		function createContainer() {
			var className = "container";
			var container = Urhola.Dom.createElement("ul");
			Urhola.Dom.addClassToElement(container, className);
			return container;
		}

		function getOrientation() {
			return settings.orientation;
		}

		function getOptionLimit() {
			return settings.optionLimit;
		}

		function getOptions() {
			return settings.options;
		}

		function getWrapperClass() {
			return settings.wrapperClass;
		}

		function getParentElement() {
			return settings.parentElement;
		}

		function getDefaultValue() {
			return settings.defaultValue;
		}

		function getOnChange() {
			return settings.onChange;
		}

		function getSort() {
			return settings.sort;
		}
	},

	Dom: {

		getElementById: function(id) {
			return document.getElementById(id);
		},

		createElement: function(tagName, id, classNames) {
			var elem = document.createElement(tagName);
			if (id !== undefined)
				elem.id = id;
			if (Urhola.Utils.isArray(classNames)) {
				for (var i = 0; i < classNames.length; i++)
					elem.className = classNames[i];
			}
			else if (typeof classNames === "string")
				elem.className = className;
			return elem;
		},

		addIdToElement: function(elem, id) {
			elem.id = id;
			return elem;
		},

		addClassToElement: function(elem, className) {
			elem.className = className;
			return elem;
		},

		addStyleToElement: function(elem, name, value) {
			elem.style[name] = value;
			return elem;
		},

		getElementStyleValue: function(elem, name) {
			return elem.style[name];
		},

		getElementAttribute: function(elem, name) {
			return elem.getAttribute(name);
		},

		addPropertyToElement: function(elem, name, value) {
			elem.setAttribute(name, value);
			return elem;
		},

		appendChildToElement: function(child, elem) {
			elem.appendChild(child);
			return parent;
		},

		createTextNode: function(text) {
			return document.createTextNode(text);
		},

		appendTextToElement: function(text, elem) {
			var node = Urhola.Dom.createTextNode(text);
			Urhola.Dom.appendChildToElement(node, elem);
			return node;
		}
	},

	Utils: {
		mergeSettings: function(a, b) {
			for (var key in b) {
				if (a[key] !== undefined)
					b[key] = a[key];
			}
			return b;
		},

		isArray: function(arr) {
			if (Array.isArray)
				return Array.isArray(arr);
			return false;
		}
	}
}

Urhola.SelectBox.validateOptionList = function(options) {
	if (Object.prototype.toString.call(options) !== '[object Array]')
		throw new Error("Options must be an object array! Each array object must contain label and value attributes!");
}

Urhola.SelectBox.validateElement = function(parentElement) {
	if (typeof parentElement !== "object")
		throw new Error("Parent element must be an element!");
}

Urhola.SelectBox.validateSettings = function(settings) {
	Urhola.SelectBox.validateOptionList(settings.options);
	Urhola.SelectBox.validateElement(settings.parentElement);
}<|endoftext|>


<commit_before>// Abstract model
var Class = require('shipyard/class/Class'),
    Model = require('shipyard/model/Model'),
    fields = require('shipyard/model/fields'),
    Syncable = require('shipyard/sync/Syncable'),
    Request = require('shipyard/http/Request'),
    string = require('shipyard/utils/string');

var idCounter = 1;

var File = module.exports = new Class({

    Extends: Model,

    Implements: Syncable,

    fields: {
        id: fields.NumberField(),
        filename: fields.TextField({ required: true }),
        ext: fields.TextField({ 'default': 'js' }),
        content: fields.TextField(),
        main: fields.BooleanField({ 'default': false, write: false }),
        readonly: fields.BooleanField({ 'default': false, write: false }),

        url: fields.TextField({ write: false }),
        get_url: fields.TextField({ write: false })
    },

    initialize: function File(data) {
        if (!data.id) data.id = idCounter++;
        this.parent(data);
    },

    shortName: function() {
        return this.get('fullName').split('/').pop();
    },

    fullName: function() {
        var name = this.get('filename'),
            ext = this.get('ext');

        if (ext) {
            return name + '.' + ext;
        } else {
            return name;
        }
    },

    uid: function() {
         //TODO: this should be the unique hash from the new API
        return this._uid || (this._uid = string.uniqueID());
    },

    isEditable: function() {
        return this.constructor.EDITABLE_EXTS.indexOf(this.get('ext')) !== -1;
    },

    //TODO: Shipyard Models should probably has a isDirty API
    setChanged: function(isChanged) {
        this.changed = isChanged;
        if (isChanged) {
            this.fireEvent('change');
        } else {
            this.fireEvent('reset');
        }
    },

    loadContent: function(callback) {
        var file = this;
        var spinnerEl;
        return new Request({
			method: 'get',
			url: this.get('get_url'),
			useSpinner: !!spinnerEl,
			spinnerTarget: spinnerEl,
            spinnerOptions: {
                img: {
                    'class': 'spinner-img spinner-16'
                },
                maskBorder: false
            },
			onSuccess: function(text) {
                var content = text || '';
				file.original_content = content;
                file.set('content', content);
				file.fireEvent('loadcontent', content);
                if (callback) callback.call(this, content);
			}
		}).send();

    },

    isLoaded: function() {
        return this.get('content') != null;
    },

    toString: function() {
        return this.get('fullName');
    }

});

File.EDITABLE_EXTS = ['js', 'html', 'css', 'txt', 'json', 'md'];

var sanitizeRE = /[^a-zA-Z0-9=!@#\$%\^&\(\)\+\-_\/\.]+/g;
File.sanitize = function(name) {
    return name.replace(sanitizeRE, '-');
};
<commit_msg>adding isImage method to File<commit_after>// Abstract model
var Class = require('shipyard/class/Class'),
    Model = require('shipyard/model/Model'),
    fields = require('shipyard/model/fields'),
    Syncable = require('shipyard/sync/Syncable'),
    Request = require('shipyard/http/Request'),
    string = require('shipyard/utils/string');

var idCounter = 1;

var File = module.exports = new Class({

    Extends: Model,

    Implements: Syncable,

    fields: {
        id: fields.NumberField(),
        filename: fields.TextField({ required: true }),
        ext: fields.TextField({ 'default': 'js' }),
        content: fields.TextField(),
        main: fields.BooleanField({ 'default': false, write: false }),
        readonly: fields.BooleanField({ 'default': false, write: false }),

        url: fields.TextField({ write: false }),
        get_url: fields.TextField({ write: false })
    },

    initialize: function File(data) {
        if (!data.id) data.id = idCounter++;
        this.parent(data);
    },

    shortName: function() {
        return this.get('fullName').split('/').pop();
    },

    fullName: function() {
        var name = this.get('filename'),
            ext = this.get('ext');

        if (ext) {
            return name + '.' + ext;
        } else {
            return name;
        }
    },

    uid: function() {
         //TODO: this should be the unique hash from the new API
        return this._uid || (this._uid = string.uniqueID());
    },

    isEditable: function() {
        return this.constructor.EDITABLE_EXTS.indexOf(this.get('ext')) !== -1;
    },

    isImage: function() {
        return this.constructor.IMAGE_EXTS.indexOf(this.get('ext')) !== -1;
    },

    //TODO: Shipyard Models should probably has a isDirty API
    setChanged: function(isChanged) {
        this.changed = isChanged;
        if (isChanged) {
            this.fireEvent('change');
        } else {
            this.fireEvent('reset');
        }
    },

    loadContent: function(callback) {
        var file = this;
        var spinnerEl;
        return new Request({
			method: 'get',
			url: this.get('get_url'),
			useSpinner: !!spinnerEl,
			spinnerTarget: spinnerEl,
            spinnerOptions: {
                img: {
                    'class': 'spinner-img spinner-16'
                },
                maskBorder: false
            },
			onSuccess: function(text) {
                var content = text || '';
				file.original_content = content;
                file.set('content', content);
				file.fireEvent('loadcontent', content);
                if (callback) callback.call(this, content);
			}
		}).send();

    },

    isLoaded: function() {
        return this.get('content') != null;
    },

    toString: function() {
        return this.get('fullName');
    }

});

File.EDITABLE_EXTS = ['js', 'html', 'css', 'txt', 'json', 'md'];
File.IMAGE_EXTS = ['png', 'jpg', 'gif'];

var sanitizeRE = /[^a-zA-Z0-9=!@#\$%\^&\(\)\+\-_\/\.]+/g;
File.sanitize = function(name) {
    return name.replace(sanitizeRE, '-');
};
<|endoftext|>


<commit_before>'use strict';

const chai = require( 'chai' );
const expect = chai.expect;
const sinon = require( 'sinon' );
const chalk = require( 'chalk' );
console.log( chalk.red ); // eslint-disable-line no-console
const handleErrors = require( '../dist/compiler' ).handleErrors;
const compiler = require( '../dist/compiler' ).default;

describe( 'handleErrors', () => {
	it( 'is a function', () => {
		expect( handleErrors ).to.be.a( 'function' );
	} );

	it( 'displays all errors before throwing', () => {
		const consoleSpy = sinon.spy( console, 'error' );

		expect( () => {
			compiler( {
				'index.ts': `function() {
					return
					'hello world';`
			} );
		} ).to.throw( Error, 'Compilation was unsuccessful!' );

		expect( consoleSpy.callCount ).to.equal( 3 );

		consoleSpy.restore();
	} );
} );
<commit_msg>test(handleError): remove unnecessary code<commit_after>'use strict';

const chai = require( 'chai' );
const expect = chai.expect;
const sinon = require( 'sinon' );
const handleErrors = require( '../dist/compiler' ).handleErrors;
const compiler = require( '../dist/compiler' ).default;

describe( 'handleErrors', () => {
	it( 'is a function', () => {
		expect( handleErrors ).to.be.a( 'function' );
	} );

	it( 'displays all errors before throwing', () => {
		const consoleSpy = sinon.spy( console, 'error' );

		expect( () => {
			compiler( {
				'index.ts': `function() {
					return
					'hello world';`
			} );
		} ).to.throw( Error, 'Compilation was unsuccessful!' );

		expect( consoleSpy.callCount ).to.equal( 3 );

		consoleSpy.restore();
	} );
} );
<|endoftext|>


<commit_before>importScripts('lib/peg-0.8.0.min.js','lib/utils.js', 'lib/pegjslabeller.js');

var userPEG,parser;
self.addEventListener('message',function(evt){
	var data = evt.data, tree;
	if (!parser || data.peg!=userPEG){
		userPEG = data.peg;
		parser = generateParser();
	}
	if (parser){
		try{      tree = parser.parse(data.input)                                         }
		catch(e){ self.postMessage({error:'Error Parsing Input',details:errorDetails(e)}) }
		if (tree) self.postMessage({success:true,parseTree:tree});
	}
},false);

function generateParser(){
	var annotatingPEG, parser;
	try{ annotatingPEG = pegJSRuleLabeller.parse(userPEG)                             }
	catch(e){ self.postMessage({error:'Error Compiling PEG',details:errorDetails(e)}) }
	if (annotatingPEG){
		try{      parser = PEG.buildParser(annotatingPEG)                                            }
		catch(e){ self.postMessage({error:'Error Compiling Annotating PEG',details:errorDetails(e)}) }
		return parser;
	}
}

function errorDetails(e){
	return {
		summary: e+"",
		line:    e.line,
		column:  e.column,
		offset:  e.offset
	}
}<commit_msg>Attempt to compile PEG directly before annotating it, to find errors in the clean source<commit_after>importScripts('lib/peg-0.8.0.min.js','lib/utils.js', 'lib/pegjslabeller.js');

var userPEG,parser;
self.addEventListener('message',function(evt){
	var data = evt.data, tree;
	if (!parser || data.peg!=userPEG){
		userPEG = data.peg;
		parser = generateParser();
	}
	if (parser){
		try{      tree = parser.parse(data.input)                                         }
		catch(e){ self.postMessage({error:'Error Parsing Input',details:errorDetails(e)}) }
		if (tree) self.postMessage({success:true,parseTree:tree});
	}
},false);

function generateParser(){
	var annotatingPEG, parser;
	try{
		PEG.buildParser(userPEG); // Do this just to get an error if there's a problem with the original PEG
		annotatingPEG = pegJSRuleLabeller.parse(userPEG);
	}
	catch(e){ self.postMessage({error:'Error Compiling PEG',details:errorDetails(e)}); }
	if (annotatingPEG){
		try{      parser = PEG.buildParser(annotatingPEG)                                            }
		catch(e){ self.postMessage({error:'Error Compiling Annotating PEG',details:errorDetails(e)}) }
		return parser;
	}
}

function errorDetails(e){
	return {
		summary: e+"",
		line:    e.line,
		column:  e.column,
		offset:  e.offset
	}
}<|endoftext|>


<commit_before>var test = require('tape')
var ActionCreators = require('../../actions')
var constants = require('../../constants')

function createStore () {
  return function (state) {
    return state
  }
}

test('ActionCreators(store) returns action creators', function (t) {
  t.plan(12)
  var store = createStore()
  var actions = ActionCreators(store)
  t.ok(actions.editor)
  t.ok(actions.github)
  t.ok(actions.save)
  t.ok(actions.file)
  t.ok(actions.modal)
  t.ok(actions.menu)
  t.ok(actions.reset)
  t.ok(actions.setUrl)
  t.ok(actions.setUser)
  t.ok(actions.setUserProfile)
  t.ok(actions.setRoute)
  t.ok(actions.signOut)
})

test('signOut', function (t) {
  t.plan(1)
  var store = createStore()
  var actions = ActionCreators(store)
  var action = actions.signOut()
  t.equal(action.type, constants.SIGN_OUT)
})
<commit_msg>Update tests to pass.<commit_after>var test = require('tape')
var ActionCreators = require('../../actions')
var constants = require('../../constants')

function createStore () {
  return function (state) {
    return state
  }
}

test('ActionCreators(store) returns action creators', function (t) {
  t.plan(12)
  var store = createStore()
  var actions = ActionCreators({store: store})
  t.ok(actions.editor)
  t.ok(actions.github)
  t.ok(actions.save)
  t.ok(actions.file)
  t.ok(actions.modal)
  t.ok(actions.menu)
  t.ok(actions.reset)
  t.ok(actions.setUrl)
  t.ok(actions.setUser)
  t.ok(actions.setUserProfile)
  t.ok(actions.setRoute)
  t.ok(actions.signOut)
})

test('signOut', function (t) {
  t.plan(1)
  var store = createStore()
  var actions = ActionCreators({ store: store })
  var action = actions.signOut()
  console.log(action)
  t.equal(action.type, constants.SIGN_OUT)
})
<|endoftext|>