<commit_before>
$(function() {

    $("#addButton").click(function() {
        // Hide the modal
        $('#alignmentsModal').modal('hide');
        $('.noAlignmentsYet').hide();
        // Dig out the data
        var formEducationAlignment = $('#educationalAlignment').val();
        var formAlignmentType = $('#alignmentType').val();
        var formDotNotation = $('#dotNotation').val();
        var formDescription = $('#description').val();
        var formItemUrl = $('#itemURL').val();
        var formGuid = $('#itemGUID').val();

        // Check to see if the current Alignment is already Added to the currentAlignmentArray
        // @TODO These should be a hash but dont have time
        var alreadyExists = false;
        for (i = 0; i < currentAlignmentArray.length; i++) {
            if ((currentAlignmentArray[i].educationalAlignment == formEducationAlignment) &&
                (currentAlignmentArray[i].alignmentType == formAlignmentType) &&
                (currentAlignmentArray[i].dotNotation == formDotNotation) &&
                (currentAlignmentArray[i].itemURL == formItemUrl) &&
                (currentAlignmentArray[i].description == formDescription) &&
                (currentAlignmentArray[i].guid == formGuid)
            ) {
                alreadyExists = true;
            }
        }

        // Okay add it.
        if (!alreadyExists) {
            blankCurrentAlignment();

            // Add to the currentAlignmentArray
            currentAlignmentArray.push({
                'educationalAlignment'  : formEducationAlignment,
                'alignmentType'         : formAlignmentType,
                'dotNotation'           : formDotNotation,
                'itemURL'               : formItemUrl,
                'description'           : formDescription,
                'guid'                  : formGuid
            });

            //Updates the Alignment Table on the Alignment Tab
            if (formDotNotation == '') formDotNotation = 'N/A';
            $('#currentAlignmentTable > tbody:last').append('
<input type="checkbox" value="'+formGuid+'" />'+ formDotNotation +'	'+ formAlignmentType +'
');

            currentAlignmentItem = currentAlignmentCounter;
            currentAlignmentCounter++;
        }

        updateTextArea();

//        $("#multiItemSelector input[type=checkbox]:checked").each(function(i,obj) {
//
//            //Check to see if the EducationalArray already contains this Alignment
//            var inEducationalAlignmentTaggedItems = false;
//            if (typeof items[obj.id].educationAlignmentArray[0] !== 'undefined' && items[obj.id].educationAlignmentArray[0] !== null){
//                for (var j = 0; j < items[obj.id].educationAlignmentArray.length; j++) {
//                    if(	(items[obj.id].educationAlignmentArray[j].educationalAlignment == $('#educationalAlignment').val()) &&
//                        (items[obj.id].educationAlignmentArray[j].alignmentType == $('#alignmentType').val()) &&
//                        (items[obj.id].educationAlignmentArray[j].dotNotation == $('#dotNotation').val()) &&
//                        (items[obj.id].educationAlignmentArray[j].itemURL == $('#itemURL').val()) &&
//                        (items[obj.id].educationAlignmentArray[j].description == $('#description').val() ) &&
//                        (items[obj.id].educationAlignmentArray[j].guid == $('#itemGUID').val() )  ){
//                        inEducationalAlignmentTaggedItems = true;
//                        if (items[obj.id].title == '') alert("This alignment has already been added to the Tagged Item: " + items[obj.id].id );
//                        if (items[obj.id].title != '') alert("This alignment has already been added to the Tagged Item: " + items[obj.id].title );
//                    }
//                }
//                if (!inEducationalAlignmentTaggedItems) {
//                    // @TODO Why was he using a settimeout here for this?  If it doesn't exist, push it in -- in 3 seconds?  huh?
//                    setTimeout(items[obj.id].educationAlignmentArray.push({'educationalAlignment':metaSourceValue1,'alignmentType':metaSourceValue2,'dotNotation':metaSourceValue3,'itemURL':metaSourceValue4,'description':metaSourceValue5,'guid':metaSourceValue6}),3000);
//                }
//            }
//            // @TODO Why was he using a settimeout here for this?
//            else setTimeout(items[obj.id].educationAlignmentArray.push({'educationalAlignment':metaSourceValue1,'alignmentType':metaSourceValue2,'dotNotation':metaSourceValue3,'itemURL':metaSourceValue4,'description':metaSourceValue5,'guid':metaSourceValue6}),3000);
//
//        });

        return false;
    });

});<commit_msg>Add button is now short and sweet<commit_after>
$(function() {

    $("#addButton").click(function() {
        // Hide the modal
        $('#alignmentsModal').modal('hide');
        $('.noAlignmentsYet').hide();

        // Dig out the data
        var formEducationAlignment = $('#educationalAlignment').val();
        var formAlignmentType = $('#alignmentType').val();
        var formDotNotation = $('#dotNotation').val();
        var formDescription = $('#description').val();
        var formItemUrl = $('#itemURL').val();
        var formGuid = $('#itemGUID').val();

        // Okay add it.
        if (alignments[formGuid] == undefined) {

            // Add to alignment hash
            alignments[formGuid] = {
                'educationalAlignment' : formEducationAlignment,
                'alignmentType' : formAlignmentType,
                'dotNotation' : formDotNotation,
                'description' : formDescription,
                'itemURL' : formItemUrl,
                'guid' : formGuid
            };

            //Updates the Alignment Table on the Alignment Tab
            if (formDotNotation == '') formDotNotation = 'N/A';
            $('#currentAlignmentTable > tbody:last').append('
<input type="checkbox" class="alignment-checkbox" value="'+formGuid+'" />'+ formDotNotation +'	'+ formAlignmentType +'
');

        }

        updateTextArea();

        // Zero the form
        $('#alignmentType').val('');
        $('#dotNotation').val('');
        $('#description').val('');
        $('#itemURL').val('');
        $('#itemGUID').val('');

        return false;
    });

});<|endoftext|>


<commit_before>steal('funcunit/qunit').then('./route.js',function(){

module("jquery/dom/route")

test("deparam", function(){
	$.route.routes = {};
	$.route(":page",{
		page: "index"
	})
	var obj = $.route.deparam("jQuery.Controller");
	same(obj, {
		page : "jQuery.Controller"
	});

	obj = $.route.deparam("");

	same(obj, {
		page : "index"
	});

	obj = $.route.deparam("jQuery.Controller&where=there");

	same(obj, {
		page : "jQuery.Controller",
		where: "there"
	});
})

test("param", function(){
	$.route.routes = {};
	$.route("pages/:page",{
		page: "index"
	})
	var res = $.route.param({page: "foo"});

	equals(res, "pages/foo")
})

test("light param", function(){
	$.route.routes = {};
	$.route(":page",{
		page: "index"
	})

	var res = $.route.param({page: "index"});
	equals(res, "")
})

test("precident", function(){
	$.route.routes = {};
	$.route(":who",{who: "index"});
	$.route("search/:search");

	var obj = $.route.deparam("jQuery.Controller");
	same(obj, {
		who : "jQuery.Controller"
	});

	obj = $.route.deparam("search/jQuery.Controller");
	same(obj, {
		search : "jQuery.Controller"
	},"bad deparam");

	equal( $.route.param({
			search : "jQuery.Controller"
		}),
		"search/jQuery.Controller" , "bad param");

	equal( $.route.param({
			who : "jQuery.Controller"
		}),
		"jQuery.Controller" );
})

test("precident2", function(){
	$.route.routes = {};
	$.route(":type",{who: "index"});
	$.route(":type/:id");

	equal( $.route.param({
			type : "foo",
			id: "bar"
		}),
		"foo/bar" );
})

test("linkTo", function(){
    $.route.routes = {};
    $.route(":foo");
    var res = $.route.link("Hello",{foo: "bar", baz: 'foo'});
    equal( res, 'Hello');
})

})
<commit_msg>dom/route: Added more unit tests. Some tests fail!<commit_after>steal('funcunit/qunit').then('./route.js',function(){

module("jquery/dom/route")

test("deparam", function(){
	$.route.routes = {};
	$.route(":page",{
		page: "index"
	})

	var obj = $.route.deparam("jQuery.Controller");
	same(obj, {
		page : "jQuery.Controller"
	});

	obj = $.route.deparam("");
	same(obj, {
		page : "index"
	});

	obj = $.route.deparam("jQuery.Controller&where=there");
	same(obj, {
		page : "jQuery.Controller",
		where: "there"
	});

    $.route.routes = {};
    $.route(":page/:index",{
        page: "index",
        index: "foo"
	});

    obj = $.route.deparam("jQuery.Controller/&where=there");
	same(obj, {
		page : "jQuery.Controller",
        index: "foo",
		where: "there"
	});
})

test("deparam of invalid url", function(){
    $.route.routes = {};
    $.route("pages/:var1/:var2/:var3", {
        var1: 'default1',
        var2: 'default2',
        var3: 'default3'
    });

    // This path does not match the above route, and since the hash is not
    // a &key=value list there should not be data.
    obj = $.route.deparam("pages//");
	same(obj, {});

    // A valid path with invalid parameters should return the path data but
    // ignore the parameters.
    obj = $.route.deparam("pages/val1/val2/val3&invalid-parameters");
	same(obj, {
        var1: 'val1',
        var2: 'val2',
        var3: 'val3'
    });
})

test("param", function(){
	$.route.routes = {};
	$.route("pages/:page",{
		page: "index"
	})

	var res = $.route.param({page: "foo"});
	equals(res, "pages/foo")

	res = $.route.param({page: "foo", index: "bar"});
	equals(res, "pages/foo&index=bar")

	$.route("pages/:page/:foo",{
		page: "index",
        foo: "bar"
	})

    res = $.route.param({page: "foo", foo: "bar", where: "there"});
	equals(res, "pages/foo/&where=there")

    // There is no matching route so the hash should be empty.
    res = $.route.param({});
	equals(res, "")

    $.route.routes = {};

    res = $.route.param({page: "foo", bar: "baz", where: "there"});
	equals(res, "&page=foo&bar=baz&where=there")

    res = $.route.param({});
	equals(res, "")
})

test("light param", function(){
	$.route.routes = {};
	$.route(":page",{
		page: "index"
	})

	var res = $.route.param({page: "index"});
	equals(res, "")

    $.route("pages/:p1/:p2/:p3",{
		p1: "index",
        p2: "foo",
        p3: "bar"
	})

    res = $.route.param({p1: "index", p2: "foo", p3: "bar"});
	equals(res, "pages///")

    res = $.route.param({p1: "index", p2: "baz", p3: "bar"});
	equals(res, "pages//baz/")
})

test("param-deparam", function(){

	$.route(":page/:type",{
		page: "index",
        type: "foo"
	})

    var data = {page: "jQuery.Controller", type: "document", bar: "baz", where: "there"};
    var res = $.route.param(data);
    var obj = $.route.deparam(res);
	same(data, obj)

    data = {page: "jQuery.Controller", type: "foo", bar: "baz", where: "there"};
    res = $.route.param(data);
    obj = $.route.deparam(res);
	same(data, obj)

    data = {page: "index", type: "foo", bar: "baz", where: "there"};
    res = $.route.param(data);
    obj = $.route.deparam(res);
	same(data, obj)

    $.route.routes = {};

    data = {page: "foo", bar: "baz", where: "there"};
    res = $.route.param(data);
    obj = $.route.deparam(res);
	same(data, obj)
})

test("precident", function(){
	$.route.routes = {};
	$.route(":who",{who: "index"});
	$.route("search/:search");

	var obj = $.route.deparam("jQuery.Controller");
	same(obj, {
		who : "jQuery.Controller"
	});

	obj = $.route.deparam("search/jQuery.Controller");
	same(obj, {
		search : "jQuery.Controller"
	},"bad deparam");

	equal( $.route.param({
			search : "jQuery.Controller"
		}),
		"search/jQuery.Controller" , "bad param");

	equal( $.route.param({
			who : "jQuery.Controller"
		}),
		"jQuery.Controller" );
})

test("precident2", function(){
	$.route.routes = {};
	$.route(":type",{who: "index"});
	$.route(":type/:id");

	equal( $.route.param({
			type : "foo",
			id: "bar"
		}),
		"foo/bar" );
})

test("linkTo", function(){
    $.route.routes = {};
    $.route(":foo");
    var res = $.route.link("Hello",{foo: "bar", baz: 'foo'});
    equal( res, 'Hello');
})

})
<|endoftext|>


<commit_before>function giveChange(value) {
  var change = [];
  var coins = [25, 10, 5, 1];

  // run through each item in coins
  for (var i = 0; i <= coins.length; i++) {

    if (value / coins[i])
    var toChange = Math.floor(value / coins[i]);
    change.push(coins[i]);
  }
  return change;
}

$('#coin-changer').on('submit', function(ev) {
  ev.preventDefault();
  var amount = $('#convert').val();
  var change = giveChange(amount);
  console.log(change);
  $('#show-change').html();
});

// The coin changer is a simple kata. Build a function that will return an array of USD change [Quarters, Dimes, Nickels, Pennies] for any given integer.
//
// make_change(145) #=> [25, 25, 25, 25, 25, 10, 10]
// make_change(100) #=> [25, 25, 25, 25]
// make_change(75)  #=> [25, 25, 25]
// make_change(80)  #=> [25, 25, 25, 5]
// make_change(70)  #=> [25, 25, 10, 10]
// make_change(62)  #=> [25, 25, 10, 1, 1]
// make_change(4)   #=> [1, 1, 1, 1]
// make_change(0)   #=> []
<commit_msg>coin kata solution 1/25<commit_after>function giveChange(value) {
  var change = [];
  var coins = [25, 10, 5, 1];
  // run through each item in coins
  for (var i = 0; i <= coins.length; i++) {
    var times = Math.floor(value / coins[i]);
      // Number of times to push into `change`
      for (var j = 0; j < times; j++) {
        change.push(coins[i]);
      }
      value = value - (coins[i] * times);
  }
  return change;
}

$('#coin-changer').on('submit', function(ev) {
  ev.preventDefault();
  var amount = $('#convert').val();
  var change = giveChange(amount);
  console.log(change);
  $('#show-change').html();
});

// The coin changer is a simple kata. Build a function that will return an array of USD change [Quarters, Dimes, Nickels, Pennies] for any given integer.
//
// make_change(145) #=> [25, 25, 25, 25, 25, 10, 10]
// make_change(100) #=> [25, 25, 25, 25]
// make_change(75)  #=> [25, 25, 25]
// make_change(80)  #=> [25, 25, 25, 5]
// make_change(70)  #=> [25, 25, 10, 10]
// make_change(62)  #=> [25, 25, 10, 1, 1]
// make_change(4)   #=> [1, 1, 1, 1]
// make_change(0)   #=> []
<|endoftext|>


<commit_before>'use strict';

/**
 * Fetch command line arguments
 */
const argv = (() => {
  let tba = null;
  return process.argv.reduce((options, arg) => {
    if (arg.startsWith('--')) {
      tba = arg.replace(/^--/, '');
      options[tba] = true;
    } else {
      if (tba) {
        options[tba] = arg;
      }
      tba = null;
    }
    return options;
  }, {});
})();

/**
 * Core configuration details.
 */
let baseConfig = {

  /**
   * Default configuration schema.
   *
   * A schema element describes a configuration parameter.
   * argName and/or default will be used if set to source the value for a parameter.
   *
   * Example Schema:
   *
   FOO: {
      argName:     '--foo',         // Command line arg name
      description: 'Foo Parameter', // Description
      default:     'foo value'      // Default value
    },
   *
   */
  schema : {
    PROJECT:             { description: 'ACS Project Name'                        },
    PROJECT_VERSION:     { description: 'ACS Project Version (e.g. poc, mvp1)'    },
    PROJECT_PREFIX:      { description: 'ACS Project Prefix'                      },
    API_PACKAGE_PREFIX:  { description: 'API Package Prefix',  default: 'api-'    },
    API_PACKAGE_VERSION: { description: 'API Package Version', default: '0.0.1'   },
    AWS_PROFILE:         { description: 'AWS Profile',         argName: 'profile' },
    AWS_REGION:          { description: 'AWS Region',          argName: 'region'  },
    ENVIRONMENT_STAGE:   { description: 'Environment stage',   argName: 'env'     },
    ORGANIZATION:        { description: 'Environment stage',   argName: 'org'     }
  },

  /**
   * Initialize configuration.
   * @param configuration configuration setup for this session
   */
  init : (configuration) => {
    if (configuration.config) { Object.assign(baseConfig, configuration.config); }
    if (configuration.schema) { Object.assign(baseConfig.schema, configuration.schema); }
  },

  /**
   * Prime AWS environment and return AWS object.
   */
  get AWS() {
    process.env.AWS_PROFILE = config.AWS_PROFILE;
    process.env.AWS_REGION = config.AWS_REGION;

    delete this.AWS;
    return this.AWS = require('aws-sdk');
  },

  /**
   * Get a logger for this session. Sets up a bunyan logger is not already set.
   */
  get logger() {
    // If logger not specified use bunyan by default
    let bunyan = require('bunyan');
    let PrettyStream = require('bunyan-prettystream');

    let prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout);
    let prettyStdErr = new PrettyStream(); prettyStdErr.pipe(process.stderr);
    let name = config.PROJECT_PREFIX.slice(0, -1);

    delete this.logger;
    return this.logger = bunyan.createLogger({
      name: name,
      streams: [{
        level: 'debug',
        type: 'raw',
        stream: prettyStdOut,
        reemitErrorEvents: true
      }]
    });
  },
  set logger(logger) {
    delete this.logger;
    this.logger = logger;
  },

  /**
   * Get the name of a core resource with the given suffix
   * @param suffix
   * @return {*}
   */
  getResourceName : (suffix) => {
    return config.getResourcePrefix() + suffix;
  },

  /**
   * Get the prefix for all core resources
   * @return {string}
   */
  getResourcePrefix : () => {
    return config.PROJECT_PREFIX + config.ENVIRONMENT_STAGE + '-';
  },

  /**
   * Get the name of an org resource with the given suffix
   * @param suffix
   * @return {*}
   */
  getOrgResourceName : (suffix) => {
    return config.getOrgResourcePrefix() + suffix;
  },

  /**
   * Get the prefix for all org resources
   * @return {string}
   */
  getOrgResourcePrefix : () => {
    return config.PROJECT_PREFIX + config.ORGANIZATION + '-' + config.ENVIRONMENT_STAGE + '-';
  },

  /**
   * Get the name of a core parameter with the given name
   * @param name
   * @return {*}
   */
  getParameterName : (name) => {
    return config.getParameterPrefix() + name;
  },

  /**
   * Get the prefix for all core parameters
   * @return {string}
   */
  getParameterPrefix : () => {
    return config.PROJECT_PREFIX + config.ENVIRONMENT_STAGE + '-' + config.AWS_REGION + '-';
  },

  /**
   * Get the name of a org parameter with the given name
   * @param name
   * @return {*}
   */
  getOrgParameterName : (name) => {
    return config.getOrgParameterPrefix() + name;
  },

  /**
   * Get the prefix for all org parameters
   * @return {string}
   */
  getOrgParameterPrefix : () => {
    return config.PROJECT_PREFIX + config.ORGANIZATION + '-' + config.ENVIRONMENT_STAGE + '-' + config.AWS_REGION + '-';
  },

  /**
   * Get the name of the lambda zip file
   * @return {string}
   */
  getLambdaZipName : () => {
    return config.API_PACKAGE_PREFIX + config.API_PACKAGE_VERSION + '.zip';
  },

  /**
   * Get the S3 object key for the lambda bundle
   * @return {string}
   */
  getLambdaZipS3Key : () => {
    return 'api/' + config.getLambdaZipName();
  }

};

/**
 * Configuration details.
 */
let config = new Proxy(baseConfig, {
  /**
   * Get the specified config parameter (value will be sourced from command line or schema default if available)
   */
  get: (target, parameter) => {
    if (!target.hasOwnProperty(parameter)) {
      let value = undefined;
      let schema = target.schema[parameter] || {};
      if (schema.argName && argv[schema.argName]) {
        value = argv[schema.argName];
      }
      if (!value && schema.default) {
        value = schema.default;
      }
      if (value === undefined) {
        let error = (schema.argName) ?
          `${schema.description || parameter} is unset. Did you forget to set '--${schema.argName}' on command line?` :
          `${schema.description || parameter} is unset. Did you forget to set \'config.${parameter}\'?`;
        throw new Error(error);
      }
      return target.parameter = value;
    }
    return target[parameter];
  }

});

module.exports = config;
<commit_msg>Fixed desscription field of org parameter<commit_after>'use strict';

/**
 * Fetch command line arguments
 */
const argv = (() => {
  let tba = null;
  return process.argv.reduce((options, arg) => {
    if (arg.startsWith('--')) {
      tba = arg.replace(/^--/, '');
      options[tba] = true;
    } else {
      if (tba) {
        options[tba] = arg;
      }
      tba = null;
    }
    return options;
  }, {});
})();

/**
 * Core configuration details.
 */
let baseConfig = {

  /**
   * Default configuration schema.
   *
   * A schema element describes a configuration parameter.
   * argName and/or default will be used if set to source the value for a parameter.
   *
   * Example Schema:
   *
   FOO: {
      argName:     '--foo',         // Command line arg name
      description: 'Foo Parameter', // Description
      default:     'foo value'      // Default value
    },
   *
   */
  schema : {
    PROJECT:             { description: 'ACS Project Name'                        },
    PROJECT_VERSION:     { description: 'ACS Project Version (e.g. poc, mvp1)'    },
    PROJECT_PREFIX:      { description: 'ACS Project Prefix'                      },
    API_PACKAGE_PREFIX:  { description: 'API Package Prefix',  default: 'api-'    },
    API_PACKAGE_VERSION: { description: 'API Package Version', default: '0.0.1'   },
    AWS_PROFILE:         { description: 'AWS Profile',         argName: 'profile' },
    AWS_REGION:          { description: 'AWS Region',          argName: 'region'  },
    ENVIRONMENT_STAGE:   { description: 'Environment stage',   argName: 'env'     },
    ORGANIZATION:        { description: 'Organization Tag',    argName: 'org'     }
  },

  /**
   * Initialize configuration.
   * @param configuration configuration setup for this session
   */
  init : (configuration) => {
    if (configuration.config) { Object.assign(baseConfig, configuration.config); }
    if (configuration.schema) { Object.assign(baseConfig.schema, configuration.schema); }
  },

  /**
   * Prime AWS environment and return AWS object.
   */
  get AWS() {
    process.env.AWS_PROFILE = config.AWS_PROFILE;
    process.env.AWS_REGION = config.AWS_REGION;

    delete this.AWS;
    return this.AWS = require('aws-sdk');
  },

  /**
   * Get a logger for this session. Sets up a bunyan logger is not already set.
   */
  get logger() {
    // If logger not specified use bunyan by default
    let bunyan = require('bunyan');
    let PrettyStream = require('bunyan-prettystream');

    let prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout);
    let prettyStdErr = new PrettyStream(); prettyStdErr.pipe(process.stderr);
    let name = config.PROJECT_PREFIX.slice(0, -1);

    delete this.logger;
    return this.logger = bunyan.createLogger({
      name: name,
      streams: [{
        level: 'debug',
        type: 'raw',
        stream: prettyStdOut,
        reemitErrorEvents: true
      }]
    });
  },
  set logger(logger) {
    delete this.logger;
    this.logger = logger;
  },

  /**
   * Get the name of a core resource with the given suffix
   * @param suffix
   * @return {*}
   */
  getResourceName : (suffix) => {
    return config.getResourcePrefix() + suffix;
  },

  /**
   * Get the prefix for all core resources
   * @return {string}
   */
  getResourcePrefix : () => {
    return config.PROJECT_PREFIX + config.ENVIRONMENT_STAGE + '-';
  },

  /**
   * Get the name of an org resource with the given suffix
   * @param suffix
   * @return {*}
   */
  getOrgResourceName : (suffix) => {
    return config.getOrgResourcePrefix() + suffix;
  },

  /**
   * Get the prefix for all org resources
   * @return {string}
   */
  getOrgResourcePrefix : () => {
    return config.PROJECT_PREFIX + config.ORGANIZATION + '-' + config.ENVIRONMENT_STAGE + '-';
  },

  /**
   * Get the name of a core parameter with the given name
   * @param name
   * @return {*}
   */
  getParameterName : (name) => {
    return config.getParameterPrefix() + name;
  },

  /**
   * Get the prefix for all core parameters
   * @return {string}
   */
  getParameterPrefix : () => {
    return config.PROJECT_PREFIX + config.ENVIRONMENT_STAGE + '-' + config.AWS_REGION + '-';
  },

  /**
   * Get the name of a org parameter with the given name
   * @param name
   * @return {*}
   */
  getOrgParameterName : (name) => {
    return config.getOrgParameterPrefix() + name;
  },

  /**
   * Get the prefix for all org parameters
   * @return {string}
   */
  getOrgParameterPrefix : () => {
    return config.PROJECT_PREFIX + config.ORGANIZATION + '-' + config.ENVIRONMENT_STAGE + '-' + config.AWS_REGION + '-';
  },

  /**
   * Get the name of the lambda zip file
   * @return {string}
   */
  getLambdaZipName : () => {
    return config.API_PACKAGE_PREFIX + config.API_PACKAGE_VERSION + '.zip';
  },

  /**
   * Get the S3 object key for the lambda bundle
   * @return {string}
   */
  getLambdaZipS3Key : () => {
    return 'api/' + config.getLambdaZipName();
  }

};

/**
 * Configuration details.
 */
let config = new Proxy(baseConfig, {
  /**
   * Get the specified config parameter (value will be sourced from command line or schema default if available)
   */
  get: (target, parameter) => {
    if (!target.hasOwnProperty(parameter)) {
      let value = undefined;
      let schema = target.schema[parameter] || {};
      if (schema.argName && argv[schema.argName]) {
        value = argv[schema.argName];
      }
      if (!value && schema.default) {
        value = schema.default;
      }
      if (value === undefined) {
        let error = (schema.argName) ?
          `${schema.description || parameter} is unset. Did you forget to set '--${schema.argName}' on command line?` :
          `${schema.description || parameter} is unset. Did you forget to set \'config.${parameter}\'?`;
        throw new Error(error);
      }
      return target.parameter = value;
    }
    return target[parameter];
  }

});

module.exports = config;
<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"), require("../../mode/sql/sql"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror", "../../mode/sql/sql"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  var tables;
  var defaultTable;
  var keywords;
  var CONS = {
    QUERY_DIV: ";",
    ALIAS_KEYWORD: "AS"
  };
  var Pos = CodeMirror.Pos;

  function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" }

  function getKeywords(editor) {
    var mode = editor.doc.modeOption;
    if (mode === "sql") mode = "text/x-sql";
    return CodeMirror.resolveMode(mode).keywords;
  }

  function getText(item) {
    return typeof item == "string" ? item : item.text;
  }

  function wrapTable(name, value) {
    if (isArray(value)) value = {columns: value}
    if (!value.text) value.text = name
    return value
  }

  function parseTables(input) {
    var result = {}
    if (isArray(input)) {
      for (var i = input.length - 1; i >= 0; i--) {
        var item = input[i]
        result[getText(item).toUpperCase()] = wrapTable(getText(item), item)
      }
    } else if (input) {
      for (var name in input)
        result[name.toUpperCase()] = wrapTable(name, input[name])
    }
    return result
  }

  function getTable(name) {
    return tables[name.toUpperCase()]
  }

  function shallowClone(object) {
    var result = {};
    for (var key in object) if (object.hasOwnProperty(key))
      result[key] = object[key];
    return result;
  }

  function match(string, word) {
    var len = string.length;
    var sub = getText(word).substr(0, len);
    return string.toUpperCase() === sub.toUpperCase();
  }

  function addMatches(result, search, wordlist, formatter) {
    if (isArray(wordlist)) {
      for (var i = 0; i < wordlist.length; i++)
        if (match(search, wordlist[i])) result.push(formatter(wordlist[i]))
    } else {
      for (var word in wordlist) if (wordlist.hasOwnProperty(word)) {
        var val = wordlist[word]
        if (!val || val === true)
          val = word
        else
          val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text
        if (match(search, val)) result.push(formatter(val))
      }
    }
  }

  function cleanName(name) {
    // Get rid name from backticks(`) and preceding dot(.)
    if (name.charAt(0) == ".") {
      name = name.substr(1);
    }
    return name.replace(/`/g, "");
  }

  function insertBackticks(name) {
    var nameParts = getText(name).split(".");
    for (var i = 0; i < nameParts.length; i++)
      nameParts[i] = "`" + nameParts[i] + "`";
    var escaped = nameParts.join(".");
    if (typeof name == "string") return escaped;
    name = shallowClone(name);
    name.text = escaped;
    return name;
  }

  function nameCompletion(cur, token, result, editor) {
    // Try to complete table, column names and return start position of completion
    var useBacktick = false;
    var nameParts = [];
    var start = token.start;
    var cont = true;
    while (cont) {
      cont = (token.string.charAt(0) == ".");
      useBacktick = useBacktick || (token.string.charAt(0) == "`");

      start = token.start;
      nameParts.unshift(cleanName(token.string));

      token = editor.getTokenAt(Pos(cur.line, token.start));
      if (token.string == ".") {
        cont = true;
        token = editor.getTokenAt(Pos(cur.line, token.start));
      }
    }

    // Try to complete table names
    var string = nameParts.join(".");
    addMatches(result, string, tables, function(w) {
      return useBacktick ? insertBackticks(w) : w;
    });

    // Try to complete columns from defaultTable
    addMatches(result, string, defaultTable, function(w) {
      return useBacktick ? insertBackticks(w) : w;
    });

    // Try to complete columns
    string = nameParts.pop();
    var table = nameParts.join(".");

    var alias = false;
    var aliasTable = table;
    // Check if table is available. If not, find table by Alias
    if (!getTable(table)) {
      var oldTable = table;
      table = findTableByAlias(table, editor);
      if (table !== oldTable) alias = true;
    }

    var columns = getTable(table);
    if (columns && columns.columns)
      columns = columns.columns;

    if (columns) {
      addMatches(result, string, columns, function(w) {
        var tableInsert = table;
        if (alias == true) tableInsert = aliasTable;
        if (typeof w == "string") {
          w = tableInsert + "." + w;
        } else {
          w = shallowClone(w);
          w.text = tableInsert + "." + w.text;
        }
        return useBacktick ? insertBackticks(w) : w;
      });
    }

    return start;
  }

  function eachWord(lineText, f) {
    if (!lineText) return;
    var excepted = /[,;]/g;
    var words = lineText.split(" ");
    for (var i = 0; i < words.length; i++) {
      f(words[i]?words[i].replace(excepted, '') : '');
    }
  }

  function convertCurToNumber(cur) {
    // max characters of a line is 999,999.
    return cur.line + cur.ch / Math.pow(10, 6);
  }

  function convertNumberToCur(num) {
    return Pos(Math.floor(num), +num.toString().split('.').pop());
  }

  function findTableByAlias(alias, editor) {
    var doc = editor.doc;
    var fullQuery = doc.getValue();
    var aliasUpperCase = alias.toUpperCase();
    var previousWord = "";
    var table = "";
    var separator = [];
    var validRange = {
      start: Pos(0, 0),
      end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)
    };

    //add separator
    var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);
    while(indexOfSeparator != -1) {
      separator.push(doc.posFromIndex(indexOfSeparator));
      indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);
    }
    separator.unshift(Pos(0, 0));
    separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));

    //find valid range
    var prevItem = 0;
    var current = convertCurToNumber(editor.getCursor());
    for (var i = 0; i < separator.length; i++) {
      var _v = convertCurToNumber(separator[i]);
      if (current > prevItem && current <= _v) {
        validRange = { start: convertNumberToCur(prevItem), end: convertNumberToCur(_v) };
        break;
      }
      prevItem = _v;
    }

    var query = doc.getRange(validRange.start, validRange.end, false);

    for (var i = 0; i < query.length; i++) {
      var lineText = query[i];
      eachWord(lineText, function(word) {
        var wordUpperCase = word.toUpperCase();
        if (wordUpperCase === aliasUpperCase && getTable(previousWord))
          table = previousWord;
        if (wordUpperCase !== CONS.ALIAS_KEYWORD)
          previousWord = word;
      });
      if (table) break;
    }
    return table;
  }

  CodeMirror.registerHelper("hint", "sql", function(editor, options) {
    tables = parseTables(options && options.tables)
    var defaultTableName = options && options.defaultTable;
    var disableKeywords = options && options.disableKeywords;
    defaultTable = defaultTableName && getTable(defaultTableName);
    keywords = getKeywords(editor);

    if (defaultTableName && !defaultTable)
      defaultTable = findTableByAlias(defaultTableName, editor);

    defaultTable = defaultTable || [];

    if (defaultTable.columns)
      defaultTable = defaultTable.columns;

    var cur = editor.getCursor();
    var result = [];
    var token = editor.getTokenAt(cur), start, end, search;
    if (token.end > cur.ch) {
      token.end = cur.ch;
      token.string = token.string.slice(0, cur.ch - token.start);
    }

    if (token.string.match(/^[.`\w@]\w*$/)) {
      search = token.string;
      start = token.start;
      end = token.end;
    } else {
      start = end = cur.ch;
      search = "";
    }
    if (search.charAt(0) == "." || search.charAt(0) == "`") {
      start = nameCompletion(cur, token, result, editor);
    } else {
      addMatches(result, search, tables, function(w) {return w;});
      addMatches(result, search, defaultTable, function(w) {return w;});
      if (!disableKeywords)
        addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
    }

    return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};
  });
});
<commit_msg>[sql-hint addon] Use all applicable decimal positions in convertNumberToCur<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"), require("../../mode/sql/sql"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror", "../../mode/sql/sql"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  var tables;
  var defaultTable;
  var keywords;
  var CONS = {
    QUERY_DIV: ";",
    ALIAS_KEYWORD: "AS"
  };
  var Pos = CodeMirror.Pos;

  function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" }

  function getKeywords(editor) {
    var mode = editor.doc.modeOption;
    if (mode === "sql") mode = "text/x-sql";
    return CodeMirror.resolveMode(mode).keywords;
  }

  function getText(item) {
    return typeof item == "string" ? item : item.text;
  }

  function wrapTable(name, value) {
    if (isArray(value)) value = {columns: value}
    if (!value.text) value.text = name
    return value
  }

  function parseTables(input) {
    var result = {}
    if (isArray(input)) {
      for (var i = input.length - 1; i >= 0; i--) {
        var item = input[i]
        result[getText(item).toUpperCase()] = wrapTable(getText(item), item)
      }
    } else if (input) {
      for (var name in input)
        result[name.toUpperCase()] = wrapTable(name, input[name])
    }
    return result
  }

  function getTable(name) {
    return tables[name.toUpperCase()]
  }

  function shallowClone(object) {
    var result = {};
    for (var key in object) if (object.hasOwnProperty(key))
      result[key] = object[key];
    return result;
  }

  function match(string, word) {
    var len = string.length;
    var sub = getText(word).substr(0, len);
    return string.toUpperCase() === sub.toUpperCase();
  }

  function addMatches(result, search, wordlist, formatter) {
    if (isArray(wordlist)) {
      for (var i = 0; i < wordlist.length; i++)
        if (match(search, wordlist[i])) result.push(formatter(wordlist[i]))
    } else {
      for (var word in wordlist) if (wordlist.hasOwnProperty(word)) {
        var val = wordlist[word]
        if (!val || val === true)
          val = word
        else
          val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text
        if (match(search, val)) result.push(formatter(val))
      }
    }
  }

  function cleanName(name) {
    // Get rid name from backticks(`) and preceding dot(.)
    if (name.charAt(0) == ".") {
      name = name.substr(1);
    }
    return name.replace(/`/g, "");
  }

  function insertBackticks(name) {
    var nameParts = getText(name).split(".");
    for (var i = 0; i < nameParts.length; i++)
      nameParts[i] = "`" + nameParts[i] + "`";
    var escaped = nameParts.join(".");
    if (typeof name == "string") return escaped;
    name = shallowClone(name);
    name.text = escaped;
    return name;
  }

  function nameCompletion(cur, token, result, editor) {
    // Try to complete table, column names and return start position of completion
    var useBacktick = false;
    var nameParts = [];
    var start = token.start;
    var cont = true;
    while (cont) {
      cont = (token.string.charAt(0) == ".");
      useBacktick = useBacktick || (token.string.charAt(0) == "`");

      start = token.start;
      nameParts.unshift(cleanName(token.string));

      token = editor.getTokenAt(Pos(cur.line, token.start));
      if (token.string == ".") {
        cont = true;
        token = editor.getTokenAt(Pos(cur.line, token.start));
      }
    }

    // Try to complete table names
    var string = nameParts.join(".");
    addMatches(result, string, tables, function(w) {
      return useBacktick ? insertBackticks(w) : w;
    });

    // Try to complete columns from defaultTable
    addMatches(result, string, defaultTable, function(w) {
      return useBacktick ? insertBackticks(w) : w;
    });

    // Try to complete columns
    string = nameParts.pop();
    var table = nameParts.join(".");

    var alias = false;
    var aliasTable = table;
    // Check if table is available. If not, find table by Alias
    if (!getTable(table)) {
      var oldTable = table;
      table = findTableByAlias(table, editor);
      if (table !== oldTable) alias = true;
    }

    var columns = getTable(table);
    if (columns && columns.columns)
      columns = columns.columns;

    if (columns) {
      addMatches(result, string, columns, function(w) {
        var tableInsert = table;
        if (alias == true) tableInsert = aliasTable;
        if (typeof w == "string") {
          w = tableInsert + "." + w;
        } else {
          w = shallowClone(w);
          w.text = tableInsert + "." + w.text;
        }
        return useBacktick ? insertBackticks(w) : w;
      });
    }

    return start;
  }

  function eachWord(lineText, f) {
    if (!lineText) return;
    var excepted = /[,;]/g;
    var words = lineText.split(" ");
    for (var i = 0; i < words.length; i++) {
      f(words[i]?words[i].replace(excepted, '') : '');
    }
  }

  function convertCurToNumber(cur) {
    // max characters of a line is 999,999.
    return cur.line + cur.ch / Math.pow(10, 6);
  }

  function convertNumberToCur(num) {
    return Pos(Math.floor(num), +num.toFixed(6).toString().split('.').pop());
  }

  function findTableByAlias(alias, editor) {
    var doc = editor.doc;
    var fullQuery = doc.getValue();
    var aliasUpperCase = alias.toUpperCase();
    var previousWord = "";
    var table = "";
    var separator = [];
    var validRange = {
      start: Pos(0, 0),
      end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)
    };

    //add separator
    var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);
    while(indexOfSeparator != -1) {
      separator.push(doc.posFromIndex(indexOfSeparator));
      indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);
    }
    separator.unshift(Pos(0, 0));
    separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));

    //find valid range
    var prevItem = 0;
    var current = convertCurToNumber(editor.getCursor());
    for (var i = 0; i < separator.length; i++) {
      var _v = convertCurToNumber(separator[i]);
      if (current > prevItem && current <= _v) {
        validRange = { start: convertNumberToCur(prevItem), end: convertNumberToCur(_v) };
        break;
      }
      prevItem = _v;
    }

    var query = doc.getRange(validRange.start, validRange.end, false);

    for (var i = 0; i < query.length; i++) {
      var lineText = query[i];
      eachWord(lineText, function(word) {
        var wordUpperCase = word.toUpperCase();
        if (wordUpperCase === aliasUpperCase && getTable(previousWord))
          table = previousWord;
        if (wordUpperCase !== CONS.ALIAS_KEYWORD)
          previousWord = word;
      });
      if (table) break;
    }
    return table;
  }

  CodeMirror.registerHelper("hint", "sql", function(editor, options) {
    tables = parseTables(options && options.tables)
    var defaultTableName = options && options.defaultTable;
    var disableKeywords = options && options.disableKeywords;
    defaultTable = defaultTableName && getTable(defaultTableName);
    keywords = getKeywords(editor);

    if (defaultTableName && !defaultTable)
      defaultTable = findTableByAlias(defaultTableName, editor);

    defaultTable = defaultTable || [];

    if (defaultTable.columns)
      defaultTable = defaultTable.columns;

    var cur = editor.getCursor();
    var result = [];
    var token = editor.getTokenAt(cur), start, end, search;
    if (token.end > cur.ch) {
      token.end = cur.ch;
      token.string = token.string.slice(0, cur.ch - token.start);
    }

    if (token.string.match(/^[.`\w@]\w*$/)) {
      search = token.string;
      start = token.start;
      end = token.end;
    } else {
      start = end = cur.ch;
      search = "";
    }
    if (search.charAt(0) == "." || search.charAt(0) == "`") {
      start = nameCompletion(cur, token, result, editor);
    } else {
      addMatches(result, search, tables, function(w) {return w;});
      addMatches(result, search, defaultTable, function(w) {return w;});
      if (!disableKeywords)
        addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
    }

    return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};
  });
});
<|endoftext|>


<commit_before>import get from 'lodash/get'

const CURRENT_VERSION = 0
const HEADER_ENTRIES = 7
const HEADER_LENGTH = 9 // type + entries
const TIMES_GRID_TYPE = 'ACCESSGR'

/**
 * Parse the ArrayBuffer from a `*_times.dat` file for a point in a network.
 */
export function parseTimesData(ab) {
  const headerData = new Int8Array(ab, 0, TIMES_GRID_TYPE.length)
  const headerType = String.fromCharCode(...headerData)
  if (headerType !== TIMES_GRID_TYPE) {
    throw new Error(
      `Retrieved grid header ${headerType} !== ${TIMES_GRID_TYPE}. Please check your data.`
    )
  }

  // First read the header to figure out how big the body is, then read the full
  // body, then read the JSON metadata at the end.
  const header = new Int32Array(
    ab,
    2 * Int32Array.BYTES_PER_ELEMENT,
    HEADER_ENTRIES
  )
  const version = header[0]
  // validate header and version
  if (version !== CURRENT_VERSION) {
    throw new Error(`Unsupported version ${version} of travel time surface`)
  }
  const zoom = header[1]
  const west = header[2]
  const north = header[3]
  const width = header[4]
  const height = header[5]
  const depth = header[6]
  const gridSize = width * height

  // skip the header
  const data = new Int32Array(
    ab,
    HEADER_LENGTH * Int32Array.BYTES_PER_ELEMENT,
    gridSize * depth
  )

  // de delta-code
  for (let i = 0, position = 0; i < depth; i++) {
    let previous = 0
    for (let j = 0; j < gridSize; j++, position++) {
      data[position] = data[position] + previous
      previous = data[position]
    }
  }

  // Decode metadata
  const rawMetadata = new Uint8Array(
    ab,
    (HEADER_LENGTH + width * height * depth) * Int32Array.BYTES_PER_ELEMENT
  )
  const metadata = decodeMetadata(rawMetadata)

  return {
    version,
    zoom,
    west,
    north,
    width,
    height,
    depth,
    data,
    errors: [],
    warnings: metadata.scenarioApplicationWarnings || [],
    get(x, y, z) {
      return data[z * gridSize + y * width + x]
    }
  }
}

function decodeMetadata(rawMetadata) {
  const decoder = getDecoder()
  return JSON.parse(decoder.decode(rawMetadata))
}

function getDecoder() {
  if (window === 'undefined' || typeof window.TextDecoder !== 'function') {
    const util = require('util')
    return new util.TextDecoder('utf-8')
  } else {
    return new window.TextDecoder('utf-8')
  }
}
<commit_msg>Remove unused import<commit_after>const CURRENT_VERSION = 0
const HEADER_ENTRIES = 7
const HEADER_LENGTH = 9 // type + entries
const TIMES_GRID_TYPE = 'ACCESSGR'

/**
 * Parse the ArrayBuffer from a `*_times.dat` file for a point in a network.
 */
export function parseTimesData(ab) {
  const headerData = new Int8Array(ab, 0, TIMES_GRID_TYPE.length)
  const headerType = String.fromCharCode(...headerData)
  if (headerType !== TIMES_GRID_TYPE) {
    throw new Error(
      `Retrieved grid header ${headerType} !== ${TIMES_GRID_TYPE}. Please check your data.`
    )
  }

  // First read the header to figure out how big the body is, then read the full
  // body, then read the JSON metadata at the end.
  const header = new Int32Array(
    ab,
    2 * Int32Array.BYTES_PER_ELEMENT,
    HEADER_ENTRIES
  )
  const version = header[0]
  // validate header and version
  if (version !== CURRENT_VERSION) {
    throw new Error(`Unsupported version ${version} of travel time surface`)
  }
  const zoom = header[1]
  const west = header[2]
  const north = header[3]
  const width = header[4]
  const height = header[5]
  const depth = header[6]
  const gridSize = width * height

  // skip the header
  const data = new Int32Array(
    ab,
    HEADER_LENGTH * Int32Array.BYTES_PER_ELEMENT,
    gridSize * depth
  )

  // de delta-code
  for (let i = 0, position = 0; i < depth; i++) {
    let previous = 0
    for (let j = 0; j < gridSize; j++, position++) {
      data[position] = data[position] + previous
      previous = data[position]
    }
  }

  // Decode metadata
  const rawMetadata = new Uint8Array(
    ab,
    (HEADER_LENGTH + width * height * depth) * Int32Array.BYTES_PER_ELEMENT
  )
  const metadata = decodeMetadata(rawMetadata)

  return {
    version,
    zoom,
    west,
    north,
    width,
    height,
    depth,
    data,
    errors: [],
    warnings: metadata.scenarioApplicationWarnings || [],
    get(x, y, z) {
      return data[z * gridSize + y * width + x]
    }
  }
}

function decodeMetadata(rawMetadata) {
  const decoder = getDecoder()
  return JSON.parse(decoder.decode(rawMetadata))
}

function getDecoder() {
  if (window === 'undefined' || typeof window.TextDecoder !== 'function') {
    const util = require('util')
    return new util.TextDecoder('utf-8')
  } else {
    return new window.TextDecoder('utf-8')
  }
}
<|endoftext|>


<commit_before>var Backbone = require('backbone');

var Leaflet = require('leaflet');

module.exports = Backbone.View.extend({

    el: '#coordinate-select',

    zoom: 14,

    events: {
        'click .lookup-button': 'lookup',
    },

    initialize: function () {
        this.$latitudeInput = this.$('input[name="latitude"]');
        this.$longitudeInput = this.$('input[name="longitude"]');

        this.$latitudeText = this.$('.latitude');
        this.$longitudeText = this.$('.longitude');

        this.latitude = parseFloat(this.$latitudeInput.val());
        this.longitude = parseFloat(this.$longitudeInput.val());

        var that = this;

        this.map = Leaflet.map(this.$('.map')[0], {
            scrollWheelZoom: false,
        }).setView([this.latitude, this.longitude], 14);

        this.tile = Leaflet.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(this.map);

        this.map.on('moveend', this.getCenter, this);
    },

    // Move map center by hand
    getCenter: function () {
        var center = this.map.getCenter();
        this.setCoordinate(center.lat, center.lng);
    },

    setCenter: function () {
        this.map.setView([this.latitude, this.longitude], 14);
    },

    setCoordinate: function (latitude, longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
        this.$latitudeInput.val(latitude);
        this.$longitudeInput.val(longitude);
        this.$latitudeText.text(latitude);
        this.$longitudeText.text(longitude);
    },

    openFoundAlert: function () {
        this.$('.alert-success').show();
        var that = this;
        setTimeout(function () {
            that.$('.alert-success').fadeOut();
        }, 2000);
    },

    openNotFoundAlert: function () {
        this.$('.alert-warning').show();
        var that = this;
        setTimeout(function () {
            that.$('.alert-warning').fadeOut();
        }, 2000);
    },

    search: function (query, alert) {
        var url = 'https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(query) + '&json_callback=?';
        var that = this;
        $.getJSON(url, function(data) {
            if (data.length > 0) {
                that.setCoordinate(parseFloat(data[0].lat), parseFloat(data[0].lon));
                that.setCenter();
                if (alert) {
                    that.openFoundAlert();
                }
            } else {
                if (alert) {
                    that.openNotFoundAlert();
                }
            }
        });
    },

    lookup: function () {
        this.search(this.address(), true);
    }
});
<commit_msg>Fix map bug when latitude or longitude is null<commit_after>var Backbone = require('backbone');

var Leaflet = require('leaflet');

module.exports = Backbone.View.extend({

    el: '#coordinate-select',

    zoom: 14,

    events: {
        'click .lookup-button': 'lookup',
    },

    initialize: function () {
        this.$latitudeInput = this.$('input[name="latitude"]');
        this.$longitudeInput = this.$('input[name="longitude"]');

        this.$latitudeText = this.$('.latitude');
        this.$longitudeText = this.$('.longitude');

        this.latitude = parseFloat(this.$latitudeInput.val());
        this.longitude = parseFloat(this.$longitudeInput.val());

        var that = this;

        this.map = Leaflet.map(this.$('.map')[0], {
            scrollWheelZoom: false,
        });

        this.tile = Leaflet.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(this.map);

        this.map.on('moveend', this.getCenter, this);

        this.setCenter();
    },

    // Move map center by hand
    getCenter: function () {
        var center = this.map.getCenter();
        this.setCoordinate(center.lat, center.lng);
    },

    setCenter: function () {
        if (this.latitude && this.longitude) {
            this.map.setView([this.latitude, this.longitude], 14);
        }
    },

    setCoordinate: function (latitude, longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
        this.$latitudeInput.val(latitude);
        this.$longitudeInput.val(longitude);
        this.$latitudeText.text(latitude);
        this.$longitudeText.text(longitude);
    },

    openFoundAlert: function () {
        this.$('.alert-success').show();
        var that = this;
        setTimeout(function () {
            that.$('.alert-success').fadeOut();
        }, 2000);
    },

    openNotFoundAlert: function () {
        this.$('.alert-warning').show();
        var that = this;
        setTimeout(function () {
            that.$('.alert-warning').fadeOut();
        }, 2000);
    },

    search: function (query, alert) {
        var url = 'https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(query) + '&json_callback=?';
        var that = this;
        $.getJSON(url, function(data) {
            if (data.length > 0) {
                that.setCoordinate(parseFloat(data[0].lat), parseFloat(data[0].lon));
                that.setCenter();
                if (alert) {
                    that.openFoundAlert();
                }
            } else {
                if (alert) {
                    that.openNotFoundAlert();
                }
            }
        });
    },

    lookup: function () {
        this.search(this.address(), true);
    }
});
<|endoftext|>


<commit_before>import RefManager from '../src/RefManager';
import { MongoClient } from 'mongodb';

describe('Octobus', () => {
  let rm;
  let db;
  let products;
  let categories;

  beforeAll(() => (
    MongoClient.connect('mongodb://localhost:27017/mdnorm').then((_db) => {
      db = _db;
    })
  ));

  beforeEach(() => (
    db.dropDatabase().then(async () => {
      rm = new RefManager(db);

      rm.add({
        source: 'Product',
        destination: 'Category',
        extractor: ({ name }) => ({ name }),
      });

      rm.add({
        source: 'Category',
        destination: 'Product',
        type: 'many',
        extractor: ({ name }) => ({ name }),
      });

      categories = (await db.collection('Category').insert([
        { name: 'category1' },
        { name: 'category2' },
        { name: 'category3' },
        { name: 'category4' },
      ])).ops;

      products = (await db.collection('Product').insert([
        { name: 'product1', categoryId: categories[0]._id },
        { name: 'product2', categoryId: categories[1]._id },
        { name: 'product3', categoryId: categories[3]._id },
        { name: 'product4', categoryId: categories[3]._id },
      ])).ops;

      await Promise.all([
        await db.collection('Category').update({
          _id: categories[0]._id,
        }, {
          $set: {
            productIds: [products[0]._id],
          },
        }),
        await db.collection('Category').update({
          _id: categories[1]._id,
        }, {
          $set: {
            productIds: [products[1]._id],
          },
        }),
        await db.collection('Category').update({
          _id: categories[3]._id,
        }, {
          $set: {
            productIds: [products[2]._id, products[3]._id],
          },
        }),
      ]);

      categories = await db.collection('Category').find().toArray();
    })
  ));

  it('stores the references configuration', () => {
    expect(rm.references).toMatchSnapshot();
  });

  describe('it should populate the cache after insert', () => {
    it('for type=one reference', async () => {
      await rm.notifyInsert('Product', products);
      const productsWithReferences = (await db.collection('Product').find().toArray())
        .map(({ _category, name }) => ({
          _category,
          name,
        }));

      expect(productsWithReferences).toMatchSnapshot();
    });

    it('for type=many reference', async () => {
      await rm.notifyInsert('Category', categories);
      const categoriesWithReferences = await db.collection('Category').find().toArray();
      const firstCategory = categoriesWithReferences.find(({ name }) => name === 'category1');
      const fourthCategory = categoriesWithReferences.find(({ name }) => name === 'category4');
      expect(firstCategory._products).toBeDefined();
      expect(firstCategory._products[products[0]._id.toString()]).toEqual({
        name: 'product1',
      });
      expect(fourthCategory._products).toBeDefined();
      expect(fourthCategory._products).toEqual({
        [products[2]._id.toString()]: {
          name: 'product3',
        },
        [products[3]._id.toString()]: {
          name: 'product4',
        },
      });
    });
  });
});
<commit_msg>tests fixes<commit_after>import RefManager from '../src/RefManager';
import { MongoClient } from 'mongodb';

describe('Octobus', () => {
  let rm;
  let db;
  let products;
  let categories;

  beforeAll(() => (
    MongoClient.connect('mongodb://localhost:27017/mdnorm').then((_db) => {
      db = _db;
    })
  ));

  afterAll(() => {
    db.close();
  });

  beforeEach(() => (
    db.dropDatabase().then(async () => {
      rm = new RefManager(db);

      rm.add({
        source: 'Product',
        destination: 'Category',
        extractor: ({ name }) => ({ name }),
      });

      rm.add({
        source: 'Category',
        destination: 'Product',
        type: 'many',
        extractor: ({ name }) => ({ name }),
      });

      categories = (await db.collection('Category').insert([
        { name: 'category1' },
        { name: 'category2' },
        { name: 'category3' },
        { name: 'category4' },
      ])).ops;

      products = (await db.collection('Product').insert([
        { name: 'product1', categoryId: categories[0]._id },
        { name: 'product2', categoryId: categories[1]._id },
        { name: 'product3', categoryId: categories[3]._id },
        { name: 'product4', categoryId: categories[3]._id },
      ])).ops;

      await Promise.all([
        await db.collection('Category').update({
          _id: categories[0]._id,
        }, {
          $set: {
            productIds: [products[0]._id],
          },
        }),
        await db.collection('Category').update({
          _id: categories[1]._id,
        }, {
          $set: {
            productIds: [products[1]._id],
          },
        }),
        await db.collection('Category').update({
          _id: categories[3]._id,
        }, {
          $set: {
            productIds: [products[2]._id, products[3]._id],
          },
        }),
      ]);

      categories = await db.collection('Category').find().toArray();
    })
  ));

  it('stores the references configuration', () => {
    expect(rm.references).toMatchSnapshot();
  });

  describe('it should populate the cache after insert', () => {
    it('for type=one reference', async () => {
      await rm.notifyInsert('Product', products);
      const productsWithReferences = (await db.collection('Product').find().toArray())
        .map(({ _category, name }) => ({
          _category,
          name,
        }));

      expect(productsWithReferences).toMatchSnapshot();
    });

    it('for type=many reference', async () => {
      await rm.notifyInsert('Category', categories);
      const categoriesWithReferences = await db.collection('Category').find().toArray();
      const firstCategory = categoriesWithReferences.find(({ name }) => name === 'category1');
      const fourthCategory = categoriesWithReferences.find(({ name }) => name === 'category4');
      expect(firstCategory._products).toBeDefined();
      expect(firstCategory._products[products[0]._id.toString()]).toEqual({
        name: 'product1',
      });
      expect(fourthCategory._products).toBeDefined();
      expect(fourthCategory._products).toEqual({
        [products[2]._id.toString()]: {
          name: 'product3',
        },
        [products[3]._id.toString()]: {
          name: 'product4',
        },
      });
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var core;
var tile;

describe('abilities', function() {

before(function(done) {
    require('./support/start').start(function(command) {
        core = command.servers['Core'];
        tile = command.servers['Tile'];
        done();
    });
});

after(function(done) {
    core.close();
    tile.close();
    done();
});

it('GET should return JSON', function(done) {
    assert.response(core,
        { url: '/assets/tilemill/js/abilities.js' },
        { status: 200 },
        function(res) {
            var body = res.body.replace(/^\s*var\s+abilities\s*=\s*(.+?);?$/, '$1');
            var abilities = JSON.parse(body);

            assert.ok(/v\d+.\d+.\d+-\d+-[a-z0-9]+/.test(abilities.version[0]));
            assert.ok(/\d+.\d+.\d+.\d+/.test(abilities.version[1]));
            assert.ok(abilities.fonts.indexOf('Arial Regular') >= 0 ||
                      abilities.fonts.indexOf('DejaVu Sans Book') >= 0);
            assert.deepEqual([0,206,209], abilities.carto.colors.darkturquoise);
            assert.deepEqual([
                "background-color",
                "background-image",
                "srs",
                "buffer-size",
                "maximum-extent",
                "base",
                "paths-from-xml",
                "minimum-version",
                "font-directory"
            ], Object.keys(abilities.carto.symbolizers.map));

            assert.deepEqual({
                mbtiles: true,
                png: true,
                pdf: true,
                svg: true
            }, abilities.exports);
            done();
        }
    );
});

});

<commit_msg>fix abilities test to adapt to new mapnik<commit_after>var assert = require('assert');
var core;
var tile;

describe('abilities', function() {

before(function(done) {
    require('./support/start').start(function(command) {
        core = command.servers['Core'];
        tile = command.servers['Tile'];
        done();
    });
});

after(function(done) {
    core.close();
    tile.close();
    done();
});

it('GET should return JSON', function(done) {
    assert.response(core,
        { url: '/assets/tilemill/js/abilities.js' },
        { status: 200 },
        function(res) {
            var body = res.body.replace(/^\s*var\s+abilities\s*=\s*(.+?);?$/, '$1');
            var abilities = JSON.parse(body);

            assert.ok(/v\d+.\d+.\d+-\d+-[a-z0-9]+/.test(abilities.version[0]));
            assert.ok(/\d+.\d+.\d+.\d+/.test(abilities.version[1]));
            assert.ok(abilities.fonts.indexOf('Arial Regular') >= 0 ||
                      abilities.fonts.indexOf('DejaVu Sans Book') >= 0);
            assert.deepEqual([0,206,209], abilities.carto.colors.darkturquoise);
            assert.deepEqual([
                "background-color",
                "background-image",
                "background-image-comp-op",
                "background-image-opacity",
                "srs",
                "buffer-size",
                "maximum-extent",
                "base",
                "paths-from-xml",
                "minimum-version",
                "font-directory"
            ], Object.keys(abilities.carto.symbolizers.map));

            assert.deepEqual({
                mbtiles: true,
                png: true,
                pdf: true,
                svg: true
            }, abilities.exports);
            done();
        }
    );
});

});

<|endoftext|>


<commit_before>var common = require("./common");
var sys    = require("./sys");
var assert = require('assert');

var Worker = require("../lib/worker").Worker;

process.ENV["NODE_PATH"] = common.libDir;

function makeWorker (filename) {
  return new Worker(__dirname+"/fixtures/"+filename);
}

// basic test
var worker = makeWorker("worker.js");

worker.onmessage = function (msg) {
  if (msg.input) {
    assert.ok(msg.output == msg.input * 3, "We can multiply asyncly");
    if(msg.input * 3 == 12) {
      worker.terminate();
    }
  }
};

worker.postMessage({
  input: 1
});
worker.postMessage({
  input: 2
});
worker.postMessage({
  input: 3
});
worker.postMessage({
  input: 4
});

// error handling
setTimeout(function () {
  setTimeout(function () {

    var w2 = makeWorker("worker.js");
    w2.postMessage({
      error: true
    });
    w2.addListener("error", function () {
      assert.ok(true, "Received expected error via event");
      w2.terminate();
    });
    w2.addListener("message", function () {
      assert.ok(false, "Wanted an error, but got a message");
      w2.terminate();
    });

    var w3 = makeWorker("worker.js");
    w3.postMessage({
      error: true
    });
    w3.onerror = function () {
      assert.ok(true, "Received expected error with onerror");
      w3.terminate();
    };
    w3.addListener("message", function () {
      assert.ok(false, "Wanted an error, but got a message");
      w3.terminate();
    });

  }, 10);
}, 10);

// syntax error handling
var syntaxError = makeWorker("syntax-error-worker.js");
var hadSyntaxError = false;
syntaxError.onerror = function (err) {
  if(err instanceof SyntaxError) {
    hadSyntaxError = true;
  }
}
process.addListener("exit", function () {
  assert.ok(hadSyntaxError, "detected syntax error");
})

// long running processes
var fibWorker = makeWorker("fib-worker.js");
sys.puts("Giving hard work to worker")
fibWorker.postMessage({
  fib: 41
});
var longRunningReturned = false;
var interval = setInterval(function () {
  sys.puts("# working in the background")
}, 500);
fibWorker.addListener("message", function (fib) {
  sys.error("Fib "+fib);
  longRunningReturned = true;
  assert.ok(fib === 165580141, "Worker can do long running stuff.")
  fibWorker.terminate();
  clearInterval(interval);
});
for(var i = 0; i < 100; ++i) {
  // counting;
}
assert.ok(!longRunningReturned, "Can do work while background spins");
process.addListener("exit", function () {
  assert.ok(longRunningReturned, "Did long running calculation")
})

var waitWorker = makeWorker("worker.js");
waitWorker.postMessage({
  wait: true
});
waitWorker.addListener("message", function () {
  assert.ok(true, "Worker response can be async.")
  waitWorker.terminate();
});<commit_msg>Why should sys be local?<commit_after>var common = require("./common");
var sys    = require("sys");
var assert = require('assert');

var Worker = require("../lib/worker").Worker;

process.ENV["NODE_PATH"] = common.libDir;

function makeWorker (filename) {
  return new Worker(__dirname+"/fixtures/"+filename);
}

// basic test
var worker = makeWorker("worker.js");

worker.onmessage = function (msg) {
  if (msg.input) {
    assert.ok(msg.output == msg.input * 3, "We can multiply asyncly");
    if(msg.input * 3 == 12) {
      worker.terminate();
    }
  }
};

worker.postMessage({
  input: 1
});
worker.postMessage({
  input: 2
});
worker.postMessage({
  input: 3
});
worker.postMessage({
  input: 4
});

// error handling
setTimeout(function () {
  setTimeout(function () {

    var w2 = makeWorker("worker.js");
    w2.postMessage({
      error: true
    });
    w2.addListener("error", function () {
      assert.ok(true, "Received expected error via event");
      w2.terminate();
    });
    w2.addListener("message", function () {
      assert.ok(false, "Wanted an error, but got a message");
      w2.terminate();
    });

    var w3 = makeWorker("worker.js");
    w3.postMessage({
      error: true
    });
    w3.onerror = function () {
      assert.ok(true, "Received expected error with onerror");
      w3.terminate();
    };
    w3.addListener("message", function () {
      assert.ok(false, "Wanted an error, but got a message");
      w3.terminate();
    });

  }, 10);
}, 10);

// syntax error handling
var syntaxError = makeWorker("syntax-error-worker.js");
var hadSyntaxError = false;
syntaxError.onerror = function (err) {
  if(err instanceof SyntaxError) {
    hadSyntaxError = true;
  }
}
process.addListener("exit", function () {
  assert.ok(hadSyntaxError, "detected syntax error");
})

// long running processes
var fibWorker = makeWorker("fib-worker.js");
sys.puts("Giving hard work to worker")
fibWorker.postMessage({
  fib: 41
});
var longRunningReturned = false;
var interval = setInterval(function () {
  sys.puts("# working in the background")
}, 500);
fibWorker.addListener("message", function (fib) {
  sys.error("Fib "+fib);
  longRunningReturned = true;
  assert.ok(fib === 165580141, "Worker can do long running stuff.")
  fibWorker.terminate();
  clearInterval(interval);
});
for(var i = 0; i < 100; ++i) {
  // counting;
}
assert.ok(!longRunningReturned, "Can do work while background spins");
process.addListener("exit", function () {
  assert.ok(longRunningReturned, "Did long running calculation")
})

var waitWorker = makeWorker("worker.js");
waitWorker.postMessage({
  wait: true
});
waitWorker.addListener("message", function () {
  assert.ok(true, "Worker response can be async.")
  waitWorker.terminate();
});<|endoftext|>


<commit_before>$(document).ready(function(){
   $(".transaction_other").hide();

   // $(".transaction_other").attr();

 $('#paymentlmethod').change(function(){

		var tran_other = $('#paymentlmethod option:selected').val();
		if (tran_other != 'Cash') {
			$('.transaction_other').slideDown();
			$('#paymenttrans').prop('required',true);
		}else{
			$('.transaction_other').slideUp();
			$('#paymenttrans').prop('required',false);
		};
	});

    $('#paymentfor_1').change(function(){
      $("#payment_1").prop("disabled", !$(this).is(':checked'));
    });

    $('#paymentfor_2').change(function(){
      $("#payment_2").prop("disabled", !$(this).is(':checked'));
    });

    $('#paymentfor_3').change(function(){
      $("#payment_3").prop("disabled", !$(this).is(':checked'));
    });

    // ....Function for registering tenants.... //
 $(function(){
       $("#paymentransaction").submit(function(){

         var formData = new FormData($(this)[0]);

         $.ajax({
           type: "POST",
           url: "payments/paymenttransaction",
           data: formData,
           async: false,
           cache: false,
           contentType: false,
           processData: false,
           success: function(data){
               // ....After successful registration, then....//

              swal({   title: "Payment Done",   text: "Payment Recorded",   timer: 3000 });

           }

         });

         return false;  //stop the actual form post !important!

      });
   });

     // ....end of function.... //

});<commit_msg>Success messages have been updated<commit_after>$(document).ready(function(){
   $(".transaction_other").hide();

   // $(".transaction_other").attr();

 $('#paymentlmethod').change(function(){

		var tran_other = $('#paymentlmethod option:selected').val();
		if (tran_other != 'Cash') {
			$('.transaction_other').slideDown();
			$('#paymenttrans').prop('required',true);
		}else{
			$('.transaction_other').slideUp();
			$('#paymenttrans').prop('required',false);
		};
	});

    $('#paymentfor_1').change(function(){
      $("#payment_1").prop("disabled", !$(this).is(':checked'));
    });

    $('#paymentfor_2').change(function(){
      $("#payment_2").prop("disabled", !$(this).is(':checked'));
    });

    $('#paymentfor_3').change(function(){
      $("#payment_3").prop("disabled", !$(this).is(':checked'));
    });

    // ....Function for registering tenants.... //
 $(function(){
       $("#paymentransaction").submit(function(){

         var formData = new FormData($(this)[0]);

         $.ajax({
           type: "POST",
           url: "payments/paymenttransaction",
           data: formData,
           async: false,
           cache: false,
           contentType: false,
           processData: false,
           success: function(data){
               // ....After successful registration, then....//

              swal({   title: "Payment Done",   text: "Payment has been Recorded",   timer: 3000 });

           }

         });

         return false;  //stop the actual form post !important!

      });
   });

     // ....end of function.... //

});<|endoftext|>


<commit_before>
/*
 * namespace for the DSP Adapter
 */
var EmberDreamFactoryAdapter = {};

/*
 * Serializer overrides
 */
EmberDreamFactoryAdapter.Serializer = DS.RESTSerializer.extend({

	extractArray: function(store, primaryType, payload) {
		var namespacedPayload = {};
		namespacedPayload[Ember.String.pluralize(primaryType.typeKey)] = payload.record;
		return this._super(store, primaryType, namespacedPayload);
	},

	extractSingle: function (store, primaryType, payload, recordId) {
		var namespacedPayload = {};
		namespacedPayload[primaryType.typeKey] = payload;
		return this._super(store, primaryType, namespacedPayload, recordId);
	},

	typeForRoot: function (key) {
		return Ember.String.dasherize(Ember.String.singularize(key));
	},

	serialize: function (record, options) {
		options = options || { includeId: true };
		return this._super(record, options);
	},

	// set the JSON root to 'record' to make DSP happy
	serializeIntoHash: function (data, type, record, options) {
		var root = 'record';
		data[root] = this.serialize(record, options);
	}
});

/*
 * An Ember Data Adapter written to use DreamFactory REST API
 * @type {DS.RESTAdapter}
 */
EmberDreamFactoryAdapter.Adapter = DS.RESTAdapter.extend({

	defaultSerializer: '-dreamfactory',

	init: function () {
		this._super();
		this.set('headers', {
			'X-DreamFactory-Application-Name': this.get('applicationName')
		});
	},

	pathForType: function (type) {
		return Ember.String.pluralize(Ember.String.capitalize(Ember.String.camelize(type)));
	},

	// Used https://github.com/clintjhill/ember-parse-adapter/blob/master/dist/ember-parse-adapter.js#L290 as a starting point
	createRecord: function(store, type, record) {
		var data = {};
		var serializer = store.serializerFor(type.typeKey);
		serializer.serializeIntoHash(data, type, record);
		var adapter = this;

		return new Ember.RSVP.Promise(function(resolve, reject) {
			adapter.ajax(adapter.buildURL(type.typeKey, id), "POST", { data: data }).then(function(json){
				// if the request is a success we'll return the same data we passed in
				var completed = Ember.merge(data.record, json);
				resolve(completed);
			}, function(reason){
				reject(reason.responseJSON);
			});
		});
	},

	// Used https://github.com/clintjhill/ember-parse-adapter/blob/master/dist/ember-parse-adapter.js#L290 as a starting point
	updateRecord: function(store, type, record) {
		var data = {};
		var serializer = store.serializerFor(type.typeKey);
		serializer.serializeIntoHash(data, type, record);
		var adapter = this;

		return new Ember.RSVP.Promise(function(resolve, reject) {
			// hack to make DSP send back the full object
			adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
				// if the request is a success we'll return the same data we passed in
				resolve(json);
			}, function(reason){
				reject(reason.responseJSON);
			});
		});
	},

	sessionToken: Ember.computed('headers.X-DreamFactory-Session-Token', function (key, value) {
		if (arguments.length < 2) {
			return this.get('headers.X-DreamFactory-Session-Token');
		} else {
			this.set('header.X-DreamFactory-Session-Token', value);
			return value;
		}
	})
});

EmberDreamFactoryAdapter.setupContainer = function(container) {
	container.register('serializer:-dreamfactory', EmberDreamFactoryAdapter.Serializer);
};

/**
 * Setup the DSP Adapter in the app.
 */
Ember.onLoad('Ember.Application', function(Application) {
	Application.initializer({
		after: "ember-data",
		name: 'dreamfactory-adapter',
		initialize: function(container, application) {
			EmberDreamFactoryAdapter.setupContainer(container);
		}
	});
});
<commit_msg>Add buildProcUrl and isEmpty methods to adapter<commit_after>
/*
 * namespace for the DSP Adapter
 */
var EmberDreamFactoryAdapter = {};

/*
 * Serializer overrides
 */
EmberDreamFactoryAdapter.Serializer = DS.RESTSerializer.extend({

	extractArray: function(store, primaryType, payload) {
		var namespacedPayload = {};
		namespacedPayload[Ember.String.pluralize(primaryType.typeKey)] = payload.record;
		return this._super(store, primaryType, namespacedPayload);
	},

	extractSingle: function (store, primaryType, payload, recordId) {
		var namespacedPayload = {};
		namespacedPayload[primaryType.typeKey] = payload;
		return this._super(store, primaryType, namespacedPayload, recordId);
	},

	typeForRoot: function (key) {
		return Ember.String.dasherize(Ember.String.singularize(key));
	},

	serialize: function (record, options) {
		options = options || { includeId: true };
		return this._super(record, options);
	},

	// set the JSON root to 'record' to make DSP happy
	serializeIntoHash: function (data, type, record, options) {
		var root = 'record';
		data[root] = this.serialize(record, options);
	}
});

/*
 * An Ember Data Adapter written to use DreamFactory REST API
 * @type {DS.RESTAdapter}
 */
EmberDreamFactoryAdapter.Adapter = DS.RESTAdapter.extend({

	defaultSerializer: '-dreamfactory',

	init: function () {
		this._super();
		this.set('headers', {
			'X-DreamFactory-Application-Name': this.get('applicationName')
		});
	},

	// Used https://github.com/clintjhill/ember-parse-adapter/blob/master/dist/ember-parse-adapter.js#L290 as a starting point
	createRecord: function(store, type, record) {
		var data = {};
		var serializer = store.serializerFor(type.typeKey);
		serializer.serializeIntoHash(data, type, record);
		var adapter = this;

		return new Ember.RSVP.Promise(function(resolve, reject) {
			adapter.ajax(adapter.buildURL(type.typeKey, id), "POST", { data: data }).then(function(json){
				// if the request is a success we'll return the same data we passed in
				var completed = Ember.merge(data.record, json);
				resolve(completed);
			}, function(reason){
				reject(reason.responseJSON);
			});
		});
	},

	// Used https://github.com/clintjhill/ember-parse-adapter/blob/master/dist/ember-parse-adapter.js#L290 as a starting point
	updateRecord: function(store, type, record) {
		var data = {};
		var serializer = store.serializerFor(type.typeKey);
		serializer.serializeIntoHash(data, type, record);
		var adapter = this;

		return new Ember.RSVP.Promise(function(resolve, reject) {
			// hack to make DSP send back the full object
			adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
				// if the request is a success we'll return the same data we passed in
				resolve(json);
			}, function(reason){
				reject(reason.responseJSON);
			});
		});
	}

	pathForType: function (type) {
		return Ember.String.pluralize(Ember.String.capitalize(Ember.String.camelize(type)));
	},

	buildProcUrl: function (proc) {
		var url = [],
			host = this.get('host'),
			prefix = this.urlPrefix();

		url.push('_proc');
		url.push(proc);

		if (prefix) { url.unshift(prefix); }

		url = url.join('/');

		return url;
	},
	sessionToken: Ember.computed('headers.X-DreamFactory-Session-Token', function (key, value) {
		if (arguments.length < 2) {
			return this.get('headers.X-DreamFactory-Session-Token');
		} else {
			this.set('header.X-DreamFactory-Session-Token', value);
			return value;
		}
	})
});

EmberDreamFactoryAdapter.setupContainer = function(container) {
	container.register('serializer:-dreamfactory', EmberDreamFactoryAdapter.Serializer);
};

/**
 * Setup the DSP Adapter in the app.
 */
Ember.onLoad('Ember.Application', function(Application) {
	Application.initializer({
		after: "ember-data",
		name: 'dreamfactory-adapter',
		initialize: function(container, application) {
			EmberDreamFactoryAdapter.setupContainer(container);
		}
	});
});
<|endoftext|>


<commit_before>import Ember from 'ember';

/**
 * This service translates through gettext.js.
 * There are two available methods to be used
 * for translations message ids from JS source:
 *
 * - t(msgid, hash);
 * - n(msgid, msgid_plural, count, hash);
 *
 * Furthermore, there's an auto initialization
 * feature (default: true), which detects user's
 * locale according to system preferences. If the
 * user's locale is supported in `availableLocales`,
 * the corresponding translations are loaded. If the
 * user's locale is not supported, the default locale
 * will be used instead (default: 'en'). Please use the
 * following method to change locales:
 *
 * - setLocale(locale);
 *
 * The following utility methods are also availalbe:
 *
 * - hasLocale(locale);
 * - detectLocale();
 *
 * To configure the path of the JSON files (depending on
 * the path configured via gettext.sh extractor) use the
 * `jsonPath` property (default: '/assets/locales').
 *
 * @namespace Service
 * @class L10N
 * @extends Ember.Service
 * @extends Ember.Evented
 * @public
 */
export default Ember.Service.extend(Ember.Evented, {
  // -------------------------------------------------------------------------
  // Dependencies

  ajax: Ember.inject.service('l10n-ajax'),

  // -------------------------------------------------------------------------
  // Properties

  /**
   * Current locale from user, defaults
   * to 'defaultLocale' if not retrievable
   * or currently available due to missing
   * translations.
   *
   * @property locale
   * @type {String}
   * @default null
   * @public
   */
  locale: null,

  /**
   * Use this property if you want to force
   * a specific locale and skip automatic
   * detection of user's system settings.
   * This is useful for signed in users,
   * but beware that unsupported locales
   * will fallback to the default locale!
   *
   * @property forceLocale
   * @type {String}
   * @default null
   * @public
   */
  forceLocale: null,

  /**
   * Fallback locale for unavailable locales.
   *
   * @property defaultLocale
   * @type {String}
   * @default 'en'
   * @public
   */
  defaultLocale: 'en',

  /**
   * Will invoke a language detection or loads
   * language from `forceLanguage` on service
   * instantiation. If disabling, make sure to
   * set locale manually with setLocale().
   *
   * @property autoInitialize
   * @type {String}
   * @default null
   * @public
   */
  autoInitialize: true,

  /**
   * Directory containing JSON files with all
   * translations for corresponding locale.
   *
   * @property jsonPath
   * @type {String}
   * @default 'assets/locales'
   * @public
   */
  jsonPath: '/assets/locales',

  /**
   * Currently available translations hash.
   *
   * @property availableLocales
   * @type {Object}
   * @public
   */
  availableLocales: Ember.computed(function() {
    return {
      'en': this.t('en')
    };
  }),

  /**
   * Reference to gettext library.
   *
   * @property _gettext
   * @type {String}
   * @default null
   * @private
   */
  _gettext: window.i18n(),

  /**
   * Cache persisting loaded JSON files to
   * avoid duplicated requests going out.
   *
   * @property _cache
   * @type {Object}
   * @default {}
   * @private
   */
  _cache: Ember.computed(function() {
    return {}; // complex type!
  }),

  // -------------------------------------------------------------------------
  // Methods

  /**
   * Sets initial locale. If you want to to
   * skip language detection, please provide
   * `forceLocale` property with reopen().
   *
   * @method init
   * @return {Void}
   * @public
   */
  init() {
    this._super(...arguments);
    if (!this.get('autoInitialize')) {
      return;
    }

    this.setLocale(this.detectLocale());
  },

  /**
   * Provides current locale. If not set,
   * delivers default locale.
   *
   * @method setLocale
   * @param {String} locale
   * @return {String}
   * @public
   */
  getLocale() {
    let defaultLocale = this.get('defaultLocale');
    let locale = this.get('locale');
    if (Ember.isNone(locale)) {
      return defaultLocale;
    }

    return locale;
  },

  /**
   * Sets active locale if available.
   *
   * @method setLocale
   * @param {String} locale
   * @return {String}
   * @public
   */
  setLocale(locale) {
    if (!this.hasLocale(locale)) {
      return;
    }

    console.info(`l10n.js: Locale set to: "${locale}"`);
    this.get('_gettext').setLocale(locale);
    this.set('locale', locale);
    this._loadJSON();
  },

  /**
   * Checks if locale is available.
   *
   * @method setLocale
   * @param {String} locale
   * @return {Boolean}
   * @public
   */
  hasLocale(locale) {
    let availableLocales = this.get('availableLocales');
    let hasLocale = !Ember.isNone(availableLocales[locale]);
    if (!hasLocale) {
      console.warn(`l10n.js: Locale "${locale}" is not available!`);
    }

    return hasLocale;
  },

  /**
   * Gets user's current client language and
   * provides extracted ISO-Code.
   *
   * @method detectLocale
   * @return {String}
   * @public
   */
  detectLocale() {
    let defaultLocale = this.get('defaultLocale');
    let forceLocale = this.get('forceLocale');
    let { navigator } = window;
    let locale;

    // auto detect locale if no force locale
    if (Ember.isNone(forceLocale)) {

      // special case: android user agents
      if (navigator && navigator.userAgent &&
        (locale = navigator.userAgent.match(
          /android.*\W(\w\w)-(\w\w)\W/i
        ))
      ) {
        locale = locale[1];
      }

      // for all other browsers
      if (Ember.isNone(locale) && navigator) {
        if (navigator.language) {
          locale = navigator.language;
        } else if (navigator.browserLanguage) {
          locale = navigator.browserLanguage;
        } else if (navigator.systemLanguage) {
          locale = navigator.systemLanguage;
        } else if (navigator.userLanguage) {
          locale = navigator.userLanguage;
        }
      }

      locale = locale.substr(0, 2);
    } else {
      locale = forceLocale;
    }

    // provide default locale if not available
    if (!this.hasLocale(locale)) {
      console.info(`l10n.js: Falling back to default language: "${defaultLocale}"!`);
      return defaultLocale;
    }

    // otherwise return detected locale
    if (Ember.isNone(forceLocale)) {
      console.info(`l10n.js: Automatically detected user language: "${locale}"`);
    } else {
      console.info(`l10n.js: Using forced locale: "${locale}"`);
    }

    return locale;
  },

  /**
   * Translates a singular form message id.
   *
   * @method t
   * @param {String} msgid
   * @param {Object} hash
   * @return {String}
   * @public
   */
  t(msgid, hash = {}) {
    if (Ember.typeOf(msgid) !== 'string') {
      try {
        msgid = msgid.toString();
      } catch (e) {
        console.log('l10n.js: "msgid" param for t() should be either a string or an object implementing toString() method!');
        return msgid;
      }
    }

    return this._strfmt(this.get('_gettext').gettext(msgid), hash);
  },

  /**
   * Translates a plural form message id.
   *
   * @method n
   * @param {String} msgid
   * @param {String} msgidPlural
   * @param {Number} count
   * @param {Object} hash
   * @return {String}
   * @public
   */
  n(msgid, msgidPlural, count = 1, hash = {}) {
    if (Ember.typeOf(msgid) !== 'string') {
      try {
        msgid = msgid.toString();
      } catch (e) {
        console.log('l10n.js: "msgid" param for n() should be either a string or an object implementing toString() method!');
        return msgid;
      }
    }

    if (Ember.typeOf(msgidPlural) !== 'string') {
      try {
        msgidPlural = msgidPlural.toString();
      } catch (e) {
        console.log('l10n.js: "msgid_plural" param for n() should be either a string or an object implementing toString() method!');
        return msgid;
      }
    }

    return this._strfmt(this.get('_gettext').ngettext(msgid, msgidPlural, count), hash);
  },

  /**
   * Replaces placeholders like {{placeholder}} from string.
   *
   * @method _strfmt
   * @param {String} string
   * @param {Object} hash
   * @return {String}
   * @private
   */
  _strfmt(string, hash) {
    // don't process empty hashes
    if (Ember.isNone(hash)) {
      return string;
    }

    // find and replace all {{placeholder}}
    let pattern = /{{\s*([\w]+)\s*}}/g;
    let replace = (idx, match) => {
      let value = hash[match];
      if (Ember.isNone(value)) {
        return `{{${match}}}`;
      }

      if (Ember.typeOf(value) === 'string') {
        value = this.get('_gettext').gettext(value);
      }

      return value;
    };

    return string.replace(pattern, replace);
  },

  /**
   * Loads current locale translation file.
   * Triggers `translation_loaded` event.
   *
   * @method _load
   * @return {Void}
   * @private
   */
  _loadJSON() {
    let ajax = this.get('ajax');
    let cache = this.get('_cache');
    let locale = this.get('locale');
    let url = `${this.get('jsonPath')}/${locale}.json`;

    let successCallback = (response) => {
      let cachedResponse = Ember.copy(response, true);
      this.notifyPropertyChange('availableLocales');
      this.get('_gettext').loadJSON(response);
      this.trigger('translation_loaded');
      cache[locale] = cachedResponse;
    };

    let failureCallback = (reason) => {
      console.error(`l10n.js: An error occured loading "${url}": ${reason}`);
    };

    // used cache translation if present
    if (cache.hasOwnProperty(locale)) {
      successCallback(cache[locale]);
      return;
    }

    // otherwise load json file from assets
    ajax.request(url).then(
      successCallback,
      failureCallback
    );
  }

});
<commit_msg>Fix typo in jsdoc<commit_after>import Ember from 'ember';

/**
 * This service translates through gettext.js.
 * There are two available methods to be used
 * for translations message ids from JS source:
 *
 * - t(msgid, hash);
 * - n(msgid, msgidPlural, count, hash);
 *
 * Furthermore, there's an auto initialization
 * feature (default: true), which detects user's
 * locale according to system preferences. If the
 * user's locale is supported in `availableLocales`,
 * the corresponding translations are loaded. If the
 * user's locale is not supported, the default locale
 * will be used instead (default: 'en'). Please use the
 * following method to change locales:
 *
 * - setLocale(locale);
 *
 * The following utility methods are also availalbe:
 *
 * - hasLocale(locale);
 * - detectLocale();
 *
 * To configure the path of the JSON files (depending on
 * the path configured via gettext.sh extractor) use the
 * `jsonPath` property (default: '/assets/locales').
 *
 * @namespace Service
 * @class L10N
 * @extends Ember.Service
 * @extends Ember.Evented
 * @public
 */
export default Ember.Service.extend(Ember.Evented, {
  // -------------------------------------------------------------------------
  // Dependencies

  ajax: Ember.inject.service('l10n-ajax'),

  // -------------------------------------------------------------------------
  // Properties

  /**
   * Current locale from user, defaults
   * to 'defaultLocale' if not retrievable
   * or currently available due to missing
   * translations.
   *
   * @property locale
   * @type {String}
   * @default null
   * @public
   */
  locale: null,

  /**
   * Use this property if you want to force
   * a specific locale and skip automatic
   * detection of user's system settings.
   * This is useful for signed in users,
   * but beware that unsupported locales
   * will fallback to the default locale!
   *
   * @property forceLocale
   * @type {String}
   * @default null
   * @public
   */
  forceLocale: null,

  /**
   * Fallback locale for unavailable locales.
   *
   * @property defaultLocale
   * @type {String}
   * @default 'en'
   * @public
   */
  defaultLocale: 'en',

  /**
   * Will invoke a language detection or loads
   * language from `forceLanguage` on service
   * instantiation. If disabling, make sure to
   * set locale manually with setLocale().
   *
   * @property autoInitialize
   * @type {String}
   * @default null
   * @public
   */
  autoInitialize: true,

  /**
   * Directory containing JSON files with all
   * translations for corresponding locale.
   *
   * @property jsonPath
   * @type {String}
   * @default 'assets/locales'
   * @public
   */
  jsonPath: '/assets/locales',

  /**
   * Currently available translations hash.
   *
   * @property availableLocales
   * @type {Object}
   * @public
   */
  availableLocales: Ember.computed(function() {
    return {
      'en': this.t('en')
    };
  }),

  /**
   * Reference to gettext library.
   *
   * @property _gettext
   * @type {String}
   * @default null
   * @private
   */
  _gettext: window.i18n(),

  /**
   * Cache persisting loaded JSON files to
   * avoid duplicated requests going out.
   *
   * @property _cache
   * @type {Object}
   * @default {}
   * @private
   */
  _cache: Ember.computed(function() {
    return {}; // complex type!
  }),

  // -------------------------------------------------------------------------
  // Methods

  /**
   * Sets initial locale. If you want to to
   * skip language detection, please provide
   * `forceLocale` property with reopen().
   *
   * @method init
   * @return {Void}
   * @public
   */
  init() {
    this._super(...arguments);
    if (!this.get('autoInitialize')) {
      return;
    }

    this.setLocale(this.detectLocale());
  },

  /**
   * Provides current locale. If not set,
   * delivers default locale.
   *
   * @method setLocale
   * @param {String} locale
   * @return {String}
   * @public
   */
  getLocale() {
    let defaultLocale = this.get('defaultLocale');
    let locale = this.get('locale');
    if (Ember.isNone(locale)) {
      return defaultLocale;
    }

    return locale;
  },

  /**
   * Sets active locale if available.
   *
   * @method setLocale
   * @param {String} locale
   * @return {String}
   * @public
   */
  setLocale(locale) {
    if (!this.hasLocale(locale)) {
      return;
    }

    console.info(`l10n.js: Locale set to: "${locale}"`);
    this.get('_gettext').setLocale(locale);
    this.set('locale', locale);
    this._loadJSON();
  },

  /**
   * Checks if locale is available.
   *
   * @method setLocale
   * @param {String} locale
   * @return {Boolean}
   * @public
   */
  hasLocale(locale) {
    let availableLocales = this.get('availableLocales');
    let hasLocale = !Ember.isNone(availableLocales[locale]);
    if (!hasLocale) {
      console.warn(`l10n.js: Locale "${locale}" is not available!`);
    }

    return hasLocale;
  },

  /**
   * Gets user's current client language and
   * provides extracted ISO-Code.
   *
   * @method detectLocale
   * @return {String}
   * @public
   */
  detectLocale() {
    let defaultLocale = this.get('defaultLocale');
    let forceLocale = this.get('forceLocale');
    let { navigator } = window;
    let locale;

    // auto detect locale if no force locale
    if (Ember.isNone(forceLocale)) {

      // special case: android user agents
      if (navigator && navigator.userAgent &&
        (locale = navigator.userAgent.match(
          /android.*\W(\w\w)-(\w\w)\W/i
        ))
      ) {
        locale = locale[1];
      }

      // for all other browsers
      if (Ember.isNone(locale) && navigator) {
        if (navigator.language) {
          locale = navigator.language;
        } else if (navigator.browserLanguage) {
          locale = navigator.browserLanguage;
        } else if (navigator.systemLanguage) {
          locale = navigator.systemLanguage;
        } else if (navigator.userLanguage) {
          locale = navigator.userLanguage;
        }
      }

      locale = locale.substr(0, 2);
    } else {
      locale = forceLocale;
    }

    // provide default locale if not available
    if (!this.hasLocale(locale)) {
      console.info(`l10n.js: Falling back to default language: "${defaultLocale}"!`);
      return defaultLocale;
    }

    // otherwise return detected locale
    if (Ember.isNone(forceLocale)) {
      console.info(`l10n.js: Automatically detected user language: "${locale}"`);
    } else {
      console.info(`l10n.js: Using forced locale: "${locale}"`);
    }

    return locale;
  },

  /**
   * Translates a singular form message id.
   *
   * @method t
   * @param {String} msgid
   * @param {Object} hash
   * @return {String}
   * @public
   */
  t(msgid, hash = {}) {
    if (Ember.typeOf(msgid) !== 'string') {
      try {
        msgid = msgid.toString();
      } catch (e) {
        console.log('l10n.js: "msgid" param for t() should be either a string or an object implementing toString() method!');
        return msgid;
      }
    }

    return this._strfmt(this.get('_gettext').gettext(msgid), hash);
  },

  /**
   * Translates a plural form message id.
   *
   * @method n
   * @param {String} msgid
   * @param {String} msgidPlural
   * @param {Number} count
   * @param {Object} hash
   * @return {String}
   * @public
   */
  n(msgid, msgidPlural, count = 1, hash = {}) {
    if (Ember.typeOf(msgid) !== 'string') {
      try {
        msgid = msgid.toString();
      } catch (e) {
        console.log('l10n.js: "msgid" param for n() should be either a string or an object implementing toString() method!');
        return msgid;
      }
    }

    if (Ember.typeOf(msgidPlural) !== 'string') {
      try {
        msgidPlural = msgidPlural.toString();
      } catch (e) {
        console.log('l10n.js: "msgid_plural" param for n() should be either a string or an object implementing toString() method!');
        return msgid;
      }
    }

    return this._strfmt(this.get('_gettext').ngettext(msgid, msgidPlural, count), hash);
  },

  /**
   * Replaces placeholders like {{placeholder}} from string.
   *
   * @method _strfmt
   * @param {String} string
   * @param {Object} hash
   * @return {String}
   * @private
   */
  _strfmt(string, hash) {
    // don't process empty hashes
    if (Ember.isNone(hash)) {
      return string;
    }

    // find and replace all {{placeholder}}
    let pattern = /{{\s*([\w]+)\s*}}/g;
    let replace = (idx, match) => {
      let value = hash[match];
      if (Ember.isNone(value)) {
        return `{{${match}}}`;
      }

      if (Ember.typeOf(value) === 'string') {
        value = this.get('_gettext').gettext(value);
      }

      return value;
    };

    return string.replace(pattern, replace);
  },

  /**
   * Loads current locale translation file.
   * Triggers `translation_loaded` event.
   *
   * @method _load
   * @return {Void}
   * @private
   */
  _loadJSON() {
    let ajax = this.get('ajax');
    let cache = this.get('_cache');
    let locale = this.get('locale');
    let url = `${this.get('jsonPath')}/${locale}.json`;

    let successCallback = (response) => {
      let cachedResponse = Ember.copy(response, true);
      this.notifyPropertyChange('availableLocales');
      this.get('_gettext').loadJSON(response);
      this.trigger('translation_loaded');
      cache[locale] = cachedResponse;
    };

    let failureCallback = (reason) => {
      console.error(`l10n.js: An error occured loading "${url}": ${reason}`);
    };

    // used cache translation if present
    if (cache.hasOwnProperty(locale)) {
      successCallback(cache[locale]);
      return;
    }

    // otherwise load json file from assets
    ajax.request(url).then(
      successCallback,
      failureCallback
    );
  }

});
<|endoftext|>