<commit_before>module.exports = function() {
  const fs = require('fs');
  const request = require('request');
  const getJson = require('./getjson.js');
  const scrape = require('./scrape.js');
  const clientid = require('./clientid.js');

  const points = require('./public/points.json');
  const americas = require('./public/americas.json');
  const china = require('./public/china.json');
  const europe = require('./public/europe.json');
  const se_asia = require('./public/se_asia.json');

  // twitch api login
  const login = {
    url: 'https://api.twitch.tv/kraken/streams?limit=100&offset=0&game=DOTA+2',
    headers: {
      "Client-ID": clientid.clientId
    }
  };

  class Streamer {
    constructor(name, rank, mmr, points, url, img, lang, card) {
      this.name = name;
      this.rank = rank;
      this.mmr = mmr;
      this.points = points;
      this.url = url;
      this.img = img;
      this.lang = lang;
      this.card = card;
    }
  }

  let streamers = []; // list of top tier players, confusingly called streamers

  function getRegion(region) {
    for (let i=0; i < region.leaderboard.length; i++) {
      let streamer = new Streamer(region.leaderboard[i].name, i+1, region.leaderboard[i].solo_mmr);
      streamers.push(streamer);
      }
    }

  getRegion(americas);
  getRegion(china);
  getRegion(europe);
  getRegion(se_asia);

  let playerMap = new Map(); // player map where the value is the index of the players

  for (let i=0; i < streamers.length; i++) {
    playerMap.set(streamers[i].name, i);
  }

  function getPoints() {
    for (let i=0; i < points.length; i++) {
      if (playerMap.has(points[i].name) === true) {
        streamers[playerMap.get(points[i].name)].points = points[i].points;
      } else {
        let streamer = new Streamer(points[i].name, null, points[i].points);
        streamers.push(streamer);
        playerMap.set(points[i].name, streamers.length -1);
      }
    }
  }

  getPoints();

  let filteredPlayers = []; // streamers list reduced to
  let twitch = [];  // list from Twitch JSON request
  let cards = '';
  // Twitch API call
  request(login, function(error, response, body) {
  // nomenclature is a little weird. what does filterList mean vs reduceList?
    function filterList(arr) {
      for (let i=0; i < arr.length; i++) {
        if (playerMap.has(arr[i].name) === true) {
          streamers[playerMap.get(arr[i].name)].url = arr[i].url;
          streamers[playerMap.get(arr[i].name)].img = arr[i].img;
          streamers[playerMap.get(arr[i].name)].lang = arr[i].lang;
        }
      }
      reduceList(streamers);
      for (let p in filteredPlayers) {
        if (filteredPlayers[p].rank === undefined) {
          filteredPlayers[p].rank = 0;
        }
        if (filteredPlayers[p].points === undefined) {
          filteredPlayers[p].points = 0;
        }
        filteredPlayers[p].card = `

${filteredPlayers[p].name}

                                        Rank ${filteredPlayers[p].rank}

                                        ${filteredPlayers[p].points} Qualifying Points

\n`;
      }
      fs.writeFile('./public/dreamstream.json', JSON.stringify(filteredPlayers), 'UTF-8', (err) => {
        if (err) throw err;
      });
      for (let c in filteredPlayers) {
        cards = cards + filteredPlayers[c].card;
      }
      let cardsJson = { text: cards };

      fs.writeFile('./public/cards.json', JSON.stringify(cardsJson), 'UTF-8', (err) => {
        if (err) throw err;
      });
    }
  // says if there is no twitch url then don't bother including it on the list
    function reduceList(arr) {
      for (let i=0; i < arr.length; i++) {
        if (arr[i].url !== undefined) {
          filteredPlayers.push(arr[i]);
        }
      }
    }

    if (!error && response.statusCode == 200) {
      let live = JSON.parse(body);
      for (let i=0; i < live.streams.length; i++) {
        let stream = new Streamer(live.streams[i].channel.display_name, null, null, null, live.streams[i].channel.url, live.streams[i].channel.logo, live.streams[i].channel.broadcaster_language);
        twitch.push(stream);
      }
      nameSwitch();
      filterList(twitch);
    } else {
      console.log('Error: ' + error + ' Status code: ' + response.statusCode);
    }
  });

  // on left: twitch name, on right: valve name
  function nameSwitch() {
    for (let i=0; i < twitch.length; i++) {
      let name = twitch[i].name;
      switch(name) {
        case "ABFnggshka": twitch[i].name = "Fng";
        break;
        case "ALOHADANCETV": twitch[i].name = "ALOHADANCE";
        break;
        case "Attackerdota": twitch[i].name = "!Attacker";
        break;
        case "Arteezy": twitch[i].name = "rtz";
        break;
        case "BananaSlamJamma": twitch[i].name = "BSJ";
        break;
        case "BlackDotATV": twitch[i].name = "Black^";
        break;
        case "BlitzDotA": twitch[i].name = "Blitz";
        break;
        case "BloodyNine_": twitch[i].name = "Bloody Nine";
        break;
        case "bryle_": twitch[i].name = "Bryle";
        break;
        case "canceldota": twitch[i].name = "canceL^^";
        break;
        case "CCnCDotA2": twitch[i].name = "CCnC";
        break;
        case "Cr1tdota": twitch[i].name = "Cr1t-";
        break;
        case "dotademon": twitch[i].name = "DeMoN";
        break;
        case "DotACapitalist": twitch[i].name = "Capitalist";
        break;
        case "EternaLEnVyy": twitch[i].name = "EternaLEnVy";
        break;
        case "FearDarkness": twitch[i].name = "Fear";
        break;
        case "febbydoto": twitch[i].name = "Febby";
        break;
        case "forev": twitch[i].name = "FoREv";
        break;
        case "fozzy4444": twitch[i].name = "tv/fozzy4444";
        break;
        case "GGwpLanaya": twitch[i].name = "GGwpLanaya Ift";
        break;
        case "Illidanstrdoto": twitch[i].name = "Illidan";
        break;
        case "inK_Dota": twitch[i].name = "@inKDota";
        break;
        case "lanarinho": twitch[i].name = "Larano";
        break;
        case "midone": twitch[i].name = "MidOne";
        break;
        case "Miracle_doto": twitch[i].name = "Miracle-";
        break;
        case "MiSeRyTheSLAYER": twitch[i].name = "MiSeRy";
        break;
        case "MooDota2": twitch[i].name = "Moo";
        break;
        case "Moonmeander": twitch[i].name = "MoonMayMays";
        break;
        case "ramzesdoto": twitch[i].name = "RAMZES666";
        break;
        case "shuma4": twitch[i].name = "ShuMa";
        break;
        case "Sing_sing": twitch[i].name = "SingSing";
        break;
        case "slahserDota": twitch[i].name = "slahser";
        break;
        case "SumaiLDoto": twitch[i].name = "SumaiL";
        break;
        case "Sovereigndota": twitch[i].name = "Sovereign";
        break;
        case "universedota": twitch[i].name = "Universe";
        break;
        case "w33haa": twitch[i].name = "w33";
        break;
        case "WagamamaTV": twitch[i].name = "Wagamama";
        break;
        case "YapzOrdota": twitch[i].name = "YapzOr";
        break;
        default: name = twitch[i].name;
        break;
      }
    }
  }
}
<commit_msg>Updated name switch function<commit_after>module.exports = function() {
  const fs = require('fs');
  const request = require('request');
  const getJson = require('./getjson.js');
  const scrape = require('./scrape.js');
  const clientid = require('./clientid.js');

  const points = require('./public/points.json');
  const americas = require('./public/americas.json');
  const china = require('./public/china.json');
  const europe = require('./public/europe.json');
  const se_asia = require('./public/se_asia.json');

  // twitch api login
  const login = {
    url: 'https://api.twitch.tv/kraken/streams?limit=100&offset=0&game=DOTA+2',
    headers: {
      "Client-ID": clientid.clientId
    }
  };

  class Streamer {
    constructor(name, rank, mmr, points, url, img, lang, card) {
      this.name = name;
      this.rank = rank;
      this.mmr = mmr;
      this.points = points;
      this.url = url;
      this.img = img;
      this.lang = lang;
      this.card = card;
    }
  }

  let streamers = []; // list of top tier players, confusingly called streamers

  function getRegion(region) {
    for (let i=0; i < region.leaderboard.length; i++) {
      let streamer = new Streamer(region.leaderboard[i].name, i+1, region.leaderboard[i].solo_mmr);
      streamers.push(streamer);
      }
    }

  getRegion(americas);
  getRegion(china);
  getRegion(europe);
  getRegion(se_asia);

  let playerMap = new Map(); // player map where the value is the index of the players

  for (let i=0; i < streamers.length; i++) {
    playerMap.set(streamers[i].name, i);
  }

  function getPoints() {
    for (let i=0; i < points.length; i++) {
      if (playerMap.has(points[i].name) === true) {
        streamers[playerMap.get(points[i].name)].points = points[i].points;
      } else {
        let streamer = new Streamer(points[i].name, null, points[i].points);
        streamers.push(streamer);
        playerMap.set(points[i].name, streamers.length -1);
      }
    }
  }

  getPoints();

  let filteredPlayers = []; // streamers list reduced to
  let twitch = [];  // list from Twitch JSON request
  let cards = '';
  // Twitch API call
  request(login, function(error, response, body) {
  // nomenclature is a little weird. what does filterList mean vs reduceList?
    function filterList(arr) {
      for (let i=0; i < arr.length; i++) {
        if (playerMap.has(arr[i].name) === true) {
          streamers[playerMap.get(arr[i].name)].url = arr[i].url;
          streamers[playerMap.get(arr[i].name)].img = arr[i].img;
          streamers[playerMap.get(arr[i].name)].lang = arr[i].lang;
        }
      }
      reduceList(streamers);
      for (let p in filteredPlayers) {
        if (filteredPlayers[p].rank === undefined) {
          filteredPlayers[p].rank = 0;
        }
        if (filteredPlayers[p].points === undefined) {
          filteredPlayers[p].points = 0;
        }
        filteredPlayers[p].card = `

${filteredPlayers[p].name}

                                        Rank ${filteredPlayers[p].rank}

                                        ${filteredPlayers[p].points} Qualifying Points

\n`;
      }
      fs.writeFile('./public/dreamstream.json', JSON.stringify(filteredPlayers), 'UTF-8', (err) => {
        if (err) throw err;
      });
      for (let c in filteredPlayers) {
        cards = cards + filteredPlayers[c].card;
      }
      let cardsJson = { text: cards };

      fs.writeFile('./public/cards.json', JSON.stringify(cardsJson), 'UTF-8', (err) => {
        if (err) throw err;
      });
    }
  // says if there is no twitch url then don't bother including it on the list
    function reduceList(arr) {
      for (let i=0; i < arr.length; i++) {
        if (arr[i].url !== undefined) {
          filteredPlayers.push(arr[i]);
        }
      }
    }

    if (!error && response.statusCode == 200) {
      let live = JSON.parse(body);
      for (let i=0; i < live.streams.length; i++) {
        let stream = new Streamer(live.streams[i].channel.display_name, null, null, null, live.streams[i].channel.url, live.streams[i].channel.logo, live.streams[i].channel.broadcaster_language);
        twitch.push(stream);
      }
      nameSwitch();
      filterList(twitch);
    } else {
      console.log('Error: ' + error + ' Status code: ' + response.statusCode);
    }
  });

  // on left: twitch name, on right: valve name
  function nameSwitch() {
    for (let i=0; i < twitch.length; i++) {
      let name = twitch[i].name;
      switch(name) {
        case "7ckngMad": twitch[i].name = "7Mad-";
        break;
        case "ABFnggshka": twitch[i].name = "Fng";
        break;
        case "ALOHADANCETV": twitch[i].name = "ALOHADANCE";
        break;
        case "Attackerdota": twitch[i].name = "!Attacker";
        break;
        case "Arteezy": twitch[i].name = "rtz";
        break;
        case "BananaSlamJamma": twitch[i].name = "BSJ";
        break;
        case "BlackDotATV": twitch[i].name = "Black^";
        break;
        case "BlitzDotA": twitch[i].name = "Blitz";
        break;
        case "BloodyNine_": twitch[i].name = "Bloody Nine";
        break;
        case "bryle_": twitch[i].name = "Bryle";
        break;
        case "canceldota": twitch[i].name = "canceL^^";
        break;
        case "CCnCDotA2": twitch[i].name = "CCnC";
        break;
        case "Cr1tdota": twitch[i].name = "Cr1t-";
        break;
        case "dotademon": twitch[i].name = "DeMoN";
        break;
        case "DotACapitalist": twitch[i].name = "Capitalist";
        break;
        case "EternaLEnVyy": twitch[i].name = "EternaLEnVy";
        break;
        case "FearDarkness": twitch[i].name = "Fear";
        break;
        case "febbydoto": twitch[i].name = "Febby";
        break;
        case "forev": twitch[i].name = "FoREv";
        break;
        case "fozzy4444": twitch[i].name = "tv/fozzy4444";
        break;
        case "GGwpLanaya": twitch[i].name = "GGwpLanaya Ift";
        break;
        case "Gorgcc": twitch[i].name = "Gorgc";
        break;
        case "Illidanstrdoto": twitch[i].name = "Illidan";
        break;
        case "inK_Dota": twitch[i].name = "@inKDota";
        break;
        case "lanarinho": twitch[i].name = "Larano";
        break;
        case "midone": twitch[i].name = "MidOne";
        break;
        case "Miracle_doto": twitch[i].name = "Miracle-";
        break;
        case "MiSeRyTheSLAYER": twitch[i].name = "MiSeRy";
        break;
        case "MooDota2": twitch[i].name = "Moo";
        break;
        case "Moonmeander": twitch[i].name = "MoonMayMays";
        break;
        case "qSnake": twitch[i].name = " ุqSnake";
        break;
        case "ramzesdoto": twitch[i].name = "RAMZES666";
        break;
        case "shuma4": twitch[i].name = "ShuMa";
        break;
        case "Sing_sing": twitch[i].name = "SingSing";
        break;
        case "slahserDota": twitch[i].name = "slahser";
        break;
        case "smashdota": twitch[i].name = "SmAsH";
        break;
        case "SneykingDota": twitch[i].name = "Sneyking";
        break;
        case "SumaiLDoto": twitch[i].name = "SumaiL";
        break;
        case "Sovereigndota": twitch[i].name = "Sovereign";
        break;
        case "universedota": twitch[i].name = "Universe";
        break;
        case "vanNDota": twitch[i].name = "vanN";
        break;
        case "w33haa": twitch[i].name = "w33";
        break;
        case "WagamamaTV": twitch[i].name = "Wagamama";
        break;
        case "YapzOrdota": twitch[i].name = "YapzOr";
        break;
        default: name = twitch[i].name;
        break;
      }
    }
  }
}
<|endoftext|>


<commit_before>/* eslint-disable no-undef */
function getOptions () {
  return Object.assign({}, {
    treeData: [],
    selectId: 'tree_type_' + this._uid
  }, this.translations, this.dataOptions)
}

function initTreeType () {
  let self = this
  try {
    $('#id_tree_type_' + self._uid).TreeType(self.options)
  } catch (ex) {}
}

function getTranslations () {
  return {
    modalTitle: this.$t('tree.modalTitle'),
    modalResetLabel: this.$t('tree.modalResetLabel'),
    modalCancelLabel: this.$t('tree.modalCancelLabel'),
    modalOkLabel: this.$t('tree.modalOkLabel'),
    textUnmatched: this.$t('tree.textUnmatched'),
    textSelectHierarchy: this.$t('tree.textSelectHierarchy'),
    noResults: this.$t('label.selectNoResults'),
    textSelected: this.$t('tree.textSelected'),
    searchPlaceholder: this.$t('tree.searchPlaceholder')
  }
}

function updateTreeData (treeData) {
  try {
    $('#id_tree_type_' + this._uid).TreeType('treeData', treeData)
    $('#tree_type_' + this._uid).trigger('update')
  } catch (ex) {}
}

export default {
  methods: {
    getOptions,
    initTreeType,
    getTranslations,
    updateTreeData
  }
}
<commit_msg>Improvement(TreeType): Update displayed info<commit_after>/* eslint-disable no-undef */
function getOptions () {
  return Object.assign({}, {
    treeData: [],
    selectId: 'tree_type_' + this._uid
  }, this.translations, this.dataOptions)
}

function initTreeType () {
  let self = this
  try {
    $('#id_tree_type_' + self._uid).TreeType(self.options)
  } catch (ex) {}
}

function getTranslations () {
  return {
    modalTitle: this.$t('tree.modalTitle'),
    modalResetLabel: this.$t('tree.modalResetLabel'),
    modalCancelLabel: this.$t('tree.modalCancelLabel'),
    modalOkLabel: this.$t('tree.modalOkLabel'),
    textUnmatched: this.$t('tree.textUnmatched'),
    textSelectHierarchy: this.$t('tree.textSelectHierarchy'),
    noResults: this.$t('label.selectNoResults'),
    textSelected: this.$t('tree.textSelected'),
    searchPlaceholder: this.$t('tree.searchPlaceholder')
  }
}

function updateTreeData (treeData) {
  try {
    $('#id_tree_type_' + this._uid).TreeType('treeData', treeData)
    $('#tree_type_' + this._uid).trigger('update')
    console.log($('#tree_type_' + this._uid))
  } catch (ex) {}
}

export default {
  methods: {
    getOptions,
    initTreeType,
    getTranslations,
    updateTreeData
  }
}
<|endoftext|>


<commit_before>/**
 * tab-content.js
 */

import {
  getType, isObjectNotEmpty, isString, logErr, setElementDataset, throwErr,
} from "./common.js";
import {
  getTab, updateTab,
} from "./browser.js";
import {
  closeTabs, muteTabs,
} from "./browser-tabs.js";
import {
  getSidebarTab, getSidebarTabId,
} from "./util.js";

/* api */
const {i18n} = browser;

/* constants */
import {
  CLASS_TAB_AUDIO, CLASS_TAB_CLOSE, CLASS_TAB_CONTENT, CLASS_TAB_ICON,
  CLASS_TAB_TITLE, HIGHLIGHTED, IDENTIFIED, TAB_CLOSE, TAB_MUTE,
  TAB_MUTE_UNMUTE, TABS_CLOSE, TABS_MUTE, TABS_MUTE_UNMUTE, URL_AUDIO_MUTED,
  URL_AUDIO_PLAYING, URL_FAVICON_DEFAULT, URL_LOADING_THROBBER,
} from "./constant.js";

/* favicon */
export const favicon = new Map([
  [
    "https://abs.twimg.com/favicons/favicon.ico",
    "../img/twitter-logo-blue.svg",
  ],
  [
    "https://abs.twimg.com/icons/apple-touch-icon-192x192.png",
    "../img/twitter-logo-blue.svg",
  ],
  [
    "chrome://browser/skin/customize.svg",
    "../img/customize-favicon.svg",
  ],
  [
    "chrome://browser/skin/settings.svg",
    "../img/options-favicon.svg",
  ],
  [
    "chrome://mozapps/skin/extensions/extensionGeneric-16.svg",
    "../img/addons-favicon.svg",
  ],
]);

/* contextual identities icon name */
export const contextualIdentitiesIconName = new Set([
  "briefcase", "cart", "chill", "dollar", "fingerprint", "food", "fruit",
  "gift", "pet", "tree", "vacation",
]);

/* contextual identities icon color */
export const contextualIdentitiesIconColor = new Set([
  "blue", "purple", "pink", "red", "orange", "yellow", "green",
  "turquoise",
]);

/**
 * tab icon fallback
 * @param {Object} evt - event
 * @returns {boolean} - false
 */
export const tabIconFallback = evt => {
  if (isObjectNotEmpty(evt)) {
    const {target, type} = evt;
    if (type === "error" && target && isString(target.src)) {
      target.src = URL_FAVICON_DEFAULT;
    }
  }
  return false;
};

/**
 * add tab icon error listener
 * @param {Object} elm - img element
 * @returns {void}
 */
export const addTabIconErrorListener = async elm => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img") {
    elm.addEventListener("error", tabIconFallback);
  }
};

/**
 * set tab icon
 * @param {Object} elm - img element
 * @param {Object} info - tab info
 * @returns {void}
 */
export const setTabIcon = async (elm, info) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img" &&
      isObjectNotEmpty(info)) {
    const {favIconUrl, status, title, url} = info;
    if (status === "loading") {
      try {
        if (isString(title) && isString(url)) {
          const {hostname} = new URL(url);
          const connecting =
            title.endsWith("/") && hostname.endsWith(title.replace(/\/$/, ""));
          if (connecting) {
            elm.dataset.connecting = url;
          } else if (elm.dataset.connecting) {
            const {stroke} = window.getComputedStyle(elm);
            elm.style.fill = stroke;
            elm.dataset.connecting = "";
          }
        } else {
          elm.dataset.connecting = url;
        }
      } catch (e) {
        logErr(e);
        elm.dataset.connecting = url;
      }
      elm.src = URL_LOADING_THROBBER;
    } else {
      elm.dataset.connecting = "";
      if (favIconUrl) {
        elm.src = favicon.get(favIconUrl) || favIconUrl;
      } else {
        elm.src = URL_FAVICON_DEFAULT;
      }
      elm.style.fill = "";
    }
  }
};

/* tab content */
/**
 * set tab content
 * @param {Object} tab - tab element
 * @param {Object} tabsTab - tabs.Tab
 * @returns {void}
 */
export const setTabContent = async (tab, tabsTab) => {
  if (tab && tab.nodeType === Node.ELEMENT_NODE && isObjectNotEmpty(tabsTab)) {
    const {favIconUrl, status, title, url} = tabsTab;
    const tabContent = tab.querySelector(`.${CLASS_TAB_CONTENT}`);
    const tabTitle = tab.querySelector(`.${CLASS_TAB_TITLE}`);
    const tabIcon = tab.querySelector(`.${CLASS_TAB_ICON}`);
    tabContent.title = title;
    tabTitle.textContent = title;
    await setTabIcon(tabIcon, {favIconUrl, status, title, url});
    await setElementDataset(tab, "tab", JSON.stringify(tabsTab));
  }
};

/* audio */
/**
 * handle clicked audio button
 * @param {!Object} evt - event
 * @returns {?AsyncFunction} - muteTabs / updateTab()
 */
export const handleClickedTabAudio = async evt => {
  const {target} = evt;
  const tab = getSidebarTab(target);
  const tabId = getSidebarTabId(tab);
  let func;
  if (Number.isInteger(tabId)) {
    const tabsTab = await getTab(tabId);
    const {mutedInfo: {muted}} = tabsTab;
    const {classList} = tab;
    if (classList.contains(HIGHLIGHTED)) {
      const selectedTabs = document.querySelectorAll(`.${HIGHLIGHTED}`);
      func = muteTabs(Array.from(selectedTabs), !muted);
    } else {
      func = updateTab(tabId, {muted: !muted});
    }
  }
  return func;
};

/**
 * handle tab audio onclick
 * @param {!Object} evt - Event
 * @returns {AsyncFunction} - handleClickedTabAudio()
 */
export const tabAudioOnClick = evt =>
  handleClickedTabAudio(evt).catch(throwErr);

/**
 * add tab audio click event listener
 * @param {Object} elm - element
 * @returns {void}
 */
export const addTabAudioClickListener = async elm => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE &&
      elm.classList.contains(CLASS_TAB_AUDIO)) {
    elm.addEventListener("click", tabAudioOnClick);
  }
};

/**
 * set tab audio
 * @param {Object} elm - element
 * @param {Object} info - audio info
 * @returns {void}
 */
export const setTabAudio = async (elm, info) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && isObjectNotEmpty(info)) {
    const {audible, muted, highlighted} = info;
    if (muted) {
      if (highlighted) {
        elm.title = i18n.getMessage(`${TABS_MUTE_UNMUTE}_tooltip`);
      } else {
        elm.title = i18n.getMessage(`${TAB_MUTE_UNMUTE}_tooltip`);
      }
    } else if (audible) {
      if (highlighted) {
        elm.title = i18n.getMessage(`${TABS_MUTE}_tooltip`);
      } else {
        elm.title = i18n.getMessage(`${TAB_MUTE}_tooltip`);
      }
    } else {
      elm.title = "";
    }
  }
};

/**
 * set tab audio icon
 * @param {Object} elm - element
 * @param {Object} info - audio info
 * @returns {void}
 */
export const setTabAudioIcon = async (elm, info) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img" &&
      isObjectNotEmpty(info)) {
    const {audible, muted} = info;
    if (muted) {
      elm.alt = i18n.getMessage(`${TAB_MUTE_UNMUTE}`);
      elm.src = URL_AUDIO_MUTED;
    } else if (audible) {
      elm.alt = i18n.getMessage(`${TAB_MUTE}`);
      elm.src = URL_AUDIO_PLAYING;
    } else {
      elm.alt = "";
      elm.src = "";
    }
  }
};

/* close button */
/**
 * set close tab button tooltip
 * @param {Object} elm - element
 * @param {boolean} highlighted - highlighted
 * @returns {void}
 */
export const setCloseTab = async (elm, highlighted) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE &&
      elm.classList.contains(CLASS_TAB_CLOSE)) {
    if (highlighted) {
      elm.title = i18n.getMessage(`${TABS_CLOSE}_tooltip`);
    } else {
      elm.title = i18n.getMessage(`${TAB_CLOSE}_tooltip`);
    }
  }
};

/**
 * handle clicked close button
 * @param {Object} evt - event
 * @returns {?AsyncFunction} - closeTabs()
 */
export const handleClickedCloseButton = async evt => {
  const {target} = evt;
  const tab = getSidebarTab(target);
  let func;
  if (tab) {
    const {classList} = tab;
    if (classList.contains(HIGHLIGHTED)) {
      const selectedTabs = document.querySelectorAll(`.${HIGHLIGHTED}`);
      func = closeTabs(Array.from(selectedTabs));
    } else {
      func = closeTabs([tab]);
    }
  }
  return func || null;
};

/**
 * handle tab close button click
 * @param {!Object} evt - Event
 * @returns {AsyncFunction} - handleClickedCloseButton()
 */
export const tabCloseOnClick = evt =>
  handleClickedCloseButton(evt).catch(throwErr);

/**
 * add tab close click listener
 * @param {Object} elm - element
 * @returns {void}
 */
export const addTabCloseClickListener = async elm => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE &&
      elm.classList.contains(CLASS_TAB_CLOSE)) {
    elm.addEventListener("click", tabCloseOnClick);
  }
};

/* contextual identities */
/**
 * set contextual identities icon
 * @param {Object} elm - element
 * @param {Object} info - contextual identities info
 * @returns {void}
 */
export const setContextualIdentitiesIcon = async (elm, info) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img" &&
      isObjectNotEmpty(info)) {
    const {color, icon, name} = info;
    if (contextualIdentitiesIconColor.has(color) &&
        contextualIdentitiesIconName.has(icon) &&
        isString(name)) {
      elm.alt = name;
      elm.src = `../img/${icon}.svg#${color}`;
      elm.parentNode.classList.add(IDENTIFIED);
    }
  }
};

/* highlight */
/**
 * add hightlight class to tab
 * @param {Object} elm - element
 * @returns {Promise.<Array>} - results of each handler
 */
export const addHighlight = async elm => {
  const func = [];
  const tabId = getSidebarTabId(elm);
  if (Number.isInteger(tabId)) {
    const tab = await getTab(tabId);
    const {audible, mutedInfo: {muted}} = tab;
    const closeElm = elm.querySelector(`.${CLASS_TAB_CLOSE}`);
    const muteElm = elm.querySelector(`.${CLASS_TAB_AUDIO}`);
    elm.classList.add(HIGHLIGHTED);
    func.push(
      setCloseTab(closeElm, true),
      setTabAudio(muteElm, {
        audible, muted,
        highlighted: true,
      }),
    );
  }
  return Promise.all(func);
};

/**
 * add highlight class to tabs
 * @param {Array} tabIds - array of tab ID
 * @returns {Promise.<Array>} - results of each handler
 */
export const addHighlightToTabs = async tabIds => {
  if (!Array.isArray(tabIds)) {
    throw new TypeError(`Expected Array but got ${getType(tabIds)}.`);
  }
  const func = [];
  for (const id of tabIds) {
    const item = document.querySelector(`[data-tab-id="${id}"]`);
    if (item) {
      func.push(addHighlight(item));
    }
  }
  return Promise.all(func);
};

/**
 * remove hightlight class from tab
 * @param {Object} elm - element
 * @returns {Promise.<Array>} - results of each handler
 */
export const removeHighlight = async elm => {
  const func = [];
  const tabId = getSidebarTabId(elm);
  if (Number.isInteger(tabId)) {
    const tab = await getTab(tabId);
    const {audible, mutedInfo: {muted}} = tab;
    const closeElm = elm.querySelector(`.${CLASS_TAB_CLOSE}`);
    const muteElm = elm.querySelector(`.${CLASS_TAB_AUDIO}`);
    elm.classList.remove(HIGHLIGHTED);
    func.push(
      setCloseTab(closeElm, false),
      setTabAudio(muteElm, {
        audible, muted,
        highlighted: false,
      }),
    );
  }
  return Promise.all(func);
};

/**
 * toggle highlight class of tab
 * @param {Object} elm - element
 * @returns {AsyncFunction} - addHighlight() / removeHightlight()
 */
export const toggleHighlight = async elm => {
  let func;
  if (elm && elm.nodeType === Node.ELEMENT_NODE) {
    if (elm.classList.contains(HIGHLIGHTED)) {
      func = removeHighlight(elm);
    } else {
      func = addHighlight(elm);
    }
  }
  return func;
};
<commit_msg>Add icon map<commit_after>/**
 * tab-content.js
 */

import {
  getType, isObjectNotEmpty, isString, logErr, setElementDataset, throwErr,
} from "./common.js";
import {
  getTab, updateTab,
} from "./browser.js";
import {
  closeTabs, muteTabs,
} from "./browser-tabs.js";
import {
  getSidebarTab, getSidebarTabId,
} from "./util.js";

/* api */
const {i18n} = browser;

/* constants */
import {
  CLASS_TAB_AUDIO, CLASS_TAB_CLOSE, CLASS_TAB_CONTENT, CLASS_TAB_ICON,
  CLASS_TAB_TITLE, HIGHLIGHTED, IDENTIFIED, TAB_CLOSE, TAB_MUTE,
  TAB_MUTE_UNMUTE, TABS_CLOSE, TABS_MUTE, TABS_MUTE_UNMUTE, URL_AUDIO_MUTED,
  URL_AUDIO_PLAYING, URL_FAVICON_DEFAULT, URL_LOADING_THROBBER,
} from "./constant.js";

/* favicon */
export const favicon = new Map([
  [
    "https://abs.twimg.com/favicons/favicon.ico",
    "../img/twitter-logo-blue.svg",
  ],
  [
    "https://abs.twimg.com/icons/apple-touch-icon-192x192.png",
    "../img/twitter-logo-blue.svg",
  ],
  [
    "chrome://browser/skin/customize.svg",
    "../img/customize-favicon.svg",
  ],
  [
    "chrome://browser/skin/settings.svg",
    "../img/options-favicon.svg",
  ],
  [
    "chrome://mozapps/skin/extensions/extensionGeneric-16.svg",
    "../img/addons-favicon.svg",
  ],
  [
    "chrome://mozapps/skin/extensions/extension.svg",
    "../img/addons-favicon.svg",
  ],
]);

/* contextual identities icon name */
export const contextualIdentitiesIconName = new Set([
  "briefcase", "cart", "chill", "dollar", "fingerprint", "food", "fruit",
  "gift", "pet", "tree", "vacation",
]);

/* contextual identities icon color */
export const contextualIdentitiesIconColor = new Set([
  "blue", "purple", "pink", "red", "orange", "yellow", "green",
  "turquoise",
]);

/**
 * tab icon fallback
 * @param {Object} evt - event
 * @returns {boolean} - false
 */
export const tabIconFallback = evt => {
  if (isObjectNotEmpty(evt)) {
    const {target, type} = evt;
    if (type === "error" && target && isString(target.src)) {
      target.src = URL_FAVICON_DEFAULT;
    }
  }
  return false;
};

/**
 * add tab icon error listener
 * @param {Object} elm - img element
 * @returns {void}
 */
export const addTabIconErrorListener = async elm => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img") {
    elm.addEventListener("error", tabIconFallback);
  }
};

/**
 * set tab icon
 * @param {Object} elm - img element
 * @param {Object} info - tab info
 * @returns {void}
 */
export const setTabIcon = async (elm, info) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img" &&
      isObjectNotEmpty(info)) {
    const {favIconUrl, status, title, url} = info;
    if (status === "loading") {
      try {
        if (isString(title) && isString(url)) {
          const {hostname} = new URL(url);
          const connecting =
            title.endsWith("/") && hostname.endsWith(title.replace(/\/$/, ""));
          if (connecting) {
            elm.dataset.connecting = url;
          } else if (elm.dataset.connecting) {
            const {stroke} = window.getComputedStyle(elm);
            elm.style.fill = stroke;
            elm.dataset.connecting = "";
          }
        } else {
          elm.dataset.connecting = url;
        }
      } catch (e) {
        logErr(e);
        elm.dataset.connecting = url;
      }
      elm.src = URL_LOADING_THROBBER;
    } else {
      elm.dataset.connecting = "";
      if (favIconUrl) {
        elm.src = favicon.get(favIconUrl) || favIconUrl;
      } else {
        elm.src = URL_FAVICON_DEFAULT;
      }
      elm.style.fill = "";
    }
  }
};

/* tab content */
/**
 * set tab content
 * @param {Object} tab - tab element
 * @param {Object} tabsTab - tabs.Tab
 * @returns {void}
 */
export const setTabContent = async (tab, tabsTab) => {
  if (tab && tab.nodeType === Node.ELEMENT_NODE && isObjectNotEmpty(tabsTab)) {
    const {favIconUrl, status, title, url} = tabsTab;
    const tabContent = tab.querySelector(`.${CLASS_TAB_CONTENT}`);
    const tabTitle = tab.querySelector(`.${CLASS_TAB_TITLE}`);
    const tabIcon = tab.querySelector(`.${CLASS_TAB_ICON}`);
    tabContent.title = title;
    tabTitle.textContent = title;
    await setTabIcon(tabIcon, {favIconUrl, status, title, url});
    await setElementDataset(tab, "tab", JSON.stringify(tabsTab));
  }
};

/* audio */
/**
 * handle clicked audio button
 * @param {!Object} evt - event
 * @returns {?AsyncFunction} - muteTabs / updateTab()
 */
export const handleClickedTabAudio = async evt => {
  const {target} = evt;
  const tab = getSidebarTab(target);
  const tabId = getSidebarTabId(tab);
  let func;
  if (Number.isInteger(tabId)) {
    const tabsTab = await getTab(tabId);
    const {mutedInfo: {muted}} = tabsTab;
    const {classList} = tab;
    if (classList.contains(HIGHLIGHTED)) {
      const selectedTabs = document.querySelectorAll(`.${HIGHLIGHTED}`);
      func = muteTabs(Array.from(selectedTabs), !muted);
    } else {
      func = updateTab(tabId, {muted: !muted});
    }
  }
  return func;
};

/**
 * handle tab audio onclick
 * @param {!Object} evt - Event
 * @returns {AsyncFunction} - handleClickedTabAudio()
 */
export const tabAudioOnClick = evt =>
  handleClickedTabAudio(evt).catch(throwErr);

/**
 * add tab audio click event listener
 * @param {Object} elm - element
 * @returns {void}
 */
export const addTabAudioClickListener = async elm => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE &&
      elm.classList.contains(CLASS_TAB_AUDIO)) {
    elm.addEventListener("click", tabAudioOnClick);
  }
};

/**
 * set tab audio
 * @param {Object} elm - element
 * @param {Object} info - audio info
 * @returns {void}
 */
export const setTabAudio = async (elm, info) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && isObjectNotEmpty(info)) {
    const {audible, muted, highlighted} = info;
    if (muted) {
      if (highlighted) {
        elm.title = i18n.getMessage(`${TABS_MUTE_UNMUTE}_tooltip`);
      } else {
        elm.title = i18n.getMessage(`${TAB_MUTE_UNMUTE}_tooltip`);
      }
    } else if (audible) {
      if (highlighted) {
        elm.title = i18n.getMessage(`${TABS_MUTE}_tooltip`);
      } else {
        elm.title = i18n.getMessage(`${TAB_MUTE}_tooltip`);
      }
    } else {
      elm.title = "";
    }
  }
};

/**
 * set tab audio icon
 * @param {Object} elm - element
 * @param {Object} info - audio info
 * @returns {void}
 */
export const setTabAudioIcon = async (elm, info) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img" &&
      isObjectNotEmpty(info)) {
    const {audible, muted} = info;
    if (muted) {
      elm.alt = i18n.getMessage(`${TAB_MUTE_UNMUTE}`);
      elm.src = URL_AUDIO_MUTED;
    } else if (audible) {
      elm.alt = i18n.getMessage(`${TAB_MUTE}`);
      elm.src = URL_AUDIO_PLAYING;
    } else {
      elm.alt = "";
      elm.src = "";
    }
  }
};

/* close button */
/**
 * set close tab button tooltip
 * @param {Object} elm - element
 * @param {boolean} highlighted - highlighted
 * @returns {void}
 */
export const setCloseTab = async (elm, highlighted) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE &&
      elm.classList.contains(CLASS_TAB_CLOSE)) {
    if (highlighted) {
      elm.title = i18n.getMessage(`${TABS_CLOSE}_tooltip`);
    } else {
      elm.title = i18n.getMessage(`${TAB_CLOSE}_tooltip`);
    }
  }
};

/**
 * handle clicked close button
 * @param {Object} evt - event
 * @returns {?AsyncFunction} - closeTabs()
 */
export const handleClickedCloseButton = async evt => {
  const {target} = evt;
  const tab = getSidebarTab(target);
  let func;
  if (tab) {
    const {classList} = tab;
    if (classList.contains(HIGHLIGHTED)) {
      const selectedTabs = document.querySelectorAll(`.${HIGHLIGHTED}`);
      func = closeTabs(Array.from(selectedTabs));
    } else {
      func = closeTabs([tab]);
    }
  }
  return func || null;
};

/**
 * handle tab close button click
 * @param {!Object} evt - Event
 * @returns {AsyncFunction} - handleClickedCloseButton()
 */
export const tabCloseOnClick = evt =>
  handleClickedCloseButton(evt).catch(throwErr);

/**
 * add tab close click listener
 * @param {Object} elm - element
 * @returns {void}
 */
export const addTabCloseClickListener = async elm => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE &&
      elm.classList.contains(CLASS_TAB_CLOSE)) {
    elm.addEventListener("click", tabCloseOnClick);
  }
};

/* contextual identities */
/**
 * set contextual identities icon
 * @param {Object} elm - element
 * @param {Object} info - contextual identities info
 * @returns {void}
 */
export const setContextualIdentitiesIcon = async (elm, info) => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE && elm.localName === "img" &&
      isObjectNotEmpty(info)) {
    const {color, icon, name} = info;
    if (contextualIdentitiesIconColor.has(color) &&
        contextualIdentitiesIconName.has(icon) &&
        isString(name)) {
      elm.alt = name;
      elm.src = `../img/${icon}.svg#${color}`;
      elm.parentNode.classList.add(IDENTIFIED);
    }
  }
};

/* highlight */
/**
 * add hightlight class to tab
 * @param {Object} elm - element
 * @returns {Promise.<Array>} - results of each handler
 */
export const addHighlight = async elm => {
  const func = [];
  const tabId = getSidebarTabId(elm);
  if (Number.isInteger(tabId)) {
    const tab = await getTab(tabId);
    const {audible, mutedInfo: {muted}} = tab;
    const closeElm = elm.querySelector(`.${CLASS_TAB_CLOSE}`);
    const muteElm = elm.querySelector(`.${CLASS_TAB_AUDIO}`);
    elm.classList.add(HIGHLIGHTED);
    func.push(
      setCloseTab(closeElm, true),
      setTabAudio(muteElm, {
        audible, muted,
        highlighted: true,
      }),
    );
  }
  return Promise.all(func);
};

/**
 * add highlight class to tabs
 * @param {Array} tabIds - array of tab ID
 * @returns {Promise.<Array>} - results of each handler
 */
export const addHighlightToTabs = async tabIds => {
  if (!Array.isArray(tabIds)) {
    throw new TypeError(`Expected Array but got ${getType(tabIds)}.`);
  }
  const func = [];
  for (const id of tabIds) {
    const item = document.querySelector(`[data-tab-id="${id}"]`);
    if (item) {
      func.push(addHighlight(item));
    }
  }
  return Promise.all(func);
};

/**
 * remove hightlight class from tab
 * @param {Object} elm - element
 * @returns {Promise.<Array>} - results of each handler
 */
export const removeHighlight = async elm => {
  const func = [];
  const tabId = getSidebarTabId(elm);
  if (Number.isInteger(tabId)) {
    const tab = await getTab(tabId);
    const {audible, mutedInfo: {muted}} = tab;
    const closeElm = elm.querySelector(`.${CLASS_TAB_CLOSE}`);
    const muteElm = elm.querySelector(`.${CLASS_TAB_AUDIO}`);
    elm.classList.remove(HIGHLIGHTED);
    func.push(
      setCloseTab(closeElm, false),
      setTabAudio(muteElm, {
        audible, muted,
        highlighted: false,
      }),
    );
  }
  return Promise.all(func);
};

/**
 * toggle highlight class of tab
 * @param {Object} elm - element
 * @returns {AsyncFunction} - addHighlight() / removeHightlight()
 */
export const toggleHighlight = async elm => {
  let func;
  if (elm && elm.nodeType === Node.ELEMENT_NODE) {
    if (elm.classList.contains(HIGHLIGHTED)) {
      func = removeHighlight(elm);
    } else {
      func = addHighlight(elm);
    }
  }
  return func;
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright (c) 2015 MediaMath Inc. All rights reserved.
 * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt

*/
/*jshint -W030 */
(function (scope) {

	var BehaviorUtils = StrandLib.BehaviorUtils,
		_ajax = StrandLib.Ajax.getBehavior();

	scope.Ajax = Polymer({
		is: 'mm-ajax',

		GET: StrandLib.Ajax.GET,
		POST: StrandLib.Ajax.POST,
		PUT: StrandLib.Ajax.PUT,
		DELETE: StrandLib.Ajax.DELETE,

		behaviors: [
			_ajax,
			StrandTraits.Refable
		],

		properties: {
			url: {
				type:String,
				value:"",
				observer:"_updateOpts"
			},
			query: {
				type: String,
				value: "",
				observer:"_updateOpts"
			},
			method: {
				type:String,
				value:"GET",
				observer:"_updateOpts"
			},
			responseType: {
				type:String,
				value:"",
				observer:"_updateOpts"
			},
			response:{
				type:Object,
				value:function() { return {}; },
				notify:true,
			},
			contentType:{
				type:String,
				value: 'application/x-www-form-urlencoded',
				observer:"_updateOpts"
			},
			auto: {
				type:Boolean,
				value:false,
				observer:"_updateOpts"
			},
			body: {
				type:Object,
				value: null,
				observer:"_updateOpts"
			},
			withCredentials: {
				type: Boolean,
				value: false,
				observer:"_updateOpts"
			},
			timeout: {
				type:Number,
				value: 10000,
				observer:"_updateOpts"
			},
			concurrency: {
				type:Number,
				value:4,
				observer:"_updateOpts"
			},
			progress: {
				type:Object,
				value: function() {
					return {
						percent:0,
						total:0,
						current:0
					};
				},
				notify:true
			},

		},

		ready: function() {
			this.async(function() {
				if (this._validateAjax()) {
					this.exec();
				}
			});
		},

		_updateOpts: function() {
			//TODO(dlasky): expose binds for additional prefs
			this.debounce("options", function() {
				this.options = StrandLib.DataUtils.copy(this.options, {
					contentType:this.contentType,
					responseType:this.responseType,
					method:this.method,
					url:this.url,
					body:this.body,
					query:this.query,
					withCredentials:this.withCredentials,
					timeout:this.timeout,
					concurrency:this.concurrency
				});
			}.bind(this));
		},

		_validateAjax: function() {
			if (!this.method || !this.auto) return false;
			if (this.method === StrandLib.Ajax.GET) {
				if (this.url) return true;
			} else {
				if (this.url && this.body) return true;
			}
			return false;
		},

		exec: function(data, options) {
			var inherited = BehaviorUtils.findSuper(_ajax, 'exec');
			var p = inherited.apply(this, arguments);
			this.current.progress = this._handleProgress.bind(this);
			p.then(this._handleResponse.bind(this), this._handleError.bind(this));
			return p;
		},

		abort: function() {
			var inherited = BehaviorUtils.findSuper(_ajax, 'exec');
			inherited.apply(this, arguments);
			if (this.current) {
				this.current.promise.then(this._handleAbort.bind(this), this._handleAbort.bind(this));
			}
		},

		_handleAbort: function(e) {
			this.fire("data-abort", e);
		},

		_handleResponse: function(resp) {
			if (resp.response) {
				this.set("response", resp.response);
			}
			this.fire("data-ready", resp);
		},

		_handleError: function(error) {
			if(error.response)
				this.set("response", error.response);
			this.fire("data-error", error);
		},

		_handleProgress: function(progress) {
			this.progress = progress;
			this.fire("data-progress", progress);
		}
	});

})(window.Strand = window.Strand || {});
<commit_msg>correct inheritance<commit_after>/**
 * @license
 * Copyright (c) 2015 MediaMath Inc. All rights reserved.
 * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt

*/
/*jshint -W030 */
(function (scope) {

	var BehaviorUtils = StrandLib.BehaviorUtils,
		_ajax = StrandLib.Ajax.getBehavior();

	scope.Ajax = Polymer({
		is: 'mm-ajax',

		GET: StrandLib.Ajax.GET,
		POST: StrandLib.Ajax.POST,
		PUT: StrandLib.Ajax.PUT,
		DELETE: StrandLib.Ajax.DELETE,

		behaviors: [
			_ajax,
			StrandTraits.Refable
		],

		properties: {
			url: {
				type:String,
				value:"",
				observer:"_updateOpts"
			},
			query: {
				type: String,
				value: "",
				observer:"_updateOpts"
			},
			method: {
				type:String,
				value:"GET",
				observer:"_updateOpts"
			},
			responseType: {
				type:String,
				value:"",
				observer:"_updateOpts"
			},
			response:{
				type:Object,
				value:function() { return {}; },
				notify:true,
			},
			contentType:{
				type:String,
				value: 'application/x-www-form-urlencoded',
				observer:"_updateOpts"
			},
			auto: {
				type:Boolean,
				value:false,
				observer:"_updateOpts"
			},
			body: {
				type:Object,
				value: null,
				observer:"_updateOpts"
			},
			withCredentials: {
				type: Boolean,
				value: false,
				observer:"_updateOpts"
			},
			timeout: {
				type:Number,
				value: 10000,
				observer:"_updateOpts"
			},
			concurrency: {
				type:Number,
				value:4,
				observer:"_updateOpts"
			},
			progress: {
				type:Object,
				value: function() {
					return {
						percent:0,
						total:0,
						current:0
					};
				},
				notify:true
			},

		},

		ready: function() {
			this.async(function() {
				if (this._validateAjax()) {
					this.exec();
				}
			});
		},

		_updateOpts: function() {
			//TODO(dlasky): expose binds for additional prefs
			this.debounce("options", function() {
				this.options = StrandLib.DataUtils.copy(this.options, {
					contentType:this.contentType,
					responseType:this.responseType,
					method:this.method,
					url:this.url,
					body:this.body,
					query:this.query,
					withCredentials:this.withCredentials,
					timeout:this.timeout,
					concurrency:this.concurrency
				});
			}.bind(this));
		},

		_validateAjax: function() {
			if (!this.method || !this.auto) return false;
			if (this.method === StrandLib.Ajax.GET) {
				if (this.url) return true;
			} else {
				if (this.url && this.body) return true;
			}
			return false;
		},

		exec: function(data, options) {
			var inherited = BehaviorUtils.findSuper(_ajax, 'exec');
			var p = inherited.apply(this, arguments);
			this.current.progress = this._handleProgress.bind(this);
			p.then(this._handleResponse.bind(this), this._handleError.bind(this));
			return p;
		},

		abort: function() {
			var inherited = BehaviorUtils.findSuper(_ajax, 'abort');
			inherited.apply(this, arguments);
			if (this.current) {
				this.current.promise.then(this._handleAbort.bind(this), this._handleAbort.bind(this));
			}
		},

		_handleAbort: function(e) {
			this.fire("data-abort", e);
		},

		_handleResponse: function(resp) {
			if (resp.response) {
				this.set("response", resp.response);
			}
			this.fire("data-ready", resp);
		},

		_handleError: function(error) {
			if(error.response)
				this.set("response", error.response);
			this.fire("data-error", error);
		},

		_handleProgress: function(progress) {
			this.progress = progress;
			this.fire("data-progress", progress);
		}
	});

})(window.Strand = window.Strand || {});
<|endoftext|>


<commit_before>const locales = {};
const fs = Promise.promisifyAll(require("fs"));
const path = require("path");

async function loadLocales() {
	for(let locale of bot.locales) {
		let strings = await fs.readFileAsync(path.resolve("locales", `${locale}.json`));
		locales[locale] = JSON.parse(strings);
	}
}

global.__ = (context, message = { locale: "en" }, values = {}) => {
	let string = locales[message.locale];
	for(let part of context.split(".")) {
		if(!string[part]) {
			return `Invalid context for translation: ${context}, ${part}. Please report this to Support`;
		}

		string = string[part];
	}

	let placeholders = string.match(/{{[^{}]+}}/g);
	placeholders.forEach(placeholder => {
		placeholder = placeholder.substring(2, placeholder.length - 2);
		string = string.replace(new RegExp(`{{${placeholder}}}`, "gi"), values[placeholder] || "**INVALID PLACEHOLDER**");
	});

	return string;
};

module.exports = { loadLocales, __ };
loadLocales();
<commit_msg>locale fix<commit_after>const locales = {};
const fs = Promise.promisifyAll(require("fs"));
const path = require("path");

async function loadLocales() {
	for(let locale of bot.locales) {
		let strings = await fs.readFileAsync(path.resolve("locales", `${locale}.json`));
		locales[locale] = JSON.parse(strings);
	}
}

global.__ = (context, message = { locale: "en" }, values = {}) => {
	let string = locales[message.locale];
	for(let part of context.split(".")) {
		if(!string[part]) {
			return `Invalid context for translation: ${context}, ${part}. Please report this to Support`;
		}

		string = string[part];
	}

	let placeholders = string.match(/{{[^{}]+}}/g);
	if(placeholders) {
		placeholders.forEach(placeholder => {
			placeholder = placeholder.substring(2, placeholder.length - 2);
			string = string.replace(new RegExp(`{{${placeholder}}}`, "gi"), values[placeholder] || "**INVALID PLACEHOLDER**");
		});
	}

	return string;
};

module.exports = { loadLocales, __ };
loadLocales();
<|endoftext|>


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

import generate from "project-name-generator";
import { CommandsArray } from "../models/Command";
import UiState from "./view/UiState";

export default function seed(store, numberOfSuites = 5) {
  function generateSuite() {
    return store.createSuite(generate({ words: 2}).spaced);
  }
  function generateTestCase() {
    return store.createTestCase(generate({ words: 2}).spaced);
  }
  const targets = ["a", "button"];
  function generateCommand(test) {
    const command = test.createCommand();
    command.setCommand(CommandsArray[Math.floor(Math.random() * CommandsArray.length)]);
    let targetChance = Math.floor(Math.random() * 10);
    command.setTarget(targetChance < targets.length ? targets[targetChance] : "");
    command.setValue(Math.floor(Math.random() * 2) ? generate({ words: 1}).spaced : "");
    return command;
  }
  function randomBetween(min, max) {
    return (Math.floor(Math.random() * (max - min)) + min);
  }
  for (let i = 0; i < numberOfSuites; i++) {
    let suite = generateSuite();
    for (let j = 0; j < randomBetween(3, 6); j++) {
      const testCase = generateTestCase();
      for (let k = 0; k < randomBetween(9, 16); k++) {
        generateCommand(testCase);
      }
      suite.addTestCase(testCase);
    }
  }

  const url = "https://en.wikipedia.org";
  store.setUrl(url);
  store.addUrl(url);
  const playbackTest = store.createTestCase("aa playback");
  const open = playbackTest.createCommand();
  open.setCommand("open");
  open.setTarget("/wiki/Legislation");
  const firstClick = playbackTest.createCommand();
  firstClick.setCommand("click");
  firstClick.setTarget("css=a:contains(\"enacted\")");
  const secondClick = playbackTest.createCommand();
  secondClick.setCommand("clickAt");
  secondClick.setTarget("link=parliamentary systems");

  const playbackTest2 = store.createTestCase("aab playback");
  const open2 = playbackTest2.createCommand();
  open2.setCommand("open");
  open2.setTarget("/wiki/River_Chater");
  const firstClick2 = playbackTest2.createCommand();
  firstClick2.setCommand("clickAt");
  firstClick2.setTarget("link=River Welland");
  const secondClick2 = playbackTest2.createCommand();
  secondClick2.setCommand("clickAt");
  secondClick2.setTarget("link=floods of 1947");
  const thirdClick2 = playbackTest2.createCommand();
  thirdClick2.setCommand("clickAt");
  thirdClick2.setTarget("link=scapegoat");

  const typeTest = store.createTestCase("aab type");
  const open3 = typeTest.createCommand();
  open3.setCommand("open");
  open3.setTarget("/wiki/Main_Page");
  const type = typeTest.createCommand();
  type.setCommand("type");
  type.setTarget("id=searchInput");
  type.setValue("testtest");

  const suite = store.createSuite("aaa suite");
  suite.addTestCase(playbackTest);
  suite.addTestCase(playbackTest2);

  const failTest = store.createTestCase("aaba failure");
  const failCommand = failTest.createCommand();
  failCommand.setCommand("waitForPageToLoad");

  const failTest2 = store.createTestCase("aabb failure");
  const failCommand2 = failTest2.createCommand();
  failCommand2.setCommand("waitForElementPresent");

  const suite2 = store.createSuite("aaab suite");
  suite2.addTestCase(failTest);
  suite2.addTestCase(failTest2);

  UiState.selectTest(playbackTest);

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

import generate from "project-name-generator";
import { CommandsArray } from "../models/Command";
import UiState from "./view/UiState";

export default function seed(store, numberOfSuites = 5) {
  function generateSuite() {
    return store.createSuite(generate({ words: 2}).spaced);
  }
  function generateTestCase() {
    return store.createTestCase(generate({ words: 2}).spaced);
  }
  const targets = ["a", "button"];
  function generateCommand(test) {
    const command = test.createCommand();
    command.setCommand(CommandsArray[Math.floor(Math.random() * CommandsArray.length)]);
    let targetChance = Math.floor(Math.random() * 10);
    command.setTarget(targetChance < targets.length ? targets[targetChance] : "");
    command.setValue(Math.floor(Math.random() * 2) ? generate({ words: 1}).spaced : "");
    return command;
  }
  function randomBetween(min, max) {
    return (Math.floor(Math.random() * (max - min)) + min);
  }
  for (let i = 0; i < numberOfSuites; i++) {
    let suite = generateSuite();
    for (let j = 0; j < randomBetween(3, 6); j++) {
      const testCase = generateTestCase();
      for (let k = 0; k < randomBetween(9, 16); k++) {
        generateCommand(testCase);
      }
      suite.addTestCase(testCase);
    }
  }

  const url = "https://en.wikipedia.org";
  store.setUrl(url);
  store.addUrl(url);
  const playbackTest = store.createTestCase("aa playback");
  const open = playbackTest.createCommand();
  open.setCommand("open");
  open.setTarget("/wiki/Legislation");
  const firstClick = playbackTest.createCommand();
  firstClick.setCommand("click");
  firstClick.setTarget("link=enacted");
  const secondClick = playbackTest.createCommand();
  secondClick.setCommand("clickAt");
  secondClick.setTarget("link=parliamentary systems");

  const playbackTest2 = store.createTestCase("aab playback");
  const open2 = playbackTest2.createCommand();
  open2.setCommand("open");
  open2.setTarget("/wiki/River_Chater");
  const firstClick2 = playbackTest2.createCommand();
  firstClick2.setCommand("clickAt");
  firstClick2.setTarget("link=River Welland");
  const secondClick2 = playbackTest2.createCommand();
  secondClick2.setCommand("clickAt");
  secondClick2.setTarget("link=floods of 1947");
  const thirdClick2 = playbackTest2.createCommand();
  thirdClick2.setCommand("clickAt");
  thirdClick2.setTarget("link=scapegoat");

  const typeTest = store.createTestCase("aab type");
  const open3 = typeTest.createCommand();
  open3.setCommand("open");
  open3.setTarget("/wiki/Main_Page");
  const type = typeTest.createCommand();
  type.setCommand("type");
  type.setTarget("id=searchInput");
  type.setValue("testtest");

  const suite = store.createSuite("aaa suite");
  suite.addTestCase(playbackTest);
  suite.addTestCase(playbackTest2);

  const failTest = store.createTestCase("aaba failure");
  const failCommand = failTest.createCommand();
  failCommand.setCommand("waitForPageToLoad");

  const failTest2 = store.createTestCase("aabb failure");
  const failCommand2 = failTest2.createCommand();
  failCommand2.setCommand("waitForElementPresent");

  const suite2 = store.createSuite("aaab suite");
  suite2.addTestCase(failTest);
  suite2.addTestCase(failTest2);

  UiState.selectTest(playbackTest);

  store.changeName("project");

  return store;
}
<|endoftext|>


<commit_before>const pg = require('pg')
const json = require('../config/config.json')
const time = require('./time.js')

const start = function () {
  insert()
}

const end = function () {
  // D
}

const insert = function () {
  const query = "INSERT INTO time (starttime) VALUES(" + "'" + time.getDate()  + "')"
  callDB(query)
}

const update = function () {
  // D
}

const callDB = function (query) {
  pg.defaults.ssl = true;
  pg.connect(json.postgresUrl, function(err, client) {
   if (err) throw err

   client
    .query(query, function(err) {
      if (err) throw err
    })
    .on('row', function(row) {
      return row
    })
  })
}

module.exports = {
  start : start,
  end : end
}<commit_msg>implement end and update<commit_after>const pg = require('pg')
const json = require('../config/config.json')
const time = require('./time.js')

const start = function () {
  insert()
}

const end = function () {
  update()
}

const insert = function () {
  const query = "INSERT INTO time (starttime) VALUES(" + "'" + time.getDate()  + "')"
  callDB(query)
}

const update = function () {
	const query ="UPDATE time SET endtime=" + "'" + time.getDate()  + "' WHERE id in (SELECT max(id) from time)"
	callDB(query)
}

const callDB = function (query) {
  pg.defaults.ssl = true;
  pg.connect(json.postgresUrl, function(err, client) {
   if (err) throw err

   client
    .query(query, function(err) {
      if (err) throw err
    })
    .on('row', function(row) {
      return row
    })
  })
}

module.exports = {
  start : start,
  end : end
}<|endoftext|>


<commit_before>console.log('Hello world!');

/*
 * CONSTANTS AND VARIABLES
 */
const DIRECTION = {
		LEFT:37,
	    UP: 38,
	    RIGHT: 39,
	    DOWN: 40
	},
	cellSize = 10;

var canvas = document.getElementById('canvas');
	ctx = canvas.getContext('2d'),
	canvasWidth = canvas.width,
	canvasHeight = canvas.height,
	snake = {
		startLength: 5,
		bodyPos: [],
		direction: DIRECTION.RIGHT,
		move: function() {
			var tail = snake.bodyPos.pop();
			var head = snake.bodyPos[0];
			switch(snake.direction) {
				case DIRECTION.UP:
					tail.x = head.x;
					tail.y = head.y - 1;
					break;
				case DIRECTION.DOWN:
					tail.x = head.x;
					tail.y = head.y + 1;
					break;
				case DIRECTION.LEFT:
					tail.x = head.x - 1;
					tail.y = head.y;
					break;
				case DIRECTION.RIGHT:
					tail.x = head.x + 1;
					tail.y = head.y;
					break;
			}
			snake.bodyPos.unshift(tail);
		},
		draw: function() {
			for(var i = 0; i < snake.bodyPos.length; ++i) {
				var cell = snake.bodyPos[i];
				ctx.fillStyle = '#00ff00';
				ctx.fillRect(cell.x * cellSize, cell.y * cellSize, cellSize, cellSize);
				ctx.strokeStyle = '#fff';
				ctx.strokeRect(cell.x * cellSize, cell.y * cellSize, cellSize, cellSize);
			}
		}
	};

/*
 * INPUTS
 */
document.addEventListener('keydown', onkeydown);

function onkeydown(evt) {
	var key = evt.which;
	if(key === DIRECTION.UP && snake.direction !== DIRECTION.DOWN){
		snake.direction = DIRECTION.UP;
	} else if(key === DIRECTION.DOWN && snake.direction !== DIRECTION.UP){
		snake.direction = DIRECTION.DOWN;
	} else if(key === DIRECTION.LEFT && snake.direction !== DIRECTION.RIGHT){
		snake.direction = DIRECTION.LEFT;
	} else if(key === DIRECTION.RIGHT && snake.direction !== DIRECTION.LEFT) {
		snake.direction = DIRECTION.RIGHT;
	}
}

function game_start() {
	snake.bodyPos = [];
	snake.direction = DIRECTION.RIGHT;

	for(var i = snake.startLength - 1; i >= 0; --i) {
		snake.bodyPos.push({x: i, y: 0});
	}
}

function game_loop() {
	update();
	render();
	game_loop_ref = requestAnimationFrame(game_loop); //request next frame
}

function update() {
	snake.move();

	var head = snake.bodyPos[0];
	if(head.x === -1 || head.x === canvasWidth/cellSize || head.y === -1 || head.y === canvasHeight/cellSize) {
		//window.cancelAnimationFrame(game_loop_ref);
		console.log('GAME OVER');
		game_start();
	}
}

function render() {
	//draw the background to clear previous frame
	ctx.fillStyle = '#fff';
	ctx.fillRect(0, 0, canvasWidth, canvasHeight);
	ctx.strokeStyle = '#000'
	ctx.strokeRect(0, 0, canvasWidth, canvasHeight);

	//draw the snake
	snake.draw();
}

game_start();
var game_loop_ref = requestAnimationFrame(game_loop); //start the first frame<commit_msg>Added food generation and created draw_cell refactor<commit_after>console.log('Hello world!');

/*
 * CONSTANTS AND VARIABLES
 */
const DIRECTION = {
		LEFT:37,
	    UP: 38,
	    RIGHT: 39,
	    DOWN: 40
	},
	cellSize = 10;

var canvas = document.getElementById('canvas');
	ctx = canvas.getContext('2d'),
	canvasWidth = canvas.width,
	canvasHeight = canvas.height,
	snake = {
		startLength: 5,
		bodyPos: [],
		direction: DIRECTION.RIGHT,
		move: function() {
			var tail = snake.bodyPos.pop();
			var head = snake.bodyPos[0];
			switch(snake.direction) {
				case DIRECTION.UP:
					tail.x = head.x;
					tail.y = head.y - 1;
					break;
				case DIRECTION.DOWN:
					tail.x = head.x;
					tail.y = head.y + 1;
					break;
				case DIRECTION.LEFT:
					tail.x = head.x - 1;
					tail.y = head.y;
					break;
				case DIRECTION.RIGHT:
					tail.x = head.x + 1;
					tail.y = head.y;
					break;
			}
			snake.bodyPos.unshift(tail);
		},
		draw: function() {
			for(var i = 0; i < snake.bodyPos.length; ++i) {
				var cell = snake.bodyPos[i];
				draw_cell(cell.x, cell.y);
			}
		}
	},
	food = {
		x: null,
		y: null,
		create: function() {
			this.x = Math.round(Math.random() * (canvasWidth - cellSize) / cellSize);
			this.y = Math.round(Math.random() * (canvasHeight - cellSize) / cellSize);
		},
		draw: function() {
			draw_cell(this.x, this.y);
		}
	};

/*
 * INPUTS
 */
document.addEventListener('keydown', onkeydown);

function onkeydown(evt) {
	var key = evt.which;
	if(key === DIRECTION.UP && snake.direction !== DIRECTION.DOWN){
		snake.direction = DIRECTION.UP;
	} else if(key === DIRECTION.DOWN && snake.direction !== DIRECTION.UP){
		snake.direction = DIRECTION.DOWN;
	} else if(key === DIRECTION.LEFT && snake.direction !== DIRECTION.RIGHT){
		snake.direction = DIRECTION.LEFT;
	} else if(key === DIRECTION.RIGHT && snake.direction !== DIRECTION.LEFT) {
		snake.direction = DIRECTION.RIGHT;
	}
}

function game_start() {
	snake.bodyPos = []; //clear previous snake bodyPos from previous game
	snake.direction = DIRECTION.RIGHT;

	for(var i = snake.startLength - 1; i >= 0; --i) {
		snake.bodyPos.push({x: i, y: 0});
	}

	food.create();
}

function update() {
	snake.move();

	//if the snake hits a wall start a new game
	var head = snake.bodyPos[0];
	if(head.x === -1 || head.x === canvasWidth/cellSize || head.y === -1 || head.y === canvasHeight/cellSize) {
		game_start();
	}
}

function draw_cell(x, y) {
	ctx.fillStyle = '#00ff00';
	ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
	ctx.strokeStyle = '#fff';
	ctx.strokeRect(x * cellSize, y * cellSize, cellSize, cellSize);
}

function render() {
	//draw the background to clear previous frame
	ctx.fillStyle = '#fff';
	ctx.fillRect(0, 0, canvasWidth, canvasHeight);
	ctx.strokeStyle = '#000'
	ctx.strokeRect(0, 0, canvasWidth, canvasHeight);

	snake.draw();
	food.draw();
}

function main_loop() {
	update();
	render();
	requestAnimationFrame(main_loop); //request next frame
}

game_start();
requestAnimationFrame(main_loop); //start the first frame
<|endoftext|>


<commit_before>define('lyria/math', ['root', 'random', 'clamp', 'fisheryates'], function(root, random, clamp, fisheryates) {

  var Math = {
    random: random,
    clamp: clamp,
    fisherYates: fisheryates
  };

  return Math;

});
<commit_msg>Removed unncessary dependency to root<commit_after>define('lyria/math', ['random', 'clamp', 'fisheryates'], function(random, clamp, fisheryates) {

  var Math = {
    random: random,
    clamp: clamp,
    fisherYates: fisheryates
  };

  return Math;

});
<|endoftext|>


<commit_before>define('lyria/math', function() {

});
<commit_msg>Added clamp function to math<commit_after>define('lyria/math', function() {

  var Math = {
    clamp: function(value, min, max) {
      var _ref, _ref1;

      if ( typeof value === 'object') {
        _ref = value, min = _ref.min, max = _ref.max, value = _ref.value;
      }
      if (min == null) {
        min = 0.0;
      }
      if (max == null) {
        max = 1.0;
      }
      if (min > max) {
        _ref1 = [max, min], min = _ref1[0], max = _ref1[1];
      }
      if ((min <= value && value <= max)) {
        return value;
      } else {
        if (value > max) {
          return max;
        } else {
          return min;
        }
      }
    }
  };

  return Math;

});
<|endoftext|>


<commit_before>/**
 * @author Rob Taylor [manix84@gmail.com]
 */
define('utils/object/isObject', function () {
    /**
     * Checks whether argument passed is an object
     * @param {mixed} object - Item to be tested
     * @example object.isObject({key1: 'var', key2: 'var'}); // RETURNS: true
     * @example object.isObject(['key1', 'key2']); // RETURNS: false
     * @returns {boolean}
     */
    var isObject = function (objectObj) {
        return (Object.prototype.toString.call(objectObj) === '[object Object]');
    };

    return isObject;
});
<commit_msg>Relocating object/isObject references.<commit_after>/**
 * @author Rob Taylor [manix84@gmail.com]
 */
define('object/isObject', function () {
    /**
     * Checks whether argument passed is an object
     * @exports object/isObject
     *
     * @param {mixed} object - Item to be tested
     * @example object.isObject({key1: 'var', key2: 'var'}); // RETURNS: true
     * @example object.isObject(['key1', 'key2']); // RETURNS: false
     * @returns {boolean}
     */
    var isObject = function (objectObj) {
        return (Object.prototype.toString.call(objectObj) === '[object Object]');
    };

    return isObject;
});
<|endoftext|>


<commit_before>// Copyright (c) 2017 Adobe Systems Incorporated. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var mina = (function (eve) {
    var animations = {},
    requestAnimFrame = window.requestAnimationFrame       ||
                       window.webkitRequestAnimationFrame ||
                       window.mozRequestAnimationFrame    ||
                       window.oRequestAnimationFrame      ||
                       window.msRequestAnimationFrame     ||
                       function (callback) {
                           setTimeout(callback, 16);
                       },
    isArray = Array.isArray || function (a) {
        return a instanceof Array ||
            Object.prototype.toString.call(a) == "[object Array]";
    },
    idgen = 0,
    idprefix = "M" + (+new Date).toString(36),
    ID = function () {
        return idprefix + (idgen++).toString(36);
    },
    diff = function (a, b, A, B) {
        if (isArray(a)) {
            res = [];
            for (var i = 0, ii = a.length; i < ii; i++) {
                res[i] = diff(a[i], b, A[i], B);
            }
            return res;
        }
        var dif = (A - a) / (B - b);
        return function (bb) {
            return a + dif * (bb - b);
        };
    },
    timer = Date.now || function () {
        return +new Date;
    },
    sta = function (val) {
        var a = this;
        if (val == null) {
            return a.s;
        }
        var ds = a.s - val;
        a.b += a.dur * ds;
        a.B += a.dur * ds;
        a.s = val;
    },
    speed = function (val) {
        var a = this;
        if (val == null) {
            return a.spd;
        }
        a.spd = val;
    },
    duration = function (val) {
        var a = this;
        if (val == null) {
            return a.dur;
        }
        a.s = a.s * val / a.dur;
        a.dur = val;
    },
    stopit = function () {
        var a = this;
        delete animations[a.id];
        a.update();
        eve("mina.stop." + a.id, a);
    },
    pause = function () {
        var a = this;
        if (a.pdif) {
            return;
        }
        delete animations[a.id];
        a.update();
        a.pdif = a.get() - a.b;
    },
    resume = function () {
        var a = this;
        if (!a.pdif) {
            return;
        }
        a.b = a.get() - a.pdif;
        delete a.pdif;
        animations[a.id] = a;
    },
    update = function () {
        var a = this,
            res;
        if (isArray(a.start)) {
            res = [];
            for (var j = 0, jj = a.start.length; j < jj; j++) {
                res[j] = +a.start[j] +
                    (a.end[j] - a.start[j]) * a.easing(a.s);
            }
        } else {
            res = +a.start + (a.end - a.start) * a.easing(a.s);
        }
        a.set(res);
    },
    frame = function () {
        var len = 0;
        for (var i in animations) if (animations.hasOwnProperty(i)) {
            var a = animations[i],
                b = a.get(),
                res;
            len++;
            a.s = (b - a.b) / (a.dur / a.spd);
            if (a.s >= 1) {
                delete animations[i];
                a.s = 1;
                len--;
                (function (a) {
                    setTimeout(function () {
                        eve("mina.finish." + a.id, a);
                    });
                }(a));
            }
            a.update();
        }
        len && requestAnimFrame(frame);
    },
    /*\
     * mina
     [ method ]
     **
     * Generic animation of numbers
     **
     - a (number) start _slave_ number
     - A (number) end _slave_ number
     - b (number) start _master_ number (start time in general case)
     - B (number) end _master_ number (end time in general case)
     - get (function) getter of _master_ number (see @mina.time)
     - set (function) setter of _slave_ number
     - easing (function) #optional easing function, default is @mina.linear
     = (object) animation descriptor
     o {
     o         id (string) animation id,
     o         start (number) start _slave_ number,
     o         end (number) end _slave_ number,
     o         b (number) start _master_ number,
     o         s (number) animation status (0..1),
     o         dur (number) animation duration,
     o         spd (number) animation speed,
     o         get (function) getter of _master_ number (see @mina.time),
     o         set (function) setter of _slave_ number,
     o         easing (function) easing function, default is @mina.linear,
     o         status (function) status getter/setter,
     o         speed (function) speed getter/setter,
     o         duration (function) duration getter/setter,
     o         stop (function) animation stopper
     o         pause (function) pauses the animation
     o         resume (function) resumes the animation
     o         update (function) calles setter with the right value of the animation
     o }
    \*/
    mina = function (a, A, b, B, get, set, easing) {
        var anim = {
            id: ID(),
            start: a,
            end: A,
            b: b,
            s: 0,
            dur: B - b,
            spd: 1,
            get: get,
            set: set,
            easing: easing || mina.linear,
            status: sta,
            speed: speed,
            duration: duration,
            stop: stopit,
            pause: pause,
            resume: resume,
            update: update
        };
        animations[anim.id] = anim;
        var len = 0, i;
        for (i in animations) if (animations.hasOwnProperty(i)) {
            len++;
            if (len == 2) {
                break;
            }
        }
        len == 1 && requestAnimFrame(frame);
        return anim;
    };
    /*\
     * mina.time
     [ method ]
     **
     * Returns the current time. Equivalent to:
     | function () {
     |     return (new Date).getTime();
     | }
    \*/
    mina.time = timer;
    /*\
     * mina.getById
     [ method ]
     **
     * Returns an animation by its id
     - id (string) animation's id
     = (object) See @mina
    \*/
    mina.getById = function (id) {
        return animations[id] || null;
    };

    /*\
     * mina.linear
     [ method ]
     **
     * Default linear easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.linear = function (n) {
        return n;
    };
    /*\
     * mina.easeout
     [ method ]
     **
     * Easeout easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.easeout = function (n) {
        return Math.pow(n, 1.7);
    };
    /*\
     * mina.easein
     [ method ]
     **
     * Easein easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.easein = function (n) {
        return Math.pow(n, .48);
    };
    /*\
     * mina.easeinout
     [ method ]
     **
     * Easeinout easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.easeinout = function (n) {
        if (n == 1) {
            return 1;
        }
        if (n == 0) {
            return 0;
        }
        var q = .48 - n / 1.04,
            Q = Math.sqrt(.1734 + q * q),
            x = Q - q,
            X = Math.pow(Math.abs(x), 1 / 3) * (x < 0 ? -1 : 1),
            y = -Q - q,
            Y = Math.pow(Math.abs(y), 1 / 3) * (y < 0 ? -1 : 1),
            t = X + Y + .5;
        return (1 - t) * 3 * t * t + t * t * t;
    };
    /*\
     * mina.backin
     [ method ]
     **
     * Backin easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.backin = function (n) {
        if (n == 1) {
            return 1;
        }
        var s = 1.70158;
        return n * n * ((s + 1) * n - s);
    };
    /*\
     * mina.backout
     [ method ]
     **
     * Backout easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.backout = function (n) {
        if (n == 0) {
            return 0;
        }
        n = n - 1;
        var s = 1.70158;
        return n * n * ((s + 1) * n + s) + 1;
    };
    /*\
     * mina.elastic
     [ method ]
     **
     * Elastic easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.elastic = function (n) {
        if (n == !!n) {
            return n;
        }
        return Math.pow(2, -10 * n) * Math.sin((n - .075) *
            (2 * Math.PI) / .3) + 1;
    };
    /*\
     * mina.bounce
     [ method ]
     **
     * Bounce easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.bounce = function (n) {
        var s = 7.5625,
            p = 2.75,
            l;
        if (n < 1 / p) {
            l = s * n * n;
        } else {
            if (n < 2 / p) {
                n -= 1.5 / p;
                l = s * n * n + .75;
            } else {
                if (n < 2.5 / p) {
                    n -= 2.25 / p;
                    l = s * n * n + .9375;
                } else {
                    n -= 2.625 / p;
                    l = s * n * n + .984375;
                }
            }
        }
        return l;
    };
    window.mina = mina;
    return mina;
})(typeof eve == "undefined" ? function () {} : eve);
<commit_msg>Fix mina frame loop exit on resume (#499)<commit_after>// Copyright (c) 2017 Adobe Systems Incorporated. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var mina = (function (eve) {
    var animations = {},
    requestAnimFrame = window.requestAnimationFrame       ||
                       window.webkitRequestAnimationFrame ||
                       window.mozRequestAnimationFrame    ||
                       window.oRequestAnimationFrame      ||
                       window.msRequestAnimationFrame     ||
                       function (callback) {
                           setTimeout(callback, 16, new Date().getTime());
                           return true;
                       },
    requestID,
    isArray = Array.isArray || function (a) {
        return a instanceof Array ||
            Object.prototype.toString.call(a) == "[object Array]";
    },
    idgen = 0,
    idprefix = "M" + (+new Date).toString(36),
    ID = function () {
        return idprefix + (idgen++).toString(36);
    },
    diff = function (a, b, A, B) {
        if (isArray(a)) {
            res = [];
            for (var i = 0, ii = a.length; i < ii; i++) {
                res[i] = diff(a[i], b, A[i], B);
            }
            return res;
        }
        var dif = (A - a) / (B - b);
        return function (bb) {
            return a + dif * (bb - b);
        };
    },
    timer = Date.now || function () {
        return +new Date;
    },
    sta = function (val) {
        var a = this;
        if (val == null) {
            return a.s;
        }
        var ds = a.s - val;
        a.b += a.dur * ds;
        a.B += a.dur * ds;
        a.s = val;
    },
    speed = function (val) {
        var a = this;
        if (val == null) {
            return a.spd;
        }
        a.spd = val;
    },
    duration = function (val) {
        var a = this;
        if (val == null) {
            return a.dur;
        }
        a.s = a.s * val / a.dur;
        a.dur = val;
    },
    stopit = function () {
        var a = this;
        delete animations[a.id];
        a.update();
        eve("mina.stop." + a.id, a);
    },
    pause = function () {
        var a = this;
        if (a.pdif) {
            return;
        }
        delete animations[a.id];
        a.update();
        a.pdif = a.get() - a.b;
    },
    resume = function () {
        var a = this;
        if (!a.pdif) {
            return;
        }
        a.b = a.get() - a.pdif;
        delete a.pdif;
        animations[a.id] = a;
        frame();
    },
    update = function () {
        var a = this,
            res;
        if (isArray(a.start)) {
            res = [];
            for (var j = 0, jj = a.start.length; j < jj; j++) {
                res[j] = +a.start[j] +
                    (a.end[j] - a.start[j]) * a.easing(a.s);
            }
        } else {
            res = +a.start + (a.end - a.start) * a.easing(a.s);
        }
        a.set(res);
    },
    frame = function (timeStamp) {
        // Manual invokation?
        if (!timeStamp) {
            // Frame loop stopped?
            if (!requestID) {
                // Start frame loop...
                requestID = requestAnimFrame(frame);
            }
            return;
        }
        var len = 0;
        for (var i in animations) if (animations.hasOwnProperty(i)) {
            var a = animations[i],
                b = a.get(),
                res;
            len++;
            a.s = (b - a.b) / (a.dur / a.spd);
            if (a.s >= 1) {
                delete animations[i];
                a.s = 1;
                len--;
                (function (a) {
                    setTimeout(function () {
                        eve("mina.finish." + a.id, a);
                    });
                }(a));
            }
            a.update();
        }
        requestID = len ? requestAnimFrame(frame) : false;
    },
    /*\
     * mina
     [ method ]
     **
     * Generic animation of numbers
     **
     - a (number) start _slave_ number
     - A (number) end _slave_ number
     - b (number) start _master_ number (start time in general case)
     - B (number) end _master_ number (end time in general case)
     - get (function) getter of _master_ number (see @mina.time)
     - set (function) setter of _slave_ number
     - easing (function) #optional easing function, default is @mina.linear
     = (object) animation descriptor
     o {
     o         id (string) animation id,
     o         start (number) start _slave_ number,
     o         end (number) end _slave_ number,
     o         b (number) start _master_ number,
     o         s (number) animation status (0..1),
     o         dur (number) animation duration,
     o         spd (number) animation speed,
     o         get (function) getter of _master_ number (see @mina.time),
     o         set (function) setter of _slave_ number,
     o         easing (function) easing function, default is @mina.linear,
     o         status (function) status getter/setter,
     o         speed (function) speed getter/setter,
     o         duration (function) duration getter/setter,
     o         stop (function) animation stopper
     o         pause (function) pauses the animation
     o         resume (function) resumes the animation
     o         update (function) calles setter with the right value of the animation
     o }
    \*/
    mina = function (a, A, b, B, get, set, easing) {
        var anim = {
            id: ID(),
            start: a,
            end: A,
            b: b,
            s: 0,
            dur: B - b,
            spd: 1,
            get: get,
            set: set,
            easing: easing || mina.linear,
            status: sta,
            speed: speed,
            duration: duration,
            stop: stopit,
            pause: pause,
            resume: resume,
            update: update
        };
        animations[anim.id] = anim;
        var len = 0, i;
        for (i in animations) if (animations.hasOwnProperty(i)) {
            len++;
            if (len == 2) {
                break;
            }
        }
        len == 1 && frame();
        return anim;
    };
    /*\
     * mina.time
     [ method ]
     **
     * Returns the current time. Equivalent to:
     | function () {
     |     return (new Date).getTime();
     | }
    \*/
    mina.time = timer;
    /*\
     * mina.getById
     [ method ]
     **
     * Returns an animation by its id
     - id (string) animation's id
     = (object) See @mina
    \*/
    mina.getById = function (id) {
        return animations[id] || null;
    };

    /*\
     * mina.linear
     [ method ]
     **
     * Default linear easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.linear = function (n) {
        return n;
    };
    /*\
     * mina.easeout
     [ method ]
     **
     * Easeout easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.easeout = function (n) {
        return Math.pow(n, 1.7);
    };
    /*\
     * mina.easein
     [ method ]
     **
     * Easein easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.easein = function (n) {
        return Math.pow(n, .48);
    };
    /*\
     * mina.easeinout
     [ method ]
     **
     * Easeinout easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.easeinout = function (n) {
        if (n == 1) {
            return 1;
        }
        if (n == 0) {
            return 0;
        }
        var q = .48 - n / 1.04,
            Q = Math.sqrt(.1734 + q * q),
            x = Q - q,
            X = Math.pow(Math.abs(x), 1 / 3) * (x < 0 ? -1 : 1),
            y = -Q - q,
            Y = Math.pow(Math.abs(y), 1 / 3) * (y < 0 ? -1 : 1),
            t = X + Y + .5;
        return (1 - t) * 3 * t * t + t * t * t;
    };
    /*\
     * mina.backin
     [ method ]
     **
     * Backin easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.backin = function (n) {
        if (n == 1) {
            return 1;
        }
        var s = 1.70158;
        return n * n * ((s + 1) * n - s);
    };
    /*\
     * mina.backout
     [ method ]
     **
     * Backout easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.backout = function (n) {
        if (n == 0) {
            return 0;
        }
        n = n - 1;
        var s = 1.70158;
        return n * n * ((s + 1) * n + s) + 1;
    };
    /*\
     * mina.elastic
     [ method ]
     **
     * Elastic easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.elastic = function (n) {
        if (n == !!n) {
            return n;
        }
        return Math.pow(2, -10 * n) * Math.sin((n - .075) *
            (2 * Math.PI) / .3) + 1;
    };
    /*\
     * mina.bounce
     [ method ]
     **
     * Bounce easing
     - n (number) input 0..1
     = (number) output 0..1
    \*/
    mina.bounce = function (n) {
        var s = 7.5625,
            p = 2.75,
            l;
        if (n < 1 / p) {
            l = s * n * n;
        } else {
            if (n < 2 / p) {
                n -= 1.5 / p;
                l = s * n * n + .75;
            } else {
                if (n < 2.5 / p) {
                    n -= 2.25 / p;
                    l = s * n * n + .9375;
                } else {
                    n -= 2.625 / p;
                    l = s * n * n + .984375;
                }
            }
        }
        return l;
    };
    window.mina = mina;
    return mina;
})(typeof eve == "undefined" ? function () {} : eve);
<|endoftext|>


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

var team = [{
  key: 1,
  name: "Mark Kim",
  bio: "Completely synergize resource taxing relationships via premier niche markets. Professionally cultivate one-to-one customer service with robust ideas. Dynamically innovate resource-leveling customer service for state of the art customer service.",
  image: "../assets/mark-profile.jpg",
  git: "https://github.com/marksanghoonkim",
  linked: "https://www.linkedin.com/in/marksanghoonkim"
}, {
  key: 2,
  name: "Rick Yeh",
  bio: "Objectively innovate empowered manufactured products whereas parallel platforms. Holisticly predominate extensible testing procedures for reliable supply chains. Dramatically engage top-line web services vis-a-vis cutting-edge deliverables.",
  image: "../assets/rick-profile.jpg",
  git: "https://github.com/rickyeh",
  linked: "https://www.linkedin.com/in/rickyeh"
}, {
  key: 3,
  name: "Jordan Allen",
  bio: "I owned my own business at 21, self taught(mostly) guitarist, owned and worked on a couple project cars(0 - 60 around 4 seconds), I have loved traveling around a few different parts of the world.",
  image: "../assets/jordan-profile.jpg",
  git: "https://github.com/jordanallen98",
  linked: "https://www.linkedin.com/in/jordandallen"
}, {
  key: 4,
  name: "Nicholas Der",
  bio: "Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. Dramatically maintain clicks-and-mortar solutions without functional solutions.",
  image: "../assets/nick-profile.jpg",
  git: "https://github.com/kiritsuzu",
  linked: "https://www.linkedin.com/in/kiritsuzu"
}];

class About extends Component {
  render() {
    var Profiles = team.map(function(profile){
      return ( <AboutProfile key={profile.key} name={profile.name} bio={profile.bio} image={profile.image} git={profile.git} linked={profile.linked}> </AboutProfile> );
    });

    return (

Meet The Team

 nimblecode repo

        {Profiles}

    );
  }
}

export default About;
<commit_msg>[update] update bio content to third person<commit_after>import React, { Component } from 'react';
import AboutProfile from './AboutProfile.js';

var team = [{
  key: 1,
  name: "Mark Kim",
  bio: "Completely synergize resource taxing relationships via premier niche markets. Professionally cultivate one-to-one customer service with robust ideas. Dynamically innovate resource-leveling customer service for state of the art customer service.",
  image: "../assets/mark-profile.jpg",
  git: "https://github.com/marksanghoonkim",
  linked: "https://www.linkedin.com/in/marksanghoonkim"
}, {
  key: 2,
  name: "Rick Yeh",
  bio: "Objectively innovate empowered manufactured products whereas parallel platforms. Holisticly predominate extensible testing procedures for reliable supply chains. Dramatically engage top-line web services vis-a-vis cutting-edge deliverables.",
  image: "../assets/rick-profile.jpg",
  git: "https://github.com/rickyeh",
  linked: "https://www.linkedin.com/in/rickyeh"
}, {
  key: 3,
  name: "Jordan Allen",
  bio: "Jordan owned his own business at 21, is a avid, self taught(mostly), guitarist, and also has owned and worked on a couple project cars(0 - 60 around 4 seconds). He loves traveling around the world every chance he gets.",
  image: "../assets/jordan-profile.jpg",
  git: "https://github.com/jordanallen98",
  linked: "https://www.linkedin.com/in/jordandallen"
}, {
  key: 4,
  name: "Nicholas Der",
  bio: "Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. Dramatically maintain clicks-and-mortar solutions without functional solutions.",
  image: "../assets/nick-profile.jpg",
  git: "https://github.com/kiritsuzu",
  linked: "https://www.linkedin.com/in/kiritsuzu"
}];

class About extends Component {
  render() {
    var Profiles = team.map(function(profile){
      return ( <AboutProfile key={profile.key} name={profile.name} bio={profile.bio} image={profile.image} git={profile.git} linked={profile.linked}> </AboutProfile> );
    });

    return (

Meet The Team

 nimblecode repo

        {Profiles}

    );
  }
}

export default About;
<|endoftext|>


<commit_before>/**
 * `components/index.js` exists simply as a 'central export' for our components.
 * This way, we can import all of our components from the same place, rather than
 * having to figure out which file they belong to!
 */
export { default as Main } from './main';
export { default as Landing } from './landing';
export { default as Splash } from './Splash';
export { default as DataVisPanel } from './DataVisPanel';
export { default as DataVisWordCloud } from './DataVisWordCloud';
export { default as UserHome } from './user-home';
export { default as Record } from './Record';
export { default as Navbar } from './Navbar';
export { default as Games } from './Games';
export { default as SynonymGame } from './SynonymGame';
export { default as Definitions } from './games/Definitions';
export { Login, Signup } from './auth-form';
export { default as NewWordsPanel } from './new-words/NewWordsPanel';
<commit_msg>Update index.js<commit_after>/**
 * `components/index.js` exists simply as a 'central export' for our components.
 * This way, we can import all of our components from the same place, rather than
 * having to figure out which file they belong to!
 */
export { default as Main } from './main';
export { default as Landing } from './Landing';
export { default as Splash } from './Splash';
export { default as DataVisPanel } from './DataVisPanel';
export { default as DataVisWordCloud } from './DataVisWordCloud';
export { default as UserHome } from './user-home';
export { default as Record } from './Record';
export { default as Navbar } from './Navbar';
export { default as Games } from './Games';
export { default as SynonymGame } from './SynonymGame';
export { default as Definitions } from './games/Definitions';
export { Login, Signup } from './auth-form';
export { default as NewWordsPanel } from './new-words/NewWordsPanel';
<|endoftext|>