<commit_before>// ----------------------------------------------------------------------------
//
// connect-blog.js - Blog middleware you can add to your Connect/Express app.
//
// Copyright (c) 2013 Andrew Chilton. All rights resered.
//
// License: http://chilts.mit-license.org/2013/
//
// ----------------------------------------------------------------------------

// core
var fs = require('fs');

// npm
var xtend = require('xtend');
var blogz = require('blogz');

// ----------------------------------------------------------------------------

var defaults = {
    title                : 'Blog',
    description          : '',
    contentDir           : 'blog',
    indexCount           : 10,
    latestCount          : 20,
    basePath             : '',
    indexTemplate        : 'blog-index',
    postTemplate         : 'blog-post',
    tagAllTemplate       : 'blog-tag-all',
    tagOneTemplate       : 'blog-tag-one',
    catAllTemplate       : 'blog-category-all',
    catOneTemplate       : 'blog-category-one',
    archiveAllTemplate   : 'blog-archive-all',
    archiveYearTemplate  : 'blog-archive-year',
    archiveMonthTemplate : 'blog-archive-month',
};

// ----------------------------------------------------------------------------

module.exports = function(args) {
    var opts = xtend({}, defaults, args);

    if ( !opts.domain ) {
        throw new Error("Provide a domain");
    }

    // read in all the blog data (sync - since it's at server startup) (ToDo: change to async)
    var data = blogz.readSync(opts);

    var middleware = function(req, res, next) {
        // for every page (and a side-effect for the feeds), give them each access to these things
        res.locals.blog = {
            title    : opts.title,
            posts    : data.posts,
            pages    : data.pages,
            latest   : data.latest,
            archive  : data.archive,
            tag      : data.tag,
            category : data.category,
            domain   : opts.domain,
            base     : opts.base,

            // Others:
            // * thisPost
            // * thisArchive
            // * thisTagName
            // * thisTag
            // * thesePosts - for blog-index, ???
            // * thisPageNum - for blog-index
            // * prevUrl \_ for blog-post, blog-archive and blog-index
            // * nextUrl /
        };

        var path = req.params.path;

        // this is the index
        if ( !path ) {
            res.locals.blog.thesePosts  = data.pages[0];
            res.locals.blog.thisPageNum = 1;
            res.locals.blog.prevUrl     = undefined;
            res.locals.blog.nextUrl     = data.pages.length > 1 ? './page:2' : undefined;
            return res.render(opts.indexTemplate);
        }

        // look for a page that looks like a blog
        if ( path === 'rss20.xml' ) {
            res.set('Content-Type', 'application/xml');
            return res.send(data.rss);
        }

        if ( path === 'atom.xml' ) {
            res.set('Content-Type', 'application/xml');
            return res.send(data.atom);
        }

        if ( path.indexOf('page:') === 0 ) {
            // Note: the pages are 1..10, but our pages array is 0..9.
            var page = path.split(/:/)[1];

            // Note1: can return NaN, which will fail the following 'if'.
            // Note2: we use +page rather than parseInt(page, 10) since
            //        '1asd' won't give a 1 in the first case, but in the second it will.
            page = +page;

            if ( page > 0 && page <= data.pages.length ) {
                res.locals.blog.thesePosts  = data.pages[page-1];
                res.locals.blog.thisPageNum = page;
                res.locals.blog.prevUrl     = page > 1 ? './page:' + (page-1) : undefined;
                res.locals.blog.nextUrl     = page < data.pages.length ? './page:' + (page+1) : undefined;
                return res.render(opts.indexTemplate);
            }

            // unknown page
            return next();
        }

        if ( path === 'archive' ) {
            res.locals.blog.title = opts.title + ' : Archive';
            return res.render(opts.archiveAllTemplate);
        }

        if ( path.indexOf('archive-') === 0 ) {
            var thisArchive = {};
            var parts = path.split(/-/);
            var thisYear = parts[1];
            var thisMonth = parts[2];
            var template;

            // archive-yyyy
            if ( parts.length === 2 && data.archive[thisYear] ) {
                res.locals.blog.title           = opts.title + ' : Archive : ' + thisYear;
                res.locals.blog.yearNum         = thisYear;
                res.locals.blog.thisArchiveYear = data.archive[thisYear];
                return res.render(opts.archiveYearTemplate);
            }

            // archive-yyyy-mm
            if ( parts.length === 3 && data.archive[thisYear] && data.archive[thisYear][thisMonth] ) {
                res.locals.blog.title            = opts.title + ' : Archive : ' + thisYear + '-' + thisMonth;
                res.locals.blog.yearNum          = thisYear;
                res.locals.blog.monthName        = data.archive[thisYear][thisMonth][0].meta.moment.format('MMM');
                res.locals.blog.thisArchiveMonth = data.archive[thisYear][thisMonth];
                return res.render(opts.archiveMonthTemplate);
            }

            // don't know this format
            return next();
        }

        if ( path === 'tag' ) {
            res.locals.blog.title = opts.title + ' : TagCloud';
            return res.render(opts.tagAllTemplate);
        }

        if ( path.indexOf('tag-') === 0 ) {
            var parts = path.split(/-/);
            var tagName = parts.slice(1).join('-');
            if ( !data.tag[tagName] ) {
                // 404 - Not Found
                return next();
            }

            res.locals.blog.title      = opts.title + ' : Tag : ' + tagName;
            res.locals.blog.tagName    = tagName;
            res.locals.blog.thesePosts = data.tag[tagName];
            return res.render(opts.tagOneTemplate);
        }

        if ( path === 'category' ) {
            res.locals.blog.title = opts.title + ' : CategoryCloud';
            return res.render(opts.catAllTemplate);
        }

        if ( path.indexOf('category-') === 0 ) {
            var parts = path.split(/-/);
            var catName = parts.slice(1).join('-');
            if ( !data.category[catName] ) {
                // 404 - Not Found
                return next();
            }

            res.locals.blog.title      = opts.title + ' : Tag : ' + tagName;
            res.locals.blog.catName    = catName;
            res.locals.blog.thesePosts = data.category[catName];
            return res.render(opts.catOneTemplate);
        }

        // is this a post
        if ( data.post[path] ) {
            res.locals.blog.title    = opts.title + ' : ' + data.post[path].meta.title;
            res.locals.blog.thisPost = data.post[path];
            return res.render(opts.postTemplate);
        }

        // didn't find anything interesting, pass it on
        next();
    };

    // prior to returning, let's put these vars onto this middleware so
    // the user can get access to some interesting things
    middleware.posts    = data.posts;
    middleware.latest   = data.latest;
    middleware.archive  = data.archive;
    middleware.tag      = data.tag;
    middleware.category = data.category;

    middleware.reloadData = function() {
        data = readBlogSync(opts);
        middleware.posts    = data.posts;
        middleware.latest   = data.latest;
        middleware.archive  = data.archive;
        middleware.tag      = data.tag;
        middleware.category = data.category;
    };

    return middleware;
};

// ----------------------------------------------------------------------------
<commit_msg>Remove title prefix from all pages<commit_after>// ----------------------------------------------------------------------------
//
// connect-blog.js - Blog middleware you can add to your Connect/Express app.
//
// Copyright (c) 2013 Andrew Chilton. All rights resered.
//
// License: http://chilts.mit-license.org/2013/
//
// ----------------------------------------------------------------------------

// core
var fs = require('fs');

// npm
var xtend = require('xtend');
var blogz = require('blogz');

// ----------------------------------------------------------------------------

var defaults = {
    title                : '',
    description          : '',
    contentDir           : 'blog',
    indexCount           : 10,
    latestCount          : 20,
    basePath             : '',
    indexTemplate        : 'blog-index',
    postTemplate         : 'blog-post',
    tagAllTemplate       : 'blog-tag-all',
    tagOneTemplate       : 'blog-tag-one',
    catAllTemplate       : 'blog-category-all',
    catOneTemplate       : 'blog-category-one',
    archiveAllTemplate   : 'blog-archive-all',
    archiveYearTemplate  : 'blog-archive-year',
    archiveMonthTemplate : 'blog-archive-month',
};

// ----------------------------------------------------------------------------

module.exports = function(args) {
    var opts = xtend({}, defaults, args);

    if ( !opts.domain ) {
        throw new Error("Provide a domain");
    }

    // read in all the blog data (sync - since it's at server startup) (ToDo: change to async)
    var data = blogz.readSync(opts);

    var middleware = function(req, res, next) {
        // for every page (and a side-effect for the feeds), give them each access to these things
        res.locals.blog = {
            title    : opts.title,
            posts    : data.posts,
            pages    : data.pages,
            latest   : data.latest,
            archive  : data.archive,
            tag      : data.tag,
            category : data.category,
            domain   : opts.domain,
            base     : opts.base,

            // Others:
            // * thisPost
            // * thisArchive
            // * thisTagName
            // * thisTag
            // * thesePosts - for blog-index, ???
            // * thisPageNum - for blog-index
            // * prevUrl \_ for blog-post, blog-archive and blog-index
            // * nextUrl /
        };

        var path = req.params.path;

        // this is the index
        if ( !path ) {
            res.locals.blog.thesePosts  = data.pages[0];
            res.locals.blog.thisPageNum = 1;
            res.locals.blog.prevUrl     = undefined;
            res.locals.blog.nextUrl     = data.pages.length > 1 ? './page:2' : undefined;
            return res.render(opts.indexTemplate);
        }

        // look for a page that looks like a blog
        if ( path === 'rss20.xml' ) {
            res.set('Content-Type', 'application/xml');
            return res.send(data.rss);
        }

        if ( path === 'atom.xml' ) {
            res.set('Content-Type', 'application/xml');
            return res.send(data.atom);
        }

        if ( path.indexOf('page:') === 0 ) {
            // Note: the pages are 1..10, but our pages array is 0..9.
            var page = path.split(/:/)[1];

            // Note1: can return NaN, which will fail the following 'if'.
            // Note2: we use +page rather than parseInt(page, 10) since
            //        '1asd' won't give a 1 in the first case, but in the second it will.
            page = +page;

            if ( page > 0 && page <= data.pages.length ) {
                res.locals.blog.thesePosts  = data.pages[page-1];
                res.locals.blog.thisPageNum = page;
                res.locals.blog.prevUrl     = page > 1 ? './page:' + (page-1) : undefined;
                res.locals.blog.nextUrl     = page < data.pages.length ? './page:' + (page+1) : undefined;
                return res.render(opts.indexTemplate);
            }

            // unknown page
            return next();
        }

        if ( path === 'archive' ) {
            res.locals.blog.title = 'Archive';
            return res.render(opts.archiveAllTemplate);
        }

        if ( path.indexOf('archive-') === 0 ) {
            var thisArchive = {};
            var parts = path.split(/-/);
            var thisYear = parts[1];
            var thisMonth = parts[2];
            var template;

            // archive-yyyy
            if ( parts.length === 2 && data.archive[thisYear] ) {
                res.locals.blog.title           = 'Archive : ' + thisYear;
                res.locals.blog.yearNum         = thisYear;
                res.locals.blog.thisArchiveYear = data.archive[thisYear];
                return res.render(opts.archiveYearTemplate);
            }

            // archive-yyyy-mm
            if ( parts.length === 3 && data.archive[thisYear] && data.archive[thisYear][thisMonth] ) {
                res.locals.blog.title            = 'Archive : ' + thisYear + '-' + thisMonth;
                res.locals.blog.yearNum          = thisYear;
                res.locals.blog.monthName        = data.archive[thisYear][thisMonth][0].meta.moment.format('MMM');
                res.locals.blog.thisArchiveMonth = data.archive[thisYear][thisMonth];
                return res.render(opts.archiveMonthTemplate);
            }

            // don't know this format
            return next();
        }

        if ( path === 'tag' ) {
            res.locals.blog.title = 'Tags';
            return res.render(opts.tagAllTemplate);
        }

        if ( path.indexOf('tag-') === 0 ) {
            var parts = path.split(/-/);
            var tagName = parts.slice(1).join('-');
            if ( !data.tag[tagName] ) {
                // 404 - Not Found
                return next();
            }

            res.locals.blog.title      = 'Tag : ' + tagName;
            res.locals.blog.tagName    = tagName;
            res.locals.blog.thesePosts = data.tag[tagName];
            return res.render(opts.tagOneTemplate);
        }

        if ( path === 'category' ) {
            res.locals.blog.title = 'Categories';
            return res.render(opts.catAllTemplate);
        }

        if ( path.indexOf('category-') === 0 ) {
            var parts = path.split(/-/);
            var catName = parts.slice(1).join('-');
            if ( !data.category[catName] ) {
                // 404 - Not Found
                return next();
            }

            res.locals.blog.title      = 'Tag : ' + tagName;
            res.locals.blog.catName    = catName;
            res.locals.blog.thesePosts = data.category[catName];
            return res.render(opts.catOneTemplate);
        }

        // is this a post
        if ( data.post[path] ) {
            res.locals.blog.title    = data.post[path].meta.title;
            res.locals.blog.thisPost = data.post[path];
            return res.render(opts.postTemplate);
        }

        // didn't find anything interesting, pass it on
        next();
    };

    // prior to returning, let's put these vars onto this middleware so
    // the user can get access to some interesting things
    middleware.posts    = data.posts;
    middleware.latest   = data.latest;
    middleware.archive  = data.archive;
    middleware.tag      = data.tag;
    middleware.category = data.category;

    middleware.reloadData = function() {
        data = readBlogSync(opts);
        middleware.posts    = data.posts;
        middleware.latest   = data.latest;
        middleware.archive  = data.archive;
        middleware.tag      = data.tag;
        middleware.category = data.category;
    };

    return middleware;
};

// ----------------------------------------------------------------------------
<|endoftext|>


<commit_before>"use strict";

/* @ngInject */
function AddExpenseController($stateParams, expenseService, notificationService) {
  var model = this;

  model.expense = {
    label: undefined,
    purchaserUuid: undefined,
    amount: undefined,
    participantsUuids: [],
    description: undefined
  };

  model.addExpense = addExpense;

  function addExpense(expense) {
    delete model.errors;
    expenseService.addExpense($stateParams.id, expense).then(function () {
      clearForm();
      notificationService.success("EXPENSE_ADDED_SUCCESS");
    }).catch(extractMessagesFromError);
  }

  function clearForm() {
    if (model.form) {
      model.form.$setPristine();
      model.form.$setUntouched();
    }
    model.expense.label = undefined;
    model.expense.purchaserUuid = undefined;
    model.expense.amount = undefined;
    model.expense.participantsUuids = [];
    model.expense.description = undefined;
  }

  function extractMessagesFromError(error) {
    model.errors = (error.status === 400) ? error.data.errors : [{message: "ADD_EXPENSE_DEFAULT_ERROR"}];
  }
}

module.exports = AddExpenseController;<commit_msg>Useless code<commit_after>"use strict";

/* @ngInject */
function AddExpenseController($stateParams, expenseService, notificationService) {
  var model = this;

  model.expense = {};

  model.addExpense = addExpense;

  function addExpense(expense) {
    delete model.errors;
    expenseService.addExpense($stateParams.id, expense).then(function () {
      clearForm();
      notificationService.success("EXPENSE_ADDED_SUCCESS");
    }).catch(extractMessagesFromError);
  }

  function clearForm() {
    if (model.form) {
      model.form.$setPristine();
      model.form.$setUntouched();
    }
    delete model.expense.label;
    delete model.expense.purchaserUuid;
    delete model.expense.amount;
    model.expense.participantsUuids = [];
    delete model.expense.description;
  }

  function extractMessagesFromError(error) {
    model.errors = (error.status === 400) ? error.data.errors : [{message: "ADD_EXPENSE_DEFAULT_ERROR"}];
  }
}

module.exports = AddExpenseController;<|endoftext|>


<commit_before><commit_msg>Added empty AI in direction model.<commit_after><|endoftext|>


<commit_before>'use strict';

// trails controller
angular.module('trails').controller('TrailsController', ['$scope',
                                                              '$stateParams',
                                                              '$rootScope',
                                                              '$location',
                                                              'Authentication',
                                                              'Trails',
                                                              '$state',
                                                              'leafletData',
  function ($scope, $stateParams, $rootScope, $location, Authentication, Trails, $state, leafletData) {
    // boolean for trail toggle menu
    $scope.iconCollapse = false;
    $scope.uploadCollapse = false;

    //icons list
    $scope.icon = [];
    $scope.icons = [
        'bicycle',
        'bus-stop',
        'campsite',
        'first-aid',
        'food',
        'head',
        'hospital',
        'lodging',
        'parking',
        'pets',
        'picnic',
        'restrooms',
        'visitor-center',
        'wheelchair',
        'wi-fi'
    ];

    $scope.authentication = Authentication;
    $scope.loading = true;

    // Create new Trail
    $scope.create = function (content) {
      $scope.error = null;
      var trail = new Trails(JSON.parse(content));

      trail.$save(function (response) {
        $scope.success = true;
        $scope.statusMessage = 'Added';
      }, function (errorResponse) {
          $scope.failure = true;
          $scope.statusMessage = errorResponse.data.message;
      });
    };

    // Remove existing Trail
    $scope.remove = function (trail) {
      if (confirm('Are you sure you want to delete this user?')) {
        Trails.delete({ trailId: $stateParams.trailId })
              .$promise.then(function (res) {
                    $scope.success = true;
                    $scope.statusMessage = 'Deleted';
              }, function(error) {
                $scope.error = 'Unable to remove trail!\n' + error;
              });
        }
    };

    // Update existing trail
    $scope.update = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'trailForm');
        return false;
      }

      var trail = $scope.trail;

      trail.$update(function () {
        $scope.success = true;
        $scope.statusMessage = 'Updated';
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Find a list of trails
    $scope.find = function () {
      Trails.query().$promise.then(function (res) {
        $scope.trails = res;
        $scope.loading = false;
      });
    };

    // Find existing trail
    $scope.findOne = function () {
      angular.extend($scope, {
          edit: {
                lat: 29.671316,
                lng: -82.327766,
                zoom: 10
          }
      });

      Trails.get({ trailId: $stateParams.trailId })
        .$promise.then(function (res) {
            $scope.trail = res;
            console.log($scope.trail);
            var previewData = $scope.trail;
            var poly = L.geoJson($scope.trail);
            var center = poly.getBounds().getCenter();
            console.log(center);
            angular.extend($scope, {
              edit: {
                  lat: center.lat,
                  lng: center.lng,
                  zoom: 14
              },
              geojson: {
                data: previewData,
                style: {
                  color: 'red'
                }
              }
            });
         $scope.loading = false;
      });
    };

    $scope.showContent = function($fileContent){
      $scope.content = $fileContent;
      $scope.iconCollapse = false;
      $scope.uploadCollapse = false;
      var previewData = JSON.parse($scope.content);
      angular.extend($scope, {
        center: {
            lat: 29.671316,
            lng: -82.327766,
            zoom: 10
        },
        geojson: {
          data: previewData,
          style: {
            color: 'red'
          }
        }
      });
    };

    // Find existing trail
    $scope.createIcon = function (isValid) {
        $scope.error = null;

        if (!isValid) {
          $scope.$broadcast('show-errors-check-validity', 'iconForm');
          return false;
        }

        var trail = {
            "type": "Feature",
            "properties": {
                "Name": $scope.icon.type ,
                "color": "null",
                "boundary": $scope.icon.boundary
            },
            "geometry": {
                "type": "Point",
                "coordinates": [$scope.icon.lat, $scope.icon.lng]
            }
        };

        var icon = new Trails(trail);
        icon.$save(function (response) {
          $scope.success = true;
          $scope.statusMessage = 'Icon Added';
        }, function (errorResponse) {
            $scope.failure = true;
            $scope.statusMessage = errorResponse.data.message;
        });
        console.log(icon);
    };

}
]);
<commit_msg>fixed string error<commit_after>'use strict';

// trails controller
angular.module('trails').controller('TrailsController', ['$scope',
                                                              '$stateParams',
                                                              '$rootScope',
                                                              '$location',
                                                              'Authentication',
                                                              'Trails',
                                                              '$state',
                                                              'leafletData',
  function ($scope, $stateParams, $rootScope, $location, Authentication, Trails, $state, leafletData) {
    // boolean for trail toggle menu
    $scope.iconCollapse = false;
    $scope.uploadCollapse = false;

    //icons list
    $scope.icon = [];
    $scope.icons = [
        'bicycle',
        'bus-stop',
        'campsite',
        'first-aid',
        'food',
        'head',
        'hospital',
        'lodging',
        'parking',
        'pets',
        'picnic',
        'restrooms',
        'visitor-center',
        'wheelchair',
        'wi-fi'
    ];

    $scope.authentication = Authentication;
    $scope.loading = true;

    // Create new Trail
    $scope.create = function (content) {
      $scope.error = null;
      var trail = new Trails(JSON.parse(content));

      trail.$save(function (response) {
        $scope.success = true;
        $scope.statusMessage = 'Added';
      }, function (errorResponse) {
          $scope.failure = true;
          $scope.statusMessage = errorResponse.data.message;
      });
    };

    // Remove existing Trail
    $scope.remove = function (trail) {
      if (confirm('Are you sure you want to delete this user?')) {
        Trails.delete({ trailId: $stateParams.trailId })
              .$promise.then(function (res) {
                    $scope.success = true;
                    $scope.statusMessage = 'Deleted';
              }, function(error) {
                $scope.error = 'Unable to remove trail!\n' + error;
              });
        }
    };

    // Update existing trail
    $scope.update = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'trailForm');
        return false;
      }

      var trail = $scope.trail;

      trail.$update(function () {
        $scope.success = true;
        $scope.statusMessage = 'Updated';
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Find a list of trails
    $scope.find = function () {
      Trails.query().$promise.then(function (res) {
        $scope.trails = res;
        $scope.loading = false;
      });
    };

    // Find existing trail
    $scope.findOne = function () {
      angular.extend($scope, {
          edit: {
                lat: 29.671316,
                lng: -82.327766,
                zoom: 10
          }
      });

      Trails.get({ trailId: $stateParams.trailId })
        .$promise.then(function (res) {
            $scope.trail = res;
            console.log($scope.trail);
            var previewData = $scope.trail;
            var poly = L.geoJson($scope.trail);
            var center = poly.getBounds().getCenter();
            console.log(center);
            angular.extend($scope, {
              edit: {
                  lat: center.lat,
                  lng: center.lng,
                  zoom: 14
              },
              geojson: {
                data: previewData,
                style: {
                  color: 'red'
                }
              }
            });
         $scope.loading = false;
      });
    };

    $scope.showContent = function($fileContent){
      $scope.content = $fileContent;
      $scope.iconCollapse = false;
      $scope.uploadCollapse = false;
      var previewData = JSON.parse($scope.content);
      angular.extend($scope, {
        center: {
            lat: 29.671316,
            lng: -82.327766,
            zoom: 10
        },
        geojson: {
          data: previewData,
          style: {
            color: 'red'
          }
        }
      });
    };

    // Find existing trail
    $scope.createIcon = function (isValid) {
        $scope.error = null;

        if (!isValid) {
          $scope.$broadcast('show-errors-check-validity', 'iconForm');
          return false;
        }

        var trail = {
            'type': 'Feature',
            'properties': {
                'Name': $scope.icon.type ,
                'color': 'null',
                'boundary': $scope.icon.boundary
            },
            'geometry': {
                'type': 'Point',
                'coordinates': [$scope.icon.lat, $scope.icon.lng]
            }
        };

        var icon = new Trails(trail);
        icon.$save(function (response) {
          $scope.success = true;
          $scope.statusMessage = 'Icon Added';
        }, function (errorResponse) {
            $scope.failure = true;
            $scope.statusMessage = errorResponse.data.message;
        });
        console.log(icon);
    };

}
]);
<|endoftext|>


<commit_before>var path = require('path');
var test = require('ava');
var postcss = require('postcss');
var colorblindPlugin = require('..');
var colorTransformer = require('../src/color-transformer');
var colorNames = require('css-color-names');
var colorblind = require('color-blind');
var onecolor = require('onecolor');
var getProcessor = require('./_getProcessor');
var testPostCSS = require('./_testPostCSS');
var getFixture = require('./_getFixture');

function testColorMutation (t, color, method) {
  if (!method) {
    method = 'deuteranopia';
  }
  return testPostCSS(
    t,
    getFixture(color),
    getFixture(colorblind[method.toLowerCase().trim()](color)),
    {method: method}
  );
}

['#123', '#000', '#fff', '#f06d06'].forEach(function(hex, index) {
  test(
    'should transform hex (' + (index + 1) + ')',
    testColorMutation,
    hex
  );
});

[{
  from: '#1234',
  hex: '#123',
  alpha: '0.27',
}, {
  from: '#9344ABCD',
  hex: '#9344AB',
  alpha: '0.8',
}, {
  from: '#FFFFFFFF',
  hex: '#FFFFFF',
  alpha: '1',
}, {
  from: '#0000',
  hex: '#000',
  alpha: '0',
}, {
  from: 'rgba(30, 50, 200, 1)',
  hex: '#1E32C8',
  alpha: 1,
}, {
  from: 'rgba(100, 200, 0, 0)',
  hex: '#64C800',
  alpha: 0,
}, {
  from: 'rgba(150,50,50,.4)',
  hex: '#963232',
  alpha: .4,
}, {
  from: 'hsla(30, 50%, 50%, 1)',
  hex: '#BF8040',
  alpha: 1,
}, {
  from: 'hsla(100, 80%, 30%, 0)',
  hex: '#388A0F',
  alpha: 0,
}, {
  from: 'hsla(150,50%,50%,.4)',
  hex: '#40BF80',
  alpha: .4,
}].forEach(function(map, index) {
  test(
    `should transform ${map.from} (${index + 1})`,
    testPostCSS,
    getFixture(map.from),
    getFixture(onecolor(colorblind.deuteranopia(map.hex)).alpha(map.alpha).cssa())
  );
});

var keywordMap = {
  mediumSeaGreen: '#3CB371',
  PapayaWhip: '#FFEFD5',
  thistle: '#D8BFD8',
  BlanchedAlmond: '#FFEBCD',
  rebeccaPurple: '#639',
};

Object.keys(keywordMap).forEach(function(keyword, index) {
  var hex = keywordMap[keyword];
  test(
    'should transform named color (' + (index + 1) + ')',
    testColorMutation,
    keyword
  );
});

var hexRgbMap = {
  '#1E32C8': 'rgb(30, 50, 200)',
  '#64C800': 'rgb(100, 200, 0)',
  '#963232': 'rgb(150,50,50)',
};

Object.keys(hexRgbMap).forEach(function(hex, index) {
  var rgb = hexRgbMap[hex];
  test(
    'should transform rgb (' + (index + 1) + ')',
    testPostCSS,
    getFixture(rgb),
    getFixture(onecolor(colorblind.deuteranopia(hex)).css())
  );
});

var hexHslMap = {
  '#BF8040': 'hsl(30, 50%, 50%)',
  '#388A0F': 'hsl(100, 80%, 30%)',
  '#40BF80': 'hsl(150,50%,50%)',
};

Object.keys(hexHslMap).forEach(function(hex, index) {
  var hsl = hexHslMap[hex];
  test(
    'should transform hsl (' + (index + 1) + ')',
    testPostCSS,
    getFixture(hsl),
    getFixture(onecolor(colorblind.deuteranopia(hex)).css())
  );
});

test(
  'should do a simple hex deuteranopia transform',
  testColorMutation,
  `#FFCC00`
);

test(
  'should do a simple hex achromatopsia transform',
  testColorMutation,
  `#D929E2`,
  'achromatopsia'
);

test(
  'should do a simple named color deuteranopia transform',
  testPostCSS,
  `.some-color { border: 3px red solid; font-size: 12px }`,
  `.some-color { border: 3px ${colorblind.deuteranopia(colorNames.red)} solid; font-size: 12px }`
);

test(
  'should do a multi tritanopia transform',
  testPostCSS,
  `.some-color { border: 3px #D929E2 solid; color: lime }`,
  `.some-color { border: 3px ${colorblind.tritanopia('#D929E2')} solid; color: ${colorblind.tritanopia('lime')} }`,
  {method: 'tritanopia'}
);

test(
  'should work inside gradients',
  testPostCSS,
  `.some-color { background: linear-gradient(#000000, hsla(120, 30%, 80%, .8)) }`,
  `.some-color { background: linear-gradient(#000000, ${colorTransformer('hsla(120, 30%, 80%, .8)', 'deuteranopia')}) }`
);

test('should process images and yield an inlined data url', t => {
  return getProcessor().process(`a{background:url(${path.join(__dirname, 'fixture.jpg')})}`).then(function(result) {
    t.deepEqual(result.css.indexOf('data:image/jpeg;base64'), 17);
  });
});

test(
  'should handle weird capitalization of method names',
  testColorMutation,
  '#FFCC00',
  'DEuTerAnopiA'
);

test(
  'should handle weird whitespace',
  testColorMutation,
  '#FFCC00',
  ' deuteranopia      '
);

test(
  'should handle capitalized color names',
  testColorMutation,
  'ALICebLuE'
);

test('should throw an error on a bad method name', function(t) {
  t.throws(function () {
    return testPostCSS(t, 'h1{}', 'h1{}', {method:'bad method name'})
  });
});
<commit_msg>Remove last reference to the color transformer from the tests.<commit_after>var path = require('path');
var test = require('ava');
var postcss = require('postcss');
var colorblindPlugin = require('..');
var colorNames = require('css-color-names');
var colorblind = require('color-blind');
var onecolor = require('onecolor');
var getProcessor = require('./_getProcessor');
var testPostCSS = require('./_testPostCSS');
var getFixture = require('./_getFixture');

function testColorMutation (t, color, method) {
  if (!method) {
    method = 'deuteranopia';
  }
  return testPostCSS(
    t,
    getFixture(color),
    getFixture(colorblind[method.toLowerCase().trim()](color)),
    {method: method}
  );
}

['#123', '#000', '#fff', '#f06d06'].forEach(function(hex, index) {
  test(
    'should transform hex (' + (index + 1) + ')',
    testColorMutation,
    hex
  );
});

[{
  from: '#1234',
  hex: '#123',
  alpha: '0.27',
}, {
  from: '#9344ABCD',
  hex: '#9344AB',
  alpha: '0.8',
}, {
  from: '#FFFFFFFF',
  hex: '#FFFFFF',
  alpha: '1',
}, {
  from: '#0000',
  hex: '#000',
  alpha: '0',
}, {
  from: 'rgba(30, 50, 200, 1)',
  hex: '#1E32C8',
  alpha: 1,
}, {
  from: 'rgba(100, 200, 0, 0)',
  hex: '#64C800',
  alpha: 0,
}, {
  from: 'rgba(150,50,50,.4)',
  hex: '#963232',
  alpha: .4,
}, {
  from: 'hsla(30, 50%, 50%, 1)',
  hex: '#BF8040',
  alpha: 1,
}, {
  from: 'hsla(100, 80%, 30%, 0)',
  hex: '#388A0F',
  alpha: 0,
}, {
  from: 'hsla(150,50%,50%,.4)',
  hex: '#40BF80',
  alpha: .4,
}].forEach(function(map, index) {
  test(
    `should transform ${map.from} (${index + 1})`,
    testPostCSS,
    getFixture(map.from),
    getFixture(onecolor(colorblind.deuteranopia(map.hex)).alpha(map.alpha).cssa())
  );
});

var keywordMap = {
  mediumSeaGreen: '#3CB371',
  PapayaWhip: '#FFEFD5',
  thistle: '#D8BFD8',
  BlanchedAlmond: '#FFEBCD',
  rebeccaPurple: '#639',
};

Object.keys(keywordMap).forEach(function(keyword, index) {
  var hex = keywordMap[keyword];
  test(
    'should transform named color (' + (index + 1) + ')',
    testColorMutation,
    keyword
  );
});

var hexRgbMap = {
  '#1E32C8': 'rgb(30, 50, 200)',
  '#64C800': 'rgb(100, 200, 0)',
  '#963232': 'rgb(150,50,50)',
};

Object.keys(hexRgbMap).forEach(function(hex, index) {
  var rgb = hexRgbMap[hex];
  test(
    'should transform rgb (' + (index + 1) + ')',
    testPostCSS,
    getFixture(rgb),
    getFixture(onecolor(colorblind.deuteranopia(hex)).css())
  );
});

var hexHslMap = {
  '#BF8040': 'hsl(30, 50%, 50%)',
  '#388A0F': 'hsl(100, 80%, 30%)',
  '#40BF80': 'hsl(150,50%,50%)',
};

Object.keys(hexHslMap).forEach(function(hex, index) {
  var hsl = hexHslMap[hex];
  test(
    'should transform hsl (' + (index + 1) + ')',
    testPostCSS,
    getFixture(hsl),
    getFixture(onecolor(colorblind.deuteranopia(hex)).css())
  );
});

test(
  'should do a simple hex deuteranopia transform',
  testColorMutation,
  `#FFCC00`
);

test(
  'should do a simple hex achromatopsia transform',
  testColorMutation,
  `#D929E2`,
  'achromatopsia'
);

test(
  'should do a simple named color deuteranopia transform',
  testPostCSS,
  `.some-color { border: 3px red solid; font-size: 12px }`,
  `.some-color { border: 3px ${colorblind.deuteranopia(colorNames.red)} solid; font-size: 12px }`
);

test(
  'should do a multi tritanopia transform',
  testPostCSS,
  `.some-color { border: 3px #D929E2 solid; color: lime }`,
  `.some-color { border: 3px ${colorblind.tritanopia('#D929E2')} solid; color: ${colorblind.tritanopia('lime')} }`,
  {method: 'tritanopia'}
);

test(
  'should work inside gradients',
  testPostCSS,
  `.some-color { background: linear-gradient(#000000, hsla(120, 30%, 80%, .8)) }`,
  `.some-color { background: linear-gradient(#000000, ${onecolor(colorblind.deuteranopia('#bddbbd')).alpha('0.8').cssa()}) }`
);

test('should process images and yield an inlined data url', t => {
  return getProcessor().process(`a{background:url(${path.join(__dirname, 'fixture.jpg')})}`).then(function(result) {
    t.deepEqual(result.css.indexOf('data:image/jpeg;base64'), 17);
  });
});

test(
  'should handle weird capitalization of method names',
  testColorMutation,
  '#FFCC00',
  'DEuTerAnopiA'
);

test(
  'should handle weird whitespace',
  testColorMutation,
  '#FFCC00',
  ' deuteranopia      '
);

test(
  'should handle capitalized color names',
  testColorMutation,
  'ALICebLuE'
);

test('should throw an error on a bad method name', function(t) {
  t.throws(function () {
    return testPostCSS(t, 'h1{}', 'h1{}', {method:'bad method name'})
  });
});
<|endoftext|>


<commit_before>const Future = Npm.require("fibers/future");

Meteor.methods({
  'graphql.transport': function(query, variables, operationName) {
    check(query, String);
    check(variables, Match.OneOf(Object, undefined, null));
    check(operationName, Match.OneOf(String, undefined, null));

    variables = {...variables, ...{
      mongoId: this.userId
    }}

    const payload = { query, variables, operationName };
    const f = new Future();

    fetch(Meteor.settings.heighliner, {
        method: "POST",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      })
      .then((response) => {
        return response.json()
      })
      .then((data) => {
        f.return(data);
      })
      .catch(error => {
        f.throw(error);
      });

    return f.wait()

  }
});
<commit_msg>add in debug logs<commit_after>const Future = Npm.require("fibers/future");

Meteor.methods({
  'graphql.transport': function(query, variables, operationName) {
    check(query, String);
    check(variables, Match.OneOf(Object, undefined, null));
    check(operationName, Match.OneOf(String, undefined, null));

    variables = {...variables, ...{
      mongoId: this.userId
    }}

    const payload = { query, variables, operationName };
    const f = new Future();

    console.log(`Making request to ${Meteor.settings.heighliner}`)
    fetch(Meteor.settings.heighliner, {
        method: "POST",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      })
      .then((response) => {
        return response.json()
      })
      .then((data) => {
        f.return(data);
      })
      .catch(error => {
        console.error(error)
        f.throw(error);
      });

    return f.wait()

  }
});
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define([], function() {
	"use strict";

	/**
	 * Static collection of utility functions to handle time zone related conversions
	 *
	 * @author SAP SE
	 * @version ${version}
	 * @namespace
	 * @alias sap.ui.core.format.TimezoneUtil
	 * @private
	 * @ui5-restricted sap.ui.core.Configuration, sap.ui.core.format.DateFormat
	 */
	var TimezoneUtil = {};

	/**
	 * Cache for the (browser's) local IANA timezone ID
	 *
	 * @type {string}
	 */
	var sLocalTimezone = "";

	/**
	 * Cache for valid time zones provided by Intl.supportedValuesOf("timeZone")
	 *
	 * @type {Array}
	 */
	var aSupportedTimezoneIDs;

	/**
	 * Cache for Intl.DateTimeFormat instances
	 */
	var oIntlDateTimeFormatCache = {
		_oCache: new Map(),
		/**
		 * When cache limit is reached, it gets cleared
		 */
		_iCacheLimit: 10,

		/**
		 * Creates or gets an instance of Intl.DateTimeFormat.
		 *
		 * @param {string} sTimezone IANA timezone ID
		 * @returns {Intl.DateTimeFormat} Intl.DateTimeFormat instance
		 */
		get: function (sTimezone) {
			var cacheEntry = this._oCache.get(sTimezone);
			if (cacheEntry) {
				return cacheEntry;
			}

			var oOptions = {
				hourCycle: "h23",
				hour: "2-digit",
				minute: "2-digit",
				second: "2-digit",
				fractionalSecondDigits: 3,
				day: "2-digit",
				month: "2-digit",
				year: "numeric",
				timeZone: sTimezone,
				timeZoneName: 'short',
				era: 'narrow'
			};
			var oInstance = new Intl.DateTimeFormat("en-US", oOptions);

			// only store a limited number of entries in the cache
			if (this._oCache.size === this._iCacheLimit) {
				this._oCache = new Map();
			}
			this._oCache.set(sTimezone, oInstance);
			return oInstance;
		}
	};

	/**
	 * Uses the Intl.supportedValuesOf('timeZone') and Intl.DateTimeFormat
	 * API to check if the browser can handle the given IANA timezone ID.
	 * Intl.supportedValuesOf('timeZone') offers direct access to the list of supported
	 * time zones. It is not yet supported by all browsers but if it is supported and the given time
	 * zone is in the list it is faster than probing.
	 *
	 * Intl.supportedValuesOf('timeZone') does not return all IANA timezone IDs which
	 * the Intl.DateTimeFormat can handle, e.g. "Japan", "Etc/UTC".
	 *
	 * @param {string} sTimezone The IANA timezone ID which is checked, e.g "Europe/Berlin"
	 * @returns {boolean} Whether the time zone is a valid IANA timezone ID
	 * @private
	 * @ui5-restricted sap.ui.core.Configuration, sap.ui.core.format.DateFormat
	 */
	TimezoneUtil.isValidTimezone = function(sTimezone) {
		if (!sTimezone) {
			return false;
		}

		if (Intl.supportedValuesOf) {
			try {
				aSupportedTimezoneIDs = aSupportedTimezoneIDs || Intl.supportedValuesOf('timeZone');
				if (aSupportedTimezoneIDs.includes(sTimezone)) {
					return true;
				}
				// although not contained in the supportedValues it still can be valid, therefore continue
			} catch (oError) {
				// ignore error
				aSupportedTimezoneIDs = [];
			}
		}

		try {
			oIntlDateTimeFormatCache.get(sTimezone);
			return true;
		} catch (oError) {
			return false;
		}
	};

	/**
	 * Converts a date to a specific time zone.
	 * The resulting date reflects the given time zone such that the "UTC" Date methods
	 * can be used, e.g. Date#getUTCHours() to display the hours in the given time zone.
	 *
	 * @example
	 * var oDate = new Date("2021-10-13T15:22:33Z"); // UTC
	 * // time zone difference UTC-4 (DST)
	 * TimezoneUtil.convertToTimezone(oDate, "America/New_York");
	 * // 2021-10-13 11:22:33 in America/New_York
	 *
	 * @param {Date} oDate The date which should be converted.
	 * @param {string} sTargetTimezone The target IANA timezone ID, e.g "Europe/Berlin"
	 * @returns {Date} The new date in the target time zone.
	 * @private
	 * @ui5-restricted sap.ui.core.format.DateFormat, sap.ui.unified, sap.m
	 */
	TimezoneUtil.convertToTimezone = function(oDate, sTargetTimezone) {
		var oFormatParts = this._getParts(oDate, sTargetTimezone);
		return TimezoneUtil._getDateFromParts(oFormatParts);
	};

	/**
	 * Uses the Intl.DateTimeFormat API to convert a date to a specific time zone.
	 *
	 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts
	 * @param {Date} oDate The date which should be converted.
	 * @param {string} sTargetTimezone The target IANA timezone ID, e.g "Europe/Berlin"
	 * @returns {{
	 *     month: string,
	 *     day: string,
	 *     year: string,
	 *     hour: string,
	 *     minute: string,
	 *     second: string,
	 *     era: string,
	 *     fractionalSecond: string,
	 *     timeZoneName: string
	 * }} An object containing the date and time fields considering the target time zone.
	 * @private
	 */
	TimezoneUtil._getParts = function(oDate, sTargetTimezone) {
		var oIntlDate = oIntlDateTimeFormatCache.get(sTargetTimezone);
		// clone the date object before passing it to the Intl API, to ensure that no
		// UniversalDate gets passed to it
		var oParts = oIntlDate.formatToParts(new Date(oDate.getTime()));
		var oDateParts = Object.create(null);
		for (var sKey in oParts) {
			var oPart = oParts[sKey];
			if (oPart.type !== "literal") {
				oDateParts[oPart.type] = oPart.value;
			}
		}
		return oDateParts;
	};

	/**
	 * Creates a Date from the provided date parts.
	 *
	 * @param {object} oParts Separated date and time fields as object, see {@link #_getParts}.
	 * @returns {Date} Returns the date object created from the provided parts.
	 * @private
	 */
	TimezoneUtil._getDateFromParts = function(oParts) {
		var oDate = new Date(0);

		var iUTCYear = parseInt(oParts.year);
		if (oParts.era === "B") {
			// The JS Date uses astronomical year numbering which supports year zero and negative
			// year numbers.
			// The Intl.DateTimeFormat API uses eras (no year zero and no negative year numbers).
			// years around zero overview:
			// | Astronomical | In Era
			// |            2 | 2 Anno Domini (era: "A")
			// |            1 | 1 Anno Domini (era: "A")
			// |            0 | 1 Before Christ (era: "B")
			// |           -1 | 2 Before Christ (era: "B")
			// |           -2 | 3 Before Christ (era: "B")
			// For the conversion to the JS Date the parts returned by the Intl.DateTimeFormat API
			// need to be adapted.
			iUTCYear = (iUTCYear * -1) + 1;
		}

		// Date.UTC cannot be used here to be able to support dates before the UNIX epoch
		oDate.setUTCFullYear(iUTCYear,
			parseInt(oParts.month) - 1,
			parseInt(oParts.day));
		oDate.setUTCHours(
			parseInt(oParts.hour),
			parseInt(oParts.minute),
			parseInt(oParts.second),
			parseInt(oParts.fractionalSecond || 0)); // some older browsers don't support fractionalSecond, e.g. Safari < 14.1 */

		return oDate;
	};

	/**
	 * Gets the offset to UTC in seconds for a given date in the time zone specified.
	 *
	 * For non-unique points in time, the daylight saving time takes precedence over the standard
	 * time shortly after the switch back (e.g. clock gets set back 1 hour, duplicate hour).
	 *
	 * @example
	 * var oDate = new Date("2021-10-13T13:22:33Z");
	 * TimezoneUtil.calculateOffset(oDate, "America/New_York");
	 * // => +14400 seconds (4 * 60 * 60 seconds)
	 *
	 * TimezoneUtil.calculateOffset(oDate, "Europe/Berlin");
	 * // => -7200 seconds (-2 * 60 * 60 seconds)
	 *
	 * // daylight saving time (2018 Sun, 25 Mar, 02:00	CET → CEST	+1 hour (DST start)	UTC+2h)
	 * // the given date is taken as it is in the time zone
	 * TimezoneUtil.calculateOffset(new Date("2018-03-25T00:00:00Z"), "Europe/Berlin");
	 * // => -3600 seconds (-1 * 60 * 60 seconds), interpreted as: 2018-03-25 00:00:00 (CET)
	 *
	 * TimezoneUtil.calculateOffset(new Date("2018-03-25T03:00:00Z"), "Europe/Berlin");
	 * // => -7200 seconds (-2 * 60 * 60 seconds)
	 *
	 * var oHistoricalDate = new Date("1800-10-13T13:22:33Z");
	 * TimezoneUtil.calculateOffset(oHistoricalDate, "Europe/Berlin");
	 * // => -3208 seconds (-3208 seconds)
	 *
	 * @param {Date} oDate The date in the time zone used to calculate the offset to UTC.
	 * @param {string} sTimezoneSource The source IANA timezone ID, e.g "Europe/Berlin"
	 * @returns {number} The difference to UTC between the date in the time zone.
	 * @private
	 * @ui5-restricted sap.ui.core.format.DateFormat
	 */
	TimezoneUtil.calculateOffset = function(oDate, sTimezoneSource) {
		var oFirstGuess = this.convertToTimezone(oDate, sTimezoneSource);

		var iInitialOffset = oDate.getTime() - oFirstGuess.getTime();

		// to get the correct summer/wintertime (daylight saving time) handling use the source date (apply the diff)
		var oDateSource = new Date(oDate.getTime() + iInitialOffset);
		var oDateTarget = this.convertToTimezone(oDateSource, sTimezoneSource);

		return (oDateSource.getTime() - oDateTarget.getTime()) / 1000;
	};

	/**
	 * Retrieves the browser's local IANA timezone ID.
	 *
	 * @returns {string} The local IANA timezone ID of the browser, e.g "Europe/Berlin"
	 * @private
	 * @ui5-restricted sap.ui.core.Configuration,sap.m.DateTimeField
	 */
	TimezoneUtil.getLocalTimezone = function() {
		if (sLocalTimezone) {
			return sLocalTimezone;
		}
		sLocalTimezone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
		return sLocalTimezone;
	};

	return TimezoneUtil;
});
<commit_msg>[INTERNAL] sap.ui.core.format.TimezoneUtil: documentation<commit_after>/*!
 * ${copyright}
 */

sap.ui.define([], function() {
	"use strict";

	/**
	 * Static collection of utility functions to handle time zone related conversions
	 *
	 * @author SAP SE
	 * @version ${version}
	 * @namespace
	 * @alias sap.ui.core.format.TimezoneUtil
	 * @private
	 * @ui5-restricted sap.ui.core.Configuration, sap.ui.core.format.DateFormat
	 */
	var TimezoneUtil = {};

	/**
	 * Cache for the (browser's) local IANA timezone ID
	 *
	 * @type {string}
	 */
	var sLocalTimezone = "";

	/**
	 * Cache for valid time zones provided by Intl.supportedValuesOf("timeZone")
	 *
	 * @type {Array}
	 */
	var aSupportedTimezoneIDs;

	/**
	 * Cache for Intl.DateTimeFormat instances
	 */
	var oIntlDateTimeFormatCache = {
		_oCache: new Map(),
		/**
		 * When cache limit is reached, it gets cleared
		 */
		_iCacheLimit: 10,

		/**
		 * Creates or gets an instance of Intl.DateTimeFormat.
		 *
		 * @param {string} sTimezone IANA timezone ID
		 * @returns {Intl.DateTimeFormat} Intl.DateTimeFormat instance
		 */
		get: function (sTimezone) {
			var cacheEntry = this._oCache.get(sTimezone);
			if (cacheEntry) {
				return cacheEntry;
			}

			var oOptions = {
				hourCycle: "h23",
				hour: "2-digit",
				minute: "2-digit",
				second: "2-digit",
				fractionalSecondDigits: 3,
				day: "2-digit",
				month: "2-digit",
				year: "numeric",
				timeZone: sTimezone,
				timeZoneName: 'short',
				era: 'narrow'
			};
			var oInstance = new Intl.DateTimeFormat("en-US", oOptions);

			// only store a limited number of entries in the cache
			if (this._oCache.size === this._iCacheLimit) {
				this._oCache = new Map();
			}
			this._oCache.set(sTimezone, oInstance);
			return oInstance;
		}
	};

	/**
	 * Uses the Intl.supportedValuesOf('timeZone') and Intl.DateTimeFormat
	 * API to check if the browser can handle the given IANA timezone ID.
	 * Intl.supportedValuesOf('timeZone') offers direct access to the list of supported
	 * time zones. It is not yet supported by all browsers but if it is supported and the given time
	 * zone is in the list it is faster than probing.
	 *
	 * Intl.supportedValuesOf('timeZone') does not return all IANA timezone IDs which
	 * the Intl.DateTimeFormat can handle, e.g. "Japan", "Etc/UTC".
	 *
	 * @param {string} sTimezone The IANA timezone ID which is checked, e.g "Europe/Berlin"
	 * @returns {boolean} Whether the time zone is a valid IANA timezone ID
	 * @private
	 * @ui5-restricted sap.ui.core.Configuration, sap.ui.core.format.DateFormat
	 */
	TimezoneUtil.isValidTimezone = function(sTimezone) {
		if (!sTimezone) {
			return false;
		}

		if (Intl.supportedValuesOf) {
			try {
				aSupportedTimezoneIDs = aSupportedTimezoneIDs || Intl.supportedValuesOf('timeZone');
				if (aSupportedTimezoneIDs.includes(sTimezone)) {
					return true;
				}
				// although not contained in the supportedValues it still can be valid, therefore continue
			} catch (oError) {
				// ignore error
				aSupportedTimezoneIDs = [];
			}
		}

		try {
			oIntlDateTimeFormatCache.get(sTimezone);
			return true;
		} catch (oError) {
			return false;
		}
	};

	/**
	 * Converts a date to a specific time zone.
	 * The resulting date reflects the given time zone such that the "UTC" Date methods
	 * can be used, e.g. Date#getUTCHours() to display the hours in the given time zone.
	 *
	 * @example
	 * var oDate = new Date("2021-10-13T15:22:33Z"); // UTC
	 * // time zone difference UTC-4 (DST)
	 * TimezoneUtil.convertToTimezone(oDate, "America/New_York");
	 * result is:
	 * // 2021-10-13 11:22:33 in America/New_York
	 * // same as new Date("2021-10-13T11:22:33Z"); // UTC
	 *
	 * @param {Date} oDate The date which should be converted.
	 * @param {string} sTargetTimezone The target IANA timezone ID, e.g "Europe/Berlin"
	 * @returns {Date} The new date in the target time zone.
	 * @private
	 * @ui5-restricted sap.ui.core.format.DateFormat, sap.ui.unified, sap.m
	 */
	TimezoneUtil.convertToTimezone = function(oDate, sTargetTimezone) {
		var oFormatParts = this._getParts(oDate, sTargetTimezone);
		return TimezoneUtil._getDateFromParts(oFormatParts);
	};

	/**
	 * Uses the Intl.DateTimeFormat API to convert a date to a specific time zone.
	 *
	 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts
	 * @param {Date} oDate The date which should be converted.
	 * @param {string} sTargetTimezone The target IANA timezone ID, e.g "Europe/Berlin"
	 * @returns {{
	 *     month: string,
	 *     day: string,
	 *     year: string,
	 *     hour: string,
	 *     minute: string,
	 *     second: string,
	 *     era: string,
	 *     fractionalSecond: string,
	 *     timeZoneName: string
	 * }} An object containing the date and time fields considering the target time zone.
	 * @private
	 */
	TimezoneUtil._getParts = function(oDate, sTargetTimezone) {
		var oIntlDate = oIntlDateTimeFormatCache.get(sTargetTimezone);
		// clone the date object before passing it to the Intl API, to ensure that no
		// UniversalDate gets passed to it
		var oParts = oIntlDate.formatToParts(new Date(oDate.getTime()));
		var oDateParts = Object.create(null);
		for (var sKey in oParts) {
			var oPart = oParts[sKey];
			if (oPart.type !== "literal") {
				oDateParts[oPart.type] = oPart.value;
			}
		}
		return oDateParts;
	};

	/**
	 * Creates a Date from the provided date parts.
	 *
	 * @param {object} oParts Separated date and time fields as object, see {@link #_getParts}.
	 * @returns {Date} Returns the date object created from the provided parts.
	 * @private
	 */
	TimezoneUtil._getDateFromParts = function(oParts) {
		var oDate = new Date(0);

		var iUTCYear = parseInt(oParts.year);
		if (oParts.era === "B") {
			// The JS Date uses astronomical year numbering which supports year zero and negative
			// year numbers.
			// The Intl.DateTimeFormat API uses eras (no year zero and no negative year numbers).
			// years around zero overview:
			// | Astronomical | In Era
			// |            2 | 2 Anno Domini (era: "A")
			// |            1 | 1 Anno Domini (era: "A")
			// |            0 | 1 Before Christ (era: "B")
			// |           -1 | 2 Before Christ (era: "B")
			// |           -2 | 3 Before Christ (era: "B")
			// For the conversion to the JS Date the parts returned by the Intl.DateTimeFormat API
			// need to be adapted.
			iUTCYear = (iUTCYear * -1) + 1;
		}

		// Date.UTC cannot be used here to be able to support dates before the UNIX epoch
		oDate.setUTCFullYear(iUTCYear,
			parseInt(oParts.month) - 1,
			parseInt(oParts.day));
		oDate.setUTCHours(
			parseInt(oParts.hour),
			parseInt(oParts.minute),
			parseInt(oParts.second),
			parseInt(oParts.fractionalSecond || 0)); // some older browsers don't support fractionalSecond, e.g. Safari < 14.1 */

		return oDate;
	};

	/**
	 * Gets the offset to UTC in seconds for a given date in the time zone specified.
	 *
	 * For non-unique points in time, the daylight saving time takes precedence over the standard
	 * time shortly after the switch back (e.g. clock gets set back 1 hour, duplicate hour).
	 *
	 * @example
	 * var oDate = new Date("2021-10-13T13:22:33Z");
	 * TimezoneUtil.calculateOffset(oDate, "America/New_York");
	 * // => +14400 seconds (4 * 60 * 60 seconds)
	 *
	 * TimezoneUtil.calculateOffset(oDate, "Europe/Berlin");
	 * // => -7200 seconds (-2 * 60 * 60 seconds)
	 *
	 * // daylight saving time (2018 Sun, 25 Mar, 02:00	CET → CEST	+1 hour (DST start)	UTC+2h)
	 * // the given date is taken as it is in the time zone
	 * TimezoneUtil.calculateOffset(new Date("2018-03-25T00:00:00Z"), "Europe/Berlin");
	 * // => -3600 seconds (-1 * 60 * 60 seconds), interpreted as: 2018-03-25 00:00:00 (CET)
	 *
	 * TimezoneUtil.calculateOffset(new Date("2018-03-25T03:00:00Z"), "Europe/Berlin");
	 * // => -7200 seconds (-2 * 60 * 60 seconds)
	 *
	 * var oHistoricalDate = new Date("1800-10-13T13:22:33Z");
	 * TimezoneUtil.calculateOffset(oHistoricalDate, "Europe/Berlin");
	 * // => -3208 seconds (-3208 seconds)
	 *
	 * @param {Date} oDate The date in the time zone used to calculate the offset to UTC.
	 * @param {string} sTimezoneSource The source IANA timezone ID, e.g "Europe/Berlin"
	 * @returns {number} The difference to UTC between the date in the time zone.
	 * @private
	 * @ui5-restricted sap.ui.core.format.DateFormat
	 */
	TimezoneUtil.calculateOffset = function(oDate, sTimezoneSource) {
		var oFirstGuess = this.convertToTimezone(oDate, sTimezoneSource);

		var iInitialOffset = oDate.getTime() - oFirstGuess.getTime();

		// to get the correct summer/wintertime (daylight saving time) handling use the source date (apply the diff)
		var oDateSource = new Date(oDate.getTime() + iInitialOffset);
		var oDateTarget = this.convertToTimezone(oDateSource, sTimezoneSource);

		return (oDateSource.getTime() - oDateTarget.getTime()) / 1000;
	};

	/**
	 * Retrieves the browser's local IANA timezone ID.
	 *
	 * @returns {string} The local IANA timezone ID of the browser, e.g "Europe/Berlin"
	 * @private
	 * @ui5-restricted sap.ui.core.Configuration,sap.m.DateTimeField
	 */
	TimezoneUtil.getLocalTimezone = function() {
		if (sLocalTimezone) {
			return sLocalTimezone;
		}
		sLocalTimezone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
		return sLocalTimezone;
	};

	return TimezoneUtil;
});
<|endoftext|>


<commit_before>import React, {Component} from 'react';

import Rate from 'src/Rate';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Rate.json';

export default class RateExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            value: 3,
            value2: 3.5
        };

        this.onChangeHandle = ::this.onChangeHandle;

    }

    onChangeHandle(value) {
        this.setState({
            value
        });
    }

    onChangeHandle2(value2) {
        this.setState({
            value2
        });
    }

    render() {

        const {value, value2} = this.state;

        return (

Rate

                    The Rate is used to evaluate something.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

A simple Rate example.

                            <Rate value={value}
                                  onChange={(value) => {
                                      this.onChangeHandle(value);
                                  }}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With allowHalf"/>

Set the allowHalf property to display half star.

                            <Rate value={value2}
                                  allowHalf={true}
                                  onChange={(value2) => {
                                      this.onChangeHandle2(value2);
                                  }}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With disabled"/>

Set the disabled property to disabled the Rate component.

                            <Rate value={value2}
                                  allowHalf={true}
                                  disabled={true}
                                  onChange={(value2) => {
                                      this.onChangeHandle2(value2);
                                  }}/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
}<commit_msg>update RateExamples<commit_after>import React, {Component} from 'react';

import Rate from 'src/Rate';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Rate.json';

class RateExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            value: 3,
            value2: 3.5
        };

    }

    onChangeHandle = value => {
        this.setState({
            value
        });
    };

    onChangeHandle2 = value2 => {
        this.setState({
            value2
        });
    };

    render() {

        const {value, value2} = this.state;

        return (

Rate

                    The Rate is used to evaluate something.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

A simple Rate example.

                            <Rate value={value}
                                  onChange={(value) => {
                                      this.onChangeHandle(value);
                                  }}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With allowHalf"/>

Set the allowHalf property to display half star.

                            <Rate value={value2}
                                  allowHalf={true}
                                  onChange={(value2) => {
                                      this.onChangeHandle2(value2);
                                  }}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With disabled"/>

Set the disabled property to disabled the Rate component.

                            <Rate value={value2}
                                  allowHalf={true}
                                  disabled={true}
                                  onChange={(value2) => {
                                      this.onChangeHandle2(value2);
                                  }}/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
}

export default RateExamples;<|endoftext|>


<commit_before>import MailchimpLists from '../src/MailchimpLists';
import MailChimp from '../src/index';

/**
 * Remember to replace (email, api-key, list-id) with real values
 */

let mailChimp = new MailChimp('email','api-key');

test('Get info about mailchimp list',()=>{
    expect.assertions(1);

    return mailChimp.list.readListInfo('ccb8a60b4b',{}).then((data) => {
        expect(data.status).toBe(200);
    }).catch((error) => {
        expect(error.status).toBe(404);
    });
});

test('Create new list',()=>{
    expect.assertions(1);

    const listData = {'name':'Library Test List',
        'contact':{
            'company':'Mailchimp',
            'address1':'France',
            'city':'Paris',
            'state':'Paris',
            'zip':'000',
            'country':'France'
        },
        "permission_reminder":"You gave us permission",
        "campaign_defaults":{
            "from_name":",Mayowa",
            "from_email":"Mayowa@mayor.com",
            "subject":"New list created",
            "language":"en"
        },
        "email_type_option":true
    };

    return mailChimp.list.createList(listData).then((data)=>{
        /**
         * write your other codes here
         */
        expect(data.status).toBe(200); /*Test code - You can ignore this line of code*/
    }).catch((error)=>{
        expect(error.status).toBe(400); /*Test code - You can ignore this line of code*/
    })
});<commit_msg>Add all tests for MailchimpList<commit_after>import MailchimpLists from '../src/MailchimpLists';
import MailChimp from '../src/index';

/**
 * Remember to replace (email, api-key, list-id) with real values
 */

let mailChimp = new MailChimp('email','api-key');

test('Create new list',()=>{
    expect.assertions(1);

    const listData = {'name':'Library Test List',
        'contact':{
            'company':'Mailchimp',
            'address1':'France',
            'city':'Paris',
            'state':'Paris',
            'zip':'000',
            'country':'France'
        },
        "permission_reminder":"You gave us permission",
        "campaign_defaults":{
            "from_name":",Mayowa",
            "from_email":"Mayowa@mayor.com",
            "subject":"New list created",
            "language":"en"
        },
        "email_type_option":true
    };

    return mailChimp.list.createList(listData).then((data)=>{
        /**
         * The code below is a test code - You can do whatever you like with 'data'
         */
        expect(data.status).toBe(200);
    }).catch((error)=>{
        expect(error.status).toBe(400);
    })
});

test('Get info about mailchimp list',()=>{
    expect.assertions(1);

    return mailChimp.list.readListInfo('list-id',{}).then((data) => {
        /**
         * The code below is a test code - You can do whatever you like with 'data'
         */
        expect(data.status).toBe(200);
    }).catch((error) => {
        expect(error.status).toBe(404);
    });
});

test('Batch subscribe members to list', ()=>{
    expect.assertions(1);
    const body ={
        'members':[{
            'email_address':'mayowa@mayor.com',
            'email_type':'text',
            'status':'subscribed'
        }]
    };
    return mailChimp.list.batchSubscribe('list-id',body).then((data) =>{
        /**
         * The code below is a test code - You can do whatever you like with 'data'
         */
        expect(data.status).toBe(200);
    }).catch((error)=>{
        console.log(error);
        expect(error.status).toBe(400);
    });
});

test('Update list', ()=>{
    expect.assertions(1);

    const body ={
        'name':'Library Test List',
        'contact':{
            'company':'Mailchimp',
            'address1':'France',
            'city':'Paris',
            'state':'Paris',
            'zip':'000',
            'country':'France'
        },
        "permission_reminder":"You gave us permission",
        "campaign_defaults":{
            "from_name":",Mayowa",
            "from_email":"Mayowa@mayor.com",
            "subject":"New list created",
            "language":"en"
        },
        "email_type_option":true
    };
    return mailChimp.list.updateList('list-id',body).then((data)=>{
        /**
         * The code below is a test code - You can do whatever you like with 'data'
         */
        expect(data.status).toBe(200);
    }).catch((error)=>{
        expect(error.status).toBe(404);
    });
});

test('Delete a list',()=>{
   expect(mailChimp.list.deleteList('list-id')).toBeUndefined();
});<|endoftext|>


<commit_before>;var conpigurator = {
	active:false,
	handleChange:function(event){
		if(event.target.className.includes('conpiguratorInput')){
			if(event.target.value && event.target.value !== '' && typeof event.target.value === 'string'){
				if(event.target.dataset){
					var pigment = event.target.value;
					if(pigment.substring(0,1) !== '#') pigment = '#'+pigment;
					pigment = (pigment.length > 7)? pigment.substring(0,7) : pigment;
					conpigurator.conpigurateElements(event.target.dataset.conpigbg,'backgroundColor',pigment);
					conpigurator.conpigurateElements(event.target.dataset.conpigborder,'borderColor',pigment);
					conpigurator.conpigurateElements(event.target.dataset.conpigtext,'color',pigment);
				}
			}
		}
	},
	conpigurateElements:function(selector,colorProperty,pigment){
		if(selector){
			colorProperty = colorProperty || 'backgroundColor';
			var arrElements = document.querySelectorAll(selector);
			for(var i=0;i<arrElements.length;i++){
				arrElements[i].style[colorProperty] = pigment;
			}
		}
	},
	init:function(){
		if(!conpigurator.active){
			document.body.addEventListener('change',function(event){conpigurator.handleChange(event);});
			conpigurator.active = true;
		}
	}
};
<commit_msg>Protoype Build Done<commit_after>;var ConpiguratorArray = [];
function Conpigurator (id) {
	this.el = document.getElementById(id);
	this.el.setAttribute('data-conpigurator-index',ConpiguratorArray.length);
	this.targets = [];
	this.el.addEventListener('change',function(event){
		ConpiguratorArray[Number(event.target.getAttribute('data-conpigurator-index'))].update();
	});
	this.update = function () {
		var hex = this.el.value;// Assumes this.el.value is a Hexadecimal value
		if(hex.substring(0,1) !== '#') hex = '#'+hex;
		for(var idx in this.targets){
			document.getElementById(this.targets[idx].ID).style[this.targets[idx].prop] = hex;
		}
		return this;
	};
	this.addTarget = function (id,property) {// No safeguards against ID or property name typos OR incompatible property names
		id = id || '';
		property = property || 'backgroundColor';
		this.targets.push({ID:id,prop:property});
		return this;
	};
	ConpiguratorArray.push(this);
	return this;
}
/*
	CONPIGURATOR By Nathaniel Wiley
	==========
	var myConpigurator = new Conpigurator('inputID')
		.addTarget('targetID','backgroundColor')
		.addTarget('targetID','color')...;
	myConpigurator.addTarget('targetID','CSS color property');// Add
	myConpigurator.update();// Force application of myConpigurator
	==========
	1.0.0 - 2017-12-18
		- Functionality with Hexadecimal input proven in:
		IE9, IE10, Edge, Firefox 56.0.2, and Chrome 63.0.3239.84
*/<|endoftext|>


<commit_before>var nope = function() {

var WRITE_LIFECYCLE_MODE = "write";
var knownLifecycleModes = [ "read", WRITE_LIFECYCLE_MODE ];
var lifecycleMode = WRITE_LIFECYCLE_MODE;

define(HTMLDocument.prototype, 'write', nope);
define(HTMLDocument.prototype, 'writeln', nope);
define(HTMLDocument.prototype, 'open', nope);
define(HTMLDocument.prototype, 'close', nope);

var layoutTriggers = {
  'Document': {
    'proto': {
      'getter': [
        'scrollingElement',
      ],
      'method': [
        'execCommand',
      ]
    }
  },
  'HTMLElement': {
    'proto': {
      'getter': [
        'offsetLeft',
        'offsetTop',
        'offsetWidth',
        'offsetHeight',
        'offsetParent',
        'innerText',
        'outerText',
      ]
    }
  },
  'Element': {
    'proto': {
      'method': [
        'scrollIntoView',
        'scrollBy', // experimental
        'scrollTo', // experimental
        'getClientRect',
        'getBoundingClientRect',
        'computedRole', // experimental
        'computedName', // experimental
        'focus',
      ],
      'getter': [
        'clientLeft',
        'clientWidth',
        'clientHeight',
        'scrollLeft',
        'scrollTop',
        'scrollWidth',
        'scrollHeight',
      ],
      'setter': [
        'scrollLeft',
        'scrollTop',
      ],
    }
  },
  'Range': {
    'proto': {
      'method': [
        'getClientRects',
        'getBoundingClientRect',
      ],
    }
  },
  'UIEvent': {
    'proto': {
      'getter': [
        'layerX',
        'layerY',
      ],
    }
  },
  'MouseEvent': {
    'proto': {
      'getter': [
        'offsetX',
        'offsetY',
      ],
    }
  },
  'HTMLButtonElement': {
    'proto': {
      'method': [
        'reportValidity',
      ]
    }
  },
  'HTMLDialogElement': {
    'proto': {
      'method': [
        'showModal',
      ]
    }
  },
  'HTMLFieldSetElement': {
    'proto': {
      'method': [
        'reportValidity',
      ]
    }
  },
  'HTMLImageElement': {
    'proto': {
      'getter': [
        'width',
        'height',
        'x',
        'y',
      ]
    }
  },
  'HTMLInputElement': {
    'proto': {
      'method': [
        'reportValidity',
      ]
    }
  },
  'HTMLButtonElement': {
    'proto': {
      'method': [
        'reportValidity',
      ]
    }
  },
  'HTMLKeygenElement': {
    'proto': {
      'method': [
        'reportValidity',
      ]
    }
  },
  'CSSStyleDeclaration': {
    'proto': {
      'method': [
        'getPropertyValue',
      ]
    }
  },
  'Window': {
    // 'instance': { // should these stay on instance?
    //   'getter': [
    //     'innerHeight',
    //     'innerWidth',
    //     'scrollX',
    //     'scrollY',
    //   ]
    // },
    'proto': {
      'method': [
        'scrollBy',
        'scrollTo',
      ]
    }
  },
  'SVGSVGElement': {
    'proto': {
      'setter': [
        'currentScale',
      ]
    }
  },
};

processSpec(layoutTriggers);

function nope() {
  throw new Error('nope');
}

function synthesizeNopeWhenWriting(func) {
  return function() {
    if (lifecycleMode != WRITE_LIFECYCLE_MODE) {
      return func.apply(this, arguments);
    }
    throw new Error('nope');
  }
}

define(HTMLDocument.prototype, 'setLifecycleMode', function(mode) {
  if (knownLifecycleModes.indexOf(mode) == -1) {
    throw new Error(`Unknown lifecycle mode. The known modes are: ${knownLifecycleModes}.`);
    return;
  }
  lifecycleMode = mode;
});

function processSpec(spec) {
  Object.keys(spec).forEach(function(objectName) {
    var protoMemberSpecs = spec[objectName].proto;
    if (protoMemberSpecs) {
      protoMemberSpecs.getter && protoMemberSpecs.getter.forEach(function(getterName) {
        redefineGetter(window[objectName].prototype, getterName, synthesizeNopeWhenWriting);
      });
      protoMemberSpecs.setter && protoMemberSpecs.setter.forEach(function(setterName) {
        redefineSetter(window[objectName].prototype, setterName, synthesizeNopeWhenWriting);
      });
      protoMemberSpecs.method && protoMemberSpecs.method.forEach(function(methodName) {
        define(window[objectName].prototype, methodName, nope);
      });
    }
    var instanceMemberSpecs = spec[objectName].instance;
    if (instanceMemberSpecs) {
      // TODO(dglazkov): This will blow up for instances other than window.
      instanceMemberSpecs.getter && instanceMemberSpecs.getter.forEach(function(getterName) {
        redefineGetter(window, getterName, synthesizeNopeWhenWriting);
      });
    }
  });
}

function redefineGetter(obj, key, getterSynthesizer) {
  var descriptor = Object.getOwnPropertyDescriptor(obj, key);
  if (!descriptor || !descriptor.get)
    throw new Error(`Unable to redefine getter ${key} on ${obj.constructor}.`);

  descriptor.get = getterSynthesizer(descriptor.get);

  Object.defineProperty(obj, key, descriptor);
}

function redefineSetter(obj, key, setterSynthesizer) {
  var descriptor = Object.getOwnPropertyDescriptor(obj, key);
  if (!descriptor || !descriptor.set)
    throw new Error(`Unable to redefine setter ${key} on ${obj.constructor}.`);

  descriptor.set = setterSynthesizer(descriptor.set);

  Object.defineProperty(obj, key, descriptor);

}

function define(obj, key, func) {
  Object.defineProperty(obj, key, {
    value: func,
    writable: true,
    configurable: true,
    enumerable: true
  });
}

}

var script = document.createElement('script');
script.textContent = `~${nope}();`;
document.documentElement.appendChild(script);

<commit_msg>Support buggy window accessors.<commit_after>var nope = function() {

var WRITE_LIFECYCLE_MODE = "write";
var knownLifecycleModes = [ "read", WRITE_LIFECYCLE_MODE ];
var lifecycleMode = WRITE_LIFECYCLE_MODE;

var terribleIdeas = {
  'HTMLDocument': {
    'method': [
      'write',
      'writeln',
      'open',
      'close'
    ]
  }
}

var layoutTriggers = {
  'Document': {
    'getter': [
      'scrollingElement',
    ],
    'method': [
      'execCommand',
    ]
  },
  'HTMLElement': {
    'getter': [
      'offsetLeft',
      'offsetTop',
      'offsetWidth',
      'offsetHeight',
      'offsetParent',
      'innerText',
      'outerText',
    ]
  },
  'Element': {
    'method': [
      'scrollIntoView',
      'scrollBy', // experimental
      'scrollTo', // experimental
      'getClientRect',
      'getBoundingClientRect',
      'computedRole', // experimental
      'computedName', // experimental
      'focus',
    ],
    'getter': [
      'clientLeft',
      'clientWidth',
      'clientHeight',
      'scrollLeft',
      'scrollTop',
      'scrollWidth',
      'scrollHeight',
    ],
    'setter': [
      'scrollLeft',
      'scrollTop',
    ],
  },
  'Range': {
    'method': [
      'getClientRects',
      'getBoundingClientRect',
    ],
  },
  'UIEvent': {
    'getter': [
      'layerX',
      'layerY',
    ],
  },
  'MouseEvent': {
    'getter': [
      'offsetX',
      'offsetY',
    ],
  },
  'HTMLButtonElement': {
    'method': [
      'reportValidity',
    ]
  },
  'HTMLDialogElement': {
    'method': [
      'showModal',
    ]
  },
  'HTMLFieldSetElement': {
    'method': [
      'reportValidity',
    ]
  },
  'HTMLImageElement': {
    'getter': [
      'width',
      'height',
      'x',
      'y',
    ]
  },
  'HTMLInputElement': {
    'method': [
      'reportValidity',
    ]
  },
  'HTMLButtonElement': {
    'method': [
      'reportValidity',
    ]
  },
  'HTMLKeygenElement': {
    'method': [
      'reportValidity',
    ]
  },
  'CSSStyleDeclaration': {
    'method': [
      'getPropertyValue',
    ]
  },
  'Window': {
    'method': [
      'scrollBy',
      'scrollTo',
    ]
  },
  'SVGSVGElement': {
    'setter': [
      'currentScale',
    ]
  },
};

processSpec(layoutTriggers);
processSpec(terribleIdeas);

var buggyWindowAccessors = [
  'innerHeight',
  'innerWidth',
  'scrollX',
  'scrollY',
];

buggyWindowAccessors.forEach(function(accessor) {
  overrideGetterSetter(window, accessor, nope, nope);
});

function nope() {
  throw new Error('nope');
}

function synthesizeNopeWhenWriting(func) {
  return function() {
    if (lifecycleMode != WRITE_LIFECYCLE_MODE) {
      return func.apply(this, arguments);
    }
    throw new Error('nope');
  }
}

define(HTMLDocument.prototype, 'setLifecycleMode', function(mode) {
  if (knownLifecycleModes.indexOf(mode) == -1) {
    throw new Error(`Unknown lifecycle mode. The known modes are: ${knownLifecycleModes}.`);
    return;
  }
  lifecycleMode = mode;
});

function processSpec(spec) {
  Object.keys(spec).forEach(function(objectName) {
    var objectSpecs = spec[objectName];
    objectSpecs.getter && objectSpecs.getter.forEach(function(getterName) {
      redefineGetter(window[objectName].prototype, getterName, synthesizeNopeWhenWriting);
    });
    objectSpecs.setter && objectSpecs.setter.forEach(function(setterName) {
      redefineSetter(window[objectName].prototype, setterName, synthesizeNopeWhenWriting);
    });
    objectSpecs.method && objectSpecs.method.forEach(function(methodName) {
      define(window[objectName].prototype, methodName, nope);
    });
  });
}

function redefineGetter(obj, key, getterSynthesizer) {
  var descriptor = Object.getOwnPropertyDescriptor(obj, key);
  if (!descriptor || !descriptor.get)
    throw new Error(`Unable to redefine getter ${key} on ${obj.constructor}.`);

  descriptor.get = getterSynthesizer(descriptor.get);

  Object.defineProperty(obj, key, descriptor);
}

function redefineSetter(obj, key, setterSynthesizer) {
  var descriptor = Object.getOwnPropertyDescriptor(obj, key);
  if (!descriptor || !descriptor.set)
    throw new Error(`Unable to redefine setter ${key} on ${obj.constructor}.`);

  descriptor.set = setterSynthesizer(descriptor.set);

  Object.defineProperty(obj, key, descriptor);

}

function overrideGetterSetter(obj, key, getter, setter) {
  Object.defineProperty(obj, key, {
    get: getter,
    set: setter,
    configurable: true,
    enumerable: true
  });
}

function define(obj, key, func) {
  Object.defineProperty(obj, key, {
    value: func,
    writable: true,
    configurable: true,
    enumerable: true
  });
}

}

var script = document.createElement('script');
script.textContent = `~${nope}(); document.currentScript.remove();`;
document.documentElement.appendChild(script);

<|endoftext|>


<commit_before>import kebabCase from 'lodash/kebabCase';

export default function getElementType(defaultEl = 'div') {
  const tag = this.$vnode && this.$vnode.data.tag;
  if (!tag) return defaultEl;

  const context = this.$vnode.context;
  const entry = Object
    .entries(context.$options.components || {})
    .find(([name]) => kebabCase(name) === tag);

  if (entry) {
    return entry[1];
  }

  return tag;
}
<commit_msg>Add special case for dynamic components (#212)<commit_after>import kebabCase from 'lodash/kebabCase';

export default function getElementType(defaultEl = 'div') {
  const tag = this.$vnode && this.$vnode.data.tag;
  if (!tag || tag === 'component') return defaultEl;

  const context = this.$vnode.context;
  const entry = Object
    .entries(context.$options.components || {})
    .find(([name]) => kebabCase(name) === tag);

  if (entry) {
    return entry[1];
  }

  return tag;
}
<|endoftext|>


<commit_before>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Send Image MOD",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "Image Editing",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
	const channels = ['Same Channel', 'Command Author', 'Mentioned User', 'Mentioned Channel', 'Default Channel (Top Channel)', 'Temp Variable', 'Server Variable', 'Global Variable'];
	return `${channels[parseInt(data.channel)]}`;
},

//---------------------------------------------------------------------
// Action Storage Function << added
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------

variableStorage: function(data, varType) {
	const type = parseInt(data.storage2);
	if(type !== varType) return;
	return ([data.varName3, 'Message']);
},

//---------------------------------------------------------------------
	// DBM Mods Manager Variables (Optional but nice to have!)
	//
	// These are variables that DBM Mods Manager uses to show information
	// about the mods for people to see in the list.
	//---------------------------------------------------------------------

	// Who made the mod (If not set, defaults to "DBM Mods")
	author: "EGGSY & Tindus",

	// The version of the mod (Defaults to 1.0.0)
	version: "1.9.5",

	// A short description to show on the mod line for this mod (Must be on a single line)
	short_description: "You can rename DBM image names and image formats, and Store!",

// If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

//---------------------------------------------------------------------

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["storage", "varName", "channel", "varName2", "message", "imageName", "imageFormat", "storage2", "varName3"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
	return `

		Source Image:

		<select id="storage" class="round" onchange="glob.refreshVariableList(this)">
			${data.variables[1]}
		</select>

		Variable Name:

		<input id="varName" class="round" type="text" list="variableList">

		Send To:

		<select id="channel" class="round" onchange="glob.sendTargetChange(this, 'varNameContainer2')">
			${data.sendTargets[isEvent ? 1 : 0]}
		</select>

		Variable Name:

		<input id="varName2" class="round" type="text">

	Message:
	<textarea id="message" rows="3" placeholder="Insert message here..." style="width: 99%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

		Image Format:

		<select id="imageFormat" class="round">
			<option value=".jpg">JPG</option>
			<option value=".png">PNG</option>
		</select>

		Image Name:

		<input id="imageName" class="round" type="text">

		Store In:

		<select id="storage2" class="round" onchange="glob.variableChange(this, 'varNameContainer3')">
			${data.variables[0]}
		</select>

		Variable Name:

		<input id="varName3" class="round" type="text">

	`
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {
	const {glob, document} = this;

	glob.refreshVariableList(document.getElementById('storage'));
	glob.sendTargetChange(document.getElementById('channel'), 'varNameContainer2');
},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function(cache) {
	const data = cache.actions[cache.index];
	const server = cache.server;
	const msg = cache.msg;
	const storage = parseInt(data.storage);
	const varName = this.evalMessage(data.varName, cache);
	const image = this.getVariable(storage, varName, cache);
	if(!image) {
		this.callNextAction(cache);
		return;
	}
	const channel = parseInt(data.channel);
	const varName2 = this.evalMessage(data.varName2, cache);
	const target = this.getSendTarget(channel, varName2, cache);
	const fileName = this.evalMessage(data.imageName, cache);
	if(Array.isArray(target)) {
		const Images = this.getDBM().Images;
		Images.createBuffer(image).then(function(buffer) {
			this.callListFunc(target, 'send', [this.evalMessage(data.message, cache), {
				files: [
					{
						attachment: buffer,
						name: `${fileName}${data.imageFormat}`
					}
				]
			}]).then(function(resultMsg) {
			const varName3 = this.evalMessage(data.varName3, cache);
			const storage2 = parseInt(data.storage2);
			this.storeValue(resultMsg, storage2, varName3, cache);
				this.callNextAction(cache);
			}.bind(this));
		}.bind(this)).catch(this.displayError.bind(this, data, cache));
	} else if(target && target.send) {
		const Images = this.getDBM().Images;
		Images.createBuffer(image).then(function(buffer) {
			const varName3 = this.evalMessage(data.varName3, cache);
			const storage2 = parseInt(data.storage2);
			target.send(this.evalMessage(data.message, cache), {
				files: [
					{
						attachment: buffer,
						name: `${fileName}${data.imageFormat}`
					}
				]
			}).then(function(resultMsg) {
				this.storeValue(resultMsg, storage2, varName3, cache);
				this.callNextAction(cache);
			}.bind(this)).catch(this.displayError.bind(this, data, cache));
		}.bind(this)).catch(this.displayError.bind(this, data, cache));
	} else {
		this.callNextAction(cache);
	}
},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
}

}; // End of module
<commit_msg>Fix 'store in' not working<commit_after>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Send Image MOD",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "Image Editing",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
	const channels = ['Same Channel', 'Command Author', 'Mentioned User', 'Mentioned Channel', 'Default Channel (Top Channel)', 'Temp Variable', 'Server Variable', 'Global Variable'];
	return `${channels[parseInt(data.channel)]}`;
},

//---------------------------------------------------------------------
// Action Storage Function << added
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------

variableStorage: function(data, varType) {
	const type = parseInt(data.storage2);
	if(type !== varType) return;
	return ([data.varName3, 'Message']);
},

//---------------------------------------------------------------------
	// DBM Mods Manager Variables (Optional but nice to have!)
	//
	// These are variables that DBM Mods Manager uses to show information
	// about the mods for people to see in the list.
	//---------------------------------------------------------------------

	// Who made the mod (If not set, defaults to "DBM Mods")
	author: "EGGSY & Tindus",

	// The version of the mod (Defaults to 1.0.0)
	version: "1.9.5",

	// A short description to show on the mod line for this mod (Must be on a single line)
	short_description: "You can rename DBM image names and image formats, and Store!",

// If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

//---------------------------------------------------------------------

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["storage", "varName", "channel", "varName2", "message", "imageName", "imageFormat", "storage2", "varName3"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
	return `

		Source Image:

		<select id="storage" class="round" onchange="glob.refreshVariableList(this)">
			${data.variables[1]}
		</select>

		Variable Name:

		<input id="varName" class="round" type="text" list="variableList">

		Send To:

		<select id="channel" class="round" onchange="glob.sendTargetChange(this, 'varNameContainer2')">
			${data.sendTargets[isEvent ? 1 : 0]}
		</select>

		Variable Name:

		<input id="varName2" class="round" type="text">

	Message:
	<textarea id="message" rows="3" placeholder="Insert message here..." style="width: 99%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

		Image Format:

		<select id="imageFormat" class="round">
			<option value=".jpg">JPG</option>
			<option value=".png">PNG</option>
		</select>

		Image Name:

		<input id="imageName" class="round" type="text">

		Store In:

		<select id="storage2" class="round" onchange="glob.variableChange(this, 'varNameContainer3')">
			${data.variables[0]}
		</select>

		Variable Name:

		<input id="varName3" class="round" type="text">

	`
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {
	const {glob, document} = this;

	glob.refreshVariableList(document.getElementById('storage'));
	glob.variableChange(document.getElementById('storage2'), 'varNameContainer3'); //Fix the varname container poofing ~TheMonDon
	glob.sendTargetChange(document.getElementById('channel'), 'varNameContainer2');
},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function(cache) {
	const data = cache.actions[cache.index];
	const server = cache.server;
	const msg = cache.msg;
	const storage = parseInt(data.storage);
	const varName = this.evalMessage(data.varName, cache);
	const image = this.getVariable(storage, varName, cache);
	if(!image) {
		this.callNextAction(cache);
		return;
	}
	const channel = parseInt(data.channel);
	const varName2 = this.evalMessage(data.varName2, cache);
	const target = this.getSendTarget(channel, varName2, cache);
	const fileName = this.evalMessage(data.imageName, cache);
	if(Array.isArray(target)) {
		const Images = this.getDBM().Images;
		Images.createBuffer(image).then(function(buffer) {
			this.callListFunc(target, 'send', [this.evalMessage(data.message, cache), {
				files: [
					{
						attachment: buffer,
						name: `${fileName}${data.imageFormat}`
					}
				]
			}]).then(function(resultMsg) {
			const varName3 = this.evalMessage(data.varName3, cache);
			const storage2 = parseInt(data.storage2);
			this.storeValue(resultMsg, storage2, varName3, cache);
				this.callNextAction(cache);
			}.bind(this));
		}.bind(this)).catch(this.displayError.bind(this, data, cache));
	} else if(target && target.send) {
		const Images = this.getDBM().Images;
		Images.createBuffer(image).then(function(buffer) {
			const varName3 = this.evalMessage(data.varName3, cache);
			const storage2 = parseInt(data.storage2);
			target.send(this.evalMessage(data.message, cache), {
				files: [
					{
						attachment: buffer,
						name: `${fileName}${data.imageFormat}`
					}
				]
			}).then(function(resultMsg) {
				this.storeValue(resultMsg, storage2, varName3, cache);
				this.callNextAction(cache);
			}.bind(this)).catch(this.displayError.bind(this, data, cache));
		}.bind(this)).catch(this.displayError.bind(this, data, cache));
	} else {
		this.callNextAction(cache);
	}
},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
}

}; // End of module
<|endoftext|>