<commit_before>'use strict';

const request = require('request-promise');

const config = require('../../config');
const scraper = require('./scraper');

module.exports = {
  getFirstMessagingEntry: (body) => {
    const val = body.object == 'page' &&
      body.entry &&
      Array.isArray(body.entry) &&
      body.entry.length > 0 &&
      body.entry[0] &&
      body.entry[0].id == config.Facebook.pageId &&
      body.entry[0].messaging &&
      Array.isArray(body.entry[0].messaging) &&
      body.entry[0].messaging.length > 0 &&
      body.entry[0].messaging[0]
      ;
    return val || null;
  },
  sendTextMessage: (sender, text) => {
    const url = text;

    const metadata = scraper(url);
    return metadata.metadata().then((meta) => {
      let messageData = {
        attachment: {
          type: 'template',
          payload: {
            template_type: 'generic',
            elements: [
              {
                title: 'Test',
                image_url: meta.image,
                subtitle: 'test',
                buttons: [{
                  type: 'web_url',
                  url: url,
                  title: 'Click here'
                }]
              }
            ]
          }
        }
      };
      console.log(messageData);
      return request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: config.Facebook.pageToken},
        method: 'POST',
        body: {
          recipient: {id: sender},
          message: messageData,
        },
        json: true
      });
    });
  }
};
<commit_msg>Add title and description<commit_after>'use strict';

const request = require('request-promise');

const config = require('../../config');
const scraper = require('./scraper');

module.exports = {
  getFirstMessagingEntry: (body) => {
    const val = body.object == 'page' &&
      body.entry &&
      Array.isArray(body.entry) &&
      body.entry.length > 0 &&
      body.entry[0] &&
      body.entry[0].id == config.Facebook.pageId &&
      body.entry[0].messaging &&
      Array.isArray(body.entry[0].messaging) &&
      body.entry[0].messaging.length > 0 &&
      body.entry[0].messaging[0]
      ;
    return val || null;
  },
  sendTextMessage: (sender, text) => {
    const url = text;

    const metadata = scraper(url);
    return metadata.metadata().then((meta) => {
      let messageData = {
        attachment: {
          type: 'template',
          payload: {
            template_type: 'generic',
            elements: [
              {
                title: meta.title,
                image_url: meta.image,
                subtitle: meta.description,
                buttons: [{
                  type: 'web_url',
                  url: url,
                  title: 'View article'
                }]
              }
            ]
          }
        }
      };
      console.log(messageData);
      return request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: config.Facebook.pageToken},
        method: 'POST',
        body: {
          recipient: {id: sender},
          message: messageData,
        },
        json: true
      });
    });
  }
};
<|endoftext|>


<commit_before>var async = require("async");
var Blog = require("blog");
var url_parser = require("url").parse;
var https = require("https");

var RESULT;

function capitalize(str) {
  return str[0].toUpperCase() + str.slice(1);
}

// Add new sites at the start

var sites = [
  ["keywords.oxus.net", "Kerim Friedman teaches anthropology in Taiwan. Kerim"],
  [
    "hannautkin.com",
    "Hanna Utkin is a filmmaker and producer from New York City. Hanna"
  ],

  [
    "www.rebeccatron.com",
    "Rebecca Kukshtel is an engineer based in New York City. Rebecca "
  ],
  [
    "www.matthewbattles.org",
    "Matthew Battles directs metaLAB at Harvard. Matthew’s website"
  ],
  [
    "fagerheimen.no",
    "Fagerheimen Borettslag is an apartment building in Oslo, Norway. Its website"
  ],

  [
    "www.alexgibson.nyc",
    "Alexander Gibson is an artist from New York City. Alexander’s website"
  ],
  [
    "www.jacobyyoung.com/about",
    "Jacoby Young works at Kapālama Elementary School in Hawaii. Jacoby"
  ],
  [
    "www.kristianhjelle.com",
    "Kristian Hjelle is a designer and partner at Bakken & Bæck. Kristian"
  ],

  [
    "tf2.blot.im",
    "Theo Francis is a reporter at The Wall Street Journal. Theo’s blog"
  ],
  [
    "john.pavlusoffice.com",
    "John Pavlus is a writer and filmmaker based in Portland, Oregon. John"
  ],
  [
    "sportsmanfc.com",
    "The Sportsman Flying Club is a pigeon‐racing club in Toft Hill, UK. Their website"
  ],

  [
    "www.theliminal.co",
    "The Liminal is a podcast about metaphysical speculation. Their website"
  ],
  [
    "blog.aurynn.com",
    "Aurynn Shaw is a writer and engineer from New Zealand. Aurynn’s site"
  ],
  [
    "iiiiiiiii.in",
    "Ishtaarth Dalmia writes about internet culture and economics from Bengaluru, India. Ishtaarth"
  ],
  [
    "kiefer.design",
    "Kiefer Sutherland is a freelance designer and art director. Kiefer’s website"
  ],
  [
    "www.failuretolerated.com",
    "Sean McCoy is a game designer from Dallas, Texas. Sean’s site"
  ],
  [
    "mrfris.by",
    "Stuart Frisby is the Director of Design at Booking.com. Stuart’s site"
  ],
  [
    "www.querlin.com",
    "Querlin Ricci is a designer in Atlanta. Querlin’s website"
  ]
];

module.exports = function(callback) {
  if (RESULT) return callback(null, RESULT);

  var result = [];

  // Only show the first 12 sites on the homepage
  sites = sites.slice(0, 12);

  async.eachSeries(
    sites,
    function(site, next) {
      var parsed_URL = url_parser("https://" + site[0]);

      var domain = parsed_URL.host;
      var description = site[1].trim();
      var template;
      var is_subdomain = domain.indexOf("blot.im") !== -1;
      var url, display_url, protocol, by, custom_template, template_name;
          var response = "";

      var get = https.get(
        require("url").format({
          protocol: "https",
          hostname: domain,
          pathname: "/verify/domain-setup"
        }),
        function check(res) {
          res.setEncoding("utf8");
          res.on("data", function(chunk) {
            response += chunk;
          });
          res.on("end", handle);
        }
      );

      get.on("error", function(chunk) {
        handle();
      });

      function handle() {
        if (is_subdomain) {
          by = { handle: domain.split(".blot.im").join("") };
        } else {
          by = { domain: domain };
        }

        Blog.get(by, function(err, blog) {
          if (err || !blog) {
            console.log(domain, "is not in the database");
            return next();
          }

          if (!is_subdomain && response !== blog.handle) {
            console.log(domain, "is not on blot it points to...");
            return next();
          }

          template = blog.template;

          protocol = domain.indexOf("blot.im") > -1 ? "http" : "https";

          url = protocol + "://" + site[0];
          display_url = domain.split("www.").join("");
          custom_template = template.indexOf("SITE") === -1;
          template_name = custom_template
            ? "custom"
            : capitalize(template.split("SITE:").join(""));

          description += " uses ";
          description += custom_template ? "a" : "the";
          description +=
            ' ' + template_name + " template.";

          // Redirect
          if (display_url === "john.pavlusoffice.com")
            display_url = "johnpavlus.com";

          result.push({
            url: url,
            first: result.length === 0,
            clear: (result.length + 1) % 3 === 0,
            display_url: display_url,
            description: description,
            domain: domain,
            template: template
          });

          next();
        });
      }
    },
    function() {
      RESULT = result;
      callback(null, result);
    }
  );
};
<commit_msg>Added John to homepage<commit_after>var async = require("async");
var Blog = require("blog");
var url_parser = require("url").parse;
var https = require("https");

var RESULT;

function capitalize(str) {
  return str[0].toUpperCase() + str.slice(1);
}

// Add new sites at the start

var sites = [
  [
    "com.johnbeeler.com",
    "John Beeler is the label director at Asthmatic Kitty Records. John"
  ],
  ["keywords.oxus.net", "Kerim Friedman teaches anthropology in Taiwan. Kerim"],
  [
    "hannautkin.com",
    "Hanna Utkin is a filmmaker and producer from New York City. Hanna"
  ],

  [
    "www.rebeccatron.com",
    "Rebecca Kukshtel is an engineer based in New York City. Rebecca "
  ],
  [
    "www.matthewbattles.org",
    "Matthew Battles directs metaLAB at Harvard. Matthew’s website"
  ],
  [
    "fagerheimen.no",
    "Fagerheimen Borettslag is an apartment building in Oslo, Norway. Its website"
  ],

  [
    "www.alexgibson.nyc",
    "Alexander Gibson is an artist from New York City. Alexander’s website"
  ],
  [
    "www.jacobyyoung.com/about",
    "Jacoby Young works at Kapālama Elementary School in Hawaii. Jacoby"
  ],
  [
    "www.kristianhjelle.com",
    "Kristian Hjelle is a designer and partner at Bakken & Bæck. Kristian"
  ],

  [
    "tf2.blot.im",
    "Theo Francis is a reporter at The Wall Street Journal. Theo’s blog"
  ],
  [
    "john.pavlusoffice.com",
    "John Pavlus is a writer and filmmaker based in Portland, Oregon. John"
  ],
  [
    "sportsmanfc.com",
    "The Sportsman Flying Club is a pigeon‐racing club in Toft Hill, UK. Their website"
  ],

  [
    "www.theliminal.co",
    "The Liminal is a podcast about metaphysical speculation. Their website"
  ],
  [
    "blog.aurynn.com",
    "Aurynn Shaw is a writer and engineer from New Zealand. Aurynn’s site"
  ],
  [
    "iiiiiiiii.in",
    "Ishtaarth Dalmia writes about internet culture and economics from Bengaluru, India. Ishtaarth"
  ],
  [
    "kiefer.design",
    "Kiefer Sutherland is a freelance designer and art director. Kiefer’s website"
  ],
  [
    "www.failuretolerated.com",
    "Sean McCoy is a game designer from Dallas, Texas. Sean’s site"
  ],
  [
    "mrfris.by",
    "Stuart Frisby is the Director of Design at Booking.com. Stuart’s site"
  ],
  [
    "www.querlin.com",
    "Querlin Ricci is a designer in Atlanta. Querlin’s website"
  ]
];

module.exports = function(callback) {
  if (RESULT) return callback(null, RESULT);

  var result = [];

  // Only show the first 12 sites on the homepage
  sites = sites.slice(0, 12);

  async.eachSeries(
    sites,
    function(site, next) {
      var parsed_URL = url_parser("https://" + site[0]);

      var domain = parsed_URL.host;
      var description = site[1].trim();
      var template;
      var is_subdomain = domain.indexOf("blot.im") !== -1;
      var url, display_url, protocol, by, custom_template, template_name;
      var response = "";

      var get = https.get(
        require("url").format({
          protocol: "https",
          hostname: domain,
          pathname: "/verify/domain-setup"
        }),
        function check(res) {
          res.setEncoding("utf8");
          res.on("data", function(chunk) {
            response += chunk;
          });
          res.on("end", handle);
        }
      );

      get.on("error", function(chunk) {
        handle();
      });

      function handle() {
        if (is_subdomain) {
          by = { handle: domain.split(".blot.im").join("") };
        } else {
          by = { domain: domain };
        }

        Blog.get(by, function(err, blog) {
          if (err || !blog) {
            console.log(domain, "is not in the database");
            return next();
          }

          if (!is_subdomain && response !== blog.handle) {
            console.log(domain, "is not on blot it points to...");
            return next();
          }

          template = blog.template;

          protocol = domain.indexOf("blot.im") > -1 ? "http" : "https";

          url = protocol + "://" + site[0];
          display_url = domain.split("www.").join("");
          custom_template = template.indexOf("SITE") === -1;
          template_name = custom_template
            ? "custom"
            : capitalize(template.split("SITE:").join(""));

          description += " uses ";
          description += custom_template ? "a" : "the";
          description +=
            ' ' + template_name + " template.";

          // Redirect
          if (display_url === "john.pavlusoffice.com")
            display_url = "johnpavlus.com";

          result.push({
            url: url,
            first: result.length === 0,
            clear: (result.length + 1) % 3 === 0,
            display_url: display_url,
            description: description,
            domain: domain,
            template: template
          });

          next();
        });
      }
    },
    function() {
      RESULT = result;
      callback(null, result);
    }
  );
};
<|endoftext|>


<commit_before>var Future = require("../future.js");
var Card = require("../card/schedule/visual.js");
var jsdom = require('jsdom');
var Handlebars = require("../../vendor/js/handlebars-v2.0.0.js");

var doc = jsdom.jsdom(''),
    window = doc.parentWindow;

var $ = require('jquery')(window);

var assert = require("assert");

describe("Always shows the visual schedule", function() {
    global.$ = $;
    global.window = window;
    global.Handlebars = Handlebars;
    global.VisualScheduleCard = Card.VisualScheduleCard;
    // Just mocked out - otherwise it calls WSData
    global.NoticeBanner = { render_init: function() { } };
    global.CourseCards = {};
    global.TextbookCard = {};
    global.Cards = { load_cards_in_order: function() { } };
    window.user = {};
    window.user.student = true;

    window.card_display_dates = {};

    it("by default it should be hidden", function() {
        window.card_display_dates.is_before_last_day_of_classes = false;
        assert.equal(false, Card.VisualScheduleCard.should_display_card());
    });
    it("should show when force-shown", function() {
        window.card_display_dates.is_before_last_day_of_classes = false;
        window.force_visual_schedule_display = true;
        assert.equal(true, Card.VisualScheduleCard.should_display_card());
    });
    it("should show when force-shown by method", function() {
        window.card_display_dates.is_before_last_day_of_classes = false;
        window.force_visual_schedule_display = false;
        Card.VisualScheduleCard.force_visual_schedule_display();
        assert.equal(true, Card.VisualScheduleCard.should_display_card());
    });

    it("should be set after the future quarter page renders", function() {
        window.card_display_dates.is_before_last_day_of_classes = false;
        window.force_visual_schedule_display = false;
        Future.FutureQuarter.make_html();
        assert.equal(true, Card.VisualScheduleCard.should_display_card());
    });

});
<commit_msg>Dropping the test w/ the future page method<commit_after>var Future = require("../future.js");
var Card = require("../card/schedule/visual.js");
var jsdom = require('jsdom');
var Handlebars = require("../../vendor/js/handlebars-v2.0.0.js");

var doc = jsdom.jsdom(''),
    window = doc.parentWindow;

var $ = require('jquery')(window);
var assert = require("assert");

describe("Always shows the visual schedule", function() {
    global.$ = $;
    global.window = window;
    global.Handlebars = Handlebars;
    global.VisualScheduleCard = Card.VisualScheduleCard;
    window.user = {};
    window.user.student = true;

    window.card_display_dates = {};

    it("by default it should be hidden", function() {
        window.card_display_dates.is_before_last_day_of_classes = false;
        assert.equal(false, Card.VisualScheduleCard.should_display_card());
    });
    it("should show when force-shown", function() {
        window.card_display_dates.is_before_last_day_of_classes = false;
        window.force_visual_schedule_display = true;
        assert.equal(true, Card.VisualScheduleCard.should_display_card());
    });
    it("should show when force-shown by method", function() {
        window.card_display_dates.is_before_last_day_of_classes = false;
        window.force_visual_schedule_display = false;
        Card.VisualScheduleCard.force_visual_schedule_display();
        assert.equal(true, Card.VisualScheduleCard.should_display_card());
    });
});
<|endoftext|>


<commit_before>var path = require("path");
var fs = require("fs");
var assert = require("assert");
var sinon = require("sinon");

var Environment = {
    _stub: null,

    init: function (config) {
        if (!config) {
            config = {};
        }

        // create test document
        var window = require('jsdom').jsdom().defaultView;

        // pull in supporting tools
        var $ = require('jquery')(window);
        global.$ = $;
        global.window = window;
        global.assert = require("assert");
        global.moment = require("moment");
        global.Handlebars = require("../../vendor/js/handlebars-v2.0.0.js");
        var MomentTZ = require("moment-timezone");
        var HandlebarsHelpers = require("../handlebars-helpers.js")

        // set up client environment
        window.user = {};
        window.user.student = true;

        // default test term
        window.term = {};
        window.term.year = 2013;
        window.term.quarter = 'spring';

        if (config.hasOwnProperty('render_id')) {
            $('body').append($('<div/>', { 'id': config.render_id }));
        }

        // stub onload init routines
        window.RenderPage = function () {};
        global.Profile = { add_events: function () {} };
        global.Modal = { add_events: function () {} };
        global.LogUtils = {
            init_logging: function () {},
            cardLoaded: function(name, el) {
                $(window).trigger("myuw:card_load", [ name, el ])
            }
        };

        // pull in scripts
        Environment._load_script('myuw/static/js/myuw_m.js');
        Environment._load_script('myuw/static/js/ws_data.js');
        if (config.hasOwnProperty('scripts')) {
            $.each(config.scripts, function () {
                Environment._load_script(this.toString());
            });
        }

        // pull in templates
        if (config.hasOwnProperty('templates')) {
            $.each(config.templates, function () {
                Environment._load_template(this.toString());
            });
        }
    },
    _abs_path: function (relative_path) {
        return path.join(__dirname, '../../../../', relative_path);
    },
    ajax_stub: function (json_data_file) {
        var json_dir = path.join('myuw/static/js/test/ajax', json_data_file);
        var json_file = Environment._abs_path(json_dir);
        var json_data = JSON.parse(fs.readFileSync(json_file));
        Environment._stub = sinon.stub($, 'ajax');
        Environment._stub.yieldsTo('success', json_data);
    },
    ajax_stub_restore: function () {
        if (Environment._stub) {
            Environment._stub.restore();
        }
    },
    _load_script: function (script) {
        var r = require(Environment._abs_path(script));
        $.each(r, function(k, v) { global[k] = v;});
    },
    _read_template: function (template_file) {
        var template_path = Environment._abs_path(template_file);
        var raw = fs.readFileSync(template_path).toString();
        var template = raw.replace(/{\%[ ]+load[ ]+templatetag_handlebars[ ]+\%}/, '')
            .replace(/{\%[ ]*tplhandlebars[ ]+["]?([^ \%]+)["]?[ ]*\%}/,
                     '<script id="$1" type="text/x-handlebars-template">')
            .replace(/{\%[ ]*endtplhandlebars[ ]*\%}/,
                     '</script>')
            .replace(/{\%[ ]*(end)?verbatim[ ]*\%}/g, '');

        while (true) {
            // pull in server-side includes
            var m = template.match(/{\%[ ]*include[ ]+["]?([^ \%"]+)["]?[ ]*\%}/);
            if (m) {
                var text = Environment._read_template('myuw/templates/' + m[1]);
                template = template.replace(m[0], text);
            } else {
                break;
            }
        }

        return template;
    },
    _load_template: function(template_file) {
        var template = Environment._read_template(template_file);
        $('body').append(template);
    }
};

describe("Global Test Environment", function () {
    it("loads nested server-side templates", function (){
        var f = 'myuw/templates/handlebars/card/instructor_schedule/course_resource_panel.html';
        var t = Environment._read_template(f);

        assert(t.indexOf('instructor_course_resource_panel') > 0, 'template id');
        assert(t.indexOf('endtplhandlebars') < 0, 'end handlebars block stripped');
        assert(t.indexOf('verbatim') < 0, 'verbatim stripped');
        assert(t.indexOf('endverbatim') < 0, 'endverbatim stripped');
        assert(t.indexOf('show_course_textbook') > 0, 'first inclusion');
        assert(t.indexOf('list_admin_url') > 0, 'second inclusion');
        assert.equal(true, true);
    });
});

/* node.js exports */
if (typeof exports == "undefined") {
    var exports = {};
}
exports.Environment = Environment;
<commit_msg>update handlebars version in test<commit_after>var path = require("path");
var fs = require("fs");
var assert = require("assert");
var sinon = require("sinon");

var Environment = {
    _stub: null,

    init: function (config) {
        if (!config) {
            config = {};
        }

        // create test document
        var window = require('jsdom').jsdom().defaultView;

        // pull in supporting tools
        var $ = require('jquery')(window);
        global.$ = $;
        global.window = window;
        global.assert = require("assert");
        global.moment = require("moment");
        global.Handlebars = require("../../vendor/js/handlebars-v4.0.5.js");
        var MomentTZ = require("moment-timezone");
        var HandlebarsHelpers = require("../handlebars-helpers.js")

        // set up client environment
        window.user = {};
        window.user.student = true;

        // default test term
        window.term = {};
        window.term.year = 2013;
        window.term.quarter = 'spring';

        if (config.hasOwnProperty('render_id')) {
            $('body').append($('<div/>', { 'id': config.render_id }));
        }

        // stub onload init routines
        window.RenderPage = function () {};
        global.Profile = { add_events: function () {} };
        global.Modal = { add_events: function () {} };
        global.LogUtils = {
            init_logging: function () {},
            cardLoaded: function(name, el) {
                $(window).trigger("myuw:card_load", [ name, el ])
            }
        };

        // pull in scripts
        Environment._load_script('myuw/static/js/myuw_m.js');
        Environment._load_script('myuw/static/js/ws_data.js');
        if (config.hasOwnProperty('scripts')) {
            $.each(config.scripts, function () {
                Environment._load_script(this.toString());
            });
        }

        // pull in templates
        if (config.hasOwnProperty('templates')) {
            $.each(config.templates, function () {
                Environment._load_template(this.toString());
            });
        }
    },
    _abs_path: function (relative_path) {
        return path.join(__dirname, '../../../../', relative_path);
    },
    ajax_stub: function (json_data_file) {
        var json_dir = path.join('myuw/static/js/test/ajax', json_data_file);
        var json_file = Environment._abs_path(json_dir);
        var json_data = JSON.parse(fs.readFileSync(json_file));
        Environment._stub = sinon.stub($, 'ajax');
        Environment._stub.yieldsTo('success', json_data);
    },
    ajax_stub_restore: function () {
        if (Environment._stub) {
            Environment._stub.restore();
        }
    },
    _load_script: function (script) {
        var r = require(Environment._abs_path(script));
        $.each(r, function(k, v) { global[k] = v;});
    },
    _read_template: function (template_file) {
        var template_path = Environment._abs_path(template_file);
        var raw = fs.readFileSync(template_path).toString();
        var template = raw.replace(/{\%[ ]+load[ ]+templatetag_handlebars[ ]+\%}/, '')
            .replace(/{\%[ ]*tplhandlebars[ ]+["]?([^ \%]+)["]?[ ]*\%}/,
                     '<script id="$1" type="text/x-handlebars-template">')
            .replace(/{\%[ ]*endtplhandlebars[ ]*\%}/,
                     '</script>')
            .replace(/{\%[ ]*(end)?verbatim[ ]*\%}/g, '');

        while (true) {
            // pull in server-side includes
            var m = template.match(/{\%[ ]*include[ ]+["]?([^ \%"]+)["]?[ ]*\%}/);
            if (m) {
                var text = Environment._read_template('myuw/templates/' + m[1]);
                template = template.replace(m[0], text);
            } else {
                break;
            }
        }

        return template;
    },
    _load_template: function(template_file) {
        var template = Environment._read_template(template_file);
        $('body').append(template);
    }
};

describe("Global Test Environment", function () {
    it("loads nested server-side templates", function (){
        var f = 'myuw/templates/handlebars/card/instructor_schedule/course_resource_panel.html';
        var t = Environment._read_template(f);

        assert(t.indexOf('instructor_course_resource_panel') > 0, 'template id');
        assert(t.indexOf('endtplhandlebars') < 0, 'end handlebars block stripped');
        assert(t.indexOf('verbatim') < 0, 'verbatim stripped');
        assert(t.indexOf('endverbatim') < 0, 'endverbatim stripped');
        assert(t.indexOf('show_course_textbook') > 0, 'first inclusion');
        assert(t.indexOf('list_admin_url') > 0, 'second inclusion');
        assert.equal(true, true);
    });
});

/* node.js exports */
if (typeof exports == "undefined") {
    var exports = {};
}
exports.Environment = Environment;
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { BACKGROUND_COLOR, BLUE_WHITE, DARK_GREY } from './colors';
import { APP_FONT_FAMILY, APP_GENERAL_FONT_SIZE } from './fonts';

const newDataTableStyles = {
  cellContainer: {
    left: {
      borderRightWidth: 2,
      borderColor: '#ecf3fc',
      flex: 1,
      justifyContent: 'center',
      textAlign: 'left',
    },
    right: {
      borderRightWidth: 2,
      borderColor: '#ecf3fc',
      flex: 1,
      justifyContent: 'center',
      textAlign: 'right',
    },
    center: {
      borderRightWidth: 2,
      borderColor: '#ecf3fc',
      flex: 1,
      justifyContent: 'center',
      textAlign: 'center',
    },
  },
  cellText: {
    left: {
      marginLeft: 20,
      textAlign: 'left',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
    right: {
      marginRight: 20,
      textAlign: 'right',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
    center: {
      textAlign: 'center',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
  },
  editableCellUnfocused: {
    right: {
      textAlign: 'right',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
    center: {
      textAlign: 'center',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
    left: {
      textAlign: 'left',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
  },
  editableCellText: {
    textAlign: 'right',
    fontFamily: APP_FONT_FAMILY,
    fontSize: APP_GENERAL_FONT_SIZE,
    color: DARK_GREY,
    marginRight: 20,
  },
  editableCellTextView: {
    borderBottomColor: '#cbcbcb',
    borderBottomWidth: 1,
    flex: 1,
    flexDirection: 'row',
    width: '88%',
    maxHeight: '65%',
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center',
    marginRight: 20,
  },
  touchableCellContainer: {
    borderRightWidth: 2,
    borderColor: '#ecf3fc',
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  row: {
    backgroundColor: BACKGROUND_COLOR,
    flex: 1,
    flexDirection: 'row',
    height: 45,
  },
  alternateRow: {
    backgroundColor: 'white',
    flex: 1,
    flexDirection: 'row',
    height: 45,
  },
  headerRow: {
    backgroundColor: 'white',
    flexDirection: 'row',
  },
  headerCells: {
    left: {
      height: 40,
      borderRightWidth: 2,
      borderBottomWidth: 2,
      backgroundColor: 'white',
      borderColor: BLUE_WHITE,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
    },
    right: {
      height: 40,
      borderRightWidth: 2,
      borderBottomWidth: 2,
      backgroundColor: 'white',
      borderColor: BLUE_WHITE,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'flex-end',
    },
    center: {
      height: 40,
      borderRightWidth: 2,
      borderBottomWidth: 2,
      backgroundColor: 'white',
      borderColor: BLUE_WHITE,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
    },
  },
};

export default newDataTableStyles;
<commit_msg>Add new expiry date styles<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { BACKGROUND_COLOR, BLUE_WHITE, DARK_GREY, LIGHT_GREY } from './colors';
import { APP_FONT_FAMILY, APP_GENERAL_FONT_SIZE } from './fonts';

const newDataTableStyles = {
  cellContainer: {
    left: {
      borderRightWidth: 2,
      borderColor: '#ecf3fc',
      flex: 1,
      justifyContent: 'center',
      textAlign: 'left',
    },
    right: {
      borderRightWidth: 2,
      borderColor: '#ecf3fc',
      flex: 1,
      justifyContent: 'center',
      textAlign: 'right',
    },
    center: {
      borderRightWidth: 2,
      borderColor: '#ecf3fc',
      flex: 1,
      justifyContent: 'center',
      textAlign: 'center',
    },
  },
  cellText: {
    left: {
      marginLeft: 20,
      textAlign: 'left',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
    right: {
      marginRight: 20,
      textAlign: 'right',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
    center: {
      textAlign: 'center',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
  },
  editableCellUnfocused: {
    right: {
      textAlign: 'right',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
    center: {
      textAlign: 'center',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
    left: {
      textAlign: 'left',
      fontFamily: APP_FONT_FAMILY,
      fontSize: APP_GENERAL_FONT_SIZE,
      color: DARK_GREY,
    },
  },
  editableCellText: {
    textAlign: 'right',
    fontFamily: APP_FONT_FAMILY,
    fontSize: APP_GENERAL_FONT_SIZE,
    color: DARK_GREY,
    marginRight: 20,
  },
  editableCellTextView: {
    borderBottomColor: '#cbcbcb',
    borderBottomWidth: 1,
    flex: 1,
    flexDirection: 'row',
    width: '88%',
    maxHeight: '65%',
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center',
    marginRight: 20,
  },
  touchableCellContainer: {
    borderRightWidth: 2,
    borderColor: '#ecf3fc',
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  row: {
    backgroundColor: BACKGROUND_COLOR,
    flex: 1,
    flexDirection: 'row',
    height: 45,
  },
  alternateRow: {
    backgroundColor: 'white',
    flex: 1,
    flexDirection: 'row',
    height: 45,
  },
  headerRow: {
    backgroundColor: 'white',
    flexDirection: 'row',
  },
  headerCells: {
    left: {
      height: 40,
      borderRightWidth: 2,
      borderBottomWidth: 2,
      backgroundColor: 'white',
      borderColor: BLUE_WHITE,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
    },
    right: {
      height: 40,
      borderRightWidth: 2,
      borderBottomWidth: 2,
      backgroundColor: 'white',
      borderColor: BLUE_WHITE,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'flex-end',
    },
    center: {
      height: 40,
      borderRightWidth: 2,
      borderBottomWidth: 2,
      backgroundColor: 'white',
      borderColor: BLUE_WHITE,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
    },
  },
  expiryBatchTextView: {
    borderBottomColor: '#cbcbcb',
    borderBottomWidth: 1,
    flex: 1,
    flexDirection: 'row',
    width: '88%',
    maxHeight: '65%',
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center',
  },
  expiryBatchViewStyle: {
    borderRightWidth: 2,
    borderColor: '#ecf3fc',
    flex: 1,
    justifyContent: 'center',
    textAlign: 'center',
  },
  expiryBatchText: {
    textAlign: 'center',
    fontFamily: APP_FONT_FAMILY,
    fontSize: APP_GENERAL_FONT_SIZE,
    color: DARK_GREY,
  },
  expiryBatchPlaceholderText: {
    textAlign: 'center',
    fontFamily: APP_FONT_FAMILY,
    fontSize: APP_GENERAL_FONT_SIZE,
    color: LIGHT_GREY,
  },
};

export default newDataTableStyles;
<|endoftext|>


<commit_before>// Thanks to: https://github.com/calebroseland/vue-dom-portal

const objectAssign = require('object-assign')
/**
 * Get target DOM Node
 * @param {(Node|string|Boolean)} [node=document.body] DOM Node, CSS selector, or Boolean
 * @return {Node} The target that the el will be appended to
 */
function getTarget (node) {
  if (node === void 0) {
    return document.body
  }

  if (typeof node === 'string' && node.indexOf('?') === 0) {
    return document.body
  } else if (typeof node === 'string' && node.indexOf('?') > 0) {
    node = node.split('?')[0]
  }

  if (node === 'body' || node === true) {
    return document.body
  }

  return node instanceof window.Node ? node : document.querySelector(node)
}

function getShouldUpdate (node) {
  // do not updated by default
  if (!node) {
    return false
  }
  if (typeof node === 'string' && node.indexOf('?') > 0) {
    try {
      const config = JSON.parse(node.split('?')[1])
      return config.autoUpdate || false
    } catch (e) {
      return false
    }
  }
  return false
}

const directive = {
  inserted (el, { value }, vnode) {
    el.className = el.className ? el.className + ' v-transfer-dom' : 'v-transfer-dom'
    const parentNode = el.parentNode
    var home = document.createComment('')
    var hasMovedOut = false

    if (value !== false) {
      parentNode.replaceChild(home, el) // moving out, el is no longer in the document
      getTarget(value).appendChild(el) // moving into new place
      hasMovedOut = true
    }
    if (!el.__transferDomData) {
      el.__transferDomData = {
        parentNode: parentNode,
        home: home,
        target: getTarget(value),
        hasMovedOut: hasMovedOut
      }
    }
  },
  componentUpdated (el, { value }) {
    const shouldUpdate = getShouldUpdate(value)
    if (!shouldUpdate) {
      return
    }
    // need to make sure children are done updating (vs. `update`)
    var ref$1 = el.__transferDomData
    // homes.get(el)
    var parentNode = ref$1.parentNode
    var home = ref$1.home
    var hasMovedOut = ref$1.hasMovedOut // recall where home is

    if (!hasMovedOut && value) {
      // remove from document and leave placeholder
      parentNode.replaceChild(home, el)
      // append to target
      getTarget(value).appendChild(el)
      el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: true, target: getTarget(value) })
    } else if (hasMovedOut && value === false) {
      // previously moved, coming back home
      parentNode.replaceChild(el, home)
      el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: false, target: getTarget(value) })
    } else if (value) {
      // already moved, going somewhere else
      getTarget(value).appendChild(el)
    }
  },
  unbind: function unbind (el, binding) {
    el.className = el.className.replace('v-transfer-dom', '')
    if (el.__transferDomData.hasMovedOut === true) {
      el.__transferDomData.parentNode && el.__transferDomData.parentNode.appendChild(el)
    }
    el.__transferDomData = null
  }
}

module.exports = directive
<commit_msg>transfer-dom: fix TypeError: "Cannot read property 'hasMovedOut' of null" (#2224)<commit_after>// Thanks to: https://github.com/calebroseland/vue-dom-portal

const objectAssign = require('object-assign')
/**
 * Get target DOM Node
 * @param {(Node|string|Boolean)} [node=document.body] DOM Node, CSS selector, or Boolean
 * @return {Node} The target that the el will be appended to
 */
function getTarget (node) {
  if (node === void 0) {
    return document.body
  }

  if (typeof node === 'string' && node.indexOf('?') === 0) {
    return document.body
  } else if (typeof node === 'string' && node.indexOf('?') > 0) {
    node = node.split('?')[0]
  }

  if (node === 'body' || node === true) {
    return document.body
  }

  return node instanceof window.Node ? node : document.querySelector(node)
}

function getShouldUpdate (node) {
  // do not updated by default
  if (!node) {
    return false
  }
  if (typeof node === 'string' && node.indexOf('?') > 0) {
    try {
      const config = JSON.parse(node.split('?')[1])
      return config.autoUpdate || false
    } catch (e) {
      return false
    }
  }
  return false
}

const directive = {
  inserted (el, { value }, vnode) {
    el.className = el.className ? el.className + ' v-transfer-dom' : 'v-transfer-dom'
    const parentNode = el.parentNode
    var home = document.createComment('')
    var hasMovedOut = false

    if (value !== false) {
      parentNode.replaceChild(home, el) // moving out, el is no longer in the document
      getTarget(value).appendChild(el) // moving into new place
      hasMovedOut = true
    }
    if (!el.__transferDomData) {
      el.__transferDomData = {
        parentNode: parentNode,
        home: home,
        target: getTarget(value),
        hasMovedOut: hasMovedOut
      }
    }
  },
  componentUpdated (el, { value }) {
    const shouldUpdate = getShouldUpdate(value)
    if (!shouldUpdate) {
      return
    }
    // need to make sure children are done updating (vs. `update`)
    var ref$1 = el.__transferDomData
    // homes.get(el)
    var parentNode = ref$1.parentNode
    var home = ref$1.home
    var hasMovedOut = ref$1.hasMovedOut // recall where home is

    if (!hasMovedOut && value) {
      // remove from document and leave placeholder
      parentNode.replaceChild(home, el)
      // append to target
      getTarget(value).appendChild(el)
      el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: true, target: getTarget(value) })
    } else if (hasMovedOut && value === false) {
      // previously moved, coming back home
      parentNode.replaceChild(el, home)
      el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: false, target: getTarget(value) })
    } else if (value) {
      // already moved, going somewhere else
      getTarget(value).appendChild(el)
    }
  },
  unbind: function unbind (el, binding) {
    el.className = el.className.replace('v-transfer-dom', '')
    if (el.__transferDomData && el.__transferDomData.hasMovedOut === true) {
      el.__transferDomData.parentNode && el.__transferDomData.parentNode.appendChild(el)
    }
    el.__transferDomData = null
  }
}

module.exports = directive
<|endoftext|>


<commit_before>"use strict";
(function() {
  function domReady(callback) {
      document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
  };
  function kaiosPadNav (e) {
    var childElems = document.querySelectorAll('div, a, input, button, select, textarea,ul,li');
    var currentIndex = 0, lastTabIndex, lastTabIndexElems, values = [];
    var genericTabs = function (a) {
      for(i = 0; i < a.length; i++ ){
        a[i].className += " items";
        a[i].setAttribute('tabindex', i);
        values.push(a[i]);
      }
      return values;
    }
    genericTabs(childElems).forEach(function(item, index, array) {
      lastTabIndex = index;
      lastTabIndexElems = item;
      values = array;
      return lastTabIndex, lastTabIndexElems, values;
    });

    function nav(ev) {
      var next = currentIndex + ev;
      var items = document.querySelectorAll(".items");
      currentIndex = next;
      var targetElement = items[next];
      console.log(targetElement);
      targetElement.focus();
    }

    var handleKeydown = function(e) {
      switch(e.key) {
        case 'ArrowUp':
          nav(-1);
          console.log('You click on ArrowUp', e.which || e.keyCode);
          break;
        case 'ArrowDown':
          nav(1);
          console.log('You click on ArrowDown', e.which || e.keyCode)
          break;
        case 'ArrowRight':
          nav(1);
          console.log('You click on ArrowRight', e.which || e.keyCode)
          break;
        case 'ArrowLeft':
          nav(-1);
          console.log('You click on ArrowLeft', e.which || e.keyCode)
          break;
      }
    };
    document.activeElement.addEventListener('keydown', handleKeydown, true);
  };

  var softkeyCallback = {
    left: function() { console.log('You click on SoftLeft') },
    center: function() {
      console.log('You click on Enter')

    },
    right: function() { console.log('You click on SoftRight') }
  };
  function handleKeyDownEvent(evt) {
    switch (evt.key) {
        case 'SoftLeft':
            // Action case press left key
            softkeyCallback.left();
        break;

        case 'SoftRight':
            // Action case press right key
            softkeyCallback.right();
        break;

        case 'Enter':
            // Action case press center key
            softkeyCallback.center();
        break;
    }
  };

  domReady(function() {
    kaiosPadNav();
    document.addEventListener('keydown', handleKeyDownEvent);
  });
})();
<commit_msg>update scripts to work<commit_after>"use strict";
(function() {
  function domReady(callback) {
      document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
  };
  function kaiosPadNav (e) {
    var childElems = document.querySelectorAll('div, a, input, button, select, textarea,ul,li');
    var currentIndex = 0, lastTabIndex, lastTabIndexElems, values = [];
    var genericTabs = function (a) {
      for(i = 0; i < a.length; i++ ){
        a[i].className += " items";
        a[i].setAttribute('tabindex', i);
        values.push(a[i]);
      }
      return values;
    }
    genericTabs(childElems).forEach(function(item, index, array) {
      lastTabIndex = index;
      lastTabIndexElems = item;
      values = array;
      return lastTabIndex, lastTabIndexElems, values;
    });

    function nav(ev) {
      var next = currentIndex + ev;
      var items = document.querySelectorAll(".items");
      currentIndex = next;
      var targetElement = items[next];
      targetElement.focus();
    }

    var handleKeydown = function(e) {
      switch(e.key) {
        case 'ArrowUp':
          nav(-1);
          console.log('You click on ArrowUp', e.which || e.keyCode);
          break;
        case 'ArrowDown':
          nav(1);
          console.log('You click on ArrowDown', e.which || e.keyCode)
          break;
        case 'ArrowRight':
          nav(1);
          console.log('You click on ArrowRight', e.which || e.keyCode)
          break;
        case 'ArrowLeft':
          nav(-1);
          console.log('You click on ArrowLeft', e.which || e.keyCode)
          break;
      }
    };
    document.activeElement.addEventListener('keydown', handleKeydown, true);
  };

  var softkeyCallback = {
    left: function() { console.log('You click on SoftLeft') },
    center: function() {
      console.log('You click on Enter')

    },
    right: function() { console.log('You click on SoftRight') }
  };
  function handleKeyDownEvent(evt) {
    switch (evt.key) {
        case 'SoftLeft':
            // Action case press left key
            softkeyCallback.left();
        break;

        case 'SoftRight':
            // Action case press right key
            softkeyCallback.right();
        break;

        case 'Enter':
            // Action case press center key
            softkeyCallback.center();
        break;
    }
  };

  domReady(function() {
    kaiosPadNav();
    document.addEventListener('keydown', handleKeyDownEvent);
  });
})();
<|endoftext|>


<commit_before>/*
 * Checks that the links in the navbar on the homepage have the right URLs to redirect to
 *
 * Test cases: https://github.com/LLK/scratch-www/wiki/Most-Important-Workflows#Create_should_take_you_to_the_editor
 */

var tap=require('tap');
var seleniumWebdriver = require('selenium-webdriver');

//chrome driver
var driver = new seleniumWebdriver.Builder().withCapabilities(seleniumWebdriver.Capabilities.chrome()).build();
//open scratch.ly in a new instance of the browser
driver.get('https://scratch.ly');

//find the create link within the navbar
//the create link depends on whether the user is signed in or not (tips window opens)
tap.test('checkCreateLinkWhenSignedOut', function (t) {
    var xPathLink = '//li[contains(@class, "link") and contains(@class, "create")]/a';
    var createLinkSignedOut = driver.findElement(seleniumWebdriver.By.xpath(xPathLink));
    createLinkSignedOut.getAttribute('href').then( function (url) {
        //expected value of the href
        var expectedHref = '/projects/editor/?tip_bar=home';
        //the create href should match `/projects/editor/?tip_bar=home`
        //the create href should be at the end of the URL
        t.equal(url.substr(-expectedHref.length), expectedHref);
        console.log(url.substr(-expectedHref.length));
        t.end();
    });
});

// close the instance of the browser
driver.quit();

<commit_msg>removed console log statement accidentally left from testing<commit_after>/*
 * Checks that the links in the navbar on the homepage have the right URLs to redirect to
 *
 * Test cases: https://github.com/LLK/scratch-www/wiki/Most-Important-Workflows#Create_should_take_you_to_the_editor
 */

var tap=require('tap');
var seleniumWebdriver = require('selenium-webdriver');

//chrome driver
var driver = new seleniumWebdriver.Builder().withCapabilities(seleniumWebdriver.Capabilities.chrome()).build();
//open scratch.ly in a new instance of the browser
driver.get('https://scratch.ly');

//find the create link within the navbar
//the create link depends on whether the user is signed in or not (tips window opens)
tap.test('checkCreateLinkWhenSignedOut', function (t) {
    var xPathLink = '//li[contains(@class, "link") and contains(@class, "create")]/a';
    var createLinkSignedOut = driver.findElement(seleniumWebdriver.By.xpath(xPathLink));
    createLinkSignedOut.getAttribute('href').then( function (url) {
        //expected value of the href
        var expectedHref = '/projects/editor/?tip_bar=home';
        //the create href should match `/projects/editor/?tip_bar=home`
        //the create href should be at the end of the URL
        t.equal(url.substr(-expectedHref.length), expectedHref);
        t.end();
    });
});

// close the instance of the browser
driver.quit();

<|endoftext|>


<commit_before>var should   = require('should');
var helper   = require('../support/spec_helper');
var common   = require('../common');
var ORM      = require('../../');

// Only MySql support for now
if (common.protocol() != 'mysql') return;

describe("Timezones", function() {
	var db    = null;
	var Event = null;

	var setup = function (opts) {
		return function (done) {
			helper.connect({ query: opts.query }, function (connection) {
				db = connection;
				db.settings.set('instance.cache', false);

				Event = db.define("event", {
					name : { type: 'text' },
					when : { type: 'date', time: true }
				});

				if (opts.sync) {
					return helper.dropSync(Event, done);
				} else {
					return done();
				}
			});
		};
	};

	describe("specified", function () {
		var a, zones = ['local', '-0734', '+11:22'];

		for (a = 0; a < zones.length; a++ ) {
			describe(zones[a], function () {
				before(setup({ sync: true, query: { timezone: zones[a] } }));

				after(function () {
					return db.close();
				});

				it("should get back the same date that was stored", function (done) {
					var when = new Date(2013,12,5,11,34,27);

					Event.create({ name: "raid fridge", when: when }, function (err) {
						should.not.exist(err);

						Event.one({ name: "raid fridge" }, function (err, item) {
							should.not.exist(err);
							when.should.eql(item.when);

							done();
						});
					});
				});
			});
		}
	});

	describe("different for each connection", function () {
		before(setup({ query: { timezone: '-1234' } }));

		after(function () {
			return db.close();
		});

		it("should get back a correctly offset time", function (done) {
			var when = new Date(2013,12,5,5,34,27);

			setup({ sync: true, query: { timezone: '+0200' }})(function () {
				Event.create({ name: "raid fridge", when: when }, function (err) {
					should.not.exist(err);

					Event.one({ name: "raid fridge" }, function (err, item) {
						should.not.exist(err);
						when.should.eql(item.when);

						db.close();

						setup({ query: { timezone: '+0400' }})(function () {
							Event.one({ name: "raid fridge" }, function (err, item) {
								var expected = new Date(2013,12,5,3,34,27);

								should.not.exist(err);
								expected.should.eql(item.when);

								done();
							});
						});
					});
				});
			});
		});
	});

});
<commit_msg>Adjust timezone test<commit_after>var should   = require('should');
var helper   = require('../support/spec_helper');
var common   = require('../common');
var ORM      = require('../../');

// Only MySql support for now
if (common.protocol() != 'mysql') return;

describe("Timezones", function() {
	var db    = null;
	var Event = null;

	var setup = function (opts) {
		return function (done) {
			helper.connect({ query: opts.query }, function (connection) {
				db = connection;
				db.settings.set('instance.cache', false);

				Event = db.define("event", {
					name : { type: 'text' },
					when : { type: 'date', time: true }
				});

				if (opts.sync) {
					return helper.dropSync(Event, done);
				} else {
					return done();
				}
			});
		};
	};

	describe("specified", function () {
		var a, zones = ['local', '-0734', '+11:22'];

		for (a = 0; a < zones.length; a++ ) {
			describe(zones[a], function () {
				before(setup({ sync: true, query: { timezone: zones[a] } }));

				after(function () {
					return db.close();
				});

				it("should get back the same date that was stored", function (done) {
					var when = new Date(2013,12,5,5,34,27);

					Event.create({ name: "raid fridge", when: when }, function (err) {
						should.not.exist(err);

						Event.one({ name: "raid fridge" }, function (err, item) {
							should.not.exist(err);
							when.should.eql(item.when);

							done();
						});
					});
				});
			});
		}
	});

	describe("different for each connection", function () {
		after(function () {
			return db.close();
		});

		it("should get back a correctly offset time", function (done) {
			var when = new Date(2013,12,5,5,34,27);

			setup({ sync: true, query: { timezone: '+0200' }})(function () {
				Event.create({ name: "raid fridge", when: when }, function (err) {
					should.not.exist(err);

					Event.one({ name: "raid fridge" }, function (err, item) {
						should.not.exist(err);
						when.should.eql(item.when);

						db.close();

						setup({ query: { timezone: '+0400' }})(function () {
							Event.one({ name: "raid fridge" }, function (err, item) {
								var expected = new Date(2013,12,5,3,34,27);

								should.not.exist(err);
								expected.should.eql(item.when);

								done();
							});
						});
					});
				});
			});
		});
	});

});
<|endoftext|>


<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import * as timeline from './timeline';

function waitTime(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time);
    });
};

export class ActionPlayback {

    constructor() {
        this._timer = 0;
        this._current = 0;

        this._ops = [];
        this._currentOpIndex = 0;

        this._isLastOpMousewheel = false;
    }

    getContext() {
        return {
            elapsedTime: this._elapsedTime,
            currentOpIndex: this._currentOpIndex,
            isLastOpMouseWheel: this._isLastOpMousewheel
        }
    }

    _reset() {
        this._currentOpIndex = 0;
        this._current = Date.now();
        this._elapsedTime = 0;
        this._isLastOpMousewheel = false;
    }

    _restoreContext(ctx) {
        this._elapsedTime = ctx.elapsedTime;
        this._currentOpIndex = ctx.currentOpIndex;
        this._isLastOpMousewheel = ctx.isLastOpMouseWheel;
    }

    async runAction(action, ctxToRestore) {
        this.stop();

        if (!action.ops.length) {
            return;
        }

        this._ops = action.ops.slice().sort((a, b) => {
            return a.time - b.time;
        });
        let firstOp = this._ops[0];
        this._ops.forEach(op => {
            op.time -= firstOp.time;
        });

        this._reset();

        if (ctxToRestore) {
            this._restoreContext(ctxToRestore);
            // Usually restore context happens when page is reloaded after mouseup.
            // In this case the _currentOpIndex is not increased yet.
            this._currentOpIndex++;
        }

        let self = this;

        async function takeScreenshot() {
            // Pause timeline when doing screenshot to avoid screenshot needs taking a while.
            timeline.pause();
            await __VRT_ACTION_SCREENSHOT__(action);
            timeline.resume();
        }

        return new Promise((resolve, reject) => {
            async function tick() {
                let current = Date.now();
                let dTime = current - self._current;
                self._elapsedTime += dTime;
                self._current = current;

                try {
                    // Execute all if there are multiple ops in one frame.
                    do {
                        const executed = await self._update(takeScreenshot);
                        if (!executed) {
                            break;
                        }
                    } while (true);
                }
                catch (e) {
                    // Stop running and throw error.
                    reject(e);
                    return;
                }

                if (self._currentOpIndex >= self._ops.length) {
                    // Finished
                    resolve();
                }
                else {
                    self._timer = setTimeout(tick, 0);
                }
            }
            tick();
        });
    }

    stop() {
        if (this._timer) {
            clearTimeout(this._timer);
            this._timer = 0;
        }
    }

    async _update(takeScreenshot) {
        let op = this._ops[this._currentOpIndex];

        if (!op || (op.time > this._elapsedTime)) {
            // Not yet.
            return;
        }

        let screenshotTaken = false;
        switch (op.type) {
            case 'mousedown':
                // Pause timeline to avoid frame not sync.
                timeline.pause();
                await __VRT_MOUSE_MOVE__(op.x, op.y);
                await __VRT_MOUSE_DOWN__();
                timeline.resume();
                break;
            case 'mouseup':
                timeline.pause();
                await __VRT_MOUSE_MOVE__(op.x, op.y);
                await __VRT_MOUSE_UP__();
                if (window.__VRT_RELOAD_TRIGGERED__) {
                    return;
                }
                timeline.resume();
                break;
            case 'mousemove':
                timeline.pause();
                await __VRT_MOUSE_MOVE__(op.x, op.y);
                timeline.resume();
                break;
            case 'mousewheel':
                let element = document.elementFromPoint(op.x, op.y);
                // Here dispatch mousewheel event because echarts used it.
                // TODO Consider upgrade?
                let event = new WheelEvent('mousewheel', {
                    // PENDING
                    // Needs inverse delta?
                    deltaY: op.deltaY,
                    clientX: op.x, clientY: op.y,
                    // Needs bubble to parent container
                    bubbles: true
                });
                element.dispatchEvent(event);
                this._isLastOpMousewheel = true;
                break;
            case 'screenshot':
                await takeScreenshot();
                screenshotTaken = true;
                break;
            case 'valuechange':
                document.querySelector(op.selector).value = op.value;
                break;
        }

        this._currentOpIndex++;

        // If next op is an auto screenshot
        let nextOp = this._ops[this._currentOpIndex];
        if (nextOp && nextOp.type === 'screenshot-auto') {
            let delay = nextOp.delay == null ? 400 : nextOp.delay;
            // TODO Configuration time
            await waitTime(delay);
            await takeScreenshot();
            screenshotTaken = true;
            this._currentOpIndex++;
        }

        if (this._isLastOpMousewheel && op.type !== 'mousewheel') {
            // Only take screenshot after mousewheel finished
            if (!screenshotTaken) {
                await takeScreenshot();
            }
            this._isLastOpMousewheel = false;
        }

        return true;
    }
};<commit_msg>test(vrt): fix changing value of select via js doesn't trigger `change` event.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import * as timeline from './timeline';

function waitTime(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time);
    });
};

export class ActionPlayback {

    constructor() {
        this._timer = 0;
        this._current = 0;

        this._ops = [];
        this._currentOpIndex = 0;

        this._isLastOpMousewheel = false;
    }

    getContext() {
        return {
            elapsedTime: this._elapsedTime,
            currentOpIndex: this._currentOpIndex,
            isLastOpMouseWheel: this._isLastOpMousewheel
        }
    }

    _reset() {
        this._currentOpIndex = 0;
        this._current = Date.now();
        this._elapsedTime = 0;
        this._isLastOpMousewheel = false;
    }

    _restoreContext(ctx) {
        this._elapsedTime = ctx.elapsedTime;
        this._currentOpIndex = ctx.currentOpIndex;
        this._isLastOpMousewheel = ctx.isLastOpMouseWheel;
    }

    async runAction(action, ctxToRestore) {
        this.stop();

        if (!action.ops.length) {
            return;
        }

        this._ops = action.ops.slice().sort((a, b) => {
            return a.time - b.time;
        });
        let firstOp = this._ops[0];
        this._ops.forEach(op => {
            op.time -= firstOp.time;
        });

        this._reset();

        if (ctxToRestore) {
            this._restoreContext(ctxToRestore);
            // Usually restore context happens when page is reloaded after mouseup.
            // In this case the _currentOpIndex is not increased yet.
            this._currentOpIndex++;
        }

        let self = this;

        async function takeScreenshot() {
            // Pause timeline when doing screenshot to avoid screenshot needs taking a while.
            timeline.pause();
            await __VRT_ACTION_SCREENSHOT__(action);
            timeline.resume();
        }

        return new Promise((resolve, reject) => {
            async function tick() {
                let current = Date.now();
                let dTime = current - self._current;
                self._elapsedTime += dTime;
                self._current = current;

                try {
                    // Execute all if there are multiple ops in one frame.
                    do {
                        const executed = await self._update(takeScreenshot);
                        if (!executed) {
                            break;
                        }
                    } while (true);
                }
                catch (e) {
                    // Stop running and throw error.
                    reject(e);
                    return;
                }

                if (self._currentOpIndex >= self._ops.length) {
                    // Finished
                    resolve();
                }
                else {
                    self._timer = setTimeout(tick, 0);
                }
            }
            tick();
        });
    }

    stop() {
        if (this._timer) {
            clearTimeout(this._timer);
            this._timer = 0;
        }
    }

    async _update(takeScreenshot) {
        let op = this._ops[this._currentOpIndex];

        if (!op || (op.time > this._elapsedTime)) {
            // Not yet.
            return;
        }

        let screenshotTaken = false;
        switch (op.type) {
            case 'mousedown':
                // Pause timeline to avoid frame not sync.
                timeline.pause();
                await __VRT_MOUSE_MOVE__(op.x, op.y);
                await __VRT_MOUSE_DOWN__();
                timeline.resume();
                break;
            case 'mouseup':
                timeline.pause();
                await __VRT_MOUSE_MOVE__(op.x, op.y);
                await __VRT_MOUSE_UP__();
                if (window.__VRT_RELOAD_TRIGGERED__) {
                    return;
                }
                timeline.resume();
                break;
            case 'mousemove':
                timeline.pause();
                await __VRT_MOUSE_MOVE__(op.x, op.y);
                timeline.resume();
                break;
            case 'mousewheel':
                let element = document.elementFromPoint(op.x, op.y);
                // Here dispatch mousewheel event because echarts used it.
                // TODO Consider upgrade?
                let event = new WheelEvent('mousewheel', {
                    // PENDING
                    // Needs inverse delta?
                    deltaY: op.deltaY,
                    clientX: op.x, clientY: op.y,
                    // Needs bubble to parent container
                    bubbles: true
                });
                element.dispatchEvent(event);
                this._isLastOpMousewheel = true;
                break;
            case 'screenshot':
                await takeScreenshot();
                screenshotTaken = true;
                break;
            case 'valuechange':
                const selector = document.querySelector(op.selector);
                selector.value = op.value;
                // changing value via js won't trigger `change` event, so trigger it manually
                selector.dispatchEvent(new Event('change'));
                break;
        }

        this._currentOpIndex++;

        // If next op is an auto screenshot
        let nextOp = this._ops[this._currentOpIndex];
        if (nextOp && nextOp.type === 'screenshot-auto') {
            let delay = nextOp.delay == null ? 400 : nextOp.delay;
            // TODO Configuration time
            await waitTime(delay);
            await takeScreenshot();
            screenshotTaken = true;
            this._currentOpIndex++;
        }

        if (this._isLastOpMousewheel && op.type !== 'mousewheel') {
            // Only take screenshot after mousewheel finished
            if (!screenshotTaken) {
                await takeScreenshot();
            }
            this._isLastOpMousewheel = false;
        }

        return true;
    }
};
<|endoftext|>


<commit_before>'use strict';

describe('Directive: emuwebapp', function() {

    var httpBackend, elm, scope;
    beforeEach(module('emuwebApp', 'emuwebApp.templates'));

    beforeEach(inject(function($injector, $rootScope, $compile) {
        scope = $rootScope.$new();
        httpBackend = $injector.get('$httpBackend');
        httpBackend.whenGET('schemaFiles/annotationFileSchema.json').respond(annotationFileSchema);
        httpBackend.whenGET('schemaFiles/emuwebappConfigSchema.json').respond(emuwebappConfigSchema);
        httpBackend.whenGET('schemaFiles/DBconfigFileSchema.json').respond(DBconfigFileSchema);
        httpBackend.whenGET('schemaFiles/bundleListSchema.json').respond(bundleListSchema);
        httpBackend.whenGET('schemaFiles/bundleSchema.json').respond(bundleSchema);
        httpBackend.whenGET('schemaFiles/designSchema.json').respond(designSchema);
    }));

    function compileDirective(tpl) {
        if (!tpl) tpl = '<emuwebApp audio-get-url="/testData/oldFormat/msajc003/msajc003.wav" label-get-url="/testData/oldFormat/msajc003/msajc003.TextGrid" label-type="TEXTGRID"></emuwebApp>';
        inject(function($compile) {
            elm = $compile(tpl)(scope);
        });
        scope.$digest();
    }

    it('should set correct values', inject(function ($rootScope, viewState, ConfigProviderService) {
        ConfigProviderService.setVals(defaultEmuwebappConfig);
        viewState.mouseInEmuWebApp = undefined;
        compileDirective();
        $rootScope.$digest();
        expect(ConfigProviderService.embeddedVals.audioGetUrl).toEqual('/testData/oldFormat/msajc003/msajc003.wav');
        expect(ConfigProviderService.embeddedVals.labelGetUrl).toEqual('/testData/oldFormat/msajc003/msajc003.TextGrid');
        expect(ConfigProviderService.embeddedVals.labelType).toEqual('TEXTGRID');
        elm.triggerHandler('mouseenter');
        expect(viewState.mouseInEmuWebApp).toBeTruthy();
        elm.triggerHandler('mouseleave');
        expect(viewState.mouseInEmuWebApp).not.toBeTruthy();
    }));
});<commit_msg>fixed no response handling problem in test<commit_after>'use strict';

describe('Directive: emuwebapp', function() {

    var httpBackend, elm, scope;
    beforeEach(module('emuwebApp', 'emuwebApp.templates'));

    beforeEach(inject(function($injector, $rootScope, $compile) {
        scope = $rootScope.$new();
        httpBackend = $injector.get('$httpBackend');
        httpBackend.whenGET('schemaFiles/annotationFileSchema.json').respond(annotationFileSchema);
        httpBackend.whenGET('schemaFiles/emuwebappConfigSchema.json').respond(emuwebappConfigSchema);
        httpBackend.whenGET('schemaFiles/DBconfigFileSchema.json').respond(DBconfigFileSchema);
        httpBackend.whenGET('schemaFiles/bundleListSchema.json').respond(bundleListSchema);
        httpBackend.whenGET('schemaFiles/bundleSchema.json').respond(bundleSchema);
        httpBackend.whenGET('schemaFiles/designSchema.json').respond(designSchema);
        httpBackend.whenGET('NEWS.md').respond('# I am the fake NEWS.md');
    }));

    function compileDirective(tpl) {
        if (!tpl) tpl = '<emuwebApp audio-get-url="/testData/oldFormat/msajc003/msajc003.wav" label-get-url="/testData/oldFormat/msajc003/msajc003.TextGrid" label-type="TEXTGRID"></emuwebApp>';
        inject(function($compile) {
            elm = $compile(tpl)(scope);
        });
        scope.$digest();
    }

    it('should set correct values', inject(function ($rootScope, viewState, ConfigProviderService) {
        ConfigProviderService.setVals(defaultEmuwebappConfig);
        viewState.mouseInEmuWebApp = undefined;
        compileDirective();
        $rootScope.$digest();
        expect(ConfigProviderService.embeddedVals.audioGetUrl).toEqual('/testData/oldFormat/msajc003/msajc003.wav');
        expect(ConfigProviderService.embeddedVals.labelGetUrl).toEqual('/testData/oldFormat/msajc003/msajc003.TextGrid');
        expect(ConfigProviderService.embeddedVals.labelType).toEqual('TEXTGRID');
        elm.triggerHandler('mouseenter');
        expect(viewState.mouseInEmuWebApp).toBeTruthy();
        elm.triggerHandler('mouseleave');
        expect(viewState.mouseInEmuWebApp).not.toBeTruthy();
    }));
});<|endoftext|>


<commit_before>'use strict';

const expect = require('chai').expect,
    fs = require('fs'),
    fail = expect.fail,
    Exporter = require('../../../lib/export/json_exporter'),
    JDLParser = require('../../../lib/parser/jdl_parser'),
    EntityParser = require('../../../lib/parser/entity_parser'),
    parseFromFiles = require('../../../lib/reader/jdl_reader').parseFromFiles;

describe('::exportToJSON', function () {
  describe('when passing invalid parameters', function () {
    describe('such as undefined', function () {
      it('throws an error', function () {
        try {
          Exporter.exportToJSON();
          fail();
        } catch (error) {
          expect(error.name).to.eq('NullPointerException')
        }
      });
    });
  });
  describe('when passing valid arguments', function () {
    describe('when exporting JDL to entity json for SQL type', function () {
      it('exports it', function () {
        var input = parseFromFiles(['./test/test_files/complex_jdl.jdl']);
        var content = EntityParser.parse({jdlObject: JDLParser.parse(input, 'sql'), databaseType: 'sql'});
        Exporter.exportToJSON(content);
        expect(fs.statSync('.jhipster/Department.json').isFile()).to.be.true;
        expect(fs.statSync('.jhipster/JobHistory.json').isFile()).to.be.true;
        expect(fs.statSync('.jhipster/Job.json').isFile()).to.be.true;
        expect(fs.statSync('.jhipster/Employee.json').isFile()).to.be.true;
        expect(fs.statSync('.jhipster/Location.json').isFile()).to.be.true;
        expect(fs.statSync('.jhipster/Task.json').isFile()).to.be.true;
        expect(fs.statSync('.jhipster/Country.json').isFile()).to.be.true;
        expect(fs.statSync('.jhipster/Region.json').isFile()).to.be.true;
      });
    });
  });
});
<commit_msg>Tried to make the tests pass<commit_after>'use strict';

const expect = require('chai').expect,
    fs = require('fs'),
    fail = expect.fail,
    Exporter = require('../../../lib/export/json_exporter'),
    JDLParser = require('../../../lib/parser/jdl_parser'),
    EntityParser = require('../../../lib/parser/entity_parser'),
    parseFromFiles = require('../../../lib/reader/jdl_reader').parseFromFiles;

describe('::exportToJSON', function () {
  describe('when passing invalid parameters', function () {
    describe('such as undefined', function () {
      it('throws an error', function () {
        try {
          Exporter.exportToJSON();
          fail();
        } catch (error) {
          expect(error.name).to.eq('NullPointerException')
        }
      });
    });
  });
  describe('when passing valid arguments', function () {
    describe('when exporting JDL to entity json for SQL type', function () {
      it('exports it', function () {
        var input = parseFromFiles(['./test/test_files/complex_jdl.jdl']);
        var content = EntityParser.parse({jdlObject: JDLParser.parse(input, 'sql'), databaseType: 'sql'});
        Exporter.exportToJSON(content);
        expect(fs.statSync('./.jhipster/Department.json').isFile()).to.be.true;
        expect(fs.statSync('./.jhipster/JobHistory.json').isFile()).to.be.true;
        expect(fs.statSync('./.jhipster/Job.json').isFile()).to.be.true;
        expect(fs.statSync('./.jhipster/Employee.json').isFile()).to.be.true;
        expect(fs.statSync('./.jhipster/Location.json').isFile()).to.be.true;
        expect(fs.statSync('./.jhipster/Task.json').isFile()).to.be.true;
        expect(fs.statSync('./.jhipster/Country.json').isFile()).to.be.true;
        expect(fs.statSync('./.jhipster/Region.json').isFile()).to.be.true;
      });
    });
  });
});
<|endoftext|>


<commit_before>/* @flow */

const _ = require('lodash')

const {
  assignId,
  assignPlatformIncompatibilities
} = require('../../../../core/metadata')
const timestamp = require('../../../../core/timestamp')

const pouchdbBuilders = require('../pouchdb')

/*::
import type fs from 'fs-extra'
import type {
  Metadata,
  MetadataRemoteInfo,
  MetadataSidesInfo
} from '../../../../core/metadata'
import type Pouch from '../../../../core/pouch'
*/

module.exports = class BaseMetadataBuilder {
  /*::
  pouch: ?Pouch
  opts: {
    path: string,
    ino?: number,
    remote: MetadataRemoteInfo,
    updated_at?: string|Date,
    trashed?: true,
    sides: MetadataSidesInfo
  }
  */

  constructor (pouch /*: ?Pouch */) {
    this.pouch = pouch
    this.opts = {
      path: 'foo',
      remote: {
        _id: pouchdbBuilders.id(),
        _rev: pouchdbBuilders.rev()
      },
      sides: {},
      updated_at: timestamp.stringify(timestamp.current())
    }
  }

  incompatible () /*: this */ {
    const { platform } = process

    if (platform === 'win32' || platform === 'darwin') {
      // Colon is currently considered forbidden on both platforms by the app
      // (although it probably shouldn't on macOS).
      return this.path('in:compatible')
    } else {
      throw new Error(`Cannot build incompatible doc on ${platform}`)
    }
  }

  ino (ino /*: number */) /*: this */ {
    this.opts.ino = ino
    return this
  }

  stats ({ino, mtime, ctime} /*: fs.Stats */) /*: this */ {
    return this.ino(ino).updatedAt(timestamp.maxDate(mtime, ctime))
  }

  path (path /*: string */) /*: this */ {
    this.opts.path = path
    return this
  }

  trashed () /*: this */ {
    this.opts.trashed = true
    return this
  }

  updatedAt (date /*: Date */) /*: this */ {
    this.opts.updated_at = timestamp.fromDate(date).toISOString()
    return this
  }

  newerThan (doc /*: Metadata */) /*: this */ {
    this.opts.updated_at = new Date(timestamp.fromDate(doc.updated_at) + 2000)
    return this
  }

  olderThan (doc /*: Metadata */) /*: this */ {
    this.opts.updated_at = new Date(timestamp.fromDate(doc.updated_at) - 2000)
    return this
  }

  remoteId (_id /*: string */) /*: this */ {
    this.opts.remote = {
      _id,
      _rev: pouchdbBuilders.rev()
    }
    return this
  }

  upToDate () /*: this */ {
    this.opts.sides = {local: 1, remote: 1}
    return this
  }

  notUpToDate () /*: this */ {
    this.opts.sides = {remote: 1}
    return this
  }

  attributesByType () /*: * */ {
    throw new Error('BaseMetadataBuilder#attributesByType() not implemented')
  }

  build () /*: Metadata */ {
    const doc = _.merge({
      _id: '',
      tags: [],
      updated_at: new Date()
    }, this.opts, this.attributesByType())

    assignId(doc)
    // Don't detect incompatibilities according to syncPath for test data, to
    // prevent environment related failures.
    assignPlatformIncompatibilities(doc, '')

    return doc
  }

  async create () /*: Promise<Metadata> */ {
    if (this.pouch == null) {
      throw new Error('Cannot create dir metadata without Pouch')
    }
    const doc = this.build()
    // $FlowFixMe
    const {rev} = await this.pouch.put(doc)
    doc._rev = rev
    return doc
  }
}
<commit_msg>test/support/builders/metadata: Add #rev() & #sides()<commit_after>/* @flow */

const _ = require('lodash')

const {
  assignId,
  assignPlatformIncompatibilities
} = require('../../../../core/metadata')
const timestamp = require('../../../../core/timestamp')

const pouchdbBuilders = require('../pouchdb')

/*::
import type fs from 'fs-extra'
import type {
  Metadata,
  MetadataRemoteInfo,
  MetadataSidesInfo,
  SideName
} from '../../../../core/metadata'
import type Pouch from '../../../../core/pouch'
*/

module.exports = class BaseMetadataBuilder {
  /*::
  pouch: ?Pouch
  opts: {
    _rev?: string,
    path: string,
    ino?: number,
    remote: MetadataRemoteInfo,
    updated_at?: string|Date,
    trashed?: true,
    sides: MetadataSidesInfo
  }
  */

  constructor (pouch /*: ?Pouch */) {
    this.pouch = pouch
    this.opts = {
      path: 'foo',
      remote: {
        _id: pouchdbBuilders.id(),
        _rev: pouchdbBuilders.rev()
      },
      sides: {},
      updated_at: timestamp.stringify(timestamp.current())
    }
  }

  rev (rev /*: string */) /*: this */ {
    this.opts._rev = rev
    return this
  }

  incompatible () /*: this */ {
    const { platform } = process

    if (platform === 'win32' || platform === 'darwin') {
      // Colon is currently considered forbidden on both platforms by the app
      // (although it probably shouldn't on macOS).
      return this.path('in:compatible')
    } else {
      throw new Error(`Cannot build incompatible doc on ${platform}`)
    }
  }

  ino (ino /*: number */) /*: this */ {
    this.opts.ino = ino
    return this
  }

  stats ({ino, mtime, ctime} /*: fs.Stats */) /*: this */ {
    return this.ino(ino).updatedAt(timestamp.maxDate(mtime, ctime))
  }

  path (path /*: string */) /*: this */ {
    this.opts.path = path
    return this
  }

  trashed () /*: this */ {
    this.opts.trashed = true
    return this
  }

  updatedAt (date /*: Date */) /*: this */ {
    this.opts.updated_at = timestamp.fromDate(date).toISOString()
    return this
  }

  newerThan (doc /*: Metadata */) /*: this */ {
    this.opts.updated_at = new Date(timestamp.fromDate(doc.updated_at) + 2000)
    return this
  }

  olderThan (doc /*: Metadata */) /*: this */ {
    this.opts.updated_at = new Date(timestamp.fromDate(doc.updated_at) - 2000)
    return this
  }

  remoteId (_id /*: string */) /*: this */ {
    this.opts.remote = {
      _id,
      _rev: pouchdbBuilders.rev()
    }
    return this
  }

  upToDate () /*: this */ {
    this.opts.sides = {local: 1, remote: 1}
    return this
  }

  notUpToDate () /*: this */ {
    this.opts.sides = {remote: 1}
    return this
  }

  sides (sides /*: MetadataSidesInfo */) /*: this */ {
    this.opts.sides = sides
    return this
  }

  attributesByType () /*: * */ {
    throw new Error('BaseMetadataBuilder#attributesByType() not implemented')
  }

  build () /*: Metadata */ {
    const doc = _.merge({
      _id: '',
      tags: [],
      updated_at: new Date()
    }, this.opts, this.attributesByType())

    assignId(doc)
    // Don't detect incompatibilities according to syncPath for test data, to
    // prevent environment related failures.
    assignPlatformIncompatibilities(doc, '')

    return doc
  }

  async create () /*: Promise<Metadata> */ {
    if (this.pouch == null) {
      throw new Error('Cannot create dir metadata without Pouch')
    }
    const doc = this.build()
    // $FlowFixMe
    const {rev} = await this.pouch.put(doc)
    doc._rev = rev
    return doc
  }
}
<|endoftext|>


<commit_before>'use strict';

const trackRegEx = new RegExp(String.fromCharCode(160), 'g');

Connector.playerSelector = '.m-playbar';

Connector.getTrackArt = () => {
	let src = $('.head.j-flag img').attr('src');
	return src.split('?').shift();
};

Connector.getTrack = () => {
	let track = $('.fc1').text();
	return track.replace(trackRegEx, ' ');
};

Connector.getArtist = () => $('.by span').attr('title');

Connector.playButtonSelector = '.btns .ply';

Connector.timeInfoSelector = '.j-flag.time';

Connector.isPlaying = () => $('.btns .ply').hasClass('pas');

Connector.getUniqueID = () => $('.fc1').attr('href').substr(9);
<commit_msg>163 music: fix isPlaying<commit_after>'use strict';

const trackRegEx = new RegExp(String.fromCharCode(160), 'g');

Connector.playerSelector = '.m-playbar';

Connector.getTrackArt = () => {
	let src = $('.head.j-flag img').attr('src');
	return src.split('?').shift();
};

Connector.getTrack = () => {
	let track = $('.fc1').text();
	return track.replace(trackRegEx, ' ');
};

Connector.getArtist = () => $('.by span').attr('title');

Connector.playButtonSelector = '[data-action="play"]';

Connector.timeInfoSelector = '.time';

Connector.getUniqueID = () => $('.fc1').attr('href').split('id=').pop();
<|endoftext|>


<commit_before>var geoip = require('geoip-lite');
var net = require('net');

var local_ip, local_geoip;

exports.hook_connect = function (next, connection) {
    var plugin = this;
    connection.notes.geoip = geoip.lookup(connection.remote_ip);

    if (!connection.notes.geoip) return next();

    var cfg = this.config.get('connect.geoip.ini');
    calculate_distance(plugin, connection, cfg);

    connection.notes.geoip.human = get_results(connection, cfg);
    connection.loginfo(plugin, connection.notes.geoip.human);

    return next();
};

exports.hook_data_post = function (next, connection) {
    var txn = connection.transaction;
    txn.remove_header('X-Haraka-GeoIP');
    txn.remove_header('X-Haraka-GeoIP-Received');
    if (connection.notes.geoip) {
        var cfg = this.config.get('connect.geoip.ini');
        txn.add_header('X-Haraka-GeoIP', get_results(connection, cfg));
    }

    var received = [];

    var rh = received_headers(connection, this);
    if (rh) received.push(rh);
    if (!rh) user_agent(connection, this); // No received headers.

    var oh = originating_headers(connection, this);
    if (oh) received.push(oh);

    // Add any received results to a trace header
    if (received.length) {
        txn.add_header('X-Haraka-GeoIP-Received', received.join(' '));
    }
    return next();
};

function calculate_distance(plugin, connection, cfg) {
    if (!cfg.main.calc_distance) return;

    if (!local_ip) { local_ip = cfg.main.public_ip; }
    if (!local_ip) { local_ip = connection.local_ip; }
    if (!local_ip) return;

    if (!local_geoip) { local_geoip = geoip.lookup(local_ip); }
    if (!local_geoip) return;

    var gcd = haversine(local_geoip.ll[0], local_geoip.ll[1],
        connection.notes.geoip.ll[0], connection.notes.geoip.ll[1]);

    if (cfg.main.too_far && (parseFloat(cfg.main.too_far) < parseFloat(gcd))) {
        connection.notes.geoip.too_far=true;
    }
    connection.notes.geoip.distance = gcd;
}

function haversine(lat1, lon1, lat2, lon2) {
    // calculate the great circle distance using the haversine formula
    // found here: http://www.movable-type.co.uk/scripts/latlong.html
    var R = 6371; // km
    function toRad(v) { return v * Math.PI / 180; };
    var dLat = toRad(lat2-lat1);
    var dLon = toRad(lon2-lon1);
    var lat1 = toRad(lat1);
    var lat2 = toRad(lat2);

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;
    return d.toFixed(0);
}

function get_results(connection, cfg) {
    var r = connection.notes.geoip;
    if (!r) return '';

    // geoip.lookup results look like this:
    // range: [ 3479299040, 3479299071 ],
    //    country: 'US',
    //    region: 'CA',
    //    city: 'San Francisco',
    //    ll: [37.7484, -122.4156]

    var show = [ r.country ];
    if (r.region   && cfg.main.show_region  ) show.push(r.region);
    if (r.city     && cfg.main.show_city    ) show.push(r.city);
    if (r.distance && cfg.main.calc_distance) show.push(r.distance+'km');

    return show.join(', ');
};

function user_agent(connection, plugin) {
    // Check for User-Agent
    var ua = connection.transaction.header.get('user-agent');
    var xm = connection.transaction.header.get('x-mailer');
    var xmu = connection.transaction.header.get('x-mua');
    if (ua || xm || xmu) {
        connection.loginfo(plugin, 'direct-to-mx?');
    }
};

function received_headers(connection, plugin) {
    var txn = connection.transaction;
    var received = txn.header.get_all('received');
    if (!received.length) return;

    var results = [];

    // Try and parse each received header
    for (var i=0; i < received.length; i++) {
        var match = /\[(\d+\.\d+\.\d+\.\d+)\]/.exec(received[i]);
        if (match && net.isIPv4(match[1])) {
            var gi = geoip.lookup(match[1]);
            connection.loginfo(plugin, 'received=' + match[1] + ' country=' + ((gi) ? gi.country : 'UNKNOWN'));
            results.push(match[1] + ':' + ((gi) ? gi.country : 'UNKNOWN'));
        }
    }
    return results;
};

function originating_headers(connection, plugin) {
    var txn = connection.transaction;

    // Try and parse any originating IP headers
    var orig = txn.header.get('x-originating-ip') ||
               txn.header.get('x-ip') ||
               txn.header.get('x-remote-ip');

    if (!orig) return;

    var match = /(\d+\.\d+\.\d+\.\d+)/.exec(orig);
    if (!match) return;
    var found_ip = match[1];
    if (!net.isIPv4(found_ip)) return;

    var gi = geoip.lookup(found_ip);
    connection.loginfo(plugin, 'originating=' + found_ip + ' country=' + ((gi) ? gi.country : 'UNKNOWN'));
    return found_ip + ':' + ((gi) ? gi.country : 'UNKNOWN');
}
<commit_msg>don't geolocate Private IPs, use ResultStore<commit_after>var geoip = require('geoip-lite');
var net = require('net');
var net_utils = require('./net_utils');

var local_ip, local_geoip;

exports.hook_connect = function (next, connection) {
    var plugin = this;

    // geoip.lookup results look like this:
    // range: [ 3479299040, 3479299071 ],
    //    country: 'US',
    //    region: 'CA',
    //    city: 'San Francisco',
    //    ll: [37.7484, -122.4156]

    var r = geoip.lookup(connection.remote_ip);
    if (!r) return next();

    connection.results.add(plugin, r);

    var cfg = plugin.config.get('connect.geoip.ini');
    if (cfg.main.calc_distance) plugin.calculate_distance(connection, r);

    var show = [ r.country ];
    if (r.region   && cfg.main.show_region  ) show.push(r.region);
    if (r.city     && cfg.main.show_city    ) show.push(r.city);
    if (r.distance && cfg.main.calc_distance) show.push(r.distance+'km');

    connection.results.add(plugin, {human: show.join(', '), emit:true});

    return next();
};

exports.hook_data_post = function (next, connection) {
    var plugin = this;
    var txn = connection.transaction;
    if (!txn) return;
    txn.remove_header('X-Haraka-GeoIP');
    txn.remove_header('X-Haraka-GeoIP-Received');
    var geoip = connection.results.get('connect.geoip');
    if (geoip) {
        txn.add_header('X-Haraka-GeoIP', geoip.human);
    }

    var received = [];

    var rh = plugin.received_headers(connection);
    if (rh) received.push(rh);
    if (!rh) plugin.user_agent(connection); // No received headers.

    var oh = plugin.originating_headers(connection);
    if (oh) received.push(oh);

    // Add any received results to a trace header
    if (received.length) {
        txn.add_header('X-Haraka-GeoIP-Received', received.join(' '));
    }
    return next();
};

exports.calculate_distance = function (connection, r_geoip) {
    var plugin = this;
    var cfg = plugin.config.get('connect.geoip.ini');

    if (!local_ip) { local_ip = cfg.main.public_ip; }
    if (!local_ip) { local_ip = connection.local_ip; }
    if (!local_ip) {
        connection.logerror(plugin, "can't calculate distance without local IP!");
        return;
    }

    if (!local_geoip) { local_geoip = geoip.lookup(local_ip); }
    if (!local_geoip) {
        connection.logerror(plugin, "no GeoIP results for local_ip!");
        return;
    }

    var gcd = haversine(local_geoip.ll[0], local_geoip.ll[1], r_geoip.ll[0], r_geoip.ll[1]);

    connection.results.add(plugin, {distance: gcd});

    if (cfg.main.too_far && (parseFloat(cfg.main.too_far) < parseFloat(gcd))) {
        connection.results.add(plugin, {too_far: true});
    }
};

function haversine(lat1, lon1, lat2, lon2) {
    // calculate the great circle distance using the haversine formula
    // found here: http://www.movable-type.co.uk/scripts/latlong.html
    var R = 6371; // km
    function toRad(v) { return v * Math.PI / 180; };
    var dLat = toRad(lat2-lat1);
    var dLon = toRad(lon2-lon1);
    var lat1 = toRad(lat1);
    var lat2 = toRad(lat2);

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;
    return d.toFixed(0);
}

exports.received_headers = function (connection) {
    var plugin = this;
    var txn = connection.transaction;
    var received = txn.header.get_all('received');
    if (!received.length) return;

    var results = [];

    // Try and parse each received header
    for (var i=0; i < received.length; i++) {
        var match = /\[(\d+\.\d+\.\d+\.\d+)\]/.exec(received[i]);
        if (!match) continue;
        if (!net.isIPv4(match[1])) continue;  // TODO: support IPv6
        if (net_utils.is_rfc1918(match[1])) continue;  // exclude private IP

        var gi = geoip.lookup(match[1]);
        connection.loginfo(plugin, 'received=' + match[1] + ' country=' + ((gi) ? gi.country : 'UNKNOWN'));
        results.push(match[1] + ':' + ((gi) ? gi.country : 'UNKNOWN'));
    }
    return results;
};

exports.originating_headers = function (connection) {
    var plugin = this;
    var txn = connection.transaction;

    // Try and parse any originating IP headers
    var orig = txn.header.get('x-originating-ip') ||
               txn.header.get('x-ip') ||
               txn.header.get('x-remote-ip');

    if (!orig) return;

    var match = /(\d+\.\d+\.\d+\.\d+)/.exec(orig);
    if (!match) return;
    var found_ip = match[1];
    if (!net.isIPv4(found_ip)) return;
    if (net_utils.is_rfc1918(found_ip)) return;

    var gi = geoip.lookup(found_ip);
    connection.loginfo(plugin, 'originating=' + found_ip + ' country=' + ((gi) ? gi.country : 'UNKNOWN'));
    return found_ip + ':' + ((gi) ? gi.country : 'UNKNOWN');
};
<|endoftext|>


<commit_before>L.FreeRotateAction = L.EditAction.extend({
  initialize: function(map, overlay, options) {
    options = options || {};
    options.toolbarIcon = {
      svg: true,
      html: 'crop_rotate',
      tooltip: overlay.options.translation.freeRotateImage,
      className: 'freeRotate',
    };

    L.DistortableImage.action_map.f = '_freeRotateMode';
    L.EditAction.prototype.initialize.call(this, map, overlay, options);
  },

  addHooks: function() {
    var edit = this._overlay.editing;
    edit._freeRotateMode();
  },
});
<commit_msg>Update method creation syntax to ES6 FreeRotationAction.js<commit_after>L.FreeRotateAction = L.EditAction.extend({
  initialize(map, overlay, options) {
    options = options || {};
    options.toolbarIcon = {
      svg: true,
      html: 'crop_rotate',
      tooltip: overlay.options.translation.freeRotateImage,
      className: 'freeRotate',
    };

    L.DistortableImage.action_map.f = '_freeRotateMode';
    L.EditAction.prototype.initialize.call(this, map, overlay, options);
  },

  addHooks() {
    var edit = this._overlay.editing;
    edit._freeRotateMode();
  },
});
<|endoftext|>


<commit_before>
function readText(uri){
  var jf = new java.io.File(uri);
  var sb = new java.lang.StringBuffer();
  var input = new java.io.BufferedReader(new java.io.FileReader(jf));
  var line = "";
  var str = "";
  while((line = input.readLine()) != null){
    sb.append(line);
    sb.append(java.lang.System.getProperty("line.separator"));
  }
  // Cast to real JS String
  str += sb.toString();
  return str;
}
function alert(str) {
  throw(str);
}

function main(args) {
  // Upgrade passed script args to real Array
  if (!args.length) {
    print('Usage: rhino preparse.js zoneFileDirectory [exemplarCities] > outputfile.json');
    print('Ex. >>> rhino preparse.js olson_files "Asia/Tokyo, America/New_York, Europe/London" > major_cities.json');
    print('Ex. >>> rhino preparse.js olson_files > all_cities.json');
    return;
  }
  var baseDir = args[0];
  var cities = args[1];
  load('date.js');
  load('../../src/json.js');
  var _tz = fleegix.date.timezone;
  _tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
  for (var i = 0; i < _tz.zoneFiles.length; i++) {
    var zoneFile = _tz.zoneFiles[i];
    var zoneData = readText(baseDir + '/' + zoneFile);
    _tz.parseZones(zoneData);
  }
  var result = {};
  if (cities) {
    cities = cities.replace(/ /g, '').split(',');
    var zones = {};
    var rules = {};
    for (var i = 0; i < cities.length; i++) {
      var city = cities[i];
      zones[city] = _tz.zones[city];
    }
    for (var n in zones) {
      var zList = zones[n];
      for (var i = 0; i < zList.length; i++) {
        var ruleKey = zList[i][1];
        rules[ruleKey] = _tz.rules[ruleKey];
      }
    }
    result.zones = zones;
    result.rules = rules;
  }
  else {
    result.zones = _tz.zones;
    result.rules = _tz.rules
  }
  result = fleegix.json.serialize(result);
  print(result);
}

main(arguments);

<commit_msg>Removed reimplemented 'alert' function. The alert function is no longer used in the timezone code.<commit_after>
function readText(uri){
  var jf = new java.io.File(uri);
  var sb = new java.lang.StringBuffer();
  var input = new java.io.BufferedReader(new java.io.FileReader(jf));
  var line = "";
  var str = "";
  while((line = input.readLine()) != null){
    sb.append(line);
    sb.append(java.lang.System.getProperty("line.separator"));
  }
  // Cast to real JS String
  str += sb.toString();
  return str;
}

function main(args) {
  // Upgrade passed script args to real Array
  if (!args.length) {
    print('Usage: rhino preparse.js zoneFileDirectory [exemplarCities] > outputfile.json');
    print('Ex. >>> rhino preparse.js olson_files "Asia/Tokyo, America/New_York, Europe/London" > major_cities.json');
    print('Ex. >>> rhino preparse.js olson_files > all_cities.json');
    return;
  }
  var baseDir = args[0];
  var cities = args[1];
  load('date.js');
  load('../../src/json.js');
  var _tz = fleegix.date.timezone;
  _tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
  for (var i = 0; i < _tz.zoneFiles.length; i++) {
    var zoneFile = _tz.zoneFiles[i];
    var zoneData = readText(baseDir + '/' + zoneFile);
    _tz.parseZones(zoneData);
  }
  var result = {};
  if (cities) {
    cities = cities.replace(/ /g, '').split(',');
    var zones = {};
    var rules = {};
    for (var i = 0; i < cities.length; i++) {
      var city = cities[i];
      zones[city] = _tz.zones[city];
    }
    for (var n in zones) {
      var zList = zones[n];
      for (var i = 0; i < zList.length; i++) {
        var ruleKey = zList[i][1];
        rules[ruleKey] = _tz.rules[ruleKey];
      }
    }
    result.zones = zones;
    result.rules = rules;
  }
  else {
    result.zones = _tz.zones;
    result.rules = _tz.rules
  }
  result = fleegix.json.serialize(result);
  print(result);
}

main(arguments);

<|endoftext|>