<commit_before>/* jshint strict: false */
/* global before, after, describe, it */
var Buffer = require('buffer').Buffer,
    chai = require('chai'),
    File = require('gulp-util').File,
    fs = require('fs'),
    path = require('path'),
    uglify = require('../');

require('mocha');

var should = chai.should();

var FILE0_CONTENTS = 'function test1() { var asdf = 3; }',
    FILE0_UGLIFIED = 'function test1(){}',
    FILE0_UGLIFIED_WITH_SM = 'function test1(){}\r\n//# sourceMappingURL=test' + path.sep + 'file0.js.map',
    FILE0_SOURCE_MAP = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js"],"names":["test1"],"mappings":"AAAA,QAASA"}';

var FILE1_CONTENTS = 'function test2() { var qwerty = \'keyboard\'; return qwerty; }';

var FILE0_1_UGLIFIED = 'function test1(){}function test2(){var t="keyboard";return t}',
    FILE0_1_UGLIFIED_WITH_SM = 'function test1(){}function test2(){var t=\"keyboard\";return t}\r\n//# sourceMappingURL=test' + path.sep + 'file0.js.map',
    FILE0_1_UNMANGLED = 'function test1(){}function test2(){var qwerty=\"keyboard\";return qwerty}',
    FILE0_1_SOURCE_MAP = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js","test\\\\file1.js"],"names":["test1","test2","qwerty"],"mappings":"AAAA,QAASA,UCAT,QAASC,SAAU,GAAIC,GAAS,UAAY,OAAOA"}';

function testFiles(stream, contents, expectedContents, expectedPaths) {
  it('should uglify one or several files', function(done) {
    var index = 0;

    stream.on('data', function(uglifiedFile){
      should.exist(uglifiedFile);
      should.exist(uglifiedFile.path);
      should.exist(uglifiedFile.relative);
      should.exist(uglifiedFile.contents);

      var newFilePath = path.resolve(uglifiedFile.path);
      var expectedFilePath = path.resolve(expectedPaths[index]);
      newFilePath.should.equal(expectedFilePath);

      String(uglifiedFile.contents).should.equal(expectedContents[index]);
      Buffer.isBuffer(uglifiedFile.contents).should.equal(true);

      index++;
    });

    stream.on('end', function() {
      done();
    });

    contents.forEach(function(contents, i) {
      stream.write(new File({
        cwd: '.',
        base: '.',
        path: 'test/file' + i.toString() + '.js',
        contents: new Buffer(contents)
      }));
    });

    stream.end();
  });
}

describe('gulp-uglifyjs', function() {
  before(function() {
    fs.writeFileSync('test/file0.js', [FILE0_CONTENTS]);
    fs.writeFileSync('test/file1.js', [FILE1_CONTENTS]);
  });

  after(function() {
    fs.unlinkSync('test/file0.js');
    fs.unlinkSync('test/file1.js');
  });

  describe('uglify()', function() {
    testFiles(uglify(), [FILE0_CONTENTS], [FILE0_UGLIFIED], ['test/file0.js']);
    testFiles(uglify(), [FILE0_CONTENTS, FILE1_CONTENTS], [FILE0_1_UGLIFIED], ['test/file0.js']);
  });

  describe('uglify(filename)', function() {
    testFiles(uglify('test.js'), [FILE0_CONTENTS], [FILE0_UGLIFIED], ['test.js']);
    testFiles(uglify('test.js'), [FILE0_CONTENTS, FILE1_CONTENTS], [FILE0_1_UGLIFIED], ['test.js']);
  });

  describe('uglify(options)', function() {
    testFiles(uglify({ mangle: false }), [FILE0_CONTENTS], [FILE0_UGLIFIED], ['test/file0.js']);
    testFiles(uglify({ mangle: false }), [FILE0_CONTENTS, FILE1_CONTENTS], [FILE0_1_UNMANGLED], ['test/file0.js']);
  });

  describe('uglify(filename, options)', function() {
    testFiles(uglify('test.js', { mangle: false }), [FILE0_CONTENTS], [FILE0_UGLIFIED], ['test.js']);
    testFiles(uglify('test.js', { mangle: false }), [FILE0_CONTENTS, FILE1_CONTENTS], [FILE0_1_UNMANGLED], ['test.js']);
  });

  describe('uglify(options) with sourcemap', function() {
    testFiles(
      uglify({ outSourceMap: true }),
      [FILE0_CONTENTS],
      [FILE0_UGLIFIED_WITH_SM, FILE0_SOURCE_MAP],
      ['test/file0.js', 'test/file0.js.map']
    );

    testFiles(
      uglify({ outSourceMap: true }),
      [FILE0_CONTENTS, FILE1_CONTENTS],
      [FILE0_1_UGLIFIED_WITH_SM, FILE0_1_SOURCE_MAP],
      ['test/file0.js', 'test/file0.js.map']
    );
  });
});<commit_msg>Adding windows-specific strings for tests<commit_after>/* jshint strict: false */
/* global before, after, describe, it */
var Buffer = require('buffer').Buffer,
    chai = require('chai'),
    File = require('gulp-util').File,
    fs = require('fs'),
    path = require('path'),
    uglify = require('../');

require('mocha');

var should = chai.should();

var isWindows = process.platform === 'win32';

var FILE0_CONTENTS = 'function test1() { var asdf = 3; }',
    FILE0_UGLIFIED = 'function test1(){}',
    FILE0_UGLIFIED_WITH_SM = 'function test1(){}\r\n//# sourceMappingURL=test' + path.sep + 'file0.js.map';

var FILE1_CONTENTS = 'function test2() { var qwerty = \'keyboard\'; return qwerty; }';

var FILE0_1_UGLIFIED = 'function test1(){}function test2(){var t="keyboard";return t}',
    FILE0_1_UGLIFIED_WITH_SM = 'function test1(){}function test2(){var t=\"keyboard\";return t}\r\n//# sourceMappingURL=test' + path.sep + 'file0.js.map',
    FILE0_1_UNMANGLED = 'function test1(){}function test2(){var qwerty=\"keyboard\";return qwerty}';

var FILE0_SOURCE_MAP,
    FILE0_1_SOURCE_MAP;

if (isWindows) {
  FILE0_SOURCE_MAP = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js"],"names":["test1"],"mappings":"AAAA,QAASA"}';
  FILE0_1_SOURCE_MAP = '{"version":3,"file":"test\\\\file0.js.map","sources":["test\\\\file0.js","test\\\\file1.js"],"names":["test1","test2","qwerty"],"mappings":"AAAA,QAASA,UCAT,QAASC,SAAU,GAAIC,GAAS,UAAY,OAAOA"}';
} else {
  FILE0_SOURCE_MAP = '{"version":3,"file":"test/file0.js.map","sources":["test/file0.js"],"names":["test1"],"mappings":"AAAA,QAASA"}';
  FILE0_1_SOURCE_MAP = '{"version":3,"file":"test/file0.js.map","sources":["test/file0.js","test/file1.js"],"names":["test1","test2","qwerty"],"mappings":"AAAA,QAASA,UCAT,QAASC,SAAU,GAAIC,GAAS,UAAY,OAAOA"}';
}

function testFiles(stream, contents, expectedContents, expectedPaths) {
  it('should uglify one or several files', function(done) {
    var index = 0;

    stream.on('data', function(uglifiedFile){
      should.exist(uglifiedFile);
      should.exist(uglifiedFile.path);
      should.exist(uglifiedFile.relative);
      should.exist(uglifiedFile.contents);

      var newFilePath = path.resolve(uglifiedFile.path);
      var expectedFilePath = path.resolve(expectedPaths[index]);
      newFilePath.should.equal(expectedFilePath);

      String(uglifiedFile.contents).should.equal(expectedContents[index]);
      Buffer.isBuffer(uglifiedFile.contents).should.equal(true);

      index++;
    });

    stream.on('end', function() {
      done();
    });

    contents.forEach(function(contents, i) {
      stream.write(new File({
        cwd: '.',
        base: '.',
        path: 'test/file' + i.toString() + '.js',
        contents: new Buffer(contents)
      }));
    });

    stream.end();
  });
}

describe('gulp-uglifyjs', function() {
  before(function() {
    fs.writeFileSync('test/file0.js', [FILE0_CONTENTS]);
    fs.writeFileSync('test/file1.js', [FILE1_CONTENTS]);
  });

  after(function() {
    fs.unlinkSync('test/file0.js');
    fs.unlinkSync('test/file1.js');
  });

  describe('uglify()', function() {
    testFiles(uglify(), [FILE0_CONTENTS], [FILE0_UGLIFIED], ['test/file0.js']);
    testFiles(uglify(), [FILE0_CONTENTS, FILE1_CONTENTS], [FILE0_1_UGLIFIED], ['test/file0.js']);
  });

  describe('uglify(filename)', function() {
    testFiles(uglify('test.js'), [FILE0_CONTENTS], [FILE0_UGLIFIED], ['test.js']);
    testFiles(uglify('test.js'), [FILE0_CONTENTS, FILE1_CONTENTS], [FILE0_1_UGLIFIED], ['test.js']);
  });

  describe('uglify(options)', function() {
    testFiles(uglify({ mangle: false }), [FILE0_CONTENTS], [FILE0_UGLIFIED], ['test/file0.js']);
    testFiles(uglify({ mangle: false }), [FILE0_CONTENTS, FILE1_CONTENTS], [FILE0_1_UNMANGLED], ['test/file0.js']);
  });

  describe('uglify(filename, options)', function() {
    testFiles(uglify('test.js', { mangle: false }), [FILE0_CONTENTS], [FILE0_UGLIFIED], ['test.js']);
    testFiles(uglify('test.js', { mangle: false }), [FILE0_CONTENTS, FILE1_CONTENTS], [FILE0_1_UNMANGLED], ['test.js']);
  });

  describe('uglify(options) with sourcemap', function() {
    testFiles(
      uglify({ outSourceMap: true }),
      [FILE0_CONTENTS],
      [FILE0_UGLIFIED_WITH_SM, FILE0_SOURCE_MAP],
      ['test/file0.js', 'test/file0.js.map']
    );

    testFiles(
      uglify({ outSourceMap: true }),
      [FILE0_CONTENTS, FILE1_CONTENTS],
      [FILE0_1_UGLIFIED_WITH_SM, FILE0_1_SOURCE_MAP],
      ['test/file0.js', 'test/file0.js.map']
    );
  });
});<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var res_api       = require('res.api');
var $middlewares  = require('mount-middlewares')(__dirname);
var OAuth         = require('wechat-oauth');
var WXPay         = require('weixin-pay');
// core controller
var $ = require('mount-controllers')(__dirname).wechats_controller;

var c = require('../../wechat_config');

function wx_config (req, res, next) {
  if (req.wx) {
    req.wx_client = new OAuth(req.wx.app_id, req.wx.app_secret);
    console.log('req.mch_id && req.pfx')
        console.log(req.wx.mch_id && req.wx.pfx)
        console.log(req.wx.mch_id)
        console.log(req.wx.pfx)
    if (req.wx.mch_id && req.wx.pfx) {
      req.wx_pay = WXPay({
        appid: req.wx.app_id,
        mch_id: req.wx.mch_id,
        partner_key: req.wx.app_secret, //微信商户平台API密钥
        pfx: req.wx.pfx
      });
    }

    next();
  } else {
    console.log('please check your wechat settings with req.wx!');
    return res.status(200).json({
      status:{
        code:-1,
        msg:"please check your wechat settings with req.wx!"
      }
    });
  }
}

function wx_pay_option (req, res, next) {
  if (!req.wx_pay){
    return res.status(200).json({
      data  : req.wx,
      status:{
        code:-2,
        msg:"当前是req.wx_pay不存在，请检查配置项mch_id和pfx是否配置"
      }
    });
  }else{
    console.log("当前是(req.wx_pay存在)")
    next();
  }
}

function wx_option (req, res, next) {
  if (!req.wx.enable_admin){
    return res.status(200).json({
      status:{
        code:-2,
        msg:"当前是(req.wx.enable_admin==false),管理接口不可用"
      }
    });
  }else{
    console.log("当前是(req.wx.enable_admin==true),管理接口可用,访问/wechats")
    next();
  }
}

// 主页,主要是负责OAuth认证
router.get('/oauth', c, wx_config, wx_option, function(req, res) {
  var url = req.wx_client.getAuthorizeURL(req.wx.domain + '/wechats/callback','','snsapi_userinfo');

  // 重定向请求到微信服务器
  res.redirect(url);
})

/**
 * 认证授权后回调函数
 *
 * 根据openid判断是否用户已经存在
 * - 如果是新用户，注册并绑定，然后跳转到手机号验证界面
 * - 如果是老用户，跳转到主页
 */
router.get('/callback', c, res_api, wx_config, wx_option, $.oauth_callback);

router.post('/getsignature', c, wx_config, wx_option, function config(req, res, next){
  req.wx_config = {
    cache_json_file : req.server_path,
    appId           : req.wx.app_id,
    appSecret       : req.wx.app_secret,
    appToken        : req.wx.app_token
  };

  next();
}, $.getsignature);

// 主要是负责pay
/**
公众号支付 (JS API)

参数req.params

- id      = openid
- order_id= 订单编号
- body    = 产品名称
- detail  = 产品规格描述
- fee     = 支付费用，单位是分
- cb_url  = 回调url

function jsApiCall(){
  var ordor_id = _get_out_trade_no ();
  alert(ordor_id)
  $.get('/wechats/pay_h5?id=o12hcuKXjejDFUwxMgToaGtjtqf4&order_id=' + ordor_id + '&body=1111&detail=222222&fee=1&cb_url=/wechats/pay_calllback/'+ ordor_id, function(data){
    var r = data.data;

    WeixinJSBridge.invoke('getBrandWCPayRequest', r, function(res){
      if(res.err_msg == "get_brand_wcpay_request:ok"){
        alert("支付成功");
        // 这里可以跳转到订单完成页面向用户展示
      }else{
        alert("支付失败，请重试");
      }
    });
  });
}

*/
router.get('/pay_h5/', c, wx_config, wx_pay_option, function(req, res) {
  var call_back_url = req.wx.domain + req.query.cb_url;
  var out_trade_no = req.query.order_id;
  console.log(req.query.id);
  // return;
  // req.wx_pay
  var p = {
    openid: req.query.id,
    body: req.query.body,
    detail: req.query.detail,
    out_trade_no: out_trade_no,// 2015_10_14_18_37_187949638969
    total_fee: req.query.fee,
    spbill_create_ip: req.ip,// 请求的ip地址
    notify_url: call_back_url,
    prepay_id:out_trade_no
  }

  console.log(p)
  req.wx_pay.getBrandWCPayRequestParams(p, function(err, result){
    console.log('getBrandWCPayRequestParams=' +err);
    console.log(result);
    if (err) {
      res.status(200).json({
        data: err,
        status: {
          code: 2,
          msg: 'create order filde'
        }
      });
    }else{
      res.status(200).json({
        data: result,
        status: {
          code: 0,
          msg: 'success'
        }
      })
    };
  });
})

router.get('/pay_calllback', function(req, res, next){
  console.log('/wechats/pay_calllback get sucess')
});

router.post('/pay_calllback/:id', function(req, res, next){
  console.log(req.params.id)
  console.log('/wechats/pay_calllback post sucess')
});

// var wxpay = require('weixin-pay');
// // 支付结果异步通知
// router.use('/notify', wxpay.useWXCallback(function(msg, req, res, next){
//     // 处理商户业务逻辑
//   console.log(msg);
//     // res.success() 向微信返回处理成功信息，res.fail()返回失败信息。
//     res.success();
// }));
// 2015_10_14_18_32_53

/**
 * Auto generate RESTful url routes.
 *
 * URL routes:
 *
 *  GET    /wechats[/]        => wechat.list()
 *  GET    /wechats/new       => wechat.new()
 *  GET    /wechats/:id       => wechat.show()
 *  GET    /wechats/:id/edit  => wechat.edit()
 *  POST   /wechats[/]        => wechat.create()
 *  PATCH  /wechats/:id       => wechat.update()
 *  DELETE /wechats/:id       => wechat.destroy()
 *
 */

router.get('/new', $.new);
router.get('/:id/edit', $.edit);

router.route('/')
  .get($.list)
  .post($.create);

router.route('/:id')
  .patch($.update)
  .get($.show)
  .delete($.destroy);

// -- custom routes

module.exports = router;<commit_msg>refact && code format<commit_after>var express = require('express');
var router = express.Router();
var res_api       = require('res.api');
var $middlewares  = require('mount-middlewares')(__dirname);
var OAuth         = require('wechat-oauth');
var WXPay         = require('weixin-pay');
// core controller
var $ = require('mount-controllers')(__dirname).wechats_controller;

var c = function(req, res, next){
  next();
}

if(process.env.moas == 1){
  console.log('当前在使用moas调试，加载../../wechat_config');
  c = require('../../wechat_config');
}else{
  console.log('当前未使用moas调试，请注意中间件配置');
}

function wx_config (req, res, next) {
  if (req.wx) {
    req.wx_client = new OAuth(req.wx.app_id, req.wx.app_secret);
    console.log('req.mch_id && req.pfx')
    console.log(req.wx.mch_id && req.wx.pfx)
    console.log(req.wx.mch_id)
    console.log(req.wx.pfx)

    if (req.wx.mch_id && req.wx.pfx) {
      req.wx_pay = WXPay({
        appid: req.wx.app_id,
        mch_id: req.wx.mch_id,
        partner_key: req.wx.app_secret, //微信商户平台API密钥
        pfx: req.wx.pfx
      });
    }

    next();
  } else {
    console.log('please check your wechat settings with req.wx!');
    return res.status(200).json({
      status:{
        code:-1,
        msg:"please check your wechat settings with req.wx!"
      }
    });
  }
}

function wx_pay_option (req, res, next) {
  if (!req.wx_pay){
    return res.status(200).json({
      data  : req.wx,
      status:{
        code:-2,
        msg:"当前是req.wx_pay不存在，请检查配置项mch_id和pfx是否配置"
      }
    });
  }else{
    console.log("当前是(req.wx_pay存在)")
    next();
  }
}

function wx_option (req, res, next) {
  if (!req.wx.enable_admin){
    return res.status(200).json({
      status:{
        code:-2,
        msg:"当前是(req.wx.enable_admin==false),管理接口不可用"
      }
    });
  }else{
    console.log("当前是(req.wx.enable_admin==true),管理接口可用,访问/wechats")
    next();
  }
}

// 主页,主要是负责OAuth认证
router.get('/oauth', c, wx_config, wx_option, function(req, res) {
  var url = req.wx_client.getAuthorizeURL(req.wx.domain + '/wechats/callback','','snsapi_userinfo');

  // 重定向请求到微信服务器
  res.redirect(url);
})

/**
 * 认证授权后回调函数
 *
 * 根据openid判断是否用户已经存在
 * - 如果是新用户，注册并绑定，然后跳转到手机号验证界面
 * - 如果是老用户，跳转到主页
 */
router.get('/callback', c, res_api, wx_config, wx_option, $.oauth_callback);

router.post('/getsignature', c, wx_config, wx_option, function config(req, res, next){
  req.wx_config = {
    cache_json_file : req.server_path,
    appId           : req.wx.app_id,
    appSecret       : req.wx.app_secret,
    appToken        : req.wx.app_token
  };

  next();
}, $.getsignature);

// 主要是负责pay
/**
公众号支付 (JS API)

参数req.params

- id      = openid
- order_id= 订单编号
- body    = 产品名称
- detail  = 产品规格描述
- fee     = 支付费用，单位是分
- cb_url  = 回调url

function jsApiCall(){
  var ordor_id = _get_out_trade_no ();
  alert(ordor_id)
  $.get('/wechats/pay_h5?id=o12hcuKXjejDFUwxMgToaGtjtqf4&order_id=' + ordor_id + '&body=1111&detail=222222&fee=1&cb_url=/wechats/pay_calllback/'+ ordor_id, function(data){
    var r = data.data;

    WeixinJSBridge.invoke('getBrandWCPayRequest', r, function(res){
      if(res.err_msg == "get_brand_wcpay_request:ok"){
        alert("支付成功");
        // 这里可以跳转到订单完成页面向用户展示
      }else{
        alert("支付失败，请重试");
      }
    });
  });
}

*/
router.get('/pay_h5/', c, wx_config, wx_pay_option, function(req, res) {
  var call_back_url = req.wx.domain + req.query.cb_url;
  var out_trade_no = req.query.order_id;
  console.log(req.query.id);
  // return;
  // req.wx_pay
  var p = {
    openid: req.query.id,
    body: req.query.body,
    detail: req.query.detail,
    out_trade_no: out_trade_no,// 2015_10_14_18_37_187949638969
    total_fee: req.query.fee,
    spbill_create_ip: req.ip,// 请求的ip地址
    notify_url: call_back_url,
    prepay_id:out_trade_no
  }

  console.log(p)
  req.wx_pay.getBrandWCPayRequestParams(p, function(err, result){
    console.log('getBrandWCPayRequestParams=' +err);
    console.log(result);
    if (err) {
      res.status(200).json({
        data: err,
        status: {
          code: 2,
          msg: 'create order filde'
        }
      });
    }else{
      res.status(200).json({
        data: result,
        status: {
          code: 0,
          msg: 'success'
        }
      })
    };
  });
})

// 仅供测试支付成功后回调使用
router.post('/pay_calllback/:id', function(req, res, next){
  console.log(req.params.id)
  console.log('/wechats/pay_calllback post sucess')
});

/**
 * Auto generate RESTful url routes.
 *
 * URL routes:
 *
 *  GET    /wechats[/]        => wechat.list()
 *  GET    /wechats/new       => wechat.new()
 *  GET    /wechats/:id       => wechat.show()
 *  GET    /wechats/:id/edit  => wechat.edit()
 *  POST   /wechats[/]        => wechat.create()
 *  PATCH  /wechats/:id       => wechat.update()
 *  DELETE /wechats/:id       => wechat.destroy()
 *
 */

router.get('/new', $.new);
router.get('/:id/edit', $.edit);

router.route('/')
  .get($.list)
  .post($.create);

router.route('/:id')
  .patch($.update)
  .get($.show)
  .delete($.destroy);

// -- custom routes

module.exports = router;<|endoftext|>


<commit_before>'use strict';
angular.module('Lunch.browse', ['Lunch.service.matchData', 'Lunch.factory.storedUserData'])
.config(function($stateProvider){
  $stateProvider
  .state('app.browse', {
      url: '/browse',
      views: {
        'menuContent' :{
          templateUrl: 'templates/browse.html',
          controller: 'BrowseCtrl'
        }
      }
  });
})
.controller('BrowseCtrl', function($rootScope, $state, $scope, matchData, $location, requests, storedUserData){
    var userId = storedUserData.id;
    var matchId;
    var matchedData = matchData.getMatches();
    $scope.counter = matchData.getCount();

    var renderMatch = function() {
        var userData = matchedData[$scope.counter];
        $scope.firstname = userData.firstname;
        $scope.lastname = userData.lastname;
        $scope.likes = userData.likes;
        $scope.city = userData.city;
        $scope.tags = userData.tags;
        $scope.photo_url = userData.profileImage;
        matchId = userData.id;
        // TODO: show splash screen of come back tomorrow!
    };

    var next = function(){
      if($scope.counter < matchedData.length){
        renderMatch();
        matchData.incrementMatchedUserCounter();
        $scope.counter++;
      } else {
        matchData.getMatchesFromServer().then(function(data){
          matchedData = data;
          if(!matchedData.length){
            $state.go('app.nomatches')
          } else {
            // resetting the scope counter
            $scope.counter = 0;
            next();
          }
        });
      }
    };

    next();

    // records an approval for the currently displayed profile
    $scope.postDecision = function(decision) {
      // call service to send approval to db
      requests.postDecision({
          id: storedUserData.id,
          selectedUserId : matchId,
          accepted: decision
      })
      .then(function(returnedData){
        var parsedData = angular.fromJson(returnedData);
          if(returnedData.id){
            $state.go('app.matched');
          }
        next();
      });
    };

});
<commit_msg>Reviewed browse.js<commit_after>'use strict';

angular.module('Lunch.browse', ['Lunch.service.matchData', 'Lunch.factory.storedUserData'])
.config(function($stateProvider){
  $stateProvider
  .state('app.browse', {
      url: '/browse',
      views: {
        'menuContent' :{
          templateUrl: 'templates/browse.html',
          controller: 'BrowseCtrl'
        }
      }
  });
})

.controller('BrowseCtrl', function($rootScope, $state, $scope, matchData, $location, requests, OpenFB, match){
    var matchId;
    var matchedData = matchData.getMatches();

    var renderMatch = function(match){
        match.photo_url = match.profileImage;
        matchId = match.id;
        angular.extend($scope, match);
    };

    var next = function(){
      if(matchedData.length){
        renderMatch(matchedData.unshift());
      } else {
        matchData.getMatches().then(function(data){
          if (data.length) {
            matchedData = data;
            next();
          } else {
            $state.go('app.nomatches')
          }
        });
      }
    };

    next();

    // records an approval for the currently displayed profile
    $scope.postDecision = function(decision){
      // call service to send approval to db
      OpenFB.checkLogin(function(id){
        requests.postDecision({
            id: id,
            selectedUserId : matchId,
            accepted: decision
        })
        .then(function(returnedData){
          var parsedData = angular.fromJson(returnedData);
            if(parsedData.id){
              match = parsedData.id;
              $state.go('app.matched');
            }
          next();
        });
      });
    };

});
<|endoftext|>


<commit_before>var concat = require('concat-stream')
var mock = require('mock-data')
var hyperquest = require('hyperquest')
var debug = require('debug')('mapeo-mock-device')
var path = require('path')
var Mapeo = require('mapeo-server')
var blobstore = require('safe-fs-blob-store')
var osmdb = require('osm-p2p')
var http = require('http')

module.exports = createMockDevice

function createMockDevice (dir) {
  var osm = osmdb(path.join(dir, 'osm'))
  var media = blobstore(path.join(dir, 'media'))
  var mapeo = Mapeo(osm, media)
  var server = http.createServer(function (req, res) {
    if (!mapeo.handle(req, res)) {
      res.statusCode = 404
      res.end('404')
    }
  })

  server.mapeo = mapeo
  server.shutdown = shutdown
  server.shutdown.bind(server)
  server.turnOn = turnOn
  server.turnOn.bind(server)
  server.openSyncScreen = openSyncScreen
  server.openSyncScreen.bind(server)
  server.closeSyncScreen = closeSyncScreen
  server.closeSyncScreen.bind(server)
  server.createMockData = createMockData
  server.createMockData.bind(server)
  return server
}

var DEFAULT_PORT = 5006

function turnOn (opts, cb) {
  var server = this
  if (typeof opts === 'number' || typeof opts === 'string') opts = { port: opts }
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }
  var port = opts.port || DEFAULT_PORT

  server.listen(port, cb)
}

function openSyncScreen (cb) {
  var server = this
  if (server.interval) return cb && cb()
  server.interval = setInterval(function () {
    debug('announcing')
    var port = server.address().port
    var hq2 = hyperquest.get(`http://localhost:${port}/sync/announce`, {})
    hq2.pipe(concat({ encoding: 'string' }, function (body) {
      debug('announced', body)
      if (cb) return cb(body)
    }))
    hq2.end()
  }, 2000)
}

function closeSyncScreen (cb) {
  var server = this
  if (!server.interval) return cb && cb()
  clearInterval(server.interval)
  server.interval = undefined
  debug('unannouncing')
  var port = server.address().port
  var hq2 = hyperquest.get(`http://localhost:${port}/sync/unannounce`, {})
  hq2.pipe(concat({ encoding: 'string' }, function (body) {
    debug('unannounced', body)
    if (cb) return cb(body)
  }))
  hq2.end()
}

function createMockData (count, cb) {
  if (!cb) {
    cb = count
    count = 1
  }
  var bounds = [-78.3155, -3.3493, -74.9871, 0.6275]
  bounds = bounds.map((b) => b * 100)

  var server = this
  var port = server.address().port
  var base = `http://localhost:${port}`
  var fpath = encodeURIComponent(path.join(__dirname, 'image.jpg'))

  // create at least one dummy
  createObservation({
    lon: bounds[0] / 100,
    lat: bounds[1] / 100,
    notes: '',
    observedBy: 'you',
    type: 'observation'
  })

  mock.generate({
    type: 'integer',
    count: count,
    params: { start: bounds[0], end: bounds[2] }
  }, function (err, lons) {
    if (err) throw err
    mock.generate({
      type: 'integer',
      count: count,
      params: { start: bounds[1], end: bounds[3] }
    }, function (err, lats) {
      if (err) throw err
      lons.forEach((lon, i) => {
        var obs = {
          type: 'observation',
          lat: lats[i] / 100,
          lon: lon / 100,
          notes: '',
          observedBy: 'you'
        }
        createObservation(obs)
      })
    })
  })

  function createObservation (obs) {
    if (obs.lat < -90 || obs.lat > 90 || obs.lon < -180 || obs.lon > 180) return console.error('observation has lon/lat out of range:', obs)
    var hq = hyperquest.put(base + '/media?file=' + fpath, {})
    hq.pipe(concat({ encoding: 'string' }, function (body) {
      var hq = hyperquest.post(base + '/observations', {
        headers: { 'content-type': 'application/json' }
      })
      var obj = JSON.parse(body)

      hq.on('response', function (res) {
        if (res.statusCode !== 200) cb(new Error('create observation failed', res))
      })

      hq.pipe(concat({ encoding: 'string' }, function (body) {
        debug('created observation', body)
        if (cb) cb(null, body)
      }))

      obs.attachments = [{
        id: obj.id,
        type: 'image/jpeg'
      }]

      hq.end(JSON.stringify(obs))
    }))

    hq.end()
  }
}

function shutdown (cb) {
  var server = this
  clearInterval(server.interval)
  server.interval = undefined
  server.closed = true
  server.on('close', function () {
    server.mapeo.api.close(cb)
  })
  server.close()
}

if (require.main === module) {
  var dir = path.join(__dirname, 'test-data')
  var device = createMockDevice(dir)

  var port = process.argv.splice(2)[0] || DEFAULT_PORT

  device.turnOn(port, function () {
    console.log('listening on port', device.address().port)
    device.createMockData(1000, function () {
    })
    device.openSyncScreen(function () {
      console.log('announced')
    })
  })

  process.on('SIGINT', function () {
    debug('shutting down')
    device.shutdown(function () {
      console.log('device finished shut down')
      process.exit()
    })
  })
}
<commit_msg>update mock for mapeo-mobile new observation format<commit_after>var concat = require('concat-stream')
var mock = require('mock-data')
var hyperquest = require('hyperquest')
var debug = require('debug')('mapeo-mock-device')
var path = require('path')
var Mapeo = require('mapeo-server')
var blobstore = require('safe-fs-blob-store')
var osmdb = require('osm-p2p')
var http = require('http')

module.exports = createMockDevice

function createMockDevice (dir) {
  var osm = osmdb(path.join(dir, 'osm'))
  var media = blobstore(path.join(dir, 'media'))
  var mapeo = Mapeo(osm, media)
  var server = http.createServer(function (req, res) {
    if (!mapeo.handle(req, res)) {
      res.statusCode = 404
      res.end('404')
    }
  })

  server.mapeo = mapeo
  server.shutdown = shutdown
  server.shutdown.bind(server)
  server.turnOn = turnOn
  server.turnOn.bind(server)
  server.openSyncScreen = openSyncScreen
  server.openSyncScreen.bind(server)
  server.closeSyncScreen = closeSyncScreen
  server.closeSyncScreen.bind(server)
  server.createMockData = createMockData
  server.createMockData.bind(server)
  return server
}

var DEFAULT_PORT = 5006

function turnOn (opts, cb) {
  var server = this
  if (typeof opts === 'number' || typeof opts === 'string') opts = { port: opts }
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }
  var port = opts.port || DEFAULT_PORT

  server.listen(port, cb)
}

function openSyncScreen (cb) {
  var server = this
  if (server.interval) return cb && cb()
  server.interval = setInterval(function () {
    debug('announcing')
    var port = server.address().port
    var hq2 = hyperquest.get(`http://localhost:${port}/sync/announce`, {})
    hq2.pipe(concat({ encoding: 'string' }, function (body) {
      debug('announced', body)
      if (cb) return cb(body)
    }))
    hq2.end()
  }, 2000)
}

function closeSyncScreen (cb) {
  var server = this
  if (!server.interval) return cb && cb()
  clearInterval(server.interval)
  server.interval = undefined
  debug('unannouncing')
  var port = server.address().port
  var hq2 = hyperquest.get(`http://localhost:${port}/sync/unannounce`, {})
  hq2.pipe(concat({ encoding: 'string' }, function (body) {
    debug('unannounced', body)
    if (cb) return cb(body)
  }))
  hq2.end()
}

function createMockData (count, cb) {
  if (!cb) {
    cb = count
    count = 1
  }
  var bounds = [-78.3155, -3.3493, -74.9871, 0.6275]
  bounds = bounds.map((b) => b * 100)

  var server = this
  var port = server.address().port
  var base = `http://localhost:${port}`
  var fpath = encodeURIComponent(path.join(__dirname, 'image.jpg'))

  // create at least one dummy
  createObservation({
    lon: bounds[0] / 100,
    lat: bounds[1] / 100,
    tags: {
      notes: '',
      observedBy: 'you'
    },
    type: 'observation'
  })

  mock.generate({
    type: 'integer',
    count: count,
    params: { start: bounds[0], end: bounds[2] }
  }, function (err, lons) {
    if (err) throw err
    mock.generate({
      type: 'integer',
      count: count,
      params: { start: bounds[1], end: bounds[3] }
    }, function (err, lats) {
      if (err) throw err
      lons.forEach((lon, i) => {
        var obs = {
          type: 'observation',
          lat: lats[i] / 100,
          lon: lon / 100,
          tags: {
            notes: '',
            observedBy: 'you'
          }
        }
        createObservation(obs)
      })
    })
  })

  function createObservation (obs) {
    if (obs.lat < -90 || obs.lat > 90 || obs.lon < -180 || obs.lon > 180) return console.error('observation has lon/lat out of range:', obs)
    var hq = hyperquest.put(base + '/media?file=' + fpath, {})
    hq.pipe(concat({ encoding: 'string' }, function (body) {
      var hq = hyperquest.post(base + '/observations', {
        headers: { 'content-type': 'application/json' }
      })
      var obj = JSON.parse(body)

      hq.on('response', function (res) {
        if (res.statusCode !== 200) cb(new Error('create observation failed', res))
      })

      hq.pipe(concat({ encoding: 'string' }, function (body) {
        debug('created observation', body)
        if (cb) cb(null, body)
      }))

      obs.attachments = [{
        id: obj.id,
        type: 'image/jpeg'
      }]

      hq.end(JSON.stringify(obs))
    }))

    hq.end()
  }
}

function shutdown (cb) {
  var server = this
  clearInterval(server.interval)
  server.interval = undefined
  server.closed = true
  server.on('close', function () {
    server.mapeo.api.close(cb)
  })
  server.close()
}

if (require.main === module) {
  var dir = path.join(__dirname, 'test-data')
  var device = createMockDevice(dir)

  var port = process.argv.splice(2)[0] || DEFAULT_PORT

  device.turnOn(port, function () {
    console.log('listening on port', device.address().port)
    device.createMockData(1000, function () {
    })
    device.openSyncScreen(function () {
      console.log('announced')
    })
  })

  process.on('SIGINT', function () {
    debug('shutting down')
    device.shutdown(function () {
      console.log('device finished shut down')
      process.exit()
    })
  })
}
<|endoftext|>


<commit_before>var WEBRTC = require('../');

var config = {
  iceServers: [
    {
      url: 'stun:stun.l.google.com:19302',
    },
  ],
};

var constraints = {
  optional: [
    {
      DtlsSrtpKeyAgreement: true,
    },
  ],
  mandatory: {
    OfferToReceiveAudio: true,
    OfferToReceiveVideo: true,
  },
};

var totalChannels = 0;

function RunTest(done) {
  function P2P(alice, bob) {
    function showState() {
      console.log('Alice State:', alice.signalingState);
      console.log('Bob State:', bob.signalingState);
    }

    alice.onicecandidate = function(event) {
      var candidate = event.candidate || event;
      bob.addIceCandidate(candidate);
    };

    bob.onicecandidate = function(event) {
      var candidate = event.candidate || event;
      alice.addIceCandidate(candidate);
    };

    alice.onnegotiationneeded = function() {
      showState();

      alice.createOffer(function(sdp) {
        showState();

        alice.setLocalDescription(sdp, function() {
          showState();

          bob.setRemoteDescription(sdp, function() {
            showState();

            bob.createAnswer(function(sdp) {
              showState();

              bob.setLocalDescription(sdp, function() {
                showState();

                alice.setRemoteDescription(sdp, function() {
                  showState();
                });
              });
            });
          });
        });
      });
    };

    bob.onnegotiationneeded = function() {
      showState();

      bob.createOffer(function(sdp) {
        showState();

        bob.setLocalDescription(sdp, function() {
          showState();

          alice.setRemoteDescription(sdp, function() {
            showState();

            alice.createAnswer(function(sdp) {
              showState();

              alice.setLocalDescription(sdp, function() {
                showState();

                bob.setRemoteDescription(sdp, function() {
                  showState();
                });
              });
            });
          });
        });
      });
    };

    alice.ondatachannel = function(event, callback) {
      var channel = event.channel || event;

      channel.onopen = function() {
        totalChannels += 1;
        console.log('Alice: DataChannel Open!');

        if (callback) {
          callback(channel);
        }
      };

      channel.onmessage = function(data) {
        console.log('Alice:', data);

        WEBRTC.RTCGarbageCollect();
      };

      channel.onclose = function() {
        console.log('Alice: DataChannel Closed!');
        channel = null;
      };
    };

    bob.ondatachannel = function(event, callback) {
      var channel = event.channel || event;

      channel.onopen = function() {
        totalChannels += 1;
        console.log('Bob: DataChannel Open!');

        if (callback) {
          callback(channel);
        }
      };

      channel.onmessage = function(data) {
        if (typeof(data) == 'string') {
          console.log('Bob:', data);
        } else {
          var buf = new Buffer(new Uint8Array(data));
          if (buf.toString('utf8') === 'HELLO') {
            console.log('TEST SUCCESS');
          } else {
            console.log('TEST FAILED');
          }
        }

        channel.send('Hello World!');

        WEBRTC.RTCGarbageCollect();
      };

      channel.onclose = function() {
        console.log('Bob: DataChannel Closed!');
        channel = null;
      };
    };
  }

  var peers = [];

  function createPeers() {
    for (var instances = 0; instances < 1; instances++) {
      var alice = new WEBRTC.RTCPeerConnection(config, constraints);
      var bob = new WEBRTC.RTCPeerConnection(config, constraints);

      P2P(alice, bob);

      peers.push(alice);
      peers.push(bob);

      for (var channels = 0; channels < 1; channels++) {
        alice.ondatachannel(alice.createDataChannel('TestChannel'), function(channel) {
          var buf = new Buffer(5);
          buf.write('HELLO');

          channel.send(new Uint8Array(buf));
        });
      }
    }
  }

  createPeers();

  setTimeout(function() {
    while (peers.length) {
      var peer = peers[0];
      peers.splice(0, 1);
      peer.close();
    }
    setTimeout(function() {
      console.log('Total count of channels:', totalChannels);
    }, 5000);
  }, 1000);
}

RunTest(function() {
  WEBRTC.RTCGarbageCollect();
});
<commit_msg>Disable OfferToReceive*<commit_after>var WEBRTC = require('../');

var config = {
  iceServers: [
    {
      url: 'stun:stun.l.google.com:19302',
    },
  ],
};

var constraints = {
  optional: [
    {
      DtlsSrtpKeyAgreement: true,
    },
  ],
  mandatory: {
    OfferToReceiveAudio: false,
    OfferToReceiveVideo: false,
  },
};

var totalChannels = 0;

function RunTest(done) {
  function P2P(alice, bob) {
    function showState() {
      console.log('Alice State:', alice.signalingState);
      console.log('Bob State:', bob.signalingState);
    }

    alice.onicecandidate = function(event) {
      var candidate = event.candidate || event;
      bob.addIceCandidate(candidate);
    };

    bob.onicecandidate = function(event) {
      var candidate = event.candidate || event;
      alice.addIceCandidate(candidate);
    };

    alice.onnegotiationneeded = function() {
      showState();

      alice.createOffer(function(sdp) {
        showState();

        alice.setLocalDescription(sdp, function() {
          showState();

          bob.setRemoteDescription(sdp, function() {
            showState();

            bob.createAnswer(function(sdp) {
              showState();

              bob.setLocalDescription(sdp, function() {
                showState();

                alice.setRemoteDescription(sdp, function() {
                  showState();
                });
              });
            });
          });
        });
      });
    };

    bob.onnegotiationneeded = function() {
      showState();

      bob.createOffer(function(sdp) {
        showState();

        bob.setLocalDescription(sdp, function() {
          showState();

          alice.setRemoteDescription(sdp, function() {
            showState();

            alice.createAnswer(function(sdp) {
              showState();

              alice.setLocalDescription(sdp, function() {
                showState();

                bob.setRemoteDescription(sdp, function() {
                  showState();
                });
              });
            });
          });
        });
      });
    };

    alice.ondatachannel = function(event, callback) {
      var channel = event.channel || event;

      channel.onopen = function() {
        totalChannels += 1;
        console.log('Alice: DataChannel Open!');

        if (callback) {
          callback(channel);
        }
      };

      channel.onmessage = function(data) {
        console.log('Alice:', data);

        WEBRTC.RTCGarbageCollect();
      };

      channel.onclose = function() {
        console.log('Alice: DataChannel Closed!');
        channel = null;
      };
    };

    bob.ondatachannel = function(event, callback) {
      var channel = event.channel || event;

      channel.onopen = function() {
        totalChannels += 1;
        console.log('Bob: DataChannel Open!');

        if (callback) {
          callback(channel);
        }
      };

      channel.onmessage = function(data) {
        if (typeof(data) == 'string') {
          console.log('Bob:', data);
        } else {
          var buf = new Buffer(new Uint8Array(data));
          if (buf.toString('utf8') === 'HELLO') {
            console.log('TEST SUCCESS');
          } else {
            console.log('TEST FAILED');
          }
        }

        channel.send('Hello World!');

        WEBRTC.RTCGarbageCollect();
      };

      channel.onclose = function() {
        console.log('Bob: DataChannel Closed!');
        channel = null;
      };
    };
  }

  var peers = [];

  function createPeers() {
    for (var instances = 0; instances < 1; instances++) {
      var alice = new WEBRTC.RTCPeerConnection(config, constraints);
      var bob = new WEBRTC.RTCPeerConnection(config, constraints);

      P2P(alice, bob);

      peers.push(alice);
      peers.push(bob);

      for (var channels = 0; channels < 1; channels++) {
        alice.ondatachannel(alice.createDataChannel('TestChannel'), function(channel) {
          var buf = new Buffer(5);
          buf.write('HELLO');

          channel.send(new Uint8Array(buf));
        });
      }
    }
  }

  createPeers();

  setTimeout(function() {
    while (peers.length) {
      var peer = peers[0];
      peers.splice(0, 1);
      peer.close();
    }
    setTimeout(function() {
      console.log('Total count of channels:', totalChannels);
    }, 5000);
  }, 1000);
}

RunTest(function() {
  WEBRTC.RTCGarbageCollect();
});
<|endoftext|>


<commit_before>'use strict';

const fs      = require('fs');
const path    = require('path');
const http    = require('http');
const os      = require('os');
const zlib    = require('zlib');

const tar = require('tar-fs');

const pipe    = require('..');
const test    = require('tape');

const random  = Math.random();

test('check parameters', function(t) {
    t.throws(pipe, /streams could not be empty!/, 'check streams');
    t.throws(pipe.bind(null, []), /callback could not be empty!/, 'check callback');
    t.end();
});

test('getBody', function(t) {
    const read = fs.createReadStream(__filename);

    pipe.getBody(read, function(error, data) {
        const file = fs.readFileSync(__filename, 'utf8');

        t.equal(data, file, 'getbody <-> readFile');

        t.end();
    });
});

test('getBody: error', function(t) {
    const read = fs.createReadStream(String(Math.random()));

    pipe.getBody(read, function(error) {
        t.ok(error, 'read error: ' + error.message);
        t.end();
    });
});

test('file1 | file2: no error', function(t) {
    const tmp     = os.tmpdir(),
        name    = path.basename(__filename),
        nameTmp = path.join(tmp, name + random);

    tryPipe(__filename, nameTmp, function() {
        const file1 = fs.readFileSync(__filename, 'utf8'),
            file2 = fs.readFileSync(nameTmp, 'utf8');

        fs.unlinkSync(nameTmp);

        t.equal(file1, file2, 'files equal');
        t.end();
    });
});

test('file1 | file2: write open EACESS', function(t) {
    const name    = path.basename(__filename),
        nameTmp = '/' + name + random;

    tryPipe(__filename, nameTmp, function(error) {
        t.ok(error, error && error.message);

        t.end();
    });
});

test('file1 | file2: read open ENOENT', function(t) {
    const tmp     = os.tmpdir(),
        name    = path.basename(__filename),
        nameTmp = path.join(tmp, name + random);

    tryPipe(__filename + random, nameTmp, function(error) {
        t.ok(error, error && error.message);

        t.end();
    });
});

test('file1 | file2: error read EISDIR', function(t) {
    const tmp         = os.tmpdir(),
        name        = path.basename(__filename),
        nameTmp     = path.join(tmp, name + random);

    tryPipe('/', nameTmp, function(error) {
        fs.unlinkSync(nameTmp);
        t.equal(error.code, 'EISDIR', 'EISDIR: read error');
        t.end();
    });
});

test('file1 | file2: error write EISDIR', function(t) {
    tryPipe(__filename, '/', function(error) {
        t.equal(error.code, 'EISDIR', 'EISDIR: write error');
        t.end();
    });
});

test('file1 | file2: error read/write EISDIR', function(t) {
    tryPipe(__dirname, '/', function(error) {
        t.equal(error.code, 'EISDIR', 'read/write EISDIR');
        t.end();
    });
});

test('file1 | gzip | file2: no errors', function(t) {
    const tmp         = os.tmpdir(),
        name        = path.basename(__filename),
        nameTmp     = path.join(tmp, name + random),

        read        = fs.createReadStream(__filename),
        write       = fs.createWriteStream(nameTmp),
        zip         = zlib.createGzip();

    pipe([read, zip, write], function(error) {
        const file1   = fs.readFileSync(__filename, 'utf8'),
            file2   = fs.readFileSync(nameTmp),
            zip     = zlib.gzipSync(file1);

        fs.unlinkSync(nameTmp);

        t.notOk(error, 'no errors');
        t.deepEqual(zip, file2, 'file gziped');
        t.end();
    });
});

test('file1 | gzip', function(t) {
    const read        = fs.createReadStream(__filename),
        zip         = zlib.createGzip();

    pipe([read, zip], function(error) {
        t.notOk(error, 'no errors');
        t.end();
    });
});

test('file1 | gzip: error ENOENT', function(t) {
    const read        = fs.createReadStream(__filename + random),
        zip         = zlib.createGzip();

    pipe([read, zip], function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gzip: error EISDIR', function(t) {
    const read        = fs.createReadStream('/'),
        zip         = zlib.createGzip();

    pipe([read, zip], function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip: error header check', function(t) {
    const read    = fs.createReadStream(__filename),
        gunzip  = zlib.createGunzip();

    pipe([read, gunzip], function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip | untar: error header check', function(t) {
    const read = fs.createReadStream(__filename);
    const gunzip = zlib.createGunzip();
    const tarStream = tar.extract(__dirname);

    pipe([read, gunzip, tarStream], function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('tar | gzip | file', (t) => {
    const fixture = path.join(__dirname, 'fixture');
    const from = path.join(fixture, 'pipe.txt');
    const to = path.join(os.tmpdir(), `${Math.random()}.tar.gz`);
    const tarStream = tar.pack(fixture, {
        entries: [
            'pipe.txt'
        ]
    });

    const gzip = zlib.createGzip();
    const write = fs.createWriteStream(to);

    pipe([tarStream, gzip, write], (error) => {
        const toFile = fs.readFileSync(to);
        const fromFile = fs.readFileSync(`${from}.tar.gz`);

        t.equal(toFile.length, fromFile.length, 'should pack file');
        t.end();
    });
});

test('file1, file2 | response: end false', function(t) {
    const server = http.createServer((req, res) => {
        const read1 = fs.createReadStream(__filename);
        const read2 = fs.createReadStream(__filename);

        pipe([read1, res], {end: false}, () => {
            pipe([read2, res], (error) => {
                t.notOk(error, 'file1, file2 -> response');
            });
        });
    });

    server.listen(() => {
        const {port} = server.address();
        const url = `http://127.0.0.1:${port}`;

        console.log(`server: 127.0.0.1:${port}`);

        http.get(url, (res) => {
            console.log(`request: ${url}`);

            pipe.getBody(res, (error, data) => {
                const file = fs.readFileSync(__filename, 'utf8');
                t.equal(data, file + file, 'reponse == file1 + file2');
                t.end();
                server.close();
            });
        }).on('error', function(error) {
            t.ok(error, error.message);
            t.end();
        });
    });

    server.on('error', function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1, file2 | options: empty object', function(t) {
    const server = http.createServer(function (req, res) {
        const read1 = fs.createReadStream(__filename),
            read2 = fs.createReadStream(__filename);

        pipe([read1, res], {}, function() {
            pipe([read2, res], function() {
            });
        });
    });

    server.listen(7331, '127.0.0.1', function() {
        console.log('server: 127.0.0.1:7331');

        http.get('http://127.0.0.1:7331', function(res) {
            console.log('request: http://127.0.0.1:7331');

            pipe.getBody(res, function(error, data) {
                const file = fs.readFileSync(__filename, 'utf8');
                t.equal(data, file, 'reponse == file1 + file2');
                t.end();
                server.close();
            });
        }).on('error', function(error) {
            t.ok(error, error.message);
            t.end();
        });
    });

    server.on('error', function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

function tryPipe(from, to, fn) {
    const read = fs.createReadStream(from);
    const write = fs.createWriteStream(to);

    pipe([read, write], (error) => {
        const name = checkListenersLeak([read, write]);

        if (name)
            console.error('possible memory leak: ', name);

        fn(error);
    });
}

function checkListenersLeak(streams) {
    let name;
    const events  = ['open', 'error', 'end', 'finish'];
    const regExp  = /^function (onError|onReadError|onWriteError|onReadEnd|onWriteFinish)/;

    streams.some(function(stream) {
        events.some(function(event) {
            stream.listeners(event).some(function(fn) {
                const is = (fn + '').match(regExp);

                if (is)
                    name = is[1];

                return name;
            });

            return name;
        });

        return name;
    });

    return name;
}

<commit_msg>test(pipe) deepEqual -> fileFrom.equals(fileTo)<commit_after>'use strict';

const fs      = require('fs');
const path    = require('path');
const http    = require('http');
const os      = require('os');
const zlib    = require('zlib');

const tar = require('tar-fs');

const pipe    = require('..');
const test    = require('tape');

const random  = Math.random();

test('check parameters', function(t) {
    t.throws(pipe, /streams could not be empty!/, 'check streams');
    t.throws(pipe.bind(null, []), /callback could not be empty!/, 'check callback');
    t.end();
});

test('getBody', function(t) {
    const read = fs.createReadStream(__filename);

    pipe.getBody(read, function(error, data) {
        const file = fs.readFileSync(__filename, 'utf8');

        t.equal(data, file, 'getbody <-> readFile');

        t.end();
    });
});

test('getBody: error', function(t) {
    const read = fs.createReadStream(String(Math.random()));

    pipe.getBody(read, function(error) {
        t.ok(error, 'read error: ' + error.message);
        t.end();
    });
});

test('file1 | file2: no error', function(t) {
    const tmp     = os.tmpdir(),
        name    = path.basename(__filename),
        nameTmp = path.join(tmp, name + random);

    tryPipe(__filename, nameTmp, function() {
        const file1 = fs.readFileSync(__filename, 'utf8'),
            file2 = fs.readFileSync(nameTmp, 'utf8');

        fs.unlinkSync(nameTmp);

        t.equal(file1, file2, 'files equal');
        t.end();
    });
});

test('file1 | file2: write open EACESS', function(t) {
    const name    = path.basename(__filename),
        nameTmp = '/' + name + random;

    tryPipe(__filename, nameTmp, function(error) {
        t.ok(error, error && error.message);

        t.end();
    });
});

test('file1 | file2: read open ENOENT', function(t) {
    const tmp     = os.tmpdir(),
        name    = path.basename(__filename),
        nameTmp = path.join(tmp, name + random);

    tryPipe(__filename + random, nameTmp, function(error) {
        t.ok(error, error && error.message);

        t.end();
    });
});

test('file1 | file2: error read EISDIR', function(t) {
    const tmp         = os.tmpdir(),
        name        = path.basename(__filename),
        nameTmp     = path.join(tmp, name + random);

    tryPipe('/', nameTmp, function(error) {
        fs.unlinkSync(nameTmp);
        t.equal(error.code, 'EISDIR', 'EISDIR: read error');
        t.end();
    });
});

test('file1 | file2: error write EISDIR', function(t) {
    tryPipe(__filename, '/', function(error) {
        t.equal(error.code, 'EISDIR', 'EISDIR: write error');
        t.end();
    });
});

test('file1 | file2: error read/write EISDIR', function(t) {
    tryPipe(__dirname, '/', function(error) {
        t.equal(error.code, 'EISDIR', 'read/write EISDIR');
        t.end();
    });
});

test('file1 | gzip | file2: no errors', function(t) {
    const tmp         = os.tmpdir(),
        name        = path.basename(__filename),
        nameTmp     = path.join(tmp, name + random),

        read        = fs.createReadStream(__filename),
        write       = fs.createWriteStream(nameTmp),
        zip         = zlib.createGzip();

    pipe([read, zip, write], function(error) {
        const file1   = fs.readFileSync(__filename, 'utf8'),
            file2   = fs.readFileSync(nameTmp),
            zip     = zlib.gzipSync(file1);

        fs.unlinkSync(nameTmp);

        t.notOk(error, 'no errors');
        t.deepEqual(zip, file2, 'file gziped');
        t.end();
    });
});

test('file1 | gzip', function(t) {
    const read        = fs.createReadStream(__filename),
        zip         = zlib.createGzip();

    pipe([read, zip], function(error) {
        t.notOk(error, 'no errors');
        t.end();
    });
});

test('file1 | gzip: error ENOENT', function(t) {
    const read        = fs.createReadStream(__filename + random),
        zip         = zlib.createGzip();

    pipe([read, zip], function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gzip: error EISDIR', function(t) {
    const read        = fs.createReadStream('/'),
        zip         = zlib.createGzip();

    pipe([read, zip], function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip: error header check', function(t) {
    const read    = fs.createReadStream(__filename),
        gunzip  = zlib.createGunzip();

    pipe([read, gunzip], function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip | untar: error header check', function(t) {
    const read = fs.createReadStream(__filename);
    const gunzip = zlib.createGunzip();
    const tarStream = tar.extract(__dirname);

    pipe([read, gunzip, tarStream], function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('tar | gzip | file', (t) => {
    const fixture = path.join(__dirname, 'fixture');
    const from = path.join(fixture, 'pipe.txt');
    const to = path.join(os.tmpdir(), `${Math.random()}.tar.gz`);
    const tarStream = tar.pack(fixture, {
        entries: [
            'pipe.txt'
        ]
    });

    const gzip = zlib.createGzip();
    const write = fs.createWriteStream(to);

    pipe([tarStream, gzip, write], (error) => {
        const toFile = fs.readFileSync(to);
        const fromFile = fs.readFileSync(`${from}.tar.gz`);

        fs.unlinkSync(to);
        t.ok(toFile.equals(fromFile), 'should pack file');
        t.end();
    });
});

test('file1, file2 | response: end false', function(t) {
    const server = http.createServer((req, res) => {
        const read1 = fs.createReadStream(__filename);
        const read2 = fs.createReadStream(__filename);

        pipe([read1, res], {end: false}, () => {
            pipe([read2, res], (error) => {
                t.notOk(error, 'file1, file2 -> response');
            });
        });
    });

    server.listen(() => {
        const {port} = server.address();
        const url = `http://127.0.0.1:${port}`;

        console.log(`server: 127.0.0.1:${port}`);

        http.get(url, (res) => {
            console.log(`request: ${url}`);

            pipe.getBody(res, (error, data) => {
                const file = fs.readFileSync(__filename, 'utf8');
                t.equal(data, file + file, 'reponse == file1 + file2');
                t.end();
                server.close();
            });
        }).on('error', function(error) {
            t.ok(error, error.message);
            t.end();
        });
    });

    server.on('error', function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1, file2 | options: empty object', function(t) {
    const server = http.createServer(function (req, res) {
        const read1 = fs.createReadStream(__filename),
            read2 = fs.createReadStream(__filename);

        pipe([read1, res], {}, function() {
            pipe([read2, res], function() {
            });
        });
    });

    server.listen(7331, '127.0.0.1', function() {
        console.log('server: 127.0.0.1:7331');

        http.get('http://127.0.0.1:7331', function(res) {
            console.log('request: http://127.0.0.1:7331');

            pipe.getBody(res, function(error, data) {
                const file = fs.readFileSync(__filename, 'utf8');
                t.equal(data, file, 'reponse == file1 + file2');
                t.end();
                server.close();
            });
        }).on('error', function(error) {
            t.ok(error, error.message);
            t.end();
        });
    });

    server.on('error', function(error) {
        t.ok(error, error.message);
        t.end();
    });
});

function tryPipe(from, to, fn) {
    const read = fs.createReadStream(from);
    const write = fs.createWriteStream(to);

    pipe([read, write], (error) => {
        const name = checkListenersLeak([read, write]);

        if (name)
            console.error('possible memory leak: ', name);

        fn(error);
    });
}

function checkListenersLeak(streams) {
    let name;
    const events  = ['open', 'error', 'end', 'finish'];
    const regExp  = /^function (onError|onReadError|onWriteError|onReadEnd|onWriteFinish)/;

    streams.some(function(stream) {
        events.some(function(event) {
            stream.listeners(event).some(function(fn) {
                const is = (fn + '').match(regExp);

                if (is)
                    name = is[1];

                return name;
            });

            return name;
        });

        return name;
    });

    return name;
}

<|endoftext|>


<commit_before>
<commit_msg>Update service-worker.js<commit_after>
//This is the "Offline copy of pages" wervice worker

//Install stage sets up the index page (home page) in the cahche and opens a new cache
self.addEventListener('install', function(event) {
  var indexPage = new Request('index.html');
  event.waitUntil(
    fetch(indexPage).then(function(response) {
      return caches.open('pwabuilder-offline').then(function(cache) {
        console.log('[PWA Builder] Cached index page during Install'+ response.url);
        return cache.put(indexPage, response);
      });
  }));
});

//If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener('fetch', function(event) {
  var updateCache = function(request){
    return caches.open('pwabuilder-offline').then(function (cache) {
      return fetch(request).then(function (response) {
        console.log('[PWA Builder] add page to offline'+response.url)
        return cache.put(request, response);
      });
    });
  };

  event.waitUntil(updateCache(event.request));

  event.respondWith(
    fetch(event.request).catch(function(error) {
      console.log( '[PWA Builder] Network request Failed. Serving content from cache: ' + error );

      //Check to see if you have it in the cache
      //Return response
      //If not in the cache, then return error page
      return caches.open('pwabuilder-offline').then(function (cache) {
        return cache.match(event.request).then(function (matching) {
          var report =  !matching || matching.status == 404?Promise.reject('no-match'): matching;
          return report
        });
      });
    })
  );
})
<|endoftext|>


<commit_before>'use strict';

require('mocha');
require('should');
var assert = require('assert');
var extract = require('..');
var fs = require('fs');

function read(fp) {
  return fs.readFileSync(__dirname + '/fixtures/' + fp, 'utf8');
}

describe('comments', function() {
  it('should throw an error when comment is not a string', function(cb) {
    try {
      extract();
      cb('expected an error');
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected a string');
      cb();
    }
  });

  it('should get block comments and line comments', function() {
    var str = read('mixed.js');
    var actual = extract(str);
    assert.equal(actual[0].raw, '/*!\n * this is a multiline\n * block comment\n */');
    assert.equal(actual[actual.length - 1].raw, '// eos');
  });

  it('should return an empty array if no comments are found', function() {
    var str = 'foo';
    var actual = extract(str);
    assert.deepEqual(actual, []);
  });

  it('should support passing a callback as the last argument', function() {
    var str = read('mixed.js');
    var actual = extract(str, function(comment) {
      comment.foo = 'bar';
      return comment;
    });
    assert.equal(actual[0].foo, 'bar');
  });
});

describe('block comments', function() {
  it('should throw an error when comment is not a string', function(cb) {
    try {
      extract.block();
      cb('expected an error');
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected a string');
      cb();
    }
  });

  it('should return an empty array if no comments are found', function() {
    var str = 'foo';
    var actual = extract.block(str);
    assert.deepEqual(actual, []);
  });

  it('should take options as the second argument', function() {
    var str = 'foo';
    var actual = extract.block(str);
    assert.deepEqual(actual, []);
  });

  it('should extract a block comment', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].raw, '/**\n * this is\n *\n * a comment\n*/');
  });

  it('should strip protected comments', function() {
    var str = read('mixed.js');
    var actual = extract.block(str);
    assert.equal(actual[0].raw, '/*!\n * this is a multiline\n * block comment\n */');
  });

  it('should not extract comments in quoted strings', function() {
    var a = '/* this is a block comment */\n\nvar foo = "/* bar */"';
    var actual = extract(a);
    assert.equal(actual.length, 1);
    assert.equal(actual[0].raw, '/* this is a block comment */');

    var b = '/* this is a block comment */\n\nvar foo = "abc /* bar */ xyz "';
    var actual = extract(b);
    assert.equal(actual.length, 1);
    assert.equal(actual[0].raw, '/* this is a block comment */');
  });

  it('should extract comments in functions', function() {
    var a = 'function foo(/*a, b, c*/);';
    var actual = extract(a);
    assert.equal(actual[0].raw, '/*a, b, c*/');
  });

  it('should extract comments after quoted strings', function() {
    var a = '"some code"\n/**\n * some comment\n*/\n';
    var actual = extract(a);
    assert.equal(actual.length, 1);
  });

  it('should strip leading stars to create the "value" property', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].value, 'this is\na comment');
  });

  it('should split the comment into lines', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].lines[0], 'this is');
    assert.equal(actual[0].lines[1], 'a comment');
  });

  it('should get the starting line number', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.start.line, 1);
  });

  it('should get the starting index', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.start.pos, 0);
  });

  it('should get the ending line number', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.end.line, 5);
  });

  it('should get the ending index', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    var loc = actual[0].loc;
    assert.equal(loc.end.pos, 33);
  });
});

describe('code', function() {
  it('should get the code line that follows the comment', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n// var one = two';
    var actual = extract(str);
    assert.equal(actual[0].code.value, 'var foo = "bar";');
  });

  it('should get the code starting and ending indices', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    var code = actual[0].code;
    var start = code.loc.start.pos;
    var end = code.loc.end.pos;
    assert.equal(start, 36);
    assert.equal(end, 52);
    assert.equal(str.slice(start, end), 'var foo = "bar";');
  });

  it('should get comments after code', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n/* foo */';
    var actual = extract(str);
    var comment = actual[1];
    assert.equal(comment.raw, '/* foo */');
  });

  it('should get the code line number', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    var code = actual[0].code;
    var start = code.loc.start.line;
    var lines = str.split('\n');
    var line = lines.indexOf('var foo = "bar";');
    assert.equal(line, start);
  });
});

describe('line comments', function() {
  it('should throw an error when comment is not a string', function(cb) {
    try {
      extract.line();
      cb('expected an error');
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected a string');
      cb();
    }
  });

  it('should return an empty array if no comments are found', function() {
    var str = 'foo';
    var actual = extract.line(str);
    assert.deepEqual(actual, []);
  });

  it('should take options as the second argument', function() {
    var str = 'foo';
    var actual = extract.line(str);
    assert.deepEqual(actual, []);
  });

  it('should extract a line comment', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].raw, '// this is a line comment');
  });

  it('should not extract comments in quoted strings', function() {
    var a = '// this is a line comment\n\nvar foo = ". // \' \\ . // \' \\ .";\n';
    var actual = extract(a);
    assert.equal(actual.length, 1);
    assert.equal(actual[0].raw, '// this is a line comment');

    var b = '// this is a line comment\n\nvar foo = "// one two"';
    var actual = extract(b);
    assert.equal(actual.length, 1);
    assert.equal(actual[0].raw, '// this is a line comment');
  });

  it('should strip leading slashes to create the "value" property', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].value, 'this is a line comment');
  });

  it('should get the starting line number', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.start.line, 1);
  });

  it('should get the starting index', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.start.pos, 0);
  });

  it('should get the ending line number', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.end.line, 1);
  });

  it('should get the ending index', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.end.pos, 25);
  });
});

describe('first', function() {
  it('should throw an error when comment is not a string', function(cb) {
    try {
      extract.first();
      cb('expected an error');
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected a string');
      cb();
    }
  });

  it('should extract the first block comment', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n/* baz */';
    var actual = extract.first(str);
    assert.equal(actual, '/**\n * this is\n *\n * a comment\n*/');
  });

  it('should extract the first line comment', function() {
    var str = '// this is a comment\n\nvar foo = "bar";\n/* baz */';
    var actual = extract.first(str);
    assert.equal(actual, '// this is a comment');
  });

  it('should return null if no comments are found', function() {
    var str = 'foo';
    var actual = extract.first(str);
    assert.equal(actual, null);
  });
});
<commit_msg>adding a test to ensure comments aren't treated as code context<commit_after>'use strict';

require('mocha');
require('should');
var assert = require('assert');
var extract = require('..');
var fs = require('fs');

function read(fp) {
  return fs.readFileSync(__dirname + '/fixtures/' + fp, 'utf8');
}

describe('comments', function() {
  it('should throw an error when comment is not a string', function(cb) {
    try {
      extract();
      cb('expected an error');
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected a string');
      cb();
    }
  });

  it('should get block comments and line comments', function() {
    var str = read('mixed.js');
    var actual = extract(str);
    assert.equal(actual[0].raw, '/*!\n * this is a multiline\n * block comment\n */');
    assert.equal(actual[actual.length - 1].raw, '// eos');
  });

  it('should return an empty array if no comments are found', function() {
    var str = 'foo';
    var actual = extract(str);
    assert.deepEqual(actual, []);
  });

  it('should support passing a callback as the last argument', function() {
    var str = read('mixed.js');
    var actual = extract(str, function(comment) {
      comment.foo = 'bar';
      return comment;
    });
    assert.equal(actual[0].foo, 'bar');
  });
});

describe('block comments', function() {
  it('should throw an error when comment is not a string', function(cb) {
    try {
      extract.block();
      cb('expected an error');
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected a string');
      cb();
    }
  });

  it('should return an empty array if no comments are found', function() {
    var str = 'foo';
    var actual = extract.block(str);
    assert.deepEqual(actual, []);
  });

  it('should take options as the second argument', function() {
    var str = 'foo';
    var actual = extract.block(str);
    assert.deepEqual(actual, []);
  });

  it('should extract a block comment', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].raw, '/**\n * this is\n *\n * a comment\n*/');
  });

  it('should strip protected comments', function() {
    var str = read('mixed.js');
    var actual = extract.block(str);
    assert.equal(actual[0].raw, '/*!\n * this is a multiline\n * block comment\n */');
  });

  it('should not extract comments in quoted strings', function() {
    var a = '/* this is a block comment */\n\nvar foo = "/* bar */"';
    var actual = extract(a);
    assert.equal(actual.length, 1);
    assert.equal(actual[0].raw, '/* this is a block comment */');

    var b = '/* this is a block comment */\n\nvar foo = "abc /* bar */ xyz "';
    var actual = extract(b);
    assert.equal(actual.length, 1);
    assert.equal(actual[0].raw, '/* this is a block comment */');
  });

  it('should extract comments in functions', function() {
    var a = 'function foo(/*a, b, c*/);';
    var actual = extract(a);
    assert.equal(actual[0].raw, '/*a, b, c*/');
  });

  it('should extract comments after quoted strings', function() {
    var a = '"some code"\n/**\n * some comment\n*/\n';
    var actual = extract(a);
    assert.equal(actual.length, 1);
  });

  it('should strip leading stars to create the "value" property', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].value, 'this is\na comment');
  });

  it('should split the comment into lines', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].lines[0], 'this is');
    assert.equal(actual[0].lines[1], 'a comment');
  });

  it('should get the starting line number', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.start.line, 1);
  });

  it('should get the starting index', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.start.pos, 0);
  });

  it('should get the ending line number', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.end.line, 5);
  });

  it('should get the ending index', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    var loc = actual[0].loc;
    assert.equal(loc.end.pos, 33);
  });
});

describe('code', function() {
  it('should get the code line that follows the comment', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n// var one = two';
    var actual = extract(str);
    assert.equal(actual[0].code.value, 'var foo = "bar";');
  });

  it('should not get a comment following a comment', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n// var one = two';
    var actual = extract(str);
    assert.equal(actual[0].code.value, '');
  });

  it('should get the code starting and ending indices', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    var code = actual[0].code;
    var start = code.loc.start.pos;
    var end = code.loc.end.pos;
    assert.equal(start, 36);
    assert.equal(end, 52);
    assert.equal(str.slice(start, end), 'var foo = "bar";');
  });

  it('should get comments after code', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n/* foo */';
    var actual = extract(str);
    var comment = actual[1];
    assert.equal(comment.raw, '/* foo */');
  });

  it('should get the code line number', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    var code = actual[0].code;
    var start = code.loc.start.line;
    var lines = str.split('\n');
    var line = lines.indexOf('var foo = "bar";');
    assert.equal(line, start);
  });
});

describe('line comments', function() {
  it('should throw an error when comment is not a string', function(cb) {
    try {
      extract.line();
      cb('expected an error');
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected a string');
      cb();
    }
  });

  it('should return an empty array if no comments are found', function() {
    var str = 'foo';
    var actual = extract.line(str);
    assert.deepEqual(actual, []);
  });

  it('should take options as the second argument', function() {
    var str = 'foo';
    var actual = extract.line(str);
    assert.deepEqual(actual, []);
  });

  it('should extract a line comment', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].raw, '// this is a line comment');
  });

  it('should not extract comments in quoted strings', function() {
    var a = '// this is a line comment\n\nvar foo = ". // \' \\ . // \' \\ .";\n';
    var actual = extract(a);
    assert.equal(actual.length, 1);
    assert.equal(actual[0].raw, '// this is a line comment');

    var b = '// this is a line comment\n\nvar foo = "// one two"';
    var actual = extract(b);
    assert.equal(actual.length, 1);
    assert.equal(actual[0].raw, '// this is a line comment');
  });

  it('should strip leading slashes to create the "value" property', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].value, 'this is a line comment');
  });

  it('should get the starting line number', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.start.line, 1);
  });

  it('should get the starting index', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.start.pos, 0);
  });

  it('should get the ending line number', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.end.line, 1);
  });

  it('should get the ending index', function() {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert.equal(actual[0].loc.end.pos, 25);
  });
});

describe('first', function() {
  it('should throw an error when comment is not a string', function(cb) {
    try {
      extract.first();
      cb('expected an error');
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected a string');
      cb();
    }
  });

  it('should extract the first block comment', function() {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n/* baz */';
    var actual = extract.first(str);
    assert.equal(actual, '/**\n * this is\n *\n * a comment\n*/');
  });

  it('should extract the first line comment', function() {
    var str = '// this is a comment\n\nvar foo = "bar";\n/* baz */';
    var actual = extract.first(str);
    assert.equal(actual, '// this is a comment');
  });

  it('should return null if no comments are found', function() {
    var str = 'foo';
    var actual = extract.first(str);
    assert.equal(actual, null);
  });
});
<|endoftext|>


<commit_before><commit_msg>Add a option selectOnCollapse in subgrid which allow to select a row when it is collapsed and the option is true<commit_after><|endoftext|>


<commit_before>'use strict';

var URI = require('URIjs');
var config = require('./config.js');
var PocketClient = require('./pocket_client.js');
var common = require('./common.js');
var client = new PocketClient(config.pocket);

chrome.webNavigation.onCommitted.addListener(function(details) {
  if (details.frameId === 0) {
    var uri = new URI(details.url);
    var found = false;
    var key;

    var data = {
      domain: uri.host()
    };
    var success = function(pocketItems) {
      common.displayIcon(details.tabId, details.url, pocketItems);
    };
    var error = function() {
      common.displayOfflineIcon(details.tabId);
    };

    if (localStorage.accessToken) {
      client.retrieve(localStorage.accessToken, data, success, error);
    } else {
      error();
    }
  }
});
<commit_msg>Should use singular form<commit_after>'use strict';

var URI = require('URIjs');
var config = require('./config.js');
var PocketClient = require('./pocket_client.js');
var common = require('./common.js');
var client = new PocketClient(config.pocket);

chrome.webNavigation.onCommitted.addListener(function(details) {
  if (details.frameId === 0) {
    var uri = new URI(details.url);
    var found = false;
    var key;

    var data = {
      domain: uri.host()
    };
    var success = function(pocketItem) {
      common.displayIcon(details.tabId, details.url, pocketItem);
    };
    var error = function() {
      common.displayOfflineIcon(details.tabId);
    };

    if (localStorage.accessToken) {
      client.retrieve(localStorage.accessToken, data, success, error);
    } else {
      error();
    }
  }
});
<|endoftext|>


<commit_before><commit_msg>Removed debug log.<commit_after><|endoftext|>


<commit_before>var createContext = require('./util/create-context')
var createREGL = require('../../regl')
var tape = require('tape')

tape('read pixels', function (t) {
  var W = 5
  var H = 5
  var gl = createContext(W, H)
  var regl = createREGL({
    gl: gl,
    optionalExtensions: ['oes_texture_float', 'ext_srgb']
  })

  function checkFBO (pixels, color, name) {
    function checkPixels () {
      for (var i = 0; i < W * H * 4; i += 4) {
        if (pixels[i] !== color[0] ||
            pixels[i + 1] !== color[1] ||
            pixels[i + 2] !== color[2] ||
            pixels[i + 3] !== color[3]) {
          return false
        }
      }
      return true
    }

    t.ok(checkPixels(), name)
  }

  function throws (name, args) {
    t.throws(function () {
      regl.read.apply(regl, args)
    }, /\(regl\)/, name)
  }

  // typedarray input
  var bytes = new Uint8Array(100)
  var result = regl.read(bytes)
  t.equals(result, bytes, 'read typedarray ok')

  // width/height input
  t.equals(regl.read({width: 2, height: 2}).length, 16, 'width/height ok')

  // options input
  t.equals(regl.read({x: 3, y: 3}).length, 16, 'offset ok')

  // read out of bounds
  throws('bad width', [{width: -2}])
  throws('bad height', [{height: -2}])
  throws('bad offset', [{ x: -2 }])
  throws('bad typedarray', [{data: []}])
  throws('small typedarray', [new Uint8Array(1)])

  // check pixels for default framebuffer
  regl.clear({color: [0.5, 0, 0, 1]})
  var pixels = regl.read()
  checkFBO(pixels, [128, 0, 0, 255], 'read null fbo ok')

  regl.clear({color: [0.5, 0, 0, 1]})
  pixels = new Uint8Array(W * H * 4)
  regl.read({data: pixels})
  checkFBO(pixels, [128, 0, 0, 255], 'read null fbo, reuse buffer, ok')

  pixels = new Float32Array(W * H * 4)
  throws('throws if attempt use Float32Array to null fbo', [{data: pixels}])
  throws('throws if attempt use object to null fbo', [{data: {}}])

  // now do it for an uint8 fbo
  var fbo = regl.framebuffer({
    width: W,
    height: H,
    colorFormat: 'rgba',
    colorType: 'uint8'
  })
  regl({framebuffer: fbo})(function () {
    regl.clear({color: [0.5, 0, 0, 1]})
    pixels = regl.read()
    checkFBO(pixels, [128, 0, 0, 255], 'read uint8 fbo ok')
  })

  regl({framebuffer: fbo})(function () {
    regl.clear({color: [0.5, 0, 0, 1]})
    pixels = new Uint8Array(W * H * 4)
    regl.read({data: pixels})
    checkFBO(pixels, [128, 0, 0, 255], 'read uint8 fbo, reuse buffer, ok')
  })

  regl({framebuffer: fbo})(function () {
    pixels = new Float32Array(W * H * 4)
    throws('throws if attempt use Float32Array to uint8 fbo', [{data: pixels}])
    throws('throws if attempt use object to uint8 fbo', [{data: {}}])
  })

  // now do it for an float fbo
  if (regl.hasExtension('oes_texture_float')) {
    fbo = regl.framebuffer({
      width: W,
      height: H,
      colorFormat: 'rgba',
      colorType: 'float'
    })

    regl({framebuffer: fbo})(function () {
      regl.clear({color: [0.5, 0.25, 0.5, 0.25]})
      pixels = regl.read()
      checkFBO(pixels, [0.5, 0.25, 0.5, 0.25], 'read float fbo ok')
    })

    regl({framebuffer: fbo})(function () {
      regl.clear({color: [0.5, 0.25, 0.5, 0.25]})
      pixels = new Float32Array(W * H * 4)
      regl.read({data: pixels})
      checkFBO(pixels, [0.5, 0.25, 0.5, 0.25], 'read float fbo, reuse buffer, ok')
    })

    regl({framebuffer: fbo})(function () {
      pixels = new Uint8Array(W * H * 4)
      throws('throws if attempt use Uint8Array to float fbo', [{data: pixels}])
      throws('throws if attempt use object to float fbo', [{data: {}}])
    })
  }

  var badTestCases = []
  badTestCases.push('rgba4')
  badTestCases.push('rgb565')
  badTestCases.push('rgb5 a1')
  if (regl.hasExtension('ext_srgb')) {
    badTestCases.push('srgba')
  }

  badTestCases.forEach(function (testCase, i) {
    fbo = regl.framebuffer({
      colorFormat: testCase,
      width: W,
      height: H
    })
    regl({framebuffer: fbo})(function () {
      throws('attempt to read from renderbuffer of type ' + testCase, [{}])
    })
  })

  regl.destroy()
  createContext.destroy(gl)
  t.end()
})
<commit_msg>make read pixel test more stable<commit_after>var createContext = require('./util/create-context')
var createREGL = require('../../regl')
var tape = require('tape')

tape('read pixels', function (t) {
  var W = 5
  var H = 5
  var gl = createContext(W, H)
  var regl = createREGL({
    gl: gl,
    optionalExtensions: ['oes_texture_float', 'ext_srgb']
  })

  function checkFBO (pixels, color, name) {
    function checkPixels () {
      for (var i = 0; i < W * H * 4; i += 4) {
        if (pixels[i] !== color[0] ||
            pixels[i + 1] !== color[1] ||
            pixels[i + 2] !== color[2] ||
            pixels[i + 3] !== color[3]) {
          return false
        }
      }
      return true
    }

    t.ok(checkPixels(), name)
  }

  function throws (name, args) {
    t.throws(function () {
      regl.read.apply(regl, args)
    }, /\(regl\)/, name)
  }

  // typedarray input
  var bytes = new Uint8Array(100)
  var result = regl.read(bytes)
  t.equals(result, bytes, 'read typedarray ok')

  // width/height input
  t.equals(regl.read({width: 2, height: 2}).length, 16, 'width/height ok')

  // options input
  t.equals(regl.read({x: 3, y: 3}).length, 16, 'offset ok')

  // read out of bounds
  throws('bad width', [{width: -2}])
  throws('bad height', [{height: -2}])
  throws('bad offset', [{ x: -2 }])
  throws('bad typedarray', [{data: []}])
  throws('small typedarray', [new Uint8Array(1)])

  // check pixels for default framebuffer
  regl.clear({color: [1, 0, 0, 1]})
  var pixels = regl.read()
  checkFBO(pixels, [255, 0, 0, 255], 'read null fbo ok')

  regl.clear({color: [1, 0, 0, 1]})
  pixels = new Uint8Array(W * H * 4)
  regl.read({data: pixels})
  checkFBO(pixels, [255, 0, 0, 255], 'read null fbo, reuse buffer, ok')

  pixels = new Float32Array(W * H * 4)
  throws('throws if attempt use Float32Array to null fbo', [{data: pixels}])
  throws('throws if attempt use object to null fbo', [{data: {}}])

  // now do it for an uint8 fbo
  var fbo = regl.framebuffer({
    width: W,
    height: H,
    colorFormat: 'rgba',
    colorType: 'uint8'
  })
  regl({framebuffer: fbo})(function () {
    regl.clear({color: [1, 0, 0, 1]})
    pixels = regl.read()
    checkFBO(pixels, [255, 0, 0, 255], 'read uint8 fbo ok')
  })

  regl({framebuffer: fbo})(function () {
    regl.clear({color: [1, 0, 0, 1]})
    pixels = new Uint8Array(W * H * 4)
    regl.read({data: pixels})
    checkFBO(pixels, [255, 0, 0, 255], 'read uint8 fbo, reuse buffer, ok')
  })

  regl({framebuffer: fbo})(function () {
    pixels = new Float32Array(W * H * 4)
    throws('throws if attempt use Float32Array to uint8 fbo', [{data: pixels}])
    throws('throws if attempt use object to uint8 fbo', [{data: {}}])
  })

  // now do it for an float fbo
  if (regl.hasExtension('oes_texture_float')) {
    fbo = regl.framebuffer({
      width: W,
      height: H,
      colorFormat: 'rgba',
      colorType: 'float'
    })

    regl({framebuffer: fbo})(function () {
      regl.clear({color: [0.5, 0.25, 0.5, 0.25]})
      pixels = regl.read()
      checkFBO(pixels, [0.5, 0.25, 0.5, 0.25], 'read float fbo ok')
    })

    regl({framebuffer: fbo})(function () {
      regl.clear({color: [0.5, 0.25, 0.5, 0.25]})
      pixels = new Float32Array(W * H * 4)
      regl.read({data: pixels})
      checkFBO(pixels, [0.5, 0.25, 0.5, 0.25], 'read float fbo, reuse buffer, ok')
    })

    regl({framebuffer: fbo})(function () {
      pixels = new Uint8Array(W * H * 4)
      throws('throws if attempt use Uint8Array to float fbo', [{data: pixels}])
      throws('throws if attempt use object to float fbo', [{data: {}}])
    })
  }

  var badTestCases = []
  badTestCases.push('rgba4')
  badTestCases.push('rgb565')
  badTestCases.push('rgb5 a1')
  if (regl.hasExtension('ext_srgb')) {
    badTestCases.push('srgba')
  }

  badTestCases.forEach(function (testCase, i) {
    fbo = regl.framebuffer({
      colorFormat: testCase,
      width: W,
      height: H
    })
    regl({framebuffer: fbo})(function () {
      throws('attempt to read from renderbuffer of type ' + testCase, [{}])
    })
  })

  regl.destroy()
  createContext.destroy(gl)
  t.end()
})
<|endoftext|>


<commit_before>'use strict';

var logger = require('logger');
var moment = require('moment');
var CronJob = require('cron').CronJob;
var config = require('config');

var taskConfig = require('../../config/cron.json');

var SubscriptionEvent = require('models/subscriptionEvent');

const CHANNEL = 'subscription_alerts';
var AsyncClient = require('vizz.async-client');
var asynClient = new AsyncClient(AsyncClient.REDIS, {
    url: `redis://${config.get('redisLocal.host')}:${config.get('redisLocal.port')}`
});
asynClient = asynClient.toChannel(CHANNEL);

var load = function() {
  taskConfig.forEach(function(task) {

    /* THIS CODE IS TO TEST */
    logger.info('Creating cron task for ' + task.name);

    new CronJob(task.crontab, function() {
        logger.info('Publishing ' + task.dataset);
        let beginData = moment().subtract(0, 'months').subtract(task.periodicity, 'milliseconds').toDate();
        let endDate = moment().subtract(0, 'months').toDate();

        asynClient.emit(JSON.stringify({
            layer_slug: task.dataset,
            begin_date: beginData,
            end_date: endDate
        }));
    }, null, true, 'Europe/London');
  });
};

module.exports = {load: load};
<commit_msg>add gap<commit_after>'use strict';

var logger = require('logger');
var moment = require('moment');
var CronJob = require('cron').CronJob;
var config = require('config');

var taskConfig = require('../../config/cron.json');

var SubscriptionEvent = require('models/subscriptionEvent');

const CHANNEL = 'subscription_alerts';
var AsyncClient = require('vizz.async-client');
var asynClient = new AsyncClient(AsyncClient.REDIS, {
    url: `redis://${config.get('redisLocal.host')}:${config.get('redisLocal.port')}`
});
asynClient = asynClient.toChannel(CHANNEL);

var load = function() {
  taskConfig.forEach(function(task) {

    /* THIS CODE IS TO TEST */
    logger.info('Creating cron task for ' + task.name);

    new CronJob(task.crontab, function() {
        logger.info('Publishing ' + task.dataset);
        let beginData = moment().subtract(task.gap, 'months').subtract(task.periodicity, 'milliseconds').toDate();
        let endDate = moment().subtract(task.gap, 'months').toDate();

        asynClient.emit(JSON.stringify({
            layer_slug: task.dataset,
            begin_date: beginData,
            end_date: endDate
        }));
    }, null, true, 'Europe/London');
  });
};

module.exports = {load: load};
<|endoftext|>