<commit_before>(function($){
	var _deleteAllMarket = function(){
	    var currentMarkers = _markers.markers;
	    for(var i=0 ; i < currentMarkers.length; i++){
	        currentMarkers[i].destroy();
	    }
	    _markers.markers = new Array();
	},
	_setMarket = function(lon,lat,code,businessName,address,city,country){
	    var size = new OpenLayers.Size(21,25);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var icon = new OpenLayers.Icon(_iconUrl,size,offset);
	    marker = new OpenLayers.Marker(new OpenLayers.LonLat(lon, lat).transform(_fromProjection, _toProjection),icon);
	    eventMarkerOver = function(evt){
	        var popup = _findPopupByCode(code);
	        if(popup == null){
	        	var data = {
	        		code: code,
	        		businessName: businessName,
	        		address: address,
	        		city: city,
	        		country: country
	        	};
	        	_initTemplate("marketTemplate", "marketImpl");
	        	var htmlContent = $.render.marketImpl(data);
	            popup = new OpenLayers.Popup.FramedCloud(code,
	            new OpenLayers.LonLat(lon, lat).transform(_fromProjection, _toProjection),
	            new OpenLayers.Size(200,200),
	            htmlContent,
	            null,true);
	            _map.addPopup(popup);
	        }else{
	            popup.show();
	        }
	    }
	    eventMarkerOut = function(evt){
	        var popup = _findPopupByCode(code);
	        popup.hide();
	    }
	    marker.events.register("click", marker, eventMarkerOver);
//	    marker.events.register("mouseout", marker, eventMarkerOut);
	    _markers.addMarker(marker);
	},
	_findPopupByCode = function(code){
	    var popups = _map.popups;
	    if(popups == null)
	    {
	        return null;
	    }
	    for(var i = 0 ; i < popups.length ; i++){
	        if(popups[i].id == code ){
	            return popups[i];
	        }
	    }
	    return null;
	},
	_buildSelectCountry = function(dataJson){
	    var data = dataJson;
//	    var html = "<option value =''>All</option>";
//	    for(var i = 0; i < data.length ; i++){
//	     html += "<option value ='"+ i +"'>"+ data[i].code +"</option>";
//	    }
	    _initTemplate("selectCountryTemplate", "countryImpl");
    	var htmlContent = $.render.countryImpl({data:data});
	    $('#country').html(htmlContent);
	},
	_buildSelectCityAndSetMarker = function( dataJson, indexCountry ){
	    var country = dataJson[indexCountry] ;
	    var cities = country.cities ;
	    var html ="<option value =''>All</option>";
	    for(var i = 0; i < cities.length ; i++){
	        html += "<option value ='"+ i +"'>"+ cities[i].name +"</option>";
	        var stores = cities[i].stores;
	        _buildSetMarkerByCoordinates(stores);
	    }
	    _initTemplate("selectCityTemplate", "cityImpl");
    	var htmlContent = $.render.cityImpl({data:cities});
	    $('#city').html(html);
	},
	_buildSetMarkerByCoordinates = function(stores){
	    for(var i = 0 ; i < stores.length ; i++){
	         var lon = stores[i].longitude;
	         var lat = stores[i].latitude;
	         var code = stores[i].code;
	         var businessName = stores[i].businessName;
	         var address = stores[i].address1;
	         var city = stores[i].city;
	         var country = stores[i].country;
	         _setMarket(lon,lat,code,businessName,address,city,country);
	         _buildStoreFound(stores[i]);
	    }
	},
	_buildSetAllMarker = function(dataJson){
	    for(var i = 0; i < dataJson.length; i++){
	        var country = dataJson[i] ;
	        var cities = country.cities ;
	        for(var j = 0; j < cities.length ; j++){
	            var coordinates = cities[j].stores;
	            _buildSetMarkerByCoordinates(coordinates);
	        }
	    }
	    _buildSliderStore();
	    _setCenter();
	    _map.zoomToMaxExtent();
	},
	_buildSetAllMarkerByCountry = function(indexCountry){
	        var country = _dataOSM[indexCountry] ;
	        var cities = country.cities ;
	        for(var j = 0; j < cities.length ; j++){
	            var stores = cities[j].stores;
	            _buildSetMarkerByCoordinates(stores);
	        }
	},
	_buildStoreFound = function(store){
		_storesFound.push(store);
	},
	_buildSliderStore = function(){
		_initTemplate("storesTemplate", "storesImpl");
    	var htmlContent = $.render.storesImpl({data:_storesFound});
    	$('.slides_container.row.products-grid').html(htmlContent);
		$('#location-store-list').slides({
				preload: true,
				generateNextPrev: true,
				play: 0,
				hoverPause: true
			});
			_storesFound = [];
	    },
	_setCenter = function(){
         var currentMarkers = _markers.markers;
          var newBound = new OpenLayers.Bounds();
        for(var i=0 ; i < currentMarkers.length; i++){
            var tempMarker = currentMarkers[i];
            newBound.extend(tempMarker.lonlat);
        }
        var centerPosition = newBound.getCenterLonLat();
         var zoomLv = _map.getZoomForExtent(newBound,true);
        _map.setCenter(centerPosition, zoomLv -1 );
    },
    _setCenterByPosition = function(lat, lon){
    	var positionCenter = new OpenLayers.LonLat(lon, lat).transform(_fromProjection, _toProjection);
    	_map.setCenter(positionCenter, 18);
    },
    _searchAll = function(dataSearch,textSearch){
    	var positionFound = [];
    	 for(var i = 0 ; i < dataSearch.length ; i++){
             var cities = dataSearch[i].cities;
             for(var j = 0 ; j< cities.length; j++){
                 var stores = cities[j].stores;
                 for(var k = 0; k< stores.length; k++){
                     if(stores[k].businessName.search(new RegExp(textSearch,"i") ) !== -1){
                     positionFound.push(stores[k]);
                 }
             }
         }
     }
	 return positionFound;
	},
	_searchByCountry = function(dataSearch, indexCountry, textSearch){
		 var positionFound = [];
		 var cities = dataSearch[indexCountry].cities;
	     for(var j = 0 ; j< cities.length; j++){
	         var stores = cities[j].stores;
	         for(var k = 0; k< stores.length; k++){
	             if(stores[k].businessName.search(new RegExp(textSearch,"i") ) !== -1){
	                 positionFound.push(stores[k]);
	             }
	         }
	     }
	     return positionFound;
	},
	_searchByCity = function(dataSearch, indexCountry, indexCity,textSearch){
		 var positionFound = [];
		 var cities = dataSearch[indexCountry].cities;
	     var stores = cities[indexCity].stores;
	     for(var k = 0; k< stores.length; k++){
	         if(stores[k].businessName.search(new RegExp(textSearch,"i") ) !== -1){
	             positionFound.push(stores[k]);
	         }
	     }
	     return positionFound;
	},
	_hideAllPopup = function(){
    	var popups = _map.popups;
        if(popups == null)
        {
            return null;
        }
        for(var i = 0 ; i < popups.length ; i++){
                return popups[i].hide();
        }
    },
	_DEFAULTS = {
		map: {
			zoom: 3,
			lonCenter: -30.000,
			latCenter: 45.000
		},
		data: [],
		iconUrl: "http://www.openlayers.org/dev/img/marker.png"
	},
	_dataOSM 		= [],
	_map 			= {},
	_fromProjection = {} ,
	_toProjection	= {},
	_markers		= {},
	_iconUrl		= "",
	_storesFound 	= [],
	_initTemplate = function(templateId, templateName){
		templateId = "#" + templateId;
		$.templates(templateName, templateId);
	};

	$.qalingo = function(){};

	$.qalingo.storeLocator = function(options){
		var settings ={};
		$.extend(settings, _DEFAULTS, options);
	    var zoom                 = settings.map.zoom;
	    var lonCenter            = settings.map.lonCenter;
	    var latCenter            = settings.map.latCenter;
	    _fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
	    _toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
	    _dataOSM = settings.data;
	    _iconUrl = settings.iconUrl;
	    _map = new OpenLayers.Map("map-store");
	    var mapnik = new OpenLayers.Layer.OSM();
	    _map.addLayer(mapnik);
	    _markers = new OpenLayers.Layer.Markers("Markers");
	    _map.addLayer(_markers);
	    _map.addControl(new OpenLayers.Control.LayerSwitcher());
	    controls = _map.getControlsByClass('OpenLayers.Control.Navigation');
	    for(var i = 0; i < controls.length; ++i)
	    {
	         controls[i].disableZoomWheel();
	    }

	    $('a.store-item').live('click',function(){
	    	var lon   = $(this).data("lon");
	    	var lat   = $(this).data("lat");
	    	_setCenterByPosition(lat, lon);
	    });
	    $('#bt-search').click(function(){
	        var textSearch = $('input#search').val();
	        var positionFound = [];
	        var indexCountry = $('#country').find(":selected").attr("value");
	        var optionCity = $('#city').find(":selected");
	        if(indexCountry == ''){
	        	positionFound = _searchAll(_dataOSM,textSearch);
	        }else{
	        	if(optionCity.length > 0){
	        		indexCity = optionCity.attr("value");
	        		if(indexCity == ''){
	        			positionFound = _searchByCountry(_dataOSM ,indexCountry,textSearch );
	        		}else{
	        			positionFound = _searchByCity(_dataOSM, indexCountry, indexCity,textSearch);
	        		}
	        	}else{
	        		positionFound = _searchByCountry(_dataOSM ,indexCountry,textSearch );
	        	}
	        }
	        if(positionFound.length > 0){
	            _deleteAllMarket();
	            _buildSetMarkerByCoordinates(positionFound);
	            _storesFound = positionFound;
	            _buildSliderStore();
	            _setCenter();
	            _hideAllPopup();
	        }
	    });
	    $('#country').change(function(){
	        var option = $(this).find(":selected");
	        var index = option.attr("value");
	        if(index == ''){
	             _buildSetAllMarker(_dataOSM);
	             $('#city').html('<option value="" selected="selected">City/Province</option>');
	        }else{
	            _deleteAllMarket();
	            _buildSelectCityAndSetMarker(_dataOSM,index);
	            _buildSliderStore();
	        }
	        $('input#search').val();
	        _setCenter();
	        _hideAllPopup();
	    });
	    $('#city').change(function(){
	        var indexCountry = $('#country').find(":selected").attr("value");
	        var indexCity = $(this).find(":selected").attr("value");
	        if(indexCity==''){
	            _deleteAllMarket();
	            _buildSetAllMarkerByCountry(indexCountry);
	        }else{
	            var stores =_dataOSM[indexCountry].cities[indexCity].stores;
	            _deleteAllMarket();
	            _buildSetMarkerByCoordinates(stores);
	        }
	        $('input#search').val();
	        _buildSliderStore();
	        _setCenter();
	        _hideAllPopup();
	    });
	    _buildSelectCountry(_dataOSM);
	    _buildSetAllMarker(_dataOSM);
	    _setCenter();
	};
})(jQuery);<commit_msg>add js render + add icon marker<commit_after>(function($){
	var _deleteAllMarket = function(){
	    var currentMarkers = _markers.markers;
	    for(var i=0 ; i < currentMarkers.length; i++){
	        currentMarkers[i].destroy();
	    }
	    _markers.markers = new Array();
	},
	_setMarket = function(lon,lat,code,businessName,address,city,country){
	    var size = new OpenLayers.Size(21,25);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var icon = new OpenLayers.Icon(_iconUrl,size,offset);
	    marker = new OpenLayers.Marker(new OpenLayers.LonLat(lon, lat).transform(_fromProjection, _toProjection),icon);
	    eventMarkerOver = function(evt){
	        var popup = _findPopupByCode(code);
	        if(popup == null){
	        	var data = {
	        		code: code,
	        		businessName: businessName,
	        		address: address,
	        		city: city,
	        		country: country
	        	};
	        	_initTemplate("marketTemplate", "marketImpl");
	        	var htmlContent = $.render.marketImpl(data);
	            popup = new OpenLayers.Popup.FramedCloud(code,
	            new OpenLayers.LonLat(lon, lat).transform(_fromProjection, _toProjection),
	            new OpenLayers.Size(200,200),
	            htmlContent,
	            null,true);
	            _map.addPopup(popup);
	        }else{
	            popup.show();
	        }
	    }
	    marker.events.register("click", marker, eventMarkerOver);
	    _markers.addMarker(marker);
	},
	_findPopupByCode = function(code){
	    var popups = _map.popups;
	    if(popups == null)
	    {
	        return null;
	    }
	    for(var i = 0 ; i < popups.length ; i++){
	        if(popups[i].id == code ){
	            return popups[i];
	        }
	    }
	    return null;
	},
	_buildSelectCountry = function(dataJson){
	    var data = dataJson;
	    _initTemplate("selectCountryTemplate", "countryImpl");
    	var htmlContent = $.render.countryImpl({data:data});
	    $('#country').html(htmlContent);
	},
	_buildSelectCityAndSetMarker = function( dataJson, indexCountry ){
	    var country = dataJson[indexCountry] ;
	    var cities = country.cities ;
	    var html ="<option value =''>All</option>";
	    for(var i = 0; i < cities.length ; i++){
	        html += "<option value ='"+ i +"'>"+ cities[i].name +"</option>";
	        var stores = cities[i].stores;
	        _buildSetMarkerByCoordinates(stores);
	    }
	    _initTemplate("selectCityTemplate", "cityImpl");
    	var htmlContent = $.render.cityImpl({data:cities});
	    $('#city').html(html);
	},
	_buildSetMarkerByCoordinates = function(stores){
	    for(var i = 0 ; i < stores.length ; i++){
	         var lon = stores[i].longitude;
	         var lat = stores[i].latitude;
	         var code = stores[i].code;
	         var businessName = stores[i].businessName;
	         var address = stores[i].address1;
	         var city = stores[i].city;
	         var country = stores[i].country;
	         _setMarket(lon,lat,code,businessName,address,city,country);
	         _buildStoreFound(stores[i]);
	    }
	},
	_buildSetAllMarker = function(dataJson){
	    for(var i = 0; i < dataJson.length; i++){
	        var country = dataJson[i] ;
	        var cities = country.cities ;
	        for(var j = 0; j < cities.length ; j++){
	            var coordinates = cities[j].stores;
	            _buildSetMarkerByCoordinates(coordinates);
	        }
	    }
	    _buildSliderStore();
	    _setCenter();
	    _map.zoomToMaxExtent();
	},
	_buildSetAllMarkerByCountry = function(indexCountry){
	        var country = _dataOSM[indexCountry] ;
	        var cities = country.cities ;
	        for(var j = 0; j < cities.length ; j++){
	            var stores = cities[j].stores;
	            _buildSetMarkerByCoordinates(stores);
	        }
	},
	_buildStoreFound = function(store){
		_storesFound.push(store);
	},
	_buildSliderStore = function(){
		_initTemplate("storesTemplate", "storesImpl");
    	var htmlContent = $.render.storesImpl({data:_storesFound});
    	$('.slides_container.row.products-grid').html(htmlContent);
		$('#location-store-list').slides({
				preload: true,
				generateNextPrev: true,
				play: 0,
				hoverPause: true
			});
			_storesFound = [];
	    },
	_setCenter = function(){
         var currentMarkers = _markers.markers;
          var newBound = new OpenLayers.Bounds();
        for(var i=0 ; i < currentMarkers.length; i++){
            var tempMarker = currentMarkers[i];
            newBound.extend(tempMarker.lonlat);
        }
        var centerPosition = newBound.getCenterLonLat();
         var zoomLv = _map.getZoomForExtent(newBound,true);
        _map.setCenter(centerPosition, zoomLv -1 );
    },
    _setCenterByPosition = function(lat, lon){
    	var positionCenter = new OpenLayers.LonLat(lon, lat).transform(_fromProjection, _toProjection);
    	_map.setCenter(positionCenter, 18);
    },
    _searchAll = function(dataSearch,textSearch){
    	var positionFound = [];
    	 for(var i = 0 ; i < dataSearch.length ; i++){
             var cities = dataSearch[i].cities;
             for(var j = 0 ; j< cities.length; j++){
                 var stores = cities[j].stores;
                 for(var k = 0; k< stores.length; k++){
                     if(stores[k].businessName.search(new RegExp(textSearch,"i") ) !== -1){
                     positionFound.push(stores[k]);
                 }
             }
         }
     }
	 return positionFound;
	},
	_searchByCountry = function(dataSearch, indexCountry, textSearch){
		 var positionFound = [];
		 var cities = dataSearch[indexCountry].cities;
	     for(var j = 0 ; j< cities.length; j++){
	         var stores = cities[j].stores;
	         for(var k = 0; k< stores.length; k++){
	             if(stores[k].businessName.search(new RegExp(textSearch,"i") ) !== -1){
	                 positionFound.push(stores[k]);
	             }
	         }
	     }
	     return positionFound;
	},
	_searchByCity = function(dataSearch, indexCountry, indexCity,textSearch){
		 var positionFound = [];
		 var cities = dataSearch[indexCountry].cities;
	     var stores = cities[indexCity].stores;
	     for(var k = 0; k< stores.length; k++){
	         if(stores[k].businessName.search(new RegExp(textSearch,"i") ) !== -1){
	             positionFound.push(stores[k]);
	         }
	     }
	     return positionFound;
	},
	_hideAllPopup = function(){
    	var popups = _map.popups;
        if(popups == null)
        {
            return null;
        }
        for(var i = 0 ; i < popups.length ; i++){
                return popups[i].hide();
        }
    },
	_DEFAULTS = {
		map: {
			zoom: 3,
			lonCenter: -30.000,
			latCenter: 45.000
		},
		data: [],
		iconUrl: "http://www.openlayers.org/dev/img/marker.png"
	},
	_dataOSM 		= [],
	_map 			= {},
	_fromProjection = {} ,
	_toProjection	= {},
	_markers		= {},
	_iconUrl		= "",
	_storesFound 	= [],
	_initTemplate = function(templateId, templateName){
		templateId = "#" + templateId;
		$.templates(templateName, templateId);
	};

	$.qalingo = function(){};

	$.qalingo.storeLocator = function(options){
		var settings ={};
		$.extend(settings, _DEFAULTS, options);
	    var zoom                 = settings.map.zoom;
	    var lonCenter            = settings.map.lonCenter;
	    var latCenter            = settings.map.latCenter;
	    _fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
	    _toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
	    _dataOSM = settings.data;
	    _iconUrl = settings.iconUrl;
	    _map = new OpenLayers.Map("map-store");
	    var mapnik = new OpenLayers.Layer.OSM();
	    _map.addLayer(mapnik);
	    _markers = new OpenLayers.Layer.Markers("Markers");
	    _map.addLayer(_markers);
	    _map.addControl(new OpenLayers.Control.LayerSwitcher());
	    controls = _map.getControlsByClass('OpenLayers.Control.Navigation');
	    for(var i = 0; i < controls.length; ++i)
	    {
	         controls[i].disableZoomWheel();
	    }

	    $('a.store-item').live('click',function(){
	    	var lon   = $(this).data("lon");
	    	var lat   = $(this).data("lat");
	    	_setCenterByPosition(lat, lon);
	    });
	    $('#bt-search').click(function(){
	        var textSearch = $('input#search').val();
	        var positionFound = [];
	        var indexCountry = $('#country').find(":selected").attr("value");
	        var optionCity = $('#city').find(":selected");
	        if(indexCountry == ''){
	        	positionFound = _searchAll(_dataOSM,textSearch);
	        }else{
	        	if(optionCity.length > 0){
	        		indexCity = optionCity.attr("value");
	        		if(indexCity == ''){
	        			positionFound = _searchByCountry(_dataOSM ,indexCountry,textSearch );
	        		}else{
	        			positionFound = _searchByCity(_dataOSM, indexCountry, indexCity,textSearch);
	        		}
	        	}else{
	        		positionFound = _searchByCountry(_dataOSM ,indexCountry,textSearch );
	        	}
	        }
	        if(positionFound.length > 0){
	            _deleteAllMarket();
	            _buildSetMarkerByCoordinates(positionFound);
	            _storesFound = positionFound;
	            _buildSliderStore();
	            _setCenter();
	            _hideAllPopup();
	        }
	    });
	    $('#country').change(function(){
	        var option = $(this).find(":selected");
	        var index = option.attr("value");
	        if(index == ''){
	             _buildSetAllMarker(_dataOSM);
	             $('#city').html('<option value="" selected="selected">City/Province</option>');
	        }else{
	            _deleteAllMarket();
	            _buildSelectCityAndSetMarker(_dataOSM,index);
	            _buildSliderStore();
	        }
	        $('input#search').val();
	        _setCenter();
	        _hideAllPopup();
	    });
	    $('#city').change(function(){
	        var indexCountry = $('#country').find(":selected").attr("value");
	        var indexCity = $(this).find(":selected").attr("value");
	        if(indexCity==''){
	            _deleteAllMarket();
	            _buildSetAllMarkerByCountry(indexCountry);
	        }else{
	            var stores =_dataOSM[indexCountry].cities[indexCity].stores;
	            _deleteAllMarket();
	            _buildSetMarkerByCoordinates(stores);
	        }
	        $('input#search').val();
	        _buildSliderStore();
	        _setCenter();
	        _hideAllPopup();
	    });
	    _buildSelectCountry(_dataOSM);
	    _buildSetAllMarker(_dataOSM);
	    _setCenter();
	};
})(jQuery);<|endoftext|>


<commit_before>// webview demo
'use strict';

/**
 * mock data
 */
var line = 10;
var data = [];

while (line --) {
  data.push({
    id: line,
    title: '这里的一行文字是文章标题长长长长长长长长长长长长',
    url: 'http://www.xdf.me',
    date: '2013.12.12'
  });
}

var userAgent = navigator.userAgent;
var ios = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i);
var android = userAgent.indexOf("Android") > -1 || userAgent.indexOf("Linux") > -1;

var exec = function(data, global) {
  var $ = document.querySelectorAll.bind(document);
  var content = $('#content')[0];
  var tplElm = $('#template')[0].innerHTML;
  var tpl = grace.compile(tplElm);
  var API = 'http://xudafeng.com/feedit/read.php';
  var node = tpl({
    list: data
  });
  content.innerHTML = node;
  document.addEventListener('click', function(e) {
    var target = e.target;
    if (target.nodeName === 'BUTTON') {
      var id = target.id.split('button-')[1];
      id = parseInt(id);
      var url = target.getAttribute('data-url');
      //ajax
      JSONP(API, {
        id: id
      }, 'callback', function(data) {
        if (data) {
          if (data.success) {
            target.style.display = 'none';
            location.href = url;
          }
        }
      });
    }
  }, false);
}

if (ios) {
  this.Ready = function(data) {
    if (data.success) {
      exec(data.data, window);
    }
  };
} else if(android) {
  data = dataFromInterface.get('data');
  data = JSON.parse(data);
  exec(data, this);
} else {
  exec(data, this);
}
<commit_msg>bugifx<commit_after>// webview demo
'use strict';

/**
 * mock data
 */
var line = 10;
var data = [];

while (line --) {
  data.push({
    id: line,
    title: '这里的一行文字是文章标题长长长长长长长长长长长长',
    url: 'http://www.xdf.me',
    date: '2013.12.12'
  });
}

var userAgent = navigator.userAgent;
var ios = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i);
var android = userAgent.indexOf("Android") > -1 || userAgent.indexOf("Linux") > -1;

var exec = function(data, global) {
  var $ = document.querySelectorAll.bind(document);
  var content = $('#content')[0];
  var tplElm = $('#template')[0].innerHTML;
  var tpl = grace.compile(tplElm);
  var API = 'http://xudafeng.com/feedit/read.php';
  var node = tpl({
    list: data
  });
  content.innerHTML = node;
  document.addEventListener('click', function(e) {
    var target = e.target;
    if (target.nodeName === 'BUTTON') {
      var id = target.id.split('button-')[1];
      id = parseInt(id);
      var url = target.getAttribute('data-url');
      //ajax
      JSONP(API, {
        id: id
      }, 'callback', function(data) {
        if (data) {
          if (data.success) {
            target.style.display = 'none';
            location.href = url;
          }
        }
      });
    }
  }, false);
}

if (ios) {
  this.Ready = function(data) {
    exec(data, window);
  };
} else if(android) {
  data = dataFromInterface.get('data');
  data = JSON.parse(data);
  exec(data, this);
} else {
  exec(data, this);
}
<|endoftext|>


<commit_before>var FB = function (url, gameId) {
    this.firebase = new Firebase(url);
    this.gamesRef = this.firebase.root().child('games');
    this.gameId = gameId;
};

FB.prototype.ref = function () {
    return this.firebase.root();
};

FB.prototype.newGame = function (size) {
    return this.gamesRef.push({size: size}).key();
};

FB.prototype.getGames = function () {
    var def = $.Deferred();
    this.gamesRef.orderByKey().limitToLast(5).once('value', function(snap){
        def.resolve(snap.val());
    });
    return def.promise();
};

FB.prototype.setStone = function (x, y, color) {
    return this.gamesRef.child(this.gameId + '/board/' + x + "-" + y).set(color);
};

FB.prototype.removeStone = function (x, y) {
    return this.gamesRef.child(this.gameId + '/board/' + x + "-" + y).remove();
};

FB.prototype.setToken = function (playerNum) {
    var partnerNum = Math.abs(playerNum - 1);
    var self = this;
    var player = this.gameId + '/player' + playerNum + '/token';
    var partner = this.gameId + 'player' + partnerNum + '/token';
    this.gamesRef.child(player).once('value', function (snap) {
        self.gamesRef.child(partner).once('value', function (snapPartner) {
            if (_.isNull(snap.val()) && _.isNull(snapPartner.val())) {
                self.gamesRef.child(player).transaction(function () {
                    return true;
                });
            }
        });
    });
};

FB.prototype.switchToken = function (playerNum) {
    var partnerNum = Math.abs(playerNum - 1);
    var partner = this.gameId + '/player' + partnerNum + '/token';
    var player = this.gameId + '/player' + playerNum + '/token';
    this.gamesRef.child(player).set({});
    this.gamesRef.child(partner).transaction(function () {
        return true;
    });
};

/**
 * Calls Firebase.on(), Listens for data changes at a particular location
 *
 *

 *     FB.on('board', 'child_added')
 *       .progress( childAdded )
 *       .fail( securityError )
 *       .done( listenerDisposed )
 *

 *
 * @param path
 * @param event
 * @return {jQuery.Deferred}
 */
FB.prototype.on = function (path, event) {
    var def = $.Deferred();

    this.ref().child(path).on(event, function(snap) {
        def.notify(snap);
    }, function (err) {
        console.error('Access denied attempting to read database ', err, path, event);
    });

    return def.promise();
};

/**
 * Calls Firebase.once(), Listens for exactly one event of the specified event type, and then stops listening.
 *
 * @param path
 * @param event
 * @returns {jQuery.Deferred}
 */
FB.prototype.once = function(path, event) {
    var def = $.Deferred();

    this.ref().child(path).once(event, function(snap) {
        def.resolve(snap);
    }, function(err) {
        console.error('Access denied attempting to read database', err, path, event);
        def.reject(err);
    });

    return def.promise();
};

FB.prototype.childWithTransaction = function (path, input) {
    var def = $.Deferred();
    this.ref().child(path).transaction(function (value) {
        def.resolve(value);
        if (value === null) {
            return input;
        } else {
            return;
        }
    }, function (error, committed) {
        def.reject(error, committed);
    });
    return def.promise();
};
<commit_msg>no return value<commit_after>var FB = function (url, gameId) {
    this.firebase = new Firebase(url);
    this.gamesRef = this.firebase.root().child('games');
    this.gameId = gameId;
};

FB.prototype.ref = function () {
    return this.firebase.root();
};

FB.prototype.newGame = function (size) {
    return this.gamesRef.push({size: size}).key();
};

FB.prototype.getGames = function () {
    var def = $.Deferred();
    this.gamesRef.orderByKey().limitToLast(5).once('value', function(snap){
        def.resolve(snap.val());
    });
    return def.promise();
};

FB.prototype.setStone = function (x, y, color) {
    this.gamesRef.child(this.gameId + '/board/' + x + "-" + y).set(color);
};

FB.prototype.removeStone = function (x, y) {
    this.gamesRef.child(this.gameId + '/board/' + x + "-" + y).remove();
};

FB.prototype.setToken = function (playerNum) {
    var partnerNum = Math.abs(playerNum - 1);
    var self = this;
    var player = this.gameId + '/player' + playerNum + '/token';
    var partner = this.gameId + 'player' + partnerNum + '/token';
    this.gamesRef.child(player).once('value', function (snap) {
        self.gamesRef.child(partner).once('value', function (snapPartner) {
            if (_.isNull(snap.val()) && _.isNull(snapPartner.val())) {
                self.gamesRef.child(player).transaction(function () {
                    return true;
                });
            }
        });
    });
};

FB.prototype.switchToken = function (playerNum) {
    var partnerNum = Math.abs(playerNum - 1);
    var partner = this.gameId + '/player' + partnerNum + '/token';
    var player = this.gameId + '/player' + playerNum + '/token';
    this.gamesRef.child(player).set({});
    this.gamesRef.child(partner).transaction(function () {
        return true;
    });
};

/**
 * Calls Firebase.on(), Listens for data changes at a particular location
 *
 *

 *     FB.on('board', 'child_added')
 *       .progress( childAdded )
 *       .fail( securityError )
 *       .done( listenerDisposed )
 *

 *
 * @param path
 * @param event
 * @return {jQuery.Deferred}
 */
FB.prototype.on = function (path, event) {
    var def = $.Deferred();

    this.ref().child(path).on(event, function(snap) {
        def.notify(snap);
    }, function (err) {
        console.error('Access denied attempting to read database ', err, path, event);
    });

    return def.promise();
};

/**
 * Calls Firebase.once(), Listens for exactly one event of the specified event type, and then stops listening.
 *
 * @param path
 * @param event
 * @returns {jQuery.Deferred}
 */
FB.prototype.once = function(path, event) {
    var def = $.Deferred();

    this.ref().child(path).once(event, function(snap) {
        def.resolve(snap);
    }, function(err) {
        console.error('Access denied attempting to read database', err, path, event);
        def.reject(err);
    });

    return def.promise();
};

FB.prototype.childWithTransaction = function (path, input) {
    var def = $.Deferred();
    this.ref().child(path).transaction(function (value) {
        def.resolve(value);
        if (value === null) {
            return input;
        } else {
            return;
        }
    }, function (error, committed) {
        def.reject(error, committed);
    });
    return def.promise();
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import CreateDocument from './CreateDocument'
import Warning from './home/Warning'
import './Home.css'

class Home extends Component {
  constructor (props) {
    super(props)
    this.state = {
      error: false,
      showWarning: true
    }
  }

  render () {
    return (

        {this.state.showWarning && (
          <Warning onClose={() => this.setState({showWarning: false})} />
        )}

              What is PeerPad
              Features
              How it works
              Benefits

HELLO WORLD

            PeerPad is a realtime collaborative editing tool,
            powered by IPFS and CRDTs

            <CreateDocument />
            {this.state.error ? (

{this.state.error}

            ) : null}

            About us

            Peerpad is collaborative real-time editor that works on the decentralised web, built on top of IPFS and Y.js. It uses no second or third-party: all participating nodes talk directly to each other without a central service. Peerpad is open-source and built by Protocol Labs and the IPFS community.

              Features

              Peerpad does not rely on a second or third-party.

              All nodes talk to each other directly, without intermediation.

                  Private

                  Communication between parties is encrypted.

                  Encrypted

                  Access to content depends on a secret "read" key. A node needs to have access to this key in order to read the document and follow the changes to it. A node can only change the content if they have access to a "write" key.

                  Collaborative

                  Thanks to CRDTs and Y.js, several authors can collaborate in editing the document without originating conflicts, even when they aren't connected to each other all the time.

                  Realtime

                  When multiple people are editing a document are connected to each other, they see everyone's changes reflected in the document in real-time.

            How it works

            A Conflict-free Replicated Data Type (CRDT) offers 'Strong Eventual Consistency': a flavour of eventual consistency
            that ensures conflicts can be merged automatically to produce a value that is guaranteed to be correct/consistent.

            Two objects can be either equal, have hierarchy (one descends the other) or are pairs; the latter signifies
            a branch/divergence/conflict. From the intrinsic state of the two pairs, we can determine a new descendant object which is the result of the merge.

              What you can do with PeerPad

              Peerpad can be used to edit code, markdown documents or even rich text documents. Peerpad can also be used to save snapshots and publish them to the internet.

                  Take meeting notes

                  Either using plain text, Markdown or Rich-text, you can take meeting notes and share with your colleagues in real time..

                  Collaborate or share snippets of code

                  Peerpad has a built-in code editor you can use to collaborate with colleagues while editing the same file.

                  Write articles and share them

                  You can publish a snapshot of a pad to IPFS, making it available on the internet. Choose who you share them with by sharing a read key that decrypts the content.

                  Work with multiple users at the same time

                  Peerpad can work with many users changing the document at the same time, seing each other's changes in real-time.

              What is PeerPad
              Features
              How it works
              Benefits

              © Protocol Labs
               |
              Except as noted,
              content licensed CC-BY 3.0

    )
  }

  componentDidCatch (err, info) {
    this.setState({ error: err })
  }
}

export default Home
<commit_msg>WIP more homepage content<commit_after>import React, { Component } from 'react'
import CreateDocument from './CreateDocument'
import Warning from './home/Warning'
import './Home.css'

class Home extends Component {
  constructor (props) {
    super(props)
    this.state = {
      error: false,
      showWarning: true
    }
  }

  render () {
    return (

        {this.state.showWarning && (
          <Warning onClose={() => this.setState({showWarning: false})} />
        )}

              What is PeerPad
              Features
              How it works
              Benefits

HELLO WORLD

            PeerPad is a realtime collaborative editing tool,
            powered by IPFS and CRDTs

            <CreateDocument />
            {this.state.error ? (

{this.state.error}

            ) : null}

            About us

            Peerpad is collaborative real-time editor that works on the decentralised web, built on top of IPFS and Y.js. It uses no second or third-party: all participating nodes talk directly to each other without a central service. Peerpad is open-source and built by Protocol Labs and the IPFS community.

              Features

              Peerpad does not rely on a second or third-party.

              All nodes talk to each other directly, without intermediation.

                  Private

                  Communication between parties is encrypted.

                  Encrypted

                  Access to content depends on a secret "read" key. A node needs to have access to this key in order to read the document and follow the changes to it. A node can only change the content if they have access to a "write" key.

                  Collaborative

                  Thanks to CRDTs and Y.js, several authors can collaborate in editing the document without originating conflicts, even when they aren't connected to each other all the time.

                  Realtime

                  When multiple people are editing a document are connected to each other, they see everyone's changes reflected in the document in real-time.

            How it works

            A Conflict-free Replicated Data Type (CRDT) offers 'Strong Eventual Consistency': a flavour of eventual consistency
            that ensures conflicts can be merged automatically to produce a value that is guaranteed to be correct/consistent.

            Two objects can be either equal, have hierarchy (one descends the other) or are pairs; the latter signifies
            a branch/divergence/conflict. From the intrinsic state of the two pairs, we can determine a new descendant object which is the result of the merge.

              What you can do with PeerPad

              Peerpad can be used to edit code, markdown documents or even rich text documents. Peerpad can also be used to save snapshots and publish them to the internet.

                    Take meeting notes

                    Either using plain text, Markdown or Rich-text, you can take meeting notes and share with your colleagues in real time..

                    Collaborate or share snippets of code

                    Peerpad has a built-in code editor you can use to collaborate with colleagues while editing the same file.

                    Write articles and share them

                    You can publish a snapshot of a pad to IPFS, making it available on the internet. Choose who you share them with by sharing a read key that decrypts the content.

                    Work with multiple users at the same time

                    Peerpad can work with many users changing the document at the same time, seing each other's changes in real-time.

              What is PeerPad
              Features
              How it works
              Benefits

              © Protocol Labs
               |
              Except as noted,
              content licensed CC-BY 3.0

    )
  }

  componentDidCatch (err, info) {
    this.setState({ error: err })
  }
}

export default Home
<|endoftext|>


<commit_before>/*
	Basic Commands
*/
var repeatTimer = null;

function setPermission(room, perm, rank) {
	if (!Settings.settings.commands) Settings.settings.commands = {};
	if (!Settings.settings.commands[room]) Settings.settings.commands[room] = {};
	Settings.settings.commands[room][perm] = rank;
	Settings.save();
}

function repeat(room) {
	Bot.say(room, 'hi friends!');
}

Settings.addPermissions(['say']);

exports.commands = {
	credits: 'about',
	bot: 'about',
	about: function () {
		this.restrictReply(this.trad('about') + " (https://github.com/Ecuacion/Pokemon-Showdown-Node-Bot)", 'info');
	},

	suspect: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('suspect') + " (http://www.smogon.com/forums/threads/lc-suspect-diglett.3566865/)", 'info');
	},

	viability: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('viability') + " (http://www.smogon.com/forums/threads/lc-viability-rankings-2-0.3547566/page-5#post-6519836)", 'info');
	},

	introductions: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('introductions') + " (http://www.smogon.com/forums/threads/useful-lc-stuff-introductions-simple-questions-simple-answers.3491009/)", 'info');
	},

	timburr: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('timburr') + " (http://www.smogon.com/forums/threads/metagame-discussion-thread.3505710/page-55#post-6586231)", 'info');
	},

	resource: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('resource') + " (http://www.smogon.com/forums/threads/little-cup-resource-thread.3548652/)", 'info');
	},

	bottime: 'time',
	time: function () {
		var f = new Date();
		this.restrictReply("**" + this.trad('time') + ":** __" + f.toString() + "__", 'info');
	},

	uptime: function () {
		var text = '';
		text += '**Uptime:** ';
		var divisors = [52, 7, 24, 60, 60];
		var units = [this.trad('week'), this.trad('day'), this.trad('hour'), this.trad('minute'), this.trad('second')];
		var buffer = [];
		var uptime = ~~(process.uptime());
		do {
			var divisor = divisors.pop();
			var unit = uptime % divisor;
			if (!unit) {
				units.pop();
				uptime = ~~(uptime / divisor);
				continue;
			}
			buffer.push(unit > 1 ? unit + ' ' + units.pop() + 's' : unit + ' ' + units.pop());
			uptime = ~~(uptime / divisor);
		} while (uptime);

		switch (buffer.length) {
		case 5:
			text += buffer[4] + ', ';
			text += buffer[3] + ', ';
			text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0];
			break;
		case 4:
			text += buffer[3] + ', ';
			text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0];
			break;
		case 3:
			text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0];
			break;
		case 2:
			text += buffer[1] + ' ' + this.trad('and') + ' ' + buffer[0];
			break;
		case 1:
			text += buffer[0];
			break;
		}
		this.restrictReply(text, 'info');
	},

	seen: function (arg, by, room, cmd) {
		var text = '';
		var name = arg;
		arg = toId(arg);
		if (!arg || arg.length > 18) return this.pmReply(this.trad('inv'));
		if (arg === toId(Bot.status.nickName)) return this.pmReply(this.trad('bot'));
		if (arg === toId(by)) return this.pmReply(this.trad('self'));
		if (Settings.seen[arg]) {
			var dSeen = Settings.seen[arg];
			var lang = Config.language || 'english';
			if (Settings.settings['language'] && Settings.settings['language'][room]) lang = Settings.settings['language'][room];
			text += name + ' ' + this.trad('s1') + ' ' + Tools.getTimeAgo(dSeen.time, lang) + (this.trad('s2') ? (' ' + this.trad('s2')) : '');
			if (dSeen.room) {
				switch (dSeen.action) {
					case 'j':
						text += ', ' + this.trad('j') + ' ' + dSeen.room;
						break;
					case 'l':
						text += ', ' + this.trad('l') + ' ' + dSeen.room;
						break;
					case 'c':
						text += ', ' + this.trad('c') + ' ' + dSeen.room;
						break;
					case 'n':
						text += ', ' + this.trad('n') + ' ' + dSeen.args[0];
						break;
				}
			}
		} else {
			text += this.trad('n1') + ' ' + arg + ' ' + this.trad('n2');
		}
		this.pmReply(text);
	},

	say: function (arg) {
		if (!arg) return;
		if (!this.can('say')) return;
		this.reply(Tools.stripCommands(arg));
	},

	repeat: function (arg, by, room, cmd) {
		if (!this.isRanked('#')) return false;
		var lang = toId(arg);
		if (lang === 'on') {
			var repeatTimer = setInterval(repeat(room), 180000);
		} else if (lang === 'off') {
			clearInterval(repeatTimer);
		}
		Bot.say(room, "Now on repeat mode");
	},

	lang: 'language',
	language: function (arg, by, room, cmd) {
		if (!this.isRanked('#')) return false;
		if (this.roomType !== 'chat') return this.reply(this.trad('notchat'));
		var lang = toId(arg);
		if (!lang.length) return this.reply(this.trad('nolang'));
		if (!Tools.translations[lang]) return this.reply(this.trad('v') + ': ' + Object.keys(Tools.translations).join(', '));
		if (!Settings.settings['language']) Settings.settings['language'] = {};
		Settings.settings['language'][room] = lang;
		Settings.save();
		this.reply(this.trad('l'));
	},

	   insult: function (target, room, user) {
		if (!this.isRanked('%')) return false;
        if (this.roomType !== 'chat' || !this.can('insult')) return;
        if (!target) return;

        var arrayA = [
            'the dude who got shit on by Pawniard on ladder and changed his Timburr to Spritzee',
            'guess you couldve gone all the way after critting me 4 times in our dpp ou playoffs game but hey not quite there yet in terms of skill',
            'bet you played more mons than me in the last 2 weeks alone good job "not caring"',
            'if i cared about mons half as much as you do id jerk off to the unbelievable thought of you winning once in your life',
            'i hate it when dumbass bitches like you make retarded moves and choke the whole fucking game away that way',
            'i swear to fucking god how can a single player be this lucky after getting played all the fucking way',
            'no person using a team that shit and standard and fucking horrible in ORAS should ever be gaining any of my respect whatsoever because its disgusting and a waste of time',
            'arent you the guy whose friend got fucking trashbagged by me in what 12 minutes? while he cheered for him',
            'arent you the guy whose friend got fucking trashbagged by me in what 12 minutes? while he cheered for him',
            'something is very wrong with your head to begin with, seeing how you cant handle a timer consisting of 300 seconds in a game designed for children and actually start to hyperventilate'];

        var arrayB = [
            'Maybe you should shut the fuck up instead of calling out other people',
            'Get real',
            'Why are you still posting',
            'You almost ruined our season by just existing',
            'You are a mere slave',
            'I am here to show Smogon how fucking awful you are at everything',
            'You\'re useless for everything everywhere on Smogon',
            'I wish the people i played werent actually worthless',
            'Die in a ditch and dont ever mention my name again',
            'This felt like the special olympics of ORAS'];

        var arrayC = [
            'nut-hugger',
            'dumbass baboon',
            'glorified heap of trash',
            'filth',
            'stinky italian',
            'worthless protoplasm',
            'random grinch',
            'useless sack of shit',
            'no one on a site that means nothing',
            'literal trash'];

        var returnInfo = [arrayA[Math.floor(Math.random() * 10)], arrayB[Math.floor(Math.random() * 10)], arrayC[Math.floor(Math.random() * 10)]];
        this.reply('Oh, its ' + target + ', ' + returnInfo[0] + '. ' + returnInfo[1] + ' you ' + returnInfo[2] + '.');
    },

    	flirt: function (target, room, user) {
		if (!this.isRanked('%')) return false;
        if (this.roomType !== 'chat' || !this.can('flirt')) return;
        if (!target) return;

        var lines = [
       		'you are hotter than the bottom of my laptop.',
       		'if i could rearrange the alphabet, i\'d put my dick in your butt.',
       		'my mom thinks i\'m gay, can you help me prove her wrong?',
       		'there are 8 planets in the universe, but only 7 after I destroy Uranus',
       		'you know why I am like a squirrel? Cause I want to bury my nuts in you.',
       		'I like every bone in your body, especially mine.',
       		'I`m no weatherman, but you can expect a few inches tonight.',
       		'You make me want to calibrate my joystick without the latest drivers',
       		'is that a keg in your pants? Because I’d love to tap that ass'
        	];
        var line = Math.floor(Math.random() * lines.length);
        this.reply('Hey' + target + ', ' + lines[line]);
    },

	settings: 'set',
	set: function (arg, by, room, cmd) {
		if (!this.isRanked('#')) return false;
		if (this.roomType !== 'chat') return this.reply(this.trad('notchat'));
		var args = arg.split(",");
		if (args.length < 2) return this.reply(this.trad('u1') + ": " + this.cmdToken + cmd + " " + this.trad('u2'));
		var perm = toId(args[0]);
		var rank = args[1].trim();
		if (!(perm in Settings.permissions)) {
			return this.reply(this.trad('ps') + ": " + Object.keys(Settings.permissions).sort().join(", "));
		}
		if (rank in {'off': 1, 'disable': 1}) {
			if (!this.canSet(perm, true)) return this.reply(this.trad('denied'));
			setPermission(room, perm, true);
			return this.reply(this.trad('p') + " **" + perm + "** " + this.trad('d'));
		}
		if (rank in {'on': 1, 'all': 1, 'enable': 1}) {
			if (!this.canSet(perm, ' ')) return this.reply(this.trad('denied'));
			setPermission(room, perm, ' ');
			return this.reply(this.trad('p') + " **" + perm + "** " + this.trad('a'));
		}
		if (Config.ranks.indexOf(rank) >= 0) {
			if (!this.canSet(perm, rank)) return this.reply(this.trad('denied'));
			setPermission(room, perm, rank);
			return this.reply(this.trad('p') + " **" + perm + "** " + this.trad('r') + ' ' + rank + " " + this.trad('r2'));
		} else {
			return this.reply(this.trad('not1') + " " + rank + " " + this.trad('not2'));
		}
	}
};
<commit_msg>Update basic.js<commit_after>/*
	Basic Commands
*/
var repeatTimer = null;

function setPermission(room, perm, rank) {
	if (!Settings.settings.commands) Settings.settings.commands = {};
	if (!Settings.settings.commands[room]) Settings.settings.commands[room] = {};
	Settings.settings.commands[room][perm] = rank;
	Settings.save();
}

function repeat(room) {
	Bot.say(room, 'hi friends!');
}

Settings.addPermissions(['say']);

exports.commands = {
	credits: 'about',
	bot: 'about',
	about: function () {
		this.restrictReply(this.trad('about') + " (https://github.com/Ecuacion/Pokemon-Showdown-Node-Bot)", 'info');
	},

	suspect: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('suspect') + " (http://www.smogon.com/forums/threads/lc-suspect-diglett.3566865/)", 'info');
	},

	viability: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('viability') + " (http://www.smogon.com/forums/threads/lc-viability-rankings-2-0.3547566/page-5#post-6519836)", 'info');
	},

	introductions: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('introductions') + " (http://www.smogon.com/forums/threads/useful-lc-stuff-introductions-simple-questions-simple-answers.3491009/)", 'info');
	},

	timburr: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('timburr') + " (http://www.smogon.com/forums/threads/metagame-discussion-thread.3505710/page-55#post-6586231)", 'info');
	},

	resource: function () {
		if (!this.isRanked('+')) return false;
		this.reply(this.trad('resource') + " (http://www.smogon.com/forums/threads/little-cup-resource-thread.3548652/)", 'info');
	},

	bottime: 'time',
	time: function () {
		var f = new Date();
		this.restrictReply("**" + this.trad('time') + ":** __" + f.toString() + "__", 'info');
	},

	uptime: function () {
		var text = '';
		text += '**Uptime:** ';
		var divisors = [52, 7, 24, 60, 60];
		var units = [this.trad('week'), this.trad('day'), this.trad('hour'), this.trad('minute'), this.trad('second')];
		var buffer = [];
		var uptime = ~~(process.uptime());
		do {
			var divisor = divisors.pop();
			var unit = uptime % divisor;
			if (!unit) {
				units.pop();
				uptime = ~~(uptime / divisor);
				continue;
			}
			buffer.push(unit > 1 ? unit + ' ' + units.pop() + 's' : unit + ' ' + units.pop());
			uptime = ~~(uptime / divisor);
		} while (uptime);

		switch (buffer.length) {
		case 5:
			text += buffer[4] + ', ';
			text += buffer[3] + ', ';
			text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0];
			break;
		case 4:
			text += buffer[3] + ', ';
			text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0];
			break;
		case 3:
			text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0];
			break;
		case 2:
			text += buffer[1] + ' ' + this.trad('and') + ' ' + buffer[0];
			break;
		case 1:
			text += buffer[0];
			break;
		}
		this.restrictReply(text, 'info');
	},

	seen: function (arg, by, room, cmd) {
		var text = '';
		var name = arg;
		arg = toId(arg);
		if (!arg || arg.length > 18) return this.pmReply(this.trad('inv'));
		if (arg === toId(Bot.status.nickName)) return this.pmReply(this.trad('bot'));
		if (arg === toId(by)) return this.pmReply(this.trad('self'));
		if (Settings.seen[arg]) {
			var dSeen = Settings.seen[arg];
			var lang = Config.language || 'english';
			if (Settings.settings['language'] && Settings.settings['language'][room]) lang = Settings.settings['language'][room];
			text += name + ' ' + this.trad('s1') + ' ' + Tools.getTimeAgo(dSeen.time, lang) + (this.trad('s2') ? (' ' + this.trad('s2')) : '');
			if (dSeen.room) {
				switch (dSeen.action) {
					case 'j':
						text += ', ' + this.trad('j') + ' ' + dSeen.room;
						break;
					case 'l':
						text += ', ' + this.trad('l') + ' ' + dSeen.room;
						break;
					case 'c':
						text += ', ' + this.trad('c') + ' ' + dSeen.room;
						break;
					case 'n':
						text += ', ' + this.trad('n') + ' ' + dSeen.args[0];
						break;
				}
			}
		} else {
			text += this.trad('n1') + ' ' + arg + ' ' + this.trad('n2');
		}
		this.pmReply(text);
	},

	say: function (arg) {
		if (!arg) return;
		if (!this.can('say')) return;
		this.reply(Tools.stripCommands(arg));
	},

	repeat: function (arg, by, room, cmd) {
		if (!this.isRanked('#')) return false;
		var lang = toId(arg);
		if (lang === 'on') {
			var repeatTimer = setInterval(repeat(room), 180000);
		} else if (lang === 'off') {
			clearInterval(repeatTimer);
		}
		Bot.say(room, "Now on repeat mode");
	},

	lang: 'language',
	language: function (arg, by, room, cmd) {
		if (!this.isRanked('#')) return false;
		if (this.roomType !== 'chat') return this.reply(this.trad('notchat'));
		var lang = toId(arg);
		if (!lang.length) return this.reply(this.trad('nolang'));
		if (!Tools.translations[lang]) return this.reply(this.trad('v') + ': ' + Object.keys(Tools.translations).join(', '));
		if (!Settings.settings['language']) Settings.settings['language'] = {};
		Settings.settings['language'][room] = lang;
		Settings.save();
		this.reply(this.trad('l'));
	},

	   insult: function (target, room, user) {
		if (!this.isRanked('%')) return false;
        if (this.roomType !== 'chat' || !this.can('insult')) return;
        if (!target) return;

        var arrayA = [
            'the dude who got shit on by Pawniard on ladder and changed his Timburr to Spritzee',
            'guess you couldve gone all the way after critting me 4 times in our dpp ou playoffs game but hey not quite there yet in terms of skill',
            'bet you played more mons than me in the last 2 weeks alone good job "not caring"',
            'if i cared about mons half as much as you do id jerk off to the unbelievable thought of you winning once in your life',
            'i hate it when dumbass bitches like you make retarded moves and choke the whole fucking game away that way',
            'i swear to fucking god how can a single player be this lucky after getting played all the fucking way',
            'no person using a team that shit and standard and fucking horrible in ORAS should ever be gaining any of my respect whatsoever because its disgusting and a waste of time',
            'arent you the guy whose friend got fucking trashbagged by me in what 12 minutes? while he cheered for him',
            'arent you the guy whose friend got fucking trashbagged by me in what 12 minutes? while he cheered for him',
            'something is very wrong with your head to begin with, seeing how you cant handle a timer consisting of 300 seconds in a game designed for children and actually start to hyperventilate'];

        var arrayB = [
            'Maybe you should shut the fuck up instead of calling out other people',
            'Get real',
            'Why are you still posting',
            'You almost ruined our season by just existing',
            'You are a mere slave',
            'I am here to show Smogon how fucking awful you are at everything',
            'You\'re useless for everything everywhere on Smogon',
            'I wish the people i played werent actually worthless',
            'Die in a ditch and dont ever mention my name again',
            'This felt like the special olympics of ORAS'];

        var arrayC = [
            'nut-hugger',
            'dumbass baboon',
            'glorified heap of trash',
            'filth',
            'stinky italian',
            'worthless protoplasm',
            'random grinch',
            'useless sack of shit',
            'no one on a site that means nothing',
            'literal trash'];

        var returnInfo = [arrayA[Math.floor(Math.random() * 10)], arrayB[Math.floor(Math.random() * 10)], arrayC[Math.floor(Math.random() * 10)]];
        this.reply('Oh, its ' + target + ', ' + returnInfo[0] + '. ' + returnInfo[1] + ' you ' + returnInfo[2] + '.');
    },

    	flirt: function (target, room, user) {
		if (!this.isRanked('%')) return false;
        if (this.roomType !== 'chat' || !this.can('flirt')) return;
        if (!target) return;

        var lines = [
       		'you are hotter than the bottom of my laptop.',
       		'if i could rearrange the alphabet, i\'d put my dick in your butt.',
       		'my mom thinks i\'m gay, can you help me prove her wrong?',
       		'there are 8 planets in the universe, but only 7 after I destroy Uranus',
       		'you know why I am like a squirrel? Cause I want to bury my nuts in you.',
       		'I like every bone in your body, especially mine.',
       		'I`m no weatherman, but you can expect a few inches tonight.',
       		'You make me want to calibrate my joystick without the latest drivers',
       		'is that a keg in your pants? Because I’d love to tap that ass'
        	];
        var line = Math.floor(Math.random() * lines.length);
        this.reply('Hey ' + target + ', ' + lines[line]);
    },

	settings: 'set',
	set: function (arg, by, room, cmd) {
		if (!this.isRanked('#')) return false;
		if (this.roomType !== 'chat') return this.reply(this.trad('notchat'));
		var args = arg.split(",");
		if (args.length < 2) return this.reply(this.trad('u1') + ": " + this.cmdToken + cmd + " " + this.trad('u2'));
		var perm = toId(args[0]);
		var rank = args[1].trim();
		if (!(perm in Settings.permissions)) {
			return this.reply(this.trad('ps') + ": " + Object.keys(Settings.permissions).sort().join(", "));
		}
		if (rank in {'off': 1, 'disable': 1}) {
			if (!this.canSet(perm, true)) return this.reply(this.trad('denied'));
			setPermission(room, perm, true);
			return this.reply(this.trad('p') + " **" + perm + "** " + this.trad('d'));
		}
		if (rank in {'on': 1, 'all': 1, 'enable': 1}) {
			if (!this.canSet(perm, ' ')) return this.reply(this.trad('denied'));
			setPermission(room, perm, ' ');
			return this.reply(this.trad('p') + " **" + perm + "** " + this.trad('a'));
		}
		if (Config.ranks.indexOf(rank) >= 0) {
			if (!this.canSet(perm, rank)) return this.reply(this.trad('denied'));
			setPermission(room, perm, rank);
			return this.reply(this.trad('p') + " **" + perm + "** " + this.trad('r') + ' ' + rank + " " + this.trad('r2'));
		} else {
			return this.reply(this.trad('not1') + " " + rank + " " + this.trad('not2'));
		}
	}
};
<|endoftext|>


<commit_before><commit_msg>style: fix some xo glitches<commit_after><|endoftext|>


<commit_before>// Load the twilio module
var twilio = require('twilio');

// Create a new REST API client to make authenticated requests against the
// twilio back end
var client = new twilio.RestClient('AC9a185252ea97841e6812a5f414d56c9f', '08b1eaf92fd66749470c93088253c7b4');

// Pass in parameters to the REST API using an object literal notation. The
// REST client will handle authentication and response serialzation for you.
client.sms.messages.create({
    to:'+16096755596',
    from:'+14046203337',
    body:'ahoy hoy! Testing Twilio and node.js'
}, function(error, message) {
    // The HTTP request to Twilio will run asynchronously. This callback
    // function will be called when a response is received from Twilio
    // The "error" variable will contain error information, if any.
    // If the request was successful, this value will be "falsy"
    if (!error) {
        // The second argument to the callback will contain the information
        // sent back by Twilio for the request. In this case, it is the
        // information about the text messsage you just sent:
        console.log('Success! The SID for this SMS message is:');
        console.log(message.sid);

        console.log('Message sent on:');
        console.log(message.dateCreated);
    } else {
        console.log('Oops! There was an error.');
    }
});
<commit_msg>modularized text sending <(o.o)><commit_after>var twilio = require('twilio');
var client = new twilio.RestClient('AC9a185252ea97841e6812a5f414d56c9f', '08b1eaf92fd66749470c93088253c7b4');

var sendText = function(number, text, callback) {
    client.sms.messages.create({
        to: number,
        from: '+14046203337',
        body: text
    }, function(error, message) {
        if (!error) {
            console.log('Success! The SID for this SMS message is:');
            console.log(message.sid);

            console.log('Message sent on:');
            console.log(message.dateCreated);
            callback(null);
        } else {
            console.log('Oops! There was an error.');
            console.log(error);
            callback(error);
        }
    });
};

module.exports = sendText;
<|endoftext|>


<commit_before>var mainModule = angular.module('app', []).
	controller("forumCtrl", function forumCtrl($scope, $window, $timeout, $http){
		$scope.users = [
			{
				id: 0,
				firstName: "Michal",
				surname: "Paszkiewicz"
			},
			{
				id: 1,
				firstName: "Aaron",
				surname: "Dennis"
			},
			{
				id: 2
				firstName: "Dave",
				surname: "Da rave"
			}
		];

		$scope.projects = [
			{
				id: 0,
				threads: [
					{
						id: 0,
						projectID: 0,
						subject: "when to do this",
						posts: [
							{
								id: 0,
								userID: 0,
								threadID: 0,
								projectID: 0
								date: "2014",
								message: "hi"
							},
							{
								id: 1,
								userID: 2,
								threadID: 0								threadID: 0,
								projectID: 0
								date: "2014",
								message: "hi"
							}
						]
					},
					{
						id: 1,
						projectID: 0,
						subject: "stuff and things",
						posts: [
							{
								id: 2,
								userID: 1,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "yo"
							},
							{
								id: 3,
								userID: 2,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "kazaa"
							}
						]
					}
				]
			}
		];

	};
<commit_msg>Update forum.js<commit_after>var mainModule = angular.module('app', []).
	controller("forumCtrl", function forumCtrl($scope, $window, $timeout, $http){
		$scope.users = [
			{
				id: 0,
				firstName: "Michal",
				surname: "Paszkiewicz"
			},
			{
				id: 1,
				firstName: "Aaron",
				surname: "Dennis"
			},
			{
				id: 2
				firstName: "Dave",
				surname: "Da rave"
			}
		];

		$scope.projects = [
			{
				id: 0,
				name: "Prince of Egypt",
				threads: [
					{
						id: 0,
						projectID: 0,
						subject: "when to do this",
						posts: [
							{
								id: 0,
								userID: 0,
								threadID: 0,
								projectID: 0
								date: "2014",
								message: "hi"
							},
							{
								id: 1,
								userID: 2,
								threadID: 0								threadID: 0,
								projectID: 0
								date: "2014",
								message: "hi"
							}
						]
					},
					{
						id: 1,
						projectID: 0,
						subject: "stuff and things",
						posts: [
							{
								id: 2,
								userID: 1,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "yo"
							},
							{
								id: 3,
								userID: 2,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "kazaa"
							}
						]
					}
				]
			}
		];

	};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Header from './Header.js';
import Button from './Button';
import hackathonImage from '../assets/amsterdam-hackathon.jpg';

export default class Main extends Component {
  render() {
    return (

						 View the Challenge Statement

Peoria Civic Hackathon 2017 is taking place in conjunction with Ignite Peoria, an event at the Peoria Civic Center that attracts thousands of visitors to interact with the City's thriving arts and tech community.

What is the 2017 Peoria Civic Hackathon?

Individuals or teams of 2-7 participants will come together to solve a local challenge. Participants will receive a Challenge Statement and access to relevant data sets. They will then utilize this data to create a website, app, or other tool that could improve the lives of people who live, work, and play in the Peoria area.

After the 10 hour hacking session, teams will demo their projects to a panel of judges who will decide which 2 teams created the best solution to the Challenge Statement. The first and runner-up team will receive cash prizes.

Agenda

Friday Night Social

The Fieldhouse Bar & Grill (The Back Room)

6-6:30 PM: Check-in, pick up a name tag, and grab a drink (if you wish)!

6:30-7 PM: Welcome from the City of Peoria and Q & A session about the Hackathon

Gather with your team or find a team if you are looking to join one. Members from the City of Peoria Innovation Team will answer questions about the hackathon.

7-8 PM: Mingle with fellow hackers!

Brainstorm with your team, welcome new team members, or just meet new people and have fun!

Saturday Civic Hackathon

Civic Center Verizon Lobby

8-8:30 AM: Check-in and Breakfast

Stop at the registration table to check-in, grab a name tag, register new team members, and find your team’s work space. Teams will also have the opportunity to move around once the Hackathon period begins.

8:30-9 AM: Opening Remarks from the City of Peoria

This will be the first time that Hackathon participants will hear the challenge statement they will be solving during the 10-hour hack. Also, a word from our sponsors.

9 AM: Registration Closes and HACKATHON BEGINS

12 PM: Lunch

5 PM: Dinner

7 PM: HACKING ENDS

At 7 PM, your project must be submitted and your team must be ready to demonstrate its functionality to the judges panel.

7-7:30 PM: Presentation of demos

Present your projects and see what other teams created!

7:30-7:45 PM: Judging Period

7:45-8:00 PM: Winners Announced and Presentation of Awards

						<Button href="/faq" styleName="goldbutton">Learn More</Button>

    );
  }
}
<commit_msg>changed photo on home page and added alt text to image<commit_after>import React, { Component } from 'react';
import Header from './Header.js';
import Button from './Button';
import hackathonImage from '../assets/peoria-hackathon.jpg';

export default class Main extends Component {
  render() {
    return (

						 View the Challenge Statement

Peoria Civic Hackathon 2017 is taking place in conjunction with Ignite Peoria, an event at the Peoria Civic Center that attracts thousands of visitors to interact with the City's thriving arts and tech community.

What is the 2017 Peoria Civic Hackathon?

Individuals or teams of 2-7 participants will come together to solve a local challenge. Participants will receive a Challenge Statement and access to relevant data sets. They will then utilize this data to create a website, app, or other tool that could improve the lives of people who live, work, and play in the Peoria area.

After the 10 hour hacking session, teams will demo their projects to a panel of judges who will decide which 2 teams created the best solution to the Challenge Statement. The first and runner-up team will receive cash prizes.

Agenda

Friday Night Social

The Fieldhouse Bar & Grill (The Back Room)

6-6:30 PM: Check-in, pick up a name tag, and grab a drink (if you wish)!

6:30-7 PM: Welcome from the City of Peoria and Q & A session about the Hackathon

Gather with your team or find a team if you are looking to join one. Members from the City of Peoria Innovation Team will answer questions about the hackathon.

7-8 PM: Mingle with fellow hackers!

Brainstorm with your team, welcome new team members, or just meet new people and have fun!

Saturday Civic Hackathon

Civic Center Verizon Lobby

8-8:30 AM: Check-in and Breakfast

Stop at the registration table to check-in, grab a name tag, register new team members, and find your team’s work space. Teams will also have the opportunity to move around once the Hackathon period begins.

8:30-9 AM: Opening Remarks from the City of Peoria

This will be the first time that Hackathon participants will hear the challenge statement they will be solving during the 10-hour hack. Also, a word from our sponsors.

9 AM: Registration Closes and HACKATHON BEGINS

12 PM: Lunch

5 PM: Dinner

7 PM: HACKING ENDS

At 7 PM, your project must be submitted and your team must be ready to demonstrate its functionality to the judges panel.

7-7:30 PM: Presentation of demos

Present your projects and see what other teams created!

7:30-7:45 PM: Judging Period

7:45-8:00 PM: Winners Announced and Presentation of Awards

						<Button href="/faq" styleName="goldbutton">Learn More</Button>

    );
  }
}
<|endoftext|>


<commit_before><commit_msg>页签 切换效果<commit_after>angular.module('zfpxMod',['ngRoute']);

angular.module('zfpxMod').config(function($routeProvider){
    $routeProvider.when('/main',{
        templateUrl:'main.html',
        controller:'MainCtrl'
    }).when('/contact',{
        templateUrl:'contact.html',
        controller:'ContactCtrl'
    }).otherwise({
        redirectTo:'/main'
    });
});<|endoftext|>


<commit_before>// Copyright 2018-2019, University of Colorado Boulder

/**
 * A Scenery Node that portrays a thermometer and a triangular indicator of the precise location where the temperature
 * is being sensed. The triangular indicator can be filled with a color to make it more clear what exactly is being
 * measured.
 *
 * @author John Blanco
 */
define( require => {
  'use strict';

  // modules
  const Bounds2 = require( 'DOT/Bounds2' );
  const EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  const energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  const ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
  const MovableDragHandler = require( 'SCENERY_PHET/input/MovableDragHandler' );
  const Node = require( 'SCENERY/nodes/Node' );
  const Property = require( 'AXON/Property' );
  const TemperatureAndColorSensorNode = require( 'SCENERY_PHET/TemperatureAndColorSensorNode' );

  class EFACTemperatureAndColorSensorNode extends Node {

    /**
     * @param {TemperatureAndColorSensor} temperatureAndColorSensor - model element that measures temperature and color
     * at a position in model space
     * @param {Object} [options]
     */
    constructor( temperatureAndColorSensor, options ) {
      super( { cursor: 'pointer' } );

      options = _.extend( {
        modelViewTransform: ModelViewTransform2.createIdentity(),
        draggable: false,
        dragBounds: Bounds2.EVERYTHING
      }, options );

      // @public (read-only) {TemperatureAndColorSensorNode} - public so getBounds functions can be called
      this.temperatureAndColorSensorNode = new TemperatureAndColorSensorNode(
        EFACConstants.WATER_FREEZING_POINT_TEMPERATURE,
        EFACConstants.OLIVE_OIL_BOILING_POINT_TEMPERATURE,
        temperatureAndColorSensor.sensedTemperatureProperty
      );
      this.addChild( this.temperatureAndColorSensorNode );

      // set the fill color of the triangle as the 'sensed color' changes
      Property.multilink(
        [
          temperatureAndColorSensor.activeProperty,
          temperatureAndColorSensor.sensedElementColorProperty
        ],
        ( active, color ) => {
          const fillColor = active ? color : EFACConstants.TEMPERATURE_SENSOR_INACTIVE_COLOR;
          this.temperatureAndColorSensorNode.changeColor( fillColor );
        }
      );

      // move this node when the model element moves
      temperatureAndColorSensor.positionProperty.link( position => {
        this.translation = options.modelViewTransform.modelToViewPosition( position );
      } );

      // add a drag handler if needed
      if ( options.draggable ) {
        this.addInputListener( new MovableDragHandler( temperatureAndColorSensor.positionProperty, {
          modelViewTransform: options.modelViewTransform,
          dragBounds: options.dragBounds.withMaxX(
            options.dragBounds.right - options.modelViewTransform.viewToModelDeltaX( this.width )
          ),
          attach: true,
          startDrag: () => {
            temperatureAndColorSensor.userControlledProperty.set( true );
          },
          endDrag: () => {
            temperatureAndColorSensor.userControlledProperty.set( false );
          }
        } ) );
      }
    }
  }

  return energyFormsAndChanges.register( 'EFACTemperatureAndColorSensorNode', EFACTemperatureAndColorSensorNode );
} );
<commit_msg>TemperatureAndColorSensorNode uses Range instead of min/max temp parameters, see https://github.com/phetsims/scenery-phet/issues/523<commit_after>// Copyright 2018-2019, University of Colorado Boulder

/**
 * A Scenery Node that portrays a thermometer and a triangular indicator of the precise location where the temperature
 * is being sensed. The triangular indicator can be filled with a color to make it more clear what exactly is being
 * measured.
 *
 * @author John Blanco
 */
define( require => {
  'use strict';

  // modules
  const Bounds2 = require( 'DOT/Bounds2' );
  const EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  const energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  const ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
  const MovableDragHandler = require( 'SCENERY_PHET/input/MovableDragHandler' );
  const Node = require( 'SCENERY/nodes/Node' );
  const Property = require( 'AXON/Property' );
  const Range = require( 'DOT/Range' );
  const TemperatureAndColorSensorNode = require( 'SCENERY_PHET/TemperatureAndColorSensorNode' );

  class EFACTemperatureAndColorSensorNode extends Node {

    /**
     * @param {TemperatureAndColorSensor} temperatureAndColorSensor - model element that measures temperature and color
     * at a position in model space
     * @param {Object} [options]
     */
    constructor( temperatureAndColorSensor, options ) {
      super( { cursor: 'pointer' } );

      options = _.extend( {
        modelViewTransform: ModelViewTransform2.createIdentity(),
        draggable: false,
        dragBounds: Bounds2.EVERYTHING
      }, options );

      // @public (read-only) {TemperatureAndColorSensorNode} - public so getBounds functions can be called
      this.temperatureAndColorSensorNode = new TemperatureAndColorSensorNode( new Range(
        EFACConstants.WATER_FREEZING_POINT_TEMPERATURE,
        EFACConstants.OLIVE_OIL_BOILING_POINT_TEMPERATURE
        ), temperatureAndColorSensor.sensedTemperatureProperty
      );
      this.addChild( this.temperatureAndColorSensorNode );

      // set the fill color of the triangle as the 'sensed color' changes
      Property.multilink(
        [
          temperatureAndColorSensor.activeProperty,
          temperatureAndColorSensor.sensedElementColorProperty
        ],
        ( active, color ) => {
          const fillColor = active ? color : EFACConstants.TEMPERATURE_SENSOR_INACTIVE_COLOR;
          this.temperatureAndColorSensorNode.changeColor( fillColor );
        }
      );

      // move this node when the model element moves
      temperatureAndColorSensor.positionProperty.link( position => {
        this.translation = options.modelViewTransform.modelToViewPosition( position );
      } );

      // add a drag handler if needed
      if ( options.draggable ) {
        this.addInputListener( new MovableDragHandler( temperatureAndColorSensor.positionProperty, {
          modelViewTransform: options.modelViewTransform,
          dragBounds: options.dragBounds.withMaxX(
            options.dragBounds.right - options.modelViewTransform.viewToModelDeltaX( this.width )
          ),
          attach: true,
          startDrag: () => {
            temperatureAndColorSensor.userControlledProperty.set( true );
          },
          endDrag: () => {
            temperatureAndColorSensor.userControlledProperty.set( false );
          }
        } ) );
      }
    }
  }

  return energyFormsAndChanges.register( 'EFACTemperatureAndColorSensorNode', EFACTemperatureAndColorSensorNode );
} );
<|endoftext|>


<commit_before>(function() {

    // Show and hide checkbox toggled content

    function showHideCheckboxToggledContent() {

        $(".block-label input[type='checkbox']").each(function() {

            var $checkbox = $(this);
            var $checkboxLabel = $(this).parent();

            var $dataTarget = $checkboxLabel.attr('data-target');

            // Add ARIA attributes

            // If the data-target attribute is defined
            if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {

                // Set aria-controls
                $checkbox.attr('aria-controls', $dataTarget);

                // Set aria-expanded and aria-hidden
                $checkbox.attr('aria-expanded', 'false');
                $('#'+$dataTarget).attr('aria-hidden', 'true');

                // For checkboxes revealing hidden content
                $checkbox.on('click', function() {

                    var state = $(this).attr('aria-expanded') === 'false' ? true : false;

                    // Toggle hidden content
                    $('#'+$dataTarget).toggle();

                    // Update aria-expanded and aria-hidden attributes
                    $(this).attr('aria-expanded', state);
                    $('#'+$dataTarget).attr('aria-hidden', !state);

                });
            }

        });

    }

    // Show & hide radio toggled content

    function showHideRadioToggledContent() {

        $(".block-label input[type='radio']").each(function() {

            var $radio = $(this);
            var $radioGroupName = $(this).attr('name');
            var $radioLabel = $(this).parent();

            var $dataTarget = $radioLabel.attr('data-target');

            // Add ARIA attributes

            // If the data-target attribute is defined
            if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {

                // Set aria-controls
                $radio.attr('aria-controls', $dataTarget);

                // Set aria-expanded and aria-hidden
                $radio.attr('aria-expanded', 'false');
                $('#'+$dataTarget).attr('aria-hidden', 'true');

                // For radio buttons revealing hidden content
                $radio.on('click', function() {

                    var state = $(this).attr('aria-expanded') === 'false' ? true : false;

                    // Toggle hidden content
                    $('#'+$dataTarget).toggle();

                    // Update aria-expanded and aria-hidden attributes
                    $(this).attr('aria-expanded', state);
                    $('#'+$dataTarget).attr('aria-hidden', !state);

                });
            }

            // If the data-target attribute is undefined for a radio button,
            // hide visible data-target content for radio buttons in the same group
            else {

                $radio.on('click', function() {

                    // Select radio buttons in the same group
                    $(".block-label input[name=" + $radioGroupName + "]").each(function() {

                        var groupDataTarget = $(this).parent().attr('data-target');

                        // Hide toggled content
                        $('#'+groupDataTarget).hide();

                        // Update aria-expanded and aria-hidden attributes
                        if ($(this).attr('aria-controls')) {
                            $(this).attr('aria-expanded', 'false');
                        }
                        $('#'+groupDataTarget).attr('aria-hidden', 'true');

                    });

                });
            }

        });

    }

    // Show modal

    function showModal() {

      if ($('.modal').length>0) {

        // Open modal

        $('a[data-toggle=modal]').on('click', function(e) {

          e.preventDefault();
          e.stopPropagation();

          var activeElement = $(this);

          // Grab the target

          var data   = '#' + $(this).attr('data-target');

          // Toggle attribute and get focus

          $(data).attr('aria-hidden', 'false')
            .find('.modal-holder').focus()
            .attr('tabindex', '-1');

        });

        // Close modal only if visible

        function closeModal() {

          $('.modal[aria-hidden=false]').attr('aria-hidden', 'true')
            .find('.modal-holder').blur()
            .attr('tabindex', '0');

        }

        // Stop bubbling

        $('.modal-holder').on('click', function(e) {

          e.stopPropagation();

        });

        $('.modal-close').on('click', function(e) {

          e.stopPropagation();

          closeModal();

        });

        // Document binding events

        $(document).bind({

          click: function(e) {

            closeModal();

          },

          keyup: function(e) {

            if (e.keyCode == 27) {

              closeModal();

            }

          }

        });

      }

    }

    // Toggle tabs

    function toggleTabs() {

      if ($('.tabs').length>0) {

          $('.tabs').tabs();

      }

    }

    // Multiple checkboxes

    function formMultipleCheckboxes() {

        if ($('.form-checkboxes').length > 0) {

            $('.form-checkboxes > li').on('click', function(event) {

                var target   = $(event.target);
                var checkbox = $(this).find("input[type='checkbox']");

                if (target.is("input[type='checkbox']")) {

                    if ($(this).hasClass('selected')) {

                        $(this).removeClass('selected');
                        $(this).removeClass('focused');

                    } else {

                        $(this).addClass('selected');
                        $(this).addClass('focused');
                    }

                    return;
                }

                event.preventDefault();

                if (!checkbox.prop('checked')) {

                    $(this).addClass('selected');
                    $(this).addClass('focused');

                    checkbox.prop('checked', true);

                } else {

                    $(this).removeClass('selected');
                    $(this).removeClass('focused');

                    checkbox.prop('checked', false);

                }

            });

        }

    }

    // Form validation

    function formValidation() {

        $('.validation-list a[href^="#"]').on('click', function(e) {

            e.preventDefault();

            // Declare variables
            var link = $(this),
                id   = link.attr('href');

            // Get focus
            $(id).focus();

            // Smooth movement to error
            $('html, body').animate({

                scrollTop: ($(id).offset().top) - 20

            }, 500);

        });

    }

    // Document ready

    $(document).ready(function() {

        // Turn off jQuery animation
        jQuery.fx.off = true;

        // Use GOV.UK selection-buttons.js to set selected
        // and focused states for block labels
        var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']");

        GOVUK.selectionButtons($blockLabels);

        // Details/summary polyfill
        // See /javascripts/vendor/details.polyfill.js

        // Where .block-label uses the data-target attribute
        // to toggle hidden content

        showHideCheckboxToggledContent();
        showHideRadioToggledContent();

        toggleTabs();
        formValidation();
        formMultipleCheckboxes();
        showModal();

    });

})();<commit_msg>Some improvements to jQuery for modals<commit_after>(function() {

    // Show and hide checkbox toggled content

    function showHideCheckboxToggledContent() {

        $(".block-label input[type='checkbox']").each(function() {

            var $checkbox = $(this);
            var $checkboxLabel = $(this).parent();

            var $dataTarget = $checkboxLabel.attr('data-target');

            // Add ARIA attributes

            // If the data-target attribute is defined
            if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {

                // Set aria-controls
                $checkbox.attr('aria-controls', $dataTarget);

                // Set aria-expanded and aria-hidden
                $checkbox.attr('aria-expanded', 'false');
                $('#'+$dataTarget).attr('aria-hidden', 'true');

                // For checkboxes revealing hidden content
                $checkbox.on('click', function() {

                    var state = $(this).attr('aria-expanded') === 'false' ? true : false;

                    // Toggle hidden content
                    $('#'+$dataTarget).toggle();

                    // Update aria-expanded and aria-hidden attributes
                    $(this).attr('aria-expanded', state);
                    $('#'+$dataTarget).attr('aria-hidden', !state);

                });
            }

        });

    }

    // Show & hide radio toggled content

    function showHideRadioToggledContent() {

        $(".block-label input[type='radio']").each(function() {

            var $radio = $(this);
            var $radioGroupName = $(this).attr('name');
            var $radioLabel = $(this).parent();

            var $dataTarget = $radioLabel.attr('data-target');

            // Add ARIA attributes

            // If the data-target attribute is defined
            if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {

                // Set aria-controls
                $radio.attr('aria-controls', $dataTarget);

                // Set aria-expanded and aria-hidden
                $radio.attr('aria-expanded', 'false');
                $('#'+$dataTarget).attr('aria-hidden', 'true');

                // For radio buttons revealing hidden content
                $radio.on('click', function() {

                    var state = $(this).attr('aria-expanded') === 'false' ? true : false;

                    // Toggle hidden content
                    $('#'+$dataTarget).toggle();

                    // Update aria-expanded and aria-hidden attributes
                    $(this).attr('aria-expanded', state);
                    $('#'+$dataTarget).attr('aria-hidden', !state);

                });
            }

            // If the data-target attribute is undefined for a radio button,
            // hide visible data-target content for radio buttons in the same group
            else {

                $radio.on('click', function() {

                    // Select radio buttons in the same group
                    $(".block-label input[name=" + $radioGroupName + "]").each(function() {

                        var groupDataTarget = $(this).parent().attr('data-target');

                        // Hide toggled content
                        $('#'+groupDataTarget).hide();

                        // Update aria-expanded and aria-hidden attributes
                        if ($(this).attr('aria-controls')) {
                            $(this).attr('aria-expanded', 'false');
                        }
                        $('#'+groupDataTarget).attr('aria-hidden', 'true');

                    });

                });
            }

        });

    }

    // Show modal

    function showModal() {

      if ($('.modal').length>0) {

        // Open modal

        $('a[data-toggle=modal]').on('click', function(e) {

          e.preventDefault();
          e.stopPropagation();

          var data = '#' + $(this).attr('data-target');

          openModal(data); // Pass data value into function

        });

        // Open modal

        function openModal(e,data) {

          $(data).attr('aria-hidden', 'false')
            .find('.modal-content').focus()
            .attr('tabindex', '-1');

        }

        // Close modal only if visible

        function closeModal() {

          $('.modal[aria-hidden=false]').attr('aria-hidden', 'true')
            .find('.modal-content').blur()
            .attr('tabindex', '0');

        }

        // Stop bubbling

        $('.modal-holder').on('click', function(e) {

          e.stopPropagation();

        });

        $('.modal-close').on('click', function(e) {

          e.stopPropagation();

          closeModal();

        });

        // Document binding events

        $(document).bind({

          click: function(e) {

            closeModal();

          },

          keyup: function(e) {

            if (e.keyCode == 27) {

              closeModal();

            }

          }

        });

      }

    }

    // Toggle tabs

    function toggleTabs() {

      if ($('.tabs').length>0) {

          $('.tabs').tabs();

      }

    }

    // Multiple checkboxes

    function formMultipleCheckboxes() {

        if ($('.form-checkboxes').length > 0) {

            $('.form-checkboxes > li').on('click', function(event) {

                var target   = $(event.target);
                var checkbox = $(this).find("input[type='checkbox']");

                if (target.is("input[type='checkbox']")) {

                    if ($(this).hasClass('selected')) {

                        $(this).removeClass('selected');
                        $(this).removeClass('focused');

                    } else {

                        $(this).addClass('selected');
                        $(this).addClass('focused');
                    }

                    return;
                }

                event.preventDefault();

                if (!checkbox.prop('checked')) {

                    $(this).addClass('selected');
                    $(this).addClass('focused');

                    checkbox.prop('checked', true);

                } else {

                    $(this).removeClass('selected');
                    $(this).removeClass('focused');

                    checkbox.prop('checked', false);

                }

            });

        }

    }

    // Form validation

    function formValidation() {

        $('.validation-list a[href^="#"]').on('click', function(e) {

            e.preventDefault();

            // Declare variables
            var link = $(this),
                id   = link.attr('href');

            // Get focus
            $(id).focus();

            // Smooth movement to error
            $('html, body').animate({

                scrollTop: ($(id).offset().top) - 20

            }, 500);

        });

    }

    // Document ready

    $(document).ready(function() {

        // Turn off jQuery animation
        jQuery.fx.off = true;

        // Use GOV.UK selection-buttons.js to set selected
        // and focused states for block labels
        var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']");

        GOVUK.selectionButtons($blockLabels);

        // Details/summary polyfill
        // See /javascripts/vendor/details.polyfill.js

        // Where .block-label uses the data-target attribute
        // to toggle hidden content

        showHideCheckboxToggledContent();
        showHideRadioToggledContent();

        toggleTabs();
        formValidation();
        formMultipleCheckboxes();
        showModal();

    });

})();<|endoftext|>


<commit_before>// Tests are placed alongside files under test.
// This file does the following:
// 1. Sets the environment to 'production' so that
//    dev-specific babel config in .babelrc doesn't run.
// 2. Disables Webpack-specific features that Mocha doesn't understand.
// 3. Registers babel for transpiling our code for testing.

// This assures the .babelrc dev config (which includes
// hot module reloading code) doesn't apply for tests.
process.env.NODE_ENV = 'production';

// Disable webpack-specific features for tests since
// Mocha doesn't know what to do with them.
require.extensions['.css'] = () => {
  return null;
};
require.extensions['.png'] = () => {
  return null;
};
require.extensions['.jpg'] = () => {
  return null;
};

// Register babel so that it will transpile ES6 to ES5
// before our tests run.
require('babel-register')();
<commit_msg>Added .scss as excluded feature for tests<commit_after>// Tests are placed alongside files under test.
// This file does the following:
// 1. Sets the environment to 'production' so that
//    dev-specific babel config in .babelrc doesn't run.
// 2. Disables Webpack-specific features that Mocha doesn't understand.
// 3. Registers babel for transpiling our code for testing.

// This assures the .babelrc dev config (which includes
// hot module reloading code) doesn't apply for tests.
process.env.NODE_ENV = 'production';

// Disable webpack-specific features for tests since
// Mocha doesn't know what to do with them.
['.css', '.scss', '.png', '.jpg'].forEach(ext => {
  require.extensions[ext] = () => null;
});

// Register babel so that it will transpile ES6 to ES5
// before our tests run.
require('babel-register')();
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var Mex = {
	'account':{
		'id':101,
		'username':'Mario Rossi'
	},
	'show':{
		'message':{
			'message_id':{
				'social':['Twitter','Facebook','Google+']
			}
		}
	}
};

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));

/*app.engine('json',function(req,res,next){
	res.set('Content-Type','application/json');
	next();
});*/

app.use('/',function(req,res,next){
	res.send(req.param.Mex);
	next();
});

app.post('/message/social',function(req,res){
	console.log(req.body.social);
	res.json(req.body.social);
});

app.put('/message/message_id',function(req,res){
});

app.post('/account',function(req,res){
	console.log(req.body.account);
	res.json(req.body.account);
});

app.get('/account/:username',function(req,res){
	res.send(Mex[req.param.username]);
	console.log(Mex.account.username);
});

app.put('/account/:id',function(req,res){
});

app.get('/show/message/message_id',function(req,res){
	res.send(Mex[req.param.message_id]);
	console.log(Mex.show.message.message_id);
});

app.get('/show/message/message_id/social',function(req,res){
	res.send(Mex[req.param.social]);
	console.log(Mex.show.message.message_id.social);
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});<commit_msg>return Json account and social<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var Mex = {
	'account':{
		'id':Number,
		'username':String
	},
	'show':{
		'message':{
			'message_id':{
				'social':['Twitter','Facebook','Google+']
			}
		}
	}
};

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));

app.post('/message/social',function(req,res){
	console.log(req.body.social);
	res.json({social:req.body.social});
});

app.put('/message/message_id',function(req,res){
});

app.post('/account',function(req,res){
	console.log(req.body.account);
	res.json({id:req.body.id, username:req.body.username});
});

app.get('/account/username',function(req,res){
	res.send(Mex[req.param.username]);
	console.log(Mex.account.username);
});

app.put('/account/id',function(req,res){
});

app.get('/show/message/message_id',function(req,res){
	res.send(Mex[req.param.message_id]);
	console.log(Mex.show.message.message_id);
});

app.get('/show/message/message_id/social',function(req,res){
	res.send(Mex[req.param.social]);
	console.log(Mex.show.message.message_id.social);
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});<|endoftext|>


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

var settings = {
  debugMaxLength: 10000000,
  autoInstallModules: true,
  httpAdminRoot: '/red',
  httpNodeRoot: '/',
  nodesDir: path.join(__dirname, 'nodes'),
  functionGlobalContext: { },    // enables global context
  httpNodeCors: {
    origin: "*",
    methods: "GET,PUT,POST,DELETE"
  }
};

if (process.env.MONGO_URI) {
  settings.storageModule = require('./mongostorage');
  settings.mongoUrl = process.env.MONGO_URI;
  settings.mongoAppname = 'enebular';
} else {
  settings.userDir = path.join(__dirname);
}

module.exports = settings;<commit_msg>Enabled MONGOLAB_URI env<commit_after>var path = require('path');

var settings = {
  debugMaxLength: 10000000,
  autoInstallModules: true,
  httpAdminRoot: '/red',
  httpNodeRoot: '/',
  nodesDir: path.join(__dirname, 'nodes'),
  functionGlobalContext: { },    // enables global context
  httpNodeCors: {
    origin: "*",
    methods: "GET,PUT,POST,DELETE"
  }
};

if (process.env.MONGO_URI || process.env.MONGOLAB_URI) {
  settings.storageModule = require('./mongostorage');
  settings.mongoUrl = process.env.MONGO_URI || process.env.MONGOLAB_URI;
  settings.mongoAppname = 'enebular';
} else {
  settings.userDir = path.join(__dirname);
}

module.exports = settings;<|endoftext|>