<commit_before>const Command = require("../base/Command");
// const moment = require('moment');
require("moment-duration-format");

class MyMods extends Command {
    constructor(client) {
        super(client, {
            name: "mymods",
            category: "SWGoH",
            guildOnly: false,
            aliases: ["charactermods", "charmods", "cmods", "cm", "mm"],
            permissions: ["EMBED_LINKS"],
            subArgs: {
                b: {
                    aliases: ["best"],
                    default: null
                }
            },
            flags: {
                t: {
                    aliases: ["total"]
                }
            }
        });
    }

    async run(client, message, [userID, ...searchChar], options) { // eslint-disable-line no-unused-vars
        // const lang = message.guildSettings.swgohLanguage;
        const cooldown = client.getPlayerCooldown(message.author.id);
        const icons = {
            STATMOD_SLOT_01: await client.getEmoji("362066327101243392") || "Square",
            STATMOD_SLOT_02: await client.getEmoji("362066325474115605") || "Arrow",
            STATMOD_SLOT_03: await client.getEmoji("362066326925082637") || "Diamond",
            STATMOD_SLOT_04: await client.getEmoji("362066327168352257") || "Triangle",
            STATMOD_SLOT_05: await client.getEmoji("362066326996385812") || "Circle",
            STATMOD_SLOT_06: await client.getEmoji("362066327516610570") || "Cross"
        };

        if (searchChar) searchChar = searchChar.join(" ");

        // Need to get the allycode from the db, then use that
        if (!userID) {
            if (!options.subArgs.b) {
                return message.channel.send(message.language.get("BASE_SWGOH_MISSING_CHAR"));
            } else {
                userID = message.author.id;
            }
        } else if (userID === "me") {
            userID = message.author.id;
        } else if (client.isAllyCode(userID) || client.isUserID(userID)) {
            userID = userID.replace(/[^\d]*/g, "");
        } else {
            // If they're just looking for a character for themselves, get the char
            searchChar = userID + " " + searchChar;
            searchChar = searchChar.trim();
            userID = message.author.id;
        }

        const msg = await message.channel.send(message.language.get("COMMAND_MYMODS_WAIT"));

        const allyCodes = await client.getAllyCode(message, userID);
        if (!allyCodes.length) {
            return msg.edit(message.language.get("BASE_SWGOH_NOT_REG", client.users.get(userID).tag));
        } else if (allyCodes.length > 1) {
            return msg.edit("Found " + allyCodes.length + " matches. Please make sure your code is correct.");
        }

        const allyCode = allyCodes[0];

        if (!options.subArgs.b) {
            let character;
            if (!searchChar) {
                return msg.edit(message.language.get("BASE_SWGOH_MISSING_CHAR"));
            }

            const chars = client.findChar(searchChar, client.characters);
            if (chars.length === 0) {
                return msg.edit(message.language.get("BASE_SWGOH_NO_CHAR_FOUND", searchChar));
            } else if (chars.length > 1) {
                const charL = [];
                const charS = chars.sort((p, c) => p.name > c.name ? 1 : -1);
                charS.forEach(c => {
                    charL.push(c.name);
                });
                return msg.edit(message.language.get("BASE_SWGOH_CHAR_LIST", charL.join("\n")));
            } else {
                character = chars[0];
            }

            let player;
            try {
                player = await client.swgohAPI.player(allyCode, null, cooldown);
            } catch (e) {
                console.log(e);
            }

            const charMods = player.roster.filter(c => c.defId === character.uniqueName)[0].mods;

            const {inspect} = require("util");
            console.log(inspect(charMods, {depth: 5}));

            const slots = {};

            const sets = message.language.get("BASE_MODSETS_FROM_GAME");
            const stats = message.language.get("BASE_MODS_FROM_GAME");

            charMods.forEach(mod => {
                slots[mod.slot] = {
                    stats: [],
                    type: sets[mod.set],
                    lvl: mod.level,
                    pip: mod.pips
                };

                // Add the primary in
                slots[mod.slot].stats.push(`${mod.primaryStat.value} ${stats[mod.primaryStat.unitStat].replace("+", "").replace("%", "")}`);

                // Then all the secondaries
                mod.secondaryStat.forEach(s => {
                    const t = stats[s.unitStat].replace("%", "").trim();

                    let statStr = s.value;
                    if (s.roll > 0) statStr = `(${s.roll}) ${statStr}`;
                    statStr +=  " " + t;
                    slots[mod.slot].stats.push(statStr);
                });
            });

            const fields = [];
            Object.keys(slots).forEach(mod => {
                const stats = slots[mod].stats;
                fields.push({
                    name: `${icons[`STATMOD_SLOT_0${mod}`]} ${slots[mod].type} (${slots[mod].pip}* Lvl: ${slots[mod].lvl})`,
                    value: `**${stats.shift()}**\n${stats.join("\n")}\n\`${"-".repeat(28)}\``,
                    inline: true
                });
            });

            msg.edit({embed: {
                author: {
                    name: `${player.name}'s ${character.name}`,
                    icon_url: character.avatarURL
                },
                fields: fields,
                footer: {
                    text: message.language.get("BASE_SWGOH_LAST_UPDATED", client.duration(player.updated, message))
                }
            }});
        } else {
            const checkableStats = {
                "Health": {
                    aliases: ["HP"]
                },
                "Protection": {
                    aliases: ["Prot"]
                },
                "Speed": {
                    aliases: []
                },
                "Potency": {
                    aliases: ["Pot"]
                },
                "Physical Critical Chance": {
                    aliases: ["PCC", "CC", "Crit Chance", "Critical Chance", "Physical Crit Chance"],
                },
                "Special Critical Chance": {
                    aliases: ["SCC", "Special Crit Chance"]
                },
                "Critical Damage": {
                    aliases: ["CD", "Crit Damage"]
                },
                "Tenacity": {
                    aliases: ["Ten"]
                },
                "Accuracy": {
                    aliases: []
                },
                "Armor": {
                    aliases: []
                },
                "Resistance": {
                    aliases: ["Res", "Resist"]
                }
            };
            let found = false;
            if (searchChar.length) options.subArgs.b = options.subArgs.b + " " + searchChar;
            if (Object.keys(checkableStats).filter(c => c.toLowerCase() === options.subArgs.b.toLowerCase()).length > 0) {
                options.subArgs.b =  options.subArgs.b.toProperCase();
                found = true;
            } else {
                Object.keys(checkableStats).forEach(s => {
                    if (checkableStats[s].aliases.filter(c => c.toLowerCase() === options.subArgs.b.toLowerCase()).length > 0) {
                        options.subArgs.b = s;
                        found = true;
                        return;
                    }
                });
            }
            if (!found) {
                return msg.edit(message.language.get("COMMAND_MYMODS_BAD_STAT", client.codeBlock(Object.keys(checkableStats).join("\n"))));
            }
            const statToCheck = options.subArgs.b;
            const stats = await client.swgohAPI.unitStats(allyCode, cooldown);

            stats.forEach(c => {
                if (c.stats.final && !c.stats.final[statToCheck]) {
                    c.stats.final[statToCheck] = 0;
                }
                if (c.stats.mods && !c.stats.mods[statToCheck]) {
                    c.stats.mods[statToCheck] = 0;
                }
            });

            let sorted;
            if (options.flags.t) {
                sorted = stats.sort((p, c) => p.stats.final && c.stats.final && p.stats.final[statToCheck] > c.stats.final[statToCheck] ? -1 : 1);
            } else {
                sorted = stats.sort((p, c) => p.stats.mods && c.stats.mods && p.stats.mods[statToCheck] > c.stats.mods[statToCheck] ? -1 : 1);

            }
            const out = sorted.map(c => {
                const finalStat = c.stats.final ? (c.stats.final[statToCheck] % 1 === 0 ? c.stats.final[statToCheck] : (c.stats.final[statToCheck] * 100).toFixed(2)+"%") : 0;
                const modStat = c.stats.mods && c.stats.mods[statToCheck] ? (c.stats.mods[statToCheck] % 1 === 0 ? `(${c.stats.mods[statToCheck]})` : `(${(c.stats.mods[statToCheck] * 100).toFixed(2)}%)`) : "";
                return {
                    stat: `${finalStat}${modStat.length ? " " + modStat : ""}`,
                    name: `: ${c.unit.name}`
                };
            });
            const longest = out.reduce((max, s) => Math.max(max, s.stat.length), 0);
            let outStr = "";
            for (let ix = 0; ix < 10; ix++) {
                outStr += "`" + out[ix].stat + ` ${client.zws}`.repeat(longest-out[ix].stat.length) + "`**" + out[ix].name + "**\n";
            }
            const author = {};
            if (options.flags.t) {
                // ${playerName}'s Highest ${stat} Characters
                author.name = message.language.get("COMMAND_MYMODS_HEADER_TOTAL", stats[0].unit.player, options.subArgs.b);
            } else {
                // ${playerName}'s Best ${stat} From Mods
                author.name = message.language.get("COMMAND_MYMODS_HEADER_MODS", stats[0].unit.player, options.subArgs.b);
            }
            return msg.edit({embed: {
                author: author,
                description: "==============================\n" + outStr + "=============================="
            }});
        }
    }
}

module.exports = MyMods;

<commit_msg>And again, fixed MyMods<commit_after>const Command = require("../base/Command");
// const moment = require('moment');
require("moment-duration-format");

class MyMods extends Command {
    constructor(client) {
        super(client, {
            name: "mymods",
            category: "SWGoH",
            guildOnly: false,
            aliases: ["charactermods", "charmods", "cmods", "cm", "mm"],
            permissions: ["EMBED_LINKS"],
            subArgs: {
                b: {
                    aliases: ["best"],
                    default: null
                }
            },
            flags: {
                t: {
                    aliases: ["total"]
                }
            }
        });
    }

    async run(client, message, [userID, ...searchChar], options) { // eslint-disable-line no-unused-vars
        // const lang = message.guildSettings.swgohLanguage;
        const cooldown = client.getPlayerCooldown(message.author.id);
        const icons = {
            STATMOD_SLOT_01: await client.getEmoji("362066327101243392") || "Square",
            STATMOD_SLOT_02: await client.getEmoji("362066325474115605") || "Arrow",
            STATMOD_SLOT_03: await client.getEmoji("362066326925082637") || "Diamond",
            STATMOD_SLOT_04: await client.getEmoji("362066327168352257") || "Triangle",
            STATMOD_SLOT_05: await client.getEmoji("362066326996385812") || "Circle",
            STATMOD_SLOT_06: await client.getEmoji("362066327516610570") || "Cross"
        };

        if (searchChar) searchChar = searchChar.join(" ");

        // Need to get the allycode from the db, then use that
        if (!userID) {
            if (!options.subArgs.b) {
                return message.channel.send(message.language.get("BASE_SWGOH_MISSING_CHAR"));
            } else {
                userID = message.author.id;
            }
        } else if (userID === "me") {
            userID = message.author.id;
        } else if (client.isAllyCode(userID) || client.isUserID(userID)) {
            userID = userID.replace(/[^\d]*/g, "");
        } else {
            // If they're just looking for a character for themselves, get the char
            searchChar = userID + " " + searchChar;
            searchChar = searchChar.trim();
            userID = message.author.id;
        }

        const msg = await message.channel.send(message.language.get("COMMAND_MYMODS_WAIT"));

        const allyCodes = await client.getAllyCode(message, userID);
        if (!allyCodes.length) {
            return msg.edit(message.language.get("BASE_SWGOH_NOT_REG", client.users.get(userID).tag));
        } else if (allyCodes.length > 1) {
            return msg.edit("Found " + allyCodes.length + " matches. Please make sure your code is correct.");
        }

        const allyCode = allyCodes[0];

        if (!options.subArgs.b) {
            let character;
            if (!searchChar) {
                return msg.edit(message.language.get("BASE_SWGOH_MISSING_CHAR"));
            }

            const chars = client.findChar(searchChar, client.characters);
            if (chars.length === 0) {
                return msg.edit(message.language.get("BASE_SWGOH_NO_CHAR_FOUND", searchChar));
            } else if (chars.length > 1) {
                const charL = [];
                const charS = chars.sort((p, c) => p.name > c.name ? 1 : -1);
                charS.forEach(c => {
                    charL.push(c.name);
                });
                return msg.edit(message.language.get("BASE_SWGOH_CHAR_LIST", charL.join("\n")));
            } else {
                character = chars[0];
            }

            let player;
            try {
                player = await client.swgohAPI.player(allyCode, null, cooldown);
            } catch (e) {
                console.log(e);
            }

            const charMods = player.roster.filter(c => c.defId === character.uniqueName)[0].mods;

            const slots = {};

            const sets = message.language.get("BASE_MODSETS_FROM_GAME");
            const stats = message.language.get("BASE_MODS_FROM_GAME");

            charMods.forEach(mod => {
                slots[mod.slot] = {
                    stats: [],
                    type: sets[mod.set],
                    lvl: mod.level,
                    pip: mod.pips
                };

                // Add the primary in
                slots[mod.slot].stats.push(`${mod.primaryStat.value} ${stats[mod.primaryStat.unitStat].replace("+", "").replace("%", "")}`);

                // Then all the secondaries
                mod.secondaryStat.forEach(s => {
                    let t = stats[s.unitStat];
                    if (t.indexOf("%") > -1) {
                        t = t.replace("%", "").trim();
                        s.value = s.value.toFixed(2) + "%";
                    }

                    let statStr = s.value;
                    if (s.roll > 0) statStr = `(${s.roll}) ${statStr}`;
                    statStr +=  " " + t;
                    slots[mod.slot].stats.push(statStr);
                });
            });

            const fields = [];
            Object.keys(slots).forEach(mod => {
                const stats = slots[mod].stats;
                fields.push({
                    name: `${icons[`STATMOD_SLOT_0${mod}`]} ${slots[mod].type} (${slots[mod].pip}* Lvl: ${slots[mod].lvl})`,
                    value: `**${stats.shift()}**\n${stats.join("\n")}\n\`${"-".repeat(28)}\``,
                    inline: true
                });
            });

            msg.edit({embed: {
                author: {
                    name: `${player.name}'s ${character.name}`,
                    icon_url: character.avatarURL
                },
                fields: fields,
                footer: {
                    text: message.language.get("BASE_SWGOH_LAST_UPDATED", client.duration(player.updated, message))
                }
            }});
        } else {
            const checkableStats = {
                "Health": {
                    aliases: ["HP"]
                },
                "Protection": {
                    aliases: ["Prot"]
                },
                "Speed": {
                    aliases: []
                },
                "Potency": {
                    aliases: ["Pot"]
                },
                "Physical Critical Chance": {
                    aliases: ["PCC", "CC", "Crit Chance", "Critical Chance", "Physical Crit Chance"],
                },
                "Special Critical Chance": {
                    aliases: ["SCC", "Special Crit Chance"]
                },
                "Critical Damage": {
                    aliases: ["CD", "Crit Damage"]
                },
                "Tenacity": {
                    aliases: ["Ten"]
                },
                "Accuracy": {
                    aliases: []
                },
                "Armor": {
                    aliases: []
                },
                "Resistance": {
                    aliases: ["Res", "Resist"]
                }
            };
            let found = false;
            if (searchChar.length) options.subArgs.b = options.subArgs.b + " " + searchChar;
            if (Object.keys(checkableStats).filter(c => c.toLowerCase() === options.subArgs.b.toLowerCase()).length > 0) {
                options.subArgs.b =  options.subArgs.b.toProperCase();
                found = true;
            } else {
                Object.keys(checkableStats).forEach(s => {
                    if (checkableStats[s].aliases.filter(c => c.toLowerCase() === options.subArgs.b.toLowerCase()).length > 0) {
                        options.subArgs.b = s;
                        found = true;
                        return;
                    }
                });
            }
            if (!found) {
                return msg.edit(message.language.get("COMMAND_MYMODS_BAD_STAT", client.codeBlock(Object.keys(checkableStats).join("\n"))));
            }
            const statToCheck = options.subArgs.b;
            const stats = await client.swgohAPI.unitStats(allyCode, cooldown);

            stats.forEach(c => {
                if (c.stats.final && !c.stats.final[statToCheck]) {
                    c.stats.final[statToCheck] = 0;
                }
                if (c.stats.mods && !c.stats.mods[statToCheck]) {
                    c.stats.mods[statToCheck] = 0;
                }
            });

            let sorted;
            if (options.flags.t) {
                sorted = stats.sort((p, c) => p.stats.final && c.stats.final && p.stats.final[statToCheck] > c.stats.final[statToCheck] ? -1 : 1);
            } else {
                sorted = stats.sort((p, c) => p.stats.mods && c.stats.mods && p.stats.mods[statToCheck] > c.stats.mods[statToCheck] ? -1 : 1);

            }
            const out = sorted.map(c => {
                const finalStat = c.stats.final ? (c.stats.final[statToCheck] % 1 === 0 ? c.stats.final[statToCheck] : (c.stats.final[statToCheck] * 100).toFixed(2)+"%") : 0;
                const modStat = c.stats.mods && c.stats.mods[statToCheck] ? (c.stats.mods[statToCheck] % 1 === 0 ? `(${c.stats.mods[statToCheck]})` : `(${(c.stats.mods[statToCheck] * 100).toFixed(2)}%)`) : "";
                return {
                    stat: `${finalStat}${modStat.length ? " " + modStat : ""}`,
                    name: `: ${c.unit.name}`
                };
            });
            const longest = out.reduce((max, s) => Math.max(max, s.stat.length), 0);
            let outStr = "";
            for (let ix = 0; ix < 10; ix++) {
                outStr += "`" + out[ix].stat + ` ${client.zws}`.repeat(longest-out[ix].stat.length) + "`**" + out[ix].name + "**\n";
            }
            const author = {};
            if (options.flags.t) {
                // ${playerName}'s Highest ${stat} Characters
                author.name = message.language.get("COMMAND_MYMODS_HEADER_TOTAL", stats[0].unit.player, options.subArgs.b);
            } else {
                // ${playerName}'s Best ${stat} From Mods
                author.name = message.language.get("COMMAND_MYMODS_HEADER_MODS", stats[0].unit.player, options.subArgs.b);
            }
            return msg.edit({embed: {
                author: author,
                description: "==============================\n" + outStr + "=============================="
            }});
        }
    }
}

module.exports = MyMods;

<|endoftext|>


<commit_before>"use strict";

var d3 = require('d3')
  , h = require('react-hyperscript')
  , React = require('react')

const width = 1600
    , height = 200
    , padding = 50

module.exports = React.createClass({
  name: 'Timeline',

  getInitialState() {
    return { rendering: false }
  },

  update() {
    this.setState({ rendering: true });

    const svg = d3.select(this.refs.svg)
        , t = svg.transition().duration(420)
        , dates = this.props.dates.toArray()

    const x = (
      d3.time.scale()
        .range([0, width - padding])
        .domain(d3.extent(dates))
    );

    const data = (
      d3.layout.histogram()
        .bins(x.ticks(100))(dates)
    );

    data.pop();

    const y = (
      d3.scale.linear()
        .range([height - padding, 0])
        .domain([0, d3.max(data, d => d.y)])
    );

    const line = (
      d3.svg.line()
        .x(d => x(d.x))
        .y(d => y(d.y))
        .interpolate('step')
    )

    t.select('.x-axis').call(
      d3.svg.axis()
        .scale(x)
        .orient('bottom')
        .ticks(8)
    );

    t.select('.y-axis').call(
      d3.svg.axis()
        .scale(y)
        .orient('left')
        .ticks(4)
    );

    t.select('.data').attr('d', line(data));

    setTimeout(() => {
      this.setState({ rendering: false });
    }, 420);
  },

  componentDidUpdate() {
    const { rendering } = this.state

    if (!rendering) {
      this.update();
    }
  },

  render() {
    return (
      h('svg', {
        ref: 'svg',
        height,
        width
      }, [
        h('g', {
          transform: `translate(${padding},${padding / 2})`
        }, [
          h('g .x-axis', {
            transform: `translate(0,${height - padding})`
          }),
          h('g .y-axis'),
          h('path .data', {
            stroke: 'red',
            fill: 'none'
          })
        ])
      ])
    )
  }
});
<commit_msg>Omit the last line in the histogram.<commit_after>"use strict";

var d3 = require('d3')
  , h = require('react-hyperscript')
  , React = require('react')

const width = 1600
    , height = 200
    , padding = 50

module.exports = React.createClass({
  name: 'Timeline',

  getInitialState() {
    return { rendering: false }
  },

  update() {
    this.setState({ rendering: true });

    const svg = d3.select(this.refs.svg)
        , t = svg.transition().duration(420)
        , dates = this.props.dates.toArray()

    const x = (
      d3.time.scale()
        .range([0, width - padding])
        .domain(d3.extent(dates))
    );

    const data = (
      d3.layout.histogram()
        .bins(x.ticks(100))(dates)
    );

    // data.pop();

    const y = (
      d3.scale.linear()
        .range([height - padding, 0])
        .domain([0, d3.max(data, d => d.y)])
    );

    const line = (
      d3.svg.line()
        .x(d => x(d.x))
        .y(d => y(d.y))
        .interpolate('step')
    )

    t.select('.x-axis').call(
      d3.svg.axis()
        .scale(x)
        .orient('bottom')
        .ticks(8)
    );

    t.select('.y-axis').call(
      d3.svg.axis()
        .scale(y)
        .orient('left')
        .ticks(4)
    );

    t.select('.data').attr('d', line(data));

    setTimeout(() => {
      this.setState({ rendering: false });
    }, 420);
  },

  componentDidUpdate() {
    const { rendering } = this.state

    if (!rendering) {
      this.update();
    }
  },

  render() {
    return (
      h('svg', {
        ref: 'svg',
        height,
        width
      }, [
        h('g', {
          transform: `translate(${padding},${padding / 2})`
        }, [
          h('g .x-axis', {
            transform: `translate(0,${height - padding})`
          }),
          h('g .y-axis'),
          h('path .data', {
            stroke: 'red',
            fill: 'none'
          })
        ])
      ])
    )
  }
});
<|endoftext|>


<commit_before>/**
 * Created by quasarchimaere on 21.01.2019.
 */
import { get } from "../../utils.js";
import * as processUtils from "../utils/process-utils.js";
import { createSelector } from "reselect";
import { getPossibleRequestCredentialsForAtom } from "~/app/redux/selectors/general-selectors";

const getProcessState = createSelector(
  state => get(state, "process"),
  state => state
);

/**
 * Check if anything in the state sub-map of process is currently marked as loading
 * @param state (full redux-state)
 * @returns true if anything is currently loading
 */
export const isLoading = createSelector(
  getProcessState,
  process =>
    processUtils.isProcessingInitialLoad(process) ||
    processUtils.isProcessingWhatsAround(process) ||
    processUtils.isProcessingMetaAtoms(process) ||
    processUtils.isProcessingWhatsNew(process) ||
    processUtils.isProcessingLogin(process) ||
    processUtils.isProcessingLogout(process) ||
    processUtils.isProcessingPublish(process) ||
    processUtils.isProcessingAcceptTermsOfService(process) ||
    processUtils.isProcessingVerifyEmailAddress(process) ||
    processUtils.isProcessingResendVerificationEmail(process) ||
    processUtils.isProcessingSendAnonymousLinkEmail(process) ||
    processUtils.isAnyAtomLoading(process) ||
    processUtils.isAnyConnectionLoadingMessages(process) ||
    processUtils.isAnyConnectionLoading(process, true) ||
    processUtils.isAnyConnectionContainerLoading(process)
);

export const isProcessingWhatsNew = createSelector(getProcessState, process =>
  processUtils.isProcessingWhatsNew(process)
);

export const isProcessingPublish = createSelector(getProcessState, process =>
  processUtils.isProcessingPublish(process)
);

export const isProcessingAcceptTermsOfService = createSelector(
  getProcessState,
  process => processUtils.isProcessingAcceptTermsOfService(process)
);

export const isProcessingVerifyEmailAddress = createSelector(
  getProcessState,
  process => processUtils.isProcessingVerifyEmailAddress(process)
);

export const isProcessingResendVerificationEmail = createSelector(
  getProcessState,
  process => processUtils.isProcessingResendVerificationEmail(process)
);

export const isProcessingSendAnonymousLinkEmail = createSelector(
  getProcessState,
  process => processUtils.isProcessingSendAnonymousLinkEmail(process)
);

export const isAtomLoading = atomUri =>
  createSelector(getProcessState, processState =>
    processUtils.isAtomLoading(processState, atomUri)
  );

export const getAtomRequests = atomUri =>
  createSelector(getProcessState, processState =>
    processUtils.getAtomRequests(processState, atomUri)
  );

export const getConnectionContainerRequests = atomUri =>
  createSelector(getProcessState, processState =>
    processUtils.getConnectionContainerRequests(processState, atomUri)
  );

export const getFetchTokenRequests = (atomUri, tokenScopeUri) =>
  createSelector(getProcessState, processState =>
    processUtils.getFetchTokenRequests(processState, atomUri, tokenScopeUri)
  );

export const getAllConnectionContainerRequests = createSelector(
  getProcessState,
  processState =>
    get(processState, ["connectionContainers"]).map(atom =>
      get(atom, "connectionContainers")
    )
);

export const getAllAtomRequests = createSelector(
  getProcessState,
  processState =>
    get(processState, ["atoms"]).map(atom => get(atom, "requests"))
);

export const getUnusedRequestCredentialsForConnectionContainer = createSelector(
  state => state,
  getProcessState,
  state => get(state, "atoms"),
  (state, processState, atoms) =>
    atoms
      .filterNot(
        (_, atomUri) =>
          processUtils.isConnectionContainerToLoad(processState, atomUri) ||
          processUtils.isConnectionContainerLoading(processState, atomUri)
      )
      .map((_, atomUri) => {
        const priorRequests = getConnectionContainerRequests(atomUri);
        return getPossibleRequestCredentialsForAtom(atomUri)(state).filterNot(
          requestCredentials =>
            processUtils.isUsedCredentials(priorRequests, requestCredentials)
        );
      })
      .filter(
        requestCredentials => requestCredentials && requestCredentials.size > 0
      )
);
<commit_msg>Adds missing function execution<commit_after>/**
 * Created by quasarchimaere on 21.01.2019.
 */
import { get } from "../../utils.js";
import * as processUtils from "../utils/process-utils.js";
import { createSelector } from "reselect";
import { getPossibleRequestCredentialsForAtom } from "~/app/redux/selectors/general-selectors";

const getProcessState = createSelector(
  state => get(state, "process"),
  state => state
);

/**
 * Check if anything in the state sub-map of process is currently marked as loading
 * @param state (full redux-state)
 * @returns true if anything is currently loading
 */
export const isLoading = createSelector(
  getProcessState,
  process =>
    processUtils.isProcessingInitialLoad(process) ||
    processUtils.isProcessingWhatsAround(process) ||
    processUtils.isProcessingMetaAtoms(process) ||
    processUtils.isProcessingWhatsNew(process) ||
    processUtils.isProcessingLogin(process) ||
    processUtils.isProcessingLogout(process) ||
    processUtils.isProcessingPublish(process) ||
    processUtils.isProcessingAcceptTermsOfService(process) ||
    processUtils.isProcessingVerifyEmailAddress(process) ||
    processUtils.isProcessingResendVerificationEmail(process) ||
    processUtils.isProcessingSendAnonymousLinkEmail(process) ||
    processUtils.isAnyAtomLoading(process) ||
    processUtils.isAnyConnectionLoadingMessages(process) ||
    processUtils.isAnyConnectionLoading(process, true) ||
    processUtils.isAnyConnectionContainerLoading(process)
);

export const isProcessingWhatsNew = createSelector(getProcessState, process =>
  processUtils.isProcessingWhatsNew(process)
);

export const isProcessingPublish = createSelector(getProcessState, process =>
  processUtils.isProcessingPublish(process)
);

export const isProcessingAcceptTermsOfService = createSelector(
  getProcessState,
  process => processUtils.isProcessingAcceptTermsOfService(process)
);

export const isProcessingVerifyEmailAddress = createSelector(
  getProcessState,
  process => processUtils.isProcessingVerifyEmailAddress(process)
);

export const isProcessingResendVerificationEmail = createSelector(
  getProcessState,
  process => processUtils.isProcessingResendVerificationEmail(process)
);

export const isProcessingSendAnonymousLinkEmail = createSelector(
  getProcessState,
  process => processUtils.isProcessingSendAnonymousLinkEmail(process)
);

export const isAtomLoading = atomUri =>
  createSelector(getProcessState, processState =>
    processUtils.isAtomLoading(processState, atomUri)
  );

export const getAtomRequests = atomUri =>
  createSelector(getProcessState, processState =>
    processUtils.getAtomRequests(processState, atomUri)
  );

export const getConnectionContainerRequests = atomUri =>
  createSelector(getProcessState, processState =>
    processUtils.getConnectionContainerRequests(processState, atomUri)
  );

export const getFetchTokenRequests = (atomUri, tokenScopeUri) =>
  createSelector(getProcessState, processState =>
    processUtils.getFetchTokenRequests(processState, atomUri, tokenScopeUri)
  );

export const getAllConnectionContainerRequests = createSelector(
  getProcessState,
  processState =>
    get(processState, ["connectionContainers"]).map(atom =>
      get(atom, "connectionContainers")
    )
);

export const getAllAtomRequests = createSelector(
  getProcessState,
  processState =>
    get(processState, ["atoms"]).map(atom => get(atom, "requests"))
);

export const getUnusedRequestCredentialsForConnectionContainer = createSelector(
  state => state,
  getProcessState,
  state => get(state, "atoms"),
  (state, processState, atoms) =>
    atoms
      .filterNot(
        (_, atomUri) =>
          processUtils.isConnectionContainerToLoad(processState, atomUri) ||
          processUtils.isConnectionContainerLoading(processState, atomUri)
      )
      .map((_, atomUri) => {
        const priorRequests = getConnectionContainerRequests(atomUri)(state);
        return getPossibleRequestCredentialsForAtom(atomUri)(state).filterNot(
          requestCredentials =>
            processUtils.isUsedCredentials(priorRequests, requestCredentials)
        );
      })
      .filter(
        requestCredentials => requestCredentials && requestCredentials.size > 0
      )
);
<|endoftext|>


<commit_before>import { options } from 'preact';

const hasWindow = typeof window !== 'undefined';
const mc = new MessageChannel();

/** @type {number} */
let currentIndex;

/** @type {import('./internal').Component} */
let currentComponent;

/** @type {Array<import('./internal').Component>} */
let afterPaintEffects = [];

/** @type {boolean} */
let stateChanged;

// Temp variables used by for loop
// let i, j;

let oldBeforeRender = options.beforeRender;
options.beforeRender = vnode => {
	if (oldBeforeRender) oldBeforeRender(vnode);

	currentComponent = vnode._component;
	currentIndex = 0;

	// !Drain queue

	// ORIGINAL: 874 B
	// const hooks = currentComponent.__hooks;
	// if (!hooks) return;
	// let effect;
	// while (effect = hooks._pendingEffects.shift()) {
	// 	invokeEffect(effect);
	// }

	// WHILE (SHIFT): 855 B
	// const hooks = currentComponent.__hooks;
	// if (!hooks) return;
	// let effect;
	// while (effect = hooks._pendingEffects.shift()) {
	// 	invokeEffect(effect);
	// }

	// WHILE (POP): 853 B
	// const hooks = currentComponent.__hooks;
	// if (!hooks) return;
	// let effect;
	// while (effect=hooks._pendingEffects.pop()) {
	// 	invokeEffect(effect);
	// }

	// FOR (TEMP): 886 B
	// if (!currentComponent.__hooks) return;
	// let list = currentComponent.__hooks._pendingEffects; currentComponent.__hooks._pendingEffects = [];
	// for (i = 0; i < list.length; i++) {
	// 	invokeEffect(list[i]);
	// }

	// FOREACH (SPLICE): 837 B
	// if (!currentComponent.__hooks) return;
	// currentComponent.__hooks._pendingEffects.splice(0, currentComponent.__hooks._pendingEffects.length).forEach(invokeEffect);

	// FOREACH (TEMP): 832 B
	if (!currentComponent.__hooks) return;
	let effects = currentComponent.__hooks._pendingEffects; currentComponent.__hooks._pendingEffects = [];
	effects.forEach(invokeEffect);

	// FOREACH (RESET AFTER): 829 B
	// if (!currentComponent.__hooks) return;
	// currentComponent.__hooks._pendingEffects.forEach(invokeEffect);
	// currentComponent.__hooks._pendingEffects = [];
};

let oldAfterDiff = options.afterDiff;
options.afterDiff = vnode => {
	if (oldAfterDiff) oldAfterDiff(vnode);

	const c = vnode._component;
	if (!c) return;

	const hooks = c.__hooks;
	if (!hooks) return;

	stateChanged = false;

	// !Drain queue

	// ORIGINAL: 874 B
	// let effect;
	// while (effect = hooks._pendingLayoutEffects.shift()) {
	// 	invokeEffect(effect);
	// }

	// WHILE (SHIFT): 855 B
	// let effect;
	// while (effect = hooks._pendingLayoutEffects.shift()) {
	// 	invokeEffect(effect);
	// }

	// WHILE (POP): 853 B
	// let effect;
	// while (effect=hooks._pendingLayoutEffects.pop()) {
	// 	invokeEffect(effect);
	// }

	// FOR (TEMP): 886 B
	// let list = hooks._pendingLayoutEffects; hooks._pendingLayoutEffects = [];
	// for (i = 0; i < list.length; i++) {
	// 	invokeEffect(list[i]);
	// }

	// FOREACH (SPLICE): 837 B
	// hooks._pendingLayoutEffects.splice(0, hooks._pendingLayoutEffects.length).forEach(invokeEffect);

	// FOREACH (TEMP): 832 B
	// NOTE: Tests pass without neding to store effects in a temp variable when
	// using forEach, so using RESET AFTER strategy here
	hooks._pendingLayoutEffects.forEach(invokeEffect);
	hooks._pendingLayoutEffects = [];

	// FOREACH (RESET AFTER): 829 B
	// hooks._pendingLayoutEffects.forEach(invokeEffect);
	// hooks._pendingLayoutEffects = [];

	if (stateChanged) c.forceUpdate();
};

let oldBeforeUnmount = options.beforeUnmount;
options.beforeUnmount = vnode => {
	if (oldBeforeUnmount) oldBeforeUnmount(vnode);

	const hooks = vnode._component.__hooks;
	if (!hooks) return;

	// ORIGINAL: 874 B
	// for (let i = 0; i < hooks._list.length; i++) {
	// 	if (hooks._list[i]._cleanup) {
	// 		hooks._list[i]._cleanup();
	// 	}
	// }

	// WHILE (SHIFT): 855 B
	// let hook;
	// while (hook = hooks._list.shift()) {
	// 	if (hook._cleanup) {
	// 		hook._cleanup();
	// 	}
	// }

	// WHILE (POP): 853 B
	// let hook;
	// while (hook = hooks._list.pop()) {
	// 	if (hook._cleanup) {
	// 		hook._cleanup();
	// 	}
	// }

	// FOR: 886 B
	// for (let i = 0; i < hooks._list.length; i++) {
	// 	if (hooks._list[i]._cleanup) {
	// 		hooks._list[i]._cleanup();
	// 	}
	// }

	// FOREACH: 837 B, 832 B, 829 B
	hooks._list.forEach(hook => hook._cleanup && hook._cleanup());
};

/**
 * Create a Hook instance and invoke its implementation as determined by
 * the `shouldRun` parameter
 * @param {import('./internal').HookImplementationFactory} create
 * @param {import('./internal').HookShouldRun} [shouldRun]
 * @returns {import('./internal').Hook}
 */
const createHook = (create, shouldRun) => (...args) => {
	if (!currentComponent) return;

	const hooks = currentComponent.__hooks || (currentComponent.__hooks = { _list: [], _pendingEffects: [], _pendingLayoutEffects: [] });

	let _index = currentIndex++;
	let hook = hooks._list[_index];

	if (!hook) {
		hook = hooks._list[_index] = { _index };
		hook._run = create(hook, currentComponent, ...args);
	}
	else if (shouldRun && shouldRun(hook._args, args) === false) {
		return hook._value;
	}

	hook._args = args;

	return (hook._value = hook._run(...args));
};

const useStateReducer = (state, newState) => typeof newState === 'function' ? newState(state) : newState;
export const useState = initialState => useReducer(useStateReducer, initialState);

export const useReducer = createHook((hook, component, reducer, initialState, initialAction) => {
	const initState = typeof initialState === 'function' ? initialState() : initialState;
	const ret = [
		component.state[hook._index] = initialAction ? reducer(initState, initialAction) : initState,
		action => {
			const setter = {};
			ret[0] = setter[hook._index] = reducer(ret[0], action);
			stateChanged = true;
			component.setState(setter);
		}
	];
	return () => ret;
});

// eslint-disable-next-line arrow-body-style
export const useEffect = hasWindow ? createHook((hook, component) => {
	return callback => {
		component.__hooks._pendingEffects.push(hook);
		afterPaint(component);
		return callback;
	};
}, propsChanged) : noop;

// eslint-disable-next-line arrow-body-style
export const useLayoutEffect = hasWindow ? createHook((hook, component) => {
	return callback => {
		component.__hooks._pendingLayoutEffects.push(hook);
		return callback;
	};
}, propsChanged) : noop;

export const useRef = createHook((hook, component, initialValue) => {
	const ref = { current: initialValue };
	return () => ref;
});

export const useMemo = createHook(() => callback => callback(), memoChanged);
export const useCallback = createHook(() => callback => callback, propsChanged);

// Note: if someone used Component.debounce = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
 * Invoke a component's pending effects after the next frame renders
 * @param {import('./internal').Component} args
 */
function afterPaint(args) {
	if (afterPaintEffects.push(args) === 1) {
		requestAnimationFrame(onPaint);
	}
}

function onPaint() {
	mc.port1.postMessage(0);
}

mc.port2.onmessage = () => {
	// !Drain Queue

	// ORIGINAL: 874 B
	// afterPaintEffects.splice(0, afterPaintEffects.length).forEach(component => {
	// 	if (!component._parentDom) return;
	// 	const effects = component.__hooks._pendingEffects;
	// 	// !Drain Queue 2
	// 	effects.splice(0, effects.length).forEach(invokeEffect);
	// });

	// WHILE (SHIFT): 855 B  ❌ if we don't support sync Component.debounce. See 852 B comment below.
	// let c, effect;
	// while (c = afterPaintEffects.shift()) {
	// 	if (!c._parentDom) continue;
	// 	while (effect = c.__hooks._pendingEffects.shift()) {
	// 		invokeEffect(effect);
	// 	}
	// }

	// WHILE (POP): 853 B  ❌ if we don't support sync Component.debounce. See 852 B comment below.
	// let c, effect;
	// while (c = afterPaintEffects.pop()) {
	// 	if (!c._parentDom) continue;
	// 	while (effect = c.__hooks._pendingEffects.pop()) {
	// 		invokeEffect(effect);
	// 	}
	// }

	// FOR (TEMP): 886 B
	// let list1 = afterPaintEffects; afterPaintEffects = [];
	// for (j = 0; j < list1.length; j++) {
	// 	currentComponent = list1[j];
	// 	if (!currentComponent._parentDom) continue;
	// 	let list2 = currentComponent.__hooks._pendingEffects; currentComponent.__hooks._pendingEffects = [];
	// 	for (i = 0; i < list2.length; i++) {
	// 		invokeEffect(list2[i]);
	// 	}
	// }

	// FOREACH (SPLICE): 837 B
	// afterPaintEffects.splice(0, afterPaintEffects.length).forEach(component => {
	// 	if (!component._parentDom) return;
	// 	component.__hooks._pendingEffects.splice(0, component.__hooks._pendingEffects.length).forEach(invokeEffect);
	// });

	// FOREACH (TEMP): 832 B
	afterPaintEffects.forEach(component => {
		if (!component._parentDom) return;
		let effects = component.__hooks._pendingEffects; component.__hooks._pendingEffects = [];
		effects.forEach(invokeEffect);
	});
	afterPaintEffects = [];

	// FOREACH (RESET AFTER): 829 B ❌
	// Doesn't pass sync debounce test cuz we need to clear the _pendingEffects
	// list before traversing it to avoid re-entering effects in the beforeRender loop
	// afterPaintEffects.forEach(component => {
	// 	if (!component._parentDom) return;
	// 	component.__hooks._pendingEffects.forEach(invokeEffect);
	// 	component.__hooks._pendingEffects = [];
	// });
	// afterPaintEffects = [];
};

/**
 * Invoke a Hook's effect
 * @param {import('./internal').HookInstance} hook
 */
function invokeEffect(hook) {
	if (hook._cleanup) hook._cleanup();
	const result = hook._value();
	if (typeof result === 'function') hook._cleanup = result;
}

function propsChanged(oldArgs, newArgs) {
	const props = newArgs[1];
	if (!props) return;

	// ORIGINAL: 874 B
	// const oldProps = oldArgs[1];
	// for (let i = 0; i < props.length; i++) {
	// 	if (props[i] !== oldProps[i]) return true;
	// }
	// return false;

	// WHILE: 855 B (shift) or 853 B (pop)
	// NOTE: Terser rewrites while loop as for loop
	// const oldProps = oldArgs[1];
	// let i = 0;
	// while (i < props.length) {
	// 	if (props[i] !== oldProps[i]) return true;
	// 	i++;
	// }
	// return false;

	// FOR: 886 B
	// const oldProps = oldArgs[1];
	// for (let i = 0; i < props.length; i++) {
	// 	if (props[i] !== oldProps[i]) return true;
	// }
	// return false;

	// FOREACH: 837 B, 832 B, 829 B
	return props.some((prop, index) => prop !== oldArgs[1][index]);
}

function memoChanged(oldArgs, newArgs) {
	const propsDidChange = propsChanged(oldArgs, newArgs);

	return propsDidChange !== undefined
		? propsDidChange
		: newArgs[0] !== oldArgs[0];
}

function noop() {}
<commit_msg>Simplify propsChanged and memoChanged (816 B)<commit_after>import { options } from 'preact';

const hasWindow = typeof window !== 'undefined';
const mc = new MessageChannel();

/** @type {number} */
let currentIndex;

/** @type {import('./internal').Component} */
let currentComponent;

/** @type {Array<import('./internal').Component>} */
let afterPaintEffects = [];

/** @type {boolean} */
let stateChanged;

// Temp variables used by for loop
// let i, j;

let oldBeforeRender = options.beforeRender;
options.beforeRender = vnode => {
	if (oldBeforeRender) oldBeforeRender(vnode);

	currentComponent = vnode._component;
	currentIndex = 0;

	// !Drain queue

	// ORIGINAL: 874 B
	// const hooks = currentComponent.__hooks;
	// if (!hooks) return;
	// let effect;
	// while (effect = hooks._pendingEffects.shift()) {
	// 	invokeEffect(effect);
	// }

	// WHILE (SHIFT): 855 B
	// const hooks = currentComponent.__hooks;
	// if (!hooks) return;
	// let effect;
	// while (effect = hooks._pendingEffects.shift()) {
	// 	invokeEffect(effect);
	// }

	// WHILE (POP): 853 B
	// const hooks = currentComponent.__hooks;
	// if (!hooks) return;
	// let effect;
	// while (effect=hooks._pendingEffects.pop()) {
	// 	invokeEffect(effect);
	// }

	// FOR (TEMP): 886 B
	// if (!currentComponent.__hooks) return;
	// let list = currentComponent.__hooks._pendingEffects; currentComponent.__hooks._pendingEffects = [];
	// for (i = 0; i < list.length; i++) {
	// 	invokeEffect(list[i]);
	// }

	// FOREACH (SPLICE): 837 B
	// if (!currentComponent.__hooks) return;
	// currentComponent.__hooks._pendingEffects.splice(0, currentComponent.__hooks._pendingEffects.length).forEach(invokeEffect);

	// FOREACH (TEMP): 832 B
	if (!currentComponent.__hooks) return;
	let effects = currentComponent.__hooks._pendingEffects; currentComponent.__hooks._pendingEffects = [];
	effects.forEach(invokeEffect);

	// FOREACH (RESET AFTER): 829 B
	// if (!currentComponent.__hooks) return;
	// currentComponent.__hooks._pendingEffects.forEach(invokeEffect);
	// currentComponent.__hooks._pendingEffects = [];
};

let oldAfterDiff = options.afterDiff;
options.afterDiff = vnode => {
	if (oldAfterDiff) oldAfterDiff(vnode);

	const c = vnode._component;
	if (!c) return;

	const hooks = c.__hooks;
	if (!hooks) return;

	stateChanged = false;

	// !Drain queue

	// ORIGINAL: 874 B
	// let effect;
	// while (effect = hooks._pendingLayoutEffects.shift()) {
	// 	invokeEffect(effect);
	// }

	// WHILE (SHIFT): 855 B
	// let effect;
	// while (effect = hooks._pendingLayoutEffects.shift()) {
	// 	invokeEffect(effect);
	// }

	// WHILE (POP): 853 B
	// let effect;
	// while (effect=hooks._pendingLayoutEffects.pop()) {
	// 	invokeEffect(effect);
	// }

	// FOR (TEMP): 886 B
	// let list = hooks._pendingLayoutEffects; hooks._pendingLayoutEffects = [];
	// for (i = 0; i < list.length; i++) {
	// 	invokeEffect(list[i]);
	// }

	// FOREACH (SPLICE): 837 B
	// hooks._pendingLayoutEffects.splice(0, hooks._pendingLayoutEffects.length).forEach(invokeEffect);

	// FOREACH (TEMP): 832 B
	// NOTE: Tests pass without neding to store effects in a temp variable when
	// using forEach, so using RESET AFTER strategy here
	hooks._pendingLayoutEffects.forEach(invokeEffect);
	hooks._pendingLayoutEffects = [];

	// FOREACH (RESET AFTER): 829 B
	// hooks._pendingLayoutEffects.forEach(invokeEffect);
	// hooks._pendingLayoutEffects = [];

	if (stateChanged) c.forceUpdate();
};

let oldBeforeUnmount = options.beforeUnmount;
options.beforeUnmount = vnode => {
	if (oldBeforeUnmount) oldBeforeUnmount(vnode);

	const hooks = vnode._component.__hooks;
	if (!hooks) return;

	// ORIGINAL: 874 B
	// for (let i = 0; i < hooks._list.length; i++) {
	// 	if (hooks._list[i]._cleanup) {
	// 		hooks._list[i]._cleanup();
	// 	}
	// }

	// WHILE (SHIFT): 855 B
	// let hook;
	// while (hook = hooks._list.shift()) {
	// 	if (hook._cleanup) {
	// 		hook._cleanup();
	// 	}
	// }

	// WHILE (POP): 853 B
	// let hook;
	// while (hook = hooks._list.pop()) {
	// 	if (hook._cleanup) {
	// 		hook._cleanup();
	// 	}
	// }

	// FOR: 886 B
	// for (let i = 0; i < hooks._list.length; i++) {
	// 	if (hooks._list[i]._cleanup) {
	// 		hooks._list[i]._cleanup();
	// 	}
	// }

	// FOREACH: 837 B, 832 B, 829 B
	hooks._list.forEach(hook => hook._cleanup && hook._cleanup());
};

/**
 * Create a Hook instance and invoke its implementation as determined by
 * the `shouldRun` parameter
 * @param {import('./internal').HookImplementationFactory} create
 * @param {import('./internal').HookShouldRun} [shouldRun]
 * @returns {import('./internal').Hook}
 */
const createHook = (create, shouldRun) => (...args) => {
	if (!currentComponent) return;

	const hooks = currentComponent.__hooks || (currentComponent.__hooks = { _list: [], _pendingEffects: [], _pendingLayoutEffects: [] });

	let _index = currentIndex++;
	let hook = hooks._list[_index];

	if (!hook) {
		hook = hooks._list[_index] = { _index };
		hook._run = create(hook, currentComponent, ...args);
	}
	else if (shouldRun && shouldRun(hook._args, args) === false) {
		return hook._value;
	}

	hook._args = args;

	return (hook._value = hook._run(...args));
};

const useStateReducer = (state, newState) => typeof newState === 'function' ? newState(state) : newState;
export const useState = initialState => useReducer(useStateReducer, initialState);

export const useReducer = createHook((hook, component, reducer, initialState, initialAction) => {
	const initState = typeof initialState === 'function' ? initialState() : initialState;
	const ret = [
		component.state[hook._index] = initialAction ? reducer(initState, initialAction) : initState,
		action => {
			const setter = {};
			ret[0] = setter[hook._index] = reducer(ret[0], action);
			stateChanged = true;
			component.setState(setter);
		}
	];
	return () => ret;
});

// eslint-disable-next-line arrow-body-style
export const useEffect = hasWindow ? createHook((hook, component) => {
	return callback => {
		component.__hooks._pendingEffects.push(hook);
		afterPaint(component);
		return callback;
	};
}, propsChanged) : noop;

// eslint-disable-next-line arrow-body-style
export const useLayoutEffect = hasWindow ? createHook((hook, component) => {
	return callback => {
		component.__hooks._pendingLayoutEffects.push(hook);
		return callback;
	};
}, propsChanged) : noop;

export const useRef = createHook((hook, component, initialValue) => {
	const ref = { current: initialValue };
	return () => ref;
});

export const useMemo = createHook(() => callback => callback(), memoChanged);
export const useCallback = createHook(() => callback => callback, propsChanged);

// Note: if someone used Component.debounce = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
 * Invoke a component's pending effects after the next frame renders
 * @param {import('./internal').Component} args
 */
function afterPaint(args) {
	if (afterPaintEffects.push(args) === 1) {
		requestAnimationFrame(onPaint);
	}
}

function onPaint() {
	mc.port1.postMessage(0);
}

mc.port2.onmessage = () => {
	// !Drain Queue

	// ORIGINAL: 874 B
	// afterPaintEffects.splice(0, afterPaintEffects.length).forEach(component => {
	// 	if (!component._parentDom) return;
	// 	const effects = component.__hooks._pendingEffects;
	// 	// !Drain Queue 2
	// 	effects.splice(0, effects.length).forEach(invokeEffect);
	// });

	// WHILE (SHIFT): 855 B  ❌ if we don't support sync Component.debounce. See 852 B comment below.
	// let c, effect;
	// while (c = afterPaintEffects.shift()) {
	// 	if (!c._parentDom) continue;
	// 	while (effect = c.__hooks._pendingEffects.shift()) {
	// 		invokeEffect(effect);
	// 	}
	// }

	// WHILE (POP): 853 B  ❌ if we don't support sync Component.debounce. See 852 B comment below.
	// let c, effect;
	// while (c = afterPaintEffects.pop()) {
	// 	if (!c._parentDom) continue;
	// 	while (effect = c.__hooks._pendingEffects.pop()) {
	// 		invokeEffect(effect);
	// 	}
	// }

	// FOR (TEMP): 886 B
	// let list1 = afterPaintEffects; afterPaintEffects = [];
	// for (j = 0; j < list1.length; j++) {
	// 	currentComponent = list1[j];
	// 	if (!currentComponent._parentDom) continue;
	// 	let list2 = currentComponent.__hooks._pendingEffects; currentComponent.__hooks._pendingEffects = [];
	// 	for (i = 0; i < list2.length; i++) {
	// 		invokeEffect(list2[i]);
	// 	}
	// }

	// FOREACH (SPLICE): 837 B
	// afterPaintEffects.splice(0, afterPaintEffects.length).forEach(component => {
	// 	if (!component._parentDom) return;
	// 	component.__hooks._pendingEffects.splice(0, component.__hooks._pendingEffects.length).forEach(invokeEffect);
	// });

	// FOREACH (TEMP): 832 B
	afterPaintEffects.forEach(component => {
		if (!component._parentDom) return;
		let effects = component.__hooks._pendingEffects; component.__hooks._pendingEffects = [];
		effects.forEach(invokeEffect);
	});
	afterPaintEffects = [];

	// FOREACH (RESET AFTER): 829 B ❌
	// Doesn't pass sync debounce test cuz we need to clear the _pendingEffects
	// list before traversing it to avoid re-entering effects in the beforeRender loop
	// afterPaintEffects.forEach(component => {
	// 	if (!component._parentDom) return;
	// 	component.__hooks._pendingEffects.forEach(invokeEffect);
	// 	component.__hooks._pendingEffects = [];
	// });
	// afterPaintEffects = [];
};

/**
 * Invoke a Hook's effect
 * @param {import('./internal').HookInstance} hook
 */
function invokeEffect(hook) {
	if (hook._cleanup) hook._cleanup();
	const result = hook._value();
	if (typeof result === 'function') hook._cleanup = result;
}

function propsChanged(oldArgs, newArgs) {
	// const props = newArgs[1];
	// if (!props) return;

	// ORIGINAL: 874 B
	// const oldProps = oldArgs[1];
	// for (let i = 0; i < props.length; i++) {
	// 	if (props[i] !== oldProps[i]) return true;
	// }
	// return false;

	// WHILE: 855 B (shift) or 853 B (pop)
	// NOTE: Terser rewrites while loop as for loop
	// const oldProps = oldArgs[1];
	// let i = 0;
	// while (i < props.length) {
	// 	if (props[i] !== oldProps[i]) return true;
	// 	i++;
	// }
	// return false;

	// FOR: 886 B
	// const oldProps = oldArgs[1];
	// for (let i = 0; i < props.length; i++) {
	// 	if (props[i] !== oldProps[i]) return true;
	// }
	// return false;

	// FOREACH: 837 B, 832 B, 829 B
	// return props.some((prop, index) => prop !== oldArgs[1][index]);

	// FOREACH (SIMPLIFIED): 816 B
	return newArgs[1] === undefined || newArgs[1].some((prop, index) => prop !== oldArgs[1][index]);
}

function memoChanged(oldArgs, newArgs) {
	// 816 B
	return newArgs[1] !== undefined ? propsChanged(oldArgs, newArgs) : newArgs[0] !== oldArgs[0];

	// const propsDidChange = propsChanged(oldArgs, newArgs);
	// return propsDidChange !== undefined
	// 	? propsDidChange
	// 	: newArgs[0] !== oldArgs[0];
}

function noop() {}
<|endoftext|>


<commit_before>// required : -http://openlayers.org/dev/OpenLayers.js
//              -http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js

if (!('fms_store' in window)) {
    window.fms_store = {};
    window.fms_store.KEY_PREFERRED_DATA_TABLE_COLUMN_SORT = "fms-table-column-sort";
    window.fms_store.KEY_DATA_TABLE_INACTIVE_COLUMN = "fms-table-column-inactive";
    window.fms_store.KEY_DATA_TABLE_MAX_ROWS = "fms-table-max-rows";
}

/**
 * Method used to store datatable sort preferences
 */
fms_store.setTablePreferedSortedColumn = function(argSortIdx, argSortOrder) {
    if (localStorage) {
        localStorage.setItem(
            this.KEY_PREFERRED_DATA_TABLE_COLUMN_SORT,
            JSON.stringify({'idx':argSortIdx, 'order':argSortOrder/*asc or desc*/})
        );
    }
};

/**
 * Method used to store datatable invisible columns
 */
fms_store.setTableVisibleColumns = function(argUnselectedColumns) {
    if (localStorage) {
        localStorage.setItem(
            this.KEY_DATA_TABLE_INACTIVE_COLUMN,
            JSON.stringify(argUnselectedColumns)
        );
    }
};

/**
 * Method used to get datatable sort preferences
 */
fms_store.getTablePreferedSortedColumn = function() {
    if (localStorage) {
        var sortItem = localStorage.getItem(this.KEY_PREFERRED_DATA_TABLE_COLUMN_SORT);
        if (sortItem) {
            return JSON.parse(sortItem);
        } else {
            return {'idx':0, 'order':'desc'};
        }
    }
};

/**
 * Method used to get datatable invisible columns
 */
fms_store.getTableInvisibleColumns = function() {
    if (localStorage) {
        var unselectedColumnsItem = localStorage.getItem(this.KEY_DATA_TABLE_INACTIVE_COLUMN);
        if (unselectedColumnsItem) {
            return JSON.parse(unselectedColumnsItem);
        } else {
            return {};
        }
    }
};

/**
 * Method used to store datatable max number of records in the result set
 */
fms_store.setTableMaxRows = function(argMaxRows) {
    if (localStorage) {
        localStorage.setItem(this.KEY_DATA_TABLE_MAX_ROWS, argMaxRows);
    }
};

/**
 * Method used to get datatable max number of records in the result set
 */
fms_store.getTableMaxRows = function(argMaxRows) {
    if (localStorage) {
        return localStorage.getItem(this.KEY_DATA_TABLE_MAX_ROWS) || argMaxRows;
    }
    return argMaxRows;
};
<commit_msg>bug fix in the incidents table pagination<commit_after>// required : -http://openlayers.org/dev/OpenLayers.js
//              -http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js

if (!('fms_store' in window)) {
    window.fms_store = {};
    window.fms_store.KEY_PREFERRED_DATA_TABLE_COLUMN_SORT = "fms-table-column-sort";
    window.fms_store.KEY_DATA_TABLE_INACTIVE_COLUMN = "fms-table-column-inactive";
    window.fms_store.KEY_DATA_TABLE_MAX_ROWS = "fms-table-max-rows";
}

/**
 * Method used to store datatable sort preferences
 */
fms_store.setTablePreferedSortedColumn = function(argSortIdx, argSortOrder) {
    if (localStorage) {
        localStorage.setItem(
            this.KEY_PREFERRED_DATA_TABLE_COLUMN_SORT,
            JSON.stringify({'idx':argSortIdx, 'order':argSortOrder/*asc or desc*/})
        );
    }
};

/**
 * Method used to store datatable invisible columns
 */
fms_store.setTableVisibleColumns = function(argUnselectedColumns) {
    if (localStorage) {
        localStorage.setItem(
            this.KEY_DATA_TABLE_INACTIVE_COLUMN,
            JSON.stringify(argUnselectedColumns)
        );
    }
};

/**
 * Method used to get datatable sort preferences
 */
fms_store.getTablePreferedSortedColumn = function() {
    if (localStorage) {
        var sortItem = localStorage.getItem(this.KEY_PREFERRED_DATA_TABLE_COLUMN_SORT);
        if (sortItem) {
            return JSON.parse(sortItem);
        } else {
            return {'idx':0, 'order':'desc'};
        }
    }
};

/**
 * Method used to get datatable invisible columns
 */
fms_store.getTableInvisibleColumns = function() {
    if (localStorage) {
        var unselectedColumnsItem = localStorage.getItem(this.KEY_DATA_TABLE_INACTIVE_COLUMN);
        if (unselectedColumnsItem) {
            return JSON.parse(unselectedColumnsItem);
        } else {
            return {};
        }
    }
};

/**
 * Method used to store datatable max number of records in the result set
 */
fms_store.setTableMaxRows = function(argMaxRows) {
    if (localStorage) {
        localStorage.setItem(this.KEY_DATA_TABLE_MAX_ROWS, argMaxRows);
    }
};

/**
 * Method used to get datatable max number of records in the result set
 */
fms_store.getTableMaxRows = function(argMaxRows) {
    if (localStorage) {
        return Number(localStorage.getItem(this.KEY_DATA_TABLE_MAX_ROWS)) || argMaxRows;
    }
    return argMaxRows;
};
<|endoftext|>


<commit_before>// TODO: Comments needed in this file.

// Add your team to this list when you've put an icon in /logos!
var icons = [
	171,
	236,
	330,
	548,

	1058,
	1108,
	1418,
	1452,
	1982,

	2370,
	2403,
	2412,
	2626,
	2827,
	2855,
	2848,

	3015,
	3928,
	3946,

	4150,
	4909,
	4924,

	5113,
	5115,
	5431,
	5482,
	5859,
	5881,
	5938,
];

// Is your team's location wrong?  Add your team and coordinates to this object to update their correct coordinates manually
var updatedLocations = {
	330: {
		lat: 33.87253,
		lng: -118.395732
	},
	364: { // GeeII
		lat: 30.3897667,
		lng: -89.0436744
	},
	1421: { // GeeII
		lat: 30.6252185,
		lng: -89.6565752
	},
	1912: { // GeeII
		lat: 30.2715933,
		lng: -89.7455335
	},
	1920: { // GeeII
		lat: 29.9419,
		lng: -90.1140
	},
	1927: { // GeeII
		lat: 30.552632,
		lng: -89.0239767
	},
	2080: { // GeeII
		lat: 30.5172157,
		lng: -90.3809465
	},
	2183: { // GeeII
		lat: 29.8891,
		lnt: -90.4083
	},
	2190: { // GeeII
		lat: 31.3515155,
		lng: -89.2072034
	},
	2221: { // GeeII
		lat: 30.4068,
		lng: -90.0407
	},
	2992: { // GeeII
		lat: 30.3813461,
		lng: -90.1028666
	},
	2403: {
		lat: 33.434551,
		lng: -111.672356
	},
	2626: {
		lat: 45.403450,
		lng: -71.894242
	},
    2930: {
        lat: 47.868753,
        lng: -122.133521
    },
	3039: { // GeeII
		lat: 29.9657,
		lng: -90.3839029
	},
    3223: {
        lat: 47.651672,
        lng: -122.698748
    },
	3946: { // GeeII
		lat: 30.2888866,
		lng: -89.772360
	},
	4087: { // GeeII
		lat: 30.0248,
		lng: -90.0677
	},
	4107: { // GeeII
		lat: 30.4349106,
		lng: -89.1967398
	},
    4309: {
        lat: 47.884388,
        lng: -121.863099
    },
	4316: { // GeeII
		lat: 29.6931,
		lng: -90.5588
	},
    4512: {
        lat: 47.924402,
        lng: -122.222745
    },
    4681: {
        lat: 47.880796,
        lng: -122.178467
    },
	4805: { //GeeII
		lat: 29.9255
		lng: -90.1046
	},
    4915: {
        lat: 47.636593,
        lng: -122.524264
    },
	5168: { // GeeII
		lat: 29.9685,
		lng: -90.0927
	},
	5325: { // GeeII
		lat: 29.8829956,
		lng: -90.1317362
	},
	5881: {
		lat: 42.6918615,
		lng: -73.8357275
	},
	5938: {
		lat: 39.15819444,
		lng: -75.524405556
	},
	5965: { // GeeII
		lat: 29.902892,
		lng: -90.1547547
	},
	5971: { // GeeII
		lat: 29.9900,
		lng: -90.1615
	}
}

var map;
var teamMarkers = []
var regionalMarkers = []
var districtMarkers = []

var teamState = true;
var regState = true;
var distState = true;

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: {
			lat: 30,
			lng: 0
		},
		zoom: 2,
		disableDefaultUI: true,
		zoomControl: true,
		mapTypeControl: false,
		streetViewControl: false,
		rotateControl: false,
		fullscreenControl: true,
		styles: [{
			featureType: 'water',
			elementType: 'geometry',
			stylers: [{
				color: '#193341'
			}]
		}, {
			featureType: 'landscape',
			elementType: 'geometry',
			stylers: [{
				color: '#2c5a71'
			}]
		}, {
			featureType: 'road',
			elementType: 'geometry',
			stylers: [{
				color: '#29768a'
			}, {
				lightness: -37
			}]
		}, {
			featureType: 'poi',
			elementType: 'geometry',
			stylers: [{
				color: '#406d80'
			}]
		}, {
			featureType: 'transit',
			elementType: 'geometry',
			stylers: [{
				color: '#406d80'
			}]
		}, {
			elementType: 'labels.text.stroke',
			stylers: [{
				visibility: 'on'
			}, {
				color: '#3e606f'
			}, {
				weight: 2
			}, {
				gamma: 0.84
			}]
		}, {
			elementType: 'labels.text.fill',
			stylers: [{
				color: '#ffffff'
			}]
		}, {
			featureType: 'administrative',
			elementType: 'geometry',
			stylers: [{
				weight: 0.6
			}, {
				color: '#1a3541'
			}]
		}, {
			elementType: 'labels.icon',
			stylers: [{
				visibility: 'off'
			}]
		}, {
			featureType: 'poi.park',
			elementType: 'geometry',
			stylers: [{
				color: '#2c5a71'
			}]
		}]
	});

	for (i = 0; i < teams.length; i++) {
		createTeamMarker(coordinates[i], teams[i]);
	}

	for (i = 0; i < regionals.length; i++) {
		createCompetitionMarker('regional', regionals[i]);
	}

	for (i = 0; i < districts.length; i++) {
		createCompetitionMarker('district', districts[i]);
	}
}

function createCompetitionMarker(type, competitionEntry) {
	if (competitionEntry) {
		var position = {
			lat: (type == 'regional') ? competitionEntry[1].lat : competitionEntry[2].lat,
			lng: (type == 'regional') ? competitionEntry[1].lng : competitionEntry[2].lng
		};

		if (position.lat && position.lng) {
			var image = {
				url: type + '.png',
				scaledSize: new google.maps.Size(30, 30)
			};

			var marker = new google.maps.Marker({
				position: position,
				map: map,
				title: competitionEntry[0],
				icon: type + '.png'
			});

			google.maps.event.addListener(marker, 'click', function() {
				openCompInfo(type, competitionEntry, marker);
			});

			if (type === 'regional') {
				regionalMarkers.push(marker);
			} else {
				districtMarkers.push(marker);
			}
		}
	}
}

function createTeamMarker(pos, title) {
	if (pos) {
		var position = {};

		if (title in updatedLocations) {
			position = {
				lat: updatedLocations[title].lat,
				lng: updatedLocations[title].lng
			};
		} else {
			position = {
				lat: pos.lat + ((Math.random() / 100) * ((Math.random() >= 0.5) ? -1 : 1)),
				lng: pos.lng + ((Math.random() / 100) * ((Math.random() >= 0.5) ? -1 : 1))
			};
		}

		var custom = icons.indexOf(title) !== -1;
		var image = {
			url: custom ? 'logos/' + title + '.png' : 'marker.png',
			scaledSize: custom ? new google.maps.Size(30, 30) : undefined
		};

		var marker = new google.maps.Marker({
			position: position,
			map: map,
			title: title.toString(),
			icon: image
		});

		google.maps.event.addListener(marker, 'click', function() {
			openTeamInfo(title, marker);
		});

		teamMarkers.push(marker);
	}
}

function openCompInfo(type, entry, marker) {
	var dates = ((type === 'regional') ? entry[4] : entry[5]).split(' - ');
	var start = (new Date(dates[0])).toLocaleDateString();
	var end = (new Date(dates[1])).toLocaleDateString();

	var content = '';

	content += '
' + ((type == 'regional') ? entry[0] : entry[1]) + '
';
	content += '
';

	if (type === 'district') {
		content += '
District: ' + entry[0] + '
';
	}

	content += '
Week: ' + ((type === 'regional') ? entry[2] : entry[3]) + '
';
	content += '
Date: ' + start + ' thru ' + end + '
';
	content += '
View on The Blue Alliance
';
	content += '
';

	try {
		var oldInfoWindow = document.getElementsByClassName('gm-style-iw')[0];
		oldInfoWindow.parentNode.parentNode.removeChild(oldInfoWindow.parentNode);
	} catch (e) {}

	var infoWindow = new google.maps.InfoWindow({
		content: content
	});

	infoWindow.open(map, marker);
}

function openTeamInfo(num, marker) {
	var req = new XMLHttpRequest();

	req.open('GET', 'https://www.thebluealliance.com/api/v2/team/frc' + num + '?X-TBA-App-Id=erikboesen:frcmap:v1.0');
	req.send();
	req.onreadystatechange = function() {
		if (req.readyState === 4 && req.status === 200) {
			var team = JSON.parse(req.responseText);
			var content = '
';

			content += team.website ? '' : '';
			content += 'Team ' + team.team_number;
			content += team.nickname ? ' - ' + team.nickname : '';
			content += team.website ? '
' : '
';
			content += team.motto ? '
"' + team.motto + '"
' : '';
			content += '
';
			content += '
Location: ' + team.location + '
';
			content += team.rookie_year ? '
Rookie year: ' + team.rookie_year + '
' : '';
			content += '
View on The Blue Alliance
';
			content += '
';

			try {
				var oldInfoWindow = document.getElementsByClassName('gm-style-iw')[0];
				oldInfoWindow.parentNode.parentNode.removeChild(oldInfoWindow.parentNode);
			} catch (e) {}

			var infoWindow = new google.maps.InfoWindow({
				content: content
			});

			infoWindow.open(map, marker);
		}
	};
}

function toggleMarkers(type) {
	switch (type) {
		case 'teams':
			for (i = 0; i < teamMarkers.length; i++) {
				if (teamState) {
					teamMarkers[i].setMap(null);
				} else {
					teamMarkers[i].setMap(map);
				}
			}

			teamState = !teamState;

			break;
		case 'regionals':
			for (i = 0; i < regionalMarkers.length; i++) {
				if (regState) {
					regionalMarkers[i].setMap(null);
				} else {
					regionalMarkers[i].setMap(map);
				}
			}

			regState = !regState;

			break;
		case 'districts':
			for (i = 0; i < districtMarkers.length; i++) {
				if (distState == true) {
					districtMarkers[i].setMap(null);
				} else {
					districtMarkers[i].setMap(map);
				}
			}

			distState = !distState;

			break;
	}
}
<commit_msg>Update scripts.js<commit_after>// TODO: Comments needed in this file.

// Add your team to this list when you've put an icon in /logos!
var icons = [
	171,
	236,
	330,
	548,

	1058,
	1108,
	1418,
	1452,
	1982,

	2370,
	2403,
	2412,
	2626,
	2827,
	2855,
	2848,

	3015,
	3928,
	3946,

	4150,
	4909,
	4924,

	5113,
	5115,
	5431,
	5482,
	5859,
	5881,
	5938,
];

// Is your team's location wrong?  Add your team and coordinates to this object to update their correct coordinates manually
var updatedLocations = {
	330: {
		lat: 33.87253,
		lng: -118.395732
	},
	364: { // GeeII
		lat: 30.3897667,
		lng: -89.0436744
	},
	1421: { // GeeII
		lat: 30.6252185,
		lng: -89.6565752
	},
	1912: { // GeeII
		lat: 30.2715933,
		lng: -89.7455335
	},
	1920: { // GeeII
		lat: 29.9419,
		lng: -90.1140
	},
	1927: { // GeeII
		lat: 30.552632,
		lng: -89.0239767
	},
	2080: { // GeeII
		lat: 30.5172157,
		lng: -90.3809465
	},
	2183: { // GeeII
		lat: 29.8891,
		lnt: -90.4083
	},
	2190: { // GeeII
		lat: 31.3515155,
		lng: -89.2072034
	},
	2221: { // GeeII
		lat: 30.4068,
		lng: -90.0407
	},
	2992: { // GeeII
		lat: 30.3813461,
		lng: -90.1028666
	},
	2403: {
		lat: 33.434551,
		lng: -111.672356
	},
	2626: {
		lat: 45.403450,
		lng: -71.894242
	},
    2930: {
        lat: 47.868753,
        lng: -122.133521
    },
	3039: { // GeeII
		lat: 29.9657,
		lng: -90.3839029
	},
    3223: {
        lat: 47.651672,
        lng: -122.698748
    },
	3337: { // GeeII
		lat: 30.3742,
		lng: -91.0136
	},
	3606: { // GeeII
		lat: 30.4407,
		lng: -91.1589
	},
	3753: { // GeeII
		lat: 30.3994,
		lng: -91.0514
	},
	3946: { // GeeII
		lat: 30.2888866,
		lng: -89.772360
	},
	3991: { // GeeII
		lat: 30.4227,
		lng: -91.0351
	},
	4053: { // GeeII
		lat: 30.1010,
		lng: -91.0028
	},
	4087: { // GeeII
		lat: 30.0248,
		lng: -90.0677
	},
	4107: { // GeeII
		lat: 30.4349106,
		lng: -89.1967398
	},
    4309: {
        lat: 47.884388,
        lng: -121.863099
    },
	4316: { // GeeII
		lat: 29.6931,
		lng: -90.5588
	},
    4512: {
        lat: 47.924402,
        lng: -122.222745
    },
    4681: {
        lat: 47.880796,
        lng: -122.178467
    },
	4805: { //GeeII
		lat: 29.9255,
		lng: -90.1046
	},
    4915: {
        lat: 47.636593,
        lng: -122.524264
    },
	4978: { // GeeII
		lat: 30.3831,
		lng: -91.0875
	},
	5168: { // GeeII
		lat: 29.9685,
		lng: -90.0927
	},
	5325: { // GeeII
		lat: 29.8829956,
		lng: -90.1317362
	},
	5785: { // GeeII
		lat: 30.4369,
		lng: -91.1590
	},
	5863: { // GeeII
		lat: 30.3930,
		lng: -91.2407
	},
	5864: { // GeeII
		lat: 30.4599,
		lng: -91.2583
	},
	5881: {
		lat: 42.6918615,
		lng: -73.8357275
	},
	5938: {
		lat: 39.15819444,
		lng: -75.524405556
	},
	5965: { // GeeII
		lat: 29.902892,
		lng: -90.1547547
	},
	5971: { // GeeII
		lat: 29.9900,
		lng: -90.1615
	},
	5997: { // GeeII
		lat: 30.2605,
		lng: -91.104573
	},
	6103: { // GeeII
		lat: 30.2619,
		lng: -91.2534
	}
}

var map;
var teamMarkers = []
var regionalMarkers = []
var districtMarkers = []

var teamState = true;
var regState = true;
var distState = true;

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: {
			lat: 30,
			lng: 0
		},
		zoom: 2,
		disableDefaultUI: true,
		zoomControl: true,
		mapTypeControl: false,
		streetViewControl: false,
		rotateControl: false,
		fullscreenControl: true,
		styles: [{
			featureType: 'water',
			elementType: 'geometry',
			stylers: [{
				color: '#193341'
			}]
		}, {
			featureType: 'landscape',
			elementType: 'geometry',
			stylers: [{
				color: '#2c5a71'
			}]
		}, {
			featureType: 'road',
			elementType: 'geometry',
			stylers: [{
				color: '#29768a'
			}, {
				lightness: -37
			}]
		}, {
			featureType: 'poi',
			elementType: 'geometry',
			stylers: [{
				color: '#406d80'
			}]
		}, {
			featureType: 'transit',
			elementType: 'geometry',
			stylers: [{
				color: '#406d80'
			}]
		}, {
			elementType: 'labels.text.stroke',
			stylers: [{
				visibility: 'on'
			}, {
				color: '#3e606f'
			}, {
				weight: 2
			}, {
				gamma: 0.84
			}]
		}, {
			elementType: 'labels.text.fill',
			stylers: [{
				color: '#ffffff'
			}]
		}, {
			featureType: 'administrative',
			elementType: 'geometry',
			stylers: [{
				weight: 0.6
			}, {
				color: '#1a3541'
			}]
		}, {
			elementType: 'labels.icon',
			stylers: [{
				visibility: 'off'
			}]
		}, {
			featureType: 'poi.park',
			elementType: 'geometry',
			stylers: [{
				color: '#2c5a71'
			}]
		}]
	});

	for (i = 0; i < teams.length; i++) {
		createTeamMarker(coordinates[i], teams[i]);
	}

	for (i = 0; i < regionals.length; i++) {
		createCompetitionMarker('regional', regionals[i]);
	}

	for (i = 0; i < districts.length; i++) {
		createCompetitionMarker('district', districts[i]);
	}
}

function createCompetitionMarker(type, competitionEntry) {
	if (competitionEntry) {
		var position = {
			lat: (type == 'regional') ? competitionEntry[1].lat : competitionEntry[2].lat,
			lng: (type == 'regional') ? competitionEntry[1].lng : competitionEntry[2].lng
		};

		if (position.lat && position.lng) {
			var image = {
				url: type + '.png',
				scaledSize: new google.maps.Size(30, 30)
			};

			var marker = new google.maps.Marker({
				position: position,
				map: map,
				title: competitionEntry[0],
				icon: type + '.png'
			});

			google.maps.event.addListener(marker, 'click', function() {
				openCompInfo(type, competitionEntry, marker);
			});

			if (type === 'regional') {
				regionalMarkers.push(marker);
			} else {
				districtMarkers.push(marker);
			}
		}
	}
}

function createTeamMarker(pos, title) {
	if (pos) {
		var position = {};

		if (title in updatedLocations) {
			position = {
				lat: updatedLocations[title].lat,
				lng: updatedLocations[title].lng
			};
		} else {
			position = {
				lat: pos.lat + ((Math.random() / 100) * ((Math.random() >= 0.5) ? -1 : 1)),
				lng: pos.lng + ((Math.random() / 100) * ((Math.random() >= 0.5) ? -1 : 1))
			};
		}

		var custom = icons.indexOf(title) !== -1;
		var image = {
			url: custom ? 'logos/' + title + '.png' : 'marker.png',
			scaledSize: custom ? new google.maps.Size(30, 30) : undefined
		};

		var marker = new google.maps.Marker({
			position: position,
			map: map,
			title: title.toString(),
			icon: image
		});

		google.maps.event.addListener(marker, 'click', function() {
			openTeamInfo(title, marker);
		});

		teamMarkers.push(marker);
	}
}

function openCompInfo(type, entry, marker) {
	var dates = ((type === 'regional') ? entry[4] : entry[5]).split(' - ');
	var start = (new Date(dates[0])).toLocaleDateString();
	var end = (new Date(dates[1])).toLocaleDateString();

	var content = '';

	content += '
' + ((type == 'regional') ? entry[0] : entry[1]) + '
';
	content += '
';

	if (type === 'district') {
		content += '
District: ' + entry[0] + '
';
	}

	content += '
Week: ' + ((type === 'regional') ? entry[2] : entry[3]) + '
';
	content += '
Date: ' + start + ' thru ' + end + '
';
	content += '
View on The Blue Alliance
';
	content += '
';

	try {
		var oldInfoWindow = document.getElementsByClassName('gm-style-iw')[0];
		oldInfoWindow.parentNode.parentNode.removeChild(oldInfoWindow.parentNode);
	} catch (e) {}

	var infoWindow = new google.maps.InfoWindow({
		content: content
	});

	infoWindow.open(map, marker);
}

function openTeamInfo(num, marker) {
	var req = new XMLHttpRequest();

	req.open('GET', 'https://www.thebluealliance.com/api/v2/team/frc' + num + '?X-TBA-App-Id=erikboesen:frcmap:v1.0');
	req.send();
	req.onreadystatechange = function() {
		if (req.readyState === 4 && req.status === 200) {
			var team = JSON.parse(req.responseText);
			var content = '
';

			content += team.website ? '' : '';
			content += 'Team ' + team.team_number;
			content += team.nickname ? ' - ' + team.nickname : '';
			content += team.website ? '
' : '
';
			content += team.motto ? '
"' + team.motto + '"
' : '';
			content += '
';
			content += '
Location: ' + team.location + '
';
			content += team.rookie_year ? '
Rookie year: ' + team.rookie_year + '
' : '';
			content += '
View on The Blue Alliance
';
			content += '
';

			try {
				var oldInfoWindow = document.getElementsByClassName('gm-style-iw')[0];
				oldInfoWindow.parentNode.parentNode.removeChild(oldInfoWindow.parentNode);
			} catch (e) {}

			var infoWindow = new google.maps.InfoWindow({
				content: content
			});

			infoWindow.open(map, marker);
		}
	};
}

function toggleMarkers(type) {
	switch (type) {
		case 'teams':
			for (i = 0; i < teamMarkers.length; i++) {
				if (teamState) {
					teamMarkers[i].setMap(null);
				} else {
					teamMarkers[i].setMap(map);
				}
			}

			teamState = !teamState;

			break;
		case 'regionals':
			for (i = 0; i < regionalMarkers.length; i++) {
				if (regState) {
					regionalMarkers[i].setMap(null);
				} else {
					regionalMarkers[i].setMap(map);
				}
			}

			regState = !regState;

			break;
		case 'districts':
			for (i = 0; i < districtMarkers.length; i++) {
				if (distState == true) {
					districtMarkers[i].setMap(null);
				} else {
					districtMarkers[i].setMap(map);
				}
			}

			distState = !distState;

			break;
	}
}
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { text } from '@storybook/addon-knobs';
import notes from './documentation/notes.md';
import Fieldset from './fieldset';
import Textbox from '../textbox';

storiesOf('Fieldset', module)
  .addParameters({
    info: {
      propTablesExclude: [Fieldset, Textbox]
    }
  })
  .add('default', () => {
    const legend = text('legend', '');

    return (
      <Fieldset
        legend={ legend }
      >
        <Textbox
          label='First Name'
          labelInline
          labelAlign='right'
        />
        <Textbox
          label='Last Name'
          labelInline
          labelAlign='right'
        />
      </Fieldset>
    );
  }, {
    info: {
      propTables: [Fieldset]
    },
    notes: { markdown: notes },
    knobs: { escapeHTML: false }
  });
<commit_msg>FE-1354 - add missing fieldset demo fields<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { text } from '@storybook/addon-knobs';
import notes from './documentation/notes.md';
import Fieldset from './fieldset';
import Textbox from '../textbox';

storiesOf('Fieldset', module)
  .addParameters({
    info: {
      propTablesExclude: [Textbox]
    }
  })
  .add('default', () => {
    const legend = text('legend', '');

    return (
      <Fieldset
        legend={ legend }
      >
        <Textbox
          label='First Name'
          labelInline
          labelAlign='right'
        />
        <Textbox
          label='Last Name'
          labelInline
          labelAlign='right'
        />
        <Textbox
          label='Address'
          labelInline
          labelAlign='right'
        />
        <Textbox
          label='City'
          labelInline
          labelAlign='right'
        />
        <Textbox
          label='Country'
          labelInline
          labelAlign='right'
        />
        <Textbox
          label='Telephone'
          labelInline
          labelAlign='right'
        />
      </Fieldset>
    );
  }, {
    notes: { markdown: notes },
    knobs: { escapeHTML: false }
  });
<|endoftext|>


<commit_before>exports.run = (client,message,args) =>
{
    const config = require("../config.json");
    if (message.author.id === config.botOwnerID)
    {
        try
        {
            if (!args || args.size < 1) return message.channel.send("please specify a command name to reload!");

            delete require.cache[require.resolve(`./${args[0]}.js`)];  //deletes the cache for the bot, since node.js is cache-based.
            message.channel.send(`the command ${args[0]} has been reloaded`).delete(10000);
        }
        catch (e)
        {
            console.log(e);
        }
    }
    else
    {
        message.channel.send("this command is intended for Bot Owner only, used to reload commands which require emergency fixing.");
    }
}<commit_msg>fixing a small error which gets caught by the control panel<commit_after>exports.run = (client,message,args) =>
{
    const config = require("../config.json");
    if (message.author.id === config.botOwnerID)
    {
        try
        {
            if (!args || args.size < 1) return message.channel.send("please specify a command name to reload!");

            delete require.cache[require.resolve(`./${args[0]}.js`)];  //deletes the cache for the bot, since node.js is cache-based.
            message.channel.send(`the command ${args[0]} has been reloaded`);
        }
        catch (e)
        {
            console.log(e);
        }
    }
    else
    {
        message.channel.send("this command is intended for Bot Owner only, used to reload commands which require emergency fixing.");
    }
}<|endoftext|>


<commit_before>var hotkeyCommander = (function() {

  var template;

  var public_api = {
    init: init
  };

  return public_api;

  // the original keys (before mapping);
  var keyDictionary = {};

  // an object with keycodes for keys
  // this is what the hotkey engine will call when keys are pressed
  var keymap = {};
  var recording = false;
  var rootElement;

  // load template
  function init(hotkeys, el) {
    var templates = document.getElementById('hotkeyTemplate').import;
    template = templates.getElementById('hotkey-setting');

    // store the original hotkeys
    // TODO: move these into local storage after initial load
    keyDictionary = hotkeys;
    rootElement = el;

    reload(keyDictionary, rootElement);

    window.addEventListener('keydown', onkeydown);
  }

  function loadKeys(hotkeys, el) {
    // load hotkeys into the template
    // and write it to the page.
    for (var i in hotkeys) {
      var clone = document.importNode(template.content, true);
      console.log(i, ' ',  hotkeys[i]);

      clone.querySelector('.settingButton')
        .addEventListener("click", function(evt) {
          if (!recording) {
            // add highlighting to bg for this element
            this.parentElement.style.background = 'red';
            console.log('Attempting to change key: ', i);
            console.log(keymap[i]);
            recording = i;
            // popup a modal that lets the user know whats up
          }

        });

      clone.querySelector('.functionLabel').innerText = stripUnderscores(hotkeys[i].name);
      clone.querySelector('.settingLabel').innerText = String.fromCharCode(i);
      el.appendChild(clone);
    }
  }

  // takes in an object of mapped hotkeys
  // and builds an object with keyCode keys
  // so that the hotkeys can be accessed by their keycode
  // instead of by their name
  // this is what would be used by the hotkey engine
  function buildKeyMap(hotkeys) {
    var result = {};

    for(var hotkey in hotkeys){
      if(hotkeys.hasOwnProperty(hotkey)){
        // build new hotkey dictionary here
        var thisKey = hotkeys[hotkey];
        result[thisKey.keyCode] = {
          name: hotkey,
          ctrlKey: hotkeys[hotkey].ctrlKey,
          altKey: hotkeys[hotkey].altKey,
          shiftKey: hotkeys[hotkey].shiftKey,
        };
      }
    }
    return result;
  }

  // rebuild the keymap
  // render the hotkeys element
  function reload(hotkeys, el) {
    keymap = buildKeyMap(hotkeys);

    el.innerHTML = '';
    //load the hotkeys into the DOM
    loadKeys(keymap, el);
  }

  function onkeydown(evt) {
    // already recording - this is the new key
    if (recording) {
      console.log('You are trying to change ', recording, ' to : ', evt.keyCode);

      //TODO: validate that the key is not already in use.

      var keyToSet = findKeyByCode(recording);
      // set the key in the hotkey dictionary
      if (keyToSet) {
        keyToSet.keyCode = evt.keyCode;
        reload(keyDictionary, rootElement);
      } else {
        console.error('Could not find key: ', recording);
        console.log('Proper keys are: ', keymap);
      }

      // remove bg highlighting
      var keys = document.getElementsByClassName('hotkeyConfig');
      for (var key in keys) {
        if (keys.hasOwnProperty(key)){
          keys[key].style.background = '';
        }
      }
      recording = false;

    } else {
      if (keymap[evt.keyCode]){
        console.log('Keymap exists');
        console.log(keymap[evt.keyCode]);
      } else {
        console.log('No key mapped to ', evt.keyCode);
      }
    }
  }

  //       HELPERS

  /**
   * searches through the keyDictionary and
   * attempts to find the key containing
   * the passed in keycode
   * @returns {Key Object} or null
  */
  function findKeyByCode(keycode) {
    for (var key in keyDictionary){
      console.log(key, ' ', keyDictionary[key]);
      if (+keyDictionary[key].keyCode === +keycode) {
        return keyDictionary[key];
      }
    }
    return null
  }

  function stripUnderscores(string){
    return string.replace('_', ' ');
  }

  // turn a snake case string into a camelCase string
  function snakeCaseToCamelCase(string) {
    string = stripUnderscores(string);
    string = string.split(' ');
    var result = string.map(function(word, index){
      // uppercase the first character of each word
      // except the first word
      if(index !== 0) {
        return word[0].toUpperCase() + word.slice(1).toLowerCase();
      } else {
        return word.toLowerCase();
      }
    });
    return result.join('');
  }

})();
<commit_msg>Fixed a bug with ye old iterator variables. Thanks let.<commit_after>var hotkeyCommander = (function() {

  var template;

  var public_api = {
    init: init
  };

  return public_api;

  // the original keys (before mapping);
  var keyDictionary = {};

  // an object with keycodes for keys
  // this is what the hotkey engine will call when keys are pressed
  var keymap = {};
  var recording = false;
  var rootElement;

  // load template
  function init(hotkeys, el) {
    var templates = document.getElementById('hotkeyTemplate').import;
    template = templates.getElementById('hotkey-setting');

    // store the original hotkeys
    // TODO: move these into local storage after initial load
    keyDictionary = hotkeys;
    rootElement = el;

    reload(keyDictionary, rootElement);

    window.addEventListener('keydown', onkeydown);
  }

  function loadKeys(hotkeys, el) {
    // load hotkeys into the template
    // and write it to the page.
    for (let i in hotkeys) {
      var clone = document.importNode(template.content, true);
      console.log(i, ' ',  hotkeys[i]);

      clone.querySelector('.settingButton')
        .addEventListener("click", function(evt) {
          if (!recording) {
            // add highlighting to bg for this element
            this.parentElement.style.background = 'red';
            console.log('Attempting to change key: ', i);
            console.log(keymap[i]);
            recording = i;
          }

        });

      clone.querySelector('.functionLabel').innerText = stripUnderscores(hotkeys[i].name);
      clone.querySelector('.settingLabel').innerText = String.fromCharCode(i);
      el.appendChild(clone);
    }
  }

  // takes in an object of mapped hotkeys
  // and builds an object with keyCode keys
  // so that the hotkeys can be accessed by their keycode
  // instead of by their name
  // this is what would be used by the hotkey engine
  function buildKeyMap(hotkeys) {
    var result = {};

    for(var hotkey in hotkeys){
      if(hotkeys.hasOwnProperty(hotkey)){
        // build new hotkey dictionary here
        var thisKey = hotkeys[hotkey];
        result[thisKey.keyCode] = {
          name: hotkey,
          ctrlKey: hotkeys[hotkey].ctrlKey,
          altKey: hotkeys[hotkey].altKey,
          shiftKey: hotkeys[hotkey].shiftKey,
        };
      }
    }
    return result;
  }

  // rebuild the keymap
  // render the hotkeys element
  function reload(hotkeys, el) {
    keymap = buildKeyMap(hotkeys);

    el.innerHTML = '';
    //load the hotkeys into the DOM
    loadKeys(keymap, el);
  }

  function onkeydown(evt) {
    // already recording - this is the new key
    if (recording) {
      console.log('You are trying to change ', recording, ' to : ', evt.keyCode);

      //TODO: validate that the key is not already in use.

      var keyToSet = findKeyByCode(recording);
      // set the key in the hotkey dictionary
      if (keyToSet) {
        keyToSet.keyCode = evt.keyCode;
        reload(keyDictionary, rootElement);
      } else {
        console.error('Could not find key: ', recording);
        console.log('Proper keys are: ', keymap);
      }

      // remove bg highlighting
      var keys = document.getElementsByClassName('hotkeyConfig');
      for (var key in keys) {
        if (keys.hasOwnProperty(key)){
          keys[key].style.background = '';
        }
      }
      recording = false;

    } else {
      if (keymap[evt.keyCode]){
        console.log('Keymap exists');
        console.log(keymap[evt.keyCode]);
      } else {
        console.log('No key mapped to ', evt.keyCode);
      }
    }
  }

  //       HELPERS

  /**
   * searches through the keyDictionary and
   * attempts to find the key containing
   * the passed in keycode
   * @returns {Key Object} or null
  */
  function findKeyByCode(keycode) {
    for (var key in keyDictionary){
      console.log(key, ' ', keyDictionary[key]);
      if (+keyDictionary[key].keyCode === +keycode) {
        return keyDictionary[key];
      }
    }
    return null
  }

  function stripUnderscores(string){
    return string.replace('_', ' ');
  }

  // turn a snake case string into a camelCase string
  function snakeCaseToCamelCase(string) {
    string = stripUnderscores(string);
    string = string.split(' ');
    var result = string.map(function(word, index){
      // uppercase the first character of each word
      // except the first word
      if(index !== 0) {
        return word[0].toUpperCase() + word.slice(1).toLowerCase();
      } else {
        return word.toLowerCase();
      }
    });
    return result.join('');
  }

})();
<|endoftext|>


<commit_before>'use strict';

var url = require('url');
var http = require('http');
var fs = require('fs');

var repository = require('./loan/repository.js');

var APPLICATION = "apply";
var FETCH = "fetch";
var TICKET_ID = "ticketId";
var APPROVE = "approve";

var serv = {
    keso : function() {

    }
};

var srv = http.createServer(function (req, res) {

    var nextId = function(application, callback) {
	fs.readdir('loans/', function determineNextId(err, data) {
	    if (err) {
		throw err;
	    } else {
		var id = data.length + 1;
		repository.toDisk(application, callback, id);
		callback(JSON.stringify({ticketId: id}));
	    }
	});
    }

    res.writeHead(200, {'Content-Type': 'application/json'});
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    if (query.action === 'apply') {
	var application = {amount: query['amount'],
			   contact: query['contact'],
			  };
	nextId(application, function printTicket(ticket) {
	    res.end(ticket + '\n');
	});
	return;

    } else if (query.action === 'fetch') {
	var ticketId = query[TICKET_ID];
        repository.fetch(ticketId, function printFetched(application) {
	    res.end(application + '\n');
	});
	return;
    } else if (query.action === 'approve') {
        repository.approveLoan(query[TICKET_ID], function printTicketAfterApprove(ticket) {
	    res.end(ticket + '\n');
	});
	return;
    }

    res.end('Incorrect parameters provided\n');
}).listen(8080);
<commit_msg>Removed junk<commit_after>'use strict';

var url = require('url');
var http = require('http');
var fs = require('fs');

var repository = require('./loan/repository.js');

var APPLICATION = "apply";
var FETCH = "fetch";
var TICKET_ID = "ticketId";
var APPROVE = "approve";

var srv = http.createServer(function (req, res) {

    var nextId = function(application, callback) {
	fs.readdir('loans/', function determineNextId(err, data) {
	    if (err) {
		throw err;
	    } else {
		var id = data.length + 1;
		repository.toDisk(application, callback, id);
		callback(JSON.stringify({ticketId: id}));
	    }
	});
    }

    res.writeHead(200, {'Content-Type': 'application/json'});
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    if (query.action === 'apply') {
	var application = {amount: query['amount'],
			   contact: query['contact'],
			  };
	nextId(application, function printTicket(ticket) {
	    res.end(ticket + '\n');
	});
	return;

    } else if (query.action === 'fetch') {
	var ticketId = query[TICKET_ID];
        repository.fetch(ticketId, function printFetched(application) {
	    res.end(application + '\n');
	});
	return;
    } else if (query.action === 'approve') {
        repository.approveLoan(query[TICKET_ID], function printTicketAfterApprove(ticket) {
	    res.end(ticket + '\n');
	});
	return;
    }

    res.end('Incorrect parameters provided\n');
}).listen(8080);
<|endoftext|>