<commit_before>(function () {
    'use strict';

    angular.module('admin')
        .component('scientillaAdminBackup', {
            templateUrl: 'partials/scientilla-admin-backup.html',
            controller: scientillaAdminBackup,
            controllerAs: 'vm',
            bindings: {}
        });

    scientillaAdminBackup.$inject = [
        'Restangular',
        'ModalService',
        'Notification'
    ];

    function scientillaAdminBackup(Restangular, ModalService, Notification) {
        const vm = this;
        vm.getDumps = getDumps;
        vm.toggleDump = toggleDump;
        vm.restoreBackup = restoreBackup;
        vm.makeBackup = makeBackup;

        vm.dumps = [];
        vm.loading = false;

        vm.$onInit = function () {
            loadDumps();
        };

        function getDumps() {
            return Restangular.one('backup', 'dumps').getList()
                .then(dumps =>
                    dumps.sort(function (a, b) {
                        if (a.filename > b.filename) return -1;
                        if (a.filename < b.filename) return 1;
                        return 0;
                    }));
        }

        function toggleDump(dumpFilename) {
            if (vm.loading)
                return;
            vm.dumpSelected = !vm.dumpSelected;
            vm.dumps.filter(d => d.selected && d.filename !== dumpFilename).forEach(d => d.selected = false);
            vm.dumpSelected = vm.dumps.find(d => d.filename === dumpFilename);
            if (vm.dumpSelected) {
                vm.dumpSelected.selected = !vm.dumpSelected.selected;
                if (!vm.dumpSelected.selected)
                    delete vm.dumpSelected;
            }
        }

        function restoreBackup() {
            ModalService
                .multipleChoiceConfirm('Restoring backup',
                    `Are you sure you want to restore the backup ${vm.dumpSelected.filename}?`,
                    ['Proceed'])
                .then(function (buttonIndex) {
                    switch (buttonIndex) {
                        case 0:
                            const postData = {filename: vm.dumpSelected.filename};
                            vm.loading = true;
                            return Restangular.one('backup', 'restore')
                                .customPOST(postData)
                                .then(e => {
                                    console.log(e);
                                    vm.loading = false;
                                    Notification.success('Backup correctly restored');
                                })
                                .catch(() => {
                                    Notification.error('An error happened');
                                    vm.loading = false;
                                });
                    }
                });
        }

        function makeBackup() {
            ModalService
                .multipleChoiceConfirm('Making backup',
                    `Are you sure you want to make a new backup?`,
                    ['Proceed'])
                .then(function (buttonIndex) {
                    switch (buttonIndex) {
                        case 0:
                            vm.loading = true;
                            return Restangular.one('backup', 'make')
                                .customPOST()
                                .then(res => {
                                    vm.loading = false;
                                    Notification.success(`Backup ${res.filename} correctly created`);
                                    loadDumps();
                                })
                                .catch(() => {
                                    Notification.error('An error happened');
                                    vm.loading = false;
                                });
                    }
                });
        }

        function loadDumps() {
            getDumps().then(dumps => {
                vm.dumps = dumps;
            });
        }

    }

})();<commit_msg>Removed console.log<commit_after>(function () {
    'use strict';

    angular.module('admin')
        .component('scientillaAdminBackup', {
            templateUrl: 'partials/scientilla-admin-backup.html',
            controller: scientillaAdminBackup,
            controllerAs: 'vm',
            bindings: {}
        });

    scientillaAdminBackup.$inject = [
        'Restangular',
        'ModalService',
        'Notification'
    ];

    function scientillaAdminBackup(Restangular, ModalService, Notification) {
        const vm = this;
        vm.getDumps = getDumps;
        vm.toggleDump = toggleDump;
        vm.restoreBackup = restoreBackup;
        vm.makeBackup = makeBackup;

        vm.dumps = [];
        vm.loading = false;

        vm.$onInit = function () {
            loadDumps();
        };

        function getDumps() {
            return Restangular.one('backup', 'dumps').getList()
                .then(dumps =>
                    dumps.sort(function (a, b) {
                        if (a.filename > b.filename) return -1;
                        if (a.filename < b.filename) return 1;
                        return 0;
                    }));
        }

        function toggleDump(dumpFilename) {
            if (vm.loading)
                return;
            vm.dumpSelected = !vm.dumpSelected;
            vm.dumps.filter(d => d.selected && d.filename !== dumpFilename).forEach(d => d.selected = false);
            vm.dumpSelected = vm.dumps.find(d => d.filename === dumpFilename);
            if (vm.dumpSelected) {
                vm.dumpSelected.selected = !vm.dumpSelected.selected;
                if (!vm.dumpSelected.selected)
                    delete vm.dumpSelected;
            }
        }

        function restoreBackup() {
            ModalService
                .multipleChoiceConfirm('Restoring backup',
                    `Are you sure you want to restore the backup ${vm.dumpSelected.filename}?`,
                    ['Proceed'])
                .then(function (buttonIndex) {
                    switch (buttonIndex) {
                        case 0:
                            const postData = {filename: vm.dumpSelected.filename};
                            vm.loading = true;
                            return Restangular.one('backup', 'restore')
                                .customPOST(postData)
                                .then(e => {
                                    vm.loading = false;
                                    Notification.success('Backup correctly restored');
                                })
                                .catch(() => {
                                    Notification.error('An error happened');
                                    vm.loading = false;
                                });
                    }
                });
        }

        function makeBackup() {
            ModalService
                .multipleChoiceConfirm('Making backup',
                    `Are you sure you want to make a new backup?`,
                    ['Proceed'])
                .then(function (buttonIndex) {
                    switch (buttonIndex) {
                        case 0:
                            vm.loading = true;
                            return Restangular.one('backup', 'make')
                                .customPOST()
                                .then(res => {
                                    vm.loading = false;
                                    Notification.success(`Backup ${res.filename} correctly created`);
                                    loadDumps();
                                })
                                .catch(() => {
                                    Notification.error('An error happened');
                                    vm.loading = false;
                                });
                    }
                });
        }

        function loadDumps() {
            getDumps().then(dumps => {
                vm.dumps = dumps;
            });
        }

    }

})();<|endoftext|>


<commit_before>var loaderUtils = require('loader-utils')
var assign = require('object-assign')
var parse = require('./parser')
var path = require('path')
var normalize = require('./normalize')
var genId = require('./gen-id')

// internal lib loaders
var selectorPath = normalize.lib('selector')
var templateLoaderPath = normalize.lib('template-loader')
var templateCompilerPath = normalize.lib('template-compiler')
var styleRewriterPath = normalize.lib('style-rewriter')

// dep loaders
var styleLoaderPath = normalize.dep('vue-style-loader')
var hotReloadAPIPath = normalize.dep('vue-hot-reload-api')

var hasBabel = true
try {
  require('babel-loader')
} catch (e) {
  hasBabel = false
}

var rewriterInjectRE = /\b(css(?:-loader)?(?:\?[^!]+)?)(?:!|$)/

var defaultLang = {
  template: 'html',
  styles: 'css',
  script: 'js'
}

module.exports = function (content) {
  this.cacheable()
  var isServer = this.options.target === 'node'
  var loaderContext = this
  var options = this.options.vue || {}
  var query = loaderUtils.parseQuery(this.query)
  var filePath = this.resourcePath
  var fileName = path.basename(filePath)
  var moduleId = 'data-v-' + genId(filePath)
  var styleRewriter = styleRewriterPath + '?id=' + moduleId

  var isProduction = this.minimize || process.env.NODE_ENV === 'production'

  var needCssSourceMap =
    !isProduction &&
    this.sourceMap &&
    options.cssSourceMap !== false

  var defaultLoaders = {
    html: templateCompilerPath + '?id=' + moduleId,
    css: styleLoaderPath + '!css-loader' + (needCssSourceMap ? '?sourceMap' : ''),
    js: hasBabel ? 'babel-loader' : ''
  }

  // check if there are custom loaders specified via
  // webpack config, otherwise use defaults
  var loaders = assign({}, defaultLoaders, options.loaders)

  function getRequire (type, part, index, scoped) {
    return 'require(' +
      getRequireString(type, part, index, scoped) +
    ')\n'
  }

  function getRequireString (type, part, index, scoped) {
    return loaderUtils.stringifyRequest(loaderContext,
      // disable all configuration loaders
      '!!' +
      // get loader string for pre-processors
      getLoaderString(type, part, scoped) +
      // select the corresponding part from the vue file
      getSelectorString(type, index || 0) +
      // the url to the actual vuefile
      filePath
    )
  }

  function getRequireForImport (type, impt, scoped) {
    return 'require(' +
      getRequireForImportString(type, impt, scoped) +
    ')\n'
  }

  function getRequireForImportString (type, impt, scoped) {
    return loaderUtils.stringifyRequest(loaderContext,
      '!!' +
      getLoaderString(type, impt, scoped) +
      impt.src
    )
  }

  function getLoaderString (type, part, scoped) {
    var lang = part.lang || defaultLang[type]
    var loader = loaders[lang]
    var rewriter = type === 'styles' ? styleRewriter + (scoped ? '&scoped=true!' : '!') : ''
    var injectString = (type === 'script' && query.inject) ? 'inject!' : ''
    if (loader !== undefined) {
      // inject rewriter before css/html loader for
      // extractTextPlugin use cases
      if (rewriterInjectRE.test(loader)) {
        loader = loader.replace(rewriterInjectRE, function (m, $1) {
          return ensureBang($1) + rewriter
        })
      } else {
        loader = ensureBang(loader) + rewriter
      }
      return injectString + ensureBang(loader)
    } else {
      // unknown lang, infer the loader to be used
      switch (type) {
        case 'template':
          return defaultLoaders.html + '!' + templateLoaderPath + '?raw&engine=' + lang + '!'
        case 'styles':
          return defaultLoaders.css + '!' + rewriter + lang + '!'
        case 'script':
          return injectString + lang + '!'
      }
    }
  }

  function getSelectorString (type, index) {
    return selectorPath +
      '?type=' + type +
      '&index=' + index + '!'
  }

  function ensureBang (loader) {
    if (loader.charAt(loader.length - 1) !== '!') {
      return loader + '!'
    } else {
      return loader
    }
  }

  var parts = parse(content, fileName, this.sourceMap)
  var hasScoped = parts.styles.some(function (s) { return s.scoped })
  var output = 'var __vue_exports__, __vue_options__\n'

  // add requires for styles
  if (!isServer && parts.styles.length) {
    output += '\n/* styles */\n'
    parts.styles.forEach(function (style, i) {
      output += style.src
        ? getRequireForImport('styles', style, style.scoped)
        : getRequire('styles', style, i, style.scoped)
    })
  }

  // add require for script
  var script = parts.script
  if (script) {
    output += '\n/* script */\n'
    output +=
      '__vue_exports__ = ' + (
        script.src
          ? getRequireForImport('script', script)
          : getRequire('script', script)
      )
  }

  var exports =
    '__vue_options__ = __vue_exports__ || {}\n' +
    // ES6 modules interop
    'if (__vue_options__.__esModule) __vue_options__ = __vue_options__.default\n' +
    // constructor export interop
    'if (typeof __vue_options__ === "function") __vue_options__ = __vue_options__.options\n'

  // add require for template
  var template = parts.template
  if (template) {
    output += '\n/* template */\n'
    output += 'var __vue_template__ = ' + (
      template.src
        ? getRequireForImport('template', template)
        : getRequire('template', template)
    )
    // attach render functions to exported options
    exports +=
      '__vue_options__.render = __vue_template__.render\n' +
      '__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n'
    // attach scoped id
    if (hasScoped) {
      exports += '__vue_options__._scopeId = "' + moduleId + '"\n'
    }
  }

  if (!query.inject) {
    output += exports
    // hot reload
    if (
      !isServer &&
      !isProduction &&
      (parts.script || parts.template)
    ) {
      output +=
        '\n/* hot reload */\n' +
        'if (module.hot) {(function () {\n' +
        '  var hotAPI = require("' + hotReloadAPIPath + '")\n' +
        '  hotAPI.install(require("vue"), false)\n' +
        '  if (!hotAPI.compatible) return\n' +
        '  module.hot.accept()\n' +
        '  if (!module.hot.data) {\n' +
        // initial insert
        '    hotAPI.createRecord("' + moduleId + '", __vue_options__)\n' +
        '  } else {\n' +
        // update
        '    hotAPI.reload("' + moduleId + '", __vue_options__)\n' +
        '  }\n' +
        '})()}\n'
    }
    // check functional
    if (!isProduction) {
      output +=
        'if (__vue_options__.functional) {console.error("' +
          '[vue-loader] ' + fileName + ': functional components are not ' +
          'supported and should be defined in plain js files using render ' +
          'functions.' +
        '")}\n'
    }
    // final export
    output += '\nmodule.exports = __vue_exports__ || __vue_options__\n'
  } else {
    // inject-loader support
    output +=
      '\n/* dependency injection */\n' +
      'module.exports = function (injections) {\n' +
      '  __vue_exports__ = __vue_exports__(injections)\n' +
      exports +
      '  return __vue_exports__ || __vue_options__\n' +
      '}'
  }

  // done
  return output
}
<commit_msg>add scopeId as long as there is scoped CSS<commit_after>var loaderUtils = require('loader-utils')
var assign = require('object-assign')
var parse = require('./parser')
var path = require('path')
var normalize = require('./normalize')
var genId = require('./gen-id')

// internal lib loaders
var selectorPath = normalize.lib('selector')
var templateLoaderPath = normalize.lib('template-loader')
var templateCompilerPath = normalize.lib('template-compiler')
var styleRewriterPath = normalize.lib('style-rewriter')

// dep loaders
var styleLoaderPath = normalize.dep('vue-style-loader')
var hotReloadAPIPath = normalize.dep('vue-hot-reload-api')

var hasBabel = true
try {
  require('babel-loader')
} catch (e) {
  hasBabel = false
}

var rewriterInjectRE = /\b(css(?:-loader)?(?:\?[^!]+)?)(?:!|$)/

var defaultLang = {
  template: 'html',
  styles: 'css',
  script: 'js'
}

module.exports = function (content) {
  this.cacheable()
  var isServer = this.options.target === 'node'
  var loaderContext = this
  var options = this.options.vue || {}
  var query = loaderUtils.parseQuery(this.query)
  var filePath = this.resourcePath
  var fileName = path.basename(filePath)
  var moduleId = 'data-v-' + genId(filePath)
  var styleRewriter = styleRewriterPath + '?id=' + moduleId

  var isProduction = this.minimize || process.env.NODE_ENV === 'production'

  var needCssSourceMap =
    !isProduction &&
    this.sourceMap &&
    options.cssSourceMap !== false

  var defaultLoaders = {
    html: templateCompilerPath + '?id=' + moduleId,
    css: styleLoaderPath + '!css-loader' + (needCssSourceMap ? '?sourceMap' : ''),
    js: hasBabel ? 'babel-loader' : ''
  }

  // check if there are custom loaders specified via
  // webpack config, otherwise use defaults
  var loaders = assign({}, defaultLoaders, options.loaders)

  function getRequire (type, part, index, scoped) {
    return 'require(' +
      getRequireString(type, part, index, scoped) +
    ')\n'
  }

  function getRequireString (type, part, index, scoped) {
    return loaderUtils.stringifyRequest(loaderContext,
      // disable all configuration loaders
      '!!' +
      // get loader string for pre-processors
      getLoaderString(type, part, scoped) +
      // select the corresponding part from the vue file
      getSelectorString(type, index || 0) +
      // the url to the actual vuefile
      filePath
    )
  }

  function getRequireForImport (type, impt, scoped) {
    return 'require(' +
      getRequireForImportString(type, impt, scoped) +
    ')\n'
  }

  function getRequireForImportString (type, impt, scoped) {
    return loaderUtils.stringifyRequest(loaderContext,
      '!!' +
      getLoaderString(type, impt, scoped) +
      impt.src
    )
  }

  function getLoaderString (type, part, scoped) {
    var lang = part.lang || defaultLang[type]
    var loader = loaders[lang]
    var rewriter = type === 'styles' ? styleRewriter + (scoped ? '&scoped=true!' : '!') : ''
    var injectString = (type === 'script' && query.inject) ? 'inject!' : ''
    if (loader !== undefined) {
      // inject rewriter before css/html loader for
      // extractTextPlugin use cases
      if (rewriterInjectRE.test(loader)) {
        loader = loader.replace(rewriterInjectRE, function (m, $1) {
          return ensureBang($1) + rewriter
        })
      } else {
        loader = ensureBang(loader) + rewriter
      }
      return injectString + ensureBang(loader)
    } else {
      // unknown lang, infer the loader to be used
      switch (type) {
        case 'template':
          return defaultLoaders.html + '!' + templateLoaderPath + '?raw&engine=' + lang + '!'
        case 'styles':
          return defaultLoaders.css + '!' + rewriter + lang + '!'
        case 'script':
          return injectString + lang + '!'
      }
    }
  }

  function getSelectorString (type, index) {
    return selectorPath +
      '?type=' + type +
      '&index=' + index + '!'
  }

  function ensureBang (loader) {
    if (loader.charAt(loader.length - 1) !== '!') {
      return loader + '!'
    } else {
      return loader
    }
  }

  var parts = parse(content, fileName, this.sourceMap)
  var hasScoped = parts.styles.some(function (s) { return s.scoped })
  var output = 'var __vue_exports__, __vue_options__\n'

  // add requires for styles
  if (!isServer && parts.styles.length) {
    output += '\n/* styles */\n'
    parts.styles.forEach(function (style, i) {
      output += style.src
        ? getRequireForImport('styles', style, style.scoped)
        : getRequire('styles', style, i, style.scoped)
    })
  }

  // add require for script
  var script = parts.script
  if (script) {
    output += '\n/* script */\n'
    output +=
      '__vue_exports__ = ' + (
        script.src
          ? getRequireForImport('script', script)
          : getRequire('script', script)
      )
  }

  var exports =
    '__vue_options__ = __vue_exports__ || {}\n' +
    // ES6 modules interop
    'if (__vue_options__.__esModule) __vue_options__ = __vue_options__.default\n' +
    // constructor export interop
    'if (typeof __vue_options__ === "function") __vue_options__ = __vue_options__.options\n'

  // add require for template
  var template = parts.template
  if (template) {
    output += '\n/* template */\n'
    output += 'var __vue_template__ = ' + (
      template.src
        ? getRequireForImport('template', template)
        : getRequire('template', template)
    )
    // attach render functions to exported options
    exports +=
      '__vue_options__.render = __vue_template__.render\n' +
      '__vue_options__.staticRenderFns = __vue_template__.staticRenderFns\n'
  }

  // attach scoped id
  if (hasScoped) {
    exports += '__vue_options__._scopeId = "' + moduleId + '"\n'
  }

  if (!query.inject) {
    output += exports
    // hot reload
    if (
      !isServer &&
      !isProduction &&
      (parts.script || parts.template)
    ) {
      output +=
        '\n/* hot reload */\n' +
        'if (module.hot) {(function () {\n' +
        '  var hotAPI = require("' + hotReloadAPIPath + '")\n' +
        '  hotAPI.install(require("vue"), false)\n' +
        '  if (!hotAPI.compatible) return\n' +
        '  module.hot.accept()\n' +
        '  if (!module.hot.data) {\n' +
        // initial insert
        '    hotAPI.createRecord("' + moduleId + '", __vue_options__)\n' +
        '  } else {\n' +
        // update
        '    hotAPI.reload("' + moduleId + '", __vue_options__)\n' +
        '  }\n' +
        '})()}\n'
    }
    // check functional
    if (!isProduction) {
      output +=
        'if (__vue_options__.functional) {console.error("' +
          '[vue-loader] ' + fileName + ': functional components are not ' +
          'supported and should be defined in plain js files using render ' +
          'functions.' +
        '")}\n'
    }
    // final export
    output += '\nmodule.exports = __vue_exports__ || __vue_options__\n'
  } else {
    // inject-loader support
    output +=
      '\n/* dependency injection */\n' +
      'module.exports = function (injections) {\n' +
      '  __vue_exports__ = __vue_exports__(injections)\n' +
      exports +
      '  return __vue_exports__ || __vue_options__\n' +
      '}'
  }

  // done
  return output
}
<|endoftext|>


<commit_before>var margin = {top: 20, right: 20, bottom: 30, left: 60},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var formatPercent = d3.format(".0%");

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .2);

var y = d3.scale.linear()
    .domain([105000, 140000])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10);

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "Invånare: " + d.frequency + "";
  })

var svg = d3.select("#graph1").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.call(tip);

d3.tsv("data.tsv", type, function(error, data) {
  x.domain(data.map(function(d) { return d.letter; }));
  y.domain([105000, 140000]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(0)")
      .attr("y", -12)
        .attr("x", 8)
        .attr("font-size", 11)
        .attr("font-family", "ROBOTO")
      .attr("dy", "0")
      .style("text-anchor", "start")
      .text("Population");

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.letter); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.frequency); })
      .attr("height", function(d) { return height - y(d.frequency); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide)

});

function type(d) {
  d.frequency = +d.frequency;
  return d;
}<commit_msg>94<commit_after>var margin = {top: 20, right: 20, bottom: 30, left: 60},
    width = 900 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

var formatPercent = d3.format(".0%");

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .2);

var y = d3.scale.linear()
    .domain([105000, 140000])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10);

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "Invånare: " + d.frequency + "";
  })

var svg = d3.select("#graph1").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.call(tip);

d3.tsv("data.tsv", type, function(error, data) {
  x.domain(data.map(function(d) { return d.letter; }));
  y.domain([105000, 140000]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(0)")
      .attr("y", -12)
        .attr("x", 8)
        .attr("font-size", 11)
        .attr("font-family", "ROBOTO")
      .attr("dy", "0")
      .style("text-anchor", "start")
      .text("Population");

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.letter); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.frequency); })
      .attr("height", function(d) { return height - y(d.frequency); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide)

});

function type(d) {
  d.frequency = +d.frequency;
  return d;
}<|endoftext|>


<commit_before>/**
 * @ngdoc directive
 * @memberof ngmap
 * @name custom-marker
 * @param Attr2Options {service} convert html attribute to Gogole map api options
 * @param $timeout {service} AngularJS $timeout
 * @description
 *   Marker with html
 *   Requires:  map directive
 *   Restrict To:  Element
 *
 * @attr {String} position required, position on map
 * @attr {Number} z-index optional
 * @attr {Boolean} visible optional
 * @example
 *
 * Example:
 *   <map center="41.850033,-87.6500523" zoom="3">
 *     <custom-marker position="41.850033,-87.6500523">
 *

 *         Home
 *

 *     </custom-marker>
 *   </map>
 *
 */
/* global document */
(function() {
  'use strict';
  var parser, $timeout, $compile, NgMap;

  var CustomMarker = function(options) {
    options = options || {};

    this.el = document.createElement('div');
    this.el.style.display = 'inline-block';
    this.el.style.visibility = "hidden";
    this.visible = true;
    for (var key in options) { /* jshint ignore:line */
     this[key] = options[key];
    }
  };

  var setCustomMarker = function() {

    CustomMarker.prototype = new google.maps.OverlayView();

    CustomMarker.prototype.setContent = function(html, scope) {
      this.el.innerHTML = html;
      this.el.style.position = 'absolute';
      if (scope) {
        $compile(angular.element(this.el).contents())(scope);
      }
    };

    CustomMarker.prototype.getDraggable = function() {
      return this.draggable;
    };

    CustomMarker.prototype.setDraggable = function(draggable) {
      this.draggable = draggable;
    };

    CustomMarker.prototype.getPosition = function() {
      return this.position;
    };

    CustomMarker.prototype.setPosition = function(position) {
      position && (this.position = position); /* jshint ignore:line */
      var _this = this;
      if (this.getProjection() && typeof this.position.lng == 'function') {
        console.log(_this.getProjection());
        var setPosition = function() {
          var posPixel = _this.getProjection().fromLatLngToDivPixel(_this.position);
          var x = Math.round(posPixel.x - (_this.el.offsetWidth/2));
          var y = Math.round(posPixel.y - _this.el.offsetHeight - 10); // 10px for anchor
          _this.el.style.left = x + "px";
          _this.el.style.top = y + "px";
          _this.el.style.visibility = "visible";
        };
        if (_this.el.offsetWidth && _this.el.offsetHeight) {
          setPosition();
        } else {
          //delayed left/top calculation when width/height are not set instantly
          $timeout(setPosition, 300);
        }
      }
    };

    CustomMarker.prototype.setZIndex = function(zIndex) {
      zIndex && (this.zIndex = zIndex); /* jshint ignore:line */
      this.el.style.zIndex = this.zIndex;
    };

    CustomMarker.prototype.getVisible = function() {
      return this.visible;
    };

    CustomMarker.prototype.setVisible = function(visible) {
      this.el.style.display = visible ? 'inline-block' : 'none';
      this.visible = visible;
    };

    CustomMarker.prototype.addClass = function(className) {
      var classNames = this.el.className.trim().split(' ');
      (classNames.indexOf(className) == -1) && classNames.push(className); /* jshint ignore:line */
      this.el.className = classNames.join(' ');
    };

    CustomMarker.prototype.removeClass = function(className) {
      var classNames = this.el.className.split(' ');
      var index = classNames.indexOf(className);
      (index > -1) && classNames.splice(index, 1); /* jshint ignore:line */
      this.el.className = classNames.join(' ');
    };

    CustomMarker.prototype.onAdd = function() {
      this.getPanes().overlayMouseTarget.appendChild(this.el);
    };

    CustomMarker.prototype.draw = function() {
      this.setPosition();
      this.setZIndex(this.zIndex);
      this.setVisible(this.visible);
    };

    CustomMarker.prototype.onRemove = function() {
      this.el.parentNode.removeChild(this.el);
      //this.el = null;
    };
  };

  var linkFunc = function(orgHtml, varsToWatch) {
    //console.log('orgHtml', orgHtml, 'varsToWatch', varsToWatch);

    return function(scope, element, attrs, mapController) {
      mapController = mapController[0]||mapController[1];
      var orgAttrs = parser.orgAttributes(element);

      var filtered = parser.filter(attrs);
      var options = parser.getOptions(filtered, {scope: scope});
      var events = parser.getEvents(scope, filtered);

      /**
       * build a custom marker element
       */
      element[0].style.display = 'none';
      console.log("custom-marker options", options);
      var customMarker = new CustomMarker(options);

      $timeout(function() { //apply contents, class, and location after it is compiled

        scope.$watch('[' + varsToWatch.join(',') + ']', function() {
          customMarker.setContent(orgHtml, scope);
        }, true);

        customMarker.setContent(element[0].innerHTML, scope);
        var classNames = element[0].firstElementChild.className;
        customMarker.addClass('custom-marker');
        customMarker.addClass(classNames);
        console.log('customMarker', customMarker, 'classNames', classNames);

        if (!(options.position instanceof google.maps.LatLng)) {
          NgMap.getGeoLocation(options.position).then(
                function(latlng) {
                  customMarker.setPosition(latlng);
                }
          );
        }

      });

      console.log("custom-marker events", "events");
      for (var eventName in events) { /* jshint ignore:line */
        google.maps.event.addDomListener(
          customMarker.el, eventName, events[eventName]);
      }
      mapController.addObject('customMarkers', customMarker);

      //set observers
      mapController.observeAttrSetObj(orgAttrs, attrs, customMarker);

      element.bind('$destroy', function() {
        //Is it required to remove event listeners when DOM is removed?
        mapController.deleteObject('customMarkers', customMarker);
      });

    }; // linkFunc
  };

  var customMarkerDirective = function(
      _$timeout_, _$compile_, Attr2MapOptions, _NgMap_
    )  {
    parser = Attr2MapOptions;
    $timeout = _$timeout_;
    $compile = _$compile_;
    NgMap = _NgMap_;

    return {
      restrict: 'E',
      require: ['?^map','?^ngMap'],
      compile: function(element) {
        setCustomMarker();
        element[0].style.display ='none';
        var orgHtml = element.html();
        var matches = orgHtml.match(/{{([^}]+)}}/g);
        var varsToWatch = [];
        //filter out that contains '::', 'this.'
        (matches || []).forEach(function(match) {
          var toWatch = match.replace('{{','').replace('}}','');
          if (match.indexOf('::') == -1 &&
            match.indexOf('this.') == -1 &&
            varsToWatch.indexOf(toWatch) == -1) {
            varsToWatch.push(match.replace('{{','').replace('}}',''));
          }
        });

        return linkFunc(orgHtml, varsToWatch);
      }
    }; // return
  };// function
  customMarkerDirective.$inject =
    ['$timeout', '$compile', 'Attr2MapOptions', 'NgMap'];

  angular.module('ngMap').directive('customMarker', customMarkerDirective);
})();
<commit_msg>Custom Marker Directive - Return from setPosition if the getProjection() returns null.  -Solves issue where a marker clusterer removes markers from the map and getProjection().fromLatLnToPixel() throws a TypeError<commit_after>/**
 * @ngdoc directive
 * @memberof ngmap
 * @name custom-marker
 * @param Attr2Options {service} convert html attribute to Gogole map api options
 * @param $timeout {service} AngularJS $timeout
 * @description
 *   Marker with html
 *   Requires:  map directive
 *   Restrict To:  Element
 *
 * @attr {String} position required, position on map
 * @attr {Number} z-index optional
 * @attr {Boolean} visible optional
 * @example
 *
 * Example:
 *   <map center="41.850033,-87.6500523" zoom="3">
 *     <custom-marker position="41.850033,-87.6500523">
 *

 *         Home
 *

 *     </custom-marker>
 *   </map>
 *
 */
/* global document */
(function() {
  'use strict';
  var parser, $timeout, $compile, NgMap;

  var CustomMarker = function(options) {
    options = options || {};

    this.el = document.createElement('div');
    this.el.style.display = 'inline-block';
    this.el.style.visibility = "hidden";
    this.visible = true;
    for (var key in options) { /* jshint ignore:line */
     this[key] = options[key];
    }
  };

  var setCustomMarker = function() {

    CustomMarker.prototype = new google.maps.OverlayView();

    CustomMarker.prototype.setContent = function(html, scope) {
      this.el.innerHTML = html;
      this.el.style.position = 'absolute';
      if (scope) {
        $compile(angular.element(this.el).contents())(scope);
      }
    };

    CustomMarker.prototype.getDraggable = function() {
      return this.draggable;
    };

    CustomMarker.prototype.setDraggable = function(draggable) {
      this.draggable = draggable;
    };

    CustomMarker.prototype.getPosition = function() {
      return this.position;
    };

    CustomMarker.prototype.setPosition = function(position) {
      position && (this.position = position); /* jshint ignore:line */
      var _this = this;
      if (this.getProjection() && typeof this.position.lng == 'function') {
        console.log(_this.getProjection());
        var setPosition = function() {
          if (!_this.getProjection()) { return; }
          var posPixel = _this.getProjection().fromLatLngToDivPixel(_this.position);
          var x = Math.round(posPixel.x - (_this.el.offsetWidth/2));
          var y = Math.round(posPixel.y - _this.el.offsetHeight - 10); // 10px for anchor
          _this.el.style.left = x + "px";
          _this.el.style.top = y + "px";
          _this.el.style.visibility = "visible";
        };
        if (_this.el.offsetWidth && _this.el.offsetHeight) {
          setPosition();
        } else {
          //delayed left/top calculation when width/height are not set instantly
          $timeout(setPosition, 300);
        }
      }
    };

    CustomMarker.prototype.setZIndex = function(zIndex) {
      zIndex && (this.zIndex = zIndex); /* jshint ignore:line */
      this.el.style.zIndex = this.zIndex;
    };

    CustomMarker.prototype.getVisible = function() {
      return this.visible;
    };

    CustomMarker.prototype.setVisible = function(visible) {
      this.el.style.display = visible ? 'inline-block' : 'none';
      this.visible = visible;
    };

    CustomMarker.prototype.addClass = function(className) {
      var classNames = this.el.className.trim().split(' ');
      (classNames.indexOf(className) == -1) && classNames.push(className); /* jshint ignore:line */
      this.el.className = classNames.join(' ');
    };

    CustomMarker.prototype.removeClass = function(className) {
      var classNames = this.el.className.split(' ');
      var index = classNames.indexOf(className);
      (index > -1) && classNames.splice(index, 1); /* jshint ignore:line */
      this.el.className = classNames.join(' ');
    };

    CustomMarker.prototype.onAdd = function() {
      this.getPanes().overlayMouseTarget.appendChild(this.el);
    };

    CustomMarker.prototype.draw = function() {
      this.setPosition();
      this.setZIndex(this.zIndex);
      this.setVisible(this.visible);
    };

    CustomMarker.prototype.onRemove = function() {
      this.el.parentNode.removeChild(this.el);
      //this.el = null;
    };
  };

  var linkFunc = function(orgHtml, varsToWatch) {
    //console.log('orgHtml', orgHtml, 'varsToWatch', varsToWatch);

    return function(scope, element, attrs, mapController) {
      mapController = mapController[0]||mapController[1];
      var orgAttrs = parser.orgAttributes(element);

      var filtered = parser.filter(attrs);
      var options = parser.getOptions(filtered, {scope: scope});
      var events = parser.getEvents(scope, filtered);

      /**
       * build a custom marker element
       */
      element[0].style.display = 'none';
      console.log("custom-marker options", options);
      var customMarker = new CustomMarker(options);

      $timeout(function() { //apply contents, class, and location after it is compiled

        scope.$watch('[' + varsToWatch.join(',') + ']', function() {
          customMarker.setContent(orgHtml, scope);
        }, true);

        customMarker.setContent(element[0].innerHTML, scope);
        var classNames = element[0].firstElementChild.className;
        customMarker.addClass('custom-marker');
        customMarker.addClass(classNames);
        console.log('customMarker', customMarker, 'classNames', classNames);

        if (!(options.position instanceof google.maps.LatLng)) {
          NgMap.getGeoLocation(options.position).then(
                function(latlng) {
                  customMarker.setPosition(latlng);
                }
          );
        }

      });

      console.log("custom-marker events", "events");
      for (var eventName in events) { /* jshint ignore:line */
        google.maps.event.addDomListener(
          customMarker.el, eventName, events[eventName]);
      }
      mapController.addObject('customMarkers', customMarker);

      //set observers
      mapController.observeAttrSetObj(orgAttrs, attrs, customMarker);

      element.bind('$destroy', function() {
        //Is it required to remove event listeners when DOM is removed?
        mapController.deleteObject('customMarkers', customMarker);
      });

    }; // linkFunc
  };

  var customMarkerDirective = function(
      _$timeout_, _$compile_, Attr2MapOptions, _NgMap_
    )  {
    parser = Attr2MapOptions;
    $timeout = _$timeout_;
    $compile = _$compile_;
    NgMap = _NgMap_;

    return {
      restrict: 'E',
      require: ['?^map','?^ngMap'],
      compile: function(element) {
        setCustomMarker();
        element[0].style.display ='none';
        var orgHtml = element.html();
        var matches = orgHtml.match(/{{([^}]+)}}/g);
        var varsToWatch = [];
        //filter out that contains '::', 'this.'
        (matches || []).forEach(function(match) {
          var toWatch = match.replace('{{','').replace('}}','');
          if (match.indexOf('::') == -1 &&
            match.indexOf('this.') == -1 &&
            varsToWatch.indexOf(toWatch) == -1) {
            varsToWatch.push(match.replace('{{','').replace('}}',''));
          }
        });

        return linkFunc(orgHtml, varsToWatch);
      }
    }; // return
  };// function
  customMarkerDirective.$inject =
    ['$timeout', '$compile', 'Attr2MapOptions', 'NgMap'];

  angular.module('ngMap').directive('customMarker', customMarkerDirective);
})();
<|endoftext|>


<commit_before>var feature_flags = (function () {

var exports = {};

// Helpers
var internal_24_hour_people= _.contains([],
    page_params.email);

var zulip_mit_emails = [];
var is_zulip_mit_user = _.contains(zulip_mit_emails, page_params.email);

var iceland = page_params.domain === 'customer8.invalid';

var customer4_realms = [
  'customer4.invalid',
  'users.customer4.invalid'
];
var is_customer4 = _.contains(customer4_realms, page_params.domain);

// Enterprise-related flags
exports.do_not_share_the_love = page_params.enterprise;

// Manually-flipped debugging flags
exports.log_send_times = false;
exports.collect_send_times = false;

// Permanent realm-specific stuff:
exports.disable_message_editing = _.contains(['mit.edu'], page_params.domain);

exports.twenty_four_hour_time = internal_24_hour_people || iceland;

exports.dropbox_integration = page_params.staging || _.contains(['dropbox.com'], page_params.domain);

exports.mandatory_topics = _.contains([
    'customer7.invalid'
    ],
    page_params.domain
);

exports.left_side_userlist = page_params.staging || _.contains(['customer7.invalid'], page_params.domain);

// Still very beta:
exports.fade_users_when_composing = page_params.staging || is_customer4;
exports.use_socket = page_params.staging;

exports.clicking_notification_causes_narrow = page_params.staging || is_customer4 ||
    _.contains(['customer25.invalid', 'mit.edu', 'customer21.invalid'], page_params.domain);

exports.full_width = page_params.staging;

exports.show_digest_email_setting = page_params.staging;

// Still burning in...
exports.topic_zooming = true;
exports.mark_read_at_bottom = true;
exports.propagate_topic_edits = true;
exports.summarize_read_while_narrowed = false;

// Ready for deprecation.
exports.collapsible = false;

return exports;

}());
<commit_msg>Disable Dropbox integration feature flag for us.<commit_after>var feature_flags = (function () {

var exports = {};

// Helpers
var internal_24_hour_people= _.contains([],
    page_params.email);

var zulip_mit_emails = [];
var is_zulip_mit_user = _.contains(zulip_mit_emails, page_params.email);

var iceland = page_params.domain === 'customer8.invalid';

var customer4_realms = [
  'customer4.invalid',
  'users.customer4.invalid'
];
var is_customer4 = _.contains(customer4_realms, page_params.domain);

// Enterprise-related flags
exports.do_not_share_the_love = page_params.enterprise;

// Manually-flipped debugging flags
exports.log_send_times = false;
exports.collect_send_times = false;

// Permanent realm-specific stuff:
exports.disable_message_editing = _.contains(['mit.edu'], page_params.domain);

exports.twenty_four_hour_time = internal_24_hour_people || iceland;

exports.mandatory_topics = _.contains([
    'customer7.invalid'
    ],
    page_params.domain
);

exports.left_side_userlist = page_params.staging || _.contains(['customer7.invalid'], page_params.domain);

// Still very beta:
exports.fade_users_when_composing = page_params.staging || is_customer4;
exports.use_socket = page_params.staging;

exports.clicking_notification_causes_narrow = page_params.staging || is_customer4 ||
    _.contains(['customer25.invalid', 'mit.edu', 'customer21.invalid'], page_params.domain);

exports.full_width = page_params.staging;

exports.show_digest_email_setting = page_params.staging;

// Still burning in...
exports.topic_zooming = true;
exports.mark_read_at_bottom = true;
exports.propagate_topic_edits = true;
exports.summarize_read_while_narrowed = false;

// Ready for deprecation.
exports.collapsible = false;
exports.dropbox_integration = false;

return exports;

}());
<|endoftext|>


<commit_before>'use strict'

const mongoose = require('mongoose')
const config = require('./config')
const Schema = mongoose.Schema
const mongoosastic = require('../lib/mongoosastic')
const indexName = 'es-test'
const DummySchema = new Schema({
  text: String
})
const DummySchemaRefresh = new Schema({
  text: String
})
DummySchema.plugin(mongoosastic, {
  index: indexName,
  type: '_doc'
})
DummySchemaRefresh.plugin(mongoosastic, {
  index: indexName,
  type: '_doc',
  forceIndexRefresh: true
})
const Dummy = mongoose.model('Dummy', DummySchema)
const DummyRefresh = mongoose.model('DummyRefresh', DummySchemaRefresh)

describe('forceIndexRefresh connection option', function () {
  before(function (done) {
    // connect to mongodb
    mongoose.connect(config.mongoUrl, config.mongoOpts, function () {
      // delete the index from elasticsearch
      config.deleteIndexIfExists([indexName], function (err) {
        // recreate the index
        Dummy.createMapping({
          'analysis': {
            'analyzer': {
              'content': {
                'type': 'custom',
                'tokenizer': 'whitespace'
              }
            }
          }
        }, function (err, mapping) {
          // clean mongodb
          config.deleteDocs([Dummy, DummyRefresh], function () {
            setTimeout(done, config.INDEXING_TIMEOUT)
          })
        })
      })
    })
  })

  after(function (done) {
    config.deleteIndexIfExists([indexName], function (err) {
      config.deleteDocs([Dummy, DummyRefresh], function () {
        // disconnect mongodb
        mongoose.disconnect()
        // disconnect elasticsearch
        Dummy.esClient.close()
        DummyRefresh.esClient.close()
        done()
      })
    })
  })

  it('should always suceed: refresh the index immediately on insert', function (done) {
    const d = new DummyRefresh({text: 'Text1'})
    const refresh = true

    doInsertOperation(DummyRefresh, d, indexName, refresh, done)
  })

  it('should fail randomly: refresh the index every 1s on insert', function (done) {
    const d = new Dummy({text: 'Text1'})
    const refresh = false

    doInsertOperation(Dummy, d, indexName, refresh, done)
  })

  it('should always suceed: refresh the index immediately on update', function (done) {
    const d = new DummyRefresh({text: 'Text1'})
    const refresh = true

    doUpdateOperation(DummyRefresh, d, 'this is the new text', indexName, refresh, done)
  })

  it('should fail randomly: refresh the index every 1s on update', function (done) {
    const d = new Dummy({text: 'Text1'})
    const refresh = false

    doUpdateOperation(Dummy, d, 'this is the new text', indexName, refresh, done)
  })
})

function doInsertOperation (Model, object, indexName, refresh, callback) {
  // save object
  object.save(function (err, savedObject) {
    if (err) {
      return callback(err)
    }
    // wait for indexing
    savedObject.on('es-indexed', function (err) {
      if (err) {
        return callback(err)
      }
      // look for the object just saved
      Model.search({
        term: {_id: savedObject._id}
      },
      function (err, results) {
        if (refresh) {
          results.hits.total.should.eql(1)
        } else {
          results.hits.total.should.eql(0)
        }
        callback()
      })
    })
  })
}

function doUpdateOperation (Model, object, newText, indexName, refresh, callback) {
  // save object
  object.save(function (err, savedObject) {
    if (err) {
      return callback(err)
    }
    // update object
    Model
      .findOneAndUpdate({_id: savedObject._id}, {text: newText}, {'new': true})
      .exec(function (err, updatedObject) {
        if (err) {
          return callback(err)
        }
        // wait for indexing
        updatedObject.on('es-indexed', function (err) {
          if (err) {
            return callback(err)
          }
          // look for the object just saved
          Model.search({
            term: {_id: savedObject._id.toString()}
          },
          function (err, results) {
            if (refresh) {
              results.hits.total.should.eql(1)
              results.hits.hits[0]._source.text.should.eql(newText)
            } else {
              results.hits.total.should.eql(0)
            }
            callback()
          })
        })
      })
  })
}
<commit_msg>Update force-index-refresh-test.js<commit_after>'use strict'

const mongoose = require('mongoose')
const config = require('./config')
const Schema = mongoose.Schema
const mongoosastic = require('../lib/mongoosastic')
const indexName = 'es-test'
const DummySchema = new Schema({
  text: String
})
const DummySchemaRefresh = new Schema({
  text: String
})
DummySchema.plugin(mongoosastic, {
  index: indexName,
  type: '_doc'
})
DummySchemaRefresh.plugin(mongoosastic, {
  index: indexName,
  type: '_doc',
  forceIndexRefresh: true
})
const Dummy = mongoose.model('Dummy', DummySchema)
const DummyRefresh = mongoose.model('DummyRefresh', DummySchemaRefresh)

describe('forceIndexRefresh connection option', function () {
  before(function (done) {
    // connect to mongodb
    mongoose.connect(config.mongoUrl, config.mongoOpts, function () {
      // delete the index from elasticsearch
      config.deleteIndexIfExists([indexName], function (err) {
        // recreate the index
        Dummy.createMapping({
          'analysis': {
            'analyzer': {
              'content': {
                'type': 'custom',
                'tokenizer': 'whitespace'
              }
            }
          }
        }, function (err, mapping) {
          // clean mongodb
          config.deleteDocs([Dummy, DummyRefresh], function () {
            setTimeout(done, config.INDEXING_TIMEOUT)
          })
        })
      })
    })
  })

  after(function (done) {
    config.deleteIndexIfExists([indexName], function (err) {
      config.deleteDocs([Dummy, DummyRefresh], function () {
        // disconnect mongodb
        mongoose.disconnect()
        // disconnect elasticsearch
        Dummy.esClient.close()
        DummyRefresh.esClient.close()
        done()
      })
    })
  })

  it('should always suceed: refresh the index immediately on insert', function (done) {
    const d = new DummyRefresh({ text: 'Text1' })
    const refresh = true

    doInsertOperation(DummyRefresh, d, indexName, refresh, done)
  })

  it('should fail randomly: refresh the index every 1s on insert', function (done) {
    const d = new Dummy({ text: 'Text1' })
    const refresh = false

    doInsertOperation(Dummy, d, indexName, refresh, done)
  })

  it('should always suceed: refresh the index immediately on update', function (done) {
    const d = new DummyRefresh({ text: 'Text1' })
    const refresh = true

    doUpdateOperation(DummyRefresh, d, 'this is the new text', indexName, refresh, done)
  })

  it('should fail randomly: refresh the index every 1s on update', function (done) {
    const d = new Dummy({ text: 'Text1' })
    const refresh = false

    doUpdateOperation(Dummy, d, 'this is the new text', indexName, refresh, done)
  })
})

function doInsertOperation (Model, object, indexName, refresh, callback) {
  // save object
  object.save(function (err, savedObject) {
    if (err) {
      return callback(err)
    }
    // wait for indexing
    savedObject.on('es-indexed', function (err) {
      if (err) {
        return callback(err)
      }
      // look for the object just saved
      Model.search({
        term: { _id: savedObject._id }
      },
      function (err, results) {
        if (refresh) {
          results.hits.total.should.eql(1)
        } else {
          results.hits.total.should.eql(0)
        }
        callback()
      })
    })
  })
}

function doUpdateOperation (Model, object, newText, indexName, refresh, callback) {
  // save object
  object.save(function (err, savedObject) {
    if (err) {
      return callback(err)
    }
    // update object
    Model
      .findOneAndUpdate({ _id: savedObject._id }, { text: newText }, { 'new': true })
      .exec(function (err, updatedObject) {
        if (err) {
          return callback(err)
        }
        // wait for indexing
        updatedObject.on('es-indexed', function (err) {
          if (err) {
            return callback(err)
          }
          // look for the object just saved
          Model.search({
            term: { _id: savedObject._id.toString() }
          },
          function (err, results) {
            if (refresh) {
              results.hits.total.should.eql(1)
              results.hits.hits[0]._source.text.should.eql(newText)
            } else {
              results.hits.total.should.eql(0)
            }
            callback()
          })
        })
      })
  })
}
<|endoftext|>


<commit_before>/*global -$ */
'use strict';
// generated on 2015-06-05 using generator-gulp-webapp 0.3.0
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var del = require('del');
var mainBowerFiles = require('main-bower-files');
var exec = require('child_process').exec;
var fs = require('fs');
var semver = require('semver');
var autoprefixer = require('autoprefixer');
var pkg = (function () {
  return JSON.parse(fs.readFileSync('./package.json', 'utf8'));
})();

gulp.task('styles', function () {
  return gulp.src('app/styles/main.scss')
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      outputStyle: 'nested', // libsass doesn't support expanded yet
      precision: 10,
      includePaths: ['.'],
      onError: console.error.bind(console, 'Sass error:')
    }))
    .pipe($.postcss([
      autoprefixer({browsers: ['last 4 versions']})
    ]))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(reload({stream: true}));
});

gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

gulp.task('html', ['styles'], function () {
  var assets = $.useref.assets({searchPath: ['.tmp', 'app', '.']});

  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.if('*.html', $.htmlmin({conditionals: true, loose: true})))
    .pipe(gulp.dest('dist'));
});

gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true,
      // don't remove IDs from SVGs, they are often used
      // as hooks for embedding and styling
      svgoPlugins: [{cleanupIDs: false}]
    })))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', function () {
  return gulp.src(mainBowerFiles({
    filter: '**/*.{eot,svg,ttf,woff,woff2}',
    debugging: false
  }).concat('app/fonts/**/*'))
    .pipe(gulp.dest('.tmp/fonts'))
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    'app/CNAME',
    '!app/*.html'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

gulp.task('serve', ['styles', 'fonts'], function () {
  browserSync({
    notify: false,
    port: 10000,
    server: {
      baseDir: ['.tmp', 'app'],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  // watch for changes
  gulp.watch([
    'app/*.html',
    'app/scripts/**/*.js',
    'app/images/**/*',
    '.tmp/fonts/**/*'
  ]).on('change', reload);

  gulp.watch('app/styles/**/*.scss', ['styles']);
  gulp.watch('app/fonts/**/*', ['fonts']);
  gulp.watch('bower.json', ['wiredep', 'fonts']);
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;

  gulp.src('app/styles/*.scss')
    .pipe(wiredep({
      ignorePath: /^(\.\.\/)+/
    }))
    .pipe(gulp.dest('app/styles'));

  gulp.src('app/*.html')
    .pipe(wiredep({
      ignorePath: /^(\.\.\/)*\.\./
    }))
    .pipe(gulp.dest('app'));
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});

gulp.task('semverCommit', ['bump'], function () {

  exec('git commit app/manifest.json bower.json package.json -m "Update semver to v'+pkg.version+'"');
});

gulp.task('commitDist', ['build'], function () {

  exec('git add ./dist && git commit ./dist -m "Update dist folder to v'+pkg.version+'"');
});

gulp.task('gitPush', function () {

  exec('git push origin master', function(error, stdout, stderr) {

    $.util.log(stderr);
  });
});

// bump versions on package/bower/manifest
gulp.task('bump', function () {

  // increment version
  var newVer = semver.inc(pkg.version, 'patch');

  pkg.version = newVer;

  // uses gulp-filter
  var manifestFilter = $.filter(['**/manifest.json'], {restore: true});
  var regularJsons = $.filter(['*', '!manifest.json']);

  return gulp.src(['./bower.json', './package.json', './app/manifest.json'])
    .pipe($.bump({
      version: newVer
    }))
    .pipe(manifestFilter)
    .pipe(gulp.dest('./app'))
    .pipe(manifestFilter.restore)
    .pipe(regularJsons)
    .pipe(gulp.dest('./'));
});

gulp.task('upstream', ['commitDist'], function () {

  // return exec('git subtree push --prefix=dist --squash upstream master');

  var upstreamDelayed = function () {

    exec('git subtree push --prefix=dist upstream master', function(error, stdout, stderr){

      $.util.log(stderr);

      exec('git push origin master', function (error, stdout, stderr) {

        // $.util.log('Resetting ./dist temporary commit');
        // exec('git reset HEAD^');
      });
    })
  };

  setTimeout(upstreamDelayed, 1500);
});

gulp.task('deploy', ['clean', 'semverCommit'], function () {
  gulp.start('upstream');
});
;
<commit_msg>minor cleaning<commit_after>/*global -$ */
'use strict';
// generated on 2015-06-05 using generator-gulp-webapp 0.3.0
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var del = require('del');
var mainBowerFiles = require('main-bower-files');
var exec = require('child_process').exec;
var fs = require('fs');
var semver = require('semver');
var autoprefixer = require('autoprefixer');
var pkg = (function () {
  return JSON.parse(fs.readFileSync('./package.json', 'utf8'));
})();

gulp.task('styles', function () {
  return gulp.src('app/styles/main.scss')
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      outputStyle: 'nested', // libsass doesn't support expanded yet
      precision: 10,
      includePaths: ['.'],
      onError: console.error.bind(console, 'Sass error:')
    }))
    .pipe($.postcss([
      autoprefixer({browsers: ['last 4 versions']})
    ]))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(reload({stream: true}));
});

gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

gulp.task('html', ['styles'], function () {
  var assets = $.useref.assets({searchPath: ['.tmp', 'app', '.']});

  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.if('*.html', $.htmlmin({conditionals: true, loose: true})))
    .pipe(gulp.dest('dist'));
});

gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true,
      // don't remove IDs from SVGs, they are often used
      // as hooks for embedding and styling
      svgoPlugins: [{cleanupIDs: false}]
    })))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', function () {
  return gulp.src(mainBowerFiles({
    filter: '**/*.{eot,svg,ttf,woff,woff2}',
    debugging: false
  }).concat('app/fonts/**/*'))
    .pipe(gulp.dest('.tmp/fonts'))
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    'app/CNAME',
    '!app/*.html'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

gulp.task('serve', ['styles', 'fonts'], function () {
  browserSync({
    notify: false,
    port: 10000,
    server: {
      baseDir: ['.tmp', 'app'],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  // watch for changes
  gulp.watch([
    'app/*.html',
    'app/scripts/**/*.js',
    'app/images/**/*',
    '.tmp/fonts/**/*'
  ]).on('change', reload);

  gulp.watch('app/styles/**/*.scss', ['styles']);
  gulp.watch('app/fonts/**/*', ['fonts']);
  gulp.watch('bower.json', ['wiredep', 'fonts']);
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;

  gulp.src('app/styles/*.scss')
    .pipe(wiredep({
      ignorePath: /^(\.\.\/)+/
    }))
    .pipe(gulp.dest('app/styles'));

  gulp.src('app/*.html')
    .pipe(wiredep({
      ignorePath: /^(\.\.\/)*\.\./
    }))
    .pipe(gulp.dest('app'));
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});

gulp.task('semverCommit', ['bump'], function () {
  exec('git commit app/manifest.json bower.json package.json -m "Update semver to v'+pkg.version+'"');
});

gulp.task('commitDist', ['build'], function () {
  exec('git add ./dist && git commit ./dist -m "Update dist folder to v'+pkg.version+'"');
});

gulp.task('gitPush', function () {

  exec('git push origin master', function(error, stdout, stderr) {

    $.util.log(stderr);
  });
});

// bump versions on package/bower/manifest
gulp.task('bump', function () {

  // increment version
  var newVer = semver.inc(pkg.version, 'patch');

  pkg.version = newVer;

  // uses gulp-filter
  var manifestFilter = $.filter(['**/manifest.json'], {restore: true});
  var regularJsons = $.filter(['*', '!manifest.json']);

  return gulp.src(['./bower.json', './package.json', './app/manifest.json'])
    .pipe($.bump({
      version: newVer
    }))
    .pipe(manifestFilter)
    .pipe(gulp.dest('./app'))
    .pipe(manifestFilter.restore)
    .pipe(regularJsons)
    .pipe(gulp.dest('./'));
});

gulp.task('upstream', ['commitDist'], function () {

  var upstreamDelayed = function () {

    exec('git subtree push --prefix=dist upstream master', function(error, stdout, stderr){

      $.util.log(stderr);

      exec('git push origin master', function (error, stdout, stderr) {

        // $.util.log('Resetting ./dist temporary commit');
        // exec('git reset HEAD^');
      });
    })
  };

  setTimeout(upstreamDelayed, 1500);
});

gulp.task('deploy', ['clean', 'semverCommit'], function () {
  gulp.start('upstream');
});
;
<|endoftext|>


<commit_before> 'use strict';

 import {
     q
 }
 from '../controllers/queue.server.controller';
 import * as GameRoomManager from '../controllers/game_room_manager.server.controller';

 var setSocket = false;

 // Create the game socket.io configuration
 export default function(io, socket) {

     if (!setSocket) {
         setSocket = true;
         q.setIO(io);
     }

     console.log(socket.request.user.username, 'connected');
     GameRoomManager.ConnectedPlayers.set(socket.request.user.username, {
         in_queue: false,
         in_game: false,
         in_lobby: false,
         socket_id: socket.id
     });

     socket.on('join public game', function() {
         var ConnectedPlayer = GameRoomManager.ConnectedPlayers.get(socket.request.user.username);

         if (ConnectedPlayer.in_queue) {
            socket.emit('already in queue');
         } else if (ConnectedPlayer.in_game) {
            socket.emit('already in game');
         } else {
             q.addPlayer(socket);

             ConnectedPlayer.in_queue = true;
             GameRoomManager.ConnectedPlayers.set(socket.request.user.username, ConnectedPlayer);
         }
     });

    socket.on('join private lobby', function(msg) {
	   console.log('join private jobby');
	   console.log(msg);
	   //ADDING THE PLAYER ISNT WORKING I DONT KNOW WHY
	   GameRoomManager.getGameRoom(msg[0]).addPlayer(socket);
	   console.log('added player');
	   console.log(GameRoomManager.getGameRoom(msg[0]).players);
	   io.to(msg[1]).emit('joined private lobby');
	});

     socket.on('create private game', function() {
         var ConnectedPlayer = GameRoomManager.ConnectedPlayers.get(socket.request.user.username);
	 console.log('creating private game');
         if (ConnectedPlayer.in_queue) {
            socket.emit('already in queue');
	    //remove from queue?
         } else if (ConnectedPlayer.in_game) {
            socket.emit('already in game');
	    //remove from game?
         } else {
	     GameRoomManager.createGameRoom([socket], false);
	     ConnectedPlayer.in_game = true;
         }
     });

     socket.on('get all avaliable players', function(){
	 var avaliablePlayers = {};
	 GameRoomManager.ConnectedPlayers.forEach(function(val, key){if( !val.in_game && !val.in_queue){avaliablePlayers[key]=val;}});
	 console.log(avaliablePlayers);
	 socket.emit('avaliable players responding', avaliablePlayers);
     });

     socket.on('invite player', function(msg){
	 console.log(socket.game_room_id);
     var invite_socket_id = msg;
	 io.to(msg).emit('invite notification', [socket.game_room_id, socket.request.user.username, invite_socket_id]);
     });

     socket.on('get game info', function() {
	 console.log(socket.game_room_id);
         var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
	 console.log('1');
	 console.log(GameRoom);
	 console.log('2');
         socket.emit('game info responding', {
             _id: GameRoom._id,
             players: GameRoom.getPlayerUserNames(),
             waiting_players: GameRoom.getWaitingPlayerUserNames(),
             state: GameRoom.getStateName(),
             judge: GameRoom.getJudgeUserName(),
             phrases: GameRoom.getPhrases()
         });

         for (let username of GameRoom.getPlayerUserNames()) {
             var ConnectedPlayer = GameRoomManager.ConnectedPlayers.get(socket.request.user.username);
             ConnectedPlayer.in_queue = false;
             ConnectedPlayer.in_game = true;
             GameRoomManager.ConnectedPlayers.set(socket.request.user.username, ConnectedPlayer);
         }
     });

     socket.on('get lobby info', function(){
	  console.log('hellolobby');
	//THIS IS FAILING, HE ISNT PUT INTO THE GAME ROOM????
          var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
	  console.log(GameRoom);
          socket.emit('lobby info responding', {
	       _id: GameRoom._id,
	       players: GameRoom.getPlayerUserNames(),
	       state: GameRoom.getStateName()
          });
     });

     socket.on('set phrase', function(msg) {
         var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
         GameRoom.setPhrase(msg);
     });

     socket.on('set winner', function(msg) {
         var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
         GameRoom.setWinner(msg);
         GameRoom.setState('Ending');
     });

     socket.on('leave room', function() {
         if (socket.game_room_id) {
             var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
             GameRoom.removePlayer(socket);

             var ConnectedPlayer = GameRoomManager.ConnectedPlayers.get(socket.request.user.username);
             ConnectedPlayer.in_game = false;
             GameRoomManager.ConnectedPlayers.set(socket.request.user.username, ConnectedPlayer);
         }
     });

     socket.on('admin updates subscribe', function() {
         socket.join('admin_updates');
         socket.emit('initial queue info', q.getInfo());
         socket.emit('initial rooms info', GameRoomManager.getInfo());
     });

     socket.on('disconnect', function() {
         if (socket.request.user.username) {
             console.log(socket.request.user.username, 'has disconnected');
             if (socket.game_room_id) {
                 var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
                 GameRoom.removePlayer(socket);
             }

             GameRoomManager.ConnectedPlayers.delete(socket.request.user.username);
         }
     });
 }
<commit_msg>hello<commit_after> 'use strict';

 import {
     q
 }
 from '../controllers/queue.server.controller';
 import * as GameRoomManager from '../controllers/game_room_manager.server.controller';

 var setSocket = false;

 // Create the game socket.io configuration
 export default function(io, socket) {

     if (!setSocket) {
         setSocket = true;
         q.setIO(io);
     }

     console.log(socket.request.user.username, 'connected');
     GameRoomManager.ConnectedPlayers.set(socket.request.user.username, {
         in_queue: false,
         in_game: false,
         in_lobby: false,
         socket_id: socket.id
     });

     socket.on('join public game', function() {
         var ConnectedPlayer = GameRoomManager.ConnectedPlayers.get(socket.request.user.username);

         if (ConnectedPlayer.in_queue) {
            socket.emit('already in queue');
         } else if (ConnectedPlayer.in_game) {
            socket.emit('already in game');
         } else {
             q.addPlayer(socket);

             ConnectedPlayer.in_queue = true;
             GameRoomManager.ConnectedPlayers.set(socket.request.user.username, ConnectedPlayer);
         }
     });

    socket.on('join private lobby', function(msg) {
	   console.log('join private jobby');
	   console.log(msg);
	   //ADDING THE PLAYER ISNT WORKING I DONT KNOW WHY
	   GameRoomManager.getGameRoom(msg[0]).addPlayer(socket);
	   console.log('added player');
	   console.log(GameRoomManager.getGameRoom(msg[0]).players);
	   io.to(msg[1]).emit('joined private lobby');
	});

     socket.on('create private game', function() {
         var ConnectedPlayer = GameRoomManager.ConnectedPlayers.get(socket.request.user.username);
	 console.log('creating private game');
         if (ConnectedPlayer.in_queue) {
            socket.emit('already in queue');
	    //remove from queue?
         } else if (ConnectedPlayer.in_game) {
            socket.emit('already in game');
	    //remove from game?
         } else {
	     GameRoomManager.createGameRoom([socket], false);
	     ConnectedPlayer.in_game = true;
         }
     });

     socket.on('get all avaliable players', function(){
	 var avaliablePlayers = {};
	 GameRoomManager.ConnectedPlayers.forEach(function(val, key){if( !val.in_game && !val.in_queue){avaliablePlayers[key]=val;}});
	 console.log(avaliablePlayers);
	 socket.emit('avaliable players responding', avaliablePlayers);
     });

     socket.on('invite player', function(msg){
	 console.log(socket.game_room_id);
     var invite_socket_id = msg;
	 io.to(msg).emit('invite notification', [socket.game_room_id, socket.request.user.username, invite_socket_id]);
     });

     socket.on('get game info', function() {
	 console.log(socket.game_room_id);
         var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
	 console.log('1');
	 console.log(GameRoom);
	 console.log('2');
         socket.emit('game info responding', {
             _id: GameRoom._id,
             players: GameRoom.getPlayerUserNames(),
             waiting_players: GameRoom.getWaitingPlayerUserNames(),
             state: GameRoom.getStateName(),
             judge: GameRoom.getJudgeUserName(),
             phrases: GameRoom.getPhrases()
         });

         for (let username of GameRoom.getPlayerUserNames()) {
             var ConnectedPlayer = GameRoomManager.ConnectedPlayers.get(socket.request.user.username);
             ConnectedPlayer.in_queue = false;
             ConnectedPlayer.in_game = true;
             GameRoomManager.ConnectedPlayers.set(socket.request.user.username, ConnectedPlayer);
         }
     });

     socket.on('get lobby info', function(){
	  console.log('hellolobby');
      console.log(socket);
      console.log(socket.game_room_id);
	//THIS IS FAILING, HE ISNT PUT INTO THE GAME ROOM????
          var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
	  console.log(GameRoom);
          socket.emit('lobby info responding', {
	       _id: GameRoom._id,
	       players: GameRoom.getPlayerUserNames(),
	       state: GameRoom.getStateName()
          });
     });

     socket.on('set phrase', function(msg) {
         var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
         GameRoom.setPhrase(msg);
     });

     socket.on('set winner', function(msg) {
         var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
         GameRoom.setWinner(msg);
         GameRoom.setState('Ending');
     });

     socket.on('leave room', function() {
         if (socket.game_room_id) {
             var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
             GameRoom.removePlayer(socket);

             var ConnectedPlayer = GameRoomManager.ConnectedPlayers.get(socket.request.user.username);
             ConnectedPlayer.in_game = false;
             GameRoomManager.ConnectedPlayers.set(socket.request.user.username, ConnectedPlayer);
         }
     });

     socket.on('admin updates subscribe', function() {
         socket.join('admin_updates');
         socket.emit('initial queue info', q.getInfo());
         socket.emit('initial rooms info', GameRoomManager.getInfo());
     });

     socket.on('disconnect', function() {
         if (socket.request.user.username) {
             console.log(socket.request.user.username, 'has disconnected');
             if (socket.game_room_id) {
                 var GameRoom = GameRoomManager.getGameRoom(socket.game_room_id);
                 GameRoom.removePlayer(socket);
             }

             GameRoomManager.ConnectedPlayers.delete(socket.request.user.username);
         }
     });
 }
<|endoftext|>


<commit_before>// Shinryu Extreme
[{
  zoneRegex: /^The Minstrel's Ballad: Shinryu's Domain$/,
  triggers: [
    { regex: /starts using Akh Morn/,
      infoText: function(data) { return "Akh morn: Spread and move"; },
    },
    { regex: /Shinryu starts using Diamond Dust/,
      infoText: function(data) { return "Ice: Stack and Stop"; },
      run: function(data) { data.ice = true },
      condition: function(data) { return !data.ice },
    },
    { regex: /:Shinryu:....:Diamond Dust:/,
      run: function(data) { data.ice = false },
    },
    { regex: /starts using Dragonfist/,
      infoText: function(data) { return "Out of middle"; },
    },
    { regex: /starts using Earth Breath/,
      alertText: function(data) { return "Shakers"; },
    },
    { regex: /starts using Hellfire/,
      durationSeconds: 7,
      alertText: function(data) { return "Get in water"; },
      run: function(data) { data.hellfire = true },
      condition: function(data) { return !data.hellfire },
    },
    { regex: /:Shinryu:....:Hellfire:/,
      run: function(data) { data.hellfire = false },
    },
    { regex: /Wing starts using Hypernova/,  // Right Wing only?
      durationSeconds: 7,
      alertText: function(data) { return "Stack in water"; },
      //run: function(data) { data.water2 = true },
      //condition: function(data) { return !data.water2 },
    },
    //{ regex: /:Shinryu:....:Hypernova:/,
    //  run: function(data) { data.water2 = false },
    //},
    { regex: /Shinryu starts using Judgment Bolt/,
      durationSeconds: 7,
      alertText: function(data) { return "Stack, no water"; },
      run: function(data) { data.judgement = true },
      condition: function(data) { return !data.judgement },
    },
    { regex: /:Shinryu:....:Judgment Bolt:/,
      run: function(data) { data.judgement = false },
    },
    { regex: /starts using Levinbolt/,
      durationSeconds: 7,
      alertText: function(data) { return "Spread out, no water"; },
    },
    { regex: /Left Wing starts using Summon Icicle/,
      alarmText: function(data) { return "look back at icicles"; },
    },
    {
      regex: /Shinryu starts using Tidal Wave/,
      delaySeconds: 3,
      durationSeconds: 5,//7,
      infoText: function(data) { return "Knockback: look for water"; },
      condition: function(data) { var run = !data.water; data.water = true; return run; },
    },
    { regex: /:Shinryu:....:Tidal Wave:/,
      run: function(data) { data.water = false },
    },
    { regex: /starts using Tail Slap/,
      delaySeconds: 2,
      infoText: function(data) { return "Tail: Switch targets"; },
    },
    { regex: /:Added new combatant The Worm's Heart/,
      infoText: function(data) { return "Heart: Switch targets"; },
    },
  ]
}]
<commit_msg>Extra improved triggers<commit_after>// Shinryu Extreme
[{
  zoneRegex: /^The Minstrel's Ballad: Shinryu's Domain$/,
  triggers: [
    { id: 'ShinryuEx Akh Morn',
      regex: /:Shinryu starts using Akh Morn on (\y{Name})/,
      alertText: function(data, matches) {
        if (matches[1] == data.me)
          return 'Akh Morn on you';
        if (data.role == 'tank')
          return 'Akh Morn on ' + matches[1];
      },
      infoText: function(data, matches) {
        if (matches[1] == data.me || data.role == 'tank')
          return;
        return 'Akh Rhai: spread and move';
      },
    },
    { id: 'ShinryuEx Diamond Dust',
      regex: /:25DD:Shinryu starts using Diamond Dust/,
      infoText: function(data) { return 'Ice: Stack and Stop'; },
    },
    { id: 'ShinryuEx Dragonfist',
      regex: /:Shinryu starts using Dragonfist/,
      infoText: function(data) { return 'Out of middle'; },
    },
    { id: 'ShinryuEx Hellfire',
      regex: /:25DB:Shinryu starts using Hellfire/,
      durationSeconds: 7,
      alertText: function(data) { return 'Get in water'; },
    },
    { id: 'ShinryuEx Hypernova',
      regex: /:Right Wing starts using Hypernova/,
      durationSeconds: 7,
      alertText: function(data) { return 'Stack in water'; },
    },
    { id: 'ShinryuEx Judgement Bolt',
      regex: /:25DC:Shinryu starts using Judgment Bolt/,
      durationSeconds: 7,
      alertText: function(data) { return 'Stack, no water'; },
    },
    { id: 'ShinryuEx Levinbolt',
      regex: /:Right Wing starts using Levinbolt/,
      durationSeconds: 7,
      alertText: function(data) { return 'Spread out, no water'; },
    },
    { id: 'ShinryuEx Icicle',
      regex: /:Left Wing starts using Summon Icicle/,
      delaySeconds: 4,
      alarmText: function(data) { return 'look back at icicles'; },
    },
    { id: 'ShinryuEx Tidal Wave',
      regex: /:25DA:Shinryu starts using Tidal Wave/,
      delaySeconds: 3,
      durationSeconds: 5,
      infoText: function(data) { return 'Knockback: look for water'; },
    },
    { id: 'ShinryuEx Tail Slap',
      regex: /:Tail starts using Tail Slap/,
      delaySeconds: 2,
      infoText: function(data) { return 'Tail: Switch targets'; },
    },
    { id: 'ShinryuEx Heart',
      regex: /:Added new combatant The Worm's Heart/,
      infoText: function(data) { return 'Heart: Switch targets'; },
    },
    { id: 'ShinryuEx Divebomb',
      regex: /:Shinryu starts using Gyre Charge/,
      alarmText: function(data) { return 'move away from divebomb'; },
    },
    { id: 'ShinryuEx Tera Slash',
      regex: /:25DA:Shinryu starts using Tera Slash/,
      alarmText: function(data) {
        if (data.role == 'tank')
          return 'Tank Buster / Swap'; },
    },
    { id: 'ShinryuEx Tethers',
      regex: /1B:........:(\y{Name}):....:....:0061:0000:0000:0000:/,
      condition: function(data, matches) {
        return matches[1] == data.me;
      },
      delaySeconds: 3.8,
      infoText: function(data) {
        return 'break tethers';
      },
    },
    { id: 'ShinryuEx Tail Marker',
      regex: /1B:........:(\y{Name}):....:....:007E:0000:0000:0000:/,
      condition: function(data, matches) {
        return matches[1] == data.me;
      },
      alarmText: function(data) {
        return 'tail marker on you';
      },
    },
    { id: 'ShinryuEx Shakers',
      regex: /1B:........:(\y{Name}):....:....:0028:0000:0000:0000:/,
      condition: function(data, matches) {
        data.shakerTargets = data.shakerTargets || [];
        data.shakerTargets.push(matches[1]);
        return data.shakerTargets.length == 2;
      },
      alarmText: function(data) {
        if (data.shakerTargets.indexOf(data.me) >= 0)
          return 'earthshaker on you';
      },
      alertText: function(data) {
        if (data.shakerTargets.indexOf(data.me) == -1)
          return 'avoid earthshakers';
      },
      run: function(data) {
        delete data.shakerTargets;
      },
    },
  ]
}]
<|endoftext|>


<commit_before>$(document).ready(function(){
    var initialValue = 0;
    var counterDuration = 2;

    getCounter(function(newValue) {
        updateCounterAnimated(initialValue, newValue, counterDuration, updateCounter);

        // register timer to keep counter up to date
        setInterval(function() {
            getCounter(updateCounter);
        }, 5000);
    });

    function getCounter(callback) {
        var counterUrl = "https://bigdatauniversity.com/web/admin/counter.json.php";
        $.get(counterUrl, function(data) {
            if (data.ok) {
                callback(data.registered_users)
            }
        });
    }

    function updateCounter(newValue) {
        $("#counter").html(newValue.toLocaleString());
    }

    function updateCounterAnimated(currentValue, newValue, duration, callback) {
        var start = null;
        var d = duration;
        var b = currentValue;
        var c = newValue - currentValue;

        function step(timestamp) {
            if (!start) {
                start = timestamp +1;
            }

            var t = timestamp - start;
            var r = t/(d * 1000);
            var factor = Math.pow(r - 1, 5) + 1;

            var v = Math.max(Math.ceil(c * factor + b), 0);
            callback(Math.min(v, newValue));

            if (v < newValue) {
                window.requestAnimationFrame(step);
            }
        }

        window.requestAnimationFrame(step);
    }
});
<commit_msg>remove DDOS<commit_after>$(document).ready(function(){
    var initialValue = 0;
    var counterDuration = 2;

    getCounter(function(newValue) {
        updateCounterAnimated(initialValue, newValue, counterDuration, updateCounter);
    });

    function getCounter(callback) {
        var counterUrl = "https://bigdatauniversity.com/web/admin/counter.json.php";
        $.get(counterUrl, function(data) {
            if (data.ok) {
                callback(data.registered_users)
            }
        });
    }

    function updateCounter(newValue) {
        $("#counter").html(newValue.toLocaleString());
    }

    function updateCounterAnimated(currentValue, newValue, duration, callback) {
        var start = null;
        var d = duration;
        var b = currentValue;
        var c = newValue - currentValue;

        function step(timestamp) {
            if (!start) {
                start = timestamp +1;
            }

            var t = timestamp - start;
            var r = t/(d * 1000);
            var factor = Math.pow(r - 1, 5) + 1;

            var v = Math.max(Math.ceil(c * factor + b), 0);
            callback(Math.min(v, newValue));

            if (v < newValue) {
                window.requestAnimationFrame(step);
            }
        }

        window.requestAnimationFrame(step);
    }
});
<|endoftext|>


<commit_before><commit_msg>Added default route configuration in app.js<commit_after>angular.module("SpeedTyperSPA", [])
	.config(["$routeProvider", function ($routeProvider) {
	    $routeProvider
			.when("/",
			{
				templateUrl: "",
				controller: HomeController
			})
			.when("/rooms/",
			{
				templateUrl: "",
				controller: RoomsController
			})
			.otherwise(
			{
				redirectTo: "/" }
			);
	}]);
<|endoftext|>