<commit_before>one.color.installMethod('mix', function (otherColor, weight) {
    var weight = 1 - (weight || 0.5),
        w = weight * 2 - 1,
        a = this._alpha - otherColor._alpha,
        weight1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2,
        weight2 = 1 - weight1,
        rgb = this.rgb(),
        otherColor = otherColor.rgb();

    return (this
        .red(this._red * weight1 + otherColor._red * weight2)
        .green(this._green * weight1 + otherColor._green * weight2)
        .blue(this._blue * weight1 + otherColor._blue * weight2)
        .alpha(this._alpha * weight + otherColor._alpha * (1 - weight)));
});
<commit_msg>refactored plugins/mix.js to parse the other color and reduced the number of calculations in the return statement<commit_after>one.color.installMethod('mix', function (otherColor, weight) {
    var otherColor = one.color(otherColor),
        weight = 1 - (weight || 0.5),
        w = weight * 2 - 1,
        a = this._alpha - otherColor._alpha,
        weight1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2,
        weight2 = 1 - weight1,
        rgb = this.rgb(),
        otherColor = otherColor.rgb();

    return new one.color.RGB(
        this._red * weight1 + otherColor._red * weight2,
        this._green * weight1 + otherColor._green * weight2,
        this._blue * weight1 + otherColor._blue * weight2,
        this._alpha * weight + otherColor._alpha * (1 - weight)
    );
});
<|endoftext|>


<commit_before>import domain from 'domain';
import os from 'os-family';

const connectionResetDomain = domain.create();

connectionResetDomain.on('error', err => {
    // NOTE: The nodejs throw the EPIPE error instead of the ECONNRESET error
    // when the connection is broken in some cases on MacOS and Linux
    if (err.code === 'ECONNRESET' || !os.win && err.code === 'EPIPE')
        return;

    connectionResetDomain.removeAllListeners('error');
    throw err;
});

export default function (fn) {
    connectionResetDomain.run(fn);
}
<commit_msg>fix `Error: write ECONNABORTED` (close #1744) (#1811)<commit_after>import domain from 'domain';
import os from 'os-family';

const connectionResetDomain = domain.create();

connectionResetDomain.on('error', err => {
    // NOTE: The nodejs throw the EPIPE error instead of the ECONNRESET error
    // when the connection is broken in some cases on MacOS and Linux
    // https://github.com/nodejs/node/blob/8b4af64f50c5e41ce0155716f294c24ccdecad03/test/parallel/test-http-destroyed-socket-write2.js
    if (err.code === 'ECONNRESET' || !os.win && err.code === 'EPIPE' || os.win && err.code === 'ECONNABORTED')
        return;

    connectionResetDomain.removeAllListeners('error');
    throw err;
});

export default function (fn) {
    connectionResetDomain.run(fn);
}
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function () {

    'use strict';

    /**
     * @name order-sync
     *
     * @description
     * Updates requisition-less draft and created when app is online.
     */
    angular
        .module('requisition-order-create')
        .run(synchronizeOrders);

    synchronizeOrders.$inject = [
        '$rootScope',
        'offlineService',
        'localStorageService',
        'orderCreateService',
        'notificationService',
    ];

    function synchronizeOrders(
        $rootScope,
        offlineService,
        localStorageService,
        orderCreateService,
        notificationService,
    ) {
        $rootScope.$watch(function () {
            return offlineService.isOffline();
        }, function (isOffline, wasOffline) {
            if (!isOffline && isOffline !== wasOffline) {
                var ordersLocalStorageKey = 'reduxPersist.requisition';
                var orders = JSON.parse(localStorageService.get(ordersLocalStorageKey));

                syncDraftOrders(JSON.parse(orders.drafts));
                var notSentOfflineOrders = sendOfflineCreatedOrders(JSON.parse(orders.createdOffline));
                orders.createdOffline = JSON.stringify(notSentOfflineOrders);

                localStorageService.add(ordersLocalStorageKey, JSON.stringify(orders));
            }
        }, true);

        /**
         * @ngdoc method
         * @methodOf order-sync
         * @name syncDraftOrders
         *
         * @param drafts Drafts to update
         * @description Send draft orders saved offline
         */
        function syncDraftOrders(drafts) {
            _.each(drafts, function (orderDraft) {
                orderCreateService.update(orderDraft)
                    .then(() => {
                        notificationService.success('requisition.orderCreate.draftUpdate.success');
                    })
                    .catch(function () {
                        notificationService.error('requisition.orderCreate.draftUpdate.error');
                    });
            });
        }

        /**
         * @ngdoc method
         * @methodOf order-sync
         * @name sendOfflineCreatedOrders
         * @param orders Object Id-indexed object of orders
         *
         * @return Object Orders which failed to create
         * @description Send orders created offline
         */
        function sendOfflineCreatedOrders(orders) {
            var notSentOfflineOrders = {};

            _.each(orders, function (order) {
                orderCreateService.send(order)
                    .then(() => {
                        notificationService.success('requisition.orderCreate.createdOrderSent.success');
                    })
                    .catch(function () {
                        notSentOfflineOrders[order.id] = order;
                        notificationService.error('requisition.orderCreate.createdOrderSent.error');
                    });
            });

            return notSentOfflineOrders;
        }
    }
})();

<commit_msg>OLMIS-7539 Codestyle fix<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

    'use strict';

    /**
     * @name order-sync
     *
     * @description
     * Updates requisition-less draft and created when app is online.
     */
    angular
        .module('requisition-order-create')
        .run(synchronizeOrders);

    synchronizeOrders.$inject = [
        '$rootScope',
        'offlineService',
        'localStorageService',
        'orderCreateService',
        'notificationService'
    ];

    function synchronizeOrders(
        $rootScope,
        offlineService,
        localStorageService,
        orderCreateService,
        notificationService
    ) {
        $rootScope.$watch(function() {
            return offlineService.isOffline();
        }, function(isOffline, wasOffline) {
            if (!isOffline && isOffline !== wasOffline) {
                var ordersLocalStorageKey = 'reduxPersist.requisition';
                var orders = JSON.parse(localStorageService.get(ordersLocalStorageKey));

                syncDraftOrders(JSON.parse(orders.drafts));
                var notSentOfflineOrders = sendOfflineCreatedOrders(JSON.parse(orders.createdOffline));
                orders.createdOffline = JSON.stringify(notSentOfflineOrders);

                localStorageService.add(ordersLocalStorageKey, JSON.stringify(orders));
            }
        }, true);

        /**
         * @ngdoc method
         * @methodOf order-sync
         * @name syncDraftOrders
         *
         * @param drafts Drafts to update
         * @description Send draft orders saved offline
         */
        function syncDraftOrders(drafts) {
            _.each(drafts, function(orderDraft) {
                orderCreateService.update(orderDraft)
                    .then(function() {
                        notificationService.success('requisition.orderCreate.draftUpdate.success');
                    })
                    .catch(function() {
                        notificationService.error('requisition.orderCreate.draftUpdate.error');
                    });
            });
        }

        /**
         * @ngdoc method
         * @methodOf order-sync
         * @name sendOfflineCreatedOrders
         * @param orders Object Id-indexed object of orders
         *
         * @return Object Orders which failed to create
         * @description Send orders created offline
         */
        function sendOfflineCreatedOrders(orders) {
            var notSentOfflineOrders = {};

            _.each(orders, function(order) {
                orderCreateService.send(order)
                    .then(function() {
                        notificationService.success('requisition.orderCreate.createdOrderSent.success');
                    })
                    .catch(function() {
                        notSentOfflineOrders[order.id] = order;
                        notificationService.error('requisition.orderCreate.createdOrderSent.error');
                    });
            });

            return notSentOfflineOrders;
        }
    }
})();

<|endoftext|>


<commit_before>'use strict';

/**
 * The old verificatuion and budget.json was deprecated in 8.0
 */
const get = require('lodash.get');
const merge = require('lodash.merge');
const log = require('intel').getLogger('sitespeedio.plugin.budget');
const friendlyNames = require('../../support/friendlynames');

function getItem(friendlyName, type, metric, value, limit, limitType) {
  return {
    metric: friendlyName.name,
    type,
    value,
    friendlyValue: friendlyName.format(value),
    limit,
    friendlyLimit: friendlyName.format(limit),
    limitType,
    status: 'working'
  };
}

module.exports = {
  verify(message, result, budgets) {
    // Let us merge the specific configuration for this URL together
    // with the generic one. In the future we can fine tune this, since
    // we keep all metrics within a specific URL
    const budgetSetupSpecificForThisURL = get(budgets.budget, message.url);
    const budgetForThisURL = {};
    merge(budgetForThisURL, budgets.budget, budgetSetupSpecificForThisURL);

    // Keep failing/working metrics here
    const failing = [];
    const working = [];
    const url = message.url;
    log.verbose('Applying budget to url %s', url);
    const tool = message.type.split('.')[0];
    // Go through all metrics that are configured
    // timing, request, coach etc
    for (let metricType of Object.keys(budgetForThisURL)) {
      for (let metric of Object.keys(budgetForThisURL[metricType])) {
        if (friendlyNames[tool][metricType]) {
          const fullPath = friendlyNames[tool][metricType][metric].path;
          let value = get(message.data, fullPath);
          if (value && message.type === 'lighthouse.pageSummary') {
            value = value * 100; // The score in Lighthouse is 0-1
          } else if (
            value &&
            message.type === 'pagexray.pageSummary' &&
            metricType === 'httpErrors'
          ) {
            // count number of http server error
            value = Object.keys(value).filter(code => code > 399).length;
          }
          // We got a matching metric
          if (value !== undefined) {
            const budgetValue = budgetForThisURL[metricType][metric];
            const item = getItem(
              friendlyNames[tool][metricType][metric],
              metricType,
              metric,
              value,
              budgetValue,
              tool === 'coach' || tool === 'lighthouse' || tool === 'gpsi'
                ? 'min'
                : 'max'
            );
            if (tool === 'coach' || tool === 'lighthouse' || tool === 'gpsi') {
              if (value < budgetValue) {
                item.status = 'failing';
                failing.push(item);
              } else {
                working.push(item);
              }
            } else {
              if (value > budgetValue) {
                item.status = 'failing';
                failing.push(item);
              } else {
                working.push(item);
              }
            }
          } else {
            log.debug('Missing data for budget metric ' + metric);
          }
        }
      }
    }
    // group working/failing per URL
    if (failing.length > 0) {
      result.failing[message.url] = result.failing[message.url]
        ? result.failing[message.url].concat(failing)
        : failing;
    }

    if (working.length > 0) {
      result.working[message.url] = result.working[message.url]
        ? result.working[message.url].concat(working)
        : working;
    }
  }
};
<commit_msg>Better error message for wrong configured metrics https://github.com/sitespeedio/sitespeed.io/issues/3256<commit_after>'use strict';

/**
 * The old verificatuion and budget.json was deprecated in 8.0
 */
const get = require('lodash.get');
const merge = require('lodash.merge');
const log = require('intel').getLogger('sitespeedio.plugin.budget');
const friendlyNames = require('../../support/friendlynames');

function getItem(friendlyName, type, metric, value, limit, limitType) {
  return {
    metric: friendlyName.name,
    type,
    value,
    friendlyValue: friendlyName.format(value),
    limit,
    friendlyLimit: friendlyName.format(limit),
    limitType,
    status: 'working'
  };
}

module.exports = {
  verify(message, result, budgets) {
    // Let us merge the specific configuration for this URL together
    // with the generic one. In the future we can fine tune this, since
    // we keep all metrics within a specific URL
    const budgetSetupSpecificForThisURL = get(budgets.budget, message.url);
    const budgetForThisURL = {};
    merge(budgetForThisURL, budgets.budget, budgetSetupSpecificForThisURL);

    // Keep failing/working metrics here
    const failing = [];
    const working = [];
    const url = message.url;
    log.verbose('Applying budget to url %s', url);
    const tool = message.type.split('.')[0];
    // Go through all metrics that are configured
    // timing, request, coach etc
    for (let metricType of Object.keys(budgetForThisURL)) {
      for (let metric of Object.keys(budgetForThisURL[metricType])) {
        if (friendlyNames[tool][metricType]) {
          if (!friendlyNames[tool][metricType][metric]) {
            log.error(
              `It seems like you configure a metric ${metric} that we do not have a friendly name. Please check the docs if it is right.`
            );
          }
          const fullPath = friendlyNames[tool][metricType][metric].path;
          let value = get(message.data, fullPath);
          if (value && message.type === 'lighthouse.pageSummary') {
            value = value * 100; // The score in Lighthouse is 0-1
          } else if (
            value &&
            message.type === 'pagexray.pageSummary' &&
            metricType === 'httpErrors'
          ) {
            // count number of http server error
            value = Object.keys(value).filter(code => code > 399).length;
          }
          // We got a matching metric
          if (value !== undefined) {
            const budgetValue = budgetForThisURL[metricType][metric];
            const item = getItem(
              friendlyNames[tool][metricType][metric],
              metricType,
              metric,
              value,
              budgetValue,
              tool === 'coach' || tool === 'lighthouse' || tool === 'gpsi'
                ? 'min'
                : 'max'
            );
            if (tool === 'coach' || tool === 'lighthouse' || tool === 'gpsi') {
              if (value < budgetValue) {
                item.status = 'failing';
                failing.push(item);
              } else {
                working.push(item);
              }
            } else {
              if (value > budgetValue) {
                item.status = 'failing';
                failing.push(item);
              } else {
                working.push(item);
              }
            }
          } else {
            log.debug('Missing data for budget metric ' + metric);
          }
        }
      }
    }
    // group working/failing per URL
    if (failing.length > 0) {
      result.failing[message.url] = result.failing[message.url]
        ? result.failing[message.url].concat(failing)
        : failing;
    }

    if (working.length > 0) {
      result.working[message.url] = result.working[message.url]
        ? result.working[message.url].concat(working)
        : working;
    }
  }
};
<|endoftext|>


<commit_before>'use strict';

class InstallCmd {
  constructor(sqz) {
    this.sqz = sqz;

    this.commands = [
      {
        arg         : ['install'],
        summary     : 'Install project\'s & microservices packages',
        lifecycle   : [
          'project:validate',
          'microservices:load',
          'project:install'
        ],
        description : null,
        options     : {},
        examples    : [
          '--name my-first-project --template aws-generic'
        ]
      }
    ];
  }
}

module.exports = InstallCmd;
<commit_msg>fixed install command examples<commit_after>'use strict';

class InstallCmd {
  constructor(sqz) {
    this.sqz = sqz;

    this.commands = [
      {
        arg         : ['install'],
        summary     : 'Install project\'s & microservices packages',
        lifecycle   : [
          'project:validate',
          'microservices:load',
          'project:install'
        ],
        description : null,
        options     : {},
        examples    : [
          ''
        ]
      }
    ];
  }
}

module.exports = InstallCmd;
<|endoftext|>


<commit_before>'use strict';

var MethodBase = function(impl) {
  if (!impl) {
    throw new Error('Implementation object is invalid.');
  }
  this._impl = impl;
}

MethodBase.prototype._registerSingleRead = function(cb) {
  console.log('register');
  var tag = this._impl.getFreeTag();
  if (!tag) {
    throw new Error('Unable to open call session.');
  }
  var errorCallback = function(t, err) {
    console.log('error');
    if (t === tag) {
      cb && cb(undefined, err || 'Unknown error');
      disconnect();
    }
  };
  var dataCallback = function(t, data) {
    console.log('data');
    if (t === tag) {
      console.log('data hit');
      cb && cb(data);
      disconnect();
    }
  };
  var that = this;
  var disconnect = function() {
    console.log('disc');
    that._impl.error.disconnect(errorCallback);
    that._impl.data.disconnect(dataCallback);
  };
  this._impl.error.connect(errorCallback);
  this._impl.data.connect(dataCallback);
  return tag;
};

MethodBase.prototype._registerMultiRead = function(cb) {
  var tag = this._registerMultiRead(cb);
  if (!tag) {
    throw new Error('Unable to open writer session.');
  }
  var errorCallback = function(t, err) {
    if (t === tag) {
      cb && cb(undefined, err || 'Unknown error');
      disconnect();
    }
  };
  var dataCallback = function(t, data) {
    if (t === tag) {
      cb && cb(data);
    }
  };
  var dataEndCallback = function(t) {
    if (t === tag) {
      cb && cb(undefined, undefined, true);
      disconnect();
    }
  };
  var disconnect = function() {
    this._impl.error.disconnect(errorCallback);
    this._impl.read.disconnect(dataCallback);
    this._impl.readEnd.disconnect(dataEndCallback);
  };
  this._impl.error.connect(errorCallback);
  this._impl.data.connect(dataCallback);
  this._impl.dataEnd.connect(dataEndCallback);
  return tag;
};

MethodBase.prototype._singleWrite = function(tag, msg) {
  if (msg) {
    this._impl.write(tag, msg._raw);
    this._impl.writeEnd(tag);
  } else {
    this._impl.read(tag);
  }
}

MethodBase.prototype._multiWrite = function(tag) {
  this._impl.read(tag);
  return {
    write: function(msg) {
      if (!tag) {
        throw new Error('Writer session is closed.');
      }
      this._impl.write(tag, msg._raw);
    },

    writeEnd: function() {
      if (!tag) {
        throw new Error('Writer session is closed.');
      }
      this._impl.writeEnd(tag);
      tag = 0;
    },
  };
}

var ReaderWriterMethod = function(impl) { MethodBase.call(this, impl); };
ReaderWriterMethod.prototype = Object.create(MethodBase.prototype);
ReaderWriterMethod.prototype.call = function(cb) {
  return this._multiWrite(this._registerMultiRead(cb));
};

var WriterMethod = function(impl) { MethodBase.call(this, impl); };
WriterMethod.prototype = Object.create(MethodBase.prototype);
WriterMethod.prototype.call = function(cb) {
  return this._multiWrite(this._registerSingleRead(cb));
};

var ReaderMethod = function(impl) { MethodBase.call(this, impl); };
ReaderMethod.prototype = Object.create(MethodBase.prototype);
ReaderMethod.prototype.call = function(msg, cb) {
  this._singleWrite(this._registerMultiRead(cb), msg);
};

var UnaryMethod = function(impl) { MethodBase.call(this, impl); };
UnaryMethod.prototype = Object.create(MethodBase.prototype);
UnaryMethod.prototype.call = function(msg, cb) {
  this._singleWrite(this._registerSingleRead(cb), msg);
};
<commit_msg>Make single read to unsubscript when recieved readEnd<commit_after>'use strict';

var MethodBase = function(impl) {
  if (!impl) {
    throw new Error('Implementation object is invalid.');
  }
  this._impl = impl;
}

MethodBase.prototype._registerRead = function(cb, oneshot) {
  var tag = this._impl.getFreeTag();
  if (!tag) {
    throw new Error('Unable to open writer session.');
  }
  var errorCallback = function(t, err) {
    if (t === tag) {
      cb && cb(undefined, err || 'Unknown error');
      disconnect();
    }
  };
  var dataCallback = function(t, data) {
    if (t === tag) {
      cb && cb(data);
    }
    if (oneshot) {
      disconnect();
    }
  };
  var dataEndCallback = function(t) {
    if (t === tag) {
      if (oneshot) {
        // For now, consider data end for oneshot an error.
        cb && cb(undefined, 'Received data end.');
      } else {
        cb && cb(undefined, undefined, true);
      }
      disconnect();
    }
  };
  var that = this;
  var disconnect = function() {
    that._impl.error.disconnect(errorCallback);
    that._impl.data.disconnect(dataCallback);
    that._impl.dataEnd.disconnect(dataEndCallback);
  };
  this._impl.error.connect(errorCallback);
  this._impl.data.connect(dataCallback);
  this._impl.dataEnd.connect(dataEndCallback);
  return tag;
};

MethodBase.prototype._registerSingleRead = function(cb) {
  return this._registerRead(cb, true);
};

MethodBase.prototype._registerMultiRead = function(cb) {
  return this._registerRead(cb, false);
};

MethodBase.prototype._singleWrite = function(tag, msg) {
  if (msg) {
    this._impl.write(tag, msg._raw);
    this._impl.writeEnd(tag);
  } else {
    this._impl.read(tag);
  }
}

MethodBase.prototype._multiWrite = function(tag) {
  this._impl.read(tag);
  return {
    write: function(msg) {
      if (!tag) {
        throw new Error('Writer session is closed.');
      }
      this._impl.write(tag, msg._raw);
    },

    writeEnd: function() {
      if (!tag) {
        throw new Error('Writer session is closed.');
      }
      this._impl.writeEnd(tag);
      tag = 0;
    },
  };
}

var ReaderWriterMethod = function(impl) { MethodBase.call(this, impl); };
ReaderWriterMethod.prototype = Object.create(MethodBase.prototype);
ReaderWriterMethod.prototype.call = function(cb) {
  return this._multiWrite(this._registerMultiRead(cb));
};

var WriterMethod = function(impl) { MethodBase.call(this, impl); };
WriterMethod.prototype = Object.create(MethodBase.prototype);
WriterMethod.prototype.call = function(cb) {
  return this._multiWrite(this._registerSingleRead(cb));
};

var ReaderMethod = function(impl) { MethodBase.call(this, impl); };
ReaderMethod.prototype = Object.create(MethodBase.prototype);
ReaderMethod.prototype.call = function(msg, cb) {
  this._singleWrite(this._registerMultiRead(cb), msg);
};

var UnaryMethod = function(impl) { MethodBase.call(this, impl); };
UnaryMethod.prototype = Object.create(MethodBase.prototype);
UnaryMethod.prototype.call = function(msg, cb) {
  this._singleWrite(this._registerSingleRead(cb), msg);
};
<|endoftext|>


<commit_before>'use strict';

var astUtils = require('../util/ast'),
    additionalSuiteNames = require('../util/settings').additionalSuiteNames;

module.exports = function noNestedTests(context) {
    var testNestingLevel = 0,
        settings = context.settings;

    function report(callExpression, isTestCase) {
        var message = isTestCase ? 'Unexpected test nested within another test.' :
            'Unexpected suite nested within a test.';

        context.report({
            message: message,
            node: callExpression.callee
        });
    }

    return {
        CallExpression: function (node) {
            var isTestCase = astUtils.isTestCase(node),
                isDescribe = astUtils.isDescribe(node, additionalSuiteNames(settings));

            if (testNestingLevel > 0 && (isTestCase || isDescribe)) {
                report(node, isTestCase);
            }

            if (isTestCase) {
                testNestingLevel += 1;
            }
        },

        'CallExpression:exit': function (node) {
            if (astUtils.isTestCase(node)) {
                testNestingLevel -= 1;
            }
        }
    };
};
<commit_msg>Extract isNestedTest function<commit_after>'use strict';

var astUtils = require('../util/ast'),
    additionalSuiteNames = require('../util/settings').additionalSuiteNames;

module.exports = function noNestedTests(context) {
    var testNestingLevel = 0,
        settings = context.settings;

    function report(callExpression, isTestCase) {
        var message = isTestCase ? 'Unexpected test nested within another test.' :
            'Unexpected suite nested within a test.';

        context.report({
            message: message,
            node: callExpression.callee
        });
    }

    function isNestedTest(isTestCase, isDescribe) {
        var isNested = testNestingLevel > 0,
            isTest = isTestCase || isDescribe;

        return isNested && isTest;
    }

    return {
        CallExpression: function (node) {
            var isTestCase = astUtils.isTestCase(node),
                isDescribe = astUtils.isDescribe(node, additionalSuiteNames(settings));

            if (isNestedTest(isTestCase, isDescribe)) {
                report(node, isTestCase);
            }

            if (isTestCase) {
                testNestingLevel += 1;
            }
        },

        'CallExpression:exit': function (node) {
            if (astUtils.isTestCase(node)) {
                testNestingLevel -= 1;
            }
        }
    };
};
<|endoftext|>


<commit_before>'use strict';
var alexa = require('alexa-app'),
    HarmonyUtils = require('harmony-hub-util'),
    harmony_clients = {},
    conf = require('./remote_conf.js'),
    hub_ip = conf.hub_ip,
    app_id = conf.app_id;

// Define an alexa-app
var app = new alexa.app('remote');

app.launch(function(req, res) {
    console.log("Launching the application");
});

function execCmdDF(hutils, is_device, dev_or_act, cmd, cnt, fn, res) {
    console.log("execCmd called with cnt = " + cnt + " is_dev " + is_device +
                " dev/act " + dev_or_act + " cmd = " + cmd);
    if (cnt === 0) {
        fn(res);
        hutils.end();
        return;
    }
    hutils.executeCommand(is_device, dev_or_act, cmd).then(function (res) {
        console.log(cnt + ". Command " + cmd + " to device/activity " +
                    dev_or_act + " was executed with result : " + res);
        if (res) {
            setTimeout(function () {
                execCmdDF(hutils, is_device, dev_or_act, cmd, cnt - 1, fn, res);
            }, 100);
        }
    }, function(err) {
        console.log("ERROR Occured " + err);
        console.log("      stack " + err.stack);
    });
}

function execCmd(dev, cmd, cnt, fn, res) {
    new HarmonyUtils(hub_ip).then(function (hutil) {
        execCmdDF(hutil, true, dev, cmd, cnt, fn, res);
    });
}

function execCmdCurrentActivity(cmd, cnt, fn, res) {
    new HarmonyUtils(hub_ip).then(function (hutils) {
        hutils.readCurrentActivity().then(function (current_activity) {
            execCmdDF(hutils, false, current_activity, cmd, cnt, fn, res);
        });
    });
}

function execActivity(act, fn) {
    new HarmonyUtils(hub_ip).then(function (hutils) {
        hutils.executeActivity(act).then(function (res) {
            fn(res);
        });
    });
}

app.pre = function(req, res, type) {
    if (req.applicationId !== app_id) {
        console.log(" Received and invalid applicaiton ID " + req.applicationId);
        res.fail("Invalid applicationId");
    }
};

app.intent('IncreaseVolume',
    {
        "slots" : {'AMOUNT' : 'NUMBER'},
        "utterances" : ["{increase|} volume {by|} {1-9|AMOUNT}"]
    },
    function (req, res) {
        var amt = parseInt(req.slot('AMOUNT'), 10);
        if (isNaN(amt)) {
            amt = 1;
        }
        res.say('Increasing volume by ' + amt);
        console.log('Increasing volume by ' + amt);
        execCmdCurrentActivity('Volume,Volume Up', amt, function (res) {
            console.log("Command Volume UP was executed with result : " + res);
        });
    });
app.intent('DecreaseVolume',
    {
        "slots" : {'AMOUNT' : 'NUMBER'},
        "utterances" : ["{decrease volume|reduce volume|down volume|volume down} {by|} {1-9|AMOUNT}"]
    },
    function (req, res) {
        var amt = parseInt(req.slot('AMOUNT'), 10);
        if (isNaN(amt)) {
            amt = 1;
        }
        res.say('Decreasing volume by ' + amt);
        console.log('Decreasing volume by ' + amt);
        execCmdCurrentActivity('Volume,Volume Down', amt, function (res) {
            console.log("Command Volume Down was executed with result : " + res);
        });
    });

app.intent('MuteVolume',
    {
        "slots" : {},
        "utterances" : ["{mute|quiet|shut up|unmute}"]
    },
    function (req, res) {
        res.say('Muting!');
        console.log('Muting!');
        execCmdCurrentActivity('Volume,Mute', 1, function (res) {
            console.log("Command Mute executed with result : " + res);
        });
    });

app.intent('IncreaseTVVolume',
    {
        "slots" : {'AMOUNT' : 'NUMBER'},
        "utterances" : ["{increase|} TV volume by {1-9|AMOUNT}"]
    },
    function (req, res) {
        var amt = parseInt(req.slot('AMOUNT'), 10);
        if (isNaN(amt)) {
            amt = 1;
        }
        res.say('Increasing TV volume by ' + amt);
        console.log('Increasing volume by ' + amt);
        execCmd('TV', 'VolumeUp', amt, function (res) {
            console.log("Command Volume UP was executed with result : " + res);
        });
    });
app.intent('DecreaseTVVolume',
    {
        "slots" : {'AMOUNT' : 'NUMBER'},
        "utterances" : ["{decrease TV volume|reduce TV volume} by {1-9|AMOUNT}"]
    },
    function (req, res) {
        var amt = parseInt(req.slot('AMOUNT'), 10);
        if (isNaN(amt)) {
            amt = 1;
        }
        res.say('Decreasing TV volume by ' + amt);
        console.log('Decreasing volume by ' + amt);
        execCmd('TV', 'VolumeDown', amt, function (res) {
            console.log("Command Volume Down was executed with result : " + res);
        });
    });

app.intent('MuteTVVolume',
    {
        "slots" : {},
        "utterances" : ["{mute|unmute} {TV|telivision}"]
    },
    function (req, res) {
        res.say('Muting TV!');
        console.log('Muting!');
        execCmd('TV', 'Mute', 1, function (res) {
            console.log("Command Mute executed with result : " + res);
        });
    });

app.intent('TurnOffTV',
    {
        "slots" : {},
        "utterances" : ["{turn the TV off|turn TV off}"]
    },
    function (req, res) {
        res.say('Turning TV off!');
        console.log('Turning TV off!');
        execCmd('TV', 'PowerOff', 1, function (res) {
            console.log("Command TV PowerOff executed with result : " + res);
        });
    });

app.intent('TurnOnTV',
    {
        "slots" : {},
        "utterances" : ["{turn on the TV|turn the TV on|turn on TV|turn TV on}"]
    },
    function (req, res) {
        res.say('Turning TV on!');
        console.log('Turning TV on!');
        execCmd('TV', 'PowerOn', 1, function (res) {
            console.log("Command TV PowerOn executed with result : " + res);
        });
    });

app.intent('TurnOffAmplifier',
    {
        "slots" : {},
        "utterances" : ["{turn the amplifer off|turn amplifier off}"]
    },
    function (req, res) {
        res.say('Turning amplifer off!');
        console.log('Turning amplifier off!');
        execCmd('Amplifier', 'PowerToggle', 1, function (res) {
            console.log("Command for amplifer PowerToggle executed with result : " + res);
        });
    });

app.intent('TurnOnAmplifier',
    {
        "slots" : {},
        "utterances" : ["{turn on the amplifier|turn the amplifier on}"]
    },
    function (req, res) {
        res.say('Toggle power on the amplifier!');
        console.log('Turning amplifier on!');
        execCmd('Amplifier', 'PowerToggle', 1, function (res) {
            console.log("Command Amplifier PowerToggle executed with result : " + res);
        });
    });

app.intent('AmplifierInputNext',
    {
        "slots" : {},
        "utterances" : ["{select next amplifier input}"]
    },
    function (req, res) {
        res.say('selecting next input on amplifier!');
        console.log('Selecting next amplifier input!');
        execCmd('Amplifier', 'InputNext', 1, function (res) {
            console.log("Command Amplifier InputNext executed with result : " + res);
        });
    });

app.intent('SelectChromeCast',
    {
        "slots" : {},
        "utterances" : ["{to|} {select|} {chrome cast|chromecast}"]
    },
    function (req, res) {
        res.say('Selecting Chromecast!');
        console.log('Selecting Chromecast!');
        execCmd('TV', 'InputHdmi3', 1, function (res) {
            console.log("Command TV InputHdmi3 executed with result : " + res);
        });
    });

app.intent('SelectTivo',
    {
        "slots" : {},
        "utterances" : ["{to|} select tivo"]
    },
    function (req, res) {
        res.say('Selecting tivo!');
        console.log('Selecting tivo!');
        execCmd('TV', 'InputHdmi2', 1, function (res) {
            console.log("Command TV InputHdmi2 executed with result : " + res);
        });
    });

app.intent('SelectPlaystation',
    {
        "slots" : {},
        "utterances" : ["{select|} {playstation}"]
    },
    function (req, res) {
        res.say('Selecting ps4!');
        console.log('Selecting ps4!');
        execCmd('TV', 'InputHdmi1', 1, function (res) {
            console.log("Command TV InputHdmi1 executed with result : " + res);
        });
    });

app.intent('WatchNBC',
      {
          "slots" : {},
          "utterances" : ["{to|} watch nbc"]
      },
      function (req, res) {
          res.say('Turning on NBC!');
          console.log('Turning on NBC!');
          execActivity('Watch Tivo', function (res) {
              console.log("Command to Watch Tivo executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 5, function (res) {
              console.log("Command Tivo NumericBasic 5 executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 1, function (res) {
              console.log("Command Tivo NumericBasic 1 executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 6, function (res) {
              console.log("Command Tivo NumericBasic 6 executed with result : " + res);
          });
      });
app.intent('WatchTBS',
      {
          "slots" : {},
          "utterances" : ["{to|} watch nbc"]
      },
      function (req, res) {
          res.say('Turning on TBS!');
          console.log('Turning on TBS!');
          execActivity('Watch Tivo', function (res) {
              console.log("Command to Watch Tivo executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 5, function (res) {
              console.log("Command Tivo NumericBasic 5 executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 5, function (res) {
              console.log("Command Tivo NumericBasic 5 executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 2, function (res) {
              console.log("Command Tivo NumericBasic 2 executed with result : " + res);
          });
      });

app.intent('TurnOff',
    {
        "slots" : {},
        "utterances" : ["{shutdown|good night|power everything off|power off everything|turn everything off|turn off everything|shut down}"]
    },
    function (req, res) {
        res.say('Turning off everything!');
        console.log('Turning off everythign!');
        execActivity('PowerOff', function (res) {
            console.log("Command to PowerOff executed with result : " + res);
        });
    });

app.intent('Movie',
    {
        "slots" : {},
        "utterances" : ["{movie|start movie|watch movie}"]
    },
    function (req, res) {
        res.say('Turning on Movie Mode!');
        console.log('Turning on Movie Mode!');
        execActivity('Watch a Movie', function (res) {
            console.log("Command to Watch a Movie executed with result : " + res);
        });
    });

app.intent('TIVO',
    {
        "slots" : {},
        "utterances" : ["{tivo|start tivo|watch tivo}"]
    },
    function (req, res) {
        res.say('Turning on Tivo Mode!');
        console.log('Turning on Tivo Mode!');
        execActivity('Watch Tivo', function (res) {
            console.log("Command to Watch Tivo executed with result : " + res);
        });
    });

app.intent('Music',
    {
        "slots" : {},
        "utterances" : ["{music|start music}"]
    },
    function (req, res) {
        res.say('Turning on Music Mode!');
        console.log('Turning on Music Mode!');
        execActivity('Listen to Digital Music', function (res) {
            console.log("Command to Music executed with result : " + res);
        });
    });

module.exports = app;
<commit_msg>Fixed TBS utterance<commit_after>'use strict';
var alexa = require('alexa-app'),
    HarmonyUtils = require('harmony-hub-util'),
    harmony_clients = {},
    conf = require('./remote_conf.js'),
    hub_ip = conf.hub_ip,
    app_id = conf.app_id;

// Define an alexa-app
var app = new alexa.app('remote');

app.launch(function(req, res) {
    console.log("Launching the application");
});

function execCmdDF(hutils, is_device, dev_or_act, cmd, cnt, fn, res) {
    console.log("execCmd called with cnt = " + cnt + " is_dev " + is_device +
                " dev/act " + dev_or_act + " cmd = " + cmd);
    if (cnt === 0) {
        fn(res);
        hutils.end();
        return;
    }
    hutils.executeCommand(is_device, dev_or_act, cmd).then(function (res) {
        console.log(cnt + ". Command " + cmd + " to device/activity " +
                    dev_or_act + " was executed with result : " + res);
        if (res) {
            setTimeout(function () {
                execCmdDF(hutils, is_device, dev_or_act, cmd, cnt - 1, fn, res);
            }, 100);
        }
    }, function(err) {
        console.log("ERROR Occured " + err);
        console.log("      stack " + err.stack);
    });
}

function execCmd(dev, cmd, cnt, fn, res) {
    new HarmonyUtils(hub_ip).then(function (hutil) {
        execCmdDF(hutil, true, dev, cmd, cnt, fn, res);
    });
}

function execCmdCurrentActivity(cmd, cnt, fn, res) {
    new HarmonyUtils(hub_ip).then(function (hutils) {
        hutils.readCurrentActivity().then(function (current_activity) {
            execCmdDF(hutils, false, current_activity, cmd, cnt, fn, res);
        });
    });
}

function execActivity(act, fn) {
    new HarmonyUtils(hub_ip).then(function (hutils) {
        hutils.executeActivity(act).then(function (res) {
            fn(res);
        });
    });
}

app.pre = function(req, res, type) {
    if (req.applicationId !== app_id) {
        console.log(" Received and invalid applicaiton ID " + req.applicationId);
        res.fail("Invalid applicationId");
    }
};

app.intent('IncreaseVolume',
    {
        "slots" : {'AMOUNT' : 'NUMBER'},
        "utterances" : ["{increase|} volume {by|} {1-9|AMOUNT}"]
    },
    function (req, res) {
        var amt = parseInt(req.slot('AMOUNT'), 10);
        if (isNaN(amt)) {
            amt = 1;
        }
        res.say('Increasing volume by ' + amt);
        console.log('Increasing volume by ' + amt);
        execCmdCurrentActivity('Volume,Volume Up', amt, function (res) {
            console.log("Command Volume UP was executed with result : " + res);
        });
    });
app.intent('DecreaseVolume',
    {
        "slots" : {'AMOUNT' : 'NUMBER'},
        "utterances" : ["{decrease volume|reduce volume|down volume|volume down} {by|} {1-9|AMOUNT}"]
    },
    function (req, res) {
        var amt = parseInt(req.slot('AMOUNT'), 10);
        if (isNaN(amt)) {
            amt = 1;
        }
        res.say('Decreasing volume by ' + amt);
        console.log('Decreasing volume by ' + amt);
        execCmdCurrentActivity('Volume,Volume Down', amt, function (res) {
            console.log("Command Volume Down was executed with result : " + res);
        });
    });

app.intent('MuteVolume',
    {
        "slots" : {},
        "utterances" : ["{mute|quiet|shut up|unmute}"]
    },
    function (req, res) {
        res.say('Muting!');
        console.log('Muting!');
        execCmdCurrentActivity('Volume,Mute', 1, function (res) {
            console.log("Command Mute executed with result : " + res);
        });
    });

app.intent('IncreaseTVVolume',
    {
        "slots" : {'AMOUNT' : 'NUMBER'},
        "utterances" : ["{increase|} TV volume by {1-9|AMOUNT}"]
    },
    function (req, res) {
        var amt = parseInt(req.slot('AMOUNT'), 10);
        if (isNaN(amt)) {
            amt = 1;
        }
        res.say('Increasing TV volume by ' + amt);
        console.log('Increasing volume by ' + amt);
        execCmd('TV', 'VolumeUp', amt, function (res) {
            console.log("Command Volume UP was executed with result : " + res);
        });
    });
app.intent('DecreaseTVVolume',
    {
        "slots" : {'AMOUNT' : 'NUMBER'},
        "utterances" : ["{decrease TV volume|reduce TV volume} by {1-9|AMOUNT}"]
    },
    function (req, res) {
        var amt = parseInt(req.slot('AMOUNT'), 10);
        if (isNaN(amt)) {
            amt = 1;
        }
        res.say('Decreasing TV volume by ' + amt);
        console.log('Decreasing volume by ' + amt);
        execCmd('TV', 'VolumeDown', amt, function (res) {
            console.log("Command Volume Down was executed with result : " + res);
        });
    });

app.intent('MuteTVVolume',
    {
        "slots" : {},
        "utterances" : ["{mute|unmute} {TV|telivision}"]
    },
    function (req, res) {
        res.say('Muting TV!');
        console.log('Muting!');
        execCmd('TV', 'Mute', 1, function (res) {
            console.log("Command Mute executed with result : " + res);
        });
    });

app.intent('TurnOffTV',
    {
        "slots" : {},
        "utterances" : ["{turn the TV off|turn TV off}"]
    },
    function (req, res) {
        res.say('Turning TV off!');
        console.log('Turning TV off!');
        execCmd('TV', 'PowerOff', 1, function (res) {
            console.log("Command TV PowerOff executed with result : " + res);
        });
    });

app.intent('TurnOnTV',
    {
        "slots" : {},
        "utterances" : ["{turn on the TV|turn the TV on|turn on TV|turn TV on}"]
    },
    function (req, res) {
        res.say('Turning TV on!');
        console.log('Turning TV on!');
        execCmd('TV', 'PowerOn', 1, function (res) {
            console.log("Command TV PowerOn executed with result : " + res);
        });
    });

app.intent('TurnOffAmplifier',
    {
        "slots" : {},
        "utterances" : ["{turn the amplifer off|turn amplifier off}"]
    },
    function (req, res) {
        res.say('Turning amplifer off!');
        console.log('Turning amplifier off!');
        execCmd('Amplifier', 'PowerToggle', 1, function (res) {
            console.log("Command for amplifer PowerToggle executed with result : " + res);
        });
    });

app.intent('TurnOnAmplifier',
    {
        "slots" : {},
        "utterances" : ["{turn on the amplifier|turn the amplifier on}"]
    },
    function (req, res) {
        res.say('Toggle power on the amplifier!');
        console.log('Turning amplifier on!');
        execCmd('Amplifier', 'PowerToggle', 1, function (res) {
            console.log("Command Amplifier PowerToggle executed with result : " + res);
        });
    });

app.intent('AmplifierInputNext',
    {
        "slots" : {},
        "utterances" : ["{select next amplifier input}"]
    },
    function (req, res) {
        res.say('selecting next input on amplifier!');
        console.log('Selecting next amplifier input!');
        execCmd('Amplifier', 'InputNext', 1, function (res) {
            console.log("Command Amplifier InputNext executed with result : " + res);
        });
    });

app.intent('SelectChromeCast',
    {
        "slots" : {},
        "utterances" : ["{to|} {select|} {chrome cast|chromecast}"]
    },
    function (req, res) {
        res.say('Selecting Chromecast!');
        console.log('Selecting Chromecast!');
        execCmd('TV', 'InputHdmi3', 1, function (res) {
            console.log("Command TV InputHdmi3 executed with result : " + res);
        });
    });

app.intent('SelectTivo',
    {
        "slots" : {},
        "utterances" : ["{to|} select tivo"]
    },
    function (req, res) {
        res.say('Selecting tivo!');
        console.log('Selecting tivo!');
        execCmd('TV', 'InputHdmi2', 1, function (res) {
            console.log("Command TV InputHdmi2 executed with result : " + res);
        });
    });

app.intent('SelectPlaystation',
    {
        "slots" : {},
        "utterances" : ["{select|} {playstation}"]
    },
    function (req, res) {
        res.say('Selecting ps4!');
        console.log('Selecting ps4!');
        execCmd('TV', 'InputHdmi1', 1, function (res) {
            console.log("Command TV InputHdmi1 executed with result : " + res);
        });
    });

app.intent('TurnOff',
    {
        "slots" : {},
        "utterances" : ["{shutdown|good night|power everything off|power off everything|turn everything off|turn off everything|shut down}"]
    },
    function (req, res) {
        res.say('Turning off everything!');
        console.log('Turning off everythign!');
        execActivity('PowerOff', function (res) {
            console.log("Command to PowerOff executed with result : " + res);
        });
    });

app.intent('Movie',
    {
        "slots" : {},
        "utterances" : ["{movie|start movie|watch movie}"]
    },
    function (req, res) {
        res.say('Turning on Movie Mode!');
        console.log('Turning on Movie Mode!');
        execActivity('Watch a Movie', function (res) {
            console.log("Command to Watch a Movie executed with result : " + res);
        });
    });

app.intent('TIVO',
    {
        "slots" : {},
        "utterances" : ["{tivo|start tivo|watch tivo}"]
    },
    function (req, res) {
        res.say('Turning on Tivo Mode!');
        console.log('Turning on Tivo Mode!');
        execActivity('Watch Tivo', function (res) {
            console.log("Command to Watch Tivo executed with result : " + res);
        });
    });

app.intent('Music',
    {
        "slots" : {},
        "utterances" : ["{music|start music}"]
    },
    function (req, res) {
        res.say('Turning on Music Mode!');
        console.log('Turning on Music Mode!');
        execActivity('Listen to Digital Music', function (res) {
            console.log("Command to Music executed with result : " + res);
        });
    });

app.intent('WatchNBC',
      {
          "slots" : {},
          "utterances" : ["{to|} watch nbc"]
      },
      function (req, res) {
          res.say('Turning on NBC!');
          console.log('Turning on NBC!');
          execActivity('Watch Tivo', function (res) {
              console.log("Command to Watch Tivo executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 5, function (res) {
              console.log("Command Tivo NumericBasic 5 executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 1, function (res) {
              console.log("Command Tivo NumericBasic 1 executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 6, function (res) {
              console.log("Command Tivo NumericBasic 6 executed with result : " + res);
          });
      });

app.intent('WatchTBS',
      {
          "slots" : {},
          "utterances" : ["{to|} watch tbs"]
      },
      function (req, res) {
          res.say('Turning on TBS!');
          console.log('Turning on TBS!');
          execActivity('Watch Tivo', function (res) {
              console.log("Command to Watch Tivo executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 5, function (res) {
              console.log("Command Tivo NumericBasic 5 executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 5, function (res) {
              console.log("Command Tivo NumericBasic 5 executed with result : " + res);
          });
          execCmd('Tivo', 'NumericBasic', 2, function (res) {
              console.log("Command Tivo NumericBasic 2 executed with result : " + res);
          });
      });

module.exports = app;
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const merge = require('webpack-merge');
const xmldom = require('xmldom');
const svgToMiniDataURI = require('mini-svg-data-uri');
const { findUniqueVariables, rewriteVariables } = require('../variable-parser');

// Variables
const INDENT = '    ';

module.exports = (symbols = [], options = {}) => {
    options = merge({
        prefix: ''
    }, options);

    const XMLSerializer = new xmldom.XMLSerializer();
    const XMLDoc = new xmldom.DOMImplementation().createDocument(null, null, null);

    const output = symbols.reduce((accumulator, symbol) => {
        const svg = XMLDoc.createElement('svg');
        svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
        svg.setAttribute('viewBox', symbol.getAttribute('viewBox'));

        // Clone symbol contents to svg
        Array.from(symbol.childNodes).forEach((childNode) => {
            if ( ['title'].includes(childNode.nodeName.toLowerCase()) ) {
                return;
            }

            svg.appendChild(childNode);
        });

        // Parse variables
        const sprite = XMLSerializer.serializeToString(svg);
        const variables = findUniqueVariables(sprite).map((variable) => {
            const value = svgToMiniDataURI(variable.value).replace('data:image/svg+xml,', '');
            return `"${variable.name}": "${value}"`
        });

        const selector = symbol.getAttribute('id').replace(options.prefix, '');
        const dataURI = svgToMiniDataURI(rewriteVariables(sprite, (name, attribute) => {
            return `${attribute}="___${name}___"`;
        }));

        return Object.assign({}, accumulator, {
            sprites: [...accumulator.sprites, `'${selector}': "${dataURI}"`],
            variables: [...accumulator.variables, `'${selector}': (\n${INDENT}${INDENT}${variables.join(`,\n${INDENT}${INDENT}`)}\n${INDENT})`]
        });
    }, {
        sprites: [],
        variables: []
    });

    return fs.readFileSync(path.join(__dirname, '../templates/styles.scss'), 'utf8')
        .replace('/* SPRITES */', output.sprites.map((sprite) => `${INDENT}${sprite}`).join(',\n').trim())
        .replace('/* VARIABLES */', output.variables.map((variable) => `${INDENT}${variable}`).join(',\n').trim());
};
<commit_msg>Improves indentation method for SCSS formatter<commit_after>const fs = require('fs');
const path = require('path');
const merge = require('webpack-merge');
const xmldom = require('xmldom');
const svgToMiniDataURI = require('mini-svg-data-uri');
const { findUniqueVariables, rewriteVariables } = require('../variable-parser');

// Variables
const indent = (columns = 1, indenation = 4) => {
    return ' '.repeat(columns * indenation);
};

module.exports = (symbols = [], options = {}) => {
    options = merge({
        prefix: ''
    }, options);

    const XMLSerializer = new xmldom.XMLSerializer();
    const XMLDoc = new xmldom.DOMImplementation().createDocument(null, null, null);

    const output = symbols.reduce((accumulator, symbol) => {
        const svg = XMLDoc.createElement('svg');
        svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
        svg.setAttribute('viewBox', symbol.getAttribute('viewBox'));

        // Clone symbol contents to svg
        Array.from(symbol.childNodes).forEach((childNode) => {
            if ( ['title'].includes(childNode.nodeName.toLowerCase()) ) {
                return;
            }

            svg.appendChild(childNode);
        });

        // Parse variables
        const sprite = XMLSerializer.serializeToString(svg);
        const variables = findUniqueVariables(sprite).map((variable) => {
            const value = svgToMiniDataURI(variable.value).replace('data:image/svg+xml,', '');
            return `"${variable.name}": "${value}"`
        });

        const selector = symbol.getAttribute('id').replace(options.prefix, '');
        const dataURI = svgToMiniDataURI(rewriteVariables(sprite, (name, attribute) => {
            return `${attribute}="___${name}___"`;
        }));

        return Object.assign({}, accumulator, {
            sprites: [...accumulator.sprites, `'${selector}': "${dataURI}"`],
            variables: [...accumulator.variables, `'${selector}': (\n${indent(2)}${variables.join(`,\n${indent(2)}`)}\n${indent()})`]
        });
    }, {
        sprites: [],
        variables: []
    });

    return fs.readFileSync(path.join(__dirname, '../templates/styles.scss'), 'utf8')
        .replace('/* SPRITES */', output.sprites.map((sprite) => `${indent()}${sprite}`).join(',\n').trim())
        .replace('/* VARIABLES */', output.variables.map((variable) => `${indent()}${variable}`).join(',\n').trim());
};
<|endoftext|>


<commit_before>/* global define */
/*
 * TimePicker - Enhances an input field with a time picker dropdown
 * https://github.com/BrandwatchLtd/timepicker
 *
 * Dependencies: jQuery, underscore.js, moment.js
 *
 * License: MIT
 **/
(function (root, factory) {
    'use strict';

    /**
     * MicroEvent - to make any js object an event emitter (server or browser)
     *
     * - pure javascript - server compatible, browser compatible
     * - dont rely on the browser doms
     * - super simple - you get it immediatly, no mistery, no magic involved
     *
     * - create a MicroEventDebug with goodies to debug
     *   - make it safer to use
     */

    var MicroEvent = function () {};
    MicroEvent.prototype = {
        bind: function (event, fct) {
            this._events = this._events || {};
            this._events[event] = this._events[event] || [];
            this._events[event].push(fct);
        },
        unbind: function (event, fct) {
            this._events = this._events || {};
            if (event in this._events === false) {
                return;
            }
            this._events[event].splice(this._events[event].indexOf(fct), 1);
        },
        trigger: function (event /* , args... */ ) {
            this._events = this._events || {};
            if (event in this._events === false) {
                return;
            }
            for (var i = 0; i < this._events[event].length; i++) {
                this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
            }
        }
    };

    /**
     * mixin will delegate all MicroEvent.js function in the destination object
     *
     * - require('MicroEvent').mixin(Foobar) will make Foobar able to use MicroEvent
     *
     * @param {Object} the object which will support MicroEvent
     */
    MicroEvent.mixin = function (destObject) {
        var props = ['bind', 'unbind', 'trigger'];
        for (var i = 0; i < props.length; i++) {
            if (typeof destObject === 'function') {
                destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
            } else {
                destObject[props[i]] = MicroEvent.prototype[props[i]];
            }
        }
    };
    /// END MicroEvents

    // Work with AMD or plain-ol script tag
    if (typeof define === 'function' && define.amd) {
        // If window.jQuery or window._ are not defined, then assume we're using AMD modules
        define(['jquery', 'underscore', 'moment'], function ($, _, moment) {
            return factory($ || root.jQuery, _ || root._, moment || root.moment, MicroEvent);
        });
    } else {
        root.timepicker = factory(root.jQuery, root._, root.moment, MicroEvent);
    }

})(this, function ($, _, moment, MicroEvent) {
    'use strict';

    if (!$) {
        throw new Error('timepicker requires jQuery to be loaded');
    }

    if (!_) {
        throw new Error('timepicker requires underscore to be loaded');
    }

    if (!moment) {
        throw new Error('timepicker requires moment to be loaded');
    }

    // TimePicker
    var TIME_REGEX = /^([01]\d|2[0-3]):?([0-5]\d)$/,
        DOWN_ARROW_CODE = 40,
        MAX_MINUTES_CHECKED = 60,
        PUBLIC_METHODS = [
            'destroy',
            'open',
            'close',
            'select',
            'deselect',
            'reset'
        ],
        findNearestPresetTimeMemo = _.memoize(findNearestPresetTime);

    function buildTimePickerList(presetTimes) {
        return presetTimes.map(function (time) {
            return '
' + time + '
';
        }).join('');
    }

    function buildPicker(options) {
        var $ul = $('
');

        $ul
            .addClass(options.pickerClassName)
            .html(buildTimePickerList(options.presetTimes));

        return $ul;
    }

    function getPresetTimes(intervalDuration) {
        var presetTimes = [],
            interval = moment(intervalDuration, 'HH:mm'),
            start = moment().startOf('day'),
            end = moment(start).add({
                'days': 1
            }),
            duration = moment.duration({
                'hours': interval.hours(),
                'minutes': interval.minutes()
            });

        while (start.diff(end) < 0) {
            presetTimes.push(start.format('HH:mm'));
            start = start.add(duration);
        }

        return presetTimes;
    }

    function setupEvents(timepicker) {
        timepicker.$input.on('click.timepicker', function (e) {
            e.stopPropagation();
            e.preventDefault();

            timepicker.open();
        });

        timepicker.$input.on('blur.timepicker', function () {
            timepicker.close();
        });

        timepicker.$input.on('focus.timepicker', function () {
            timepicker.open();
        });

        timepicker.$picker.on('click.timepicker', 'li', function (e) {
            e.preventDefault();
            e.stopPropagation();

            timepicker._preventClose = false;
            timepicker.select($(e.target).data('time'));
            timepicker.close();
        });

        timepicker.$picker.on('mousedown.timepicker', 'li', function () {
            timepicker._preventClose = true;

            $('body').one('mouseup', function () {
                timepicker.$picker.hide();
            });
        });

        timepicker.$input.on('keydown.timepicker', function (e) {
            if (e.keyCode === DOWN_ARROW_CODE) {
                timepicker.open();
                return;
            }
            timepicker.close();
            timepicker.reset();
        });
    }

    function isPresetTime(timeStr, presetTimes) {
        return presetTimes.indexOf(timeStr) >= 0;
    }

    function findNearestPresetTime(timeStr, presetTimes) {
        var time,
            minutesChecked = 0;

        time = moment(timeStr, 'HH:mm');

        function direction() {
            return (minutesChecked % 2) ? minutesChecked : -minutesChecked;
        }

        function seek(time) {
            var attemptTimeStr = time.format('HH:mm');

            if (isPresetTime(attemptTimeStr, presetTimes)) {
                return attemptTimeStr;
            }

            if (minutesChecked > MAX_MINUTES_CHECKED) {
                return;
            }

            minutesChecked += 1;

            time.add('minutes', direction());

            return seek(time);
        }

        return seek(time);
    }

    function TimePicker($input) {
        this.presetTimes = getPresetTimes(this.custom.interval);

        this.$input = $input;

        this.$picker = buildPicker({
            pickerClassName: this.custom.pickerClassName,
            presetTimes: this.presetTimes
        });

        this._preventClose = false;
        this._preventOpen = false;
        this._isOpen = false;

        setupEvents(this);
    }

    TimePicker.prototype.open = function () {
        if(this._preventOpen || this._isOpen) {
           return;
        }

        var inputPosition = this.$input.offset(),
            currentTime = this.$input.val();

        this.$picker
            .appendTo(this.custom.pickerContainer)
            .css({
                top: inputPosition.top + this.$input.outerHeight(),
                left: inputPosition.left
            })
            .show();

        this._isOpen = true;

        if (isPresetTime(currentTime, this.presetTimes)) {
            this.select(currentTime, {silent: true});
        }
        scrollToShowTime(this, currentTime, this.presetTimes);

        this.trigger('onOpen');
    };

    TimePicker.prototype.findOptionByTime = function (time) {
        return this.$picker.find('[data-time="' + time + '"]');
    };

    TimePicker.prototype.close = function () {
        if (this._preventClose) {
            return;
        }
        this.$picker.hide();
        this._isOpen = false;
    };

    TimePicker.prototype.select = function (time, options) {
        var $option = this.findOptionByTime(time),
            isSilent = (options || {}).silent === true;

        this.deselect();

        if (this.$input.val() !== time) {
            this.$input.val(time);
        }
        $option.addClass(this.custom.pickerSelectedClassName);

        this._preventOpen = true;

        if (!isSilent) {
            this.$input.trigger('change').trigger('focus');
            this.trigger('onSelect', time);
        }

        this._preventOpen = false;
    };

    TimePicker.prototype.reset = function () {
        this.deselect();
    };

    TimePicker.prototype.destroy = function () {
        this.$picker.remove();
        this.$input.off('.timepicker');
        this.$input.removeData('timepicker');
    };

    TimePicker.prototype.deselect = function () {
        this.$picker.find('li').removeClass(this.custom.pickerSelectedClassName);
    };

    function scrollToShowTime(picker, time, presetTimes) {
        var timePickerHeight,
            itemHeight,
            idealPosition,
            selectedTimePosition,
            scrollAdjustment = 0,
            needsAdjustment,
            nearestPresetTime,
            $selectedTime;

        if (!time) {
            picker.$picker.scrollTop(scrollAdjustment);
            return;
        }

        nearestPresetTime = findNearestPresetTimeMemo(time, presetTimes);

        if (!nearestPresetTime) {
            picker.$picker.scrollTop(scrollAdjustment);
            return;
        }

        $selectedTime = picker.findOptionByTime(nearestPresetTime);

        timePickerHeight = picker.$picker.outerHeight();
        itemHeight = $selectedTime.outerHeight();
        selectedTimePosition = $selectedTime.index() * itemHeight;

        // ideally should be in the middle of the time picker
        idealPosition = timePickerHeight / 2 - itemHeight / 2;

        // only adjust if the selected item is outside the ideal position
        needsAdjustment = selectedTimePosition > idealPosition;

        if (needsAdjustment) {
            scrollAdjustment = Math.abs(selectedTimePosition - idealPosition);
        }

        picker.$picker.scrollTop(scrollAdjustment);
    }

    function isValidMethod(method) {
        if (PUBLIC_METHODS.indexOf(method) === -1) {
            throw new Error('Invalid timepicker method');
        }
        return true;
    }

    function isValidInterval(interval) {
        if (!TIME_REGEX.exec(interval)) {
            throw new Error('Invalid interval, must be a valid time');
        }
    }

    function isValidOptions(options) {
        if (options.interval) {
            isValidInterval(options.interval);
        }
        return true;
    }

    MicroEvent.mixin(TimePicker);

    function setupPlugin($inputs, options) {
        options = $.extend({}, $.timepicker.defaults, options);

        return $inputs.each(function () {
            var $input = $(this),
                instance,
                currentInstance = $input.data('timepicker');

            // destroy the existing time picker
            if (currentInstance) {
                currentInstance.destroy();
                currentInstance = undefined;
            }

            // extend prototype with customisable options
            $.extend(TimePicker.prototype, {
                custom: options
            });

            instance = new TimePicker($input);

            // store reference to timepicker instance on elements $.data
            $input.data('timepicker', instance);
        });
    }

    function runPluginMethod($inputs, method, args) {
        return $inputs.each(function () {
            var $input = $(this),
                timepicker;

            timepicker = $input.data('timepicker');
            timepicker[method].apply(timepicker, args);
        });
    }

    function isInstantiation(options) {
        return _.isObject(options) && isValidOptions(options);
    }

    function isMethodCall(options) {
        return _.isString(options) && isValidMethod(options);
    }

    $.fn.timepicker = function (value) {
        var options = value || {};

        if (isInstantiation(options)) {
            return setupPlugin(this, options);
        } else if (isMethodCall(options)) {
            return runPluginMethod(this, options, Array.prototype.slice.call(arguments, 1));
        } else {
            throw new Error('Invalid timepicker call');
        }
    };

    // static methods
    $.timepicker = {};

    // default options
    $.timepicker.defaults = {
        pickerContainer: 'body',
        pickerClassName: 'time-picker',
        pickerSelectedClassName: 'time-picker--selected',
        interval: '01:00'
    };

    // custom selector
    $.expr[':'].timepicker = function (elem) {
        return $(elem).data('timepicker') !== undefined;
    };

    return TimePicker;
});
<commit_msg>Replace isOpen state with DOM check<commit_after>/* global define */
/*
 * TimePicker - Enhances an input field with a time picker dropdown
 * https://github.com/BrandwatchLtd/timepicker
 *
 * Dependencies: jQuery, underscore.js, moment.js
 *
 * License: MIT
 **/
(function (root, factory) {
    'use strict';

    /**
     * MicroEvent - to make any js object an event emitter (server or browser)
     *
     * - pure javascript - server compatible, browser compatible
     * - dont rely on the browser doms
     * - super simple - you get it immediatly, no mistery, no magic involved
     *
     * - create a MicroEventDebug with goodies to debug
     *   - make it safer to use
     */

    var MicroEvent = function () {};
    MicroEvent.prototype = {
        bind: function (event, fct) {
            this._events = this._events || {};
            this._events[event] = this._events[event] || [];
            this._events[event].push(fct);
        },
        unbind: function (event, fct) {
            this._events = this._events || {};
            if (event in this._events === false) {
                return;
            }
            this._events[event].splice(this._events[event].indexOf(fct), 1);
        },
        trigger: function (event /* , args... */ ) {
            this._events = this._events || {};
            if (event in this._events === false) {
                return;
            }
            for (var i = 0; i < this._events[event].length; i++) {
                this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
            }
        }
    };

    /**
     * mixin will delegate all MicroEvent.js function in the destination object
     *
     * - require('MicroEvent').mixin(Foobar) will make Foobar able to use MicroEvent
     *
     * @param {Object} the object which will support MicroEvent
     */
    MicroEvent.mixin = function (destObject) {
        var props = ['bind', 'unbind', 'trigger'];
        for (var i = 0; i < props.length; i++) {
            if (typeof destObject === 'function') {
                destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
            } else {
                destObject[props[i]] = MicroEvent.prototype[props[i]];
            }
        }
    };
    /// END MicroEvents

    // Work with AMD or plain-ol script tag
    if (typeof define === 'function' && define.amd) {
        // If window.jQuery or window._ are not defined, then assume we're using AMD modules
        define(['jquery', 'underscore', 'moment'], function ($, _, moment) {
            return factory($ || root.jQuery, _ || root._, moment || root.moment, MicroEvent);
        });
    } else {
        root.timepicker = factory(root.jQuery, root._, root.moment, MicroEvent);
    }

})(this, function ($, _, moment, MicroEvent) {
    'use strict';

    if (!$) {
        throw new Error('timepicker requires jQuery to be loaded');
    }

    if (!_) {
        throw new Error('timepicker requires underscore to be loaded');
    }

    if (!moment) {
        throw new Error('timepicker requires moment to be loaded');
    }

    // TimePicker
    var TIME_REGEX = /^([01]\d|2[0-3]):?([0-5]\d)$/,
        DOWN_ARROW_CODE = 40,
        MAX_MINUTES_CHECKED = 60,
        PUBLIC_METHODS = [
            'destroy',
            'open',
            'close',
            'select',
            'deselect',
            'reset'
        ],
        findNearestPresetTimeMemo = _.memoize(findNearestPresetTime);

    function buildTimePickerList(presetTimes) {
        return presetTimes.map(function (time) {
            return '
' + time + '
';
        }).join('');
    }

    function buildPicker(options) {
        var $ul = $('
');

        $ul
            .addClass(options.pickerClassName)
            .html(buildTimePickerList(options.presetTimes));

        return $ul;
    }

    function getPresetTimes(intervalDuration) {
        var presetTimes = [],
            interval = moment(intervalDuration, 'HH:mm'),
            start = moment().startOf('day'),
            end = moment(start).add({
                'days': 1
            }),
            duration = moment.duration({
                'hours': interval.hours(),
                'minutes': interval.minutes()
            });

        while (start.diff(end) < 0) {
            presetTimes.push(start.format('HH:mm'));
            start = start.add(duration);
        }

        return presetTimes;
    }

    function setupEvents(timepicker) {
        timepicker.$input.on('click.timepicker', function (e) {
            e.stopPropagation();
            e.preventDefault();

            timepicker.open();
        });

        timepicker.$input.on('blur.timepicker', function () {
            timepicker.close();
        });

        timepicker.$input.on('focus.timepicker', function () {
            timepicker.open();
        });

        timepicker.$picker.on('click.timepicker', 'li', function (e) {
            e.preventDefault();
            e.stopPropagation();

            timepicker._preventClose = false;
            timepicker.select($(e.target).data('time'));
            timepicker.close();
        });

        timepicker.$picker.on('mousedown.timepicker', 'li', function () {
            timepicker._preventClose = true;

            $('body').one('mouseup', function () {
                timepicker.$picker.hide();
            });
        });

        timepicker.$input.on('keydown.timepicker', function (e) {
            if (e.keyCode === DOWN_ARROW_CODE) {
                timepicker.open();
                return;
            }
            timepicker.close();
            timepicker.reset();
        });
    }

    function isPresetTime(timeStr, presetTimes) {
        return presetTimes.indexOf(timeStr) >= 0;
    }

    function findNearestPresetTime(timeStr, presetTimes) {
        var time,
            minutesChecked = 0;

        time = moment(timeStr, 'HH:mm');

        function direction() {
            return (minutesChecked % 2) ? minutesChecked : -minutesChecked;
        }

        function seek(time) {
            var attemptTimeStr = time.format('HH:mm');

            if (isPresetTime(attemptTimeStr, presetTimes)) {
                return attemptTimeStr;
            }

            if (minutesChecked > MAX_MINUTES_CHECKED) {
                return;
            }

            minutesChecked += 1;

            time.add('minutes', direction());

            return seek(time);
        }

        return seek(time);
    }

    function TimePicker($input) {
        this.presetTimes = getPresetTimes(this.custom.interval);

        this.$input = $input;

        this.$picker = buildPicker({
            pickerClassName: this.custom.pickerClassName,
            presetTimes: this.presetTimes
        });

        this._preventClose = false;
        this._preventOpen = false;

        setupEvents(this);
    }

    TimePicker.prototype.isOpen = function() {
        return this.$picker.is(':visible');
    };

    TimePicker.prototype.open = function () {
        if(this._preventOpen || this.isOpen()) {
           return;
        }

        var inputPosition = this.$input.offset(),
            currentTime = this.$input.val();

        this.$picker
            .appendTo(this.custom.pickerContainer)
            .css({
                top: inputPosition.top + this.$input.outerHeight(),
                left: inputPosition.left
            })
            .show();

        if (isPresetTime(currentTime, this.presetTimes)) {
            this.select(currentTime, {silent: true});
        }
        scrollToShowTime(this, currentTime, this.presetTimes);

        this.trigger('onOpen');
    };

    TimePicker.prototype.findOptionByTime = function (time) {
        return this.$picker.find('[data-time="' + time + '"]');
    };

    TimePicker.prototype.close = function () {
        if (this._preventClose) {
            return;
        }
        this.$picker.hide();
    };

    TimePicker.prototype.select = function (time, options) {
        var $option = this.findOptionByTime(time),
            isSilent = (options || {}).silent === true;

        this.deselect();

        if (this.$input.val() !== time) {
            this.$input.val(time);
        }
        $option.addClass(this.custom.pickerSelectedClassName);

        this._preventOpen = true;

        if (!isSilent) {
            this.$input.trigger('change').trigger('focus');
            this.trigger('onSelect', time);
        }

        this._preventOpen = false;
    };

    TimePicker.prototype.reset = function () {
        this.deselect();
    };

    TimePicker.prototype.destroy = function () {
        this.$picker.remove();
        this.$input.off('.timepicker');
        this.$input.removeData('timepicker');
    };

    TimePicker.prototype.deselect = function () {
        this.$picker.find('li').removeClass(this.custom.pickerSelectedClassName);
    };

    function scrollToShowTime(picker, time, presetTimes) {
        var timePickerHeight,
            itemHeight,
            idealPosition,
            selectedTimePosition,
            scrollAdjustment = 0,
            needsAdjustment,
            nearestPresetTime,
            $selectedTime;

        if (!time) {
            picker.$picker.scrollTop(scrollAdjustment);
            return;
        }

        nearestPresetTime = findNearestPresetTimeMemo(time, presetTimes);

        if (!nearestPresetTime) {
            picker.$picker.scrollTop(scrollAdjustment);
            return;
        }

        $selectedTime = picker.findOptionByTime(nearestPresetTime);

        timePickerHeight = picker.$picker.outerHeight();
        itemHeight = $selectedTime.outerHeight();
        selectedTimePosition = $selectedTime.index() * itemHeight;

        // ideally should be in the middle of the time picker
        idealPosition = timePickerHeight / 2 - itemHeight / 2;

        // only adjust if the selected item is outside the ideal position
        needsAdjustment = selectedTimePosition > idealPosition;

        if (needsAdjustment) {
            scrollAdjustment = Math.abs(selectedTimePosition - idealPosition);
        }

        picker.$picker.scrollTop(scrollAdjustment);
    }

    function isValidMethod(method) {
        if (PUBLIC_METHODS.indexOf(method) === -1) {
            throw new Error('Invalid timepicker method');
        }
        return true;
    }

    function isValidInterval(interval) {
        if (!TIME_REGEX.exec(interval)) {
            throw new Error('Invalid interval, must be a valid time');
        }
    }

    function isValidOptions(options) {
        if (options.interval) {
            isValidInterval(options.interval);
        }
        return true;
    }

    MicroEvent.mixin(TimePicker);

    function setupPlugin($inputs, options) {
        options = $.extend({}, $.timepicker.defaults, options);

        return $inputs.each(function () {
            var $input = $(this),
                instance,
                currentInstance = $input.data('timepicker');

            // destroy the existing time picker
            if (currentInstance) {
                currentInstance.destroy();
                currentInstance = undefined;
            }

            // extend prototype with customisable options
            $.extend(TimePicker.prototype, {
                custom: options
            });

            instance = new TimePicker($input);

            // store reference to timepicker instance on elements $.data
            $input.data('timepicker', instance);
        });
    }

    function runPluginMethod($inputs, method, args) {
        return $inputs.each(function () {
            var $input = $(this),
                timepicker;

            timepicker = $input.data('timepicker');
            timepicker[method].apply(timepicker, args);
        });
    }

    function isInstantiation(options) {
        return _.isObject(options) && isValidOptions(options);
    }

    function isMethodCall(options) {
        return _.isString(options) && isValidMethod(options);
    }

    $.fn.timepicker = function (value) {
        var options = value || {};

        if (isInstantiation(options)) {
            return setupPlugin(this, options);
        } else if (isMethodCall(options)) {
            return runPluginMethod(this, options, Array.prototype.slice.call(arguments, 1));
        } else {
            throw new Error('Invalid timepicker call');
        }
    };

    // static methods
    $.timepicker = {};

    // default options
    $.timepicker.defaults = {
        pickerContainer: 'body',
        pickerClassName: 'time-picker',
        pickerSelectedClassName: 'time-picker--selected',
        interval: '01:00'
    };

    // custom selector
    $.expr[':'].timepicker = function (elem) {
        return $(elem).data('timepicker') !== undefined;
    };

    return TimePicker;
});
<|endoftext|>


<commit_before>(function() {
  var http = require("http");
  var express = require("express");
  var logfmt = require("logfmt");
  var redditData = require("./rdata");
  var app = express();
  var default_settings = {limit:5};
  reddit = function() {
    function reddit(settings) {
      default_settings.limit = settings.limit || default_settings.limit;
      default_settings.next = settings.next;
    }
    reddit.prototype.get_feed = reddit.prototype.get;

    reddit.prototype.get = function(url, callback) {
      default_settings.what=url;
      url = ("http:") + "//" + "www." + "reddit." + "com" + "/r/" + url + "/.json";
      if (default_settings.limit) {
        url = url + "?limit=" + default_settings.limit;
      }
      if (default_settings.next) {
        url = url + "&after=" + default_settings.next;
      }
      if (typeof url === "undefined") {
        //this is impossible.
      }

      http.get(url, function(res) {
        var body = "";
        res.on("data", function(chunk) {
          body += chunk;
        });
        res.on("end", function() {
          if (res.statusCode == "200") {
            var resp = JSON.parse(body);
            if (typeof callback === "function") {
              if (resp && resp.data) {
                rdata = new redditData(resp.data);
                rdata.settings=default_settings;
                callback(undefined, rdata);
              }
            }
          } else {
            if (typeof callback === "function") {
              callback({message:"Undefined location"}, undefined);
            }
          }
        });
      }).on("error", function(e) {
        callback(e, undefined);
      });

    };
    return reddit;
  }();

  module.exports = reddit;
}).call(this);
<commit_msg>changes<commit_after>(function() {
  var http = require("http");
  var logfmt = require("logfmt");
  var redditData = require("./rdata");
  var rperm = require("./rperm");
  var default_settings = {limit:5};
  reddit = function() {
    function reddit(settings) {
      default_settings.limit = settings.limit || default_settings.limit;
      default_settings.next = settings.next;
    }
    reddit.prototype.get_feed = reddit.prototype.get;
    reddit.prototype.get = function(url, callback) {
      if (typeof url === "undefined") {
        callback && callback({message:"Undefined location"}, undefined);
      }
      default_settings.what = url;
      url = "http:" + "//" + "www." + "reddit." + "com" + "/r/" + url + "/.json";
      if (default_settings.limit) {
        url = url + "?limit=" + default_settings.limit;
      }
      if (default_settings.next) {
        url = url + "&after=" + default_settings.next;
      }
      http.get(url, function(res) {
        var body = "";
        res.on("data", function(chunk) {
          body += chunk;
        });
        res.on("end", function() {
          if (res.statusCode == "200") {
            var resp = JSON.parse(body);
            if (resp && resp.data) {
              resp.data.children.forEach(function(result) {
                result.data.permalink = new rperm("http://www.reddit.com" + result.data.permalink + ".json");
              });
              rdata = new redditData(resp.data);
              rdata.settings = default_settings;
              callback && callback(null, rdata);
            }
          } else {
            callback && callback({message:"Undefined location"}, null);
          }
        });
      }).on("error", function(e) {
        callback(e, null);
      });
    };
    return reddit;
  }();
  module.exports = reddit;
}).call(this);<|endoftext|>


<commit_before>'use strict';

var chalk = require('chalk');
var utils = require('middleware-utils');
var middleware = require('../middleware');
var toTemplate = require('to-template');

/**
 * Initialize default middleware
 */

module.exports = function middleware_(app) {
  app.onLoad(/./, utils.parallel([
    middleware.data,
    middleware.src,
    middleware.ext,
    logFile('onLoad'),
  ]), utils.error('onLoad'));

  app.preRender(/./, utils.series([
    middleware.engine(app),
  ]), utils.error('preRender'));

  app.onSrc(/./, logFile('onSrc', true));

  app.preCompile(/./, logFile('preCompile', true));
  app.preCompile(/./, function (file, next) {
    next();
  });

  app.preRender(/./, logFile('preRender', true));
  app.preRender(/./, function (file, next) {
    // console.log(file)
    next();
  });

  app.postRender(/./, logFile('postRender', true));
  app.postRender(/./, function (file, next) {
    next();
  });

  app.onDest(/./, logFile('onDest', true));
  // app.onDest(/./, utils.series([
  //   middleware.render(app)
  // ]));

  app.onLast(/./, logFile('onLast'));
  app.onLast(/./, function (file, next) {
    // console.log(toTemplate(file))
    next();
  });
};

function logFile(method, output) {
  return function(file, next) {
    if (!output) return next();
    console.log(chalk.yellow('//', method + ' ----------------'));
    console.log(chalk.bold('file.path:'), file.path);
    // console.log(chalk.cyan('file.data:'), file.data);
    // console.log(chalk.gray('file.opts:'), file.options);
    console.log(chalk.yellow('// end -----------------------'));
    console.log();
    next();
  }
}
<commit_msg>rendering middleware<commit_after>'use strict';

var chalk = require('chalk');
var utils = require('middleware-utils');
var toTemplate = require('to-template');
var middleware = require('../middleware');

/**
 * Initialize default middleware
 */

module.exports = function middleware_(app) {
  var render = middleware.render(app);

  app.onLoad(/./, utils.parallel([
    middleware.data,
    middleware.src,
    middleware.ext,
    logFile('onLoad'),
  ]), utils.error('onLoad'));

  app.preRender(/./, utils.series([
    middleware.engine(app),
  ]), utils.error('preRender'));

  app.onSrc(/./, logFile('onSrc', true));

  app.preCompile(/./, logFile('preCompile', true));
  app.preCompile(/./, function (file, next) {
    next();
  });

  app.preRender(/./, logFile('preRender', true));
  app.preRender(/./, function (file, next) {
    // console.log(file)
    next();
  });

  app.postRender(/./, logFile('postRender', true));
  app.postRender(/./, function (file, next) {
    next();
  });

  app.onDest(/./, logFile('onDest', true));
  app.onDest(/./, render);

  app.onLast(/./, logFile('onLast'));
  app.onLast(/./, function (file, next) {
    // console.log(toTemplate(file))
    next();
  });
};

function logFile(method, output) {
  return function(file, next) {
    if (!output) return next();
    console.log(chalk.yellow('//', method + ' ----------------'));
    console.log(chalk.bold('file.path:'), file.path);
    // console.log(chalk.cyan('file.data:'), file.data);
    // console.log(chalk.gray('file.opts:'), file.options);
    console.log(chalk.yellow('// end -----------------------'));
    console.log();
    next();
  }
}
<|endoftext|>


<commit_before>function trackDependencies(dependencies, result = '') {
  let first = dependencies.shift().replace(/"/g, '');
  let node = `digraph "${first}" { %nodes% }`;
  let prev = first;
  if (dependencies.length === 0) {
    return node.replace('%nodes%', '"' + first + '"');
  }
  let depAsString = '"{first}" -> "{dep}"';
  dependencies[0].forEach((elem) => {
    if (typeof elem !== 'string') {
      first = prev;
    }
    result += depAsString.replace('{first}', first).replace('{dep}', elem) + '; ';
    prev = elem;
  });
  return node.replace('%nodes%', result.slice(0, -1));
}

export default (dependencyObject) => {
  return trackDependencies(dependencyObject);
}
<commit_msg>First attempt to multi-level dependency<commit_after>function trackDependencies(dependencies, result = '') {
  let first = dependencies.shift().replace(/"/g, '');
  let node = `digraph "${first}" { %nodes% }`;
  let prev = first;
  if (dependencies.length === 0) {
    return node.replace('%nodes%', '"' + first + '"');
  }
  console.log(first, dependencies[0]);
  let depAsString = '"{first}" -> "{dep}"';
  dependencies[0].forEach((elem) => {
    if (typeof elem !== 'string') {
      first = prev;
    }
    result += depAsString.replace('{first}', first).replace('{dep}', elem) + '; ';
    prev = elem;
  });

  let dependantsPool = [].push(first);
  let i = 0;
  let depAsString = '"{first}" -> "{dep}"';
  result = '';
  while (i < dependencies.length) {
    let first = dependantsPool.pop();
    if (typeof dependencies[i] === 'string') {
      result += depAsString.replace('{first}', first).replace('{dep}', dependencies[i]) + '; ';
    }
    else {
      dependantsPool.push(first).push(dependencies[i]);
    }
  }

  return node.replace('%nodes%', result.slice(0, -1));
}

export default (dependencyObject) => {
  return trackDependencies(dependencyObject);
}
<|endoftext|>