<commit_before>var win = Titanium.UI.currentWindow;
var flexSpace = Ti.UI.createButton({ systemButton:Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE });

//Bring the module into the example
var map = require('bencoding.map');

//Create mapView
//We support all of the same functions the native Ti.Map.View does
var mapView = map.createView({
	mapType: Ti.Map.STANDARD_TYPE,
	animate:true,
	userLocation:true
});

//Add to Window
win.add(mapView);

var bZoomIn = Ti.UI.createButton({
	title:'+', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bZoomOut = Ti.UI.createButton({
	title:'-', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bZoomIn.addEventListener('click',function() {
	mapView.zoom(1);
});

bZoomOut.addEventListener('click',function() {
	mapView.zoom(-1);
});

var zoomControl = Titanium.UI.iOS.createToolbar({
	items:[bZoomIn,bZoomOut],
	top:0,width:70,left:0, borderRadius:5,
	borderTop:true, borderBottom:false, translucent:true
});
win.add(zoomControl);

var bAddKML = Ti.UI.createButton({
	title:'Load GeoJSON', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bRemoveKML = Ti.UI.createButton({
	title:'Remove GeoJSON', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bMore = Ti.UI.createButton({
	title:'More', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

function onComplete(){
	alert("GeoJSON File Loaded");
};

//Add event handler to let us know when the KML file has been loaded
mapView.addEventListener('geoJSONCompleted',onComplete);

bAddGeoJSON.addEventListener('click',function() {

	mapView.addGeoJSON({
		path:"geo.json", //Path to our geo json file
		tag : 55, //Integer value used as the tag for all polygons and annotations. If you want use remove you need to set this to a known value.
       	alpha:0.5, //Alpha value of your overlays
	    lineWidth:1.2, //Line Width of your overlays
	    strokeColor:'#000', //Stroke Color of your overlays
	    color:'yellow', //Sets the color of all your overlays ( if left off, a random color will be selected)
	    useRandomColor:true //If true, a random color will be selected, this overrides the color provided if true
	});

});

bRemoveGeoJSON.addEventListener('click',function() {
	//The tag is used to remove polygons.
	mapView.removePolygon({tag:55});
});

bMore.addEventListener('click',function() {

	var dialog = Ti.UI.createOptionDialog({
		options:['Zoom Out To World', 'Zoom To Overlays', 'Clear Map'],
		title:'More Options'
	});

	dialog.addEventListener('click',function(e){
		if(e.index===0){
			mapView.ZoomOutFull();
		}
		if(e.index===1){
			mapView.ZoomToFit();
		}
		if(e.index===2){
			//Remove everything
			mapView.clear();
		}
	});
	dialog.show();
});

win.setToolbar([bAddGeoJSON,flexSpace,bRemoveGeoJSON,flexSpace,bMore]);

<commit_msg>More GeoJSON updates<commit_after>var win = Titanium.UI.currentWindow;
var flexSpace = Ti.UI.createButton({ systemButton:Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE });

//Bring the module into the example
var map = require('bencoding.map');

//Create mapView
//We support all of the same functions the native Ti.Map.View does
var mapView = map.createView({
	mapType: Ti.Map.STANDARD_TYPE,
	animate:true,
	userLocation:true
});

//Add to Window
win.add(mapView);

var bZoomIn = Ti.UI.createButton({
	title:'+', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bZoomOut = Ti.UI.createButton({
	title:'-', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bZoomIn.addEventListener('click',function() {
	mapView.zoom(1);
});

bZoomOut.addEventListener('click',function() {
	mapView.zoom(-1);
});

var zoomControl = Titanium.UI.iOS.createToolbar({
	items:[bZoomIn,bZoomOut],
	top:0,width:70,left:0, borderRadius:5,
	borderTop:true, borderBottom:false, translucent:true
});
win.add(zoomControl);

var bAddKML = Ti.UI.createButton({
	title:'Load GeoJSON', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bRemoveKML = Ti.UI.createButton({
	title:'Remove GeoJSON', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bMore = Ti.UI.createButton({
	title:'More', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

function onComplete(){
	alert("GeoJSON File Loaded");
};

//Add event handler to let us know when the KML file has been loaded
mapView.addEventListener('geoJSONCompleted',onComplete);

bAddGeoJSON.addEventListener('click',function() {

	mapView.addGeoJSON({
		path:"geo.json", //Path to our geo json file
		tag : 55, //Integer value used as the tag for all polygons. If you want use remove you need to set this to a known value.
       	alpha:0.5, //Alpha value of your overlays
	    lineWidth:1.2, //Line Width of your overlays
	    strokeColor:'#000', //Stroke Color of your overlays
	    color:'yellow', //Sets the color of all your overlays ( if left off, a random color will be selected)
	    useRandomColor:true //If true, a random color will be selected, this overrides the color provided if true
	});

});

bRemoveGeoJSON.addEventListener('click',function() {
	//The tag is used to remove polygons.
	mapView.removePolygon({tag:55});
});

bMore.addEventListener('click',function() {

	var dialog = Ti.UI.createOptionDialog({
		options:['Zoom Out To World', 'Zoom To Overlays', 'Clear Map'],
		title:'More Options'
	});

	dialog.addEventListener('click',function(e){
		if(e.index===0){
			mapView.ZoomOutFull();
		}
		if(e.index===1){
			mapView.ZoomToFit();
		}
		if(e.index===2){
			//Remove everything
			mapView.clear();
		}
	});
	dialog.show();
});

win.setToolbar([bAddGeoJSON,flexSpace,bRemoveGeoJSON,flexSpace,bMore]);

<|endoftext|>


<commit_before>// Karma configuration
// Generated on Wed Nov 26 2014 15:52:30 GMT-0700 (MST)
"use strict";

module.exports = function( config ) {
    config.set( {

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '../../..',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: [ 'mocha', 'requirejs', 'sinon-chai' ],

        // list of files / patterns to load in the browser
        files: [
            'public/js/src/require-config.js',
            'test/client/test-main.js', {
                pattern: 'test/client/**/*.spec.js',
                included: false
            }, {
                pattern: 'config/config.json',
                included: false
            }, {
                pattern: 'test/client/**/*.browser-spec.js',
                included: false
            }, {
                pattern: 'public/lib/bower-components/q/q.js',
                included: false
            }, {
                pattern: 'public/lib/bower-components/jquery/dist/jquery.js',
                included: false
            }, {
                pattern: 'public/lib/martijnr-db.js/src/db.js',
                included: false
            }, {
                pattern: 'public/js/src/**/*.js',
                included: false
            }, {
                pattern: 'public/lib/enketo-core/lib/Modernizr.js',
                included: false
            }, {
                pattern: 'public/lib/enketo-core/lib/text/text.js',
                included: false
            }, {
                pattern: 'public/lib/bower-components/i18next/i18next.amd.js',
                included: false
            }
        ],

        // list of files to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {},

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        // reporters: [ 'dots' ],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        //browsers: [ 'Chrome', 'Safari', 'Firefox', 'Opera' ],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    } );
};
<commit_msg>fixed: karma browser tests<commit_after>// Karma configuration
// Generated on Wed Nov 26 2014 15:52:30 GMT-0700 (MST)
"use strict";

module.exports = function( config ) {
    config.set( {

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '../../..',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: [ 'mocha', 'requirejs', 'sinon-chai' ],

        // list of files / patterns to load in the browser
        files: [
            'public/js/src/require-config.js',
            'test/client/test-main.js', {
                pattern: 'test/client/**/*.spec.js',
                included: false
            }, {
                pattern: 'config/config.json',
                included: false
            }, {
                pattern: 'test/client/**/*.browser-spec.js',
                included: false
            }, {
                pattern: 'public/lib/bower-components/q/q.js',
                included: false
            }, {
                pattern: 'public/lib/bower-components/papaparse/papaparse.js',
                included: false
            }, {
                pattern: 'public/lib/bower-components/jquery/dist/jquery.js',
                included: false
            }, {
                pattern: 'public/lib/martijnr-db.js/src/db.js',
                included: false
            }, {
                pattern: 'public/js/src/**/*.js',
                included: false
            }, {
                pattern: 'public/lib/enketo-core/lib/Modernizr.js',
                included: false
            }, {
                pattern: 'public/lib/enketo-core/lib/text/text.js',
                included: false
            }, {
                pattern: 'public/lib/bower-components/i18next/i18next.amd.js',
                included: false
            }
        ],

        // list of files to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {},

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        // reporters: [ 'dots' ],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        //browsers: [ 'Chrome', 'Safari', 'Firefox', 'Opera' ],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    } );
};
<|endoftext|>


<commit_before>// -------------------------------------------------------
//  Author:    CreativeKoen
//  Github:    github.com/CreativeKoen
// -------------------------------------------------------
var gulp = require('gulp');
var args = require('yargs').argv;
var $ = require('gulp-load-plugins')();

var browserSync	= require('browser-sync');
var reload			= browserSync.reload;

var pkg				= require('./package.json');

var build			= !!(args.build);
var dist			= !!(args.dist);

var displayError = function(error) {
    var errorString = '[' + error.plugin + ']';
    errorString += ' ' + error.message.replace("\n",'');
    if(error.fileName)
        errorString += ' in ' + error.fileName;
    if(error.lineNumber)
        errorString += ' on line ' + error.lineNumber;
    console.error(errorString);
}

var SOURCEPATH = 'source/';
var BUILDPATH = 'build/';
var DISTPATH = 'dist/';
<% if (includeStylus) {%>

// -------------------------------------------------------
// Stylus
// -------------------------------------------------------
gulp.task('stylus', function () {
	var nib = require('nib');
	var rupture = require('rupture');
	var lost = require('lost');
	gulp.src(SOURCEPATH+'stylus/*.styl')
		.pipe($.memoryCache('stylusCached'))
		.pipe($.stylus({
			compress: false,
			errLogToConsole: true
		<% if (includeStylusStack) { %>
			,use: [ nib(), rupture()]
		<% } %>
		}))
		<% if (includeStylusStack) { %>
		.pipe($.postcss([lost()]))
		<% } %>
		.pipe($.autoprefixer({
            browser: [
              'last 2 version',
              'Firefox ESR',
              'Opera 12.1',
              'ie10',
              'ie11'
		],
            cascade: true}))
        .pipe($.rename({ suffix: '.min' }))
        .pipe($.if(args.dist, $.minifyCss()))
        .pipe($.if(args.build, gulp.dest(BUILDPATH+'css')))
        .pipe($.if(args.dist, gulp.dest(DISTPATH+'css')));
});
<% } %>
<% if (includeSass) {%>
// -------------------------------------------------------
// Sass
// -------------------------------------------------------
gulp.task('scss', function () {
// var breakpoint-sass = require('breakpoint-sass');
// there is a failing build of breakpoint-sass so import it using bower

// task failing
	var lost = require('lost');
	gulp.src(SOURCEPATH+'scss/*.scss')
		.pipe($.memoryCache('scssCached'))
		.pipe($.sass({
			compress: false,
			errLogToConsole: false
		}))
		<% if (includeSassStack) { %>
		.pipe($.postcss([lost()]))
		<% } %>
		.on('error', function(err){ displayError(err);})
		.pipe($.autoprefixer({
            browser: [
              'last 2 version',
              'Firefox ESR',
              'Opera 12.1',
              'ie10',
              'ie11'
		],
            cascade: true}))
        .pipe($.rename({ suffix: '.min' }))
        .pipe($.if(args.dist, $.minifyCss()))
        .pipe($.if(args.build, gulp.dest(BUILDPATH+'css')))
        .pipe($.if(args.dist, gulp.dest(DISTPATH+'css')));
});
<% } %>

// -------------------------------------------------------
// Scripts
// -------------------------------------------------------
gulp.task('scripts', function () {
	gulp.src(SOURCEPATH+'js/*.js')
			.pipe($.memoryCache('jsCached'))
			.pipe($.jshint())
			.pipe($.jshint.reporter($.jshintStylish))
			.pipe($.plumber())
			.pipe($.uglify())
			//.pipe($.if(args.dist, $.concat('main.js')))
			.pipe($.if(args.dist, $.rename({ suffix: '.min' })))
			.pipe($.if(args.build, gulp.dest(BUILDPATH+'js')))
			.pipe($.if(args.dist, gulp.dest(DISTPATH+'js') ));
});

<% if(includeHtmlJade){%>
// -------------------------------------------------------
// Jade
// -------------------------------------------------------
gulp.task('jade', function () {
	gulp.src(SOURCEPATH+'*.jade')
		.pipe($.memoryCache('jadeCached'))
		.pipe($.if(args.build, $.jade({pretty: false}) ))
		.pipe($.if(args.dist, $.jade({pretty: true}) ))
		.pipe($.if(args.build, gulp.dest(BUILDPATH)))
		.pipe($.if(args.dist, gulp.dest(DISTPATH)));
});
<% } %>
<% if(includePhpJade){%>
// -------------------------------------------------------
// Jade to PHP
// -------------------------------------------------------
gulp.task('jadePhp', function () {
	gulp.src(SOURCEPATH+'*.jade')
		.pipe($.memoryCache('jadePhpCached'))
		.pipe($.if(args.build, $.jadePhp({pretty: false}) ))
		.pipe($.if(args.dist, $.jadePhp({pretty: true}) ))
		.pipe($.if(args.build, gulp.dest(BUILDPATH)))
		.pipe($.if(args.dist, gulp.dest(DISTPATH)));
});
gulp.task(jadePhp);
<% } %>
<% if(includeHtml){%>
// -------------------------------------------------------
// HTML
// -------------------------------------------------------
gulp.task('html', function () {
	gulp.src(SOURCEPATH+'*.html')
		.pipe($.memoryCache('htmlCached'))
		.pipe($.if(args.build, gulp.dest(BUILDPATH)))
		.pipe($.if(args.dist, gulp.dest(DISTPATH)));
});
<% } %>
<% if(includePhp){%>
// -------------------------------------------------------
// PHP
// -------------------------------------------------------
gulp.task('php', function () {
	gulp.src(SOURCEPATH+'*.php')
		.pipe($.memoryCache('phpCached'))
		.pipe($.if(args.build, gulp.dest(BUILDPATH)))
		.pipe($.if(args.dist, gulp.dest(DISTPATH)));
});
<% } %>

// -------------------------------------------------------
// Editor
// -------------------------------------------------------
gulp.task('editor', function () {
	var options = {err: true,stderr: true,stdout: true};
	gulp.src('/', {read:false})
		.pipe($.exec('gvim'))
		.pipe($.exec.reporter(options));
});

// -------------------------------------------------------
// Clean tasks
// -------------------------------------------------------
gulp.task('clean:build', function (done) {
	var del = require('del');
	del(['build'], done);
});

gulp.task('clean:dist', function (done) {
	var del = require('del');
	del(['dist'], done);
});

gulp.task('cleanCache', function () {
    $.memoryCache.caches = {};
    console.log("Deleted cache files!"+'\n');
});

// -------------------------------------------------------
// Vendor
// -------------------------------------------------------
gulp.task('vendor:js', function(){
	gulp.src([
		'bower_components/jquery/dist/jquery.min.js',
		'bower_components/modernizr/modernizr.js',
		'source/js/vendor/*.js'
		])
		.pipe($.if(args.build, gulp.dest(BUILDPATH+'js/vendor')))
		.pipe($.if(args.dist, gulp.dest(DISTPATH+'js/vendor')))
});

gulp.task('vendor:css', function(){
	gulp.src(['bower_components/normalize.css/normalize.css'])
		.pipe($.if(args.build, gulp.dest(BUILDPATH+'css/vendor')))
		.pipe($.if(args.dist, gulp.dest(DISTPATH+'css/vendor')))
});

gulp.task('vendor', gulp.series('vendor:js','vendor:css'));

// -------------------------------------------------------
// Watch
// -------------------------------------------------------
gulp.task('watch', function () {

	// build server
	if (args.build == true) {
		console.log('-----------------------\n');
		console.log('build server is running\n');
		console.log('-----------------------\n');
		browserSync({
		//proxy: 'local.example.nl',
			server: {
				baseDir: BUILDPATH
			},
			index: 'index.html',
			port: 3000,
			notify: false,
			open: true,
			ui: false,
			browser: ['firefox']

			/*
			this is to see the http requests
			uncomment if you want that
			*/

			// middleware: function(req, res, next){
			//	console.log(req.url);
			//	next();
			//}
		});
	}
	if (args.dist == true) {
		console.log('-----------------------\n');
		console.log('dist server is running \n');
		console.log('-----------------------\n');
		browserSync({
			//proxy: 'local.gelskemout.nl',
			server: {
				baseDir: DISTPATH
			},
			index: 'index.html',
			port: 6000,
			notify: false,
			open: true,
			ui: false,
			browser: ['firefox']

			/*
			this is to see the http requests
			uncomment if you want that
			*/

			// middleware: function(req, res, next){
			//     console.log(req.url);
			//     next();
			// }
		});
	}

    var watchFiles = [
        'source/scss/**/*.scss'
        ,'source/stylus/**/*.styl'
        ,'source/js/**.js'
        ,'source/*.jade',
        ,'source/*.php',
        'source/*.html'
    ];

<% if(includeHtml){%>
    gulp.watch( watchFiles[5],
        gulp.parallel('html', reload))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('htmlCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('htmlCached');
                    console.log('cache updated');
                }
            });
<% } %>

<% if(includePhp){%>
    gulp.watch( watchFiles[4],
        gulp.parallel('php', reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('phpCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('phpCached');
                    console.log('cache updated');
                }
            });
<% } %>

<% if(includeHtmlJade){%>
    gulp.watch( watchFiles[3],
        gulp.parallel('jade', reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('jadeCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('jadeCached');
                    console.log('cache updated');
                }
            });
<% } %>

<% if(includePhpJade){%>
    gulp.watch( watchFiles[3],
        gulp.parallel('jadePhp', reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('jadePhpCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('jadePhpCached');
                    console.log('cache updated');
                }
            });
<% } %>
// CACHE scripts/sass/stylus/
<% if (includeStylus) {%>
    gulp.watch( watchFiles[1],
        gulp.parallel('stylus', reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('stylusCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('stylusCached');
                    console.log('cache updated');
                }
            });
<% } %>

<% if (includeSass) {%>
    gulp.watch( watchFiles[0],
        gulp.parallel('scss', reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('scssCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('scssCached');
                    console.log('cache updated');
                }
            });
<% } %>

    gulp.watch( watchFiles[2],
        gulp.parallel('scripts', reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('scriptsCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('scriptsCached');
                    console.log('cache updated');
                }
            });
});

// -------------------------------------------------------
// Build
// -------------------------------------------------------
gulp.task('build',
	gulp.parallel(
		'cleanCache',
		'scripts',
		<% if (includeStylus) {%>'stylus'<% } %>
		<% if (includeSass) {%>'scss'<% } %>,
		<% if (includeHtml) {%>'html'<% } %>
		<% if (includeHtmlJade) {%>'jade'<% } %>
		<% if (includePhp) {%>'php'<% } %>
		<% if (includePhpJade) {%>'jadePhp'<% } %>
));

// -------------------------------------------------------
// Serve
// -------------------------------------------------------
gulp.task('serve', gulp.series('build', 'watch','editor'),
	gulp.parallel(
		'scripts',
		<% if (includeStylus) {%>'stylus'<% } %>
		<% if (includeSass) {%>'scss'<% } %>,
		<% if (includeHtml) {%>'html'<% } %>
		<% if (includeHtmlJade) {%>'jade'<% } %>
		<% if (includePhp) {%>'php'<% } %>
		<% if (includePhpJade) {%>'jadePhp'<% } %>
));
<commit_msg>rewrote the gulp task to be normal function statements<commit_after>// -------------------------------------------------------
//  Author:    CreativeKoen
//  Github:    github.com/CreativeKoen
// -------------------------------------------------------
var gulp = require('gulp');
var args = require('yargs').argv;
var $ = require('gulp-load-plugins')();

var browserSync	= require('browser-sync');
var reload			= browserSync.reload;

var pkg				= require('./package.json');

var build			= !!(args.build);
var dist			= !!(args.dist);

var displayError = function(error) {
    var errorString = '[' + error.plugin + ']';
    errorString += ' ' + error.message.replace("\n",'');
    if(error.fileName)
        errorString += ' in ' + error.fileName;
    if(error.lineNumber)
        errorString += ' on line ' + error.lineNumber;
    console.error(errorString);
}

var SOURCEPATH = 'source/';
var BUILDPATH = 'build/';
var DISTPATH = 'dist/';
<% if (includeStylus) {%>

// -------------------------------------------------------
// Stylus
// -------------------------------------------------------
function stylus() {
	<% if (includeStylusStack) { %>
	var nib = require('nib');
	var rupture = require('rupture');
	var lost = require('lost');
	<% } %>
	gulp.src(SOURCEPATH+'stylus/*.styl')
		.pipe($.memoryCache('stylusCached'))
		.pipe($.stylus({
			compress: false,
			errLogToConsole: true
		<% if (includeStylusStack) { %>
			,use: [ nib(), rupture()]
		<% } %>
		}))
		<% if (includeStylusStack) { %>
		.pipe($.postcss([lost()]))
		<% } %>
		.pipe($.autoprefixer({
            browser: [
              'last 2 version',
              'Firefox ESR',
              'Opera 12.1',
              'ie10',
              'ie11'
		],
            cascade: true}))
        .pipe($.rename({ suffix: '.min' }))
        .pipe($.if(args.dist, $.minifyCss()))
        .pipe($.if(args.build, gulp.dest(BUILDPATH+'css')))
        .pipe($.if(args.dist, gulp.dest(DISTPATH+'css')));
};
<% } %>
<% if (includeSass) {%>
// -------------------------------------------------------
// Sass
// -------------------------------------------------------
function scss() {
// var breakpoint-sass = require('breakpoint-sass');
// there is a failing build of breakpoint-sass so import it using bower

// task failing
	var lost = require('lost');
	gulp.src(SOURCEPATH+'scss/*.scss')
		.pipe($.memoryCache('scssCached'))
		.pipe($.sass({
			compress: false,
			errLogToConsole: false
		}))
		<% if (includeSassStack) { %>
		.pipe($.postcss([lost()]))
		<% } %>
		.on('error', function(err){ displayError(err);})
		.pipe($.autoprefixer({
            browser: [
              'last 2 version',
              'Firefox ESR',
              'Opera 12.1',
              'ie10',
              'ie11'
		],
            cascade: true}))
        .pipe($.rename({ suffix: '.min' }))
        .pipe($.if(args.dist, $.minifyCss()))
        .pipe($.if(args.build, gulp.dest(BUILDPATH+'css')))
        .pipe($.if(args.dist, gulp.dest(DISTPATH+'css')));
};
<% } %>

// -------------------------------------------------------
// Scripts
// -------------------------------------------------------
function scripts() {
	gulp.src(SOURCEPATH+'js/*.js')
			.pipe($.memoryCache('jsCached'))
			.pipe($.jshint())
			.pipe($.jshint.reporter($.jshintStylish))
			.pipe($.plumber())
			.pipe($.uglify())
			//.pipe($.if(args.dist, $.concat('main.js')))
			.pipe($.if(args.dist, $.rename({ suffix: '.min' })))
			.pipe($.if(args.build, gulp.dest(BUILDPATH+'js')))
			.pipe($.if(args.dist, gulp.dest(DISTPATH+'js') ));
};

<% if(includeHtmlJade){%>
// -------------------------------------------------------
// Jade
// -------------------------------------------------------
function jade() {
	gulp.src(SOURCEPATH+'*.jade')
		.pipe($.memoryCache('jadeCached'))
		.pipe($.if(args.build, $.jade({pretty: false}) ))
		.pipe($.if(args.dist, $.jade({pretty: true}) ))
		.pipe($.if(args.build, gulp.dest(BUILDPATH)))
		.pipe($.if(args.dist, gulp.dest(DISTPATH)));
};
<% } %>
<% if(includePhpJade){%>
// -------------------------------------------------------
// Jade to PHP
// -------------------------------------------------------
function jadePhp() {
	gulp.src(SOURCEPATH+'*.jade')
		.pipe($.memoryCache('jadePhpCached'))
		.pipe($.if(args.build, $.jadePhp({pretty: false}) ))
		.pipe($.if(args.dist, $.jadePhp({pretty: true}) ))
		.pipe($.if(args.build, gulp.dest(BUILDPATH)))
		.pipe($.if(args.dist, gulp.dest(DISTPATH)));
};
<% } %>
<% if(includeHtml){%>
// -------------------------------------------------------
// HTML
// -------------------------------------------------------
function html() {
	gulp.src(SOURCEPATH+'*.html')
		.pipe($.memoryCache('htmlCached'))
		.pipe($.if(args.build, gulp.dest(BUILDPATH)))
		.pipe($.if(args.dist, gulp.dest(DISTPATH)));
};
<% } %>
<% if(includePhp){%>
// -------------------------------------------------------
// PHP
// -------------------------------------------------------
function php() {
	gulp.src(SOURCEPATH+'*.php')
		.pipe($.memoryCache('phpCached'))
		.pipe($.if(args.build, gulp.dest(BUILDPATH)))
		.pipe($.if(args.dist, gulp.dest(DISTPATH)));
};
<% } %>

// -------------------------------------------------------
// Editor
// -------------------------------------------------------
function editor() {
	var options = {err: true,stderr: true,stdout: true};
	gulp.src('/', {read:false})
		.pipe($.exec('gvim'))
		.pipe($.exec.reporter(options));
};

// -------------------------------------------------------
// Clean tasks
// -------------------------------------------------------
gulp.task('clean:build', function (done) {
	var del = require('del');
	del(['build'], done);
});

gulp.task('clean:dist', function (done) {
	var del = require('del');
	del(['dist'], done);
});

gulp.task('cleanCache', function () {
    $.memoryCache.caches = {};
    console.log("Deleted cache files!"+'\n');
});

// -------------------------------------------------------
// Vendor
// -------------------------------------------------------
gulp.task('vendor:js', function(){
	gulp.src([
		'bower_components/jquery/dist/jquery.min.js',
		'bower_components/modernizr/modernizr.js',
		'source/js/vendor/*.js'
		])
		.pipe($.if(args.build, gulp.dest(BUILDPATH+'js/vendor')))
		.pipe($.if(args.dist, gulp.dest(DISTPATH+'js/vendor')))
});

gulp.task('vendor:css', function(){
	gulp.src(['bower_components/normalize.css/normalize.css'])
		.pipe($.if(args.build, gulp.dest(BUILDPATH+'css/vendor')))
		.pipe($.if(args.dist, gulp.dest(DISTPATH+'css/vendor')))
});

gulp.task('vendor', gulp.series('vendor:js','vendor:css'));

// -------------------------------------------------------
// Watch
// -------------------------------------------------------
function watch() {

	// build server
	if (args.build == true) {
		console.log('-----------------------\n');
		console.log('build server is running\n');
		console.log('-----------------------\n');
		browserSync({
		//proxy: 'local.example.nl',
			server: {
				baseDir: BUILDPATH
			},
			index: 'index.html',
			port: 3000,
			notify: false,
			open: true,
			ui: false,
			browser: ['firefox']

			/*
			this is to see the http requests
			uncomment if you want that
			*/

			// middleware: function(req, res, next){
			//	console.log(req.url);
			//	next();
			//}
		});
	}
	if (args.dist == true) {
		console.log('-----------------------\n');
		console.log('dist server is running \n');
		console.log('-----------------------\n');
		browserSync({
			//proxy: 'local.gelskemout.nl',
			server: {
				baseDir: DISTPATH
			},
			index: 'index.html',
			port: 6000,
			notify: false,
			open: true,
			ui: false,
			browser: ['firefox']

			/*
			this is to see the http requests
			uncomment if you want that
			*/

			// middleware: function(req, res, next){
			//     console.log(req.url);
			//     next();
			// }
		});
	}

    var watchFiles = [
        'source/scss/**/*.scss'
        ,'source/stylus/**/*.styl'
        ,'source/js/**.js'
        ,'source/*.jade',
        ,'source/*.php',
        'source/*.html'
    ];

<% if(includeHtml){%>
    gulp.watch( watchFiles[5],
        gulp.parallel(html, reload))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('htmlCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('htmlCached');
                    console.log('cache updated');
                }
            });
<% } %>

<% if(includePhp){%>
    gulp.watch( watchFiles[4],
        gulp.parallel(php, reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('phpCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('phpCached');
                    console.log('cache updated');
                }
            });
<% } %>

<% if(includeHtmlJade){%>
    gulp.watch( watchFiles[3],
        gulp.parallel(jade, reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('jadeCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('jadeCached');
                    console.log('cache updated');
                }
            });
<% } %>

<% if(includePhpJade){%>
    gulp.watch( watchFiles[3],
        gulp.parallel(jadePhp, reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('jadePhpCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('jadePhpCached');
                    console.log('cache updated');
                }
            });
<% } %>
// CACHE scripts/sass/stylus/
<% if (includeStylus) {%>
    gulp.watch( watchFiles[1],
        gulp.parallel(stylus, reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('stylusCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('stylusCached');
                    console.log('cache updated');
                }
            });
<% } %>

<% if (includeSass) {%>
    gulp.watch( watchFiles[0],
        gulp.parallel(scss, reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('scssCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('scssCached');
                    console.log('cache updated');
                }
            });
<% } %>

    gulp.watch( watchFiles[2],
        gulp.parallel(scripts, reload ))
            .on('change', function(event){
                console.log('cache check');
                if (event.type === 'deleted'){
                    $.memoryCache.forget('scriptsCached', event.path);
                    console.log('a file was deleted');
                }
                else{
                    $.memoryCache.update('scriptsCached');
                    console.log('cache updated');
                }
            });
};

// -------------------------------------------------------
// Build
// -------------------------------------------------------
gulp.task('build',
	gulp.parallel(
		'cleanCache',
		scripts,
		<% if (includeStylus) {%>stylus<% } %>
		<% if (includeSass) {%>scss<% } %>,
		<% if (includeHtml) {%>html<% } %>
		<% if (includeHtmlJade) {%>jade<% } %>
		<% if (includePhp) {%>php<% } %>
		<% if (includePhpJade) {%>jadePhp<% } %>
));

// -------------------------------------------------------
// Serve
// -------------------------------------------------------
gulp.task('serve', gulp.parallel('build',editor,
		scripts,
		<% if (includeStylus) {%>stylus<% } %>
		<% if (includeSass) {%>scss<% } %>,
		<% if (includeHtml) {%>html<% } %>
		<% if (includeHtmlJade) {%>jade<% } %>
		<% if (includePhp) {%>php<% } %>
		<% if (includePhpJade) {%>jadePhp<% } %>
		,watch
));
<|endoftext|>


<commit_before>'use strict';

/**
 * Import plugins
 */
var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    reload = browserSync.reload,
    runSequence = require('run-sequence'),
    argv = require('yargs').argv,
    del = require('del');

/**
 * Build vendors dependencies
 */
gulp.task('vendors', function() {

  /**
   * CSS VENDORS
   */
  gulp.src([
        ''
      ])
      .pipe($.concat('vendors.css'))
      .pipe($.minifyCss())
      .pipe(gulp.dest('build/css'));

  /**
   * JS VENDORS
   * (with jQuery and Bootstrap dependencies first)
   */

  gulp.src([
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/affix.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/alert.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/button.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/carousel.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/collapse.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/dropdown.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/modal.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/tooltip.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/popover.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/scrollspy.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/tab.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/transition.js'
    ])
    .pipe($.concat('vendors.min.js'))
    .pipe($.uglify())
    .pipe(gulp.dest('build/js'));

  /**
   * FONTS SOURCES
   * Important to add the bootstrap fonts to avoid issues with the fonts include path
   */
  gulp.src([
      'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
      'assets/fonts/*'
    ])
    .pipe(gulp.dest('build/fonts'));

  /**
   * POLYFILLS SOURCES
   * Various polyfills required for old IE
   */
  gulp.src([
      'bower_components/html5shiv/dist/html5shiv.js',
      'bower_components/respond/dest/respond.src.js'
    ])
    .pipe($.concat('polyfills.min.js'))
    .pipe($.uglify())
    .pipe(gulp.dest('build/js'));
});

/**
 * Build styles from SCSS files
 * With error reporting on compiling (so that there's no crash)
 */
gulp.task('styles', function() {
  if (argv.production) { console.log('Processing styles for production env.' ); }
  return gulp.src('assets/sass/<%=appname%>.scss')
    .pipe($.rubySass({style: 'compact'}))
      .on('error', $.notify.onError(function (error) {
         console.log(error.message);
         if (!argv.production) {
           return 'Message to the notifier: ' + error.message;
         }
      }))
    .pipe($.autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1'))
    .pipe($.minifyCss())
    .pipe(gulp.dest('build/css'));
});

/**
 * Build JS
 * With error reporting on compiling (so that there's no crash)
 * And jshint check to highlight errors as we go.
 */
gulp.task('scripts', function() {
  return gulp.src('assets/js/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.concat('main.js'))
    .pipe(gulp.dest('build/js'))
    .pipe($.rename({ suffix: '.min' }))
    .pipe($.uglify())
    .pipe(gulp.dest('build/js'));
});

/**
 * Build Hologram Styleguide
 */
gulp.task('styleguide', function () {
  return gulp.src('hologram_config.yml')
    .pipe($.hologram());
});

/**
 * Clean output directories
 */
gulp.task('clean', del.bind(null, ['build', 'styleguide']));

/**
 * Serve
 */
gulp.task('serve', ['styles', 'scripts'], function () {
  browserSync({
    server: {
      baseDir: ['styleguide'],
    },
    open: false
  });
  gulp.watch(['styleguide/*.html'], reload);
  gulp.watch(['assets/sass/**/*.scss'], function() {
    runSequence('styles', 'styleguide', reload);
  });
  gulp.watch(['assets/js/**/*.js'], function() {
    runSequence('scripts', reload);
  });
});

/**
 * Deploy to GH pages
 */

gulp.task('deploy', function () {
  gulp.src("styleguide/**/*")
    .pipe($.ghPages());
});

/**
 * Task to build assets on production server
 */
gulp.task('production',['clean'], function() {
    argv.production = true;
    runSequence('vendors', 'styles', 'scripts');
});

/**
 * Default task
 */
gulp.task('default', ['clean'], function(cb) {
  runSequence('vendors', 'styles', 'scripts', 'styleguide', cb);
});

<commit_msg>minify css only if "production" argument is passed<commit_after>'use strict';

/**
 * Import plugins
 */
var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    reload = browserSync.reload,
    runSequence = require('run-sequence'),
    argv = require('yargs').argv,
    del = require('del');

/**
 * Build vendors dependencies
 */
gulp.task('vendors', function() {

  /**
   * CSS VENDORS
   */
  gulp.src([
        ''
      ])
      .pipe($.concat('vendors.css'))
      .pipe($.minifyCss())
      .pipe(gulp.dest('build/css'));

  /**
   * JS VENDORS
   * (with jQuery and Bootstrap dependencies first)
   */

  gulp.src([
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/affix.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/alert.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/button.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/carousel.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/collapse.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/dropdown.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/modal.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/tooltip.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/popover.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/scrollspy.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/tab.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/transition.js'
    ])
    .pipe($.concat('vendors.min.js'))
    .pipe($.uglify())
    .pipe(gulp.dest('build/js'));

  /**
   * FONTS SOURCES
   * Important to add the bootstrap fonts to avoid issues with the fonts include path
   */
  gulp.src([
      'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
      'assets/fonts/*'
    ])
    .pipe(gulp.dest('build/fonts'));

  /**
   * POLYFILLS SOURCES
   * Various polyfills required for old IE
   */
  gulp.src([
      'bower_components/html5shiv/dist/html5shiv.js',
      'bower_components/respond/dest/respond.src.js'
    ])
    .pipe($.concat('polyfills.min.js'))
    .pipe($.uglify())
    .pipe(gulp.dest('build/js'));
});

/**
 * Build styles from SCSS files
 * With error reporting on compiling (so that there's no crash)
 */
gulp.task('styles', function() {
  if (argv.production) { console.log('[styles] Processing styles for production env.' ); }
  else { console.log('[styles] Processing styles for dev env. No minifying here, for sourcemaps!') }
  return gulp.src('assets/sass/<%=appname%>.scss')
    .pipe($.rubySass({style: 'compact'}))
      .on('error', $.notify.onError(function (error) {
         console.log(error.message);
         if (!argv.production) {
           return 'Message to the notifier: ' + error.message;
         }
      }))
    .pipe($.autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1'))
    .pipe($.if(argv.production, $.minifyCss()))
    .pipe(gulp.dest('build/css'));
});

/**
 * Build JS
 * With error reporting on compiling (so that there's no crash)
 * And jshint check to highlight errors as we go.
 */
gulp.task('scripts', function() {
  return gulp.src('assets/js/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.concat('main.js'))
    .pipe(gulp.dest('build/js'))
    .pipe($.rename({ suffix: '.min' }))
    .pipe($.uglify())
    .pipe(gulp.dest('build/js'));
});

/**
 * Build Hologram Styleguide
 */
gulp.task('styleguide', function () {
  return gulp.src('hologram_config.yml')
    .pipe($.hologram());
});

/**
 * Clean output directories
 */
gulp.task('clean', del.bind(null, ['build', 'styleguide']));

/**
 * Serve
 */
gulp.task('serve', ['styles', 'scripts'], function () {
  browserSync({
    server: {
      baseDir: ['styleguide'],
    },
    open: false
  });
  gulp.watch(['styleguide/*.html'], reload);
  gulp.watch(['assets/sass/**/*.scss'], function() {
    runSequence('styles', 'styleguide', reload);
  });
  gulp.watch(['assets/js/**/*.js'], function() {
    runSequence('scripts', reload);
  });
});

/**
 * Deploy to GH pages
 */

gulp.task('deploy', function () {
  gulp.src("styleguide/**/*")
    .pipe($.ghPages());
});

/**
 * Task to build assets on production server
 */
gulp.task('production',['clean'], function() {
    argv.production = true;
    runSequence('vendors', 'styles', 'scripts');
});

/**
 * Default task
 */
gulp.task('default', ['clean'], function(cb) {
  runSequence('vendors', 'styles', 'scripts', 'styleguide', cb);
});

<|endoftext|>


<commit_before>import { createSelector, createStructuredSelector } from 'reselect';
import moment from 'moment';
import { format } from 'd3-format';
import isEmpty from 'lodash/isEmpty';
import sumBy from 'lodash/sumBy';
import sortBy from 'lodash/sortBy';

import { getChartConfig } from 'components/widgets/utils/data';

const getActive = state => state.active;
const getAlerts = state => state.data && state.data.alerts;
const getColors = state => state.colors || null;
const getStartDate = state => state.settings.startDate;
const getEndDate = state => state.settings.endDate;
const getSentences = state => state.sentence || null;
const getLocationObject = state => state.location;
const getOptionsSelected = state => state.optionsSelected;
const getStartIndex = state => state.settings.startIndex;
const getEndIndex = state => state.settings.endIndex || null;

const MAXGAP = 90;

const zeroFillDays = (startDate, endDate) => {
  const start = moment(startDate);
  const diffInDays = moment(endDate).diff(moment(startDate), 'days');
  const dates = Array.from(Array(diffInDays).keys());

  return [startDate, ...dates.map(() => start.add(1, 'days').format('YYYY-MM-DD'))];
};

export const getData = createSelector(
  [getAlerts, getStartDate, getEndDate],
  (data, startDate, endDate) => {
    if (!data || isEmpty(data)) return null;

    const zeroFilledData = zeroFillDays(startDate, endDate).map(date => ({
      date,
      alert__count: 0,
      count: 0,
      ...(data.find(d => d.alert__date === date))
    }));

    return sortBy(zeroFilledData, 'date');
  }
);

export const getStartEndIndexes = createSelector(
  [getStartIndex, getEndIndex, getActive, getData],
  (startIndex, endIndex, active, currentData) => {
    if (!currentData) {
      return {
        startIndex,
        endIndex
      };
    }

    const start = startIndex || currentData.length - 365;
    const end = endIndex || currentData.length - 1;

    if (active && end - start > MAXGAP) {
      return {
        startIndex: end - MAXGAP,
        endIndex: end
      };
    }

    return {
      startIndex: start,
      endIndex: end
    };
  }
);

export const parseBrushedData = createSelector(
  [getData, getStartEndIndexes],
  (data, indexes) => {
    if (!data) return null;
    const { startIndex, endIndex } = indexes;

    const start = startIndex || 0;
    const end = endIndex || data.length - 1;

    return data.slice(start, end + 1);
  }
);

export const parseConfig = createSelector(
  [getColors, getStartEndIndexes, getActive],
  (colors, indexes, active) => {
    const { startIndex, endIndex } = indexes;

    const tooltip = [
      {
        label: 'Fire alerts'
      },
      {
        key: 'count',
        labelKey: 'alert__date',
        labelFormat: value => moment(value).format('YYYY-MM-DD'),
        unit: ' VIIRS alerts',
        color: colors.main,
        unitFormat: value =>
          (Number.isInteger(value) ? format(',')(value) : value)
      }
    ];

    return {
      ...getChartConfig(colors),
      tooltip,
      xAxis: {
        tickFormatter: t => moment(t).format('MMM YY')
      },
      brush: {
        width: '100%',
        height: 60,
        margin: {
          top: 0,
          right: 10,
          left: 48,
          bottom: 12
        },
        minimumGap: MAXGAP,
        maximumGap: active ? MAXGAP : 365,
        dataKey: 'date',
        startIndex: startIndex || 0,
        endIndex,
        config: {
          margin: {
            top: 5,
            right: 0,
            left: 42,
            bottom: 20
          },
          yKeys: {
            lines: {
              count: {
                stroke: colors.main,
                isAnimationActive: false
              },
              compareCount: {
                stroke: '#49b5e3',
                isAnimationActive: false
              }
            }
          },
          xAxis: {
            hide: true
          },
          yAxis: {
            hide: true
          },
          cartesianGrid: {
            horizontal: false,
            vertical: false
          },
          height: 60
        }
      }
    };
  }
);

export const parseSentence = createSelector(
  [
    parseBrushedData,
    getColors,
    getSentences,
    getLocationObject,
    getOptionsSelected
  ],
  (data, colors, sentence, location, options) => {
    if (!data) return null;
    const { dataset } = options;
    const startDate = data[0].date;
    const endDate = data[data.length - 1].date;
    const total = sumBy(data, 'alert__count');
    const params = {
      location: location.label || '',
      start_date: moment(startDate).format('Do of MMMM YYYY'),
      end_date: moment(endDate).format('Do of MMMM YYYY'),
      dataset: dataset && dataset.label,
      total_alerts: {
        value: total ? format(',')(total) : 0,
        color: colors.main
      }
    };
    return { sentence, params };
  }
);

export default createStructuredSelector({
  originalData: getData,
  data: parseBrushedData,
  config: parseConfig,
  sentence: parseSentence
});
<commit_msg>fix for startIndex === 0 in historical fires widget<commit_after>import { createSelector, createStructuredSelector } from 'reselect';
import moment from 'moment';
import { format } from 'd3-format';
import isEmpty from 'lodash/isEmpty';
import sumBy from 'lodash/sumBy';
import sortBy from 'lodash/sortBy';

import { getChartConfig } from 'components/widgets/utils/data';

const getActive = state => state.active;
const getAlerts = state => state.data && state.data.alerts;
const getColors = state => state.colors || null;
const getStartDate = state => state.settings.startDate;
const getEndDate = state => state.settings.endDate;
const getSentences = state => state.sentence || null;
const getLocationObject = state => state.location;
const getOptionsSelected = state => state.optionsSelected;
const getStartIndex = state => state.settings.startIndex;
const getEndIndex = state => console.log(state) || state.settings.endIndex || null;

const MAXGAP = 90;

const zeroFillDays = (startDate, endDate) => {
  const start = moment(startDate);
  const diffInDays = moment(endDate).diff(moment(startDate), 'days');
  const dates = Array.from(Array(diffInDays).keys());

  return [startDate, ...dates.map(() => start.add(1, 'days').format('YYYY-MM-DD'))];
};

export const getData = createSelector(
  [getAlerts, getStartDate, getEndDate],
  (data, startDate, endDate) => {
    if (!data || isEmpty(data)) return null;

    const zeroFilledData = zeroFillDays(startDate, endDate).map(date => ({
      date,
      alert__count: 0,
      count: 0,
      ...(data.find(d => d.alert__date === date))
    }));

    return sortBy(zeroFilledData, 'date');
  }
);

export const getStartEndIndexes = createSelector(
  [getStartIndex, getEndIndex, getActive, getData],
  (startIndex, endIndex, active, currentData) => {
    if (!currentData) {
      return {
        startIndex,
        endIndex
      };
    }

    const start = startIndex || startIndex === 0 ? startIndex : currentData.length - 365;
    const end = endIndex || currentData.length - 1;

    if (active && end - start > MAXGAP) {
      return {
        startIndex: end - MAXGAP,
        endIndex: end
      };
    }

    return {
      startIndex: start,
      endIndex: end
    };
  }
);

export const parseBrushedData = createSelector(
  [getData, getStartEndIndexes],
  (data, indexes) => {
    if (!data) return null;
    const { startIndex, endIndex } = indexes;

    const start = startIndex || 0;
    const end = endIndex || data.length - 1;
    console.log('data', data, start, end);

    return data.slice(start, end + 1);
  }
);

export const parseConfig = createSelector(
  [getColors, getStartEndIndexes, getActive],
  (colors, indexes, active) => {
    const { startIndex, endIndex } = indexes;

    const tooltip = [
      {
        label: 'Fire alerts'
      },
      {
        key: 'count',
        labelKey: 'alert__date',
        labelFormat: value => moment(value).format('YYYY-MM-DD'),
        unit: ' VIIRS alerts',
        color: colors.main,
        unitFormat: value =>
          (Number.isInteger(value) ? format(',')(value) : value)
      }
    ];

    return {
      ...getChartConfig(colors),
      tooltip,
      xAxis: {
        tickFormatter: t => moment(t).format('MMM YY')
      },
      brush: {
        width: '100%',
        height: 60,
        margin: {
          top: 0,
          right: 10,
          left: 48,
          bottom: 12
        },
        minimumGap: MAXGAP,
        maximumGap: active ? MAXGAP : 365,
        dataKey: 'date',
        startIndex: startIndex || 0,
        endIndex,
        config: {
          margin: {
            top: 5,
            right: 0,
            left: 42,
            bottom: 20
          },
          yKeys: {
            lines: {
              count: {
                stroke: colors.main,
                isAnimationActive: false
              },
              compareCount: {
                stroke: '#49b5e3',
                isAnimationActive: false
              }
            }
          },
          xAxis: {
            hide: true
          },
          yAxis: {
            hide: true
          },
          cartesianGrid: {
            horizontal: false,
            vertical: false
          },
          height: 60
        }
      }
    };
  }
);

export const parseSentence = createSelector(
  [
    parseBrushedData,
    getColors,
    getSentences,
    getLocationObject,
    getOptionsSelected
  ],
  (data, colors, sentence, location, options) => {
    if (!data) return null;
    const { dataset } = options;
    const startDate = !!data.length && data[0].date;
    const endDate = !!data.length && data[data.length - 1].date;
    const total = sumBy(data, 'alert__count');
    const params = {
      location: location.label || '',
      start_date: moment(startDate).format('Do of MMMM YYYY'),
      end_date: moment(endDate).format('Do of MMMM YYYY'),
      dataset: dataset && dataset.label,
      total_alerts: {
        value: total ? format(',')(total) : 0,
        color: colors.main
      }
    };
    return { sentence, params };
  }
);

export default createStructuredSelector({
  originalData: getData,
  data: parseBrushedData,
  config: parseConfig,
  sentence: parseSentence
});
<|endoftext|>


<commit_before>var Transaction = require('ethereumjs-tx');
var _ = require('lodash');
var util = require('../util');

module.exports = {
  init: function(optionsOrRlp) {
    if (optionsOrRlp) {
      if (_.isString(optionsOrRlp)) {
        this.tx = new Transaction(util.toBuffer(optionsOrRlp));
        this.from = util.toHex(this.tx.getSenderAddress());
        this.nonce = util.toBigNumber(this.tx.nonce);
        this.gasLimit = util.toBigNumber(this.tx.gasLimit);
        this.gasPrice = util.toBigNumber(this.tx.gasPrice);
        this.value = util.toBigNumber(this.tx.value);
      } else
        _.assign(this, optionsOrRlp);
    }
    return this;
  },
  getTx: function() {
    if (this.tx) return this.tx;
    var tx = new Transaction({
      nonce: !this.nonce || this.nonce.isZero() ? null : this.nonce.toNumber(),
      gasPrice: this.gasPrice.toNumber(),
      gasLimit: this.gasLimit.toNumber(),
      to: this.to ? util.toBuffer(this.to) : null,
      value: !this.value || this.value.isZero() ? null : this.value.toNumber(),
      data: this.data ? util.toBuffer(this.data) : null
    });
    tx.sign(util.toBuffer(this.pkey));
    return tx;
  }
};
<commit_msg>Fix a bug in raw tx parsing<commit_after>var Transaction = require('ethereumjs-tx');
var _ = require('lodash');
var util = require('../util');

module.exports = {
  init: function(optionsOrRlp) {
    if (optionsOrRlp) {
      if (_.isString(optionsOrRlp)) {
        this.tx = new Transaction(util.toBuffer(optionsOrRlp));
        this.from = util.toHex(this.tx.getSenderAddress());
        this.to = this.tx.to.length > 0 ? util.toHex(this.tx.to) : null;
        this.nonce = util.toBigNumber(this.tx.nonce);
        this.gasLimit = util.toBigNumber(this.tx.gasLimit);
        this.gasPrice = util.toBigNumber(this.tx.gasPrice);
        this.value = util.toBigNumber(this.tx.value);
      } else
        _.assign(this, optionsOrRlp);
    }
    return this;
  },
  getTx: function() {
    if (this.tx) return this.tx;
    var tx = new Transaction({
      nonce: !this.nonce || this.nonce.isZero() ? null : this.nonce.toNumber(),
      gasPrice: this.gasPrice.toNumber(),
      gasLimit: this.gasLimit.toNumber(),
      to: this.to ? util.toBuffer(this.to) : null,
      value: !this.value || this.value.isZero() ? null : this.value.toNumber(),
      data: this.data ? util.toBuffer(this.data) : null
    });
    tx.sign(util.toBuffer(this.pkey));
    return tx;
  }
};
<|endoftext|>


<commit_before>var async = require('async');
var AWS = require('aws-sdk');
require('dotenv').config();

AWS.config.update({
  region: process.env.AWS_REGION
});

var docClient = new AWS.DynamoDB.DocumentClient();

module.exports = {
  // Periodically recording of taxis locations
  taxis: function (event, context) {
    require('./taxis').fetch(function (err, results, headers) {
      if (err) {
        return context.fail(err);
      }

      var params = {
        TableName: process.env.AWS_DYNAMODB_TABLE
      };
      var timestamp = Math.floor(new Date(headers.lastmod).getTime() / 1000);

      var q = async.queue(function (location, callback) {
        params['Item'] = {
          timestamp: timestamp,
          coord: location.lat + ',' + location.lng
        }
        console.log(q.length() + ' left in queue');
        docClient.put(params, function (err, data) {
          if (err) {
            console.log(err);

            if (err.retryable === true) {
              console.log('Added current one to retry');
              q.push(location);
            }
          }
          callback(err);
        });
      }, process.env.AWS_DYNAMODB_WRITE_CONCURRENCY);

      q.drain = function() {
        return context.done(null, '[DONE] ' + results.length + ' locations saved successfully. ' + headers.lastmod);
      };

      console.log(results.length + ' locations obtained. Saving...');
      results.forEach(function (location) {
        q.push(location);
      });
    });
  }
};
<commit_msg>Store as a whole document instead of individual rows as it can get really expensive<commit_after>var async = require('async');
var AWS = require('aws-sdk');
require('dotenv').config();

AWS.config.update({
  region: process.env.AWS_REGION
});

var docClient = new AWS.DynamoDB.DocumentClient();

module.exports = {
  // Log of taxis locations
  // Trigger this every 30 seconds
  logTaxis: function (event, context) {
    require('./taxis').fetch(function (err, results, headers) {
      if (err) {
        return context.fail(err);
      }

      var params = {
        TableName: process.env.AWS_DYNAMODB_TABLE,
        Item: {
          timestamp: Math.floor(new Date(headers.lastmod).getTime() / 1000),
          locations: results
        }
      };

      var saved = false;
      async.whilst( function() {
          return !saved;
        }, function (callback) {
        docClient.put(params, function (err, data) {
          saved = true;
          if (err && err.retryable === true) {
            saved = false;
          }
          callback(err, data);
        });
      }, function (err, data) {
        if (err) {
          console.error(err);
        }
        return context.done(err, results.length + ' locations saved successfully with timestamp ' + headers.lastmod);
      });
    });
  }
};
<|endoftext|>


<commit_before>//https://mapzen.com/documentation/mobility/decoding/
// This is adapted from the implementation in Project-OSRM
// https://github.com/DennisOSRM/Project-OSRM-Web/blob/master/WebContent/routing/OSRM.RoutingGeometry.js
window.polyline = {};
window.polyline.decode = function(str, precision) {
    var index = 0,
        lat = 0,
        lng = 0,
        coordinates = [],
        shift = 0,
        result = 0,
        byte = null,
        latitude_change,
        longitude_change,
        factor = Math.pow(10, precision || 6);

    // Coordinates have variable length when encoded, so just keep
    // track of whether we've hit the end of the string. In each
    // loop iteration, a single coordinate is decoded.
    while (index < str.length) {

        // Reset shift, result, and byte
        byte = null;
        shift = 0;
        result = 0;

        do {
            byte = str.charCodeAt(index++) - 63;
            result |= (byte & 0x1f) << shift;
            shift += 5;
        } while (byte >= 0x20);

        latitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));

        shift = result = 0;

        do {
            byte = str.charCodeAt(index++) - 63;
            result |= (byte & 0x1f) << shift;
            shift += 5;
        } while (byte >= 0x20);

        longitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));

        lat += latitude_change;
        lng += longitude_change;

        coordinates.push([lat / factor, lng / factor]);
    }

    return coordinates;
};
<commit_msg>Update decode.js<commit_after>// This is adapted from the implementation in Project-OSRM
// https://github.com/DennisOSRM/Project-OSRM-Web/blob/master/WebContent/routing/OSRM.RoutingGeometry.js
window.polyline = {};
window.polyline.decode = function(str, precision) {
    var index = 0,
        lat = 0,
        lng = 0,
        coordinates = [],
        shift = 0,
        result = 0,
        byte = null,
        latitude_change,
        longitude_change,
        factor = Math.pow(10, precision || 6);

    // Coordinates have variable length when encoded, so just keep
    // track of whether we've hit the end of the string. In each
    // loop iteration, a single coordinate is decoded.
    while (index < str.length) {

        // Reset shift, result, and byte
        byte = null;
        shift = 0;
        result = 0;

        do {
            byte = str.charCodeAt(index++) - 63;
            result |= (byte & 0x1f) << shift;
            shift += 5;
        } while (byte >= 0x20);

        latitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));

        shift = result = 0;

        do {
            byte = str.charCodeAt(index++) - 63;
            result |= (byte & 0x1f) << shift;
            shift += 5;
        } while (byte >= 0x20);

        longitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));

        lat += latitude_change;
        lng += longitude_change;

        coordinates.push([lng / factor, lat / factor]);
    }

    return coordinates;
};<|endoftext|>


<commit_before>// This is a one-line comment
/* This is a Multi-line
   Comment
*/
var a;<commit_msg>119. Understand Boolean Values<commit_after>function welcomeToBooleans() {

// don't change code above here

  return true;

// Only change code above this line.
}

welcomeToBooleans();<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Resolver
////////////////////////////////////////////////////////////////////////////////

// XXX the whole resolver heavily relies on these statements to be true:
// - every unit version ever used was added to the resolver with addUnitVersion
// - every constraint ever used was instantiated with getConstraint
// - every constraint was added exactly once
// - every unit version was added exactly once
// - if two unit versions are the same, their refs point at the same object
// - if two constraints are the same, their refs point at the same object
ConstraintSolver.Resolver = function () {
  var self = this;

  // Maps unit name string to an array of version definitions
  self.unitsVersions = {};

  // Refs to all constraints. Mapping String -> instance
  self._constraints = {};
};

ConstraintSolver.Resolver.prototype.addUnitVersion = function (unitVersion) {
  var self = this;

  check(unitVersion, ConstraintSolver.UnitVersion);

  if (! _.has(self.unitsVersions, unitVersion.name))
    self.unitsVersions[unitVersion.name] = [];

  self.unitsVersions[unitVersion.name].push(unitVersion);
};

// name - String - "someUnit"
// versionConstraint - String - "=1.2.3" or "2.1.0"
ConstraintSolver.Resolver.prototype.getConstraint =
  function (name, versionConstraint) {
  var self = this;

  check(name, String);
  check(versionConstraint, String);

  var idString = JSON.stringify([name, versionConstraint]);

  if (_.has(self._constraints, idString))
    return self._constraints[idString];

  return self._constraints[idString] =
    new ConstraintSolver.Constraint(name, versionConstraint);
};

ConstraintSolver.Resolver.prototype.resolve =
  function (dependencies, constraints, choices, options) {
  var self = this;

  constraints = constraints || [];
  choices = choices || [];
  options = options || {};

  dependencies = _.uniq(dependencies);
  constraints = _.uniq(constraints);

  var exactDepsConstraints = _.filter(constraints, function (c) {
    return c.exact && _.contains(dependencies, c.name);
  });

  var exactDepsVersions = _.map(exactDepsConstraints, function (c) {
    return c.getSatisfyingUnitVersion(self);
  });

  var exactDepsNames = _.pluck(exactDepsVersions, "name");

  // Remove them from dependencies.
  dependencies = _.difference(dependencies, exactDepsNames);

  // Take exact dependencies and propagate them.
  // Will also pick these versions into choices as we have no choice but take
  // them.
  _.each(exactDepsVersions, function (uv) {
    var propagatedExactTransDeps =
      self._propagateExactTransDeps(uv, dependencies, constraints, choices);
    dependencies = propagatedExactTransDeps.dependencies;
    constraints = propagatedExactTransDeps.constraints;
    choices = propagatedExactTransDeps.choices;
  });

  var result = self._resolve(dependencies, constraints, choices, options);

  if (! result.success)
    throw new Error(result.failureMsg);

  return result.choices;
};

// dependencies: [String] - remaining dependencies
// constraints: [ConstraintSolver.Constraint] - constraints to satisfy
// choices: [ConstraintSolver.UnitVersion] - current fixed set of choices
//
// returns {
//   success: Boolean,
//   failureMsg: String,
//   choices: [ConstraintSolver.UnitVersion]
// }
//
// NOTE: assumes that exact dependencies are already propagated
ConstraintSolver.Resolver.prototype._resolve =
  function (dependencies, constraints, choices, options) {
  var self = this;

  if (! choicesDontValidateConstraints(choices, constraints))
    return { success: false,
             failureMsg: "initial choices are validating constraints" };

  if (_.isEmpty(dependencies) || options.stopAfterFirstPropagation)
    return { success: true, choices: choices };

  var candidateName = dependencies[0];
  dependencies = dependencies.slice(1);

  var candidateVersions =
    _.filter(self.unitsVersions[candidateName], function (uv) {
      return unitVersionDoesntValidateConstraints(uv, constraints);
    });

  if (_.isEmpty(candidateVersions))
    return { success: false,
             failureMsg: "package constraint cannot be satisfied -- "
                         + candidateName };

  var winningChoices = null;
  _.each(candidateVersions, function (uv) {
    var nDependencies = _.clone(dependencies);
    var nConstraints = _.clone(constraints);
    var nChoices = _.clone(choices);

    nChoices.push(uv);
    var propagatedExactTransDeps =
      self._propagateExactTransDeps(uv, nDependencies, nConstraints, nChoices);

    nDependencies = propagatedExactTransDeps.dependencies;
    nConstraints = propagatedExactTransDeps.constraints;
    nChoices = propagatedExactTransDeps.choices;

    var result = self._resolve(nDependencies, nConstraints, nChoices, options);

    if (result.success) {
      winningChoices = result.choices;
      return false;
    }
  });

  if (winningChoices)
    return { success: true, choices: winningChoices };
  return { success: false,
           failureMsg: "cannot find a satisfying version for package "
                       + candidateName };
};

// Propagates exact dependencies (depencies which have exact constraints) from
// the given unit version taking into account the existing set of dependencies
// and constraints.
// Assumes that the unit versions graph without passed unit version is already
// propagated (i.e. doesn't try to propagate anything not related to the passed
// unit version).
ConstraintSolver.Resolver.prototype._propagateExactTransDeps =
  function (uv, dependencies, constraints, choices) {
  var self = this;

  // XXX representing a queue as an array with push/shift operations is not
  // efficient as Array.shift is O(N). Replace if it becomes a problem.
  var queue = [];
  queue.push(uv);

  while (queue.length > 0) {
    uv = queue[0];
    queue.shift();

    choices = _.union(choices, [uv]);

    var exactTransitiveDepsVersions =
      uv.exactTransitiveDependenciesVersions(self);
    var inexactTransitiveDeps = uv.inexactTransitiveDependencies(self);
    var transitiveContraints = _.chain(exactTransitiveDepsVersions).union([uv])
      .map(function (uv) { return uv.constraints; }).flatten().uniq().value();

    dependencies = _.union(dependencies, inexactTransitiveDeps),
    constraints = _.union(constraints, transitiveContraints),
    choices = _.union(choices, exactTransitiveDepsVersions)

    // Since exact transitive deps are put into choices, there is no need to
    // keep them in dependencies.
    dependencies = _.difference(dependencies, _.pluck(choices, "name"));

    var exactDeps = _.chain(dependencies).map(function (dep) {
      return _.find(constraints, function (c) {
        return c.name === dep && c.exact; });
    }).filter(_.identity).map(function (c) {
      return c.getSatisfyingUnitVersion(self);
    }).difference(choices).value();

    [].push.apply(queue, exactDeps);
  }

  return {
    dependencies: dependencies,
    constraints: constraints,
    choices: choices
  };
};

var unitVersionDoesntValidateConstraints = function (uv, constraints) {
  return _.all(constraints, function (c) {
    return c.name !== uv.name || c.isSatisfied(uv);
  });
};

var choicesDontValidateConstraints = function (choices, constraints) {
  return _.all(choices, function (uv) {
    return unitVersionDoesntValidateConstraints(uv, constraints);
  });
};

////////////////////////////////////////////////////////////////////////////////
// UnitVersion
////////////////////////////////////////////////////////////////////////////////

ConstraintSolver.UnitVersion = function (name, unitVersion, ecv) {
  var self = this;

  check(name, String);
  check(unitVersion, String);
  check(ecv, String);
  check(self, ConstraintSolver.UnitVersion);

  self.name = name;
  self.version = unitVersion;
  // array of Strings - names of dependencies
  self.dependencies = [];
  // array of ConstraintSolver.Constraint's
  self.constraints = [];
  // a string in a form of "1.2.0"
  self.ecv = ecv;
};

_.extend(ConstraintSolver.UnitVersion.prototype, {
  addDependency: function (name) {
    var self = this;

    check(name, String);
    if (_.contains(self.dependencies, name))
      throw new Error("Dependency already exists -- " + name);
    self.dependencies.push(name);
  },
  addConstraint: function (constraint) {
    var self = this;

    check(constraint, ConstraintSolver.Constraint);
    if (_.contains(self.constraints, constraint))
      throw new Error("Constraint already exists -- " + constraint.toString());

    self.constraints.push(constraint);
  },
  exactConstraits: function () {
    var self = this;
    return _.filter(self.constraints, function (c) { return c.exact; });
  },
  looseConstraints: function () {
    var self = this;
    return _.filter(self.constraints, function (c) { return !c.exact; });
  },

  // Returns a list of transitive exact constraints, those could be found as
  // transitive dependencies.
  _exactTransitiveConstraints: function (resolver) {
    var self = this;

    // Get all dependencies we depend on and have constraints to pick an exact
    // version simultaneously as constraints.
    var exactDeps = _.filter(self.exactConstraits(), function (c) {
      return _.contains(self.dependencies, c.name);
    });

    // Merge all their's transitive exact dependencies
    var exactTransitiveConstraints = _.clone(exactDeps);

    _.each(exactDeps, function (c) {
      var unitVersion = c.getSatisfyingUnitVersion(resolver);
      // TODO: error handling in case a satisfying dependency wasn't found

      // Collect the transitive dependencies of the direct exact dependencies.
      exactTransitiveConstraints = _.union(exactTransitiveConstraints,
                unitVersion._exactTransitiveConstraints(resolver));
    });

    return exactTransitiveConstraints;
  },

  exactTransitiveDependenciesVersions: function (resolver) {
    var self = this;
    return _.map(self._exactTransitiveConstraints(resolver), function (c) {
      return c.getSatisfyingUnitVersion(resolver);
    });
  },
  inexactTransitiveDependencies: function (resolver) {
    var self = this;
    var exactTransitiveConstraints = self._exactTransitiveConstraints(resolver);

    return _.chain(exactTransitiveConstraints).map(function (c) {
      var unitVersion = c.getSatisfyingUnitVersion(resolver);
      // TODO: error handling in case unitVersion wasn't found

      return unitVersion.dependencies;
    }).flatten().union(self.dependencies).uniq()
      .difference(_.pluck(exactTransitiveConstraints, "name")).value();
  },
  toString: function () {
    var self = this;
    return self.name + "@" + self.version;
  }
});

////////////////////////////////////////////////////////////////////////////////
// Constraint
////////////////////////////////////////////////////////////////////////////////

// Can be called either:
//    new PackageVersion.Constraint("packageA", "=2.1.0")
// or:
//    new PackageVersion.Constraint("pacakgeA@=2.1.0")
ConstraintSolver.Constraint = function (name, versionString) {
  var self = this;

  if (versionString) {
    _.extend(self, PackageVersion.parseVersionConstraint(versionString));
    self.name = name;
  } else {
    _.extend(self, PackageVersion.parseConstraint(name));
  }
};

ConstraintSolver.Constraint.prototype.toString = function () {
  var self = this;
  return self.name + "@" + (self.exact ? "=" : "") + self.version;
};

var semver = Npm.require('semver');

ConstraintSolver.Constraint.prototype.isSatisfied = function (unitVersion) {
  var self = this;
  check(unitVersion, ConstraintSolver.UnitVersion);

  if (self.exact)
    return self.version === unitVersion.version;

  return semver.lte(self.version, unitVersion.version) &&
    semver.lte(unitVersion.ecv, self.version);
};

// Returns any unit version satisfying the constraint in the resolver
ConstraintSolver.Constraint.prototype.getSatisfyingUnitVersion =
  function (resolver) {
  var self = this;
  var unitVersion = _.find(resolver.unitsVersions[self.name],
                           _.bind(self.isSatisfied, self));
  return unitVersion;
};

<commit_msg>correctly break out of the iteration<commit_after>////////////////////////////////////////////////////////////////////////////////
// Resolver
////////////////////////////////////////////////////////////////////////////////

// XXX the whole resolver heavily relies on these statements to be true:
// - every unit version ever used was added to the resolver with addUnitVersion
// - every constraint ever used was instantiated with getConstraint
// - every constraint was added exactly once
// - every unit version was added exactly once
// - if two unit versions are the same, their refs point at the same object
// - if two constraints are the same, their refs point at the same object
ConstraintSolver.Resolver = function () {
  var self = this;

  // Maps unit name string to an array of version definitions
  self.unitsVersions = {};

  // Refs to all constraints. Mapping String -> instance
  self._constraints = {};
};

ConstraintSolver.Resolver.prototype.addUnitVersion = function (unitVersion) {
  var self = this;

  check(unitVersion, ConstraintSolver.UnitVersion);

  if (! _.has(self.unitsVersions, unitVersion.name))
    self.unitsVersions[unitVersion.name] = [];

  self.unitsVersions[unitVersion.name].push(unitVersion);
};

// name - String - "someUnit"
// versionConstraint - String - "=1.2.3" or "2.1.0"
ConstraintSolver.Resolver.prototype.getConstraint =
  function (name, versionConstraint) {
  var self = this;

  check(name, String);
  check(versionConstraint, String);

  var idString = JSON.stringify([name, versionConstraint]);

  if (_.has(self._constraints, idString))
    return self._constraints[idString];

  return self._constraints[idString] =
    new ConstraintSolver.Constraint(name, versionConstraint);
};

ConstraintSolver.Resolver.prototype.resolve =
  function (dependencies, constraints, choices, options) {
  var self = this;

  constraints = constraints || [];
  choices = choices || [];
  options = options || {};

  dependencies = _.uniq(dependencies);
  constraints = _.uniq(constraints);

  var exactDepsConstraints = _.filter(constraints, function (c) {
    return c.exact && _.contains(dependencies, c.name);
  });

  var exactDepsVersions = _.map(exactDepsConstraints, function (c) {
    return c.getSatisfyingUnitVersion(self);
  });

  var exactDepsNames = _.pluck(exactDepsVersions, "name");

  // Remove them from dependencies.
  dependencies = _.difference(dependencies, exactDepsNames);

  // Take exact dependencies and propagate them.
  // Will also pick these versions into choices as we have no choice but take
  // them.
  _.each(exactDepsVersions, function (uv) {
    var propagatedExactTransDeps =
      self._propagateExactTransDeps(uv, dependencies, constraints, choices);
    dependencies = propagatedExactTransDeps.dependencies;
    constraints = propagatedExactTransDeps.constraints;
    choices = propagatedExactTransDeps.choices;
  });

  var result = self._resolve(dependencies, constraints, choices, options);

  if (! result.success)
    throw new Error(result.failureMsg);

  return result.choices;
};

// dependencies: [String] - remaining dependencies
// constraints: [ConstraintSolver.Constraint] - constraints to satisfy
// choices: [ConstraintSolver.UnitVersion] - current fixed set of choices
//
// returns {
//   success: Boolean,
//   failureMsg: String,
//   choices: [ConstraintSolver.UnitVersion]
// }
//
// NOTE: assumes that exact dependencies are already propagated
ConstraintSolver.Resolver.prototype._resolve =
  function (dependencies, constraints, choices, options) {
  var self = this;

  if (! choicesDontValidateConstraints(choices, constraints))
    return { success: false,
             failureMsg: "initial choices are validating constraints" };

  if (_.isEmpty(dependencies) || options.stopAfterFirstPropagation)
    return { success: true, choices: choices };

  var candidateName = dependencies[0];
  dependencies = dependencies.slice(1);

  var candidateVersions =
    _.filter(self.unitsVersions[candidateName], function (uv) {
      return unitVersionDoesntValidateConstraints(uv, constraints);
    });

  if (_.isEmpty(candidateVersions))
    return { success: false,
             failureMsg: "package constraint cannot be satisfied -- "
                         + candidateName };

  var winningChoices = null;
  _.each(candidateVersions, function (uv) {
    if (winningChoices)
      return;

    var nDependencies = _.clone(dependencies);
    var nConstraints = _.clone(constraints);
    var nChoices = _.clone(choices);

    nChoices.push(uv);
    var propagatedExactTransDeps =
      self._propagateExactTransDeps(uv, nDependencies, nConstraints, nChoices);

    nDependencies = propagatedExactTransDeps.dependencies;
    nConstraints = propagatedExactTransDeps.constraints;
    nChoices = propagatedExactTransDeps.choices;

    var result = self._resolve(nDependencies, nConstraints, nChoices, options);

    if (result.success) {
      winningChoices = result.choices;
    }
  });

  if (winningChoices)
    return { success: true, choices: winningChoices };
  return { success: false,
           failureMsg: "cannot find a satisfying version for package "
                       + candidateName };
};

// Propagates exact dependencies (depencies which have exact constraints) from
// the given unit version taking into account the existing set of dependencies
// and constraints.
// Assumes that the unit versions graph without passed unit version is already
// propagated (i.e. doesn't try to propagate anything not related to the passed
// unit version).
ConstraintSolver.Resolver.prototype._propagateExactTransDeps =
  function (uv, dependencies, constraints, choices) {
  var self = this;

  // XXX representing a queue as an array with push/shift operations is not
  // efficient as Array.shift is O(N). Replace if it becomes a problem.
  var queue = [];
  queue.push(uv);

  while (queue.length > 0) {
    uv = queue[0];
    queue.shift();

    choices = _.union(choices, [uv]);

    var exactTransitiveDepsVersions =
      uv.exactTransitiveDependenciesVersions(self);
    var inexactTransitiveDeps = uv.inexactTransitiveDependencies(self);
    var transitiveContraints = _.chain(exactTransitiveDepsVersions).union([uv])
      .map(function (uv) { return uv.constraints; }).flatten().uniq().value();

    dependencies = _.union(dependencies, inexactTransitiveDeps),
    constraints = _.union(constraints, transitiveContraints),
    choices = _.union(choices, exactTransitiveDepsVersions)

    // Since exact transitive deps are put into choices, there is no need to
    // keep them in dependencies.
    dependencies = _.difference(dependencies, _.pluck(choices, "name"));

    var exactDeps = _.chain(dependencies).map(function (dep) {
      return _.find(constraints, function (c) {
        return c.name === dep && c.exact; });
    }).filter(_.identity).map(function (c) {
      return c.getSatisfyingUnitVersion(self);
    }).difference(choices).value();

    [].push.apply(queue, exactDeps);
  }

  return {
    dependencies: dependencies,
    constraints: constraints,
    choices: choices
  };
};

var unitVersionDoesntValidateConstraints = function (uv, constraints) {
  return _.all(constraints, function (c) {
    return c.name !== uv.name || c.isSatisfied(uv);
  });
};

var choicesDontValidateConstraints = function (choices, constraints) {
  return _.all(choices, function (uv) {
    return unitVersionDoesntValidateConstraints(uv, constraints);
  });
};

////////////////////////////////////////////////////////////////////////////////
// UnitVersion
////////////////////////////////////////////////////////////////////////////////

ConstraintSolver.UnitVersion = function (name, unitVersion, ecv) {
  var self = this;

  check(name, String);
  check(unitVersion, String);
  check(ecv, String);
  check(self, ConstraintSolver.UnitVersion);

  self.name = name;
  self.version = unitVersion;
  // array of Strings - names of dependencies
  self.dependencies = [];
  // array of ConstraintSolver.Constraint's
  self.constraints = [];
  // a string in a form of "1.2.0"
  self.ecv = ecv;
};

_.extend(ConstraintSolver.UnitVersion.prototype, {
  addDependency: function (name) {
    var self = this;

    check(name, String);
    if (_.contains(self.dependencies, name))
      throw new Error("Dependency already exists -- " + name);
    self.dependencies.push(name);
  },
  addConstraint: function (constraint) {
    var self = this;

    check(constraint, ConstraintSolver.Constraint);
    if (_.contains(self.constraints, constraint))
      throw new Error("Constraint already exists -- " + constraint.toString());

    self.constraints.push(constraint);
  },
  exactConstraits: function () {
    var self = this;
    return _.filter(self.constraints, function (c) { return c.exact; });
  },
  looseConstraints: function () {
    var self = this;
    return _.filter(self.constraints, function (c) { return !c.exact; });
  },

  // Returns a list of transitive exact constraints, those could be found as
  // transitive dependencies.
  _exactTransitiveConstraints: function (resolver) {
    var self = this;

    // Get all dependencies we depend on and have constraints to pick an exact
    // version simultaneously as constraints.
    var exactDeps = _.filter(self.exactConstraits(), function (c) {
      return _.contains(self.dependencies, c.name);
    });

    // Merge all their's transitive exact dependencies
    var exactTransitiveConstraints = _.clone(exactDeps);

    _.each(exactDeps, function (c) {
      var unitVersion = c.getSatisfyingUnitVersion(resolver);
      // TODO: error handling in case a satisfying dependency wasn't found

      // Collect the transitive dependencies of the direct exact dependencies.
      exactTransitiveConstraints = _.union(exactTransitiveConstraints,
                unitVersion._exactTransitiveConstraints(resolver));
    });

    return exactTransitiveConstraints;
  },

  exactTransitiveDependenciesVersions: function (resolver) {
    var self = this;
    return _.map(self._exactTransitiveConstraints(resolver), function (c) {
      return c.getSatisfyingUnitVersion(resolver);
    });
  },
  inexactTransitiveDependencies: function (resolver) {
    var self = this;
    var exactTransitiveConstraints = self._exactTransitiveConstraints(resolver);

    return _.chain(exactTransitiveConstraints).map(function (c) {
      var unitVersion = c.getSatisfyingUnitVersion(resolver);
      // TODO: error handling in case unitVersion wasn't found

      return unitVersion.dependencies;
    }).flatten().union(self.dependencies).uniq()
      .difference(_.pluck(exactTransitiveConstraints, "name")).value();
  },
  toString: function () {
    var self = this;
    return self.name + "@" + self.version;
  }
});

////////////////////////////////////////////////////////////////////////////////
// Constraint
////////////////////////////////////////////////////////////////////////////////

// Can be called either:
//    new PackageVersion.Constraint("packageA", "=2.1.0")
// or:
//    new PackageVersion.Constraint("pacakgeA@=2.1.0")
ConstraintSolver.Constraint = function (name, versionString) {
  var self = this;

  if (versionString) {
    _.extend(self, PackageVersion.parseVersionConstraint(versionString));
    self.name = name;
  } else {
    _.extend(self, PackageVersion.parseConstraint(name));
  }
};

ConstraintSolver.Constraint.prototype.toString = function () {
  var self = this;
  return self.name + "@" + (self.exact ? "=" : "") + self.version;
};

var semver = Npm.require('semver');

ConstraintSolver.Constraint.prototype.isSatisfied = function (unitVersion) {
  var self = this;
  check(unitVersion, ConstraintSolver.UnitVersion);

  if (self.exact)
    return self.version === unitVersion.version;

  return semver.lte(self.version, unitVersion.version) &&
    semver.lte(unitVersion.ecv, self.version);
};

// Returns any unit version satisfying the constraint in the resolver
ConstraintSolver.Constraint.prototype.getSatisfyingUnitVersion =
  function (resolver) {
  var self = this;
  var unitVersion = _.find(resolver.unitsVersions[self.name],
                           _.bind(self.isSatisfied, self));
  return unitVersion;
};

<|endoftext|>


<commit_before>// This file configures a web server for testing the production build
// on your local machine.

import browserSync from 'browser-sync';
import historyApiFallback from 'connect-history-api-fallback';
import {chalkProcessing} from './chalkConfig';

/* eslint-disable no-console */

console.log(chalkProcessing('Opening production build...'));

// Run Browsersync
browserSync({
  open: false,
  port: 80,
  ui: false,
  server: {
    baseDir: 'build/tools/dist'
  },

  files: [
    'src/*.html'
  ],

  middleware: [historyApiFallback()]
});
<commit_msg>bugfix. changed port.<commit_after>// This file configures a web server for testing the production build
// on your local machine.

import browserSync from 'browser-sync';
import historyApiFallback from 'connect-history-api-fallback';
import {chalkProcessing} from './chalkConfig';

/* eslint-disable no-console */

console.log(chalkProcessing('Opening production build...'));

// Run Browsersync
browserSync({
  open: false,
  port: 8080,
  ui: false,
  server: {
    baseDir: 'build/tools/dist'
  },

  files: [
    'src/*.html'
  ],

  middleware: [historyApiFallback()]
});
<|endoftext|>