<commit_before>
// This protractor scen file tests the tubularHttp.
describe('tbHttp', function () {

    beforeEach(function () {
         browser.get('index.html');
        element(by.id('tbLogin')).click();
    });

    it('should be authenticated', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnAuth')).click().then(function(){
            expect($('#isAuth').getText()).toBe('is Authenticated!');
        });
    });

    it('retrieve data', function () {
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnRetData')).click().then(function () {
            expect($('#lbRet').getText()).toBe('true');
        });
    });

    it('should not login bad credentials', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.');
        element(by.id('submitBtn')).click().then(function(){
            expect($('#isAuth').getText()).toBe('false');
        });
    });

    it('should expirated', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnExp')).click().then(function(){
            expect($('#expAuth').getText()).toBe('Not Authenticated');
        });
    });

    it('get method-Is not authenticated', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnExp')).click();
        element(by.id('btnGet')).click().then(function(){
            if($('#lbGet').getText()){
                expect($('#lbGet').getText()).toBe('cancel');
            }
        });
    });

    it('post method-Is not authenticated', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnExp')).click();
        element(by.id('btnPost')).click().then(function(){
            expect($('#lbPost').getText()).toBe('null');
        });
    });
});
<commit_msg>fix test<commit_after>
// This protractor scen file tests the tubularHttp.
describe('tbHttp', function () {

    beforeEach(function () {
         browser.get('index.html');
        element(by.id('tbLogin')).click();
    });

    it('should be authenticated', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnAuth')).click().then(function(){
            expect($('#isAuth').getText()).toBe('is Authenticated!');
        });
    });

    it('retrieve data', function () {
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnRetData')).click().then(function () {
            expect($('#lbRet').getText()).toBe('true');
        });
    });

    it('should not login bad credentials', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.');
        element(by.id('submitBtn')).click().then(function(){
            expect($('#isAuth').getText()).toBe('false');
        });
    });

    it('should expirated', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnExp')).click().then(function(){
            expect($('#expAuth').getText()).toBe('Not Authenticated');
        });
    });

    it('get method-Is not authenticated', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnExp')).click();
        element(by.id('btnGet')).click().then(function(){
            if($('#lbGet').getText()){
                expect($('#lbGet').getText()).toBe('');
            }
        });
    });

    it('post method-Is not authenticated', function(){
        element(by.model('username')).sendKeys('admin');
        element(by.model('password')).sendKeys('pass.word');
        element(by.id('submitBtn')).click();
        element(by.id('btnExp')).click();
        element(by.id('btnPost')).click().then(function(){
            expect($('#lbPost').getText()).toBe('null');
        });
    });
});
<|endoftext|>


<commit_before>function angleFromCoordinate(latLng1, latLng2) {
    var dLon = (latLng2.lng - latLng1.lng);

    var y = Math.sin(dLon) * Math.cos(latLng2.lat);
    var x = Math.cos(latLng1.lat) * Math.sin(latLng2.lat) - Math.sin(latLng1.lat) * Math.cos(latLng2.lat) * Math.cos(dLon);

    var brng = Math.atan2(y, x);

    brng = brng * (180 / Math.PI);
    brng = (brng + 360) % 360;
    brng = 360 - brng;
    return Math.floor(brng);
}

function MoveDegrees(degrees) {
    while (degrees < 0 || degrees >= 360) {
        if (degrees < 0)
            degrees = degrees + 360;
        if (degrees >= 360)
            degrees = degrees - 360;
    }
    return degrees;
}

/*function rotateMap() {
    if (bearingNow == bearingTarget || positionBefore == null)
        return;
    bearingNow = MoveDegrees(bearingNow);
    var dist = bearingTarget - bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        bearingNow -= 1;
        map.setBearing(bearingNow);
    } else {
        bearingNow += 1;
        map.setBearing(bearingNow);
    }
}*/

function rotateMap() {
    if (navigationSystem.bearingNow == navigationSystem.bearingTarget || navigationSystem.positionBefore == null)
        return;
    navigationSystem.bearingNow = MoveDegrees(navigationSystem.bearingNow);
    var dist = navigationSystem.bearingTarget - navigationSystem.bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        navigationSystem.bearingNow -= 1;
        map.setBearing(navigationSystem.bearingNow);
    } else {
        navigationSystem.bearingNow += 1;
        map.setBearing(navigationSystem.bearingNow);
    }
}

var NavigationSystem = function() {
    this.initAmount = 0;

    map.addControl(new label(id = "speedField", value = "Speed: 0"));
    map.addControl(new label(id = "accuracyField", value = "Accuracy: 0"));
    map.addControl(new returnButton());

    this.naviMarker = L.Marker.movingMarker([
        [0, 0],
        [0, 0]
    ], [10000], { autostart: true, icon: navigationIcon }).addTo(map);

    this.position = new L.latLng(0, 0);
    this.positionBefore;
    this.bearingNow = 0.0;
    this.bearingTarget = 0.0;

    this.watchGeoLocation = navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 100, enableHighAccuracy: true });
    var intervalRotateMap = window.setInterval(rotateMap, 30);
    var intervalPosMap = window.setInterval(this.setMapPos.bind(this), 50);

    this.loadRoute();
}

NavigationSystem.prototype = {
    initNavigation: function() {
        navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });

    },
    successInitGeoLocate: function(pos) {
        this.initAmount += 1;
        this.naviMarker.setLatLng(new L.LatLng(pos.coords.latitude, pos.coords.longitude));
        if (this.initAmount < 10) {
            navigator.geolocation.clearWatch(this.watchGeoLocation);
            this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
        }
    },
    setMapPos: function() {
        if (this.naviMarker.isRunning())
            map.panTo(this.naviMarker._latlng);
    },
    loadRoute: function() {
        var route = new Route();
        var routejson = localStorage.getItem(location.search.split('=')[1]);
        if (routejson != null) {
            route.dehydrate(routejson);
            route.loadOnMap();
        }
    },
    successGeoLocate: function(pos) {
        document.getElementById("speedField").value = "Speed: " + (pos.coords.speed).toFixed(2);
        document.getElementById("accuracyField").value = "Accuracy: " + pos.coords.accuracy;

        if ((pos.coords.latitude == this.position.lat && pos.coords.longitude == this.position.lng))
            return;

        this.positionBefore = this.position;
        this.position = new L.latLng(pos.coords.latitude, pos.coords.longitude);

        this.naviMarker.moveTo([this.position.lat, this.position.lng], 2100);
        this.naviMarker.start();

        this.bearingTarget = 180 - angleFromCoordinate(this.position, this.positionBefore);
        this.bearingTarget = MoveDegrees(this.bearingTarget);
        this.bearingNow = MoveDegrees(this.bearingNow);
    },
    errorGeoLocate: function(error) {
        alert('nope: ' + error.code + '\n' +
            'message: ' + error.message + '\n');

        cordova.plugins.settings.openSetting("settings", function(){alert("poszlo")}, function(){alert("nieposzlo")});
    }
}

var navigationSystem = new NavigationSystem();
<commit_msg>refs #5 po rollabcku do commita przed<commit_after>function angleFromCoordinate(latLng1, latLng2) {
    var dLon = (latLng2.lng - latLng1.lng);

    var y = Math.sin(dLon) * Math.cos(latLng2.lat);
    var x = Math.cos(latLng1.lat) * Math.sin(latLng2.lat) - Math.sin(latLng1.lat) * Math.cos(latLng2.lat) * Math.cos(dLon);

    var brng = Math.atan2(y, x);

    brng = brng * (180 / Math.PI);
    brng = (brng + 360) % 360;
    brng = 360 - brng;
    return Math.floor(brng);
}

function MoveDegrees(degrees) {
    while (degrees < 0 || degrees >= 360) {
        if (degrees < 0)
            degrees = degrees + 360;
        if (degrees >= 360)
            degrees = degrees - 360;
    }
    return degrees;
}

/*function rotateMap() {
    if (bearingNow == bearingTarget || positionBefore == null)
        return;
    bearingNow = MoveDegrees(bearingNow);
    var dist = bearingTarget - bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        bearingNow -= 1;
        map.setBearing(bearingNow);
    } else {
        bearingNow += 1;
        map.setBearing(bearingNow);
    }
}*/

function rotateMap() {
    if (navigationSystem.bearingNow == navigationSystem.bearingTarget || navigationSystem.positionBefore == null)
        return;
    navigationSystem.bearingNow = MoveDegrees(navigationSystem.bearingNow);
    var dist = navigationSystem.bearingTarget - navigationSystem.bearingNow;
    if (dist < 0)
        dist += 360;
    if (dist > 180) {
        navigationSystem.bearingNow -= 1;
        map.setBearing(navigationSystem.bearingNow);
    } else {
        navigationSystem.bearingNow += 1;
        map.setBearing(navigationSystem.bearingNow);
    }
}

var NavigationSystem = function() {
    this.initAmount = 0;

    map.addControl(new label(id = "speedField", value = "Speed: 0"));
    map.addControl(new label(id = "accuracyField", value = "Accuracy: 0"));
    map.addControl(new returnButton());

    this.naviMarker = L.Marker.movingMarker([
        [0, 0],
        [0, 0]
    ], [10000], { autostart: true, icon: navigationIcon }).addTo(map);

    this.position = new L.latLng(0, 0);
    this.positionBefore;
    this.bearingNow = 0.0;
    this.bearingTarget = 0.0;

    this.watchGeoLocation = navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 100, enableHighAccuracy: true });
    var intervalRotateMap = window.setInterval(rotateMap, 30);
    var intervalPosMap = window.setInterval(this.setMapPos.bind(this), 50);

    this.loadRoute();
}

NavigationSystem.prototype = {
    initNavigation: function() {
        navigator.geolocation.watchPosition(this.successInitGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });

    },
    successInitGeoLocate: function(pos) {
        this.initAmount += 1;
        this.naviMarker.setLatLng(new L.LatLng(pos.coords.latitude, pos.coords.longitude));
        if (this.initAmount < 10) {
            navigator.geolocation.clearWatch(this.watchGeoLocation);
            this.watchGeoLocation = navigator.geolocation.watchPosition(this.successGeoLocate.bind(this), this.errorGeoLocate, { timeout: 2000, enableHighAccuracy: true });
        }
    },
    setMapPos: function() {
        if (this.naviMarker.isRunning())
            map.panTo(this.naviMarker._latlng);
    },
    loadRoute: function() {
        var route = new Route();
        var routejson = localStorage.getItem(location.search.split('=')[1]);
        if (routejson != null) {
            route.dehydrate(routejson);
            route.loadOnMap();
        }
    },
    successGeoLocate: function(pos) {
        document.getElementById("speedField").value = "Speed: " + (pos.coords.speed).toFixed(2);
        document.getElementById("accuracyField").value = "Accuracy: " + pos.coords.accuracy;

        if ((pos.coords.latitude == this.position.lat && pos.coords.longitude == this.position.lng))
            return;

        this.positionBefore = this.position;
        this.position = new L.latLng(pos.coords.latitude, pos.coords.longitude);

        this.naviMarker.moveTo([this.position.lat, this.position.lng], 2100);
        this.naviMarker.start();

        this.bearingTarget = 180 - angleFromCoordinate(this.position, this.positionBefore);
        this.bearingTarget = MoveDegrees(this.bearingTarget);
        this.bearingNow = MoveDegrees(this.bearingNow);
    },
    errorGeoLocate: function(error) {
        alert('nope: ' + error.code + '\n' +
            'message: ' + error.message + '\n');

        cordova.plugins.settings.openSetting("settings", function(){alert("poszlo")}, function(){alert("nieposzlo")});
    }
}

var navigationSystem = new NavigationSystem();
<|endoftext|>


<commit_before>dojo.provide("dojox.editor.plugins.TextColor");

dojo.require("dijit._editor._Plugin");
dojo.require("dijit.TooltipDialog");
dojo.require("dijit.form.Button");
dojo.require("dojox.widget.ColorPicker");

dojo.require("dojo.i18n");
dojo.requireLocalization("dojox.editor.plugins", "TextColor");

dojo.experimental("dojox.editor.plugins.TextColor");

dojo.declare("dojox.editor.plugins._TextColorDropDown", [dijit._Widget, dijit._Templated], {
	// summary:
	//		A smple widget that uses/creates a dropdown with a dojox.widget.ColorPicker.  Also provides
	//		passthroughs to the value of the color picker and convenient hook points.
	// tags:
	//		private

	// templateString: String
	//		The template used to create the ColorPicker.
	templateString: "
" +
		"
" +
			"

" +
			"
" +
			"" +
				"<button dojoType='dijit.form.Button' dojoAttachPoint='_setButton'>${setButtonText}</button>" +
				" " +
				"<button dojoType='dijit.form.Button' dojoAttachPoint='_cancelButton'>${cancelButtonText}</button>" +
			"" +
		"
" +
		"
",

	// widgetsInTemplate: Boolean
	//		Flag denoting widgets are contained in the template.
	widgetsInTemplate: true,

	constructor: function(){
		// summary:
		//		Constructor over-ride so that the translated strings are mixsed in so
		//		the template fills out.
		var strings = dojo.i18n.getLocalization("dojox.editor.plugins", "TextColor");
		dojo.mixin(this, strings);

		// We do not want default command/onclick stuff.
		this.useDefaultCommand = false;
	},

	startup: function(){
		// summary:
		//		Over-ride of startup to do the basic connect setups and such.
		if(!this._started){
			this.inherited(arguments);
			this.connect(this._setButton, "onClick", dojo.hitch(this, function(){
				this.onChange(this.get("value"));
			}));
			this.connect(this._cancelButton, "onClick", dojo.hitch(this, function(){
				dijit.popup.close(this.dialog);
				this.onCancel();
			}));
			// Fully statred, so go ahead and remove the hide.
			dojo.style(this.domNode, "display", "block");
		}
	},

	_setValueAttr: function(value, priorityChange){
		// summary:
		//		Passthrough function for the color picker value.
		// value: String
		//		The value to set in the color picker
		// priorityChange:
		//		Value to indicate whether or not to trigger an onChange event.
		this._colorPicker.set("value", value, priorityChange);
	},

	_getValueAttr: function(){
		// summary:
		//		Passthrough function for the color picker value.
		return this._colorPicker.get("value");
	},

	onChange: function(value){
		// summary:
		//		Hook point to get the value when the color picker value is selected.
		// value: String
		//		The value from the color picker.
	},

	onCancel: function(){
		// summary:
		//		Hook point to get when the dialog is canceled.
	}
});

dojo.declare("dojox.editor.plugins.TextColor", dijit._editor._Plugin, {
	// summary:
	//		This plugin provides dropdown color pickers for setting text color and background color
	//		and makes use of the nicer-looking (though not entirely accessible), dojox.widget.ColorPicker.
	//
	// description:
	//		The commands provided by this plugin are:
	//		* foreColor - sets the text color
	//		* hiliteColor - sets the background color

	// Override _Plugin.buttonClass to use DropDownButton (with ColorPalette) to control this plugin
	buttonClass: dijit.form.DropDownButton,

	constructor: function(){
		this._picker = new dojox.editor.plugins._TextColorDropDown();
		dojo.body().appendChild(this._picker.domNode);
		this._picker.startup();
		this.dropDown = this._picker.dialog;
		this.connect(this._picker, "onChange", function(color){
			this.editor.execCommand(this.command, color);
		});
		this.connect(this._picker, "onCancel", function(){
			this.editor.focus();
		});
	},

	updateState: function(){
		// summary:
		//		Overrides _Plugin.updateState().  This updates the ColorPalette
		//		to show the color of the currently selected text.
		// tags:
		//		protected
		var _e = this.editor;
		var _c = this.command;
		if(!_e || !_e.isLoaded || !_c.length){
			return;
		}

		var value;
		if(this.button){
			try{
				value = _e.queryCommandValue(_c)|| "";
			}catch(e){
				//Firefox may throw error above if the editor is just loaded, ignore it
				value = "";
			}
		}

		if(value == ""){
			value = "#000000";
		}
		if(value == "transparent"){
			value = "#ffffff";
		}

		if(typeof value == "string"){
			//if RGB value, convert to hex value
			if(value.indexOf("rgb")> -1){
				value = dojo.colorFromRgb(value).toHex();
			}
		}else{	//it's an integer(IE returns an MS access #)
			value =((value & 0x0000ff)<< 16)|(value & 0x00ff00)|((value & 0xff0000)>>> 16);
			value = value.toString(16);
			value = "#000000".slice(0, 7 - value.length)+ value;

		}

		if(value !== this._picker.get('value')){
			this._picker.set('value', value, false);
		}
	},

	destroy: function(){
		// summary:
		//		Over-ride cleanup function.
		this.inherited(arguments);
		this._picker.destroyRecursive();
		delete this._picker;
	}
});

// Register this plugin.  Uses the same name as the dijit one, so you
// use one or the other, not both.
dojo.subscribe(dijit._scopeName + ".Editor.getPlugin", null, function(o){
	if(o.plugin){
		return;
	}
	switch(o.args.name){
		case "foreColor":
		case "hiliteColor":
			o.plugin = new dojox.editor.plugins.TextColor({
				command: o.args.name
			});
	}
});
<commit_msg>Tweak to TextColor to fast-close issue caused by changeset 21691.  Set it in the right widget, goofball. :-)  refs #11010<commit_after>dojo.provide("dojox.editor.plugins.TextColor");

dojo.require("dijit._editor._Plugin");
dojo.require("dijit.TooltipDialog");
dojo.require("dijit.form.Button");
dojo.require("dojox.widget.ColorPicker");

dojo.require("dojo.i18n");
dojo.requireLocalization("dojox.editor.plugins", "TextColor");

dojo.experimental("dojox.editor.plugins.TextColor");

dojo.declare("dojox.editor.plugins._TextColorDropDown", [dijit._Widget, dijit._Templated], {
	// summary:
	//		A smple widget that uses/creates a dropdown with a dojox.widget.ColorPicker.  Also provides
	//		passthroughs to the value of the color picker and convenient hook points.
	// tags:
	//		private

	// templateString: String
	//		The template used to create the ColorPicker.
	templateString: "
" +
		"
" +
			"

" +
			"
" +
			"" +
				"<button dojoType='dijit.form.Button' dojoAttachPoint='_setButton'>${setButtonText}</button>" +
				" " +
				"<button dojoType='dijit.form.Button' dojoAttachPoint='_cancelButton'>${cancelButtonText}</button>" +
			"" +
		"
" +
		"
",

	// widgetsInTemplate: Boolean
	//		Flag denoting widgets are contained in the template.
	widgetsInTemplate: true,

	constructor: function(){
		// summary:
		//		Constructor over-ride so that the translated strings are mixsed in so
		//		the template fills out.
		var strings = dojo.i18n.getLocalization("dojox.editor.plugins", "TextColor");
		dojo.mixin(this, strings);
	},

	startup: function(){
		// summary:
		//		Over-ride of startup to do the basic connect setups and such.
		if(!this._started){
			this.inherited(arguments);
			this.connect(this._setButton, "onClick", dojo.hitch(this, function(){
				this.onChange(this.get("value"));
			}));
			this.connect(this._cancelButton, "onClick", dojo.hitch(this, function(){
				dijit.popup.close(this.dialog);
				this.onCancel();
			}));
			// Fully statred, so go ahead and remove the hide.
			dojo.style(this.domNode, "display", "block");
		}
	},

	_setValueAttr: function(value, priorityChange){
		// summary:
		//		Passthrough function for the color picker value.
		// value: String
		//		The value to set in the color picker
		// priorityChange:
		//		Value to indicate whether or not to trigger an onChange event.
		this._colorPicker.set("value", value, priorityChange);
	},

	_getValueAttr: function(){
		// summary:
		//		Passthrough function for the color picker value.
		return this._colorPicker.get("value");
	},

	onChange: function(value){
		// summary:
		//		Hook point to get the value when the color picker value is selected.
		// value: String
		//		The value from the color picker.
	},

	onCancel: function(){
		// summary:
		//		Hook point to get when the dialog is canceled.
	}
});

dojo.declare("dojox.editor.plugins.TextColor", dijit._editor._Plugin, {
	// summary:
	//		This plugin provides dropdown color pickers for setting text color and background color
	//		and makes use of the nicer-looking (though not entirely accessible), dojox.widget.ColorPicker.
	//
	// description:
	//		The commands provided by this plugin are:
	//		* foreColor - sets the text color
	//		* hiliteColor - sets the background color

	// Override _Plugin.buttonClass to use DropDownButton (with ColorPalette) to control this plugin
	buttonClass: dijit.form.DropDownButton,

	constructor: function(){
		this._picker = new dojox.editor.plugins._TextColorDropDown();
		dojo.body().appendChild(this._picker.domNode);
		this._picker.startup();
		this.dropDown = this._picker.dialog;
		this.connect(this._picker, "onChange", function(color){
			this.editor.execCommand(this.command, color);
		});
		this.connect(this._picker, "onCancel", function(){
			this.editor.focus();
		});
		// We do not want default command/onclick stuff.
		this.useDefaultCommand = false;
	},

	updateState: function(){
		// summary:
		//		Overrides _Plugin.updateState().  This updates the ColorPalette
		//		to show the color of the currently selected text.
		// tags:
		//		protected
		var _e = this.editor;
		var _c = this.command;
		if(!_e || !_e.isLoaded || !_c.length){
			return;
		}

		var value;
		if(this.button){
			try{
				value = _e.queryCommandValue(_c)|| "";
			}catch(e){
				//Firefox may throw error above if the editor is just loaded, ignore it
				value = "";
			}
		}

		if(value == ""){
			value = "#000000";
		}
		if(value == "transparent"){
			value = "#ffffff";
		}

		if(typeof value == "string"){
			//if RGB value, convert to hex value
			if(value.indexOf("rgb")> -1){
				value = dojo.colorFromRgb(value).toHex();
			}
		}else{	//it's an integer(IE returns an MS access #)
			value =((value & 0x0000ff)<< 16)|(value & 0x00ff00)|((value & 0xff0000)>>> 16);
			value = value.toString(16);
			value = "#000000".slice(0, 7 - value.length)+ value;

		}

		if(value !== this._picker.get('value')){
			this._picker.set('value', value, false);
		}
	},

	destroy: function(){
		// summary:
		//		Over-ride cleanup function.
		this.inherited(arguments);
		this._picker.destroyRecursive();
		delete this._picker;
	}
});

// Register this plugin.  Uses the same name as the dijit one, so you
// use one or the other, not both.
dojo.subscribe(dijit._scopeName + ".Editor.getPlugin", null, function(o){
	if(o.plugin){
		return;
	}
	switch(o.args.name){
		case "foreColor":
		case "hiliteColor":
			o.plugin = new dojox.editor.plugins.TextColor({
				command: o.args.name
			});
	}
});
<|endoftext|>


<commit_before>export default class TimekeeperController {
  constructor($filter, $interval, $scope, timekeeperService, voiceService) {
    'ngInject';
    this._$filter = $filter;
    this._$interval = $interval;
    this._$scope = $scope;
    this._timekeeperService = timekeeperService;
    this._voiceService = voiceService;
  }

  start() {
    this.running = true;
    this.cleared = false;
    // _intervalFn to be implemented in child class
    this._intervalPromise = this._$interval(this._intervalFn.bind(this), 1000);
  }

  pause() {
    this.running = false;
    this._$interval.cancel(this._intervalPromise);
  }

  reset() {
    this._pause();
    this.cleared = true;
  }

  $onInit() {
    this.time = this._timekeeperService.time;
    this.running = false;
    this.cleared = true;
    this._voiceService.listen();
    this._unlistenRecognition = this._$scope.$on('recognition.incoming',
        (event, command) => {
      if (command === 'start') {
        this.start();
      }
      if (command === 'pause') {
        this.pause();
      }
    });
  }

  $onDestroy() {
    this._unlistenRecognition();
    this._voiceService.stopListening();
    this._timekeeperService.time = this.time;
    this._$interval.cancel(this._intervalPromise);
  }
}

<commit_msg>Fix reset misspelling<commit_after>export default class TimekeeperController {
  constructor($filter, $interval, $scope, timekeeperService, voiceService) {
    'ngInject';
    this._$filter = $filter;
    this._$interval = $interval;
    this._$scope = $scope;
    this._timekeeperService = timekeeperService;
    this._voiceService = voiceService;
  }

  start() {
    this.running = true;
    this.cleared = false;
    // _intervalFn to be implemented in child class
    this._intervalPromise = this._$interval(this._intervalFn.bind(this), 1000);
  }

  pause() {
    this.running = false;
    this._$interval.cancel(this._intervalPromise);
  }

  reset() {
    this.pause();
    this.cleared = true;
  }

  $onInit() {
    this.time = this._timekeeperService.time;
    this.running = false;
    this.cleared = true;
    this._voiceService.listen();
    this._unlistenRecognition = this._$scope.$on('recognition.incoming',
        (event, command) => {
      if (command === 'start') {
        this.start();
      }
      if (command === 'pause') {
        this.pause();
      }
    });
  }

  $onDestroy() {
    this._unlistenRecognition();
    this._voiceService.stopListening();
    this._timekeeperService.time = this.time;
    this._$interval.cancel(this._intervalPromise);
  }
}

<|endoftext|>


<commit_before>import { assign } from '@ember/polyfills';
import { assert } from '@ember/debug';
import { set } from '@ember/object';
import { capitalize } from '@ember/string';
import { compact } from '../utils/object-transforms';
import removeFromDOM from '../utils/remove-from-dom';
import BaseAdapter from './base';
import classic from 'ember-classic-decorator';

@classic
export default class GoogleTagManager extends BaseAdapter {
  dataLayer = 'dataLayer';

  toStringExtension() {
    return 'GoogleTagManager';
  }

  init() {
    const { id, dataLayer, envParams } = this.config;
    const envParamsString = envParams ? `&${envParams}` : '';

    assert(
      `[ember-metrics] You must pass a valid \`id\` to the ${this.toString()} adapter`,
      id
    );

    this._injectScript(id, envParamsString);

    set(this, 'dataLayer', dataLayer || 'dataLayer');

    this._injectScript();
  }

  // prettier-ignore
  _injectScript(id, envParamsString) {
    (function(w, d, s, l, i) {
      w[l] = w[l] || [];
      w[l].push({
        'gtm.start': new Date().getTime(),
        event: 'gtm.js'
      });
      var f = d.getElementsByTagName(s)[0],
          j = d.createElement(s),
          dl = l !== 'dataLayer' ? '&l=' + l : '';
      j.async = true;
      j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl + envParamsString;
      f.parentNode.insertBefore(j, f);
    })(window, document, 'script', this.dataLayer, id);
  }

  trackEvent(options = {}) {
    const compactedOptions = compact(options);
    const dataLayer = this.dataLayer;
    const gtmEvent = { event: compactedOptions['event'] };

    delete compactedOptions['event'];

    for (let key in compactedOptions) {
      const capitalizedKey = capitalize(key);
      gtmEvent[`event${capitalizedKey}`] = compactedOptions[key];
    }

    window[dataLayer].push(gtmEvent);

    return gtmEvent;
  }

  trackPage(options = {}) {
    const compactedOptions = compact(options);
    const dataLayer = this.dataLayer;
    const sendEvent = {
      event: compactedOptions['event'] || 'pageview',
    };

    const pageEvent = assign(sendEvent, compactedOptions);

    window[dataLayer].push(pageEvent);

    return pageEvent;
  }

  willDestroy() {
    removeFromDOM('script[src*="gtm.js"]');

    delete window.dataLayer;
  }
}
<commit_msg>Fix duplicate GTM script injection<commit_after>import { assign } from '@ember/polyfills';
import { assert } from '@ember/debug';
import { set } from '@ember/object';
import { capitalize } from '@ember/string';
import { compact } from '../utils/object-transforms';
import removeFromDOM from '../utils/remove-from-dom';
import BaseAdapter from './base';
import classic from 'ember-classic-decorator';

@classic
export default class GoogleTagManager extends BaseAdapter {
  dataLayer = 'dataLayer';

  toStringExtension() {
    return 'GoogleTagManager';
  }

  init() {
    const { id, dataLayer, envParams } = this.config;
    const envParamsString = envParams ? `&${envParams}` : '';

    assert(
      `[ember-metrics] You must pass a valid \`id\` to the ${this.toString()} adapter`,
      id
    );

    this._injectScript(id, envParamsString);

    set(this, 'dataLayer', dataLayer || 'dataLayer');
  }

  // prettier-ignore
  _injectScript(id, envParamsString) {
    (function(w, d, s, l, i) {
      w[l] = w[l] || [];
      w[l].push({
        'gtm.start': new Date().getTime(),
        event: 'gtm.js'
      });
      var f = d.getElementsByTagName(s)[0],
          j = d.createElement(s),
          dl = l !== 'dataLayer' ? '&l=' + l : '';
      j.async = true;
      j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl + envParamsString;
      f.parentNode.insertBefore(j, f);
    })(window, document, 'script', this.dataLayer, id);
  }

  trackEvent(options = {}) {
    const compactedOptions = compact(options);
    const dataLayer = this.dataLayer;
    const gtmEvent = { event: compactedOptions['event'] };

    delete compactedOptions['event'];

    for (let key in compactedOptions) {
      const capitalizedKey = capitalize(key);
      gtmEvent[`event${capitalizedKey}`] = compactedOptions[key];
    }

    window[dataLayer].push(gtmEvent);

    return gtmEvent;
  }

  trackPage(options = {}) {
    const compactedOptions = compact(options);
    const dataLayer = this.dataLayer;
    const sendEvent = {
      event: compactedOptions['event'] || 'pageview',
    };

    const pageEvent = assign(sendEvent, compactedOptions);

    window[dataLayer].push(pageEvent);

    return pageEvent;
  }

  willDestroy() {
    removeFromDOM('script[src*="gtm.js"]');

    delete window.dataLayer;
  }
}
<|endoftext|>


<commit_before>/*jshint expr: true*/

'use strict';

require('./index');

describe('disclosureApi', function() {
  var disclosureApi;

  beforeEach(angular.mock.module('disclosure'));

  beforeEach(angular.mock.inject(function(_disclosureApi_) {
    disclosureApi = _disclosureApi_;
  }));

  it('exists', function() {
    expect(disclosureApi).to.be.ok;
  });

  it('has contributions', function() {
    expect(disclosureApi).to.have.property('contributions');
  });

  it('has elections', function() {
    expect(disclosureApi).to.have.property('elections');
  });

  it('has locations', function() {
    expect(disclosureApi).to.have.property('locations');
  });

  it('has search', function() {
    expect(disclosureApi).to.have.property('search');
  });

  it('lists 10 contributions', function() {
    // This hits a live API, so changes outside of this project could failt his test :(
    return disclosureApi.contributions.list()
      .then(function(contributions) {
        expect(contributions).to.have.length(9);
      });
  });
});
<commit_msg>TST: fix tests to be independent of amount of data on test server.<commit_after>/*jshint expr: true*/

'use strict';

require('./index');

describe('disclosureApi', function() {
  var disclosureApi;

  beforeEach(angular.mock.module('disclosure'));

  beforeEach(angular.mock.inject(function(_disclosureApi_) {
    disclosureApi = _disclosureApi_;
  }));

  it('exists', function() {
    expect(disclosureApi).to.be.ok;
  });

  it('has contributions', function() {
    expect(disclosureApi).to.have.property('contributions');
  });

  it('has elections', function() {
    expect(disclosureApi).to.have.property('elections');
  });

  it('has locations', function() {
    expect(disclosureApi).to.have.property('locations');
  });

  it('has search', function() {
    expect(disclosureApi).to.have.property('search');
  });

  it('lists some contributions', function() {
    // This hits a live API, so changes outside of this project could fail this test :(
    return disclosureApi.contributions.list()
      .then(function(contributions) {
        expect(contributions[0]).to.have.property('amount');
      });
  });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name maureillasApp.RestService
 * @description
 * # rest
 * Factory in the pbrApp.
 */
angular.module('maureillasApp.common')
  .factory('RestService', function ($q, $http, TechnicalExceptionService, URLS) {

      var promiseStart = $q.when('start');

      var httpSuccess = function(data, status, headers, config) {
                return data;
              }

      var httpError = function(data, status, headers, config) {
        return $q.reject();
      }

      // verifie l'objet config avec url et method
      var verifyConfig = function(config) {
        var message = ', attendu : config { url, method } voir https://docs.angularjs.org/api/ng/service/$http';
        if (angular.isUndefined(config)) {
          TechnicalExceptionService.new('objet config pour un appel Rest : [undefined]' + message);
        }
        if (angular.isUndefined(config.url)) {
           TechnicalExceptionService.new('url dans config pour un appel Rest : [undefined]' + message);
        }
        if (angular.isUndefined(config.method)) {
          TechnicalExceptionService.new('method dans config pour un appel Rest : [undefined]' + message);
        }
      }

      //construit une configuration pour le service $http
      var makeConfig = function(config) {

        return {
          url : URLS.urlBackend + config.url,
          method : config.method,
          data : config.data || '',
          params : config.params || undefined
        }
      }

      return {
        call: function(config) {
          verifyConfig(config);
          var makedConfig = makeConfig(config);
          var promiseAppel = promiseStart.then(function () {
            return $http(makedConfig).
              success(httpSuccess).
              error(httpError);
          });
          return promiseAppel;
        }
    }
});
<commit_msg>register test<commit_after>'use strict';

/**
 * @ngdoc service
 * @name maureillasApp.RestService
 * @description
 * # rest
 * Factory in the pbrApp.
 */
angular.module('maureillasApp.common')
  .factory('RestService', function ($q, $http, TechnicalExceptionService, URLS) {

      var promiseStart = $q.when('start');

      var httpSuccess = function(data, status, headers, config) {
                return data;
              }

      var httpError = function(data, status, headers, config) {
        alert(status);
        return $q.reject();
      }

      // verifie l'objet config avec url et method
      var verifyConfig = function(config) {
        var message = ', attendu : config { url, method } voir https://docs.angularjs.org/api/ng/service/$http';
        if (angular.isUndefined(config)) {
          TechnicalExceptionService.new('objet config pour un appel Rest : [undefined]' + message);
        }
        if (angular.isUndefined(config.url)) {
           TechnicalExceptionService.new('url dans config pour un appel Rest : [undefined]' + message);
        }
        if (angular.isUndefined(config.method)) {
          TechnicalExceptionService.new('method dans config pour un appel Rest : [undefined]' + message);
        }
      }

      //construit une configuration pour le service $http
      var makeConfig = function(config) {

        return {
          url : URLS.urlBackend + config.url,
          method : config.method,
          data : config.data || '',
          params : config.params || undefined
        }
      }

      return {
        call: function(config) {
          verifyConfig(config);
          var makedConfig = makeConfig(config);
          alert(makedConfig.url);
          var promiseAppel = promiseStart.then(function () {
            return $http(makedConfig).
              success(httpSuccess).
              error(httpError);
          });
          return promiseAppel;
        }
    }
});
<|endoftext|>


<commit_before>var MazePainter = (function(window, MazeGenerator) {
  'use strict';

  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;

  var paintingMaze = false;
  var mazePainted = false;

  var mazePaintedCallbacks = [];

  function callMazePaintedCallbacks() {
    mazePaintedCallbacks.forEach(function(callback) {
      callback();
    });
  }

  var mazePainter = {

    init: function(canvas, cellSize, cellColor, frontierColor, wallColor, entryColor, exitColor, solutionColor, userSolutionColor) {
      this.canvas = canvas;
      this.ctx = canvas.getContext('2d');

      this.cellSize = cellSize;

      this.cellColor = cellColor;
      this.frontierColor = frontierColor;
      this.wallColor = wallColor;

      this.entryColor = entryColor;
      this.exitColor = exitColor;

      this.solutionColor = solutionColor;
      this.userSolutionColor = userSolutionColor;

      paintingMaze = false;
      mazePainted = false;

      mazePaintedCallbacks = [];

      this.clear(0, 0, canvas.width, canvas.height);
    },

    isMazePainted: function() {
      return mazePainted;
    },

    drawLine: function(xFrom, yFrom, xTo, yTo, color) {
      this.ctx.strokeStyle = color;
      this.ctx.beginPath();
      this.ctx.moveTo(xFrom, yFrom);
      this.ctx.lineTo(xTo, yTo);
      this.ctx.stroke();
    },

    drawCell: function(x, y, width, height, color) {
      this.ctx.fillStyle = color;
      this.ctx.fillRect(x, y, width, height);
    },

    startPainting: function() {
      this.paintMazeGeneration();
      this.paintEntryExit();
      this.paintSolution(MazeGenerator.solution, this.solutionColor);
      //this.paintSolution(MazeInteraction.solution, this.userSolutionColor);
      this.paintUserSolution(MazeInteraction.solution, this.userSolutionColor);

      window.requestAnimationFrame(this.startPainting.bind(this));
    },

    paintMazeGeneration: function() {

      if (MazeGenerator.exposedForPainting.length > 0) {
        paintingMaze = true;

        // Paint 4 cells each animation frame iteration to
        // increase the speed of generation
        for (var i = 0; i < 4; i++) {
          var exposed = MazeGenerator.exposedForPainting.shift();
          this.paintGeneratedCell(exposed);
        }
      }
      else {
        if (paintingMaze) {
          mazePainted = true;
          callMazePaintedCallbacks();
        }
      }
    },

    paintGeneratedCell: function(cellInfo) {
      if (cellInfo) {

        // Calculate x and y
        var xCellToPaint = this.getX(cellInfo.cellToPaint[1]);
        var yCellToPaint = this.getY(cellInfo.cellToPaint[0]);

        // Paint a cell from the maze
        this.drawCell(xCellToPaint, yCellToPaint, this.cellSize, this.cellSize, this.cellColor);

        // Paint walls surrounding this cell
        if (cellInfo.walls) {
          this.paintWalls(cellInfo.cellToPaint[0], cellInfo.cellToPaint[1], xCellToPaint, yCellToPaint, cellInfo.walls);
        }
      }
    },

    paintWalls: function(i, j, x, y, cellsNotConnected) {
      cellsNotConnected.forEach(function(cell) {

        // Up
        if (cell[0] < i) {
          this.drawLine(x, y, x + this.cellSize, y, this.wallColor);
        }

        // Down
        if (cell[0] > i) {
          this.drawLine(x, y + this.cellSize, x + this.cellSize, y + this.cellSize, this.wallColor);
        }

        // Left
        if (cell[1] < j) {
          this.drawLine(x, y, x, y + this.cellSize, this.wallColor);
        }

        // Right
        if (cell[1] > j) {
          this.drawLine(x + this.cellSize, y, x + this.cellSize, y + this.cellSize, this.wallColor);
        }

      }.bind(this));

    },

    paintEntryExit: function() {
      if (MazeGenerator.entry && MazeGenerator.exit) {
        this.drawCell(this.getX(MazeGenerator.entry[1]), this.getY(MazeGenerator.entry[0]), this.cellSize, this.cellSize, this.entryColor);
        this.drawCell(this.getX(MazeGenerator.exit[1]), this.getY(MazeGenerator.exit[0]), this.cellSize, this.cellSize, this.entryColor);
      }
    },

    paintSolution: function(solution, color) {
      if (solution.length > 0) {
        //console.log(solution);
        var cell = solution.shift();
        //console.log(cell);
        this.drawCell(this.getX(cell[1]), this.getY(cell[0]), this.cellSize, this.cellSize, color);
      }
    },

    paintUserSolution: function(solution, color) {
      if (solution.length > 0) {
        var cellInfo = solution.shift();
        var cell = cellInfo.cell;

        if (cellInfo.clear) {
          color = this.cellColor;
        }

        this.drawCell(this.getX(cell[1]), this.getY(cell[0]), this.cellSize, this.cellSize, color);
      }
    },

    clear: function(x, y, width, height) {
      this.ctx.clearRect(x, y, width, height);
    },

    getX: function(j) {
      return j * this.cellSize;
    },

    getY: function(i) {
      return i * this.cellSize;
    },

    onMazePainted: function(callback) {
      mazePaintedCallbacks.push(callback);
    }
  };

  return mazePainter;

}(window, MazeGenerator));
<commit_msg>Fix bug that created infinite mouse listeners<commit_after>var MazePainter = (function(window, MazeGenerator) {
  'use strict';

  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;

  var paintingMaze = false;
  var mazePainted = false;

  var mazePaintedCallbacks = [];

  function callMazePaintedCallbacks() {
    mazePaintedCallbacks.forEach(function(callback) {
      callback();
    });
  }

  var mazePainter = {

    init: function(canvas, cellSize, cellColor, frontierColor, wallColor, entryColor, exitColor, solutionColor, userSolutionColor) {
      this.canvas = canvas;
      this.ctx = canvas.getContext('2d');

      this.cellSize = cellSize;

      this.cellColor = cellColor;
      this.frontierColor = frontierColor;
      this.wallColor = wallColor;

      this.entryColor = entryColor;
      this.exitColor = exitColor;

      this.solutionColor = solutionColor;
      this.userSolutionColor = userSolutionColor;

      paintingMaze = false;
      mazePainted = false;

      mazePaintedCallbacks = [];

      this.clear(0, 0, canvas.width, canvas.height);
    },

    isMazePainted: function() {
      return mazePainted;
    },

    drawLine: function(xFrom, yFrom, xTo, yTo, color) {
      this.ctx.strokeStyle = color;
      this.ctx.beginPath();
      this.ctx.moveTo(xFrom, yFrom);
      this.ctx.lineTo(xTo, yTo);
      this.ctx.stroke();
    },

    drawCell: function(x, y, width, height, color) {
      this.ctx.fillStyle = color;
      this.ctx.fillRect(x, y, width, height);
    },

    startPainting: function() {
      this.paintMazeGeneration();
      this.paintEntryExit();
      this.paintSolution(MazeGenerator.solution, this.solutionColor);
      //this.paintSolution(MazeInteraction.solution, this.userSolutionColor);
      this.paintUserSolution(MazeInteraction.solution, this.userSolutionColor);

      window.requestAnimationFrame(this.startPainting.bind(this));
    },

    paintMazeGeneration: function() {

      if (mazePainted) {
        return;
      }

      if (MazeGenerator.exposedForPainting.length > 0) {
        paintingMaze = true;

        // Paint 4 cells each animation frame iteration to
        // increase the speed of generation
        for (var i = 0; i < 4; i++) {
          var exposed = MazeGenerator.exposedForPainting.shift();
          this.paintGeneratedCell(exposed);
        }
      }
      else {
        if (paintingMaze) {
          mazePainted = true;
          callMazePaintedCallbacks();
        }
      }
    },

    paintGeneratedCell: function(cellInfo) {
      if (cellInfo) {

        // Calculate x and y
        var xCellToPaint = this.getX(cellInfo.cellToPaint[1]);
        var yCellToPaint = this.getY(cellInfo.cellToPaint[0]);

        // Paint a cell from the maze
        this.drawCell(xCellToPaint, yCellToPaint, this.cellSize, this.cellSize, this.cellColor);

        // Paint walls surrounding this cell
        if (cellInfo.walls) {
          this.paintWalls(cellInfo.cellToPaint[0], cellInfo.cellToPaint[1], xCellToPaint, yCellToPaint, cellInfo.walls);
        }
      }
    },

    paintWalls: function(i, j, x, y, cellsNotConnected) {
      cellsNotConnected.forEach(function(cell) {

        // Up
        if (cell[0] < i) {
          this.drawLine(x, y, x + this.cellSize, y, this.wallColor);
        }

        // Down
        if (cell[0] > i) {
          this.drawLine(x, y + this.cellSize, x + this.cellSize, y + this.cellSize, this.wallColor);
        }

        // Left
        if (cell[1] < j) {
          this.drawLine(x, y, x, y + this.cellSize, this.wallColor);
        }

        // Right
        if (cell[1] > j) {
          this.drawLine(x + this.cellSize, y, x + this.cellSize, y + this.cellSize, this.wallColor);
        }

      }.bind(this));

    },

    paintEntryExit: function() {
      if (MazeGenerator.entry && MazeGenerator.exit) {
        this.drawCell(this.getX(MazeGenerator.entry[1]), this.getY(MazeGenerator.entry[0]), this.cellSize, this.cellSize, this.entryColor);
        this.drawCell(this.getX(MazeGenerator.exit[1]), this.getY(MazeGenerator.exit[0]), this.cellSize, this.cellSize, this.entryColor);
      }
    },

    paintSolution: function(solution, color) {
      if (solution.length > 0) {
        //console.log(solution);
        var cell = solution.shift();
        //console.log(cell);
        this.drawCell(this.getX(cell[1]), this.getY(cell[0]), this.cellSize, this.cellSize, color);
      }
    },

    paintUserSolution: function(solution, color) {
      if (solution.length > 0) {
        var cellInfo = solution.shift();
        var cell = cellInfo.cell;

        if (cellInfo.clear) {
          color = this.cellColor;
        }

        this.drawCell(this.getX(cell[1]), this.getY(cell[0]), this.cellSize, this.cellSize, color);
      }
    },

    clear: function(x, y, width, height) {
      this.ctx.clearRect(x, y, width, height);
    },

    getX: function(j) {
      return j * this.cellSize;
    },

    getY: function(i) {
      return i * this.cellSize;
    },

    onMazePainted: function(callback) {
      mazePaintedCallbacks.push(callback);
    }
  };

  return mazePainter;

}(window, MazeGenerator));
<|endoftext|>


<commit_before>var striptags = require('striptags');

module.exports.getTags = function(tags, type) {
    return tags.filter(function(t) { return t.type === type; });
};

module.exports.getTag = function(tags, type) {
    return tags.filter(function(t) { return t.type === type; })[0];
};

module.exports.reformat = function(str) {
    return striptags(str.replace('
', ' ').replace(/{\@\w+\s*([^}]+)\s*}/g, '$1'));
};
<commit_msg>Overload util/getTag<commit_after>var striptags = require('striptags');

function find (array, func) {
    if (!Array.isArray(array)) return undefined;

    var index = 0, length = array.length;
    while (index < length) {
        if (func(array[index], index, array)) return array[index];
        index++;
    }
}

module.exports.getTags = function(tags, type) {
    return tags.filter(function(t) { return t.type === type; });
};

module.exports.getTag = function getTag (tags, type) {
    if (Array.isArray(type)) return getTag(
        tags,
        find(type, function (singleType) { return getTag(tags, singleType); })
    );
    return find(tags, function(t) { return t.type === type; });
};

module.exports.reformat = function(str) {
    return striptags(str.replace('
', ' ').replace(/{\@\w+\s*([^}]+)\s*}/g, '$1'));
};
<|endoftext|>


<commit_before>import * as Reflux from 'reflux'
import * as Immutable from 'immutable'
import studentActions from 'app/flux/studentActions'
import Student from 'app/models/student'

let studentStore = Reflux.createStore({
	listenables: studentActions,

	init() {
		this.students = Immutable.Map()
		this.history = Immutable.Stack()
		this.future = Immutable.Stack()

		this._loadData()
	},

	getInitialState() {
		return this.students
	},

	undo() {
		this.future = this.future.unshift(this.history.first())
		this.students = this.history.shift()
	},

	redo() {
		if (this.future.size) {
			this.history = this.future
			this.students = this.future.shift()
		}
	},

	_loadData(opts={}) {
		console.log('studentStore._loadData, with', opts)
		let rawStudent;
		let studentId = localStorage.getItem('activeStudentId')
		let demoStudentId = '3AE9E7EE-DA8F-4014-B987-8D88814BB848'

		let localStudent = localStorage.getItem(studentId || demoStudentId) || localStorage.getItem('student-v3.0a6')

		try {
			rawStudent = JSON.parse(localStudent)
		}
		catch (e) {
			console.info('using demo student')
			rawStudent = demoStudent
			rawStudent.active = true
			rawStudent.id = null
		}

		let student = new Student(rawStudent)
		window.studentData = student

		this._preChange()
		this.students = this.students.set(student.id, student)
		this._postChange()
	},

	_preChange() {
		this.history = this.history.unshift(this.students)
	},

	_postChange() {
		console.groupCollapsed('studentStore._postChange')
		console.log('studentStore._postChange', this.students)
		this.students.forEach(student => student.save())
		console.groupEnd('studentStore._postChange')
		this.trigger(this.students)
	},

	changeName(studentId, newName) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).rename(newName))
		this._postChange()
	},

	changeActive(studentId, isActive) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).changeActive(isActive))
		this._postChange()
	},

	changeCreditsNeeded(studentId, newCreditsNeeded) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).changeCreditsNeeded(newCreditsNeeded))
		this._postChange()
	},

	changeMatriculation(studentId, newMatriculation) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).changeMatriculation(newMatriculation))
		this._postChange()
	},

	changeGraduation(studentId, newGraduation) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).changeGraduation(newGraduation))
		this._postChange()
	},

	addArea(studentId, newArea) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).addArea(newArea))
		this._postChange()
	},

	addSchedule(studentId, newSchedule) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).addSchedule(newSchedule))
		this._postChange()
	},

	removeArea(studentId, areaId) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).removeArea(areaId))
		this._postChange()
	},

	removeMultipleAreas(studentId, ids) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).removeMultipleArea(ids))
		this._postChange()
	},

	destroySchedule(studentId, scheduleId) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).destroySchedule(scheduleId))
		this._postChange()
	},

	destroyMultipleSchedules(studentId, ids) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId).destroyMultipleSchedules(ids))
		this._postChange()
	},

	renameSchedule(studentId, scheduleId, newTitle) {
		this._preChange()
		this.students = this.students.setIn([studentId, 'schedules', scheduleId], this.students.getIn([studentId, 'schedules', scheduleId]).renameSchedule(newTitle))
		this._postChange()
	},

	reorderSchedule(studentId, scheduleId, newIndex) {
		this._preChange()
		this.students = this.students.setIn([studentId, 'schedules', scheduleId], this.students.getIn([studentId, 'schedules', scheduleId]).reorderSchedule(newIndex))
		this._postChange()
	},

	moveSchedule(studentId, scheduleId, to) {
		this._preChange()
		this.students = this.students.setIn([studentId, 'schedules', scheduleId], this.students.getIn([studentId, 'schedules', scheduleId]).moveSchedule(to))
		this._postChange()
	},

	addCourse(studentId, scheduleId, clbid) {
		this._preChange()
		this.students = this.students.setIn([studentId, 'schedules', scheduleId], this.students.getIn([studentId, 'schedules', scheduleId]).addCourse(clbid))
		this._postChange()
	},

	removeCourse(studentId, scheduleId, clbid) {
		this._preChange()
		this.students = this.students.setIn([studentId, 'schedules', scheduleId], this.students.getIn([studentId, 'schedules', scheduleId]).removeCourse(clbid))
		this._postChange()
	},

	reorderCourse(studentId, scheduleId, clbid, newIndex) {
		this._preChange()
		this.students = this.students.setIn([studentId, 'schedules', scheduleId], this.students.getIn([studentId, 'schedules', scheduleId]).reorderCourse(clbid, newIndex))
		this._postChange()
	},

	reorderArea(studentId, areaId, newIndex) {
		this._preChange()
		this.students = this.students.setIn([studentId, 'studies'], this.students.getIn([studentId, 'studies']).reorderArea(newIndex))
		this._postChange()
	},
})

window.store = studentStore

export default studentStore
<commit_msg>DRY out the studentStore change methods<commit_after>import * as Reflux from 'reflux'
import * as Immutable from 'immutable'
import studentActions from 'app/flux/studentActions'
import Student from 'app/models/student'

let studentStore = Reflux.createStore({
	listenables: studentActions,

	init() {
		this.students = Immutable.Map()
		this.history = Immutable.Stack()
		this.future = Immutable.Stack()

		this._loadData()
	},

	getInitialState() {
		return this.students
	},

	undo() {
		this.future = this.future.unshift(this.history.first())
		this.students = this.history.shift()
	},

	redo() {
		if (this.future.size) {
			this.history = this.future
			this.students = this.future.shift()
		}
	},

	_loadData(opts={}) {
		console.log('studentStore._loadData, with', opts)
		let rawStudent;
		let studentId = localStorage.getItem('activeStudentId')
		let demoStudentId = '3AE9E7EE-DA8F-4014-B987-8D88814BB848'

		let localStudent = localStorage.getItem(studentId || demoStudentId) || localStorage.getItem('student-v3.0a6')

		try {
			rawStudent = JSON.parse(localStudent)
		}
		catch (e) {
			console.info('using demo student')
			rawStudent = demoStudent
			rawStudent.active = true
			rawStudent.id = null
		}

		let student = new Student(rawStudent)
		window.studentData = student

		this._preChange()
		this.students = this.students.set(student.id, student)
		this._postChange()
	},

	_preChange() {
		this.history = this.history.unshift(this.students)
	},

	_postChange() {
		console.groupCollapsed('studentStore._postChange')
		console.log('studentStore._postChange', this.students)
		this.students.forEach(student => student.save())
		console.groupEnd('studentStore._postChange')
		this.trigger(this.students)
	},

	_change(studentId, method, ...args) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId)[method](...args))
		this._postChange()
	},

	_alter(pathToData, method, ...args) {
		this._preChange()
		this.students = this.students.setIn(pathToData, this.students.getIn(pathToData)[method](...args))
		this._postChange()
	},

	changeName(studentId, ...args)               { this._change(studentId, 'rename',                   ...args) },
	changeActive(studentId, ...args)             { this._change(studentId, 'changeActive',             ...args) },
	changeCreditsNeeded(studentId, ...args)      { this._change(studentId, 'changeCreditsNeeded',      ...args) },
	changeMatriculation(studentId, ...args)      { this._change(studentId, 'changeMatriculation',      ...args) },
	changeGraduation(studentId, ...args)         { this._change(studentId, 'changeGraduation',         ...args) },
	changeSetting(studentId, key, value)         { this._change(studentId, 'changeSetting',            key, value) },
	addArea(studentId, ...args)                  { this._change(studentId, 'addArea',                  ...args) },
	addSchedule(studentId, ...args)              { this._change(studentId, 'addSchedule',              ...args) },
	addFabrication(studentId, ...args)           { this._change(studentId, 'addArea',                  ...args) },
	addOverride(studentId, ...args)              { this._change(studentId, 'addSchedule',              ...args) },
	removeArea(studentId, ...args)               { this._change(studentId, 'removeArea',               ...args) },
	removeMultipleAreas(studentId, ...args)      { this._change(studentId, 'removeMultipleArea',       ...args) },
	destroySchedule(studentId, ...args)          { this._change(studentId, 'destroySchedule',          ...args) },
	destroyMultipleSchedules(studentId, ...args) { this._change(studentId, 'destroyMultipleSchedules', ...args) },

	renameSchedule(studentId, scheduleId, ...args)  { this._alter([studentId, 'schedules', scheduleId], 'rename',        ...args) },
	reorderSchedule(studentId, scheduleId, ...args) { this._alter([studentId, 'schedules', scheduleId], 'reorder',       ...args) },
	moveSchedule(studentId, scheduleId, ...args)    { this._alter([studentId, 'schedules', scheduleId], 'move',          ...args) },
	addCourse(studentId, scheduleId, ...args)       { this._alter([studentId, 'schedules', scheduleId], 'addCourse',     ...args) },
	removeCourse(studentId, scheduleId, ...args)    { this._alter([studentId, 'schedules', scheduleId], 'removeCourse',  ...args) },
	reorderCourse(studentId, scheduleId, ...args)   { this._alter([studentId, 'schedules', scheduleId], 'reorderCourse', ...args) },
	reorderArea(studentId, areaId, ...args)         { this._alter([studentId, 'studies', areaId],       'reorder',       ...args) },
})

window.store = studentStore

export default studentStore
<|endoftext|>


<commit_before>(function (window, document) {

    'use strict';

    var $, Imager;

    window.requestAnimationFrame =
    window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };

    $ = (function (dollar) {
        if (dollar) {
            return dollar;
        }

        return function (selector) {
            return Array.prototype.slice.call(document.querySelectorAll(selector));
        };
    }(window.$));

    /*
        Construct a new Imager instance, passing an optional configuration object.

        Example usage:

            {
                // Available widths for your images
                availableWidths: [Number]

                // Selector to be used to locate your div placeholders
                selector: '',

                // Class name to give your resizable images.
                className: '',

                // Regular expression to match against your image endpoint's naming conventions
                // e.g. http://yourserver.com/image/horse/400
                regex: RegExp
            }

        @param {object} configuration settings
        @return {object} instance of Imager
     */
    window.Imager = Imager = function (opts) {
        var self = this;
            opts = opts || {};

        this.availableWidths = opts.availableWidths || [96, 130, 165, 200, 235, 270, 304, 340, 375, 410, 445, 485, 520, 555, 590, 625, 660, 695, 736];
        this.selector        = opts.selector || '.delayed-image-load';
        this.className       = '.' + (opts.className || 'image-replace').replace(/^\.+/, '.');
        this.regex           = opts.regex || /^(.+\/)\d+$/i;
        this.gif             = document.createElement('img');
        this.gif.src         = 'data:image/gif;base64,R0lGODlhEAAJAIAAAP///wAAACH5BAEAAAAALAAAAAAQAAkAAAIKhI+py+0Po5yUFQA7';
        this.gif.className   = this.className.replace(/^[#.]/, '');
        this.divs            = $(this.selector);
        this.cache           = {};
        this.changeDivsToEmptyImages();

        window.requestAnimationFrame(function(){
            self.init();
        });
    };

    Imager.prototype.init = function () {
        var self = this;

        this.initialized = true;
        this.checkImagesNeedReplacing();

        window.addEventListener('resize', function(){
            self.checkImagesNeedReplacing();
        }, false);
    };

    Imager.prototype.changeDivsToEmptyImages = function () {
        var divs = this.divs,
            i = divs.length,
            gif;

        while (i--) {
            gif = this.gif.cloneNode(false);
            gif.width = divs[i].getAttribute('data-width');
            gif.setAttribute('data-src', divs[i].getAttribute('data-src'));
            divs[i].parentNode.replaceChild(gif, divs[i]);
        }

        if (this.initialized) {
            this.checkImagesNeedReplacing();
        }
    };

    Imager.prototype.checkImagesNeedReplacing = function () {
        var self = this,
            images = $(this.className),
            i = images.length;

        if (!this.isResizing) {
            this.isResizing = true;

            while (i--) {
                this.replaceImagesBasedOnScreenDimensions(images[i]);
            }

            this.isResizing = false;
        }
    };

    Imager.prototype.replaceImagesBasedOnScreenDimensions = function (image) {
        var src = this.determineAppropriateResolution(image),
            parent = image.parentNode,
            replacedImage;

        if (this.cache[src]) {
            replacedImage = this.cache[src].cloneNode(false);
            replacedImage.width = image.getAttribute('width');
        } else {
            replacedImage = image.cloneNode(false);
            replacedImage.src = src;
            this.cache[src] = replacedImage;
        }

        parent.replaceChild(replacedImage, image);
    };

    Imager.prototype.determineAppropriateResolution = function (image) {
        var src           = image.getAttribute('data-src'),
            imagewidth    = image.clientWidth,
            selectedWidth = this.availableWidths[0],
            i             = this.availableWidths.length;

        while (i--) {
            if (imagewidth <= this.availableWidths[i]) {
                selectedWidth = this.availableWidths[i];
            }
        }

        return this.changeImageSrcToUseNewImageDimensions(src, selectedWidth);
    };

    Imager.prototype.changeImageSrcToUseNewImageDimensions = function (src, selectedWidth) {
        return src.replace(this.regex, function (match, path, file, extension) {
            file = (file) ? file : '';
            extension = (extension && extension !== match) ? extension : '';
            return path + file + selectedWidth + ((extension) ? extension : '');
        });
    };

}(window, document));<commit_msg>Clean-up code<commit_after>(function (window, document) {

    'use strict';

    var $, Imager;

    window.requestAnimationFrame =
    window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };

    $ = (function (dollar) {
        if (dollar) {
            return dollar;
        }

        return function (selector) {
            return Array.prototype.slice.call(document.querySelectorAll(selector));
        };
    }(window.$));

    /*
        Construct a new Imager instance, passing an optional configuration object.

        Example usage:

            {
                // Available widths for your images
                availableWidths: [Number]

                // Selector to be used to locate your div placeholders
                selector: '',

                // Class name to give your resizable images.
                className: '',

                // Regular expression to match against your image endpoint's naming conventions
                // e.g. http://yourserver.com/image/horse/400
                regex: RegExp
            }

        @param {object} configuration settings
        @return {object} instance of Imager
     */
    window.Imager = Imager = function (opts) {
        var self = this;
            opts = opts || {};

        this.availableWidths = opts.availableWidths || [96, 130, 165, 200, 235, 270, 304, 340, 375, 410, 445, 485, 520, 555, 590, 625, 660, 695, 736];
        this.selector        = opts.selector || '.delayed-image-load';
        this.className       = '.' + (opts.className || 'image-replace').replace(/^\.+/, '.');
        this.regex           = opts.regex || /^(.+\/)\d+$/i;
        this.gif             = document.createElement('img');
        this.gif.src         = 'data:image/gif;base64,R0lGODlhEAAJAIAAAP///wAAACH5BAEAAAAALAAAAAAQAAkAAAIKhI+py+0Po5yUFQA7';
        this.gif.className   = this.className.replace(/^[#.]/, '');
        this.divs            = $(this.selector);
        this.cache           = {};
        this.changeDivsToEmptyImages();

        window.requestAnimationFrame(function(){
            self.init();
        });
    };

    Imager.prototype.init = function () {
        var self = this;

        this.initialized = true;
        this.checkImagesNeedReplacing();

        window.addEventListener('resize', function(){
            self.checkImagesNeedReplacing();
        }, false);
    };

    Imager.prototype.changeDivsToEmptyImages = function () {
        var divs = this.divs,
            i = divs.length,
            gif;

        while (i--) {
            gif = this.gif.cloneNode(false);
            gif.width = divs[i].getAttribute('data-width');
            gif.setAttribute('data-src', divs[i].getAttribute('data-src'));
            divs[i].parentNode.replaceChild(gif, divs[i]);
        }

        if (this.initialized) {
            this.checkImagesNeedReplacing();
        }
    };

    Imager.prototype.checkImagesNeedReplacing = function () {
        var self = this,
            images = $(this.className),
            i = images.length;

        if (!this.isResizing) {
            this.isResizing = true;

            while (i--) {
                this.replaceImagesBasedOnScreenDimensions(images[i]);
            }

            this.isResizing = false;
        }
    };

    Imager.prototype.replaceImagesBasedOnScreenDimensions = function (image) {
        var src = this.determineAppropriateResolution(image),
            parent = image.parentNode,
            replacedImage;

        if (this.cache[src]) {
            replacedImage = this.cache[src].cloneNode(false);
            replacedImage.width = image.getAttribute('width');
        } else {
            replacedImage = image.cloneNode(false);
            replacedImage.src = src;
            this.cache[src] = replacedImage;
        }

        parent.replaceChild(replacedImage, image);
    };

    Imager.prototype.determineAppropriateResolution = function (image) {
        var src           = image.getAttribute('data-src'),
            imagewidth    = image.clientWidth,
            selectedWidth = this.availableWidths[0],
            i             = this.availableWidths.length;

        while (i--) {
            if (imagewidth <= this.availableWidths[i]) {
                selectedWidth = this.availableWidths[i];
            }
        }

        return this.changeImageSrcToUseNewImageDimensions(src, selectedWidth);
    };

    Imager.prototype.changeImageSrcToUseNewImageDimensions = function (src, selectedWidth) {
        return src.replace(this.regex, function (match, path, file, extension) {
            file = file || '';
            extension = extension !== match ? extension : '';
            return path + file + selectedWidth + ((extension) ? extension : '');
        });
    };

}(window, document));<|endoftext|>


<commit_before>var latlng;
var options;
var map;
var markers = [];
var circles = [];
var me;

/* スタイル配列 */
var stylesArray = [
    /* 幾何学要素 */
    {
        featureType:"all",
        elementType:"geometry",
        stylers: [
            {hue: '#ccc'},
            {visibility:"on"},
            {saturation:0},
            {lightness:50}
        ]
    },
    /* ラベル */
    {
        featureType:"all",
        elementType:"labels",
        stylers: [
            {hue: '#ccc'},
            {visibility:"on"},
            {saturation:0},
            {lightness:30}
        ]
    },
    /* 観光スポット */
    {
        featureType:"poi.attraction",
        elementType:"all",
        stylers: [
            {hue: '#ff6699'},
            {saturation:100},
            {lightness:20}
        ]
    }
];

if(navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(setLate, errorLate);
}

function setLate(position) {
  var lat = position.coords.latitude;
  var lon = position.coords.longitude;
  var myMaptypeId="skytree";

  //lat = Math.round(lat * 1000) / 1000;
  //lon = Math.round(lon * 1000) / 1000;

  latlng = new google.maps.LatLng(lat, lon);

  options = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControlOptions: {
         mapTypeIds: [google.maps.MapTypeId.ROADMAP, myMaptypeId]
      },
      mapTypeId:myMaptypeId,
      disableDefaultUI: true

  };
  map = new google.maps.Map(document.getElementById('map-canvas'), options);

  var styledMapOptions = {
      /* ボタンにマウスオーバーした時のツールチップ */
      alt: "ハイライト表示",
      /* 最大ズームレベル */
      maxZoom: 20,
      /* ボタンに表示する名前 */
      name: "スカイツリー",
  };
  var myMapType = new google.maps.StyledMapType(stylesArray, styledMapOptions);
  map.mapTypes.set(myMaptypeId, myMapType);
}

function setPositionHere()
{
  navigator.geolocation.getCurrentPosition(function(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    me = makeMarker('', {lat: lat, lng: lng}, '');
  });
}

function errorLate(position) {
  latlng = new google.maps.LatLng(35.66, 139.69);
  options = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), options);
}

function makeMarker(title, position, message) {
  return new google.maps.Marker({
    map: map,
    title: title,
    position: position,
    message: message,
  });
}

function makeMyMarker(title, position, message) {
  var image = {
    url :'/static/miuride_app/images/car_marker.png',
    scaledSize : new google.maps.Size(30, 30)
  };
  return new google.maps.Marker({
    map: map,
    title: title,
    position: position,
    message: message,
    icon:image
  });
}

function makeCircle(position) {
  circle = new google.maps.Circle({
    strokeColor: '#1e90ff',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#1e90ff',
    fillOpacity: 0.35,
    map: map,
    center: {lat: position.lat, lng: position.lng},
    radius: 200
  });
  return circle;
}

function getAndLocatePoints(category) {
  url = '';
  if (category) {
    url = "/api/v1/tourism_point/?category=" + category;
  } else {
    url = "/api/v1/tourism_point/"
  }
  $.ajax({
    url: url
  }).done(function(data) {
    removeMarkers();
    removeCircles();
    for (point in data) {
      if (data.hasOwnProperty(point)) {
        marker = makeMarker('test', {lat: parseFloat(data[point].lat), lng: parseFloat(data[point].lng)}, '');
        markers.push(marker);
        circle = makeCircle({lat: parseFloat(data[point].lat), lng: parseFloat(data[point].lng)});
        circles.push(circle);
      }
    }
  }).fail(function(data) {
    console.log('error');
    console.log(data);
  });
}

document.addEventListener('keydown', function (event) {
  console.log(me);
  if (me && me.setMap !== undefined) {
      var lat = me.position.lat;
      var lng = me.position.lng;
      if (event.key == 'a') {
        me.setMap(null);
        me = makeMyMarker('myMarker', {lat: lat(), lng: lng() - 0.0001}, '');
      } else if (event.key == 'd') {
        me.setMap(null);
        me = makeMyMarker('myMarker', {lat: lat(), lng: lng() + 0.0001}, '');
      }
      if (event.key == 'w') {
        me.setMap(null);
        me = makeMyMarker('myMarker', {lat: lat() + 0.0001, lng: lng()}, '');
      } else if (event.key == 's') {
        me.setMap(null);
        me = makeMyMarker('myMarker', {lat: lat() - 0.0001, lng: lng()}, '');
      }
  } else {
    setPositionHere()
  }
});

function removeMarkers() {
  for(var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers.length = 0;
}

function removeCircles() {
  for(var i = 0; i < circles.length; i++) {
    circles[i].setMap(null);
  }
  circles.length = 0;
}
<commit_msg>push speak<commit_after>var latlng;
var options;
var map;
var markers = [];
var circles = [];
var me;

/* スタイル配列 */
var stylesArray = [
    /* 幾何学要素 */
    {
        featureType:"all",
        elementType:"geometry",
        stylers: [
            {hue: '#ccc'},
            {visibility:"on"},
            {saturation:0},
            {lightness:50}
        ]
    },
    /* ラベル */
    {
        featureType:"all",
        elementType:"labels",
        stylers: [
            {hue: '#ccc'},
            {visibility:"on"},
            {saturation:0},
            {lightness:30}
        ]
    },
    /* 観光スポット */
    {
        featureType:"poi.attraction",
        elementType:"all",
        stylers: [
            {hue: '#ff6699'},
            {saturation:100},
            {lightness:20}
        ]
    }
];

if(navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(setLate, errorLate);
}

function setLate(position) {
  var lat = position.coords.latitude;
  var lon = position.coords.longitude;
  var myMaptypeId="skytree";

  //lat = Math.round(lat * 1000) / 1000;
  //lon = Math.round(lon * 1000) / 1000;

  latlng = new google.maps.LatLng(lat, lon);

  options = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControlOptions: {
         mapTypeIds: [google.maps.MapTypeId.ROADMAP, myMaptypeId]
      },
      mapTypeId:myMaptypeId,
      disableDefaultUI: true

  };
  map = new google.maps.Map(document.getElementById('map-canvas'), options);

  var styledMapOptions = {
      /* ボタンにマウスオーバーした時のツールチップ */
      alt: "ハイライト表示",
      /* 最大ズームレベル */
      maxZoom: 20,
      /* ボタンに表示する名前 */
      name: "スカイツリー",
  };
  var myMapType = new google.maps.StyledMapType(stylesArray, styledMapOptions);
  map.mapTypes.set(myMaptypeId, myMapType);
}

function setPositionHere()
{
  navigator.geolocation.getCurrentPosition(function(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    me = makeMarker('', {lat: lat, lng: lng}, '');
  });
}

function errorLate(position) {
  latlng = new google.maps.LatLng(35.66, 139.69);
  options = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), options);
}

function makeMarker(title, position, message) {
  return new google.maps.Marker({
    map: map,
    title: title,
    position: position,
    message: message,
  });
}

function makeMyMarker(title, position, message) {
  var image = {
    url :'/static/miuride_app/images/car_marker.png',
    scaledSize : new google.maps.Size(30, 30)
  };
  return new google.maps.Marker({
    map: map,
    title: title,
    position: position,
    message: message,
    icon:image
  });
}

function makeCircle(position) {
  circle = new google.maps.Circle({
    strokeColor: '#1e90ff',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#1e90ff',
    fillOpacity: 0.35,
    map: map,
    center: {lat: position.lat, lng: position.lng},
    radius: 200
  });
  return circle;
}

function getAndLocatePoints(category) {
  url = '';
  if (category) {
    url = "/api/v1/tourism_point/?category=" + category;
  } else {
    url = "/api/v1/tourism_point/"
  }
  $.ajax({
    url: url
  }).done(function(data) {
    removeMarkers();
    removeCircles();
    for (point in data) {
      if (data.hasOwnProperty(point)) {
        marker = makeMarker('test', {lat: parseFloat(data[point].lat), lng: parseFloat(data[point].lng)}, '');
        marker.description = data[point].description;
        console.log(marker.description);
        marker.addListener('click', function() {
          addTweet('こんばんは');
        });
        markers.push(marker);
        circle = makeCircle({lat: parseFloat(data[point].lat), lng: parseFloat(data[point].lng)});
        circles.push(circle);
      }
    }
  }).fail(function(data) {
    console.log('error');
    console.log(data);
  });
}

document.addEventListener('keydown', function (event) {
  console.log(me);
  if (me && me.setMap !== undefined) {
      var lat = me.position.lat;
      var lng = me.position.lng;
      if (event.key == 'a') {
        me.setMap(null);
        me = makeMyMarker('myMarker', {lat: lat(), lng: lng() - 0.0001}, '');
      } else if (event.key == 'd') {
        me.setMap(null);
        me = makeMyMarker('myMarker', {lat: lat(), lng: lng() + 0.0001}, '');
      }
      if (event.key == 'w') {
        me.setMap(null);
        me = makeMyMarker('myMarker', {lat: lat() + 0.0001, lng: lng()}, '');
      } else if (event.key == 's') {
        me.setMap(null);
        me = makeMyMarker('myMarker', {lat: lat() - 0.0001, lng: lng()}, '');
      }
  } else {
    setPositionHere()
  }
});

function removeMarkers() {
  for(var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers.length = 0;
}

function removeCircles() {
  for(var i = 0; i < circles.length; i++) {
    circles[i].setMap(null);
  }
  circles.length = 0;
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
    Container, Content, Form, Item, Input, Label, H2,
    Textarea, Radio, Right, Left, Text, ListItem, Button, Picker
} from 'native-base';
import { StyleSheet, AsyncStorage } from 'react-native';

export default class FloatingLabelExample extends Component {
    constructor() {
        super();
        this.state = {
            patientName: '',
            patientAge: '',
        }
        this.submit = this.submit.bind(this);
        this.inputChange = this.inputChange.bind(this);
    }

    submit() {

        let patientData = {
            patientName: this.state.patientName,
            patientAge: this.state.patientAge
        }
        console.log("this.state.patientName", this.state.patientName);
    }
    showState(state) {
        let myData;
        let saveData;
        if (state == 'add') {
            saveData = this.state;
            AsyncStorage.setItem("patientData", saveData)
            console.log("added");
        } else {
            AsyncStorage.getItem("patientData").then((data) => {
                console.log("got");
                myData = data;
                console.log("myData", myData);
            })
        }
    }
    inputChange(e) {
        this.setState({
            [e.target.name]: e.target.value
        })
    }

    render() {
        return (
            <Container style={styles.container} >
                <Content>

Add Patient

                    <Form {...this.props} >
                        <Item floatingLabel>
                            Name
                            <Input
                                {...this.props}
                                maxLength={50}
                                returnKeyType='next'
                                onChangeText={(name) => this.setState({ patientName: name })}
                            />
                        </Item>
                        <Item floatingLabel>
                            Age
                            <Input keyboardType='numeric' type='number' maxLength={2}
                                onChangeText={(age) => this.setState({ patientAge: age })}
                            />
                        </Item>
                        <ListItem >

                            Gender

                            <Text  >Male</Text>
                            <Radio style={{ marginRight: 30 }} />

                            <Text>Female</Text>

                            <Radio />
                        </ListItem>
                        <Item floatingLabel >
                            Disease
                            <Input type='text' />
                        </Item>
                        <Item floatingLabel last>
                            History
                            <Textarea />
                        </Item>
                        <Button onPress={() => this.showState('add')} full success ><Text> Submit</Text></Button>
                        <Button onPress={() => this.showState('get')} full ><Text> View</Text></Button>
                    </Form>

                </Content>
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});<commit_msg>Done local storage<commit_after>import React, { Component } from 'react';
import {
    Container, Content, Form, Item, Input, Label, H2,
    Textarea, Radio, Right, Left, Text, ListItem, Button, Picker
} from 'native-base';
import { StyleSheet, AsyncStorage } from 'react-native';

var allPatients = [];

export default class FloatingLabelExample extends Component {

    constructor() {
        super();
        this.state = {
            patientName: '',
            patientAge: '',
        }
    }

    componentDidMount() {
        this.viewPatient();
    }

    addPatient() {

        allPatients.push(this.state);
        console.log("add", allPatients)
        AsyncStorage.setItem("patientData", JSON.stringify(allPatients)).then(() => {
            console.log("Saved");
        })

    }

    viewPatient() {
        allPatients = [];
        let Mydata;
        AsyncStorage.getItem("patientData").then((data) => {
            Mydata = JSON.parse(data);
            console.log("data", Mydata);

            for (var i = 0; i < Mydata.length; i++) {
                allPatients.push(Mydata[i]);
            }

            // for(var prop in Mydata){
            //     allPatients.push((Mydata[prop]));
            // }

            console.log("allPatients", allPatients);
        })

    }

    render() {
        return (
            <Container style={styles.container} >
                <Content>

Add Patient

                    <Form {...this.props} >
                        <Item floatingLabel>
                            Name
                            <Input
                                {...this.props}
                                maxLength={50}
                                returnKeyType='next'
                                onChangeText={(name) => this.setState({ patientName: name })}
                            />
                        </Item>
                        <Item floatingLabel>
                            Age
                            <Input keyboardType='numeric' type='number' maxLength={2}
                                onChangeText={(age) => this.setState({ patientAge: age })}
                            />
                        </Item>
                        <ListItem >

                            Gender

                            <Text  >Male</Text>
                            <Radio style={{ marginRight: 30 }} />

                            <Text>Female</Text>

                            <Radio />
                        </ListItem>
                        <Item floatingLabel >
                            Disease
                            <Input type='text' />
                        </Item>
                        <Item floatingLabel last>
                            History
                            <Textarea />
                        </Item>
                        <Button onPress={() => this.addPatient()} full success ><Text> Submit</Text></Button>
                        <Button onPress={() => this.viewPatient()} full ><Text> View</Text></Button>
                    </Form>

                </Content>
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});<|endoftext|>


<commit_before>//= require leaflet/map
//= require leaflet/awesome-markers
//= require map/sidebar
//= require leaflet/easy-button
//= require map/routes
//= require map/search
//= require leaflet/indoor-map

//Buildings

//Method called when click on one building
function onEachFeature(feature,layer){
    layer.on('click', function(){
        //The key references to that building clicked
        var buildingKey = this.feature.geometry.coordinates[0].key;

        if(sidebar.isVisible()){
            sidebar.hide();
        } else {
            //selects the building clicked and shows sidebar
            var numberToBuilding = '/map/data/building/' + buildingKey;
            $("#sidebar").load(numberToBuilding, function() {
                sidebar.toggle();
            });
        }
  });
}

var buildingLayer = L.geoJSON('', {
  onEachFeature: onEachFeature
});

//adds layer of building on map
map.addLayer(buildingLayer);

//Insert each building on the layer of building
$.getJSON( "/map/data/buildings", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){

        try {
            var geo_json = JSON.parse(val.geo_data);
            geo_json.features[0].geometry.coordinates[0].key = val.id;
            buildingLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          //console.log(err);
        }
    });
});

//Bikes

//Layer with bikes icon personalized
var bikesLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/24/bike-icon.png',
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

//adds layer to bikes on map
map.addLayer(bikesLayer);

//Insert each bicycle rack on the layer of bikes
$.getJSON( "/map/data/bikes", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            bikesLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});

//Bathrooms

//Layer with bathroom icon personalized
var bathroomLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/rokey/smooth/32/toilet-paper-icon.png',
            iconSize: [24, 24],
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

//adds layer to bathroom on map
map.addLayer(bathroomLayer);

//Insert each bathroom on the layer of bathrooms
$.getJSON( "/map/data/bathrooms", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            bathroomLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});

//Snackbar

var snackbarLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/graphicloads/colorful-long-shadow/24/Restaurant-icon.png',
            iconSize: [24, 24],
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

map.addLayer(snackbarLayer);

$.getJSON( "/map/data/snackbars", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            snackbarLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});

//Bus Stops

var busstopLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/32/school-bus-icon.png',
            iconSize: [24, 24],
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

map.addLayer(busstopLayer);

$.getJSON( "/map/data/busstops", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            busstopLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});

//Entrances

var entranceLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat-one-color/24/door-icon.png',
            iconSize: [24, 24],
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

map.addLayer(entranceLayer);

$.getJSON( "/map/data/entrances", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            entranceLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});
<commit_msg>indoor map test<commit_after>//= require leaflet/map
//= require leaflet/awesome-markers
//= require map/sidebar
//= require leaflet/easy-button
//= require map/routes
//= require map/search
//= require leaflet/indoor-map

//Buildings

//Method called when click on one building
function onEachFeature(feature,layer){
    layer.on('click', function(){
        //The key references to that building clicked
        var buildingKey = this.feature.geometry.coordinates[0].key;

        if(sidebar.isVisible()){
            sidebar.hide();
        } else {
            //selects the building clicked and shows sidebar
            var numberToBuilding = '/map/data/building/' + buildingKey;
            $("#sidebar").load(numberToBuilding, function() {
                sidebar.toggle();
            });
        }
  });
}

var buildingLayer = L.geoJSON('', {
  onEachFeature: onEachFeature
});

//adds layer of building on map
map.addLayer(buildingLayer);

//Insert each building on the layer of building
$.getJSON( "/map/data/buildings", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){

        try {
            var geo_json = JSON.parse(val.geo_data);
            geo_json.features[0].geometry.coordinates[0].key = val.id;
            buildingLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          //console.log(err);
        }
    });
});

//Indoor map

// Indoor Map

var data = {
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "properties": {
            "level": [0, 1],
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-15.76165129822223, -47.86936283111573]
        }
      }
      ]
};

var indoorLayer = new L.Indoor(data);
indoorLayer.setLevel("0");

indoorLayer.addTo(map);

var levelControl = new L.Control.Level({
    level: "0",
    levels: [-1, 0, 1],
});

// Connect the level control to the indoor layer
// levelControl.addEventListener("levelchange", indoorLayer.setLevel, indoorLayer);
levelControl.addTo(map);

// END Indoor Map

//Bikes

//Layer with bikes icon personalized
var bikesLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/24/bike-icon.png',
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

//adds layer to bikes on map
map.addLayer(bikesLayer);

//Insert each bicycle rack on the layer of bikes
$.getJSON( "/map/data/bikes", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            bikesLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});

//Bathrooms

//Layer with bathroom icon personalized
var bathroomLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/rokey/smooth/32/toilet-paper-icon.png',
            iconSize: [24, 24],
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

//adds layer to bathroom on map
map.addLayer(bathroomLayer);

//Insert each bathroom on the layer of bathrooms
$.getJSON( "/map/data/bathrooms", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            bathroomLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});

//Snackbar

var snackbarLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/graphicloads/colorful-long-shadow/24/Restaurant-icon.png',
            iconSize: [24, 24],
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

map.addLayer(snackbarLayer);

$.getJSON( "/map/data/snackbars", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            snackbarLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});

//Bus Stops

var busstopLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/32/school-bus-icon.png',
            iconSize: [24, 24],
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

map.addLayer(busstopLayer);

$.getJSON( "/map/data/busstops", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            busstopLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});

//Entrances

var entranceLayer = L.geoJSON('', {
    pointToLayer: function(feature, latlng) {
        var smallIcon = new L.Icon({
            iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat-one-color/24/door-icon.png',
            iconSize: [24, 24],
        });
        return L.marker(latlng, {icon: smallIcon});
    }
});

map.addLayer(entranceLayer);

$.getJSON( "/map/data/entrances", function(data) { //getting the json data
    var items = [];
    $.each(data, function (key, val){
        try {
            var geo_json = JSON.parse(val.geo_data);
            entranceLayer.addData(geo_json); //adding the json data to the building layer
        } catch(err) {
          console.log(err);
        }
    });
});
<|endoftext|>