<commit_before>var _=require('underscore');
var sqlite3 = require('sqlite3').verbose();

function SQlite(databaseName) {
    db= new sqlite3.Database('chain.sqlite3');
}
SQlite.prototype.find= function(model, query, callback) {
    var sqlstring="SELECT * FROM ";
    sqlstring=sqlstring+model;
    if(!_.isEmpty(query)){
       sqlstring=sqlstring+" WHERE ";
    }
    var t=0;
    _.each(query, function (value, key) {
        if (typeof value === "string" || typeof value==="number") {

            if (t === 0) {
                sqlstring=sqlstring+" " +key+" ="+" $"+key ;
                t= 1;
            }
            else{
                sqlstring=sqlstring+" AND " +key+" ="+" $"+key ;
            }
            Object.defineProperty(query, "$"+key, Object.getOwnPropertyDescriptor(query, key));
            delete query[key];

        }

    });

        db.all(sqlstring,query, function (err, row) {
            if (err) {
                callback(err, null)
            }
            else{
                callback(null, row);
            }
        });
        db.close();

};

SQlite.prototype.update=function(model, query, values, callback) {
    var sqlstring=" UPDATE ";
    sqlstring=sqlstring+model+ " SET " ;
    var qString=" WHERE ";
    var t=0;
    _.each(query, function (value, key) {
        if (typeof value === "string" || typeof value==="number") {
            if (t === 0) {
                qString=qString+" " +key+" ="+" $"+key ;
                sqlstring=sqlstring+" "+key+" ="+"$up"+key;
                t= 1;
            }
            else{
                qString=qString+" AND " +key+" ="+" $up"+key ;
                sqlstring=sqlstring+" "+key+" ="+"$"+key;
            }
            Object.defineProperty(query, "$"+key, Object.getOwnPropertyDescriptor(query, key));
            Object.defineProperty(query, "$up"+key, Object.getOwnPropertyDescriptor(values, key));
            delete query[key];
        }

    });

    db.run(sqlstring+qString,query, function (err, changes) {
        if (err) {
            callback(err, null  );
        }
        else{
            callback(null, this.changes);
        }
    });
};

SQlite.prototype.destroy=function(model, query, callback) {
    var sqlstring="DELETE  FROM ";

    sqlstring=sqlstring+model;
    if(!_.isEmpty(query)){
        sqlstring=sqlstring+" WHERE ";
    }
    var t=0;
    _.each(query, function (value, key) {
        if (typeof value === "string" || typeof value==="number") {
            if (t === 0) {
                sqlstring=sqlstring+" " +key+" ="+" $"+key ;
                t= 1;
            }
            else{
                sqlstring=sqlstring+" AND " +key+" ="+" $"+key ;
            }
            Object.defineProperty(query, "$"+key, Object.getOwnPropertyDescriptor(query, key));
            delete query[key];
        }

    });
    db.run(sqlstring,query, function (err, changes) {
        if (err) {
            callback(err, null)
        }
        else{
            callback(null, this.changes);
        }
    });

};

<commit_msg>fixed jscsrc errors sqlite file<commit_after>var _  = require('underscore');
var sqlite3 = require('sqlite3').verbose();

function SQlite (databaseName) {
    db  =  new sqlite3.Database('chain.sqlite3');
}
SQlite.prototype.find  =  function (model, query, callback) {
    var sqlstring  = 'SELECT * FROM ';
    sqlstring = sqlstring  +  model;

    if (!_.isEmpty(query)) {sqlstring = sqlstring  + ' WHERE ';
    }
    var t  = 0;
    _.each(query, function (value, key) {
        if (typeof value === 'string' || typeof value === 'number') {

            if (t === 0) {
                sqlstring  = sqlstring  +  ' '  +  key + ' = ' + ' $' + key ;
                t = 1;
            } else {sqlstring = sqlstring + ' AND ' + key + ' = ' + ' $' + key ;}
            Object.defineProperty(query, '$' + key,
                Object.getOwnPropertyDescriptor(query, key));
            delete query[key];
        }
    });

    db.all(sqlstring, query, function (err, row) {
            if (err) {callback(err, null)} else { callback(null, row);}});
    db.close();
};

SQlite.prototype.update  = function (model, query, values, callback) {
    var sqlstring  = ' UPDATE ';
    sqlstring  = sqlstring + model +  ' SET ' ;
    var qString  = ' WHERE ';
    var t  = 0;
    _.each(query, function (value, key) {

        if (typeof value === 'string' || typeof value === 'number') {

            if (t === 0) {
                qString  = qString + ' '  + key + ' =' + ' $' + key ;
                sqlstring  = sqlstring + ' ' + key + ' =' + '$up' + key;
                t = 1;
            } else {
                qString  = qString + ' AND '  + key + ' =' + ' $up' + key ;
                sqlstring  = sqlstring + ' ' + key + ' =' + '$' + key;
            }
            Object.defineProperty(query, '$' + key,
                Object.getOwnPropertyDescriptor(query, key));
            Object.defineProperty(query, '$up' + key,
                Object.getOwnPropertyDescriptor(values, key));
            delete query[key];
        }
    });

    db.run(sqlstring + qString, query, function (err, changes) {

        if (err) {
            callback(err, null  );
        } else {
            callback(null, this.changes);
        }
    });
};

SQlite.prototype.destroy  = function (model, query, callback) {
    var sqlstring  = 'DELETE  FROM ';
    sqlstring  = sqlstring + model;

    if (!_.isEmpty(query)) {
        sqlstring  = sqlstring + ' WHERE ';
    }
    var t  = 0;
    _.each(query, function (value, key) {
        if (typeof value === 'string' || typeof value === 'number') {
            if (t === 0) {
                sqlstring  = sqlstring + ' '  + key + ' =' + ' $' + key ;
                t = 1;
            } else {
                sqlstring  = sqlstring + ' AND '  + key + ' =' + ' $' + key ;
            }
            Object.defineProperty(query, '$' + key, Object.getOwnPropertyDescriptor(query, key));
            delete query[key];
        }
    });
    db.run(sqlstring, query, function (err, changes) {
        if (err) {
            callback(err, null)
        } else {
            callback(null, this.changes);
        }
    });
};<|endoftext|>


<commit_before>Meteor.startup(function() {
	RocketChat.settings.addGroup('Atlassian Crowd', function() {
		const enableQuery = {_id: 'CROWD_Enable', value: true};
		this.add('CROWD_Enable', false, { type: 'boolean', public: true, i18nLabel: 'Enabled' });
		this.add('CROWD_URL', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'URL' });
		this.add('CROWD_Reject_Unauthorized', true, { type: 'boolean', enableQuery: enableQuery });
		this.add('CROWD_APP_USERNAME', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'Username' });
		this.add('CROWD_APP_PASSWORD', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'Password' });
		this.add('CROWD_Sync_User_Data', false, { type: 'boolean', enableQuery: enableQuery, i18nLabel: 'Sync_Users' });
		this.add('CROWD_Test_Connection', 'crowd_test_connection', { type: 'action', actionText: 'Test_Connection', i18nLabel: 'Test_Connection' });
	});
});
<commit_msg>Set crowd password field as a password input<commit_after>Meteor.startup(function() {
	RocketChat.settings.addGroup('Atlassian Crowd', function() {
		const enableQuery = {_id: 'CROWD_Enable', value: true};
		this.add('CROWD_Enable', false, { type: 'boolean', public: true, i18nLabel: 'Enabled' });
		this.add('CROWD_URL', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'URL' });
		this.add('CROWD_Reject_Unauthorized', true, { type: 'boolean', enableQuery: enableQuery });
		this.add('CROWD_APP_USERNAME', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'Username' });
		this.add('CROWD_APP_PASSWORD', '', { type: 'password', enableQuery: enableQuery, i18nLabel: 'Password' });
		this.add('CROWD_Sync_User_Data', false, { type: 'boolean', enableQuery: enableQuery, i18nLabel: 'Sync_Users' });
		this.add('CROWD_Test_Connection', 'crowd_test_connection', { type: 'action', actionText: 'Test_Connection', i18nLabel: 'Test_Connection' });
	});
});
<|endoftext|>


<commit_before>// Declarations

var coords, map, updater, live;

const fadeTime = 250,
	  updateTime = 2000,
	  zoomLevel = 16,
	  flyTime = 1;

// Functions (Time)

function getParameter(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

function getSecondsSinceMidnight() {
	return ~~((new Date() - new Date().setHours(0, 0, 0, 0)) / 1000);
}

function toHMS(seconds) {
	var hours   = Math.floor(seconds / 3600),
		minutes = Math.floor((seconds % 3600) / 60);
	seconds = seconds - (minutes * 60) - (hours * 3600);
	return {h: hours, m: minutes, s: seconds};
}

function toCountdown(seconds) {
	seconds = seconds - getSecondsSinceMidnight();
	var time = toHMS(Math.abs(seconds));
	return (seconds < 0 ? '-' : '') + (!live && time.h !== 0 ? time.h + 'h ' : '') + (time.m !== 0 ? time.h !== 0 && time.m < 10 ? ('0' + time.m).slice(-2) + 'm ' : time.m + 'm ' : '') + (!live && time.h === 0 && time.m === 0 || live ? (time.m !== 0 ? ('0' + time.s).slice(-2) : time.s) + 's' : '');
}

function toTime(seconds) {
	var time = toHMS(seconds);
	return ('0' + time.h).slice(-2) + ':' + ('0' + time.m).slice(-2);
}

// Functions (Stops)

function showStop(id, settings) {
	if (updater && !live) {

		$('.trip-scheduled').each(function() {
			$(this).text(toCountdown($(this).attr('data-time')));

			if ($(this).attr('data-time') < getSecondsSinceMidnight()) $(this).parent().remove();
		});

		return;
	}

	$.get('//' + location.host + '/getstop?id=' + id).done(function(stop) {hideBookmarks();
		var trips   = stop.trips,
			content = '';

		live = stop.live;

		for (var i = 0; i < trips.length; i++) {
			var trip = trips[i];

			if (live) {
				content += '

' + trip.number + '

' + toCountdown(trip.scheduled) + '

' + toCountdown(trip.expected) + '

';
			} else {
				content += '

' + trip.short_name + '

' + toCountdown(trip.time) + '

' + toTime(trip.time) + '

';
			}

		}
		$('#stop-trips').html(content);

		if (settings.panMap) map.flyTo({
			lat: stop.lat,
			lng: stop.lng
		}, zoomLevel, {duration: flyTime});

		if (!settings.fadeIn) return;

		document.title = 'Bussiaeg - ' + stop.name + (stop.desc ? ' - ' + stop.desc : '');
		history.pushState(null, document.title, '/?stop=' + stop.id);

		$('#stop-name').text(stop.name);
		$('#stop-desc').text(stop.desc);

		$('#stop').fadeIn(fadeTime);
	});

}

function showStops() {

	if (map.getZoom() <= 15) return map.eachLayer(function(layer) {
		if (layer._icon !== undefined) map.removeLayer(layer);
	});

	var bounds = map.getBounds();
	$.get('//' + location.host + '/getstops?lat_min=' + bounds._northEast.lat + '&lng_min=' + bounds._northEast.lng + '&lat_max=' + bounds._southWest.lat + '&lng_max=' + bounds._southWest.lng, function(stops) {

		for (var i = 0; i < stops.length; i++) {

			(function() {
				var stop = stops[i];

				L.marker([stop.lat, stop.lng], {
					icon: L.icon({
						iconUrl: 'assets/stop_' + stop.type + '.png',
						iconSize: [24, 24]
					})
				}).addTo(map).on('click', function() {
					if (updater) return;

					showStop(stop.id, {panMap: false, fadeIn: true});
					updater = setInterval(function() {
						showStop(stop.id, {panMap: false, fadeIn: false});
					}, updateTime);

				});

			})();

		}

	});

}

// Functions (Bookmarks)

function addBookmark() {

	swal({
		type: 'input',
		title: 'Sisesta nimi',
		confirmButtonText: 'Lisa',
		cancelButtonText: 'Tagasi',
		showCancelButton: true,
		inputPlaceholder: 'Minu kodu',
		animation: 'slide-from-top'
	}, function(input) {
		var bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];

		if (input !== false && input.trim() !== '') bookmarks.push({
			name: input,
			lat:  map.getCenter().lat,
			lng:  map.getCenter().lng,
			zoom: map.getZoom()
		});

		localStorage.setItem('bookmarks', JSON.stringify(bookmarks));

		hideBookmarks();
	});

}

function deleteBookmark(el) {

	swal({
		title: 'Kustuta?',
		text: el.text(),
		confirmButtonText: 'Jah',
		cancelButtonText: 'Ei',
		showCancelButton: true,
		animation: 'slide-from-bottom'
	}, function(isConfirm) {
		if (!isConfirm) return;

		var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));

		for (var i = 0; i < bookmarks.length; i++) {
			var bookmark = bookmarks[i];

			if (bookmark.lat !== el.data('lat') || bookmark.lng !== el.data('lng')) continue;

			bookmarks.splice(i, 1); el.remove();

			break;
		}

		localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
	});

}

function showBookmarks() {
	var bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];

	var content = '
Lisa asukoht
';
	for (var i = 0; i < bookmarks.length; i++) {
		var bookmark = bookmarks[i];

		content += '
' + bookmark.name + '
';

	}
	$('#bookmarks').html(content);

	$('.bookmark').each(function() {
		$(this).hammer().on('swiperight', function() {
			deleteBookmark($(this));
		});
	});

	$('#bookmarks').animate({left: '0px'}, fadeTime);
}

function hideBookmarks() {
	$('#bookmarks').animate({left: '-240px'}, fadeTime);
}

// Initialization (Donation)

localStorage.setItem('visitCount', parseInt(localStorage.getItem('visitCount')) + 1 || 1);
if (!getParameter('nodonate') && (parseInt(localStorage.getItem('visitCount')) === 10 || !(parseInt(localStorage.getItem('visitCount')) % 50))) {

	swal({
		title: 'Tere!',
		text: 'Oleme märganud, et teile meeldib Bussiaeg.ee.\nKas soovite tegijaid toetada?',
		confirmButtonText: 'PayPal',
		cancelButtonText: 'Ei',
		showCancelButton: true
	}, function(isConfirm) {
		if (isConfirm) window.open('https://www.paypal.me/bussiaeg', '_self');
	});

}

// Initialization (Share)

const share = parseInt(getParameter('stop'));
if (share) if (!isNaN(share)) if (!updater) {

	showStop(share, {panMap: true, fadeIn: true});
	updater = setInterval(function() {
		showStop(share, {panMap: false, fadeIn: false});
	}, updateTime);

}

// Initialization (Map)

var map = L.map('map', {
	center: [
		parseFloat(getParameter('lat')) || 59.388,
		parseFloat(getParameter('lng')) || 24.685
	],
	zoom: zoomLevel,
	minZoom: 10,
	maxZoom: 18,
	maxBounds: [[59.874204, 21.396935], [57.290822, 28.838625]],
	attributionControl: false,
	bounceAtZoomLimits: false,
	doubleClickZoom: false,
	zoomControl: false,
	keyboard: false,
	boxZoom: false
});

L.tileLayer('//{s}.google.com/vt/lyrs=phl=en&x={x}&y={y}&z={z}&pbhttps://maps.googleapis.com/maps/vt?pb=!1m5!1m4!1i{z}!2i{x}!3i{y}!4i256!2m3!1e0!2sm!3i372053562!3m14!2sen-US!3sUS!5e18!12m1!1e47!12m3!1e37!2m1!1ssmartmaps!12m4!1e26!2m2!1sstyles!2zcy50OjY2fHAudjpvZmY!4e0', {
    subdomains: ['mt0', 'mt1', 'mt2', 'mt3']
}).addTo(map);

L.control.attribution({
	position: 'bottomleft',
	prefix: 'Bussiaeg.ee | Sõiduplaanid | Peatus | Google | Leaflet'
}).addTo(map);

showStops();
map.on('moveend', function() {
	showStops();
});

// Initialization (GPS)

navigator.geolocation.getCurrentPosition(function(pos) {
	map.flyTo([pos.coords.latitude, pos.coords.longitude], zoomLevel, {duration: flyTime});

	coords = pos.coords; $('#btn-locate').fadeIn(fadeTime * 2);

}, function(err) {}, {timeout: 3000});

navigator.geolocation.watchPosition(function(pos) {
	coords = pos.coords; $('#btn-locate').fadeIn(fadeTime * 2);
});

// User Interface

$('#btn-bookmarks, #btn-locate').on('animationend', function() {
	$(this).removeClass('bounce');
});

// User Interface (Stops)

$('#stop-top').click(function() {
	clearInterval(updater); updater = null;

	$(this).parent().fadeOut(fadeTime);

	document.title = 'Bussiaeg';
	history.pushState(null, document.title, '/');

});

// User Interface (Bookmarks)

map.on('click dragstart', function() {
	$(this).addClass('bounce');
	hideBookmarks();
});

$('#bookmarks').hammer().on('swipeleft', function() {
	hideBookmarks();
});

$('#btn-bookmarks').click(function() {
	$(this).addClass('bounce');
	showBookmarks();
});

$('#bookmarks').on('click', '#bookmarks-add', function() {
	addBookmark();
});

$('#bookmarks').on('click', '.bookmark', function() {
	hideBookmarks();
	map.flyTo([$(this).data('lat'), $(this).data('lng')], $(this).data('zoom'), {duration: flyTime});
});

// User Interface (Help)

$('#btn-help').click(function() {
	$(this).addClass('bounce');

	hideBookmarks();

	$('#help').fadeIn(fadeTime, function() {
		$('#btn-help').removeClass('bounce');
	});

});

$('#help').click(function() {
	$(this).fadeOut(fadeTime);
});

// User Interface (Locate)

$('#btn-locate').click(function() {
	$(this).addClass('bounce');

	if (coords) map.flyTo([coords.latitude, coords.longitude], zoomLevel, {duration: flyTime});
});<commit_msg>Remove unnecessary code<commit_after>// Declarations

var coords, map, updater, live;

const fadeTime = 250,
	  updateTime = 2000,
	  zoomLevel = 16,
	  flyTime = 1;

// Functions (Time)

function getParameter(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

function getSecondsSinceMidnight() {
	return ~~((new Date() - new Date().setHours(0, 0, 0, 0)) / 1000);
}

function toHMS(seconds) {
	var hours   = Math.floor(seconds / 3600),
		minutes = Math.floor((seconds % 3600) / 60);
	seconds = seconds - (minutes * 60) - (hours * 3600);
	return {h: hours, m: minutes, s: seconds};
}

function toCountdown(seconds) {
	seconds = seconds - getSecondsSinceMidnight();
	var time = toHMS(Math.abs(seconds));
	return (seconds < 0 ? '-' : '') + (!live && time.h !== 0 ? time.h + 'h ' : '') + (time.m !== 0 ? time.h !== 0 && time.m < 10 ? ('0' + time.m).slice(-2) + 'm ' : time.m + 'm ' : '') + (!live && time.h === 0 && time.m === 0 || live ? (time.m !== 0 ? ('0' + time.s).slice(-2) : time.s) + 's' : '');
}

function toTime(seconds) {
	var time = toHMS(seconds);
	return ('0' + time.h).slice(-2) + ':' + ('0' + time.m).slice(-2);
}

// Functions (Stops)

function showStop(id, settings) {
	if (updater && !live) {

		$('.trip-scheduled').each(function() {
			$(this).text(toCountdown($(this).attr('data-time')));

			if ($(this).attr('data-time') < getSecondsSinceMidnight()) $(this).parent().remove();
		});

		return;
	}

	$.get('//' + location.host + '/getstop?id=' + id).done(function(stop) {hideBookmarks();
		var trips   = stop.trips,
			content = '';

		live = stop.live;

		for (var i = 0; i < trips.length; i++) {
			var trip = trips[i];

			if (live) {
				content += '

' + trip.number + '

' + toCountdown(trip.scheduled) + '

' + toCountdown(trip.expected) + '

';
			} else {
				content += '

' + trip.short_name + '

' + toCountdown(trip.time) + '

' + toTime(trip.time) + '

';
			}

		}
		$('#stop-trips').html(content);

		if (settings.panMap) map.flyTo({
			lat: stop.lat,
			lng: stop.lng
		}, zoomLevel, {duration: flyTime});

		if (!settings.fadeIn) return;

		document.title = 'Bussiaeg - ' + stop.name + (stop.desc ? ' - ' + stop.desc : '');
		history.pushState(null, document.title, '/?stop=' + stop.id);

		$('#stop-name').text(stop.name);
		$('#stop-desc').text(stop.desc);

		$('#stop').fadeIn(fadeTime);
	});

}

function showStops() {

	if (map.getZoom() <= 15) return map.eachLayer(function(layer) {
		if (layer._icon !== undefined) map.removeLayer(layer);
	});

	var bounds = map.getBounds();
	$.get('//' + location.host + '/getstops?lat_min=' + bounds._northEast.lat + '&lng_min=' + bounds._northEast.lng + '&lat_max=' + bounds._southWest.lat + '&lng_max=' + bounds._southWest.lng, function(stops) {

		for (var i = 0; i < stops.length; i++) {

			(function() {
				var stop = stops[i];

				L.marker([stop.lat, stop.lng], {
					icon: L.icon({
						iconUrl: 'assets/stop_' + stop.type + '.png',
						iconSize: [24, 24]
					})
				}).addTo(map).on('click', function() {
					if (updater) return;

					showStop(stop.id, {panMap: false, fadeIn: true});
					updater = setInterval(function() {
						showStop(stop.id, {panMap: false, fadeIn: false});
					}, updateTime);

				});

			})();

		}

	});

}

// Functions (Bookmarks)

function addBookmark() {

	swal({
		type: 'input',
		title: 'Sisesta nimi',
		confirmButtonText: 'Lisa',
		cancelButtonText: 'Tagasi',
		showCancelButton: true,
		inputPlaceholder: 'Minu kodu',
		animation: 'slide-from-top'
	}, function(input) {
		var bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];

		if (input !== false && input.trim() !== '') bookmarks.push({
			name: input,
			lat:  map.getCenter().lat,
			lng:  map.getCenter().lng,
			zoom: map.getZoom()
		});

		localStorage.setItem('bookmarks', JSON.stringify(bookmarks));

		hideBookmarks();
	});

}

function deleteBookmark(el) {

	swal({
		title: 'Kustuta?',
		text: el.text(),
		confirmButtonText: 'Jah',
		cancelButtonText: 'Ei',
		showCancelButton: true,
		animation: 'slide-from-bottom'
	}, function(isConfirm) {
		if (!isConfirm) return;

		var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));

		for (var i = 0; i < bookmarks.length; i++) {
			var bookmark = bookmarks[i];

			if (bookmark.lat !== el.data('lat') || bookmark.lng !== el.data('lng')) continue;

			bookmarks.splice(i, 1); el.remove();

			break;
		}

		localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
	});

}

function showBookmarks() {
	var bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];

	var content = '
Lisa asukoht
';
	for (var i = 0; i < bookmarks.length; i++) {
		var bookmark = bookmarks[i];

		content += '
' + bookmark.name + '
';

	}
	$('#bookmarks').html(content);

	$('.bookmark').each(function() {
		$(this).hammer().on('swiperight', function() {
			deleteBookmark($(this));
		});
	});

	$('#bookmarks').animate({left: '0px'}, fadeTime);
}

function hideBookmarks() {
	$('#bookmarks').animate({left: '-240px'}, fadeTime);
}

// Initialization (Donation)

localStorage.setItem('visitCount', parseInt(localStorage.getItem('visitCount')) + 1 || 1);
if (!getParameter('nodonate') && (parseInt(localStorage.getItem('visitCount')) === 10 || !(parseInt(localStorage.getItem('visitCount')) % 50))) {

	swal({
		title: 'Tere!',
		text: 'Oleme märganud, et teile meeldib Bussiaeg.ee.\nKas soovite tegijaid toetada?',
		confirmButtonText: 'PayPal',
		cancelButtonText: 'Ei',
		showCancelButton: true
	}, function(isConfirm) {
		if (isConfirm) window.open('https://www.paypal.me/bussiaeg', '_self');
	});

}

// Initialization (Share)

const share = parseInt(getParameter('stop'));
if (share) if (!isNaN(share)) if (!updater) {

	showStop(share, {panMap: true, fadeIn: true});
	updater = setInterval(function() {
		showStop(share, {panMap: false, fadeIn: false});
	}, updateTime);

}

// Initialization (Map)

var map = L.map('map', {
	center: [
		parseFloat(getParameter('lat')) || 59.388,
		parseFloat(getParameter('lng')) || 24.685
	],
	zoom: zoomLevel,
	minZoom: 10,
	maxZoom: 18,
	maxBounds: [[59.874204, 21.396935], [57.290822, 28.838625]],
	attributionControl: false,
	bounceAtZoomLimits: false,
	doubleClickZoom: false,
	zoomControl: false,
	keyboard: false,
	boxZoom: false
});

L.tileLayer('//{s}.google.com/vt/lyrs=phl=en&x={x}&y={y}&z={z}&pbhttps://maps.googleapis.com/maps/vt?pb=!1m5!1m4!1i{z}!2i{x}!3i{y}!4i256!2m3!1e0!2sm!3i372053562!3m14!2sen-US!3sUS!5e18!12m1!1e47!12m3!1e37!2m1!1ssmartmaps!12m4!1e26!2m2!1sstyles!2zcy50OjY2fHAudjpvZmY!4e0', {
    subdomains: ['mt0', 'mt1', 'mt2', 'mt3']
}).addTo(map);

L.control.attribution({
	position: 'bottomleft',
	prefix: 'Bussiaeg.ee | Sõiduplaanid | Peatus | Google | Leaflet'
}).addTo(map);

showStops();
map.on('moveend', function() {
	showStops();
});

// Initialization (GPS)

navigator.geolocation.getCurrentPosition(function(pos) {
	map.flyTo([pos.coords.latitude, pos.coords.longitude], zoomLevel, {duration: flyTime});

	coords = pos.coords; $('#btn-locate').fadeIn(fadeTime * 2);

}, function(err) {}, {timeout: 3000});

navigator.geolocation.watchPosition(function(pos) {
	coords = pos.coords; $('#btn-locate').fadeIn(fadeTime * 2);
});

// User Interface

$('#btn-bookmarks, #btn-locate').on('animationend', function() {
	$(this).removeClass('bounce');
});

// User Interface (Stops)

$('#stop-top').click(function() {
	clearInterval(updater); updater = null;

	$(this).parent().fadeOut(fadeTime);

	document.title = 'Bussiaeg';
	history.pushState(null, document.title, '/');

});

// User Interface (Bookmarks)

map.on('click dragstart', function() {
	hideBookmarks();
});

$('#bookmarks').hammer().on('swipeleft', function() {
	hideBookmarks();
});

$('#btn-bookmarks').click(function() {
	$(this).addClass('bounce');
	showBookmarks();
});

$('#bookmarks').on('click', '#bookmarks-add', function() {
	addBookmark();
});

$('#bookmarks').on('click', '.bookmark', function() {
	hideBookmarks();
	map.flyTo([$(this).data('lat'), $(this).data('lng')], $(this).data('zoom'), {duration: flyTime});
});

// User Interface (Help)

$('#btn-help').click(function() {
	$(this).addClass('bounce');

	hideBookmarks();

	$('#help').fadeIn(fadeTime, function() {
		$('#btn-help').removeClass('bounce');
	});

});

$('#help').click(function() {
	$(this).fadeOut(fadeTime);
});

// User Interface (Locate)

$('#btn-locate').click(function() {
	$(this).addClass('bounce');

	if (coords) map.flyTo([coords.latitude, coords.longitude], zoomLevel, {duration: flyTime});
});<|endoftext|>


<commit_before>'use strict';

var parser = new (require('./ast').Parser)();
var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function loop() {
    rl.question('$>: ', function(answer) {
        if (answer == 'q') {
            rl.close();
            process.exit();
        }

        console.log(parser.fromSource(answer));
        console.log(parser.fromSource(answer).Eval());
        loop();
    });
};

loop();
<commit_msg>in repl, don't die on errors<commit_after>'use strict';

var parser = new (require('./ast').Parser)();
var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function loop() {
    rl.question('$>: ', function(answer) {
        if (answer == 'q') {
            rl.close();
            process.exit();
        }

        try {
            console.log(parser.fromSource(answer));
            console.log(parser.fromSource(answer).Eval());
        } catch (e) {
            console.log(e, Object.keys(e));
        }
        loop();
    });
};

loop();
<|endoftext|>


<commit_before>/**
 * Created by mingzhang on 8/22/17.
 */
'use strict';

function bubble(list) {
  let cp = list.slice();
  let j = cp.length;
  while (--j > 0) {
    for (let i = 0; i < j; i++) {
      if (cp[i] > cp[i + 1]) {
        [cp[i], cp[i + 1]] = [cp[i + 1], cp[i]];
      }
    }
  }
  return cp;
}

let a = [2, 8, 3, 7, 5, 9, 10, 4, 1, 6];

// console.log(bubble(a));

function reSplit(list) {
  if (list.length < 2) {
    return list;
  }
  if (list.length === 2) {
    if (list[0] > list[1]) {
      return [list[1], list[0]];
    }
    return list;
  }
  if (list.length >  2) {
    let p1 = [list[0]];
    let p2 = [];
    for (let i = 1; i < list.length; i++) {
      if (list[i] > list[0]) {
        p2.push(list[i]);
      } else {
        p1.push(list[i]);
      }
    }
    if (p2.length === 0) {
      return reSplit(list.slice(1)).concat(list[0]);
    } else {
      return reSplit(p1).concat(p2);
    }

  }
}

console.log(reSplit(a));<commit_msg>sorting<commit_after>/**
 * Created by mingzhang on 8/22/17.
 */
'use strict';

function bubble(list) {
  let cp = list.slice();
  let j = cp.length;
  while (--j > 0) {
    for (let i = 0; i < j; i++) {
      if (cp[i] > cp[i + 1]) {
        [cp[i], cp[i + 1]] = [cp[i + 1], cp[i]];
      }
    }
  }
  return cp;
}

let a = [2, 8, 3, 7, 5, 9, 10, 4, 1, 6];

// console.log(bubble(a));

function reSplit(list) {
  if (list.length < 2) {
    return list;
  }
  if (list.length === 2) {
    if (list[0] > list[1]) {
      return [list[1], list[0]];
    }
    return list;
  }
  if (list.length >  2) {
    let p1 = [list[0]];
    let p2 = [];
    for (let i = 1; i < list.length; i++) {
      if (list[i] > list[0]) {
        p2.push(list[i]);
      } else {
        p1.push(list[i]);
      }
    }
    if (p2.length === 0) {
      return reSplit(list.slice(1)).concat(list[0]);
    } else {
      return reSplit(p1).concat(reSplit(p2));
    }

  }
}

console.log(reSplit(a));<|endoftext|>


<commit_before>'use strict'
/* eslint-env browser */

const debug = require('debug')
const log = debug('ipfs-companion:client:external')
log.error = debug('ipfs-companion:client:external:error')

const IpfsApi = require('ipfs-http-client')

exports.init = async function (opts) {
  log(`init with IPFS API at ${opts.apiURLString}`)

  const url = opts.apiURL
  const protocol = url.protocol.substr(0, url.protocol.length - 1) // http: -> http
  const host = url.hostname.replace(/[[\]]+/g, '') // temporary fix for ipv6: https://github.com/ipfs-shipyard/ipfs-companion/issues/668
  const api = IpfsApi({ host, port: url.port, protocol })
  return api
}

exports.destroy = async function () {
  log('destroy')
}
<commit_msg>fix: support API on ipv6 with go-ipfs 0.8+ (#931)<commit_after>'use strict'
/* eslint-env browser */

const debug = require('debug')
const log = debug('ipfs-companion:client:external')
log.error = debug('ipfs-companion:client:external:error')

const httpClient = require('ipfs-http-client')

exports.init = async function (opts) {
  log(`init with IPFS API at ${opts.apiURLString}`)
  const clientConfig = opts.apiURLString
  // https://github.com/ipfs/js-ipfs/tree/master/packages/ipfs-http-client#importing-the-module-and-usage
  const api = httpClient(clientConfig)
  return api
}

exports.destroy = async function () {
  log('destroy')
}
<|endoftext|>


<commit_before>/**
 * @author Craig Thayer <cthayer@sazze.com>
 * @copyright 2014 Sazze, Inc.
 */

var _ = require('lodash');
var client = require('request');
var async = require('async');

var AURA_DEFINED = !_.isUndefined(global.aura);

var log = (!AURA_DEFINED || _.isUndefined(global.aura.log) ? {error: console.error, warn: console.warn, info: console.info, debug: _.noop, verbose: _.noop} : global.aura.log);

function Riak(bucket) {
  this.bucket = bucket;
  this.host = process.env.SZ_RIAK_HOST || (AURA_DEFINED && !_.isUndefined(global.aura.config.riak) ? global.aura.config.riak.host : '127.0.0.1');
  this.port = process.env.SZ_RIAK_PORT || (AURA_DEFINED && !_.isUndefined(global.aura.config.riak) ? global.aura.config.riak.port : 8098);
}

Riak.ASYNC_LIMIT = 20;

//
// static methods
//

Riak.parseHeaders = function (headers) {
  var properties = {
    vclock: '',
    links: [],
    meta: {},
    index: {},
    contentType: ''
  };

  if (_.isEmpty(headers)) {
    return properties;
  }

  _.forEach(headers, function (val, name) {
    switch (name.toLowerCase()) {
      case 'content-type':
        properties.contentType = val;
        break;

      case 'x-riak-vclock':
        properties.vclock = val;
        break;

      case 'link':
        val = val.split(',');

        _.forEach(val, function (l) {
          var parts = l.trim().split(';');
          var link = {link: parts[0].trim().replace('<', '').replace('>', ''), tag: ''};

          if (!_.isUndefined(parts[1])) {
            // skip internal riak headers that are not allowed client requests
            if (_.contains(parts[1], 'rel=')) {
              return;
            }

            link.tag = parts[1].trim().replace('riaktag="', '').replace('"', '');
          }

          properties.links.push(link);
        });

        break;

      default:
        if (_.contains(name, 'x-riak-meta-')) {
          properties.meta[name.replace('x-riak-meta-', '')] = val;
          break;
        }

        if (_.contains(name, 'x-riak-index-')) {
          if (_.contains(name, 'x-riak-index-')) {
            properties.index[name.replace('x-riak-index-', '')] = val;
            break;
          }
        }

        break;
    }
  });

  log.verbose(properties);

  return properties;
};

Riak.prepareHeaders = function (obj) {
  var headers = {};

  if (_.isEmpty(obj)) {
    return headers;
  }

  var links = [];

  _.forEach(obj, function (val, name) {
    switch (name.toLowerCase()) {
      case 'vclock':
        headers['x-riak-vclock'] = val;

        delete obj.vclock;

        break;

      case 'links':
        _.forEach(obj.links, function (link) {
          if (_.isUndefined(link.link)) {
            return;
          }

          if (_.isUndefined(link.tag) || _.isEmpty(link.tag)) {
            links.push('<' + link.link + '>');
          } else {
            links.push('<' + link.link + '>; riaktag="' + link.tag + '"');
          }
        });

        delete obj.links;

        break;

      case 'meta':
        _.forEach(obj.meta, function (val, name) {
          headers['x-riak-meta-' + name] = val;
        });

        delete obj.meta;

        break;

      case 'index':
        _.forEach(obj.index, function (val, name) {
          headers['x-riak-index-' + name] = val;
        });

        delete obj.index;

        break;

      default:
        break;
    }
  });

  if (links.length > 0) {
    headers['link'] = links.join(', ');
  }

  log.verbose(headers);

  return headers;
};

module.exports = Riak;

//
// methods
//

Riak.prototype.getUrl = function (key) {
  return 'http://' + this.host + ':' + this.port + '/buckets/' + this.bucket + '/keys/' + key;
};

Riak.prototype.mget = function (keys, cb) {
  if (!_.isArray(keys)) {
    cb(new Error('keys must be an array'));
    return;
  }

  async.mapLimit(keys, Riak.ASYNC_LIMIT, function (key, callback) {
    this.get(key, function (err, res, headers) {
      callback(err, {resp: res, headers: headers});
    });
  }.bind(this), function (err, results) {
    cb(err, results);
  });
};

Riak.prototype.get = function (key, cb) {
  if (!_.isFunction(cb)) {
    cb = _.noop;
  }

  if (!_.isString(key) || !key) {
    cb(new Error('Invalid key: ' + key));
    return;
  }

  var url = this.getUrl(key);

  log.verbose('riak url: GET ' + url);

  client(url, function (err, resp, body) {
    if (err) {
      cb(err);
      return;
    }

    log.debug('riak response code: ' + resp.statusCode);
    log.verbose('riak headers: ' + JSON.stringify(resp.headers));
    log.verbose('riak response: ' + body);

    if (resp.statusCode == 404) {
      // handle not found response
      cb(null, {});
      return;
    }

    if (resp.statusCode != 200) {
      cb(new Error('riak returned status code: ' + resp.statusCode));
      return;
    }

    if (_.isString(body) && resp.headers['content-type'].toLowerCase() == 'application/json') {
      body = JSON.parse(body);
    }

    _.merge(body, Riak.parseHeaders(resp.headers));

    cb(null, body, resp.headers);
  });
};

Riak.prototype.mput = function (puts, cb) {
  if (!_.isArray(puts)) {
    cb(new Error('puts must be an array of put objects'));
    return;
  }

  async.mapLimit(puts, Riak.ASYNC_LIMIT, function (put, callback) {
    if (!_.isPlainObject(put)) {
      callback(new Error('Invalid request object: ' + put));
      return;
    }

    this.put(put.key, put.body, put.headers, function (err, res, headers) {
      callback(err, {resp: res, headers: headers});
    });
  }.bind(this), function (err, results) {
    cb(err, results);
  });
};

Riak.prototype.put = function (key, body, headers, cb) {
  if (_.isUndefined(headers)) {
    headers = {};
  }

  if (_.isFunction(headers)) {
    cb = headers;
    headers = {};
  }

  if (!_.isFunction(cb)) {
    cb = _.noop;
  }

  if (!_.isString(key) || !key) {
    cb(new Error('Invalid key: ' + key));
    return;
  }

  // if the body is not a string, we treat it as an object and store with content-type: application/json
  if (!_.isString(body)) {
    headers['content-type'] = 'application/json';

    if (_.isObject(body)) {
      _.merge(headers, Riak.prepareHeaders(body));
    }

    body = JSON.stringify(body);
  }

  if (_.isUndefined(headers['content-type'])) {
    headers['content-type'] = 'text/plain';
  }

  var url = this.getUrl(key);

  log.verbose('riak url: PUT ' + url);

  client.put({url: url, body: body, headers: headers, qs: {returnbody: true}}, function (err, resp, body) {
    if (err) {
      cb(err);
      return;
    }

    log.debug('riak response code: ' + resp.statusCode);
    log.verbose('riak headers: ' + JSON.stringify(resp.headers));
    log.verbose('riak response: ' + body);

    if (resp.statusCode != 200) {
      cb(new Error('riak returned status code: ' + resp.statusCode));
      return;
    }

    if (_.isString(body) && resp.headers['content-type'].toLowerCase() == 'application/json') {
      body = JSON.parse(body);
    }

    _.merge(body, Riak.parseHeaders(resp.headers));

    cb(null, body, resp.headers);
  });
};

Riak.prototype.mdel = function (keys, cb) {
  if (!_.isArray(keys)) {
    cb(new Error('keys must be an array'));
    return;
  }

  async.mapLimit(keys, Riak.ASYNC_LIMIT, this.del.bind(this), function (err) {
    cb(err);
  });
};

Riak.prototype.del = function (key, cb) {
  if (!_.isFunction(cb)) {
    cb = _.noop;
  }

  if (!_.isString(key) || !key) {
    cb(new Error('Invalid key: ' + key));
    return;
  }

  var url = this.getUrl(key);

  log.verbose('riak url: DELETE ' + url);

  client.del(url, function (err, resp) {
    if (err) {
      cb(err);
      return;
    }

    log.debug('riak response code: ' + resp.statusCode);
    log.verbose('riak headers: ' + JSON.stringify(resp.headers));

    if (resp.statusCode == 404) {
      // handle not found response
      cb(null);
      return;
    }

    if (resp.statusCode != 204) {
      cb(new Error('riak returned status code: ' + resp.statusCode));
      return;
    }

    cb(null);
  });
};<commit_msg>allow ASYNC_LIMIT to be configurable via the SZ_RIAK_ASYNC_LIMIT environment variable<commit_after>/**
 * @author Craig Thayer <cthayer@sazze.com>
 * @copyright 2014 Sazze, Inc.
 */

var _ = require('lodash');
var client = require('request');
var async = require('async');

var AURA_DEFINED = !_.isUndefined(global.aura);

var log = (!AURA_DEFINED || _.isUndefined(global.aura.log) ? {error: console.error, warn: console.warn, info: console.info, debug: _.noop, verbose: _.noop} : global.aura.log);

function Riak(bucket) {
  this.bucket = bucket;
  this.host = process.env.SZ_RIAK_HOST || (AURA_DEFINED && !_.isUndefined(global.aura.config.riak) ? global.aura.config.riak.host : '127.0.0.1');
  this.port = process.env.SZ_RIAK_PORT || (AURA_DEFINED && !_.isUndefined(global.aura.config.riak) ? global.aura.config.riak.port : 8098);
}

Riak.ASYNC_LIMIT = process.env.SZ_RIAK_ASYNC_LIMIT || 20;

//
// static methods
//

Riak.parseHeaders = function (headers) {
  var properties = {
    vclock: '',
    links: [],
    meta: {},
    index: {},
    contentType: ''
  };

  if (_.isEmpty(headers)) {
    return properties;
  }

  _.forEach(headers, function (val, name) {
    switch (name.toLowerCase()) {
      case 'content-type':
        properties.contentType = val;
        break;

      case 'x-riak-vclock':
        properties.vclock = val;
        break;

      case 'link':
        val = val.split(',');

        _.forEach(val, function (l) {
          var parts = l.trim().split(';');
          var link = {link: parts[0].trim().replace('<', '').replace('>', ''), tag: ''};

          if (!_.isUndefined(parts[1])) {
            // skip internal riak headers that are not allowed client requests
            if (_.contains(parts[1], 'rel=')) {
              return;
            }

            link.tag = parts[1].trim().replace('riaktag="', '').replace('"', '');
          }

          properties.links.push(link);
        });

        break;

      default:
        if (_.contains(name, 'x-riak-meta-')) {
          properties.meta[name.replace('x-riak-meta-', '')] = val;
          break;
        }

        if (_.contains(name, 'x-riak-index-')) {
          if (_.contains(name, 'x-riak-index-')) {
            properties.index[name.replace('x-riak-index-', '')] = val;
            break;
          }
        }

        break;
    }
  });

  log.verbose(properties);

  return properties;
};

Riak.prepareHeaders = function (obj) {
  var headers = {};

  if (_.isEmpty(obj)) {
    return headers;
  }

  var links = [];

  _.forEach(obj, function (val, name) {
    switch (name.toLowerCase()) {
      case 'vclock':
        headers['x-riak-vclock'] = val;

        delete obj.vclock;

        break;

      case 'links':
        _.forEach(obj.links, function (link) {
          if (_.isUndefined(link.link)) {
            return;
          }

          if (_.isUndefined(link.tag) || _.isEmpty(link.tag)) {
            links.push('<' + link.link + '>');
          } else {
            links.push('<' + link.link + '>; riaktag="' + link.tag + '"');
          }
        });

        delete obj.links;

        break;

      case 'meta':
        _.forEach(obj.meta, function (val, name) {
          headers['x-riak-meta-' + name] = val;
        });

        delete obj.meta;

        break;

      case 'index':
        _.forEach(obj.index, function (val, name) {
          headers['x-riak-index-' + name] = val;
        });

        delete obj.index;

        break;

      default:
        break;
    }
  });

  if (links.length > 0) {
    headers['link'] = links.join(', ');
  }

  log.verbose(headers);

  return headers;
};

module.exports = Riak;

//
// methods
//

Riak.prototype.getUrl = function (key) {
  return 'http://' + this.host + ':' + this.port + '/buckets/' + this.bucket + '/keys/' + key;
};

Riak.prototype.mget = function (keys, cb) {
  if (!_.isArray(keys)) {
    cb(new Error('keys must be an array'));
    return;
  }

  async.mapLimit(keys, Riak.ASYNC_LIMIT, function (key, callback) {
    this.get(key, function (err, res, headers) {
      callback(err, {resp: res, headers: headers});
    });
  }.bind(this), function (err, results) {
    cb(err, results);
  });
};

Riak.prototype.get = function (key, cb) {
  if (!_.isFunction(cb)) {
    cb = _.noop;
  }

  if (!_.isString(key) || !key) {
    cb(new Error('Invalid key: ' + key));
    return;
  }

  var url = this.getUrl(key);

  log.verbose('riak url: GET ' + url);

  client(url, function (err, resp, body) {
    if (err) {
      cb(err);
      return;
    }

    log.debug('riak response code: ' + resp.statusCode);
    log.verbose('riak headers: ' + JSON.stringify(resp.headers));
    log.verbose('riak response: ' + body);

    if (resp.statusCode == 404) {
      // handle not found response
      cb(null, {});
      return;
    }

    if (resp.statusCode != 200) {
      cb(new Error('riak returned status code: ' + resp.statusCode));
      return;
    }

    if (_.isString(body) && resp.headers['content-type'].toLowerCase() == 'application/json') {
      body = JSON.parse(body);
    }

    _.merge(body, Riak.parseHeaders(resp.headers));

    cb(null, body, resp.headers);
  });
};

Riak.prototype.mput = function (puts, cb) {
  if (!_.isArray(puts)) {
    cb(new Error('puts must be an array of put objects'));
    return;
  }

  async.mapLimit(puts, Riak.ASYNC_LIMIT, function (put, callback) {
    if (!_.isPlainObject(put)) {
      callback(new Error('Invalid request object: ' + put));
      return;
    }

    this.put(put.key, put.body, put.headers, function (err, res, headers) {
      callback(err, {resp: res, headers: headers});
    });
  }.bind(this), function (err, results) {
    cb(err, results);
  });
};

Riak.prototype.put = function (key, body, headers, cb) {
  if (_.isUndefined(headers)) {
    headers = {};
  }

  if (_.isFunction(headers)) {
    cb = headers;
    headers = {};
  }

  if (!_.isFunction(cb)) {
    cb = _.noop;
  }

  if (!_.isString(key) || !key) {
    cb(new Error('Invalid key: ' + key));
    return;
  }

  // if the body is not a string, we treat it as an object and store with content-type: application/json
  if (!_.isString(body)) {
    headers['content-type'] = 'application/json';

    if (_.isObject(body)) {
      _.merge(headers, Riak.prepareHeaders(body));
    }

    body = JSON.stringify(body);
  }

  if (_.isUndefined(headers['content-type'])) {
    headers['content-type'] = 'text/plain';
  }

  var url = this.getUrl(key);

  log.verbose('riak url: PUT ' + url);

  client.put({url: url, body: body, headers: headers, qs: {returnbody: true}}, function (err, resp, body) {
    if (err) {
      cb(err);
      return;
    }

    log.debug('riak response code: ' + resp.statusCode);
    log.verbose('riak headers: ' + JSON.stringify(resp.headers));
    log.verbose('riak response: ' + body);

    if (resp.statusCode != 200) {
      cb(new Error('riak returned status code: ' + resp.statusCode));
      return;
    }

    if (_.isString(body) && resp.headers['content-type'].toLowerCase() == 'application/json') {
      body = JSON.parse(body);
    }

    _.merge(body, Riak.parseHeaders(resp.headers));

    cb(null, body, resp.headers);
  });
};

Riak.prototype.mdel = function (keys, cb) {
  if (!_.isArray(keys)) {
    cb(new Error('keys must be an array'));
    return;
  }

  async.mapLimit(keys, Riak.ASYNC_LIMIT, this.del.bind(this), function (err) {
    cb(err);
  });
};

Riak.prototype.del = function (key, cb) {
  if (!_.isFunction(cb)) {
    cb = _.noop;
  }

  if (!_.isString(key) || !key) {
    cb(new Error('Invalid key: ' + key));
    return;
  }

  var url = this.getUrl(key);

  log.verbose('riak url: DELETE ' + url);

  client.del(url, function (err, resp) {
    if (err) {
      cb(err);
      return;
    }

    log.debug('riak response code: ' + resp.statusCode);
    log.verbose('riak headers: ' + JSON.stringify(resp.headers));

    if (resp.statusCode == 404) {
      // handle not found response
      cb(null);
      return;
    }

    if (resp.statusCode != 204) {
      cb(new Error('riak returned status code: ' + resp.statusCode));
      return;
    }

    cb(null);
  });
};<|endoftext|>


<commit_before>import Ember from 'ember';
import TooltipAndPopoverComponent from 'ember-tooltips/components/tooltip-and-popover';
import layout from 'ember-tooltips/templates/components/popover-on-element';

const { $, run } = Ember;

export default TooltipAndPopoverComponent.extend({

  hideDelay: '250',

  layout,
  classNames: ['ember-popover'],
  _isMouseInside: false,
  didInsertElement() {
    this._super(...arguments);

    const event = this.get('event');
    const target = this.get('target');
    const $target = $(target);
    const $popover = this.$();

    if (event === 'none') {

      return;

    } else if (event === 'hover') {

      const _showOn = this.get('_showOn');
      const _hideOn = this.get('_hideOn');

      // _showOn == 'mouseenter'
      $target.on(_showOn, () => this.show());

      // _hideOn == 'mouseleave'
      $target.add($popover).on(_hideOn, () => {
        run.later(() => {
          if (!this.get('_isMouseInside')) {
            this.hide();
          }
        }, +this.get('hideDelay'));
      });

      // we must use mouseover/mouseout because they correctly
      // register hover interactivity when spacing='0'
      $target.add($popover).on('mouseover', () => this.set('_isMouseInside', true));
      $target.add($popover).on('mouseout', () => this.set('_isMouseInside', false));

    } else if (event === 'click') {

      $(document).on(`click.${target}`, (event) => {
        // this lightweight, name-spaced click handler is necessary to determine
        // if a click is NOT on $target and NOT an ancestor of $target.
        // If so then it must be a click elsewhere and should close the popover
        // see... https://css-tricks.com/dangers-stopping-event-propagation/
        const isClickedElementElsewhere = this._isElementElsewhere(event.target);
        const isPopoverShown = this.get('isShown');

        if (isClickedElementElsewhere && isPopoverShown) {
          this.hide();
        }
      });

      // we use mousedown because it occurs before the focus event
      $target.on('mousedown', (event) => {
        // $target.on('mousedown') is called when the $popover is
        // clicked because the $popover is contained within the $target.
        // This will ignores those types of clicks.
        const isMouseDownElementInPopover = this._isElementInPopover(event.target);
        if (isMouseDownElementInPopover) {
          return;
        }
        this.toggle();
      });
    }

    $target.on('focus', () => this.show());

    $popover.on('focusout', () => {
      // use a run.later() to allow the 'focusout' event to finish handling
      run.later(() => {
        const isFocusedElementElsewhere = this._isElementElsewhere(document.activeElement);
        if (isFocusedElementElsewhere) {
          this.hide();
        }
      });
    });
  },
  willDestroyElement() {
    this._super(...arguments);

    const target = this.get('target');
    const $target = $(target);
    const $popover = this.$();
    const _showOn = this.get('_showOn');
    const _hideOn = this.get('_hideOn');

    $target.add($popover).off(`${_showOn} mouseover ${_hideOn} mouseout mousedown focus focusout`);

    $(document).off(`click.${target}`);
  },
  _isElementInPopover(newElement) {
    // determines if newElement is $popover or contained within $popover
    const $popover = this.$();
    return $popover.is(newElement) || $popover.find(newElement).length;
  },
  _isElementElsewhere(newElement) {
    // determines if newElement is not $target, not $popover, and not contained within either
    const $target = $(this.get('target'));

    const isNewElementOutsideTarget = !$target.is(newElement) && !$target.find(newElement).length;
    const isNewElementOutsidePopover = !this._isElementInPopover(newElement);

    return isNewElementOutsideTarget && isNewElementOutsidePopover;
  },
  actions: {
    hide() {
      this.hide();
    }
  },
});
<commit_msg>make hideDelay an integer<commit_after>import Ember from 'ember';
import TooltipAndPopoverComponent from 'ember-tooltips/components/tooltip-and-popover';
import layout from 'ember-tooltips/templates/components/popover-on-element';

const { $, run } = Ember;

export default TooltipAndPopoverComponent.extend({

  /* Options */
  hideDelay: 250,

  /* Properties */
  layout,
  classNames: ['ember-popover'],
  _isMouseInside: false,
  didInsertElement() {
    this._super(...arguments);

    const event = this.get('event');
    const target = this.get('target');
    const $target = $(target);
    const $popover = this.$();

    if (event === 'none') {

      return;

    } else if (event === 'hover') {

      const _showOn = this.get('_showOn');
      const _hideOn = this.get('_hideOn');

      // _showOn == 'mouseenter'
      $target.on(_showOn, () => this.show());

      // _hideOn == 'mouseleave'
      $target.add($popover).on(_hideOn, () => {
        run.later(() => {
          if (!this.get('_isMouseInside')) {
            this.hide();
          }
        }, +this.get('hideDelay'));
      });

      // we must use mouseover/mouseout because they correctly
      // register hover interactivity when spacing='0'
      $target.add($popover).on('mouseover', () => this.set('_isMouseInside', true));
      $target.add($popover).on('mouseout', () => this.set('_isMouseInside', false));

    } else if (event === 'click') {

      $(document).on(`click.${target}`, (event) => {
        // this lightweight, name-spaced click handler is necessary to determine
        // if a click is NOT on $target and NOT an ancestor of $target.
        // If so then it must be a click elsewhere and should close the popover
        // see... https://css-tricks.com/dangers-stopping-event-propagation/
        const isClickedElementElsewhere = this._isElementElsewhere(event.target);
        const isPopoverShown = this.get('isShown');

        if (isClickedElementElsewhere && isPopoverShown) {
          this.hide();
        }
      });

      // we use mousedown because it occurs before the focus event
      $target.on('mousedown', (event) => {
        // $target.on('mousedown') is called when the $popover is
        // clicked because the $popover is contained within the $target.
        // This will ignores those types of clicks.
        const isMouseDownElementInPopover = this._isElementInPopover(event.target);
        if (isMouseDownElementInPopover) {
          return;
        }
        this.toggle();
      });
    }

    $target.on('focus', () => this.show());

    $popover.on('focusout', () => {
      // use a run.later() to allow the 'focusout' event to finish handling
      run.later(() => {
        const isFocusedElementElsewhere = this._isElementElsewhere(document.activeElement);
        if (isFocusedElementElsewhere) {
          this.hide();
        }
      });
    });
  },
  willDestroyElement() {
    this._super(...arguments);

    const target = this.get('target');
    const $target = $(target);
    const $popover = this.$();
    const _showOn = this.get('_showOn');
    const _hideOn = this.get('_hideOn');

    $target.add($popover).off(`${_showOn} mouseover ${_hideOn} mouseout mousedown focus focusout`);

    $(document).off(`click.${target}`);
  },
  _isElementInPopover(newElement) {
    // determines if newElement is $popover or contained within $popover
    const $popover = this.$();
    return $popover.is(newElement) || $popover.find(newElement).length;
  },
  _isElementElsewhere(newElement) {
    // determines if newElement is not $target, not $popover, and not contained within either
    const $target = $(this.get('target'));

    const isNewElementOutsideTarget = !$target.is(newElement) && !$target.find(newElement).length;
    const isNewElementOutsidePopover = !this._isElementInPopover(newElement);

    return isNewElementOutsideTarget && isNewElementOutsidePopover;
  },
  actions: {
    hide() {
      this.hide();
    }
  },
});
<|endoftext|>


<commit_before>function (user, context, callback) {
  var jwt  = require("jsonwebtoken");
  var CLIENTS_WITH_MFA = ['{REPLACE_WITH_YOUR_CLIENT_ID}'];

  // run only for the specified clients
  if (CLIENTS_WITH_MFA.indexOf(context.clientID) === -1) {
    return callback(null,user,context);
  }

  // returning from MFA validation
  if(context.protocol === 'redirect-callback') {

    var decoded = jwt.verify(context.request.query.id_token, new Buffer(configuration.slack_mfa_secret, 'base64'));
    if (!decoded) return callback(new Error('Invalid Token'));
    if (decoded.status !== 'ok') return callback(new Error('Invalid Token Status'));

    return callback(null, user, context);

  } else {

    var uuid = require('uuid');
    var token_payload = { jti: uuid.v4() };
    if (user.user_metadata) {
      token_payload = {
        slack_username: user.user_metadata.slack_mfa_username,
        slack_enrolled:  user.user_metadata.slack_mfa_enrolled,
        jti: uuid.v4()
      };
    }

    var token = jwt.sign(token_payload,
      new Buffer(configuration.slack_mfa_secret, 'base64'),
      {
        subject: user.user_id,
        expiresInMinutes: 5,
        audience: context.clientID,
        issuer: 'urn:sgmeyer:slack:mfa',
        iat: new Date().getTime() / 1000,
      });

    //Trigger MFA
    context.redirect = { url: configuration.slack_mfa_url + '?token=' + token };
    callback(null, user, context);

  }
}
<commit_msg>Restricting callback to only accept the callback issuer token<commit_after>function (user, context, callback) {
  var jwt  = require("jsonwebtoken");
  var CLIENTS_WITH_MFA = ['{REPLACE_WITH_YOUR_CLIENT_ID}'];

  // run only for the specified clients
  if (CLIENTS_WITH_MFA.indexOf(context.clientID) === -1) {
    return callback(null,user,context);
  }

  // returning from MFA validation
  if(context.protocol === 'redirect-callback') {
    var decoded = jwt.verify(context.request.query.id_token, new Buffer(configuration.slack_mfa_secret, 'base64'));
    if (!decoded || decoded.issuer !== 'urn:sgmeyer:slack:mfacallback') return callback(new Error('Invalid Token'));

    return callback(null, user, context);
  } else {
    var uuid = require('uuid');
    var token_payload = { jti: uuid.v4() };
    if (user.user_metadata) {
      token_payload = {
        slack_username: user.user_metadata.slack_mfa_username,
        slack_enrolled:  user.user_metadata.slack_mfa_enrolled,
        jti: uuid.v4()
      };
    }

    var token = jwt.sign(token_payload,
      new Buffer(configuration.slack_mfa_secret, 'base64'),
      {
        subject: user.user_id,
        expiresInMinutes: 5,
        audience: context.clientID,
        issuer: 'urn:sgmeyer:slack:mfa',
        iat: new Date().getTime() / 1000,
      });

    //Trigger MFA
    context.redirect = { url: configuration.slack_mfa_url + '?token=' + token };
    callback(null, user, context);
  }
}
<|endoftext|>


<commit_before>'use strict';

(function(root, factory) {

    if (typeof exports === 'object' && exports) {
        factory(exports); // CommonJS
    } else {
        var sUTL = {};
        factory(sUTL);
        if (typeof define === 'function' && define.amd)
            define(sUTL); // AMD
        else
            root.sUTL = sUTL; // <script>
    }

}(this, function(sUTL) {

    //exports
    sUTL.name = 'sUTL.js';
    sUTL.version = '0.0.0';
    sUTL.transform = transform;

    function builtins()
    {
        return {
            "path": function(parentscope, scope, source, tt)
            {
                var fullpath = scope["path"]
                var unwrap = scope["unwrap"]

                var prefix = fullpath.slice(0, 1)
                var path = fullpath.slice(1)
                var childscope = null;

                if (prefix == '@')
                {
                    childscope = parentscope
                }
                if (prefix == '^')
                {
                    childscope = scope
                }
                else if (prefix == '$')
                {
                    childscope = source
                }
                else if (prefix == '~')
                {
                    childscope = tt
                }

                var retval = jsonPath(childscope, "$" + path)

                if (unwrap)
                {
                    if (retval.length > 0)
                        retval = retval[0]
                    else
                        retval = null
                }

                return retval
            },
            "cons": function(parentscope, scope, source, tt)
            {
                var head = scope["head"]
                var tail = scope["tail"]

                var retval = [head]

                if (tail)
                    retval = retval.concat(tail)

                return retval
            },
            "last": function(parentscope, scope, source, tt)
            {
                var lin = scope["in"]

                var retval = lin[lin.length-1]

                return retval
            },
            "add": function(parentscope, scope, source, tt)
            {
                var a = scope["a"]
                var b = scope["b"]

                return a + b
            },
            "if": function(parentscope, scope, source, tt)
            {
                var retval = null;
                var condvalue = false;

                if ("cond" in scope)
                    condvalue = Evaluate(parentscope, scope["cond"], source, tt)
                    if (isArray(condvalue) && condvalue.length == 0)
                        condvalue = false

                if (condvalue)
                {
                    if ("true" in scope)
                        retval = Evaluate(parentscope, scope["true"], source, tt)
                }
                else
                {
                    if ("false" in scope)
                        retval = Evaluate(parentscope, scope["false"], source, tt)
                }

                return retval
            }
        }
    }

    function transform(source, t)
    {
        return Evaluate(source, t, source, t)
    }

    function Evaluate(scope, t, source, tt)
    {
        var retval = null;

        if (isBuiltinEval(t))
        {
            var builtinf = builtins()[t["&"]]
            if (!builtinf)
            {
                throw {"message": "builtin '" + t["&"] + "' not found"}
            }
            else
            {
                var transformedt = {}
                for (key in t)
                {
                    if (key != "&")
                    {
                        transformedt[key] = Evaluate(scope, t[key], source, tt)
                    }
                }

                retval = builtinf(scope, transformedt, source, tt)
            }
        }
        else if (isSimpleEval(t))
        {
            var transform = Evaluate(scope, t["!"], source, tt)

            var transformscope = {}
            for (key in t)
            {
                if (key != "!")
                {
                    transformscope[key] = Evaluate(scope, t[key], source, tt)
                }
            }

            retval = Evaluate(transformscope, transform, source, tt)
        }
        else if (isQuoteEval(t))
        {
            retval = t["'"]
        }
        else if (isObject(t))
        {
            retval = {}
            for (var key in t)
            {
                retval[key] = Evaluate(scope, t[key], source, tt)
            }
        }
        else if (isArray(t))
        {
            retval = []
            var unwrap = false
            for (var ix in t)
            {
                if (ix == 0 && t[ix] == "&&")
                {
                    unwrap = true
                    continue;
                }
                var itemresult = Evaluate(scope, t[ix], source, tt)
                if (unwrap && isArray(itemresult))
                    retval = retval.concat(itemresult)
                else
                    retval.push(itemresult)
            }
        }
        else if (isPath(t))
        {
            retval = Evaluate(scope, {"&": "path", "unwrap": false, "path": t.slice(2)}, source, tt)
        }
        else if (isUnwrapPath(t))
        {
            retval = Evaluate(scope, {"&": "path", "unwrap": true, "path": t.slice(1)}, source, tt)
        }
        else
        {
            retval = t;
        }

        return retval;
    }

    function isBuiltinEval(obj) {
        return isObject(obj) && "&" in obj;
    }

    function isSimpleEval(obj) {
        return isObject(obj) && "!" in obj;
    }

    function isQuoteEval(obj) {
        return isObject(obj) && "'" in obj;
    }

    function isObject(obj) {
        return !isArray(obj) && obj === Object(obj);
    }

    function isArray(obj) {
        return Array.isArray(obj)
    }

    function isString(obj) {
        return (typeof obj === 'string' || obj instanceof String);
    }

    function isPath(obj) {
        return isString(obj) && obj.slice(0, 2) == "##";
    }

    function isUnwrapPath(obj) {
        return isString(obj) && obj.slice(0, 1) == "#";
    }

    /* JSONPath 0.8.5 - XPath for JSON
 *
 * Copyright (c) 2007 Stefan Goessner (goessner.net)
 * Licensed under the MIT (MIT-LICENSE.txt) licence.
 *
 * Proposal of Chris Zyp goes into version 0.9.x
 * Issue 7 resolved
 */
    function jsonPath(obj, expr, arg) {
        var P = {
            resultType: arg && arg.resultType || "VALUE",
            result: [],
            normalize: function(expr) {
                var subx = [];
                return expr.replace(/[\['](\??\(.*?\))[\]']|\['(.*?)'\]/g, function($0, $1, $2) {
                    return "[#" + (subx.push($1 || $2) - 1) + "]";
                }) /* http://code.google.com/p/jsonpath/issues/detail?id=4 */
                .replace(/'?\.'?|\['?/g, ";")
                .replace(/;;;|;;/g, ";..;")
                .replace(/;$|'?\]|'$/g, "")
                .replace(/#([0-9]+)/g, function($0, $1) {
                    return subx[$1];
                });
            },
            asPath: function(path) {
                var x = path.split(";"), p = "$";
                for (var i = 1, n = x.length; i < n; i++)
                    p += /^[0-9*]+$/.test(x[i]) ? ("[" + x[i] + "]") : ("['" + x[i] + "']");
                return p;
            },
            store: function(p, v) {
                if (p)
                    P.result[P.result.length] = P.resultType == "PATH" ? P.asPath(p) : v;
                return !!p;
            },
            trace: function(expr, val, path) {
                if (expr !== "") {
                    var x = expr.split(";"), loc = x.shift();
                    x = x.join(";");
                    if (val && val.hasOwnProperty(loc))
                        P.trace(x, val[loc], path + ";" + loc);
                    else if (loc === "*")
                        P.walk(loc, x, val, path, function(m, l, x, v, p) {
                            P.trace(m + ";" + x, v, p);
                        });
                    else if (loc === "..") {
                        P.trace(x, val, path);
                        P.walk(loc, x, val, path, function(m, l, x, v, p) {
                            typeof v[m] === "object" && P.trace("..;" + x, v[m], p + ";" + m);
                        });
                    }
                    else if (/^\(.*?\)$/.test(loc)) // [(expr)]
                        P.trace(P.eval(loc, val, path.substr(path.lastIndexOf(";") + 1)) + ";" + x, val, path);
                    else if (/^\?\(.*?\)$/.test(loc)) // [?(expr)]
                        P.walk(loc, x, val, path, function(m, l, x, v, p) {
                            if (P.eval(l.replace(/^\?\((.*?)\)$/, "$1"), v instanceof Array ? v[m] : v, m))
                                P.trace(m + ";" + x, v, p);
                        }); // issue 5 resolved
                    else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc)) // [start:end:step]  phyton slice syntax
                        P.slice(loc, x, val, path);
                    else if (/,/.test(loc)) { // [name1,name2,...]
                        for (var s = loc.split(/'?,'?/), i = 0, n = s.length; i < n; i++)
                            P.trace(s[i] + ";" + x, val, path);
                    }
                }
                else
                    P.store(path, val);
            },
            walk: function(loc, expr, val, path, f) {
                if (val instanceof Array) {
                    for (var i = 0, n = val.length; i < n; i++)
                        if (i in val)
                            f(i, loc, expr, val, path);
                }
                else if (typeof val === "object") {
                    for (var m in val)
                        if (val.hasOwnProperty(m))
                            f(m, loc, expr, val, path);
                }
            },
            slice: function(loc, expr, val, path) {
                if (val instanceof Array) {
                    var len = val.length, start = 0, end = len, step = 1;
                    loc.replace(/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/g, function($0, $1, $2, $3) {
                        start = parseInt($1 || start);
                        end = parseInt($2 || end);
                        step = parseInt($3 || step);
                    });
                    start = (start < 0) ? Math.max(0, start + len) : Math.min(len, start);
                    end = (end < 0) ? Math.max(0, end + len) : Math.min(len, end);
                    for (var i = start; i < end; i += step)
                        P.trace(i + ";" + expr, val, path);
                }
            },
            eval: function(x, _v, _vname) {
                try {
                    return $ && _v && eval(x.replace(/(^|[^\\])@/g, "$1_v").replace(/\\@/g, "@"));
                }  // issue 7 : resolved ..
                catch (e) {
                    throw new SyntaxError("jsonPath: " + e.message + ": " + x.replace(/(^|[^\\])@/g, "$1_v").replace(/\\@/g, "@"));
                } // issue 7 : resolved ..
            }
        };

        var $ = obj;
        if (expr && obj && (P.resultType == "VALUE" || P.resultType == "PATH")) {
            P.trace(P.normalize(expr).replace(/^\$;?/, ""), obj, "$"); // issue 6 resolved
            return P.result.length ? P.result : false;
        }
    }

}));
<commit_msg>Added a bunch of builtins<commit_after>'use strict';

(function(root, factory) {

    if (typeof exports === 'object' && exports) {
        factory(exports); // CommonJS
    } else {
        var sUTL = {};
        factory(sUTL);
        if (typeof define === 'function' && define.amd)
            define(sUTL); // AMD
        else
            root.sUTL = sUTL; // <script>
    }

}(this, function(sUTL) {

    //exports
    sUTL.name = 'sUTL.js';
    sUTL.version = '0.0.0';
    sUTL.transform = transform;

    function get(scope, key, adefault)
    {
        if (key in scope)
            return scope[key]
        else
            return adefault
    }

    function builtins()
    {
        return {
            "path": function(parentscope, scope, source, tt)
            {
                var fullpath = scope["path"]
                var unwrap = scope["unwrap"]

                var prefix = fullpath.slice(0, 1)
                var path = fullpath.slice(1)
                var childscope = null;

                if (prefix == '@')
                {
                    childscope = parentscope
                }
                if (prefix == '^')
                {
                    childscope = scope
                }
                else if (prefix == '$')
                {
                    childscope = source
                }
                else if (prefix == '~')
                {
                    childscope = tt
                }

                var retval = jsonPath(childscope, "$" + path)

                if (unwrap)
                {
                    if (retval.length > 0)
                        retval = retval[0]
                    else
                        retval = null
                }

                return retval
            },
//             "cons": function(parentscope, scope, source, tt)
//             {
//                 var head = scope["head"]
//                 var tail = scope["tail"]

//                 var retval = [head]

//                 if (tail)
//                     retval = retval.concat(tail)

//                 return retval
//             },
//             "last": function(parentscope, scope, source, tt)
//             {
//                 var lin = scope["in"]

//                 var retval = lin[lin.length-1]

//                 return retval
//             },
            "+": function(parentscope, scope, source, tt)
            {
                return get(scope, "a", 0) + get(scope, "b", 0)
            },
            "-": function(parentscope, scope, source, tt)
            {
                return get(scope, "a", 0) - get(scope, "b", 0)
            },
            "*": function(parentscope, scope, source, tt)
            {
                return get(scope, "a", 1) * get(scope, "b", 1)
            },
            "/": function(parentscope, scope, source, tt)
            {
                return get(scope, "a", 1) / get(scope, "b", 1)
            },
            "if": function(parentscope, scope, source, tt)
            {
                var retval = null;
                var condvalue = false;

                if ("cond" in scope)
                    condvalue = Evaluate(parentscope, scope["cond"], source, tt)
                    if (isArray(condvalue) && condvalue.length == 0)
                        condvalue = false

                if (condvalue)
                {
                    if ("true" in scope)
                        retval = Evaluate(parentscope, scope["true"], source, tt)
                }
                else
                {
                    if ("false" in scope)
                        retval = Evaluate(parentscope, scope["false"], source, tt)
                }

                return retval
            }
        }
    }

    function transform(source, t)
    {
        return Evaluate(source, t, source, t)
    }

    function Evaluate(scope, t, source, tt)
    {
        var retval = null;

        if (isBuiltinEval(t))
        {
            var builtinf = builtins()[t["&"]]
            if (!builtinf)
            {
                throw {"message": "builtin '" + t["&"] + "' not found"}
            }
            else
            {
                var transformedt = {}
                for (key in t)
                {
                    if (key != "&")
                    {
                        transformedt[key] = Evaluate(scope, t[key], source, tt)
                    }
                }

                retval = builtinf(scope, transformedt, source, tt)
            }
        }
        else if (isSimpleEval(t))
        {
            var transform = Evaluate(scope, t["!"], source, tt)

            var transformscope = {}
            for (key in t)
            {
                if (key != "!")
                {
                    transformscope[key] = Evaluate(scope, t[key], source, tt)
                }
            }

            retval = Evaluate(transformscope, transform, source, tt)
        }
        else if (isQuoteEval(t))
        {
            retval = t["'"]
        }
        else if (isObject(t))
        {
            retval = {}
            for (var key in t)
            {
                retval[key] = Evaluate(scope, t[key], source, tt)
            }
        }
        else if (isArray(t))
        {
            retval = []
            var unwrap = false
            for (var ix in t)
            {
                if (ix == 0 && t[ix] == "&&")
                {
                    unwrap = true
                    continue;
                }
                var itemresult = Evaluate(scope, t[ix], source, tt)
                if (unwrap && isArray(itemresult))
                    retval = retval.concat(itemresult)
                else
                    retval.push(itemresult)
            }
        }
        else if (isPath(t))
        {
            retval = Evaluate(scope, {"&": "path", "unwrap": false, "path": t.slice(2)}, source, tt)
        }
        else if (isUnwrapPath(t))
        {
            retval = Evaluate(scope, {"&": "path", "unwrap": true, "path": t.slice(1)}, source, tt)
        }
        else
        {
            retval = t;
        }

        return retval;
    }

    function isBuiltinEval(obj) {
        return isObject(obj) && "&" in obj;
    }

    function isSimpleEval(obj) {
        return isObject(obj) && "!" in obj;
    }

    function isQuoteEval(obj) {
        return isObject(obj) && "'" in obj;
    }

    function isObject(obj) {
        return !isArray(obj) && obj === Object(obj);
    }

    function isArray(obj) {
        return Array.isArray(obj)
    }

    function isString(obj) {
        return (typeof obj === 'string' || obj instanceof String);
    }

    function isPath(obj) {
        return isString(obj) && obj.slice(0, 2) == "##";
    }

    function isUnwrapPath(obj) {
        return isString(obj) && obj.slice(0, 1) == "#";
    }

    /* JSONPath 0.8.5 - XPath for JSON
 *
 * Copyright (c) 2007 Stefan Goessner (goessner.net)
 * Licensed under the MIT (MIT-LICENSE.txt) licence.
 *
 * Proposal of Chris Zyp goes into version 0.9.x
 * Issue 7 resolved
 */
    function jsonPath(obj, expr, arg) {
        var P = {
            resultType: arg && arg.resultType || "VALUE",
            result: [],
            normalize: function(expr) {
                var subx = [];
                return expr.replace(/[\['](\??\(.*?\))[\]']|\['(.*?)'\]/g, function($0, $1, $2) {
                    return "[#" + (subx.push($1 || $2) - 1) + "]";
                }) /* http://code.google.com/p/jsonpath/issues/detail?id=4 */
                .replace(/'?\.'?|\['?/g, ";")
                .replace(/;;;|;;/g, ";..;")
                .replace(/;$|'?\]|'$/g, "")
                .replace(/#([0-9]+)/g, function($0, $1) {
                    return subx[$1];
                });
            },
            asPath: function(path) {
                var x = path.split(";"), p = "$";
                for (var i = 1, n = x.length; i < n; i++)
                    p += /^[0-9*]+$/.test(x[i]) ? ("[" + x[i] + "]") : ("['" + x[i] + "']");
                return p;
            },
            store: function(p, v) {
                if (p)
                    P.result[P.result.length] = P.resultType == "PATH" ? P.asPath(p) : v;
                return !!p;
            },
            trace: function(expr, val, path) {
                if (expr !== "") {
                    var x = expr.split(";"), loc = x.shift();
                    x = x.join(";");
                    if (val && val.hasOwnProperty(loc))
                        P.trace(x, val[loc], path + ";" + loc);
                    else if (loc === "*")
                        P.walk(loc, x, val, path, function(m, l, x, v, p) {
                            P.trace(m + ";" + x, v, p);
                        });
                    else if (loc === "..") {
                        P.trace(x, val, path);
                        P.walk(loc, x, val, path, function(m, l, x, v, p) {
                            typeof v[m] === "object" && P.trace("..;" + x, v[m], p + ";" + m);
                        });
                    }
                    else if (/^\(.*?\)$/.test(loc)) // [(expr)]
                        P.trace(P.eval(loc, val, path.substr(path.lastIndexOf(";") + 1)) + ";" + x, val, path);
                    else if (/^\?\(.*?\)$/.test(loc)) // [?(expr)]
                        P.walk(loc, x, val, path, function(m, l, x, v, p) {
                            if (P.eval(l.replace(/^\?\((.*?)\)$/, "$1"), v instanceof Array ? v[m] : v, m))
                                P.trace(m + ";" + x, v, p);
                        }); // issue 5 resolved
                    else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc)) // [start:end:step]  phyton slice syntax
                        P.slice(loc, x, val, path);
                    else if (/,/.test(loc)) { // [name1,name2,...]
                        for (var s = loc.split(/'?,'?/), i = 0, n = s.length; i < n; i++)
                            P.trace(s[i] + ";" + x, val, path);
                    }
                }
                else
                    P.store(path, val);
            },
            walk: function(loc, expr, val, path, f) {
                if (val instanceof Array) {
                    for (var i = 0, n = val.length; i < n; i++)
                        if (i in val)
                            f(i, loc, expr, val, path);
                }
                else if (typeof val === "object") {
                    for (var m in val)
                        if (val.hasOwnProperty(m))
                            f(m, loc, expr, val, path);
                }
            },
            slice: function(loc, expr, val, path) {
                if (val instanceof Array) {
                    var len = val.length, start = 0, end = len, step = 1;
                    loc.replace(/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/g, function($0, $1, $2, $3) {
                        start = parseInt($1 || start);
                        end = parseInt($2 || end);
                        step = parseInt($3 || step);
                    });
                    start = (start < 0) ? Math.max(0, start + len) : Math.min(len, start);
                    end = (end < 0) ? Math.max(0, end + len) : Math.min(len, end);
                    for (var i = start; i < end; i += step)
                        P.trace(i + ";" + expr, val, path);
                }
            },
            eval: function(x, _v, _vname) {
                try {
                    return $ && _v && eval(x.replace(/(^|[^\\])@/g, "$1_v").replace(/\\@/g, "@"));
                }  // issue 7 : resolved ..
                catch (e) {
                    throw new SyntaxError("jsonPath: " + e.message + ": " + x.replace(/(^|[^\\])@/g, "$1_v").replace(/\\@/g, "@"));
                } // issue 7 : resolved ..
            }
        };

        var $ = obj;
        if (expr && obj && (P.resultType == "VALUE" || P.resultType == "PATH")) {
            P.trace(P.normalize(expr).replace(/^\$;?/, ""), obj, "$"); // issue 6 resolved
            return P.result.length ? P.result : false;
        }
    }

}));
<|endoftext|>


<commit_before>'use strict';

// See original base source for this file (and it's apache2 license) in
// https://googlechrome.github.io/samples/service-worker/custom-offline-page/

// TODO explain this
const CACHE_VERSION = 1;
let CURRENT_CACHES = {
  offline: 'offline-v' + CACHE_VERSION
};

let POST_CMDS = {
  install: 'INSTALL_URL',
  primer: 'PRIMER_STATUS', // TODO emit different stages in `install` handler
};
const FLASHCARD_INDEXES = 'cards.index';
const OFFLINE_URL = 'study.html'
let OFFLINE_URL_DEPS = [
  'study.js',
  FLASHCARD_INDEXES
];

const CARDSET_URL_PREFIX = 'cards';

function objectVals(obj) {
  return Object.keys(obj).map(function(key) {
    return obj[key];
  });
}

function createCacheBustedRequest(url) {
  let request = new Request(url, {cache: 'reload'});
  // See https://fetch.spec.whatwg.org/#concept-request-mode
  if ('cache' in request) {
    return request;
  }

  // if {cache: 'reload'} didn't have any effect, append a cache-busting URL
  // parameter instead
  let bustedUrl = new URL(url, self.location.href);
  bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
  return new Request(bustedUrl);
}

function refreshDepsCache(cache) {
  return Promise.all(OFFLINE_URL_DEPS.map(depUrl => {
    return fetch(depUrl).then(function(depResp) {
      return cache.put(depUrl, depResp.clone());
    });
  }));
}

let installKeyVal = function(cmd, payload) {
  return self.clients.matchAll({includeUncontrolled: true}).then(allClients => {
    return Promise.all(allClients.map(client => {
      client.postMessage(JSON.stringify({cmd: cmd, payload: payload}));
    }));
  });
};

function refreshFlashcards(fileCache) {
  let parseIndexTxt = function(rawIndexTxt) {
    return rawIndexTxt.split("\n").filter(e => {
      return Boolean(
          e &&
          e.length &&
          e.match(/[^\s]/)) // nonempty lines
    });
  };
  return fileCache.match(FLASHCARD_INDEXES).then(function(resp) {
    return resp.clone().text()
        .then(parseIndexTxt)
        .then(cardSets => {
          return installKeyVal(POST_CMDS.install, {url: FLASHCARD_INDEXES, resp: cardSets})
              .then(_ => { return cardSets;});
        })
        .then(cardSets => {
          return Promise.all(cardSets
              .map(cardSet => {
                return CARDSET_URL_PREFIX + '/' + cardSet;
              })
              .map(cardSetUrl => {
                let cardIndex;
                let metadataFetch = function(metadata) {
                  let metadataUrl = cardSetUrl + '/' + metadata;
                  return fetch(metadataUrl).then(resp => {
                    return resp.text().then(body => {
                      let content = body;
                      if (metadata == 'index') {
                        content = parseIndexTxt(body);
                        cardIndex = content;
                      }
                      return installKeyVal(POST_CMDS.install, {url: metadataUrl, resp: content});
                    });
                  });
                };
                return Promise
                  .all([
                    metadataFetch('index'),
                    metadataFetch('title'),
                    metadataFetch('description'),
                  ]).
                  then(_ => {
                    return Promise.all(cardIndex.map(card => {
                      let cardUrl = cardSetUrl + '/' + card;
                      return fetch(cardUrl).then(imgResp => {
                        return fileCache.put(cardUrl, imgResp.clone());
                      });
                    }));
                  });
              }));
        });
  });
}

self.addEventListener('install', event => {
  // We can't use cache.add() here, since we want OFFLINE_URL to be the cache
  // key, but the actual URL we end up requesting might include a cache-busting
  // parameter.
  event.waitUntil(
      fetch(createCacheBustedRequest(OFFLINE_URL))
          .then(function(freshResponse) {
            return caches
                .open(CURRENT_CACHES.offline)
                .then(openCache => {
                  return openCache
                      .put(OFFLINE_URL, freshResponse)
                      .then(_ => refreshDepsCache(openCache))
                      .then(_ => refreshFlashcards(openCache));
                });
          }));
});

// Delete all caches that aren't named in CURRENT_CACHES. While there is only
// one cache in this example, the same logic will handle the case where there
// exists multiple versioned caches
self.addEventListener('activate', event => {
  let expectedCacheNames = objectVals(CURRENT_CACHES);

  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (expectedCacheNames.indexOf(cacheName) === -1) {
            console.log('Deleting out of data cache: "%s"', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', event => {
  // TODO fetch "accept...image" requests, and respondWith() corresponding
  // webp's we already have in cache.

  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  // request.mode of 'navigate' is unfortunately not supported in Chrome
  // versions older than 49, so we need to include a less precise fallback,
  // which checks for a GET request with an Accept: text/html header.
  if (event.request.mode === 'navigate' || (
        event.request.method === 'GET' &&
        event.request.headers.get('accept').includes('text/html'))) {
    console.log('Handling navigation-looking fetch event for URL: "%s"', event.request.url);
    event.respondWith(fetch(event.request).catch(error => {
      // The catch is only triggered if fetch() throws an exception which will
      // most likely happen due to the server being unreachable. If fetch()
      // returns a valid HTTP response with a response code in 4xx or 5xx range,
      // the catch() will NOT be called. If you need custom handling for said
      // ranges, see
      // https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/fallback-response
      console.log('Fetch failed; returning offline page instead.', error);
      return caches.match(OFFLINE_URL);
    }));
  }

  // If the above if() is false, then this fetch handler won't intercept the
  // request. If there are any other fetch handlers registered, they will get a
  // chance to call event.respondWith(). If no fetch handlers call
  // event.respondWith(), the request will be handled by the browser as if there
  // were no service worker involvement.
});
<commit_msg>trim surrounding whitespace on non listing contents<commit_after>'use strict';

// See original base source for this file (and it's apache2 license) in
// https://googlechrome.github.io/samples/service-worker/custom-offline-page/

// TODO explain this
const CACHE_VERSION = 1;
let CURRENT_CACHES = {
  offline: 'offline-v' + CACHE_VERSION
};

let POST_CMDS = {
  install: 'INSTALL_URL',
  primer: 'PRIMER_STATUS', // TODO emit different stages in `install` handler
};
const FLASHCARD_INDEXES = 'cards.index';
const OFFLINE_URL = 'study.html'
let OFFLINE_URL_DEPS = [
  'study.js',
  FLASHCARD_INDEXES
];

const CARDSET_URL_PREFIX = 'cards';

function objectVals(obj) {
  return Object.keys(obj).map(function(key) {
    return obj[key];
  });
}

function createCacheBustedRequest(url) {
  let request = new Request(url, {cache: 'reload'});
  // See https://fetch.spec.whatwg.org/#concept-request-mode
  if ('cache' in request) {
    return request;
  }

  // if {cache: 'reload'} didn't have any effect, append a cache-busting URL
  // parameter instead
  let bustedUrl = new URL(url, self.location.href);
  bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
  return new Request(bustedUrl);
}

function refreshDepsCache(cache) {
  return Promise.all(OFFLINE_URL_DEPS.map(depUrl => {
    return fetch(depUrl).then(function(depResp) {
      return cache.put(depUrl, depResp.clone());
    });
  }));
}

let installKeyVal = function(cmd, payload) {
  return self.clients.matchAll({includeUncontrolled: true}).then(allClients => {
    return Promise.all(allClients.map(client => {
      client.postMessage(JSON.stringify({cmd: cmd, payload: payload}));
    }));
  });
};

function refreshFlashcards(fileCache) {
  let parseIndexTxt = function(rawIndexTxt) {
    return rawIndexTxt.split("\n").filter(e => {
      return Boolean(
          e &&
          e.length &&
          e.match(/[^\s]/)) // nonempty lines
    });
  };
  return fileCache.match(FLASHCARD_INDEXES).then(function(resp) {
    return resp.clone().text()
        .then(parseIndexTxt)
        .then(cardSets => {
          return installKeyVal(POST_CMDS.install, {url: FLASHCARD_INDEXES, resp: cardSets})
              .then(_ => { return cardSets;});
        })
        .then(cardSets => {
          return Promise.all(cardSets
              .map(cardSet => {
                return CARDSET_URL_PREFIX + '/' + cardSet;
              })
              .map(cardSetUrl => {
                let cardIndex;
                let metadataFetch = function(metadata) {
                  let metadataUrl = cardSetUrl + '/' + metadata;
                  return fetch(metadataUrl).then(resp => {
                    return resp.text().then(body => {
                      let content;
                      if (metadata == 'index') {
                        content = parseIndexTxt(body);
                        cardIndex = content;
                      } else {
                        content = body
                          .replace(/^\s*/, '')
                          .replace(/\s*$/, '');
                      }
                      return installKeyVal(POST_CMDS.install, {url: metadataUrl, resp: content});
                    });
                  });
                };
                return Promise
                  .all([
                    metadataFetch('index'),
                    metadataFetch('title'),
                    metadataFetch('description'),
                  ]).
                  then(_ => {
                    return Promise.all(cardIndex.map(card => {
                      let cardUrl = cardSetUrl + '/' + card;
                      return fetch(cardUrl).then(imgResp => {
                        return fileCache.put(cardUrl, imgResp.clone());
                      });
                    }));
                  });
              }));
        });
  });
}

self.addEventListener('install', event => {
  // We can't use cache.add() here, since we want OFFLINE_URL to be the cache
  // key, but the actual URL we end up requesting might include a cache-busting
  // parameter.
  event.waitUntil(
      fetch(createCacheBustedRequest(OFFLINE_URL))
          .then(function(freshResponse) {
            return caches
                .open(CURRENT_CACHES.offline)
                .then(openCache => {
                  return openCache
                      .put(OFFLINE_URL, freshResponse)
                      .then(_ => refreshDepsCache(openCache))
                      .then(_ => refreshFlashcards(openCache));
                });
          }));
});

// Delete all caches that aren't named in CURRENT_CACHES. While there is only
// one cache in this example, the same logic will handle the case where there
// exists multiple versioned caches
self.addEventListener('activate', event => {
  let expectedCacheNames = objectVals(CURRENT_CACHES);

  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (expectedCacheNames.indexOf(cacheName) === -1) {
            console.log('Deleting out of data cache: "%s"', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', event => {
  // TODO fetch "accept...image" requests, and respondWith() corresponding
  // webp's we already have in cache.

  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  // request.mode of 'navigate' is unfortunately not supported in Chrome
  // versions older than 49, so we need to include a less precise fallback,
  // which checks for a GET request with an Accept: text/html header.
  if (event.request.mode === 'navigate' || (
        event.request.method === 'GET' &&
        event.request.headers.get('accept').includes('text/html'))) {
    console.log('Handling navigation-looking fetch event for URL: "%s"', event.request.url);
    event.respondWith(fetch(event.request).catch(error => {
      // The catch is only triggered if fetch() throws an exception which will
      // most likely happen due to the server being unreachable. If fetch()
      // returns a valid HTTP response with a response code in 4xx or 5xx range,
      // the catch() will NOT be called. If you need custom handling for said
      // ranges, see
      // https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/fallback-response
      console.log('Fetch failed; returning offline page instead.', error);
      return caches.match(OFFLINE_URL);
    }));
  }

  // If the above if() is false, then this fetch handler won't intercept the
  // request. If there are any other fetch handlers registered, they will get a
  // chance to call event.respondWith(). If no fetch handlers call
  // event.respondWith(), the request will be handled by the browser as if there
  // were no service worker involvement.
});
<|endoftext|>


<commit_before>/**
 * @file
 * Search for any ticker symbols on the current page and display the ticker
 * bar if any are found.
 */

/**
 * Print all tickers into the ticker bar.
 */
showBar = function(symbols, tickerbar) {
    var text = '';
    for (symbol in symbols.tickers) {
        var ticker = symbols.tickers[symbol];
        text = text + symbol + ': ';
        for (var i=0; i<tickerbar.metrics.length; i++) {
            tbmetric = tickerbar.metrics[i];
            if ((tbmetric.show == true) && (typeof(ticker.resource.cache.metrics[tbmetric.name]) != 'undefined')) {
                text = text + tbmetric.name + ':' + ticker.resource.cache.metrics[tbmetric.name].value + ' ';
            }
        }
        text = text + '   ';
    }
    if (text.length) {
        $('body').append('
Test
');
        $('#cstContainer').html('
'+text+'
');
        $('html').css('position', 'relative');
        $('html').css({'margin-top':'30px'});
    }
};

chrome.storage.sync.get(['resource', 'tickerbar', 'patterns'], function(result) {
    jQuery(document).ready(function($) {
        symbols = new GSTSymbols($('html').html(), result.patterns, result.resource);
        symbols.findSymbols();
        symbols.loadTickers(function() {
            showBar(symbols, result.tickerbar);
        });
    });
});

<commit_msg>Tickerbar now uses formatted metric replacement value.<commit_after>/**
 * @file
 * Search for any ticker symbols on the current page and display the ticker
 * bar if any are found.
 */

/**
 * Print all tickers into the ticker bar.
 */
showBar = function(symbols, tickerbar) {
    var text = '';
    for (symbol in symbols.tickers) {
        var ticker = symbols.tickers[symbol];
        text = text + symbol + ': ';
        for (var i=0; i<tickerbar.metrics.length; i++) {
            tbmetric = tickerbar.metrics[i];
            if ((tbmetric.show == true) && (typeof(ticker.resource.cache.metrics[tbmetric.name]) != 'undefined')) {
                var formatted = tbmetric.format.replace('[[METRIC]]', ticker.resource.cache.metrics[tbmetric.name].value)
                text = text + formatted + ' ';
            }
        }
        text = text + '   ';
    }
    if (text.length) {
        $('body').append('
Test
');
        $('#cstContainer').html('
'+text+'
');
        $('html').css('position', 'relative');
        $('html').css({'margin-top':'30px'});
    }
};

chrome.storage.sync.get(['resource', 'tickerbar', 'patterns'], function(result) {
    jQuery(document).ready(function($) {
        symbols = new GSTSymbols($('html').html(), result.patterns, result.resource);
        symbols.findSymbols();
        symbols.loadTickers(function() {
            showBar(symbols, result.tickerbar);
        });
    });
});

<|endoftext|>