<commit_before>var path = require('path');
var fs = require('fs');

var levels = require('enb-bem/techs/levels');
var files = require('enb-bem/techs/files');
var mergeFiles = require('enb/techs/file-merge');

var provide = require('enb/techs/file-provider');
var bemdeclToDeps = require('./techs/bemdecl-to-deps');
var bemdeclFromBemjson = require('enb-bem/techs/bemdecl-from-bemjson');
var bemdeclFromDepsByTech = require('enb-bem/techs/bemdecl-from-deps-by-tech');
var mergeBemdecl = require('enb-bem/techs/merge-bemdecl');
var deps = require('enb-bem/techs/deps-old');

var bemhtml = require('enb-bemxjst/techs/bemhtml-old');
var htmlFromBemjson = require('enb-bemxjst/techs/html-from-bemjson');

var css = require('enb-stylus/techs/css-stylus');
var js = require('./techs/borschik-include-js');
var modules = require('enb-modules/techs/prepend-modules');

var borschik = require('enb-borschik/techs/borschik');
var copy = require('enb/techs/file-copy');

var NEED_COVERAGE = process.env.ISTANBUL_COVERAGE;
var borschikTechIstanbulPath = path.join(__dirname, '..', 'node_modules', 'borschik-tech-istanbul');

exports.configure = function (config, options) {
    var pattern = path.join(options.destPath, '*');
    var sourceLevels = [].concat(options.sourceLevels);

    config.nodes(pattern, function (nodeConfig) {
        var sublevel = path.join(nodeConfig.getNodePath(), 'blocks');

        if (fs.existsSync(sublevel)) {
            sourceLevels.push(sublevel);
        }

        // Base techs
        nodeConfig.addTechs([
            [levels, { levels: sourceLevels }]
        ]);

        // Deps
        nodeConfig.addTechs([
            [provide, { target: '?.bemjson.js' }],
            [provide, { target: '?.base.bemdecl.js' }],

            [bemdeclFromBemjson, { target: '?.bemjson.bemdecl.js' }],
            [mergeBemdecl, {
                bemdeclSources: ['?.base.bemdecl.js', '?.bemjson.bemdecl.js'],
                bemdeclTarget: '?.bemdecl.js'
            }],
            [bemdeclToDeps, { source: '?.base.bemdecl.js', target: '?.base.deps.js' }],

            [deps]
        ]);

        // Files
        nodeConfig.addTechs([
            [files, {
                depsTarget: '?.base.deps.js',
                filesTarget: '?.base.files',
                dirsTarget: '?.base.dirs'
            }],
            [files]
        ]);

        // Client BEMHTML
        nodeConfig.addTechs([
            [bemdeclFromDepsByTech, {
                target: '?.js.bemhtml.bemdecl.js',
                sourceTech: 'js',
                destTech: 'bemhtml'
            }],
            [bemdeclFromDepsByTech, {
                target: '?.spec-js.bemhtml.bemdecl.js',
                sourceTech: 'spec.js',
                destTech: 'bemhtml'
            }],
            [mergeBemdecl, {
                bemdeclSources: ['?.js.bemhtml.bemdecl.js', '?.spec-js.bemhtml.bemdecl.js', '?.bemjson.bemdecl.js'],
                bemdeclTarget: '?.bemhtml.bemdecl.js'
            }],

            [deps, {
                depsTarget: '?.bemhtml.deps.js',
                bemdeclTarget: '?.bemhtml.bemdecl.js'
            }],
            [files, {
                depsTarget: '?.bemhtml.deps.js',
                filesTarget: '?.bemhtml.files',
                dirsTarget: '?.bemhtml.dirs'
            }],

            [bemhtml, {
                target: '?.browser.bemhtml.js',
                filesTarget: '?.bemhtml.files',
                devMode: false
            }]
        ]);

        // HTML
        nodeConfig.addTechs([
            [bemhtml, { devMode: false }],
            [htmlFromBemjson]
        ]);

        // Browser JS
        nodeConfig.addTechs([
            [js, {
                sourceSuffixes: options.jsSuffixes,
                target: '?.source.browser.js'
            }],
            [modules, {
                target: '?.browser.js',
                source: '?.source.browser.js'
            }],
            [js, {
                target: '?.pure.spec.js',
                sourceSuffixes: ['spec.js'],
                filesTarget: '?.base.files'
            }],
            [mergeFiles, {
                target: '?.pre.spec.js',
                sources: ['?.browser.js', '?.bemhtml.js', '?.pure.spec.js']
            }]
        ]);

        if (NEED_COVERAGE) {
            nodeConfig.addTechs([
                [borschik, {
                    source: '?.pre.spec.js',
                    target: '?.coverage.spec.js',
                    tech: borschikTechIstanbulPath,
                    techOptions: {
                        instrumentPaths: options.levels.map(function (level) {
                            return typeof level === 'string' ? level : level.path;
                        })
                    },
                    levels: options.levels,
                    freeze: true,
                    minify: false
                }],
                [copy, {
                    source: '?.coverage.spec.js',
                    target: '?.spec.js'
                }]
            ]);
        } else {
            nodeConfig.addTech(
                [borschik, {
                    source: '?.pre.spec.js',
                    target: '?.spec.js',
                    freeze: true,
                    minify: false
                }]
            );
        }

        // CSS
        nodeConfig.addTech(css);

        nodeConfig.addTargets([
            '?.spec.js', '?.css', '?.html'
        ]);
    });
};
<commit_msg>Updated `node-configurator`<commit_after>var path = require('path');
var fs = require('fs');

var levels = require('enb-bem/techs/levels');
var files = require('enb-bem/techs/files');
var mergeFiles = require('enb/techs/file-merge');

var provide = require('enb/techs/file-provider');
var bemdeclToDeps = require('./techs/bemdecl-to-deps');
var bemdeclFromBemjson = require('enb-bem/techs/bemdecl-from-bemjson');
var bemdeclFromDepsByTech = require('enb-bem/techs/bemdecl-from-deps-by-tech');
var mergeBemdecl = require('enb-bem/techs/merge-bemdecl');
var deps = require('enb-bem/techs/deps-old');

var bemhtml = require('enb-bemxjst/techs/bemhtml-old');
var htmlFromBemjson = require('enb-bemxjst/techs/html-from-bemjson');

var css = require('enb-stylus/techs/css-stylus');
var js = require('./techs/borschik-include-js');
var modules = require('enb-modules/techs/prepend-modules');

var borschik = require('enb-borschik/techs/borschik');
var copy = require('enb/techs/file-copy');

var NEED_COVERAGE = process.env.ISTANBUL_COVERAGE;
var borschikTechIstanbulPath = path.join(__dirname, '..', 'node_modules', 'borschik-tech-istanbul');

exports.configure = function (config, options) {
    var pattern = path.join(options.destPath, '*');
    var sourceLevels = [].concat(options.sourceLevels);

    config.nodes(pattern, function (nodeConfig) {
        var sublevel = path.join(nodeConfig.getNodePath(), 'blocks');

        if (fs.existsSync(sublevel)) {
            sourceLevels.push(sublevel);
        }

        // Base techs
        nodeConfig.addTechs([
            [levels, { levels: sourceLevels }]
        ]);

        // Deps
        nodeConfig.addTechs([
            [provide, { target: '?.bemjson.js' }],
            [provide, { target: '?.base.bemdecl.js' }],

            [bemdeclFromBemjson, { target: '?.bemjson.bemdecl.js' }],
            [mergeBemdecl, {
                target: '?.bemdecl.js',
                sources: ['?.base.bemdecl.js', '?.bemjson.bemdecl.js']
            }],
            [bemdeclToDeps, { source: '?.base.bemdecl.js', target: '?.base.deps.js' }],

            [deps]
        ]);

        // Files
        nodeConfig.addTechs([
            [files, {
                depsFile: '?.base.deps.js',
                filesTarget: '?.base.files',
                dirsTarget: '?.base.dirs'
            }],
            [files]
        ]);

        // Client BEMHTML
        nodeConfig.addTechs([
            [bemdeclFromDepsByTech, {
                target: '?.js.bemhtml.bemdecl.js',
                sourceTech: 'js',
                destTech: 'bemhtml'
            }],
            [bemdeclFromDepsByTech, {
                target: '?.spec-js.bemhtml.bemdecl.js',
                sourceTech: 'spec.js',
                destTech: 'bemhtml'
            }],
            [mergeBemdecl, {
                target: '?.bemhtml.bemdecl.js',
                sources: ['?.js.bemhtml.bemdecl.js', '?.spec-js.bemhtml.bemdecl.js', '?.bemjson.bemdecl.js']
            }],

            [deps, {
                target: '?.bemhtml.deps.js',
                sourceDepsFile: '?.bemhtml.bemdecl.js'
            }],
            [files, {
                depsFile: '?.bemhtml.deps.js',
                filesTarget: '?.bemhtml.files',
                dirsTarget: '?.bemhtml.dirs'
            }],

            [bemhtml, {
                target: '?.browser.bemhtml.js',
                filesTarget: '?.bemhtml.files',
                devMode: false
            }]
        ]);

        // HTML
        nodeConfig.addTechs([
            [bemhtml, { devMode: false }],
            [htmlFromBemjson]
        ]);

        // Browser JS
        nodeConfig.addTechs([
            [js, {
                sourceSuffixes: options.jsSuffixes,
                target: '?.source.browser.js'
            }],
            [modules, {
                target: '?.browser.js',
                source: '?.source.browser.js'
            }],
            [js, {
                target: '?.pure.spec.js',
                sourceSuffixes: ['spec.js'],
                filesTarget: '?.base.files'
            }],
            [mergeFiles, {
                target: '?.pre.spec.js',
                sources: ['?.browser.js', '?.bemhtml.js', '?.pure.spec.js']
            }]
        ]);

        if (NEED_COVERAGE) {
            nodeConfig.addTechs([
                [borschik, {
                    source: '?.pre.spec.js',
                    target: '?.coverage.spec.js',
                    tech: borschikTechIstanbulPath,
                    techOptions: {
                        instrumentPaths: options.levels.map(function (level) {
                            return typeof level === 'string' ? level : level.path;
                        })
                    },
                    levels: options.levels,
                    freeze: true,
                    minify: false
                }],
                [copy, {
                    source: '?.coverage.spec.js',
                    target: '?.spec.js'
                }]
            ]);
        } else {
            nodeConfig.addTech(
                [borschik, {
                    source: '?.pre.spec.js',
                    target: '?.spec.js',
                    freeze: true,
                    minify: false
                }]
            );
        }

        // CSS
        nodeConfig.addTech(css);

        nodeConfig.addTargets([
            '?.spec.js', '?.css', '?.html'
        ]);
    });
};
<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>Solved AboutMutability<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe('John Smith');

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe('Smith, John');
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe("John");
    expect(aPerson.getLastName()).toBe("Smith");
    expect(aPerson.getFullName()).toBe('John Smith');

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe('Andrews, Penny');
  });

});
<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>Completed AboutMutability koans<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe("Smith, John");
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe("John");
    expect(aPerson.getLastName()).toBe("Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe("Andrews, Penny");
  });

});
<|endoftext|>


<commit_before>/*
 * Mensuration Widget
 * Logic code from Ian Wilson's (Esri PS) Image Observables demo
 * Transformed into a widget (mostly AMD) for the Basic Viewer by James Tedrick
 *
 * Declaration syntax:
 * require(['dtc/Mensuration], function(Mensuration){
 * 	new Mensuration({map: <esri.Map>, imageService: <esri.layers.ArcGISImageServiceLayer>}, <string|domNode>domNode)
 * });
 *
 * Resources used by this widget:
 * 		-templates/Mensuration.html
 * 		-css/Mensuration.css
 * 		-assets/BaseTop.png
 * 		-assets/BaseTopShadow.png
 * 		-assets/TopTopShadow.png
 *
 */

define(["dojo/_base/declare", "dojo/_base/connect", "dojo/_base/array", "dojo/_base/lang",
		"dijit/_WidgetBase", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin",
		"dojo/text!./templates/Mensuration.html",
		"dijit/form/Select", "dijit/form/DropDownButton",
		"dojo/dom", "dojo/dom-attr", "dojo/dom-construct", "dijit/registry"],
		function(	declare, connect, array, lang,
					_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin,
					dijitTemplate,
					Select, ToggleButton,
					dom, domAttr, domConstruct, registry) {
	return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
		declaredClass : "dtc.Mensuration",
		templateString : dijitTemplate,

		options : {
			map : null,
			imageService : null
		},
		//imageService: esri.layers.ArcGISImageServiceLayer
		imageService : null,
		//drawToolbar: esri.toolbars.Draw
		drawToolbar : null,
		//measureMethod: string -> esriMensurationHeightFromBaseAndTop|esriMensurationHeightFromBaseAndTopShadow|esriMensurationHeightFromTopAndTopShadow
		measureMethod : null,
		//measureLine: esri.geometry.Polyline (in this application, it will always be a 2 point line)
		measureLine : null,
		//units: string (Linear units from esri.Units)
		units : null,
		//_MENSURATIONOPTIONS: The types of mensuration operations that can be done.  Populates the buttons during startup
		_MENSURATIONOPTIONS : [{
			method : "esriMensurationHeightFromBaseAndTop",
			title : "Measure from the base of the building to the top of the building",
			iconClass : "iconBaseTop"
		}, {
			method : "esriMensurationHeightFromBaseAndTopShadow",
			title : "Measure from the base of the building to the shadow of the top of the building",
			iconClass : "iconBaseTopShadow"
		}, {
			method : "esriMensurationHeightFromTopAndTopShadow",
			title : "Measure from the top of the building to the shadow of the top of the building",
			iconClass : "iconTopTopShadow"
		}],
		//_UNITS: the types of valid (i.e., linear) units. Populates this.unitsSelect during startup
		_UNITS : [{
			value : "esriInches",
			label : "Inches"
		}, {
			value : "esriFeet",
			label : "Feet"
		}, {
			value : "esriYards",
			label : "Yards"
		}, {
			value : "esriMiles",
			label : "Miles"
		}, {
			value : "esriMillimeters",
			label : "Millimeters"
		}, {
			value : "esriCentimeters",
			label : "Centimeters"
		}, {
			value : "esriMeters",
			label : "Meters",
			selected : true
		}, {
			value : "esriKilometers",
			label : "Kilometers"
		}, {
			value : "esriDecimeters",
			label : "Decimeters"
		}],

		constructor : function(options, srcRefNode) {
			declare.safeMixin(this.options, options);

			this.domNode = srcRefNode;
			this.map = this.options.map;
			this.imageService = this.options.imageService;

		},

		startup : function() {
			var _self = this;

			if (!_self.map) {
				console.log('map required');
				_self.destroy();
			}

			if (this.map.loaded) {
				_self._init();
			} else {
				connect.connect(_self.map, "onLoad", function() {
					_self._init()
				});
			}
		},

		//Initialization code here (called by startup)
		_init : function() {
			var _self = this;
			//Load the stylesheet
			domConstruct.create("link", {
				rel : "stylesheet",
				type : "text/css",
				href : "dtc/css/Mensuration.css"
			}, document.getElementsByTagName('head')[0]);

			//Instantiate the draw toolbar and have it perform a measurement when the line is completed
			//I'm getting a multiple define error when I try to load via AMD (5/10/13)
			_self.drawToolbar = new esri.toolbars.Draw(this.map, {
				tooltipOffset : 50
			});
			connect.connect(_self.drawToolbar, "onDrawEnd", lang.hitch(_self, _self.measureBuilding));

			//Add the Units to the Select and set the default
			_self.unitsSelect.addOption(_self._UNITS);
			_self.units = 'esriMeters';

			/*
			//Add Units to the dropdown button
			require(["dijit/DropDownMenu", "dijit/MenuItem"], function(DropDownMenu, MenuItem){
				var unitMenu = new DropDownMenu();
				array.forEach(_self._UNITS, function(thisUnit){
					var thisUnitItem = new MenuItem({
						label: thisUnit.label,
						onClick: function(){_self.units = thisUnit.value; _self.measureBuilding(null);}
					});
					console.log(thisUnitItem);
					unitMenu.addChild(thisUnitItem);
				});
				console.log(unitMenu);
				_self.btnUnits.set('dropdown', unitMenu);
				console.log(_self.btnUnits);
			});
*/
			//When we change the units, update the units and fire off a new mensuration request to update the result
			_self.unitsSelect.on("change", function(newValue) {
				_self.units = newValue;
				_self.measureBuilding(null);
			});

			//Buttons - using the _MENSURATIONOPTIONS to simplify construction code with a for loop
			require(["dijit/form/Button"], function(Button) {
				array.forEach(_self._MENSURATIONOPTIONS, function(option) {
					new Button({
						onClick : lang.hitch(_self, function() {
							_self.drawBuildingHeight(option.method);
						}),
						title : option.title,
						iconClass : option.iconClass
					}).placeAt(_self.buttonContainer);
				});
			});
		},

		//Custom setter for the imageService variable to determine whether the service supports mensuration
		_setImageServiceAttr : function(/*string (ID)*/serviceID) {
			var _self = this;
			var service = null;
			//Get the service from the map and find out if it's mensurable
			if (serviceID) {
				service = this.map.getLayer(serviceID);
				if (service.loaded === true) {
					_self._buttonSet(service);
				} else {
					service.on("load", function() {
						_self._buttonSet(service);
					});
				}
			}
			//Set the service
			this._set('imageService', service);
		},
		//Corresponding getter so that the get returns the id, which is what set expects
		//In nearly every case you should be able to widget.set('attribute', widget.get('attribute'))
		_getImageServiceAttr : function() {
			return (this.imageService.id)
		},

		_buttonSet : function(service) {
			var isNotMensurable = true;
			if (service.hasOwnProperty('capabilities')) {
				isNotMensurable = (service.capabilities.indexOf('Mensuration') < 0);
			}

			//If the service doesn't support mensuration, disable the buttons
			var buttons = registry.findWidgets(this.buttonContainer);
			array.forEach(buttons, function(button) {
				button.set('disabled', isNotMensurable);
			});
		},

		drawBuildingHeight : function(method) {
			this.resetHeights();
			this.measureMethod = method;
			this.measureLine = null;
			this.map.setMapCursor('crosshair');
			this.drawToolbar.activate(esri.toolbars.Draw.LINE);
		},

		measureBuilding : function(result) {
			console.log('measureBuilding');
			var _self = this;
			this.drawToolbar.deactivate();
			var imageServiceLayer = this.imageService.url;
			if (result) {
				_self.measureLine = result;
			}
			if (!_self.measureLine) {
				return;
			}
			var fromPoint = _self.measureLine.getPoint(0, 0);
			var toPoint = _self.measureLine.getPoint(0, 1);
			domAttr.set('output.info', "innerHTML", 'Measuring building heights...');
			require(["dojo/json", "esri/request"], function(JSON, esriRequest) {
				var contentObj = {
					fromGeometry : JSON.stringify(fromPoint.toJson()),
					toGeometry : JSON.stringify(toPoint.toJson()),
					geometryType : 'esriGeometryPoint',
					measureOperation : _self.measureMethod,
					linearUnit : _self.units,
					mosaicRule : '',
					pixelSize : '',
					f : 'json'
				};
				new esriRequest({
					url : lang.replace("{0}/{1}", [imageServiceLayer, 'measure']),
					content : contentObj,
					callbackParamName : "callback",
					load : lang.hitch(_self, _self.onResult),
					error : lang.hitch(_self, _self.onResultError)
				});
			});
		},

		onResult : function(response) {
			domAttr.set('output.info', "innerHTML", '');
			// ANALYSIS RESULTS - MEASUREMENTS //
			var measurement = response.height;
			//console.log(measurement);
			// NUMBER FORMATTING //
			var numFormat = {
				places : 2
			};
			// UPDATE MEASUREMENT UI //
			require(['dojo/number'], function(number) {
				domAttr.set('output.MensurationHeight', "innerHTML", number.format(Math.abs(measurement.value), numFormat));
				domAttr.set('output.HeightUncertainty', "innerHTML", number.format(measurement.uncertainty, numFormat));
				//domAttr.set('output.LinearUnit', "innerHTML", measurement.unit.replace("esri", ""));
			});
			// DISPLAY MEASUREMENT GRAPHICS //
			//addMeasurementGraphic(userLine, measurement);
			this.map.setMapCursor('default');

		},
		onResultError : function(error) {
			domAttr.set('output.info', "innerHTML", error.message);
			this.map.setMapCursor('default');
		},

		resetHeights : function() {
			// RESET MEASUREMENT UI //
			domAttr.set('output.MensurationHeight', "innerHTML", '0.00');
			domAttr.set('output.HeightUncertainty', "innerHTML", '0.00');
			//domAttr.set('output.LinearUnit', "innerHTML", '');
			domAttr.set('output.info', "innerHTML", '');
		}
	});

});
<commit_msg>Code cleanup<commit_after>/*
 * Mensuration Widget
 * Logic code from Ian Wilson's (Esri PS) Image Observables demo
 * Transformed into a widget (mostly AMD) for the Basic Viewer by James Tedrick
 *
 * Declaration syntax:
 * require(['dtc/Mensuration], function(Mensuration){
 * 	new Mensuration({map: <esri.Map>, imageService: <esri.layers.ArcGISImageServiceLayer>}, <string|domNode>domNode)
 * });
 *
 * Resources used by this widget:
 * 		-templates/Mensuration.html
 * 		-css/Mensuration.css
 * 		-assets/BaseTop.png
 * 		-assets/BaseTopShadow.png
 * 		-assets/TopTopShadow.png
 *
 */

define(["dojo/_base/declare", "dojo/_base/connect", "dojo/_base/array", "dojo/_base/lang",
		"dijit/_WidgetBase", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin",
		"dojo/text!./templates/Mensuration.html",
		"dijit/form/Select", "dijit/form/DropDownButton",
		"dojo/dom", "dojo/dom-attr", "dojo/dom-construct", "dijit/registry"],
		function(	declare, connect, array, lang,
					_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin,
					dijitTemplate,
					Select, ToggleButton,
					dom, domAttr, domConstruct, registry) {
	return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
		declaredClass : "dtc.Mensuration",
		templateString : dijitTemplate,

		options : {
			map : null,
			imageService : null
		},
		//imageService: esri.layers.ArcGISImageServiceLayer
		imageService : null,
		//drawToolbar: esri.toolbars.Draw
		drawToolbar : null,
		//measureMethod: string -> esriMensurationHeightFromBaseAndTop|esriMensurationHeightFromBaseAndTopShadow|esriMensurationHeightFromTopAndTopShadow
		measureMethod : null,
		//measureLine: esri.geometry.Polyline (in this application, it will always be a 2 point line)
		measureLine : null,
		//units: string (Linear units from esri.Units)
		units : null,
		//_MENSURATIONOPTIONS: The types of mensuration operations that can be done.  Populates the buttons during startup
		_MENSURATIONOPTIONS : [{
			method : "esriMensurationHeightFromBaseAndTop",
			title : "Measure from the base of the building to the top of the building",
			iconClass : "iconBaseTop"
		}, {
			method : "esriMensurationHeightFromBaseAndTopShadow",
			title : "Measure from the base of the building to the shadow of the top of the building",
			iconClass : "iconBaseTopShadow"
		}, {
			method : "esriMensurationHeightFromTopAndTopShadow",
			title : "Measure from the top of the building to the shadow of the top of the building",
			iconClass : "iconTopTopShadow"
		}],
		//_UNITS: the types of valid (i.e., linear) units. Populates this.unitsSelect during startup
		_UNITS : [{
			value : "esriInches",
			label : "Inches"
		}, {
			value : "esriFeet",
			label : "Feet"
		}, {
			value : "esriYards",
			label : "Yards"
		}, {
			value : "esriMiles",
			label : "Miles"
		}, {
			value : "esriMillimeters",
			label : "Millimeters"
		}, {
			value : "esriCentimeters",
			label : "Centimeters"
		}, {
			value : "esriMeters",
			label : "Meters",
			selected : true
		}, {
			value : "esriKilometers",
			label : "Kilometers"
		}, {
			value : "esriDecimeters",
			label : "Decimeters"
		}],

		constructor : function(options, srcRefNode) {
			declare.safeMixin(this.options, options);

			this.domNode = srcRefNode;
			this.map = this.options.map;
			this.imageService = this.options.imageService;

		},

		startup : function() {
			var _self = this;

			if (!_self.map) {
				console.log('map required');
				_self.destroy();
			}

			if (this.map.loaded) {
				_self._init();
			} else {
				connect.connect(_self.map, "onLoad", function() {
					_self._init()
				});
			}
		},

		//Initialization code here (called by startup)
		_init : function() {
			var _self = this;
			//Load the stylesheet
			domConstruct.create("link", {
				rel : "stylesheet",
				type : "text/css",
				href : "dtc/css/Mensuration.css"
			}, document.getElementsByTagName('head')[0]);

			//Instantiate the draw toolbar and have it perform a measurement when the line is completed
			//I'm getting a multiple define error when I try to load via AMD (5/10/13)
			_self.drawToolbar = new esri.toolbars.Draw(this.map, {
				tooltipOffset : 50
			});
			connect.connect(_self.drawToolbar, "onDrawEnd", lang.hitch(_self, _self.measureBuilding));

			//Add the Units to the Select and set the default
			_self.unitsSelect.addOption(_self._UNITS);
			_self.units = 'esriMeters';

			//When we change the units, update the units and fire off a new mensuration request to update the result
			_self.unitsSelect.on("change", function(newValue) {
				_self.units = newValue;
				_self.measureBuilding(null);
			});

			//Buttons - using the _MENSURATIONOPTIONS to simplify construction code with a for loop
			require(["dijit/form/Button"], function(Button) {
				array.forEach(_self._MENSURATIONOPTIONS, function(option) {
					new Button({
						onClick : lang.hitch(_self, function() {
							_self.drawBuildingHeight(option.method);
						}),
						title : option.title,
						iconClass : option.iconClass
					}).placeAt(_self.buttonContainer);
				});
			});
		},

		//Custom setter for the imageService variable to determine whether the service supports mensuration
		_setImageServiceAttr : function(/*string (ID)*/serviceID) {
			var _self = this;
			var service = null;
			//Get the service from the map and find out if it's mensurable
			if (serviceID) {
				service = this.map.getLayer(serviceID);
				if (service.loaded === true) {
					_self._buttonSet(service);
				} else {
					service.on("load", function() {
						_self._buttonSet(service);
					});
				}
			}
			//Set the service
			this._set('imageService', service);
		},
		//Corresponding getter so that the get returns the id, which is what set expects
		//In nearly every case you should be able to widget.set('attribute', widget.get('attribute'))
		_getImageServiceAttr : function() {
			return (this.imageService.id)
		},

		//Detect whether the image service supports mensuration
		_buttonSet : function(service) {
			var isNotMensurable = true;
			if (service.hasOwnProperty('capabilities')) {
				isNotMensurable = (service.capabilities.indexOf('Mensuration') < 0);
			}

			//If the service doesn't support mensuration, disable the buttons
			var buttons = registry.findWidgets(this.buttonContainer);
			array.forEach(buttons, function(button) {
				button.set('disabled', isNotMensurable);
			});
		},

		//Begin measurement- change the cursor and show the line being drawn
		drawBuildingHeight : function(method) {
			this.resetHeights();
			this.measureMethod = method;
			this.measureLine = null;
			this.map.setMapCursor('crosshair');
			this.drawToolbar.activate(esri.toolbars.Draw.LINE);
		},

		measureBuilding : function(result) {
			var _self = this;
			this.drawToolbar.deactivate();
			var imageServiceLayer = this.imageService.url;
			if (result) {
				_self.measureLine = result;
			}
			if (!_self.measureLine) {
				return;
			}
			var fromPoint = _self.measureLine.getPoint(0, 0);
			var toPoint = _self.measureLine.getPoint(0, 1);
			domAttr.set('output.info', "innerHTML", 'Measuring building heights...');
			require(["dojo/json", "esri/request"], function(JSON, esriRequest) {
				var contentObj = {
					fromGeometry : JSON.stringify(fromPoint.toJson()),
					toGeometry : JSON.stringify(toPoint.toJson()),
					geometryType : 'esriGeometryPoint',
					measureOperation : _self.measureMethod,
					linearUnit : _self.units,
					mosaicRule : '',
					pixelSize : '',
					f : 'json'
				};
				new esriRequest({
					url : lang.replace("{0}/{1}", [imageServiceLayer, 'measure']),
					content : contentObj,
					callbackParamName : "callback",
					load : lang.hitch(_self, _self.onResult),
					error : lang.hitch(_self, _self.onResultError)
				});
			});
		},

		onResult : function(response) {
			domAttr.set('output.info', "innerHTML", '');
			// ANALYSIS RESULTS - MEASUREMENTS //
			var measurement = response.height;
			//console.log(measurement);
			// NUMBER FORMATTING //
			var numFormat = {
				places : 2
			};
			// UPDATE MEASUREMENT UI //
			require(['dojo/number'], function(number) {
				domAttr.set('output.MensurationHeight', "innerHTML", number.format(Math.abs(measurement.value), numFormat));
				domAttr.set('output.HeightUncertainty', "innerHTML", number.format(measurement.uncertainty, numFormat));
			});
			// DISPLAY MEASUREMENT GRAPHICS //
			this.map.setMapCursor('default');

		},
		onResultError : function(error) {
			domAttr.set('output.info', "innerHTML", error.message);
			this.map.setMapCursor('default');
		},

		resetHeights : function() {
			// RESET MEASUREMENT UI //
			domAttr.set('output.MensurationHeight', "innerHTML", '0.00');
			domAttr.set('output.HeightUncertainty', "innerHTML", '0.00');
			domAttr.set('output.info', "innerHTML", '');
		}
	});

});
<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
    'Core/loadJsonp',
    'Core/DefaultProxy',
    'Core/RequestErrorEvent'
], function(
    loadJsonp,
    DefaultProxy,
    RequestErrorEvent) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn*/

    it('throws with no url', function() {
        expect(function() {
            loadJsonp();
        }).toThrowDeveloperError();
    });

    it('returns a promise that resolves when the request loads', function() {
        var testUrl = 'http://example.invalid/testuri';
        spyOn(loadJsonp, 'loadAndExecuteScript').and.callFake(function (url, name, deffered){
            expect(url).toContain(testUrl);
            expect(name).toContain('loadJsonp');
            expect(deffered).toBeDefined();
        });
        loadJsonp(testUrl);
    });

    it('returns a promise that rejects when the request errors', function() {
        var testUrl = 'http://example.invalid/testuri';
        return loadJsonp(testUrl).otherwise(function(error) {
            expect(error).toBeDefined();
        });
    });

    it('Appends parameters specified in options', function() {
        var testUrl = 'test';
        var options = {
            parameters: {
                isTest : 'true',
                myNum : 8
            }
        };
        spyOn(loadJsonp, 'loadAndExecuteScript').and.callFake(function(url, functionName, deferred) {
            expect(url).toContain('isTest=true&myNum=8');
        });
        loadJsonp(testUrl, options);
    });

    it('Uses callback name specified in options', function() {
        var testUrl = 'test';
        var options = {
            callbackParameterName : 'testCallback'
        };
        spyOn(loadJsonp, 'loadAndExecuteScript').and.callFake(function(url, functionName, deferred) {
            expect(url).toContain('testCallback=loadJsonp');
        });
        loadJsonp(testUrl, options);
    });

    it('Uses proxy url is proxy is specified', function() {
        var testUrl = 'test';
        var testProxy = '/proxy/';
        var options = {
            proxy: new DefaultProxy(testProxy)
        };
        spyOn(loadJsonp, 'loadAndExecuteScript').and.callFake(function(url, functionName, deferred) {
            expect(url).toStartWith(testProxy + '?' + testUrl);
        });
        loadJsonp(testUrl, options);
    });

});
<commit_msg>Removed Whitespace<commit_after>/*global defineSuite*/
defineSuite([
    'Core/loadJsonp',
    'Core/DefaultProxy',
    'Core/RequestErrorEvent'
], function(
    loadJsonp,
    DefaultProxy,
    RequestErrorEvent) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn*/

    it('throws with no url', function() {
        expect(function() {
            loadJsonp();
        }).toThrowDeveloperError();
    });

    it('returns a promise that resolves when the request loads', function() {
        var testUrl = 'http://example.invalid/testuri';
        spyOn(loadJsonp, 'loadAndExecuteScript').and.callFake(function (url, name, deffered){
            expect(url).toContain(testUrl);
            expect(name).toContain('loadJsonp');
            expect(deffered).toBeDefined();
        });
        loadJsonp(testUrl);
    });

    it('returns a promise that rejects when the request errors', function() {
        var testUrl = 'http://example.invalid/testuri';
        return loadJsonp(testUrl).otherwise(function(error) {
            expect(error).toBeDefined();
        });
    });

    it('Appends parameters specified in options', function() {
        var testUrl = 'test';
        var options = {
            parameters: {
                isTest : 'true',
                myNum : 8
            }
        };
        spyOn(loadJsonp, 'loadAndExecuteScript').and.callFake(function(url, functionName, deferred) {
            expect(url).toContain('isTest=true&myNum=8');
        });
        loadJsonp(testUrl, options);
    });

    it('Uses callback name specified in options', function() {
        var testUrl = 'test';
        var options = {
            callbackParameterName : 'testCallback'
        };
        spyOn(loadJsonp, 'loadAndExecuteScript').and.callFake(function(url, functionName, deferred) {
            expect(url).toContain('testCallback=loadJsonp');
        });
        loadJsonp(testUrl, options);
    });

    it('Uses proxy url is proxy is specified', function() {
        var testUrl = 'test';
        var testProxy = '/proxy/';
        var options = {
            proxy: new DefaultProxy(testProxy)
        };
        spyOn(loadJsonp, 'loadAndExecuteScript').and.callFake(function(url, functionName, deferred) {
            expect(url).toStartWith(testProxy + '?' + testUrl);
        });
        loadJsonp(testUrl, options);
    });
});
<|endoftext|>


<commit_before>import React from 'react';
import styled from 'styled-components';
import { Link, graphql } from 'gatsby';

import SEO from '../components/seo';
import Layout from '../components/list-layout';
import { ListItems, PostListItem } from '../components/list';

const Intro = styled.p`
  margin-top: var(--gutter) !important;
`;

const HomePage = ({pageContext, data}) => {
  const {featured, posts} = data;

  return (
    <Layout slug="/" featured={featured.edges[0].node}>
      <SEO
        title="Home"
        description="Featured and recent posts from ajfisher"
        type="list"
      />

      <Intro>Observations, images and code from ajfisher</Intro>

Featured posts

      <ListItems>
        {featured.edges.map(({node}, index) => {
          // jump out on first as this will appear up top
          if (index === 0) return;

          const { slug, title, date,
            listimage, listimage_position } = node.frontmatter;
          const {readingTime} = node.fields;

          const excerpt = node.frontmatter.excerpt || node.excerpt || null;

          return (
            <PostListItem
              key={slug}
              title={title}
              date={date}
              excerpt={excerpt}
              slug={slug}
              readingtime={readingTime.minutes}
              wordcount={readingTime.words}
              image={listimage}
              position={listimage_position}
            />
          );
        })}
      </ListItems>

Recent posts

      <ListItems>
        {posts.edges.map(({node}) => {
          const { slug, title, date,
            listimage, listimage_position } = node.frontmatter;
          const {readingTime} = node.fields;

          const excerpt = node.frontmatter.excerpt || node.excerpt || null;

          return (
            <PostListItem
              key={slug}
              title={title}
              date={date}
              excerpt={excerpt}
              slug={slug}
              readingtime={readingTime.minutes}
              wordcount={readingTime.words}
              image={listimage}
              position={listimage_position}
            />
          );
        })}
      </ListItems>

<Link to="/blog">See all posts</Link>

    </Layout>
  );
};

export default HomePage;

export const pageQuery = graphql`
  query {
    featured: allMarkdownRemark(
      filter: {frontmatter: {
        layout: {regex: "/^post/"}
        featured: {eq: true}
      }}
      sort: {order: DESC, fields: frontmatter___date}
      limit: 3
    ) {
      edges {
        node {
          id
          frontmatter {
            slug
            title
            listimage
            listimage_position
            date(formatString: "YYYY-MM-DD")
            excerpt
            featured
            featureimage
            featureimage_position
            small_title
            large_title
          }
          fields {
            readingTime {
              minutes
              words
            }
          }
        }
      }
    }
    posts: allMarkdownRemark(
      filter: {frontmatter: {
        layout: {regex: "/^post/"}
        featured: {in: [null, false]}
      }}
      sort: {order: DESC, fields: frontmatter___date}
      limit: 10
    ) {
      edges {
        node {
          id
          frontmatter {
            slug
            title
            listimage
            listimage_position
            date(formatString: "YYYY-MM-DD")
            excerpt
            featured
            featureimage
            featureimage_position
            small_title
            large_title
          }
          excerpt(pruneLength: 220)
          fields {
            readingTime {
              minutes
              words
            }
          }
        }
      }
    }
  }
`;

<commit_msg>fix: Added better title for the seo on home page<commit_after>import React from 'react';
import styled from 'styled-components';
import { Link, graphql } from 'gatsby';

import SEO from '../components/seo';
import Layout from '../components/list-layout';
import { ListItems, PostListItem } from '../components/list';

const Intro = styled.p`
  margin-top: var(--gutter) !important;
`;

const HomePage = ({pageContext, data}) => {
  const {featured, posts} = data;

  return (
    <Layout slug="/" featured={featured.edges[0].node}>
      <SEO
        title="Home | ajfisher.me"
        description="Featured and recent posts from ajfisher"
        type="list"
      />

      <Intro>Observations, images and code from ajfisher</Intro>

Featured posts

      <ListItems>
        {featured.edges.map(({node}, index) => {
          // jump out on first as this will appear up top
          if (index === 0) return;

          const { slug, title, date,
            listimage, listimage_position } = node.frontmatter;
          const {readingTime} = node.fields;

          const excerpt = node.frontmatter.excerpt || node.excerpt || null;

          return (
            <PostListItem
              key={slug}
              title={title}
              date={date}
              excerpt={excerpt}
              slug={slug}
              readingtime={readingTime.minutes}
              wordcount={readingTime.words}
              image={listimage}
              position={listimage_position}
            />
          );
        })}
      </ListItems>

Recent posts

      <ListItems>
        {posts.edges.map(({node}) => {
          const { slug, title, date,
            listimage, listimage_position } = node.frontmatter;
          const {readingTime} = node.fields;

          const excerpt = node.frontmatter.excerpt || node.excerpt || null;

          return (
            <PostListItem
              key={slug}
              title={title}
              date={date}
              excerpt={excerpt}
              slug={slug}
              readingtime={readingTime.minutes}
              wordcount={readingTime.words}
              image={listimage}
              position={listimage_position}
            />
          );
        })}
      </ListItems>

<Link to="/blog">See all posts</Link>

    </Layout>
  );
};

export default HomePage;

export const pageQuery = graphql`
  query {
    featured: allMarkdownRemark(
      filter: {frontmatter: {
        layout: {regex: "/^post/"}
        featured: {eq: true}
      }}
      sort: {order: DESC, fields: frontmatter___date}
      limit: 3
    ) {
      edges {
        node {
          id
          frontmatter {
            slug
            title
            listimage
            listimage_position
            date(formatString: "YYYY-MM-DD")
            excerpt
            featured
            featureimage
            featureimage_position
            small_title
            large_title
          }
          fields {
            readingTime {
              minutes
              words
            }
          }
        }
      }
    }
    posts: allMarkdownRemark(
      filter: {frontmatter: {
        layout: {regex: "/^post/"}
        featured: {in: [null, false]}
      }}
      sort: {order: DESC, fields: frontmatter___date}
      limit: 10
    ) {
      edges {
        node {
          id
          frontmatter {
            slug
            title
            listimage
            listimage_position
            date(formatString: "YYYY-MM-DD")
            excerpt
            featured
            featureimage
            featureimage_position
            small_title
            large_title
          }
          excerpt(pruneLength: 220)
          fields {
            readingTime {
              minutes
              words
            }
          }
        }
      }
    }
  }
`;

<|endoftext|>


<commit_before>"use strict";

var BaseSoftwareModel = require('../../../lib/model/base');
var TreeNode = require('../../../lib/model/components/treenode');
var Version = require('../../../lib/model/components/version');

class JasmineRuleModel extends BaseSoftwareModel {
    constructor() {
        super();
        this._tree = new TreeNode('root');
        this._tree.add(new TreeNode('child'));
        this._version = new Version('k1', 'v1');
        this._attr = {
            'root': {
                'test.value1': 0,
                'test.value2': 1,
                'test.value3': 21,
                'test.value4': 'root'
            },
            'child' : {
                'test.value1': 100,
                'test.value2': 50,
                'test.value3': 6,
                'test.value4': 'child'
            }
        }
    }

    /**
     * Get the Models Graph. A List of Objects, connecting `source` and `target`.
     * @return {Array<Dependency>}
     */
    get graph() {
        return [];
    }

    /**
     * Get the Root-Node of the tree.
     * @return {TreeNode}
     */
    get tree() {
        return this._tree;
    }

    /**
     * Get an ordered List of all versions.
     * @return {Array<Version>}
     */
    get versions() {
        return [this._version];
    }

    /**
     * Existence Function
     * @return {boolean}
     */
    exists() {
        return true;
    }

    /**
     * Property function
     * @return {Object}
     */
    attributes(node) {
        return this._attr[String(node)];
    }
}

module.exports = JasmineRuleModel;<commit_msg>Does OSX ignore Cases?<commit_after>"use strict";

var CCV = require('../../../app');
var BaseSoftwareModel = CCV.models.base;
var TreeNode = CCV.components.node;
var Version = CCV.components.version;

class JasmineRuleModel extends BaseSoftwareModel {
    constructor() {
        super();
        this._tree = new TreeNode('root');
        this._tree.add(new TreeNode('child'));
        this._version = new Version('k1', 'v1');
        this._attr = {
            'root': {
                'test.value1': 0,
                'test.value2': 1,
                'test.value3': 21,
                'test.value4': 'root'
            },
            'child' : {
                'test.value1': 100,
                'test.value2': 50,
                'test.value3': 6,
                'test.value4': 'child'
            }
        }
    }

    /**
     * Get the Models Graph. A List of Objects, connecting `source` and `target`.
     * @return {Array<Dependency>}
     */
    get graph() {
        return [];
    }

    /**
     * Get the Root-Node of the tree.
     * @return {TreeNode}
     */
    get tree() {
        return this._tree;
    }

    /**
     * Get an ordered List of all versions.
     * @return {Array<Version>}
     */
    get versions() {
        return [this._version];
    }

    /**
     * Existence Function
     * @return {boolean}
     */
    exists() {
        return true;
    }

    /**
     * Property function
     * @return {Object}
     */
    attributes(node) {
        return this._attr[String(node)];
    }
}

module.exports = JasmineRuleModel;<|endoftext|>


<commit_before>// Copyright 2015, EMC, Inc.

/* jshint node: true */

'use strict';

describe("ipmi fru Task Parser", function () {
    var stdoutMocks;
    var taskParser;

    before('fru task parser before', function () {
        stdoutMocks = require('./stdout-helper');
        // create a child injector with on-core and the base pieces we need to test this
        helper.setupInjector([
            helper.require('/spec/mocks/logger.js'),
            helper.require('/lib/utils/job-utils/command-parser.js')
        ]);

        taskParser = helper.injector.get('JobUtils.CommandParser');

    });

    it("should parse `ipmitool fru` output", function () {
        var esesCmd = 'sudo ipmitool fru';

        var tasks = [
            {
                cmd: esesCmd,
                stdout: stdoutMocks.ipmiFru,
                stderr: '',
                error: null
            }
        ];

        return taskParser.parseTasks(tasks)
        .spread(function (result) {
            expect(result.error).to.be.undefined;
            expect(result.store).to.be.true;
            expect(result.data).to.be.ok;
            //console.log(result.data);
            expect(_.size(result.data)).to.equal(3);
            expect(result.data.AST2300).to.be.an.Object;
            expect(result.data.AST2300['Chassis Serial']).to.equal('QTFCEV4120280');
            expect(result.source).to.equal('ipmi-fru');
        });
    });
});

<commit_msg>Added timeout into fru parser spec code<commit_after>// Copyright 2015, EMC, Inc.

/* jshint node: true */

'use strict';

describe("ipmi fru Task Parser", function () {
    var stdoutMocks;
    var taskParser;

    before('fru task parser before', function () {
        this.timeout(5000);
        stdoutMocks = require('./stdout-helper');
        // create a child injector with on-core and the base pieces we need to test this
        helper.setupInjector([
            helper.require('/spec/mocks/logger.js'),
            helper.require('/lib/utils/job-utils/command-parser.js')
        ]);

        taskParser = helper.injector.get('JobUtils.CommandParser');

    });

    it("should parse `ipmitool fru` output", function () {
        var esesCmd = 'sudo ipmitool fru';

        var tasks = [
            {
                cmd: esesCmd,
                stdout: stdoutMocks.ipmiFru,
                stderr: '',
                error: null
            }
        ];

        return taskParser.parseTasks(tasks)
        .spread(function (result) {
            expect(result.error).to.be.undefined;
            expect(result.store).to.be.true;
            expect(result.data).to.be.ok;
            //console.log(result.data);
            expect(_.size(result.data)).to.equal(3);
            expect(result.data.AST2300).to.be.an.Object;
            expect(result.data.AST2300['Chassis Serial']).to.equal('QTFCEV4120280');
            expect(result.source).to.equal('ipmi-fru');
        });
    });
});

<|endoftext|>


<commit_before>// Karma configuration
// Generated on Thu Feb 13 2014 14:54:33 GMT+0000 (GMT)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '..',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
     APPLICATION_SPEC,
     'app/assets/javascripts/mortgage_calculator/application.js',
     'app/assets/javascripts/mortgage_calculator/mortgage_calculator_app.js.erb',
     'app/assets/javascripts/mortgage_calculator/angular/**/*.js',
     'spec/javascripts/unit/**/*.js',
     { pattern: 'app/assets/javascripts/mortgage_calculator/angular/**/*.js',
        watched: true,
        included: false,
        served: false },
    { pattern: 'app/assets/javascripts/mortgage_calculator/*.js.erb',
        watched: true,
        included: false,
        served: false }
    ],

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress', 'growl'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['PhantomJS'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<commit_msg>break karma config!<commit_after>// Karma configuration
// Generated on Thu Feb 13 2014 14:54:33 GMT+0000 (GMT)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '..',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
     APPLICATION_SPEC,
     'app/assets/javascripts/mortgage_calculator/application.js',
     'app/assets/javascripts/mortgage_calculator/mortgage_calculator_app.js.erb',
     'app/assets/javascripts/mortgage_calculator/angular/**/*.js',
     'spec/javascripts/unit/**/*.js',
     { pattern: 'app/assets/javascripts/mortgage_calculator/angular/**/*.js',
        watched: true,
        included: false,
        served: false },
    { pattern: 'app/assets/javascripts/mortgage_calculator/*.js.erb',
        watched: true,
        included: false,
        served: false }
    ],

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress', 'growl'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['asd'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<|endoftext|>


<commit_before>// add check-button to form
// check whether dora-id or dora-link was given
// if yes, find record in dora
// return result

ckan.module('eaw_schema_checkpublication', function ($) {
  return {
    initialize: function() {
      var module = this;
      // add check-button
      (function(element) {
	var checkbutton = $('<button>', {type: 'button', text: 'Check',
					 id: 'pubcheckbutton',
					 class: 'btn btn-primary pull-right',
					 width: '80px'});
	element.after(checkbutton);
	checkbutton.click(module.main.bind(module));
      } )(this.el);
      this.el.after($(this.modal_html));
      $('#pubmodal_button_right').click(this.prefill.bind(this));
    },

    spinner: '',

    pubdata: {},

    prefill: function() {
      var metadata = {title: '', authors: [], doi: '',
		      year: '', abstract: '', keywords: [] };
      var mods = $(this.pubdata[0]).find('mods');
      console.log('pubdata: ');
      console.log(this.pubdata[0]);
      metadata['title'] = 'Data for: '
	+ mods.children('titleinfo').children('title').text();
      metadata.title = metadata.title.replace(/<\/?[^>]+(?:>|$)/g, "");
      var namelist = mods.find('name');
      $.each(namelist, function(idx, obj) {
	  metadata['authors'][idx] = {
	    given: $(obj).children('namepart[type="given"]').text()
	  };
	  metadata['authors'][idx]['family'] =
	    $(obj).children('namepart[type="family"]').text();
      });
      var subject = mods.find('subject').children('topic');
      $.each(subject, (idx, obj) => {
	if ($(obj).text() !== '') {
	  metadata['keywords'].push($(obj).text());
	}
      });
      metadata['doi'] = mods.find('identifier[type="doi"]').text();
      metadata['year'] = mods.find('originInfo dateIssued').text();
      metadata['abstract'] = mods.find('abstract').text();
      metadata.abstract = metadata.abstract.replace(/<\/?[^>]+(?:>|$)/g, "");
      $('#field-title').val(metadata.title);
      this.sandbox.publish('slug-target-changed', metadata.title);
      $('#field-notes').val(metadata.abstract);
      $('input#field-tag_string').val(metadata.keywords).trigger('change');
      // collect all author fieldsiterate over all author fields
      let authorfields = $('input[id^=field-author-]');
      authorfields.each(function(idx) {
	let val = metadata.authors.length > idx
	      ? metadata.authors[idx]['family']
		+ ', ' + metadata.authors[idx]['given']
	      : '';
	this.value = val;
      });
      // add new authors if necessary
      let iter = metadata.authors.slice(authorfields.length).entries();
      let appendto = authorfields.last().parents('div.control-repeating').parent();
      for (let au of iter) {
	let aunum = au[0] + 1;
	let val = au[1]['family'] + ', ' + au[1]['given'];
	let el = `

	    Author ${aunum}

              <input id="field-author-${aunum}" type="text" name="author-${aunum}" value="${val}" placeholder="" class="medinput">

`;
	appendto.append(el);
      }
    },

    normalize_doraid: function(id) {
      return(id.replace('%3A', ':'));
    },

    identpub : function(value) {
      var regdora = /.*(eawag:\d+$|.*eawag%3A\d+$)/;
      var regdoi = /.*(10.\d{4,9}\/.+$)/;
      var ids = {};
      console.log('in identpub');
      console.log('this', this);
      console.log('value:', value);
      var res = value.match(regdora);
      if (res) {
	ids['dora_id'] = this.normalize_doraid(res[1]);
      } else {
	ids['dora_id'] = null;
	res = value.match(regdoi);
	if (res) {
	  ids['doi'] = res[1];
	} else {
	  ids['doi'] = null;
	}
      }
      return(ids);
    },

    mkdoralinks: function(id) {
      return({'oai': 'https://www.dora.lib4ri.ch/eawag/oai2?'+
	      'verb=GetRecord&metadataPrefix=mods&identifier='+id,
	      'citation': 'https://www.dora.lib4ri.ch/eawag/'+
	      'islandora/object/'+id+'/islandora_scholar_citation/'+
	      '?citation_style=APA'
	     });
    },

    get_dora_id_from_doi: function(doi) {
      var module = this;
      var popelre = /Detailed\s+Record<\/a>/;
      var doradoi = doi.replace('/', '~slsh~');
      var link = 'https://www.dora.lib4ri.ch/eawag/islandora/search/'
		   + 'mods_identifier_doi_mt%3A%28' + doradoi + '%29';
      var doraid = $.ajax({
	url: link,
	dataType: 'html',
	beforeSend: function() {
	  $('#pubcheckbutton').html(module.spinner);
	},
	complete: function(data, status) {
	  $('#pubcheckbutton').html('Check');
	  return(data);
	}})
	.then(
	  data => {
	    let id = data.match(popelre);
	    id = id === null ? null : this.normalize_doraid(id[1]);
	    return(id);
	  },
	  data => {
	    console.log('request to '+link+' failed');
	    return(null);
	  });
      return(doraid);
    },

    get_crossref_info: function(doi) {
      let link = 'https://data.crossref.org/'+doi;
      let params = [
	{url: link, dataType: 'json'},
	{url: link, headers: {Accept: 'text/bibliography; style=apa'}}
      ];
      return(Promise.all([$.ajax(params[0]), $.ajax(params[1])]));
    },

    get_dora_info: function(doralinks) {
      let params = [
	{url: doralinks.oai, dataType: 'xml'},
	{url: doralinks.citation, dataType: 'json'}];
      return(Promise.all([$.ajax(params[0]), $.ajax(params[1])]));
    },

    pubmodal: function(modalinfo) {
      var maintext;
      if (modalinfo.type === 'error') {
	maintext = '
Could not retrieve record for:
'
	  + '
' + modalinfo.url + '
'
	  + '
Reason: ' + modalinfo.status + '
'
	  + '
 Just continue after checking for typos.
';
	$('#pubmodal_header').addClass('alert');
	$('#pubmodal_title').html('error');
	$('#pubmodal_main').html(maintext);
	$('#pubmodal_button_left').hide();
	$('#pubmodal_button_right').html('OK').show();
      } else {
	maintext = '
Found publication:
'
	  + '
' + modalinfo.citation + '

'
	  + '
'
	  + 'If that is not the right one, just click "Wrong" and continue.
';
	$('#pubmodal_header').addClass('alert-success');
	$('#pubmodal_title').html('success');
	$('#pubmodal_main').html(maintext);
	$('#pubmodal_button_left').html('Wrong').addClass('btn-warning').show();
	$('#pubmodal_button_right').html('OK').addClass('btn-success').show();

      }
      $('#pubmodal').modal('show');

    },

    modal_html:
`

    <button style="right:-5px;" type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>

`,
    //
    main: function () {
      // identify id-type
      // if dora, get dora-record
      // if doi, search dora-record
      // if not found, get crossref-record
      // return: attributes, citationtext, error
      var value = this.el.val();
      var doralinks;
      var dorarecord;
      var doracitation;
      var xref;
      console.log('in main');
      console.log('value:', value);
      idtyp = this.identpub.call(this, value);
      console.log('idtyp', idtyp);
      if (idtyp.dora_id !== null) {
	// get the dora record and citation
	doralinks = this.mkdoralinks(idtyp.dora_id);
	this.get_dora_info(doralinks)
	  .then(data => {  //We got OAI-record and citation
	    //check if record was found via OAI-PMH
	    let error = $(data[0]).find('error');
	    if (error.length > 0) {
	      this.pubmodal(
		{type: 'error',
		 status: error.text(),
		 url: doralinks.oai});
	    } else {     // both record found
	      this.pubdata = data;
	      this.pubmodal(
		{type: 'success',
		 citation: data[1].citation});
	    }},
	    data => {    // failed request
	      this.pubmodal(
		{type: 'error',
		 status: data.statusText + '(' + data.status + ')',
		 url: doralinks.oai});
	    });

      } else if (idtyp.doi != null) {
	// check whether that is in DORA
	this.get_dora_id_from_doi.call(this, idtyp.doi)
	  .then(
	    data => {
	      if (data === null) {
		console.log('Not in DORA');
		xref = this.get_crossref_info(idtyp.doi)
		  .then(
		    data => {
		      let rec = {record: data[0], citation: data[1]};
		      console.log('Xref record:');
		      console.log(rec);
		    },
		    data => {
		      console.log('request to https://data.crossref.org/'
				  +idtyp.doi+' failed.');
		      return(null);
		    });
	      } else {
		console.log('DORA-ID: '+data);
	      }
	    },
	    data => {
	      console.log('FAIL');
	    });
      } else {
	console.log('unrecognized identifier');
      }
    }
  };
});

 //      function report_result(metadata) {
// 	print_test(JSON.stringify(metadata));
//       }

//       function print_test(res) {
// 	$( 'div#test ').append(res);
//       }

//       function makelinks(dora_id_nr) {
// 	doraread.dora_oai_id = 'eawag:' + dora_id_nr;
// 	doraread.doralink = ('https://www.dora.lib4ri.ch/eawag/islandora/object/'
// 			     + doraread.dora_oai_id);
// 	doraread.dora_oailink = ('https://www.dora.lib4ri.ch/eawag/oai2?' +
// 				 'verb=GetRecord&metadataPrefix=mods&identifier=' +
// 				 doraread.dora_oai_id);
// 	doraread.dora_citationlink = ('https://www.dora.lib4ri.ch/eawag/islandora/object/' +
// 				      doraread.dora_oai_id + '/islandora_scholar_citation/' +
// 				      '?citation_style=APA');
//       }

//       function getcitation(metadata, citationlink) {
// 	$.ajax(citationlink, {
// 	  dataType: 'json',
// 	  success: function(data, code, jqXHR) {
// 	    metadata['citation'] = $(data['citation']).children( 'div.csl-entry' ).text();
// 	    metadata['citation'] = 'Data for: ' + metadata['citation'];
// 	    metadata['citation'] = metadata['citation'].replace(doraread.re_removedoi, '');
// 	  },
// 	  beforeSend: function() {
// 	    $( '#checkbutton' ).append('');
// 	  },
// 	  complete: function() {
// 	    $( '#spinner' ).remove();
// 	    report_result(metadata);
// 	  }
// 	});
//       }

//       function getmetadata (metadata, oailink) {
// 	$.ajax(oailink, {
// 	  dataType: 'xml',
// 	  success: function(data, code, jqXHR) {
// 	    metadata = modsextract($( data ));
// 	    if (metadata['error']) {
// 	    report_result(metadata);
// 	    } else {
// 	      getcitation(metadata, doraread.dora_citationlink);
// 	    }
// 	  },
// 	  beforeSend: function() {
// 	    $( '#checkbutton' ).append('');
// 	  },
// 	  complete: function() {
// 	    $( '#spinner' ).remove();
// 	  }
// 	});
//       }

//       function modsextract(d) {
// 	var metadata = {title: '', authors: [], doi: '', year: ''
// 			, abstract: '', citation: '', error: ''};
// 	var mods;
// 	var namelist;
// 	var error;
// 	error = d.find( 'error' );
// 	if (error.length > 0) {
// 	  return({error: error.attr('code')});
// 	}
// 	mods = d.find( 'mods' );
// 	metadata['title'] = mods.children('titleinfo').children('title').text();
// 	namelist = mods.find( 'name' );
// 	$.each(namelist, function(idx, obj) {
// 	  metadata['authors'][idx] = {
// 	    given:$(obj).children( 'namepart[type="given"]' ).text()
// 	  };
// 	  metadata['authors'][idx]['family'] =
// 	    $(obj).children( 'namepart[type="family"]' ).text();
// 	});
// 	metadata['doi'] = mods.find( 'identifier[type="doi"]' ).text();
// 	metadata['year'] = mods.find( 'originInfo dateIssued' ).text();
// 	metadata['abstract'] = mods.find( 'abstract' ).text();
// 	return(metadata);
//       }

//     }
//   };
// });

<commit_msg>doi -only: prefill authors, WIP<commit_after>// add check-button to form
// check whether dora-id or dora-link was given
// if yes, find record in dora
// return result

ckan.module('eaw_schema_checkpublication', function ($) {
  return {
    initialize: function() {
      var module = this;
      // add check-button
      (function(element) {
	var checkbutton = $('<button>', {type: 'button', text: 'Check',
					 id: 'pubcheckbutton',
					 class: 'btn btn-primary pull-right',
					 width: '80px'});
	element.after(checkbutton);
	checkbutton.click(module.main.bind(module));
      } )(this.el);
      this.el.after($(this.modal_html));
      $('#pubmodal_button_right').click(this.prefill.bind(this));
    },

    spinner: '',

    pubdata: {},

    prefill: function() {
      console.log('pubdata');
      console.log(this.pubdata);
      var metadata = {title: '', authors: [], doi: '',
		      year: '', abstract: '', keywords: [] };
      if (this.pubdata[0]['source'] === 'xref') {
	metadata = this.pubdata[0];
	metadata.title = 'Data for: ' + metadata.title;
	metadata.authors = metadata.aunames;
	metadata.abstract = '';
	metadata.keywords = [];
      } else {
	var mods = $(this.pubdata[0]).find('mods');
	metadata['title'] = 'Data for: '
	  + mods.children('titleinfo').children('title').text();
	metadata.title = metadata.title.replace(/<\/?[^>]+(?:>|$)/g, "");
	var namelist = mods.find('name');
	$.each(namelist, function(idx, obj) {
	    metadata['authors'][idx] = {
	      given: $(obj).children('namepart[type="given"]').text()
	    };
	    metadata['authors'][idx]['family'] =
	      $(obj).children('namepart[type="family"]').text();
	});
	var subject = mods.find('subject').children('topic');
	$.each(subject, (idx, obj) => {
	  if ($(obj).text() !== '') {
	    metadata['keywords'].push($(obj).text());
	  }
	});
	metadata['doi'] = mods.find('identifier[type="doi"]').text();
	metadata['year'] = mods.find('originInfo dateIssued').text();
	metadata['abstract'] = mods.find('abstract').text();
	metadata.abstract = metadata.abstract.replace(/<\/?[^>]+(?:>|$)/g, "");
      }
      $('#field-title').val(metadata.title);
      this.sandbox.publish('slug-target-changed', metadata.title);
      $('#field-notes').val(metadata.abstract);
      $('input#field-tag_string').val(metadata.keywords).trigger('change');
      // collect all author fieldsiterate over all author fields
      let authorfields = $('input[id^=field-author-]');
      authorfields.each(function(idx) {
	let val = metadata.authors.length > idx
	      ? metadata.authors[idx]['family']
		+ ', ' + metadata.authors[idx]['given']
	      : '';
	this.value = val;
      });
      // add new authors if necessary
      let iter = metadata.authors.slice(authorfields.length).entries();
      let appendto = authorfields.last().parents('div.control-repeating').parent();
      for (let au of iter) {
	let aunum = au[0] + 1;
	let val = au[1]['family'] + ', ' + au[1]['given'];
	let el = `

	    Author ${aunum}

              <input id="field-author-${aunum}" type="text" name="author-${aunum}" value="${val}" placeholder="" class="medinput">

`;
	appendto.append(el);
      }
    },

    normalize_doraid: function(id) {
      return(id.replace('%3A', ':'));
    },

    identpub : function(value) {
      var regdora = /.*(eawag:\d+$|.*eawag%3A\d+$)/;
      var regdoi = /.*(10.\d{4,9}\/.+$)/;
      var ids = {};
      console.log('in identpub');
      console.log('this', this);
      console.log('value:', value);
      var res = value.match(regdora);
      if (res) {
	ids['dora_id'] = this.normalize_doraid(res[1]);
      } else {
	ids['dora_id'] = null;
	res = value.match(regdoi);
	if (res) {
	  ids['doi'] = res[1];
	} else {
	  ids['doi'] = null;
	}
      }
      return(ids);
    },

    mkdoralinks: function(id) {
      return({'oai': 'https://www.dora.lib4ri.ch/eawag/oai2?'+
	      'verb=GetRecord&metadataPrefix=mods&identifier='+id,
	      'citation': 'https://www.dora.lib4ri.ch/eawag/'+
	      'islandora/object/'+id+'/islandora_scholar_citation/'+
	      '?citation_style=APA'
	     });
    },

    get_dora_id_from_doi: function(doi) {
      var module = this;
      var popelre = /Detailed\s+Record<\/a>/;
      var doradoi = doi.replace('/', '~slsh~');
      var link = 'https://www.dora.lib4ri.ch/eawag/islandora/search/'
		   + 'mods_identifier_doi_mt%3A%28' + doradoi + '%29';
      var doraid = $.ajax({
	url: link,
	dataType: 'html',
	beforeSend: function() {
	  $('#pubcheckbutton').html(module.spinner);
	},
	complete: function(data, status) {
	  $('#pubcheckbutton').html('Check');
	  return(data);
	}})
	.then(
	  data => {
	    let id = data.match(popelre);
	    id = id === null ? null : this.normalize_doraid(id[1]);
	    return(id);
	  },
	  data => {
	    console.log('request to '+link+' failed');
	    return(null);
	  });
      return(doraid);
    },

    get_crossref_info: function(doi) {
      let link = 'https://data.crossref.org/'+doi;
      let params = {url: link, dataType: 'json'};
      return($.ajax(params));
    },

    get_dora_info: function(doralinks) {
      let params = [
	{url: doralinks.oai, dataType: 'xml'},
	{url: doralinks.citation, dataType: 'json'}];
      return(Promise.all([$.ajax(params[0]), $.ajax(params[1])]));
    },

    pubmodal: function(modalinfo) {
      var maintext;
      if (modalinfo.type === 'error') {
	maintext = '
Could not retrieve record for:
'
	  + '
' + modalinfo.url + '
'
	  + '
Reason: ' + modalinfo.status + '
'
	  + '
 Just continue after checking for typos.
';
	$('#pubmodal_header').addClass('alert');
	$('#pubmodal_title').html('error');
	$('#pubmodal_main').html(maintext);
	$('#pubmodal_button_left').hide();
	$('#pubmodal_button_right').html('OK').show();
      } else {
	maintext = '
Found publication:
'
	  + '
' + modalinfo.citation + '

'
	  + '
'
	  + 'If that is not the right one, just click "Wrong" and continue.
';
	$('#pubmodal_header').addClass('alert-success');
	$('#pubmodal_title').html('success');
	$('#pubmodal_main').html(maintext);
	$('#pubmodal_button_left').html('Wrong').addClass('btn-warning').show();
	$('#pubmodal_button_right').html('OK').addClass('btn-success').show();

      }
      $('#pubmodal').modal('show');

    },

    modal_html:
`

    <button style="right:-5px;" type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>

`,

    xref_extract: function(data) {
      let metadata = {};
      metadata.aunames = data.author.map(el => {
	return(el.family + ', ' + el.given);});
      metadata.authors = metadata.aunames.join(', ');
      metadata.title = data.title;
      metadata.year = data.created['date-parts'][0][0];
      metadata.journal = '' + data['container-title'] + '';
      metadata.page = data.page;
      metadata.volume = data.volume;
      metadata.issue = data.issue;
      metadata.doi = `https://doi.org/${data.DOI}`;
      let citation = `${metadata.authors} (${metadata.year}). `
	    + `${metadata.title}. ${metadata.journal}, `
	    + `${metadata.volume}(${metadata.issue}), ${metadata.page}. `
	    + `${metadata.doi}`;
      metadata.source = 'xref';
      this.pubdata = [metadata, {'citation': citation}];
      return(citation);
    },

    main: function () {
      // identify id-type
      // if dora, get dora-record
      // if doi, search dora-record
      // if not found, get crossref-record
      // return: attributes, citationtext, error
      var value = this.el.val();
      var doralinks;
      console.log('in main');
      console.log('value:', value);
      idtyp = this.identpub.call(this, value);
      console.log('idtyp', idtyp);
      if (idtyp.dora_id !== null) {
	// get the dora record and citation
	doralinks = this.mkdoralinks(idtyp.dora_id);
	this.get_dora_info(doralinks)
	  .then(data => {  //We got OAI-record and citation
	    //check if record was found via OAI-PMH
	    let error = $(data[0]).find('error');
	    if (error.length > 0) {
	      this.pubmodal(
		{type: 'error',
		 status: error.text(),
		 url: doralinks.oai});
	    } else {     // both record found
	      this.pubdata = data;
	      this.pubmodal(
		{type: 'success',
		 citation: data[1].citation});
	    }},
	    data => {    // failed request
	      this.pubmodal(
		{type: 'error',
		 status: data.statusText + '(' + data.status + ')',
		 url: doralinks.oai});
	    });

      } else if (idtyp.doi != null) {
	// check whether that is in DORA
	this.get_dora_id_from_doi.call(this, idtyp.doi)
	  .then(
	    data => {
	      if (data === null) {
		console.log('Not in DORA');
		this.get_crossref_info(idtyp.doi)
		  .then(
		    data => {
		      this.pubdata = [data];
		      this.pubmodal(
			{type: 'success',
			 source: 'xref',
			 citation: this.xref_extract(data)});
		    },
		    data => {
		      this.pubmodal(
			{type: 'error',
			 status: data.responseText,
			 url: 'https://data.crossref.org/' + idtyp.doi});
		    });
	      } else {
		console.log('DORA-ID: '+data);
	      }
	    },
	    data => {
	      console.log('FAIL');
	    });
      } else {
	console.log('unrecognized identifier');
      }
    }
  };
});

 //      function report_result(metadata) {
// 	print_test(JSON.stringify(metadata));
//       }

//       function print_test(res) {
// 	$( 'div#test ').append(res);
//       }

//       function makelinks(dora_id_nr) {
// 	doraread.dora_oai_id = 'eawag:' + dora_id_nr;
// 	doraread.doralink = ('https://www.dora.lib4ri.ch/eawag/islandora/object/'
// 			     + doraread.dora_oai_id);
// 	doraread.dora_oailink = ('https://www.dora.lib4ri.ch/eawag/oai2?' +
// 				 'verb=GetRecord&metadataPrefix=mods&identifier=' +
// 				 doraread.dora_oai_id);
// 	doraread.dora_citationlink = ('https://www.dora.lib4ri.ch/eawag/islandora/object/' +
// 				      doraread.dora_oai_id + '/islandora_scholar_citation/' +
// 				      '?citation_style=APA');
//       }

//       function getcitation(metadata, citationlink) {
// 	$.ajax(citationlink, {
// 	  dataType: 'json',
// 	  success: function(data, code, jqXHR) {
// 	    metadata['citation'] = $(data['citation']).children( 'div.csl-entry' ).text();
// 	    metadata['citation'] = 'Data for: ' + metadata['citation'];
// 	    metadata['citation'] = metadata['citation'].replace(doraread.re_removedoi, '');
// 	  },
// 	  beforeSend: function() {
// 	    $( '#checkbutton' ).append('');
// 	  },
// 	  complete: function() {
// 	    $( '#spinner' ).remove();
// 	    report_result(metadata);
// 	  }
// 	});
//       }

//       function getmetadata (metadata, oailink) {
// 	$.ajax(oailink, {
// 	  dataType: 'xml',
// 	  success: function(data, code, jqXHR) {
// 	    metadata = modsextract($( data ));
// 	    if (metadata['error']) {
// 	    report_result(metadata);
// 	    } else {
// 	      getcitation(metadata, doraread.dora_citationlink);
// 	    }
// 	  },
// 	  beforeSend: function() {
// 	    $( '#checkbutton' ).append('');
// 	  },
// 	  complete: function() {
// 	    $( '#spinner' ).remove();
// 	  }
// 	});
//       }

//       function modsextract(d) {
// 	var metadata = {title: '', authors: [], doi: '', year: ''
// 			, abstract: '', citation: '', error: ''};
// 	var mods;
// 	var namelist;
// 	var error;
// 	error = d.find( 'error' );
// 	if (error.length > 0) {
// 	  return({error: error.attr('code')});
// 	}
// 	mods = d.find( 'mods' );
// 	metadata['title'] = mods.children('titleinfo').children('title').text();
// 	namelist = mods.find( 'name' );
// 	$.each(namelist, function(idx, obj) {
// 	  metadata['authors'][idx] = {
// 	    given:$(obj).children( 'namepart[type="given"]' ).text()
// 	  };
// 	  metadata['authors'][idx]['family'] =
// 	    $(obj).children( 'namepart[type="family"]' ).text();
// 	});
// 	metadata['doi'] = mods.find( 'identifier[type="doi"]' ).text();
// 	metadata['year'] = mods.find( 'originInfo dateIssued' ).text();
// 	metadata['abstract'] = mods.find( 'abstract' ).text();
// 	return(metadata);
//       }

//     }
//   };
// });

<|endoftext|>