<commit_before>chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello") {
      getData();
      sendResponse({farewell: "goodbye"});
    }
  });

function getData() {
  var result = [["categoria", "loja", "valor", "data"]];
  var a = document.querySelectorAll("div.event-card")
  for (var i = 0; i < a.length; i++) {
    console.log(i);
    var categoria = a[i].querySelector("span.title").textContent;
    if (categoria != "Fatura paga") {
      var loja = a[i].querySelector("h4.description").textContent;
      var valor = a[i].querySelector("div.amount").textContent.replace(/[^0-9-,]/g, '').replace(",",".");
      var data = a[i].querySelector("span.time").textContent;
      result.push([categoria, loja, valor, data]);
    }
  }
  var csvContent = "data:text/csv,";
  result.forEach(function(infoArray, index){

    resultString = infoArray.join(",");
   csvContent += index < result.length ? resultString+ "\n" : resultString;

 });
 var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
}<commit_msg>O filename agora sugere o periodo selecionado<commit_after>chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello") {
      getData();
      sendResponse({farewell: "goodbye"});
    }
  });

function getData() {
  var result = [["categoria", "loja", "valor", "data"]];
  var a = document.querySelectorAll("div.event-card")
  for (var i = 0; i < a.length; i++) {
    console.log(i);
    var categoria = a[i].querySelector("span.title").textContent;
    if (categoria != "Fatura paga") {
      var loja = a[i].querySelector("h4.description").textContent;
      var valor = a[i].querySelector("div.amount").textContent.replace(/[^0-9-,]/g, '').replace(",",".");
      var data = a[i].querySelector("span.time").textContent;
      result.push([categoria, loja, valor, data]);
    }
  }
  var csvContent = "data:text/csv";
  result.forEach(function(infoArray, index){

    resultString = infoArray.join(",");
   csvContent += index < result.length ? resultString+ "\n" : resultString;

 });
 var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
// acha o período selecionado para usar de nome do arquivo
var periodo = document.querySelector('div #timeChart span.filter').textContent.replace(/ /g,'');
link.setAttribute("download", periodo + ".csv");

link.click(); // This will download the data file named "my_data.csv".
}<|endoftext|>


<commit_before>const fs = require('fs');
const { PackageGraph } = require('@lerna/package-graph');
const { Project } = require('@lerna/project');
const { getFilteredPackages } = require('@lerna/filter-options');
const { join, relative } = require('path');
const log = require('npmlog');

function getPackagesWithPeerDependency(packages, peerDependencyName) {
  return packages.filter((pkg) => pkg.peerDependencies && pkg.peerDependencies[peerDependencyName]);
}

async function updatePeerDependents(cwd, packages, name) {
  const peerDependencyPackage = packages.find((pkg) => pkg.name === name);

  if (!peerDependencyPackage) {
    throw new Error(`Can not update peerDependencies, could not find ${name}`);
  }

  log.info('peer', 'Updating %s peer-dependency to %s', name, peerDependencyPackage.version);

  const filteredPackages = getPackagesWithPeerDependency(packages, name);
  console.log(
    name,
    filteredPackages.map((pkg) => pkg.name),
  );

  const promises = filteredPackages.map((pkg) => {
    pkg.peerDependencies[name] = peerDependencyPackage.version;
    return pkg.serialize();
  });
  await Promise.all(promises);
}

async function updateFrameworkPeerDependents(cwd, packages) {
  return updatePeerDependents(cwd, packages, '@jovotech/framework');
}

async function updateOutputPeerDependents(cwd, packages) {
  return updatePeerDependents(cwd, packages, '@jovotech/output');
}

(async () => {
  const cwd = join(__dirname, '..');
  const project = new Project(cwd);
  const packages = await project.getPackages();
  const packageGraph = new PackageGraph(packages);

  await Promise.all([
    updateFrameworkPeerDependents(cwd, packages, packageGraph),
    updateOutputPeerDependents(cwd, packages, packageGraph),
  ]);
})()
  .then(() => {
    console.log('Success');
    process.exit(0);
  })
  .catch((e) => {
    console.error('Failure');
    console.error((e.stdout || e.message).trim());
    console.error(e.stack);
    process.exit(1);
  });
<commit_msg>:hammer: :fire: Remove redundant imports and variables from peer dependency update script<commit_after>const { Project } = require('@lerna/project');
const { join } = require('path');
const log = require('npmlog');

function getPackagesWithPeerDependency(packages, peerDependencyName) {
  return packages.filter((pkg) => pkg.peerDependencies && pkg.peerDependencies[peerDependencyName]);
}

async function updatePeerDependents(cwd, packages, name) {
  const peerDependencyPackage = packages.find((pkg) => pkg.name === name);

  if (!peerDependencyPackage) {
    throw new Error(`Can not update peerDependencies, could not find ${name}`);
  }

  log.info('peer', 'Updating %s peer-dependency to %s', name, peerDependencyPackage.version);

  const filteredPackages = getPackagesWithPeerDependency(packages, name);

  const promises = filteredPackages.map((pkg) => {
    pkg.peerDependencies[name] = peerDependencyPackage.version;
    return pkg.serialize();
  });
  await Promise.all(promises);
}

async function updateFrameworkPeerDependents(cwd, packages) {
  return updatePeerDependents(cwd, packages, '@jovotech/framework');
}

async function updateOutputPeerDependents(cwd, packages) {
  return updatePeerDependents(cwd, packages, '@jovotech/output');
}

(async () => {
  const cwd = join(__dirname, '..');
  const project = new Project(cwd);
  const packages = await project.getPackages();

  await Promise.all([
    updateFrameworkPeerDependents(cwd, packages),
    updateOutputPeerDependents(cwd, packages),
  ]);
})()
  .then(() => {
    console.log('Success');
    process.exit(0);
  })
  .catch((e) => {
    console.error('Failure');
    console.error((e.stdout || e.message).trim());
    console.error(e.stack);
    process.exit(1);
  });
<|endoftext|>


<commit_before>module.exports = function(grunt, options) {
    var webpack = require('webpack'),
        __node_dir = options.build.dir.lib.node,
        __bower_dir = options.build.dir.lib.bower;

    return {
        options: {
            debug: true,
            resolve: {
                fallback: __bower_dir,

                modulesDirectories: [
                    options.build.js,
                    options.build.src
                ],

                alias: {
                    //jQuery: __bower_dir + '/jquery/dist/jquery.js',
                    //lodash: __bower_dir + '/lodash/lodash.js'
                }
            },

            devtool: 'cheap-source-map',

            stats: {
                timings: true,
                color: true,
                reasons: true
            },

            module: {
                loaders: [
                    { test: /\.html$/, loader: 'html-loader' }
                ]
            },

            progress: true,

            externals: {
                jQuery: 'jQuery',
                lodash: 'lodash'
            }
        },

        /**
         *
         */
        debug: {
            debug: true,

            entry: {
                gplayer: options.build.js + '/gplayer.js'
            },

            output: {
                path: options.build.dir.debug,
                filename: 'gplayer.js',
                library: 'gplayer',
                libraryTarget: 'umd',
                pathinfo: true
            },

            plugins: [
                new webpack.DefinePlugin({
                    __DEBUG__: true
                }),

                new webpack.ProvidePlugin({
                    $: "jQuery",
                    jQuery: "jQuery",
                    "window.jQuery": "jQuery",
                    _: "lodash"
                })
            ]
        },

        /**
         *
         */
        release: {
            entry: {
                gplayer: options.build.js + '/gplayer.js'
            },

            output: {
                path: options.build.dir.release,
                filename: 'gplayer.js',
                library: 'gplayer',
                libraryTarget: 'umd',
                pathinfo: true
            },

            plugins: [
                new webpack.DefinePlugin({
                    __DEBUG__: true
                })

                //new webpack.DefinePlugin({'process.env.NODE_ENV': '"production"'}),
                //new webpack.optimize.DedupePlugin(),
                //new webpack.optimize.UglifyJsPlugin({ sourceMap: false }),
                //new webpack.optimize.OccurenceOrderPlugin()
                //new webpack.optimize.AggressiveMergingPlugin()
            ]
        }
    };
};<commit_msg>webpack jquery from src<commit_after>module.exports = function(grunt, options) {
    var webpack = require('webpack'),
        __node_dir = options.build.dir.lib.node,
        __bower_dir = options.build.dir.lib.bower;

    return {
        options: {
            debug: true,
            resolve: {
                fallback: __bower_dir,

                modulesDirectories: [
                    options.build.js,
                    options.build.src
                ],

                alias: {
                    //jQuery: __bower_dir + '/jquery/src/jquery.js',
                    //lodash: __bower_dir + '/lodash/lodash.js'
                }
            },

            devtool: 'cheap-source-map',

            stats: {
                timings: true,
                color: true,
                reasons: true
            },

            module: {
                loaders: [
                    { test: /\.html$/, loader: 'html-loader' }
                ]
            },

            progress: true,

            externals: {
                jQuery: 'jQuery',
                lodash: 'lodash'
            }
        },

        /**
         *
         */
        debug: {
            debug: true,

            entry: {
                gplayer: options.build.js + '/gplayer.js'
            },

            output: {
                path: options.build.dir.debug,
                filename: 'gplayer.js',
                library: 'gplayer',
                libraryTarget: 'umd',
                pathinfo: true
            },

            plugins: [
                new webpack.DefinePlugin({
                    __DEBUG__: true
                }),

                new webpack.ProvidePlugin({
                    $: "jQuery",
                    jQuery: "jQuery",
                    "window.jQuery": "jQuery",
                    _: "lodash"
                })
            ]
        },

        /**
         *
         */
        release: {
            entry: {
                gplayer: options.build.js + '/gplayer.js'
            },

            output: {
                path: options.build.dir.release,
                filename: 'gplayer.js',
                library: 'gplayer',
                libraryTarget: 'umd',
                pathinfo: true
            },

            plugins: [
                new webpack.DefinePlugin({
                    __DEBUG__: true
                })

                //new webpack.DefinePlugin({'process.env.NODE_ENV': '"production"'}),
                //new webpack.optimize.DedupePlugin(),
                //new webpack.optimize.UglifyJsPlugin({ sourceMap: false }),
                //new webpack.optimize.OccurenceOrderPlugin()
                //new webpack.optimize.AggressiveMergingPlugin()
            ]
        }
    };
};<|endoftext|>


<commit_before><commit_msg>Modified index.js to hopefully trigger recompile.<commit_after><|endoftext|>


<commit_before>/**
 * @namespace Cavas functions, wapped into shorter, simpler names and abstracted for cross-browser
 *            compatability
 * @see
 *      MDC Docs
 */
$C = {
	/**
	 * Loads the canvas and its rendering context.
	 */
	init: function() {
		/**
		 * The 2d rendering context of the canvas
		 * @type CanvasRenderingContext2D
		 */
		this.canvas =  $('canvas').getContext('2d')
		CanvasTextFunctions.enable(this.canvas)
	},
	/**
	 * Clears the canvas
	 */
	clear: function(){
		$C.canvas.clearRect(0, 0, Glop.width, Glop.height)
	},

	/**
	 * Sets canvas.fillStyle
	 * @param {String} color Color to use for future fill operations
	 */
	fill_style: function(color) {
		$C.canvas.fillStyle = color
	},
	/**
	 * Sets the fill style of the canvas to a pattern.
	 * @param {Image}  image  Image to use for pattern
	 * @param {String} repeat How to repeat pattern - "repeat", "repeat-x", "repeat-y", or
	 *                        "no-repeat"
	 */
	fill_pattern: function(image, repeat) {
		// this seems to often fail, so wrapped in a try:
		try { $C.canvas.fillStyle = $C.canvas.createPattern(image, repeat) } catch(e) {}
	},
	/**
	 * Alias of canvas.translate
	 * @param {Number} x Number of pixels to tranlate in the x direction
	 * @param {Number} y Number of pixels to tranlate in the y direction
	 */
	translate: function(x,y) {
		$C.canvas.translate(x,y)
	},

	/**
	 * Alias of canvas.scale
	 * @param {Number} x Number of pixels to stretch/shring in the x
	 *                   direction
	 * @param {Number} y Number of pixels to stretch/shring in the y
	 *                   direction
	 */
	scale: function(x,y) {
		$C.canvas.scale(x,y)
	},

	/**
	 * Alias of canvas.rotate
	 * @param {Number} rotation Amount, in radians, to rotate
	 */
	rotate: function(rotation){
		$C.canvas.rotate(rotation)
	},

	/**
	 * Alias of canvas.fillRect (filled rectangle)
	 * @param {Number} x X-coord of the top-left corner
	 * @param {Number} y Y-coord of the top-left corner
	 * @param {Number} w Width of the rectangle
	 * @param {Number} h Height of the rectangle
	 */
	rect: function(x, y, w, h){
		$C.canvas.fillRect(x, y, w, h)
	},

	/**
	 * Alias of canvas.strokeRect (unfilled rectangle
	 * @param {Number} x X-coord of the top-left corner
	 * @param {Number} y Y-coord of the top-left corner
	 * @param {Number} w Width of the rectangle
	 * @param {Number} h Height of the rectangle

	 */
	stroke_rect: function(x, y, w, h){
		$C.canvas.strokeRect(x, y, w, h)
	},

	/**
	 * Alias of canvas.strokeStyle
	 * @param {String} color Color to use for future stroke operations
	 */
	stroke_style: function(color) {
		$C.canvas.strokeStyle = color
	},

	/**
	 * Sets how succesive lines are joined.
	 * @param {String} style Style string - 'round', 'bevel', or 'miter'
	 */
	line_join: function(style) {
		$C.canvas.lineJoin = style
	},

	/**
	 * Sets how the end of a line is styled.
	 * @param {String} style Style string - 'round', 'butt', or 'square'
	 */
	line_cap: function(style) {
		$C.canvas.lineCap = style
	},

	/**
	 * Sets canvas.lineWidth
	 * @param {Number} lineWidth New width, in pixels, to use for stroke
	 *                           operations
	 */
	line_width: function(lineWidth){
		if (parseInt(lineWidth) == 0)
			$C.canvas.lineWidth = 0.0000000001
		else
			$C.canvas.lineWidth = lineWidth
	},

	/**
	 * Alias of canvas.beginPath
	 */
	begin_path: function(){
		$C.canvas.beginPath()
	},

	/**
	 * Alias of canvas.moveTo
	 * @param {Number} x X-coord of location to move to
	 * @param {Number} y Y-coord of location to move to
	 */
	move_to: function(x, y){
		$C.canvas.moveTo(x, y)
	},

	/**
	 * Alias of canvas.lineTo
	 * @param {Number} x X-coord of location to draw line to
	 * @param {Number} y Y-coord of location to draw line to
	 */
	line_to: function(x, y){
		$C.canvas.lineTo(x, y)
	},

	/**
	 * Draws a quadratic curve
	 * @param {Number} cp_x X-coord of control point
	 * @param {Number} cp_y Y-coord of control point
	 * @param {Number} x    X-coord of point to draw to
	 * @param {Number} y    Y-coord of point to draw to
	 * @see
	 *      MDC Docs
	 * @function
	 */
	quadratic_curve_to: function(cp_x, cp_y, x, y){
		$C.canvas.quadraticCurveTo(cp_x, cp_y, x, y)
	},

	/**
	 * Draws a stroke along the current path.
	 * @function
	 */
	stroke: function(){
		$C.canvas.stroke()
	},

	/**
	 * Draws an outlined (dotted, outlined, etc) stroke along the current path.
	 * @function
	 */
	outline: function(color,width){
		$C.save()
		// this should eventually inherit from the master default styles
			$C.stroke_style(color)
			$C.line_width($C.canvas.lineWidth+(width*2))
		$C.canvas.stroke()
		$C.restore()
		$C.canvas.stroke()
	},

	/**
	 * Closes the current path, then fills it.
	 */
	fill: function(){
		$C.canvas.fill()
	},

	/**
	 * Draws an arc
	 * @param {Number} x                   X-coord of circle's center
	 * @param {Number} y                   Y-coord of circle's center
	 * @param {Number} radius              Radius of circle
	 * @param {Number} startAngle          Angle, in radians, from the +x axis to start the arc
	 *                                     from
	 * @param {Number} endAngle            Angle, in radians, from the +x axis to end the arc
	 *                                     at
	 * @param {Boolean} [counterclockwise] If true, arc is drawn counterclockwise. Else, it is
	 *                                     drawn clockwise
	 */
	arc: function(x, y, radius, startAngle, endAngle, counterclockwise){
		$C.canvas.arc(x, y, radius, startAngle, endAngle, counterclockwise)
	},
	/**
	 * Draws text on the canvas. Fonts are not supported in all
	 * broswers.
	 * @param {String} font Font to use
	 * @param {Number} size Size, in pts, of text
	 * @param {Number} x    X-coord to start drawing at
	 * @param {Number} y    Y-coord to start drawing at
	 * @param {String} text Text to draw
	 */
	draw_text: function(font, size, color, x, y, text){
		if ($C.canvas.fillText) {
			$C.canvas.fillStyle = color
			$C.canvas.font = size+'pt ' + font
			$C.canvas.fillText(text, x, y)
		} else {
			$C.canvas.strokeStyle = color
			$C.canvas.drawText(font, size, x, y, text)
		}
	},
	/**
	 * Measures the width, in pixels, that the text will be
	 * @param {Object} font Font that will be drawn with
	 * @param {Object} size Size, in pts, of text
	 * @param {Object} text Text to be measured
	 */
	measure_text: function(font, size, text) {
		if ($C.canvas.fillText) {
			$C.canvas.font = size + 'pt ' + font
			var width = $C.canvas.measureText(text)
			// some browsers return TextMetrics
			if (width.width) return width.width
			return width
		}
		else {
			$C.canvas.measureCanvasText(font, size, text)
		}

	},
	/**
	 * Sets the canvas' globalAlpha.
	 * @param {Number} alpha New alpha value, between 0 and 1.
	 */
	opacity: function(alpha) {
		$C.canvas.globalAlpha = alpha
	},
	/**
	 * Saves the state of the canvas
	 * @see $C.restore
	 */
	save: function() {
		$C.canvas.save()
	},
	/**
	 * Restores the canvas its last saved state.
	 * @see $C.save
	 */
	restore: function() {
		$C.canvas.restore()
	},
	/**
	 * Return a url that contains all the data in the canvas. Essentially,
	 * it is a link to an image of the canvas.
	 * @return Data url
	 * @type String
	 */
	to_data_url: function() {
		return $C.canvas.canvas.toDataURL()
	},
	/**
	 * Identical to to_data_url, but produces an image much larger than the screen, for print quality
	 * @param {Number} width Width of resulting image in pixels
	 * @param {Number} height Height of resulting image in pixels
	 * @return Data url
	 * @type String
	 */
	to_print_data_url: function(width,height) {
		var _height = Glop.height, _width = Glop.width
		Glop.width = width
		Glop.height = height
		Glop.draw(true) // with a custom size
		var url = $C.canvas.canvas.toDataURL()
		Glop.width = _width
		Glop.height = _height
		return url
	}
}

document.observe('cartagen:init', $C.init.bindAsEventListener($C))
<commit_msg>Fix labels in browsers using non-native canvas text (issue 38)<commit_after>/**
 * @namespace Cavas functions, wapped into shorter, simpler names and abstracted for cross-browser
 *            compatability
 * @see
 *      MDC Docs
 */
$C = {
	/**
	 * Loads the canvas and its rendering context.
	 */
	init: function() {
		/**
		 * The 2d rendering context of the canvas
		 * @type CanvasRenderingContext2D
		 */
		this.canvas =  $('canvas').getContext('2d')
		CanvasTextFunctions.enable(this.canvas)
	},
	/**
	 * Clears the canvas
	 */
	clear: function(){
		$C.canvas.clearRect(0, 0, Glop.width, Glop.height)
	},

	/**
	 * Sets canvas.fillStyle
	 * @param {String} color Color to use for future fill operations
	 */
	fill_style: function(color) {
		$C.canvas.fillStyle = color
	},
	/**
	 * Sets the fill style of the canvas to a pattern.
	 * @param {Image}  image  Image to use for pattern
	 * @param {String} repeat How to repeat pattern - "repeat", "repeat-x", "repeat-y", or
	 *                        "no-repeat"
	 */
	fill_pattern: function(image, repeat) {
		// this seems to often fail, so wrapped in a try:
		try { $C.canvas.fillStyle = $C.canvas.createPattern(image, repeat) } catch(e) {}
	},
	/**
	 * Alias of canvas.translate
	 * @param {Number} x Number of pixels to tranlate in the x direction
	 * @param {Number} y Number of pixels to tranlate in the y direction
	 */
	translate: function(x,y) {
		$C.canvas.translate(x,y)
	},

	/**
	 * Alias of canvas.scale
	 * @param {Number} x Number of pixels to stretch/shring in the x
	 *                   direction
	 * @param {Number} y Number of pixels to stretch/shring in the y
	 *                   direction
	 */
	scale: function(x,y) {
		$C.canvas.scale(x,y)
	},

	/**
	 * Alias of canvas.rotate
	 * @param {Number} rotation Amount, in radians, to rotate
	 */
	rotate: function(rotation){
		$C.canvas.rotate(rotation)
	},

	/**
	 * Alias of canvas.fillRect (filled rectangle)
	 * @param {Number} x X-coord of the top-left corner
	 * @param {Number} y Y-coord of the top-left corner
	 * @param {Number} w Width of the rectangle
	 * @param {Number} h Height of the rectangle
	 */
	rect: function(x, y, w, h){
		$C.canvas.fillRect(x, y, w, h)
	},

	/**
	 * Alias of canvas.strokeRect (unfilled rectangle
	 * @param {Number} x X-coord of the top-left corner
	 * @param {Number} y Y-coord of the top-left corner
	 * @param {Number} w Width of the rectangle
	 * @param {Number} h Height of the rectangle

	 */
	stroke_rect: function(x, y, w, h){
		$C.canvas.strokeRect(x, y, w, h)
	},

	/**
	 * Alias of canvas.strokeStyle
	 * @param {String} color Color to use for future stroke operations
	 */
	stroke_style: function(color) {
		$C.canvas.strokeStyle = color
	},

	/**
	 * Sets how succesive lines are joined.
	 * @param {String} style Style string - 'round', 'bevel', or 'miter'
	 */
	line_join: function(style) {
		$C.canvas.lineJoin = style
	},

	/**
	 * Sets how the end of a line is styled.
	 * @param {String} style Style string - 'round', 'butt', or 'square'
	 */
	line_cap: function(style) {
		$C.canvas.lineCap = style
	},

	/**
	 * Sets canvas.lineWidth
	 * @param {Number} lineWidth New width, in pixels, to use for stroke
	 *                           operations
	 */
	line_width: function(lineWidth){
		if (parseInt(lineWidth) == 0)
			$C.canvas.lineWidth = 0.0000000001
		else
			$C.canvas.lineWidth = lineWidth
	},

	/**
	 * Alias of canvas.beginPath
	 */
	begin_path: function(){
		$C.canvas.beginPath()
	},

	/**
	 * Alias of canvas.moveTo
	 * @param {Number} x X-coord of location to move to
	 * @param {Number} y Y-coord of location to move to
	 */
	move_to: function(x, y){
		$C.canvas.moveTo(x, y)
	},

	/**
	 * Alias of canvas.lineTo
	 * @param {Number} x X-coord of location to draw line to
	 * @param {Number} y Y-coord of location to draw line to
	 */
	line_to: function(x, y){
		$C.canvas.lineTo(x, y)
	},

	/**
	 * Draws a quadratic curve
	 * @param {Number} cp_x X-coord of control point
	 * @param {Number} cp_y Y-coord of control point
	 * @param {Number} x    X-coord of point to draw to
	 * @param {Number} y    Y-coord of point to draw to
	 * @see
	 *      MDC Docs
	 * @function
	 */
	quadratic_curve_to: function(cp_x, cp_y, x, y){
		$C.canvas.quadraticCurveTo(cp_x, cp_y, x, y)
	},

	/**
	 * Draws a stroke along the current path.
	 * @function
	 */
	stroke: function(){
		$C.canvas.stroke()
	},

	/**
	 * Draws an outlined (dotted, outlined, etc) stroke along the current path.
	 * @function
	 */
	outline: function(color,width){
		$C.save()
		// this should eventually inherit from the master default styles
			$C.stroke_style(color)
			$C.line_width($C.canvas.lineWidth+(width*2))
		$C.canvas.stroke()
		$C.restore()
		$C.canvas.stroke()
	},

	/**
	 * Closes the current path, then fills it.
	 */
	fill: function(){
		$C.canvas.fill()
	},

	/**
	 * Draws an arc
	 * @param {Number} x                   X-coord of circle's center
	 * @param {Number} y                   Y-coord of circle's center
	 * @param {Number} radius              Radius of circle
	 * @param {Number} startAngle          Angle, in radians, from the +x axis to start the arc
	 *                                     from
	 * @param {Number} endAngle            Angle, in radians, from the +x axis to end the arc
	 *                                     at
	 * @param {Boolean} [counterclockwise] If true, arc is drawn counterclockwise. Else, it is
	 *                                     drawn clockwise
	 */
	arc: function(x, y, radius, startAngle, endAngle, counterclockwise){
		$C.canvas.arc(x, y, radius, startAngle, endAngle, counterclockwise)
	},
	/**
	 * Draws text on the canvas. Fonts are not supported in all
	 * broswers.
	 * @param {String} font Font to use
	 * @param {Number} size Size, in pts, of text
	 * @param {Number} x    X-coord to start drawing at
	 * @param {Number} y    Y-coord to start drawing at
	 * @param {String} text Text to draw
	 */
	draw_text: function(font, size, color, x, y, text){
		if ($C.canvas.fillText) {
			$C.canvas.fillStyle = color
			$C.canvas.font = size+'pt ' + font
			$C.canvas.fillText(text, x, y)
		} else {
			$C.canvas.strokeStyle = color
			$C.canvas.drawText(font, size, x, y, text)
		}
	},
	/**
	 * Measures the width, in pixels, that the text will be
	 * @param {Object} font Font that will be drawn with
	 * @param {Object} size Size, in pts, of text
	 * @param {Object} text Text to be measured
	 */
	measure_text: function(font, size, text) {
		if ($C.canvas.fillText) {
			$C.canvas.font = size + 'pt ' + font
			var width = $C.canvas.measureText(text)
			// some browsers return TextMetrics
			if (width.width) return width.width
			return width
		}
		else {
			return $C.canvas.measureCanvasText(font, size, text)
		}

	},
	/**
	 * Sets the canvas' globalAlpha.
	 * @param {Number} alpha New alpha value, between 0 and 1.
	 */
	opacity: function(alpha) {
		$C.canvas.globalAlpha = alpha
	},
	/**
	 * Saves the state of the canvas
	 * @see $C.restore
	 */
	save: function() {
		$C.canvas.save()
	},
	/**
	 * Restores the canvas its last saved state.
	 * @see $C.save
	 */
	restore: function() {
		$C.canvas.restore()
	},
	/**
	 * Return a url that contains all the data in the canvas. Essentially,
	 * it is a link to an image of the canvas.
	 * @return Data url
	 * @type String
	 */
	to_data_url: function() {
		return $C.canvas.canvas.toDataURL()
	},
	/**
	 * Identical to to_data_url, but produces an image much larger than the screen, for print quality
	 * @param {Number} width Width of resulting image in pixels
	 * @param {Number} height Height of resulting image in pixels
	 * @return Data url
	 * @type String
	 */
	to_print_data_url: function(width,height) {
		var _height = Glop.height, _width = Glop.width
		Glop.width = width
		Glop.height = height
		Glop.draw(true) // with a custom size
		var url = $C.canvas.canvas.toDataURL()
		Glop.width = _width
		Glop.height = _height
		return url
	}
}

document.observe('cartagen:init', $C.init.bindAsEventListener($C))
<|endoftext|>


<commit_before>/**
 *  API for DB Collection objects
 *
 *
 * @fileOverview dbutil.js - 10gen Database Collection  API
 * @name 10gen Database Collection API
 */

 /**
  * Database collection  API
 *  @class 10gen Database Collection  API
 * @docmodule system.database.collection
 */
 var DBCollection = function(){}

/**
 *
Drop all indexes on the specified collection.

 *
 *
Note : alpha: space is not reclaimed.

 *
 *
Note : When you drop an index, any open cursors for the collection are
 *            invalidated (even if those cursors use a different index.

 *
 * @return A result object.  result.ok will be true if successful.
 */
DBCollection.prototype.dropIndexes = function() {
    var res = this._dbCommand( { deleteIndexes: this.getName(), index: "*" } );
    if( res && res.ok && res.ok == 1 ) {
	// this.getDB().system.indexes.remove( { ns: this.getFullName() } );
	// this.getDB().system.namespaces.remove( { name: RegExp(this.getFullName() + "[.][$].*") } );
    }

    this.resetIndexCache();

    return res;
}

/**
 *
Drop a specified index.

 *
 *

 * Name is the name of the index in the system.indexes name field. (Run db.system.indexes.find() to
 *  see example data.)
 *

 *
 *
Note :  alpha: space is not reclaimed

 * @param {String} name of index to delete.
 * @return A result object.  result.ok will be true if successful.
 */
 DBCollection.prototype.dropIndex =  function(index) {
    assert(index);

    if ( ! isString( index ) && isObject( index ) )
    	index = this.genIndexName( index );

    var res = this._dbCommand( { deleteIndexes: this.getName(), index: index } );
    if( res && res.ok && res.ok == 1 ) {
        //this.getDB().system.indexes.remove( { ns: this.getFullName(), name: index } );
	//this.getDB().system.namespaces.remove( { name: this.getFullName() + ".$"+index } );
    }

    this.resetIndexCache();

    return res;
}

/**
 *

 *    Returns an array of the indexes for the collection.
 *

 *

 *   Each entry in the array is an index descriptor object than contains the
 *   following properties :
 *

 *

 *
 name : name of the index

 *
 ns : name of the namespace the index is in

 *
 key : object property that's being indexed

 *

 *
 *   @return database cursor of index descriptor objects
 */
DBCollection.prototype.getIndexes = function(){
    return this.getDB().system.indexes.find( { ns : this.getFullName() } );
}

/**
 *

 *   Re-indexes the collection
 *

 */
DBCollection.prototype.reIndex = function(){

    var coll = this;

    var all = this.getDB().system.indexes.find( { ns : this.getFullName() } ).toArray();

    all.forEach(
        function(z){
            print( z.name );
            coll._dbCommand( { clean: coll + ".$" + z.name } );
            coll.dropIndex( z.name );
            coll.ensureIndex( z.key );
        }
    );
}

/**
 * clean the collection AND all of its indexes
 * note: prints output to the console.
 */
DBCollection.prototype.cleanAll = function(){
    var coll = this;
    print("cleaning " + coll);
    print( tojson( coll.clean() ) );
    var all = this.getDB().system.indexes.find( { ns : this.getFullName() } ).toArray();
    all.forEach(
        function(z){
	    var idx = coll + ".$" + z.name;
	    print("cleaning " + idx);
	    // print("db: " + coll.getDB());
	    print( tojson(coll.getDB()[idx].clean()) );
        }
    );
}

/**
 * Validate the data in a collection, returning some stats.
 * @return An object with several fields set including:
 *

 *
result : textual description of the validation result

 *
ok : true if validate operation was performed

 *
valid : true if the collection is not corrupt

 *

 */
DBCollection.prototype.validate = function() {
    var res = this._dbCommand( { validate: this.getName() } );

    res.valid = false;

    if ( res.result ){
        var str = "-" + tojson( res.result );
        res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) );

        var p = /lastExtentSize:(\d+)/;
        var r = p.exec( str );
        if ( r ){
            res.lastExtentSize = parseNumber( r[1] );
        }
    }

    return res;
}

/**
 *
drops all objects in the collection

 *
Note :  alpha: space not reclaimed.

 *
 * @return A result object.  result.ok will be true if successful.
 */
DBCollection.prototype.drop = function()
{
    var res = this.dropIndexes();
    if( !res )
	return res;
    if( !res.ok ) {
	res.errmsg = "dropping indexes..." + res.errmsg;
	return res;
    }

    res = this._dbCommand( { drop: this.getName() } );
    if( res && res.ok && res.ok == 1 ) {
	/* note: database does this now.
	   this.getDB().system.namespaces.remove( { name: this.getFullName() } );
	*/
    }
    return res;
}

/**
 *  Drop free lists. Normally not used.
 *  Note this only does the collection itself, not the namespaces of its indexes (see cleanAll).
 */
DBCollection.prototype.clean = function() {
    return this._dbCommand( { clean: this.getName() } );
}

/**
 *

 *  count # of objects in a collection
 *

 *
 *
  You can specify a filter for counting through the optional  parameter.
 *        This parameter specifies condition that must be true for the objects to
 *        be counted.
 *

 *
Example:

 *
 *   c = count({active:true});
 *
 * @param {Object} query Optional query to use to filter objects for counting
 * @return number of objects in the collection that optionally match the filter condition
 */
DBCollection.prototype.count = function(query) {
    var cmd = { count: this.getName() };
    if( query ) cmd.query = query;
    var res = this._dbCommand( cmd );
    if( res && res.n != null ) return res.n;
    throw { exception: "count failed", res: res };
}

/* Run the specified database "command" object.
*/
DBCollection.prototype._dbCommand = function( cmdObj ) {
    return this.getDB().$cmd.findOne(cmdObj);
}

/**
 *

 * Append elements to existing objects in the collection.
 *

 *
 * @param {Object} criteria - query to match
 * @param {Object} fields - fields to append
 */
DBCollection.prototype.append = function(criteria, fields) {
    assert( criteria );
    assert( fields );
    var coll = this.getName();
    return this.getDB().eval(
	function() {
            var start = (new Date()).getTime();
	    var n = 0;
	    var f = fields;
	    db[coll].find(criteria).forEach(
		function(o) {
		    Object.extend(o, f);
		    db[coll].save(o);
		    n++;
		} );
            print( "append time : " + ( (new Date()).getTime() - start ) );
	    return n;
	}
    );
}

/**
 *

 *  Calculate a checksum for all objects in this collection.
 *

 */
DBCollection.prototype.checksum = function(){
    var r = this.getDB().eval(
        function(){
	    var sum = 0;
	    var c = db[args[0]].find();
	    while ( c.hasNext() ){
		sum += c.next().hashCode();
	    }

	    var c = db.system.indexes.find( { ns : args[1] } );

	    while(c.hasNext()) {
	      	sum += c.next().hashCode();
	    }

    	    return sum;
        } ,
        this.getName(), this.getFullName()
    );
    return r;
}

DBCollection.prototype.sample = function( num , query , fields ){
    var r = this.getDB().eval(
        function(){
            var a = db[args[0]].find( args[2] || {} , args[3] ).limit(10000).toArray();
            a.shuffle();
            return a.splice( 0 , args[1] );
        } ,
        this.getName() , num , query , fields
    );
    var a = [];
    for ( var k in r ){
        a.push( r[k] );
    }
    return a;
}

var mydb  = arguments[0];

if (!mydb) {
       throw "Error : no db object passed to augmentor for Collection";
}

Object.extend( mydb.getCollectionPrototype() , DBCollection.prototype );

return null;

//
//  other stuff
//

/**
 *  RESET - FOLLOWING IS FOR DOCUMENTATION PURPOSES ONLY
 */
DBCollection.prototype = {};

/**
 *
Returns the name of the collection.

 *
 * @return {String} Name of the collection
 */
DBCollection.prototype.name = function() {
    throw {exception : "Native Call name() : shouldn't have JS implementation"};
}

//       _entries.put( "base" , _base.getName() );

 /**
 *

 * Saves an object in the collection, or update if the object (as identified by _id)
 * is already there.
 *

 *
 *

 * If your object has a presave $TODO_DOC method, that method will be called
 * before the object is saved to the db (before both updates and inserts).
 *

 * @return SOMETHING_FIXME
 */
DBCollection.prototype.save = function(obj) {
    throw {exception : "Native Call save() : shouldn't have JS implementation"};
}

 /**
 *

 * Update an object in the database, based on supplied query criteria and options.  Normally
 * you should just use the save() method.
 *

 *

 * Current options include :
 *

 *

 *
upsert:true - perform an update if exists, or insert new if doesn't exist

 *
ids : false - do not add an object _id field

 *

 *
 *

 * Example :
 *

 * db.myColl.update( { name: "Joe" }, { name: "Joe", age: 20 }, { upsert: true } );
 *
 *
 @see  http://admin.10gen.com/wiki/pub.db.update

 *
 * @param {Object} criteria  query which selects the record @TODO{more than one?} to update
 * @param {Object} obj  updated object
 * @param {Object} options  optional options object to use in the update
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.update = function(criteria, obj, options) {
    throw {exception : "Native Call update() : shouldn't have JS implementation"};
}

 /**
 *

 * Removes all objects from the collection that match the optional criteria.
 *

 *

 * Example :
 *

 * db.myColl.remove( { name: "Joe" });
 *
 * @param {Object} criteria  query which selects the records  to be removed from the collection
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.remove = function(criteria) {
    throw {exception : "Native Call remove() : shouldn't have JS implementation"};
}

/**
 *

 *    @TODO - does something
 *

 *
 *   @param {Object} obj obj to apply
 *   @return SOMETHING_FIXME
 */
DBCollection.prototype.apply = function(obj) {
    throw {exception : "Native Call apply() : shouldn't have JS implementation"};
}

/**
 *

 *    Finds one or more objects in the collection based on the optional specified criteria.
 *

 *
 *

 *   Example :
 *

 *   db.blogposts.find();
 *

 *   db.blogposts.find({title : /10gen/} );
 *

 *   In addition to the criteria, a field selector may be applied to limit the fields that
 *   are returned in the objects.
 *

 *

 *   Example :
 *

 *   db.blogposts.find({}, {comments:true});
 *
 *

 *   The Cursor returned by find can have modifiers applied for more advanced functionalty.
 *   See @see $TODO-LINK_TO_CURSOR_DOC for more informatiion.
 *

 *   @param {Object} criteria Optional criteria for selection of object(s) to be returned
 *   @param {Object} selector Optional selector to specify the fields that should be returned in each object
 *   @return {Cursor} Cursor for the found object set
 */
DBCollection.prototype.find = function(criteria, selector) {
    throw {exception : "Native Call find() : shouldn't have JS implementation"};
}

/**
 *

 *    Finds a single objects in the collection based on the specified criteria.
 *

 *
 *

 *   Example :
 *

 *   db.blogposts.findOne({title : /10gen/} );
 *   @param {Object} criteria Criteria for selection of object to be returned
 *   @return {Object} Found object or null if no objects match the criteria
 */
DBCollection.prototype.findOne = function(criteria) {
    throw {exception : "Native Call findOne(): shouldn't have JS implementation"};
}

/**
 *

 *    Returns a JSON representation of the collection.
 *
 *   @return {String} JSON representation of the collection
 */
DBCollection.prototype.tojson = function() {
    throw {exception : "Native Call tojson() : shouldn't have JS implementation"};
}
<commit_msg>append -> extend<commit_after>/**
 *  API for DB Collection objects
 *
 *
 * @fileOverview dbutil.js - 10gen Database Collection  API
 * @name 10gen Database Collection API
 */

 /**
  * Database collection  API
 *  @class 10gen Database Collection  API
 * @docmodule system.database.collection
 */
 var DBCollection = function(){}

/**
 *
Drop all indexes on the specified collection.

 *
 *
Note : alpha: space is not reclaimed.

 *
 *
Note : When you drop an index, any open cursors for the collection are
 *            invalidated (even if those cursors use a different index.

 *
 * @return A result object.  result.ok will be true if successful.
 */
DBCollection.prototype.dropIndexes = function() {
    var res = this._dbCommand( { deleteIndexes: this.getName(), index: "*" } );
    if( res && res.ok && res.ok == 1 ) {
	// this.getDB().system.indexes.remove( { ns: this.getFullName() } );
	// this.getDB().system.namespaces.remove( { name: RegExp(this.getFullName() + "[.][$].*") } );
    }

    this.resetIndexCache();

    return res;
}

/**
 *
Drop a specified index.

 *
 *

 * Name is the name of the index in the system.indexes name field. (Run db.system.indexes.find() to
 *  see example data.)
 *

 *
 *
Note :  alpha: space is not reclaimed

 * @param {String} name of index to delete.
 * @return A result object.  result.ok will be true if successful.
 */
 DBCollection.prototype.dropIndex =  function(index) {
    assert(index);

    if ( ! isString( index ) && isObject( index ) )
    	index = this.genIndexName( index );

    var res = this._dbCommand( { deleteIndexes: this.getName(), index: index } );
    if( res && res.ok && res.ok == 1 ) {
        //this.getDB().system.indexes.remove( { ns: this.getFullName(), name: index } );
	//this.getDB().system.namespaces.remove( { name: this.getFullName() + ".$"+index } );
    }

    this.resetIndexCache();

    return res;
}

/**
 *

 *    Returns an array of the indexes for the collection.
 *

 *

 *   Each entry in the array is an index descriptor object than contains the
 *   following properties :
 *

 *

 *
 name : name of the index

 *
 ns : name of the namespace the index is in

 *
 key : object property that's being indexed

 *

 *
 *   @return database cursor of index descriptor objects
 */
DBCollection.prototype.getIndexes = function(){
    return this.getDB().system.indexes.find( { ns : this.getFullName() } );
}

/**
 *

 *   Re-indexes the collection
 *

 */
DBCollection.prototype.reIndex = function(){

    var coll = this;

    var all = this.getDB().system.indexes.find( { ns : this.getFullName() } ).toArray();

    all.forEach(
        function(z){
            print( z.name );
            coll._dbCommand( { clean: coll + ".$" + z.name } );
            coll.dropIndex( z.name );
            coll.ensureIndex( z.key );
        }
    );
}

/**
 * clean the collection AND all of its indexes
 * note: prints output to the console.
 */
DBCollection.prototype.cleanAll = function(){
    var coll = this;
    print("cleaning " + coll);
    print( tojson( coll.clean() ) );
    var all = this.getDB().system.indexes.find( { ns : this.getFullName() } ).toArray();
    all.forEach(
        function(z){
	    var idx = coll + ".$" + z.name;
	    print("cleaning " + idx);
	    // print("db: " + coll.getDB());
	    print( tojson(coll.getDB()[idx].clean()) );
        }
    );
}

/**
 * Validate the data in a collection, returning some stats.
 * @return An object with several fields set including:
 *

 *
result : textual description of the validation result

 *
ok : true if validate operation was performed

 *
valid : true if the collection is not corrupt

 *

 */
DBCollection.prototype.validate = function() {
    var res = this._dbCommand( { validate: this.getName() } );

    res.valid = false;

    if ( res.result ){
        var str = "-" + tojson( res.result );
        res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) );

        var p = /lastExtentSize:(\d+)/;
        var r = p.exec( str );
        if ( r ){
            res.lastExtentSize = parseNumber( r[1] );
        }
    }

    return res;
}

/**
 *
drops all objects in the collection

 *
Note :  alpha: space not reclaimed.

 *
 * @return A result object.  result.ok will be true if successful.
 */
DBCollection.prototype.drop = function()
{
    var res = this.dropIndexes();
    if( !res )
	return res;
    if( !res.ok ) {
	res.errmsg = "dropping indexes..." + res.errmsg;
	return res;
    }

    res = this._dbCommand( { drop: this.getName() } );
    if( res && res.ok && res.ok == 1 ) {
	/* note: database does this now.
	   this.getDB().system.namespaces.remove( { name: this.getFullName() } );
	*/
    }
    return res;
}

/**
 *  Drop free lists. Normally not used.
 *  Note this only does the collection itself, not the namespaces of its indexes (see cleanAll).
 */
DBCollection.prototype.clean = function() {
    return this._dbCommand( { clean: this.getName() } );
}

/**
 *

 *  count # of objects in a collection
 *

 *
 *
  You can specify a filter for counting through the optional  parameter.
 *        This parameter specifies condition that must be true for the objects to
 *        be counted.
 *

 *
Example:

 *
 *   c = count({active:true});
 *
 * @param {Object} query Optional query to use to filter objects for counting
 * @return number of objects in the collection that optionally match the filter condition
 */
DBCollection.prototype.count = function(query) {
    var cmd = { count: this.getName() };
    if( query ) cmd.query = query;
    var res = this._dbCommand( cmd );
    if( res && res.n != null ) return res.n;
    throw { exception: "count failed", res: res };
}

/* Run the specified database "command" object.
*/
DBCollection.prototype._dbCommand = function( cmdObj ) {
    return this.getDB().$cmd.findOne(cmdObj);
}

/**
 *

 * Append elements to existing objects in the collection.
 *

 *
 * @param {Object} criteria - query to match
 * @param {Object} fields - fields to append
 */
DBCollection.prototype.extend = function(criteria, fields) {
    assert( criteria );
    assert( fields );
    var coll = this.getName();
    return this.getDB().eval(
	function() {
	    var n = 0;
	    var f = fields;
	    db[coll].find(criteria).forEach(
		function(o) {
		    Object.extend(o, f);
		    db[coll].save(o);
		    n++;
		} );
	    return n;
	}
    );
}

/**
 *

 *  Calculate a checksum for all objects in this collection.
 *

 */
DBCollection.prototype.checksum = function(){
    var r = this.getDB().eval(
        function(){
	    var sum = 0;
	    var c = db[args[0]].find();
	    while ( c.hasNext() ){
		sum += c.next().hashCode();
	    }

	    var c = db.system.indexes.find( { ns : args[1] } );

	    while(c.hasNext()) {
	      	sum += c.next().hashCode();
	    }

    	    return sum;
        } ,
        this.getName(), this.getFullName()
    );
    return r;
}

DBCollection.prototype.sample = function( num , query , fields ){
    var r = this.getDB().eval(
        function(){
            var a = db[args[0]].find( args[2] || {} , args[3] ).limit(10000).toArray();
            a.shuffle();
            return a.splice( 0 , args[1] );
        } ,
        this.getName() , num , query , fields
    );
    var a = [];
    for ( var k in r ){
        a.push( r[k] );
    }
    return a;
}

var mydb  = arguments[0];

if (!mydb) {
       throw "Error : no db object passed to augmentor for Collection";
}

Object.extend( mydb.getCollectionPrototype() , DBCollection.prototype );

return null;

//
//  other stuff
//

/**
 *  RESET - FOLLOWING IS FOR DOCUMENTATION PURPOSES ONLY
 */
DBCollection.prototype = {};

/**
 *
Returns the name of the collection.

 *
 * @return {String} Name of the collection
 */
DBCollection.prototype.name = function() {
    throw {exception : "Native Call name() : shouldn't have JS implementation"};
}

//       _entries.put( "base" , _base.getName() );

 /**
 *

 * Saves an object in the collection, or update if the object (as identified by _id)
 * is already there.
 *

 *
 *

 * If your object has a presave $TODO_DOC method, that method will be called
 * before the object is saved to the db (before both updates and inserts).
 *

 * @return SOMETHING_FIXME
 */
DBCollection.prototype.save = function(obj) {
    throw {exception : "Native Call save() : shouldn't have JS implementation"};
}

 /**
 *

 * Update an object in the database, based on supplied query criteria and options.  Normally
 * you should just use the save() method.
 *

 *

 * Current options include :
 *

 *

 *
upsert:true - perform an update if exists, or insert new if doesn't exist

 *
ids : false - do not add an object _id field

 *

 *
 *

 * Example :
 *

 * db.myColl.update( { name: "Joe" }, { name: "Joe", age: 20 }, { upsert: true } );
 *
 *
 @see  http://admin.10gen.com/wiki/pub.db.update

 *
 * @param {Object} criteria  query which selects the record @TODO{more than one?} to update
 * @param {Object} obj  updated object
 * @param {Object} options  optional options object to use in the update
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.update = function(criteria, obj, options) {
    throw {exception : "Native Call update() : shouldn't have JS implementation"};
}

 /**
 *

 * Removes all objects from the collection that match the optional criteria.
 *

 *

 * Example :
 *

 * db.myColl.remove( { name: "Joe" });
 *
 * @param {Object} criteria  query which selects the records  to be removed from the collection
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.remove = function(criteria) {
    throw {exception : "Native Call remove() : shouldn't have JS implementation"};
}

/**
 *

 *    @TODO - does something
 *

 *
 *   @param {Object} obj obj to apply
 *   @return SOMETHING_FIXME
 */
DBCollection.prototype.apply = function(obj) {
    throw {exception : "Native Call apply() : shouldn't have JS implementation"};
}

/**
 *

 *    Finds one or more objects in the collection based on the optional specified criteria.
 *

 *
 *

 *   Example :
 *

 *   db.blogposts.find();
 *

 *   db.blogposts.find({title : /10gen/} );
 *

 *   In addition to the criteria, a field selector may be applied to limit the fields that
 *   are returned in the objects.
 *

 *

 *   Example :
 *

 *   db.blogposts.find({}, {comments:true});
 *
 *

 *   The Cursor returned by find can have modifiers applied for more advanced functionalty.
 *   See @see $TODO-LINK_TO_CURSOR_DOC for more informatiion.
 *

 *   @param {Object} criteria Optional criteria for selection of object(s) to be returned
 *   @param {Object} selector Optional selector to specify the fields that should be returned in each object
 *   @return {Cursor} Cursor for the found object set
 */
DBCollection.prototype.find = function(criteria, selector) {
    throw {exception : "Native Call find() : shouldn't have JS implementation"};
}

/**
 *

 *    Finds a single objects in the collection based on the specified criteria.
 *

 *
 *

 *   Example :
 *

 *   db.blogposts.findOne({title : /10gen/} );
 *   @param {Object} criteria Criteria for selection of object to be returned
 *   @return {Object} Found object or null if no objects match the criteria
 */
DBCollection.prototype.findOne = function(criteria) {
    throw {exception : "Native Call findOne(): shouldn't have JS implementation"};
}

/**
 *

 *    Returns a JSON representation of the collection.
 *
 *   @return {String} JSON representation of the collection
 */
DBCollection.prototype.tojson = function() {
    throw {exception : "Native Call tojson() : shouldn't have JS implementation"};
}
<|endoftext|>


<commit_before>/**
 * JsMock - A simple Javascript mocking framework.
 *
 * @author Johannes Fischer (jh-fischer@web.de)
 * @license BSD
 *
 * Copyright (c) 2015 Johannes Fischer
 */
(function () {

  /* constants */
  var _STUB = "STUB"; // Makes a mock behave like a stub
  var _ALL_CALLS = "ALL_INVOCATIONS"; // The scope of the invocations, i.e. exactly(3).returns('foo'); means return 'foo' for all invocations

  /* variables */
  var _shouldMonitorMocks = false;
  var _monitoredMocks = [];

  function _format() {
    var result = arguments[0];

    var i, len = arguments.length;
    for (i = 1; i < len; i++) {
      result = result.replace("{" + (i-1) + "}", arguments[i]);
    }

    return result;
  }

 /**
  * @class ExpectationError
  * @classdesc An ExpectationError will be thrown in any situation where a mock
  * expectation has not been met.
  *
  * @property {string} name The name of the error, will always return 'ExpectationError'.
  * @property {string} message The error message for this error instance.
  * @property {string} stack A string containing the stack trace for this error instance.
  */
  function ExpectationError(message) {
    this.name = 'ExpectationError';
    this.message = 'ExpectationError: ' + (message || 'Unknown expectation failed.');
    this.stack = (new Error()).stack;
  }
  ExpectationError.prototype = Object.create(Error.prototype);
  ExpectationError.prototype.constructor = ExpectationError;

 /**
  * Internal - Instantiated by JsMock.
  *
  * @name Mock
  * @private
  * @class
  *
  * @classdesc The object returned by JsMock.mock representing the mock
  * for a function. The object contains numerous methods to define expectations for the
  * invocations of the mocked function and will match every call of this function
  * against those expectations.
  */
  var MockClass = function (args) {

    var _name = args.name;

    var _scope, _callCount, _expectTotalCalls, _expectations;

    function reset() {
      _scope = null;
      _callCount = 0;
      _expectTotalCalls = 0;
      _expectations = {}; // {args, returnValue, will, fulfilled}
    }

    function verifyScope() {
      if (_scope === null) {
        throw new Error("You must call allowing, exactly, never, once, twice or thrice before setting any other expectations for this mock.");
      }
    }

    function doArgsMatch(expectedArgs, actualArgs) {

      if (expectedArgs === undefined) {
        // Wildcard - any args match
        return true;
      }

      if (expectedArgs.length !== actualArgs.length) {
        return false;
      }

      var i, len = expectedArgs.length;
      for (i = 0; i < len; i++) {
        //TODO: Add support for matchers here
        if (expectedArgs[i] !== actualArgs[i]) {
          return false;
        }
      }

      return true;
    }

    function findMatchingExpectation(actualArguments) {
      //find matching expectation, throw if no expectation is found
      if (_scope === _STUB) {
        var expectation = _expectations[_STUB];
        if (!doArgsMatch(expectation.args, actualArguments)) {
          throw new ExpectationError(_format("Unexpected invocation of '{0}'. Actual arguments: {2}.", _name, index, JSON.stringify(actualArguments)));
        }

        return expectation;
      }

      for (var index in _expectations) {
        var expectation = _expectations[index];

        if (expectation.fulfilled) {
          continue;
        }

        if (!doArgsMatch(expectation.args, actualArguments)) {
          break;
        }

        return expectation;
      }

      throw new ExpectationError(_format("Unexpected invocation of '{0}' for call {1}: actual arguments: {2}.", _name, index, JSON.stringify(actualArguments)));
    }

    function setInScope(propertyName, value) {
      verifyScope();

      if (_scope !== _ALL_CALLS) {
        _expectations[_scope][propertyName] = value;
        return;
      }

      for (var index in _expectations) {
        _expectations[index][propertyName] = value;
      }
    }

    var _thisMock = function evalCall() {
      if (_callCount === _expectTotalCalls) {
        throw new ExpectationError(_format("'{0}' already called {1} time(s).", _name, _expectTotalCalls));
      }

      var actualArguments = Array.prototype.slice.call(arguments);
      var expectation = findMatchingExpectation(actualArguments);

      //execute function if applicable
      if (expectation.will) {
        try {
          expectation.will.apply(null, actualArguments);
        } catch (ex) {
          throw new ExpectationError(_format("Registered action for '{0}' threw an error: {1}.", _name, JSON.stringify(ex)));
        }
      }

      //set fulfilled
      expectation.fulfilled = true;

      _callCount++;

      //return value
      return expectation.returnValue;
    };

    /**
     * Set the expectation for the mock to be called 'x' number of times.
     *
     * @param {number} count The number of times how often this mock is expected to be called.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#exactly
     */
    _thisMock.allowing = function() {
      reset();

      _expectTotalCalls = -1;
      _expectations[_STUB] = {};
      _scope = _STUB;

      return _thisMock;
    };

    /**
     * Set the expectation for the mock to be called 'x' number of times.
     *
     * @param {number} count The number of times how often this mock is expected to be called.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#exactly
     */
    _thisMock.exactly = function(count) {
      if (count < 0) {
        throw new Error("'count' must be 0 or higher");
      }

      reset();

      _scope = _ALL_CALLS;
      _expectTotalCalls = count;

      for (var i = 1; i <= count; i++) {
        _expectations[i] = {};
      }

      return _thisMock;
    };

    /**
     * Will set all following expectations for the given call.
     *
     * @param {number} number The index of the call (starting with 1) where the expectations should be set.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#onCall
     */
    _thisMock.onCall = function (index) {
      if (index < 1) {
        throw new Error("Call index must be larger than 0");
      }

      if (_expectTotalCalls < 0) {
          throw new Error("Mock is set up as a stub. Cannot set expectations for a specific call.");
      }

      if (index > _expectTotalCalls) {
        throw new Error("Attempting to set the behaviour for a call that is not expected. Calls expected: " + _expectTotalCalls + ", call attempted to change: " + index);
      }

      _scope = index;

      return _thisMock;
    };

    /**
     * Expects the function to be called with the given arguments.
     *
     * @param {...?(number|boolean|string|array|object|function)} arguments The index of the call (starting with 1) where the expectations should be set.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#withExactArgs
     */
    _thisMock.withExactArgs = function () {
      setInScope("args", Array.prototype.slice.call(arguments));
      return _thisMock;
    };

    /**
     * Expects the function to be called to return the given value.
     *
     * @param {?(number|boolean|string|array|object|function)} returnValue The value to be returned when the function is invoked.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#returns
     */
    _thisMock.returns = function (returnValue) {
      setInScope("returnValue", returnValue);
      return _thisMock;
    };

    /**
     * Executes a function if the mock was successfully matched. All arguments passed in to the mock function
     * will be passed on to the function defined in here. The function will be executed before a value is returned.
     *
     * @param {!function} func The function to be executed when the expectation is fulfilled.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#will
     */
    _thisMock.will = function (func) {
      // TODO: null check
      setInScope("will", func);
      return _thisMock;
    };

    /**
     * Verifies of all set expectations of this mock are fulfilled. If not, an ExpectationError will be thrown.
     * If the verification passes, the mock will be reset to its original state.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#verify
     */
    _thisMock.verify = function () {
      if (_scope === _STUB) {
        reset();
        return;
      }

      var unfulfilledExpectations = [];
      Object.keys(_expectations).forEach(function(index) {
        var expectation = _expectations[index];

        // TODO: Verify if this code branch can ever be executed. I think missing expectations would always fail in line 249.
        if (!expectation.fulfilled) {
          unfulfilledExpectations.push(_format("Expectation for call {0} with args {1}, will return {2}.", index, JSON.stringify(expectation.args), JSON.stringify(expectation.returnValue)));
        }
      });

      if (unfulfilledExpectations.length > 0) {
        throw new ExpectationError(_format("Missing invocations for {0}: {1}.", _name, JSON.stringify(unfulfilledExpectations))); //TODO: improve message format
      }

      reset();
    };

   /* helpers, i.e. once, twice, onFirstCall, etc */
   /**
    * Alias for exactly(0).
    *
    * @see {@link Mock#exactly}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#never
    */
   _thisMock.never = function () {
     return _thisMock.exactly(0);
   };

    /* helpers, i.e. once, twice, onFirstCall, etc */
    /**
     * Alias for exactly(1).
     *
     * @see {@link Mock#exactly}
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#once
     */
    _thisMock.once = function () {
      return _thisMock.exactly(1);
    };

   /**
    * Alias for exactly(2).
    *
    * @see {@link Mock#exactly}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#twice
    */
    _thisMock.twice = function () {
      return _thisMock.exactly(2);
    };

   /**
    * Alias for exactly(3).
    *
    * @see {@link Mock#exactly}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#thrice
    */
    _thisMock.thrice = function () {
      return _thisMock.exactly(3);
    };

   /**
    * Alias for onCall(1).
    *
    * @see {@link Mock#onCall}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#onFirstCall
    */
    _thisMock.onFirstCall = function () {
      return _thisMock.onCall(1);
    };

   /**
    * Alias for onCall(2).
    *
    * @see {@link Mock#onCall}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#onSecondCall
    */
    _thisMock.onSecondCall = function () {
      return _thisMock.onCall(2);
    };

   /**
    * Alias for onCall(3).
    *
    * @see {@link Mock#onCall}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#onThirdCall
    */
    _thisMock.onThirdCall = function () {
      return _thisMock.onCall(3);
    };

    reset();

    return _thisMock;
  };

  function mock(name) {
    var newMock = new MockClass({
      name: name
    });

    if (_shouldMonitorMocks) {
      _monitoredMocks.push(newMock);
    }

    return newMock;
  }

  function mockProperties(objName, obj) {
    var result = {};
    Object.keys(obj).forEach(function(propertyName) {
      if (typeof obj[propertyName] === "function") {
        result[propertyName] = mock(objName + "." + propertyName);
      } else {
        result[propertyName] = obj[propertyName];
      }
    });

    return result;
  }

 /**
  * JavaScript mocking framework, which can be used with any test framework. JsMock is inspired by jMock and Sinon.js
  * with its interface being very similar to Sinon in order to make it easy to switch between those two frameworks.

  *

  * JsMock does only support mocks where all expectations have to be set prior to making the call to the function under test.

  *
  * @exports js-mock
  */
  var API = {
    /**
     * Creates a mock object for a function.

     *

     * If the objectToBeMocked property is provided, the mockName will be used as a prefix for each mock of the object, while the function name will be the suffix.

     * Only functions of the object will be mocked. Any other types will simply be copied over.
     *
     * @param {string} mockName A named to be used to idenfify this mock object. The name will be include in any thrown {@link ExpectationError}.
     * @param {object=} objectToBeMocked The object to be cloned with mock functions. Only functions will be mocked, any other property values will simply be copied over.
     */
    mock: function (mockName, objectToBeMocked) {
      if (typeof mockName !== "string" || !mockName) {
        throw new TypeError("The first argument must be a string");
      }

      if (typeof objectToBeMocked === "object" && objectToBeMocked !== null) {
        return mockProperties(mockName, objectToBeMocked);
      }

      return mock(mockName);
    },

    /**
     * When testing a module or file, the best way is to define a set of global mocks,
     * which can be shared between the test cases using the JsMock.monitorMocks() function.
     * All mocks created inside the factory function will be added to the current test
     * context and can be verified with a single call to JsMock.assertIfSatisfied().

     *

     * For example:
     *

     *    var mockFunction1, mockFunction2;
     *    JsMock.monitorMocks(function () {
     *      mockFunction1 = JsMock.mock("name1");
     *      mockFunction2 = JsMock.mock("name2");
     *    });
     *

     *
     * @param {function} factoryFunc A function that will create mock objects for the current test context.
     */
    monitorMocks: function (factoryFunc) {
      if (typeof factoryFunc !== "function") {
        throw new TypeError("The first argument must be a function");
      }

      // Clean up monitored mocks so that the same JsMock context can be used between test files
      _monitoredMocks = [];

      try {
        _shouldMonitorMocks = true;
        factoryFunc();
      } finally {
        _shouldMonitorMocks = false;
      }
    },

    /**
     * Verify all mocks registered in the current test context.

     *

     * All mock objects that where created in the factory function of monitorMocks()
     * will be verified and an {@link ExpectationError} will be thrown if any of those
     * mocks fails the verification.
     *
     * @throws {ExpectationError} An error if a mock object in the current test context failed the verification.
     */
    assertIfSatisfied: function () {
      var i, len = _monitoredMocks.length;
      for (i = 0; i < len; i++) {
        _monitoredMocks[i].verify();
      }
    }
  };

  API.ExpectationError = ExpectationError;

  if ( typeof define === "function") {
  	define("js-mock", [], function() {
  		return API;
  	});
  }

  window.JsMock = API;
})();<commit_msg>Fixed linting issues.<commit_after>/**
 * JsMock - A simple Javascript mocking framework.
 *
 * @author Johannes Fischer (jh-fischer@web.de)
 * @license BSD
 *
 * Copyright (c) 2015 Johannes Fischer
 */
(function () {

  /* constants */
  var _STUB = "STUB"; // Makes a mock behave like a stub
  var _ALL_CALLS = "ALL_INVOCATIONS"; // The scope of the invocations, i.e. exactly(3).returns('foo'); means return 'foo' for all invocations

  /* variables */
  var _shouldMonitorMocks = false;
  var _monitoredMocks = [];

  function _format() {
    var result = arguments[0];

    var i, len = arguments.length;
    for (i = 1; i < len; i++) {
      result = result.replace("{" + (i-1) + "}", arguments[i]);
    }

    return result;
  }

 /**
  * @class ExpectationError
  * @classdesc An ExpectationError will be thrown in any situation where a mock
  * expectation has not been met.
  *
  * @property {string} name The name of the error, will always return 'ExpectationError'.
  * @property {string} message The error message for this error instance.
  * @property {string} stack A string containing the stack trace for this error instance.
  */
  function ExpectationError(message) {
    this.name = 'ExpectationError';
    this.message = 'ExpectationError: ' + (message || 'Unknown expectation failed.');
    this.stack = (new Error()).stack;
  }
  ExpectationError.prototype = Object.create(Error.prototype);
  ExpectationError.prototype.constructor = ExpectationError;

 /**
  * Internal - Instantiated by JsMock.
  *
  * @name Mock
  * @private
  * @class
  *
  * @classdesc The object returned by JsMock.mock representing the mock
  * for a function. The object contains numerous methods to define expectations for the
  * invocations of the mocked function and will match every call of this function
  * against those expectations.
  */
  var MockClass = function (args) {

    var _name = args.name;

    var _scope, _callCount, _expectTotalCalls, _expectations;

    function reset() {
      _scope = null;
      _callCount = 0;
      _expectTotalCalls = 0;
      _expectations = {}; // {args, returnValue, will, fulfilled}
    }

    function verifyScope() {
      if (_scope === null) {
        throw new Error("You must call allowing, exactly, never, once, twice or thrice before setting any other expectations for this mock.");
      }
    }

    function doArgsMatch(expectedArgs, actualArgs) {

      if (expectedArgs === undefined) {
        // Wildcard - any args match
        return true;
      }

      if (expectedArgs.length !== actualArgs.length) {
        return false;
      }

      var i, len = expectedArgs.length;
      for (i = 0; i < len; i++) {
        //TODO: Add support for matchers here
        if (expectedArgs[i] !== actualArgs[i]) {
          return false;
        }
      }

      return true;
    }

    function findMatchingExpectation(actualArguments) {
      //find matching expectation, throw if no expectation is found
      if (_scope === _STUB) {
        var stub = _expectations[_STUB];
        if (!doArgsMatch(stub.args, actualArguments)) {
          throw new ExpectationError(_format("Unexpected invocation of '{0}'. Actual arguments: {1}.", _name, JSON.stringify(actualArguments)));
        }

        return stub;
      }

      for (var index in _expectations) {
        var expectation = _expectations[index];

        if (expectation.fulfilled) {
          continue;
        }

        if (!doArgsMatch(expectation.args, actualArguments)) {
          break;
        }

        return expectation;
      }

      throw new ExpectationError(_format("Unexpected invocation of '{0}' for call {1}: actual arguments: {2}.", _name, index, JSON.stringify(actualArguments)));
    }

    function setInScope(propertyName, value) {
      verifyScope();

      if (_scope !== _ALL_CALLS) {
        _expectations[_scope][propertyName] = value;
        return;
      }

      for (var index in _expectations) {
        _expectations[index][propertyName] = value;
      }
    }

    var _thisMock = function evalCall() {
      if (_callCount === _expectTotalCalls) {
        throw new ExpectationError(_format("'{0}' already called {1} time(s).", _name, _expectTotalCalls));
      }

      var actualArguments = Array.prototype.slice.call(arguments);
      var expectation = findMatchingExpectation(actualArguments);

      //execute function if applicable
      if (expectation.will) {
        try {
          expectation.will.apply(null, actualArguments);
        } catch (ex) {
          throw new ExpectationError(_format("Registered action for '{0}' threw an error: {1}.", _name, JSON.stringify(ex)));
        }
      }

      //set fulfilled
      expectation.fulfilled = true;

      _callCount++;

      //return value
      return expectation.returnValue;
    };

    /**
     * Set the expectation for the mock to be called 'x' number of times.
     *
     * @param {number} count The number of times how often this mock is expected to be called.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#exactly
     */
    _thisMock.allowing = function() {
      reset();

      _expectTotalCalls = -1;
      _expectations[_STUB] = {};
      _scope = _STUB;

      return _thisMock;
    };

    /**
     * Set the expectation for the mock to be called 'x' number of times.
     *
     * @param {number} count The number of times how often this mock is expected to be called.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#exactly
     */
    _thisMock.exactly = function(count) {
      if (count < 0) {
        throw new Error("'count' must be 0 or higher");
      }

      reset();

      _scope = _ALL_CALLS;
      _expectTotalCalls = count;

      for (var i = 1; i <= count; i++) {
        _expectations[i] = {};
      }

      return _thisMock;
    };

    /**
     * Will set all following expectations for the given call.
     *
     * @param {number} number The index of the call (starting with 1) where the expectations should be set.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#onCall
     */
    _thisMock.onCall = function (index) {
      if (index < 1) {
        throw new Error("Call index must be larger than 0");
      }

      if (_expectTotalCalls < 0) {
          throw new Error("Mock is set up as a stub. Cannot set expectations for a specific call.");
      }

      if (index > _expectTotalCalls) {
        throw new Error("Attempting to set the behaviour for a call that is not expected. Calls expected: " + _expectTotalCalls + ", call attempted to change: " + index);
      }

      _scope = index;

      return _thisMock;
    };

    /**
     * Expects the function to be called with the given arguments.
     *
     * @param {...?(number|boolean|string|array|object|function)} arguments The index of the call (starting with 1) where the expectations should be set.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#withExactArgs
     */
    _thisMock.withExactArgs = function () {
      setInScope("args", Array.prototype.slice.call(arguments));
      return _thisMock;
    };

    /**
     * Expects the function to be called to return the given value.
     *
     * @param {?(number|boolean|string|array|object|function)} returnValue The value to be returned when the function is invoked.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#returns
     */
    _thisMock.returns = function (returnValue) {
      setInScope("returnValue", returnValue);
      return _thisMock;
    };

    /**
     * Executes a function if the mock was successfully matched. All arguments passed in to the mock function
     * will be passed on to the function defined in here. The function will be executed before a value is returned.
     *
     * @param {!function} func The function to be executed when the expectation is fulfilled.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#will
     */
    _thisMock.will = function (func) {
      // TODO: null check
      setInScope("will", func);
      return _thisMock;
    };

    /**
     * Verifies of all set expectations of this mock are fulfilled. If not, an ExpectationError will be thrown.
     * If the verification passes, the mock will be reset to its original state.
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#verify
     */
    _thisMock.verify = function () {
      if (_scope === _STUB) {
        reset();
        return;
      }

      var unfulfilledExpectations = [];
      Object.keys(_expectations).forEach(function(index) {
        var expectation = _expectations[index];

        // TODO: Verify if this code branch can ever be executed. I think missing expectations would always fail in line 249.
        if (!expectation.fulfilled) {
          unfulfilledExpectations.push(_format("Expectation for call {0} with args {1}, will return {2}.", index, JSON.stringify(expectation.args), JSON.stringify(expectation.returnValue)));
        }
      });

      if (unfulfilledExpectations.length > 0) {
        throw new ExpectationError(_format("Missing invocations for {0}: {1}.", _name, JSON.stringify(unfulfilledExpectations))); //TODO: improve message format
      }

      reset();
    };

   /* helpers, i.e. once, twice, onFirstCall, etc */
   /**
    * Alias for exactly(0).
    *
    * @see {@link Mock#exactly}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#never
    */
   _thisMock.never = function () {
     return _thisMock.exactly(0);
   };

    /* helpers, i.e. once, twice, onFirstCall, etc */
    /**
     * Alias for exactly(1).
     *
     * @see {@link Mock#exactly}
     *
     * @returns {MockClass} This {@link MockClass} instance.
     *
     * @function Mock#once
     */
    _thisMock.once = function () {
      return _thisMock.exactly(1);
    };

   /**
    * Alias for exactly(2).
    *
    * @see {@link Mock#exactly}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#twice
    */
    _thisMock.twice = function () {
      return _thisMock.exactly(2);
    };

   /**
    * Alias for exactly(3).
    *
    * @see {@link Mock#exactly}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#thrice
    */
    _thisMock.thrice = function () {
      return _thisMock.exactly(3);
    };

   /**
    * Alias for onCall(1).
    *
    * @see {@link Mock#onCall}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#onFirstCall
    */
    _thisMock.onFirstCall = function () {
      return _thisMock.onCall(1);
    };

   /**
    * Alias for onCall(2).
    *
    * @see {@link Mock#onCall}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#onSecondCall
    */
    _thisMock.onSecondCall = function () {
      return _thisMock.onCall(2);
    };

   /**
    * Alias for onCall(3).
    *
    * @see {@link Mock#onCall}
    *
    * @returns {MockClass} This {@link MockClass} instance.
    *
    * @function Mock#onThirdCall
    */
    _thisMock.onThirdCall = function () {
      return _thisMock.onCall(3);
    };

    reset();

    return _thisMock;
  };

  function mock(name) {
    var newMock = new MockClass({
      name: name
    });

    if (_shouldMonitorMocks) {
      _monitoredMocks.push(newMock);
    }

    return newMock;
  }

  function mockProperties(objName, obj) {
    var result = {};
    Object.keys(obj).forEach(function(propertyName) {
      if (typeof obj[propertyName] === "function") {
        result[propertyName] = mock(objName + "." + propertyName);
      } else {
        result[propertyName] = obj[propertyName];
      }
    });

    return result;
  }

 /**
  * JavaScript mocking framework, which can be used with any test framework. JsMock is inspired by jMock and Sinon.js
  * with its interface being very similar to Sinon in order to make it easy to switch between those two frameworks.

  *

  * JsMock does only support mocks where all expectations have to be set prior to making the call to the function under test.

  *
  * @exports js-mock
  */
  var API = {
    /**
     * Creates a mock object for a function.

     *

     * If the objectToBeMocked property is provided, the mockName will be used as a prefix for each mock of the object, while the function name will be the suffix.

     * Only functions of the object will be mocked. Any other types will simply be copied over.
     *
     * @param {string} mockName A named to be used to idenfify this mock object. The name will be include in any thrown {@link ExpectationError}.
     * @param {object=} objectToBeMocked The object to be cloned with mock functions. Only functions will be mocked, any other property values will simply be copied over.
     */
    mock: function (mockName, objectToBeMocked) {
      if (typeof mockName !== "string" || !mockName) {
        throw new TypeError("The first argument must be a string");
      }

      if (typeof objectToBeMocked === "object" && objectToBeMocked !== null) {
        return mockProperties(mockName, objectToBeMocked);
      }

      return mock(mockName);
    },

    /**
     * When testing a module or file, the best way is to define a set of global mocks,
     * which can be shared between the test cases using the JsMock.monitorMocks() function.
     * All mocks created inside the factory function will be added to the current test
     * context and can be verified with a single call to JsMock.assertIfSatisfied().

     *

     * For example:
     *

     *    var mockFunction1, mockFunction2;
     *    JsMock.monitorMocks(function () {
     *      mockFunction1 = JsMock.mock("name1");
     *      mockFunction2 = JsMock.mock("name2");
     *    });
     *

     *
     * @param {function} factoryFunc A function that will create mock objects for the current test context.
     */
    monitorMocks: function (factoryFunc) {
      if (typeof factoryFunc !== "function") {
        throw new TypeError("The first argument must be a function");
      }

      // Clean up monitored mocks so that the same JsMock context can be used between test files
      _monitoredMocks = [];

      try {
        _shouldMonitorMocks = true;
        factoryFunc();
      } finally {
        _shouldMonitorMocks = false;
      }
    },

    /**
     * Verify all mocks registered in the current test context.

     *

     * All mock objects that where created in the factory function of monitorMocks()
     * will be verified and an {@link ExpectationError} will be thrown if any of those
     * mocks fails the verification.
     *
     * @throws {ExpectationError} An error if a mock object in the current test context failed the verification.
     */
    assertIfSatisfied: function () {
      var i, len = _monitoredMocks.length;
      for (i = 0; i < len; i++) {
        _monitoredMocks[i].verify();
      }
    }
  };

  API.ExpectationError = ExpectationError;

  if ( typeof define === "function") {
  	define("js-mock", [], function() {
  		return API;
  	});
  }

  window.JsMock = API;
})();<|endoftext|>


<commit_before><commit_msg>Change hotkeys for brush settings<commit_after><|endoftext|>


<commit_before><commit_msg>fixed e2e tests<commit_after><|endoftext|>


<commit_before>var $ = require('jquery');
var ConfigModel = require('../../../../../../../javascripts/cartodb3/data/config-model');
var TileJSONModel = require('../../../../../../../javascripts/cartodb3/components/modals/add-basemap/tilejson/tilejson-model');
var TileJSONView = require('../../../../../../../javascripts/cartodb3/components/modals/add-basemap/tilejson/tilejson-view');
var CustomBaselayersCollection = require('../../../../../../../javascripts/cartodb3/data/custom-baselayers-collection');
var CustomBaselayerModel = require('../../../../../../../javascripts/cartodb3/data/custom-baselayer-model');

describe('components/modals/add-basemap/tilejson/tilejson-view', function () {
  beforeEach(function() {
    spyOn(_, 'debounce').and.callFake(function (func) {
      return function () {
        func.apply(this, arguments);
      };
    });

    var configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.customBaselayersCollection = new CustomBaselayersCollection([{
      id: 'basemap-id-1',
      options: {
        urlTemplate: 'https://a.tiles.mapbox.com/v3/mapbox.geography-class/{z}/{x}/{y}.png',
        category: 'TileJSON',
        className: 'httpsatilesmapboxcomv3mapboxgeographyclasszxypng'
      }
    }], {
      configModel: configModel,
      currentUserId: 'current-user-id'
    });

    this.model = new TileJSONModel(null, {
      customBaselayersCollection: this.customBaselayersCollection
    });

    var submitButton = $('<button class="is-disabled">Submit</button>');
    var modalFooter = $('

');

    this.view = new TileJSONView({
      model: this.model,
      customBaselayersCollection: this.customBaselayersCollection,
      submitButton: submitButton,
      modalFooter: modalFooter
    });
    this.view.render();
  });

  it('should render the set button as disabled initially', function() {
    expect(this.view._submitButton.hasClass('is-disabled')).toBe(true);
  });

  describe('when user written a URL', function () {
    describe('when URL is half-done or invalid', function () {
      beforeEach(function () {
        var $el = this.view.$('.js-url');
        $el.val('ht');
        $el.trigger('keydown');
        $el.val('htt');
        $el.trigger('keydown');
      });

      it('should indicate that it is validating URL', function() {
        expect(this.innerHTML()).toMatch('js-validating.*display: inline');
      });

      describe('when triggers error', function() {
        it('should show error', function () {
          expect(this.view.$('.js-error').attr('class')).toContain('is-visible');
          expect(this.innerHTML()).toContain('components.modals.add-basemap.xyz.not-valid');
        });

        it('should not indicate validating anymore', function() {
          expect(this.innerHTML()).not.toMatch('js-validating.*display: inline');
        });

        it('should disable OK button', function () {
          expect(this.view._submitButton.hasClass('is-disabled')).toBe(true);
        });
      });

      describe('when finally written/pasted a valid URL', function () {
        beforeEach(function () {
          this.layer = new CustomBaselayerModel({
            id: 'basemap-id-2',
            urlTemplate: 'https://b.tiles.mapbox.com/v3/mapbox.geography-class/{z}/{x}/{y}.png',
            attribution: null,
            maxZoom: 21,
            minZoom: 0,
            className: 'httpsbtilesmapboxcomv3mapboxgeographyclasszxypng',
            name: 'Geography Class',
            tms: false,
            category: 'TileJSON',
            type: 'Tiled'
          });
        });

        it('should create layer with url', function() {
          expect(this.model.get('layer')).toBe(this.layer);
        });

        it('should enable save button', function() {
          expect(this.view.$('.js-ok').attr('class')).not.toContain('is-disabled');
        });

        it('should hide error', function() {
          expect(this.view.$('.js-error').attr('class')).not.toContain('is-visible');
        });
      });
    });
  });

  it('should not have any leaks', function() {
    expect(this.view).toHaveNoLeaks();
  });

  afterEach(function() {
    this.view.clean();
  });
});
<commit_msg>linter<commit_after>var _ = require('underscore');
var $ = require('jquery');
var ConfigModel = require('../../../../../../../javascripts/cartodb3/data/config-model');
var TileJSONModel = require('../../../../../../../javascripts/cartodb3/components/modals/add-basemap/tilejson/tilejson-model');
var TileJSONView = require('../../../../../../../javascripts/cartodb3/components/modals/add-basemap/tilejson/tilejson-view');
var CustomBaselayersCollection = require('../../../../../../../javascripts/cartodb3/data/custom-baselayers-collection');
var CustomBaselayerModel = require('../../../../../../../javascripts/cartodb3/data/custom-baselayer-model');

describe('components/modals/add-basemap/tilejson/tilejson-view', function () {
  beforeEach(function () {
    spyOn(_, 'debounce').and.callFake(function (func) {
      return function () {
        func.apply(this, arguments);
      };
    });

    var configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.customBaselayersCollection = new CustomBaselayersCollection([{
      id: 'basemap-id-1',
      options: {
        urlTemplate: 'https://a.tiles.mapbox.com/v3/mapbox.geography-class/{z}/{x}/{y}.png',
        category: 'TileJSON',
        className: 'httpsatilesmapboxcomv3mapboxgeographyclasszxypng'
      }
    }], {
      configModel: configModel,
      currentUserId: 'current-user-id'
    });

    this.model = new TileJSONModel(null, {
      customBaselayersCollection: this.customBaselayersCollection
    });

    var submitButton = $('<button class="is-disabled">Submit</button>');
    var modalFooter = $('

');

    this.view = new TileJSONView({
      model: this.model,
      customBaselayersCollection: this.customBaselayersCollection,
      submitButton: submitButton,
      modalFooter: modalFooter
    });
    this.view.render();
  });

  it('should render the set button as disabled initially', function () {
    expect(this.view._submitButton.hasClass('is-disabled')).toBe(true);
  });

  describe('when user written a URL', function () {
    describe('when URL is half-done or invalid', function () {
      beforeEach(function () {
        var $el = this.view.$('.js-url');
        $el.val('ht');
        $el.trigger('keydown');
        $el.val('htt');
        $el.trigger('keydown');
      });

      it('should indicate that it is validating URL', function () {
        expect(this.innerHTML()).toMatch('js-validating.*display: inline');
      });

      describe('when triggers error', function () {
        it('should show error', function () {
          expect(this.view.$('.js-error').attr('class')).toContain('is-visible');
          expect(this.innerHTML()).toContain('components.modals.add-basemap.xyz.not-valid');
        });

        it('should not indicate validating anymore', function () {
          expect(this.innerHTML()).not.toMatch('js-validating.*display: inline');
        });

        it('should disable OK button', function () {
          expect(this.view._submitButton.hasClass('is-disabled')).toBe(true);
        });
      });

      describe('when finally written/pasted a valid URL', function () {
        beforeEach(function () {
          this.layer = new CustomBaselayerModel({
            id: 'basemap-id-2',
            urlTemplate: 'https://b.tiles.mapbox.com/v3/mapbox.geography-class/{z}/{x}/{y}.png',
            attribution: null,
            maxZoom: 21,
            minZoom: 0,
            className: 'httpsbtilesmapboxcomv3mapboxgeographyclasszxypng',
            name: 'Geography Class',
            tms: false,
            category: 'TileJSON',
            type: 'Tiled'
          });
        });

        it('should create layer with url', function () {
          expect(this.model.get('layer')).toBe(this.layer);
        });

        it('should enable save button', function () {
          expect(this.view.$('.js-ok').attr('class')).not.toContain('is-disabled');
        });

        it('should hide error', function () {
          expect(this.view.$('.js-error').attr('class')).not.toContain('is-visible');
        });
      });
    });
  });

  it('should not have any leaks', function () {
    expect(this.view).toHaveNoLeaks();
  });

  afterEach(function () {
    this.view.clean();
  });
});
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    // if (document.API_KEY !== '') {
    //   return  this.store.findAll("search");
    // }
  },
  actions: {
    toggle: function() {
      Ember.$('.ui.sidebar').sidebar('toggle');
    },
    transitionToSaved: function(search) {
      var query = search.get("query");
      // this.get("container").lookup("route:developments.search").resetController();
      this.transitionTo("/?" + $.param(query));
      this.refresh();
      Ember.$('.ui.modal').modal('hide');
    },
    nameSearch() {
      Ember.$('.ui.modal.save-search').modal('show');
    },
    postSearch() {
      var controller = this.controllerFor("application");
      var developmentsSearch = this.controllerFor("developments.search");
      var query = this.get("container").lookup("route:developments.search").get("storedParams");
      var search = this.store.createRecord("search", { title: controller.get("title"), query: query, saved: true });

      search.save().then(() => {
        controller.set("title", null);
        developmentsSearch.toggleProperty("successfulSave");
      },
      (error) => {
        this.controller.set('error', error)
      });
    },
    deleteSearch(search) {
      search.destroyRecord();
    }
  }
});
<commit_msg>uncommenting some functionality<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    if (document.API_KEY !== '') {
      return  this.store.findAll("search");
    }
  },
  actions: {
    toggle: function() {
      Ember.$('.ui.sidebar').sidebar('toggle');
    },
    transitionToSaved: function(search) {
      var query = search.get("query");
      // this.get("container").lookup("route:developments.search").resetController();
      this.transitionTo("/?" + $.param(query));
      this.refresh();
      Ember.$('.ui.modal').modal('hide');
    },
    nameSearch() {
      Ember.$('.ui.modal.save-search').modal('show');
    },
    postSearch() {
      var controller = this.controllerFor("application");
      var developmentsSearch = this.controllerFor("developments.search");
      var query = this.get("container").lookup("route:developments.search").get("storedParams");
      var search = this.store.createRecord("search", { title: controller.get("title"), query: query, saved: true });

      search.save().then(() => {
        controller.set("title", null);
        developmentsSearch.toggleProperty("successfulSave");
      },
      (error) => {
        this.controller.set('error', error)
      });
    },
    deleteSearch(search) {
      search.destroyRecord();
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

Connector.playerSelector = '.hype-player';

Connector.artistSelector = '#album-header-artist';

Connector.trackSelector = 'li.active .title';

Connector.trackArtSelector = 'img#album-big';

Connector.isPlaying = () => $('.hype-player').hasClass('playing');
<commit_msg>Add album selector for Hype Machine premieres. (#1947)<commit_after>'use strict';

Connector.playerSelector = '.hype-player';

Connector.artistSelector = '#album-header-artist';

Connector.albumSelector = '#album-header-title';

Connector.trackSelector = 'li.active .title';

Connector.trackArtSelector = 'img#album-big';

Connector.isPlaying = () => $('.hype-player').hasClass('playing');
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

module.exports = function defineGraphQLCommand(args) {
  args.command('graphql', 'Execute GraphQL specific tasks', function(yargs) {
    return yargs
      .usage('Usage: hops-graphql <command>')
      .command({
        command: 'introspect',
        describe: 'Fetches GraphQL schema information for introspection',
        builder: {},
        handler: function graphqlHandler(argv) {
          require('../lib/fragments')()
            .then(function() {
              console.log('Fetched and saved GraphQL fragments');
            })
            .catch(function(err) {
              console.error('Could not fetch GraphQL fragments:');
              console.trace(err);
            });
        },
      })
      .help('help')
      .alias('h', 'help')
      .demandCommand();
  });
};

if (require.main === module) {
  try {
    require.resolve('hops-local-cli');
    require('hops-local-cli').run(module.exports, 'graphql');
  } catch (_) {
    require('hops').run(module.exports, 'graphql');
  }
}
<commit_msg>fix(graphql): fix console output<commit_after>#!/usr/bin/env node
'use strict';

module.exports = function defineGraphQLCommand(args) {
  args.command('graphql', 'Execute GraphQL specific tasks', function(yargs) {
    return yargs
      .usage(
        'Usage: ' +
          (require.main === module ? 'hops-graphql' : '$0 graphql') +
          ' <command>'
      )
      .command({
        command: 'introspect',
        describe: 'Fetches GraphQL schema information for introspection',
        builder: {},
        handler: function graphqlHandler(argv) {
          require('../lib/fragments')()
            .then(function() {
              console.log('Fetched and saved GraphQL fragments');
            })
            .catch(function(err) {
              console.error('Could not fetch GraphQL fragments:');
              console.trace(err);
            });
        },
      })
      .help('help')
      .alias('h', 'help')
      .demandCommand();
  });
};

if (require.main === module) {
  try {
    require.resolve('hops-local-cli');
    require('hops-local-cli').run(module.exports, 'graphql');
  } catch (_) {
    require('hops').run(module.exports, 'graphql');
  }
}
<|endoftext|>