<commit_before>$(function () {
  var light_style = [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];

  var map;
  var infowindow;
  var loadDataLayer = function(data, z_index, click_content_fn) {
    var markers = [];
    var clickable = false;
    if (click_content_fn !== null) {
      clickable = true;
    }

    var showInfoWindow = function() {
      var content = click_content_fn(this.data);
      infowindow.close();
      infowindow.setContent(content);
      infowindow.open(map, this);
    };

    for (var i in data) {
      var rec = data[i];
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(rec.latitude, rec.longitude),
        zIndex: z_index,
        clickable: clickable
      });

      marker.data = rec;

      if (clickable) {
        marker.addListener('click', showInfoWindow);
      }

      markers.push(marker);
    }

    var len = markers.length;
    var setMap = function(m, filterFn) {
      for (var i = 0; i < len; i++) {
        if (filterFn) {
          if (filterFn(markers[i].data)) {
            markers[i].setMap(m);
          } else {
            markers[i].setMap(null);
          }
        } else {
          markers[i].setMap(m);
        }
      }
    };

    return {
      show: function() {
        setMap(map);
      },
      hide: function() {
        setMap(null);
      },
      filter: function(fn) {
        setMap(map, fn);
      }
    };
  };

  var initMap = function() {
    var mapCanvas = document.getElementById('map');
    var mapOptions = {
      center: new google.maps.LatLng(35.16899709632771, -89.85338676720858),
      zoom: 6,
      panControl: false,
      streetViewControl: false,
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        position: google.maps.ControlPosition.RIGHT_TOP,
        mapTypeIds: [
          google.maps.MapTypeId.ROADMAP,
          google.maps.MapTypeId.HYBRID,
          'style_light'
        ]
      }
    };
    map = new google.maps.Map(mapCanvas, mapOptions);
    var style = new google.maps.StyledMapType(light_style, {name:"Light"});
    map.mapTypes.set('style_light', style);
    map.setMapTypeId('style_light');

    var input = /** @type {!HTMLInputElement} */(document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.bindTo('bounds', map);

    var marker = new google.maps.Marker({map: map});
    infowindow = new google.maps.InfoWindow();
    var geocoder = new google.maps.Geocoder();
    autocomplete.addListener('place_changed', function() {
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        geocoder.geocode({
          address: input.value
        }, function(result) {
          if (result.length > 0) {
            search_result(result[0]);
          } else {
            alert("No results found.");
          }
        });
      } else {
        search_result(place);
      }
    });

    var search_result = function(result) {
      if (result.geometry.viewport) {
        map.fitBounds(result.geometry.viewport);
      } else {
        map.setCenter(result.geometry.location);
        map.setZoom(17);
      }
      marker.setPosition(result.geometry.location);
      marker.setVisible(true);
    };

    var slackHandle = function(user) {
      if(user.slack_handle) {
        return user.slack_handle;
      }

      return "??";
    };

    var memtech = loadDataLayer(locations, 999, function(data) {
      return "" + data.name + "
" +
             "" + data.origin + "
" +
             "" + slackHandle(data) + " on MTF Slack
";
    });
    memtech.show();

    /* uncomment if you want to show heatmap
    var heatmap_data = jQuery.map(locations, function(record) {
      return new google.maps.LatLng(record.latitude, record.longitude);
    });
    var heatmap = new google.maps.visualization.HeatmapLayer({
      data: heatmap_data
    });
    heatmap.setMap(map);
    */

  };
  google.maps.event.addDomListener(window, 'load', initMap);
});
<commit_msg>Add data.company<commit_after>$(function () {
  var light_style = [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];

  var map;
  var infowindow;
  var loadDataLayer = function(data, z_index, click_content_fn) {
    var markers = [];
    var clickable = false;
    if (click_content_fn !== null) {
      clickable = true;
    }

    var showInfoWindow = function() {
      var content = click_content_fn(this.data);
      infowindow.close();
      infowindow.setContent(content);
      infowindow.open(map, this);
    };

    for (var i in data) {
      var rec = data[i];
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(rec.latitude, rec.longitude),
        zIndex: z_index,
        clickable: clickable
      });

      marker.data = rec;

      if (clickable) {
        marker.addListener('click', showInfoWindow);
      }

      markers.push(marker);
    }

    var len = markers.length;
    var setMap = function(m, filterFn) {
      for (var i = 0; i < len; i++) {
        if (filterFn) {
          if (filterFn(markers[i].data)) {
            markers[i].setMap(m);
          } else {
            markers[i].setMap(null);
          }
        } else {
          markers[i].setMap(m);
        }
      }
    };

    return {
      show: function() {
        setMap(map);
      },
      hide: function() {
        setMap(null);
      },
      filter: function(fn) {
        setMap(map, fn);
      }
    };
  };

  var initMap = function() {
    var mapCanvas = document.getElementById('map');
    var mapOptions = {
      center: new google.maps.LatLng(35.16899709632771, -89.85338676720858),
      zoom: 6,
      panControl: false,
      streetViewControl: false,
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        position: google.maps.ControlPosition.RIGHT_TOP,
        mapTypeIds: [
          google.maps.MapTypeId.ROADMAP,
          google.maps.MapTypeId.HYBRID,
          'style_light'
        ]
      }
    };
    map = new google.maps.Map(mapCanvas, mapOptions);
    var style = new google.maps.StyledMapType(light_style, {name:"Light"});
    map.mapTypes.set('style_light', style);
    map.setMapTypeId('style_light');

    var input = /** @type {!HTMLInputElement} */(document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.bindTo('bounds', map);

    var marker = new google.maps.Marker({map: map});
    infowindow = new google.maps.InfoWindow();
    var geocoder = new google.maps.Geocoder();
    autocomplete.addListener('place_changed', function() {
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        geocoder.geocode({
          address: input.value
        }, function(result) {
          if (result.length > 0) {
            search_result(result[0]);
          } else {
            alert("No results found.");
          }
        });
      } else {
        search_result(place);
      }
    });

    var search_result = function(result) {
      if (result.geometry.viewport) {
        map.fitBounds(result.geometry.viewport);
      } else {
        map.setCenter(result.geometry.location);
        map.setZoom(17);
      }
      marker.setPosition(result.geometry.location);
      marker.setVisible(true);
    };

    var slackHandle = function(user) {
      if(user.slack_handle) {
        return user.slack_handle;
      }

      return "??";
    };

    var memtech = loadDataLayer(locations, 999, function(data) {
      return "" + data.name + "
" +
             "" + data.origin + "
" +
             "" + data.company + "
" +
             "" + slackHandle(data) + " on MTF Slack
";
    });
    memtech.show();

    /* uncomment if you want to show heatmap
    var heatmap_data = jQuery.map(locations, function(record) {
      return new google.maps.LatLng(record.latitude, record.longitude);
    });
    var heatmap = new google.maps.visualization.HeatmapLayer({
      data: heatmap_data
    });
    heatmap.setMap(map);
    */

  };
  google.maps.event.addDomListener(window, 'load', initMap);
});
<|endoftext|>


<commit_before>$(function() {
	var filename = "fix_me.html";

	function init() {
		tinyMCE.activeEditor.execCommand('mceFullScreen');
		var saved = localStorage.getItem("file_" + filename);
		if(saved !== null) {
			tinyMCE.activeEditor.setContent(saved);
		}
	}

	function save(editor) {
		if (Modernizr.localstorage) {
			localStorage.setItem("file_" + filename, editor.save());
		} else {
			alert("Local storage is required to save.");
		}
	}

	// tinyMCE configuration
	tinymce.init({
		selector: "textarea",
		plugins: [
			"advlist autolink lists link image charmap print preview anchor",
			"searchreplace visualblocks code fullscreen save",
			"insertdatetime media table contextmenu paste wordcount"
		],
		toolbar: "save | insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
		setup: function(editor) {
			editor.on('init', function() {
				setTimeout(init, 0);
			});
		},
		save_enablewhendirty: true,
		save_onsavecallback: save
	});
});
<commit_msg>Implemented achievements in console.log<commit_after>$(function() {
	var filename = "fix_me.html";

	var achievements = {
		3 : {text:'You wrote something!'},
		100 : {text:'Flash Fiction'},
		1000 : {text:'Short Story'},
		7500 : {text:'Novelette'},
		20000 : {text:'Novella'},
		50000 : {text:'Novel'},
		110000 : {text:'Epic'}
	};

	function achieve(threshold) {
		var achievement = achievements[threshold];
		console.log("Achievement: " + achievement.text);
		achievement.got = true;
	}

	function hasAchievement(threshold) { return achievements[threshold].got; }

	var wordCount = 2;

	function init() {
		tinyMCE.activeEditor.execCommand('mceFullScreen');
		var saved = localStorage.getItem("file_" + filename);
		if(saved !== null) {
			tinyMCE.activeEditor.setContent(saved);
		}
	}

	function keyup() {
		var before = wordCount;
		wordCount = tinyMCE.activeEditor.plugins.wordcount.getCount();
		Object.keys(achievements).forEach(function(threshold) {
			if(wordCount >= threshold &&
			   before < threshold &&
			   !hasAchievement(threshold)) {
				achieve(threshold);
			}
		});
	}

	function save(editor) {
		if (Modernizr.localstorage) {
			localStorage.setItem("file_" + filename, editor.save());
		} else {
			alert("Local storage is required to save.");
		}
	}

	// tinyMCE configuration
	tinymce.init({
		selector: "textarea",
		plugins: [
			"advlist autolink lists link image charmap print preview anchor",
			"searchreplace visualblocks code fullscreen save",
			"insertdatetime media table contextmenu paste wordcount"
		],
		toolbar: "save | insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
		setup: function(editor) {
			editor.on('init', function() {
				setTimeout(init, 0);
			});
			editor.on('keyup', keyup);
		},
		save_enablewhendirty: true,
		save_onsavecallback: save
	});
});
<|endoftext|>


<commit_before>"use strict"

var LeafletMap = function(mapId, opt){

    if (!mapId && !$("#"+mapId)){ return }
    this.mapId = mapId;

    if (!opt) {
        console.log("There is no options in LeafletMap, check this.");
        return;
     }

    this.mapData = { // dict with main states of map
        "center": {
            "lat": undefined,
            "lng": undefined
        },
        "zoom": undefined,
     };

    this.mapTylesLayer; // copy of LeafletTiles class
    this.marksLayer;

    this._validateLatLng = function(latlng){

        latlng = latlng ? latlng : opt.global.mapDefaultCenterLatLng;

        try {
            latlng = L.latLng(latlng);
        }
        catch(e) {
            latlng = L.latLng(opt.global.mapDefaultCenterLatLng);
        }

        return latlng;
     }

    this._validateZoom = function(zoom){

        if (!this.mapTylesLayer){ return opt.global.mapDefaultZoom }

        zoom = zoom ? zoom : opt.global.mapDefaultZoom;

        var minZoom = this.mapTylesLayer.minZoom;
        var maxZoom = this.mapTylesLayer.maxZoom;

        zoom = zoom>=minZoom && zoom<=maxZoom ? zoom : opt.global.mapDefaultZoom;

        return zoom;

     }

    this.createMap = function(){
        this.map = L.map(this.mapId);
     }

    this.setMapCenter = function(latlng){
        latlng = this._validateLatLng(latlng);
        this.map.panTo(latlng);

        this.mapData.center = {
            "lat": latlng.lat,
            "lng": latlng.lng,
        }
     }

    this.setMapZoom = function(zoom){
        zoom = this._validateZoom(zoom);
        this.map.setZoom(zoom);

        this.mapData.zoom = zoom;
     }

    this.setMapTilesLayer = function(layerObj){

        if (this.mapTylesLayer && this.map.hasLayer(this.mapTylesLayer)){
            this.map.removeLayer(this.mapTylesLayer)
        }

        this.mapTylesLayer = layerObj.layer;
        this.map.addLayer(this.mapTylesLayer);
     }

    this.refreshMapAfterResize = function(){
        this.map.invalidateSize();
     }

 }

var LeafletTiles = function(opt){

    parent = this;

    this.layer;

    this.server;
    this.tilesURL;
    this.maxZoom;
    this.minZoom;

    if (!opt) {
        console.log("There is no options in LeafletTiles, check this.");
        return;
    }

    // TODO: сделать проверку что это строка и ссылка
    this._validateTilesURL = function(url){
        if (url) {
            return url;
        }
        else {
            return "http://{s}.tiles.mapbox.com/v3/examples.map-y7l23tes/{z}/{x}/{y}.png";
        }
     }

    this._validateServer = function(server){
        return server && server in ["img", "wms"] ? server : "img";
     }

    this._validateMinZoom = function(minZoom){
        minZoom = parseInt(minZoom, 10);
        minZoom = minZoom<=18 && minZoom>0 ? minZoom : minZoom>18 ? 18 : 1; // If return 0 exept 1 all crashed
        return minZoom;
     }

    this._validateMaxZoom = function(maxZoom){
        maxZoom = parseInt(maxZoom, 10);
        maxZoom = maxZoom<=18 && maxZoom>0 ? maxZoom : 18;
        return maxZoom;
     }

    this._validateZoomBounds = function(){
        if (!this.maxZoom || !this.minZoom) { return }

        if (this.maxZoom < this.minZoom) {
            this.maxZoom = this.minZoom;
        }
     }

    this.setLayerOptions = function(mapName){

        var data = opt.maps[mapName];

        if (!data) { return }

        this.server = this._validateServer(data.server);
        this.tilesURL = this._validateTilesURL(data.tilesURL);
        this.maxZoom = this._validateMaxZoom(data.maxZoom);
        this.minZoom = this._validateMinZoom(data.minZoom);

        this._validateZoomBounds();
     }

    this.setLayer = function(url, minZoom, maxZoom){

        // WMS server always set using the setLayerOptions
        this.server = this.server ? this.server : this._validateServer();
        this.tilesURL = url ? this._validateTilesURL(url): this.tilesURL;
        this.maxZoom = maxZoom ? his._validateMinZoom(maxZoom): this.maxZoom;
        this.minZoom = minZoom ? this._validateMaxZoom(minZoom): this.minZoom;

        this._validateZoomBounds();

        if (this.server && this.server === "wms"){
            // TODO: server wms type
        }
        else {
            this.layer = L.tileLayer(this.tilesURL, {
                maxZoom: this.maxZoom,
                minZoom: this.minZoom,
            });
        }
     }

 }

var Options = function(){

    this.global = {
        "mapDefaultCenterLatLng": [54.31727, 48.3946],
        "mapDefaultZoom": 12,
     };

    this.maps = {
        "cloudmate": {
            tags: ["0. Современные онлайн карты"],
            src: "Internet",
            server: "img",
            title: 'Cloudmate',
            tilesURL: 'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png',
            maxZoom: 18,
            minZoom: 0,
            startZoom: 13,
        },
     };

}

var opt = new Options();

var layer = new LeafletTiles(opt);
layer.setLayerOptions("cloudmate");
layer.setLayer();

var map = new LeafletMap("map1", opt);
map.createMap();
map.setMapCenter();
map.setMapZoom();
map.setMapTilesLayer(layer);

console.log(opt)
console.log(layer)
console.log(map)
<commit_msg>Add: [LeafletMap] Setup map controls<commit_after>"use strict"

var LeafletMap = function(mapId, opt){

    if (!mapId && !$("#"+mapId)){ return }
    this.mapId = mapId;

    if (!opt) {
        console.log("There is no options in LeafletMap, check this.");
        return;
     }

    this.mapData = { // dict with main states of map
        "center": {
            "lat": undefined,
            "lng": undefined
        },
        "zoom": undefined,
        "title": undefined,
     };

    this.mapTilesLayer; // copy of LeafletTiles class
    this.marksLayer;

    this.map;

    this.setMapControls = function(){

        if (!this.map) { return }

        if (opt.global.viewControlsZoom){
            this.map.addControl(L.control.zoom(opt.global.viewControlsZoomPosition));
         }

        if (opt.global.viewControlsScale){
            var scaleControll = L.control.scale({
                position: opt.global.viewControlsScalePosition,
                imperial: opt.global.viewControlsScaleMiles,
            })
            this.map.addControl(scaleControll);
         }

        if (opt.global.viewControlsInfoCopyright){
            var infoControll = L.control.attribution({
                position: opt.global.viewControlsInfoCopyrightPosition,
                prefix: opt.global.viewControlsInfoCopyrightText,
            })
            this.map.addControl(infoControll);
         }

        if (opt.global.viewControlsInfoName){
            var infoControll = L.control.attribution({
                position: opt.global.viewControlsInfoNamePosition,
                prefix: this.mapData.title,
            })
            this.map.addControl(infoControll);
         }

        if (opt.global.viewControlsInfoZoom){
            var infoControll = L.control.attribution({
                position: opt.global.viewControlsInfoZoomPosition,
                prefix: this.mapData.zoom,
            })
            this.map.addControl(infoControll);
         }

     }

    this._validateLatLng = function(latlng){

        latlng = latlng ? latlng : opt.global.mapDefaultCenterLatLng;

        try {
            latlng = L.latLng(latlng);
        }
        catch(e) {
            latlng = L.latLng(opt.global.mapDefaultCenterLatLng);
        }

        return latlng;
     }

    this._validateZoom = function(zoom){

        if (!this.mapTilesLayer){ return opt.global.mapDefaultZoom }

        zoom = zoom ? zoom : opt.global.mapDefaultZoom;

        var minZoom = this.mapTilesLayer.minZoom;
        var maxZoom = this.mapTilesLayer.maxZoom;

        zoom = zoom>=minZoom && zoom<=maxZoom ? zoom : opt.global.mapDefaultZoom;

        return zoom;

     }

    this.createMap = function(){
        this.map = L.map(this.mapId, {
            zoomControl: false,
            attributionControl: false,
        });
     }

    this.setMapCenter = function(latlng){
        latlng = this._validateLatLng(latlng);
        this.map.panTo(latlng);

        this.mapData.center = {
            "lat": latlng.lat,
            "lng": latlng.lng,
        }
     }

    this.setMapZoom = function(zoom){
        zoom = this._validateZoom(zoom);
        this.map.setZoom(zoom);

        this.mapData.zoom = zoom;
     }

    this.setMapTilesLayer = function(layerObj){

        if (this.mapTilesLayer && this.map.hasLayer(this.mapTilesLayer)){
            this.map.removeLayer(this.mapTilesLayer)
        }

        this.mapTilesLayer = layerObj;
        this.map.addLayer(this.mapTilesLayer.layer);

        this.mapData.title = this.mapTilesLayer.title;

     }

    this.refreshMapAfterResize = function(){
        this.map.invalidateSize();
     }

 }

var LeafletTiles = function(opt){

    parent = this;

    this.layer;

    this.server;
    this.tilesURL;
    this.maxZoom;
    this.minZoom;
    this.title;

    if (!opt) {
        console.log("There is no options in LeafletTiles, check this.");
        return;
     }

    // TODO: сделать проверку что это строка и ссылка
    this._validateTilesURL = function(url){
        if (url) {
            return url;
        }
        else {
            return "http://{s}.tiles.mapbox.com/v3/examples.map-y7l23tes/{z}/{x}/{y}.png";
        }
     }

    this._validateServer = function(server){
        return server && server in ["img", "wms"] ? server : "img";
     }

    this._validateMinZoom = function(minZoom){
        minZoom = parseInt(minZoom, 10);
        minZoom = minZoom<=18 && minZoom>0 ? minZoom : minZoom>18 ? 18 : 1; // If return 0 exept 1 all crashed
        return minZoom;
     }

    this._validateMaxZoom = function(maxZoom){
        maxZoom = parseInt(maxZoom, 10);
        maxZoom = maxZoom<=18 && maxZoom>0 ? maxZoom : 18;
        return maxZoom;
     }

    this._validateZoomBounds = function(){
        if (!this.maxZoom || !this.minZoom) { return }

        if (this.maxZoom < this.minZoom) {
            this.maxZoom = this.minZoom;
        }
     }

    this.setLayerOptions = function(mapName){

        var data = opt.maps[mapName];

        if (!data) { return }

        this.server = this._validateServer(data.server);
        this.tilesURL = this._validateTilesURL(data.tilesURL);
        this.maxZoom = this._validateMaxZoom(data.maxZoom);
        this.minZoom = this._validateMinZoom(data.minZoom);
        this.title = data.title ? data.title : "Unknown Map";

        this._validateZoomBounds();
     }

    this.setLayer = function(url, minZoom, maxZoom){

        // WMS server always set using the setLayerOptions
        this.server = this.server ? this.server : this._validateServer();
        this.tilesURL = url ? this._validateTilesURL(url): this.tilesURL;
        this.maxZoom = maxZoom ? his._validateMinZoom(maxZoom): this.maxZoom;
        this.minZoom = minZoom ? this._validateMaxZoom(minZoom): this.minZoom;
        this.title = this.title ? this.title : "Unknown Map";

        this._validateZoomBounds();

        if (this.server && this.server === "wms"){
            // TODO: server wms type
        }
        else {
            this.layer = L.tileLayer(this.tilesURL, {
                maxZoom: this.maxZoom,
                minZoom: this.minZoom,
            });
        }
     }

 }

var Options = function(){

    // TODO: нужна проверка наличия всех нужных глобальных переменных, если нет то принудительно обновлять
    // TODO: сделать проверку соответствия viewControlsZoomPosition и подобных определенным значениям

    this.global = {
        "mapDefaultCenterLatLng": [54.31727, 48.3946],
        "mapDefaultZoom": 12,

        "viewControlsZoom": true,
        "viewControlsZoomPosition": "topleft",
        "viewControlsScale": true,
        "viewControlsScalePosition": "bottomleft",
        "viewControlsScaleMiles": false,
        "viewControlsInfoName": true,
        "viewControlsInfoNamePosition": "bottomright",
        "viewControlsInfoZoom": true,
        "viewControlsInfoZoomPosition": "bottomright",
        "viewControlsInfoCopyright": true,
        "viewControlsInfoCopyrightPosition": "bottomright",
        "viewControlsInfoCopyrightText": "Copyleft by Starik",
     };

    this.maps = {
        "cloudmate": {
            tags: ["0. Современные онлайн карты"],
            src: "Internet",
            server: "img",
            title: 'Cloudmate',
            tilesURL: 'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png',
            maxZoom: 18,
            minZoom: 0,
            startZoom: 13,
        },
     };

 }

var opt = new Options();

var layer = new LeafletTiles(opt);
layer.setLayerOptions("cloudmate");
layer.setLayer();

var map = new LeafletMap("map1", opt);
map.createMap();
map.setMapCenter();
map.setMapZoom();
map.setMapTilesLayer(layer);
map.setMapControls();

console.log(opt)
console.log(layer)
console.log(map)
<|endoftext|>


<commit_before>var game = new Phaser.Game(1200, 600, Phaser.AUTO, 'game', { preload: preload, create: create, update: update, render: render });
var player;
var cursors;
var trees;
var seeds = [];
var vineballs = [];
var anchor;

var vineballCount = 6;

var tileSize = 32;
var stepSize = tileSize / 4;

var seaTiles = 10;

var terrainIterations = 6;
var islandTiles;

var islandWidth;
var seaWidth = seaTiles * tileSize;

var seaLevel = game.height - (game.height / 4);

var worldHeight = 1200;

var lines = [];

var gravity = 300;

var horizontalDrag = 500;

var terrainFrames = {
	slope1: [3, 7, 19, 23],
	slope2: [2, 6, 18, 22],
	slope3: [1, 5, 17, 21],
	slope4: [0, 4, 16, 20],
	full: [8, 12, 24, 28],
};

var terrainVariations = 4;

var treeVariations = 2;

var maxPlayerDistance = 0;
// 1 in n chance for a bush
var bushInvChance = 24;
var bushVariations = 24;

// the height is how tall we treat it as in-game, NOT how tall the sprite is
var treeHeight = 530;
// width is the same as sprite width, though
var treeWidth = 72;

var music;
var seedSound;

var treeGroup;
var islandGroup;
var islandNoPhysGroup;
var bushGroup;
var vineballGroup;
var playerGroup;

function preload() {
	game.load.image('seed', 'assets/seed.png');
	game.load.image('vineball', 'assets/vineball.png');
	game.load.spritesheet('player', 'assets/player.png', 64, 64);
	game.load.spritesheet('tree1', 'assets/tree.png', treeWidth, 544);
	game.load.spritesheet('tree2', 'assets/tree2.png', treeWidth, 544);
	game.load.spritesheet('bush', 'assets/bush.png', 32, 32);
	game.load.spritesheet('terrain', 'assets/terrain.png', tileSize, tileSize);

	// invisible sprite just so we can get collision working
	game.load.image('collider', 'assets/physics_collider.png');

	game.load.audio('seed', ['assets/audio/seed.mp3', 'assets/audio/seed.ogg']);
	game.load.audio('bgm', ['assets/audio/bgm.mp3', 'assets/audio/bgm.ogg']);
}

function create() {
	trees = [];

	game.world.setBounds(-seaWidth, game.height - worldHeight, islandWidth + 2 * seaWidth, worldHeight);
	game.physics.startSystem(Phaser.Physics.ARCADE);

	game.stage.backgroundColor = 'rgb(0,0,255)';

	treeGroup = game.add.group();

	islandGroup = game.add.group();
	islandGroup.enableBody = true;

	islandNoPhysGroup = game.add.group();
	bushGroup = game.add.group();

	vineballGroup = game.add.group();

	playerGroup = game.add.group();

	makeTerrain();

	player = playerGroup.create(0, 0, 'player');
	player.anchor.setTo(0.5, 0.5);
	player.scale.x = -1;
	player.animations.add('spin', [0,1,2,3,4,5,6,7], 10, true);

	for (var i = 0; i < vineballCount; ++i) {
		var vb = vineballGroup.create(0,0,'vineball');
		vb.anchor.setTo(0.5, 0.5);
		vb.visible = false;
		vineballs.push(vb);
	}

	game.physics.arcade.enable(player);
	player.body.gravity.y = gravity;
	player.body.collideWorldBounds = true;

	cursors = game.input.keyboard.createCursorKeys();

	game.input.mouse.mouseDownCallback = function(e) {
		if (e.button === Phaser.Mouse.RIGHT_BUTTON) {
			throwSeed();
		} else {
			console.log(game.input.mouse.button);
		}
	}
	document.getElementById('game').addEventListener('contextmenu', function(e) {
		e.preventDefault();
	});

	game.camera.follow(player);

	music = game.add.audio('bgm');
	music.loop = true;
	music.play();

	seedSound = game.add.audio('seed');
}

function makeTree(x, y) {
	var variation = Math.floor(Math.random() * treeVariations) + 1;
	var tree = treeGroup.create(x, y, 'tree' + variation);
	tree.animations.add('grow', [0, 1, 2, 3, 4, 5, 6], 4, false);
	tree.animations.play('grow');
	var center = tree.x + tree.width / 2;
	tree.trunk = new Phaser.Line(center, tree.y, center, game.height);
	trees.push(tree);

}

function throwSeed() {
	if (!seedSound.isPlaying) {
		seedSound.play();
	}

	var throwStrength = 500;

	// seeds are drawn at the player's z-depth
	var seed = playerGroup.create(player.body.x, player.body.y, 'seed');
	game.physics.arcade.enable(seed);
	seed.body.gravity.y = gravity;

	seed.body.velocity = new Phaser.Point(game.input.activePointer.worldX, game.input.activePointer.worldY).subtract(player.body.position.x, player.body.position.y)
		.setMagnitude(throwStrength).add(player.body.velocity.x, player.body.velocity.y);
	seeds.push(seed);
}

function update() {
	// iterate backwards because we'll be removing elements
	for (var i = seeds.length - 1; i >= 0; --i) {
		if (game.physics.arcade.overlap(seeds[i], islandGroup)) {
			var seed = seeds[i];
			makeTree(seed.body.position.x - treeWidth / 2, heightAt(seed.body.position.x) - treeHeight);
			seed.destroy();
			seeds.splice(i, 1);
		}
	}

	// we need to collide first, and THEN give the velocity a kick away from the collision site
	if (game.physics.arcade.collide(player, islandGroup)) {
		player.body.drag.x = horizontalDrag;
		if (!anchor) {
			player.animations.stop();
		}
	} else {
		player.body.drag.x = 0;
	}

	if (game.input.activePointer.leftButton.isDown) {
		// check whether we've already got an anchor point
		if (anchor) {
			grapple();
		} else {
			var ray = new Phaser.Line(player.body.position.x, player.body.position.y, game.input.activePointer.worldX, game.input.activePointer.worldY);
			trees.forEach(function(tree) {
				var p = ray.intersects(tree.trunk, true); //returns intercept point
				if (p && (!anchor || p.distance(getMouseWorldPos()) < anchor.distance(getMouseWorldPos()))) {
					anchor = p;
				}
			});
			if (anchor) {
				grapple();
				player.animations.play('spin');
				vineballs.forEach(function(vb) {
					vb.visible = true;
				});
			}
		}
	} else {
		anchor = null;
		vineballs.forEach(function(vb) {
			vb.visible = false;
		});
	}

	if (player.x > maxPlayerDistance) {
		for (var x = maxPlayerDistance; x < player.x; ++x) {
			if (Math.random() * bushInvChance < 1) {
				spawnBush(x);
			}
		}
		maxPlayerDistance = player.x;
	}

	if (player.body.velocity.x < -1) {
		player.scale.x = 1;
	} else if (player.body.velocity.x > 1) {
		player.scale.x = -1;
	}
}

function spawnBush(x) {
	var height = heightAt(x);
	if (height === undefined) {
		return;
	}
	var bush = bushGroup.create(x, height + 10, 'bush');
	var variation = Math.floor(Math.random() * bushVariations);
	bush.frame = variation;

	var rotation = Math.floor(Math.random() * 4) * 90;
	bush.anchor.setTo(0.5, 0.5);
	bush.angle = rotation;

	var size = 2;
	bush.scale.x = size;
	bush.scale.y = size;
}

function grapple() {
	var lineStrength = 0.1;
	var airResistance = 0.005;

	// why does Phaser use negative width for flipped sprites? NO idea.
	var playerWidth = Math.abs(player.width);
	var offset = anchor.clone().subtract(player.body.position.x + playerWidth / 2, player.body.position.y + player.height / 2);
	var diff = offset.clone();
	offset.multiply(lineStrength, lineStrength);
	player.body.velocity.add(offset.x, offset.y);
	player.body.velocity.multiply(1 - airResistance, 1 - airResistance);

	var multPerBall = 1 / vineballs.length;
	vineballs.forEach(function(vb, i) {
		vb.position = diff.clone().multiply((i + 1) * multPerBall, (i + 1) * multPerBall).add(player.body.position.x + playerWidth / 2, player.body.position.y + player.height / 2);
	});
}

function render() {
	lines.forEach(function(l) {
		game.debug.geom(l);
	});

	trees.forEach(function(t) {
		//game.debug.geom(t.trunk);
	});
}
<commit_msg>Tweak seed throw force based on player motion<commit_after>var game = new Phaser.Game(1200, 600, Phaser.AUTO, 'game', { preload: preload, create: create, update: update, render: render });
var player;
var cursors;
var trees;
var seeds = [];
var vineballs = [];
var anchor;

var vineballCount = 6;

var tileSize = 32;
var stepSize = tileSize / 4;

var seaTiles = 10;

var terrainIterations = 6;
var islandTiles;

var islandWidth;
var seaWidth = seaTiles * tileSize;

var seaLevel = game.height - (game.height / 4);

var worldHeight = 1200;

var lines = [];

var gravity = 300;

var horizontalDrag = 500;

var terrainFrames = {
	slope1: [3, 7, 19, 23],
	slope2: [2, 6, 18, 22],
	slope3: [1, 5, 17, 21],
	slope4: [0, 4, 16, 20],
	full: [8, 12, 24, 28],
};

var terrainVariations = 4;

var treeVariations = 2;

var maxPlayerDistance = 0;
// 1 in n chance for a bush
var bushInvChance = 24;
var bushVariations = 24;

// the height is how tall we treat it as in-game, NOT how tall the sprite is
var treeHeight = 530;
// width is the same as sprite width, though
var treeWidth = 72;

var music;
var seedSound;

var treeGroup;
var islandGroup;
var islandNoPhysGroup;
var bushGroup;
var vineballGroup;
var playerGroup;

function preload() {
	game.load.image('seed', 'assets/seed.png');
	game.load.image('vineball', 'assets/vineball.png');
	game.load.spritesheet('player', 'assets/player.png', 64, 64);
	game.load.spritesheet('tree1', 'assets/tree.png', treeWidth, 544);
	game.load.spritesheet('tree2', 'assets/tree2.png', treeWidth, 544);
	game.load.spritesheet('bush', 'assets/bush.png', 32, 32);
	game.load.spritesheet('terrain', 'assets/terrain.png', tileSize, tileSize);

	// invisible sprite just so we can get collision working
	game.load.image('collider', 'assets/physics_collider.png');

	game.load.audio('seed', ['assets/audio/seed.mp3', 'assets/audio/seed.ogg']);
	game.load.audio('bgm', ['assets/audio/bgm.mp3', 'assets/audio/bgm.ogg']);
}

function create() {
	trees = [];

	game.world.setBounds(-seaWidth, game.height - worldHeight, islandWidth + 2 * seaWidth, worldHeight);
	game.physics.startSystem(Phaser.Physics.ARCADE);

	game.stage.backgroundColor = 'rgb(0,0,255)';

	treeGroup = game.add.group();

	islandGroup = game.add.group();
	islandGroup.enableBody = true;

	islandNoPhysGroup = game.add.group();
	bushGroup = game.add.group();

	vineballGroup = game.add.group();

	playerGroup = game.add.group();

	makeTerrain();

	player = playerGroup.create(0, 0, 'player');
	player.anchor.setTo(0.5, 0.5);
	player.scale.x = -1;
	player.animations.add('spin', [0,1,2,3,4,5,6,7], 10, true);

	for (var i = 0; i < vineballCount; ++i) {
		var vb = vineballGroup.create(0,0,'vineball');
		vb.anchor.setTo(0.5, 0.5);
		vb.visible = false;
		vineballs.push(vb);
	}

	game.physics.arcade.enable(player);
	player.body.gravity.y = gravity;
	player.body.collideWorldBounds = true;

	cursors = game.input.keyboard.createCursorKeys();

	game.input.mouse.mouseDownCallback = function(e) {
		if (e.button === Phaser.Mouse.RIGHT_BUTTON) {
			throwSeed();
		} else {
			console.log(game.input.mouse.button);
		}
	}
	document.getElementById('game').addEventListener('contextmenu', function(e) {
		e.preventDefault();
	});

	game.camera.follow(player);

	music = game.add.audio('bgm');
	music.loop = true;
	music.play();

	seedSound = game.add.audio('seed');
}

function makeTree(x, y) {
	var variation = Math.floor(Math.random() * treeVariations) + 1;
	var tree = treeGroup.create(x, y, 'tree' + variation);
	tree.animations.add('grow', [0, 1, 2, 3, 4, 5, 6], 4, false);
	tree.animations.play('grow');
	var center = tree.x + tree.width / 2;
	tree.trunk = new Phaser.Line(center, tree.y, center, game.height);
	trees.push(tree);

}

function throwSeed() {
	if (!seedSound.isPlaying) {
		seedSound.play();
	}

	var throwStrength;
	// apply only the barest throw strength if the player is not grounde
	// apply no throw strength if the player is grappling, a small amount if moving (horiz) but not grappling, and a full amount if horizontally stationary
	if (anchor) {
		throwStrength = 0;
	} else if (player.body.velocity.x != 0) {
		throwStrength = 200;
	} else {
		throwStrength = 500;
	}

	// seeds are drawn at the player's z-depth
	var seed = playerGroup.create(player.body.x, player.body.y, 'seed');
	game.physics.arcade.enable(seed);
	seed.body.gravity.y = gravity;

	seed.body.velocity = new Phaser.Point(game.input.activePointer.worldX, game.input.activePointer.worldY).subtract(player.body.position.x, player.body.position.y)
		.setMagnitude(throwStrength).add(player.body.velocity.x, player.body.velocity.y);
	seeds.push(seed);
}

function update() {
	// iterate backwards because we'll be removing elements
	for (var i = seeds.length - 1; i >= 0; --i) {
		if (game.physics.arcade.overlap(seeds[i], islandGroup)) {
			var seed = seeds[i];
			makeTree(seed.body.position.x - treeWidth / 2, heightAt(seed.body.position.x) - treeHeight);
			seed.destroy();
			seeds.splice(i, 1);
		}
	}

	// we need to collide first, and THEN give the velocity a kick away from the collision site
	if (game.physics.arcade.collide(player, islandGroup)) {
		player.body.drag.x = horizontalDrag;
		if (!anchor) {
			player.animations.stop();
		}
	} else {
		player.body.drag.x = 0;
	}

	if (game.input.activePointer.leftButton.isDown) {
		// check whether we've already got an anchor point
		if (anchor) {
			grapple();
		} else {
			var ray = new Phaser.Line(player.body.position.x, player.body.position.y, game.input.activePointer.worldX, game.input.activePointer.worldY);
			trees.forEach(function(tree) {
				var p = ray.intersects(tree.trunk, true); //returns intercept point
				if (p && (!anchor || p.distance(getMouseWorldPos()) < anchor.distance(getMouseWorldPos()))) {
					anchor = p;
				}
			});
			if (anchor) {
				grapple();
				player.animations.play('spin');
				vineballs.forEach(function(vb) {
					vb.visible = true;
				});
			}
		}
	} else {
		anchor = null;
		vineballs.forEach(function(vb) {
			vb.visible = false;
		});
	}

	if (player.x > maxPlayerDistance) {
		for (var x = maxPlayerDistance; x < player.x; ++x) {
			if (Math.random() * bushInvChance < 1) {
				spawnBush(x);
			}
		}
		maxPlayerDistance = player.x;
	}

	if (player.body.velocity.x < -1) {
		player.scale.x = 1;
	} else if (player.body.velocity.x > 1) {
		player.scale.x = -1;
	}
}

function spawnBush(x) {
	var height = heightAt(x);
	if (height === undefined) {
		return;
	}
	var bush = bushGroup.create(x, height + 10, 'bush');
	var variation = Math.floor(Math.random() * bushVariations);
	bush.frame = variation;

	var rotation = Math.floor(Math.random() * 4) * 90;
	bush.anchor.setTo(0.5, 0.5);
	bush.angle = rotation;

	var size = 2;
	bush.scale.x = size;
	bush.scale.y = size;
}

function grapple() {
	var lineStrength = 0.1;
	var airResistance = 0.005;

	// why does Phaser use negative width for flipped sprites? NO idea.
	var playerWidth = Math.abs(player.width);
	var offset = anchor.clone().subtract(player.body.position.x + playerWidth / 2, player.body.position.y + player.height / 2);
	var diff = offset.clone();
	offset.multiply(lineStrength, lineStrength);
	player.body.velocity.add(offset.x, offset.y);
	player.body.velocity.multiply(1 - airResistance, 1 - airResistance);

	var multPerBall = 1 / vineballs.length;
	vineballs.forEach(function(vb, i) {
		vb.position = diff.clone().multiply((i + 1) * multPerBall, (i + 1) * multPerBall).add(player.body.position.x + playerWidth / 2, player.body.position.y + player.height / 2);
	});
}

function render() {
	lines.forEach(function(l) {
		game.debug.geom(l);
	});

	trees.forEach(function(t) {
		//game.debug.geom(t.trunk);
	});
}
<|endoftext|>


<commit_before><commit_msg>added helper methods to structure to get backbone data<commit_after><|endoftext|>


<commit_before>Parse.initialize("7YyZO6oZNVongKR6pluyULEkMEmvLVRtVZvd6OXn", "JTOrsTnWqTBhxqxFMEvPdOUzDd9Ro01JqpiAF003");
window.fbAsyncInit = function() {
      Parse.FacebookUtils.init({ // this line replaces FB.init({
            appId      : '971388552927772', // Facebook App ID
            status     : true,  // check Facebook Login status
            cookie     : true,  // enable cookies to allow Parse to access the session
            xfbml      : true,  // initialize Facebook social plugins on the page
            version    : 'v2.3' // point to the latest Facebook Graph API version
      });

  // Run code after the Facebook SDK is loaded
};

function checkLoginState() {
      if (typeof FB !== 'undefined') {
            Parse.FacebookUtils.logIn(null, {
                  success: function(user) {
                        if (!user.existed()) {
                              //alert("User signed up and logged in through Facebook!");
                              getUserName();
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        } else {
                              //alert("User logged in through Facebook!");
                              getUserName();
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        }
                  },
                  error: function(user, error) {
                        alert("Please login to access the Locaholic services!!");
                  }
            });
      }
      else{
            alert("Your network does not support FaceBook Login!!")
      }
}
function getUserName() {
    FB.api('/me', function(response) {
      document.getElementById('usrname').innerHTML = response.name;
    });
  }
function lgOut(){
      alert("sss");
      Parse.User.logOut().then(
            function() {
                alert('success');
            },
            function(error) {
                alert('error : ' + error);
            }
      );
}

(function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<commit_msg>Update main.js<commit_after>Parse.initialize("7YyZO6oZNVongKR6pluyULEkMEmvLVRtVZvd6OXn", "JTOrsTnWqTBhxqxFMEvPdOUzDd9Ro01JqpiAF003");
window.fbAsyncInit = function() {
      Parse.FacebookUtils.init({ // this line replaces FB.init({
            appId      : '971388552927772', // Facebook App ID
            status     : true,  // check Facebook Login status
            cookie     : true,  // enable cookies to allow Parse to access the session
            xfbml      : true,  // initialize Facebook social plugins on the page
            version    : 'v2.5' // point to the latest Facebook Graph API version
      });

  // Run code after the Facebook SDK is loaded
};

function checkLoginState() {
      if (typeof FB !== 'undefined') {
            Parse.FacebookUtils.logIn(null, {
                  success: function(user) {
                        if (!user.existed()) {
                              //alert("User signed up and logged in through Facebook!");
                              getUserName();
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        } else {
                              //alert("User logged in through Facebook!");
                              getUserName();
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        }
                  },
                  error: function(user, error) {
                        alert("Please login to access the Locaholic services!!");
                  }
            });
      }
      else{
            alert("Your network does not support FaceBook Login!!")
      }
}
function getUserName() {
    FB.api('/me', function(response) {
      document.getElementById('usrname').innerHTML = response.name;
    });
  }
function lgOut(){
      alert("sss");
      Parse.User.logOut().then(
            function() {
                alert('success');
            },
            function(error) {
                alert('error : ' + error);
            }
      );
}

(function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<|endoftext|>


<commit_before>// OpenWrap v2
// Author: Nuno Aguiar
// Metrics

OpenWrap.metrics = function() {
	return ow.metrics;
};

OpenWrap.metrics.prototype.__m = {
    mem: () => {
        var res = {
            max: Number(java.lang.Runtime.getRuntime().maxMemory()),
            total: Number(java.lang.Runtime.getRuntime().totalMemory()),
            free: Number(java.lang.Runtime.getRuntime().freeMemory())
        };
        res.used = res.total - res.free;
        return res;
    },
    cpu: () => ({
        load1 : java.lang.System.getProperty("os.name").indexOf("Windows") < 0 ? getCPULoad() : "n/a",
        load2 : java.lang.System.getProperty("os.name").indexOf("Windows") < 0 ? getCPULoad(true) : "n/a",
        cores : getNumberOfCores(),
        _cores: __cpucores
    }),
    oaf: () => {
        var res = {
            libs : __loadedLibs,
            nlibs: Object.keys(__loadedLibs).length,
            nscopes: af.getScopeIds().length,
            preCompileLevel: __preCompileLevel,
            version: getVersion(),
            path   : getOpenAFPath(),
            java   : String(java.lang.System.getProperty("java.version")),
            javapath: String(java.lang.System.getProperty("java.home")),
            init   : __oafInit,
            now    : now(),
            logErr : __clogErr.get(),
            logWarn: __clogWarn.get(),
            cpuCores: __cpucores,
            threadPoolFactor: __threadPoolFactor,
            mainThreadPool: {
                parallelism: __getThreadPool().getParallelism(),
                size: __getThreadPool().getPoolSize(),
                active: __getThreadPool().getActiveThreadCount(),
                running: __getThreadPool().getRunningThreadCount(),
                steals: __getThreadPool().getStealCount(),
                tasks: __getThreadPool().getQueuedTaskCount(),
                queued: __getThreadPool().getQueuedSubmissionCount()
            },
            bottlenecks: (isDef(global.__bottleneck) ? Object.keys(global.__bottleneck).map(r => ({
                name    : r,
                running : global.__bottleneck[r].atomic.get(),
                maxWait : global.__bottleneck[r].attw,
                maxExecs: global.__bottleneck[r].ance
            })) : "n/a"),
            cache: (isDef(global.__cache) ? Object.keys(global.__cache).map(r => ({
                name: r,
                chName: global.__cache[r].name,
                ttl : global.__cache[r].ttl,
                maxSize: global.__cache[r].msize,
                size: global.__cache[r].size(),
                hits: ow.ch.__types.cache.__cacheStats[global.__cache[r].name].hits,
                miss: ow.ch.__types.cache.__cacheStats[global.__cache[r].name].miss,
                avgExecTime: ow.ch.__types.cache.__cacheStats[global.__cache[r].name].avg,
            })) : "n/a"),
            rest: (isDef(global.__openaf_rest) ? Object.keys(global.__openaf_rest.urls).map(r => ({
                url: r,
                hits: _$(global.__openaf_rest.urls[r].c).default(0),
                miss: _$(global.__openaf_rest.urls[r].f).default(0)
            })) : "n/a"),
            fns    : ow.metrics.__fnMetrics
        };
        if (isDef(res.fns)) {
            Object.keys(res.fns).map(r => {
                res.fns[r].avg = res.fns[r].sum / (res.fns[r].err + res.fns[r].end);
            });
        }
        return res;
    },
    ojob: () => {
        var res = {};
        if (isDef(ow.oJob)) {
            res = ow.oJob.getLogCh().getAll().map(j => ({
                name : j.name,
                start: j.count,
                //err  : $path(j.log, "[?not_null(error)] | length(@)"),
                //end  : $path(j.log, "[?!not_null(error)] | length(@)"),
                error: j.error,
                sum  : j.totalTime,
                avg  : j.avgTime
            }) );
        }
        return res;
    },
    os: () => ({
        pid    : getPid(),
        name   : String(java.lang.System.getProperty("os.name")),
        host   : String(java.net.InetAddress.getLocalHost().getHostName()),
        ip     : String(java.net.InetAddress.getLocalHost().getHostAddress())
    }),
    threads: () => {
        var res = {
            list  : af.fromJavaArray(java.lang.Thread.getAllStackTraces().keySet().toArray()).map(t => ({
                id      : t.getId(),
                name    : String(t.getName()),
                isAlive : t.isAlive(),
                priority: Number(t.getPriority()),
                state   : String(t.getState())
            })),
            active: Number(java.lang.Thread.activeCount()),
            total : Number(java.lang.Thread.getAllStackTraces().size())
        };
        res.states = {};
        res.list.map(r => {
            if (isUnDef(res.states[r.state]))
                res.states[r.state] = 1;
            else
                res.states[r.state] += 1;
        });
        return res;
    }
};

/**
 * <odoc>
 * <key>ow.metrics.add(aName, aFunction)</key>
 * Adds aName metric whose values are a map returned by aFunction.
 * </odoc>
 */
OpenWrap.metrics.prototype.add = function(aName, aFn) {
    if (isUnDef(ow.metrics.__m[aName])) {
        ow.metrics.__m[aName] = aFn;
    }
};

/**
 * <odoc>
 * <key>ow.metrics.getSome(anArrayOfNames) : Map</key>
 * Returns just the metrics in the provided anArrayOfNames.
 * </odoc>
 */
OpenWrap.metrics.prototype.getSome = function(aArray) {
    var r = {}, errors = [];
    aArray.map(f => {
        try {
            r[f] = ow.metrics.__m[f]();
        } catch(e) {
            r[f] = "error";
            logErr(e);
        }
    });
    return r;
};

/**
 * <odoc>
 * <key>ow.metrics.getAll() : Map</key>
 * Returns a map with all registered metrics.
 * </odoc>
 */
OpenWrap.metrics.prototype.getAll = function() {
    return ow.metrics.getSome(Object.keys(ow.metrics.__m));
};

/**
 * <odoc>
 * <key>ow.metrics.startCollecting(aChName, aPeriod, some)</key>
 * Starts collecting metrics on aChName (defaults to '__metrics') every aPeriod ms (defaults to 1000ms) optionally just some (array) metrics.
 * </odoc>
 */
OpenWrap.metrics.prototype.startCollecting = function(aChName, aPeriod, aSome) {
    var createCh = isUnDef(aChName) || $ch().list().indexOf(aChName) < 0;

    if (isUnDef(ow.metrics.__fnMetrics)) ow.metrics.__fnMetrics = {};

    aChName = _$(aChName).isString().default("__metrics");
    aPeriod = _$(aPeriod).isNumber().default(1000);

    if (createCh) $ch(aChName).create(1, "mvs", { file: "metrics.db" });

    if (isUnDef(ow.metrics.__ch)) ow.metrics.__ch = [];
    ow.metrics.__ch.push(aChName);

    if (isUnDef(ow.metrics.__t)) {
        plugin("Threads");
        ow.metrics.__t = new Threads();
        ow.metrics.__t.addScheduleThreadWithFixedDelay(function() {
            var k = { t: now() };
            var v;
            if(isArray(aSome))
               v = merge(k, ow.metrics.getSome(aSome));
            else
	       v = merge(k, ow.metrics.getAll());

            ow.metrics.__ch.map(ch => {
                $ch(ch).set(k, v);
            });
        }, aPeriod);
        ow.metrics.__t.startNoWait();
    }
};

/**
 * <odoc>
 * <key>ow.metrics.stopCollecting(aChName)</key>
 * Stops collecting metrics on aChName (defaults to '__metrics')
 * </odoc>
 */
OpenWrap.metrics.prototype.stopCollecting = function(aChName) {
    aChName = _$(aChName).isString().default("__metrics");
    if (ow.metrics.__ch.indexOf(aChName) < 0) throw "Not collecting into " + aChName;

    ow.metrics.__ch = deleteFromArray(ow.metrics.__ch, ow.metrics.__ch.indexOf(aChName));
    if (isDef(ow.metrics.__t) && ow.metrics.__ch.length <= 0) {
        ow.metrics.__t.stop(true);
        ow.metrics.__t = void 0;
    }
};

/**
 * <odoc>
 * <key>ow.metrics.collectMetrics4Fn(aName, aFn)</key>
 * Adds extra code to an existing aFn to collect functions metrics under the name aName. If the same aName and aFn
 * has been already executed before it will throw an exception "Already collecting for the provided function."
 * </odoc>
 */
OpenWrap.metrics.prototype.collectMetrics4Fn = function(aName, aFn) {
    _$(aName, "name").isString().$_();
    _$(aFn, "fn").isString().$_();

    var aBody = eval(aFn).toString();
    if (isUnDef(ow.metrics.__fnMetrics)) ow.metrics.__fnMetrics = {};
    if (isDef(ow.metrics.__fnMetrics[aName])) throw "Already collecting for the provided function.";

    aBody = aBody.split(/\n/);
    var newBody = [];
    ow.metrics.__fnMetrics[aName] = {
        start: 0,
        err  : 0,
        end  : 0,
        sum  : 0,
        avg  : 0
    };

    for(var ii in aBody) {
        if (ii == 2 || ii == aBody.length -2) {
            if (ii == 2) {
                newBody.push("ow.metrics.__fnMetrics[\"" + aName + "\"].start += 1; var __resMetricsProxyE, __resMetricsProxyR, __resMetricsProxyI = now(); try { __resMetricsProxyR = (function(){");
            } else {
                newBody.push("})(); ow.metrics.__fnMetrics[\"" + aName + "\"].end += 1; ow.metrics.__fnMetrics[\"" + aName + "\"].sum += (now() - __resMetricsProxyI); return __resMetricsProxyR; } catch(__fnMetricsProxyE) { ow.metrics.__fnMetrics[\"" + aName + "\"].err += 1; throw __fnMetricsProxyE; }");
            }
        }
        newBody.push(aBody[ii]);
    }
    eval(aFn + " = " + newBody.join("\n"));
};

/**
 * <odoc>
 * <key>ow.metrics.collectMetrics(aName, aFunction) : Object</key>
 * Executes aFunction while collecting functions metrics under the name aName. Returns whatever the function returns
 * or throws any exception.
 * </odoc>
 */
OpenWrap.metrics.prototype.collectMetrics = function(aName, aFunction) {
    _$(aName, "name").isString().$_();
    _$(aFunction).isFunction().$_();

    if (isUnDef(ow.metrics.__fnMetrics)) ow.metrics.__fnMetrics = {};
    if (isUnDef(ow.metrics.__fnMetrics[aName])) {
        ow.metrics.__fnMetrics[aName] = {
            start: 0,
            err  : 0,
            end  : 0,
            sum  : 0
        };
    }

    var __resMetricsProxyE, __resMetricsProxyR, __resMetricsProxyI = now(), res;
    try {
        ow.metrics.__fnMetrics[aName].start += 1;
        __resMetricsProxyR = aFunction();
        ow.metrics.__fnMetrics[aName].end += 1;
        return __resMetricsProxyR;
    } catch(__resMetricsProxyE) {
        ow.metrics.__fnMetrics[aName].err += 1;
        throw __resMetricsProxyE;
    }
}
<commit_msg>metrics: correcting for $cache<commit_after>// OpenWrap v2
// Author: Nuno Aguiar
// Metrics

OpenWrap.metrics = function() {
	return ow.metrics;
};

OpenWrap.metrics.prototype.__m = {
    mem: () => {
        var res = {
            max: Number(java.lang.Runtime.getRuntime().maxMemory()),
            total: Number(java.lang.Runtime.getRuntime().totalMemory()),
            free: Number(java.lang.Runtime.getRuntime().freeMemory())
        };
        res.used = res.total - res.free;
        return res;
    },
    cpu: () => ({
        load1 : java.lang.System.getProperty("os.name").indexOf("Windows") < 0 ? getCPULoad() : "n/a",
        load2 : java.lang.System.getProperty("os.name").indexOf("Windows") < 0 ? getCPULoad(true) : "n/a",
        cores : getNumberOfCores(),
        _cores: __cpucores
    }),
    oaf: () => {
        var res = {
            libs : __loadedLibs,
            nlibs: Object.keys(__loadedLibs).length,
            nscopes: af.getScopeIds().length,
            preCompileLevel: __preCompileLevel,
            version: getVersion(),
            path   : getOpenAFPath(),
            java   : String(java.lang.System.getProperty("java.version")),
            javapath: String(java.lang.System.getProperty("java.home")),
            init   : __oafInit,
            now    : now(),
            logErr : __clogErr.get(),
            logWarn: __clogWarn.get(),
            cpuCores: __cpucores,
            threadPoolFactor: __threadPoolFactor,
            mainThreadPool: {
                parallelism: __getThreadPool().getParallelism(),
                size: __getThreadPool().getPoolSize(),
                active: __getThreadPool().getActiveThreadCount(),
                running: __getThreadPool().getRunningThreadCount(),
                steals: __getThreadPool().getStealCount(),
                tasks: __getThreadPool().getQueuedTaskCount(),
                queued: __getThreadPool().getQueuedSubmissionCount()
            },
            bottlenecks: (isDef(global.__bottleneck) ? Object.keys(global.__bottleneck).map(r => ({
                name    : r,
                running : global.__bottleneck[r].atomic.get(),
                maxWait : global.__bottleneck[r].attw,
                maxExecs: global.__bottleneck[r].ance
            })) : "n/a"),
            cache: (isDef(global.__$cache) ? Object.keys(global.__$cache).map(r => ({
                name: r,
                chName: global.__$cache[r].name,
                ttl : global.__$cache[r].attl,
                maxSize: global.__$cache[r].msize,
                size: global.__$cache[r].size(),
                hits: ow.ch.__types.cache.__cacheStats[global.__$cache[r].name].hits,
                miss: ow.ch.__types.cache.__cacheStats[global.__$cache[r].name].miss,
                avgExecTime: ow.ch.__types.cache.__cacheStats[global.__$cache[r].name].avg,
            })) : "n/a"),
            rest: (isDef(global.__openaf_rest) ? Object.keys(global.__openaf_rest.urls).map(r => ({
                url: r,
                hits: _$(global.__openaf_rest.urls[r].c).default(0),
                miss: _$(global.__openaf_rest.urls[r].f).default(0)
            })) : "n/a"),
            fns    : ow.metrics.__fnMetrics
        };
        if (isDef(res.fns)) {
            Object.keys(res.fns).map(r => {
                res.fns[r].avg = res.fns[r].sum / (res.fns[r].err + res.fns[r].end);
            });
        }
        return res;
    },
    ojob: () => {
        var res = {};
        if (isDef(ow.oJob)) {
            res = ow.oJob.getLogCh().getAll().map(j => ({
                name : j.name,
                start: j.count,
                //err  : $path(j.log, "[?not_null(error)] | length(@)"),
                //end  : $path(j.log, "[?!not_null(error)] | length(@)"),
                error: j.error,
                sum  : j.totalTime,
                avg  : j.avgTime
            }) );
        }
        return res;
    },
    os: () => ({
        pid    : getPid(),
        name   : String(java.lang.System.getProperty("os.name")),
        host   : String(java.net.InetAddress.getLocalHost().getHostName()),
        ip     : String(java.net.InetAddress.getLocalHost().getHostAddress())
    }),
    threads: () => {
        var res = {
            list  : af.fromJavaArray(java.lang.Thread.getAllStackTraces().keySet().toArray()).map(t => ({
                id      : t.getId(),
                name    : String(t.getName()),
                isAlive : t.isAlive(),
                priority: Number(t.getPriority()),
                state   : String(t.getState())
            })),
            active: Number(java.lang.Thread.activeCount()),
            total : Number(java.lang.Thread.getAllStackTraces().size())
        };
        res.states = {};
        res.list.map(r => {
            if (isUnDef(res.states[r.state]))
                res.states[r.state] = 1;
            else
                res.states[r.state] += 1;
        });
        return res;
    }
};

/**
 * <odoc>
 * <key>ow.metrics.add(aName, aFunction)</key>
 * Adds aName metric whose values are a map returned by aFunction.
 * </odoc>
 */
OpenWrap.metrics.prototype.add = function(aName, aFn) {
    if (isUnDef(ow.metrics.__m[aName])) {
        ow.metrics.__m[aName] = aFn;
    }
};

/**
 * <odoc>
 * <key>ow.metrics.getSome(anArrayOfNames) : Map</key>
 * Returns just the metrics in the provided anArrayOfNames.
 * </odoc>
 */
OpenWrap.metrics.prototype.getSome = function(aArray) {
    var r = {}, errors = [];
    aArray.map(f => {
        try {
            r[f] = ow.metrics.__m[f]();
        } catch(e) {
            r[f] = "error";
            logErr(e);
        }
    });
    return r;
};

/**
 * <odoc>
 * <key>ow.metrics.getAll() : Map</key>
 * Returns a map with all registered metrics.
 * </odoc>
 */
OpenWrap.metrics.prototype.getAll = function() {
    return ow.metrics.getSome(Object.keys(ow.metrics.__m));
};

/**
 * <odoc>
 * <key>ow.metrics.startCollecting(aChName, aPeriod, some)</key>
 * Starts collecting metrics on aChName (defaults to '__metrics') every aPeriod ms (defaults to 1000ms) optionally just some (array) metrics.
 * </odoc>
 */
OpenWrap.metrics.prototype.startCollecting = function(aChName, aPeriod, aSome) {
    var createCh = isUnDef(aChName) || $ch().list().indexOf(aChName) < 0;

    if (isUnDef(ow.metrics.__fnMetrics)) ow.metrics.__fnMetrics = {};

    aChName = _$(aChName).isString().default("__metrics");
    aPeriod = _$(aPeriod).isNumber().default(1000);

    if (createCh) $ch(aChName).create(1, "mvs", { file: "metrics.db" });

    if (isUnDef(ow.metrics.__ch)) ow.metrics.__ch = [];
    ow.metrics.__ch.push(aChName);

    if (isUnDef(ow.metrics.__t)) {
        plugin("Threads");
        ow.metrics.__t = new Threads();
        ow.metrics.__t.addScheduleThreadWithFixedDelay(function() {
            var k = { t: now() };
            var v;
            if(isArray(aSome))
               v = merge(k, ow.metrics.getSome(aSome));
            else
	       v = merge(k, ow.metrics.getAll());

            ow.metrics.__ch.map(ch => {
                $ch(ch).set(k, v);
            });
        }, aPeriod);
        ow.metrics.__t.startNoWait();
    }
};

/**
 * <odoc>
 * <key>ow.metrics.stopCollecting(aChName)</key>
 * Stops collecting metrics on aChName (defaults to '__metrics')
 * </odoc>
 */
OpenWrap.metrics.prototype.stopCollecting = function(aChName) {
    aChName = _$(aChName).isString().default("__metrics");
    if (ow.metrics.__ch.indexOf(aChName) < 0) throw "Not collecting into " + aChName;

    ow.metrics.__ch = deleteFromArray(ow.metrics.__ch, ow.metrics.__ch.indexOf(aChName));
    if (isDef(ow.metrics.__t) && ow.metrics.__ch.length <= 0) {
        ow.metrics.__t.stop(true);
        ow.metrics.__t = void 0;
    }
};

/**
 * <odoc>
 * <key>ow.metrics.collectMetrics4Fn(aName, aFn)</key>
 * Adds extra code to an existing aFn to collect functions metrics under the name aName. If the same aName and aFn
 * has been already executed before it will throw an exception "Already collecting for the provided function."
 * </odoc>
 */
OpenWrap.metrics.prototype.collectMetrics4Fn = function(aName, aFn) {
    _$(aName, "name").isString().$_();
    _$(aFn, "fn").isString().$_();

    var aBody = eval(aFn).toString();
    if (isUnDef(ow.metrics.__fnMetrics)) ow.metrics.__fnMetrics = {};
    if (isDef(ow.metrics.__fnMetrics[aName])) throw "Already collecting for the provided function.";

    aBody = aBody.split(/\n/);
    var newBody = [];
    ow.metrics.__fnMetrics[aName] = {
        start: 0,
        err  : 0,
        end  : 0,
        sum  : 0,
        avg  : 0
    };

    for(var ii in aBody) {
        if (ii == 2 || ii == aBody.length -2) {
            if (ii == 2) {
                newBody.push("ow.metrics.__fnMetrics[\"" + aName + "\"].start += 1; var __resMetricsProxyE, __resMetricsProxyR, __resMetricsProxyI = now(); try { __resMetricsProxyR = (function(){");
            } else {
                newBody.push("})(); ow.metrics.__fnMetrics[\"" + aName + "\"].end += 1; ow.metrics.__fnMetrics[\"" + aName + "\"].sum += (now() - __resMetricsProxyI); return __resMetricsProxyR; } catch(__fnMetricsProxyE) { ow.metrics.__fnMetrics[\"" + aName + "\"].err += 1; throw __fnMetricsProxyE; }");
            }
        }
        newBody.push(aBody[ii]);
    }
    eval(aFn + " = " + newBody.join("\n"));
};

/**
 * <odoc>
 * <key>ow.metrics.collectMetrics(aName, aFunction) : Object</key>
 * Executes aFunction while collecting functions metrics under the name aName. Returns whatever the function returns
 * or throws any exception.
 * </odoc>
 */
OpenWrap.metrics.prototype.collectMetrics = function(aName, aFunction) {
    _$(aName, "name").isString().$_();
    _$(aFunction).isFunction().$_();

    if (isUnDef(ow.metrics.__fnMetrics)) ow.metrics.__fnMetrics = {};
    if (isUnDef(ow.metrics.__fnMetrics[aName])) {
        ow.metrics.__fnMetrics[aName] = {
            start: 0,
            err  : 0,
            end  : 0,
            sum  : 0
        };
    }

    var __resMetricsProxyE, __resMetricsProxyR, __resMetricsProxyI = now(), res;
    try {
        ow.metrics.__fnMetrics[aName].start += 1;
        __resMetricsProxyR = aFunction();
        ow.metrics.__fnMetrics[aName].end += 1;
        return __resMetricsProxyR;
    } catch(__resMetricsProxyE) {
        ow.metrics.__fnMetrics[aName].err += 1;
        throw __resMetricsProxyE;
    }
}
<|endoftext|>


<commit_before>/**
 * Homepage
 */

// switch code & video examples on the homepages
var $allVideoLi = $('#video-intro li');
var $allCodeLi = $('#code-intro li');

var activateEntry = function (type, $entries) {
	return function (event) {
		$('#' + type +'-intro .active-entry').removeClass('active-entry');
		$(event.currentTarget).addClass('active-entry');
		$entries.each(function (idx, elm) {
			$($('.stage.' + type).get(idx))[(elm === event.currentTarget ? 'removeClass' : 'addClass')]('hidden');
		});
	};
};

$allVideoLi.on('click', activateEntry('video', $allVideoLi));
$allCodeLi.on('click', activateEntry('code', $allCodeLi));

/**
 * Sidebar
 */

// activate entry
var activateEntry = function ($elm) {
	$('.sidenav .active').removeClass('active');
	$elm.addClass('active');
};

// sidebar menue change on hash change & dom load
var activeSidebar = function (event) {
	var $elm = $('.sidenav ' + window.location.hash.replace('#', '.nav-'));
	if ($elm.length === 1) {
		activateEntry($elm);
	}
};

var activeByViewport = function () {
  var inview = '.nav-undefined';
  $('.nav-helper').each(function (idx, elm) {
  	if (inViewport(elm) && inview === '.nav-undefined') {
  		inview = '.nav-' + $(elm).attr('data-name');
  	}
  });

  if (inview !== '.nav-undefined') {
  	var $elm = $('.sidenav ' + inview);
  	if (!$elm.hasClass('active')) {
		activateEntry($elm);
  	}
  }
};

$(window).on('hashchange', activeSidebar);
setInterval(activeByViewport, 250);
activeSidebar();

// iScroll sidenav
if (document.getElementById('content')) {
	var scroller = new IScroll('#content', {
		scrollbars: true,
		mouseWheel: true,
		interactiveScrollbars: true
	 });

	var sideScroller = new IScroll('#sidenav', {
		mouseWheel: true
	 });

	var $scrollToElm = $('a[data-name="' + window.location.hash.replace('#', '') + '"]');
	if ($scrollToElm.length) {
		scroller.scrollToElement($scrollToElm[0], 0);
	}

	$(window).on('hashchange', function () {
		var $scrollToElm = $('a[data-name="' + window.location.hash.replace('#', '') + '"]');
		if ($scrollToElm.length) {
			scroller.scrollToElement($scrollToElm[0], 400);
		}
	});
}<commit_msg>Navigation & responsive goodness<commit_after>/**
 * Homepage
 */

// switch code & video examples on the homepages
var $allVideoLi = $('#video-intro li');
var $allCodeLi = $('#code-intro li');

var activateEntry = function (type, $entries) {
    return function (event) {
        $('#' + type +'-intro .active-entry').removeClass('active-entry');
        $(event.currentTarget).addClass('active-entry');
        $entries.each(function (idx, elm) {
            $($('.stage.' + type).get(idx))[(elm === event.currentTarget ? 'removeClass' : 'addClass')]('hidden');
        });
    };
};

$allVideoLi.on('click', activateEntry('video', $allVideoLi));
$allCodeLi.on('click', activateEntry('code', $allCodeLi));

/**
 * Sidebar
 */

// activate entry
var activateEntry = function ($elm) {
    $('.sidenav .active').removeClass('active');
    $elm.addClass('active');
};

// sidebar menue change on hash change & dom load
var activeSidebar = function (event) {
    var $elm = $('.sidenav ' + window.location.hash.replace('#', '.nav-'));
    if ($elm.length === 1) {
        activateEntry($elm);
    }
};

var activeByViewport = function () {
  var inview = '.nav-undefined';
  $('.nav-helper').each(function (idx, elm) {
    if (inViewport(elm) && inview === '.nav-undefined') {
        inview = '.nav-' + $(elm).attr('data-name');
    }
  });

  if (inview !== '.nav-undefined') {
    var $elm = $('.sidenav ' + inview);
    if (!$elm.hasClass('active')) {
        activateEntry($elm);
    }
  }
};

$(window).on('hashchange', activeSidebar);
var checker = function () {
    return setInterval(activeByViewport, 250);
};

var interval = checker();
activeSidebar();

// iScroll sidenav
var matches = window.matchMedia ? window.matchMedia('(min-width: 500px)').matches : true;
if (document.getElementById('content') && matches) {
    var scroller = new IScroll('#content', {
        scrollbars: true,
        mouseWheel: true,
        interactiveScrollbars: true,
        click: true
     });

    var sideScroller = new IScroll('#sidenav', {
        mouseWheel: true,
        click: true
     });

    var scrolltoHash = window.location.hash.replace('#', '');

    var $scrollToElm = $('a[data-name="' + scrolltoHash + '"]');
    if ($scrollToElm.length) {
        scroller.scrollToElement($scrollToElm[0], 0);
    }

    $(window).on('hashchange', function () {
        var scrolltoHash = window.location.hash.replace('#', '');
        var $scrollToElm = $('a[data-name="' + scrolltoHash + '"]');
        clearInterval(interval);
        if ($scrollToElm.length) {
            scroller.scrollToElement($scrollToElm[0], 400);
            setTimeout(function () {
                interval = checker();
            }, 500);
        }
    });
}

// monkey bang pow! contact text on index (hate it but, whatever)
var textOnIndex = function () {
    var matchesTextShort = window.matchMedia ? window.matchMedia('(max-width: 480px)').matches : true;
    var matchesTextLong = window.matchMedia ? window.matchMedia('(min-width: 480px)').matches : true;
    if (matchesTextShort) {
        $('.longtext').text('#dalekjs@IRC');
    }

    if (matchesTextLong) {
        $('.longtext').text('#dalekjs on freenode');
    }
};

$(window).on('orientationchange', textOnIndex);
$(window).on('resize', textOnIndex);
textOnIndex();

// monkey bang pow! the second... remove/add footer position on the on the merch site (hate it but, whatever)
if (window.location.pathname.search('merch') !== -1) {

    var footerOnorientation = function () {
        var matchesPortrait = window.matchMedia ? window.matchMedia('(orientation:portrait)').matches : true;
        var matchesLandscape = window.matchMedia ? window.matchMedia('(orientation:landscape)').matches : true;

        if (matchesLandscape) {
            $('#footer').css('position', 'static');
        }

        if (matchesPortrait) {
            $('#footer').css('position', 'absolute');
        }
    };

    $(window).on('orientationchange', footerOnorientation);
    $(window).on('resize', footerOnorientation);
    footerOnorientation();
}
<|endoftext|>


<commit_before>// Data points (array of [Latitude, Longitude] objects)
var places = ["Portland, Oregon",
              "Orange County, California",
              "San Diego, California",
              "Seattle, Washington",
              "Tacoma, Washington",
              "Vancouver, Washington",
              "Vancouver, BC",
              "Chicago, Illinois",
              "Las Vegas, Nevada",
              "Boise, Idaho",
              "Phoenix, Arizona",
              "South Bend, Indiana",
              "Louisville, Kentucky",
              "Pittsburgh, Pennsylvania",
              "Sandusky, Ohio",
              "Columbus, Ohio",
              "Youngstown, Ohio",
              "Nashville, Tennessee",
              "Rome, Italy",
              "Brussels, Belgium",
              "Montreal, Quebec",
              "Punta Cana, Dominican Republic",
              "Austin, Texas",
              "Houston, Texas",
              "Saigon, Vietnam",
              "Changi, Singapore"];

// Initialize empty heatmap
function initHeatmap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(0, 0),
    zoom: 2,
  });

  setMarkers(map, places);
}

// Set the place markers on the map
//function setMarkers(map, places) {
//  var fs    = require("fs");
//  var data  = fs.readFile("../")
//}

// Set the place markers on the map
async function createMarkers(map, places) {
  // Converts place names to Latitude Longitude
  var geocoder = new google.maps.Geocoder();

  for(place in places) {
    geocoder.geocode({'address': places[place]}, function(results, status) {
      if(status === 'OK') {
        console.log(results[0].geometry.location);
      }
      else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
    await sleep(300);
  }
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// On document start
$(function() {
  createMarkers();
});<commit_msg>lat long test<commit_after>// Data points (array of [Latitude, Longitude] objects)
var places = ["Portland, Oregon",
              "Orange County, California",
              "San Diego, California",
              "Seattle, Washington",
              "Tacoma, Washington",
              "Vancouver, Washington",
              "Vancouver, BC",
              "Chicago, Illinois",
              "Las Vegas, Nevada",
              "Boise, Idaho",
              "Phoenix, Arizona",
              "South Bend, Indiana",
              "Louisville, Kentucky",
              "Pittsburgh, Pennsylvania",
              "Sandusky, Ohio",
              "Columbus, Ohio",
              "Youngstown, Ohio",
              "Nashville, Tennessee",
              "Rome, Italy",
              "Brussels, Belgium",
              "Montreal, Quebec",
              "Punta Cana, Dominican Republic",
              "Austin, Texas",
              "Houston, Texas",
              "Saigon, Vietnam",
              "Changi, Singapore"];

// Initialize empty heatmap
function initHeatmap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(0, 0),
    zoom: 2,
  });

  setMarkers(map, places);
}

// Set the place markers on the map
//function setMarkers(map, places) {
//  var fs    = require("fs");
//  var data  = fs.readFile("../")
//}

// Set the place markers on the map
async function createMarkers(map, places) {
  // Converts place names to Latitude Longitude
  var geocoder = new google.maps.Geocoder();

  for(place in places) {
    geocoder.geocode({'address': places[place]}, function(results, status) {
      if(status === 'OK') {
        console.log("good");
        console.log(results[0].geometry.location);
      }
      else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
    await sleep(300);
  }
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// On document start
$(function() {
  createMarkers();
});<|endoftext|>