<commit_before>// FLUSHALL Redis before starting

var   assert        = require('../support/assert')
    , tests         = module.exports = {}
    , _             = require('underscore')
    , querystring   = require('querystring')
    , fs            = require('fs')
    , redis         = require('redis')
    , th            = require('../support/test_helper')
    , Step          = require('step')
    , mapnik        = require('mapnik')
    , Windshaft     = require('../../lib/windshaft')
    , ServerOptions = require('../support/server_options')
    , semver        = require('semver')
    , http          = require('http');

function rmdir_recursive_sync(dirname) {
  var files = fs.readdirSync(dirname);
  for (var i=0; i<files.length; ++i) {
    var f = dirname + "/" + files[i];
    var s = fs.lstatSync(f);
    if ( s.isFile() ) {
      fs.unlinkSync(f)
    }
    else rmdir_recursive_sync(f);
  }
}

suite('server', function() {

    ////////////////////////////////////////////////////////////////////
    //
    // SETUP
    //
    ////////////////////////////////////////////////////////////////////

    var server = new Windshaft.Server(ServerOptions);
    server.setMaxListeners(0);
    var redis_client = redis.createClient(ServerOptions.redis.port);
    var res_serv; // resources server
    var res_serv_status = { numrequests:0 }; // status of resources server
    var res_serv_port = 8033; // FIXME: make configurable ?

    var mapnik_version = global.environment.mapnik_version || mapnik.versions.mapnik;

    var default_style;
    if ( semver.satisfies(mapnik_version, '<2.1.0') ) {
      // 2.0.0 default
      default_style = '#<%= table %>{marker-fill: #FF6600;marker-opacity: 1;marker-width: 8;marker-line-color: white;marker-line-width: 3;marker-line-opacity: 0.9;marker-placement: point;marker-type: ellipse;marker-allow-overlap: true;}';
    }
    else if ( semver.satisfies(mapnik_version, '<2.2.0') ) {
      // 2.1.0 default
      default_style = '#<%= table %>[mapnik-geometry-type=1] {marker-fill: #FF6600;marker-opacity: 1;marker-width: 16;marker-line-color: white;marker-line-width: 3;marker-line-opacity: 0.9;marker-placement: point;marker-type: ellipse;marker-allow-overlap: true;}#<%= table %>[mapnik-geometry-type=2] {line-color:#FF6600; line-width:1; line-opacity: 0.7;}#<%= table %>[mapnik-geometry-type=3] {polygon-fill:#FF6600; polygon-opacity: 0.7; line-opacity:1; line-color: #FFFFFF;}';
    }
    else {
      // 2.2.0+ default
      default_style = '#<%= table %>["mapnik::geometry_type"=1] {marker-fill: #FF6600;marker-opacity: 1;marker-width: 16;marker-line-color: white;marker-line-width: 3;marker-line-opacity: 0.9;marker-placement: point;marker-type: ellipse;marker-allow-overlap: true;}#<%= table %>["mapnik::geometry_type"=2] {line-color:#FF6600; line-width:1; line-opacity: 0.7;}#<%= table %>["mapnik::geometry_type"=3] {polygon-fill:#FF6600; polygon-opacity: 0.7; line-opacity:1; line-color: #FFFFFF;}';
    }

    suiteSetup(function(done) {

      // Check that we start with an empty redis db
      redis_client.keys("*", function(err, matches) {

        if ( err ) { done(err); return; }

        assert.equal(matches.length, 0,
          "redis keys present at setup time on port " +
          ServerOptions.redis.port + ":\n" + matches.join("\n"));

        // Start a server to test external resources
        res_serv = http.createServer( function(request, response) {
            ++res_serv_status.numrequests;
            var filename = __dirname + '/../fixtures/markers' + request.url;
            fs.readFile(filename, "binary", function(err, file) {
              if ( err ) {
                response.writeHead(404, {'Content-Type': 'text/plain'});
                response.write("404 Not Found\n");
              } else {
                response.writeHead(200);
                response.write(file, "binary");
              }
              response.end();
            });
        });
        res_serv.listen(res_serv_port, done);

      });

    });

    ////////////////////////////////////////////////////////////////////
    //
    // GET INVALID
    //
    ////////////////////////////////////////////////////////////////////

    test("get call to server returns 200",  function(done){
        assert.response(server, {
            url: '/',
            method: 'GET'
        },{
            // FIXME: shouldn't this be a 404 ?
            status: 200
        }, function() { done(); } );
    });

    ////////////////////////////////////////////////////////////////////
    //
    // GET VERSION
    //
    ////////////////////////////////////////////////////////////////////

    test("get /version returns versions",  function(done){
        assert.response(server, {
            url: '/version',
            method: 'GET'
        },{
            status: 200
        }, function(res) {
          var parsed = JSON.parse(res.body);
          assert.ok(parsed.hasOwnProperty('windshaft'), "No 'windshaft' version in " + parsed);
          assert.ok(parsed.hasOwnProperty('grainstore'), "No 'grainstore' version in " + parsed);
          assert.ok(parsed.hasOwnProperty('node_mapnik'), "No 'node_mapnik' version in " + parsed);
          assert.ok(parsed.hasOwnProperty('mapnik'), "No 'mapnik' version in " + parsed);
          // TODO: check actual versions ?
          done();
        });
    });

    ////////////////////////////////////////////////////////////////////
    //
    // OPTIONS TILE
    //
    ////////////////////////////////////////////////////////////////////

    test("get'ing options on tile should return CORS headers",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table_3/13/4011/3088.png',
            method: 'OPTIONS'
        },{
            status: 200,
            headers: {
              'Access-Control-Allow-Headers': 'X-Requested-With, X-Prototype-Version, X-CSRF-Token',
              'Access-Control-Allow-Origin': '*'
            }
        }, function() { done(); });
    });

    ////////////////////////////////////////////////////////////////////
    //
    // GET GRID
    //
    ////////////////////////////////////////////////////////////////////

    test("grid jsonp",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?interactivity=name&callback=test',
            method: 'GET'
        },{}, function(res){
            assert.equal(res.statusCode, 200, res.body);
            assert.deepEqual(res.headers['content-type'], 'application/json; charset=utf-8');
            var regexp = '^test\\((.*)\\);$';
            var matches = res.body.match(regexp);
            assert.equal(matches.length, 2, 'Unexpected JSONP response:'  + res.body);
            assert.utfgridEqualsFile(matches[1], './test/fixtures/test_table_13_4011_3088.grid.json', 2, done);
        });
    });

    test("get'ing a json with default style and single interactivity should return a grid",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?interactivity=name',
            method: 'GET'
        },{
            status: 200,
            headers: { 'Content-Type': 'application/json; charset=utf-8' }
        }, function(res){
            var expected_json = {
                "1":{"name":"Hawai"},
                "2":{"name":"El Estocolmo"},
                "3":{"name":"El Rey del Tallarín"},
                "4":{"name":"El Lacón"},
                "5":{"name":"El Pico"}
            };
            assert.deepEqual(JSON.parse(res.body).data, expected_json);
            done();
        });
    });

    test("get'ing a json with default style and no interactivity should return an error",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json',
            method: 'GET'
        },{
        }, function(res){
            assert.equal(res.statusCode, 400);
            assert.deepEqual(JSON.parse(res.body), {error: 'Missing interactivity parameter'});
            done();
        });
    });

    test("get grid jsonp error is returned with 200 status",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?callback=test',
            method: 'GET'
        },{}, function(res){
            assert.equal(res.statusCode, 200);
            assert.ok(res.body.match(/"error":/), 'missing error in response: ' + res.body);
            done();
        });
    });

    // See http://github.com/Vizzuality/Windshaft/issues/50
    test("get'ing a json with no data should return an empty grid",  function(done){
        var sql = querystring.stringify({sql: "SELECT * FROM test_table limit 0"});
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?interactivity=name&' + sql,
            method: 'GET'
        },{
            status: 200,
            headers: { 'Content-Type': 'application/json; charset=utf-8' }
        }, function(res){
            assert.utfgridEqualsFile(res.body, './test/fixtures/test_table_13_4011_3088_empty.grid.json', 2, done);
        });
    });

    // Another test for http://github.com/Vizzuality/Windshaft/issues/50
    // this time with interactivity and cache_buster
    test("get'ing a json with no data but interactivity should return an empty grid",  function(done){
        var sql = querystring.stringify({
          sql: "SELECT * FROM test_table limit 0",
          interactivity: 'cartodb_id',
          cache_buster: 4});
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?' + sql,
            method: 'GET'
        },{
            status: 200,
            headers: { 'Content-Type': 'application/json; charset=utf-8' }
        }, function(res){
            assert.utfgridEqualsFile(res.body, './test/fixtures/test_table_13_4011_3088_empty.grid.json', 2, done);
        });
    });

    // See https://github.com/Vizzuality/Windshaft-cartodb/issues/67
    test("get'ing a solid grid while changing interactivity fields",  function(done){
        var baseurl = '/database/windshaft_test/table/test_big_poly/3/2/2.grid.json?'
        var style211 = "#test_big_poly{polygon-fill:blue;}"; // for solid
        baseurl += querystring.stringify({
          style: style211,
          style_version: '2.1.0'}
        );
        baseurl += '&';
        assert.response(server, {
            url: baseurl + 'interactivity=name',
            method: 'GET'
        },{}, function(res){
            assert.equal(res.statusCode, 200, res.body);
            var expected_data = { "1":{"name":"west"} };
            assert.deepEqual(JSON.parse(res.body).data, expected_data);
            assert.response(server, {
                url: baseurl + 'interactivity=cartodb_id',
                method: 'GET'
            },{}, function(res){
                assert.equal(res.statusCode, 200, res.body);
                var expected_data = { "1":{"cartodb_id":"1"} };
                assert.deepEqual(JSON.parse(res.body).data, expected_data);
                done();
            });
        });
    });

    ////////////////////////////////////////////////////////////////////
    //
    // TEARDOWN
    //
    ////////////////////////////////////////////////////////////////////

    suiteTeardown(function(done) {

      // Close the resources server
      res_serv.close();

      var errors = [];

      // Check that we left the redis db empty
      redis_client.keys("*", function(err, matches) {
          if ( err ) errors.push(err);
          try {
            assert.equal(matches.length, 0, "Left over redis keys:\n" + matches.join("\n"));
          } catch (err) {
            errors.push(err);
          }

          var cachedir = global.environment.millstone.cache_basedir;
          rmdir_recursive_sync(cachedir);

          redis_client.flushall(function() {
            done(errors.length ? new Error(errors) : null);
          });
      });

    });
});

<commit_msg>Remove cors headers in tile test<commit_after>// FLUSHALL Redis before starting

var   assert        = require('../support/assert')
    , tests         = module.exports = {}
    , _             = require('underscore')
    , querystring   = require('querystring')
    , fs            = require('fs')
    , redis         = require('redis')
    , th            = require('../support/test_helper')
    , Step          = require('step')
    , mapnik        = require('mapnik')
    , Windshaft     = require('../../lib/windshaft')
    , ServerOptions = require('../support/server_options')
    , semver        = require('semver')
    , http          = require('http');

function rmdir_recursive_sync(dirname) {
  var files = fs.readdirSync(dirname);
  for (var i=0; i<files.length; ++i) {
    var f = dirname + "/" + files[i];
    var s = fs.lstatSync(f);
    if ( s.isFile() ) {
      fs.unlinkSync(f)
    }
    else rmdir_recursive_sync(f);
  }
}

suite('server', function() {

    ////////////////////////////////////////////////////////////////////
    //
    // SETUP
    //
    ////////////////////////////////////////////////////////////////////

    var server = new Windshaft.Server(ServerOptions);
    server.setMaxListeners(0);
    var redis_client = redis.createClient(ServerOptions.redis.port);
    var res_serv; // resources server
    var res_serv_status = { numrequests:0 }; // status of resources server
    var res_serv_port = 8033; // FIXME: make configurable ?

    var mapnik_version = global.environment.mapnik_version || mapnik.versions.mapnik;

    var default_style;
    if ( semver.satisfies(mapnik_version, '<2.1.0') ) {
      // 2.0.0 default
      default_style = '#<%= table %>{marker-fill: #FF6600;marker-opacity: 1;marker-width: 8;marker-line-color: white;marker-line-width: 3;marker-line-opacity: 0.9;marker-placement: point;marker-type: ellipse;marker-allow-overlap: true;}';
    }
    else if ( semver.satisfies(mapnik_version, '<2.2.0') ) {
      // 2.1.0 default
      default_style = '#<%= table %>[mapnik-geometry-type=1] {marker-fill: #FF6600;marker-opacity: 1;marker-width: 16;marker-line-color: white;marker-line-width: 3;marker-line-opacity: 0.9;marker-placement: point;marker-type: ellipse;marker-allow-overlap: true;}#<%= table %>[mapnik-geometry-type=2] {line-color:#FF6600; line-width:1; line-opacity: 0.7;}#<%= table %>[mapnik-geometry-type=3] {polygon-fill:#FF6600; polygon-opacity: 0.7; line-opacity:1; line-color: #FFFFFF;}';
    }
    else {
      // 2.2.0+ default
      default_style = '#<%= table %>["mapnik::geometry_type"=1] {marker-fill: #FF6600;marker-opacity: 1;marker-width: 16;marker-line-color: white;marker-line-width: 3;marker-line-opacity: 0.9;marker-placement: point;marker-type: ellipse;marker-allow-overlap: true;}#<%= table %>["mapnik::geometry_type"=2] {line-color:#FF6600; line-width:1; line-opacity: 0.7;}#<%= table %>["mapnik::geometry_type"=3] {polygon-fill:#FF6600; polygon-opacity: 0.7; line-opacity:1; line-color: #FFFFFF;}';
    }

    suiteSetup(function(done) {

      // Check that we start with an empty redis db
      redis_client.keys("*", function(err, matches) {

        if ( err ) { done(err); return; }

        assert.equal(matches.length, 0,
          "redis keys present at setup time on port " +
          ServerOptions.redis.port + ":\n" + matches.join("\n"));

        // Start a server to test external resources
        res_serv = http.createServer( function(request, response) {
            ++res_serv_status.numrequests;
            var filename = __dirname + '/../fixtures/markers' + request.url;
            fs.readFile(filename, "binary", function(err, file) {
              if ( err ) {
                response.writeHead(404, {'Content-Type': 'text/plain'});
                response.write("404 Not Found\n");
              } else {
                response.writeHead(200);
                response.write(file, "binary");
              }
              response.end();
            });
        });
        res_serv.listen(res_serv_port, done);

      });

    });

    ////////////////////////////////////////////////////////////////////
    //
    // GET INVALID
    //
    ////////////////////////////////////////////////////////////////////

    test("get call to server returns 200",  function(done){
        assert.response(server, {
            url: '/',
            method: 'GET'
        },{
            // FIXME: shouldn't this be a 404 ?
            status: 200
        }, function() { done(); } );
    });

    ////////////////////////////////////////////////////////////////////
    //
    // GET VERSION
    //
    ////////////////////////////////////////////////////////////////////

    test("get /version returns versions",  function(done){
        assert.response(server, {
            url: '/version',
            method: 'GET'
        },{
            status: 200
        }, function(res) {
          var parsed = JSON.parse(res.body);
          assert.ok(parsed.hasOwnProperty('windshaft'), "No 'windshaft' version in " + parsed);
          assert.ok(parsed.hasOwnProperty('grainstore'), "No 'grainstore' version in " + parsed);
          assert.ok(parsed.hasOwnProperty('node_mapnik'), "No 'node_mapnik' version in " + parsed);
          assert.ok(parsed.hasOwnProperty('mapnik'), "No 'mapnik' version in " + parsed);
          // TODO: check actual versions ?
          done();
        });
    });

    ////////////////////////////////////////////////////////////////////
    //
    // GET GRID
    //
    ////////////////////////////////////////////////////////////////////

    test.skip("grid jsonp",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?interactivity=name&callback=test',
            method: 'GET'
        },{}, function(res){
            assert.equal(res.statusCode, 200, res.body);
            assert.deepEqual(res.headers['content-type'], 'application/json; charset=utf-8');
            var regexp = '^test\\((.*)\\);$';
            var matches = res.body.match(regexp);
            assert.equal(matches.length, 2, 'Unexpected JSONP response:'  + res.body);
            assert.utfgridEqualsFile(matches[1], './test/fixtures/test_table_13_4011_3088.grid.json', 2, done);
        });
    });

    test.skip("get'ing a json with default style and single interactivity should return a grid",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?interactivity=name',
            method: 'GET'
        },{
            status: 200,
            headers: { 'Content-Type': 'application/json; charset=utf-8' }
        }, function(res){
            var expected_json = {
                "1":{"name":"Hawai"},
                "2":{"name":"El Estocolmo"},
                "3":{"name":"El Rey del Tallarín"},
                "4":{"name":"El Lacón"},
                "5":{"name":"El Pico"}
            };
            assert.deepEqual(JSON.parse(res.body).data, expected_json);
            done();
        });
    });

    test.skip("get'ing a json with default style and no interactivity should return an error",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json',
            method: 'GET'
        },{
        }, function(res){
            assert.equal(res.statusCode, 400);
            assert.deepEqual(JSON.parse(res.body), {error: 'Missing interactivity parameter'});
            done();
        });
    });

    test.skip("get grid jsonp error is returned with 200 status",  function(done){
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?callback=test',
            method: 'GET'
        },{}, function(res){
            assert.equal(res.statusCode, 200);
            assert.ok(res.body.match(/"error":/), 'missing error in response: ' + res.body);
            done();
        });
    });

    // See http://github.com/Vizzuality/Windshaft/issues/50
    test.skip("get'ing a json with no data should return an empty grid",  function(done){
        var sql = querystring.stringify({sql: "SELECT * FROM test_table limit 0"});
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?interactivity=name&' + sql,
            method: 'GET'
        },{
            status: 200,
            headers: { 'Content-Type': 'application/json; charset=utf-8' }
        }, function(res){
            assert.utfgridEqualsFile(res.body, './test/fixtures/test_table_13_4011_3088_empty.grid.json', 2, done);
        });
    });

    // Another test for http://github.com/Vizzuality/Windshaft/issues/50
    // this time with interactivity and cache_buster
    test.skip("get'ing a json with no data but interactivity should return an empty grid",  function(done){
        var sql = querystring.stringify({
          sql: "SELECT * FROM test_table limit 0",
          interactivity: 'cartodb_id',
          cache_buster: 4});
        assert.response(server, {
            url: '/database/windshaft_test/table/test_table/13/4011/3088.grid.json?' + sql,
            method: 'GET'
        },{
            status: 200,
            headers: { 'Content-Type': 'application/json; charset=utf-8' }
        }, function(res){
            assert.utfgridEqualsFile(res.body, './test/fixtures/test_table_13_4011_3088_empty.grid.json', 2, done);
        });
    });

    // See https://github.com/Vizzuality/Windshaft-cartodb/issues/67
    test.skip("get'ing a solid grid while changing interactivity fields",  function(done){
        var baseurl = '/database/windshaft_test/table/test_big_poly/3/2/2.grid.json?'
        var style211 = "#test_big_poly{polygon-fill:blue;}"; // for solid
        baseurl += querystring.stringify({
          style: style211,
          style_version: '2.1.0'}
        );
        baseurl += '&';
        assert.response(server, {
            url: baseurl + 'interactivity=name',
            method: 'GET'
        },{}, function(res){
            assert.equal(res.statusCode, 200, res.body);
            var expected_data = { "1":{"name":"west"} };
            assert.deepEqual(JSON.parse(res.body).data, expected_data);
            assert.response(server, {
                url: baseurl + 'interactivity=cartodb_id',
                method: 'GET'
            },{}, function(res){
                assert.equal(res.statusCode, 200, res.body);
                var expected_data = { "1":{"cartodb_id":"1"} };
                assert.deepEqual(JSON.parse(res.body).data, expected_data);
                done();
            });
        });
    });

    ////////////////////////////////////////////////////////////////////
    //
    // TEARDOWN
    //
    ////////////////////////////////////////////////////////////////////

    suiteTeardown(function(done) {

      // Close the resources server
      res_serv.close();

      var errors = [];

      // Check that we left the redis db empty
      redis_client.keys("*", function(err, matches) {
          if ( err ) errors.push(err);
          try {
            assert.equal(matches.length, 0, "Left over redis keys:\n" + matches.join("\n"));
          } catch (err) {
            errors.push(err);
          }

          var cachedir = global.environment.millstone.cache_basedir;
          rmdir_recursive_sync(cachedir);

          redis_client.flushall(function() {
            done(errors.length ? new Error(errors) : null);
          });
      });

    });
});

<|endoftext|>


<commit_before>/*
 * This script rely on
    "sgmap-mes-aides-api": "sgmap/mes-aides-api#replicate",
 */
var config = require('../../backend');
var expect = require('expect');
var _ = require('lodash');

var mongoose = require('mongoose');
var es = require('event-stream');

// Setup mongoose
var AcceptanceTest = mongoose.model('AcceptanceTest');
var LegacySituation = mongoose.model('LegacySituation');
var Situation = mongoose.model('Situation');

var legacyMapping = require('sgmap-mes-aides-api/lib/simulation/openfisca/mapping');

var migration = require('../../backend/lib/migrations/initial');
var mapping = require('../../backend/lib/openfisca/mapping');

function deepDiffRight(left, right) {
  // if they are equals, return undefined
  if (_.isEqual(left, right)) { return; }
  if (_.isNumber(left) && _.isNumber(right) && Math.abs(right-left)<0.000001) { return; }
  // form now on, we can assure that `left` and `right` are not equals (equivalents)

  // if `left` and `right` are primitives, value changed
  // if `left` is a primitive and `right` an object, value has been replaced with an object
  // if `left` is an object and `right` a primitive, value has been replaced with a primitive
  // use `_.copy` to prevent object referrence issues
  if (! _.isObject(left) || ! _.isObject(right)) { return _.cloneDeep(right); }

  // make `result` the same type as `right`
  var result = _.isArray(right) ? [] : {};

  // since we know that both are objects,
  // iterate on `right` to see what changed or what's new in `right`
  _.forEach(right, function (value, key) {
    // recursion
    var diff = deepDiffRight(left[key], right[key]);
    // since the function returns undefined when `left` and `right` are equals,
    // only assing non-undefined values to result
    if (! _.isUndefined(diff)) {
        result[key] = diff;
    }
  });

  //console.log(result, (! result.length), (! Object.keys(result).length));
  if ((! result.length) && (! Object.keys(result).length)) { return; }

  return result;
}

function manageRemoval(model, done) {
    if (model) {
        model.remove(function(err) {
            done(err);
        });
    } else {
        done();
    }
}

function processSituation(situationIdHolder, done) {
    var holderId = situationIdHolder._id;
    var situationId = situationIdHolder.scenario && situationIdHolder.scenario.situationId || (situationIdHolder.id || situationIdHolder._id || '').toString();

    LegacySituation.findById(situationId)
    .then(function(dbLegacySituation) {
        if (! dbLegacySituation) {
            console.log('var Err_holderId_ = \'' + holderId + '\'; // Null');
            return done();
        }
        var dbSituationJSON = JSON.stringify(dbLegacySituation.toObject(), null, 2);
        var situation = dbLegacySituation.toObject();
        migration.persistedSituationPretransformationUpdate(situation);

        var legacyOpenfiscaRequest = legacyMapping.buildOpenFiscaRequest(_.cloneDeep(situation));

        var frontSituation = migration.migratePersistedSituation(situation);
        Situation.create(frontSituation, function(err, dbSituation) {
            if (err) {
                console.log('var Err_holderId_ = \'' + holderId + '\'; // Situation.create ' + frontSituation._id );
                return done(err);
            }

            var generatedSituation = frontSituation;
            var persistedSituation = _.omit(dbSituation.toObject(), '__v');

            var diff01 = deepDiffRight(generatedSituation, persistedSituation);
            var diff02 = deepDiffRight(persistedSituation, generatedSituation);
            if (diff01 || diff02) {
                console.log('var holderId_db_ = \'' + holderId + '\' //  ' + frontSituation._id );
                return manageRemoval(dbSituation, function(err) {
                    var data = Object.assign(err || {},
                    {
                        diffs: [diff01, diff02],
                        situations: [generatedSituation, persistedSituation],
                    });
                    if (err) {
                        done(err);
                    } else {
                        done(data);
                    }
                });
            }

            var newOpenfiscaRequest = mapping.buildOpenFiscaRequest(_.cloneDeep(persistedSituation));
            legacyOpenfiscaRequest.variables.sort();

            var diff1 = deepDiffRight(legacyOpenfiscaRequest, newOpenfiscaRequest);
            var diff2 = deepDiffRight(newOpenfiscaRequest, legacyOpenfiscaRequest);
            if (diff1 || diff2) {
                console.log('var holderId_req_ = \'' + holderId + '\'; // Situation.create ' + frontSituation._id );
                return manageRemoval(dbSituation, function(err) {
                    var data = Object.assign(err || {},
                    {
                        diffs: [diff1, diff2],
                        situations: [newOpenfiscaRequest, legacyOpenfiscaRequest],
                    });
                    if (err) {
                        done(err);
                    } else {
                        done(data);
                    }
                });
            } else {
                console.log('var situation_' + situationId + ' = \'ok\';');
            }

            dbLegacySituation.remove(function(err) {
                done(err);
            });
        });
    })
    .catch(function(err) {
        console.log('var Err_holderId_ = \'' + holderId + '\'; // LegacySituation.findById');
        done(err);
    });
}

function migrateTestSituations() {
    AcceptanceTest.find({
        // _id: '54e4c0bffb31b85d4074fe15', // taux incapacite
        // _id: '54915ffadf990f5b0286cf20', // salaire_imposable were double counted
        // _id: '5422c2d95be58c0200a07585', // Refactor backend - anneeDeReference proxy ressources - missing computed ressources
        // _id: '53d79982f6aa390200a6cd08', // Refactor backend - anneeDeReference proxy ressources
        // _id: '546c9783b7fb60347d0f3b24', // Ids missing in individus
        // _id: '53d21ee5159e330200810b87', // ObjectId versus String comparison issue
        // _id: '53d7b76df6aa390200a6cd5c', // Add firstName
        // _id: '540d69a1aa90150200440ee9', // remove rejected test - Caution will hang
        // _id: '582b06f467831ca264e93def', // Situation 582b06e667831ca264e93de5 set individus.2.specificSituations = []
        // _id: '53d220ce159e330200810b8e', // Persisted situation error
        // _id: '588f2778db011fdc7a230a12', // habite_chez_parents missing in migration mapping
        // _id: '5639eb3ceeab276a0422b307', // reverted interrupted aide_logement
        // _id: '54f07c45246e5054751ccfe3', // situation.logement.isChambre
        // _id: '54d8e0821fe4e8cf448e2bf3', // rfr diff
        // _id: '53d24d0ae40a7902009c3377', // Broken diff function
        // _id: '55b8cbb1d28906b46b50376a', // Uninferable ressourcesYearMoins2Captured = true from ressources
        // _id: '5540d71646bea9643939530f', // Unknown properties autresRevenusTns and caAutresRevenusTns
        // _id: '559e4fe4fa617858013d9a39', // rounding loyer
        // _id: '54e4c0bffb31b85d4074fe15', // tauxIncapacite presence
        // _id: '545a57f8ad58ab46561f56ec', // Ressources moved from individu to group entity
        state: { '$nin': [
            'unclaimed',
            'rejected'
        ]}
    }, {}, { sort: '_id' }, processSituations);
}

function migrateRecentSituations() {
    LegacySituation.find({
        _id: { '$nin': [
            '5999dc194866593317f4b006',
            '599983ae4866593317f44818',
            '599971c44866593317f43044', // ASI partially interrupted, new version has the correct behavior
            '599961ef4866593317f41fb2', // aide_logement partially interrupted, new version has the correct behavior
            '59991f1e4866593317f3e9d4', // ass partially interrupted, new version has the correct behavior
            '599877fd4866593317f3b120', // aide_logement partially interrupted, new version has the correct behavior
            '599808db4866593317f337e8', // aide_logement and paje_base partially interrupted, new version has the correct behavior
            '5998001e4866593317f32e31', // aide_logement partially interrupted, new version has the correct behavior
            '5997642e4866593317f2f2e5', // aide_logement partially interrupted, new version has the correct behavior
            '59971f104866593317f2b3de' // paje_clca partially interrupted, new version has the correct behavior
            ],
            '$lte': '59971f104866593317f2b3de',
            //'$in': ['5998d6d04866593317f3e45f']
        }, // Dodgy situation ?
        // _id: '5998d6d04866593317f3e45f', //
        // _id: '599a898d4866593317f4fd61',
        // _id: '5999fc6e4866593317f4cb26', // legacy API bug: 'Fix not interrupted ressources for famille'
    }, {}, {
        limit: 10000,
        sort: { dateDeValeur: -1 },
    }, processSituations);
}

/*LegacySituation.find({
    status: 'test',
    //_id: '53d78cf4f6aa390200a6ccf9',
}, {}, {
    limit: 1000,
    sort: { dateDeValeur: -1 },
})
//*/
AcceptanceTest.find({
    state: { '$nin': [
        'unclaimed',
        'rejected'
    ]}
}, {}, { sort: '_id' })
.stream()
.pipe(es.map(processSituation))
.on('end', function() {
    console.log('Terminé');
    process.exit();
})
.on('error', function(err) {
    console.log(JSON.stringify(err, null, 2));
    process.exit();
})
.resume();
<commit_msg>Revert "Migrate situations used in tests"<commit_after>/*
 * This script rely on
    "sgmap-mes-aides-api": "sgmap/mes-aides-api#replicate",
 */
var config = require('../../backend');
var expect = require('expect');
var _ = require('lodash');

var mongoose = require('mongoose');
var es = require('event-stream');

// Setup mongoose
var AcceptanceTest = mongoose.model('AcceptanceTest');
var LegacySituation = mongoose.model('LegacySituation');
var Situation = mongoose.model('Situation');

var legacyMapping = require('sgmap-mes-aides-api/lib/simulation/openfisca/mapping');

var migration = require('../../backend/lib/migrations/initial');
var mapping = require('../../backend/lib/openfisca/mapping');

function deepDiffRight(left, right) {
  // if they are equals, return undefined
  if (_.isEqual(left, right)) { return; }
  if (_.isNumber(left) && _.isNumber(right) && Math.abs(right-left)<0.000001) { return; }
  // form now on, we can assure that `left` and `right` are not equals (equivalents)

  // if `left` and `right` are primitives, value changed
  // if `left` is a primitive and `right` an object, value has been replaced with an object
  // if `left` is an object and `right` a primitive, value has been replaced with a primitive
  // use `_.copy` to prevent object referrence issues
  if (! _.isObject(left) || ! _.isObject(right)) { return _.cloneDeep(right); }

  // make `result` the same type as `right`
  var result = _.isArray(right) ? [] : {};

  // since we know that both are objects,
  // iterate on `right` to see what changed or what's new in `right`
  _.forEach(right, function (value, key) {
    // recursion
    var diff = deepDiffRight(left[key], right[key]);
    // since the function returns undefined when `left` and `right` are equals,
    // only assing non-undefined values to result
    if (! _.isUndefined(diff)) {
        result[key] = diff;
    }
  });

  //console.log(result, (! result.length), (! Object.keys(result).length));
  if ((! result.length) && (! Object.keys(result).length)) { return; }

  return result;
}

var shouldFailOnError = false;

function processSituation(test, done) {

    function manageRemoval(model, done) {
        if (model) {
            model.remove(function(err) {
                done(err);
            });
        } else {
            done();
        }
    }

    var testId = test._id;
    var situationId = test.scenario && test.scenario.situationId || (test.id || test._id || '').toString();

    LegacySituation.findById(situationId)
    .then(function(dbLegacySituation) {
        if (! dbLegacySituation) {
            console.log('var Err_testID_ = \'' + testId + '\'; // Null');
            return done();
        }
        var dbSituationJSON = JSON.stringify(dbLegacySituation.toObject(), null, 2);
        var situation = dbLegacySituation.toObject();
        migration.persistedSituationPretransformationUpdate(situation);

        var legacyOpenfiscaRequest = legacyMapping.buildOpenFiscaRequest(_.cloneDeep(situation));

        var frontSituation = migration.migratePersistedSituation(situation);
        Situation.create(frontSituation, function(err, dbSituation) {
            if (err) {
                console.log('var Err_testID_ = \'' + testId + '\'; // Situation.create ' + frontSituation._id );
                return done(err);
            }

            var generatedSituation = frontSituation;
            var persistedSituation = _.omit(dbSituation.toObject(), '__v');

            var diff01 = deepDiffRight(generatedSituation, persistedSituation);
            var diff02 = deepDiffRight(persistedSituation, generatedSituation);
            if (diff01 || diff02) {
                console.log('var testID_db_ = \'' + testId + '\' //  ' + frontSituation._id );
                return manageRemoval(dbSituation, function(err) {
                    var data = Object.assign(err || {},
                    {
                        diffs: [diff01, diff02],
                        situations: [generatedSituation, persistedSituation],
                    });
                    if (err) {
                        done(err);
                    } else {
                        done(data);
                    }
                });
            }

            var newOpenfiscaRequest = mapping.buildOpenFiscaRequest(_.cloneDeep(persistedSituation));
            legacyOpenfiscaRequest.variables.sort();

            var diff1 = deepDiffRight(legacyOpenfiscaRequest, newOpenfiscaRequest);
            var diff2 = deepDiffRight(newOpenfiscaRequest, legacyOpenfiscaRequest);
            if (diff1 || diff2) {
                console.log('var testID_req_ = \'' + testId + '\'; // Situation.create ' + frontSituation._id );
                return manageRemoval(dbSituation, function(err) {
                    var data = Object.assign(err || {},
                    {
                        diffs: [diff1, diff2],
                        situations: [newOpenfiscaRequest, legacyOpenfiscaRequest],
                    });
                    if (err) {
                        done(err);
                    } else {
                        done(data);
                    }
                });
            } else {
                console.log('var situation_' + situationId + ' = \'ok\';');
            }

            return manageRemoval(dbLegacySituation, done);
        });
    }).catch(function(err) {
        console.log('var Err_testID_ = \'' + testId + '\'; // LegacySituation.findById');
        done(err);
    });
}

function migrateTestSituations() {
    AcceptanceTest.find({
        // _id: '54e4c0bffb31b85d4074fe15', // taux incapacite
        // _id: '54915ffadf990f5b0286cf20', // salaire_imposable were double counted
        // _id: '5422c2d95be58c0200a07585', // Refactor backend - anneeDeReference proxy ressources - missing computed ressources
        // _id: '53d79982f6aa390200a6cd08', // Refactor backend - anneeDeReference proxy ressources
        // _id: '546c9783b7fb60347d0f3b24', // Ids missing in individus
        // _id: '53d21ee5159e330200810b87', // ObjectId versus String comparison issue
        // _id: '53d7b76df6aa390200a6cd5c', // Add firstName
        // _id: '540d69a1aa90150200440ee9', // remove rejected test - Caution will hang
        // _id: '582b06f467831ca264e93def', // Situation 582b06e667831ca264e93de5 set individus.2.specificSituations = []
        // _id: '53d220ce159e330200810b8e', // Persisted situation error
        // _id: '588f2778db011fdc7a230a12', // habite_chez_parents missing in migration mapping
        // _id: '5639eb3ceeab276a0422b307', // reverted interrupted aide_logement
        // _id: '54f07c45246e5054751ccfe3', // situation.logement.isChambre
        // _id: '54d8e0821fe4e8cf448e2bf3', // rfr diff
        // _id: '53d24d0ae40a7902009c3377', // Broken diff function
        // _id: '55b8cbb1d28906b46b50376a', // Uninferable ressourcesYearMoins2Captured = true from ressources
        // _id: '5540d71646bea9643939530f', // Unknown properties autresRevenusTns and caAutresRevenusTns
        // _id: '559e4fe4fa617858013d9a39', // rounding loyer
        // _id: '54e4c0bffb31b85d4074fe15', // tauxIncapacite presence
        // _id: '545a57f8ad58ab46561f56ec', // Ressources moved from individu to group entity
        state: { '$nin': [
            'unclaimed',
            'rejected'
        ]}
    }, {}, { sort: '_id' }, processSituations);
}

function migrateRecentSituations() {
    LegacySituation.find({
        _id: { '$nin': [
            '5999dc194866593317f4b006',
            '599983ae4866593317f44818',
            '599971c44866593317f43044', // ASI partially interrupted, new version has the correct behavior
            '599961ef4866593317f41fb2', // aide_logement partially interrupted, new version has the correct behavior
            '59991f1e4866593317f3e9d4', // ass partially interrupted, new version has the correct behavior
            '599877fd4866593317f3b120', // aide_logement partially interrupted, new version has the correct behavior
            '599808db4866593317f337e8', // aide_logement and paje_base partially interrupted, new version has the correct behavior
            '5998001e4866593317f32e31', // aide_logement partially interrupted, new version has the correct behavior
            '5997642e4866593317f2f2e5', // aide_logement partially interrupted, new version has the correct behavior
            '59971f104866593317f2b3de' // paje_clca partially interrupted, new version has the correct behavior
            ],
            '$lte': '59971f104866593317f2b3de',
            //'$in': ['5998d6d04866593317f3e45f']
        }, // Dodgy situation ?
        // _id: '5998d6d04866593317f3e45f', //
        // _id: '599a898d4866593317f4fd61',
        // _id: '5999fc6e4866593317f4cb26', // legacy API bug: 'Fix not interrupted ressources for famille'
    }, {}, {
        limit: 10000,
        sort: { dateDeValeur: -1 },
    }, processSituations);
}

LegacySituation.find({
    status: 'test',
    //_id: '53d78cf4f6aa390200a6ccf9',
}, {}, {
    sort: { dateDeValeur: -1 },
}).stream()
.pipe(es.map(processSituation))
.on('end', function() {
    console.log('Terminé');
    process.exit();
})
.on('error', function(err) {
    console.log(JSON.stringify(err, null, 2));
    process.exit();
})
.resume();
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import {Motion, spring} from 'react-motion';
import Item from './item'
import Button from './button'

export default class Menu extends Component{
  constructor(props) {
    super(props);
    this.state = {itemNumber: 1, status: "idle"};
  }

  open() {
    if(this.state.action === "open") return;
    this._open();
  }

  _open() {
    this.setState({action: "open"});
    this.refs.button.start();
    this.refs["item"+this.state.itemNumber].start();
  }

  close() {
    if(this.state.action !== "open") return;
    this._close();
  }

  _close() {
    this.setState({action: "close"});
    this.refs.button.reverse();
    for(let i = this.state.itemNumber-1; i > 0; i-=1) {
      this.refs["item"+i].reverse();
    }
  }

  _onOpenEnd(name) {
    if(this.state.action !== "open") return;
    if (this.state.itemNumber < this.props.children.length) {
      this.refs["item"+this.state.itemNumber].start();
      return this.setState({itemNumber: this.state.itemNumber+1});
    }
    if (name === `item${this.props.children.length-1}`)
      if(this.props.onOpen) this.props.onOpen(this.props.name);
  }

  _onCloseEnd(name) {
    if(this.state.action === "open") return;
    if (this.state.itemNumber > 1) {
      if (name === 'item1')
        if(this.props.onClose) this.props.onClose(this.props.name);
      this.setState({itemNumber: this.state.itemNumber-1});
    }
  }

  _onClick() {
    if(this.state.action === "open") this._close();
    else this._open();
  }

  _getItems() {
    const {x, y, width, height, direction, distance, customStyle} = this.props;
    let button;
    let children;
    [button, ...children] = this.props.children;
    let items = [
      <Button
        ref="button"
        onClick={this._onClick.bind(this)}
        customStyle={customStyle}
        width={width}
        height={height}
        x={x}
        y={y}
        key={"button"} >
        {button.props.children}
      </Button>
    ];
    for(let i = 0; i < this.state.itemNumber && i < children.length; i+=1) {
      items.push(
        <Item
          direction={this.props.direction}
          key={i}
          ref={`item${i+1}`}
          name ={`item${i+1}`}
          onOpenAnimationEnd={this._onOpenEnd.bind(this)}
          onCloseAnimationEnd={this._onCloseEnd.bind(this)}
          customStyle={customStyle}
          width={width}
          height={height}
          x={x}
          y={y}
          distance={distance}
          x={direction === "horizontal" ? i*distance + x : x}
          y={direction === "vertical" ? i*distance + y : y} >
          {children[i].props.children}
        </Item>
      );
    }
    return items;
  }

  render() {
    return (

        {this._getItems()}

    );
  }
}

Menu.propTypes = {
  x: PropTypes.number.isRequired,
  y: PropTypes.number.isRequired,
  direction: PropTypes.string.isRequired,
  distance: PropTypes.number.isRequired,
  width: PropTypes.number.isRequired,
  height: PropTypes.number.isRequired,
  onClick: PropTypes.func,
  onAnimationEnd: PropTypes.func,
  onCloseAnimationEnd: PropTypes.func,
  customStyle: PropTypes.object,
  customClass: PropTypes.string
}
<commit_msg>[Bugfix] Remove duplicate props<commit_after>import React, {Component, PropTypes} from 'react';
import {Motion, spring} from 'react-motion';
import Item from './item'
import Button from './button'

export default class Menu extends Component{
  constructor(props) {
    super(props);
    this.state = {itemNumber: 1, status: "idle"};
  }

  open() {
    if(this.state.action === "open") return;
    this._open();
  }

  _open() {
    this.setState({action: "open"});
    this.refs.button.start();
    this.refs["item"+this.state.itemNumber].start();
  }

  close() {
    if(this.state.action !== "open") return;
    this._close();
  }

  _close() {
    this.setState({action: "close"});
    this.refs.button.reverse();
    for(let i = this.state.itemNumber-1; i > 0; i-=1) {
      this.refs["item"+i].reverse();
    }
  }

  _onOpenEnd(name) {
    if(this.state.action !== "open") return;
    if (this.state.itemNumber < this.props.children.length) {
      this.refs["item"+this.state.itemNumber].start();
      return this.setState({itemNumber: this.state.itemNumber+1});
    }
    if (name === `item${this.props.children.length-1}`)
      if(this.props.onOpen) this.props.onOpen(this.props.name);
  }

  _onCloseEnd(name) {
    if(this.state.action === "open") return;
    if (this.state.itemNumber > 1) {
      if (name === 'item1')
        if(this.props.onClose) this.props.onClose(this.props.name);
      this.setState({itemNumber: this.state.itemNumber-1});
    }
  }

  _onClick() {
    if(this.state.action === "open") this._close();
    else this._open();
  }

  _getItems() {
    const {x, y, width, height, direction, distance, customStyle} = this.props;
    let button;
    let children;
    [button, ...children] = this.props.children;
    let items = [
      <Button
        ref="button"
        onClick={this._onClick.bind(this)}
        customStyle={customStyle}
        width={width}
        height={height}
        x={x}
        y={y}
        key={"button"} >
        {button.props.children}
      </Button>
    ];
    for(let i = 0; i < this.state.itemNumber && i < children.length; i+=1) {
      items.push(
        <Item
          direction={this.props.direction}
          key={i}
          ref={`item${i+1}`}
          name ={`item${i+1}`}
          onOpenAnimationEnd={this._onOpenEnd.bind(this)}
          onCloseAnimationEnd={this._onCloseEnd.bind(this)}
          customStyle={customStyle}
          width={width}
          height={height}
          distance={distance}
          x={direction === "horizontal" ? i*distance + x : x}
          y={direction === "vertical" ? i*distance + y : y} >
          {children[i].props.children}
        </Item>
      );
    }
    return items;
  }

  render() {
    return (

        {this._getItems()}

    );
  }
}

Menu.propTypes = {
  x: PropTypes.number.isRequired,
  y: PropTypes.number.isRequired,
  direction: PropTypes.string.isRequired,
  distance: PropTypes.number.isRequired,
  width: PropTypes.number.isRequired,
  height: PropTypes.number.isRequired,
  onClick: PropTypes.func,
  onAnimationEnd: PropTypes.func,
  onCloseAnimationEnd: PropTypes.func,
  customStyle: PropTypes.object,
  customClass: PropTypes.string
}
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdirp')
var _ = require('underscore')

var generateFonts = require('./generateFonts')
var renderCss = require('./renderCss')
var renderHtml = require('./renderHtml')

var TEMPLATES_DIR = path.join(__dirname, '..', 'templates')
var TEMPLATES = {
	css: path.join(TEMPLATES_DIR, 'css.hbs'),
	scss: path.join(TEMPLATES_DIR, 'scss.hbs'),
	html: path.join(TEMPLATES_DIR, 'html.hbs')
}

var DEFAULT_TEMPLATE_OPTIONS = {
	baseSelector: '.icon',
	classPrefix: 'icon-'
}

var DEFAULT_OPTIONS = {
	writeFiles: true,
	fontName: 'iconfont',
	css: true,
	cssTemplate: TEMPLATES.css,
	html: false,
	htmlTemplate: TEMPLATES.html,
	types: ['eot', 'woff'],
	order: ['eot', 'woff', 'ttf', 'svg'],
	rename: function(file) {
		return path.basename(file, path.extname(file))
	},
	formatOptions: {},
	/**
	 * Unicode Private Use Area start.
	 * http://en.wikipedia.org/wiki/Private_Use_(Unicode)
	 */
	startCodepoint: 0xF101,
	normalize: true
}

var webfont = function(options, done) {
	if (options.cssFontsPath) {
		console.log('Option "cssFontsPath" is deprecated. Use "cssFontsUrl" instead.')
		options.cssFontsUrl = options.cssFontsPath
	}

	options = _.extend({}, DEFAULT_OPTIONS, options)

	if (options.dest === undefined) return done(new Error('"options.dest" is undefined.'))
	if (options.files === undefined) return done(new Error('"options.files" is undefined.'))
	if (!options.files.length) return done(new Error('"options.files" is empty.'))

	// We modify codepoints later, so we can't use same object from default options.
	if (options.codepoints === undefined) options.codepoints = {}

	options.names = _.map(options.files, options.rename)
	if (options.cssDest === undefined) {
		options.cssDest = path.join(options.dest, options.fontName + '.css')
	}
	if (options.htmlDest === undefined) {
		options.htmlDest = path.join(options.dest, options.fontName + '.html')
	}

	options.templateOptions = _.extend({}, DEFAULT_TEMPLATE_OPTIONS, options.templateOptions)

	// Generates codepoints starting from `options.startCodepoint`,
	// skipping codepoints explicitly specified in `options.codepoints`
	var currentCodepoint = options.startCodepoint
	var codepointsValues = _.values(options.codepoints)
	function getNextCodepoint() {
		while (_.contains(codepointsValues, currentCodepoint)) {
			currentCodepoint++
		}
		var res = currentCodepoint
		currentCodepoint++
		return res
	}
	_.each(options.names, function(name) {
		if (!options.codepoints[name]) {
			options.codepoints[name] = getNextCodepoint()
		}
	})

	// TODO output
	generateFonts(options)
		.then(function(result) {
			if (options.writeFiles) writeResult(result, options)

			result.generateCss = function(urls) {
				return renderCss(options, urls)
			}
			done(null, result)
		})
		.catch(function(err) { done(err) })
}

function writeFile(content, dest) {
	mkdirp.sync(path.dirname(dest))
	fs.writeFileSync(dest, content)
}

function writeResult(fonts, options) {
	_.each(fonts, function(content, type) {
		var filepath = path.join(options.dest, options.fontName + '.' + type)
		writeFile(content, filepath)
	})
	if (options.css) {
		var css = renderCss(options)
		writeFile(css, options.cssDest)
	}
	if (options.html) {
		var html = renderHtml(options)
		writeFile(html, options.htmlDest)
	}
}

webfont.templates = TEMPLATES

module.exports = webfont
<commit_msg>Added warning for using deprecated template option.<commit_after>var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdirp')
var _ = require('underscore')

var generateFonts = require('./generateFonts')
var renderCss = require('./renderCss')
var renderHtml = require('./renderHtml')

var TEMPLATES_DIR = path.join(__dirname, '..', 'templates')
var TEMPLATES = {
	css: path.join(TEMPLATES_DIR, 'css.hbs'),
	scss: path.join(TEMPLATES_DIR, 'scss.hbs'),
	html: path.join(TEMPLATES_DIR, 'html.hbs')
}

var DEFAULT_TEMPLATE_OPTIONS = {
	baseSelector: '.icon',
	classPrefix: 'icon-'
}

var DEFAULT_OPTIONS = {
	writeFiles: true,
	fontName: 'iconfont',
	css: true,
	cssTemplate: TEMPLATES.css,
	html: false,
	htmlTemplate: TEMPLATES.html,
	types: ['eot', 'woff'],
	order: ['eot', 'woff', 'ttf', 'svg'],
	rename: function(file) {
		return path.basename(file, path.extname(file))
	},
	formatOptions: {},
	/**
	 * Unicode Private Use Area start.
	 * http://en.wikipedia.org/wiki/Private_Use_(Unicode)
	 */
	startCodepoint: 0xF101,
	normalize: true
}

var webfont = function(options, done) {
	if (options.cssFontsPath) {
		console.log('Option "cssFontsPath" is deprecated. Use "cssFontsUrl" instead.')
		options.cssFontsUrl = options.cssFontsPath
	}

	options = _.extend({}, DEFAULT_OPTIONS, options)

	if (options.dest === undefined) return done(new Error('"options.dest" is undefined.'))
	if (options.files === undefined) return done(new Error('"options.files" is undefined.'))
	if (!options.files.length) return done(new Error('"options.files" is empty.'))

	// We modify codepoints later, so we can't use same object from default options.
	if (options.codepoints === undefined) options.codepoints = {}

	options.names = _.map(options.files, options.rename)
	if (options.cssDest === undefined) {
		options.cssDest = path.join(options.dest, options.fontName + '.css')
	}
	if (options.htmlDest === undefined) {
		options.htmlDest = path.join(options.dest, options.fontName + '.html')
	}

	// Warn about using deprecated template options.
	for(var key in options.templateOptions) {
		var value = options.templateOptions[key];
		if(key === "baseClass") {
			console.warn("[webfont-generator] Using deprecated templateOptions 'baseClass'. Use 'baseSelector' instead.");
			options.templateOptions.baseSelector = "." + value;
			delete options.templateOptions.baseClass;
			break;
		}
	}

	options.templateOptions = _.extend({}, DEFAULT_TEMPLATE_OPTIONS, options.templateOptions)

	// Generates codepoints starting from `options.startCodepoint`,
	// skipping codepoints explicitly specified in `options.codepoints`
	var currentCodepoint = options.startCodepoint
	var codepointsValues = _.values(options.codepoints)
	function getNextCodepoint() {
		while (_.contains(codepointsValues, currentCodepoint)) {
			currentCodepoint++
		}
		var res = currentCodepoint
		currentCodepoint++
		return res
	}
	_.each(options.names, function(name) {
		if (!options.codepoints[name]) {
			options.codepoints[name] = getNextCodepoint()
		}
	})

	// TODO output
	generateFonts(options)
		.then(function(result) {
			if (options.writeFiles) writeResult(result, options)

			result.generateCss = function(urls) {
				return renderCss(options, urls)
			}
			done(null, result)
		})
		.catch(function(err) { done(err) })
}

function writeFile(content, dest) {
	mkdirp.sync(path.dirname(dest))
	fs.writeFileSync(dest, content)
}

function writeResult(fonts, options) {
	_.each(fonts, function(content, type) {
		var filepath = path.join(options.dest, options.fontName + '.' + type)
		writeFile(content, filepath)
	})
	if (options.css) {
		var css = renderCss(options)
		writeFile(css, options.cssDest)
	}
	if (options.html) {
		var html = renderHtml(options)
		writeFile(html, options.htmlDest)
	}
}

webfont.templates = TEMPLATES

module.exports = webfont
<|endoftext|>


<commit_before>var m = require("../../")

test("autorun 1", function(done) {
    var _fired = 0
    var _result = null
    var _cCalcs = 0
    var to = setTimeout

    function check(fired, cCalcs, result) {
        expect(_fired).toBe(fired)
        expect(_cCalcs).toBe(cCalcs)
        if (fired) expect(_result).toBe(result)
        _fired = 0
        _cCalcs = 0
    }

    var a = m.observable(2)
    var b = m.observable(3)
    var c = m.computed(function() {
        _cCalcs++
        return a.get() * b.get()
    })
    var d = m.observable(1)
    var autorun = function() {
        _fired++
        _result = d.get() > 0 ? a.get() * c.get() : d.get()
    }
    var disp = m.autorunAsync(autorun, 20)

    check(0, 0, null)
    disp()
    to(function() {
        check(0, 0, null)
        disp = m.autorunAsync(autorun, 20)

        to(function() {
            check(1, 1, 12)
            a.set(4)
            b.set(5)
            a.set(6)
            check(0, 0, null) // a change triggered async rerun, compute will trigger after 20ms of async timeout
            to(function() {
                check(1, 1, 180)
                d.set(2)

                to(function() {
                    check(1, 0, 180)

                    d.set(-2)
                    to(function() {
                        check(1, 0, -2)

                        a.set(7)
                        to(function() {
                            check(0, 0, 0) // change a has no effect

                            a.set(4)
                            b.set(2)
                            d.set(2)

                            to(function() {
                                check(1, 1, 32)

                                disp()
                                a.set(1)
                                b.set(2)
                                d.set(4)
                                to(function() {
                                    check(0, 0, 0)
                                    done()
                                }, 30)
                            }, 30)
                        }, 30)
                    }, 30)
                }, 30)
            }, 30)
        }, 30)
    }, 30)
})

test("autorun should not result in loop", function(done) {
    var i = 0
    var a = m.observable({
        x: i
    })

    var autoRunsCalled = 0
    var d = m.autorunAsync(
        "named async",
        function() {
            autoRunsCalled++
            a.x = ++i
            setTimeout(function() {
                a.x = ++i
            }, 10)
        },
        10
    )

    setTimeout(function() {
        expect(autoRunsCalled).toBe(1)
        done()

        expect(d.$mobx.name).toBe("named async")
        d()
    }, 100)
})

test("autorunAsync passes Reaction as an argument to view function", function(done) {
    var a = m.observable(1)

    var autoRunsCalled = 0

    m.autorunAsync(r => {
        expect(typeof r.dispose).toBe("function")
        autoRunsCalled++
        if (a.get() === "pleaseDispose") r.dispose()
    }, 10)

    setTimeout(() => a.set(2), 250)
    setTimeout(() => a.set("pleaseDispose"), 400)
    setTimeout(() => a.set(3), 550)
    setTimeout(() => a.set(4), 700)

    setTimeout(function() {
        expect(autoRunsCalled).toBe(3)
        done()
    }, 1000)
})

test("autorunAsync warns when passed an action", function() {
    var action = m.action(() => {})
    expect.assertions(1)
    expect(() => m.autorunAsync(action)).toThrowError(/attempted to pass an action to autorunAsync/)
})
<commit_msg>Add unit test for autorunAsync scheduling function<commit_after>var m = require("../../")

test("autorun 1", function(done) {
    var _fired = 0
    var _result = null
    var _cCalcs = 0
    var to = setTimeout

    function check(fired, cCalcs, result) {
        expect(_fired).toBe(fired)
        expect(_cCalcs).toBe(cCalcs)
        if (fired) expect(_result).toBe(result)
        _fired = 0
        _cCalcs = 0
    }

    var a = m.observable(2)
    var b = m.observable(3)
    var c = m.computed(function() {
        _cCalcs++
        return a.get() * b.get()
    })
    var d = m.observable(1)
    var autorun = function() {
        _fired++
        _result = d.get() > 0 ? a.get() * c.get() : d.get()
    }
    var disp = m.autorunAsync(autorun, 20)

    check(0, 0, null)
    disp()
    to(function() {
        check(0, 0, null)
        disp = m.autorunAsync(autorun, 20)

        to(function() {
            check(1, 1, 12)
            a.set(4)
            b.set(5)
            a.set(6)
            check(0, 0, null) // a change triggered async rerun, compute will trigger after 20ms of async timeout
            to(function() {
                check(1, 1, 180)
                d.set(2)

                to(function() {
                    check(1, 0, 180)

                    d.set(-2)
                    to(function() {
                        check(1, 0, -2)

                        a.set(7)
                        to(function() {
                            check(0, 0, 0) // change a has no effect

                            a.set(4)
                            b.set(2)
                            d.set(2)

                            to(function() {
                                check(1, 1, 32)

                                disp()
                                a.set(1)
                                b.set(2)
                                d.set(4)
                                to(function() {
                                    check(0, 0, 0)
                                    done()
                                }, 30)
                            }, 30)
                        }, 30)
                    }, 30)
                }, 30)
            }, 30)
        }, 30)
    }, 30)
})

test("autorun should not result in loop", function(done) {
    var i = 0
    var a = m.observable({
        x: i
    })

    var autoRunsCalled = 0
    var d = m.autorunAsync(
        "named async",
        function() {
            autoRunsCalled++
            a.x = ++i
            setTimeout(function() {
                a.x = ++i
            }, 10)
        },
        10
    )

    setTimeout(function() {
        expect(autoRunsCalled).toBe(1)
        done()

        expect(d.$mobx.name).toBe("named async")
        d()
    }, 100)
})

test("autorunAsync passes Reaction as an argument to view function", function(done) {
    var a = m.observable(1)

    var autoRunsCalled = 0

    m.autorunAsync(r => {
        expect(typeof r.dispose).toBe("function")
        autoRunsCalled++
        if (a.get() === "pleaseDispose") r.dispose()
    }, 10)

    setTimeout(() => a.set(2), 250)
    setTimeout(() => a.set("pleaseDispose"), 400)
    setTimeout(() => a.set(3), 550)
    setTimeout(() => a.set(4), 700)

    setTimeout(function() {
        expect(autoRunsCalled).toBe(3)
        done()
    }, 1000)
})

test("autorunAsync accepts a scheduling function", function(done) {

    var a = m.observable({
        x: 0,
        y: 1,
    })

    var autoRunsCalled = 0
    var schedulingsCalled = 0

    m.autorunAsync(function(r) {
        autoRunsCalled++
        expect(a.y).toBe(a.x + 1)

        if (a.x < 10) {
            // Queue the two actions separately, if this was autorun it would fail
            setTimeout(function() { a.x = a.x + 1 }, 0)
            setTimeout(function() { a.y = a.y + 1 }, 0)
        }
    }, function (fn) {
        schedulingsCalled++
        setTimeout(fn, 0)
    })

    setTimeout(function() {
        expect(autoRunsCalled).toBe(11)
        expect(schedulingsCalled).toBe(11)
        done()
    }, 100)
})

test("autorunAsync warns when passed an action", function() {
    var action = m.action(() => {})
    expect.assertions(1)
    expect(() => m.autorunAsync(action)).toThrowError(/attempted to pass an action to autorunAsync/)
})
<|endoftext|>


<commit_before>/**
 * @class CM_FormField_Integer
 * @extends CM_FormField_Abstract
 */
var CM_FormField_Integer = CM_FormField_Abstract.extend({
	_class: 'CM_FormField_Integer',

	ready: function() {
		var field = this;
		var $slider = this.$(".slider");
		var $input = this.$("input");
		var input = $input.get(0);
		$slider.slider({
			value: $input.val(),
			min: field.getOption("min"),
			max: field.getOption("max"),
			step: field.getOption("step"),
			slide: function(event, ui) {
				var value = ui.value + 0;
				if (value != input.value) {
					input.value = value;
				}
				$(this).children(".ui-slider-handle").text(value);
			},
			change: function(event, ui) {
				var value = ui.value + 0;
				if (value != input.value) {
					input.value = value;
				}
				$(this).children(".ui-slider-handle").text(value);
			}
		});
		$slider.children(".ui-slider-handle").text($input.val());
		$input.watch("disabled", function(propName, oldVal, newVal) {
			$slider.slider("option", "disabled", newVal);
			return newVal;
		});
		$input.watch("value", function(propName, oldVal, newVal) {
			if (newVal != $slider.slider("option", "value")) {
				$slider.slider("option", "value", newVal);
			}
			field.trigger('change');
			return newVal;
		});

		this.on('destruct', function() {
			$input.unwatch('disabled');
			$input.unwatch('value');
		});
	}
});
<commit_msg>removed returns removed if() checks<commit_after>/**
 * @class CM_FormField_Integer
 * @extends CM_FormField_Abstract
 */
var CM_FormField_Integer = CM_FormField_Abstract.extend({
	_class: 'CM_FormField_Integer',

	ready: function() {
		var field = this;
		var $slider = this.$(".slider");
		var $input = this.$("input");
		var input = $input.get(0);
		$slider.slider({
			value: $input.val(),
			min: field.getOption("min"),
			max: field.getOption("max"),
			step: field.getOption("step"),
			slide: function(event, ui) {
				var value = ui.value + 0;
				input.value = value;
				$(this).children(".ui-slider-handle").text(value);
			},
			change: function(event, ui) {
				var value = ui.value + 0;
				input.value = value;
				$(this).children(".ui-slider-handle").text(value);
			}
		});
		$slider.children(".ui-slider-handle").text($input.val());

		$input.watch("disabled", function(propName, oldVal, newVal) {
			$slider.slider("option", "disabled", newVal);
		});

		$input.watch("value", function(propName, oldVal, newVal) {
			$slider.slider("option", "value", newVal);
			field.trigger('change');
		});

		this.on('destruct', function() {
			$input.unwatch('disabled');
			$input.unwatch('value');
		});
	}
});
<|endoftext|>


<commit_before>/**
 * react-native-openanything
 */
import { Call } from './call';
import { Email } from './email';
import { Text } from './text';
import { Web } from './web';
import { Map } from './map';
import { Launch, Supported, Open } from './launcher';
import { Twitter } from './twitter'
import { Youtube } from './youtube';
import { Facetime } from './facetime';
import { Facebook } from './facebook';
import { Instagram, InstagramMedia, InstagramApp, InstagramCamera, InstagramTag, InstagramLocation } from './instagram';
import { Pdf } from './pdf';

export { Call, Email, Text, Web, Launch, Supported, Open, Map, Twitter, Youtube, Facetime, Facebook, Instagram, InstagramMedia, InstagramApp, InstagramCamera, InstagramTag, InstagramLocation, Pdf }
<commit_msg>undo changes<commit_after>/**
 * react-native-openanything
 */
import {Call} from './call';
import {Email} from './email';
import {Text} from './text';
import {Web} from './web';
import {Map} from './map';
import {Launch, Supported, Open} from './launcher';
import {Twitter} from './twitter'
import {Youtube} from './youtube';
import {Facetime} from './facetime';
import {Facebook} from './facebook';
import {Instagram, InstagramMedia, InstagramApp, InstagramCamera, InstagramTag, InstagramLocation} from './instagram';
import {Pdf} from './pdf';

export {Call, Email, Text, Web, Launch, Supported, Open, Map, Twitter, Youtube, Facetime, Facebook, Instagram, InstagramMedia, InstagramApp, InstagramCamera, InstagramTag, InstagramLocation, Pdf}
<|endoftext|>


<commit_before>require("./env");

var vows = require('vows');
var assert = require('assert');

var suite = vows.describe('Bubble chart');

var width = 1100;
var height = 200;

function buildChart(id) {
    d3.select("body").append("div").attr("id", id);
    var chart = dc.bubbleChart("#" + id);
    chart.width(width).height(height)
        .dimension(statusDimension)
        .group(statusMultiGroup)
        .xValue(function(p) {
            return p.value.value;
        })
        .yValue(function(p) {
            return p.value.count;
        })
        .rValue(function(p) {
            return p.value.count;
        })
        .x(d3.scale.linear().domain([0, 300]))
        .y(d3.scale.linear().domain([0, 10]))
        .r(d3.scale.linear().domain([0, 30]))
        .transitionDuration(0);
    chart.render();
    return chart;
}

suite.addBatch({
    'bubble chart': {
        topic: function() {
            var chart = buildChart("chart");
            return chart;
        },
        'we get something': function(chart) {
            assert.isNotNull(chart);
        },
        'should be registered':function(chart) {
            assert.isTrue(dc.hasChart(chart));
        },
        'svg should be created': function(chart) {
            assert.isFalse(chart.select("svg").empty());
        },
        'dimension should be set': function(chart) {
            assert.equal(chart.dimension(), statusDimension);
        },
        'group should be set': function(chart) {
            assert.equal(chart.group(), statusMultiGroup);
        },
        'width should be set': function(chart) {
            assert.equal(chart.width(), width);
        },
        'height should be set': function(chart) {
            assert.equal(chart.height(), height);
        },
        'height should be used for svg': function(chart) {
            assert.equal(chart.select("svg").attr("height"), height);
        },
        'transition duration should be set': function(chart) {
            assert.equal(chart.transitionDuration(), 0);
        },
        'margin should be set': function(chart) {
            assert.isNotNull(chart.margins());
        },
        'x can be set': function(chart) {
            assert.isTrue(chart.x() != undefined);
        },
        'x range round is auto calculated based on width': function(chart) {
            assert.equal(chart.x().range()[0], 0);
            assert.equal(chart.x().range()[1], 1030);
        },
        'x domain should be set': function(chart) {
            assert.equal(chart.x().domain()[0], 0);
            assert.equal(chart.x().domain()[1], 300);
        },
        'y can be set': function(chart) {
            assert.isTrue(chart.y() != undefined);
        },
        'y range round is auto calculated based on height': function(chart) {
            assert.equal(chart.y().range()[0], 160);
            assert.equal(chart.y().range()[1], 0);
        },
        'y domain should be set': function(chart) {
            assert.equal(chart.y().domain()[0], 0);
            assert.equal(chart.y().domain()[1], 10);
        },
        'r should be set': function(chart) {
            assert.isNotNull(chart.r());
        },
        'rValue should be set': function(chart) {
            assert.isNotNull(chart.rValue());
        },
        'root g should be created': function(chart) {
            assert.isFalse(chart.select("svg g").empty());
        },
        'root g should be translated to left corner': function(chart) {
            assert.equal(chart.select("svg g").attr("transform"), "translate(20,10)");
        },
        'axis x should be placed at the bottom': function(chart) {
            assert.equal(chart.select("svg g g.x").attr("transform"), "translate(20,170)");
        },
        'axis y should be placed on the left': function(chart) {
            assert.equal(chart.select("svg g g.y").attr("transform"), "translate(20,10)");
        },
        'x units should be set': function(chart) {
            assert.equal(chart.xUnits(), dc.units.integers);
        },
        'x axis should be created': function(chart) {
            assert.isNotNull(chart.xAxis());
        },
        'y axis should be created': function(chart) {
            assert.isNotNull(chart.yAxis());
        },
        'brush should be created': function(chart) {
            assert.isNotNull(chart.select("g.brush"));
        },
        'round should be off by default': function(chart) {
            assert.isTrue(chart.round() == null);
        },
        'round can be changed': function(chart) {
            chart.round(d3.time.day.round)
            assert.isNotNull(chart.round());
        },

        'bubble rendering':{
            topic: function(chart){return chart;},
            'right number of bubbles should be rendered': function(chart){
                assert.equal(chart.selectAll("circle.bubble")[0].length, 2);
            }
        },

        teardown: function(topic) {
            resetAllFilters();
        }
    }
});

suite.export(module);
<commit_msg>added test case validating cx calculation for bubble<commit_after>require("./env");

var vows = require('vows');
var assert = require('assert');

var suite = vows.describe('Bubble chart');

var width = 1100;
var height = 200;

function buildChart(id) {
    d3.select("body").append("div").attr("id", id);
    var chart = dc.bubbleChart("#" + id);
    chart.width(width).height(height)
        .dimension(statusDimension)
        .group(statusMultiGroup)
        .xValue(function(p) {
            return p.value.value;
        })
        .yValue(function(p) {
            return p.value.count;
        })
        .rValue(function(p) {
            return p.value.count;
        })
        .x(d3.scale.linear().domain([0, 300]))
        .y(d3.scale.linear().domain([0, 10]))
        .r(d3.scale.linear().domain([0, 30]))
        .transitionDuration(0);
    chart.render();
    return chart;
}

suite.addBatch({
    'bubble chart': {
        topic: function() {
            var chart = buildChart("chart");
            return chart;
        },
        'we get something': function(chart) {
            assert.isNotNull(chart);
        },
        'should be registered':function(chart) {
            assert.isTrue(dc.hasChart(chart));
        },
        'svg should be created': function(chart) {
            assert.isFalse(chart.select("svg").empty());
        },
        'dimension should be set': function(chart) {
            assert.equal(chart.dimension(), statusDimension);
        },
        'group should be set': function(chart) {
            assert.equal(chart.group(), statusMultiGroup);
        },
        'width should be set': function(chart) {
            assert.equal(chart.width(), width);
        },
        'height should be set': function(chart) {
            assert.equal(chart.height(), height);
        },
        'height should be used for svg': function(chart) {
            assert.equal(chart.select("svg").attr("height"), height);
        },
        'transition duration should be set': function(chart) {
            assert.equal(chart.transitionDuration(), 0);
        },
        'margin should be set': function(chart) {
            assert.isNotNull(chart.margins());
        },
        'x can be set': function(chart) {
            assert.isTrue(chart.x() != undefined);
        },
        'x range round is auto calculated based on width': function(chart) {
            assert.equal(chart.x().range()[0], 0);
            assert.equal(chart.x().range()[1], 1030);
        },
        'x domain should be set': function(chart) {
            assert.equal(chart.x().domain()[0], 0);
            assert.equal(chart.x().domain()[1], 300);
        },
        'y can be set': function(chart) {
            assert.isTrue(chart.y() != undefined);
        },
        'y range round is auto calculated based on height': function(chart) {
            assert.equal(chart.y().range()[0], 160);
            assert.equal(chart.y().range()[1], 0);
        },
        'y domain should be set': function(chart) {
            assert.equal(chart.y().domain()[0], 0);
            assert.equal(chart.y().domain()[1], 10);
        },
        'r should be set': function(chart) {
            assert.isNotNull(chart.r());
        },
        'rValue should be set': function(chart) {
            assert.isNotNull(chart.rValue());
        },
        'root g should be created': function(chart) {
            assert.isFalse(chart.select("svg g").empty());
        },
        'root g should be translated to left corner': function(chart) {
            assert.equal(chart.select("svg g").attr("transform"), "translate(20,10)");
        },
        'axis x should be placed at the bottom': function(chart) {
            assert.equal(chart.select("svg g g.x").attr("transform"), "translate(20,170)");
        },
        'axis y should be placed on the left': function(chart) {
            assert.equal(chart.select("svg g g.y").attr("transform"), "translate(20,10)");
        },
        'x units should be set': function(chart) {
            assert.equal(chart.xUnits(), dc.units.integers);
        },
        'x axis should be created': function(chart) {
            assert.isNotNull(chart.xAxis());
        },
        'y axis should be created': function(chart) {
            assert.isNotNull(chart.yAxis());
        },
        'brush should be created': function(chart) {
            assert.isNotNull(chart.select("g.brush"));
        },
        'round should be off by default': function(chart) {
            assert.isTrue(chart.round() == null);
        },
        'round can be changed': function(chart) {
            chart.round(d3.time.day.round)
            assert.isNotNull(chart.round());
        },

        'bubble rendering':{
            topic: function(chart) {
                return chart;
            },
            'right number of bubbles should be rendered': function(chart) {
                assert.equal(chart.selectAll("circle.bubble")[0].length, 2);
            },
            'right cx should be calculated for each bubble': function(chart) {
                chart.selectAll("circle.bubble").each(function(d, i) {
                    if (i == 0)
                        assert.equal(d3.select(this).attr("cx"), 775.3333333333334);
                    else if (i == 1)
                        assert.equal(d3.select(this).attr("cx"), 699.8000000000001);
                });
            }
        },

        teardown: function(topic) {
            resetAllFilters();
        }
    }
});

suite.export(module);
<|endoftext|>


<commit_before>var objectKeys = require('object-keys');
var objectValues = require('./utils/object-values');
var countries = require('./data/countries.json');
var capitals = require('./data/capital.json');
var currencies = require('./data/currency.json');

module.exports = {
    all: objectValues(countries),
    getCountryCodes: objectKeys(countries),
    getCountryByCode: function (code) {
        if (code && typeof code === 'string') {
            return countries[code];
        }
    },
    getCapitals: objectValues(capitals),
    getCapitalByCountryCode: function (code) {
        if (code && typeof code === 'string') {
            return capitals[code];
        }
    },
    getCurrencies: objectValues(currencies),
    getCurrencyByCountryCode: function (code) {
        if (code && typeof code === 'string') {
            return currencies[code];
        }
    }
};
<commit_msg>added country phone code<commit_after>var objectKeys = require('object-keys');
var objectValues = require('./utils/object-values');
var countries = require('./data/countries.json');
var capitals = require('./data/capital.json');
var currencies = require('./data/currency.json');
var phone = require('./data/phone.json');

module.exports = {
    all: objectValues(countries),
    getCountryCodes: objectKeys(countries),
    getCountryByCode: function (code) {
        if (code && typeof code === 'string') {
            return countries[code];
        }
    },
    // TODO
    // getCountryByCapital: function (capital) {
    //     // Object.keys(capitals)[0]
    // }
    // // TODO
    // getCountryByCuurency: function (capital) {
    //     // Object.keys(capitals)[0]
    // }
    // // TODO
    // getCountryByPhoneCode: function (capital) {
    //     // Object.keys(capitals)[0]
    // }
    getCapitals: objectValues(capitals),
    // TODO Add the ability to accept country name too
    getCapitalByCountryCode: function (code) {
        if (code && typeof code === 'string') {
            return capitals[code];
        }
    },
    getCurrencies: objectValues(currencies),
    // TODO Add the ability to accept country name too
    getCurrencyByCountryCode: function (code) {
        if (code && typeof code === 'string') {
            return currencies[code];
        }
    },
    getPhoneCodes: objectValues(phone),
    // TODO Add the ability to accept country name too
    getPhoneCodeByCountryCode: function (code) {
        if (code && typeof code === 'string') {
            return phone[code];
        }
    }
};
<|endoftext|>


<commit_before>const {
  defaults,
  debounce,
} = require('lodash/fp');
const nodeWatch = require('node-watch');

const { series } = require('./utils');
const {
  promisifyChildProcess,
  runCommandWithPassTrough,
} = require('./children');

const defaultOptions = {
  restartSignal: 'SIGUSR2',
  signals: ['SIGINT', 'SIGTERM'],
  watch: [],
};

function runCommand(command, signals) {
  return promisifyChildProcess(runCommandWithPassTrough(command, signals));
}

function start(commands, signals) {
  const promises = commands.map(command => () => runCommand(command, signals));
  return series(promises);
}

function watchAndReload(fn, files, restartSignal) {
  return nodeWatch(files, { recursive: true }, () => {
    process.kill(process.pid, restartSignal);
    fn();
  });
}

function main(commands, options = {}) {
  const {
    signals,
    watch,
    restartSignal,
  } = defaults(defaultOptions)(options);
  const fn = () => start(commands, restartSignal.concat(signals));
  if (watch.length) {
    const watcher = watchAndReload(debounce(1000)(fn), watch, restartSignal);
    process.on('SIGINT', watcher.close);
    process.on('SIGTERM', watcher.close);
  }
  fn();
}

module.exports = main;
<commit_msg>fixed call to execCommand<commit_after>const {
  defaults,
  debounce,
} = require('lodash/fp');
const nodeWatch = require('node-watch');

const { series } = require('./utils');
const {
  execCommand,
  promisifyChildProcess,
} = require('./children');

const defaultOptions = {
  restartSignal: 'SIGUSR2',
  signals: ['SIGINT', 'SIGTERM'],
  watch: [],
};

function runCommand(command, signals) {
  return promisifyChildProcess(execCommand(command, { signals }));
}

function start(commands, signals) {
  const promises = commands.map(command => () => runCommand(command, signals));
  return series(promises);
}

function watchAndReload(fn, files, restartSignal) {
  return nodeWatch(files, { recursive: true }, () => {
    process.kill(process.pid, restartSignal);
    fn();
  });
}

function main(commands, options = {}) {
  const {
    signals,
    watch,
    restartSignal,
  } = defaults(defaultOptions)(options);
  const fn = () => start(commands, restartSignal.concat(signals));
  if (watch.length) {
    const watcher = watchAndReload(debounce(1000)(fn), watch, restartSignal);
    process.on('SIGINT', watcher.close);
    process.on('SIGTERM', watcher.close);
  }
  fn();
}

module.exports = main;
<|endoftext|>


<commit_before>import { version } from '../package.json'

export class ZeroMd extends HTMLElement {
  get src () { return this.getAttribute('src') }
  set src (val) { this.reflect('src', val) }
  get manualRender () { return this.hasAttribute('manual-render') }
  set manualRender (val) { this.reflect('manual-render', val) }

  reflect (name, val) {
    if (val === false) {
      this.removeAttribute(name)
    } else {
      this.setAttribute(name, val === true ? '' : val)
    }
  }

  static get observedAttributes () {
    return ['src']
  }

  attributeChangedCallback (name, old, val) {
    if (name === 'src' && this.connected && !this.manualRender && val !== old) {
      this.render()
    }
  }

  constructor (defaults) {
    super()
    this.version = version
    this.config = {
      markedUrl: 'https://cdn.jsdelivr.net/gh/markedjs/marked@1/marked.min.js',
      prismUrl: [
        ['https://cdn.jsdelivr.net/gh/PrismJS/prism@1/prism.min.js', 'data-manual'],
        'https://cdn.jsdelivr.net/gh/PrismJS/prism@1/plugins/autoloader/prism-autoloader.min.js'
      ],
      cssUrls: [
        'https://cdn.jsdelivr.net/gh/sindresorhus/github-markdown-css@4/github-markdown.min.css',
        'https://cdn.jsdelivr.net/gh/PrismJS/prism@1/themes/prism.min.css'
      ],
      hostCss: ':host{display:block;position:relative;contain:content;}:host([hidden]){display:none;}',
      ...defaults,
      ...window.ZeroMdConfig
    }
    this.root = this.hasAttribute('no-shadow') ? this : this.attachShadow({ mode: 'open' })
    if (!this.constructor.ready) {
      this.constructor.ready = Promise.all([
        !!window.marked || this.loadScript(this.config.markedUrl),
        !!window.Prism || this.loadScript(this.config.prismUrl)
      ])
    }
    this.ready = new Promise(resolve => {
      this._resolve = resolve
    })
    this.waitForReady().then(() => {
      this.fire('zero-md-ready')
    })
    if (!this.manualRender) {
      // Scroll to hash id after first render. However, `history.scrollRestoration` inteferes with this on refresh.
      // It's much better to use a `setTimeout` rather than to alter the browser's behaviour.
      this.render().then(() => setTimeout(() => this.goto(location.hash), 250))
    }
    this.clicked = this.clicked.bind(this)
    if (this.shadowRoot) {
      this.shadowRoot.addEventListener('click', this.clicked)
    }
  }

  connectedCallback () {
    this.connected = true
    this._resolve()
    delete this._resolve
  }

  disconnectedCallback () {
    if (this.shadowRoot) {
      this.shadowRoot.removeEventListener('click', this.clicked)
    }
  }

  waitForReady () {
    return Promise.all([this.constructor.ready, this.ready])
  }

  fire (name, detail = {}, composed = true) {
    if (detail.msg) {
      console.warn(detail.msg)
    }
    this.dispatchEvent(new CustomEvent(name, {
      detail: { node: this, ...detail },
      bubbles: true,
      composed
    }))
  }

  // Coerce anything into an array
  arrify (any) {
    return any ? (Array.isArray(any) ? any : [any]) : []
  }

  // Promisify an element's onload callback
  onload (node) {
    return new Promise((resolve, reject) => {
      node.onload = resolve
      node.onerror = err => reject(err.path ? err.path[0] : err.composedPath()[0])
    })
  }

  // Load a url or load (in order) an array of urls via


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import Root from './Root';

ReactDOM.render(<Root />, document.getElementById('root'));<commit_msg>Load css<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import Root from './Root';

import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';

ReactDOM.render(<Root />, document.getElementById('root'));<|endoftext|>


<commit_before>import initialize from './initialize';
import register from './register';
import unregister from './unregister';
import { core } from './commands/lfsCommands';
import checkout from './commands/checkout';
import push from './commands/push';
import track from './commands/track';
import version from './commands/version';
import fetch from './commands/fetch';
import prune from './commands/prune';
import list from './commands/ls';
import testPointer from './commands/pointer';
import pull from './commands/pull';

function LFS(nodegit) {
  this.NodeGit = nodegit;
}

// LFS.prototype.constructor = LFS;
LFS.prototype = {
  core,
  checkout,
  fetch,
  initialize,
  list,
  register,
  testPointer,
  track,
  prune,
  pull,
  push,
  version,
  unregister,
};

// LFS.prototype.push = push;

module.exports = (nodegit) => {
  const _NodeGit = nodegit;

  Object.getPrototypeOf(_NodeGit).LFS = new LFS(_NodeGit);

  module.exports = _NodeGit;
  return _NodeGit;
};
<commit_msg>Added a means to get filters from repo<commit_after>import initialize from './initialize';
import register from './register';
import unregister from './unregister';
import { core } from './commands/lfsCommands';
import { loadGitattributeFiltersFromRepo } from './helpers';
import checkout from './commands/checkout';
import push from './commands/push';
import track from './commands/track';
import version from './commands/version';
import fetch from './commands/fetch';
import prune from './commands/prune';
import list from './commands/ls';
import testPointer from './commands/pointer';
import pull from './commands/pull';

function LFS(nodegit) {
  this.NodeGit = nodegit;
}

// LFS.prototype.constructor = LFS;
LFS.prototype = {
  core,
  checkout,
  fetch,
  filters: loadGitattributeFiltersFromRepo,
  initialize,
  list,
  register,
  testPointer,
  track,
  prune,
  pull,
  push,
  version,
  unregister,
};

// LFS.prototype.push = push;

module.exports = (nodegit) => {
  const _NodeGit = nodegit;

  Object.getPrototypeOf(_NodeGit).LFS = new LFS(_NodeGit);

  module.exports = _NodeGit;
  return _NodeGit;
};
<|endoftext|>