<commit_before>var fs = require('fs'),
    zip = require('node-zip'),
    parseString = require('xml2js').parseString;

var fileDataInUtf8 = function(uz, fname) {
      return new Buffer(uz.files[fname].data, 'ascii').toString('utf8');
};

var cellIdToCellIdx = function(sheet, cellId) {
  var row = 0,
      col = 0;

  var i;
  for (i = 0; i < cellId.length; ++i) {
    if (cellId[i] < 65) {
      break;
    }

    col *= 10;
    col += cellId.charCodeAt(i) - 65; // cell[i] - 'A';
  }

  var rowNumber = parseInt(cellId.substr(i), 10); // the row number the user is looking for (1-based)

  if(rowNumber < 1){  //check for row number validity, TODO: check outer bounds
     throw ("Index out of bounds: "+ rowNumber);
  }

  //patch, sometimes not all columns are present under row node in the xml structure.
  //for example, first column under row 6 can be B6 and A6 is missing :
  //<row r="6" spans="1:15" ht="15" x14ac:dyDescent="0.25">
  //  <c r="B6" s="25" t="s">
  //    <v>103</v>
  //  </c>
  //  ...
  //in this case, look for column iteratively by cell id.
  //since columns might only be missing,
  //the requested cell must be in a lower col index
  //
  //as this is kinda ugly, we might want to iteratively look for the cell in the first place

  row = rowNumber - 1;   //zero based row number

  while (sheet.worksheet.sheetData[0].row[row] === undefined)
    --row;
  while (sheet.worksheet.sheetData[0].row[row].c[col] === undefined)
    --col;

  var candidateCell = sheet.worksheet.sheetData[0].row[row].c[col];

  var candidateCellAddress = candidateCell.$.r;

  if(candidateCellAddress != cellId){ //cell address is not as expected, find cell iteratively
  //  console.log("looking for :"+ cellId);
    for(j=col; j >= 0; j--){
      if(sheet.worksheet.sheetData[0].row[row].c[j].$.r == cellId){ //found requested cell id!
        col = j;
        break;
      }
    }
    if(j<0){ //cell not found, maybe missing in xml structure, return empty string
      return "";
    }
  }

  return {
    row: row,
    col: col
  };
};

var readSheetCell = function(uz, sharedStrings, sheet, cellId) {

  var idx = cellIdToCellIdx(sheet, cellId);

  var cellValue = sheet.worksheet.sheetData[0].row[idx.row].c[idx.col].v;
  var cellStyle = sheet.worksheet.sheetData[0].row[idx.row].c[idx.col].$.s;
  var cellType = sheet.worksheet.sheetData[0].row[idx.row].c[idx.col].$.t;

  // console.log("cellStyle:"+cellStyle);
  // console.log("cellType:"+cellType);
  // console.log("cellValue:"+cellValue);

  if(cellType == "s"){
    return sharedStrings[cellValue].t[0];
  }

  if(cellValue===undefined){ //cell is empty
    return "";
  }
  else{
    return cellValue[0];
  }

};

var getDimension = function(sheet) {
  var splt = sheet.worksheet.dimension[0].$.ref.split(":");
  return {
    min: splt[0],
    max: splt[1],
    minIdx: cellIdToCellIdx(sheet, splt[0]),
    maxIdx: cellIdToCellIdx(sheet, splt[1])
  };
};

// handler = function(err, result)
var readSheet = function(uz, sharedStrings,sheetId, handler) {

  parseString(fileDataInUtf8(uz, 'xl/worksheets/sheet' + sheetId + '.xml'), function (err, sheet) {
    if (err) {
      handler(err, null);
      return;
    }

    handler(null, readSheetCell.bind(this, uz, sharedStrings, sheet), getDimension(sheet));
  });
};

// handler = function(err, result)
exports.readFile = function(filename, handler) {
  fs.readFile(filename, "binary", function(err, data) {
    if (err) {
      handler(err, null);
      return;
    }
    var uz;
    try{
      uz = new zip(data, { base64: false, checkCRC32: true});
    } catch(e) {
      handler(null, e);
      return;
    }

    parseString(fileDataInUtf8(uz, 'xl/sharedStrings.xml'), function (err, sharedStrings) {
      if (err) {
        handler(err, null);
        return;
      }

      parseString(fileDataInUtf8(uz, 'xl/workbook.xml'), function (err, workbook) {
        if (err) {
          handler(err, null);
          return;
        }

        var result = {
          sheets: []
        };
        workbook.workbook.sheets[0].sheet.forEach(function(s){
          //console.log(s);
          result.sheets.push({
            name: s.$.name,
            id: s.$.sheetId,
            read: readSheet.bind(this, uz, sharedStrings.sst.si, s.$.sheetId)
          });
        });
        handler(null, result);
      });
    });
  });

};

/*
@param String filename
@param Function(Error, [sheet1,sheet2,...])
*/
exports.getFileSheetsNames = function(fileName, callback){
  exports.readFile(fileName, function(err, result) {
    callback(null,result.sheets.map(function(s){return s.name;}));
  });
};

/*
@param String filename
@param String sheet
@param String cellName
@param Function(Error,value) callback
*/
exports.getCellValue = function(filename, sheet, cellName, callback){
  exports.readFile(filename, function(err, result) {
    var _sheet = result.sheets.filter(function(s){return s.name == sheet;})[0];
    if (!_sheet) throw new Error("sheet not found!");
    _sheet.read(function(err,result){
      var value = result(cellName);
      callback(null,value);
    });
  });
};

/*
@param String filename
@param String sheet
@param Function(Error,dim) callback
*/
exports.getDimensions = function(filename, sheet, callback){
  exports.readFile(filename, function(err, result) {
    var _sheet = result.sheets.filter(function(s){return s.name == sheet;})[0];
    if (!_sheet) throw new Error("sheet not found!");
    _sheet.read(function(err,result,dim){
      callback(null,dim);
    });
  });
};<commit_msg>readSheet in xslxparser<commit_after>var fs = require('fs'),
    zip = require('node-zip'),
    parseString = require('xml2js').parseString;

var fileDataInUtf8 = function(uz, fname) {
      return new Buffer(uz.files[fname].data, 'ascii').toString('utf8');
};

var cellIdToCellIdx = function(sheet, cellId) {
  var row = 0,
      col = 0;

  var i;
  for (i = 0; i < cellId.length; ++i) {
    if (cellId[i] < 65) {
      break;
    }

    col *= 10;
    col += cellId.charCodeAt(i) - 65; // cell[i] - 'A';
  }

  var rowNumber = parseInt(cellId.substr(i), 10); // the row number the user is looking for (1-based)

  if(rowNumber < 1){  //check for row number validity, TODO: check outer bounds
     throw ("Index out of bounds: "+ rowNumber);
  }

  //patch, sometimes not all columns are present under row node in the xml structure.
  //for example, first column under row 6 can be B6 and A6 is missing :
  //<row r="6" spans="1:15" ht="15" x14ac:dyDescent="0.25">
  //  <c r="B6" s="25" t="s">
  //    <v>103</v>
  //  </c>
  //  ...
  //in this case, look for column iteratively by cell id.
  //since columns might only be missing,
  //the requested cell must be in a lower col index
  //
  //as this is kinda ugly, we might want to iteratively look for the cell in the first place

  row = rowNumber - 1;   //zero based row number

  while (sheet.worksheet.sheetData[0].row[row] === undefined)
    --row;
  while (sheet.worksheet.sheetData[0].row[row].c[col] === undefined)
    --col;

  var candidateCell = sheet.worksheet.sheetData[0].row[row].c[col];

  var candidateCellAddress = candidateCell.$.r;

  if(candidateCellAddress != cellId){ //cell address is not as expected, find cell iteratively
  //  console.log("looking for :"+ cellId);
    for(j=col; j >= 0; j--){
      if(sheet.worksheet.sheetData[0].row[row].c[j].$.r == cellId){ //found requested cell id!
        col = j;
        break;
      }
    }
    if(j<0){ //cell not found, maybe missing in xml structure, return empty string
      return "";
    }
  }

  return {
    row: row,
    col: col
  };
};

var readSheetCell = function(uz, sharedStrings, sheet, cellId) {

  var idx = cellIdToCellIdx(sheet, cellId);

  var cellValue = sheet.worksheet.sheetData[0].row[idx.row].c[idx.col].v;
  var cellStyle = sheet.worksheet.sheetData[0].row[idx.row].c[idx.col].$.s;
  var cellType = sheet.worksheet.sheetData[0].row[idx.row].c[idx.col].$.t;

  // console.log("cellStyle:"+cellStyle);
  // console.log("cellType:"+cellType);
  // console.log("cellValue:"+cellValue);

  if(cellType == "s"){
    return sharedStrings[cellValue].t[0];
  }

  if(cellValue===undefined){ //cell is empty
    return "";
  }
  else{
    return cellValue[0];
  }

};

var getDimension = function(sheet) {
  var splt = sheet.worksheet.dimension[0].$.ref.split(":");
  return {
    min: splt[0],
    max: splt[1],
    minIdx: cellIdToCellIdx(sheet, splt[0]),
    maxIdx: cellIdToCellIdx(sheet, splt[1])
  };
};

// handler = function(err, result)
var readSheet = function(uz, sharedStrings,sheetId, handler) {

  parseString(fileDataInUtf8(uz, 'xl/worksheets/sheet' + sheetId + '.xml'), function (err, sheet) {
    if (err) {
      handler(err, null);
      return;
    }

    handler(null, readSheetCell.bind(this, uz, sharedStrings, sheet), getDimension(sheet));
  });
};

// handler = function(err, result)
exports.readFile = function(filename, handler) {
  fs.readFile(filename, "binary", function(err, data) {
    if (err) {
      handler(err, null);
      return;
    }
    var uz;
    try{
      uz = new zip(data, { base64: false, checkCRC32: true});
    } catch(e) {
      handler(null, e);
      return;
    }

    parseString(fileDataInUtf8(uz, 'xl/sharedStrings.xml'), function (err, sharedStrings) {
      if (err) {
        handler(err, null);
        return;
      }

      parseString(fileDataInUtf8(uz, 'xl/workbook.xml'), function (err, workbook) {
        if (err) {
          handler(err, null);
          return;
        }

        var result = {
          sheets: []
        };
        workbook.workbook.sheets[0].sheet.forEach(function(s){
          //console.log(s);
          result.sheets.push({
            name: s.$.name,
            id: s.$.sheetId,
            read: readSheet.bind(this, uz, sharedStrings.sst.si, s.$.sheetId)
          });
        });
        handler(null, result);
      });
    });
  });

};

/*
@param String filename
@param Function(Error, [sheet1,sheet2,...])
*/
exports.getFileSheetsNames = function(fileName, callback){
  exports.readFile(fileName, function(err, result) {
    callback(null,result.sheets.map(function(s){return s.name;}));
  });
};

/*
@param String filename
@param String sheet
@param String cellName
@param Function(Error,value) callback
*/
exports.getCellValue = function(filename, sheet, cellName, callback){
  exports.readFile(filename, function(err, result) {
    var _sheet = result.sheets.filter(function(s){return s.name == sheet;})[0];
    if (!_sheet) throw new Error("sheet not found!");
    _sheet.read(function(err,result){
      var value = result(cellName);
      callback(null,value);
    });
  });
};

/*
@param String filename
@param String sheet
@param Function(Error,dim) callback
*/
exports.getDimensions = function(filename, sheet, callback){
  exports.readFile(filename, function(err, result) {
    var _sheet = result.sheets.filter(function(s){return s.name == sheet;})[0];
    if (!_sheet) throw new Error("sheet not found!");
    _sheet.read(function(err,result,dim){
      callback(null,dim);
    });
  });
};

exports.openSheet = function(filename, sheet, callback){
  exports.readFile(filename, function(err, result) {
    var _sheet = result.sheets.filter(function(s){return s.name == sheet;})[0];
    if (!_sheet){
      callback(new Error("sheet not found!"));
      return;
    }
    _sheet.read(callback);
  });
};

<|endoftext|>


<commit_before>var should = require('should'),
    vargs = require('../index.js')

describe('vargs', function () {
    it('should be a function', function () {
        vargs.should.be.type('function')
    })

    it('should add non-enumerable vargs property to all the functions', function () {
        function foo() {}
        foo.should.have.property('vargs')
        foo.should.not.have.ownProperty('vargs')
        Object.keys(foo).should.not.include('vargs')
    })

    it('should make callaback the last argument', function () {
        function foo(a, b, c) {
            should.strictEqual(a ? 1 : undefined, a)
            should.strictEqual(b ? 2 : undefined, b)
            should(c).be.type('function')
        }
        foo = foo.vargs

        foo(function () {})
        foo(1, function () {})
        foo(1, 2, function () {})
    })

    it('should not modify arguments if the last argument is not a function', function () {
        function foo(a, b, c) {
            should(c).not.be.type('function')
        }
        foo = foo.vargs

        foo()
        foo(1)
        foo(1, 2)
        foo(1, 2, 3)
        foo(function () {}, 1)
    })

    it('should not modify arguments if there are more than stated in the function definition', function () {
        var cb = function () {}

        ;(function (a, b, c) {
            arguments.should.eql([1, 2, 3, cb])
            ;[a, b, c].should.eql([1, 2, 3])
        }.vargs(1, 2, 3, cb))
    })
})
<commit_msg>Two more tests<commit_after>var should = require('should'),
    vargs = require('../index.js')

describe('vargs', function () {
    it('should add non-enumerable vargs property to all the functions', function () {
        function foo() {}
        foo.should.have.property('vargs')
        foo.should.not.have.ownProperty('vargs')
        Object.keys(foo).should.not.include('vargs')
    })

    it('should make callaback the last argument', function () {
        function foo(a, b, c) {
            should.strictEqual(a ? 1 : undefined, a)
            should.strictEqual(b ? 2 : undefined, b)
            should(c).be.type('function')
        }
        foo = foo.vargs

        foo(function () {})
        foo(1, function () {})
        foo(1, 2, function () {})
    })

    it('should not modify arguments if the last argument is not a function', function () {
        function foo(a, b, c) {
            should(c).not.be.type('function')
        }
        foo = foo.vargs

        foo()
        foo(1)
        foo(1, 2)
        foo(1, 2, 3)
        foo(function () {}, 1)
    })

    it('should not modify arguments if there are more than stated in the function definition', function () {
        var cb = function () {}

        ;(function (a, b, c) {
            arguments.should.eql([1, 2, 3, cb])
            ;[a, b, c].should.eql([1, 2, 3])
        }.vargs(1, 2, 3, cb))
    })

    it('exported object should be a function', function () {
        vargs.should.be.type('function')
    })

    it('exported function should do the same thing as .vargs property', function () {
        function foo(a, b, c) {
            return arguments
        }
        foo = foo.vargs

        function bar(a, b, c) {
            return arguments
        }
        bar = vargs(bar)

        var cb = function () {}

        foo(1, cb).should.eql(bar(1, cb))
    })
})
<|endoftext|>


<commit_before>"use strict";

const exec = require("../exec.js"),
    helper = require("../helper.js");

module.exports = (config) => {
    return _lastRelease(config)
            .then(_mkdir)
            .then(_createRelease)
            .then(_rsync);
};

function _lastRelease(config) {
    return exec.remote(
        config.internal.write,
        config.internal.server,
        `ls -1t ${config.internal.server.to}/releases | head -n 1`
        )
        .then((lastRelease) => {
            config.internal.lastRelease = lastRelease;

            return config;
        })
        .catch((error) => {
            throw new Error(error);
        });
}

function _mkdir(config) {
    return exec.remote(
        config.internal.write,
        config.internal.server,
        helper.mkdir(
            `${config.internal.server.to}/releases`,
            `${config.internal.server.to}/shared`
            ))
        .then(() => config)
        .catch((error) => {
            throw new Error(error);
        });
}

function _createRelease(config) {
    if (config.internal.lastRelease !== "") {
        let mkdirRemotePath = [
            `cp -R ${config.internal.server.to}/releases/${config.internal.lastRelease}`,
            `${config.internal.server.to}/releases/${config.internal.release}`
            ].join(" ");

        return exec.remote(
            config.internal.write,
            config.internal.server, mkdirRemotePath
            )
            .then(() => config)
            .catch((error) => {
                throw new Error(error);
            });
    }

    return config;
}

function _rsync(config) {
    let cmd = [
        "rsync",
        "-az",
        "--delete",
        config.ignores.map(function (item) {
            return `--exclude=${item}`;
        }).join(" "),
        config.shared.files.map(function (item) {
            return `--exclude=${item}`;
        }).join(" "),
        config.shared.folders.map(function (item) {
            return `--exclude=${item}`;
        }).join(" "),
        config.workspace + "/",
        [
            [config.internal.server.user, config.internal.server.host].join("@"),
            `${config.internal.server.to}/releases/${config.internal.release}`
        ].join(":")
    ].join(" ");

    return exec.local(config.internal.write, cmd)
        .then(() => config)
        .catch((error) => {
            throw new Error(error);
        });
}<commit_msg>rsync uses --delete-excluded option to remove folder newest excluded or dependencies removed by example<commit_after>"use strict";

const exec = require("../exec.js"),
    helper = require("../helper.js");

module.exports = (config) => {
    return _lastRelease(config)
            .then(_mkdir)
            .then(_createRelease)
            .then(_rsync);
};

function _lastRelease(config) {
    return exec.remote(
        config.internal.write,
        config.internal.server,
        `ls -1t ${config.internal.server.to}/releases | head -n 1`
        )
        .then((lastRelease) => {
            config.internal.lastRelease = lastRelease;

            return config;
        })
        .catch((error) => {
            throw new Error(error);
        });
}

function _mkdir(config) {
    return exec.remote(
        config.internal.write,
        config.internal.server,
        helper.mkdir(
            `${config.internal.server.to}/releases`,
            `${config.internal.server.to}/shared`
            ))
        .then(() => config)
        .catch((error) => {
            throw new Error(error);
        });
}

function _createRelease(config) {
    if (config.internal.lastRelease !== "") {
        let mkdirRemotePath = [
            `cp -R ${config.internal.server.to}/releases/${config.internal.lastRelease}`,
            `${config.internal.server.to}/releases/${config.internal.release}`
            ].join(" ");

        return exec.remote(
            config.internal.write,
            config.internal.server, mkdirRemotePath
            )
            .then(() => config)
            .catch((error) => {
                throw new Error(error);
            });
    }

    return config;
}

function _rsync(config) {
    let cmd = [
        "rsync",
        "-az",
        "--delete",
        "--delete-excluded",
        config.ignores.map(function (item) {
            return `--exclude=${item}`;
        }).join(" "),
        config.shared.files.map(function (item) {
            return `--exclude=${item}`;
        }).join(" "),
        config.shared.folders.map(function (item) {
            return `--exclude=${item}`;
        }).join(" "),
        config.workspace + "/",
        [
            [config.internal.server.user, config.internal.server.host].join("@"),
            `${config.internal.server.to}/releases/${config.internal.release}`
        ].join(":")
    ].join(" ");

    return exec.local(config.internal.write, cmd)
        .then(() => config)
        .catch((error) => {
            throw new Error(error);
        });
}<|endoftext|>


<commit_before>(function($) {
    $.fn.excerptize = function(options) {
            var defaults = {
                numberOfCharacters: 100,
                cutOffAtWord: true,
                tags: 'span',
                showMoreText: '[...]',
                showLessText: 'less'
            };

            options = $.extend(defaults, options);

            var excerptizedObj = $(this),
                fullText = excerptizedObj.text(),
                excerpt = fullText.substr(0, options.numberOfCharacters),
                excerptized = '';

            // if full text is less than or equal to excerpt, don't bother
            if(fullText.length<=options.numberOfCharacters) {
            	return;
            }

            if(options.cutOffAtWord) {
            	excerpt = excerpt.substr(0, Math.min(excerpt.length, excerpt.lastIndexOf(" ")))
            }

            excerptizedObj.html(getExcerptized(excerpt, fullText, options));
            bindControls(excerptizedObj);

            // To avoid the flicker when page first loads,
            // you can make the 'excerptized' element hidden.
            // This will ensure excerpt is displayed.
            excerptizedObj.show();
	}

    // private functions

    function getExcerptized(excerpt, fullText, options) {
        return excerpt
                + ' '
                + options.showMoreText
                + ''
                + '<'+options.tags+' style="display:none;">'
                + fullText.substr(excerpt.length)
                + ''
                + options.showLessText + ''
                + '</'+options.tags+'>';
    }

    function bindControls(excerptizedObj) {
        excerptizedObj.find('.excerptized-show-more').click(function(){
            $(this).hide();
            $(this).next().show();
        });

        excerptizedObj.find('.excerptized-show-less').click(function(){
            $(this).parent().hide();
            excerptizedObj.find('.excerptized-show-more').show();
        });
    }
})(jQuery);
<commit_msg>Added support for multiple elements.<commit_after>(function($) {
    $.fn.excerptize = function(options) {
            var defaults = {
                numberOfCharacters: 100,
                cutOffAtWord: true,
                tags: 'span',
                showMoreText: '[...]',
                showLessText: 'less'
            };

            options = $.extend(defaults, options);

            $(this).each(function(){
                var excerptizedObj = $(this),
                fullText = excerptizedObj.text(),
                excerpt = fullText.substr(0, options.numberOfCharacters),
                excerptized = '';

	            // if full text is less than or equal to excerpt, don't bother
	            if(fullText.length<=options.numberOfCharacters) {
	                return;
	            }

	            if(options.cutOffAtWord) {
	                excerpt = excerpt.substr(0, Math.min(excerpt.length, excerpt.lastIndexOf(" ")))
	            }

	            excerptizedObj.html(getExcerptized(excerpt, fullText, options));
	            bindControls(excerptizedObj);

	            // To avoid the flicker when page first loads,
	            // you can make the 'excerptized' element hidden.
	            // This will ensure excerpt is displayed.
	            excerptizedObj.show();
            });
	}

    // private functions

    function getExcerptized(excerpt, fullText, options) {
        return excerpt
                + ' '
                + options.showMoreText
                + ''
                + '<'+options.tags+' style="display:none;">'
                + fullText.substr(excerpt.length)
                + ''
                + options.showLessText + ''
                + '</'+options.tags+'>';
    }

    function bindControls(excerptizedObj) {
        excerptizedObj.find('.excerptized-show-more').click(function(){
            $(this).hide();
            $(this).next().show();
        });

        excerptizedObj.find('.excerptized-show-less').click(function(){
            $(this).parent().hide();
            excerptizedObj.find('.excerptized-show-more').show();
        });
    }
})(jQuery);
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var path = require('path')

// This is returned as the module
var indexRoute = {
    changePage: null,
    router: router
}

router.route('/')
    .get(function (req, res) {
        res.render('main/index', {
            pageId: "Home",
            pageTitle: "Home Control",
            pageDescription: "Home Control's landing page.",
            pageCss: ['main'],
            pageScripts: ['dummyScript'],
            useBootstrap: true
        });
    });

router.route('/switcher')
    .get(isLoggedIn, function (req, res) {

        if (!req.cookies.deviceName) {
            res.redirect('/device');
        }

        res.render('main/switcher', {
            pageId: "Switcher",
            pageTitle: "Home Control Switcher",
            pageDescription: "Home Control's switcher page.",
            pageCss: ['main'],
            pageScripts: ['switcher'],
            useBootstrap: true,
            useSocket: true,
            userID: req.session.passport.user
        });
    });

router.route('/viewer')
    .get(isLoggedIn, function (req, res) {

        if (!req.cookies.deviceName) {
            res.redirect('/device');
            return;
        }

        res.render('main/viewer', {
            pageId: "Viewer",
            pageTitle: "Home Control",
            pageDescription: "Home Control's viewing page.",
            pageCss: ['main'],
            pageScripts: ['viewer'],
            useBootstrap: true,
            useSocket: true,
            userID: req.session.passport.user
        });
    });

router.post('/switch', function(req, res) {
    let action = req.body.result.action;

    // Show page intent
    if (action === 'show_page') {
        let page = req.body.result.parameters.page;
        let devices = req.body.result.parameters.devices;
        indexRoute.changePage(page, devices);
        let speech = "Showing " + page;
        if (devices) {
            speech += " on ";
            devices.forEach(function(device, index) {
                if (index === devices.length - 1 && devices.length !== 1) {
                    speech += ", and " + device;
                } else {
                    speech += ", " + device;
                }
            });
        }
        res.json({
            "speech": speech,
            "displayText": speech,
            "source": "home.carlschriever.com",
            "data": {
                "google": {
                    "expect_user_response": false,
                }
            }
        });
    } else if (action === 'show_weather') {
        let location = req.body.result.parameters.location || 'Atlanta';
        indexRoute.changePage('weather/' + location);
        res.json({
            "speech": "Showing weather for " + location,
            "displayText": "Showing weather for " + location,
            "source": "home.carlschriever.com",
            "data": {
                "google": {
                    "expect_user_response": false,
                }
            }
        });
    } else if (action === 'activate_button') {
        let button = req.body.result.parameters.button_id;
        res.json({
            "speech": "Pressing " + button,
            "displayText": "Pressing " + button,
            "source": "home.carlschriever.com",
            "data": {
                "google": {
                    "expect_user_response": false,
                }
            }
        });
    } else if (action === 'show_cheat_sheet') {
        let page = 'cheatsheet/' + req.body.result.parameters.cheatsheet;
        let devices = req.body.result.parameters.devices;
        indexRoute.changePage(page, devices);
        let speech = "Showing " + page;
        if (devices) {
            speech += " on ";
            devices.forEach(function(device, index) {
                if (index === devices.length - 1 && devices.length !== 1) {
                    speech += ", and " + device;
                } else {
                    speech += ", " + device;
                }
            });
        }
        res.json({
            "speech": speech,
            "displayText": speech,
            "source": "home.carlschriever.com",
            "data": {
                "google": {
                    "expect_user_response": false,
                }
            }
        });
        indexRoute.changePage('weather/' + location);
    }
});

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/user/login');
}

module.exports = function(changePage) {
    indexRoute.changePage = changePage;

    return indexRoute;
};<commit_msg>Remove additional page switch<commit_after>var express = require('express');
var router = express.Router();
var path = require('path')

// This is returned as the module
var indexRoute = {
    changePage: null,
    router: router
}

router.route('/')
    .get(function (req, res) {
        res.render('main/index', {
            pageId: "Home",
            pageTitle: "Home Control",
            pageDescription: "Home Control's landing page.",
            pageCss: ['main'],
            pageScripts: ['dummyScript'],
            useBootstrap: true
        });
    });

router.route('/switcher')
    .get(isLoggedIn, function (req, res) {

        if (!req.cookies.deviceName) {
            res.redirect('/device');
        }

        res.render('main/switcher', {
            pageId: "Switcher",
            pageTitle: "Home Control Switcher",
            pageDescription: "Home Control's switcher page.",
            pageCss: ['main'],
            pageScripts: ['switcher'],
            useBootstrap: true,
            useSocket: true,
            userID: req.session.passport.user
        });
    });

router.route('/viewer')
    .get(isLoggedIn, function (req, res) {

        if (!req.cookies.deviceName) {
            res.redirect('/device');
            return;
        }

        res.render('main/viewer', {
            pageId: "Viewer",
            pageTitle: "Home Control",
            pageDescription: "Home Control's viewing page.",
            pageCss: ['main'],
            pageScripts: ['viewer'],
            useBootstrap: true,
            useSocket: true,
            userID: req.session.passport.user
        });
    });

router.post('/switch', function(req, res) {
    let action = req.body.result.action;

    // Show page intent
    if (action === 'show_page') {
        let page = req.body.result.parameters.page;
        let devices = req.body.result.parameters.devices;
        indexRoute.changePage(page, devices);
        let speech = "Showing " + page;
        if (devices) {
            speech += " on ";
            devices.forEach(function(device, index) {
                if (index === devices.length - 1 && devices.length !== 1) {
                    speech += ", and " + device;
                } else {
                    speech += ", " + device;
                }
            });
        }
        res.json({
            "speech": speech,
            "displayText": speech,
            "source": "home.carlschriever.com",
            "data": {
                "google": {
                    "expect_user_response": false,
                }
            }
        });
    } else if (action === 'show_weather') {
        let location = req.body.result.parameters.location || 'Atlanta';
        indexRoute.changePage('weather/' + location);
        res.json({
            "speech": "Showing weather for " + location,
            "displayText": "Showing weather for " + location,
            "source": "home.carlschriever.com",
            "data": {
                "google": {
                    "expect_user_response": false,
                }
            }
        });
    } else if (action === 'activate_button') {
        let button = req.body.result.parameters.button_id;
        res.json({
            "speech": "Pressing " + button,
            "displayText": "Pressing " + button,
            "source": "home.carlschriever.com",
            "data": {
                "google": {
                    "expect_user_response": false,
                }
            }
        });
    } else if (action === 'show_cheat_sheet') {
        let page = 'cheatsheet/' + req.body.result.parameters.cheatsheet;
        let devices = req.body.result.parameters.devices;
        indexRoute.changePage(page, devices);
        let speech = "Showing " + page;
        if (devices) {
            speech += " on ";
            devices.forEach(function(device, index) {
                if (index === devices.length - 1 && devices.length !== 1) {
                    speech += ", and " + device;
                } else {
                    speech += ", " + device;
                }
            });
        }
        res.json({
            "speech": speech,
            "displayText": speech,
            "source": "home.carlschriever.com",
            "data": {
                "google": {
                    "expect_user_response": false,
                }
            }
        });
    }
});

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/user/login');
}

module.exports = function(changePage) {
    indexRoute.changePage = changePage;

    return indexRoute;
};<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var should = require('should');

exports = module.exports = function(runtime, util){
  should.exists(util);
  var create = runtime.create;
  var testFile = 'test/dir/watch.js';

  before(function(done){
    util.mkdirp('test/dir', done);
  });

  beforeEach(function(done){
    fs.writeFile(testFile, util.content, done);
  });

  after(function(done){
    util.rimraf('test/dir', done);
  });

  it('(no opts) on change, should invoke callback', function(done){
    var gulp = create('watch callback', {log: false});

    var watcher = gulp.watch(testFile, function(){
      watcher.end();
      done();
    });

    util.rimraf(testFile, function(err){
      if(err){ throw err; }
    });
  });

  it('(opt string) should run tasks given', function(done){
    var gulp = create('watch opt string', {log: false});

    var watcher = gulp.watch(testFile, 'string', function(){
      watcher.end();
    });

    gulp.task('string', function(next){
      next(); done();
    });

    util.rimraf(testFile, function(err){
      if(err){ throw err; }
    });
  });

  it('(opt array) should run tasks given', function(done){
    var gulp = create('opt array', {log: false});

    gulp.task('array', function(next){
      next(); done();
    });

    var watcher = gulp.watch(testFile, ['array'], function(){
      watcher.end();
    });

    util.rimraf(testFile, function(err){
      if(err){ throw err; }
    });
  });

  it('should reload files if so was said', function(done){
    var gulp = create('reload file', {log: false});

    // arrange state change
    gulp.task('reload file', function(next){
      // assert initial state
      var testModule = require('./dir/watch');
      testModule.should.be.eql({content: 'changed'});

      // change exports
      testModule.prop = 'here';

      testModule.should.have.properties({
        content: 'changed',
        prop: 'here'
      });
      next();
    });

    var watcher = gulp.watch(testFile, {
      reload: true,
      tasks: 'reload file'
    }, function(){
      var reloaded = require('./dir/watch');
      reloaded.should.be.eql({content: 'changed'});
      watcher.end();
      done();
    });

    setTimeout(function(){
      fs.writeFile(testFile, util.contentChanged, function(err){
        if(err){ done(err); }
      });
    }, 150);
  });
};
<commit_msg>tests: add new watch tests<commit_after>'use strict';

var fs = require('fs');
var should = require('should');

exports = module.exports = function(Gulp, util){
  should.exists(util);

  before(function(done){
    util.mkdirp('test/dir', done);
  });

  after(function(done){
    util.rimraf('test/dir', done);
  });

  function setupTest(onSuccess, onError){
    fs.writeFile(util.testFile, util.content, function(writeError){
      if(writeError){ onError(writeError); return; }

      onSuccess();

      setTimeout(function(){
        util.rimraf(util.testFile, function (deleteError){
          if(deleteError){ onError(deleteError); }
        });
      }, 10);
    });
  }

  it('watch(glob, [Function]) should call function on change', function(done){
    var gulp = Gulp.create({log: false});

    setupTest(function(){
      var watcher = gulp.watch(util.testFile, function(){
        watcher.end();
        done();
      });
    }, done);
  });

  it('watch(glob, tasks) runs `tasks` in parallel after change', function(done){
    var pile = [];
    var gulp = Gulp.create({
      log: false,
      onHandleError: done
    });

    gulp.task('one', function(next){
      setTimeout(function(){
        pile.push('one');
        next();
      }, Math.random() * 10);
    });

    gulp.task('two', function(next){
      setTimeout(function(){
        pile.push('two');
        next();
      }, Math.random() * 10);
    });

    setupTest(function(){
      var watcher = gulp.watch(util.testFile, ['one', 'two'], function(){
        pile.should.containDeep(['one', 'two']);
        watcher.end();
        done();
      });
    }, done);
  });
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { featureCollection } from '@turf/helpers';
import turfCentroid from '@turf/centroid';
import turfBbox from '@turf/bbox';
import turfBboxPolygon from '@turf/bbox-polygon';

import mapboxgl from 'mapbox-gl/dist/mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

import EditBar from './edit_bar';

import { MAPBOX_ACCESS_TOKEN, MAPBOX_GEOCODER_URL, JOSM_RC_URL, ID_URL } from '../../config';
import ItemsActionCreators from '../../stores/items_action_creators';
import ModalsActionCreators from '../../stores/modals_action_creators';
import ItemsSelectors from '../../stores/items_selectors';
import UserSelectors from '../../stores/user_selectors';
import SettingsSelectors from '../../stores/settings_selectors';
import TasksSelectors from '../../stores/tasks_selectors';

import TaskControl from './controls/task';
const taskControl = new TaskControl();

const mapStateToProps = (state) => ({
  currentTask: TasksSelectors.getCurrentTask(state),
  currentTaskId: TasksSelectors.getCurrentTaskId(state),
  currentTaskType: TasksSelectors.getCurrentTaskType(state),
  user: UserSelectors.getUsername(state),
  editor: SettingsSelectors.getEditorSetting(state),
  sidebar: SettingsSelectors.getSidebarSetting(state),
  currentItem: ItemsSelectors.getCurrentItem(state),
  currentItemId: ItemsSelectors.getCurrentItemId(state),
});

const mapDispatchToProps = {
  fetchRandomItem: ItemsActionCreators.fetchRandomItem,
  openErrorModal: ModalsActionCreators.openErrorModal,
};

mapboxgl.accessToken = MAPBOX_ACCESS_TOKEN;

class Task extends Component {
  state = {
    map: null,
    geolocation: '',
  }

  editTask = () => {
    const { map } = this.state;
    const { editor } = this.props;

    if (editor === 'josm') {
      const { currentItem } = this.props;
      const { _osmType, _osmId } = currentItem.properties;

      if (_osmType && _osmId) {
        const objects = `${_osmType.substr(0, 1)}${_osmId}`;

        const query = {
          new_layer: true,
          objects,
          relation_members: true,
        };
        const params = Object.keys(query).map(key => `${key}=${query[key]}`).join('&');

        fetch(`${JOSM_RC_URL}/load_object?${params}`)
          .catch(() => this.props.openErrorModal('Could not connect to JOSM remote control.'));
      } else {
        const bounds = map.getBounds();

        const bottom = bounds.getSouthWest().lat - 0.0005;
        const left = bounds.getSouthWest().lng - 0.0005;
        const top = bounds.getNorthEast().lat - 0.0005;
        const right = bounds.getNorthEast().lng - 0.0005;

        const query = { left, right, top, bottom };
        const params = Object.keys(query).map(key => `${key}=${query[key]}`).join('&');

        fetch(`${JOSM_RC_URL}/load_and_zoom?${params}`)
          .catch(() => this.props.openErrorModal('Could not connect to JOSM remote control.'));
      }
    }

    if (editor === 'id') {
      const {lng, lat} = map.getCenter();
      const zoom = map.getZoom();

      const iDEditPath = `${ID_URL}/#map=${zoom}/${lat}/${lng}`;

      window.open(iDEditPath, '_blank');
    }
  }

  reset = () => {
    this.setState({
      geolocation: '',
    });
  }

  fetchNextItem = () => {
    const { user, editor, currentTaskId, currentTaskType, fetchRandomItem } = this.props;
    const payload = {
      user: user || '',
      editor,
    };

    fetchRandomItem({ taskId: currentTaskId, taskType: currentTaskType, payload })
      .then(this.reset);
  }

  geolocate = (center) => {
    const [lng, lat] = center;
    const placeRegex = /place./;

    fetch(`${MAPBOX_GEOCODER_URL}/mapbox.places/${lng},${lat}.json?types=place&access_token=${MAPBOX_ACCESS_TOKEN}`)
      .then(data => data.json())
      .then(json => (json.features.length && json.features.find(f => placeRegex.test(f.id)).place_name) || '')
      .then(geolocation => this.setState({ geolocation }));
  }

  addSource(id) {
    const { map } = this.state;
    map.addSource(id, {
      type: 'geojson',
      data: featureCollection([]),
    });
    map.addSource(`${id}-bbox`, {
      type: 'geojson',
      data: featureCollection([]),
    });
  }

  updateSource(id, feature) {
    const { map } = this.state;
    const flattenedFeatures = this.flattenRelations(feature);
    const geojson = featureCollection(flattenedFeatures);
    const bbox = this.getBoundingBox(geojson);
    map.getSource(id).setData(geojson);
    map.getSource(`${id}-bbox`).setData(bbox);
  }

  removeSource(id) {
    const { map } = this.state;
    map.removeSource(id);
    map.removeSource(`${id}-bbox`);
  }

  flattenRelations(feature) {
    const relations = feature.properties.relations || [];
    return [feature].concat(relations);
  }

  getBoundingBox(geojson) {
    const [ minX, minY, maxX, maxY ] = turfBbox(geojson);
    const padX = Math.max((maxX - minX) / 5, 0.0001);
    const padY = Math.max((maxY - minY) / 5, 0.0001);
    const bboxWithPadding = [
      minX - padX,
      minY - padY,
      maxX + padX,
      maxY + padY,
    ];
    const bboxPolygon = turfBboxPolygon(bboxWithPadding);
    return featureCollection([bboxPolygon]);
  }

  addLayers(id) {
    const { map } = this.state;

    map.addLayer({
      id: `${id}-bbox-bg`,
      type: 'line',
      source: `${id}-bbox`,
      paint: {
        'line-width': 6,
        'line-color': 'HSL(247, 100%, 100%)',
        'line-opacity': 0.5,
      },
    });

    map.addLayer({
      id: `${id}-bbox`,
      type: 'line',
      source: `${id}-bbox`,
      paint: {
        'line-width': 2,
        'line-color': 'HSL(247, 60%, 50%)',
        'line-opacity': 0.75,
      },
    });

    map.addLayer({
      id: `${id}-circle`,
      type: 'circle',
      source: id,
      paint: {
        'circle-radius': {
          'stops': [
            [12,4],
            [16,8]
          ]
        },
        'circle-opacity': {
          'stops': [
            [12,0.5],
            [16,0.75]
          ]
        },
        'circle-color': '#dc322f',
      },
    });

    map.addLayer({
      id: `${id}-line`,
      type: 'line',
      source: id,
      paint: {
        'line-width': {
          'stops': [
            [12,2],
            [16,5]
          ]
        },
        'line-opacity': 0.75,
        'line-color': '#dc322f',
      },
    });

    map.addLayer({
      id: `${id}-fill`,
      type: 'fill',
      source: id,
      paint: {
        'fill-opacity': 0,
        'fill-outline-color': '#dc322f',
      },
    });
  }

  removeLayers(id) {
    const { map } = this.state;
    map.removeLayer(`${id}-circle`);
    map.removeLayer(`${id}-line`);
    map.removeLayer(`${id}-fill`);
    map.removeLayer(`${id}-bbox`);
  }

  fitBounds(bounds) {
    const { map } = this.state;
    map.fitBounds(bounds, { linear: true, padding: 200 });
  }

  resize() {
    const { map } = this.state;
    // Needs a slight delay because of the sidebar animation
    window.setTimeout(() => map.resize(), 120);
  }

  componentDidMount() {
    const map = new mapboxgl.Map({
      container: this.mapContainer,
      style: 'mapbox://styles/mapbox/streets-v9',
      zoom: 18,
      center: [-74.50, 40],
    });

    map.addControl(new mapboxgl.NavigationControl());
    map.addControl(taskControl, 'top-left');

    map.once('load', () => {
      this.setState({ map })
      taskControl.update(this.props.currentTask);
    });
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      nextState.map !== this.state.map ||
      nextState.geolocation !== this.state.geolocation ||
      nextProps.currentTaskId !== this.props.currentTaskId ||
      nextProps.currentItemId !== this.props.currentItemId ||
      nextProps.sidebar !== this.props.sidebar
    );
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.map !== this.state.map) {
      const { currentTaskId } = this.props;
      this.addSource(currentTaskId);
      this.addLayers(currentTaskId);
      this.fetchNextItem();
      return;
    }

    if (this.state.map && prevProps.currentTaskId !== this.props.currentTaskId) {
      this.removeSource(prevProps.currentTaskId);
      this.removeLayers(prevProps.currentTaskId);
      this.addSource(this.props.currentTaskId);
      this.addLayers(this.props.currentTaskId);
      this.fetchNextItem();
      taskControl.update(this.props.currentTask);
      return;
    }

    if (this.state.map && prevProps.currentItemId !== this.props.currentItemId) {
      const { currentTaskId, currentItem } = this.props;
      this.updateSource(currentTaskId, currentItem);

      const center = turfCentroid(currentItem).geometry.coordinates;
      this.geolocate(center);

      const bboxPolygon = this.state.map.getSource(`${currentTaskId}-bbox`)._data.features[0];
      const bboxCoordiantes = bboxPolygon.geometry.coordinates[0];
      this.fitBounds([bboxCoordiantes[0], bboxCoordiantes[2]]);
      return;
    }

    if (this.state.map && prevProps.sidebar !== this.props.sidebar) {
      this.resize();
    }
  }

  componentWillUnmount() {
    const { map } = this.state;
    if (map) map.remove();
  }

  render() {
    const { geolocation, iDEdit, iDEditPath } = this.state;
    const { currentItemId } = this.props;

    const editBar = (
      <EditBar
        onTaskEdit={this.editTask}
        onUpdate={this.fetchNextItem}
        geolocation={geolocation} />
    );

    return (

 this.mapContainer = node} className='mode active map fill-navy-dark contain'>
        { currentItemId && editBar }

    );
  }
}

Task.propTypes = {
  currentTask: PropTypes.object.isRequired,
  currentTaskId: PropTypes.string.isRequired,
  user: PropTypes.string,
  editor: PropTypes.string.isRequired,
  sidebar: PropTypes.bool.isRequired,
  currentItem: PropTypes.object,
  currentItemId: PropTypes.string,
  fetchRandomItem: PropTypes.func.isRequired,
  openErrorModal: PropTypes.func.isRequired,
};

Task = connect(
  mapStateToProps,
  mapDispatchToProps
)(Task);

export default Task;
<commit_msg>preset changeset comment<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { featureCollection } from '@turf/helpers';
import turfCentroid from '@turf/centroid';
import turfBbox from '@turf/bbox';
import turfBboxPolygon from '@turf/bbox-polygon';

import mapboxgl from 'mapbox-gl/dist/mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

import EditBar from './edit_bar';

import { MAPBOX_ACCESS_TOKEN, MAPBOX_GEOCODER_URL, JOSM_RC_URL, ID_URL } from '../../config';
import ItemsActionCreators from '../../stores/items_action_creators';
import ModalsActionCreators from '../../stores/modals_action_creators';
import ItemsSelectors from '../../stores/items_selectors';
import UserSelectors from '../../stores/user_selectors';
import SettingsSelectors from '../../stores/settings_selectors';
import TasksSelectors from '../../stores/tasks_selectors';

import TaskControl from './controls/task';
const taskControl = new TaskControl();

const mapStateToProps = (state) => ({
  currentTask: TasksSelectors.getCurrentTask(state),
  currentTaskId: TasksSelectors.getCurrentTaskId(state),
  currentTaskType: TasksSelectors.getCurrentTaskType(state),
  user: UserSelectors.getUsername(state),
  editor: SettingsSelectors.getEditorSetting(state),
  sidebar: SettingsSelectors.getSidebarSetting(state),
  currentItem: ItemsSelectors.getCurrentItem(state),
  currentItemId: ItemsSelectors.getCurrentItemId(state),
});

const mapDispatchToProps = {
  fetchRandomItem: ItemsActionCreators.fetchRandomItem,
  openErrorModal: ModalsActionCreators.openErrorModal,
};

mapboxgl.accessToken = MAPBOX_ACCESS_TOKEN;

class Task extends Component {
  state = {
    map: null,
    geolocation: '',
  }

  editTask = () => {
    const { map } = this.state;
    const { editor } = this.props;

    if (editor === 'josm') {
      const { currentItem } = this.props;
      const { _osmType, _osmId } = currentItem.properties;

      if (_osmType && _osmId) {
        const objects = `${_osmType.substr(0, 1)}${_osmId}`;

        const query = {
          new_layer: true,
          objects,
          relation_members: true,
        };
        const params = Object.keys(query).map(key => `${key}=${query[key]}`).join('&');

        fetch(`${JOSM_RC_URL}/load_object?${params}`)
          .catch(() => this.props.openErrorModal('Could not connect to JOSM remote control.'));
      } else {
        const bounds = map.getBounds();

        const bottom = bounds.getSouthWest().lat - 0.0005;
        const left = bounds.getSouthWest().lng - 0.0005;
        const top = bounds.getNorthEast().lat - 0.0005;
        const right = bounds.getNorthEast().lng - 0.0005;

        const query = { left, right, top, bottom };
        const params = Object.keys(query).map(key => `${key}=${query[key]}`).join('&');

        fetch(`${JOSM_RC_URL}/load_and_zoom?${params}`)
          .catch(() => this.props.openErrorModal('Could not connect to JOSM remote control.'));
      }
    }

    if (editor === 'id') {
      const {lng, lat} = map.getCenter();
      const zoom = map.getZoom();
      const { currentTask } = this.props;
      const { changesetComment } = currentTask.value;

      const iDEditPath = `${ID_URL}/#comment=${encodeURI(changesetComment)}&map=${zoom}/${lat}/${lng}`;

      window.open(iDEditPath, '_blank');
    }
  }

  reset = () => {
    this.setState({
      geolocation: '',
    });
  }

  fetchNextItem = () => {
    const { user, editor, currentTaskId, currentTaskType, fetchRandomItem } = this.props;
    const payload = {
      user: user || '',
      editor,
    };

    fetchRandomItem({ taskId: currentTaskId, taskType: currentTaskType, payload })
      .then(this.reset);
  }

  geolocate = (center) => {
    const [lng, lat] = center;
    const placeRegex = /place./;

    fetch(`${MAPBOX_GEOCODER_URL}/mapbox.places/${lng},${lat}.json?types=place&access_token=${MAPBOX_ACCESS_TOKEN}`)
      .then(data => data.json())
      .then(json => (json.features.length && json.features.find(f => placeRegex.test(f.id)).place_name) || '')
      .then(geolocation => this.setState({ geolocation }));
  }

  addSource(id) {
    const { map } = this.state;
    map.addSource(id, {
      type: 'geojson',
      data: featureCollection([]),
    });
    map.addSource(`${id}-bbox`, {
      type: 'geojson',
      data: featureCollection([]),
    });
  }

  updateSource(id, feature) {
    const { map } = this.state;
    const flattenedFeatures = this.flattenRelations(feature);
    const geojson = featureCollection(flattenedFeatures);
    const bbox = this.getBoundingBox(geojson);
    map.getSource(id).setData(geojson);
    map.getSource(`${id}-bbox`).setData(bbox);
  }

  removeSource(id) {
    const { map } = this.state;
    map.removeSource(id);
    map.removeSource(`${id}-bbox`);
  }

  flattenRelations(feature) {
    const relations = feature.properties.relations || [];
    return [feature].concat(relations);
  }

  getBoundingBox(geojson) {
    const [ minX, minY, maxX, maxY ] = turfBbox(geojson);
    const padX = Math.max((maxX - minX) / 5, 0.0001);
    const padY = Math.max((maxY - minY) / 5, 0.0001);
    const bboxWithPadding = [
      minX - padX,
      minY - padY,
      maxX + padX,
      maxY + padY,
    ];
    const bboxPolygon = turfBboxPolygon(bboxWithPadding);
    return featureCollection([bboxPolygon]);
  }

  addLayers(id) {
    const { map } = this.state;

    map.addLayer({
      id: `${id}-bbox-bg`,
      type: 'line',
      source: `${id}-bbox`,
      paint: {
        'line-width': 6,
        'line-color': 'HSL(247, 100%, 100%)',
        'line-opacity': 0.5,
      },
    });

    map.addLayer({
      id: `${id}-bbox`,
      type: 'line',
      source: `${id}-bbox`,
      paint: {
        'line-width': 2,
        'line-color': 'HSL(247, 60%, 50%)',
        'line-opacity': 0.75,
      },
    });

    map.addLayer({
      id: `${id}-circle`,
      type: 'circle',
      source: id,
      paint: {
        'circle-radius': {
          'stops': [
            [12,4],
            [16,8]
          ]
        },
        'circle-opacity': {
          'stops': [
            [12,0.5],
            [16,0.75]
          ]
        },
        'circle-color': '#dc322f',
      },
    });

    map.addLayer({
      id: `${id}-line`,
      type: 'line',
      source: id,
      paint: {
        'line-width': {
          'stops': [
            [12,2],
            [16,5]
          ]
        },
        'line-opacity': 0.75,
        'line-color': '#dc322f',
      },
    });

    map.addLayer({
      id: `${id}-fill`,
      type: 'fill',
      source: id,
      paint: {
        'fill-opacity': 0,
        'fill-outline-color': '#dc322f',
      },
    });
  }

  removeLayers(id) {
    const { map } = this.state;
    map.removeLayer(`${id}-circle`);
    map.removeLayer(`${id}-line`);
    map.removeLayer(`${id}-fill`);
    map.removeLayer(`${id}-bbox`);
  }

  fitBounds(bounds) {
    const { map } = this.state;
    map.fitBounds(bounds, { linear: true, padding: 200 });
  }

  resize() {
    const { map } = this.state;
    // Needs a slight delay because of the sidebar animation
    window.setTimeout(() => map.resize(), 120);
  }

  componentDidMount() {
    const map = new mapboxgl.Map({
      container: this.mapContainer,
      style: 'mapbox://styles/mapbox/streets-v9',
      zoom: 18,
      center: [-74.50, 40],
    });

    map.addControl(new mapboxgl.NavigationControl());
    map.addControl(taskControl, 'top-left');

    map.once('load', () => {
      this.setState({ map })
      taskControl.update(this.props.currentTask);
    });
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      nextState.map !== this.state.map ||
      nextState.geolocation !== this.state.geolocation ||
      nextProps.currentTaskId !== this.props.currentTaskId ||
      nextProps.currentItemId !== this.props.currentItemId ||
      nextProps.sidebar !== this.props.sidebar
    );
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.map !== this.state.map) {
      const { currentTaskId } = this.props;
      this.addSource(currentTaskId);
      this.addLayers(currentTaskId);
      this.fetchNextItem();
      return;
    }

    if (this.state.map && prevProps.currentTaskId !== this.props.currentTaskId) {
      this.removeSource(prevProps.currentTaskId);
      this.removeLayers(prevProps.currentTaskId);
      this.addSource(this.props.currentTaskId);
      this.addLayers(this.props.currentTaskId);
      this.fetchNextItem();
      taskControl.update(this.props.currentTask);
      return;
    }

    if (this.state.map && prevProps.currentItemId !== this.props.currentItemId) {
      const { currentTaskId, currentItem } = this.props;
      this.updateSource(currentTaskId, currentItem);

      const center = turfCentroid(currentItem).geometry.coordinates;
      this.geolocate(center);

      const bboxPolygon = this.state.map.getSource(`${currentTaskId}-bbox`)._data.features[0];
      const bboxCoordiantes = bboxPolygon.geometry.coordinates[0];
      this.fitBounds([bboxCoordiantes[0], bboxCoordiantes[2]]);
      return;
    }

    if (this.state.map && prevProps.sidebar !== this.props.sidebar) {
      this.resize();
    }
  }

  componentWillUnmount() {
    const { map } = this.state;
    if (map) map.remove();
  }

  render() {
    const { geolocation, iDEdit, iDEditPath } = this.state;
    const { currentItemId } = this.props;

    const editBar = (
      <EditBar
        onTaskEdit={this.editTask}
        onUpdate={this.fetchNextItem}
        geolocation={geolocation} />
    );

    return (

 this.mapContainer = node} className='mode active map fill-navy-dark contain'>
        { currentItemId && editBar }

    );
  }
}

Task.propTypes = {
  currentTask: PropTypes.object.isRequired,
  currentTaskId: PropTypes.string.isRequired,
  user: PropTypes.string,
  editor: PropTypes.string.isRequired,
  sidebar: PropTypes.bool.isRequired,
  currentItem: PropTypes.object,
  currentItemId: PropTypes.string,
  fetchRandomItem: PropTypes.func.isRequired,
  openErrorModal: PropTypes.func.isRequired,
};

Task = connect(
  mapStateToProps,
  mapDispatchToProps
)(Task);

export default Task;
<|endoftext|>


<commit_before>'use strict';

//users router

var express = require('express');
var restify = require('express-restify-mongoose');
var router = express.Router();
//var user = require('../domain/user');

var mongoose = require('../utils/mongoConnection');

var Schema = mongoose.Schema;

var User = new Schema({
    //user schema
    //id: { type: String, required: true },
    username: { type: String, required: true },
    password: { type: String, required: true },
    email: { type: String, required: true }
});

var UserModel = mongoose.model('User', User);

restify.serve(router, UserModel);

module.exports = router;

<commit_msg>update user schema: include plans and activities<commit_after>'use strict';

//users router

var express = require('express');
var restify = require('express-restify-mongoose');
var router = express.Router();
//var user = require('../domain/user');

var mongoose = require('../utils/mongoConnection');

var Schema = mongoose.Schema;

var User = new Schema({
    //user schema
    //id: { type: String, required: true },
    username: { type: String, required: true },
    password: { type: String, required: true },
    email: { type: String, required: true },
    plans:[{
        destAddr: String,
        destLat: Number,
        destLng: Number,
        startDate: Date,
        endDate: Date,
        active: {type: Boolean, default: true },
        activities:[{
            venue: String,
            startTime: String, //store time as string????
            duration: Number,
            category: String
        }]
    }]
});

var UserModel = mongoose.model('User', User);

restify.serve(router, UserModel);

module.exports = router;

<|endoftext|>


<commit_before>(function(context, safeEval){
	if (context.requireOnce && context.rquire_once && context.requireOnce === context.rquire_once){
		return
	}
	var registry = {}

	var seekOrGet = function(url, callback){
		var requestUrl = url,
			registryEntry = registry[url],
			attemptConnection = function(queue){
				var connection = queue.request = new XMLHttpRequest(),
					recur = function(){
						attemptConnection(queue)
					}

				connection.onreadystatechange = function(){
					if (connection.readyState == XMLHttpRequest.DONE){
						if ((connection.status >= 200 && connection.status < 300) || connection.status == 304) {
							// success
							queue.result = 'success'
							for (var i = 0; i < queue.waiters.length; i++){
								if (i == 0){
									queue.waiters[i](queue)
								}
								else {
									seekOrGet(url, queue.waiters[i])
								}
							}
						}

						else if (connection.status >= 300 && connection.status < 400) {
							requestUrl = connection.getResponseHeader("Location") || url
							if (requestUrl != url){
								recur()
							}
							else {
								queue.attempts++
								setTimeout(recur, queue.attempts*100)
							}
						}

						else if (queue.attempts < 5){
							// retry this process with timeout
							queue.attempts++
							setTimeout(recur, queue.attempts*100)
						}

						else {
							queue.result = 'failed'
							// asset failed to load.
							for (var i = 0; i < queue.waiters.length; i++){
								queue.waiters[i](queue)
							}
						}
					}
				}
				connection.open("GET", requestUrl, true)
				connection.send()
			}

		// already loaded and is in cache
		if (registryEntry && typeof registryEntry.result !== 'undefined'){
			//console.log("insta callback", url)
			callback(registryEntry)
		}

		// is currently in the process of fetching
		else if (registryEntry && typeof registryEntry.result === 'undefined'){
			//console.log("added to waiters", url)
			registryEntry.waiters.push(callback)
		}

		// is a completely new URL not known yet
		else {
		//	console.log("new request", url)
			attemptConnection(
				registry[url] = {
					waiters: [callback],
					attempts: 1
				}
			)
		}
	}

	if (typeof document!= "undefined" && typeof XMLHttpRequest != "undefined"){ // dont do this if in node
		function waitForDocReady (callback) {
			if (document.readyState == "complete"){
				callback()
			}
			else {
				document.addEventListener("readystatechange", function(){
					if (document.readyState == "complete"){
						callback()
					}
				})
			}
		}

		var xhrs = []
		var xhrReadyCallbacks = []
		XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send
		XMLHttpRequest.prototype.send = function(potentialData){
			var xhr = this
			var requestIndex = xhrs.push(xhr) - 1
			xhr.addEventListener("loadend", function(){
				// if something is waiting for xhr requests to finish call the first thing so it can start it's resolution cycle but only when the document is ready
                waitForDocReady(function(){
                    if (xhrReadyCallbacks.length){
                        xhrReadyCallbacks[xhrReadyCallbacks.length - 1]()
                    }
                })
			})
			if (typeof potentialData != "undefined"){
				xhr._send(potentialData)
			}
			else {
				xhr._send()
			}
		}
	}

	context.requireOnce = context.require_once = function(dependencies, callback, failed){
		if (!callback){
			throw new Error("Success callback not defined")
		}
		failed = failed || function(){}

		var obtainedDependencies = [],
			numberReturned = 0,
			finalResolution = function(){
				// resolve "returnVal" for all dependencies
				obtainedDependencies.forEach(function(opperator, index){
					if (opperator && opperator.evaluater){
						opperator.returnVal = opperator.returnVal || (opperator.evaluater.module.export != opperator.evaluater.module.exports)
							? opperator.evaluater.module.exports
							: (typeof opperator.evaluater.output == "undefined")? true : opperator.evaluater.output
					}
				})

				// call success or fail appropriately
				var successFlag = true;
				var applyArray = obtainedDependencies.map(function(dependency){
					if (!dependency){
						return successFlag = false
					}
					else {
						return dependency.returnVal
					}
				})

				if (successFlag){
					callback.apply(context, applyArray)
				}
				else {
					failed.apply(context, applyArray)
				}

				//remove the last item in callback (self)
				xhrReadyCallbacks.splice(xhrReadyCallbacks.length - 1, 1)

				// call the next item in the chain
				if (xhrReadyCallbacks.length){
					xhrReadyCallbacks[xhrReadyCallbacks.length - 1]()
				}
			},
			dependencyLoadStateCheck = function(){
                // this function will only be called when the doc is ready.
				if (numberReturned == dependencies.length){ // all dependencies have returned
                    var noXhrsLoading = xhrs.reduce(function(truthness, xhr){
                                           //xhr item is an XMLHttpRequest object  || xhr item is a script tag
                        return truthness && (xhr.readyState == XMLHttpRequest.DONE || xhr.readyState == "complete")
                    }, true)

    				noXhrsLoading && finalResolution()
				}
			},
            resolutionOrderSet = false,
            potentialScriptEvaluation = function(opperator){
                // push the current execution callback to the stack once first
                if (!resolutionOrderSet){
                    resolutionOrderSet = true
                    xhrReadyCallbacks.push(dependencyLoadStateCheck)
                }

                // evaluate the script maybe
                if (
                    opperator && // xhr did not fail
                    opperator.request.getResponseHeader("Content-Type").match(/javascript/i) && // is a javascript file
                    typeof opperator.evaluater == "undefined" // has not been evaluated already
                ){
                    //console.log("evaluating", opperator.request.responseURL)
                    opperator.evaluater = safeEval(opperator.request.responseText)
                }
                else if (
                    opperator && // xhr did not fail
                    typeof opperator.returnVal != "undefined" && // has not been evaluated already
                    !opperator.request.getResponseHeader("Content-Type").match(/javascript/i)  // file is not javascript
                ){
                    opperator.returnVal = opperator.request.responseText
                }

                // call the next step in the chain if no doc is ready
                // in the case that the doc isn't ready, the xhr onload callback will call it instead (above)
                if (document.readyState == "complete"){
                    dependencyLoadStateCheck()
                }

            }

		// actual loging for getting the dependencies and calling them
		dependencies.forEach(function(mixedDependency, index){
			var dependency
			if (typeof require != 'undefined' && typeof XMLHttpRequest == 'undefined'){ // inside node
				dependency = mixedDependency.server
				if (dependency){
					obtainedDependencies[index] = require(dependency)
				}
				else {
					obtainedDependencies[index] = false
				}

				numberReturned++
				if (numberReturned == dependencies.length){ // all dependencies have returned
					callback.apply(context, obtainedDependencies)
				}
			}
			else if (XMLHttpRequest){ // inside browser
				dependency = mixedDependency.browser || mixedDependency; // mixedDependency can be object or a URL string

				seekOrGet(dependency, function(opperator){
					console.log(opperator)
					if (opperator.result == "success"){
						obtainedDependencies[index] = opperator //{xhr: xhrObject, returnVal: cachedReturnVal}
					}
					else if (opperator.result = "failed"){
						obtainedDependencies[index] = false
					}
					numberReturned++
					//ifAllDependenciesLoaded()
                    potentialScriptEvaluation(opperator)
				})
			}
		})
	}

	if (typeof module != 'undefined'){
		module.exports = context.requireOnce
	}
})(
	this,
	function(code){
		var module = {}
		module.export = module.exports = function(o){
			module.exports = o
		}

		return {
			module: module,
			output: eval(code)
		}
	}
)
<commit_msg>tab consistancy lol<commit_after>(function(context, safeEval){
	if (context.requireOnce && context.rquire_once && context.requireOnce === context.rquire_once){
		return
	}
	var registry = {}

	var seekOrGet = function(url, callback){
		var requestUrl = url,
			registryEntry = registry[url],
			attemptConnection = function(queue){
				var connection = queue.request = new XMLHttpRequest(),
					recur = function(){
						attemptConnection(queue)
					}

				connection.onreadystatechange = function(){
					if (connection.readyState == XMLHttpRequest.DONE){
						if ((connection.status >= 200 && connection.status < 300) || connection.status == 304) {
							// success
							queue.result = 'success'
							for (var i = 0; i < queue.waiters.length; i++){
								if (i == 0){
									queue.waiters[i](queue)
								}
								else {
									seekOrGet(url, queue.waiters[i])
								}
							}
						}

						else if (connection.status >= 300 && connection.status < 400) {
							requestUrl = connection.getResponseHeader("Location") || url
							if (requestUrl != url){
								recur()
							}
							else {
								queue.attempts++
								setTimeout(recur, queue.attempts*100)
							}
						}

						else if (queue.attempts < 5){
							// retry this process with timeout
							queue.attempts++
							setTimeout(recur, queue.attempts*100)
						}

						else {
							queue.result = 'failed'
							// asset failed to load.
							for (var i = 0; i < queue.waiters.length; i++){
								queue.waiters[i](queue)
							}
						}
					}
				}
				connection.open("GET", requestUrl, true)
				connection.send()
			}

		// already loaded and is in cache
		if (registryEntry && typeof registryEntry.result !== 'undefined'){
			//console.log("insta callback", url)
			callback(registryEntry)
		}

		// is currently in the process of fetching
		else if (registryEntry && typeof registryEntry.result === 'undefined'){
			//console.log("added to waiters", url)
			registryEntry.waiters.push(callback)
		}

		// is a completely new URL not known yet
		else {
		//	console.log("new request", url)
			attemptConnection(
				registry[url] = {
					waiters: [callback],
					attempts: 1
				}
			)
		}
	}

	if (typeof document!= "undefined" && typeof XMLHttpRequest != "undefined"){ // dont do this if in node
		function waitForDocReady (callback) {
			if (document.readyState == "complete"){
				callback()
			}
			else {
				document.addEventListener("readystatechange", function(){
					if (document.readyState == "complete"){
						callback()
					}
				})
			}
		}

		var xhrs = []
		var xhrReadyCallbacks = []
		XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send
		XMLHttpRequest.prototype.send = function(potentialData){
			var xhr = this
			var requestIndex = xhrs.push(xhr) - 1
			xhr.addEventListener("loadend", function(){
				// if something is waiting for xhr requests to finish call the first thing so it can start it's resolution cycle but only when the document is ready
				waitForDocReady(function(){
					if (xhrReadyCallbacks.length){
						xhrReadyCallbacks[xhrReadyCallbacks.length - 1]()
					}
				})
			})
			if (typeof potentialData != "undefined"){
				xhr._send(potentialData)
			}
			else {
				xhr._send()
			}
		}
	}

	context.requireOnce = context.require_once = function(dependencies, callback, failed){
		if (!callback){
			throw new Error("Success callback not defined")
		}
		failed = failed || function(){}

		var obtainedDependencies = [],
			numberReturned = 0,
			finalResolution = function(){
				// resolve "returnVal" for all dependencies
				obtainedDependencies.forEach(function(opperator, index){
					if (opperator && opperator.evaluater){
						opperator.returnVal = opperator.returnVal || (opperator.evaluater.module.export != opperator.evaluater.module.exports)
							? opperator.evaluater.module.exports
							: (typeof opperator.evaluater.output == "undefined")? true : opperator.evaluater.output
					}
				})

				// call success or fail appropriately
				var successFlag = true;
				var applyArray = obtainedDependencies.map(function(dependency){
					if (!dependency){
						return successFlag = false
					}
					else {
						return dependency.returnVal
					}
				})

				if (successFlag){
					callback.apply(context, applyArray)
				}
				else {
					failed.apply(context, applyArray)
				}

				//remove the last item in callback (self)
				xhrReadyCallbacks.splice(xhrReadyCallbacks.length - 1, 1)

				// call the next item in the chain
				if (xhrReadyCallbacks.length){
					xhrReadyCallbacks[xhrReadyCallbacks.length - 1]()
				}
			},
			dependencyLoadStateCheck = function(){
				// this function will only be called when the doc is ready.
				if (numberReturned == dependencies.length){ // all dependencies have returned
					var noXhrsLoading = xhrs.reduce(function(truthness, xhr){
										   //xhr item is an XMLHttpRequest object  || xhr item is a script tag
						return truthness && (xhr.readyState == XMLHttpRequest.DONE || xhr.readyState == "complete")
					}, true)

					noXhrsLoading && finalResolution()
				}
			},
			resolutionOrderSet = false,
			potentialScriptEvaluation = function(opperator){
				// push the current execution callback to the stack once first
				if (!resolutionOrderSet){
					resolutionOrderSet = true
					xhrReadyCallbacks.push(dependencyLoadStateCheck)
				}

				// evaluate the script maybe
				if (
					opperator && // xhr did not fail
					opperator.request.getResponseHeader("Content-Type").match(/javascript/i) && // is a javascript file
					typeof opperator.evaluater == "undefined" // has not been evaluated already
				){
					//console.log("evaluating", opperator.request.responseURL)
					opperator.evaluater = safeEval(opperator.request.responseText)
				}
				else if (
					opperator && // xhr did not fail
					typeof opperator.returnVal != "undefined" && // has not been evaluated already
					!opperator.request.getResponseHeader("Content-Type").match(/javascript/i)  // file is not javascript
				){
					opperator.returnVal = opperator.request.responseText
				}

				// call the next step in the chain if no doc is ready
				// in the case that the doc isn't ready, the xhr onload callback will call it instead (above)
				if (document.readyState == "complete"){
					dependencyLoadStateCheck()
				}

			}

		// actual loging for getting the dependencies and calling them
		dependencies.forEach(function(mixedDependency, index){
			var dependency
			if (typeof require != 'undefined' && typeof XMLHttpRequest == 'undefined'){ // inside node
				dependency = mixedDependency.server
				if (dependency){
					obtainedDependencies[index] = require(dependency)
				}
				else {
					obtainedDependencies[index] = false
				}

				numberReturned++
				if (numberReturned == dependencies.length){ // all dependencies have returned
					callback.apply(context, obtainedDependencies)
				}
			}
			else if (XMLHttpRequest){ // inside browser
				dependency = mixedDependency.browser || mixedDependency; // mixedDependency can be object or a URL string

				seekOrGet(dependency, function(opperator){
					console.log(opperator)
					if (opperator.result == "success"){
						obtainedDependencies[index] = opperator //{xhr: xhrObject, returnVal: cachedReturnVal}
					}
					else if (opperator.result = "failed"){
						obtainedDependencies[index] = false
					}
					numberReturned++
					//ifAllDependenciesLoaded()
					potentialScriptEvaluation(opperator)
				})
			}
		})
	}

	if (typeof module != 'undefined'){
		module.exports = context.requireOnce
	}
})(
	this,
	function(code){
		var module = {}
		module.export = module.exports = function(o){
			module.exports = o
		}

		return {
			module: module,
			output: eval(code)
		}
	}
)
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var rr = require('recursive-readdir');
var yaml = require('js-yaml');
var widdershins = require('./index.js');

var argv = require('yargs')
	.usage('testRunner [options] [{path-to-specs}]')
	.boolean('noschema')
	.alias('n','noschema')
	.describe('noschema','Set widdershins --noschema option')
	.boolean('raw')
	.alias('r','raw')
	.describe('raw','Set widdershins --raw option')
	.count('verbose')
	.alias('v','verbose')
	.describe('verbose','Increase verbosity')
	.help('h')
    .alias('h', 'help')
	.strict()
	.version(function() {
		return require('../package.json').version;
	})
	.argv;

var red = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[31m';
var green = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[32m';
var normal = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[0m';

var pass = 0;
var fail = 0;
var failures = [];

var pathspec = argv._.length>0 ? argv._[0] : '../openapi-directory/APIs/';

var options = argv;
var widdershinsOptions = {};
if (options.raw) widdershinsOptions.sample = false;
if (options.noschema) widdershinsOptions.schema = false;

function handleResult(file, result) {
	if (result) {
		pass++;
	}
	else {
		fail++;
		failures.push(file);
	}
}

function check(file) {
	var result = false;
	var components = file.split(path.sep);
	var filename = components[components.length-1];

	if ((filename.endsWith('yaml')) || (filename.endsWith('json'))) {
		console.log(normal+file);

		var srcStr = fs.readFileSync(path.resolve(file),'utf8');
		var src;
		try {
			if (components[components.length-1].endsWith('.yaml')) {
				src = yaml.safeLoad(srcStr);
			}
			else {
				src = JSON.parse(srcStr);
			}
		}
		catch (ex) {
			console.log('Could not parse file');
			return true;
		}

		if (!src.swagger && !src.openapi && !src.asyncapi) {
			console.log('Not a known API definition');
			return true;
		}

		widdershinsOptions.source = file;
		try {
	        widdershins.convert(src, widdershinsOptions, function(err, result){
				result = result.split('is undefined').join('x');
				result = result.split('undefined to').join('x');
				result = result.split('undefined in').join('x');
				result = result.split('undefined how').join('x');
				result = result.split('undefined behavio').join('x');
				result = result.split('"undefined":').join('x');
				result = result.split('undefined|').join('x'); // not so happy about this one (google firebaserules)
				result = result.split('undefinedfault').join('x');
				if ((result != '') && (result.indexOf('undefined')<0)) {
			    	console.log(green+'  %s %s',src.info.title,src.info.version);
			    	console.log('  %s',src.host||(src.servers && src.servers.length ? src.servers[0].url : null)||'localhost');
					result = true;
				}
				else {
					result = false;
				}
				handleResult(file, result);
			});
		}
		catch (ex) {
			console.log(red+ex.message);
			result = false;
			handleResult(file, result);
		}
	}
	else {
		result = true;
	}
}

process.exitCode = 1;
pathspec = path.resolve(pathspec);
rr(pathspec, function (err, files) {
	for (var i in files) {
		check(files[i]);
	}
});

process.on('exit', function(code) {
	if (failures.length>0) {
		failures.sort();
		console.log(red);
		for (var f in failures) {
			console.log(failures[f]);
		}
	}
	console.log(normal);
	console.log('Tests: %s passing, %s failing', pass, fail);
	process.exitCode = ((fail === 0) && (pass > 0)) ? 0 : 1;
});
<commit_msg>Hardening x2<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var rr = require('recursive-readdir');
var yaml = require('js-yaml');
var widdershins = require('./index.js');

var argv = require('yargs')
	.usage('testRunner [options] [{path-to-specs}]')
	.boolean('noschema')
	.alias('n','noschema')
	.describe('noschema','Set widdershins --noschema option')
	.boolean('raw')
	.alias('r','raw')
	.describe('raw','Set widdershins --raw option')
	.count('verbose')
	.alias('v','verbose')
	.describe('verbose','Increase verbosity')
	.help('h')
    .alias('h', 'help')
	.strict()
	.version(function() {
		return require('../package.json').version;
	})
	.argv;

var red = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[31m';
var green = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[32m';
var normal = process.env.NODE_DISABLE_COLORS ? '' : '\x1b[0m';

var pass = 0;
var fail = 0;
var failures = [];

var pathspec = argv._.length>0 ? argv._[0] : '../openapi-directory/APIs/';

var options = argv;
var widdershinsOptions = {};
if (options.raw) widdershinsOptions.sample = false;
if (options.noschema) widdershinsOptions.schema = false;

function handleResult(file, result) {
	if (result) {
		pass++;
	}
	else {
		fail++;
		failures.push(file);
	}
}

function check(file) {
	var result = false;
	var components = file.split(path.sep);
	var filename = components[components.length-1];

	if ((filename.endsWith('yaml')) || (filename.endsWith('json'))) {
		console.log(normal+file);

		var srcStr = fs.readFileSync(path.resolve(file),'utf8');
		var src;
		try {
			if (components[components.length-1].endsWith('.yaml')) {
				src = yaml.safeLoad(srcStr);
			}
			else {
				src = JSON.parse(srcStr);
			}
		}
		catch (ex) {
			console.log('Could not parse file');
			return true;
		}

		if (!src.swagger && !src.openapi && !src.asyncapi) {
			console.log('Not a known API definition');
			return true;
		}

		widdershinsOptions.source = file;
		try {
	        widdershins.convert(src, widdershinsOptions, function(err, result){
				result = result.split('is undefined').join('x');
				result = result.split('undefined to').join('x');
				result = result.split('undefined in').join('x');
				result = result.split('undefined how').join('x');
				result = result.split('undefined behavio').join('x');
				result = result.split('"undefined":').join('x');
				result = result.split('» undefined').join('x');
				result = result.split('undefined|').join('x'); // not so happy about this one (google firebaserules)
				result = result.split('undefinedfault').join('x');
				if ((result != '') && (result.indexOf('undefined')<0)) {
			    	console.log(green+'  %s %s',src.info.title,src.info.version);
			    	console.log('  %s',src.host||(src.servers && src.servers.length ? src.servers[0].url : null)||'localhost');
					result = true;
				}
				else {
					result = false;
				}
				handleResult(file, result);
			});
		}
		catch (ex) {
			console.log(red+ex.message);
			result = false;
			handleResult(file, result);
		}
	}
	else {
		result = true;
	}
}

process.exitCode = 1;
pathspec = path.resolve(pathspec);
rr(pathspec, function (err, files) {
	for (var i in files) {
		check(files[i]);
	}
});

process.on('exit', function(code) {
	if (failures.length>0) {
		failures.sort();
		console.log(red);
		for (var f in failures) {
			console.log(failures[f]);
		}
	}
	console.log(normal);
	console.log('Tests: %s passing, %s failing', pass, fail);
	process.exitCode = ((fail === 0) && (pass > 0)) ? 0 : 1;
});
<|endoftext|>


<commit_before>import React from 'react'
import classNames from 'classnames'
import { getWindowSize, getAttributeForCurrentSize } from '../../utils/sizeUtils'
import styles from './styles.less'

export default class View extends React.Component {
   static propTypes = {
      aspectRatio: React.PropTypes.string,
      children: React.PropTypes.node,
      className: React.PropTypes.string,
      format: React.PropTypes.string,
      height: React.PropTypes.string,
      onScroll: React.PropTypes.func,
      padding: React.PropTypes.string,
      position: React.PropTypes.string,
      scroll: React.PropTypes.string,
      style: React.PropTypes.object,
      width: React.PropTypes.string,
      visible: React.PropTypes.string
   }

   static defaultProps = {
      format: 'float',
      padding: '0',
      style: {},
      visible: 'on'
   }

   constructor(props, context) {
      super(props, context)

      this.state = {
         width: 'auto',
         height: 'auto',
         position: {},
         size: getWindowSize()
      }

      this.windowSizeUpdated = this.windowSizeUpdated.bind(this)
   }

   componentDidMount() {
      this.setComponentAspectRatio()
      this.setComponentPosition()

      window.addEventListener('resize', this.windowSizeUpdated, false)
   }

   componentDidUpdate() {
      this.setComponentAspectRatio()
      this.setComponentPosition()
   }

   componentWillUnmount() {
      window.removeEventListener('resize', this.windowSizeUpdated)
   }

   setComponentAspectRatio() {
      let aspectRatio
      let height

      if (this.props.aspectRatio) {
         aspectRatio = getAttributeForCurrentSize(this.state.size, this.props.aspectRatio)
      }

      if (this.props.height) {
         height = getAttributeForCurrentSize(this.state.size, this.props.height)
      }

      // Will only execute aspect ratio if no height exists
      // Height takes precedence in setting View size
      if (aspectRatio && !height) {
         const aspectRatioDimensions = aspectRatio.split(':')
         const aspectRatioWidth = aspectRatioDimensions[0]
         const aspectRatioHeight = aspectRatioDimensions[1]
         const viewWidth = this.node.offsetWidth
         const viewHeight = `${Math.round((viewWidth / aspectRatioWidth) * aspectRatioHeight)}px`

         if (this.state.height !== viewHeight) {
            this.setState({ height: viewHeight })
         }
      }
   }

   setComponentPosition() {
      const position = {}
      if (this.props.position) {
         const currentPosition = getAttributeForCurrentSize(this.state.size, this.props.position)

         if (currentPosition.indexOf('top') >= 0) {
            position.top = 0
            position.bottom = 'auto'
         }

         if (currentPosition.indexOf('middle') >= 0) {
            position.top = '50%'
            if (this.state.height !== 'auto') {
               position.marginTop = `-${this.node.offsetHeight / 2}px`
            }
         }

         if (currentPosition.indexOf('bottom') >= 0) {
            position.bottom = 0
            position.top = 'auto'
         }

         if (currentPosition.indexOf('left') >= 0) {
            position.left = '0'
            position.right = 'auto'
            position.marginLeft = 'auto'
         }

         if (currentPosition.indexOf('center') >= 0) {
            position.left = '50%'
            if (this.state.width !== 'auto') {
               position.marginLeft = `-${this.node.offsetWidth / 2}px`
            }
         }

         if (currentPosition.indexOf('right') >= 0) {
            position.right = '0'
            position.left = 'auto'
         }

         // Not sure if there is a better way to do this equality comparison
         if (JSON.stringify(this.state.position) !== JSON.stringify(position)) {
            this.setState({ position })
         }
      }
   }

   windowSizeUpdated() {
      const windowSize = getWindowSize()
      this.setState({ size: windowSize })
   }

   render() {
      const viewClasses = [styles.view]
      const statelessStyles = {}

      // Stateless View Props
      const padding = getAttributeForCurrentSize(this.state.size, this.props.padding)
      if (padding !== 0) statelessStyles.padding = padding

      // Stateful View Styles
      if (this.props.width) {
         const width = getAttributeForCurrentSize(this.state.size, this.props.width)
         if (width) {
            // const unit = width.indexOf('px') === -1 ? '%' : 'px'
            this.state.width = width
         }
      }

      if (this.props.height) {
         const height = getAttributeForCurrentSize(this.state.size, this.props.height)
         if (height) {
            const unit = height.indexOf('px') === -1 ? '%' : 'px'
            this.state.height = parseFloat(height) + unit
         }
      }

      if (this.props.scroll) {
         const scroll = getAttributeForCurrentSize(this.state.size, this.props.scroll)
         if (scroll && scroll === 'on') {
            viewClasses.push(styles.scroll)
         }
      }

      if (this.props.visible) {
         const visible = getAttributeForCurrentSize(this.state.size, this.props.visible)
         if (visible && visible === 'on') {
            viewClasses.push(styles.visible)
         } else {
            viewClasses.push(styles.hidden)
         }
      }

      if (this.props.format) {
         const format = getAttributeForCurrentSize(this.state.size, this.props.format)
         if (format === 'float') {
            viewClasses.push(styles.floatFormat)
         } else if (format === 'auto') {
            viewClasses.push(styles.autoFormat)
         }
      }

      const style = {
         ...this.props.style,
         ...statelessStyles,
         ...this.state.position,
         width: this.state.width,
         height: this.state.height
      }

      return (
         <div
            ref={node => (this.node = node)}
            style={style}
            onScroll={this.props.onScroll}
            className={classNames(viewClasses, this.props.className)}>
            {this.props.children}
         </div>
      )
   }
}
<commit_msg>Added maxWidth prop to View<commit_after>import React from 'react'
import classNames from 'classnames'
import { getWindowSize, getAttributeForCurrentSize } from '../../utils/sizeUtils'
import styles from './styles.less'

export default class View extends React.Component {
   static propTypes = {
      aspectRatio: React.PropTypes.string,
      children: React.PropTypes.node,
      className: React.PropTypes.string,
      format: React.PropTypes.string,
      height: React.PropTypes.string,
      maxWidth: React.PropTypes.string,
      onScroll: React.PropTypes.func,
      padding: React.PropTypes.string,
      position: React.PropTypes.string,
      scroll: React.PropTypes.string,
      style: React.PropTypes.object,
      width: React.PropTypes.string,
      visible: React.PropTypes.string
   }

   static defaultProps = {
      format: 'float',
      padding: '0',
      style: {},
      visible: 'on'
   }

   constructor(props, context) {
      super(props, context)

      this.state = {
         width: 'auto',
         height: 'auto',
         position: {},
         size: getWindowSize()
      }

      this.windowSizeUpdated = this.windowSizeUpdated.bind(this)
   }

   componentDidMount() {
      this.setComponentAspectRatio()
      this.setComponentPosition()

      window.addEventListener('resize', this.windowSizeUpdated, false)
   }

   componentDidUpdate() {
      this.setComponentAspectRatio()
      this.setComponentPosition()
   }

   componentWillUnmount() {
      window.removeEventListener('resize', this.windowSizeUpdated)
   }

   setComponentAspectRatio() {
      let aspectRatio
      let height

      if (this.props.aspectRatio) {
         aspectRatio = getAttributeForCurrentSize(this.state.size, this.props.aspectRatio)
      }

      if (this.props.height) {
         height = getAttributeForCurrentSize(this.state.size, this.props.height)
      }

      // Will only execute aspect ratio if no height exists
      // Height takes precedence in setting View size
      if (aspectRatio && !height) {
         const aspectRatioDimensions = aspectRatio.split(':')
         const aspectRatioWidth = aspectRatioDimensions[0]
         const aspectRatioHeight = aspectRatioDimensions[1]
         const viewWidth = this.node.offsetWidth
         const viewHeight = `${Math.round((viewWidth / aspectRatioWidth) * aspectRatioHeight)}px`

         if (this.state.height !== viewHeight) {
            this.setState({ height: viewHeight })
         }
      }
   }

   setComponentPosition() {
      const position = {}
      if (this.props.position) {
         const currentPosition = getAttributeForCurrentSize(this.state.size, this.props.position)

         if (currentPosition.indexOf('top') >= 0) {
            position.top = 0
            position.bottom = 'auto'
         }

         if (currentPosition.indexOf('middle') >= 0) {
            position.top = '50%'
            if (this.state.height !== 'auto') {
               position.marginTop = `-${this.node.offsetHeight / 2}px`
            }
         }

         if (currentPosition.indexOf('bottom') >= 0) {
            position.bottom = 0
            position.top = 'auto'
         }

         if (currentPosition.indexOf('left') >= 0) {
            position.left = '0'
            position.right = 'auto'
            position.marginLeft = 'auto'
         }

         if (currentPosition.indexOf('center') >= 0) {
            position.left = '50%'
            if (this.state.width !== 'auto') {
               position.marginLeft = `-${this.node.offsetWidth / 2}px`
            }
         }

         if (currentPosition.indexOf('right') >= 0) {
            position.right = '0'
            position.left = 'auto'
         }

         // Not sure if there is a better way to do this equality comparison
         if (JSON.stringify(this.state.position) !== JSON.stringify(position)) {
            this.setState({ position })
         }
      }
   }

   windowSizeUpdated() {
      const windowSize = getWindowSize()
      this.setState({ size: windowSize })
   }

   render() {
      const viewClasses = [styles.view]
      const statelessStyles = {}

      // Stateless View Props
      const padding = getAttributeForCurrentSize(this.state.size, this.props.padding)
      if (padding !== 0) statelessStyles.padding = padding
      const maxWidth = getAttributeForCurrentSize(this.state.size, this.props.maxWidth)
      if (maxWidth) statelessStyles.maxWidth = maxWidth

      // Stateful View Styles
      if (this.props.width) {
         const width = getAttributeForCurrentSize(this.state.size, this.props.width)
         if (width) this.state.width = parseFloat(width)
      }

      if (this.props.height) {
         const height = getAttributeForCurrentSize(this.state.size, this.props.height)
         if (height) this.state.height = parseFloat(height)
      }

      if (this.props.scroll) {
         const scroll = getAttributeForCurrentSize(this.state.size, this.props.scroll)
         if (scroll && scroll === 'on') {
            viewClasses.push(styles.scroll)
         }
      }

      if (this.props.visible) {
         const visible = getAttributeForCurrentSize(this.state.size, this.props.visible)
         if (visible && visible === 'on') {
            viewClasses.push(styles.visible)
         } else {
            viewClasses.push(styles.hidden)
         }
      }

      if (this.props.format) {
         const format = getAttributeForCurrentSize(this.state.size, this.props.format)
         if (format === 'float') {
            viewClasses.push(styles.floatFormat)
         } else if (format === 'auto') {
            viewClasses.push(styles.autoFormat)
         }
      }

      const style = {
         ...this.props.style,
         ...statelessStyles,
         ...this.state.position,
         width: this.state.width,
         height: this.state.height
      }

      return (
         <div
            ref={node => (this.node = node)}
            style={style}
            onScroll={this.props.onScroll}
            className={classNames(viewClasses, this.props.className)}>
            {this.props.children}
         </div>
      )
   }
}
<|endoftext|>