<commit_before>/**
 * Created by chet on 7/18/15.
 */
var ui;
var carousel_items = [];
var prodList = [];
var dataImageLayer;

$(document).ready(function() {
    viewer = new Cesium.Viewer('cesiumContainer', {
        //imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
        //    url: '//server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer'
        //}),
        //imageryProvider: new Cesium.TileMapServiceImageryProvider({
        //    url: "../webGL2015/data/bluemarble/",
        //    fileExtension: "jpg"
        //}),
        //imageryProvider: new Cesium.TileMapServiceImageryProvider({
        //    url: "/Earth_Data/bluemmarble/",
        //    fileExtension: "jpg"
        //}),
        //imageryProvider: new Cesium.TileMapServiceImageryProvider({
        //    url: "js/cesium/Assets/Textures/NaturalEarthII",
        //    fileExtension: "jpg"
        //}),
        //terrainProvider: new Cesium.CesiumTerrainProvider({
        //    url: '//assets.agi.com/stk-terrain/world',
        //    requestVertexNormals: true
        //}),
        //terrainProvider: new Cesium.CesiumTerrainProvider({
        //    url: 'http://10.2.3.1/World_DEM',
        //    requestVertexNormals: true
        //}),
        //imageryProvider: new Cesium.TileMapServiceImageryProvider({
        //    url: "/Earth_Data/world_png",
        //    fileExtension: "png"
        //}),
        baseLayerPicker: false,
        animation: false,
        fullscreenButton: false,
        geocoder: false,
        homeButton: false,
        infoBox: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        timeline: false
    });
    //控制地球的初始视野为中国
    // alert('i am here');
    viewer.scene.camera.viewRectangle(Cesium.Rectangle.fromDegrees(100.5, -10.5, 130.0, 89.0));
    //viewer.scene.camera.viewRectangle(Cesium.Rectangle.fromDegrees(100.5, -19.5, 130.0, 70.0));
    // viewer.scene.camera.viewRectangle(new Cesium.Rectangle(124.5, -9.5, 140.0, 70.0));
    //控制球体下部的图层等信息不显示，比如cesium的图标和bing地图的credit信息
    $('.cesium-viewer-bottom').hide();
    ui = new UI();

    initializeCarousel();

    ui.carousel();
    ui.data();

    //prepareLayers();
    initializeSlider();
    initializeDatatree();

    //初始化日期标签，在卫星追踪hud－选择卫星显示框中
    initializeDatelabel();

    //显示鼠标坐标
    viewer.scene.primitives.add(mouselabels);
    var ellipsoid = viewer.scene.globe.ellipsoid;
    var scene = viewer.scene;
    //handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
    showmousePosandsatlabel(scene, mouselabels, ellipsoid);
    //双击左键回到最初的视角
    backOriginalView(scene);

    //生成全局的Balloon widget
    var balloonContainer = document.createElement('div');
    balloonContainer.className = 'cesium-viewer-balloonContainer';
    viewer.container.appendChild(balloonContainer);
    var balloon = new Cesium.Balloon(balloonContainer, viewer.scene);
    balloon.viewModel.computeScreenSpacePosition = function(value, result) {
        result.x = value.x;
        result.y = viewer.container.clientHeight - value.y;
        return result;
    };
    balloonViewModel = balloon.viewModel;

    ////初始化更新卫星数据时显示的对话框
    //initialUpdateatsDialog();

    satelliteClickDetails(viewer.scene);

    //初始化右侧div中的tabs标签
    var tabs = $("#rightInfoList_div").tabs();

    //临时添加卫星过境时所采集的数据
    //addPringonEarth();
    /**
     * 每隔1000ms更新一次，卫星billboard的位置，让其动态显示
     */
    setInterval(function() {
        var now = Cesium.JulianDate.now(); // TODO> we'll want to base on tick and time-speedup

        if (satrecs.length > 0) {
            var sats = updateSatrecsPosVel(satrecs, now); // TODO: sgp4 needs minutesSinceEpoch from timeclock
            updateSatelliteEntityPos(sats.positions);

            // propagate [GLOBAL]
            satrecs = sats.newSatrecs;

            //更新卫星轨道entity的位置（此时要求精度不是那么高，暂时不用更新轨道entity的位置）
            //updateOrbitPos(sats.newSatrecs);

            //当没有跟踪卫星时，把没有选中跟踪卫星的提示信息的div显示出来，同时把显示卫星信息的table隐藏掉
            if (!viewer.trackedEntity) {
                if ($('#satInfoTable').is(':visible')) {
                    $("#satInfoTable").hide();
                }
                if (!$('#satinfo-message').is(':visible')) {
                    $("#satinfo-message").show();
                }

            } else {
                //根据跟踪卫星entity的id去显示该卫星的详细信息
                var satNoradId = viewer.trackedEntity.id;
                displayStats(sats, satNoradId);
            }
        }

    }, CALC_INTERVAL_MS);
    /**
     * 每次更新卫星billboard的位置后，不会立即显示，需要重新绘制canvas上变化的元素，
     * 这样更新后的卫星billboard才会及时显示在球体周围
     */
    // Loop the clock
    (function tick() {
        var scene = viewer.scene;
        scene.initializeFrame(); // takes optional 'time' argument

        // changeBallon(balloonViewModel, clickposition);

        scene.render();
        Cesium.requestAnimationFrame(tick);
    }());
});<commit_msg> 主文件中加了判断Ballon是否显示，显示则不断更新其位置，不显示就不用更新，省资源<commit_after>/**
 * Created by chet on 7/18/15.
 */
var ui;
var carousel_items = [];
var prodList = [];
var dataImageLayer;

$(document).ready(function() {
    viewer = new Cesium.Viewer('cesiumContainer', {
        //imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
        //    url: '//server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer'
        //}),
        //imageryProvider: new Cesium.TileMapServiceImageryProvider({
        //    url: "../webGL2015/data/bluemarble/",
        //    fileExtension: "jpg"
        //}),
        //imageryProvider: new Cesium.TileMapServiceImageryProvider({
        //    url: "/Earth_Data/bluemmarble/",
        //    fileExtension: "jpg"
        //}),
        //imageryProvider: new Cesium.TileMapServiceImageryProvider({
        //    url: "js/cesium/Assets/Textures/NaturalEarthII",
        //    fileExtension: "jpg"
        //}),
        //terrainProvider: new Cesium.CesiumTerrainProvider({
        //    url: '//assets.agi.com/stk-terrain/world',
        //    requestVertexNormals: true
        //}),
        //terrainProvider: new Cesium.CesiumTerrainProvider({
        //    url: 'http://10.2.3.1/World_DEM',
        //    requestVertexNormals: true
        //}),
        //imageryProvider: new Cesium.TileMapServiceImageryProvider({
        //    url: "/Earth_Data/world_png",
        //    fileExtension: "png"
        //}),
        baseLayerPicker: false,
        animation: false,
        fullscreenButton: false,
        geocoder: false,
        homeButton: false,
        infoBox: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        timeline: false
    });
    //控制地球的初始视野为中国
    // alert('i am here');
    viewer.scene.camera.viewRectangle(Cesium.Rectangle.fromDegrees(100.5, -10.5, 130.0, 89.0));
    //viewer.scene.camera.viewRectangle(Cesium.Rectangle.fromDegrees(100.5, -19.5, 130.0, 70.0));
    // viewer.scene.camera.viewRectangle(new Cesium.Rectangle(124.5, -9.5, 140.0, 70.0));
    //控制球体下部的图层等信息不显示，比如cesium的图标和bing地图的credit信息
    $('.cesium-viewer-bottom').hide();
    ui = new UI();

    initializeCarousel();

    ui.carousel();
    ui.data();

    //prepareLayers();
    initializeSlider();
    initializeDatatree();

    //初始化日期标签，在卫星追踪hud－选择卫星显示框中
    initializeDatelabel();

    //显示鼠标坐标
    viewer.scene.primitives.add(mouselabels);
    var ellipsoid = viewer.scene.globe.ellipsoid;
    var scene = viewer.scene;
    //handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
    showmousePosandsatlabel(scene, mouselabels, ellipsoid);
    //双击左键回到最初的视角
    backOriginalView(scene);

    //生成全局的Balloon widget
    var balloonContainer = document.createElement('div');
    balloonContainer.className = 'cesium-viewer-balloonContainer';
    viewer.container.appendChild(balloonContainer);
    var balloon = new Cesium.Balloon(balloonContainer, viewer.scene);
    balloon.viewModel.computeScreenSpacePosition = function(value, result) {
        result.x = value.x;
        result.y = viewer.container.clientHeight - value.y;
        return result;
    };
    balloonViewModel = balloon.viewModel;

    ////初始化更新卫星数据时显示的对话框
    //initialUpdateatsDialog();

    satelliteClickDetails(viewer.scene);

    //初始化右侧div中的tabs标签
    var tabs = $("#rightInfoList_div").tabs();

    //临时添加卫星过境时所采集的数据
    //addPringonEarth();
    /**
     * 每隔1000ms更新一次，卫星billboard的位置，让其动态显示
     */
    setInterval(function() {
        var now = Cesium.JulianDate.now(); // TODO> we'll want to base on tick and time-speedup

        if (satrecs.length > 0) {
            var sats = updateSatrecsPosVel(satrecs, now); // TODO: sgp4 needs minutesSinceEpoch from timeclock
            updateSatelliteEntityPos(sats.positions);

            // propagate [GLOBAL]
            satrecs = sats.newSatrecs;

            //更新卫星轨道entity的位置（此时要求精度不是那么高，暂时不用更新轨道entity的位置）
            //updateOrbitPos(sats.newSatrecs);

            //当没有跟踪卫星时，把没有选中跟踪卫星的提示信息的div显示出来，同时把显示卫星信息的table隐藏掉
            if (!viewer.trackedEntity) {
                if ($('#satInfoTable').is(':visible')) {
                    $("#satInfoTable").hide();
                }
                if (!$('#satinfo-message').is(':visible')) {
                    $("#satinfo-message").show();
                }

            } else {
                //根据跟踪卫星entity的id去显示该卫星的详细信息
                var satNoradId = viewer.trackedEntity.id;
                displayStats(sats, satNoradId);
            }
        }

    }, CALC_INTERVAL_MS);

    function changeBallon(balloonViewModel, clickposition) {
        if (balloonViewModel) {
            if ('position' in balloonViewModel) {
                if (balloonViewModel.position && clickposition) {
                    var cart2 = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, clickposition);
                    balloonViewModel.position = cart2;
                    balloonViewModel.update();
                }
            }
        }
    }
    /**
     * 每次更新卫星billboard的位置后，不会立即显示，需要重新绘制canvas上变化的元素，
     * 这样更新后的卫星billboard才会及时显示在球体周围
     */
    // Loop the clock
    (function tick() {
        var scene = viewer.scene;
        scene.initializeFrame(); // takes optional 'time' argument

        if(balloonViewModel.showBalloon == true){
            changeBallon(balloonViewModel, clickposition);
        }

        scene.render();
        Cesium.requestAnimationFrame(tick);
    }());
});<|endoftext|>


<commit_before>/**
 * Created by i68066 on 11/16/15.
 */
var sentence = [],
	story = '',
	answer;
$.urlParam = function (name) {
	var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return null;
	}
	else {
		return results[1] || 0;
	}
};

$(function () {
	$("#sortable").sortable({
		stop: function(){correctSequence()}
	}).disableSelection();

	story = $.urlParam('story');
	story = decodeURI(story);
	story = story.replace(/\+/g, " ").replace(/%0D%0A/g, " ").replace(/%2C/g, ",").replace(/%3F/g, "?").replace(/%27/g, "'").replace(/%E2%80%94/g, "—");
	sentence = story.split(".").map(function (a) {
		return a.concat(".").trim()
	});

	function shuffle(array) {
		var currentIndex = array.length, temporaryValue, randomIndex ;

		// While there remain elements to shuffle...
		while (0 !== currentIndex) {

			// Pick a remaining element...
			randomIndex = Math.floor(Math.random() * currentIndex);
			currentIndex -= 1;

			// And swap it with the current element.
			temporaryValue = array[currentIndex];
			array[currentIndex] = array[randomIndex];
			array[randomIndex] = temporaryValue;
		}

		return array;
	}

	sentence.pop();

	shuffle(sentence);

	for (var i = 0; i < sentence.length; i++) {
		$('#sortable').append('
' + sentence[i] + '
')
	}

});

function correctSequence (){
	var arr = [];
	$('#sortable > div').each(function () {
		arr.push($(this).text())
	});
	answer = arr.join('');
	answer = answer.replace(/\s/g, '');
	story = story.replace(/\s/g, '');
	story == answer ? alert('yay!') : '';
}

//TODO see if we can stay on the same page but take out the "story" parameters
//TODO actually randomize the sentences by popping and unshifting everyother sentence
//TODO make a check for the correct sequence<commit_msg>history push<commit_after>/**
 * Created by i68066 on 11/16/15.
 */
var sentence = [],
	story = '',
	answer;
$.urlParam = function (name) {
	var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return null;
	}
	else {
		return results[1] || 0;
	}
};

$(function () {
	$("#sortable").sortable({
		stop: function(){correctSequence()}
	}).disableSelection();

	story = $.urlParam('story');
	story = decodeURI(story);
	story = story.replace(/\+/g, " ").replace(/%0D%0A/g, " ").replace(/%2C/g, ",").replace(/%3F/g, "?").replace(/%27/g, "'").replace(/%E2%80%94/g, "—");
	sentence = story.split(".").map(function (a) {
		return a.concat(".").trim()
	});

	function shuffle(array) {
		var currentIndex = array.length, temporaryValue, randomIndex ;

		// While there remain elements to shuffle...
		while (0 !== currentIndex) {

			// Pick a remaining element...
			randomIndex = Math.floor(Math.random() * currentIndex);
			currentIndex -= 1;

			// And swap it with the current element.
			temporaryValue = array[currentIndex];
			array[currentIndex] = array[randomIndex];
			array[randomIndex] = temporaryValue;
		}

		return array;
	}

	sentence.pop();

	shuffle(sentence);

	for (var i = 0; i < sentence.length; i++) {
		$('#sortable').append('
' + sentence[i] + '
')
	}

	history.pushState({}, '', 'whathappenednext.html' );

});

function correctSequence (){
	var arr = [];
	$('#sortable > div').each(function () {
		arr.push($(this).text())
	});
	answer = arr.join('');
	answer = answer.replace(/\s/g, '');
	story = story.replace(/\s/g, '');
	story == answer ? alert('yay!') : '';
}

//TODO see if we can stay on the same page but take out the "story" parameters
//TODO actually randomize the sentences by popping and unshifting everyother sentence
//TODO make a check for the correct sequence<|endoftext|>


<commit_before>var Settings = require('./settings'),
	LayerUI = require('./ui/layer_view'),
	IconButton = require('./icon_button'),
	style = require('./utils').style,
	Theme = require('./theme'),
	STORAGE_PREFIX = require('./utils').STORAGE_PREFIX,
	NumberUI = require('./ui/number')
	;

function LayerCabinet(data, dispatcher) {
	var layer_store = data.get('layers');

	var div = document.createElement('div');

	var top = document.createElement('div');
	top.style.cssText = 'margin: 0px; top: 0; left: 0; height: ' + Settings.MARKER_TRACK_HEIGHT + 'px';
	// top.style.textAlign = 'right';

	var layer_scroll = document.createElement('div');
	style(layer_scroll, {
		position: 'absolute',
		top: Settings.MARKER_TRACK_HEIGHT + 'px',
		// height: (Settings.height - Settings.MARKER_TRACK_HEIGHT) + 'px'
		left: 0,
		right: 0,
		bottom: 0,
		overflow: 'hidden'
	});

	div.appendChild(layer_scroll);

	var playing = false;

	var play_button = new IconButton(16, 'play', 'play', dispatcher);
	play_button.onClick(function(e) {
		e.preventDefault();
		dispatcher.fire('controls.toggle_play');
	});

	var stop_button = new IconButton(16, 'stop', 'stop', dispatcher);
	stop_button.onClick(function(e) {
		dispatcher.fire('controls.stop');
	});

	var undo_button = new IconButton(16, 'undo', 'undo', dispatcher);
	undo_button.onClick(function() {
		dispatcher.fire('controls.undo');
	});

	var redo_button = new IconButton(16, 'repeat', 'redo', dispatcher);
	redo_button.onClick(function() {
		dispatcher.fire('controls.redo');
	});

	var range = document.createElement('input');
	range.type = "range";
	range.min = 0;
	range.max = 100;

	range.value = convertTimeToPercent(Settings.time_scale);

	range.step = 0.01;
	style(range, {
		width: '70px'
	});

	var draggingRange = 0;

	range.addEventListener('mousedown', function() {
		draggingRange = 1;
	});

	range.addEventListener('mouseup', function() {
		draggingRange = 0;
		changeRange();
	});

	range.addEventListener('mousemove', function() {
		if (!draggingRange) return;
		changeRange();
	});

	div.appendChild(top);

	var time_options = {
		min: 0,
		step: 0.01
	};
	var currentTime = new NumberUI(time_options);
	var totalTime = new NumberUI(time_options);

	var currentTimeStore = data.get('ui:currentTime');
	var totalTimeStore = data.get('ui:totalTime');

	// UI2StoreBind(view, datastore) {
	// 	view.onChange.do(function(v) {
	// 		datastore.value = view;
	// 	})

	// 	datastore.onChange.do(function(v) {
	// 		view.setValue = v;
	// 	})
	// }

	currentTime.onChange.do(function(value, done) {
		dispatcher.fire('time.update', value);
		// repaint();
	});

	totalTime.onChange.do(function(value, done) {
		totalTimeStore.value = value;
		// repaint();
	});

	// Play Controls
	top.appendChild(currentTime.dom);
	top.appendChild(document.createTextNode('/')); // 0:00:00 / 0:10:00
	top.appendChild(totalTime.dom)
	top.appendChild(play_button.dom);
	top.appendChild(stop_button.dom);
	top.appendChild(range);

	var operations_div = document.createElement('div');
	style(operations_div, {
		marginTop: '4px',
		// borderBottom: '1px solid ' + Theme.b
	});
	top.appendChild(operations_div);
	// top.appendChild(document.createElement('br'));

	// open _alt
	var file_open = new IconButton(16, 'folder_open_alt', 'Open', dispatcher);
	operations_div.appendChild(file_open.dom);

	function populateOpen() {
		while (dropdown.length) {
			dropdown.remove(0);
		}

		var option;
		option = document.createElement('option');
		option.text = 'New';
		option.value = '*new*';
		dropdown.add(option);

		option = document.createElement('option');
		option.text = 'Import JSON';
		option.value = '*import*';
		dropdown.add(option);

		// Doesn't work
		// option = document.createElement('option');
		// option.text = 'Select File';
		// option.value = '*select*';
		// dropdown.add(option);

		option = document.createElement('option');
		option.text = '==Open==';
		option.disabled = true;
		option.selected = true;
		dropdown.add(option);

		var regex = new RegExp(STORAGE_PREFIX + '(.*)');
		for (var key in localStorage) {
			// console.log(key);

			var match = regex.exec(key);
			if (match) {
				option = document.createElement('option');
				option.text = match[1];

				dropdown.add(option);
			}
		}

	}

	// listen on other tabs
	window.addEventListener('storage', function(e) {
		var regex = new RegExp(STORAGE_PREFIX + '(.*)');
		if (regex.exec(e.key)) {
			populateOpen();
		}
	});

	dispatcher.on('save:done', populateOpen);

	var dropdown = document.createElement('select');

	style(dropdown, {
		position: 'absolute',
		// right: 0,
		// margin: 0,
		opacity: 0,
		width: '16px',
		height: '16px',
		// zIndex: 1,
	});

	dropdown.addEventListener('change', function(e) {
		// console.log('changed', dropdown.length, dropdown.value);

		switch (dropdown.value) {
			case '*new*':
				dispatcher.fire('new');
				break;
			case '*import*':
				dispatcher.fire('import');
				break;
			case '*select*':
				dispatcher.fire('openfile');
				break;
			default:
				dispatcher.fire('open', dropdown.value);
				break;
		}
	});

	file_open.dom.insertBefore(dropdown, file_open.dom.firstChild);

	populateOpen();

	// // json import
	// var import_json = new IconButton(16, 'signin', 'Import JSON', dispatcher);
	// operations_div.appendChild(import_json.dom);
	// import_json.onClick(function() {
	// 	dispatcher.fire('import');
	// });

	// // new
	// var file_alt = new IconButton(16, 'file_alt', 'New', dispatcher);
	// operations_div.appendChild(file_alt.dom);

	// save
	var save = new IconButton(16, 'save', 'Save', dispatcher);
	operations_div.appendChild(save.dom);
	save.onClick(function() {
		dispatcher.fire('save');
	});

	// save as
	var save_as = new IconButton(16, 'paste', 'Save as', dispatcher);
	operations_div.appendChild(save_as.dom);
	save_as.onClick(function() {
		dispatcher.fire('save_as');
	});

	// download json (export)
	var download_alt = new IconButton(16, 'download_alt', 'Download / Export JSON to file', dispatcher);
	operations_div.appendChild(download_alt.dom);
	download_alt.onClick(function() {
		dispatcher.fire('export');
	});

	var upload_alt = new IconButton(16, 'upload_alt', 'Load from file', dispatcher);
	operations_div.appendChild(upload_alt.dom);
	upload_alt.onClick(function() {
		dispatcher.fire('openfile');
	});

	var span = document.createElement('span');
	span.style.width = '20px';
	span.style.display = 'inline-block';
	operations_div.appendChild(span);

	operations_div.appendChild(undo_button.dom);
	operations_div.appendChild(redo_button.dom);
	operations_div.appendChild(document.createElement('br'));

	// Cloud Download / Upload edit pencil

	/*
	// // show layer
	// var eye_open = new IconButton(16, 'eye_open', 'eye_open', dispatcher);
	// operations_div.appendChild(eye_open.dom);

	// // hide / disable layer
	// var eye_close = new IconButton(16, 'eye_close', 'eye_close', dispatcher);
	// operations_div.appendChild(eye_close.dom);

	// remove layer
	var minus = new IconButton(16, 'minus', 'minus', dispatcher);
	operations_div.appendChild(minus.dom);

	// check
	var ok = new IconButton(16, 'ok', 'ok', dispatcher);
	operations_div.appendChild(ok.dom);

	// cross
	var remove = new IconButton(16, 'remove', 'remove', dispatcher);
	operations_div.appendChild(remove.dom);

	*/

	// range.addEventListener('change', changeRange);

	function convertPercentToTime(t) {
		var min_time = 1;
		var max_time = 10 * 60; // 10 minutes
		var v = 500 / (t * (max_time - min_time) + min_time);
		return v;
	}

	function convertTimeToPercent(v) {
		var min_time = 1;
		var max_time = 10 * 60; // 10 minutes
		var t  = ((500 / v) - min_time)  / (max_time - min_time);
		return t;
	}

	function changeRange() {
		var t = range.value / range.max;
		// 800px - 10 minutes - 100%
		// 50% - 5 minutes
		// 10*
		// 100% - 60s / 1 second

		// TODO: scale time correctly

		dispatcher.fire('update.scale', convertPercentToTime(t));
	}

	var layer_uis = [], visible_layers = 0;
	var unused_layers = [];

	this.layers = layer_uis;

	this.setControlStatus = function(v) {
		playing = v;
		if (playing) {
			play_button.setIcon('pause');
			play_button.setTip('pause');
		}
		else {
			play_button.setIcon('play');
			play_button.setTip('play');
		}
	};

	this.setState = function(state) {

		layer_store = state;
		layers = layer_store.value;
		// layers = state;
		console.log(layer_uis.length, layers);
		var i, layer;
		for (i = 0; i < layers.length; i++) {
			layer = layers[i];

			if (!layer_uis[i]) {
				var layer_ui;
				if (unused_layers.length) {
					layer_ui = unused_layers.pop();
					layer_ui.dom.style.display = 'block';
				} else {
					// new
					layer_ui = new LayerUI(layer, dispatcher);
					layer_scroll.appendChild(layer_ui.dom);
				}
				layer_uis.push(layer_ui);
			}

			// layer_uis[i].setState(layer);
		}

		console.log('Total layers (view, hidden, total)', layer_uis.length, unused_layers.length,
			layer_uis.length + unused_layers.length);

	};

	function repaint(s) {

		s = currentTimeStore.value;
		currentTime.setValue(s);
		totalTime.setValue(totalTimeStore.value);
		currentTime.paint();
		totalTime.paint();

		var i;

		s = s || 0;
		for (i = layer_uis.length; i-- > 0;) {
			// quick hack
			if (i >= layers.length) {
				layer_uis[i].dom.style.display = 'none';
				unused_layers.push(layer_uis.pop());
				continue;
			}

			// console.log('yoz', states.get(i).value);
			layer_uis[i].setState(layers[i], layer_store.get(i));
			// layer_uis[i].setState('layers'+':'+i);
			layer_uis[i].repaint(s);
		}

		visible_layers = layer_uis.length;

	}

	this.repaint = repaint;
	this.setState(layer_store);

	this.scrollTo = function(x) {
		layer_scroll.scrollTop = x * (layer_scroll.scrollHeight - layer_scroll.clientHeight);
	};

	this.dom = div;

	repaint();
}

module.exports = LayerCabinet;<commit_msg>Repaint when total time changes<commit_after>var Settings = require('./settings'),
	LayerUI = require('./ui/layer_view'),
	IconButton = require('./icon_button'),
	style = require('./utils').style,
	Theme = require('./theme'),
	STORAGE_PREFIX = require('./utils').STORAGE_PREFIX,
	NumberUI = require('./ui/number')
	;

function LayerCabinet(data, dispatcher) {
	var layer_store = data.get('layers');

	var div = document.createElement('div');

	var top = document.createElement('div');
	top.style.cssText = 'margin: 0px; top: 0; left: 0; height: ' + Settings.MARKER_TRACK_HEIGHT + 'px';
	// top.style.textAlign = 'right';

	var layer_scroll = document.createElement('div');
	style(layer_scroll, {
		position: 'absolute',
		top: Settings.MARKER_TRACK_HEIGHT + 'px',
		// height: (Settings.height - Settings.MARKER_TRACK_HEIGHT) + 'px'
		left: 0,
		right: 0,
		bottom: 0,
		overflow: 'hidden'
	});

	div.appendChild(layer_scroll);

	var playing = false;

	var play_button = new IconButton(16, 'play', 'play', dispatcher);
	play_button.onClick(function(e) {
		e.preventDefault();
		dispatcher.fire('controls.toggle_play');
	});

	var stop_button = new IconButton(16, 'stop', 'stop', dispatcher);
	stop_button.onClick(function(e) {
		dispatcher.fire('controls.stop');
	});

	var undo_button = new IconButton(16, 'undo', 'undo', dispatcher);
	undo_button.onClick(function() {
		dispatcher.fire('controls.undo');
	});

	var redo_button = new IconButton(16, 'repeat', 'redo', dispatcher);
	redo_button.onClick(function() {
		dispatcher.fire('controls.redo');
	});

	var range = document.createElement('input');
	range.type = "range";
	range.min = 0;
	range.max = 100;

	range.value = convertTimeToPercent(Settings.time_scale);

	range.step = 0.01;
	style(range, {
		width: '70px'
	});

	var draggingRange = 0;

	range.addEventListener('mousedown', function() {
		draggingRange = 1;
	});

	range.addEventListener('mouseup', function() {
		draggingRange = 0;
		changeRange();
	});

	range.addEventListener('mousemove', function() {
		if (!draggingRange) return;
		changeRange();
	});

	div.appendChild(top);

	var time_options = {
		min: 0,
		step: 0.01
	};
	var currentTime = new NumberUI(time_options);
	var totalTime = new NumberUI(time_options);

	var currentTimeStore = data.get('ui:currentTime');
	var totalTimeStore = data.get('ui:totalTime');

	// UI2StoreBind(view, datastore) {
	// 	view.onChange.do(function(v) {
	// 		datastore.value = view;
	// 	})

	// 	datastore.onChange.do(function(v) {
	// 		view.setValue = v;
	// 	})
	// }

	currentTime.onChange.do(function(value, done) {
		dispatcher.fire('time.update', value);
		// repaint();
	});

	totalTime.onChange.do(function(value, done) {
		totalTimeStore.value = value;
		repaint();
	});

	// Play Controls
	top.appendChild(currentTime.dom);
	top.appendChild(document.createTextNode('/')); // 0:00:00 / 0:10:00
	top.appendChild(totalTime.dom)
	top.appendChild(play_button.dom);
	top.appendChild(stop_button.dom);
	top.appendChild(range);

	var operations_div = document.createElement('div');
	style(operations_div, {
		marginTop: '4px',
		// borderBottom: '1px solid ' + Theme.b
	});
	top.appendChild(operations_div);
	// top.appendChild(document.createElement('br'));

	// open _alt
	var file_open = new IconButton(16, 'folder_open_alt', 'Open', dispatcher);
	operations_div.appendChild(file_open.dom);

	function populateOpen() {
		while (dropdown.length) {
			dropdown.remove(0);
		}

		var option;
		option = document.createElement('option');
		option.text = 'New';
		option.value = '*new*';
		dropdown.add(option);

		option = document.createElement('option');
		option.text = 'Import JSON';
		option.value = '*import*';
		dropdown.add(option);

		// Doesn't work
		// option = document.createElement('option');
		// option.text = 'Select File';
		// option.value = '*select*';
		// dropdown.add(option);

		option = document.createElement('option');
		option.text = '==Open==';
		option.disabled = true;
		option.selected = true;
		dropdown.add(option);

		var regex = new RegExp(STORAGE_PREFIX + '(.*)');
		for (var key in localStorage) {
			// console.log(key);

			var match = regex.exec(key);
			if (match) {
				option = document.createElement('option');
				option.text = match[1];

				dropdown.add(option);
			}
		}

	}

	// listen on other tabs
	window.addEventListener('storage', function(e) {
		var regex = new RegExp(STORAGE_PREFIX + '(.*)');
		if (regex.exec(e.key)) {
			populateOpen();
		}
	});

	dispatcher.on('save:done', populateOpen);

	var dropdown = document.createElement('select');

	style(dropdown, {
		position: 'absolute',
		// right: 0,
		// margin: 0,
		opacity: 0,
		width: '16px',
		height: '16px',
		// zIndex: 1,
	});

	dropdown.addEventListener('change', function(e) {
		// console.log('changed', dropdown.length, dropdown.value);

		switch (dropdown.value) {
			case '*new*':
				dispatcher.fire('new');
				break;
			case '*import*':
				dispatcher.fire('import');
				break;
			case '*select*':
				dispatcher.fire('openfile');
				break;
			default:
				dispatcher.fire('open', dropdown.value);
				break;
		}
	});

	file_open.dom.insertBefore(dropdown, file_open.dom.firstChild);

	populateOpen();

	// // json import
	// var import_json = new IconButton(16, 'signin', 'Import JSON', dispatcher);
	// operations_div.appendChild(import_json.dom);
	// import_json.onClick(function() {
	// 	dispatcher.fire('import');
	// });

	// // new
	// var file_alt = new IconButton(16, 'file_alt', 'New', dispatcher);
	// operations_div.appendChild(file_alt.dom);

	// save
	var save = new IconButton(16, 'save', 'Save', dispatcher);
	operations_div.appendChild(save.dom);
	save.onClick(function() {
		dispatcher.fire('save');
	});

	// save as
	var save_as = new IconButton(16, 'paste', 'Save as', dispatcher);
	operations_div.appendChild(save_as.dom);
	save_as.onClick(function() {
		dispatcher.fire('save_as');
	});

	// download json (export)
	var download_alt = new IconButton(16, 'download_alt', 'Download / Export JSON to file', dispatcher);
	operations_div.appendChild(download_alt.dom);
	download_alt.onClick(function() {
		dispatcher.fire('export');
	});

	var upload_alt = new IconButton(16, 'upload_alt', 'Load from file', dispatcher);
	operations_div.appendChild(upload_alt.dom);
	upload_alt.onClick(function() {
		dispatcher.fire('openfile');
	});

	var span = document.createElement('span');
	span.style.width = '20px';
	span.style.display = 'inline-block';
	operations_div.appendChild(span);

	operations_div.appendChild(undo_button.dom);
	operations_div.appendChild(redo_button.dom);
	operations_div.appendChild(document.createElement('br'));

	// Cloud Download / Upload edit pencil

	/*
	// // show layer
	// var eye_open = new IconButton(16, 'eye_open', 'eye_open', dispatcher);
	// operations_div.appendChild(eye_open.dom);

	// // hide / disable layer
	// var eye_close = new IconButton(16, 'eye_close', 'eye_close', dispatcher);
	// operations_div.appendChild(eye_close.dom);

	// remove layer
	var minus = new IconButton(16, 'minus', 'minus', dispatcher);
	operations_div.appendChild(minus.dom);

	// check
	var ok = new IconButton(16, 'ok', 'ok', dispatcher);
	operations_div.appendChild(ok.dom);

	// cross
	var remove = new IconButton(16, 'remove', 'remove', dispatcher);
	operations_div.appendChild(remove.dom);

	*/

	// range.addEventListener('change', changeRange);

	function convertPercentToTime(t) {
		var min_time = 1;
		var max_time = 10 * 60; // 10 minutes
		var v = 500 / (t * (max_time - min_time) + min_time);
		return v;
	}

	function convertTimeToPercent(v) {
		var min_time = 1;
		var max_time = 10 * 60; // 10 minutes
		var t  = ((500 / v) - min_time)  / (max_time - min_time);
		return t;
	}

	function changeRange() {
		var t = range.value / range.max;
		// 800px - 10 minutes - 100%
		// 50% - 5 minutes
		// 10*
		// 100% - 60s / 1 second

		// TODO: scale time correctly

		dispatcher.fire('update.scale', convertPercentToTime(t));
	}

	var layer_uis = [], visible_layers = 0;
	var unused_layers = [];

	this.layers = layer_uis;

	this.setControlStatus = function(v) {
		playing = v;
		if (playing) {
			play_button.setIcon('pause');
			play_button.setTip('pause');
		}
		else {
			play_button.setIcon('play');
			play_button.setTip('play');
		}
	};

	this.setState = function(state) {

		layer_store = state;
		layers = layer_store.value;
		// layers = state;
		console.log(layer_uis.length, layers);
		var i, layer;
		for (i = 0; i < layers.length; i++) {
			layer = layers[i];

			if (!layer_uis[i]) {
				var layer_ui;
				if (unused_layers.length) {
					layer_ui = unused_layers.pop();
					layer_ui.dom.style.display = 'block';
				} else {
					// new
					layer_ui = new LayerUI(layer, dispatcher);
					layer_scroll.appendChild(layer_ui.dom);
				}
				layer_uis.push(layer_ui);
			}

			// layer_uis[i].setState(layer);
		}

		console.log('Total layers (view, hidden, total)', layer_uis.length, unused_layers.length,
			layer_uis.length + unused_layers.length);

	};

	function repaint(s) {

		s = currentTimeStore.value;
		currentTime.setValue(s);
		totalTime.setValue(totalTimeStore.value);
		currentTime.paint();
		totalTime.paint();

		var i;

		s = s || 0;
		for (i = layer_uis.length; i-- > 0;) {
			// quick hack
			if (i >= layers.length) {
				layer_uis[i].dom.style.display = 'none';
				unused_layers.push(layer_uis.pop());
				continue;
			}

			// console.log('yoz', states.get(i).value);
			layer_uis[i].setState(layers[i], layer_store.get(i));
			// layer_uis[i].setState('layers'+':'+i);
			layer_uis[i].repaint(s);
		}

		visible_layers = layer_uis.length;

	}

	this.repaint = repaint;
	this.setState(layer_store);

	this.scrollTo = function(x) {
		layer_scroll.scrollTop = x * (layer_scroll.scrollHeight - layer_scroll.clientHeight);
	};

	this.dom = div;

	repaint();
}

module.exports = LayerCabinet;<|endoftext|>


<commit_before>module.exports = function (data, index, args) {
    'use strict';

    var file = index === 0 && args.o;

    if (file)
        try {
            require('fs').writeFileSync(file, data, 'utf8');
        } catch (err) {
            console.error(err);
            var exit = require('./exit');
            return exit(exit.codes.writeErr);
        }
    else
        process.stdout.write(data);
};
<commit_msg>create necessary parent dirs for output file<commit_after>module.exports = function (data, index, args) {
    'use strict';

    var file = index === 0 && args.o;

    if (file)
        try {
            var mkdirp = require('mkdirp');
            var fs = require('fs');
            var dirname = require('path').dirname;

            // Make sure the parent directory exists
            mkdirp.sync(dirname(file));

            fs.writeFileSync(file, data, 'utf8');
        } catch (err) {
            console.error(err);
            var exit = require('./exit');
            return exit(exit.codes.writeErr);
        }
    else
        process.stdout.write(data);
};
<|endoftext|>


<commit_before>var NodesChange = function() {
        this.init();
    },
    PeopleChange = function() {
        this.init();
    },
    LibrariesChange = function() {
        this.init();
    },
    Changes = function() {
        this.init();
    },
    BaseChange = {
        _added: undefined,
        _modified: undefined,
        _removed: undefined,

        _areAddedItems: function() {
            return this._added.length;
        },

        _areModifiedItems: function() {
            return this._modified.length;
        },

        _areRemovedItems: function() {
            return this._removed.length;
        },

        areModified: function() {
            return this._areAddedItems() || this._areModifiedItems() || this._areRemovedItems();
        },

        init: function() {
            this._added = [];
            this._modified = [];
            this._removed = [];
        },

        addAdded: function(item) {
            this._added.push(item);
        },

        addModified: function(item) {
            this._modified.push(item);
        },

        addRemoved: function(item) {
            this._removed.push(item);
        },

        getType: function() {
            return 'base';
        }
    };

NodesChange.prototype = Object.create(BaseChange);
NodesChange.prototype.getType = function() {
    return 'nodes';
};

PeopleChange.prototype = Object.create(BaseChange);
PeopleChange.prototype.getType = function() {
    return 'people';
};

LibrariesChange.prototype = Object.create(BaseChange);
PeopleChange.prototype.getType = function() {
    return 'libraries';
};

Changes.prototype = {
    _nodes: undefined,
    _people: undefined,
    _libraries: undefined,

    areModified: function() {
        return this.getNodes().areModified() ||
            this.getPeople().areModified() ||
            this.getLibraries().areModified();
    },

    getNodes: function() {
        return  this._nodes;
    },

    getPeople: function() {
        return this._people;
    },

    getLibraries: function() {
        return this._libraries;
    },

    init: function() {
        this._nodes = new NodesChange();
        this._people = new PeopleChange();
        this._libraries = new LibrariesChange();
    }
};

module.exports = Changes;

<commit_msg>Simplify changes model<commit_after>var Changes = function() {
        this.init();
    },
    Change = function(type) {
        this.type = type;
        this.init();
    };

Change.prototype = {
    _added: undefined,
    _modified: undefined,
    _removed: undefined,

    _areAddedItems: function() {
        return this._added.length;
    },

    _areModifiedItems: function() {
        return this._modified.length;
    },

    _areRemovedItems: function() {
        return this._removed.length;
    },

    areModified: function() {
        return this._areAddedItems() || this._areModifiedItems() || this._areRemovedItems();
    },

    init: function() {
        this._added = [];
        this._modified = [];
        this._removed = [];
    },

    addAdded: function(item) {
        this._added.push(item);
    },

    addModified: function(item) {
        this._modified.push(item);
    },

    addRemoved: function(item) {
        this._removed.push(item);
    }
};

Changes.prototype = {
    _docs: undefined,
    _nodes: undefined,
    _people: undefined,
    _libraries: undefined,

    areModified: function() {
        return this.getDocs().areModified() ||
            this.getNodes().areModified() ||
            this.getPeople().areModified() ||
            this.getLibraries().areModified();
    },

    getDocs: function() {
        return this._docs;
    },

    getNodes: function() {
        return  this._nodes;
    },

    getPeople: function() {
        return this._people;
    },

    getLibraries: function() {
        return this._libraries;
    },

    init: function() {
        this._docs = new Change('docs');
        this._nodes = new Change('nodes');
        this._people = new Change('people');
        this._libraries = new Change('libraries');
    }
};

module.exports = Changes;

<|endoftext|>


<commit_before>export const module = 'angular-meteor.utilities';
export const utils = '$$utils';

angular.module(module, [])

/*
  A utility service which is provided with general utility functions
 */
.service(utils, [
  '$rootScope',

  function($rootScope) {
    // Checks if an object is a cursor
    this.isCursor = (obj) => {
      return obj instanceof Meteor.Collection.Cursor;
    };

    // Cheecks if an object is a scope
    this.isScope = (obj) => {
      return obj instanceof $rootScope.constructor;
    };

    // Checks if two objects are siblings
    this.areSiblings = (obj1, obj2) => {
      return _.isObject(obj1) && _.isObject(obj2) &&
        Object.getPrototypeOf(obj1) === Object.getPrototypeOf(obj2);
    };

    // Binds function into a scpecified context. If an object is provided, will bind every
    // value in the object which is a function. If a tap function is provided, it will be
    // called right after the function has been invoked.
    this.bind = (fn, context, tap) => {
      tap = _.isFunction(tap) ? tap : angular.noop;
      if (_.isFunction(fn)) return bindFn(fn, context, tap);
      if (_.isObject(fn)) return bindObj(fn, context, tap);
      return fn;
    };

    const bindFn = (fn, context, tap) => {
      return (...args) => {
        const result = fn.apply(context, args);
        tap.call(context, {
          result,
          args
        });
        return result;
      };
    };

    const bindObj = (obj, context, tap) => {
      return _.keys(obj).reduce((bound, k) => {
        bound[k] = this.bind(obj[k], context, tap);
        return bound;
      }, {});
    };
  }
]);
<commit_msg>refactor($$utils): bindFn, bindObj as functions<commit_after>export const module = 'angular-meteor.utilities';
export const utils = '$$utils';

angular.module(module, [])

/*
  A utility service which is provided with general utility functions
 */
.service(utils, [
  '$rootScope',

  function($rootScope) {
    const self = this;

    // Checks if an object is a cursor
    this.isCursor = (obj) => {
      return obj instanceof Meteor.Collection.Cursor;
    };

    // Cheecks if an object is a scope
    this.isScope = (obj) => {
      return obj instanceof $rootScope.constructor;
    };

    // Checks if two objects are siblings
    this.areSiblings = (obj1, obj2) => {
      return _.isObject(obj1) && _.isObject(obj2) &&
        Object.getPrototypeOf(obj1) === Object.getPrototypeOf(obj2);
    };

    // Binds function into a scpecified context. If an object is provided, will bind every
    // value in the object which is a function. If a tap function is provided, it will be
    // called right after the function has been invoked.
    this.bind = (fn, context, tap) => {
      tap = _.isFunction(tap) ? tap : angular.noop;
      if (_.isFunction(fn)) return bindFn(fn, context, tap);
      if (_.isObject(fn)) return bindObj(fn, context, tap);
      return fn;
    };

    function bindFn(fn, context, tap) {
      return (...args) => {
        const result = fn.apply(context, args);
        tap.call(context, {
          result,
          args
        });
        return result;
      };
    }

    function bindObj(obj, context, tap) {
      return _.keys(obj).reduce((bound, k) => {
        bound[k] = self.bind(obj[k], context, tap);
        return bound;
      }, {});
    }
  }
]);
<|endoftext|>


<commit_before>/* globals $, chrome, navigator, Vk, console, Popup, Emoji, getCase*/
/*jshint esnext: true */
/*jshint -W097*/
"use strict";
/**
 * Класс сообщения
 * @constructor
 * @param {Object} mess_obj			Объект сообщения загруженный через API
 * @param {Dialog} parentDialog 	Объект родительского диалога
 * @param {Message} parentMessage	Объект родительского сообщения
 */
function Message (mess_obj, parentDialogUrl) {
	const app = new App();
	this.id = mess_obj.id;

	if (mess_obj.out === 1) {
		this.user_id = Popup.current.id;
	} else {
		this.user_id = mess_obj.user_id;
	}

	if (parentDialogUrl) {
		this.url = parentDialogUrl + '&msgid=' + this.id;
	}

	if (mess_obj.action) {

		this.body = [$('<span/>', {
			'class': 'system',
			html: app.loc(mess_obj.action) + ' ',
		})];

	} else if (mess_obj.body) {
		mess_obj.body += /[\wа-яА-Яїєёъ]/.test( mess_obj.body.charAt( mess_obj.body.length-1 ) ) ? '. ' : ' ';

		// linkify экранирует html код в строке.
		// mess_obj.body = mess_obj.body.escapeHtml();

		mess_obj.body = mess_obj.body.linkify({
			format: url => url.length > 36 ? `${url.substr(0, 35)}…` : url
		});

		if (mess_obj.emoji) {
			mess_obj.body = Emoji.emojiToHTML(mess_obj.body);
		}

		this.body = [mess_obj.body];
	} else {
		this.body = [];
	}

	// Добавляем код карту во вложения
	if (mess_obj.geo) {
		if (!mess_obj.attachments) {
			mess_obj.attachments = [];
		}
		mess_obj.attachments.push({
			type: 'geo',
			geo: mess_obj.geo
		});
		delete mess_obj.geo;
	}

	// Добавляем код вложений
	if ($.isArray(mess_obj.attachments) && mess_obj.attachments.length > 0) {
		mess_obj.attachments = mess_obj.attachments.map((attach) => {
			const type = attach.type;
			attach = attach[type];
			switch(type) {
				// Изображение
				case 'photo':
					attach.url = '';
					if		(attach.photo_2560)	attach.url = attach.photo_2560;
					else if (attach.photo_1280)	attach.url = attach.photo_1280;
					else if (attach.photo_807)	attach.url = attach.photo_807;
					else if (attach.photo_604)	attach.url = attach.photo_604;
					else if (attach.photo_130)	attach.url = attach.photo_130;
					else if (attach.photo_75)	attach.url = attach.photo_75;

					return $('<a/>', {
						href: attach.url,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-camera'}),
							app.loc('Photo'),
						]
					});

				// Подарок
				case 'gift':
					attach.url = '';
					if		(attach.thumb_256)	attach.url = attach.thumb_256;
					else if (attach.thumb_96)	attach.url = attach.thumb_96;
					else if (attach.thumb_48)	attach.url = attach.thumb_48;

					return $('<a/>', {
						href: attach.url,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-gift'}),
							app.loc('Gift'),
						]
					});

				// Пост
				case 'wall' :
					return $('<a/>', {
						href: `https://vk.com/wall${attach.from_id}_${attach.id}`,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-pencil'}),
							app.loc('Post'),
						]
					});

				// Комментарий
				case 'wall_reply' :
					return $('<a/>', {
						href: `https://vk.com/wall${attach.owner_id}_${attach.post_id}?reply=${attach.id}`,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-chat'}),
							app.loc('Comment'),
						]
					});

				// Аудиозапись
				case 'audio':
					return $('<a/>', {
						href: `https://vk.com/audio${attach.owner_id}_${attach.id}`,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-music'}),
							`<b>${attach.artist}</b> – ${attach.title}`,
						]
					});

				// Видеозапись
				case 'video':
					return $('<a/>', {
						href: `https://vk.com/video${attach.owner_id}_${attach.id}`,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-video'}),
							attach.title,
						]
					});

				// Документ
				case 'doc'	:
					return $('<a/>', {
						href: attach.url,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-doc'}),
							attach.title,
						]
					});

				// Ссылка
				case 'link'	:
					return $('<a/>', {
						href: attach.url,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-link'}),
							attach.title,
						]
					});

				// Карта
				case 'geo':
					attach.coordinates = attach.coordinates.split(' ');
					return $('<a/>', {
						href: 'https://www.google.com.ua/maps/place/@' +
							`${attach.coordinates[0]},${attach.coordinates[1]}` +
							',13z/data=!3m1!4b1!4m2!3m1!1s0x0:0x0',
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-location'}),
							(attach.place ? attach.place.title : app.loc('Map')),
						]
					});

				// Стикеры
				case 'sticker':
					return $('<img/>', {
						'class': 'emoji sticker',
						src: attach.photo_64,
						height: '32'
					});
			}
		});
		this.body = this.body.concat(mess_obj.attachments);
	}

	if ($.isArray(mess_obj.fwd_messages) && mess_obj.fwd_messages.length > 0) {
		this.body.push( $('<a/>', {
			href: this.url,
			target: '_blank',
			html: [
				$('<i/>', { 'class':'icon-chat' }),
				getCase(mess_obj.fwd_messages.length, app.loc('forwarded messages'))
			],
		}) );
	}
}

/**
 * Возвращает сгенерированный код сообщения
 * @param  {String} type Формат сообщения
 * @return {String}      HTML code
 */
Message.prototype.getHtml = function (users, type) {
	switch(type) {
		case 'compact':
			return [$('<message/>', {
				html: [ users[ this.user_id ].ava({size:25, title: true, marker: false}) ].concat(this.body)
			})];
		default :
			return this.body;
	}
};
<commit_msg>Update Message.js<commit_after>/* globals $, chrome, navigator, Vk, console, Popup, Emoji, getCase*/
/*jshint esnext: true */
/*jshint -W097*/
"use strict";
/**
 * Класс сообщения
 * @constructor
 * @param {Object} mess_obj			Объект сообщения загруженный через API
 * @param {Dialog} parentDialog 	Объект родительского диалога
 * @param {Message} parentMessage	Объект родительского сообщения
 */
function Message (mess_obj, parentDialogUrl) {
	const app = new App();
	this.id = mess_obj.id;

	if (mess_obj.out === 1) {
		this.user_id = Popup.current.id;
	} else {
		this.user_id = mess_obj.user_id;
	}

	if (parentDialogUrl) {
		this.url = parentDialogUrl + '&msgid=' + this.id;
	}

	if (mess_obj.action) {

		this.body = [$('<span/>', {
			'class': 'system',
			html: app.loc(mess_obj.action) + ' ',
		})];

	} else if (mess_obj.body) {
		mess_obj.body += /[\wа-яА-Яїєёъ]/.test(mess_obj.body.charAt( mess_obj.body.length-1 )) ? '. ' : ' ';

		// linkify экранирует html код в строке.
		// mess_obj.body = mess_obj.body.escapeHtml();

		mess_obj.body = mess_obj.body.linkify({
			format: url => url.length > 36 ? `${url.substr(0, 35)}…` : url
		});

		if (mess_obj.emoji) {
			mess_obj.body = Emoji.emojiToHTML(mess_obj.body);
		}

		this.body = [mess_obj.body];
	} else {
		this.body = [];
	}

	// Добавляем код карту во вложения
	if (mess_obj.geo) {
		if (!mess_obj.attachments) {
			mess_obj.attachments = [];
		}
		mess_obj.attachments.push({
			type: 'geo',
			geo: mess_obj.geo,
		});
		delete mess_obj.geo;
	}

	// Добавляем код вложений
	if ($.isArray(mess_obj.attachments) && mess_obj.attachments.length > 0) {
		mess_obj.attachments = mess_obj.attachments.map((attach) => {
			const type = attach.type;
			attach = attach[type];
			switch(type) {
				// Изображение
				case 'photo':
					attach.url = '';
					if		(attach.photo_2560)	attach.url = attach.photo_2560;
					else if (attach.photo_1280)	attach.url = attach.photo_1280;
					else if (attach.photo_807)	attach.url = attach.photo_807;
					else if (attach.photo_604)	attach.url = attach.photo_604;
					else if (attach.photo_130)	attach.url = attach.photo_130;
					else if (attach.photo_75)	attach.url = attach.photo_75;

					return $('<a/>', {
						href: attach.url,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-camera'}),
							app.loc('Photo'),
						]
					});

				// Подарок
				case 'gift':
					attach.url = '';
					if (attach.thumb_256)    	attach.url = attach.thumb_256;
					else if (attach.thumb_96)	attach.url = attach.thumb_96;
					else if (attach.thumb_48)	attach.url = attach.thumb_48;

					return $('<a/>', {
						href: attach.url,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-gift'}),
							app.loc('Gift'),
						]
					});

				// Пост
				case 'wall' :
					return $('<a/>', {
						href: `https://vk.com/wall${attach.from_id}_${attach.id}`,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-pencil'}),
							app.loc('Post'),
						]
					});

				// Комментарий
				case 'wall_reply' :
					return $('<a/>', {
						href: `https://vk.com/wall${attach.owner_id}_${attach.post_id}?reply=${attach.id}`,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-chat'}),
							app.loc('Comment'),
						]
					});

				// Аудиозапись
				case 'audio':
					return $('<a/>', {
						href: `https://vk.com/audio${attach.owner_id}_${attach.id}`,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-music'}),
							`<b>${attach.artist}</b> – ${attach.title}`,
						]
					});

				// Видеозапись
				case 'video':
					return $('<a/>', {
						href: `https://vk.com/video${attach.owner_id}_${attach.id}`,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-video'}),
							attach.title,
						]
					});

				// Документ
				case 'doc'	:
					return $('<a/>', {
						href: attach.url,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-doc'}),
							attach.title,
						]
					});

				// Ссылка
				case 'link'	:
					return $('<a/>', {
						href: attach.url,
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-link'}),
							attach.title,
						]
					});

				// Карта
				case 'geo':
					attach.coordinates = attach.coordinates.split(' ');
					return $('<a/>', {
						href: 'https://www.google.com.ua/maps/place/@' +
							`${attach.coordinates[0]},${attach.coordinates[1]}` +
							',13z/data=!3m1!4b1!4m2!3m1!1s0x0:0x0',
						target: '_blank',
						html: [
							$('<i/>', {'class': 'icon-location'}),
							(attach.place ? attach.place.title : app.loc('Map')),
						]
					});

				// Стикеры
				case 'sticker':
					return $('<img/>', {
						'class': 'emoji sticker',
						src: attach.photo_64,
						height: '32'
					});
			}
		});
		this.body = this.body.concat(mess_obj.attachments);
	}

	if ($.isArray(mess_obj.fwd_messages) && mess_obj.fwd_messages.length > 0) {
		this.body.push( $('<a/>', {
			href: this.url,
			target: '_blank',
			html: [
				$('<i/>', {'class':'icon-chat'}),
				getCase(mess_obj.fwd_messages.length, app.loc('forwarded messages'))
			],
		}) );
	}
}

/**
 * Возвращает сгенерированный код сообщения
 * @param  {String} type Формат сообщения
 * @return {String}      HTML code
 */
Message.prototype.getHtml = function (users, type) {
	switch(type) {
		case 'compact':
			return [$('<message/>', {
				html: [users[this.user_id].ava({size:25, title: true, marker: false})].concat(this.body)
			})];
		default :
			return this.body;
	}
};
<|endoftext|>


<commit_before>const logger = require('./logger')(module)
const Promise = require('bluebird')
const dbResult = require('./db-result')
const jobParse = require('./job-parse')

module.exports = function queueGetJob (q, jobOrId) {
  logger('getJobById: ', jobOrId)
  return Promise.resolve().then(() => {
    return jobParse.id(jobOrId)
  }).then((ids) => {
    return q.r
      .db(q.db)
      .table(q.name)
      .getAll(...ids)
      .run()
  }).then((jobsData) => {
    logger('jobsData', jobsData)
    return dbResult.toJob(q, jobsData)
  })
}
<commit_msg>Fixed logger text<commit_after>const logger = require('./logger')(module)
const Promise = require('bluebird')
const dbResult = require('./db-result')
const jobParse = require('./job-parse')

module.exports = function queueGetJob (q, jobOrId) {
  logger('queueGetJob: ', jobOrId)
  return Promise.resolve().then(() => {
    return jobParse.id(jobOrId)
  }).then((ids) => {
    return q.r
      .db(q.db)
      .table(q.name)
      .getAll(...ids)
      .run()
  }).then((jobsData) => {
    logger('jobsData', jobsData)
    return dbResult.toJob(q, jobsData)
  })
}
<|endoftext|>


<commit_before>const async = require('async');
const fs = require('fs');
const path = require('path');

const db = require('../utils').db;
const fixtures = require('../spec/fixtures');

const client = db.createClient();

client.connect();

const testManageActions = fixtures.testData.testManageActions;
const testPerformance = [fixtures.testData.testPerformance];
const testSpots = fixtures.testData.testSpots;
const testUsers = fixtures.testData.testUsers;
const insertManageActionQuery = 'INSERT INTO manage (performanceId, usernamenumber, reason, spotId, voluntary) VALUES($1, $2, $3, $4, $5)';
const insertPerformanceQueryString = 'INSERT INTO performances (name, openAt, closeAt, performDate, current) VALUES($1, $2, $3, $4, $5)';
const insertSpotQueryString = 'INSERT INTO spots VALUES ($1, $2, $3)';
const insertUserQueryString = 'INSERT INTO users (nameNumber, instrument, name, part, password, role, spotId) VALUES ($1, $2, $3, $4, $5, $6, $7)';

function createDb(value, cb) {
  const sql = fs.readFileSync(path.resolve(__dirname, 'schema.sql')).toString(); // eslint-disable-line no-sync

  client.query(sql, [], (err) => {
    cb(err);
  });
}

function insertManageAction(action, cb) {
  client.query(insertManageActionQuery, [action.performanceId, action.userNameNumber, action.reason, action.spotId, action.voluntary], (err) => {
    cb(err);
  });
}

function insertPerformance(performance, cb) {
  client.query(insertPerformanceQueryString, [performance.name, performance.openAt, performance.closeAt, performance.performDate, performance.current], (err) => {
    cb(err);
  });
}

function insertSpot(spot, cb) {
  client.query(insertSpotQueryString, [spot.id, spot.open, spot.challengedAmount], (err) => {
    cb(err);
  });
}

function insertUser(user, cb) {
  client.query(insertUserQueryString,
    [user.nameNumber, user.instrument, user.name, user.part, user.password, user.role, user.spotId],
    (err) => {
      cb(err);
    }
  );
}

async.map(['blah'], createDb, (err) => {
  if (err) {
    console.log('Error creating db', err);
  }
});

async.map(testPerformance, insertPerformance, (err) => {
  if (err) {
    console.log('Error inserting performances', err);
  }
});

async.map(testSpots, insertSpot, (err) => {
  if (err) {
    console.log('Error inserting spots', err);
  }
});

async.map(testUsers, insertUser, (err) => {
  if (err) {
    console.log('Error inserting users', err);
  }
});

async.map(testManageActions, insertManageAction, (err) => {
  if (err) {
    console.log('Error inserting manage actions', err);
  }
  client.end();
});
<commit_msg>Add test-user email to load-test-data script<commit_after>const async = require('async');
const fs = require('fs');
const path = require('path');

const db = require('../utils').db;
const fixtures = require('../spec/fixtures');

const client = db.createClient();

client.connect();

const testManageActions = fixtures.testData.testManageActions;
const testPerformance = [fixtures.testData.testPerformance];
const testSpots = fixtures.testData.testSpots;
const testUsers = fixtures.testData.testUsers;
const insertManageActionQuery = 'INSERT INTO manage (performanceId, usernamenumber, reason, spotId, voluntary) VALUES($1, $2, $3, $4, $5)';
const insertPerformanceQueryString = 'INSERT INTO performances (name, openAt, closeAt, performDate, current) VALUES($1, $2, $3, $4, $5)';
const insertSpotQueryString = 'INSERT INTO spots VALUES ($1, $2, $3)';
const insertUserQueryString = 'INSERT INTO users (nameNumber, instrument, name, part, password, role, spotId, email) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)';

function createDb(value, cb) {
  const sql = fs.readFileSync(path.resolve(__dirname, 'schema.sql')).toString(); // eslint-disable-line no-sync

  client.query(sql, [], (err) => {
    cb(err);
  });
}

function insertManageAction(action, cb) {
  client.query(insertManageActionQuery, [action.performanceId, action.userNameNumber, action.reason, action.spotId, action.voluntary], (err) => {
    cb(err);
  });
}

function insertPerformance(performance, cb) {
  client.query(insertPerformanceQueryString, [performance.name, performance.openAt, performance.closeAt, performance.performDate, performance.current], (err) => {
    cb(err);
  });
}

function insertSpot(spot, cb) {
  client.query(insertSpotQueryString, [spot.id, spot.open, spot.challengedAmount], (err) => {
    cb(err);
  });
}

function insertUser(user, cb) {
  client.query(insertUserQueryString,
    [user.nameNumber, user.instrument, user.name, user.part, user.password, user.role, user.spotId, user.email],
    (err) => {
      cb(err);
    }
  );
}

async.map(['blah'], createDb, (err) => {
  if (err) {
    console.log('Error creating db', err);
  }
});

async.map(testPerformance, insertPerformance, (err) => {
  if (err) {
    console.log('Error inserting performances', err);
  }
});

async.map(testSpots, insertSpot, (err) => {
  if (err) {
    console.log('Error inserting spots', err);
  }
});

async.map(testUsers, insertUser, (err) => {
  if (err) {
    console.log('Error inserting users', err);
  }
});

async.map(testManageActions, insertManageAction, (err) => {
  if (err) {
    console.log('Error inserting manage actions', err);
  }
  client.end();
});
<|endoftext|>


<commit_before>
// exports.seed = function(knex, Promise) {
//   // Deletes ALL existing entries
//   return knex('table_name').del()
//     .then(function () {
//       return Promise.all([
//         // Inserts seed entries
//         knex('table_name').insert({id: 1, colName: 'rowValue1'}),
//         knex('table_name').insert({id: 2, colName: 'rowValue2'}),
//         knex('table_name').insert({id: 3, colName: 'rowValue3'})
//       ]);
//     });
// };

exports.seed = function(knex, Promise) {
  return knex('users').del() // Deletes ALL existing entries
    .then(function() { // Inserts seed entries one by one in series
      return knex('users').insert({
        name: 'Elon Musk',
        title: "CEO, and CTO of SpaceX and Tesla Inc."
        age: ,
        hometown: 'Austin',
        gender: ,
        race: ,
        industry: ,
        politicalleaning: ,
        religion: ,
        yearlyincome: ,
      });
    }).then(function () {
      return knex('users').insert({
        name: '',
        title: ""
        age: ,
        hometown: ,
        gender: ,
        race: ,
        industry: ,
        politicalleaning: ,
        religion: ,
        yearlyincome: ,
      });
    }).then(function () {
      return knex('users').insert({
        name: '',
        title: ""
        age: ,
        hometown: ,
        gender: ,
        race: ,
        industry: ,
        politicalleaning: ,
        religion: ,
        yearlyincome: ,
      });
    }).then(function () {
      return knex('users').insert({
        name: '',
        title: ""
        age: ,
        hometown: ,
        gender: ,
        race: ,
        industry: ,
        politicalleaning: ,
        religion: ,
        yearlyincome: ,
      });
    });
};<commit_msg>Updated seed data file<commit_after>
// exports.seed = function(knex, Promise) {
//   // Deletes ALL existing entries
//   return knex('table_name').del()
//     .then(function () {
//       return Promise.all([
//         // Inserts seed entries
//         knex('table_name').insert({id: 1, colName: 'rowValue1'}),
//         knex('table_name').insert({id: 2, colName: 'rowValue2'}),
//         knex('table_name').insert({id: 3, colName: 'rowValue3'})
//       ]);
//     });
// };

exports.seed = function(knex, Promise) {
  return knex('users').del() // Deletes ALL existing entries
    .then(function() { // Inserts seed entries one by one in series
      return knex('users').insert({
        name: "Elon Musk",
        title: "CEO and CTO of SpaceX, CEO and product architect of Tesla Inc.",
        age: 45,
        hometown: "Los Angeles, California",
        gender: 1,
        race: 2,
        industry: 1,
        politicalleaning: 3,
        religion: 11,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: "Tim Cook",
        title: "CEO of Apple Inc.",
        age: 56,
        hometown: "Palo Alto, California",
        gender: 1,
        race: 2,
        industry: 23,
        politicalleaning: 5,
        religion: 1,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: "Jeff Bezos",
        title: "Founder, Chairman, and CEO of Amazon.com",
        age: 53,
        hometown: "Seattle, Washington",
        gender: 1,
        race: 2,
        industry: 23,
        politicalleaning: 3,
        religion: 4,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: "Bill Gates",
        title: "Technology Advisor of Microsoft",
        age: 61,
        hometown: "Medina, Washington",
        gender: 1,
        race: 2,
        industry: 23,
        politicalleaning: 3,
        religion: 2,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: "Mary Barra",
        title: "Chairman & CEO of General Motors Company",
        age: 55,
        hometown: "Royal Oak, Michigan",
        gender: 2,
        race: 2,
        industry: 3,
        politicalleaning: 3,
        religion: 2,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: "Mark Fields",
        title: "President and CEO of Ford Motor Company",
        age: 56,
        hometown: "Dearborn, Michigan",
        gender: 1,
        race: 2,
        industry: 3,
        politicalleaning: 1,
        religion: 1,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: 'Niel Degrasse Tyson',
        title: "Astrophysicist, Cosmologist, Author, and Science Communicator",
        age: 58,
        hometown: 'Manhattan',
        gender: 1,
        race: 2,
        industry: 25,
        politicalleaning: 3,
        religion: 10,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: 'Bill Nye',
        title: "The Science Guy",
        age: 61,
        hometown: 'Washington D.C.',
        gender: 1,
        race: 1,
        industry: 25,
        politicalleaning: 3,
        religion: 10,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: 'Steven Hawking',
        title: "Theoretical Physicist, Cosmologist",
        age: 75,
        hometown: 'Oxford',
        gender: 1,
        race: 1,
        industry: 25,
        politicalleaning: 3,
        religion: 10,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: 'Rush Limbaugh',
        title: 'Entertainer, Radio Talk Show Host, and Conservative Political Commentator',
        age: 66,
        hometown: 'Cape Girardeau',
        gender: 1,
        race: 1,
        industry: 10,
        politicalleaning: 1,
        religion: 1,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: 'Sarah Palin',
        title: "American Politician, Commentator, and Author",
        age: 53,
        hometown: 'Sandpoint',
        gender: 2,
        race: 1,
        industry: 13,
        politicalleaning: 1,
        religion: 1,
        yearlyincome: 7
      });
    }).then(function () {
      return knex('users').insert({
        name: 'Ted Nugent',
        title: "Musician and Political Activist",
        age: 68,
        hometown: 'Redford',
        gender: 1,
        race: 1,
        industry: 10,
        politicalleaning: 1,
        religion: 1,
        yearlyincome: 7
      });
    });
};<|endoftext|>


<commit_before>/*
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import FixedDistributor from "./distributors/fixed";
import CollapseDistributor from "./distributors/collapse";
import RoomSubListDistributor from "./distributors/roomsublist";
import Resizer from "./resizer";

module.exports = {
    Resizer,
    FixedDistributor,
    CollapseDistributor,
    RoomSubListDistributor,
};
<commit_msg>Convert resizer to ES6<commit_after>/*
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

export FixedDistributor from "./distributors/fixed";
export CollapseDistributor from "./distributors/collapse";
export RoomSubListDistributor from "./distributors/roomsublist";
export Resizer from "./resizer";
<|endoftext|>


<commit_before>var actions = require('actions')
var _ = require('lodash')

var roleHarvester = {
    run: function(creep) {
        if(creep.room.name != Memory.home) {
            actions.goHome(creep);
        } else {
            actions.harvest(creep);
	    }
    }
};

module.exports = roleHarvester;
<commit_msg>wrong home<commit_after>var actions = require('actions')
var _ = require('lodash')

var roleHarvester = {
    run: function(creep) {
        if(creep.room.name != creep.memory.home) {
            actions.goHome(creep);
        } else {
            actions.harvest(creep);
	    }
    }
};

module.exports = roleHarvester;
<|endoftext|>


<commit_before>import ngeoFormatAttributeType from 'ngeo/format/AttributeType.js';
import ngeoRuleRule from 'ngeo/rule/Rule.js';
import * as olEvents from 'ol/events.js';
import olFeature from 'ol/Feature.js';
import olFormatGeoJSON from 'ol/format/GeoJSON.js';

/**
 * @typedef {Object} GeometryOptions
 * @property {Object.<string, *>} [featureProperties] Properties for the feature.
 * @property {boolean} [active=false] (RuleOptions)
 * @property {number|string} [expression] (RuleOptions)
 * @property {boolean} [isCustom] (RuleOptions)
 * @property {number} [lowerBoundary] (RuleOptions)
 * @property {string} name (RuleOptions)
 * @property {string} [operator] (RuleOptions)
 * @property {Array.<string>} [operators] (RuleOptions)
 * @property {string} propertyName (RuleOptions)
 * @property {string} [type] (RuleOptions)
 * @property {number} [upperBoundary] (RuleOptions)
 * @extends import('ngeo/rule/Rule.js').RuleOptions
 */

export default class extends ngeoRuleRule {

  /**
   * A rule bound to the geometry of a `ol.Feature` object. Changes made
   * to the geometry are applied to the `expression` property of the rule.
   *
   * @param {!GeometryOptions} options Options.
   */
  constructor(options) {

    options.type = ngeoFormatAttributeType.GEOMETRY;

    super(options);

    // === STATIC properties ===

    const properties = options.featureProperties || {};

    /**
     * @type {!import("ol/Feature.js").default}
     * @private
     */
    this.feature_ = new olFeature(properties);

    /**
     * @type {!import("ol/format/GeoJSON.js").default}
     * @private
     */
    this.format_ = new olFormatGeoJSON();

    /**
     * @type {boolean}
     * @private
     */
    this.updatingExpression_ = false;

    /**
     * @type {boolean}
     * @private
     */
    this.updatingGeometry_ = false;

    /**
     * @type {?import("ol/events.js").EventsKey}
     * @private
     */
    this.geometryChangeListenerKey_ = null;

    this.listenerKeys.push(
      olEvents.listen(
        this.feature_,
        `change:${this.feature.getGeometryName()}`,
        this.handleFeatureGeometryChange_,
        this
      )
    );

    this.setGeometryFromExpression_();

  }

  // === Static property getters/setters ===

  /**
   * @return {!import("ol/Feature.js").default} Feature.
   * @export
   */
  get feature() {
    return this.feature_;
  }

  /**
   * @inheritDoc
   */
  setExpression(expression) {
    this.updatingExpression_ = true;
    super.setExpression(expression);

    if (!this.updatingGeometry_) {
      this.setGeometryFromExpression_();
    }

    this.registerGeometryChange_();

    this.updatingExpression_ = false;
  }

  // === Calculated property getters/setters ===

  /**
   * @return {?import("ol/geom/Geometry.js").default} Geometry
   * @export
   */
  get geometry() {
    return this.feature_.getGeometry() || null;
  }

  /**
   * @param {?import("ol/geom/Geometry.js").default} geometry Geometry
   * @export
   */
  set geometry(geometry) {
    this.feature_.setGeometry(geometry);
  }

  // === Other methods ===

  /**
   * Called when the geometry property in the feature changes. Update the
   * expression accordingly.
   * @private
   */
  handleFeatureGeometryChange_() {
    if (this.updatingExpression_) {
      return;
    }

    this.updatingGeometry_ = true;

    const geometry = this.feature_.getGeometry();
    if (geometry) {
      this.expression = this.format_.writeGeometry(geometry);
    } else {
      this.expression = null;
    }

    this.registerGeometryChange_();

    this.updatingGeometry_ = false;
  }

  /**
   * Called when the geometry of the features changes. Update the expression
   * accordingly.
   * @param {import("ol/events/Event.js").default} evt Event
   * @private
   */
  handleGeometryChange_(evt) {
    const geometry = evt.target;
    this.updatingGeometry_ = true;
    this.expression = this.format_.writeGeometry(geometry);
    this.updatingGeometry_ = false;
  }

  /**
   * Set geometry property using the expression property.
   * @private
   */
  setGeometryFromExpression_() {
    let geometry = null;
    if (this.expression) {
      // An expression can only have a string value with a geometry rule.
      const expression = this.expression;
      geometry = this.format_.readGeometry(expression);
    }
    this.geometry = geometry;
  }

  /**
   * Unlisten the feature geometry change event, then listen to it if the
   * feature has a geometry.
   * @private
   */
  registerGeometryChange_() {

    // (1) Unlisten
    if (this.geometryChangeListenerKey_ !== null) {
      olEvents.unlistenByKey(this.geometryChangeListenerKey_);
      this.geometryChangeListenerKey_ = null;
    }

    // (2) Listen, if geom
    const geometry = this.feature_.getGeometry();
    if (geometry) {
      this.geometryChangeListenerKey_ = olEvents.listen(
        geometry,
        'change',
        this.handleGeometryChange_,
        this
      );
    }
  }

}
<commit_msg>Fix types in rule<commit_after>import ngeoFormatAttributeType from 'ngeo/format/AttributeType.js';
import ngeoRuleRule from 'ngeo/rule/Rule.js';
import * as olEvents from 'ol/events.js';
import olFeature from 'ol/Feature.js';
import olFormatGeoJSON from 'ol/format/GeoJSON.js';

/**
 * extends import('ngeo/rule/Rule.js').RuleOptions
 * @typedef {Object} GeometryOptions
 * @property {Object.<string, *>} [featureProperties] Properties for the feature.
 * @property {boolean} [active=false] (RuleOptions)
 * @property {number|string} [expression] (RuleOptions)
 * @property {boolean} [isCustom] (RuleOptions)
 * @property {number} [lowerBoundary] (RuleOptions)
 * @property {string} name (RuleOptions)
 * @property {string} [operator] (RuleOptions)
 * @property {Array.<string>} [operators] (RuleOptions)
 * @property {string} propertyName (RuleOptions)
 * @property {string} [type] (RuleOptions)
 * @property {number} [upperBoundary] (RuleOptions)
 */

export default class extends ngeoRuleRule {

  /**
   * A rule bound to the geometry of a `ol.Feature` object. Changes made
   * to the geometry are applied to the `expression` property of the rule.
   *
   * @param {!GeometryOptions} options Options.
   */
  constructor(options) {

    options.type = ngeoFormatAttributeType.GEOMETRY;

    super(options);

    // === STATIC properties ===

    const properties = options.featureProperties || {};

    /**
     * @type {!import("ol/Feature.js").default}
     * @private
     */
    this.feature_ = new olFeature(properties);

    /**
     * @type {!import("ol/format/GeoJSON.js").default}
     * @private
     */
    this.format_ = new olFormatGeoJSON();

    /**
     * @type {boolean}
     * @private
     */
    this.updatingExpression_ = false;

    /**
     * @type {boolean}
     * @private
     */
    this.updatingGeometry_ = false;

    /**
     * @type {?import("ol/events.js").EventsKey}
     * @private
     */
    this.geometryChangeListenerKey_ = null;

    this.listenerKeys.push(
      olEvents.listen(
        this.feature_,
        `change:${this.feature.getGeometryName()}`,
        this.handleFeatureGeometryChange_,
        this
      )
    );

    this.setGeometryFromExpression_();

  }

  // === Static property getters/setters ===

  /**
   * @return {!import("ol/Feature.js").default} Feature.
   * @export
   */
  get feature() {
    return this.feature_;
  }

  /**
   * @inheritDoc
   */
  setExpression(expression) {
    this.updatingExpression_ = true;
    super.setExpression(expression);

    if (!this.updatingGeometry_) {
      this.setGeometryFromExpression_();
    }

    this.registerGeometryChange_();

    this.updatingExpression_ = false;
  }

  // === Calculated property getters/setters ===

  /**
   * @return {?import("ol/geom/Geometry.js").default} Geometry
   * @export
   */
  get geometry() {
    return this.feature_.getGeometry() || null;
  }

  /**
   * @param {?import("ol/geom/Geometry.js").default} geometry Geometry
   * @export
   */
  set geometry(geometry) {
    this.feature_.setGeometry(geometry);
  }

  // === Other methods ===

  /**
   * Called when the geometry property in the feature changes. Update the
   * expression accordingly.
   * @private
   */
  handleFeatureGeometryChange_() {
    if (this.updatingExpression_) {
      return;
    }

    this.updatingGeometry_ = true;

    const geometry = this.feature_.getGeometry();
    if (geometry) {
      this.expression = this.format_.writeGeometry(geometry);
    } else {
      this.expression = null;
    }

    this.registerGeometryChange_();

    this.updatingGeometry_ = false;
  }

  /**
   * Called when the geometry of the features changes. Update the expression
   * accordingly.
   * @param {import("ol/events/Event.js").default} evt Event
   * @private
   */
  handleGeometryChange_(evt) {
    const geometry = evt.target;
    this.updatingGeometry_ = true;
    this.expression = this.format_.writeGeometry(geometry);
    this.updatingGeometry_ = false;
  }

  /**
   * Set geometry property using the expression property.
   * @private
   */
  setGeometryFromExpression_() {
    let geometry = null;
    if (this.expression) {
      // An expression can only have a string value with a geometry rule.
      const expression = this.expression;
      geometry = this.format_.readGeometry(expression);
    }
    this.geometry = geometry;
  }

  /**
   * Unlisten the feature geometry change event, then listen to it if the
   * feature has a geometry.
   * @private
   */
  registerGeometryChange_() {

    // (1) Unlisten
    if (this.geometryChangeListenerKey_ !== null) {
      olEvents.unlistenByKey(this.geometryChangeListenerKey_);
      this.geometryChangeListenerKey_ = null;
    }

    // (2) Listen, if geom
    const geometry = this.feature_.getGeometry();
    if (geometry) {
      this.geometryChangeListenerKey_ = olEvents.listen(
        geometry,
        'change',
        this.handleGeometryChange_,
        this
      );
    }
  }

}
<|endoftext|>


<commit_before>'use strict';

import React, {
  Component,
  Dimensions,
  Image,
  StyleSheet,
  Text,
  ToolbarAndroid,
  TouchableOpacity,
  View,
} from 'react-native';

import { Surface } from 'gl-react-native';
var ImagePickerManager = require('NativeModules').ImagePickerManager;

import PostDetails from './post-details';
import Saturation from '../components/saturation';
import Vignette from '../components/vignette';
import Instagram from '../components/instagram';

var length = Dimensions.get('window').width;

class Camera extends Component {
  constructor(props) {
    super(props);
    this.state = {
      avatarSource: null,
      test: 'help',
      length: length,
      filter: null
    };
  }

  openCamera() {
    ImagePickerManager.showImagePicker(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePickerManager Error: ', response.error);
      } else {
        // You can display the image using either data:
        const source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true};
        this.setState({
          avatarSource: source
        });
      }
    });
  }

  renderImage() {
    var filter;
    switch (this.state.filter) {
      case "sat":
        filter = this.monoImage();
        break;
      case "vign":
        filter = this.vignetteImage();
        break;
      case "ig":
        filter = this.igImage();
        break;
      default:
        filter = this.ogImage();
        break;
    }
    return (
      <View>
        <ToolbarAndroid
          title = 'Create a Post'
          style = {styles.toolbar}
          actions = {[
            {title: 'Details', show: 'always'},
            {title: 'Camera', show: 'always'}
          ]}
          onActionSelected = {this.onActionSelected.bind(this)}
        />

        <Surface width = {this.state.length} height = {this.state.length} >
        {filter}
        </Surface>

        <View style = {{flex: 1, flexDirection: 'row', flexWrap: 'wrap' }}>

        <Text
          style = {{color: 'black', marginTop: 10, flex: 1}}>
          Original
        </Text>

        <TouchableOpacity onPress ={()=> this.setState({filter: null})} style = {{flex: 1}}>
          <Surface width = {40} height = {40}>
            {this.ogImage()}
          </Surface>
        </TouchableOpacity>

        <Text
          style = {{color: 'black', marginTop: 10, flex: 1}}>
          Monochrome
        </Text>

        <TouchableOpacity onPress = {()=> this.setState({filter: 'sat'})} style = {{flex: 1}}>
          <Surface width = {40} height = {40} >
            {this.monoImage()}
          </Surface>
        </TouchableOpacity>

        <Text
          style = {{color: 'black', marginTop: 10, flex: 1}}>
          Vignette
        </Text>

        <TouchableOpacity onPress = {()=> this.setState({filter: 'vign'})} style = {{flex: 1}}>
          <Surface width = {40} height = {40} >
            {this.vignetteImage()}
          </Surface>
        </TouchableOpacity>

        <Text
          style = {{color: 'black', marginTop: 10, flex: 1}}>
          Anything Goes
        </Text>

        <TouchableOpacity onPress = {()=> this.setState({filter: 'ig'})} style = {{flex: 1}}>
          <Surface width = {40} height = {40} >
            {this.igImage()}
          </Surface>
        </TouchableOpacity>

        </View>
        </View>

    );
  }

  ogImage() {
    return(
      <Image source = {this.state.avatarSource}
      style = {{flex: 1}}/>
    );
  }

  monoImage() {
    return(<Saturation
      factor = {0}
      image = {this.state.avatarSource}
      style = {{flex: 1}}
    />);
  }

  vignetteImage() {
    var secondSource = this.state.avatarSource;
    return (<Vignette
      time = {0.2}
      texture = {secondSource}
      style = {{flex: 1}}
    />
    );
  }

  igImage() {
    var thirdSource = this.state.avatarSource;
    return (<Instagram
      brightness = {1}
      saturation = {1}
      contrast = {1}
      hue = {0}
      sepia = {1}
      gray = {0}
      mixFactor = {0}
      tex = {thirdSource}
      />
    );
  }
  renderBars() {
    return(
      <View>
        <ToolbarAndroid
          title = 'Create a Post'
          style = {styles.toolbar}
          actions ={[
            {title: 'Details', show: 'always'},
            {title: 'Camera', show: 'always'}
          ]}

          onActionSelected = {this.onActionSelected.bind(this)}
        />
      </View>
    );
  }

  onActionSelected(position) {
    if (position == 0) {
      this.props.navigator.push({component: PostDetails});
    } else if (position == 1) {
      this.openCamera();
    }
  }

  render() {
    if ( this.state.avatarSource)
      {return this.renderImage();}
    else
      {return this.renderBars();}
  }

}

const styles = StyleSheet.create({
  toolbar: {
    height: 56,
    backgroundColor: '#4682b4',
  }
});

var options = {
  title: 'Select Avatar', // specify null or empty string to remove the title
  cancelButtonTitle: 'Cancel',
  takePhotoButtonTitle: 'Take Photo...', // specify null or empty string to remove this button
  chooseFromLibraryButtonTitle: 'Choose from Library...', // specify null or empty string to remove this button
  cameraType: 'back', // 'front' or 'back'
  mediaType: 'photo', // 'photo' or 'video'
  videoQuality: 'high', // 'low', 'medium', or 'high'
  durationLimit: 10, // video recording max time in seconds
  maxWidth: 370, // photos only
  maxHeight: 370, // photos only
  aspectX: 2, // android only - aspectX:aspectY, the cropping image's ratio of width to height
  aspectY: 1, // android only - aspectX:aspectY, the cropping image's ratio of width to height
  quality: 1, // 0 to 1, photos only
  angle: 0, // android only, photos only
  allowsEditing: false, // Built in functionality to resize, reposition the image after selection
  noData: false, // photos only - disables the base64 `data` field from being generated (greatly improves performance on large photos)
};

module.exports = Camera;
<commit_msg>changed some naming conventions<commit_after>'use strict';

import React, {
  Component,
  Dimensions,
  Image,
  StyleSheet,
  Text,
  ToolbarAndroid,
  TouchableOpacity,
  View,
} from 'react-native';

import { Surface } from 'gl-react-native';
var ImagePickerManager = require('NativeModules').ImagePickerManager;

import PostDetails from './post-details';
import Saturation from '../components/saturation';
import Vignette from '../components/vignette';
import Instagram from '../components/instagram';

var length = Dimensions.get('window').width;

class Camera extends Component {
  constructor(props) {
    super(props);
    this.state = {
      avatarSource: null,
      test: 'help',
      length: length,
      filter: null
    };
  }

  openCamera() {
    ImagePickerManager.showImagePicker(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePickerManager Error: ', response.error);
      } else {
        // You can display the image using either data:
        const source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true};
        this.setState({
          avatarSource: source
        });
      }
    });
  }

  renderImage() {
    var filter;
    switch (this.state.filter) {
      case "sat":
        filter = this.monoImage();
        break;
      case "vign":
        filter = this.vignetteImage();
        break;
      case "ig":
        filter = this.igImage();
        break;
      default:
        filter = this.ogImage();
        break;
    }
    return (
      <View>
        <ToolbarAndroid
          title = 'Create a Post'
          style = {styles.toolbar}
          actions = {[
            {title: 'Details', show: 'always'},
            {title: 'Camera', show: 'always'}
          ]}
          onActionSelected = {this.onActionSelected.bind(this)}
        />

        <Surface width = {this.state.length} height = {this.state.length} >
        {filter}
        </Surface>

        <View style = {{flex: 1, flexDirection: 'row', flexWrap: 'wrap' }}>

        <Text
          style = {{color: 'black', marginTop: 10, flex: 1}}>
          Original
        </Text>

        <TouchableOpacity onPress ={()=> this.setState({filter: null})} style = {{flex: 1}}>
          <Surface width = {40} height = {40}>
            {this.ogImage()}
          </Surface>
        </TouchableOpacity>

        <Text
          style = {{color: 'black', marginTop: 10, flex: 1}}>
          Monochrome
        </Text>

        <TouchableOpacity onPress = {()=> this.setState({filter: 'sat'})} style = {{flex: 1}}>
          <Surface width = {40} height = {40} >
            {this.monoImage()}
          </Surface>
        </TouchableOpacity>

        <Text
          style = {{color: 'black', marginTop: 10, flex: 1}}>
          Vignette
        </Text>

        <TouchableOpacity onPress = {()=> this.setState({filter: 'vign'})} style = {{flex: 1}}>
          <Surface width = {40} height = {40} >
            {this.vignetteImage()}
          </Surface>
        </TouchableOpacity>

        <Text
          style = {{color: 'black', marginTop: 10, flex: 1}}>
          Multi-purpose filter
        </Text>

        <TouchableOpacity onPress = {()=> this.setState({filter: 'ig'})} style = {{flex: 1}}>
          <Surface width = {40} height = {40} >
            {this.igImage()}
          </Surface>
        </TouchableOpacity>

        </View>
        </View>

    );
  }

  ogImage() {
    return(
      <Image source = {this.state.avatarSource}
      style = {{flex: 1}}/>
    );
  }

  monoImage() {
    return(<Saturation
      factor = {0}
      image = {this.state.avatarSource}
      style = {{flex: 1}}
    />);
  }

  vignetteImage() {
    var secondSource = this.state.avatarSource;
    return (<Vignette
      time = {0.2}
      texture = {secondSource}
      style = {{flex: 1}}
    />
    );
  }

  igImage() {
    var thirdSource = this.state.avatarSource;
    return (<Instagram
      brightness = {1}
      saturation = {1}
      contrast = {1}
      hue = {0}
      sepia = {1}
      gray = {0}
      mixFactor = {0}
      tex = {thirdSource}
      />
    );
  }
  renderBars() {
    return(
      <View>
        <ToolbarAndroid
          title = 'Create a Post'
          style = {styles.toolbar}
          actions ={[
            {title: 'Details', show: 'always'},
            {title: 'Camera', show: 'always'}
          ]}

          onActionSelected = {this.onActionSelected.bind(this)}
        />
      </View>
    );
  }

  onActionSelected(position) {
    if (position == 0) {
      this.props.navigator.push({component: PostDetails});
    } else if (position == 1) {
      this.openCamera();
    }
  }

  render() {
    if ( this.state.avatarSource)
      {return this.renderImage();}
    else
      {return this.renderBars();}
  }

}

const styles = StyleSheet.create({
  toolbar: {
    height: 56,
    backgroundColor: '#4682b4',
  }
});

var options = {
  title: 'Select Avatar', // specify null or empty string to remove the title
  cancelButtonTitle: 'Cancel',
  takePhotoButtonTitle: 'Take Photo...', // specify null or empty string to remove this button
  chooseFromLibraryButtonTitle: 'Choose from Library...', // specify null or empty string to remove this button
  cameraType: 'back', // 'front' or 'back'
  mediaType: 'photo', // 'photo' or 'video'
  videoQuality: 'high', // 'low', 'medium', or 'high'
  durationLimit: 10, // video recording max time in seconds
  maxWidth: 370, // photos only
  maxHeight: 370, // photos only
  aspectX: 2, // android only - aspectX:aspectY, the cropping image's ratio of width to height
  aspectY: 1, // android only - aspectX:aspectY, the cropping image's ratio of width to height
  quality: 1, // 0 to 1, photos only
  angle: 0, // android only, photos only
  allowsEditing: false, // Built in functionality to resize, reposition the image after selection
  noData: false, // photos only - disables the base64 `data` field from being generated (greatly improves performance on large photos)
};

module.exports = Camera;
<|endoftext|>