<commit_before>// Scribe.js (NodeJS)
// Copyright 2014 by Mathew Kurian
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT SPLICEED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

// Module dependences
// ---------------------------------

var util = require('util');
var mkdirp = require('mkdirp');
var path = require('path');
var moment = require('moment');
var fs = require('fs');
var stack = require('callsite');
var colors = require('colors');

var self = module.exports;
self.express = {};

// Configuration
// ---------------------------------

var $ = {
    app : "scribe.js",
    logPath : "./../logs",
    mainUser : "root",
    maxTagLength : 50,
    indentation : 2,
    divider : ':::',
    defaultUserDir : '_user',
    testOutput : function(result, pipes, actual, expected, opts){

        var pipe = result ? 'log' : 'error';
        var ne = expected.indexOf("\n") > -1;
        var na = actual.indexOf("\n") > -1;

        pipes[pipe]((" " + opts + " ").bold.inverse + (result ? " PASSED ".green : " FAILED ".red).bold.inverse)
        pipes[pipe](" EXPECTED "[result ? "green" : "red"].bold.inverse + " " + (!ne ? expected: ""))
        if(ne) pipes[pipe](expected);
        pipes[pipe](" ACTUAL "[result ? "green" : "red"].bold.inverse + " " + (!na ? actual : ""))
        if(na) pipes[pipe](actual);
    }
}

// Active settings
// ---------------------------------

var activeDefaultTag;
var activeUserDir;
var activeDateDir;
var activeDayIso;
var activeDir;

var loggers = {};
var theme = {};
var fsOptions = { encoding : 'utf8' }
var __reserved = [ "f", "t", "tag", "file", "should", "be", "test", "assert" ];

// Cache pipe out
// ---------------------------------

var __stdpipe = (function(){
    return console.log;
})();

// Utility functions
// ---------------------------------

var pretty = function(a){
    if(!a) return a + "";
    if(typeof a === 'object')
        return JSON.stringify(a, null, 4);
    return a.toString();
}

var compress = function(a){
    if(!a) return a + "";
    if(typeof a === 'object')
        return JSON.stringify(a);
    return a.toString();
}

var tag = function(a){
    return "[" + a + "]";
}

var createDir = function(){
    mkdirp.sync(path.normalize($.logPath), 0777 & (~process.umask()));
    mkdirp.sync(path.normalize(path.join($.logPath, activeDateDir)), 0777 & (~process.umask()));
    mkdirp.sync(activeDir = path.normalize(path.join($.logPath, activeDateDir, activeUserDir)), 0777 & (~process.umask()));
}

var getUser = function(){
    try {
        activeUserDir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'].toLowerCase();
        activeUserDir = activeUserDir.slice(activeUserDir.lastIndexOf((process.platform == 'win32') ? '\\':'/') + 1);
    } catch(e){
        activeUserDir = $.defaultUserDir;
    } finally {
        return activeUserDir;
    }
}

var validate = function(){
    var _activeDayIso = moment().day();
    if(activeDayIso != _activeDayIso) {
        activeDayIso = _activeDayIso;
        activeDateDir = moment().format('MMM_D_YY').toLowerCase();
        return true;
    }

    return false;
}

function Extender(tag, opts, stack){

    var self = this;

    self.tag = tag;
    self.opts = opts;

    self.do = self.invoke = self.should = function(actual){

        var _actual = compress(actual);

        self.expect = self.be = function(expected){

            var _expected = compress(expected);

            $.testOutput(_actual === _expected, self, pretty(actual), pretty(expected), self.opts);

            return self;
        }

        return self;
    }
}

var spaces = function(sp){
    var s = '';
    for(var z = 0; z < sp; z++)
        s += ' ';
    return s;
}

var stackTag = function(_stack){
    try {
        return tag(path.basename(_stack.getFileName()) + ":" + _stack.getLineNumber());
    } catch(e){
        return tag(activeDefaultTag);
    }
}

// Exports
// ---------------------------------

self.addLogger = function(name, file, console, color){
    if(arguments.length < 4)
        return false;

    if(__reserved.indexOf(name) > -1)
        throw Error("Reserved pipe - " + name);

    theme[name] = color;
    loggers[name] = {
        "file" : file,
        "console" : console
    }

    colors.setTheme(theme);

    addPipe(name);

    return true;
}

exports.removeLogger = function(name){
    if(loggers[name]) {
        delete loggers[name];
        delete console[name];
        return true;
    }

    return false;
}

self.set = function(a, b){
    $[a] = b;
}

self.configure = function(callback){

    var _logPath = $.logPath;
    var _activeUserDir = activeUserDir;

    if(callback) callback();

    activeDefaultTag = tag($.app.toLowerCase());
    activeUserDir = getUser();

    if($.logPath !== _logPath){
        if(_logPath) fs.unlink(_logPath, function(){})
    } else if (_activeUserDir !== activeUserDir){
        if(_activeUserDir) fs.unlink(_activeUserDir, function(){})
    }

    validate();
    createDir();
}

self.express.logger = function(validate) {

    return function(req, res, next){

        if(!validate || validate(req, res)) {
            console.info('[%s]%s %s %s %s' , "express.js"
                                        , req.ip.red
                                        , req.method.green
                                        , req.url.grey
                                        , (/mobile/i.test(req.headers['user-agent']) ? 'MOBILE' : 'DESKTOP').yellow);
        }

        next();
    }
}

self.express.webpipe = function(){

    self.addLogger('user', true, true, 'magenta');

    return function(req, res){
        console.t('scribe.js').user(req.ip.red + " " + req.body.data);
        res.send('received');
    };
}

// Web Control Panel
// ---------------------------------

var datetemplate = fs.readFileSync(path.join(__dirname, "/log.html"), { encoding : "utf8"});
var flatColors = [ "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#f39c12", "#d35400", "#c0392b", "#7f8c8d"]

self.express.controlPanel = function() {

    return function(req, res){
        var date = req.param('date');

        if(!date) {

            var logs = [];
            var datePath = path.normalize(path.join($.logPath));

            fs.readdir(datePath, function(err, files){

                var response;
                var loggerDates = "";

                for(var i = 0; i < files.length; i++){
                    try {
                        var file = files[i];
                        var fileSplit = file.split("_");
                        loggerDates += '

' + fileSplit[0] + '

' +
                                        fileSplit[1] + '

' + ("20" + fileSplit[2]) + '

';
                    } catch(e) {}
                }

                return res.send(datetemplate.replace("__title", $.app + " - Scribe.js Control Panel")
                                            .replace('__content', files.join(","))
                                            .replace('__logdates', loggerDates)
                                            .replace('__logpath', activeDir)
                                            .replace('__username', $.mainUser)
                                            .replace('__divider', $.divider));
            });

            return;
        }

        var type = req.param('type');
        type = type ? type : "log";

        var contents = "No log found";
        var filepath = path.join(activeDir, "app." + type);

        if(fs.existsSync(filepath)){
            var stream = fs.createReadStream(filepath);

            res.writeHead(200, {
              'Content-Length': fs.statSync(filepath)["size"],
              'Content-Type': 'text/plain',
            });

            stream.pipe(res);
        } else{
           res.statusCode = 404;
           res.send();
        }
    }
}

// Additional Features
// ---------------------------------

console['t'] = console['tag'] = function(n){
    return new Extender(n ? tag(n) : activeDefaultTag);
}

console['f'] = console['file'] = function(n){

    var tag;

    if(!n) {
        var st = stack()[1];
        tag = tag(path.basename(st.getFileName()) + ":" + st.getLineNumber());
    } else {
        tag = tag(path.basename(n));
    }

    return new Extender(tag);
}

console['assert'] = console['test'] = function(name, tag){
    tag = tag ? tag : stackTag(stack()[1]);
    return new Extender(tag, name, stack()[1]);
}

var addPipe = function(n) {

    Extender.prototype[n] = function(){
        var args = Array.prototype.splice.call(arguments, 0);
        args.unshift(this.tag + args.shift());
        console[n].apply(this, args);
    }

    console[n] = (function (i) {

        if(validate()){
            createDir();
        }

        return function () {

            var utfs = (arguments.length == 1 ? pretty(arguments[0]) : util.format.apply(util, arguments)).trim();
            var time = moment().format('h:mm:ss A')
            var file = path.join(activeDir, 'app.' + i )
            var indent = spaces($.indentation);
            var tag = utfs.match(/^\[(.*?)\]\s{0,}/m);

            if(loggers[i].file && utfs != ''){

                var outfs = utfs.stripColors;
                var cleanTag = "";

                if(tag) {
                    outfs = outfs.replace(tag[0], "");
                    cleanTag = tag[0].trim();
                }

                outfs = time + $.divider + cleanTag + outfs.replace(/\n/g, '\n' + time + $.divider + cleanTag) + '\n';

                fs.appendFileSync(file, outfs, fsOptions, function(err){});
            }

            if (loggers[i].console){

                if(!tag) {
                    tag = [ stackTag(stack()[1]) ];
                }

                var tabIn;
                var cleanTag = tag[0].trim();

                if(cleanTag.length <= $.maxTagLength){
                    utfs = utfs.replace(tag[0], "");
                    tabIn = spaces($.maxTagLength - cleanTag.length);
                    cleanTag = cleanTag[i].bold;
                    utfs = indent + cleanTag + tabIn + utfs.replace(/\n/g, '\n' + indent + cleanTag + tabIn);
                } else {
                    tabIn = indent + spaces($.maxTagLength);
                    utfs = tabIn + utfs.replace(/\n/g, '\n' + tabIn);
                }

                __stdpipe(utfs);
            }
        }

    })(n);

    // console.t()[n]('Created pipe console.%s', n.toUpperCase());
}

// Startup
activeUserDir = getUser();
self.configure();

// Express missing notification
try {
    var express = require("express");
    if(!express){
        throw new Error();
    }
} catch(e){
    console.warn("SCRIBE WARNING: Express not installed - visual web logger is disabled.");
}
<commit_msg>Fixing tag issue<commit_after>// Scribe.js (NodeJS)
// Copyright 2014 by Mathew Kurian
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT SPLICEED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

// Module dependences
// ---------------------------------

var util = require('util');
var mkdirp = require('mkdirp');
var path = require('path');
var moment = require('moment');
var fs = require('fs');
var stack = require('callsite');
var colors = require('colors');

var self = module.exports;
self.express = {};

// Configuration
// ---------------------------------

var $ = {
    app : "scribe.js",
    logPath : "./../logs",
    mainUser : "root",
    maxTagLength : 50,
    indentation : 2,
    divider : ':::',
    defaultUserDir : '_user',
    testOutput : function(result, pipes, actual, expected, opts){

        var pipe = result ? 'log' : 'error';
        var ne = expected.indexOf("\n") > -1;
        var na = actual.indexOf("\n") > -1;

        pipes[pipe]((" " + opts + " ").bold.inverse + (result ? " PASSED ".green : " FAILED ".red).bold.inverse)
        pipes[pipe](" EXPECTED "[result ? "green" : "red"].bold.inverse + " " + (!ne ? expected: ""))
        if(ne) pipes[pipe](expected);
        pipes[pipe](" ACTUAL "[result ? "green" : "red"].bold.inverse + " " + (!na ? actual : ""))
        if(na) pipes[pipe](actual);
    }
}

// Active settings
// ---------------------------------

var activeDefaultTag;
var activeUserDir;
var activeDateDir;
var activeDayIso;
var activeDir;

var loggers = {};
var theme = {};
var fsOptions = { encoding : 'utf8' }
var __reserved = [ "f", "t", "tag", "file", "should", "be", "test", "assert" ];

// Cache pipe out
// ---------------------------------

var __stdpipe = (function(){
    return console.log;
})();

// Utility functions
// ---------------------------------

var pretty = function(a){
    if(!a) return a + "";
    if(typeof a === 'object')
        return JSON.stringify(a, null, 4);
    return a.toString();
}

var compress = function(a){
    if(!a) return a + "";
    if(typeof a === 'object')
        return JSON.stringify(a);
    return a.toString();
}

var tag = function(a){
    return "[" + a + "]";
}

var createDir = function(){
    mkdirp.sync(path.normalize($.logPath), 0777 & (~process.umask()));
    mkdirp.sync(path.normalize(path.join($.logPath, activeDateDir)), 0777 & (~process.umask()));
    mkdirp.sync(activeDir = path.normalize(path.join($.logPath, activeDateDir, activeUserDir)), 0777 & (~process.umask()));
}

var getUser = function(){
    try {
        activeUserDir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'].toLowerCase();
        activeUserDir = activeUserDir.slice(activeUserDir.lastIndexOf((process.platform == 'win32') ? '\\':'/') + 1);
    } catch(e){
        activeUserDir = $.defaultUserDir;
    } finally {
        return activeUserDir;
    }
}

var validate = function(){
    var _activeDayIso = moment().day();
    if(activeDayIso != _activeDayIso) {
        activeDayIso = _activeDayIso;
        activeDateDir = moment().format('MMM_D_YY').toLowerCase();
        return true;
    }

    return false;
}

function Extender(tag, opts, stack){

    var self = this;

    self.tag = tag;
    self.opts = opts;

    self.do = self.invoke = self.should = function(actual){

        var _actual = compress(actual);

        self.expect = self.be = function(expected){

            var _expected = compress(expected);

            $.testOutput(_actual === _expected, self, pretty(actual), pretty(expected), self.opts);

            return self;
        }

        return self;
    }
}

var spaces = function(sp){
    var s = '';
    for(var z = 0; z < sp; z++)
        s += ' ';
    return s;
}

var stackTag = function(_stack){
    try {
        return tag(path.basename(_stack.getFileName()) + ":" + _stack.getLineNumber());
    } catch(e){
        return tag(activeDefaultTag);
    }
}

// Exports
// ---------------------------------

self.addLogger = function(name, file, console, color){
    if(arguments.length < 4)
        return false;

    if(__reserved.indexOf(name) > -1)
        throw Error("Reserved pipe - " + name);

    theme[name] = color;
    loggers[name] = {
        "file" : file,
        "console" : console
    }

    colors.setTheme(theme);

    addPipe(name);

    return true;
}

exports.removeLogger = function(name){
    if(loggers[name]) {
        delete loggers[name];
        delete console[name];
        return true;
    }

    return false;
}

self.set = function(a, b){
    $[a] = b;
}

self.configure = function(callback){

    var _logPath = $.logPath;
    var _activeUserDir = activeUserDir;

    if(callback) callback();

    activeDefaultTag = tag($.app.toLowerCase());
    activeUserDir = getUser();

    if($.logPath !== _logPath){
        if(_logPath) fs.unlink(_logPath, function(){})
    } else if (_activeUserDir !== activeUserDir){
        if(_activeUserDir) fs.unlink(_activeUserDir, function(){})
    }

    validate();
    createDir();
}

self.express.logger = function(validate) {

    return function(req, res, next){

        if(!validate || validate(req, res)) {
            console.info('[%s]%s %s %s %s' , "express.js"
                                        , req.ip.red
                                        , req.method.green
                                        , req.url.grey
                                        , (/mobile/i.test(req.headers['user-agent']) ? 'MOBILE' : 'DESKTOP').yellow);
        }

        next();
    }
}

self.express.webpipe = function(){

    self.addLogger('user', true, true, 'magenta');

    return function(req, res){
        console.t('scribe.js').user(req.ip.red + " " + req.body.data);
        res.send('received');
    };
}

// Web Control Panel
// ---------------------------------

var datetemplate = fs.readFileSync(path.join(__dirname, "/log.html"), { encoding : "utf8"});
var flatColors = [ "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#f39c12", "#d35400", "#c0392b", "#7f8c8d"]

self.express.controlPanel = function() {

    return function(req, res){
        var date = req.param('date');

        if(!date) {

            var logs = [];
            var datePath = path.normalize(path.join($.logPath));

            fs.readdir(datePath, function(err, files){

                var response;
                var loggerDates = "";

                for(var i = 0; i < files.length; i++){
                    try {
                        var file = files[i];
                        var fileSplit = file.split("_");
                        loggerDates += '

' + fileSplit[0] + '

' +
                                        fileSplit[1] + '

' + ("20" + fileSplit[2]) + '

';
                    } catch(e) {}
                }

                return res.send(datetemplate.replace("__title", $.app + " - Scribe.js Control Panel")
                                            .replace('__content', files.join(","))
                                            .replace('__logdates', loggerDates)
                                            .replace('__logpath', activeDir)
                                            .replace('__username', $.mainUser)
                                            .replace('__divider', $.divider));
            });

            return;
        }

        var type = req.param('type');
        type = type ? type : "log";

        var contents = "No log found";
        var filepath = path.join(activeDir, "app." + type);

        if(fs.existsSync(filepath)){
            var stream = fs.createReadStream(filepath);

            res.writeHead(200, {
              'Content-Length': fs.statSync(filepath)["size"],
              'Content-Type': 'text/plain',
            });

            stream.pipe(res);
        } else{
           res.statusCode = 404;
           res.send();
        }
    }
}

// Additional Features
// ---------------------------------

console['t'] = console['tag'] = function(n){
    return new Extender(n ? tag(n) : activeDefaultTag);
}

console['f'] = console['file'] = function(n){

    var _tag;

    if(!n) {
        var st = stack()[1];
        _tag = tag(path.basename(st.getFileName()) + ":" + st.getLineNumber());
    } else {
        _tag = tag(path.basename(n));
    }

    return new Extender(_tag);
}

console['assert'] = console['test'] = function(name, tag){
    tag = tag ? tag : stackTag(stack()[1]);
    return new Extender(tag, name, stack()[1]);
}

var addPipe = function(n) {

    Extender.prototype[n] = function(){
        var args = Array.prototype.splice.call(arguments, 0);
        args.unshift(this.tag + args.shift());
        console[n].apply(this, args);
    }

    console[n] = (function (i) {

        if(validate()){
            createDir();
        }

        return function () {

            var utfs = (arguments.length == 1 ? pretty(arguments[0]) : util.format.apply(util, arguments)).trim();
            var time = moment().format('h:mm:ss A')
            var file = path.join(activeDir, 'app.' + i )
            var indent = spaces($.indentation);
            var tag = utfs.match(/^\[(.*?)\]\s{0,}/m);

            if(loggers[i].file && utfs != ''){

                var outfs = utfs.stripColors;
                var cleanTag = "";

                if(tag) {
                    outfs = outfs.replace(tag[0], "");
                    cleanTag = tag[0].trim();
                }

                outfs = time + $.divider + cleanTag + outfs.replace(/\n/g, '\n' + time + $.divider + cleanTag) + '\n';

                fs.appendFileSync(file, outfs, fsOptions, function(err){});
            }

            if (loggers[i].console){

                if(!tag) {
                    tag = [ stackTag(stack()[1]) ];
                }

                var tabIn;
                var cleanTag = tag[0].trim();

                if(cleanTag.length <= $.maxTagLength){
                    utfs = utfs.replace(tag[0], "");
                    tabIn = spaces($.maxTagLength - cleanTag.length);
                    cleanTag = cleanTag[i].bold;
                    utfs = indent + cleanTag + tabIn + utfs.replace(/\n/g, '\n' + indent + cleanTag + tabIn);
                } else {
                    tabIn = indent + spaces($.maxTagLength);
                    utfs = tabIn + utfs.replace(/\n/g, '\n' + tabIn);
                }

                __stdpipe(utfs);
            }
        }

    })(n);

    // console.t()[n]('Created pipe console.%s', n.toUpperCase());
}

// Startup
activeUserDir = getUser();
self.configure();

// Express missing notification
try {
    var express = require("express");
    if(!express){
        throw new Error();
    }
} catch(e){
    console.warn("SCRIBE WARNING: Express not installed - visual web logger is disabled.");
}
<|endoftext|>


<commit_before>/* eslint-env browser */
/* global CodeMirror, ohm */

'use strict';

var domUtil = require('./domUtil');
var ohmEditor = require('./ohmEditor');

require('./editorErrors');
require('./examples');
require('./exampleGenerationRequests');  // Required for examples.
require('./externalRules');
require('./parseTree');
require('./ruleHyperlinks');
require('./searchBar');
require('./splitters');
require('./timeline');
require('./persistence');

var checkboxes;
var grammarChanged = true;
var inputChanged = true;

var showFailuresImplicitly = true;

var $ = domUtil.$;
var $$ = domUtil.$$;

var grammarMatcher = ohm.ohmGrammar.matcher();

// Helpers
// -------

function parseGrammar() {
  var matchResult = grammarMatcher.match();

  var grammar;
  var err;

  if (matchResult.succeeded()) {
    var ns = {};
    try {
      ohm._buildGrammar(matchResult, ns);
      var firstProp = Object.keys(ns)[0];
      if (firstProp) {
        grammar = ns[firstProp];
      }
    } catch (ex) {
      err = ex;
    }
  } else {
    err = {
      message: matchResult.message,
      shortMessage: matchResult.shortMessage,
      interval: matchResult.getInterval()
    };
  }
  return {
    matchResult: matchResult,
    grammar: grammar,
    error: err
  };
}

// Return the name of a valid start rule for grammar, or null if `optRuleName` is
// not valid and the grammar has no default starting rule.
function getValidStartRule(grammar, optRuleName) {
  if (optRuleName && optRuleName in grammar.rules) {
    return optRuleName;
  }
  if (grammar.defaultStartRule) {
    return grammar.defaultStartRule;
  }
  return null;
}

function refresh() {
  var grammarEditor = ohmEditor.ui.grammarEditor;
  var inputEditor = ohmEditor.ui.inputEditor;

  var grammarSource = grammarEditor.getValue();
  var inputSource = inputEditor.getValue();

  ohmEditor.saveState(inputEditor, 'input');

  // Refresh the option values.
  for (var i = 0; i < checkboxes.length; ++i) {
    var checkbox = checkboxes[i];
    ohmEditor.options[checkbox.name] = checkbox.checked;
  }

  if (inputChanged || grammarChanged) {
    showFailuresImplicitly = true;  // Reset to default.
  }

  if (inputChanged) {
    inputChanged = false;
    ohmEditor.emit('change:input', inputSource);
  }

  if (grammarChanged) {
    grammarChanged = false;
    ohmEditor.emit('change:grammar', grammarSource);

    var result = parseGrammar();
    ohmEditor.grammar = result.grammar;
    ohmEditor.emit('parse:grammar', result.matchResult, result.grammar, result.error);
  }

  if (ohmEditor.grammar) {
    var startRule = getValidStartRule(ohmEditor.grammar, ohmEditor.startRule);
    if (startRule) {
      var trace = ohmEditor.grammar.trace(inputSource, startRule);

      // When the input fails to parse, turn on "show failures" automatically.
      if (showFailuresImplicitly) {
        var checked = $('input[name=showFailures]').checked = trace.result.failed();
        ohmEditor.options.showFailures = checked;
      }

      ohmEditor.emit('parse:input', trace.result, trace);
    }
  }
}

ohmEditor.setGrammar = function(grammar) {
  if (grammar === null) { // load from local storage or default element
    grammar = localStorage.getItem('grammar');
    if (!grammar || grammar === '') {
      grammar = $('#sampleGrammar').textContent; // default element
    }
  }
  var doc = CodeMirror.Doc(grammar, 'null');
  ohmEditor.ui.grammarEditor.swapDoc(doc);
};

ohmEditor.saveState = function(editor, key) {
  localStorage.setItem(key, editor.getValue());
};

// Main
// ----

var refreshTimeout;
function triggerRefresh(delay) {
  if (refreshTimeout) {
    clearTimeout(refreshTimeout);
  }
  refreshTimeout = setTimeout(refresh.bind(ohmEditor), delay || 0);
}

function resetGrammarMatcher() {
  grammarMatcher = ohm.ohmGrammar.matcher();
  grammarMatcher.setInput(ohmEditor.ui.grammarEditor.getValue());
}

checkboxes = $$('#options input[type=checkbox]');
checkboxes.forEach(function(cb) {
  cb.addEventListener('click', function(e) {
    // Respect the user's wishes if they automatically enable/disable "show failures".
    if (e.target.name === 'showFailures') {
      showFailuresImplicitly = false;
    } else if (e.target.name === 'showExampleGenerator') {
      $$('.exampleGeneratorUI').forEach(function(el) {
        el.classList.toggle('hidden', !e.target.checked);
      });
    }
    triggerRefresh();
  });
});

ohmEditor.setGrammar(null /* restore local storage */);

ohmEditor.ui.inputEditor.on('change', function(cm) {
  inputChanged = true;
  ohmEditor.emit('change:inputEditor', cm);
  triggerRefresh(250);
});

ohmEditor.ui.grammarEditor.on('beforeChange', function(cm, change) {
  grammarMatcher.replaceInputRange(
      cm.indexFromPos(change.from),
      cm.indexFromPos(change.to),
      change.text.join('\n'));
});

ohmEditor.ui.grammarEditor.on('swapDoc', resetGrammarMatcher);

ohmEditor.ui.grammarEditor.on('change', function(cm, change) {
  grammarChanged = true;
  ohmEditor.emit('change:grammarEditor', cm);
  triggerRefresh(250);
});
ohmEditor.ui.grammarEditor.on('swapDoc', function(cm) {
  grammarChanged = true;
  ohmEditor.emit('change:grammarEditor', cm);
  triggerRefresh(250);
});

/* eslint-disable no-console */
console.log('%cOhm visualizer', 'color: #e0a; font-family: Avenir; font-size: 18px;');
console.log([
  '- `ohm` is the Ohm library',
  '- `ohmEditor` is editor object with',
  '  `.grammar` as the current grammar object (if the source is valid)',
  '  `.ui` containing the `inputEditor` and `grammarEditor`'
].join('\n'));
/* eslint-enable no-console */

resetGrammarMatcher();
refresh();
<commit_msg>Add code for example generation links (#18)<commit_after>/* eslint-env browser */
/* global CodeMirror, ohm */

'use strict';

var domUtil = require('./domUtil');
var ohmEditor = require('./ohmEditor');

require('./editorErrors');
require('./examples');
require('./exampleGenerationRequests');  // Required for examples.
require('./exampleGenerationLinks');
require('./externalRules');
require('./parseTree');
require('./ruleHyperlinks');
require('./searchBar');
require('./splitters');
require('./timeline');
require('./persistence');

var checkboxes;
var grammarChanged = true;
var inputChanged = true;

var showFailuresImplicitly = true;

var $ = domUtil.$;
var $$ = domUtil.$$;

var grammarMatcher = ohm.ohmGrammar.matcher();

// Helpers
// -------

function parseGrammar() {
  var matchResult = grammarMatcher.match();

  var grammar;
  var err;

  if (matchResult.succeeded()) {
    var ns = {};
    try {
      ohm._buildGrammar(matchResult, ns);
      var firstProp = Object.keys(ns)[0];
      if (firstProp) {
        grammar = ns[firstProp];
      }
    } catch (ex) {
      err = ex;
    }
  } else {
    err = {
      message: matchResult.message,
      shortMessage: matchResult.shortMessage,
      interval: matchResult.getInterval()
    };
  }
  return {
    matchResult: matchResult,
    grammar: grammar,
    error: err
  };
}

// Return the name of a valid start rule for grammar, or null if `optRuleName` is
// not valid and the grammar has no default starting rule.
function getValidStartRule(grammar, optRuleName) {
  if (optRuleName && optRuleName in grammar.rules) {
    return optRuleName;
  }
  if (grammar.defaultStartRule) {
    return grammar.defaultStartRule;
  }
  return null;
}

function refresh() {
  var grammarEditor = ohmEditor.ui.grammarEditor;
  var inputEditor = ohmEditor.ui.inputEditor;

  var grammarSource = grammarEditor.getValue();
  var inputSource = inputEditor.getValue();

  ohmEditor.saveState(inputEditor, 'input');

  // Refresh the option values.
  for (var i = 0; i < checkboxes.length; ++i) {
    var checkbox = checkboxes[i];
    ohmEditor.options[checkbox.name] = checkbox.checked;
  }

  if (inputChanged || grammarChanged) {
    showFailuresImplicitly = true;  // Reset to default.
  }

  if (inputChanged) {
    inputChanged = false;
    ohmEditor.emit('change:input', inputSource);
  }

  if (grammarChanged) {
    grammarChanged = false;
    ohmEditor.emit('change:grammar', grammarSource);

    var result = parseGrammar();
    ohmEditor.grammar = result.grammar;
    ohmEditor.emit('parse:grammar', result.matchResult, result.grammar, result.error);
  }

  if (ohmEditor.grammar) {
    var startRule = getValidStartRule(ohmEditor.grammar, ohmEditor.startRule);
    if (startRule) {
      var trace = ohmEditor.grammar.trace(inputSource, startRule);

      // When the input fails to parse, turn on "show failures" automatically.
      if (showFailuresImplicitly) {
        var checked = $('input[name=showFailures]').checked = trace.result.failed();
        ohmEditor.options.showFailures = checked;
      }

      ohmEditor.emit('parse:input', trace.result, trace);
    }
  }
}

ohmEditor.setGrammar = function(grammar) {
  if (grammar === null) { // load from local storage or default element
    grammar = localStorage.getItem('grammar');
    if (!grammar || grammar === '') {
      grammar = $('#sampleGrammar').textContent; // default element
    }
  }
  var doc = CodeMirror.Doc(grammar, 'null');
  ohmEditor.ui.grammarEditor.swapDoc(doc);
};

ohmEditor.saveState = function(editor, key) {
  localStorage.setItem(key, editor.getValue());
};

// Main
// ----

var refreshTimeout;
function triggerRefresh(delay) {
  if (refreshTimeout) {
    clearTimeout(refreshTimeout);
  }
  refreshTimeout = setTimeout(refresh.bind(ohmEditor), delay || 0);
}

function resetGrammarMatcher() {
  grammarMatcher = ohm.ohmGrammar.matcher();
  grammarMatcher.setInput(ohmEditor.ui.grammarEditor.getValue());
}

checkboxes = $$('#options input[type=checkbox]');
checkboxes.forEach(function(cb) {
  cb.addEventListener('click', function(e) {
    // Respect the user's wishes if they automatically enable/disable "show failures".
    if (e.target.name === 'showFailures') {
      showFailuresImplicitly = false;
    } else if (e.target.name === 'showExampleGenerator') {
      $$('.exampleGeneratorUI').forEach(function(el) {
        el.classList.toggle('hidden', !e.target.checked);
      });
    }
    triggerRefresh();
  });
});

ohmEditor.setGrammar(null /* restore local storage */);

ohmEditor.ui.inputEditor.on('change', function(cm) {
  inputChanged = true;
  ohmEditor.emit('change:inputEditor', cm);
  triggerRefresh(250);
});

ohmEditor.ui.grammarEditor.on('beforeChange', function(cm, change) {
  grammarMatcher.replaceInputRange(
      cm.indexFromPos(change.from),
      cm.indexFromPos(change.to),
      change.text.join('\n'));
});

ohmEditor.ui.grammarEditor.on('swapDoc', resetGrammarMatcher);

ohmEditor.ui.grammarEditor.on('change', function(cm, change) {
  grammarChanged = true;
  ohmEditor.emit('change:grammarEditor', cm);
  triggerRefresh(250);
});
ohmEditor.ui.grammarEditor.on('swapDoc', function(cm) {
  grammarChanged = true;
  ohmEditor.emit('change:grammarEditor', cm);
  triggerRefresh(250);
});

/* eslint-disable no-console */
console.log('%cOhm visualizer', 'color: #e0a; font-family: Avenir; font-size: 18px;');
console.log([
  '- `ohm` is the Ohm library',
  '- `ohmEditor` is editor object with',
  '  `.grammar` as the current grammar object (if the source is valid)',
  '  `.ui` containing the `inputEditor` and `grammarEditor`'
].join('\n'));
/* eslint-enable no-console */

resetGrammarMatcher();
refresh();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames'; // for building class names with dynamic data
import Api from './utils/api';
import { TweenLite, TweenMax, TimelineMax, TimelineLite } from 'gsap';

import draggable from './draggable';

let cities = [];
let cityWeather = []; // API cache
let currentCity = 0; // Index of current city displayed
const PropTypes = React.PropTypes;
const calendarContainer = document.querySelector('.calendar-container');
const containerWidth = calendarContainer.clientWidth;
let trackWidth = 0;

const GetDates = (startDate, daysToAdd, dir) => {
  let aryDates = [];

  for(let i = 1; i <= daysToAdd; i++) {
    const currentDate = new Date();
    switch (dir) {
      case 'future':
        currentDate.setDate(startDate.getDate() + i);
        break;
       case 'past':
       currentDate.setDate(startDate.getDate() - i);
       break;
    }
    aryDates.push({ day: DayAsString(currentDate.getDay()), date: currentDate.getDate(), month: MonthAsString(currentDate.getMonth()), year: currentDate.getFullYear()});
  }

  return aryDates;
}

const MonthAsString = (monthIndex) => {
    const d = new Date();
    const month = new Array();
    month[0]="январь";
    month[1]="февраль";
    month[2]="март";
    month[3]="апрель";
    month[4]="май";
    month[5]="июнь";
    month[6]="июль";
    month[7]="август";
    month[8]="сентябрь";
    month[9]="октябрь";
    month[10]="ноябрь";
    month[11]="декабрь";

    return month[monthIndex];
}

const DayAsString = (dayIndex) => {
    const weekdays = new Array(7);
    weekdays[0] = "вс";
    weekdays[1] = "пн";
    weekdays[2] = "вт";
    weekdays[3] = "ср";
    weekdays[4] = "чт";
    weekdays[5] = "пт";
    weekdays[6] = "суб";

    return weekdays[dayIndex];
}

class CalendarBlocks extends React.Component {
  getNextDays(startDate) {
    const datesArr = GetDates(startDate, 12, 'future');
    let futureDates = [];

    datesArr.forEach(calendarDate => {
      futureDates.push(

{ calendarDate.day }

{ calendarDate.date }

      );
    });

    return futureDates;
  }

  getPreviousDays(startDate) {
    const datesArr = GetDates(startDate, 10, 'past');
    let pastDates = [];

    datesArr.forEach(calendarDatePast => {
      pastDates.push(

{ calendarDatePast.day }

{ calendarDatePast.date }

      );
    });

    return (pastDates.reverse());
  }

  render() {
    const startDate = new Date();

    return (

        { this.getPreviousDays(startDate) }

{ DayAsString(startDate.getDay()) }

{ startDate.getDate() }

        { this.getNextDays(startDate) }

    );
  }
}

class CalendarContainer extends React.Component {
  render() {
    const startDate = new Date();

    return (

{ MonthAsString(startDate.getMonth()) } { startDate.getFullYear() }

              <CalendarBlocks />

    );
  }
}

class Weather extends React.Component {
  constructor() {
    super(),
    this.state = {}
  }

  fetchData() {
    // Get the data from the cache if possible
    if (cityWeather[currentCity]) {
      this.updateData();
    }
    else {
      // Request new data to the API
      Api.get(cities[currentCity])
        .then(function(data) {
          cityWeather[currentCity] = data;
          this.updateData();
        }.bind(this));
    }
  }

  updateData() {
    // Update the data for the UI
    // cityWeather[currentCity] - array, where each element is a collection of data for one period of time (3h)
    this.setState( cityWeather[currentCity].list );
  }

  componentWillMount() {
    cities[0] = 'Moscow';

    // Create a timer to clear the cache after 5 minutes, so we can get updated data from the API
    setInterval(function() {
      cityWeather = []; // Empty the cache
    }, (1000*60*5));

    this.fetchData();
  }

  render() {
    const weatherHourly = this.state;
    let result = [];

    Object.keys(weatherHourly).map((period) => {
      if (period < 3) {
        const temp = Math.round(weatherHourly[period].main.temp);
        const humidity = Math.round(weatherHourly[period].main.humidity);
        const windSpeed = weatherHourly[period].wind.speed;

        result.push(

              День и время: { weatherHourly[period].dt_txt }

              Температура воздуха: { temp }°C

              Уровень влажности: { humidity }%

              Скорость ветра: { windSpeed } м/с

        );
      }
    });

    return (

{cities[currentCity]}

        <CalendarContainer />

          { result }

    );
  }
}

const element = React.createElement(Weather, {});

ReactDOM.render(
  element,
  document.querySelector('#app')
);

[...document.querySelectorAll('.calendar-block')].forEach( block => {
  trackWidth += block.offsetWidth;
});

TweenLite.set('.calendar-track', { width: trackWidth+1 }); //, x: -(trackWidth-containerWidth)/2

module.hot.accept();
<commit_msg>centered the todays date<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames'; // for building class names with dynamic data
import Api from './utils/api';
import { TweenLite, TweenMax, TimelineMax, TimelineLite } from 'gsap';

import draggable from './draggable';

let cities = [];
let cityWeather = []; // API cache
let currentCity = 0; // Index of current city displayed
const PropTypes = React.PropTypes;

const GetDates = (startDate, daysToAdd, dir) => {
  let aryDates = [];

  for(let i = 1; i <= daysToAdd; i++) {
    const currentDate = new Date();
    switch (dir) {
      case 'future':
        currentDate.setDate(startDate.getDate() + i);
        break;
       case 'past':
       currentDate.setDate(startDate.getDate() - i);
       break;
    }
    aryDates.push({ day: DayAsString(currentDate.getDay()), date: currentDate.getDate(), month: MonthAsString(currentDate.getMonth()), year: currentDate.getFullYear()});
  }

  return aryDates;
}

const MonthAsString = (monthIndex) => {
    const d = new Date();
    const month = new Array();
    month[0]="январь";
    month[1]="февраль";
    month[2]="март";
    month[3]="апрель";
    month[4]="май";
    month[5]="июнь";
    month[6]="июль";
    month[7]="август";
    month[8]="сентябрь";
    month[9]="октябрь";
    month[10]="ноябрь";
    month[11]="декабрь";

    return month[monthIndex];
}

const DayAsString = (dayIndex) => {
    const weekdays = new Array(7);
    weekdays[0] = "вс";
    weekdays[1] = "пн";
    weekdays[2] = "вт";
    weekdays[3] = "ср";
    weekdays[4] = "чт";
    weekdays[5] = "пт";
    weekdays[6] = "суб";

    return weekdays[dayIndex];
}

class CalendarBlocks extends React.Component {
  getNextDays(startDate) {
    const datesArr = GetDates(startDate, 12, 'future');
    let futureDates = [];

    datesArr.forEach(calendarDate => {
      futureDates.push(

{ calendarDate.day }

{ calendarDate.date }

      );
    });

    return futureDates;
  }

  getPreviousDays(startDate) {
    const datesArr = GetDates(startDate, 10, 'past');
    let pastDates = [];

    datesArr.forEach(calendarDatePast => {
      pastDates.push(

{ calendarDatePast.day }

{ calendarDatePast.date }

      );
    });

    return (pastDates.reverse());
  }

  render() {
    const startDate = new Date();

    return (

        { this.getPreviousDays(startDate) }

{ DayAsString(startDate.getDay()) }

{ startDate.getDate() }

        { this.getNextDays(startDate) }

    );
  }
}

class CalendarContainer extends React.Component {
  render() {
    const startDate = new Date();

    return (

{ MonthAsString(startDate.getMonth()) } { startDate.getFullYear() }

              <CalendarBlocks />

    );
  }
}

class Weather extends React.Component {
  constructor() {
    super(),
    this.state = {}
  }

  fetchData() {
    // Get the data from the cache if possible
    if (cityWeather[currentCity]) {
      this.updateData();
    }
    else {
      // Request new data to the API
      Api.get(cities[currentCity])
        .then(function(data) {
          cityWeather[currentCity] = data;
          this.updateData();
        }.bind(this));
    }
  }

  updateData() {
    // Update the data for the UI
    // cityWeather[currentCity] - array, where each element is a collection of data for one period of time (3h)
    this.setState( cityWeather[currentCity].list );
  }

  componentWillMount() {
    cities[0] = 'Moscow';

    // Create a timer to clear the cache after 5 minutes, so we can get updated data from the API
    setInterval(function() {
      cityWeather = []; // Empty the cache
    }, (1000*60*5));

    this.fetchData();
  }

  render() {
    const weatherHourly = this.state;
    let result = [];

    Object.keys(weatherHourly).map((period) => {
      if (period < 3) {
        const temp = Math.round(weatherHourly[period].main.temp);
        const humidity = Math.round(weatherHourly[period].main.humidity);
        const windSpeed = weatherHourly[period].wind.speed;

        result.push(

              День и время: { weatherHourly[period].dt_txt }

              Температура воздуха: { temp }°C

              Уровень влажности: { humidity }%

              Скорость ветра: { windSpeed } м/с

        );
      }
    });

    return (

{cities[currentCity]}

        <CalendarContainer />

          { result }

    );
  }
}

const element = React.createElement(Weather, {});

ReactDOM.render(
  element,
  document.querySelector('#app')
);

const calendarContainer = document.querySelector('.calendar-container');
const calendarTrack = document.querySelector('.calendar-track');
const containerWidth = calendarContainer.clientWidth;
let trackWidth = 0;

[...document.querySelectorAll('.calendar-block')].forEach( block => {
  trackWidth += block.offsetWidth;
});

TweenLite.set(calendarTrack, { width: trackWidth+1 });
TweenLite.set(calendarContainer, { left: -(trackWidth-containerWidth)/2.2 });

module.hot.accept();
<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import walkdir from 'walkdir';
import minimatch from 'minimatch';
import builtInModules from 'builtin-modules';
import requirePackageName from 'require-package-name';

import component from './component';
import getNodes from './utils/get-nodes';
import discoverPropertyDep from './utils/discover-property-dep';

function constructComponent(source, name) {
  return source[name].reduce((result, current) =>
    Object.assign(result, {
      [current]: require(path.resolve(__dirname, name, current)),
    }), {});
}

function objectValues(object) {
  return Object.keys(object).map(key => object[key]);
}

const availableParsers = constructComponent(component, 'parser');

const availableDetectors = constructComponent(component, 'detector');

const availableSpecials = constructComponent(component, 'special');

const defaultOptions = {
  withoutDev: false,
  ignoreBinPackage: false,
  ignoreMatches: [
  ],
  ignoreDirs: [
    '.git',
    '.svn',
    '.hg',
    '.idea',
    'node_modules',
    'bower_components',
  ],
  parsers: {
    '*.js': availableParsers.jsx,
    '*.jsx': availableParsers.jsx,
    '*.coffee': availableParsers.coffee,
    '*.litcoffee': availableParsers.coffee,
    '*.coffee.md': availableParsers.coffee,
  },
  detectors: [
    availableDetectors.importDeclaration,
    availableDetectors.requireCallExpression,
    availableDetectors.gruntLoadTaskCallExpression,
  ],
  specials: objectValues(availableSpecials),
};

function getOrDefault(opt, key) {
  return typeof opt[key] !== 'undefined' ? opt[key] : defaultOptions[key];
}

function unifyParser(parsers) {
  return Object.assign({}, ...Object.keys(parsers).map(key => ({
    [key]: parsers[key] instanceof Array ? parsers[key] : [parsers[key]],
  })));
}

function safeDetect(detector, node) {
  try {
    return detector(node);
  } catch (error) {
    return [];
  }
}

function minus(array1, array2) {
  return array1.filter(item => array2.indexOf(item) === -1);
}

function unique(array, item) {
  return array.indexOf(item) === -1 ? array.concat([item]) : array;
}

function concat(array, item) {
  return array.concat(item);
}

function isStringArray(obj) {
  return obj instanceof Array && obj.every(item => typeof item === 'string');
}

function isNpmPackage(dep) {
  return dep && dep !== '.' && dep !== '..' && builtInModules.indexOf(dep) === -1;
}

function isModule(dir) {
  try {
    require(path.resolve(dir, 'package.json'));
    return true;
  } catch (error) {
    return false;
  }
}

function mergeBuckets(object1, object2) {
  return Object.keys(object2).reduce((result, key) => ({
    ...result,
    [key]: object2[key].concat(object1[key] || []),
  }), object1);
}

function getDependencies(dir, filename, deps, parser, detectors) {
  const detect = node =>
    detectors.map(detector => safeDetect(detector, node)).reduce(concat, []);

  return new Promise((resolve, reject) => {
    fs.readFile(filename, 'utf8', (error, content) => {
      if (error) {
        reject(error);
      }

      try {
        resolve(parser(content, filename, deps, dir));
      } catch (syntaxError) {
        reject(syntaxError);
      }
    });
  }).then(ast => {
    // when parser returns string array, skip detector step and treat them as dependencies directly.
    if (isStringArray(ast)) {
      return ast;
    }

    const dependencies = getNodes(ast)
      .map(detect)
      .reduce(concat, [])
      .reduce(unique, [])
      .map(requirePackageName);

    const peerDeps = dependencies
      .map(dep => discoverPropertyDep(dep, 'peerDependencies', deps, dir))
      .reduce(concat, []);

    const optionalDeps = dependencies
      .map(dep => discoverPropertyDep(dep, 'optionalDependencies', deps, dir))
      .reduce(concat, []);

    return dependencies.concat(peerDeps).concat(optionalDeps);
  });
}

function checkFile(dir, filename, deps, parsers, detectors) {
  const basename = path.basename(filename);
  const targets = Object.keys(parsers)
    .filter(glob => minimatch(basename, glob, { dot: true }))
    .map(key => parsers[key])
    .reduce(concat, []);

  return targets.map(parser =>
    getDependencies(dir, filename, deps, parser, detectors)
      .then(using => ({
        using: {
          [filename]: using.filter(isNpmPackage).reduce(unique, []),
        },
      }), error => ({
        invalidFiles: {
          [filename]: error,
        },
      })));
}

function checkDirectory(dir, rootDir, ignoreDirs, deps, parsers, detectors) {
  return new Promise(resolve => {
    const promises = [];
    const finder = walkdir(dir, { 'no_recurse': true });

    finder.on('directory', subdir =>
      ignoreDirs.indexOf(path.basename(subdir)) === -1 && !isModule(subdir)
      ? promises.push(checkDirectory(subdir, rootDir, ignoreDirs, deps, parsers, detectors))
      : null);

    finder.on('file', filename =>
      promises.push(...checkFile(rootDir, filename, deps, parsers, detectors)));

    finder.on('error', (dirPath, error) =>
      promises.push(Promise.resolve({
        invalidDirs: {
          [dirPath]: error,
        },
      })));

    finder.on('end', () =>
      resolve(Promise.all(promises).then(results =>
        results.reduce((obj, current) => ({
          using: mergeBuckets(obj.using, current.using || {}),
          invalidFiles: Object.assign(obj.invalidFiles, current.invalidFiles),
          invalidDirs: Object.assign(obj.invalidDirs, current.invalidDirs),
        }), {
          using: {},
          invalidFiles: {},
          invalidDirs: {},
        }))));
  });
}

function isIgnored(ignoreMatches, dependency) {
  return ignoreMatches.some(match => minimatch(dependency, match));
}

function hasBin(rootDir, dependency) {
  try {
    const metadata = require(path.join(rootDir, 'node_modules', dependency, 'package.json'));
    return metadata.hasOwnProperty('bin');
  } catch (error) {
    return false;
  }
}

function filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, dependencies) {
  return Object.keys(dependencies)
    .filter(dependency =>
      ignoreBinPackage && hasBin(rootDir, dependency) ||
      isIgnored(ignoreMatches, dependency)
      ? false
      : true);
}

function buildResult(result, deps, devDeps) {
  const usingDepsLookup = Object.keys(result.using).reduce((obj, filename) =>
    result.using[filename].reduce((object, dep) => ({
      ...object,
      [dep]: [filename].concat(object[dep] || []),
    }), obj), {});

  const usingDeps = Object.keys(usingDepsLookup);
  const missingDeps = minus(usingDeps, deps.concat(devDeps));

  const missingDepsLookup = missingDeps.reduce((obj, missingDep) => ({
    ...obj,
    [missingDep]: usingDepsLookup[missingDep],
  }), {});

  return {
    dependencies: minus(deps, usingDeps),
    devDependencies: minus(devDeps, usingDeps),
    missing: missingDepsLookup,
    invalidFiles: result.invalidFiles,
    invalidDirs: result.invalidDirs,
  };
}

export default function depcheck(rootDir, options, callback) {
  const withoutDev = getOrDefault(options, 'withoutDev');
  const ignoreBinPackage = getOrDefault(options, 'ignoreBinPackage');
  const ignoreMatches = getOrDefault(options, 'ignoreMatches');
  const ignoreDirs = defaultOptions.ignoreDirs.concat(options.ignoreDirs).reduce(unique, []);

  const detectors = getOrDefault(options, 'detectors');
  const parsers = Object.assign(
    { '*': getOrDefault(options, 'specials') },
    unifyParser(getOrDefault(options, 'parsers')));

  const metadata = options.package || require(path.join(rootDir, 'package.json'));
  const dependencies = metadata.dependencies || {};
  const devDependencies = metadata.devDependencies || {};
  const deps = filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, dependencies);
  const devDeps = filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, withoutDev ? [] : devDependencies);
  const allDeps = deps.concat(devDeps).reduce(unique, []);

  return checkDirectory(rootDir, rootDir, ignoreDirs, allDeps, parsers, detectors)
    .then(result => buildResult(result, deps, devDeps))
    .then(callback);
}

depcheck.parser = availableParsers;
depcheck.detector = availableDetectors;
depcheck.special = availableSpecials;
<commit_msg>Update the output JSON view to include using dependencies.<commit_after>import fs from 'fs';
import path from 'path';
import walkdir from 'walkdir';
import minimatch from 'minimatch';
import builtInModules from 'builtin-modules';
import requirePackageName from 'require-package-name';

import component from './component';
import getNodes from './utils/get-nodes';
import discoverPropertyDep from './utils/discover-property-dep';

function constructComponent(source, name) {
  return source[name].reduce((result, current) =>
    Object.assign(result, {
      [current]: require(path.resolve(__dirname, name, current)),
    }), {});
}

function objectValues(object) {
  return Object.keys(object).map(key => object[key]);
}

const availableParsers = constructComponent(component, 'parser');

const availableDetectors = constructComponent(component, 'detector');

const availableSpecials = constructComponent(component, 'special');

const defaultOptions = {
  withoutDev: false,
  ignoreBinPackage: false,
  ignoreMatches: [
  ],
  ignoreDirs: [
    '.git',
    '.svn',
    '.hg',
    '.idea',
    'node_modules',
    'bower_components',
  ],
  parsers: {
    '*.js': availableParsers.jsx,
    '*.jsx': availableParsers.jsx,
    '*.coffee': availableParsers.coffee,
    '*.litcoffee': availableParsers.coffee,
    '*.coffee.md': availableParsers.coffee,
  },
  detectors: [
    availableDetectors.importDeclaration,
    availableDetectors.requireCallExpression,
    availableDetectors.gruntLoadTaskCallExpression,
  ],
  specials: objectValues(availableSpecials),
};

function getOrDefault(opt, key) {
  return typeof opt[key] !== 'undefined' ? opt[key] : defaultOptions[key];
}

function unifyParser(parsers) {
  return Object.assign({}, ...Object.keys(parsers).map(key => ({
    [key]: parsers[key] instanceof Array ? parsers[key] : [parsers[key]],
  })));
}

function safeDetect(detector, node) {
  try {
    return detector(node);
  } catch (error) {
    return [];
  }
}

function minus(array1, array2) {
  return array1.filter(item => array2.indexOf(item) === -1);
}

function unique(array, item) {
  return array.indexOf(item) === -1 ? array.concat([item]) : array;
}

function concat(array, item) {
  return array.concat(item);
}

function isStringArray(obj) {
  return obj instanceof Array && obj.every(item => typeof item === 'string');
}

function isNpmPackage(dep) {
  return dep && dep !== '.' && dep !== '..' && builtInModules.indexOf(dep) === -1;
}

function isModule(dir) {
  try {
    require(path.resolve(dir, 'package.json'));
    return true;
  } catch (error) {
    return false;
  }
}

function mergeBuckets(object1, object2) {
  return Object.keys(object2).reduce((result, key) => ({
    ...result,
    [key]: object2[key].concat(object1[key] || []),
  }), object1);
}

function getDependencies(dir, filename, deps, parser, detectors) {
  const detect = node =>
    detectors.map(detector => safeDetect(detector, node)).reduce(concat, []);

  return new Promise((resolve, reject) => {
    fs.readFile(filename, 'utf8', (error, content) => {
      if (error) {
        reject(error);
      }

      try {
        resolve(parser(content, filename, deps, dir));
      } catch (syntaxError) {
        reject(syntaxError);
      }
    });
  }).then(ast => {
    // when parser returns string array, skip detector step and treat them as dependencies directly.
    if (isStringArray(ast)) {
      return ast;
    }

    const dependencies = getNodes(ast)
      .map(detect)
      .reduce(concat, [])
      .reduce(unique, [])
      .map(requirePackageName);

    const peerDeps = dependencies
      .map(dep => discoverPropertyDep(dep, 'peerDependencies', deps, dir))
      .reduce(concat, []);

    const optionalDeps = dependencies
      .map(dep => discoverPropertyDep(dep, 'optionalDependencies', deps, dir))
      .reduce(concat, []);

    return dependencies.concat(peerDeps).concat(optionalDeps);
  });
}

function checkFile(dir, filename, deps, parsers, detectors) {
  const basename = path.basename(filename);
  const targets = Object.keys(parsers)
    .filter(glob => minimatch(basename, glob, { dot: true }))
    .map(key => parsers[key])
    .reduce(concat, []);

  return targets.map(parser =>
    getDependencies(dir, filename, deps, parser, detectors)
      .then(using => ({
        using: {
          [filename]: using.filter(isNpmPackage).reduce(unique, []),
        },
      }), error => ({
        invalidFiles: {
          [filename]: error,
        },
      })));
}

function checkDirectory(dir, rootDir, ignoreDirs, deps, parsers, detectors) {
  return new Promise(resolve => {
    const promises = [];
    const finder = walkdir(dir, { 'no_recurse': true });

    finder.on('directory', subdir =>
      ignoreDirs.indexOf(path.basename(subdir)) === -1 && !isModule(subdir)
      ? promises.push(checkDirectory(subdir, rootDir, ignoreDirs, deps, parsers, detectors))
      : null);

    finder.on('file', filename =>
      promises.push(...checkFile(rootDir, filename, deps, parsers, detectors)));

    finder.on('error', (dirPath, error) =>
      promises.push(Promise.resolve({
        invalidDirs: {
          [dirPath]: error,
        },
      })));

    finder.on('end', () =>
      resolve(Promise.all(promises).then(results =>
        results.reduce((obj, current) => ({
          using: mergeBuckets(obj.using, current.using || {}),
          invalidFiles: Object.assign(obj.invalidFiles, current.invalidFiles),
          invalidDirs: Object.assign(obj.invalidDirs, current.invalidDirs),
        }), {
          using: {},
          invalidFiles: {},
          invalidDirs: {},
        }))));
  });
}

function isIgnored(ignoreMatches, dependency) {
  return ignoreMatches.some(match => minimatch(dependency, match));
}

function hasBin(rootDir, dependency) {
  try {
    const metadata = require(path.join(rootDir, 'node_modules', dependency, 'package.json'));
    return metadata.hasOwnProperty('bin');
  } catch (error) {
    return false;
  }
}

function filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, dependencies) {
  return Object.keys(dependencies)
    .filter(dependency =>
      ignoreBinPackage && hasBin(rootDir, dependency) ||
      isIgnored(ignoreMatches, dependency)
      ? false
      : true);
}

function buildResult(result, deps, devDeps) {
  const usingDepsLookup = Object.keys(result.using).reduce((obj, filename) =>
    result.using[filename].reduce((object, dep) => ({
      ...object,
      [dep]: [filename].concat(object[dep] || []),
    }), obj), {});

  const usingDeps = Object.keys(usingDepsLookup);
  const missingDeps = minus(usingDeps, deps.concat(devDeps));

  const missingDepsLookup = missingDeps.reduce((obj, missingDep) => ({
    ...obj,
    [missingDep]: usingDepsLookup[missingDep],
  }), {});

  return {
    dependencies: minus(deps, usingDeps),
    devDependencies: minus(devDeps, usingDeps),
    missing: missingDepsLookup,
    using: usingDepsLookup,
    invalidFiles: result.invalidFiles,
    invalidDirs: result.invalidDirs,
  };
}

export default function depcheck(rootDir, options, callback) {
  const withoutDev = getOrDefault(options, 'withoutDev');
  const ignoreBinPackage = getOrDefault(options, 'ignoreBinPackage');
  const ignoreMatches = getOrDefault(options, 'ignoreMatches');
  const ignoreDirs = defaultOptions.ignoreDirs.concat(options.ignoreDirs).reduce(unique, []);

  const detectors = getOrDefault(options, 'detectors');
  const parsers = Object.assign(
    { '*': getOrDefault(options, 'specials') },
    unifyParser(getOrDefault(options, 'parsers')));

  const metadata = options.package || require(path.join(rootDir, 'package.json'));
  const dependencies = metadata.dependencies || {};
  const devDependencies = metadata.devDependencies || {};
  const deps = filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, dependencies);
  const devDeps = filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, withoutDev ? [] : devDependencies);
  const allDeps = deps.concat(devDeps).reduce(unique, []);

  return checkDirectory(rootDir, rootDir, ignoreDirs, allDeps, parsers, detectors)
    .then(result => buildResult(result, deps, devDeps))
    .then(callback);
}

depcheck.parser = availableParsers;
depcheck.detector = availableDetectors;
depcheck.special = availableSpecials;
<|endoftext|>


<commit_before>import ready from 'domready'
require('mapbox.js')
require('mapbox.js/theme/style.css')
require('initcss/lib/init.css')
require('./style.css')
import { MAPBOX_ACCESS_TOKEN } from './config.js'
import papaparse from 'papaparse';
import _ from 'lodash';
import data from '../data/coral_bleaching.csv'
L.mapbox.accessToken = MAPBOX_ACCESS_TOKEN

const MIN = -4745;

ready(() => {

  var cache = {}
  var today = new Date(new Date() - 1728e5)
  var day = new Date(today.getTime())
  var dayParameter = function() {
    return day.toISOString().split("T")[0]
  };

  const map_container = document.querySelector('#map')
  const map = L.mapbox.map(map_container, 'mapbox.streets-satellite')
  map.setView([7, -123.5], 6)
  var markMap = L.mapbox.tileLayer('mapbox.streets-satellite').addTo(map);

  var seaSurfaceLayer = L.tileLayer('http://map1{s}.vis.earthdata.nasa.gov/wmts-geo/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.png', {
    layer: "GHRSST_L4_MUR_Sea_Surface_Temperature",
    tileMatrixSet: "EPSG4326_1km",
    time: dayParameter(),
    tileSize: 512,
    subdomains: "abc",
    zIndex: 1,
    opacity: 1,
    noWrap: false, // shouldnt this make it wrap-around?
    continuousWorld: true,
    bounds: [
        [-89.9999, -179.9999],
        [89.9999, 179.9999]
    ],
    attribution: 'NASA EOSDIS GIBS   View Source'
}).addTo(map);

  var landLayer = L.tileLayer('http://map1{s}.vis.earthdata.nasa.gov/wmts-geo/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.png', {
    layer: "OSM_Land_Mask",
    tileMatrixSet: "EPSG4326_250m",
    time: dayParameter(),
    tileSize: 512,
    subdomains: "abc",
    zIndex: 2,
    opacity: 1.0,
    noWrap: false, // shouldnt this make it wrap-around?
    continuousWorld: true,
    bounds: [
        [-89.9999, -179.9999],
        [89.9999, 179.9999]
    ],
    attribution: 'NASA EOSDIS GIBS   View Source'
}).addTo(map);

  var geoBathyLayer = L.tileLayer('http://map1{s}.vis.earthdata.nasa.gov/wmts-geo/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.jpeg', {
    layer: "BlueMarble_ShadedRelief_Bathymetry",
    tileMatrixSet: "EPSG4326_500m",
    time: dayParameter(),
    tileSize: 512,
    subdomains: "abc",
    zIndex: 3,
    opacity: 1,
    noWrap: false, // shouldnt this make it wrap-around?
    continuousWorld: true,
    bounds: [
        [-89.9999, -179.9999],
        [89.9999, 179.9999]
    ],
    attribution: 'NASA EOSDIS GIBS   View Source'
}).addTo(map);
  markMap.on('load', () => {
    papaparse.parse(data, { complete: completed });
  })
  const completed = (results, file) => {
    console.log('file', file);
    console.log('results', results);
    results.data.shift();
    results.data.pop();
    var geoJSON = [];
    _.forEach(results.data, (result) => {
      var colorSchema = '#2f2000'; // default
      var bleachPer = parseInt(result[17]);
      // csonsole.log('results[17]',bleachPer);
      if (bleachPer < 25 && bleachPer > 10) {
        colorSchema = '#6D4B08';
      } else if(bleachPer < 50 && bleachPer >= 25){
          colorSchema = '#AA8439';
      } else if (bleachPer < 75 && bleachPer >= 50) {
        colorSchema = '#E7C889';
      } else if (bleachPer <= 100 && bleachPer >= 75){
        colorSchema = '#FFF3DA';
      }
      if (result[13] !== undefined && result[14] !== undefined) {
        // console.log('result[13], result[14', result[13], result[14]);
        // const leafMarker = L.marker(new L.latLng([result[13], result[14]]), {
        //   icon: L.mapbox.marker.icon({
        //     'marker-size': 'large',
        //     'marker-symbol': 'bus',
        //     'marker-color': colorSchema,
        //   }),
        //   properties: {
        //     'liveCoral': result[15],
        //     'paleCoral': result[16],
        //     'bleachedCoral': result[17],
        //     'paleBleachSum': result[18]
        //   },
        // });
        // console.log('leafMarker', leafMarker);
        // leafMarker.addTo(map);
        var temp = {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [result[13],result[14]],
          },
          "properties": {
            "title": "Hawaii Island Point",
            "description": result[13] + ' ' + result[14],
            "marker-color": colorSchema,
            "marker-size": "large",
            "marker-symbol": "rocket",
          }
        }
        geoJSON.push(temp);
      }
    });
    console.log('geoJSON',geoJSON);
    //var markerLayer =  L.mapbox.featureLayer().addTo(map)
    var layer = L.mapbox.featureLayer().addTo(map);
    console.log('markerLayer',layer, map);
    layer.setGeoJSON(geoJSON)
  };

  var baseLayers =
    {
      'Marker': markMap,
      'Sea Surface Temperature': seaSurfaceLayer,
      'Geography/Ocean Depth': geoBathyLayer
    };

  var controlLayers = L.control.layers(baseLayers).addTo(map);

  // Slider values are in "days from present".
  const slider = $("#day-slider").slider({
      value: 0,
      min: MIN,
      max: 0,
      step: 30, // month increment
      slide: function(event, ui) {
        // Add the slider value (effectively subracting) to today's
        // date.
        var newDay = new Date(today.getTime());
        newDay.setUTCDate(today.getUTCDate() + ui.value);
        day = newDay;
        update();
      }
  });

  var update = function() {
      // Using the day as the cache key, see if the layer is already
      // in the cache.
      var key = dayParameter();
      var layer = cache[key];

      // If not, create a new layer and add it to the cache.
      if ( !layer ) {
          layer = createLayer();
          cache[key] = layer;
      }

      // There is only one layer in this example, but remove them all
      // anyway
      clearLayers();

      // Add the new layer for the selected time
      map.addLayer(layer);

      // Update the day label
      $("#day-label").html(dayParameter());
  };

  var clearLayers = function() {
      map.eachLayer(function(layer) {
          map.removeLayer(layer);
      });
  };

    var mapIcon = L.divIcon({className: 'mapmarker'});
    map.on('click', function(e){
        var marker = new L.marker(e.latlng, {icon: mapIcon}).addTo(map);
        var popLocation= e.latlng;
        var popup = L.popup()
        .setLatLng(popLocation)
        .setContent('
Enter
Coral
Bleaching
Data
')
        .openOn(map);
    });

  var mapGroup;
  var createLayer = function() {

        var layer = L.tileLayer("http://map1{s}.vis.earthdata.nasa.gov/wmts-geo/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.png", {
            layer: "GHRSST_L4_MUR_Sea_Surface_Temperature",
            tileMatrixSet: "EPSG4326_1km",
            time: dayParameter(),
            tileSize: 512,
            subdomains: "abc",
            noWrap: false, // <-- hmm, make map wrap around? (hard to center on hawaii at edge)
            continuousWorld: true,
            // Prevent Leaflet from retrieving non-existent tiles on the
            // borders.
            bounds: [
                [-89.9999, -179.9999],
                [89.9999, 179.9999]
            ],
            attribution:
              "" +
              "NASA EOSDIS GIBS   " +
              "" +
              "View Source" +
              ""
        });
        return layer;
        update();

    let slider_animation = MIN;
    let DELAY = 50;
    let foo = 0;

    function step(timestamp) {
      if(slider_animation < 0) {
        if(foo++ % DELAY == 0) {
          var newDay = new Date(today.getTime());
          newDay.setUTCDate(today.getUTCDate() + slider_animation);
          day = newDay;
          console.log(day)
          $('#day-slider').slider('value', slider_animation += 14);
          update()
        }
        window.requestAnimationFrame(step);
      }
    }
  }
})
<commit_msg>reverted back to the original marker without the tooltip GeoJSON<commit_after>import ready from 'domready'
require('mapbox.js')
require('mapbox.js/theme/style.css')
require('initcss/lib/init.css')
require('./style.css')
import { MAPBOX_ACCESS_TOKEN } from './config.js'
import papaparse from 'papaparse';
import _ from 'lodash';
import data from '../data/coral_bleaching.csv'
L.mapbox.accessToken = MAPBOX_ACCESS_TOKEN

const MIN = -4745;

ready(() => {

  var cache = {}
  var today = new Date(new Date() - 1728e5)
  var day = new Date(today.getTime())
  var dayParameter = function() {
    return day.toISOString().split("T")[0]
  };

  const map_container = document.querySelector('#map')
  const map = L.mapbox.map(map_container, 'mapbox.streets-satellite')
  map.setView([7, -123.5], 6)
  var markMap = L.mapbox.tileLayer('mapbox.streets-satellite').addTo(map);

  var seaSurfaceLayer = L.tileLayer('http://map1{s}.vis.earthdata.nasa.gov/wmts-geo/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.png', {
    layer: "GHRSST_L4_MUR_Sea_Surface_Temperature",
    tileMatrixSet: "EPSG4326_1km",
    time: dayParameter(),
    tileSize: 512,
    subdomains: "abc",
    zIndex: 1,
    opacity: 1,
    noWrap: false, // shouldnt this make it wrap-around?
    continuousWorld: true,
    bounds: [
        [-89.9999, -179.9999],
        [89.9999, 179.9999]
    ],
    attribution: 'NASA EOSDIS GIBS   View Source'
}).addTo(map);

  var landLayer = L.tileLayer('http://map1{s}.vis.earthdata.nasa.gov/wmts-geo/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.png', {
    layer: "OSM_Land_Mask",
    tileMatrixSet: "EPSG4326_250m",
    time: dayParameter(),
    tileSize: 512,
    subdomains: "abc",
    zIndex: 2,
    opacity: 1.0,
    noWrap: false, // shouldnt this make it wrap-around?
    continuousWorld: true,
    bounds: [
        [-89.9999, -179.9999],
        [89.9999, 179.9999]
    ],
    attribution: 'NASA EOSDIS GIBS   View Source'
}).addTo(map);

  var geoBathyLayer = L.tileLayer('http://map1{s}.vis.earthdata.nasa.gov/wmts-geo/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.jpeg', {
    layer: "BlueMarble_ShadedRelief_Bathymetry",
    tileMatrixSet: "EPSG4326_500m",
    time: dayParameter(),
    tileSize: 512,
    subdomains: "abc",
    zIndex: 3,
    opacity: 1,
    noWrap: false, // shouldnt this make it wrap-around?
    continuousWorld: true,
    bounds: [
        [-89.9999, -179.9999],
        [89.9999, 179.9999]
    ],
    attribution: 'NASA EOSDIS GIBS   View Source'
}).addTo(map);
  markMap.on('load', () => {
    papaparse.parse(data, { complete: completed });
  })
  const completed = (results, file) => {
    console.log('file', file);
    console.log('results', results);
    results.data.shift();
    results.data.pop();
    var geoJSON = [];
    _.forEach(results.data, (result) => {
      var colorSchema = '#2f2000'; // default
      var bleachPer = parseInt(result[17]);
      // csonsole.log('results[17]',bleachPer);
      if (bleachPer < 25 && bleachPer > 10) {
        colorSchema = '#6D4B08';
      } else if(bleachPer < 50 && bleachPer >= 25){
          colorSchema = '#AA8439';
      } else if (bleachPer < 75 && bleachPer >= 50) {
        colorSchema = '#E7C889';
      } else if (bleachPer <= 100 && bleachPer >= 75){
        colorSchema = '#FFF3DA';
      }
      if (result[13] !== undefined && result[14] !== undefined) {
        console.log('result[13], result[14', result[13], result[14]);
        const leafMarker = L.marker(new L.latLng([result[13], result[14]]), {
          icon: L.mapbox.marker.icon({
            'marker-size': 'large',
            'marker-symbol': 'bus',
            'marker-color': colorSchema,
          }),
          properties: {
            'liveCoral': result[15],
            'paleCoral': result[16],
            'bleachedCoral': result[17],
            'paleBleachSum': result[18]
          },
        });
        console.log('leafMarker', leafMarker);
        leafMarker.addTo(map);
        // var temp = {
        //   "type": "Feature",
        //   "geometry": {
        //     "type": "Point",
        //     "coordinates": [result[13],result[14]],
        //   },
        //   "properties": {
        //     "title": "Hawaii Island Point",
        //     "description": result[13] + ' ' + result[14],
        //     "marker-color": colorSchema,
        //     "marker-size": "large",
        //     "marker-symbol": "rocket",
        //   }
        // }
        // geoJSON.push(temp);
      }
    });
    // console.log('geoJSON',geoJSON);
    // //var markerLayer =  L.mapbox.featureLayer().addTo(map)
    // var layer = L.mapbox.featureLayer().addTo(map);
    // console.log('markerLayer',layer, map);
    // layer.setGeoJSON(geoJSON)
  };

  var baseLayers =
    {
      'Marker': markMap,
      'Sea Surface Temperature': seaSurfaceLayer,
      'Geography/Ocean Depth': geoBathyLayer
    };

  var controlLayers = L.control.layers(baseLayers).addTo(map);

  // Slider values are in "days from present".
  const slider = $("#day-slider").slider({
      value: 0,
      min: MIN,
      max: 0,
      step: 30, // month increment
      slide: function(event, ui) {
        // Add the slider value (effectively subracting) to today's
        // date.
        var newDay = new Date(today.getTime());
        newDay.setUTCDate(today.getUTCDate() + ui.value);
        day = newDay;
        update();
      }
  });

  var update = function() {
      // Using the day as the cache key, see if the layer is already
      // in the cache.
      var key = dayParameter();
      var layer = cache[key];

      // If not, create a new layer and add it to the cache.
      if ( !layer ) {
          layer = createLayer();
          cache[key] = layer;
      }

      // There is only one layer in this example, but remove them all
      // anyway
      clearLayers();

      // Add the new layer for the selected time
      map.addLayer(layer);

      // Update the day label
      $("#day-label").html(dayParameter());
  };

  var clearLayers = function() {
      map.eachLayer(function(layer) {
          map.removeLayer(layer);
      });
  };

    var mapIcon = L.divIcon({className: 'mapmarker'});
    map.on('click', function(e){
        var marker = new L.marker(e.latlng, {icon: mapIcon}).addTo(map);
        var popLocation= e.latlng;
        var popup = L.popup()
        .setLatLng(popLocation)
        .setContent('
Enter
Coral
Bleaching
Data
')
        .openOn(map);
    });

  var mapGroup;
  var createLayer = function() {

        var layer = L.tileLayer("http://map1{s}.vis.earthdata.nasa.gov/wmts-geo/{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.png", {
            layer: "GHRSST_L4_MUR_Sea_Surface_Temperature",
            tileMatrixSet: "EPSG4326_1km",
            time: dayParameter(),
            tileSize: 512,
            subdomains: "abc",
            noWrap: false, // <-- hmm, make map wrap around? (hard to center on hawaii at edge)
            continuousWorld: true,
            // Prevent Leaflet from retrieving non-existent tiles on the
            // borders.
            bounds: [
                [-89.9999, -179.9999],
                [89.9999, 179.9999]
            ],
            attribution:
              "" +
              "NASA EOSDIS GIBS   " +
              "" +
              "View Source" +
              ""
        });
        return layer;
        update();

    let slider_animation = MIN;
    let DELAY = 50;
    let foo = 0;

    function step(timestamp) {
      if(slider_animation < 0) {
        if(foo++ % DELAY == 0) {
          var newDay = new Date(today.getTime());
          newDay.setUTCDate(today.getUTCDate() + slider_animation);
          day = newDay;
          console.log(day)
          $('#day-slider').slider('value', slider_animation += 14);
          update()
        }
        window.requestAnimationFrame(step);
      }
    }
  }
})
<|endoftext|>


<commit_before>import _ from 'lodash'
import program from 'commander'
import {synchronize} from './sync'

program
  .version(require(`${__dirname}/../package.json`).version)
  .option('--root <path>', 'Path to save NPM package tarballs and metadata to')
  .option('--manifest <file>', 'Path to a package-lock.json file to use as catalog for mirrored NPM packages.')
  .option('--localUrl <url>', 'URL to use as root in stored package metadata (i.e. where folder defined as --root will be exposed at)')
  .option('--binaryAbi <list>', 'Comma-separated list of node C++ ABI numbers to download pre-built binaries for. See NODE_MODULE_VERSION column in https://nodejs.org/en/download/releases/')
  .option('--binaryArch <list>', 'Comma-separated list of CPU architectures to download pre-built binaries for. Valid values: arm, ia32, and x64')
  .option('--binaryPlatform <list>', 'Comma-separated list of OS platforms to download pre-built binaries for. Valid values: linux, darwin, win32, sunos, freebsd, openbsd, and aix')
  .option('--registryUrl [url]', 'Optional URL to use as NPM registry when fetching packages. Default value is https://registry.npmjs.org')
  .option('--dontEnforceHttps', 'Disable the default behavior of downloading tarballs over HTTPS (will use whichever protocol is defined in the registry metadata)')
  .parse(process.argv)

if (!program.root || !program.localUrl || !program.manifest || !program.binaryAbi || !program.binaryArch || !program.binaryPlatform) {
  console.error(program.help())
  process.exit(1)
}

const abis = program.binaryAbi.split(',')
const architectures = program.binaryArch.split(',')
const platforms = program.binaryPlatform.split(',')
const prebuiltBinaryProperties = _.flattenDeep(
  abis.map(abi =>
    architectures.map(arch =>
      platforms.map(platform => ({abi, arch, platform}))
    )
  )
)

const options = {
  localUrl: program.localUrl,
  manifest: program.manifest,
  prebuiltBinaryProperties,
  registryUrl: program.registryUrl || 'https://registry.npmjs.org',
  rootFolder: program.root,
  enforceTarballsOverHttps: !program.dontEnforceHttps
}

synchronize(options)
  .then(newPackages => console.log(`Downloaded ${newPackages.length} packages`))
<commit_msg>Use commander’s new .requiredOption() for required option handling<commit_after>import _ from 'lodash'
import program from 'commander'
import {synchronize} from './sync'

program
  .version(require(`${__dirname}/../package.json`).version)
  .requiredOption('--root <path>', 'Path to save NPM package tarballs and metadata to')
  .requiredOption('--manifest <file>', 'Path to a package-lock.json file to use as catalog for mirrored NPM packages.')
  .requiredOption('--localUrl <url>', 'URL to use as root in stored package metadata (i.e. where folder defined as --root will be exposed at)')
  .requiredOption('--binaryAbi <list>', 'Comma-separated list of node C++ ABI numbers to download pre-built binaries for. See NODE_MODULE_VERSION column in https://nodejs.org/en/download/releases/')
  .requiredOption('--binaryArch <list>', 'Comma-separated list of CPU architectures to download pre-built binaries for. Valid values: arm, ia32, and x64')
  .requiredOption('--binaryPlatform <list>', 'Comma-separated list of OS platforms to download pre-built binaries for. Valid values: linux, darwin, win32, sunos, freebsd, openbsd, and aix')
  .option('--registryUrl [url]', 'Optional URL to use as NPM registry when fetching packages. Default value is https://registry.npmjs.org')
  .option('--dontEnforceHttps', 'Disable the default behavior of downloading tarballs over HTTPS (will use whichever protocol is defined in the registry metadata)')
  .parse(process.argv)

const abis = program.binaryAbi.split(',')
const architectures = program.binaryArch.split(',')
const platforms = program.binaryPlatform.split(',')
const prebuiltBinaryProperties = _.flattenDeep(
  abis.map(abi =>
    architectures.map(arch =>
      platforms.map(platform => ({abi, arch, platform}))
    )
  )
)

const options = {
  localUrl: program.localUrl,
  manifest: program.manifest,
  prebuiltBinaryProperties,
  registryUrl: program.registryUrl || 'https://registry.npmjs.org',
  rootFolder: program.root,
  enforceTarballsOverHttps: !program.dontEnforceHttps
}

synchronize(options)
  .then(newPackages => console.log(`Downloaded ${newPackages.length} packages`))
<|endoftext|>


<commit_before>import Qs from 'qs';
import React, { Component } from 'react';
import { StyleSheet, View, ActivityIndicator } from 'react-native';

export default class extends Component {
  state = { html: null };

  constructor(props) {
    super(props);

    const { source } = props;
    if (source.method) {
      if (props.newWindow) {
        if (source.method === 'POST') {
          const contentType = source.headers['Content-Type'];
          let body = '';
          if (contentType && contentType.includes('application/x-www-form-urlencoded')) {
            body = Qs.parse(source.body);
          } else {
            console.warn(
              '[WebView] When opening a new window, this content-type is not supported yet, please make a PR!',
              contentType
            );
            return;
          }

          window.open(
            require('./postMock.html') +
              '?' +
              Qs.stringify({
                uri: source.uri,
                body: JSON.stringify(body),
              })
          );
        } else {
          console.warn(
            '[WebView] When opening a new window, this method is not supported yet, please make a PR!',
            source.method
          );
        }
      } else {
        const { uri, ...options } = source;
        const baseUrl = uri.substr(0, uri.lastIndexOf('/') + 1);
        fetch(uri, options)
          .then(response => response.text())
          .then(html => this.setState({ html: `<base href="${baseUrl}" />` + html }));
      }
    }
  }

  componentDidMount() {
    if (this.props.onMessage) {
      window.addEventListener('message', this.onMessage, true);
    }
  }

  componentWillUnmount() {
    if (this.props.onMessage) {
      window.removeEventListener('message', this.onMessage, true);
    }
  }

  onMessage = nativeEvent => nativeEvent.isTrusted && this.props.onMessage({ nativeEvent });

  render() {
    if (this.props.newWindow) {
      return (
        <View style={styles.loadingContainer}>
          <ActivityIndicator />
        </View>
      );
    }

    const { source } = this.props;
    return (
      <iframe
        src={!source.method ? source.uri : undefined}
        srcDoc={this.state.html || source.html}
        style={{ width: '100%', height: '100%', border: 0 }}
        allowFullScreen
        allowpaymentrequest="true"
        frameBorder="0"
        seamless
      />
    );
  }
}

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});
<commit_msg>URI, method and body changes are reflected<commit_after>import Qs from 'qs';
import React, { Component } from 'react';
import { StyleSheet, View, ActivityIndicator } from 'react-native';

export default class extends Component {
  state = { html: null };

  constructor(props) {
    super(props);
    this.handleSource(props.source, props.newWindow);
  }

  handleSource = (source, newWindow) => {
    if (!source.method) return;

    if (newWindow) {
      this.handleSourceInNewWindow(source);
    } else {
      this.handleSourceInIFrame(source);
    }
  };

  handleSourceInIFrame = source => {
    const { uri, ...options } = source;
    const baseUrl = uri.substr(0, uri.lastIndexOf('/') + 1);
    fetch(uri, options)
      .then(response => response.text())
      .then(html => this.setState({ html: `<base href="${baseUrl}" />` + html }));
  };

  handleSourceInNewWindow = source => {
    if (source.method === 'POST') {
      const contentType = source.headers['Content-Type'];
      let body = '';
      if (contentType && contentType.includes('application/x-www-form-urlencoded')) {
        body = Qs.parse(source.body);
      } else {
        console.warn(
          '[WebView] When opening a new window, this content-type is not supported yet, please make a PR!',
          contentType
        );
        return;
      }

      window.open(
        require('./postMock.html') +
          '?' +
          Qs.stringify({
            uri: source.uri,
            body: JSON.stringify(body),
          })
      );
    } else {
      console.warn(
        '[WebView] When opening a new window, this method is not supported yet, please make a PR!',
        source.method
      );
    }
  };

  componentDidMount() {
    if (this.props.onMessage) {
      window.addEventListener('message', this.onMessage, true);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (
      this.props.source.uri !== nextProps.source.uri ||
      this.props.source.method !== nextProps.source.method ||
      this.props.source.body !== nextProps.source.body
    ) {
      this.handleSource(nextProps.source, nextProps.newWindow);
    }
  }

  componentWillUnmount() {
    if (this.props.onMessage) {
      window.removeEventListener('message', this.onMessage, true);
    }
  }

  onMessage = nativeEvent => nativeEvent.isTrusted && this.props.onMessage({ nativeEvent });

  render() {
    if (this.props.newWindow) {
      return (
        <View style={styles.loadingContainer}>
          <ActivityIndicator />
        </View>
      );
    }

    const { source } = this.props;
    return (
      <iframe
        src={!source.method ? source.uri : undefined}
        srcDoc={this.state.html || source.html}
        style={{ width: '100%', height: '100%', border: 0 }}
        allowFullScreen
        allowpaymentrequest="true"
        frameBorder="0"
        seamless
      />
    );
  }
}

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});
<|endoftext|>