<commit_before>const assert = require('assert');
const jsc = require('jsverify');

const {command} = require('../../src/arbitrary/command');

const GENSIZE = 10;
function MyEmptyClass(...params) {
    this.params = params;
};

const knownArbs = {
    "bool" : {
        arb: jsc.bool,
        check: v => v === true || v === false
    },
    "nat"  : {
        arb: jsc.nat,
        check: v => typeof(v) === 'number'
    },
    "oneof": {
        arb: jsc.oneof(jsc.constant(5), jsc.constant(42)),
        check: v => v === 5 || v === 42
    },
    "array": {
        arb: jsc.array(jsc.nat),
        check: v => Array.isArray(v) && v.find(i => typeof(i) !== 'number') === undefined
    },
};
const allowedArbs = jsc.oneof.apply(this, Object.keys(knownArbs).map(v => jsc.constant(v)));

var buildCommandFor = function(CommandType, arbsName) {
    return command.apply(this, [CommandType].concat(arbsName.map(v => knownArbs[v].arb)));
};

var areRightTypes = function(params, arbsName) {
    return params.every((e, i) => knownArbs[arbsName[i]].check(e));
};

var areSameParams = function(params1, params2) {
    return params1.length === params2.length
        && params1.every((e, i) => e === params2[i]);
};

describe('command', function() {
    describe('generator', function() {
        it('should instantiate an object from the given class', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var v = arb.generator(GENSIZE);
                return v.command instanceof MyEmptyClass;
            }));
        });

        it('should call constructor with the right number of parameters', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var v = arb.generator(GENSIZE);
                return v.command.params.length === arbsName.length;
            }));
        });

        it('should call constructor with the right types', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var v = arb.generator(GENSIZE);
                return areRightTypes(v.command.params, arbsName);
            }));
        });

        it('should keep track of parameters', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var v = arb.generator(GENSIZE);
                return areSameParams(v.parameters, v.command.params);
            }));
        });
    });
    describe('shrink', function() {
        it('should instantiate objects from the given class', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var generated = arb.generator(GENSIZE);
                return arb.shrink(generated).every(v => v.command instanceof MyEmptyClass);
            }));
        });

        it('should call constructor with the right number of parameters', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var generated = arb.generator(GENSIZE);
                return arb.shrink(generated).every(v => v.command.params.length === arbsName.length);
            }));
        });

        it('should call constructor with the right types', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var generated = arb.generator(GENSIZE);
                return arb.shrink(generated).every(v => areRightTypes(v.command.params, arbsName));
            }));
        });

        it('should keep track of parameters', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var generated = arb.generator(GENSIZE);
                return arb.shrink(generated).every(v => areSameParams(v.parameters, v.command.params));
            }));
        });
    });
});<commit_msg>[test] add strict mode to command test<commit_after>"use strict";
const assert = require('assert');
const jsc = require('jsverify');

const {command} = require('../../src/arbitrary/command');

const GENSIZE = 10;
function MyEmptyClass(...params) {
    this.params = params;
};

const knownArbs = {
    "bool" : {
        arb: jsc.bool,
        check: v => v === true || v === false
    },
    "nat"  : {
        arb: jsc.nat,
        check: v => typeof(v) === 'number'
    },
    "oneof": {
        arb: jsc.oneof(jsc.constant(5), jsc.constant(42)),
        check: v => v === 5 || v === 42
    },
    "array": {
        arb: jsc.array(jsc.nat),
        check: v => Array.isArray(v) && v.find(i => typeof(i) !== 'number') === undefined
    },
};
const allowedArbs = jsc.oneof.apply(this, Object.keys(knownArbs).map(v => jsc.constant(v)));

var buildCommandFor = function(CommandType, arbsName) {
    return command.apply(this, [CommandType].concat(arbsName.map(v => knownArbs[v].arb)));
};

var areRightTypes = function(params, arbsName) {
    return params.every((e, i) => knownArbs[arbsName[i]].check(e));
};

var areSameParams = function(params1, params2) {
    return params1.length === params2.length
        && params1.every((e, i) => e === params2[i]);
};

describe('command', function() {
    describe('generator', function() {
        it('should instantiate an object from the given class', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var v = arb.generator(GENSIZE);
                return v.command instanceof MyEmptyClass;
            }));
        });

        it('should call constructor with the right number of parameters', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var v = arb.generator(GENSIZE);
                return v.command.params.length === arbsName.length;
            }));
        });

        it('should call constructor with the right types', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var v = arb.generator(GENSIZE);
                return areRightTypes(v.command.params, arbsName);
            }));
        });

        it('should keep track of parameters', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var v = arb.generator(GENSIZE);
                return areSameParams(v.parameters, v.command.params);
            }));
        });
    });
    describe('shrink', function() {
        it('should instantiate objects from the given class', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var generated = arb.generator(GENSIZE);
                return arb.shrink(generated).every(v => v.command instanceof MyEmptyClass);
            }));
        });

        it('should call constructor with the right number of parameters', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var generated = arb.generator(GENSIZE);
                return arb.shrink(generated).every(v => v.command.params.length === arbsName.length);
            }));
        });

        it('should call constructor with the right types', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var generated = arb.generator(GENSIZE);
                return arb.shrink(generated).every(v => areRightTypes(v.command.params, arbsName));
            }));
        });

        it('should keep track of parameters', function() {
            jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
                const arb = buildCommandFor(MyEmptyClass, arbsName);
                var generated = arb.generator(GENSIZE);
                return arb.shrink(generated).every(v => areSameParams(v.parameters, v.command.params));
            }));
        });
    });
});<|endoftext|>


<commit_before>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const { spawn } = require("child_process");
const { create } = require('domain');
const { textChangeRangeNewSpan } = require('typescript');

// const fs = require("fs");
// const path = require("path");

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	async function spawnChild(command, cb) {
		const process = await spawn("howdoi", [command, '-n 3']);
		let result = []
		process.stdout.on("data", data => {

			result.push(String(data));

		});

		process.stderr.on("data", data => {
			console.log(`stderr: ${data}`);
		});

		process.on('error', (error) => {
			console.log(`error: ${error.message}`);
		});

		process.on("close", code => {
			console.log(`child process exited with code ${code}`);
			cb(result);
		});

	}

	function spliceArr(obj) {

		let dataString = String(obj);
		let lines = dataString.split('\n'+'================================================================================' + '\n');

		let newArr = lines.map((elem) => elem.split(' ★'));

		return newArr
	}

	function helperFunc(editor, myArr, userTxt) {

		const newResult = spliceArr(myArr);

		const quickPick = vscode.window.createQuickPick();
			quickPick.items = newResult.map(x => ({label: x[1], link: x[0]}));

			quickPick.onDidChangeSelection(([item]) => {
				// item.answer
				if (item) {

				editor.edit(edit => {
					edit.replace(editor.selection, userTxt + '\n' + item.link + item.label);
					// 								item.text + \n + item.link + \n + item.answer
				});
				quickPick.dispose();
				}
			});
			quickPick.onDidHide(() => quickPick.dispose());
			quickPick.show();
	}

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('howdoi.extension', function () {
		// The code you place here will be executed every time your command is executed
		const editor = vscode.window.activeTextEditor;
		if (!editor) {
			vscode.window.showInformationMessage('create a file to enable howdoi');
			return;
		}

		var text = editor.document.getText(editor.selection);
        text = text.replace("#", '')
		console.log(text + "this is the replaced version")

		spawnChild(text, function(myArr) {
			helperFunc(editor, myArr, text);
		});

	});

	context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
	activate,
	deactivate
}
<commit_msg>created modifyText function and renamed a variable<commit_after>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const { spawn } = require("child_process");
const { create } = require('domain');
const { textChangeRangeNewSpan } = require('typescript');

// const fs = require("fs");
// const path = require("path");

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	async function spawnChild(command, cb) {
		const process = await spawn("howdoi", [command, '-n 3']);
		let result = []
		process.stdout.on("data", data => {

			result.push(String(data));

		});

		process.stderr.on("data", data => {
			console.log(`stderr: ${data}`);
		});

		process.on('error', (error) => {
			console.log(`error: ${error.message}`);
		});

		process.on("close", code => {
			console.log(`child process exited with code ${code}`);
			cb(result);
		});

	}

	function spliceArr(obj) {

		let dataString = String(obj);
		let lines = dataString.split('\n'+'================================================================================' + '\n');

		let newArr = lines.map((elem) => elem.split(' ★'));

		return newArr
	}

	function helperFunc(editor, myArr, userTxt) {

		const newResult = spliceArr(myArr);

		const quickPick = vscode.window.createQuickPick();
			quickPick.items = newResult.map(x => ({label: x[1], link: x[0]}));

			quickPick.onDidChangeSelection(([item]) => {
				// item.answer
				if (item) {

				editor.edit(edit => {
					edit.replace(editor.selection, userTxt + '\n' + item.link + item.label);
					// 								item.text + \n + item.link + \n + item.answer
				});
				quickPick.dispose();
				}
			});
			quickPick.onDidHide(() => quickPick.dispose());
			quickPick.show();
	}
	function modifyCommentedText(textToBeModified){
		var regexBegins =  /^[!@#<>/\$%\^\&*\)\(+=._-]+/
		var regexEnds = /[!@#<>/\$%\^\&*\)\(+=._-]+$/

			if (textToBeModified.match(regexBegins) && textToBeModified.match(regexEnds)){
				textToBeModified = textToBeModified.replace(regexBegins, '')
				textToBeModified = textToBeModified.replace(regexEnds, '')
			}
			else if(textToBeModified.match(regexEnds)){
				textToBeModified = textToBeModified.replace(regexEnds, '')
			}
			else if(textToBeModified.match(regexBegins)){
				textToBeModified = textToBeModified.replace(regexBegins, '')
			}

		return textToBeModified
	}

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('howdoi.extension', function () {
		// The code you place here will be executed every time your command is executed
		const editor = vscode.window.activeTextEditor;
		if (!editor) {
			vscode.window.showInformationMessage('create a file to enable howdoi');
			return;
		}

		var textToBeModified = editor.document.getText(editor.selection);
		var textToBeSearched = modifyCommentedText(textToBeModified)

		spawnChild(textToBeSearched, function(myArr) {
			helperFunc(editor, myArr);
		});

	});

	context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
	activate,
	deactivate
}
<|endoftext|>


<commit_before>/**
* Classes to manage maps
*/

/**
* Map layer, could be tiled or whatever
*/
cdb.geo.MapLayer = cdb.core.Model.extend({

  defaults: {
    visible: true,
    type: 'Tiled'
  }

});

// Good old fashioned tile layer
cdb.geo.TileLayer = cdb.geo.MapLayer.extend({
  getTileLayer: function() {
  }
});

cdb.geo.GMapsBaseLayer = cdb.geo.MapLayer.extend({
  OPTIONS: ['roadmap', 'satellite', 'terrain', 'custom'],
  defaults: {
    type: 'GMapsBase',
    base_type: 'roadmap',
    style: null
  }
});

/**
 * this layer allows to put a plain color or image as layer (instead of tiles)
 */
cdb.geo.PlainLayer = cdb.geo.MapLayer.extend({
  defaults: {
    type: 'Plain',
    color: '#FFFFFF'
  }
});

// CartoDB layer
cdb.geo.CartoDBLayer = cdb.geo.MapLayer.extend({
  defaults: {
    type: 'CartoDB',
    active: true,
    query: null,
    opacity: 0.99,
    auto_bound: false,
    interactivity: null,
    debug: false,
    visible: true,
    tiler_domain: "cartodb.com",
    tiler_port: "80",
    tiler_protocol: "http",
    sql_domain: "cartodb.com",
    sql_port: "80",
    sql_protocol: "http",
    extra_params: {},
    cdn_url: null
  },

  activate: function() {
    this.set({active: true, opacity: 0.99, visible: true})
  },

  deactivate: function() {
    this.set({active: false, opacity: 0, visible: false})
  },

  toggle: function() {
    if(this.get('active')) {
      this.deactivate();
    } else {
      this.activate();
    }
  }
});

cdb.geo.Layers = Backbone.Collection.extend({

  model: cdb.geo.MapLayer,

  initialize: function() {
    this.bind('add remove', this._asignIndexes, this);
  },

  clone: function() {
    var layers = new cdb.geo.Layers();
    this.each(function(layer) {
      if(layer.clone) {
        var lyr = layer.clone();
        lyr.set('id', null);
        layers.add(lyr);
      } else {
        var attrs = _.clone(layer.attributes);
        delete attrs.id;
        layers.add(attrs);
      }
    });
    return layers;
  },

  /**
   * each time a layer is added or removed
   * the index should be recalculated
   */
  _asignIndexes: function() {
    for(var i = 0; i < this.size(); ++i) {
      this.models[i].set({ order: i }, { silent: true });
    }
  }
});

/**
* map model itself
*/
cdb.geo.Map = cdb.core.Model.extend({

  defaults: {
    center: [0, 0],
    zoom: 3,
    minZoom: 0,
    maxZoom: 20,
    provider: 'leaflet'
  },

  initialize: function() {
    this.layers = new cdb.geo.Layers();

    this.layers.bind('reset', function() {
      if(this.layers.size() >= 1) {
        this._adjustZoomtoLayer(this.layers.models[0]);
      }
    }, this);

    this.geometries = new cdb.geo.Geometries();
  },

  setView: function(latlng, zoom) {
    this.set({
      center: latlng,
      zoom: zoom
    }, {
      silent: true
    });
    this.trigger("set_view");
  },

  setZoom: function(z) {
    this.set({
      zoom: z
    });
  },

  getZoom: function() {
    return this.get('zoom');
  },

  setCenter: function(latlng) {
    this.set({
      center: latlng
    });
  },

  clone: function() {
    var m = new cdb.geo.Map(_.clone(this.attributes));
    // clone lists
    m.set({
      center: _.clone(this.attributes.center),
      bounding_box_sw: _.clone(this.attributes.bounding_box_sw),
      bounding_box_ne: _.clone(this.attributes.bounding_box_ne),
      view_bounds_sw: _.clone(this.attributes.view_bounds_sw),
      view_bounds_ne: _.clone(this.attributes.view_bounds_ne)
    });
    // layers
    m.layers = this.layers.clone();
    return m;

  },

  /**
  * Change multiple options at the same time
  * @params {Object} New options object
  */
  setOptions: function(options) {
    if (typeof options != "object" || options.length) {
      if (this.options.debug) {
        throw (options + ' options has to be an object');
      } else {
        return;
      }
    }

    // Set options
    _.defauls(this.options, options);

  },

  /**
   * return getViewbounds if it is set
   */
  getViewBounds: function() {
    if(this.has('view_bounds_sw') && this.has('view_bounds_ne')) {
      return [
        this.get('view_bounds_sw'),
        this.get('view_bounds_ne')
      ];
    }
    return null;
  },

  getLayerAt: function(i) {
    return this.layers.at(i);
  },

  getLayerByCid: function(cid) {
    return this.layers.getByCid(cid);
  },

  _adjustZoomtoLayer: function(layer) {
    //set zoom
    var z = layer.get('maxZoom');
    if(_.isNumber(z)) {
      this.set({ maxZoom: z });
    }
    z = layer.get('minZoom');
    if(_.isNumber(z)) {
      this.set({ minZoom: z });
    }
  },

  addLayer: function(layer, opts) {
    if(this.layers.size() == 0) {
      this._adjustZoomtoLayer(layer);
    }
    this.layers.add(layer, opts);
    return layer.cid;
  },

  removeLayer: function(layer) {
    this.layers.remove(layer);
  },

  removeLayerByCid: function(cid) {
    var layer = this.layers.getByCid(cid);

    if (layer) this.removeLayer(layer);
    else cdb.log.error("There's no layer with cid = " + cid + ".");
  },

  removeLayerAt: function(i) {
    var layer = this.layers.at(i);

    if (layer) this.removeLayer(layer);
    else cdb.log.error("There's no layer in that position.");
  },

  clearLayers: function() {
    while (this.layers.length > 0) {
      this.removeLayer(this.layers.at(0));
    }
  },

  // by default the base layer is the layer at index 0
  getBaseLayer: function() {
    return this.layers.at(0);
  },

  // remove current base layer and set the specified
  // current base layer is removed
  setBaseLayer: function(layer) {
    var old = this.layers.at(0);
    old.destroy();
    //this.layers.remove(old);
    this.layers.add(layer, { at: 0 });
    this._adjustZoomtoLayer(layer);
    return layer;
  },

  addGeometry: function(geom) {
    this.geometries.add(geom);
  },

  removeGeometry: function(geom) {
    this.geometries.remove(geom);
  }

});

/**
* Base view for all impl
*/
cdb.geo.MapView = cdb.core.View.extend({

  initialize: function() {

    if (this.options.map === undefined) {
      throw new Exception("you should specify a map model");
    }

    this.map = this.options.map;
    this.add_related_model(this.map);
    this.add_related_model(this.map.layers);

    // this var stores views information for each model
    this.layers = {};
    this.geometries = {};

    this.bind('clean', this._removeLayers, this);
  },

  render: function() {
    return this;
  },

  /**
   * add a infowindow to the map
   */
  addInfowindow: function(infoWindowView) {

    this.$el.append(infoWindowView.render().el);
    this.addView(infoWindowView);
  },

  /**
  * search in the subviews and return the infowindows
  */
  getInfoWindows: function() {
    var result = [];
    for (var s in this._subviews) {
      if(this._subviews[s] instanceof cdb.geo.ui.Infowindow) {
        result.push(this._subviews[s]);
      }
    }
    return result;
  },

  showBounds: function(bounds) {
    throw "to be implemented";
  },

  _removeLayers: function() {
    for(var layer in this.layers) {
      this.layers[layer].remove();
    }
    this.layers = {}
  },

  /**
  * set model property but unbind changes first in order to not create an infinite loop
  */
  _setModelProperty: function(prop) {
    this._unbindModel();
    this.map.set(prop);
    this._bindModel();
  },

  /** bind model properties */
  _bindModel: function() {
    this.map.bind('change:zoom',   this._setZoom, this);
    this.map.bind('change:center', this._setCenter, this);
  },

  /** unbind model properties */
  _unbindModel: function() {
    this.map.unbind('change:zoom',   this._setZoom, this);
    this.map.unbind('change:center', this._setCenter, this);
  },

  _addLayers: function() {
    var self = this;
    this.map.layers.each(function(lyr) {
      self._addLayer(lyr);
    });
  },

  _removeLayer: function(layer) {
    var layer_view = this.layers[layer.cid];
    if(layer_view) {
      layer_view.remove();
      delete this.layers[layer.cid];
    }
  },

  _removeGeometry: function(geo) {
    var geo_view = this.geometries[geo.cid];
    delete this.layers[layer.cid];
  },

  getLayerByCid: function(cid) {
    var l = this.layers[cid];
    if(!l) {
      cdb.log.error("layer with cid " + cid + " can't be get");
    }
    return l;
  },

  addGeometry: function(geom) {
    throw "to be implemented";
  },

  _setZoom: function(model, z) {
    throw "to be implemented";
  },

  _setCenter: function(model, center) {
    throw "to be implemented";
  },

  _addLayer: function(layer, layers, opts) {
    throw "to be implemented";
  }

}, {

  _getClass: function(provider) {
    var mapViewClass = cdb.geo.LeafletMapView;
    if(provider === 'googlemaps') {
        if(typeof(google) != "undefined" && typeof(google.maps) != "undefined") {
          mapViewClass = cdb.geo.GoogleMapsMapView;
        } else {
          cdb.log.error("you must include google maps library _before_ include cdb");
        }
    }
    return mapViewClass;
  },

  create: function(el, mapModel) {
    var _mapViewClass = cdb.geo.MapView._getClass(mapModel.get('provider'));
    return new _mapViewClass({
      el: el,
      map: mapModel
    });
  }
}
);
<commit_msg>wait for base layer to be destroyed to create the new one<commit_after>/**
* Classes to manage maps
*/

/**
* Map layer, could be tiled or whatever
*/
cdb.geo.MapLayer = cdb.core.Model.extend({

  defaults: {
    visible: true,
    type: 'Tiled'
  }

});

// Good old fashioned tile layer
cdb.geo.TileLayer = cdb.geo.MapLayer.extend({
  getTileLayer: function() {
  }
});

cdb.geo.GMapsBaseLayer = cdb.geo.MapLayer.extend({
  OPTIONS: ['roadmap', 'satellite', 'terrain', 'custom'],
  defaults: {
    type: 'GMapsBase',
    base_type: 'roadmap',
    style: null
  }
});

/**
 * this layer allows to put a plain color or image as layer (instead of tiles)
 */
cdb.geo.PlainLayer = cdb.geo.MapLayer.extend({
  defaults: {
    type: 'Plain',
    color: '#FFFFFF'
  }
});

// CartoDB layer
cdb.geo.CartoDBLayer = cdb.geo.MapLayer.extend({
  defaults: {
    type: 'CartoDB',
    active: true,
    query: null,
    opacity: 0.99,
    auto_bound: false,
    interactivity: null,
    debug: false,
    visible: true,
    tiler_domain: "cartodb.com",
    tiler_port: "80",
    tiler_protocol: "http",
    sql_domain: "cartodb.com",
    sql_port: "80",
    sql_protocol: "http",
    extra_params: {},
    cdn_url: null
  },

  activate: function() {
    this.set({active: true, opacity: 0.99, visible: true})
  },

  deactivate: function() {
    this.set({active: false, opacity: 0, visible: false})
  },

  toggle: function() {
    if(this.get('active')) {
      this.deactivate();
    } else {
      this.activate();
    }
  }
});

cdb.geo.Layers = Backbone.Collection.extend({

  model: cdb.geo.MapLayer,

  initialize: function() {
    this.bind('add remove', this._asignIndexes, this);
  },

  clone: function() {
    var layers = new cdb.geo.Layers();
    this.each(function(layer) {
      if(layer.clone) {
        var lyr = layer.clone();
        lyr.set('id', null);
        layers.add(lyr);
      } else {
        var attrs = _.clone(layer.attributes);
        delete attrs.id;
        layers.add(attrs);
      }
    });
    return layers;
  },

  /**
   * each time a layer is added or removed
   * the index should be recalculated
   */
  _asignIndexes: function() {
    for(var i = 0; i < this.size(); ++i) {
      this.models[i].set({ order: i }, { silent: true });
    }
  }
});

/**
* map model itself
*/
cdb.geo.Map = cdb.core.Model.extend({

  defaults: {
    center: [0, 0],
    zoom: 3,
    minZoom: 0,
    maxZoom: 20,
    provider: 'leaflet'
  },

  initialize: function() {
    this.layers = new cdb.geo.Layers();

    this.layers.bind('reset', function() {
      if(this.layers.size() >= 1) {
        this._adjustZoomtoLayer(this.layers.models[0]);
      }
    }, this);

    this.geometries = new cdb.geo.Geometries();
  },

  setView: function(latlng, zoom) {
    this.set({
      center: latlng,
      zoom: zoom
    }, {
      silent: true
    });
    this.trigger("set_view");
  },

  setZoom: function(z) {
    this.set({
      zoom: z
    });
  },

  getZoom: function() {
    return this.get('zoom');
  },

  setCenter: function(latlng) {
    this.set({
      center: latlng
    });
  },

  clone: function() {
    var m = new cdb.geo.Map(_.clone(this.attributes));
    // clone lists
    m.set({
      center: _.clone(this.attributes.center),
      bounding_box_sw: _.clone(this.attributes.bounding_box_sw),
      bounding_box_ne: _.clone(this.attributes.bounding_box_ne),
      view_bounds_sw: _.clone(this.attributes.view_bounds_sw),
      view_bounds_ne: _.clone(this.attributes.view_bounds_ne)
    });
    // layers
    m.layers = this.layers.clone();
    return m;

  },

  /**
  * Change multiple options at the same time
  * @params {Object} New options object
  */
  setOptions: function(options) {
    if (typeof options != "object" || options.length) {
      if (this.options.debug) {
        throw (options + ' options has to be an object');
      } else {
        return;
      }
    }

    // Set options
    _.defauls(this.options, options);

  },

  /**
   * return getViewbounds if it is set
   */
  getViewBounds: function() {
    if(this.has('view_bounds_sw') && this.has('view_bounds_ne')) {
      return [
        this.get('view_bounds_sw'),
        this.get('view_bounds_ne')
      ];
    }
    return null;
  },

  getLayerAt: function(i) {
    return this.layers.at(i);
  },

  getLayerByCid: function(cid) {
    return this.layers.getByCid(cid);
  },

  _adjustZoomtoLayer: function(layer) {
    //set zoom
    var z = layer.get('maxZoom');
    if(_.isNumber(z)) {
      this.set({ maxZoom: z });
    }
    z = layer.get('minZoom');
    if(_.isNumber(z)) {
      this.set({ minZoom: z });
    }
  },

  addLayer: function(layer, opts) {
    if(this.layers.size() == 0) {
      this._adjustZoomtoLayer(layer);
    }
    this.layers.add(layer, opts);
    return layer.cid;
  },

  removeLayer: function(layer) {
    this.layers.remove(layer);
  },

  removeLayerByCid: function(cid) {
    var layer = this.layers.getByCid(cid);

    if (layer) this.removeLayer(layer);
    else cdb.log.error("There's no layer with cid = " + cid + ".");
  },

  removeLayerAt: function(i) {
    var layer = this.layers.at(i);

    if (layer) this.removeLayer(layer);
    else cdb.log.error("There's no layer in that position.");
  },

  clearLayers: function() {
    while (this.layers.length > 0) {
      this.removeLayer(this.layers.at(0));
    }
  },

  // by default the base layer is the layer at index 0
  getBaseLayer: function() {
    return this.layers.at(0);
  },

  // remove current base layer and set the specified
  // current base layer is removed
  setBaseLayer: function(layer, opts) {
    var self = this;
    var old = this.layers.at(0);
    old.destroy({
      success: function() {
        self.layers.add(layer, { at: 0 });
        self._adjustZoomtoLayer(layer);
        opts.success && opts.success();
      },
      error: opts.error
    });
    return layer;
  },

  addGeometry: function(geom) {
    this.geometries.add(geom);
  },

  removeGeometry: function(geom) {
    this.geometries.remove(geom);
  }

});

/**
* Base view for all impl
*/
cdb.geo.MapView = cdb.core.View.extend({

  initialize: function() {

    if (this.options.map === undefined) {
      throw new Exception("you should specify a map model");
    }

    this.map = this.options.map;
    this.add_related_model(this.map);
    this.add_related_model(this.map.layers);

    // this var stores views information for each model
    this.layers = {};
    this.geometries = {};

    this.bind('clean', this._removeLayers, this);
  },

  render: function() {
    return this;
  },

  /**
   * add a infowindow to the map
   */
  addInfowindow: function(infoWindowView) {

    this.$el.append(infoWindowView.render().el);
    this.addView(infoWindowView);
  },

  /**
  * search in the subviews and return the infowindows
  */
  getInfoWindows: function() {
    var result = [];
    for (var s in this._subviews) {
      if(this._subviews[s] instanceof cdb.geo.ui.Infowindow) {
        result.push(this._subviews[s]);
      }
    }
    return result;
  },

  showBounds: function(bounds) {
    throw "to be implemented";
  },

  _removeLayers: function() {
    for(var layer in this.layers) {
      this.layers[layer].remove();
    }
    this.layers = {}
  },

  /**
  * set model property but unbind changes first in order to not create an infinite loop
  */
  _setModelProperty: function(prop) {
    this._unbindModel();
    this.map.set(prop);
    this._bindModel();
  },

  /** bind model properties */
  _bindModel: function() {
    this.map.bind('change:zoom',   this._setZoom, this);
    this.map.bind('change:center', this._setCenter, this);
  },

  /** unbind model properties */
  _unbindModel: function() {
    this.map.unbind('change:zoom',   this._setZoom, this);
    this.map.unbind('change:center', this._setCenter, this);
  },

  _addLayers: function() {
    var self = this;
    this.map.layers.each(function(lyr) {
      self._addLayer(lyr);
    });
  },

  _removeLayer: function(layer) {
    var layer_view = this.layers[layer.cid];
    if(layer_view) {
      layer_view.remove();
      delete this.layers[layer.cid];
    }
  },

  _removeGeometry: function(geo) {
    var geo_view = this.geometries[geo.cid];
    delete this.layers[layer.cid];
  },

  getLayerByCid: function(cid) {
    var l = this.layers[cid];
    if(!l) {
      cdb.log.error("layer with cid " + cid + " can't be get");
    }
    return l;
  },

  addGeometry: function(geom) {
    throw "to be implemented";
  },

  _setZoom: function(model, z) {
    throw "to be implemented";
  },

  _setCenter: function(model, center) {
    throw "to be implemented";
  },

  _addLayer: function(layer, layers, opts) {
    throw "to be implemented";
  }

}, {

  _getClass: function(provider) {
    var mapViewClass = cdb.geo.LeafletMapView;
    if(provider === 'googlemaps') {
        if(typeof(google) != "undefined" && typeof(google.maps) != "undefined") {
          mapViewClass = cdb.geo.GoogleMapsMapView;
        } else {
          cdb.log.error("you must include google maps library _before_ include cdb");
        }
    }
    return mapViewClass;
  },

  create: function(el, mapModel) {
    var _mapViewClass = cdb.geo.MapView._getClass(mapModel.get('provider'));
    return new _mapViewClass({
      el: el,
      map: mapModel
    });
  }
}
);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011 Bruno Jouhier <bruno.jouhier@sage.com>
 * MIT License
 */
(function(exports) {
	function future(fn, args, i) {
		print("FUTURE")
		var err, result, done, q = [];
		args = Array.prototype.slice.call(args);
		args[i] = function(e, r) {
			err = e, result = r, done = true;
			q && q.forEach(function(f) {
				//try {
				f(e, r);
				//} catch (ex) { __trap(ex); }
			});
			q = null;
		};
		fn.apply(this, args);
		return function ___(_) {
			print("CALL FUTURE")
			if (!_) return ___;
			if (done) _(err, result);
			else q.push(_)
		}
	}

	function run(fn, args, idx) {
		var cb = args[idx],
			stack = [];
		var resume = function(err, val) {
				try {
					var g = stack.pop();
					val = g.send(val);
					while ((!val || !val.next) && stack.length > 0) {
						g.close();
						g = stack.pop();
						val = g.send(val);
					}
					stack.push(g);
					while (val && val.next) {
						stack.push(val);
						val = val.next();
					}
					if (stack.length == 1) {
						stack.pop().close();
						cb(null, val);
					}
				} catch (ex) {
					while (stack.length > 0) stack.pop().close();
					cb(ex);
				}
			}
		args[idx] = resume;
		try {
			stack.push(fn.apply(this, args));
		} catch (ex) {
			cb(ex);
		}
		resume();
	}

	exports.create = function(fn, idx) {
		function F() {
			if (arguments[idx] == null) return future(fn, arguments, idx);
			run(fn, arguments, idx);
		};
		// Memoize the original function for fast passing later
		F.gstreamlineFunction = fn;
		return F;
	}

	exports.invoke = function(that, fn, args, idx) {
		// Resolve the function to be called
		if (typeof fn !== 'function') {
			if (typeof that === 'function' && that.gstreamlineFunction && fn === 'call') {
				return that.gstreamlineFunction.apply(args[0], args.slice(1));
			}
			fn = that[fn];
		}

		// If we're waiting on a fstreamline.create function we can just call it directly instead
		if (fn.gstreamlineFunction) {
			try {
				return fn.gstreamlineFunction.apply(that, args);
			} catch (e) {
				throw e; //makeError(e, false);
			}
		}
		return fn.apply(that, args);
	}
})(typeof exports !== 'undefined' ? exports : (window.StreamlineRuntime = window.StreamlineRuntime || {
	globals: {}
}));
//require && require("streamline/lib/callbacks/builtins");<commit_msg>use more robust test for generator type<commit_after>/**
 * Copyright (c) 2011 Bruno Jouhier <bruno.jouhier@sage.com>
 * MIT License
 */
(function(exports) {
	function future(fn, args, i) {
		var err, result, done, q = [];
		args = Array.prototype.slice.call(args);
		args[i] = function(e, r) {
			err = e, result = r, done = true;
			q && q.forEach(function(f) {
				//try {
				f(e, r);
				//} catch (ex) { __trap(ex); }
			});
			q = null;
		};
		fn.apply(this, args);
		return function ___(_) {
			if (!_) return ___;
			if (done) _(err, result);
			else q.push(_)
		}
	}

	var GENERATOR_PROTO = Object.getPrototypeOf((function() { yield; })());

	function run(fn, args, idx) {
		var cb = args[idx],
			stack = [];
		var resume = function(err, val) {
				try {
					var g = stack.pop();
					val = g.send(val);
					while ((!val || !val.next) && stack.length > 0) {
						g.close();
						g = stack.pop();
						val = g.send(val);
					}
					stack.push(g);
					while (val && Object.getPrototypeOf(val) === GENERATOR_PROTO) {
						stack.push(val);
						val = val.next();
					}
					if (stack.length == 1) {
						stack.pop().close();
						cb(null, val);
					}
				} catch (ex) {
					while (stack.length > 0) stack.pop().close();
					cb(ex);
				}
			}
		args[idx] = resume;
		try {
			stack.push(fn.apply(this, args));
		} catch (ex) {
			cb(ex);
		}
		resume();
	}

	exports.create = function(fn, idx) {
		function F() {
			if (arguments[idx] == null) return future(fn, arguments, idx);
			run(fn, arguments, idx);
		};
		// Memoize the original function for fast passing later
		F.gstreamlineFunction = fn;
		return F;
	}

	exports.invoke = function(that, fn, args, idx) {
		// Resolve the function to be called
		if (typeof fn !== 'function') {
			if (typeof that === 'function' && that.gstreamlineFunction && fn === 'call') {
				return that.gstreamlineFunction.apply(args[0], args.slice(1));
			}
			fn = that[fn];
		}

		// If we're waiting on a fstreamline.create function we can just call it directly instead
		if (fn.gstreamlineFunction) {
			try {
				return fn.gstreamlineFunction.apply(that, args);
			} catch (e) {
				throw e; //makeError(e, false);
			}
		}
		return fn.apply(that, args);
	}
})(typeof exports !== 'undefined' ? exports : (window.StreamlineRuntime = window.StreamlineRuntime || {
	globals: {}
}));
//require && require("streamline/lib/callbacks/builtins");<|endoftext|>


<commit_before>(function () {
  'use strict';
  // Polls controller
  angular.module('polls').controller('AdminPollController', AdminPollController);

  AdminPollController.$inject = [
    '$scope',
    '$state',
    '$window',
    'pollResolve',
    'AdminPollsService',
    'Action',
    'toastr',
    'ngDialog'
  ];

  function AdminPollController(
    $scope,
    $state,
    $window,
    poll,
    Action,
    AdminPollsService,
    toast,
    dialog
  ) {
    var vm = this;
    vm.poll = poll;

    get_admin_poll_report();
    function get_admin_poll_report() {
      AdminPollsService.get_admin_poll_report(vm.poll._id)
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          toast.error(err.message, 'Error!');
          console.log(err);
        });
    }
  }
})();
<commit_msg>Commited from HaNhatLenh at Sun, Aug 13, 2017 10:13:13 PM<commit_after>(function () {
  'use strict';
  // Polls controller
  angular.module('polls').controller('AdminPollController', AdminPollController);

  AdminPollController.$inject = [
    '$scope',
    '$state',
    '$window',
    'pollResolve',
    'AdminPollsService',
    'Action',
    'toastr',
    'ngDialog'
  ];

  function AdminPollController(
    $scope,
    $state,
    $window,
    poll,
    AdminPollsService,
    Action,
    toast,
    dialog
  ) {
    var vm = this;
    vm.poll = poll;

    get_admin_poll_report();
    function get_admin_poll_report() {
      AdminPollsService.get_admin_poll_report(vm.poll._id)
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          toast.error(err.message, 'Error!');
          console.log(err);
        });
    }
  }
})();
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  _ = require('lodash'),
  Profile = mongoose.model('Profile'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create a profile
 */
exports.create = function (req, res) {
  var profile = new Profile(req.body);

  profile.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }
    res.json(profile);
  });
};

/**
 * Show the current profile
 */
exports.read = function (req, res) {
  res.json(req.profile);
};

/**
 * Update a profile
 */
exports.update = function (req, res) {
  var profile = req.profile;

  // Merge existing profile
  profile = _.extend(profile, req.body);
  profile.updated = Date.now();

  Profile.findOneAndUpdate(
    { _id: profile._id },
    { $set: profile },
    function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }
    res.json(profile);
  });
};

/**
 * Delete an profile
 */
exports.delete = function (req, res) {
  var profile = req.profile;

  profile.remove(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }
    res.json(profile);
  });
};

/**
 * List of profiles
 */
exports.list = function (req, res) {
  Profile.find().sort('-created').exec(function (err, profiles) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }
    res.json(profiles);
  });
};

/**
 * Profile middleware
 */
exports.profileByProvider = function (req, res, next) {
  var searchQuery = {
    loginInfo: {
      providerID: req.params.providerID,
      providerKey: req.params.providerKey,
    }
  };

  Profile.findOne(searchQuery, function (err, profile) {
    if (err) {
      return next(err);
    }
    if (!profile) {
      return res.status(404).send({
        message: 'No profile with those identifiers has been found'
      });
    }
    req.profile = profile;
    next();
  });
};
<commit_msg>Fix syntax error according to eslint<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  _ = require('lodash'),
  Profile = mongoose.model('Profile'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create a profile
 */
exports.create = function (req, res) {
  var profile = new Profile(req.body);

  profile.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }
    res.json(profile);
  });
};

/**
 * Show the current profile
 */
exports.read = function (req, res) {
  res.json(req.profile);
};

/**
 * Update a profile
 */
exports.update = function (req, res) {
  var profile = req.profile;

  // Merge existing profile
  profile = _.extend(profile, req.body);
  profile.updated = Date.now();

  Profile.findOneAndUpdate(
    { _id: profile._id },
    { $set: profile },
    function (err) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      }
      res.json(profile);
    });
};

/**
 * Delete an profile
 */
exports.delete = function (req, res) {
  var profile = req.profile;

  profile.remove(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }
    res.json(profile);
  });
};

/**
 * List of profiles
 */
exports.list = function (req, res) {
  Profile.find().sort('-created').exec(function (err, profiles) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }
    res.json(profiles);
  });
};

/**
 * Profile middleware
 */
exports.profileByProvider = function (req, res, next) {
  var searchQuery = {
    loginInfo: {
      providerID: req.params.providerID,
      providerKey: req.params.providerKey,
    }
  };

  Profile.findOne(searchQuery, function (err, profile) {
    if (err) {
      return next(err);
    }
    if (!profile) {
      return res.status(404).send({
        message: 'No profile with those identifiers has been found'
      });
    }
    req.profile = profile;
    next();
  });
};
<|endoftext|>


<commit_before>'use strict';

// Projects controller
angular.module('projects')
  .config(function ($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
      'self',                    // trust all resources from the same origin
      '*://www.youtube.com/**'   // trust all resources from `www.youtube.com`
    ]);
  })

  .controller('ProjectsController', ['$scope', '$state', '$stateParams', '$location', 'Projects', 'Authentication', 'Users','$rootScope', 'ActiveEvent', '$http',
  function ($scope, $state, $stateParams, $location, Projects, Authentication, Users, $rootScope, ActiveEvent, $http) {
    $scope.authentication = Authentication;
    $scope.user = $scope.owner = $scope.authentication.user;

    if (!$rootScope.activeProject) {
      $rootScope.activeProject = {
        description: {},
        owner: $scope.user,
        team: []
      };
    }

    ActiveEvent.get().then(function(activeEvent) {
      $scope.activeEvent = activeEvent;
      $scope.activeCategory = $scope.activeEvent.categories[0];
    });

    $scope.team = $rootScope.activeProject.team;

    $scope.saveProjectInfo = function () {
      $rootScope.activeProject.title = this.title;
      $rootScope.activeProject.youtube = this.youtube;
      $rootScope.activeProject.description.short = this.short;
      $rootScope.activeProject.description.long = this.long;

      $location.path('projects/category');
    };

    $scope.setActiveCategory = function (category) {
      $scope.activeCategory = category;
    };

    $scope.saveProjectCategory = function () {
      $rootScope.activeProject.category = $scope.activeCategory.title;

      $location.path('projects/team');
    };

    $scope.create = function (isValid) {
      $scope.error = null;

      $rootScope.activeProject.event = $scope.activeEvent;

      // Create new Project object
      var project = new Projects($rootScope.activeProject);

      // Redirect after save
      project.$save(function (response) {
        $location.path('projects/' + response._id);

        // Clear form fields
        $rootScope.activeProject = null;
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Remove existing Project
    $scope.remove = function (project) {
      if (project) {
        project.$remove();

        for (var i in $scope.projects) {
          if ($scope.projects[i] === project) {
            $scope.projects.splice(i, 1);
          }
        }
      } else {
        $scope.project.$remove(function () {
          $location.path('projects');
        });
      }
    };

    // Update existing Project
    $scope.update = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'projectForm');

        return false;
      }

      $scope.project.$update(function () {
        $location.path('projects/' + $scope.project._id);
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Find a list of Projects
    $scope.find = function () {
      $scope.projects = Projects.query(function (projects) {
        $scope.projects = projects;

        shuffle(projects);

        $scope.projects = projects;
      });
    };

    // Find existing Project
    $scope.findOne = function () {
      $scope.project = Projects.get({ projectId: $stateParams.projectId },function(project) {
        $scope.hasVoted = $scope.user.votedProjects.indexOf(project._id) !== -1;
      });
    };

    /* Initialize voting field */
    $scope.hasVoted = false;

    $scope.unvote = function (project) {
      $http.delete('/api/projects/' + project._id + '/vote')
        .success(function() {
          $scope.hasVoted = false;
        })
        .error(function () {
          console.log('data error');
        });
    };

    $scope.vote = function (project) {
      $http.put('/api/projects/' + project._id + '/vote')
        .success(function() {
         $scope.hasVoted = true;
        })
        .error(function () {
          console.log('data error');
        });
    };

    $scope.loadUsers = function() {
      $scope.users = Users.query(function (users) {
        $scope.users = users;

        // Remove owner from being able to be added
        for (var i = 0; i < $scope.users.length; i++) {
          if ($scope.owner._id === $scope.users[i]._id) {
            $scope.users.splice(i, 1);
          }
        }
      });
    };

    $scope.addMember = function(user) {
      $rootScope.activeProject.team.push(user);

      for (var i = 0; i < $scope.users.length; i++) {
        if (user._id === $scope.users[i]._id) {
          $scope.users.splice(i, 1);
        }
      }
    };

    $scope.removeMember = function(user) {
      $scope.users.push(user);

      for (var i = 0; i < $rootScope.activeProject.team.length; i++) {
        if (user._id === $rootScope.activeProject.team[i]._id) {
          $rootScope.activeProject.team.splice(i, 1);
        }
      }
    };

    function shuffle(array) {
      var currentIndex = array.length, temporaryValue, randomIndex;

      // While there remain elements to shuffle...
      while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
      }

      return array;
    }

  }]);
<commit_msg>fix lint<commit_after>'use strict';

// Projects controller
angular.module('projects')
  .config(function ($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
      'self',                    // trust all resources from the same origin
      '*://www.youtube.com/**'   // trust all resources from `www.youtube.com`
    ]);
  })

  .controller('ProjectsController', ['$scope', '$state', '$stateParams', '$location', 'Projects', 'Authentication', 'Users','$rootScope', 'ActiveEvent', '$http',
  function ($scope, $state, $stateParams, $location, Projects, Authentication, Users, $rootScope, ActiveEvent, $http) {
    $scope.authentication = Authentication;
    $scope.user = $scope.owner = $scope.authentication.user;

    if (!$rootScope.activeProject) {
      $rootScope.activeProject = {
        description: {},
        owner: $scope.user,
        team: []
      };
    }

    ActiveEvent.get().then(function(activeEvent) {
      $scope.activeEvent = activeEvent;
      $scope.activeCategory = $scope.activeEvent.categories[0];
    });

    $scope.team = $rootScope.activeProject.team;

    $scope.saveProjectInfo = function () {
      $rootScope.activeProject.title = this.title;
      $rootScope.activeProject.youtube = this.youtube;
      $rootScope.activeProject.description.short = this.short;
      $rootScope.activeProject.description.long = this.long;

      $location.path('projects/category');
    };

    $scope.setActiveCategory = function (category) {
      $scope.activeCategory = category;
    };

    $scope.saveProjectCategory = function () {
      $rootScope.activeProject.category = $scope.activeCategory.title;

      $location.path('projects/team');
    };

    $scope.create = function (isValid) {
      $scope.error = null;

      $rootScope.activeProject.event = $scope.activeEvent;

      // Create new Project object
      var project = new Projects($rootScope.activeProject);

      // Redirect after save
      project.$save(function (response) {
        $location.path('projects/' + response._id);

        // Clear form fields
        $rootScope.activeProject = null;
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Remove existing Project
    $scope.remove = function (project) {
      if (project) {
        project.$remove();

        for (var i in $scope.projects) {
          if ($scope.projects[i] === project) {
            $scope.projects.splice(i, 1);
          }
        }
      } else {
        $scope.project.$remove(function () {
          $location.path('projects');
        });
      }
    };

    // Update existing Project
    $scope.update = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'projectForm');

        return false;
      }

      $scope.project.$update(function () {
        $location.path('projects/' + $scope.project._id);
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Find a list of Projects
    $scope.find = function () {
      $scope.projects = Projects.query(function (projects) {
        $scope.projects = projects;

        shuffle(projects);

        $scope.projects = projects;
      });
    };

    // Find existing Project
    $scope.findOne = function () {
      $scope.project = Projects.get({ projectId: $stateParams.projectId },function(project) {
        $scope.hasVoted = $scope.user.votedProjects.indexOf(project._id) !== -1;
      });
    };

    /* Initialize voting field */
    $scope.hasVoted = false;

    $scope.unvote = function (project) {
      $http.delete('/api/projects/' + project._id + '/vote')
        .success(function() {
          $scope.hasVoted = false;
        })
        .error(function () {
          console.log('data error');
        });
    };

    $scope.vote = function (project) {
      $http.put('/api/projects/' + project._id + '/vote')
        .success(function() {
          $scope.hasVoted = true;
        })
        .error(function () {
          console.log('data error');
        });
    };

    $scope.loadUsers = function() {
      $scope.users = Users.query(function (users) {
        $scope.users = users;

        // Remove owner from being able to be added
        for (var i = 0; i < $scope.users.length; i++) {
          if ($scope.owner._id === $scope.users[i]._id) {
            $scope.users.splice(i, 1);
          }
        }
      });
    };

    $scope.addMember = function(user) {
      $rootScope.activeProject.team.push(user);

      for (var i = 0; i < $scope.users.length; i++) {
        if (user._id === $scope.users[i]._id) {
          $scope.users.splice(i, 1);
        }
      }
    };

    $scope.removeMember = function(user) {
      $scope.users.push(user);

      for (var i = 0; i < $rootScope.activeProject.team.length; i++) {
        if (user._id === $rootScope.activeProject.team[i]._id) {
          $rootScope.activeProject.team.splice(i, 1);
        }
      }
    };

    function shuffle(array) {
      var currentIndex = array.length, temporaryValue, randomIndex;

      // While there remain elements to shuffle...
      while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
      }

      return array;
    }

  }]);
<|endoftext|>


<commit_before>/*
 * Brando empty test.
 */

exports.test  = function ( done, assertions ) {
    var log = console.log
        , exit = typeof done === 'function' ? done : function () {}
        , assert = assertions || require( 'assert' )
        ;

    exit();
};

// single test execution with node
if ( process.argv[ 1 ] === __filename  ) exports.test = exports.test();<commit_msg>make empty test coverage happens. On branch master modified:   test/brando-empty-test.js<commit_after>/*
 * Brando empty test.
 */

exports.test  = function ( done, assertions ) {
    var log = console.log
        , exit = typeof done === 'function' ? done : function () {}
        , assert = assertions || require( 'assert' )
        , Brando = require( '../' )
        ;

    exit();
};

// single test execution with node
if ( process.argv[ 1 ] === __filename  ) exports.test = exports.test();<|endoftext|>


<commit_before>const Q             = require('q');
const {parseString} = require('xml2js');
const request       = require('request');
const sanitizeHTML  = require('sanitize-html');

function parseSimpleHTML (content) {
  return content.replace(/\<br\s?\/\>/g, '\n')
                .replace(/\<b\>/g, '')
                .replace(/\<\/b\>/g, '');
}

function BookShow(key) {

  if (!key) {
    throw new Error('A valid goodreads API key is required.');
  }

  this.execute = (id) => {
    if (!id) {
      return Q.reject('The id of the book to show is required.');
    }

    return Q.nfcall(request, `https://www.goodreads.com/book/show/${id}.xml`, { qs: { key: key } })
            .spread((response, xmlData) => Q.nfcall(parseString, xmlData, { explicitArray: false, ignoreAttrs: true }))
            .then(({ GoodreadsResponse }) => {

              const b = GoodreadsResponse.book;

              return {
                id: b.id,
                title: b.title,
                author: b.authors.author,
                rating: b.average_rating,
                thumb_url: b.image_url,
                description: parseSimpleHTML(b.description)
              };

            });
  };

}

module.exports = BookShow;<commit_msg>Removes unnecessary require sanitize-html<commit_after>const Q             = require('q');
const {parseString} = require('xml2js');
const request       = require('request');

function parseSimpleHTML (content) {
  return content.replace(/\<br\s?\/\>/g, '\n')
                .replace(/\<b\>/g, '')
                .replace(/\<\/b\>/g, '');
}

function BookShow(key) {

  if (!key) {
    throw new Error('A valid goodreads API key is required.');
  }

  this.execute = (id) => {
    if (!id) {
      return Q.reject('The id of the book to show is required.');
    }

    return Q.nfcall(request, `https://www.goodreads.com/book/show/${id}.xml`, { qs: { key: key } })
            .spread((response, xmlData) => Q.nfcall(parseString, xmlData, { explicitArray: false, ignoreAttrs: true }))
            .then(({ GoodreadsResponse }) => {

              const b = GoodreadsResponse.book;

              return {
                id: b.id,
                title: b.title,
                author: b.authors.author,
                rating: b.average_rating,
                thumb_url: b.image_url,
                description: parseSimpleHTML(b.description)
              };

            });
  };

}

module.exports = BookShow;<|endoftext|>


<commit_before>describe('direct',function() {
  require('./direct')
})

describe('instances',function() {
  require('./instances')
})
<commit_msg>commented out instances tests<commit_after>describe('direct',function() {
  require('./direct')
})

// describe('instances',function() {
//   require('./instances')
// })
<|endoftext|>


<commit_before>.import QtQuick.LocalStorage 2.0 as Sql

/*

  new QMDatabase('myApp', '1.0')
  define : returns an object with functions create/filter/delete
  create: returns an object with the properties
  */

function QMDatabase(appName, version) {
    this.migrate = false;
    //Tables to handle version control
    var qMDatabase = this;
    this.conn = Sql.LocalStorage.openDatabaseSync(appName + '_db', "1.0", appName, 100000,
        function(db) {
            qMDatabase.migrate = true;
            console.log("*** DATABASE DOESNT EXIST ****");
            db.changeVersion("", "1.0");
        }
    );
    var AppVersion = this.define('__AppVersion__', {
        appName: this.String('App Name', {accept_null:false}),
        version: this.String('Version', {accept_null:false})
    });

    var appVersion = AppVersion.filter({appName: appName}).get();

    if (appVersion) {
        if (appVersion.version !== version) {
            appVersion.version = version;
            appVersion.save();
            this.migrate = true
        }
    } else {
        appVersion = AppVersion.create({appName: appName, version: version});
        this.migrate = true;
    }
}

QMDatabase.prototype = {
    constructor: QMDatabase,

    String: function(label, params) {
        return new QMField('TEXT', label, params);
    },
    Integer: function(label, params) {
        return new QMField('INTEGER', label, params);
    },
    Float: function(label, params) {
        return new QMField('FLOAT', label, params);
    },
    Real: function(label, params) {
        return new QMField('REAL', label, params);
    },
    Date: function(label, params) {
        return new QMField('DATE', label, params);
    },
    DateTime: function(label, params) {
        return new QMField('DATETIME', label, params);
    },
    Boolean: function(label, params) {
        return new QMField('BOOLEAN', label, params);
    },
    PK: function(label, params) {
        return new QMField('PK', label, params);
    },
    FK: function(label, params) {
        return new QMField('FK', label, params);
    },
    _defineField: function(column, data) {
        var sql;
        var items = [];
        var fk = [];

        //If is a foreign key
        if (data.type === 'FK') {
            items.push(column)
            items.push('INTEGER')
            fk.push('FOREIGN KEY(' + column + ')')
        }
        else if (data.type === 'PK') {
            items.push(column);
            items.push('INTEGER PRIMARY KEY');
        }
        else {
            items.push(column);
            items.push(data.type);
        }

        for (var param in data.params) {
            switch(param) {
                case 'accept_null':
                    if (!data.params[param]) {
                        items.push('NOT NULL');
                    }
                    break;
                case 'unique':
                    if (unique) {
                        items.push('UNIQUE');
                    }
                    break;
                case 'references':
                    fk.push('REFERENCES ' + data.params[param] + '(id) ON DELETE CASCADE ON UPDATE CASCADE');
                    break;
                case 'default':
                    items.push('DEFAULT ' + data.params[param]);
                    break;

            }
        }

        return {field: items.join(' '), fk: fk.join(' ')};
    },
    retrieveFields: function(name) {
        var rs;
        var sql = "PRAGMA table_info(" + name + ")";
        this.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql);
            }
        )

        var fields = {};
        for (var idx=0; idx < rs.rows.length; idx++) {
            fields[rs.rows[idx].name] = null;
        }

        return fields;
    },
    define: function(name, fields) {
        var sql_create = "CREATE TABLE IF NOT EXISTS " + name + " (";
        var idx = 0;
        this.properties = {};
        this.tableName = name;

        fields['id'] = this.PK('Primary Key', []);

        var foreign_keys = [];
        for (var column in fields) {
            var definitions = fields[column];
            var field_data = this._defineField(column, fields[column]);
            if (idx > 0) sql_create += ", ";
            sql_create += field_data['field'];

            if (field_data['fk'].length > 0) {
                foreign_keys.push(field_data['fk']);
            }
            idx++;
        }

        //Create foreign key references
        for (var ifk=0; ifk < foreign_keys.length; ifk++) {
            sql_create += ", " + foreign_keys[ifk];
        }

        sql_create += ")";
        var model = new QMModel(this, name, fields);

        if (this.migrate) {
            var oldObjs = [];
            var oldFields = this.retrieveFields(name);
            if (!isEmpty(oldFields)) {
                var oldModel = new QMModel(this, name, oldFields);
                oldObjs = oldModel.all();
                this._runSQL("DROP TABLE " + name);
            }

            //Run create table
            this._runSQL(sql_create);

            for (var i=0; i< oldObjs.length; i++) {
                for (var field in oldObjs[i]) {
                    if (!(field in fields) && field !== '_model' && field !== 'save') {
                        delete oldObjs[i][field];
                    }
                }
                oldObjs[i].save(true);
            }
        }

        return model;
    },
    _runSQL: function(sql) {
        this.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                tx.executeSql(sql);
            }
        )
    }
};

/*******************************
  QMModel
  Define a class referencing a database table
  *****************************/

function QMModel(db, tableName, fields) {
    this.filterConditions = {};
    this.sorters = [];
    this.limiters = null;

    this._meta = {
        db: db,
        tableName: tableName,
        fields: fields,
    };
}

function isEmpty(obj) {
    // null and undefined are "empty"
    if (obj == null) return true;

    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    // If it isn't an object at this point
    // it is empty, but it can't be anything *but* empty
    // Is it empty?  Depends on your application.
    if (typeof obj !== "object") return true;

    // Otherwise, does it have any properties of its own?
    // Note that this doesn't handle
    // toString and valueOf enumeration bugs in IE < 9
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }

    return true;
}

QMModel.prototype = {
    create: function(data) {
        var obj = this.makeObject(data);
        var insertId = this.insert(obj);

        var objs = this.filter({id:insertId}).all();
        if (objs.length > 0) {
            return objs[0];
        }

        return null;
    },
    filter: function(conditions) {
        this.filterConditions = conditions;
        return this;
    },
    order: function(sorters) {
        if (typeof sorters === 'string') {
            if (!this.sorters) {
                this.sorters = [];
            }
            this.sorters.push(sorters);
        }
        else if (Array.isArray(sorters)) {
            this.sorters = sorters;
        }
        return this;
    },
    limit: function(limiter) {
        this.limiter = limiter;
        return this;
    },
    get: function() {
        var objs = this.limit(1).all();
        if (objs.length > 0)
            return objs[0];

        return null;
    },
    all: function() {
        var sql = "SELECT ";
        var fields = [];
        for (var field in this._meta.fields) {
            fields.push(field);
        }

        sql += fields.join(',');
        sql += " FROM " + this._meta.tableName;
        sql += this._defineWhereClause();

        if (this.sorters && this.sorters.constructor === String) {
            this.sorters = [this.sorters];
        }

        if (this.sorters && this.sorters.length > 0) {
            sql += " ORDER BY ";
            for (var idxOrder=0; idxOrder < this.sorters.length; idxOrder++) {
                if (idxOrder > 0) sql += ", ";
                var ord = this.sorters[idxOrder];
                if (ord[0] === '-') {
                    sql += ord.substring(1) + " DESC ";
                }
                else {
                    sql += ord;
                }
            }
        }

        if (this.limiter) {
            sql += " LIMIT " + this.limiter;
        }

        var rs = [];

        this._meta.db.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql)

                //console.log("RESULT SET: " + rs);
            }
        )

        var objs = [];
        for (var i=0; i < rs.rows.length; i++) {
            var item = rs.rows.item(i);
            var obj = this.makeObject(item);
            objs.push(obj);
        }

        this.filterConditions = {};
        this.limiter = null;
        this.sorters = null;

        return objs;
    },
    update: function(obj) {
        var sql = "UPDATE " + this._meta.tableName + " SET ";
        var idx = 0;
        for (var field in obj) {
            if (field === '_model' || field === 'save')
                continue;
            if (field === 'id' && isEmpty(obj[field]))
                continue;

            if (idx > 0) sql += ",";
            sql += field + " = " + this._convertToSqlType(obj[field]) + "";
            idx++;
        }
        sql += this._defineWhereClause(this.filterConditions);

        this._meta.db._runSQL(sql);
        this.filterConditions = {};
    },
    insert: function(obj) {
        var sql = "INSERT INTO " + this._meta.tableName + "(";
        var fields = [];
        var values = [];
        for (var field in obj) {
            if (field === '_model' || field === 'save')
                continue;
            if (field === 'id' && isEmpty(obj[field]))
                continue;
            fields.push(field);
            if (obj[field]) {
                values.push(this._convertToSqlType(obj[field]));
            } else {
                values.push('NULL');
            }
        }
        sql += fields.join(', ');
        sql += ") VALUES (" + values.join(', ') + ")";

        var rs;
        this._meta.db.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql);
            }
        )

        return rs.insertId;
    },
    remove: function() {
        var sql = "DELETE FROM " + this._meta.tableName;
        sql += this._defineWhereClause();
        this._meta.db._runSQL(sql);
        this.filterConditions = {};
    },
    _typeof : function (value) {
        var l_type = typeof value;

        // adjusting type based on object instanceof
        if (l_type === 'object') {
            if (value instanceof Date) {
                l_type = 'date';
            } else
            if (value instanceof Number) {
                l_type = 'number';
            } else
            if (value instanceof String) {
                l_type = 'string';
            } else
            if (value instanceof Boolean) {
                l_type = 'boolean';
            }
        }

        return l_type;
    },
    _convertToSqlType: function (value) {
        var l_type = this._typeof(value);

        if (l_type === 'boolean') {
            value = value ? 1 : 0;
            l_type = 'number';
        }
        if (l_type === 'date') {
            value = value.toISOString();
            l_type = 'string';
        }
        if (l_type === 'string') {
            value = "'" + value.replace("'", "''") + "'";
        }

        return value;
    },
    _convertFromSqlValue: function (value, definition) {
        if (!definition) return value;
        if (!value) return value;

        var l_type = this._typeof(value);
        var l_desiredType = definition.type;

        if (l_type === 'number') {
            if (l_desiredType === 'BOOLEAN') {
                value = value !== 0;
            }
        }

        if (l_type === 'string') {
            if ((l_desiredType === 'FLOAT') ||
                (l_desiredType === 'REAL') ||
                (l_desiredType === 'INTEGER') ||
                (l_desiredType === 'FK') ||
                (l_desiredType === 'PK')) {
                value = Number(value);
            } else
            if ((l_desiredType === 'DATE') ||
                (l_desiredType === 'DATETIME')) {
                value = new Date(value);
            } else
            if (l_desiredType === 'BOOLEAN') {
                switch (value) {
                    case "true":
                    case "1":
                    case "on":
                    case "yes":
                        value = true;
                        break;
                    default:
                        var isNum = value.match(/^[0-9]+$/);
                        if (!isNum)
                            value = false;
                        else
                            value = value !== 0;
                        break;
                }
            }
        }

        return value;
    },
    _defineWhereClause: function() {
        var sql = '';
        var idx = 0;

        for (var cond in this.filterConditions) {
            if (idx > 0) sql += " AND ";
            var operator;
            var newOperator = '=';
            var field = cond;
            var position;
            if (cond.indexOf('__') > -1) {
                var operands = cond.split('__');
                field = operands[0];
                operator = operands[1];

                switch(operator) {
                case 'gt':
                    newOperator = '>'; break;
                case 'ge':
                    newOperator = '>='; break;
                case 'lt':
                    newOperator = '<'; break;
                case 'le':
                    newOperator = '<='; break;
                case 'null':
                    if (this.filterConditions[cond])
                        newOperator = 'IS NULL';
                    else
                        newOperator = 'IS NOT NULL';
                    break;
                case 'like':
                    newOperator = 'LIKE';
                    position = 'BEGINEND';
                    break;
                case 'startswith':
                    newOperator = 'LIKE';
                    position = 'END';
                    break;
                case 'endswith':
                    newOperator = 'LIKE';
                    position = 'BEGIN';
                    break;
                }
            }
            else if (this.filterConditions[cond].constructor === Array) {
                newOperator = 'IN';
            }

            sql += field + " " + newOperator + " ";
            if (newOperator === 'LIKE') {
                sql += "'";
                if (position.indexOf('BEGIN') > -1) {
                    sql += "%";
                }
                sql += this.filterConditions[cond];
                if (position.indexOf('END') > -1) {
                    sql += "%";
                }
                sql += "'";
            } else if (operator !== 'null') {
                if (this.filterConditions[cond].constructor === String) {
                    sql += "'" + this.filterConditions[cond] + "'";
                } else if (newOperator === 'IN') {
                    sql += "('" + this.filterConditions[cond].join("','") + "')";
                }
                else {
                    sql += this._convertToSqlType(this.filterConditions[cond]);
                }
            }
            idx++;
        }

        if (sql.length > 0) {
            sql = " WHERE " + sql;
        }

        return sql;
    },
    makeObject: function(values) {
        var obj = new QMObject(this);
        for (var field in values) {
            if (field.startsWith('_') || field === 'save' || !(field in this._meta.fields))
                continue;
            obj[field] = this._convertFromSqlValue(values[field], this._meta.fields[field]);
        }
        return obj;
    }
};

/**************************************
  QMObject
  reference a single instance of a object in the database
  *************************************/
function QMObject(model) {
    this._model = model
    this.id = null;
}

QMObject.prototype = {
    //Functions for single object
    save: function(forceInsert) {
       if (typeof forceInsert === 'undefined') { forceInsert = false; }
       if (this.id && !forceInsert) {
           this._model.filter({id: this.id}).update(this);
       } else {
           this.id = this._model.insert(this);
       }
       return this;
    }
}

/*******************************************
  QMField
  Define a database field with attributes
  ******************************************/

function QMField(type, label, params) {
    this.type = type;
    this.params = params;
}

//TODO: Migrations!
//TODO: Replace concatenations with binds '?'
<commit_msg>formating code<commit_after>.import QtQuick.LocalStorage 2.0 as Sql

/*
  new QMDatabase('myApp', '1.0')
  define : returns an object with functions create/filter/delete
  create: returns an object with the properties
  */

function QMDatabase(appName, version) {
    this.migrate = false;
    //Tables to handle version control
    var qMDatabase = this;
    this.conn = Sql.LocalStorage.openDatabaseSync(appName + '_db', "1.0", appName, 100000,
        function(db) {
            qMDatabase.migrate = true;
            console.log("*** DATABASE DOESNT EXIST ****");
            db.changeVersion("", "1.0");
        }
    );
    var AppVersion = this.define('__AppVersion__', {
        appName: this.String('App Name', {
            accept_null: false
        }),
        version: this.String('Version', {
            accept_null: false
        })
    });

    var appVersion = AppVersion.filter({
        appName: appName
    }).get();

    if (appVersion) {
        if (appVersion.version !== version) {
            appVersion.version = version;
            appVersion.save();
            this.migrate = true;
        }
    } else {
        appVersion = AppVersion.create({
            appName: appName,
            version: version
        });
        this.migrate = true;
    }
}

QMDatabase.prototype = {
    constructor: QMDatabase,

    String: function(label, params) {
        return new QMField('TEXT', label, params);
    },
    Integer: function(label, params) {
        return new QMField('INTEGER', label, params);
    },
    Float: function(label, params) {
        return new QMField('FLOAT', label, params);
    },
    Real: function(label, params) {
        return new QMField('REAL', label, params);
    },
    Date: function(label, params) {
        return new QMField('DATE', label, params);
    },
    DateTime: function(label, params) {
        return new QMField('DATETIME', label, params);
    },
    Boolean: function(label, params) {
        return new QMField('BOOLEAN', label, params);
    },
    PK: function(label, params) {
        return new QMField('PK', label, params);
    },
    FK: function(label, params) {
        return new QMField('FK', label, params);
    },
    _defineField: function(column, data) {
        var sql;
        var items = [];
        var fk = [];

        //If is a foreign key
        if (data.type === 'FK') {
            items.push(column);
            items.push('INTEGER');
            fk.push('FOREIGN KEY(' + column + ')');
        } else if (data.type === 'PK') {
            items.push(column);
            items.push('INTEGER PRIMARY KEY');
        } else {
            items.push(column);
            items.push(data.type);
        }

        for (var param in data.params) {
            switch (param) {
                case 'accept_null':
                    if (!data.params[param]) {
                        items.push('NOT NULL');
                    }
                    break;
                case 'unique':
                    if (unique) {
                        items.push('UNIQUE');
                    }
                    break;
                case 'references':
                    fk.push('REFERENCES ' + data.params[param] + '(id) ON DELETE CASCADE ON UPDATE CASCADE');
                    break;
                case 'default':
                    items.push('DEFAULT ' + data.params[param]);
                    break;

            }
        }

        return {
            field: items.join(' '),
            fk: fk.join(' ')
        };
    },
    retrieveFields: function(name) {
        var rs;
        var sql = "PRAGMA table_info(" + name + ")";
        this.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql);
            }
        )

        var fields = {};
        for (var idx = 0; idx < rs.rows.length; idx++) {
            fields[rs.rows[idx].name] = null;
        }

        return fields;
    },
    define: function(name, fields) {
        var sql_create = "CREATE TABLE IF NOT EXISTS " + name + " (";
        var idx = 0;
        this.properties = {};
        this.tableName = name;

        fields['id'] = this.PK('Primary Key', []);

        var foreign_keys = [];
        for (var column in fields) {
            var definitions = fields[column];
            var field_data = this._defineField(column, fields[column]);
            if (idx > 0) sql_create += ", ";
            sql_create += field_data['field'];

            if (field_data['fk'].length > 0) {
                foreign_keys.push(field_data['fk']);
            }
            idx++;
        }

        //Create foreign key references
        for (var ifk = 0; ifk < foreign_keys.length; ifk++) {
            sql_create += ", " + foreign_keys[ifk];
        }

        sql_create += ")";
        var model = new QMModel(this, name, fields);

        if (this.migrate) {
            var oldObjs = [];
            var oldFields = this.retrieveFields(name);
            if (!isEmpty(oldFields)) {
                var oldModel = new QMModel(this, name, oldFields);
                oldObjs = oldModel.all();
                this._runSQL("DROP TABLE " + name);
            }

            //Run create table
            this._runSQL(sql_create);

            for (var i = 0; i < oldObjs.length; i++) {
                for (var field in oldObjs[i]) {
                    if (!(field in fields) && field !== '_model' && field !== 'save') {
                        delete oldObjs[i][field];
                    }
                }
                oldObjs[i].save(true);
            }
        }

        return model;
    },
    _runSQL: function(sql) {
        this.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                tx.executeSql(sql);
            }
        )
    }
};

/*******************************
  QMModel
  Define a class referencing a database table
  *****************************/

function QMModel(db, tableName, fields) {
    this.filterConditions = {};
    this.sorters = [];
    this.limiters = null;

    this._meta = {
        db: db,
        tableName: tableName,
        fields: fields,
    };
}

function isEmpty(obj) {
    // null and undefined are "empty"
    if (obj == null) return true;

    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length > 0) return false;
    if (obj.length === 0) return true;

    // If it isn't an object at this point
    // it is empty, but it can't be anything *but* empty
    // Is it empty?  Depends on your application.
    if (typeof obj !== "object") return true;

    // Otherwise, does it have any properties of its own?
    // Note that this doesn't handle
    // toString and valueOf enumeration bugs in IE < 9
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }

    return true;
}

QMModel.prototype = {
    create: function(data) {
        var obj = this.makeObject(data);
        var insertId = this.insert(obj);

        var objs = this.filter({
            id: insertId
        }).all();
        if (objs.length > 0) {
            return objs[0];
        }

        return null;
    },
    filter: function(conditions) {
        this.filterConditions = conditions;
        return this;
    },
    order: function(sorters) {
        if (typeof sorters === 'string') {
            if (!this.sorters) {
                this.sorters = [];
            }
            this.sorters.push(sorters);
        } else if (Array.isArray(sorters)) {
            this.sorters = sorters;
        }
        return this;
    },
    limit: function(limiter) {
        this.limiter = limiter;
        return this;
    },
    get: function() {
        var objs = this.limit(1).all();
        if (objs.length > 0)
            return objs[0];

        return null;
    },
    all: function() {
        var sql = "SELECT ";
        var fields = [];
        for (var field in this._meta.fields) {
            fields.push(field);
        }

        sql += fields.join(',');
        sql += " FROM " + this._meta.tableName;
        sql += this._defineWhereClause();

        if (this.sorters && this.sorters.constructor === String) {
            this.sorters = [this.sorters];
        }

        if (this.sorters && this.sorters.length > 0) {
            sql += " ORDER BY ";
            for (var idxOrder = 0; idxOrder < this.sorters.length; idxOrder++) {
                if (idxOrder > 0) sql += ", ";
                var ord = this.sorters[idxOrder];
                if (ord[0] === '-') {
                    sql += ord.substring(1) + " DESC ";
                } else {
                    sql += ord;
                }
            }
        }

        if (this.limiter) {
            sql += " LIMIT " + this.limiter;
        }

        var rs = [];

        this._meta.db.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql)

                //console.log("RESULT SET: " + rs);
            }
        )

        var objs = [];
        for (var i = 0; i < rs.rows.length; i++) {
            var item = rs.rows.item(i);
            var obj = this.makeObject(item);
            objs.push(obj);
        }

        this.filterConditions = {};
        this.limiter = null;
        this.sorters = null;

        return objs;
    },
    update: function(obj) {
        var sql = "UPDATE " + this._meta.tableName + " SET ";
        var idx = 0;
        for (var field in obj) {
            if (field === '_model' || field === 'save')
                continue;
            if (field === 'id' && isEmpty(obj[field]))
                continue;

            if (idx > 0) sql += ",";
            sql += field + " = " + this._convertToSqlType(obj[field]) + "";
            idx++;
        }
        sql += this._defineWhereClause(this.filterConditions);

        this._meta.db._runSQL(sql);
        this.filterConditions = {};
    },
    insert: function(obj) {
        var sql = "INSERT INTO " + this._meta.tableName + "(";
        var fields = [];
        var values = [];
        for (var field in obj) {
            if (field === '_model' || field === 'save')
                continue;
            if (field === 'id' && isEmpty(obj[field]))
                continue;
            fields.push(field);
            if (obj[field]) {
                values.push(this._convertToSqlType(obj[field]));
            } else {
                values.push('NULL');
            }
        }
        sql += fields.join(', ');
        sql += ") VALUES (" + values.join(', ') + ")";

        var rs;
        this._meta.db.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql);
            }
        )

        return rs.insertId;
    },
    remove: function() {
        var sql = "DELETE FROM " + this._meta.tableName;
        sql += this._defineWhereClause();
        this._meta.db._runSQL(sql);
        this.filterConditions = {};
    },
    _typeof: function(value) {
        var l_type = typeof value;

        // adjusting type based on object instanceof
        if (l_type === 'object') {
            if (value instanceof Date) {
                l_type = 'date';
            } else
            if (value instanceof Number) {
                l_type = 'number';
            } else
            if (value instanceof String) {
                l_type = 'string';
            } else
            if (value instanceof Boolean) {
                l_type = 'boolean';
            }
        }

        return l_type;
    },
    _convertToSqlType: function(value) {
        var l_type = this._typeof(value);

        if (l_type === 'boolean') {
            value = value ? 1 : 0;
            l_type = 'number';
        }
        if (l_type === 'date') {
            value = value.toISOString();
            l_type = 'string';
        }
        if (l_type === 'string') {
            value = "'" + value.replace("'", "''") + "'";
        }

        return value;
    },
    _convertFromSqlValue: function(value, definition) {
        if (!definition) return value;
        if (!value) return value;

        var l_type = this._typeof(value);
        var l_desiredType = definition.type;

        if (l_type === 'number') {
            if (l_desiredType === 'BOOLEAN') {
                value = value !== 0;
            }
        }

        if (l_type === 'string') {
            if ((l_desiredType === 'FLOAT') ||
                (l_desiredType === 'REAL') ||
                (l_desiredType === 'INTEGER') ||
                (l_desiredType === 'FK') ||
                (l_desiredType === 'PK')) {
                value = Number(value);
            } else
            if ((l_desiredType === 'DATE') ||
                (l_desiredType === 'DATETIME')) {
                value = new Date(value);
            } else
            if (l_desiredType === 'BOOLEAN') {
                switch (value) {
                    case "true":
                    case "1":
                    case "on":
                    case "yes":
                        value = true;
                        break;
                    default:
                        var isNum = value.match(/^[0-9]+$/);
                        if (!isNum)
                            value = false;
                        else
                            value = value !== 0;
                        break;
                }
            }
        }

        return value;
    },
    _defineWhereClause: function() {
        var sql = '';
        var idx = 0;

        for (var cond in this.filterConditions) {
            if (idx > 0) sql += " AND ";
            var operator;
            var newOperator = '=';
            var field = cond;
            var position;
            if (cond.indexOf('__') > -1) {
                var operands = cond.split('__');
                field = operands[0];
                operator = operands[1];

                switch (operator) {
                    case 'gt':
                        newOperator = '>';
                        break;
                    case 'ge':
                        newOperator = '>=';
                        break;
                    case 'lt':
                        newOperator = '<';
                        break;
                    case 'le':
                        newOperator = '<=';
                        break;
                    case 'null':
                        if (this.filterConditions[cond])
                            newOperator = 'IS NULL';
                        else
                            newOperator = 'IS NOT NULL';
                        break;
                    case 'like':
                        newOperator = 'LIKE';
                        position = 'BEGINEND';
                        break;
                    case 'startswith':
                        newOperator = 'LIKE';
                        position = 'END';
                        break;
                    case 'endswith':
                        newOperator = 'LIKE';
                        position = 'BEGIN';
                        break;
                }
            } else if (this.filterConditions[cond].constructor === Array) {
                newOperator = 'IN';
            }

            sql += field + " " + newOperator + " ";
            if (newOperator === 'LIKE') {
                sql += "'";
                if (position.indexOf('BEGIN') > -1) {
                    sql += "%";
                }
                sql += this.filterConditions[cond];
                if (position.indexOf('END') > -1) {
                    sql += "%";
                }
                sql += "'";
            } else if (operator !== 'null') {
                if (this.filterConditions[cond].constructor === String) {
                    sql += "'" + this.filterConditions[cond] + "'";
                } else if (newOperator === 'IN') {
                    sql += "('" + this.filterConditions[cond].join("','") + "')";
                } else {
                    sql += this._convertToSqlType(this.filterConditions[cond]);
                }
            }
            idx++;
        }

        if (sql.length > 0) {
            sql = " WHERE " + sql;
        }

        return sql;
    },
    makeObject: function(values) {
        var obj = new QMObject(this);
        for (var field in values) {
            if (field.startsWith('_') || field === 'save' || !(field in this._meta.fields))
                continue;
            obj[field] = this._convertFromSqlValue(values[field], this._meta.fields[field]);
        }
        return obj;
    }
};

/**************************************
  QMObject
  reference a single instance of a object in the database
  *************************************/
function QMObject(model) {
    this._model = model;
    this.id = null;
}

QMObject.prototype = {
    //Functions for single object
    save: function(forceInsert) {
        if (typeof forceInsert === 'undefined') {
            forceInsert = false;
        }
        if (this.id && !forceInsert) {
            this._model.filter({
                id: this.id
            }).update(this);
        } else {
            this.id = this._model.insert(this);
        }
        return this;
    }
}

/*******************************************
  QMField
  Define a database field with attributes
  ******************************************/

function QMField(type, label, params) {
    this.type = type;
    this.params = params;
}

//TODO: Migrations!
//TODO: Replace concatenations with binds '?'
<|endoftext|>