<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    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/>.
 */
'use strict';

const Promise = require('bluebird');

function extend(target) {
  var sources = [].slice.call(arguments, 1);
  sources.forEach(function (source) {
    for (var prop in source) {
      target[prop] = source[prop];
    }
  });
  return target;
}

function getPreferredName(hostObject) {
  if (hostObject==null) {
    return null
  }

  if(hostObject.name) {
    return hostObject.name // always use user customized name first
  }

  return getPreferredBName(hostObject);
}

function getPreferredBName(hostObject) {

  if (hostObject==null) {
    return null;
  }

  if(hostObject.cloudName) {
    return hostObject.cloudName
  }

  if(hostObject.dhcpName) {
    return hostObject.dhcpName
  }

  if(hostObject.bonjourName) {
    return hostObject.bonjourName
  }

  if(hostObject.bname) {
    return hostObject.bname
  }

  if (hostObject.pname) {
    return hostObject.pname
  }
  if (hostObject.hostname) {
    return hostObject.hostname
  }
  if (hostObject.macVendor != null) {
    let name = hostObject.macVendor
    return name
  }
  return hostObject.ipv4Addr
}

function delay(t) {
  return new Promise(function(resolve) {
    setTimeout(resolve, t);
  });
}

module.exports = {
  extend:extend,
  getPreferredBName: getPreferredBName,
  getPreferredName: getPreferredName,
  delay: delay
}
<commit_msg>Enhancement: include spoofMeName when finalizing bname (#1618)<commit_after>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    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/>.
 */
'use strict';

const Promise = require('bluebird');

function extend(target) {
  var sources = [].slice.call(arguments, 1);
  sources.forEach(function (source) {
    for (var prop in source) {
      target[prop] = source[prop];
    }
  });
  return target;
}

function getPreferredName(hostObject) {
  if (hostObject==null) {
    return null
  }

  if(hostObject.name) {
    return hostObject.name // always use user customized name first
  }

  return getPreferredBName(hostObject);
}

function getPreferredBName(hostObject) {

  if (hostObject==null) {
    return null;
  }

  if(hostObject.cloudName) {
    return hostObject.cloudName
  }

  if(hostObject.spoofMeName) {
    return hostObject.spoofMeName
  }

  if(hostObject.dhcpName) {
    return hostObject.dhcpName
  }

  if(hostObject.bonjourName) {
    return hostObject.bonjourName
  }

  if(hostObject.bname) {
    return hostObject.bname
  }

  if (hostObject.pname) {
    return hostObject.pname
  }
  if (hostObject.hostname) {
    return hostObject.hostname
  }
  if (hostObject.macVendor != null) {
    let name = hostObject.macVendor
    return name
  }
  return hostObject.ipv4Addr
}

function delay(t) {
  return new Promise(function(resolve) {
    setTimeout(resolve, t);
  });
}

module.exports = {
  extend:extend,
  getPreferredBName: getPreferredBName,
  getPreferredName: getPreferredName,
  delay: delay
}
<|endoftext|>


<commit_before>'use strict'
const
  fs = require('fs'),
  path = require('path'),
  async = require('async'),
  GitStatistics = require('../classes/gitStatistics.js');

function Updater(pathToReposDir) {
  this.pathToReposDir = pathToReposDir;
}

Updater.prototype.statisticsSections = function(gitStatistics) {
  return [
    function(callback) {
      gitStatistics.updateRepo(function() {
        callback(null, null);
      });
    },
    function(callback) {
      gitStatistics.get10LatestCommits(function(latestCommits) {
        callback(null, { latestCommits: latestCommits });
      });
    },
    function(callback) {
      gitStatistics.getTop10Committers(function(top10Committers) {
        callback(null, { top10Committers: top10Committers });
      });
    },
    function(callback) {
      gitStatistics.getMostRecentTags(function(mostRecentTags) {
        callback(null, { mostRecentTags: mostRecentTags });
      });
    },
    function(callback) {
      gitStatistics.getMostRecentBranches(function(mostRecentBranches) {
        callback(null, { mostRecentBranches: mostRecentBranches });
      });
    }
  ]
};

Updater.prototype.updateData = function(done) {
  var self = this;
  var repos = this.getAllRepos();
  var gitStatisticsArray = new Array();

  repos.forEach(function(repoName) {
    gitStatisticsArray.push(new GitStatistics(path.join(self.pathToReposDir, repoName)));
  });

  async.map(gitStatisticsArray, function(gitStatistics, repoCallback) {
    async.series(
      self.statisticsSections(gitStatistics),
      function(err, results) {
        var repoData = {};
        repoData[path.basename(gitStatistics.repoPath)] = {};
        self.formatResults(repoData[path.basename(gitStatistics.repoPath)], results);

        repoCallback(null, repoData);
      }
    );
  }, function(err, results) {
    var data = {};
    data.repos = repos;
    self.formatResults(data, results);

    self.calculateCombinedStatistics(data, function(combinedStatistics) {
      self.formatResults(data, [combinedStatistics]);
      data.repos.push('all');
      done(data);
    });
  });
}

Updater.prototype.getAllRepos = function() {
  var self = this;
  var repos = new Array();
  var files = fs.readdirSync(this.pathToReposDir);
  files.forEach(function(file) {
    var repoPath = path.join(self.pathToReposDir, file);
    if(fs.lstatSync(repoPath).isDirectory()) {
      repos.push(file);
    }
  });

  return repos;
}

Updater.prototype.formatResults = function(data, results) {
  for (var i in results) {
    for (var c in results[i]) {
      data[c] = results[i][c];
    }
  }
}

Updater.prototype.calculateCombinedStatistics = function(data, callback) {
  var combinedStatistics = {};

  // latestCommits
  var allCommits = this.getCombinedStatisticsSection(data, 'latestCommits');
  allCommits.sort(function(a,b) { return new Date(a.date) - new Date(b.data) } );
  combinedStatistics.latestCommits = allCommits.slice(0, 10);

  // top10Committers
  var allCommitters = this.getCombinedStatisticsSection(data, 'top10Committers');
  allCommitters.sort(function(a,b) { return parseInt(b.numberOfCommits) - parseInt(a.numberOfCommits) } );
  combinedStatistics.top10Committers = allCommitters.slice(0, 10);

  // mostRecentTags
  var allTags = this.getCombinedStatisticsSection(data, 'mostRecentTags');
  allTags.sort(function(a,b) { return new Date(a.date) - new Date(b.data) } );
  combinedStatistics.mostRecentTags = allTags.slice(0, 5);

  // mostRecentBranches
  var allBranches = this.getCombinedStatisticsSection(data, 'mostRecentBranches');
  allBranches.sort(function(a,b) { return new Date(a.date) - new Date(b.data) } );
  combinedStatistics.mostRecentBranches = allBranches.slice(0, 5);

  callback({all: combinedStatistics});
}

Updater.prototype.getCombinedStatisticsSection = function(data, section) {
  var items = [];
  for(var i in data) {
    if(data[i] == 'repos') {
      continue;
    }

    for(var c in data[i][section]) {
      var item = JSON.parse(JSON.stringify(data[i][section][c]));
      item.repo = i;
      items.push(item);
    }
  }
  return items;
}

module.exports = Updater;<commit_msg>Using let instead of var<commit_after>'use strict'
const
  fs = require('fs'),
  path = require('path'),
  async = require('async'),
  GitStatistics = require('../classes/gitStatistics.js');

function Updater(pathToReposDir) {
  this.pathToReposDir = pathToReposDir;
}

Updater.prototype.statisticsSections = function(gitStatistics) {
  return [
    function(callback) {
      gitStatistics.updateRepo(function() {
        callback(null, null);
      });
    },
    function(callback) {
      gitStatistics.get10LatestCommits(function(latestCommits) {
        callback(null, { latestCommits: latestCommits });
      });
    },
    function(callback) {
      gitStatistics.getTop10Committers(function(top10Committers) {
        callback(null, { top10Committers: top10Committers });
      });
    },
    function(callback) {
      gitStatistics.getMostRecentTags(function(mostRecentTags) {
        callback(null, { mostRecentTags: mostRecentTags });
      });
    },
    function(callback) {
      gitStatistics.getMostRecentBranches(function(mostRecentBranches) {
        callback(null, { mostRecentBranches: mostRecentBranches });
      });
    }
  ]
};

Updater.prototype.updateData = function(done) {
  let self = this;
  let repos = this.getAllRepos();
  let gitStatisticsArray = new Array();

  repos.forEach(function(repoName) {
    gitStatisticsArray.push(new GitStatistics(path.join(self.pathToReposDir, repoName)));
  });

  async.map(gitStatisticsArray, function(gitStatistics, repoCallback) {
    async.series(
      self.statisticsSections(gitStatistics),
      function(err, results) {
        let repoData = {};
        repoData[path.basename(gitStatistics.repoPath)] = {};
        self.formatResults(repoData[path.basename(gitStatistics.repoPath)], results);

        repoCallback(null, repoData);
      }
    );
  }, function(err, results) {
    let data = {};
    data.repos = repos;
    self.formatResults(data, results);

    self.calculateCombinedStatistics(data, function(combinedStatistics) {
      self.formatResults(data, [combinedStatistics]);
      data.repos.push('all');
      done(data);
    });
  });
}

Updater.prototype.getAllRepos = function() {
  let self = this;
  let repos = new Array();
  let files = fs.readdirSync(this.pathToReposDir);
  files.forEach(function(file) {
    let repoPath = path.join(self.pathToReposDir, file);
    if(fs.lstatSync(repoPath).isDirectory()) {
      repos.push(file);
    }
  });

  return repos;
}

Updater.prototype.formatResults = function(data, results) {
  for (let i in results) {
    for (let c in results[i]) {
      data[c] = results[i][c];
    }
  }
}

Updater.prototype.calculateCombinedStatistics = function(data, callback) {
  let combinedStatistics = {};

  // latestCommits
  let allCommits = this.getCombinedStatisticsSection(data, 'latestCommits');
  allCommits.sort(function(a,b) { return new Date(a.date) - new Date(b.data) } );
  combinedStatistics.latestCommits = allCommits.slice(0, 10);

  // top10Committers
  let allCommitters = this.getCombinedStatisticsSection(data, 'top10Committers');
  allCommitters.sort(function(a,b) { return parseInt(b.numberOfCommits) - parseInt(a.numberOfCommits) } );
  combinedStatistics.top10Committers = allCommitters.slice(0, 10);

  // mostRecentTags
  let allTags = this.getCombinedStatisticsSection(data, 'mostRecentTags');
  allTags.sort(function(a,b) { return new Date(a.date) - new Date(b.data) } );
  combinedStatistics.mostRecentTags = allTags.slice(0, 5);

  // mostRecentBranches
  let allBranches = this.getCombinedStatisticsSection(data, 'mostRecentBranches');
  allBranches.sort(function(a,b) { return new Date(a.date) - new Date(b.data) } );
  combinedStatistics.mostRecentBranches = allBranches.slice(0, 5);

  callback({all: combinedStatistics});
}

Updater.prototype.getCombinedStatisticsSection = function(data, section) {
  let items = [];
  for(let i in data) {
    if(data[i] == 'repos') {
      continue;
    }

    for(let c in data[i][section]) {
      let item = JSON.parse(JSON.stringify(data[i][section][c]));
      item.repo = i;
      items.push(item);
    }
  }
  return items;
}

module.exports = Updater;<|endoftext|>


<commit_before>import React from 'react';
import { Trans } from '@lingui/macro';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';

import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import StatTracker from 'parser/shared/modules/StatTracker';
import SpellUsable from 'parser/shared/modules/SpellUsable';
import Events from 'parser/core/Events';

import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';

const COOLDOWN_REDUCTION_MS = 1500;

class CrusadersMight extends Analyzer {
  static dependencies = {
    spellUsable: SpellUsable,
    statTracker: StatTracker,
  };

  effectiveHolyShockReductionMs = 0;
  wastedHolyShockReductionMs = 0;
  wastedHolyShockReductionCount = 0;
  holyShocksCastsLost = 0;

  constructor(...args) {
    super(...args);
    this.active = this.selectedCombatant.hasTalent(SPELLS.CRUSADERS_MIGHT_TALENT.id);
    if (!this.active) {
      return;
    }
    this.addEventListener(
      Events.cast.by(SELECTED_PLAYER).spell(SPELLS.CRUSADER_STRIKE),
      this.onCast,
    );
  }

  onCast(event) {
    const holyShockisOnCooldown = this.spellUsable.isOnCooldown(SPELLS.HOLY_SHOCK_CAST.id);
    if (holyShockisOnCooldown) {
      const reductionMs = this.spellUsable.reduceCooldown(
        SPELLS.HOLY_SHOCK_CAST.id,
        COOLDOWN_REDUCTION_MS,
      );
      this.effectiveHolyShockReductionMs += reductionMs;
      this.wastedHolyShockReductionMs += COOLDOWN_REDUCTION_MS - reductionMs;
    } else {
      const holyShockCooldown =
        7500 / (1 + this.statTracker.hastePercentage(this.statTracker.currentHasteRating));
      if (
        this.selectedCombatant.hasTalent(SPELLS.SANCTIFIED_WRATH_TALENT.id) &&
        this.selectedCombatant.hasBuff(SPELLS.AVENGING_WRATH.id, event.timestamp)
      ) {
        this.holyShocksCastsLost += 1;
      } else {
        this.holyShocksCastsLost += COOLDOWN_REDUCTION_MS / holyShockCooldown;
      }
      this.wastedHolyShockReductionMs += COOLDOWN_REDUCTION_MS;
      this.wastedHolyShockReductionCount += 1;

      // mark the event on the timeline //
      event.meta = event.meta || {};
      event.meta.isInefficientCast = true;
      event.meta.inefficientCastReason = (
        <Trans>
          Holy Shock was off cooldown when you cast Crusader Strike. You should cast Holy Shock
          before Crusader Strike for maximum healing or damage.
        </Trans>
      );
    }
    // for glimmer if wings is up prioritize Holy Shock > Crusader Strike > Light of Dawn
    const wingsUp = this.selectedCombatant.hasBuff(SPELLS.AVENGING_WRATH.id, event.timestamp);
    if (this.owner.builds.GLIMMER.active && wingsUp && holyShockisOnCooldown) {
      return;
    }
  }

  get holyShocksMissedThresholds() {
    return {
      actual: this.wastedHolyShockReductionCount,
      isGreaterThan: {
        minor: 0,
        average: 2,
        major: 5,
      },
      style: 'number',
    };
  }

  suggestions(when) {
    if (this.owner.builds.GLIMMER.active) {
      when(this.holyShocksMissedThresholds).addSuggestion((suggest, actual, recommended) => suggest(
          <>
            You cast <SpellLink id={SPELLS.CRUSADER_STRIKE.id} />{' '}
            {this.wastedHolyShockReductionCount} times when
            <SpellLink id={SPELLS.HOLY_SHOCK_CAST.id} /> was off cooldown.{' '}
            <SpellLink id={SPELLS.CRUSADER_STRIKE.id} /> should be used to reduce the cooldown of
            <SpellLink id={SPELLS.HOLY_SHOCK_CAST.id} /> and should never be cast when{' '}
            <SpellLink id={SPELLS.HOLY_SHOCK_CAST.id} /> is avalible. This is a core component of
            the <SpellLink id={SPELLS.GLIMMER_OF_LIGHT.id} />{' '}

              build.

          </>,
        )
          .icon(SPELLS.HOLY_SHOCK_CAST.icon)
          .actual(
            `${Math.floor(this.holyShocksCastsLost)} Holy Shock cast${
              Math.floor(this.holyShocksCastsLost) === 1 ? '' : 's'
            } missed.`,
          )
          .recommended(`Casting Holy Shock on cooldown is recommended.`));
    }
  }

  statistic() {
    const formatSeconds = seconds => <Trans>{seconds}s</Trans>;

    return (
      <StatisticBox
        position={STATISTIC_ORDER.OPTIONAL(75)}
        icon={<SpellIcon id={SPELLS.CRUSADERS_MIGHT_TALENT.id} />}
        value={
          <>
            {formatSeconds((this.effectiveHolyShockReductionMs / 1000).toFixed(1))}{' '}
            <SpellIcon
              id={SPELLS.HOLY_SHOCK_CAST.id}
              style={{
                height: '1.3em',
                marginTop: '-.1em',
              }}
            />{' '}
          </>
        }
        label={<Trans>Cooldown reduction</Trans>}
        tooltip={
          <>
            You cast Crusader Strike {this.wastedHolyShockReductionCount} time
            {this.wastedHolyShockReductionCount === 1 ? '' : 's'} when Holy Shock was off cooldown.

            This wasted {(this.wastedHolyShockReductionMs / 1000).toFixed(1)} seconds of Holy
            Shock cooldown reduction,

            preventing you from {Math.floor(this.holyShocksCastsLost)} additional Holy Shock
            cast
            {this.holyShocksLost === 1 ? '' : 's'}.

            {this.wastedLightOfDawnReductionCount === 1 ? '' : 's'} when Light of Dawn
            {this.owner.builds.GLIMMER.active ? ' and Holy Shock were' : ' was'} off cooldown.
          </>
        }
      />
    );
  }
}

export default CrusadersMight;
<commit_msg>removed more un-needed code<commit_after>import React from 'react';
import { Trans } from '@lingui/macro';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';

import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import StatTracker from 'parser/shared/modules/StatTracker';
import SpellUsable from 'parser/shared/modules/SpellUsable';
import Events from 'parser/core/Events';

import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';

const COOLDOWN_REDUCTION_MS = 1500;

class CrusadersMight extends Analyzer {
  static dependencies = {
    spellUsable: SpellUsable,
    statTracker: StatTracker,
  };

  effectiveHolyShockReductionMs = 0;
  wastedHolyShockReductionMs = 0;
  wastedHolyShockReductionCount = 0;
  holyShocksCastsLost = 0;

  constructor(...args) {
    super(...args);
    this.active = this.selectedCombatant.hasTalent(SPELLS.CRUSADERS_MIGHT_TALENT.id);
    if (!this.active) {
      return;
    }
    this.addEventListener(
      Events.cast.by(SELECTED_PLAYER).spell(SPELLS.CRUSADER_STRIKE),
      this.onCast,
    );
  }

  onCast(event) {
    const holyShockisOnCooldown = this.spellUsable.isOnCooldown(SPELLS.HOLY_SHOCK_CAST.id);
    if (holyShockisOnCooldown) {
      const reductionMs = this.spellUsable.reduceCooldown(
        SPELLS.HOLY_SHOCK_CAST.id,
        COOLDOWN_REDUCTION_MS,
      );
      this.effectiveHolyShockReductionMs += reductionMs;
      this.wastedHolyShockReductionMs += COOLDOWN_REDUCTION_MS - reductionMs;
    } else {
      const holyShockCooldown =
        7500 / (1 + this.statTracker.hastePercentage(this.statTracker.currentHasteRating));
      if (
        this.selectedCombatant.hasTalent(SPELLS.SANCTIFIED_WRATH_TALENT.id) &&
        this.selectedCombatant.hasBuff(SPELLS.AVENGING_WRATH.id, event.timestamp)
      ) {
        this.holyShocksCastsLost += 1;
      } else {
        this.holyShocksCastsLost += COOLDOWN_REDUCTION_MS / holyShockCooldown;
      }
      this.wastedHolyShockReductionMs += COOLDOWN_REDUCTION_MS;
      this.wastedHolyShockReductionCount += 1;

      // mark the event on the timeline //
      event.meta = event.meta || {};
      event.meta.isInefficientCast = true;
      event.meta.inefficientCastReason = (
        <Trans>
          Holy Shock was off cooldown when you cast Crusader Strike. You should cast Holy Shock
          before Crusader Strike for maximum healing or damage.
        </Trans>
      );
    }
  }

  get holyShocksMissedThresholds() {
    return {
      actual: this.wastedHolyShockReductionCount,
      isGreaterThan: {
        minor: 0,
        average: 2,
        major: 5,
      },
      style: 'number',
    };
  }

  suggestions(when) {
    if (this.owner.builds.GLIMMER.active) {
      when(this.holyShocksMissedThresholds).addSuggestion((suggest, actual, recommended) => suggest(
          <>
            You cast <SpellLink id={SPELLS.CRUSADER_STRIKE.id} />{' '}
            {this.wastedHolyShockReductionCount} times when
            <SpellLink id={SPELLS.HOLY_SHOCK_CAST.id} /> was off cooldown.{' '}
            <SpellLink id={SPELLS.CRUSADER_STRIKE.id} /> should be used to reduce the cooldown of
            <SpellLink id={SPELLS.HOLY_SHOCK_CAST.id} /> and should never be cast when{' '}
            <SpellLink id={SPELLS.HOLY_SHOCK_CAST.id} /> is avalible. This is a core component of
            the <SpellLink id={SPELLS.GLIMMER_OF_LIGHT.id} />{' '}

              build.

          </>,
        )
          .icon(SPELLS.HOLY_SHOCK_CAST.icon)
          .actual(
            `${Math.floor(this.holyShocksCastsLost)} Holy Shock cast${
              Math.floor(this.holyShocksCastsLost) === 1 ? '' : 's'
            } missed.`,
          )
          .recommended(`Casting Holy Shock on cooldown is recommended.`));
    }
  }

  statistic() {
    const formatSeconds = seconds => <Trans>{seconds}s</Trans>;

    return (
      <StatisticBox
        position={STATISTIC_ORDER.OPTIONAL(75)}
        icon={<SpellIcon id={SPELLS.CRUSADERS_MIGHT_TALENT.id} />}
        value={
          <>
            {formatSeconds((this.effectiveHolyShockReductionMs / 1000).toFixed(1))}{' '}
            <SpellIcon
              id={SPELLS.HOLY_SHOCK_CAST.id}
              style={{
                height: '1.3em',
                marginTop: '-.1em',
              }}
            />{' '}
          </>
        }
        label={<Trans>Cooldown reduction</Trans>}
        tooltip={
          <>
            You cast Crusader Strike {this.wastedHolyShockReductionCount} time
            {this.wastedHolyShockReductionCount === 1 ? '' : 's'} when Holy Shock was off cooldown.

            This wasted {(this.wastedHolyShockReductionMs / 1000).toFixed(1)} seconds of Holy
            Shock cooldown reduction,

            preventing you from {Math.floor(this.holyShocksCastsLost)} additional Holy Shock
            cast
            {this.holyShocksLost === 1 ? '' : 's'}.

            {this.wastedLightOfDawnReductionCount === 1 ? '' : 's'} when Light of Dawn
            {this.owner.builds.GLIMMER.active ? ' and Holy Shock were' : ' was'} off cooldown.
          </>
        }
      />
    );
  }
}

export default CrusadersMight;
<|endoftext|>


<commit_before>function applyCodeExample1() {
    Rpd.renderNext('svg', document.getElementById('example-one'),
                   { style: 'compact-v' });

    var patch = Rpd.addPatch('Generate Random Numbers').resizeCanvas(800, 110);

    // add Metro Node, it may generate `bang` signal with the requested time interval
    var metroNode = patch.addNode('util/metro', 'Metro').move(40, 10);

    // add Random Generator Node that will generate random numbers on every `bang` signal
    var randomGenNode = patch.addNode('util/random', 'Random').move(130, 20);
    randomGenNode.inlets['max'].receive(26); // set maximum value of the generated numbers

    // add Log Node, which will log last results of the Random Generator Node
    var logRandomNode = patch.addNode('util/log', 'Log').move(210, 60);
    randomGenNode.outlets['out'].connect(logRandomNode.inlets['what']);

    // define the type of the node which multiplies the incoming value on two
    var multiplyTwoNode = patch.addNode('core/basic', '* 2', {
        process: function(inlets) {
            return {
                'result': (inlets.multiplier || 0) * 2
            }
        }
    }).move(240, 10);
    var multiplierInlet = multiplyTwoNode.addInlet('util/number', 'multiplier');
    var resultOutlet = multiplyTwoNode.addOutlet('util/number', 'result');

    // connect Random Generator output to the multiplying node
    var logMultiplyNode = patch.addNode('util/log', 'Log').move(370, 20);
    resultOutlet.connect(logMultiplyNode.inlets['what']);

    // connect Random Generator output to the multiplying node
    randomGenNode.outlets['out'].connect(multiplierInlet);

    // finally connect Metro node to Random Generator, so the sequence starts
    metroNode.outlets['out'].connect(randomGenNode.inlets['bang']);
}

applyCodeExample1();

var logoPatchAdded = false;
document.getElementById('planets').addEventListener('click', function() {
    if (logoPatchAdded) return;
    logoPatchAdded = true;
    applyRpdLogoPatch(document.getElementById('rpd-logo'),
                      document.getElementById('planets'),
                      document.getElementById('patch-target'));
});

var stringFromCharCode = String.fromCharCode;
var floor = Math.floor;
function fromCodePoint(_) {
    // https://github.com/mathiasbynens/String.fromCodePoint/blob/master/fromcodepoint.js
    var MAX_SIZE = 0x4000;
    var codeUnits = [];
    var highSurrogate;
    var lowSurrogate;
    var index = -1;
    var length = arguments.length;
    if (!length) {
        return '';
    }
    var result = '';
    while (++index < length) {
        var codePoint = Number(arguments[index]);
        if (
            !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
            codePoint < 0 || // not a valid Unicode code point
            codePoint > 0x10FFFF || // not a valid Unicode code point
            floor(codePoint) != codePoint // not an integer
        ) {
            throw RangeError('Invalid code point: ' + codePoint);
        }
        if (codePoint <= 0xFFFF) { // BMP code point
            codeUnits.push(codePoint);
        } else { // Astral code point; split in surrogate halves
            // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
            codePoint -= 0x10000;
            highSurrogate = (codePoint >> 10) + 0xD800;
            lowSurrogate = (codePoint % 0x400) + 0xDC00;
            codeUnits.push(highSurrogate, lowSurrogate);
        }
        if (index + 1 == length || codeUnits.length > MAX_SIZE) {
            result += stringFromCharCode.apply(null, codeUnits);
            codeUnits.length = 0;
        }
    }
    return result;
}
<commit_msg>docs: working on second example<commit_after>function applyCodeExample1() {
    Rpd.renderNext('svg', document.getElementById('example-one'),
                   { style: 'compact-v' });

    var patch = Rpd.addPatch('Generate Random Numbers').resizeCanvas(800, 110);

    // add Metro Node, it may generate `bang` signal with the requested time interval
    var metroNode = patch.addNode('util/metro', 'Metro').move(40, 10);

    // add Random Generator Node that will generate random numbers on every `bang` signal
    var randomGenNode = patch.addNode('util/random', 'Random').move(130, 20);
    randomGenNode.inlets['max'].receive(26); // set maximum value of the generated numbers

    // add Log Node, which will log last results of the Random Generator Node
    var logRandomNode = patch.addNode('util/log', 'Log').move(210, 60);
    randomGenNode.outlets['out'].connect(logRandomNode.inlets['what']);

    // define the type of the node which multiplies the incoming value on two
    var multiplyTwoNode = patch.addNode('core/basic', '* 2', {
        process: function(inlets) {
            return {
                'result': (inlets.multiplier || 0) * 2
            }
        }
    }).move(240, 10);
    var multiplierInlet = multiplyTwoNode.addInlet('util/number', 'multiplier');
    var resultOutlet = multiplyTwoNode.addOutlet('util/number', 'result');

    // connect Random Generator output to the multiplying node
    var logMultiplyNode = patch.addNode('util/log', 'Log').move(370, 20);
    resultOutlet.connect(logMultiplyNode.inlets['what']);

    // connect Random Generator output to the multiplying node
    randomGenNode.outlets['out'].connect(multiplierInlet);

    // finally connect Metro node to Random Generator, so the sequence starts
    metroNode.outlets['out'].connect(randomGenNode.inlets['bang']);
}

function applyCodeExample2() {
    var patch = {};

    Rpd.channeltype('my/vector', {
      show: function(val) {
      	return '<' + val.x + ':' + val.y + '>';
      }
    });

    Rpd.nodetype('my/vector', {
      inlets: {
        x: { type: 'util/number', default: 0 },
        y: { type: 'util/number', default: 0 }
      },
      outlets: {
        out: { type: 'util/number' }
      },
      process: function(inlets) {
        return { x: inlets.x, y: inlets.y };
      }
    });

    Rpd.nodetype('my/canvas', {
      inlets: {
        from: { type: 'util/color' },
        to: { type: 'util/color' },
        count: { type: 'util/number', default: 5 },
        target: { type: 'my/vector' }
      },
      process: function() {}
    });

    var SVG_XMLNS = 'http://www.w3.org/2000/svg';

    Rpd.noderenderer('my/canvas', 'svg', function() {
      var context;
      var particles = [];
      var lastCount = 0;

      function draw() {
        if (context) {
          context.fillStyle = '#fff';
          context.fillRect(0, 0, 150, 150);
          context.fillStyle = '#000';
          particles.forEach(function(particle) {
            context.fillRect(Math.random() * 150, Math.random() * 150, 20, 20);
          });
        }
        requestAnimationFrame(draw);
      }
      requestAnimationFrame(draw);

      return {
        size: { width: 150, height: 150 },
        pivot: { x: 0, y: 0 },

        first: function(bodyElm) {
          var group = document.createElementNS(SVG_XMLNS, 'g');
          group.setAttributeNS(null, 'transform', 'translate(10, 10)');
          var foreign = document.createElementNS(SVG_XMLNS, 'foreignObject');
          canvas = document.createElement('canvas');
          canvas.setAttributeNS(null, 'width', '130px');
          canvas.setAttributeNS(null, 'height', '130px');
          canvas.style.position = 'fixed';
          foreign.appendChild(canvas);
          group.appendChild(foreign);
          bodyElm.appendChild(group);

          context = canvas.getContext('2d');
        },

        always: function(bodyElm, inlets) {
          if (inlets.count != lastCount) {
            particles = [];
            for (var i = 0; i < inlets.count; i++) {
              particles.push({});
            }
            lastCount = inlets.count;
          }
        }

      };
    });

    patch.addNode('util/color');
    patch.addNode('util/color');
    patch.addNode('my/vector');
    patch.addNode('my/canvas');
    patch.addNode('util/knob');
}

applyCodeExample1();

var logoPatchAdded = false;
document.getElementById('planets').addEventListener('click', function() {
    if (logoPatchAdded) return;
    logoPatchAdded = true;
    applyRpdLogoPatch(document.getElementById('rpd-logo'),
                      document.getElementById('planets'),
                      document.getElementById('patch-target'));
});

var stringFromCharCode = String.fromCharCode;
var floor = Math.floor;
function fromCodePoint(_) {
    // https://github.com/mathiasbynens/String.fromCodePoint/blob/master/fromcodepoint.js
    var MAX_SIZE = 0x4000;
    var codeUnits = [];
    var highSurrogate;
    var lowSurrogate;
    var index = -1;
    var length = arguments.length;
    if (!length) {
        return '';
    }
    var result = '';
    while (++index < length) {
        var codePoint = Number(arguments[index]);
        if (
            !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
            codePoint < 0 || // not a valid Unicode code point
            codePoint > 0x10FFFF || // not a valid Unicode code point
            floor(codePoint) != codePoint // not an integer
        ) {
            throw RangeError('Invalid code point: ' + codePoint);
        }
        if (codePoint <= 0xFFFF) { // BMP code point
            codeUnits.push(codePoint);
        } else { // Astral code point; split in surrogate halves
            // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
            codePoint -= 0x10000;
            highSurrogate = (codePoint >> 10) + 0xD800;
            lowSurrogate = (codePoint % 0x400) + 0xDC00;
            codeUnits.push(highSurrogate, lowSurrogate);
        }
        if (index + 1 == length || codeUnits.length > MAX_SIZE) {
            result += stringFromCharCode.apply(null, codeUnits);
            codeUnits.length = 0;
        }
    }
    return result;
}
<|endoftext|>


<commit_before>/* eslint-disable unicorn/no-process-exit */

import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';
import zlib from 'zlib';
import onDeath from 'death';
import fetch from 'node-fetch';
import retry from 'async-retry';
import which from 'which-promise';
import readPkg from 'read-pkg';
import plusxSync from './chmod';
import {
  disableProgress,
  enableProgress,
  info,
  showProgress,
  warn
} from './log';
import packageJSON from '../../package';

fetch.Promise = Promise;
global.Promise = Promise;
let { platform } = process;
if (detectAlpine()) platform = 'alpine';

const now = path.join(__dirname, 'now');
const targetWin32 = path.join(__dirname, 'now.exe');
const target = platform === 'win32' ? targetWin32 : now;
const partial = target + '.partial';

const platformToName = {
  alpine: 'now-alpine',
  darwin: 'now-macos',
  linux: 'now-linux',
  win32: 'now-win.exe'
};

function detectAlpine() {
  if (platform !== 'linux') return false;
  // https://github.com/sass/node-sass/issues/1589#issuecomment-265292579
  const ldd = spawnSync('ldd', [process.execPath]).stdout.toString();
  return /\bmusl\b/.test(ldd);
}

async function download() {
  try {
    fs.writeFileSync(
      now,
      '#!/usr/bin/env node\n' +
        'console.log("Please wait until the \'now\' installation completes!")\n'
    );
  } catch (err) {
    if (err.code === 'EACCES') {
      warn(
        'Please try installing Now CLI again with the `--unsafe-perm` option.'
      );
      info('Example: `npm i -g --unsafe-perm now`');

      process.exit();
    }

    throw err;
  }

  onDeath(() => {
    fs.writeFileSync(
      now,
      '#!/usr/bin/env node\n' +
        'console.log("The \'now\' installation did not complete successfully.")\n' +
        'console.log("Please run \'npm i -g now\' to reinstall!")\n'
    );
    process.exit();
  });

  info('For the source code, check out: https://github.com/zeit/now-cli');

  // Print an empty line
  console.log('');

  await retry(
    async () => {
      enableProgress('Downloading Now CLI ' + packageJSON.version);
      showProgress(0);

      try {
        const name = platformToName[platform];
        const url = `https://github.com/zeit/now-cli/releases/download/${packageJSON.version}/${name}.gz`;
        const resp = await fetch(url, { compress: false });

        if (resp.status !== 200) {
          throw new Error(resp.statusText + ' ' + url);
        }

        const size = resp.headers.get('content-length');
        const ws = fs.createWriteStream(partial);

        await new Promise((resolve, reject) => {
          let bytesRead = 0;

          resp.body.on('error', reject).on('data', chunk => {
            bytesRead += chunk.length;

            if (size) {
              showProgress(100 * bytesRead / size);
            }
          });

          const gunzip = zlib.createGunzip();

          gunzip.on('error', reject);

          resp.body.pipe(gunzip).pipe(ws);

          ws.on('error', reject).on('close', () => {
            showProgress(100);
            resolve();
          });
        });
      } finally {
        disableProgress();
      }
    },
    {
      retries: 10,
      onRetry: err => console.error(err)
    }
  );

  fs.renameSync(partial, target);
}

function modifyGitBashFile(content) {
  return (
    '#!/bin/sh\n' +
    'basedir=$(dirname "$(echo "$0" | sed -e \'s,\\\\,/,g\')")\n' +
    '\n' +
    'case `uname` in\n' +
    '    *CYGWIN*) basedir=`cygpath -w "$basedir"`;;\n' +
    'esac\n' +
    '\n' +
    content.replace('download/dist/now"', 'download/dist/now.exe"')
  );
}

async function main() {
  await download();

  if (platform === 'win32') {
    try {
      fs.writeFileSync(now, '');
      // Workaround for https://github.com/npm/cmd-shim/pull/25
      const globalPath = path.dirname(await which('npm'));
      let gitBashFile = path.join(globalPath, 'now');
      if (!fs.existsSync(gitBashFile)) {
        gitBashFile = path.join(process.env.APPDATA, 'npm/now');
      }

      fs.writeFileSync(
        gitBashFile,
        modifyGitBashFile(fs.readFileSync(gitBashFile, 'utf8'))
      );
    } catch (err) {
      if (err.code !== 'ENOENT') {
        // Not a problem. only git cmd will not work
        console.error(err);
      }
    }
  } else {
    plusxSync(now);
  }
}

main().catch(err => {
  console.error(err);
  process.exit(2);
});
<commit_msg>Overwrite the default batch file on windows (#1922)<commit_after>/* eslint-disable unicorn/no-process-exit */

import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';
import zlib from 'zlib';
import onDeath from 'death';
import fetch from 'node-fetch';
import retry from 'async-retry';
import which from 'which-promise';
import readPkg from 'read-pkg';
import plusxSync from './chmod';
import {
  disableProgress,
  enableProgress,
  info,
  showProgress,
  warn
} from './log';
import packageJSON from '../../package';

fetch.Promise = Promise;
global.Promise = Promise;
let { platform } = process;
if (detectAlpine()) platform = 'alpine';

const now = path.join(__dirname, 'now');
const targetWin32 = path.join(__dirname, 'now.exe');
const target = platform === 'win32' ? targetWin32 : now;
const partial = target + '.partial';

const platformToName = {
  alpine: 'now-alpine',
  darwin: 'now-macos',
  linux: 'now-linux',
  win32: 'now-win.exe'
};

function detectAlpine() {
  if (platform !== 'linux') return false;
  // https://github.com/sass/node-sass/issues/1589#issuecomment-265292579
  const ldd = spawnSync('ldd', [process.execPath]).stdout.toString();
  return /\bmusl\b/.test(ldd);
}

async function download() {
  try {
    fs.writeFileSync(
      now,
      '#!/usr/bin/env node\n' +
        'console.log("Please wait until the \'now\' installation completes!")\n'
    );
  } catch (err) {
    if (err.code === 'EACCES') {
      warn(
        'Please try installing Now CLI again with the `--unsafe-perm` option.'
      );
      info('Example: `npm i -g --unsafe-perm now`');

      process.exit();
    }

    throw err;
  }

  onDeath(() => {
    fs.writeFileSync(
      now,
      '#!/usr/bin/env node\n' +
        'console.log("The \'now\' installation did not complete successfully.")\n' +
        'console.log("Please run \'npm i -g now\' to reinstall!")\n'
    );
    process.exit();
  });

  info('For the source code, check out: https://github.com/zeit/now-cli');

  // Print an empty line
  console.log('');

  await retry(
    async () => {
      enableProgress('Downloading Now CLI ' + packageJSON.version);
      showProgress(0);

      try {
        const name = platformToName[platform];
        const url = `https://github.com/zeit/now-cli/releases/download/${packageJSON.version}/${name}.gz`;
        const resp = await fetch(url, { compress: false });

        if (resp.status !== 200) {
          throw new Error(resp.statusText + ' ' + url);
        }

        const size = resp.headers.get('content-length');
        const ws = fs.createWriteStream(partial);

        await new Promise((resolve, reject) => {
          let bytesRead = 0;

          resp.body.on('error', reject).on('data', chunk => {
            bytesRead += chunk.length;

            if (size) {
              showProgress(100 * bytesRead / size);
            }
          });

          const gunzip = zlib.createGunzip();

          gunzip.on('error', reject);

          resp.body.pipe(gunzip).pipe(ws);

          ws.on('error', reject).on('close', () => {
            showProgress(100);
            resolve();
          });
        });
      } finally {
        disableProgress();
      }
    },
    {
      retries: 10,
      onRetry: err => console.error(err)
    }
  );

  fs.renameSync(partial, target);
}

function modifyGitBashFile(content) {
  return (
    '#!/bin/sh\n' +
    'basedir=$(dirname "$(echo "$0" | sed -e \'s,\\\\,/,g\')")\n' +
    '\n' +
    'case `uname` in\n' +
    '    *CYGWIN*) basedir=`cygpath -w "$basedir"`;;\n' +
    'esac\n' +
    '\n' +
    content.replace('download/dist/now"', 'download/dist/now.exe"')
  );
}

async function main() {
  await download();

  if (platform === 'win32') {
    try {
      fs.writeFileSync(now, '');
      // Workaround for https://github.com/npm/cmd-shim/pull/25
      const globalPath = path.dirname(await which('npm'));
      let gitBashFile = path.join(globalPath, 'now');
      if (!fs.existsSync(gitBashFile)) {
        gitBashFile = path.join(process.env.APPDATA, 'npm/now');
      }

      fs.writeFileSync(
        gitBashFile,
        modifyGitBashFile(fs.readFileSync(gitBashFile, 'utf8'))
      );

      let npmCmdFile = path.join(globalPath, 'now.cmd');
      if (!fs.existsSync(npmCmdFile)) {
        npmCmdFile = path.join(process.env.APPDATA, 'npm/now.cmd');
      }

      fs.writeFileSync(
        npmCmdFile,
        '@%~dp0\\node_modules\\now\\download\\dist\\now.exe %*'
      );
    } catch (err) {
      if (err.code !== 'ENOENT') {
        // Not a problem. only git cmd will not work
        console.error(err);
      }
    }
  } else {
    plusxSync(now);
  }
}

main().catch(err => {
  console.error(err);
  process.exit(2);
});
<|endoftext|>


<commit_before>
angular.module('dragging', ['mouseCapture', ] )

//
// Service used to help with dragging and clicking on elements.
//
.factory('dragging', function ($rootScope, mouseCapture) {

	//
	// Threshold for dragging.
	// When the mouse moves by at least this amount dragging starts.
	//
	var threshold = 5; //todo: make this an attr option.

	return {

		//
		// Called by users of the service to register a mousedown event and start dragging.
		// Acquires the 'mouse capture' until the mouseup event.
		//
  		startDrag: function (evt, config) {

  			var draggingElement = $(event.target);
  			var draggingElementOffset = draggingElement.offset();
  			var startOffsetX = evt.clientX - draggingElementOffset.left;
  			var startOffsetY = evt.clientY - draggingElementOffset.top;
  			var parentElement = draggingElement.closest('.draggable-container') || draggingElement.parent();
  			var parentOffset = parentElement.offset();

  			var dragging = false;
			var x = evt.clientX;
			var y = evt.clientY;

			//
			// Handler for mousemove events while the mouse is 'captured'.
			//
	  		var mouseMove = function (evt) {

				if (!dragging) {
					if (evt.clientX - x > threshold ||
						evt.clientY - y > threshold)
					{
						dragging = true;

						if (config.dragStarted) {
							var relativeX = (evt.clientX - parentOffset.left) - startOffsetX;
							var relativeY = (evt.clientY - parentOffset.top) - startOffsetY;
							config.dragStarted(relativeX, relativeY);
						}
					}
				}
				else {
					if (config.dragging) {
						var deltaX = evt.clientX - x;
						var deltaY = evt.clientY - y;
						var relativeX = (evt.clientX - parentOffset.left) - startOffsetX;
						var relativeY = (evt.clientY - parentOffset.top) - startOffsetY;
						config.dragging(deltaX, deltaY, relativeX, relativeY);
					}

					x = evt.clientX;
					y = evt.clientY;
				}
	  		};

	  		//
	  		// Handler for when mouse capture is released.
	  		//
	  		var released = function(evt) {

	  			if (dragging) {
  					if (config.dragEnded) {
  						config.dragEnded();
  					}
	  			}
	  			else {
  					if (config.clicked) {
  						config.clicked();
  					}
	  			}
	  		};

			//
			// Handler for mouseup event while the mouse is 'captured'.
			// Mouseup releases the mouse capture.
			//
	  		var mouseUp = function (evt) {

	  			mouseCapture.release();

	  			evt.stopPropagation();
	  			evt.preventDefault();
	  		};

	  		//
	  		// Acquire the mouse capture and start handling mouse events.
	  		//
			mouseCapture.acquire(evt, {
				mouseMove: mouseMove,
				mouseUp: mouseUp,
				released: released,
			});

	  		evt.stopPropagation();
	  		evt.preventDefault();
  		},

	};

})

;

<commit_msg>Drag offset is now passed explicitly to the dragging callback so that the user can choose what to do with it.<commit_after>
angular.module('dragging', ['mouseCapture', ] )

//
// Service used to help with dragging and clicking on elements.
//
.factory('dragging', function ($rootScope, mouseCapture) {

	//
	// Threshold for dragging.
	// When the mouse moves by at least this amount dragging starts.
	//
	var threshold = 5; //todo: make this an attr option.

	return {

		//
		// Called by users of the service to register a mousedown event and start dragging.
		// Acquires the 'mouse capture' until the mouseup event.
		//
  		startDrag: function (evt, config) {

  			var draggingElement = $(event.target);
  			var draggingElementOffset = draggingElement.offset();
  			var startOffsetX = evt.clientX - draggingElementOffset.left;
  			var startOffsetY = evt.clientY - draggingElementOffset.top;
  			var parentElement = draggingElement.closest('.draggable-container') || draggingElement.parent();
  			var parentOffset = parentElement.offset();

  			var dragging = false;
			var x = evt.clientX;
			var y = evt.clientY;

			//
			// Handler for mousemove events while the mouse is 'captured'.
			//
	  		var mouseMove = function (evt) {

				if (!dragging) {
					if (evt.clientX - x > threshold ||
						evt.clientY - y > threshold)
					{
						dragging = true;

						if (config.dragStarted) {
							var relativeX = evt.clientX - parentOffset.left;
							var relativeY = evt.clientY - parentOffset.top;
							config.dragStarted(relativeX, relativeY, evt, startOffsetX, startOffsetY);
						}
					}
				}
				else {
					if (config.dragging) {
						var deltaX = evt.clientX - x;
						var deltaY = evt.clientY - y;
						var relativeX = evt.clientX - parentOffset.left;
						var relativeY = evt.clientY - parentOffset.top;
						config.dragging(deltaX, deltaY, relativeX, relativeY, evt, startOffsetX, startOffsetY);
					}

					x = evt.clientX;
					y = evt.clientY;
				}
	  		};

	  		//
	  		// Handler for when mouse capture is released.
	  		//
	  		var released = function() {

	  			if (dragging) {
  					if (config.dragEnded) {
  						config.dragEnded();
  					}
	  			}
	  			else {
  					if (config.clicked) {
  						config.clicked();
  					}
	  			}
	  		};

			//
			// Handler for mouseup event while the mouse is 'captured'.
			// Mouseup releases the mouse capture.
			//
	  		var mouseUp = function (evt) {

	  			mouseCapture.release();

	  			evt.stopPropagation();
	  			evt.preventDefault();
	  		};

	  		//
	  		// Acquire the mouse capture and start handling mouse events.
	  		//
			mouseCapture.acquire(evt, {
				mouseMove: mouseMove,
				mouseUp: mouseUp,
				released: released,
			});

	  		evt.stopPropagation();
	  		evt.preventDefault();
  		},

	};

})

;

<|endoftext|>


<commit_before>import React, {Component} from 'react';
import './LeaderBoard.css';
import api from '../api.js';

export default class LeaderBoard extends Component {
  constructor() {
    super();
    this.state = {
      leaders: []
    }

  }

  componentDidMount() {
    this.fetchLeader(); //By default if we don't send the level param and the correct boolean and will start at the initial question
  }

  fetchLeader = () => {
    api.getLeader()
      .then(res => {
        this.setState({leaders: this.state.leaders.concat(res.body)})

      })
      .catch(error => {
        this.setState({
          Q: "Error loading leaders: " + error
        })
      })
  }

  render() {
    return (

 All-Time Leaders

 Can you make it to our hall of fame?

              User
              Total Score

            {this.state.leaders.map((item) => (

                {item.user}
                {item.total}

            ))}

    );
  }
}<commit_msg>Started LeaderBoard CSS<commit_after>import React, {Component} from 'react';
import './LeaderBoard.css';
import api from '../api.js';

export default class LeaderBoard extends Component {
  constructor() {
    super();
    this.state = {
      leaders: []
    }

  }

  componentDidMount() {
    this.fetchLeader(); //By default if we don't send the level param and the correct boolean and will start at the initial question
  }

  fetchLeader = () => {
    api.getLeader()
      .then(res => {
        this.setState({leaders: this.state.leaders.concat(res.body)})

      })
      .catch(error => {
        this.setState({
          Q: "Error loading leaders: " + error
        })
      })
  }

  render() {
    return (

 All-Time Leaders

 Can you make it to our hall of fame?

              User
              Total Score
              Games Played

            {this.state.leaders.map((item) => (

                {item.user}
                {item.total}
                {item.cnt}

            ))}

    );
  }
}<|endoftext|>


<commit_before>import GenericResolver from 'api/resolver/generic/genericResolver'
import Util from 'api/util'
import {getHostFromHeaders} from 'util/host'
import Cache from 'util/cache'
import {preprocessCss} from './cssPreprocessor'
import {loadAllHostrules} from 'util/hostrules'

const hostrules = loadAllHostrules(false)

export const getCmsPage = async ({db, context, slug, editmode, checkHostrules, _version, headers}) => {
    let host = headers && headers['x-host-rule'] ? headers['x-host-rule'].split(':')[0] : getHostFromHeaders(headers)

    if(!host){
        host = ''
    }

    if (host && host.startsWith('www.')) {
        host = host.substring(4)
    }

    let slugMatch = {}
    let modSlug

    if(checkHostrules) {
        const hostArr = host.split('.')
        const hostsChecks = [host]

        if (hostArr.length > 2) {
            // is subdomain

            // add top level domain
            hostsChecks.push( hostArr[hostArr.length-2]+'.'+hostArr[hostArr.length-1])
        }

        for(let i = 0;i < hostsChecks.length; i++) {
            const currentHost = hostsChecks[i]
            if (hostrules[currentHost] && hostrules[currentHost].slugContext && slug.indexOf(hostrules[currentHost].slugContext) < 0) {
                modSlug = hostrules[currentHost].slugContext + (slug.length > 0 ? '/' : '') + slug
                if (hostrules[currentHost].slugFallback) {
                    slugMatch = {$or: [{slug: modSlug}, {slug}]}
                } else {
                    slugMatch = {slug: modSlug}
                }
            }
        }
    }

    if(!modSlug){
        modSlug = slug
        slugMatch = {slug}
    }else{
        console.log(slugMatch, slug)
    }

    const cacheKey = 'cmsPage-' + (_version ? _version + '-' : '') + slug + (host ? '-' + host : '')
    let cmsPages
    if (!editmode) {
        cmsPages = Cache.get(cacheKey)
    }
    if (!cmsPages) {

        let match

        /*const parts = slug.split('/')
        for(let i = parts.length; i>0;i--){
            ors.push({slug: `${parts.join('/')}/*`})
            parts.splice(-1,1)
        }*/

        if (!Util.isUserLoggedIn(context)) {
            // if no user only match public entries
            match = {$and: [slugMatch, {public: true}]}
        } else {
            match = slugMatch
        }
        cmsPages = await GenericResolver.entities(db, context, 'CmsPage', ['slug', 'name', 'template', 'script', 'style', 'serverScript', 'dataResolver', 'resources', 'ssr', 'public', 'urlSensitiv', 'parseResolvedData', 'alwaysLoadAssets', 'loadPageOptions', 'ssrStyle', 'compress'], {
            match,
            limit: 1,
            _version
        })
        // minify template if no user is logged in
        if (cmsPages.results && cmsPages.results.length) {

            if (!editmode) {
                const result = cmsPages.results[0]
                //minify script

                if (result.ssrStyle) {
                    result.style = preprocessCss(result.style)
                }
                if (result.compress) {
                    result.script = result.script.replace(/\t/g, ' ').replace(/ +(?= )/g, '').replace(/(^[ \t]*\n)/gm, "")

                    if (!result.ssrStyle) {
                        result.style = result.style
                            .replace(/\t/g, ' ') // remove tabs
                            .replace(/ +(?= )/g, '') // remove double whitespace
                            .replace(/(^[ \t]*\n)/gm, "") // remove empty lines
                            .replace(/^\s+|\s+$/gm, '') // remove whitespace at beginning of line
                            .replace(/,$\n/gm, ',') // remove line break after ,
                    }
                }
                try {
                    // TODO: Include sub CMS component to reduce number of requests
                    // TODO: also check if template is html

                    const template = JSON.parse(result.template)

                    if (result.compress) {
                        Util.findProperties(template, '$inlineEditor').forEach(({element}) => {
                            delete element.$inlineEditor
                        })
                    }

                    result.template = JSON.stringify(template, null, 0)
                } catch (e) {
                    console.warn(`${result.slug} is not a valid json template`)
                }
            }

            //only cache if public
            if (!editmode && cmsPages.results[0].public) {
                if(slug !== cmsPages.results[0].slug){
                    const cacheKeyAlias = 'cmsPage-' + (_version ? _version + '-' : '') + cmsPages.results[0].slug + (host ? '-' + host : '')
                    Cache.setAlias(cacheKeyAlias, cacheKey)
                }
                Cache.set(cacheKey, cmsPages, 6000000) // cache expires in 1h40min
            }
        }

    }
    return cmsPages
}

<commit_msg>Small improvements<commit_after>import GenericResolver from 'api/resolver/generic/genericResolver'
import Util from 'api/util'
import {getHostFromHeaders} from 'util/host'
import Cache from 'util/cache'
import {preprocessCss} from './cssPreprocessor'
import {loadAllHostrules} from 'util/hostrules'

const hostrules = loadAllHostrules(false)

export const getCmsPage = async ({db, context, slug, editmode, checkHostrules, _version, headers}) => {
    let host = headers && headers['x-host-rule'] ? headers['x-host-rule'].split(':')[0] : getHostFromHeaders(headers)

    if(!host){
        host = ''
    }
    if (host && host.startsWith('www.')) {
        host = host.substring(4)
    }

    let slugMatch = {}
    let modSlug

    if(checkHostrules) {
        const hostArr = host.split('.')
        const hostsChecks = [host]

        if (hostArr.length > 2) {
            // is subdomain

            // add top level domain
            hostsChecks.push( hostArr[hostArr.length-2]+'.'+hostArr[hostArr.length-1])
        }

        for(let i = 0;i < hostsChecks.length; i++) {
            const currentHost = hostsChecks[i]
            if (hostrules[currentHost] && hostrules[currentHost].slugContext && (slug + '/').indexOf(hostrules[currentHost].slugContext+'/')!== 0) {
                modSlug = hostrules[currentHost].slugContext + (slug.length > 0 ? '/' : '') + slug
                if (hostrules[currentHost].slugFallback) {
                    slugMatch = {$or: [{slug: modSlug}, {slug}]}
                } else {
                    slugMatch = {slug: modSlug}
                }
                break
            }
        }
    }

    if(!modSlug){
        modSlug = slug
        slugMatch = {slug}
    }

    const cacheKey = 'cmsPage-' + (_version ? _version + '-' : '') + slug + (host ? '-' + host : '')
    let cmsPages
    if (!editmode) {
        cmsPages = Cache.get(cacheKey)
    }
    if (!cmsPages) {

        let match

        /*const parts = slug.split('/')
        for(let i = parts.length; i>0;i--){
            ors.push({slug: `${parts.join('/')}/*`})
            parts.splice(-1,1)
        }*/

        if (!Util.isUserLoggedIn(context)) {
            // if no user only match public entries
            match = {$and: [slugMatch, {public: true}]}
        } else {
            match = slugMatch
        }
        cmsPages = await GenericResolver.entities(db, context, 'CmsPage', ['slug', 'name', 'template', 'script', 'style', 'serverScript', 'dataResolver', 'resources', 'ssr', 'public', 'urlSensitiv', 'parseResolvedData', 'alwaysLoadAssets', 'loadPageOptions', 'ssrStyle', 'compress'], {
            match,
            limit: 1,
            _version
        })
        // minify template if no user is logged in
        if (cmsPages.results && cmsPages.results.length) {

            if (!editmode) {
                const result = cmsPages.results[0]
                //minify script

                if (result.ssrStyle) {
                    result.style = preprocessCss(result.style)
                }
                if (result.compress) {
                    result.script = result.script.replace(/\t/g, ' ').replace(/ +(?= )/g, '').replace(/(^[ \t]*\n)/gm, "")

                    if (!result.ssrStyle) {
                        result.style = result.style
                            .replace(/\t/g, ' ') // remove tabs
                            .replace(/ +(?= )/g, '') // remove double whitespace
                            .replace(/(^[ \t]*\n)/gm, "") // remove empty lines
                            .replace(/^\s+|\s+$/gm, '') // remove whitespace at beginning of line
                            .replace(/,$\n/gm, ',') // remove line break after ,
                    }
                }
                try {
                    // TODO: Include sub CMS component to reduce number of requests
                    // TODO: also check if template is html

                    const template = JSON.parse(result.template)

                    if (result.compress) {
                        Util.findProperties(template, '$inlineEditor').forEach(({element}) => {
                            delete element.$inlineEditor
                        })
                    }

                    result.template = JSON.stringify(template, null, 0)
                } catch (e) {
                    console.warn(`${result.slug} is not a valid json template`)
                }
            }

            //only cache if public
            if (!editmode && cmsPages.results[0].public) {
                if(slug !== cmsPages.results[0].slug){
                    const cacheKeyAlias = 'cmsPage-' + (_version ? _version + '-' : '') + cmsPages.results[0].slug + (host ? '-' + host : '')
                    Cache.setAlias(cacheKeyAlias, cacheKey)
                }
                Cache.set(cacheKey, cmsPages, 6000000) // cache expires in 1h40min
            }
        }

    }
    return cmsPages
}

<|endoftext|>


<commit_before>// ==UserScript==
// @author      Robert Slifka (GitHub @rslifka)
// @connect     docs.google.com
// @connect     rslifka.github.io
// @copyright   2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools)
// @description (DEVELOPMENT) Enhancements to the Destiny Item Manager
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getValue
// @grant       GM_log
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest
// @homepage    https://github.com/rslifka/fate_of_all_fools
// @license     MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt
// @match       https://*.destinyitemmanager.com/*
// @name        (DEVELOPMENT) Fate of All Fools
// @require     file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.js
// @resource    fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.css
// @run-at      document-idle
// @supportURL  https://github.com/rslifka/fate_of_all_fools/issues
// ==/UserScript==
<commit_msg>Include only what's necessary to test locally<commit_after>// ==UserScript==
// @connect     docs.google.com
// @connect     rslifka.github.io
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getValue
// @grant       GM_log
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest
// @match       https://*.destinyitemmanager.com/*
// @name        (DEVELOPMENT) Fate of All Fools
// @require     file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.js
// @resource    fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.css
// @run-at      document-idle
// ==/UserScript==
<|endoftext|>


<commit_before>/*!
Deck JS - deck.scale
Copyright (c) 2011-2012 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/

/*
This module adds automatic scaling to the deck.  Slides are scaled down
using CSS transforms to fit within the deck container. If the container is
big enough to hold the slides without scaling, no scaling occurs. The user
can disable and enable scaling with a keyboard shortcut.

Note: CSS transforms may make Flash videos render incorrectly.  Presenters
that need to use video may want to disable scaling to play them.  HTML5 video
works fine.
*/
(function($, undefined) {
  var $document = $(document);
  var $window = $(window);
  var baseHeight, timer, rootSlides;

  /*
  Internal function to do all the dirty work of scaling the slides.
  */
  var scaleDeck = function() {
    var options = $.deck('getOptions');
    var $container = $.deck('getContainer');
    var baseHeight = options.baseHeight;

    if (!baseHeight) {
      baseHeight = $container.height();
    }

    // Scale each slide down if necessary (but don't scale up)
    $.each(rootSlides, function(i, $slide) {
      var slideHeight = $slide.innerHeight();
      var $scaler = $slide.find('.' + options.classes.scaleSlideWrapper);
      var shouldScale = $container.hasClass(options.classes.scale);
      var scale = shouldScale ? baseHeight / slideHeight : 1;

      if (scale === 1) {
        $scaler.css('transform', '');
      }
      else {
        $scaler.css('transform', 'scale(' + scale + ')');
        window.setTimeout(function() {
          $container.scrollTop(0)
        }, 1);
      }
    });
  };

  var populateRootSlides = function() {
    var options = $.deck('getOptions');
    var slideTest = $.map([
      options.classes.before,
      options.classes.previous,
      options.classes.current,
      options.classes.next,
      options.classes.after
    ], function(el, i) {
      return '.' + el;
    }).join(', ');

    rootSlides = [];
    $.each($.deck('getSlides'), function(i, $slide) {
      var $parentSlides = $slide.parentsUntil(
        options.selectors.container,
        slideTest
      );
      if (!$parentSlides.length) {
        rootSlides.push($slide);
      }
    });
  };

  var wrapRootSlideContent = function() {
    var options = $.deck('getOptions');
    var wrap = '
';
    $.each(rootSlides, function(i, $slide) {
      $slide.children().wrapAll(wrap);
    });
  };

  var scaleOnResizeAndLoad = function() {
    var options = $.deck('getOptions');

    $window.unbind('resize.deckscale');
    $window.bind('resize.deckscale', function() {
      window.clearTimeout(timer);
      timer = window.setTimeout(scaleDeck, options.scaleDebounce);
    });
    $window.unbind('load.deckscale').bind('load.deckscale', function() {
      $.deck('enableScale');
    });
  };

  var bindKeyEvents = function() {
    var options = $.deck('getOptions');
    $document.unbind('keydown.deckscale');
    $document.bind('keydown.deckscale', function(event) {
      var isKey = event.which === options.keys.scale;
      isKey = isKey || $.inArray(event.which, options.keys.scale) > -1;
      if (isKey) {
        $.deck('toggleScale');
        event.preventDefault();
      }
    });
  };

  /*
  Extends defaults/options.

  options.classes.scale
    This class is added to the deck container when scaling is enabled.
    It is enabled by default when the module is included.

  options.classes.scaleSlideWrapper
    Scaling is done using a wrapper around the contents of each slide. This
    class is applied to that wrapper.

  options.keys.scale
    The numeric keycode used to toggle enabling and disabling scaling.

  options.baseHeight
    When baseHeight is falsy, as it is by default, the deck is scaled in
    proportion to the height of the deck container. You may instead specify
    a height as a number of px, and slides will be scaled against this
    height regardless of the container size.

  options.scaleDebounce
    Scaling on the browser resize event is debounced. This number is the
    threshold in milliseconds. You can learn more about debouncing here:
    http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/

  */
  $.extend(true, $.deck.defaults, {
    classes: {
      scale: 'deck-scale',
      scaleSlideWrapper: 'deck-slide-scaler'
    },

    keys: {
      scale: 83 // s
    },

    baseHeight: null,
    scaleDebounce: 200
  });

  /*
  jQuery.deck('disableScale')

  Disables scaling and removes the scale class from the deck container.
  */
  $.deck('extend', 'disableScale', function() {
    $.deck('getContainer').removeClass($.deck('getOptions').classes.scale);
    scaleDeck();
  });

  /*
  jQuery.deck('enableScale')

  Enables scaling and adds the scale class to the deck container.
  */
  $.deck('extend', 'enableScale', function() {
    $.deck('getContainer').addClass($.deck('getOptions').classes.scale);
    scaleDeck();
  });

  /*
  jQuery.deck('toggleScale')

  Toggles between enabling and disabling scaling.
  */
  $.deck('extend', 'toggleScale', function() {
    var $container = $.deck('getContainer');
    var isScaled = $container.hasClass($.deck('getOptions').classes.scale);
    $.deck(isScaled? 'disableScale' : 'enableScale');
  });

  $document.bind('deck.init', function() {
    populateRootSlides();
    wrapRootSlideContent();
    scaleOnResizeAndLoad();
    bindKeyEvents();
  });
})(jQuery, 'deck', this);

<commit_msg>Fix scale on load not firing sometimes<commit_after>/*!
Deck JS - deck.scale
Copyright (c) 2011-2012 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/

/*
This module adds automatic scaling to the deck.  Slides are scaled down
using CSS transforms to fit within the deck container. If the container is
big enough to hold the slides without scaling, no scaling occurs. The user
can disable and enable scaling with a keyboard shortcut.

Note: CSS transforms may make Flash videos render incorrectly.  Presenters
that need to use video may want to disable scaling to play them.  HTML5 video
works fine.
*/
(function($, undefined) {
  var $document = $(document);
  var $window = $(window);
  var baseHeight, timer, rootSlides;

  /*
  Internal function to do all the dirty work of scaling the slides.
  */
  var scaleDeck = function() {
    var options = $.deck('getOptions');
    var $container = $.deck('getContainer');
    var baseHeight = options.baseHeight;

    if (!baseHeight) {
      baseHeight = $container.height();
    }

    // Scale each slide down if necessary (but don't scale up)
    $.each(rootSlides, function(i, $slide) {
      var slideHeight = $slide.innerHeight();
      var $scaler = $slide.find('.' + options.classes.scaleSlideWrapper);
      var shouldScale = $container.hasClass(options.classes.scale);
      var scale = shouldScale ? baseHeight / slideHeight : 1;

      if (scale === 1) {
        $scaler.css('transform', '');
      }
      else {
        $scaler.css('transform', 'scale(' + scale + ')');
        window.setTimeout(function() {
          $container.scrollTop(0)
        }, 1);
      }
    });
  };

  var populateRootSlides = function() {
    var options = $.deck('getOptions');
    var slideTest = $.map([
      options.classes.before,
      options.classes.previous,
      options.classes.current,
      options.classes.next,
      options.classes.after
    ], function(el, i) {
      return '.' + el;
    }).join(', ');

    rootSlides = [];
    $.each($.deck('getSlides'), function(i, $slide) {
      var $parentSlides = $slide.parentsUntil(
        options.selectors.container,
        slideTest
      );
      if (!$parentSlides.length) {
        rootSlides.push($slide);
      }
    });
  };

  var wrapRootSlideContent = function() {
    var options = $.deck('getOptions');
    var wrap = '
';
    $.each(rootSlides, function(i, $slide) {
      $slide.children().wrapAll(wrap);
    });
  };

  var scaleOnResizeAndLoad = function() {
    var options = $.deck('getOptions');

    $window.unbind('resize.deckscale');
    $window.bind('resize.deckscale', function() {
      window.clearTimeout(timer);
      timer = window.setTimeout(scaleDeck, options.scaleDebounce);
    });
    $.deck('enableScale');
    $window.unbind('load.deckscale');
    $window.bind('load.deckscale', scaleDeck);
  };

  var bindKeyEvents = function() {
    var options = $.deck('getOptions');
    $document.unbind('keydown.deckscale');
    $document.bind('keydown.deckscale', function(event) {
      var isKey = event.which === options.keys.scale;
      isKey = isKey || $.inArray(event.which, options.keys.scale) > -1;
      if (isKey) {
        $.deck('toggleScale');
        event.preventDefault();
      }
    });
  };

  /*
  Extends defaults/options.

  options.classes.scale
    This class is added to the deck container when scaling is enabled.
    It is enabled by default when the module is included.

  options.classes.scaleSlideWrapper
    Scaling is done using a wrapper around the contents of each slide. This
    class is applied to that wrapper.

  options.keys.scale
    The numeric keycode used to toggle enabling and disabling scaling.

  options.baseHeight
    When baseHeight is falsy, as it is by default, the deck is scaled in
    proportion to the height of the deck container. You may instead specify
    a height as a number of px, and slides will be scaled against this
    height regardless of the container size.

  options.scaleDebounce
    Scaling on the browser resize event is debounced. This number is the
    threshold in milliseconds. You can learn more about debouncing here:
    http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/

  */
  $.extend(true, $.deck.defaults, {
    classes: {
      scale: 'deck-scale',
      scaleSlideWrapper: 'deck-slide-scaler'
    },

    keys: {
      scale: 83 // s
    },

    baseHeight: null,
    scaleDebounce: 200
  });

  /*
  jQuery.deck('disableScale')

  Disables scaling and removes the scale class from the deck container.
  */
  $.deck('extend', 'disableScale', function() {
    $.deck('getContainer').removeClass($.deck('getOptions').classes.scale);
    scaleDeck();
  });

  /*
  jQuery.deck('enableScale')

  Enables scaling and adds the scale class to the deck container.
  */
  $.deck('extend', 'enableScale', function() {
    $.deck('getContainer').addClass($.deck('getOptions').classes.scale);
    scaleDeck();
  });

  /*
  jQuery.deck('toggleScale')

  Toggles between enabling and disabling scaling.
  */
  $.deck('extend', 'toggleScale', function() {
    var $container = $.deck('getContainer');
    var isScaled = $container.hasClass($.deck('getOptions').classes.scale);
    $.deck(isScaled? 'disableScale' : 'enableScale');
  });

  $document.bind('deck.init', function() {
    populateRootSlides();
    wrapRootSlideContent();
    scaleOnResizeAndLoad();
    bindKeyEvents();
  });
})(jQuery, 'deck', this);

<|endoftext|>


<commit_before>window.jsLibs = [
	{
		url: 'https://code.jquery.com/jquery-3.2.1.min.js',
		label: 'jQuery',
		type: 'js'
	},
	{
		url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js',
		label: 'Bootstrap 3',
		type: 'js'
	},
	{
		url:
			'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js',
		label: 'Bootstrap 4β',
		type: 'js'
	},
	{
		url:
			'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/js/foundation.min.js',
		label: 'Foundation',
		type: 'js'
	},
	{
		url: 'https://semantic-ui.com/dist/semantic.min.js',
		label: 'Semantic UI',
		type: 'js'
	},
	{
		url: 'https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js',
		label: 'Angular',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.min.js',
		label: 'React',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js',
		label: 'React DOM',
		type: 'js'
	},
	{
		url: 'https://unpkg.com/vue@2.4.4/dist/vue.min.js',
		label: 'Vue.js',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min.js',
		label: 'Three.js',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.2/d3.min.js',
		label: 'D3',
		type: 'js'
	},
	{
		url:
			'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js',
		label: 'Underscore',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js',
		label: 'Greensock TweenMax',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.4/js/uikit.min.js',
		label: 'UIkit 2',
		type: 'js'
	},
	{
		url:
			'https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.30/js/uikit.min.js',
		label: 'UIkit 3',
		type: 'js'
	}
];
window.cssLibs = [
	{
		url:
			'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css',
		label: 'Bootstrap 3',
		type: 'css'
	},
	{
		url:
			'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css',
		label: 'Bootstrap 4β',
		type: 'css'
	},
	{
		url:
			'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/css/foundation.min.css',
		label: 'Foundation',
		type: 'css'
	},
	{
		url: 'https://semantic-ui.com/dist/semantic.min.css',
		label: 'Semantic UI',
		type: 'css'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.2/css/bulma.min.css',
		label: 'Bulma',
		type: 'css'
	},

	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/hint.css/2.5.0/hint.min.css',
		label: 'Hint.css',
		type: 'css'
	},
	{
		url:
			'https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.4/css/uikit.min.css',
		label: 'UIkit 2',
		type: 'css'
	},
	{
		url:
			'https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.30/css/uikit.min.css',
		label: 'UIkit 3',
		type: 'css'
	},
	{
		url:
			'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css',
		label: 'Animate.css',
		type: 'css'
	},
	{
		url:
			'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',
		label: 'FontAwesome',
		type: 'css'
	}
];
<commit_msg>update library list(tweenmax and reactjs)<commit_after>window.jsLibs = [
	{
		url: 'https://code.jquery.com/jquery-3.2.1.min.js',
		label: 'jQuery',
		type: 'js'
	},
	{
		url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js',
		label: 'Bootstrap 3',
		type: 'js'
	},
	{
		url: 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js',
		label: 'Bootstrap 4β',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/js/foundation.min.js',
		label: 'Foundation',
		type: 'js'
	},
	{
		url: 'https://semantic-ui.com/dist/semantic.min.js',
		label: 'Semantic UI',
		type: 'js'
	},
	{
		url: 'https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js',
		label: 'Angular',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/cjs/react.production.min.js',
		label: 'React',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js',
		label: 'React DOM',
		type: 'js'
	},
	{
		url: 'https://unpkg.com/vue@2.4.4/dist/vue.min.js',
		label: 'Vue.js',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min.js',
		label: 'Three.js',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.2/d3.min.js',
		label: 'D3',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js',
		label: 'Underscore',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/TweenMax.min.js',
		label: 'Greensock TweenMax',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.4/js/uikit.min.js',
		label: 'UIkit 2',
		type: 'js'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.30/js/uikit.min.js',
		label: 'UIkit 3',
		type: 'js'
	}
];
window.cssLibs = [
	{
		url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css',
		label: 'Bootstrap 3',
		type: 'css'
	},
	{
		url: 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css',
		label: 'Bootstrap 4β',
		type: 'css'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/css/foundation.min.css',
		label: 'Foundation',
		type: 'css'
	},
	{
		url: 'https://semantic-ui.com/dist/semantic.min.css',
		label: 'Semantic UI',
		type: 'css'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.2/css/bulma.min.css',
		label: 'Bulma',
		type: 'css'
	},

	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/hint.css/2.5.0/hint.min.css',
		label: 'Hint.css',
		type: 'css'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.4/css/uikit.min.css',
		label: 'UIkit 2',
		type: 'css'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.30/css/uikit.min.css',
		label: 'UIkit 3',
		type: 'css'
	},
	{
		url: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css',
		label: 'Animate.css',
		type: 'css'
	},
	{
		url: 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',
		label: 'FontAwesome',
		type: 'css'
	}
];
<|endoftext|>


<commit_before>import request from 'superagent';

/**
 * FullSlate API class
 * @class
 */
class FullSlate {

  /**
   * FullSlate API path
   * @member {string} API path, the `{key}` string will be replaced with
   *   with the real key on construction
   */
  path = 'https://{key}.fullslate.com/api/'

  /**
   * @constructs FullSlate
   * @param {object} options FullSlate API options
   * @param {string} options.key FullSlate key (e.g {key}.fullslate.com)
   * @param {string} [options.token] FullSlate API token
   * @throws Will throw error if the FullSlate key isn't defined
   */
  constructor(options = {}) {
    const { key, token } = options;

    if (typeof key === 'undefined') {
      throw new Error('No key defined');
    }

    this.key = key;
    this.token = token;

    // Build new path based off of `key`
    this.path = this.path.replace('{key}', this.key);
  }

  /**
   * Employees resource
   * @param {number} [id] Employee ID to limit details to a single
   *   employee
   * @throws Will throw error if employee id is not a number
   * @return {Promise.<(Array|Object), Error>} Resolve with the API
   *   response: if `id` provided, an object of the employee will be
   *   returned, if no `id` provided, an array of all employees will
   *   be returned. Reject with request or API error.
   */
  employees(id) {
    if (typeof id !== 'undefined' && !Number.isInteger(id)) {
      throw new Error('Invalid employee id');
    }

    return new Promise((resolve, reject) => {
      let endpoint = 'employees';

      // Update endpoint if `id` is provided
      if (id) {
        endpoint = endpoint + `/${id}`;
      }

      request.get(this.path + endpoint)
        .query({
          'auth': this.token
        })
        .end((err, res) => {
          if (res.body.failure) {
            reject(res.body);
          } else if (err) {
            reject(err);
          }

          resolve(res.body);
        });
    });
  }

  /**
   * Services resource
   * @param {number} [id] Service ID to limit details to a single service
   * @throws Will throw error if service id is not a number
   * @return {Promise.<(Array|Object), Error>} Resolve with the API
   *   response: if `id` provided, an object of the service will be
   *   returned, if no `id` provided, an array of all services will
   *   be returned. Reject with request or API error.
   */
  services(id) {
    if (typeof id !== 'undefined' && !Number.isInteger(id)) {
      throw new Error('Invalid service id');
    }

    return new Promise((resolve, reject) => {
      let endpoint = 'services';

      // Update endpoint if `id` is provided
      if (id) {
        endpoint = endpoint + `/${id}`;
      }

      request.get(this.path + endpoint)
        .query({
          'auth': this.token
        })
        .end((err, res) => {
          if (res.body.failure) {
            reject(res.body);
          } else if (err) {
            reject(err);
          }

          resolve(res.body);
        });
    });
  }

  /**
   * Openings resource
   * @param {number|number[]} services A single service id or an array
   *   of service ids
   * @param {object} [options] Optional opening options
   * @param {string} [options.before] Openings before this date (RFC 3339
   *   formatted date)
   * @param {string} [options.after] Openings after this date (RFC 3339
   *   formatted date)
   * @param {string} [options.window] Valid window values are 'week' or 'month'
   * @throws Error will be thrown if `services` is invalid or missing
   * @return {Promise.<Object, (Object|Error)>} Resolve with the API response
   *   Reject with request or API error.
   */
  openings(services, options = {}) {

    // Validate `service` parameter
    if (Array.isArray(services)) {
      services.forEach((service) => {
        if (!Number.isInteger(service)) {
          throw new Error('Invalid services specified');
        }
      });
    } else if (!Number.isInteger(services)) {
      throw new Error('Invalid services specified');
    }

    return new Promise((resolve, reject) => {
      const endpoint = 'openings';
      let params = {
        auth: this.token,
        ...options
      };

      // Build services array
      params['services[]'] = Array.isArray(services)
        ? services.join(',')
        : services;

      request.get(this.path + endpoint)
        .query(params)
        .end((err, res) => {
          if (res.body.failure) {
            reject(res.body);
          } else if (err) {
            reject(err);
          }

          resolve(res.body);
        });
    });
  }

};

export default FullSlate;
<commit_msg>Update resouces doc return statements<commit_after>import request from 'superagent';

/**
 * FullSlate API class
 * @class
 */
class FullSlate {

  /**
   * FullSlate API path
   * @member {string} API path, the `{key}` string will be replaced with
   *   with the real key on construction
   */
  path = 'https://{key}.fullslate.com/api/'

  /**
   * @constructs FullSlate
   * @param {object} options FullSlate API options
   * @param {string} options.key FullSlate key (e.g {key}.fullslate.com)
   * @param {string} [options.token] FullSlate API token
   * @throws Will throw error if the FullSlate key isn't defined
   */
  constructor(options = {}) {
    const { key, token } = options;

    if (typeof key === 'undefined') {
      throw new Error('No key defined');
    }

    this.key = key;
    this.token = token;

    // Build new path based off of `key`
    this.path = this.path.replace('{key}', this.key);
  }

  /**
   * Employees resource
   * @param {number} [id] Employee ID to limit details to a single
   *   employee
   * @throws Will throw error if employee id is not a number
   * @return {Promise.<(Array|Object), (Object|Error)>} Resolve with the
   *   API response: if `id` provided, an object of the employee will be
   *   returned, if no `id` provided, an array of all employees will
   *   be returned. Reject with request or API error.
   */
  employees(id) {
    if (typeof id !== 'undefined' && !Number.isInteger(id)) {
      throw new Error('Invalid employee id');
    }

    return new Promise((resolve, reject) => {
      let endpoint = 'employees';

      // Update endpoint if `id` is provided
      if (id) {
        endpoint = endpoint + `/${id}`;
      }

      request.get(this.path + endpoint)
        .query({
          'auth': this.token
        })
        .end((err, res) => {
          if (res.body.failure) {
            reject(res.body);
          } else if (err) {
            reject(err);
          }

          resolve(res.body);
        });
    });
  }

  /**
   * Services resource
   * @param {number} [id] Service ID to limit details to a single service
   * @throws Will throw error if service id is not a number
   * @return {Promise.<(Array|Object), (Object|Error)>} Resolve with the
   *   API response: if `id` provided, an object of the service will be
   *   returned, if no `id` provided, an array of all services will
   *   be returned. Reject with request or API error.
   */
  services(id) {
    if (typeof id !== 'undefined' && !Number.isInteger(id)) {
      throw new Error('Invalid service id');
    }

    return new Promise((resolve, reject) => {
      let endpoint = 'services';

      // Update endpoint if `id` is provided
      if (id) {
        endpoint = endpoint + `/${id}`;
      }

      request.get(this.path + endpoint)
        .query({
          'auth': this.token
        })
        .end((err, res) => {
          if (res.body.failure) {
            reject(res.body);
          } else if (err) {
            reject(err);
          }

          resolve(res.body);
        });
    });
  }

  /**
   * Openings resource
   * @param {number|number[]} services A single service id or an array
   *   of service ids
   * @param {object} [options] Optional opening options
   * @param {string} [options.before] Openings before this date (RFC 3339
   *   formatted date)
   * @param {string} [options.after] Openings after this date (RFC 3339
   *   formatted date)
   * @param {string} [options.window] Valid window values are 'week' or 'month'
   * @throws Error will be thrown if `services` is invalid or missing
   * @return {Promise.<Object, (Object|Error)>} Resolve with the API response
   *   Reject with request or API error.
   */
  openings(services, options = {}) {

    // Validate `service` parameter
    if (Array.isArray(services)) {
      services.forEach((service) => {
        if (!Number.isInteger(service)) {
          throw new Error('Invalid services specified');
        }
      });
    } else if (!Number.isInteger(services)) {
      throw new Error('Invalid services specified');
    }

    return new Promise((resolve, reject) => {
      const endpoint = 'openings';
      let params = {
        auth: this.token,
        ...options
      };

      // Build services array
      params['services[]'] = Array.isArray(services)
        ? services.join(',')
        : services;

      request.get(this.path + endpoint)
        .query(params)
        .end((err, res) => {
          if (res.body.failure) {
            reject(res.body);
          } else if (err) {
            reject(err);
          }

          resolve(res.body);
        });
    });
  }

};

export default FullSlate;
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');

const Board = require('../board/board.model');
const mockBoard = require('./mock.json');
const computeResult = require('../../../lib/game');

const controller = {};

controller.getBoard = (req, res) => {
  if (/^[0-9a-fA-F]{24}$/.test(req.query.board_id)){
    Board.findById(req.query.board_id)
    .then((board) => {
      // check timer expires or not
      let current = new Date();
      if (current.getTime() > board._nextRoundDeadline.getTime()){
        // 1) update next move
        board.players = board.players.map((player) => {
          return {
            id: player.id,
            name: player.name,
            x: (player._nextMove && player._nextMove.x) || player.x,
            y: (player._nextMove && player._nextMove.y) || player.y,
          };
        });

        // 2) compute Result
        let tidyBoard = board.toTidyObject();
        let result = computeResult(tidyBoard);

        // 3) write back to DB
        return board.nextRound(result.players, result.status)
        .then(() => Board.findById(req.query.board_id));
      }
      return board;
    })
    .then((result) => {
      if (result) {
        result = result.toTidyObject();
        return res.status(200).json(result);
      } else {
        return res.status(200).json(mockBoard);
      }
    });
  } else {
    return res.status(200).json(mockBoard);
  }
};

controller.nextMove = (req, res) => {
  assert(req.body.userId, 'missing userId');
  assert(/^[0-9a-fA-F]{24}$/.test(req.body.userId), 'invalid userId');
  assert(req.body.boardId, 'missing boardId');
  assert(/^[0-9a-fA-F]{24}$/.test(req.body.boardId), 'invalid boardId');
  assert(req.body.nextRound, 'missing nextRound');
  assert(req.body.nextMove, 'missing nextMove');
  assert(req.body.nextMove.x, 'missing nextMove.x');
  assert(req.body.nextMove.y, 'missing nextMove.y');

  Board.updateNextMove(req.body.boardId, req.body.userId,
    req.body.nextRound, req.body.nextMove.x, req.body.nextMove.y)
  .then((result) => {
    if (result && 1 === result.nModified) {
      return res.sendStatus(204);
    } else {
      return res.status(400).send('something wrong happens...');
    }
  });
};

module.exports = exports = controller;<commit_msg>Workaround API<commit_after>'use strict';

const assert = require('assert');

const Board = require('../board/board.model');
const mockBoard = require('./mock.json');
const computeResult = require('../../../lib/game');

const controller = {};

controller.getBoard = (req, res) => {
  if (/^[0-9a-fA-F]{24}$/.test(req.query.board_id)){
    Board.findById(req.query.board_id)
    .then((board) => {
      // check timer expires or not
      let current = new Date();
      if (current.getTime() > board._nextRoundDeadline.getTime()){
        // 1) update next move
        board.players = board.players.map((player) => {
          return {
            id: player.id,
            name: player.name,
            x: (player._nextMove && player._nextMove.x) || player.x,
            y: (player._nextMove && player._nextMove.y) || player.y,
          };
        });

        // 2) compute Result
        let tidyBoard = board.toTidyObject();
        let result = computeResult(tidyBoard);

        // 3) write back to DB
        return board.nextRound(result.players, result.status)
        .then(() => Board.findById(req.query.board_id));
      }
      return board;
    })
    .then((result) => {
      if (result) {
        result = result.toTidyObject();
        return res.status(200).json(result);
      } else {
        return res.status(200).json(mockBoard);
      }
    });
  } else {
    return res.status(200).json(mockBoard);
  }
};

controller.nextMove = (req, res) => {
  assert(req.body.userId, 'missing userId');
  assert(/^[0-9a-fA-F]{24}$/.test(req.body.userId), 'invalid userId');
  assert(req.body.boardId, 'missing boardId');
  assert(/^[0-9a-fA-F]{24}$/.test(req.body.boardId), 'invalid boardId');
  assert(req.body.nextRound, 'missing nextRound');
  assert(req.body.nextMove, 'missing nextMove');
  assert(req.body.nextMoveX, 'missing nextMoveX');
  assert(req.body.nextMoveY, 'missing nextMoveY');

  Board.updateNextMove(req.body.boardId, req.body.userId,
    req.body.nextRound, req.body.nextMoveX, req.body.nextMoveY)
  .then((result) => {
    if (result && 1 === result.nModified) {
      return res.sendStatus(204);
    } else {
      return res.status(400).send('something wrong happens...');
    }
  });
};

module.exports = exports = controller;<|endoftext|>


<commit_before>const assert = require('assert');
const establishedDatabase = require('src/database/database');

class UserRepository {
  constructor(database) {
    this.database = database || establishedDatabase;
    this.queries = {
      read: 'select * from user where lower(user_name) = lower(?)',
      create: 'insert into user (user_name) values (?)',
      change: 'update user set password = ? where user_name = ?',
      retrieveHash: 'select * from user where user_name = ?',
      getAdminStateByUser: 'select admin from user where user_name = ?',
      link: 'update user set plex_userid = ? where user_name = ?'
    };
}

/**
* Create a user in a database.
* @param {User} user the user you want to create
* @returns {Promise}
*/
create(user) {
  return this.database.get(this.queries.read, user.username)
    .then(() => this.database.run(this.queries.create, user.username))
    .catch((error) => {
      if (error.name === 'AssertionError' || error.message.endsWith('user_name')) {
         throw new Error('That username is already registered');
      }
      throw Error(error)
    });
}

/**
* Retrieve a password from a database.
* @param {User} user the user you want to retrieve the password
* @returns {Promise}
*/
retrieveHash(user) {
  console.log('retrieving hash for user', user)
  return this.database.get(this.queries.retrieveHash, user.username)
    .then(row => {
      assert(row, 'The user does not exist.');
      return row.password;
    })
    .catch(err => { console.log(error); throw new Error('Unable to find your user.'); })
}

/**
* Change a user's password in a database.
* @param {User} user the user you want to create
* @param {String} password the new password you want to change
* @returns {Promise}
*/
changePassword(user, password) {
  return this.database.run(this.queries.change, [password, user.username])
}

/**
* Link plex userid with seasoned user
* @param {User} user the user you want to lunk plex userid with
* @param {Number} plexUserID plex unique id
* @returns {Promsie}
*/
linkPlexUserId(username, plexUserID) {
  return new Promise((resolve, reject) => {
    this.database.run(this.queries.link, [plexUserID, username])
      .then(row => resolve(row))
      .catch(error => {
        // TODO log this unknown db error
        console.log('db error', error)

        reject({
          status: 500,
          message: 'An unexpected error occured while linking plex and seasoned accounts',
          source: 'seasoned database'
        })
      })
  })
}

checkAdmin(user) {
  return this.database.get(this.queries.getAdminStateByUser, user.username).then((row) => {
      return row.admin;
    });
  }
}

module.exports = UserRepository;
<commit_msg>Removed unused console log<commit_after>const assert = require('assert');
const establishedDatabase = require('src/database/database');

class UserRepository {
  constructor(database) {
    this.database = database || establishedDatabase;
    this.queries = {
      read: 'select * from user where lower(user_name) = lower(?)',
      create: 'insert into user (user_name) values (?)',
      change: 'update user set password = ? where user_name = ?',
      retrieveHash: 'select * from user where user_name = ?',
      getAdminStateByUser: 'select admin from user where user_name = ?',
      link: 'update user set plex_userid = ? where user_name = ?'
    };
}

/**
* Create a user in a database.
* @param {User} user the user you want to create
* @returns {Promise}
*/
create(user) {
  return this.database.get(this.queries.read, user.username)
    .then(() => this.database.run(this.queries.create, user.username))
    .catch((error) => {
      if (error.name === 'AssertionError' || error.message.endsWith('user_name')) {
         throw new Error('That username is already registered');
      }
      throw Error(error)
    });
}

/**
* Retrieve a password from a database.
* @param {User} user the user you want to retrieve the password
* @returns {Promise}
*/
retrieveHash(user) {
  return this.database.get(this.queries.retrieveHash, user.username)
    .then(row => {
      assert(row, 'The user does not exist.');
      return row.password;
    })
    .catch(err => { console.log(error); throw new Error('Unable to find your user.'); })
}

/**
* Change a user's password in a database.
* @param {User} user the user you want to create
* @param {String} password the new password you want to change
* @returns {Promise}
*/
changePassword(user, password) {
  return this.database.run(this.queries.change, [password, user.username])
}

/**
* Link plex userid with seasoned user
* @param {User} user the user you want to lunk plex userid with
* @param {Number} plexUserID plex unique id
* @returns {Promsie}
*/
linkPlexUserId(username, plexUserID) {
  return new Promise((resolve, reject) => {
    this.database.run(this.queries.link, [plexUserID, username])
      .then(row => resolve(row))
      .catch(error => {
        // TODO log this unknown db error
        console.log('db error', error)

        reject({
          status: 500,
          message: 'An unexpected error occured while linking plex and seasoned accounts',
          source: 'seasoned database'
        })
      })
  })
}

checkAdmin(user) {
  return this.database.get(this.queries.getAdminStateByUser, user.username).then((row) => {
      return row.admin;
    });
  }
}

module.exports = UserRepository;
<|endoftext|>


<commit_before>var test = require('tape');

test('cflow sequential', function (t) {
	t.equal("ABC!!!", "ABC!!!");
	t.end();
});	<commit_msg>change to tape<commit_after>var test = require('tape');

test('cflow sequential', function (t) {
	t.equal("ABC!!!", "ABC!!!");
	t.end();
});

function slow(value, callback){
	setTimeout(function(){
		callback(value);
	}, 200)
}

function slow2(value, value2, callback){
	setTimeout(function(){
		callback(value, value2);
	}, 300)
}
	<|endoftext|>