<commit_before>import React from 'react';
import { connect } from 'react-redux';
//
import { Utils} from 'czechidm-core';
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import MonitoringStateEnum from '../../enums/MonitoringStateEnum';
import { ConfigurationManager } from '../../redux';

const uiKey = 'monitoring_table';
const manager = new ConfigurationManager();

/**
 * @Beta
 * Monitoring
 *
 * @author Vít Švanda
 */
class Monitorings extends Advanced.AbstractTableContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      filterOpened: true,
      detail: {
        show: false,
        entity: {}
      }
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.initData();
  }

  initData() {
    manager.getService().getMonitoringType('monitoring-database')
      .then(json => {
        this.setState({monitoringDatabase: json});
      })
      .catch(error => {
        this.addError(error);
      });
    manager.getService().getMonitoringType('monitoring-sync')
      .then(json => {
        this.setState({monitoringSync: json});
      })
      .catch(error => {
        this.addError(error);
      });
  }

  getManager() {
    return manager;
  }

  getUiKey() {
    return uiKey;
  }

  getContentKey() {
    return 'content.monitoring';
  }

  /**
  * Method get last string of split string by dot.
  * Used for get niceLabel for type entity.
  */
  _getType(name) {
    return Utils.Ui.getSimpleJavaType(name);
  }

  _renderType(monitoringType) {
    return (
      <Basic.Div rendered={!!monitoringType}>
        <Basic.ContentHeader>
          { this.i18n(`${monitoringType ? monitoringType.module : null}:content.monitoring.type.${monitoringType ? monitoringType.type : null}.name`,
            { escape: false }) }
        </Basic.ContentHeader>

        <Basic.Panel>
          <Basic.Table
            data={ monitoringType ? monitoringType.results : null }
            noData={ this.i18n('component.basic.Table.noData') }>
            <Basic.Column
              property="level"
              header={ this.i18n('entity.IdmMonitoringType.level') }
              cell={
                ({ rowIndex, data }) => {
                  const entity = data[rowIndex];
                  return (
                    <Basic.EnumValue
                      style={{padding: '.2em .2em .3em .4em'}}
                      value={entity.level}
                      enum={ MonitoringStateEnum }/>
                  );
                }
              }
            />
            <Basic.Column
              property="name"
              header={ this.i18n('entity.IdmMonitoringType.name') }
              cell={
                /* eslint-disable react/no-multi-comp */
                ({ rowIndex, data }) => {
                  const value = data[rowIndex];
                  if (!value) {
                    return null;
                  }
                  if (!value.dto) {
                    return value.name;
                  }
                  return (
                    <Advanced.EntityInfo
                      entityType={ this._getType(value.dtoType) }
                      entityIdentifier={ value.dto ? value.dto.id : null}
                      face="popover"
                      entity={ value.dto }
                      showEntityType
                      showIcon/>
                  );
                }
              }/>
            <Basic.Column property="value" header={ this.i18n('entity.IdmMonitoringType.value') }/>
            <Basic.Column property="threshold" header={ this.i18n('entity.IdmMonitoringType.threshold') }/>
            <Basic.Column property="module" header={ this.i18n('entity.IdmMonitoringType.module') }/>
          </Basic.Table>
        </Basic.Panel>
      </Basic.Div>
    );
  }

  render() {
    //
    const {
      monitoringDatabase,
      monitoringSync
    } = this.state;
    //
    return (
      <Basic.Div>
        { this.renderPageHeader({ icon: 'fa:heartbeat' }) }
        <Basic.Toolbar>

            <Advanced.RefreshButton
              onClick={this.initData.bind(this)}
              title={this.i18n('button.refresh')}/>

        </Basic.Toolbar>
        {this._renderType(monitoringDatabase)}
        {this._renderType(monitoringSync)}
      </Basic.Div>
    );
  }
}

function select(state) {
  return {
    i18nReady: state.config.get('i18nReady')
  };
}

export default connect(select)(Monitorings);
<commit_msg>Update Monitorings.js<commit_after>import React from 'react';
import { connect } from 'react-redux';
//
import { Utils} from 'czechidm-core';
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import MonitoringStateEnum from '../../enums/MonitoringStateEnum';
import { ConfigurationManager } from '../../redux';

const uiKey = 'monitoring_table';
const manager = new ConfigurationManager();

/**
 * @Beta
 * Monitoring
 *
 * @author Vít Švanda
 */
class Monitorings extends Advanced.AbstractTableContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      filterOpened: true,
      detail: {
        show: false,
        entity: {}
      }
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.initData();
    this.selectNavigationItem('monitoring');
  }

  initData() {
    manager.getService().getMonitoringType('monitoring-database')
      .then(json => {
        this.setState({monitoringDatabase: json});
      })
      .catch(error => {
        this.addError(error);
      });
    manager.getService().getMonitoringType('monitoring-sync')
      .then(json => {
        this.setState({monitoringSync: json});
      })
      .catch(error => {
        this.addError(error);
      });
  }

  getManager() {
    return manager;
  }

  getUiKey() {
    return uiKey;
  }

  getContentKey() {
    return 'content.monitoring';
  }

  /**
  * Method get last string of split string by dot.
  * Used for get niceLabel for type entity.
  */
  _getType(name) {
    return Utils.Ui.getSimpleJavaType(name);
  }

  _renderType(monitoringType) {
    return (
      <Basic.Div rendered={!!monitoringType}>
        <Basic.ContentHeader>
          { this.i18n(`${monitoringType ? monitoringType.module : null}:content.monitoring.type.${monitoringType ? monitoringType.type : null}.name`,
            { escape: false }) }
        </Basic.ContentHeader>

        <Basic.Panel>
          <Basic.Table
            data={ monitoringType ? monitoringType.results : null }
            noData={ this.i18n('component.basic.Table.noData') }>
            <Basic.Column
              property="level"
              header={ this.i18n('entity.IdmMonitoringType.level') }
              cell={
                ({ rowIndex, data }) => {
                  const entity = data[rowIndex];
                  return (
                    <Basic.EnumValue
                      style={{padding: '.2em .2em .3em .4em'}}
                      value={entity.level}
                      enum={ MonitoringStateEnum }/>
                  );
                }
              }
            />
            <Basic.Column
              property="name"
              header={ this.i18n('entity.IdmMonitoringType.name') }
              cell={
                /* eslint-disable react/no-multi-comp */
                ({ rowIndex, data }) => {
                  const value = data[rowIndex];
                  if (!value) {
                    return null;
                  }
                  if (!value.dto) {
                    return value.name;
                  }
                  return (
                    <Advanced.EntityInfo
                      entityType={ this._getType(value.dtoType) }
                      entityIdentifier={ value.dto ? value.dto.id : null}
                      face="popover"
                      entity={ value.dto }
                      showEntityType
                      showIcon/>
                  );
                }
              }/>
            <Basic.Column property="value" header={ this.i18n('entity.IdmMonitoringType.value') }/>
            <Basic.Column property="threshold" header={ this.i18n('entity.IdmMonitoringType.threshold') }/>
            <Basic.Column property="module" header={ this.i18n('entity.IdmMonitoringType.module') }/>
          </Basic.Table>
        </Basic.Panel>
      </Basic.Div>
    );
  }

  render() {
    //
    const {
      monitoringDatabase,
      monitoringSync
    } = this.state;
    //
    return (
      <Basic.Div>
        { this.renderPageHeader({ icon: 'fa:heartbeat' }) }
        <Basic.Toolbar>

            <Advanced.RefreshButton
              onClick={this.initData.bind(this)}
              title={this.i18n('button.refresh')}/>

        </Basic.Toolbar>
        {this._renderType(monitoringDatabase)}
        {this._renderType(monitoringSync)}
      </Basic.Div>
    );
  }
}

function select(state) {
  return {
    i18nReady: state.config.get('i18nReady')
  };
}

export default connect(select)(Monitorings);
<|endoftext|>


<commit_before>const Discord = require("discord.js");
const Command = require("./Command");
const api = require("./api");

const main = (store, client) => {
  Command.setStorage(store);

  Command.add()
    .setTest(content => content.startsWith("/help"))
    .setHandler(msg => {
      const embed = new Discord.RichEmbed()
        .setColor(0x00ae86)
        .setTitle("Список команд")
        .setDescription(
          "`/help` - Выводит текущую команду\n" +
            "`/news` - Поиск по https://haipit.news \n" +
            "`/l /lurk /lurkmore /л /лурка /лурк` - Поиск по https://lurkmore.to/ \n" +
            "`/kill` - Выводит `Тобi пизда!`\n " +
            "`/getrandomnumber` - Выводит 42\n " +
            "`/xkcd` - Выводит случайный (или с определенным id) комикс с https://xkcd.ru\n "
        );
      msg.channel.send({ embed });
    });

  // find hapi news
  Command.add()
    .setTest(content => content.startsWith("/news"))
    .setHandler(async msg => {
      const q = msg.content.substr(5).trim();
      if (!q) return;

      const result = await api.hapiNews("find", {
        keywords: q,
        platform: "Очень модный бот",
        limit: 25
      });

      const embed = new Discord.RichEmbed().setColor(0x009ea6);

      const news = JSON.parse(result);
      if (!news) {
        embed.setDescription("Ничего не найдено");
      } else {
        news.forEach((item, i) => {
          if (i > 24) return;

          embed.addField(item.title, item.url);
        });
      }

      msg.channel.send({ embed });
    });

  // random news
  Command.add()
    .setTest(content => content.startsWith("/randomnews"))
    .setHandler(async msg => {
      const q = msg.content.substr(11).trim();
      if (!q) return;

      const result = await api.hapiNews("news/random/", {
        platform: "Очень модный бот",
        limit: 25
      });

      const embed = new Discord.RichEmbed().setColor(0x009ea6);

      const news = JSON.parse(result);
      if (!news) {
        embed.setDescription("Ничего не найдено");
      } else {
        news.forEach((item, i) => {
          if (i > 24) return;

          embed.addField(item.title, item.url);
        });
      }

      msg.channel.send({ embed });
    });

  Command.add()
    .setTest(content => content.startsWith("/kill"))
    .setHandler(async msg => {
      let [_, user = ""] = msg.content.split(" ");
      if (user) user += ", ";
      msg.channel.send(`${user} Тобi пизда!`);
    });

  Command.add()
    .setTest(content => content.startsWith("/getrandomnumber"))
    .setHandler(async msg => {
      msg.channel.send("42");
    });

  Command.add()
    .setTest(content => /^\/(l|lurk|lurkmore|л|лурка|лурк) /gim.test(content))
    .setHandler(async msg => {
      const q = msg.content.replace(/^\/(.*) /gim, "").trim();
      if (!q) return;

      const embed = new Discord.RichEmbed().setColor(0x8bc34a);

      try {
        const { data } = await api.lurk(q);

        if (data.ogTitle) embed.setTitle(data.ogTitle);
        if (data.ogUrl) embed.setURL("https:" + data.ogUrl);
        if (data.ogDescription) embed.setDescription(data.ogDescription);

        msg.channel.send({ embed });
      } catch (e) {
        embed.setDescription("Не найдено");
        msg.channel.send({ embed });
      }
    });

  Command.add()
    .setTest(content =>
      /^\/(w|wiki|wikipedia|в|вики|википедия) /gim.test(content)
    )
    .setHandler(async msg => {
      const q = msg.content.replace(/^\/(.*) /gim, "").trim();
      if (!q) return;

      const embed = new Discord.RichEmbed().setColor(0x8bc34a);

      try {
        const { data } = await api.wiki(q);

        console.log(data);
        if (data.ogTitle) embed.setTitle(data.ogTitle);
        embed.setURL("https://ru.wikipedia.org/wiki/" + q);
        if (data.ogDescription) embed.setDescription(data.ogDescription);
        if (data.ogImage) {
          if (data.ogImage.url[0] !== "h")
            data.ogImage.url = `http:${data.ogImage.url}`;
          embed.setImage(data.ogImage.url);
        }

        msg.channel.send({ embed });
      } catch (e) {
        embed.setDescription("Не найдено");
        msg.channel.send({ embed });
      }
    });

  Command.add()
    .setTest(content => /^\/(xkcd)/gim.test(content))
    .setHandler(async msg => {
      let id = parseInt(msg.content.replace(/^\/(.*) /gim, "").trim(), 10);
      if (Number.isNaN(id)) id = Math.round(Math.random() * 1851);

      id = await api.xkcd(id);

      const embed = new Discord.RichEmbed().setColor(0x2196f3);
      embed.setURL(`https://xkcd.ru/${id}/`);
      embed.setImage(`https://xkcd.ru/i/${id}_v1.png`);

      msg.channel.send({ embed });
    });

  Command.add()
    .setTest(content => /^\/(t|translate|п|перевод) /gim.test(content))
    .setHandler(async msg => {
      const q = msg.content.replace(/^\/(.*) /gim, "").trim();
      if (!q) return;

      const text = await api.translate(q);
      //msg.reply(text);
    });
};

module.exports = main;
<commit_msg>add or meter<commit_after>const Discord = require("discord.js");
const Command = require("./Command");
const api = require("./api");

const main = (store, client) => {
  Command.setStorage(store);

  Command.add()
    .setTest(content => content.startsWith("/help"))
    .setHandler(msg => {
      const embed = new Discord.RichEmbed()
        .setColor(0x00ae86)
        .setTitle("Список команд")
        .setDescription(
          "`/help` - Выводит текущую команду\n" +
            "`/news` - Поиск по https://haipit.news \n" +
            "`/l /lurk /lurkmore /л /лурка /лурк` - Поиск по https://lurkmore.to/ \n" +
            "`/kill` - Выводит `Тобi пизда!`\n " +
            "`/getrandomnumber` - Выводит 42\n " +
            "`/xkcd` - Выводит случайный (или с определенным id) комикс с https://xkcd.ru\n "
        );
      msg.channel.send({ embed });
    });

  // find hapi news
  Command.add()
    .setTest(content => content.startsWith("/news"))
    .setHandler(async msg => {
      const q = msg.content.substr(5).trim();
      if (!q) return;

      const result = await api.hapiNews("find", {
        keywords: q,
        platform: "Очень модный бот",
        limit: 25
      });

      const embed = new Discord.RichEmbed().setColor(0x009ea6);

      const news = JSON.parse(result);
      if (!news) {
        embed.setDescription("Ничего не найдено");
      } else {
        news.forEach((item, i) => {
          if (i > 24) return;

          embed.addField(item.title, item.url);
        });
      }

      msg.channel.send({ embed });
    });

  // random news
  Command.add()
    .setTest(content => content.startsWith("/randomnews"))
    .setHandler(async msg => {
      const q = msg.content.substr(11).trim();
      if (!q) return;

      const result = await api.hapiNews("news/random/", {
        platform: "Очень модный бот",
        limit: 25
      });

      const embed = new Discord.RichEmbed().setColor(0x009ea6);

      const news = JSON.parse(result);
      if (!news) {
        embed.setDescription("Ничего не найдено");
      } else {
        news.forEach((item, i) => {
          if (i > 24) return;

          embed.addField(item.title, item.url);
        });
      }

      msg.channel.send({ embed });
    });

  Command.add()
    .setTest(content => content.startsWith("/kill"))
    .setHandler(async msg => {
      let [_, user = ""] = msg.content.split(" ");
      if (user) user += ", ";
      msg.channel.send(`${user} Тобi пизда!`);
    });

  Command.add()
    .setTest(content => content.startsWith("/getrandomnumber"))
    .setHandler(async msg => {
      msg.channel.send("42");
    });

  Command.add()
    .setTest(content => /^\/(l|lurk|lurkmore|л|лурка|лурк) /gim.test(content))
    .setHandler(async msg => {
      const q = msg.content.replace(/^\/(.*) /gim, "").trim();
      if (!q) return;

      const embed = new Discord.RichEmbed().setColor(0x8bc34a);

      try {
        const { data } = await api.lurk(q);

        if (data.ogTitle) embed.setTitle(data.ogTitle);
        if (data.ogUrl) embed.setURL("https:" + data.ogUrl);
        if (data.ogDescription) embed.setDescription(data.ogDescription);

        msg.channel.send({ embed });
      } catch (e) {
        embed.setDescription("Не найдено");
        msg.channel.send({ embed });
      }
    });

  Command.add()
    .setTest(content =>
      /^\/(w|wiki|wikipedia|в|вики|википедия) /gim.test(content)
    )
    .setHandler(async msg => {
      const q = msg.content.replace(/^\/(.*) /gim, "").trim();
      if (!q) return;

      const embed = new Discord.RichEmbed().setColor(0x8bc34a);

      try {
        const { data } = await api.wiki(q);

        console.log(data);
        if (data.ogTitle) embed.setTitle(data.ogTitle);
        embed.setURL("https://ru.wikipedia.org/wiki/" + q);
        if (data.ogDescription) embed.setDescription(data.ogDescription);
        if (data.ogImage) {
          if (data.ogImage.url[0] !== "h")
            data.ogImage.url = `http:${data.ogImage.url}`;
          embed.setImage(data.ogImage.url);
        }

        msg.channel.send({ embed });
      } catch (e) {
        embed.setDescription("Не найдено");
        msg.channel.send({ embed });
      }
    });

  const mountains = [
    { name: "Кула-Кангри", height: 7538 },
    { name: "Лупгхар-Шар", height: 7200 },
    { name: "Конгуртюбе", height: 7530 },
    { name: "Канченджанга", height: 8586 },
    { name: "Макалу", height: 8485 },
    { name: "Чо-Ойю", height: 8188 },
    { name: "Дхаулагири", height: 8167 },
    { name: "Манаслу", height: 8163 },
    { name: "Нангапарбат", height: 8126 },
    { name: "Аннапурна I", height: 8091 },
    { name: "Гашербрум I", height: 8080 },
    { name: "Броуд-Пик", height: 8051 },
    { name: "Гашербрум II", height: 8034 },
    { name: "Шишабангма", height: 8027 },
    { name: "Гьячунг-Канг", height: 7952 },
    { name: "Гашербрум III", height: 7946 },
    { name: "Аннапурна II", height: 7937 },
    { name: "Гашербрум IV", height: 7932 },
    { name: "Хималчули", height: 7893 },
    { name: "Дастогхил", height: 7884 },
    { name: "Нгади-Чули", height: 7871 },
    { name: "Нупцзе", height: 7864 },
    { name: "Кунианг-Киш", height: 7823 },
    { name: "Машербрум", height: 7821 },
    { name: "Нандадеви", height: 7816 },
    { name: "Чомолонзо", height: 7804 },
    { name: "Батура-Шар[en]", height: 7795 },
    { name: "Канжут-Шар", height: 7790 },
    { name: "Ракапоши (англ.)русск.", height: 7788 },
    { name: "Намджагбарва", height: 7782 },
    { name: "Камет (англ.)русск.", height: 7756 },
    { name: "Дхаулагири II", height: 7751 },
    { name: "Салторо-Кангри", height: 7742 },
    { name: "Жанну", height: 7711 },
    { name: "Тиричмир", height: 7708 },
    { name: "Моламенкинг", height: 7703 },
    { name: "Гурла-Мандхата", height: 7694 },
    { name: "Сасер-Кангри I[en]", height: 7672 },
    { name: "Чоголиза", height: 7665 },
    { name: "Дхаулагири IV", height: 7661 },
    { name: "Конгур", height: 7649 },
    { name: "Дхаулагири V", height: 7618 },
    { name: "Шиспар[en]", height: 7611 },
    { name: "Тривор", height: 7577 },
    { name: "Канкар-Пунсум", height: 7570 },
    { name: "Гунгашань[en]", height: 7556 },
    { name: "Аннапурна III", height: 7555 },
    { name: "Музтагата", height: 7546 },
    { name: "Скьянг-Кангри", height: 7545 },
    { name: "Чангзе", height: 7543 },
    { name: "Сингхи-Кангри", height: 7202 },
    { name: "Лхоцзе", height: 8516 },
    { name: "Мамостонг-Кангри (англ.)русск.", height: 7516 },
    { name: "Сасер-Кангри II (англ.)русск.[7]", height: 7513 },
    { name: "Пик Исмоила Сомони", height: 7495 },
    { name: "Сасер-Кангри III (англ.)русск.", height: 7495 },
    { name: "Ношак", height: 7492 },
    { name: "Пумари-Киш", height: 7492 },
    { name: "Пасу-Сар (англ.)русск.", height: 7476 },
    { name: "Юкшин-Гардан-Сар (англ.)русск.", height: 7469 },
    { name: "Терам Кангри I[en]", height: 7462 },
    { name: "Джонгсонг", height: 7462 },
    { name: "Малубитинг[en]", height: 7458 },
    { name: "Гангапурна", height: 7455 },
    { name: "Пик Победы", height: 7439 },
    { name: "К12", height: 7428 },
    { name: "Янгра[en](Ганеш I)", height: 7422 },
    { name: "en: Sia Kangri", height: 7422 },
    { name: "Момхиль-Шар", height: 7414 },
    { name: "en: Kabru N", height: 7412 },
    { name: "Скил-Брум", height: 7410 },
    { name: "Харамош", height: 7409 },
    { name: "en: Istor-o-Nal", height: 7403 },
    { name: "en: Ghent Kangri", height: 7401 },
    { name: "Ултар[en]", height: 7388 },
    { name: "Римо I", height: 7385 },
    { name: "Churen Himal", height: 7385 },
    { name: "Терам Кангри III[en]", height: 7382 },
    { name: "en: Sherpi Kangri", height: 7380 },
    { name: "en: Labuche Kang", height: 7367 },
    { name: "Кират-Чули", height: 7362 },
    { name: "en: Abi Gamin", height: 7355 },
    { name: "Mana", height: 7272 },
    { name: "Дхаулагири VI", height: 7268 },
    { name: "en: Diran", height: 7266 },
    { name: "en: Labuche Kang III / East[12]", height: 7250 },
    { name: "Putha Hiunchuli", height: 7246 },
    { name: "en: Apsarasas Kangri", height: 7245 },
    { name: "Mukut Parbat", height: 7242 },
    { name: "en: Rimo III", height: 7233 },
    { name: "en:Langtang Lirung", height: 7227 },
    { name: "Карджианг", height: 7221 },
    { name: "Аннапурна Южная", height: 7219 },
    { name: "Кхартапху", height: 7213 },
    { name: "Тонгшанджиабу[13][14]", height: 7207 },
    { name: "en:Malangutti Sar", height: 7207 },
    { name: "Ноценкансари", height: 7206 },
    { name: "Лангтанг-Ри[en]", height: 7205 },
    { name: "Кангпху-Канг[15]", height: 7204 },
    { name: "Чогори", height: 8611 },
    { name: "Джомолунгма\n", height: 8848 }
  ];

  Command.add()
    .setTest(content => /^ор/gim.test(content))
    .setHandler(async msg => {
      const id = Math.round(Math.random() * mountains.length * 1.1);
      let text = "";

      if (id > mountains.length - 1) text = "Ваш ор выше всех гор!";
      else if (id === 0) text = "Ваш ор ниже всех гор!";
      else if (id === mountains.length - 1) {
        const m = mountains[id];
        text = `Ваш ор выше самой высокой горы - ${m.name}(${m.height}м)!`;
      } else {
        const m1 = mountains[id];
        const m2 = mountains[id + 1];
        text = `Ваш ор выше ${m1.name}(${m1.height}м) и ниже ${m2.name}(${m2.height}м)!`;
      }

      embed.setDescription(text);

      msg.channel.send({ embed });
    });

  Command.add()
    .setTest(content => /^\/(xkcd)/gim.test(content))
    .setHandler(async msg => {
      let id = parseInt(msg.content.replace(/^\/(.*) /gim, "").trim(), 10);
      if (Number.isNaN(id)) id = Math.round(Math.random() * 1851);

      id = await api.xkcd(id);

      const embed = new Discord.RichEmbed().setColor(0x2196f3);
      embed.setURL(`https://xkcd.ru/${id}/`);
      embed.setImage(`https://xkcd.ru/i/${id}_v1.png`);

      msg.channel.send({ embed });
    });

  Command.add()
    .setTest(content => /^\/(t|translate|п|перевод) /gim.test(content))
    .setHandler(async msg => {
      const q = msg.content.replace(/^\/(.*) /gim, "").trim();
      if (!q) return;

      const text = await api.translate(q);
      //msg.reply(text);
    });
};

module.exports = main;
<|endoftext|>


<commit_before>export default function getNextIndexByKey(
  key,
  currentIndex,
  lastIndex,
  isLoading
) {
  const isNoOptionSelected = currentIndex === -1;
  let newIndex = currentIndex;

  if (key === "Home") {
    newIndex = 0;
  } else if (key === "End") {
    newIndex = lastIndex;
  } else if (key === "ArrowDown") {
    if (isLoading && currentIndex === lastIndex) {
      return lastIndex;
    }

    if (currentIndex === lastIndex || isNoOptionSelected) {
      newIndex = 0;
    } else {
      newIndex = currentIndex + 1;
    }
  } else if (key === "ArrowUp") {
    if (currentIndex === 0 || isNoOptionSelected) {
      newIndex = lastIndex;
    } else {
      newIndex = currentIndex - 1;
    }
  }

  return newIndex;
}
<commit_msg>refactor(get-next-index-by-key): use switch instead of if-else<commit_after>export default function getNextIndexByKey(
  key,
  currentIndex,
  lastIndex,
  isLoading
) {
  const isNoOptionSelected = currentIndex === -1;
  let newIndex = currentIndex;

  switch (key) {
    case "Home":
      newIndex = 0;
      break;
    case "End":
      newIndex = lastIndex;
      break;
    case "ArrowDown":
      if (isLoading && currentIndex === lastIndex) {
        return lastIndex;
      }

      if (currentIndex === lastIndex || isNoOptionSelected) {
        newIndex = 0;
      } else {
        newIndex = currentIndex + 1;
      }
      break;
    case "ArrowUp":
      if (currentIndex === 0 || isNoOptionSelected) {
        newIndex = lastIndex;
      } else {
        newIndex = currentIndex - 1;
      }
      break;
    default:
      break;
  }

  return newIndex;
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes as PT } from 'react'
import { debounce } from 'core-decorators'

export default class SpeechRecognition extends Component {
  static propTypes = {
    className: PT.string,
    onChange: PT.func,
    visible: PT.bool,
    listening: PT.bool,
    language: PT.string,
    showInterimResults: PT.bool,
    showFinalResults: PT.bool,
    entities: PT.arrayOf(PT.string),
    onHearEntity: PT.func,
    onLoad: PT.func,
    name: PT.string
  };

  static defaultProps = {
    visible: true,
    listening: true,
    showInterimResults: true,
    showFinalResults: true
  };

  constructor(props) {
    super(props)

    this.state = {
      interimTranscript: '',
      finalTranscript: '',
      browserSupportsSpeechRecognition: true,
      recognition: null
    }
  }

  componentWillMount() {
    const { language, listening, onLoad } = this.props
    const root = typeof window !== 'undefined' ? window : this
    const BrowserSpeechRecognition = root.SpeechRecognition ||
                                     root.webkitSpeechRecognition ||
                                     root.mozSpeechRecognition ||
                                     root.msSpeechRecognition ||
                                     root.oSpeechRecognition
    if (BrowserSpeechRecognition) {
      const recognition = new BrowserSpeechRecognition()
      recognition.continuous = true
      recognition.interimResults = true
      if (language) {
        recognition.lang = language
      }
      recognition.onresult = this.updateTranscript.bind(this)
      recognition.onend = this.restartRecognition.bind(this)
      if (listening) {
        recognition.start()
      }
      this.setState({ recognition })
      onLoad({ success: true })
    } else {
      this.setState({ browserSupportsSpeechRecognition: false })
      onLoad({ success: false })
    }
  }

  componentWillUnmount() {
    if (this.state.recognition) {
      this.state.recognition.abort()
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.recognition) {
      if (this.props.listening && !nextProps.listening) {
        this.state.recognition.stop()
      } else if (!this.props.listening && nextProps.listening) {
        this.state.recognition.start()
      }

      /* Changing the name prop is the equivalent of resetting the component.
        Preferably, this would be done by changing the key prop, but
        re-rendering the component seems to break the speech recognition. */
      if (this.props.name !== nextProps.name) {
        this.setState({ interimTranscript: '', finalTranscript: '' })
        this.state.recognition.abort()
      }
    }
  }

  updateTranscript(event) {
    const { onChange } = this.props
    const { finalTranscript, interimTranscript } = this.getNewTranscript(event)

    this.handleSpokenEntity(interimTranscript)

    const transcriptBefore = this.concatTranscripts(this.state.finalTranscript, this.state.interimTranscript)
    const transcriptAfter = this.concatTranscripts(finalTranscript, interimTranscript)

    if (onChange && transcriptBefore !== transcriptAfter) {
      onChange(transcriptAfter)
    }

    this.setState({ finalTranscript, interimTranscript })
  }

  @debounce(1000)
  restartRecognition() {
    const { listening } = this.props
    const { recognition } = this.state

    if (listening) {
      recognition.start()
    }
  }

  getNewTranscript(event) {
    let finalTranscript = this.state.finalTranscript
    let interimTranscript = ''
    for (let i = event.resultIndex; i < event.results.length; ++i) {
      if (event.results[i].isFinal) {
        finalTranscript = this.concatTranscripts(finalTranscript, event.results[i][0].transcript)
      } else {
        interimTranscript = this.concatTranscripts(interimTranscript, event.results[i][0].transcript)
      }
    }
    return { finalTranscript, interimTranscript }
  }

  concatTranscripts(...transcriptParts) {
    return transcriptParts.map(t => t.trim()).join(' ').trim()
  }

  handleSpokenEntity(interimTranscript) {
    const { entities, onHearEntity } = this.props

    if (entities && onHearEntity && interimTranscript !== this.state.interimTranscript) {
      const mostRecentlySpokenEntity = this.findEntity(entities, interimTranscript)
      if (mostRecentlySpokenEntity) {
        onHearEntity(mostRecentlySpokenEntity)
      }
    }
  }

  findEntity(entities, transcript) {
    const words = transcript.toLowerCase().split(' ')
    const normalisedEntities = entities.map(e => e.toLowerCase())
    for (let i = 0; i < normalisedEntities.length; ++i) {
      if (words[words.length - 1] === normalisedEntities[i]) {
        return normalisedEntities[i]
      }
    }
    return null
  }

  render() {
    const { className, visible, showInterimResults, showFinalResults } = this.props
    const { interimTranscript, finalTranscript, browserSupportsSpeechRecognition } = this.state

    if (!visible || !browserSupportsSpeechRecognition) {
      return null
    }

    const transcriptParts = []
    if (showFinalResults) {
      transcriptParts.push(finalTranscript)
    }
    if (showInterimResults) {
      transcriptParts.push(interimTranscript)
    }

    return (

        {transcriptParts.join(' ')}

    )
  }
}
<commit_msg>Only call onLoad if it is provided<commit_after>import React, { Component, PropTypes as PT } from 'react'
import { debounce } from 'core-decorators'

export default class SpeechRecognition extends Component {
  static propTypes = {
    className: PT.string,
    onChange: PT.func,
    visible: PT.bool,
    listening: PT.bool,
    language: PT.string,
    showInterimResults: PT.bool,
    showFinalResults: PT.bool,
    entities: PT.arrayOf(PT.string),
    onHearEntity: PT.func,
    onLoad: PT.func,
    name: PT.string
  };

  static defaultProps = {
    visible: true,
    listening: true,
    showInterimResults: true,
    showFinalResults: true
  };

  constructor(props) {
    super(props)

    this.state = {
      interimTranscript: '',
      finalTranscript: '',
      browserSupportsSpeechRecognition: true,
      recognition: null
    }
  }

  componentWillMount() {
    const { language, listening, onLoad } = this.props
    const root = typeof window !== 'undefined' ? window : this
    const BrowserSpeechRecognition = root.SpeechRecognition ||
                                     root.webkitSpeechRecognition ||
                                     root.mozSpeechRecognition ||
                                     root.msSpeechRecognition ||
                                     root.oSpeechRecognition
    if (BrowserSpeechRecognition) {
      const recognition = new BrowserSpeechRecognition()
      recognition.continuous = true
      recognition.interimResults = true
      if (language) {
        recognition.lang = language
      }
      recognition.onresult = this.updateTranscript.bind(this)
      recognition.onend = this.restartRecognition.bind(this)
      if (listening) {
        recognition.start()
      }
      this.setState({ recognition })
      if (onLoad) {
        onLoad({ success: true })
      }
    } else {
      this.setState({ browserSupportsSpeechRecognition: false })
      if (onLoad) {
        onLoad({ success: false })
      }
    }
  }

  componentWillUnmount() {
    if (this.state.recognition) {
      this.state.recognition.abort()
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.recognition) {
      if (this.props.listening && !nextProps.listening) {
        this.state.recognition.stop()
      } else if (!this.props.listening && nextProps.listening) {
        this.state.recognition.start()
      }

      /* Changing the name prop is the equivalent of resetting the component.
        Preferably, this would be done by changing the key prop, but
        re-rendering the component seems to break the speech recognition. */
      if (this.props.name !== nextProps.name) {
        this.setState({ interimTranscript: '', finalTranscript: '' })
        this.state.recognition.abort()
      }
    }
  }

  updateTranscript(event) {
    const { onChange } = this.props
    const { finalTranscript, interimTranscript } = this.getNewTranscript(event)

    this.handleSpokenEntity(interimTranscript)

    const transcriptBefore = this.concatTranscripts(this.state.finalTranscript, this.state.interimTranscript)
    const transcriptAfter = this.concatTranscripts(finalTranscript, interimTranscript)

    if (onChange && transcriptBefore !== transcriptAfter) {
      onChange(transcriptAfter)
    }

    this.setState({ finalTranscript, interimTranscript })
  }

  @debounce(1000)
  restartRecognition() {
    const { listening } = this.props
    const { recognition } = this.state

    if (listening) {
      recognition.start()
    }
  }

  getNewTranscript(event) {
    let finalTranscript = this.state.finalTranscript
    let interimTranscript = ''
    for (let i = event.resultIndex; i < event.results.length; ++i) {
      if (event.results[i].isFinal) {
        finalTranscript = this.concatTranscripts(finalTranscript, event.results[i][0].transcript)
      } else {
        interimTranscript = this.concatTranscripts(interimTranscript, event.results[i][0].transcript)
      }
    }
    return { finalTranscript, interimTranscript }
  }

  concatTranscripts(...transcriptParts) {
    return transcriptParts.map(t => t.trim()).join(' ').trim()
  }

  handleSpokenEntity(interimTranscript) {
    const { entities, onHearEntity } = this.props

    if (entities && onHearEntity && interimTranscript !== this.state.interimTranscript) {
      const mostRecentlySpokenEntity = this.findEntity(entities, interimTranscript)
      if (mostRecentlySpokenEntity) {
        onHearEntity(mostRecentlySpokenEntity)
      }
    }
  }

  findEntity(entities, transcript) {
    const words = transcript.toLowerCase().split(' ')
    const normalisedEntities = entities.map(e => e.toLowerCase())
    for (let i = 0; i < normalisedEntities.length; ++i) {
      if (words[words.length - 1] === normalisedEntities[i]) {
        return normalisedEntities[i]
      }
    }
    return null
  }

  render() {
    const { className, visible, showInterimResults, showFinalResults } = this.props
    const { interimTranscript, finalTranscript, browserSupportsSpeechRecognition } = this.state

    if (!visible || !browserSupportsSpeechRecognition) {
      return null
    }

    const transcriptParts = []
    if (showFinalResults) {
      transcriptParts.push(finalTranscript)
    }
    if (showInterimResults) {
      transcriptParts.push(interimTranscript)
    }

    return (

        {transcriptParts.join(' ')}

    )
  }
}
<|endoftext|>


<commit_before>/**
 * HTTP Server Settings
 * (sails.config.http)
 *
 * Configuration for the underlying HTTP server in Sails.
 * Only applies to HTTP requests (not WebSockets)
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.http.html
 */

module.exports.http = {

  /****************************************************************************
  *                                                                           *
  * Express middleware to use for every Sails request. To add custom          *
  * middleware to the mix, add a function to the middleware config object and *
  * add its key to the "order" array. The $custom key is reserved for         *
  * backwards-compatibility with Sails v0.9.x apps that use the               *
  * `customMiddleware` config option.                                         *
  *                                                                           *
  ****************************************************************************/

  // middleware: {

  /***************************************************************************
  *                                                                          *
  * The order in which middleware should be run for HTTP request. (the Sails *
  * router is invoked by the "router" middleware below.)                     *
  *                                                                          *
  ***************************************************************************/

    // order: [
    //   'startRequestTimer',
    //   'cookieParser',
    //   'session',
    //   'myRequestLogger',
    //   'bodyParser',
    //   'handleBodyParserError',
    //   'compress',
    //   'methodOverride',
    //   'poweredBy',
    //   '$custom',
    //   'router',
    //   'www',
    //   'favicon',
    //   '404',
    //   '500'
    // ],

  /****************************************************************************
  *                                                                           *
  * Example custom middleware; logs each request to the console.              *
  *                                                                           *
  ****************************************************************************/

    // myRequestLogger: function (req, res, next) {
    //     console.log("Requested :: ", req.method, req.url);
    //     return next();
    // }

  /***************************************************************************
  *                                                                          *
  * The body parser that will handle incoming multipart HTTP requests. By    *
  * default as of v0.10, Sails uses                                          *
  * [skipper](http://github.com/balderdashy/skipper). See                    *
  * http://www.senchalabs.org/connect/multipart.html for other options.      *
  *                                                                          *
  ***************************************************************************/

    // bodyParser: require('skipper')

  // },

  /***************************************************************************
  *                                                                          *
  * The number of seconds to cache flat files on disk being served by        *
  * Express static middleware (by default, these files are in `.tmp/public`) *
  *                                                                          *
  * The HTTP static cache is only active in a 'production' environment,      *
  * since that's the only time Express will cache flat-files.                *
  *                                                                          *
  ***************************************************************************/

  // cache: 31557600000
};
<commit_msg>enabled middleware, stubbed out ActiveRules middlewar<commit_after>/**
 * HTTP Server Settings
 * (sails.config.http)
 *
 * Configuration for the underlying HTTP server in Sails.
 * Only applies to HTTP requests (not WebSockets)
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.http.html
 */

module.exports.http = {

  /****************************************************************************
  *                                                                           *
  * Express middleware to use for every Sails request. To add custom          *
  * middleware to the mix, add a function to the middleware config object and *
  * add its key to the "order" array. The $custom key is reserved for         *
  * backwards-compatibility with Sails v0.9.x apps that use the               *
  * `customMiddleware` config option.                                         *
  *                                                                           *
  ****************************************************************************/

  middleware: {

  /***************************************************************************
  *                                                                          *
  * The order in which middleware should be run for HTTP request. (the Sails *
  * router is invoked by the "router" middleware below.)                     *
  *                                                                          *
  ***************************************************************************/

    order: [
      'startRequestTimer',
      'cookieParser',
      'session',
      'passportInit',    // <==== passport HTTP middleware should run after "session"
      'passportSession', // <==== (https://github.com/jaredhanson/passport#middleware)
      'requestLogger',
      'bodyParser',
      'handleBodyParserError',
      'compress',
      'methodOverride',
      'poweredBy',
      '$custom',
      'activeRulesSite',
      'router',
      'www',
      'favicon',
      '404',
      '500'
    ],

  /****************************************************************************
  *                                                                           *
  * Example custom middleware; logs each request to the console.              *
  *                                                                           *
  ****************************************************************************/

    requestLogger: function (req, res, next) {
      console.log("Requested :: ", req.method, req.url);
      return next();
    },

    activeRulesSite: function (req, res, next) {
      res.site = {'name': 'ActiveRules',
                  'copyright': 'ActiveRules © 2014',
                  'hostname': req.host
                };
      return next();
    }

  /***************************************************************************
  *                                                                          *
  * The body parser that will handle incoming multipart HTTP requests. By    *
  * default as of v0.10, Sails uses                                          *
  * [skipper](http://github.com/balderdashy/skipper). See                    *
  * http://www.senchalabs.org/connect/multipart.html for other options.      *
  *                                                                          *
  ***************************************************************************/

    // bodyParser: require('skipper')

  }

  /***************************************************************************
  *                                                                          *
  * The number of seconds to cache flat files on disk being served by        *
  * Express static middleware (by default, these files are in `.tmp/public`) *
  *                                                                          *
  * The HTTP static cache is only active in a 'production' environment,      *
  * since that's the only time Express will cache flat-files.                *
  *                                                                          *
  ***************************************************************************/

  // cache: 31557600000
};
<|endoftext|>


<commit_before>"use strict";

define(['jquery', 'messages', 'dbus!_',
        'switch', 'jquery.tipsy'],
function($, messages, dbusProxy) {

    // ExtensionState and versionCheck are stolen and should
    // be kept in sync those from the Shell.
    // Licensed under GPL2+
    // See: http://git.gnome.org/browse/gnome-shell/tree/js/ui/extensionSystem.js

    var ExtensionState = {
        ENABLED: 1,
        DISABLED: 2,
        ERROR: 3,
        OUT_OF_DATE: 4,
        DOWNLOADING: 5,
        INITIALIZED: 6,

        // Not a real state, used when there's no extension
        // with the associated UUID in the extension map.
        UNINSTALLED: 99
    };

    function versionCheck(required, current) {
        var currentArray = current.split('.');
        var major = currentArray[0];
        var minor = currentArray[1];
        var point = currentArray[2];
        for (var i = 0; i < required.length; i++) {
            var requiredArray = required[i].split('.');
            if (requiredArray[0] == major &&
                requiredArray[1] == minor &&
                (requiredArray[2] == point ||
                 (requiredArray[2] == undefined && parseInt(minor) % 2 == 0)))
                return true;
        }
        return false;
    }

    // While technically we shouldn't have mismatched API versions,
    // the plugin doesn't check whether the Shell matches, so if someone
    // is running with an old Shell version but a newer plugin, error out.
    if (dbusProxy === undefined ||
        dbusProxy.ShellVersion === undefined) {
        // We don't have a proper DBus proxy -- it's probably an old
        // version of GNOME3 or the Shell.
        messages.addError("You do not appear to have an up to date version of GNOME3. Some parts of the website may be disabled.");

        $.fn.addExtensionsSwitches = function() {
            // Don't show our switches -- CSS styles define a clickable
            // area even with no content.
            $(this).find('.switch').hide();
        };

        $.fn.addLocalExtensions = function() {
            $(this).append("GNOME Shell Extensions cannot list your installed extensions.");
        };

        $.fn.fillInErrors = function() {
            var $form = $(this);
            var $textarea = $form.find('textarea[name=error]');
            var $hidden = $form.find('input:hidden[name=has_errors]');
            $textarea.text("GNOME Shell Extensions cannot automatically detect any errors.").
                addClass('no-errors').attr('disabled', 'disabled');
            $hidden.val('');
        };

        return;
    }

    // uuid => elem
    var elems = {};

    dbusProxy.extensionStateChangedHandler = function(uuid, newState, _) {
        elems[uuid].trigger('state-changed', newState);
    };

    function addExtensionSwitch(uuid, extension, $elem) {
        var shellVersions = $elem.data('sv');

        var $switch = $elem.find('.switch');
        var _state = ExtensionState.UNINSTALLED;

        if (shellVersions && !versionCheck(shellVersions, dbusProxy.ShellVersion)) {
            _state = ExtensionState.OUT_OF_DATE;
        } else if (extension) {
            _state = extension.state;
        }

        $elem.data({'elem': $elem,
                    'state': _state,
                    'uninstalled': false});

        $switch.data('elem', $elem);
        $switch.switchify();
        if ($switch.hasClass('insensitive'))
            return;

        $switch.bind('changed', function(e, newValue) {
            var oldState = $elem.data('state');
            if (newValue) {
                if (oldState == ExtensionState.UNINSTALLED) {
                    // If the extension is uninstalled and we
                    // flick the switch on, install.
                    dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());
                } else if (oldState == ExtensionState.DISABLED ||
                           oldState == ExtensionState.INITIALIZED) {
                    dbusProxy.EnableExtension(uuid);
                }
            } else {
                if (oldState == ExtensionState.ENABLED)
                    dbusProxy.DisableExtension(uuid);
            }
        });

        $elem.bind('state-changed', function(e, newState) {
            $elem.data('state', newState);
            $switch.switchify('insensitive', false);
            $switch.tipsy({ gravity: 'e', fade: true });
            if (newState == ExtensionState.DISABLED ||
                newState == ExtensionState.INITIALIZED ||
                newState == ExtensionState.UNINSTALLED) {
                $switch.switchify('activate', false);
            } else if (newState == ExtensionState.ENABLED) {
                $switch.switchify('activate', true);
            } else if (newState == ExtensionState.ERROR) {
                $switch.switchify('insensitive', true);
                $switch.attr('title', "This extension had an error.");
            } else if (newState == ExtensionState.OUT_OF_DATE) {
                $switch.switchify('insensitive', true);
                messages.addError("This extension is not compatible with your version of GNOME.");
            }

            if ($elem.data('uninstalled') && (newState == ExtensionState.ENABLED ||
                                              newState == ExtensionState.ERROR ||
                                              newState == ExtensionState.OUT_OF_DATE)) {
                $elem.fadeIn({ queue: false }).slideDown();
                $elem.data('uninstalled', false);
            }

        });
        $elem.trigger('state-changed', _state);
        elems[uuid] = $elem;
    }

    $.fn.addLocalExtensions = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            if (extensions && Object.keys(extensions).length) {
                var extensionValues = [];
                for (var uuid in extensions) {
                    extensionValues.push(extensions[uuid]);
                }

                extensionValues.sort(function(a, b) {
                    return a.name.localeCompare(b.name);
                });

                extensionValues.forEach(function(extension) {
                    var uuid = extension.uuid;

                    function reinstall() {
                        dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());

                        // If the user clicks "Install" we need to show that we
                        // installed it by reattaching the element, but we can't do
                        // that here -- the user might click "Cancel".
                        $elem.data('uninstalled', true);

                        message.slideUp();
                    }

                    function uninstall() {
                        dbusProxy.UninstallExtension(uuid).done(function(result) {
                            if (result) {
                                $elem.fadeOut({ queue: false }).slideUp({ queue: false });

                                // Construct a dummy
 node as we need something
                                // to stuff everything else in...
                                var messageHTML = $("
You uninstalled
").
                                    append($('').text(extension.name)).
                                    append(". ").
                                    append($('', {'href': '#'}).text("Undo?")).html();

                                var message = messages.addInfo(messageHTML);
                                message.find('a').click(reinstall);
                                $elem.data('undo-uninstall-message', message);
                            }
                        });
                    }

                    var $elem = $('
', {'class': 'extension'}).
                        append($('
', {'class': 'switch'})).
                        append($('', {'class': 'icon'})).
                        append($('
', {'class': 'extension-name'}).text(extension.name)).
                        append($('', {'class': 'author'})).
                        append($('
', {'class': 'description'}).text(extension.description));

                    $.ajax({
                        url: "/ajax/detail/",
                        dataType: "json",
                        data: { uuid: uuid },
                        type: "GET",
                    }).done(function(result) {
                        $elem.
                            find('span.author').text(" by ").append($('', {'href': "/accounts/profile/" + result.creator})).end().
                            find('img.icon').detach().end().
                            find('h3').html($('', {'href': result.link}).append($('', {'class': 'icon', 'src': result.icon})).append(extension.name)).end().
                            append($('<button>', {'class': 'uninstall', 'title': "Uninstall"}).text("Uninstall").bind('click', uninstall)).
                            data('pk', result.pk);
                    });

                    // The DOM element's CSS styles won't be fully
                    // computed, so the switch will be incorrectly
                    // positioned -- wait a bit before adding them.
                    setTimeout(function() {
                        addExtensionSwitch(uuid, extension, $elem);
                    }, 0);

                    $container.append($elem);
                });
            } else {
                $container.append("You don't have any extensions installed.");
            }
        });
    };

    $.fn.fillInErrors = function (uuid) {
        var $form = $(this);
        var $textarea = $form.find('textarea');
        dbusProxy.GetErrors(uuid).done(function(errors) {
            var errorString;

            if (errors && errors.length) {
                errorString = errors.join('\n\n================\n\n');
            } else {
                errorString = "GNOME Shell Extensions did not detect any errors with this extension.";
            }

            var template = ("What's wrong?\n\n\n" +
                            "What have I tried?\n\n\n" +
                            "Automatically detected errors:\n\n" + errorString);

            $textarea.text(template);
        });
    };

    $.fn.addExtensionsSwitches = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            $container.each(function () {
                var uuid = $(this).data('uuid');
                addExtensionSwitch(uuid, extensions[uuid], $(this));
            });
        });
    };

});
<commit_msg>Fix "Undo?" on uninstall.<commit_after>"use strict";

define(['jquery', 'messages', 'dbus!_',
        'switch', 'jquery.tipsy'],
function($, messages, dbusProxy) {

    // ExtensionState and versionCheck are stolen and should
    // be kept in sync those from the Shell.
    // Licensed under GPL2+
    // See: http://git.gnome.org/browse/gnome-shell/tree/js/ui/extensionSystem.js

    var ExtensionState = {
        ENABLED: 1,
        DISABLED: 2,
        ERROR: 3,
        OUT_OF_DATE: 4,
        DOWNLOADING: 5,
        INITIALIZED: 6,

        // Not a real state, used when there's no extension
        // with the associated UUID in the extension map.
        UNINSTALLED: 99
    };

    function versionCheck(required, current) {
        var currentArray = current.split('.');
        var major = currentArray[0];
        var minor = currentArray[1];
        var point = currentArray[2];
        for (var i = 0; i < required.length; i++) {
            var requiredArray = required[i].split('.');
            if (requiredArray[0] == major &&
                requiredArray[1] == minor &&
                (requiredArray[2] == point ||
                 (requiredArray[2] == undefined && parseInt(minor) % 2 == 0)))
                return true;
        }
        return false;
    }

    // While technically we shouldn't have mismatched API versions,
    // the plugin doesn't check whether the Shell matches, so if someone
    // is running with an old Shell version but a newer plugin, error out.
    if (dbusProxy === undefined ||
        dbusProxy.ShellVersion === undefined) {
        // We don't have a proper DBus proxy -- it's probably an old
        // version of GNOME3 or the Shell.
        messages.addError("You do not appear to have an up to date version of GNOME3. Some parts of the website may be disabled.");

        $.fn.addExtensionsSwitches = function() {
            // Don't show our switches -- CSS styles define a clickable
            // area even with no content.
            $(this).find('.switch').hide();
        };

        $.fn.addLocalExtensions = function() {
            $(this).append("GNOME Shell Extensions cannot list your installed extensions.");
        };

        $.fn.fillInErrors = function() {
            var $form = $(this);
            var $textarea = $form.find('textarea[name=error]');
            var $hidden = $form.find('input:hidden[name=has_errors]');
            $textarea.text("GNOME Shell Extensions cannot automatically detect any errors.").
                addClass('no-errors').attr('disabled', 'disabled');
            $hidden.val('');
        };

        return;
    }

    // uuid => elem
    var elems = {};

    dbusProxy.extensionStateChangedHandler = function(uuid, newState, _) {
        elems[uuid].trigger('state-changed', newState);
    };

    function addExtensionSwitch(uuid, extension, $elem) {
        var shellVersions = $elem.data('sv');

        var $switch = $elem.find('.switch');
        var _state = ExtensionState.UNINSTALLED;

        if (shellVersions && !versionCheck(shellVersions, dbusProxy.ShellVersion)) {
            _state = ExtensionState.OUT_OF_DATE;
        } else if (extension) {
            _state = extension.state;
        }

        $elem.data({'elem': $elem,
                    'state': _state,
                    'uninstalled': false,
                    'undo-uninstall-message': null});

        $switch.data('elem', $elem);
        $switch.switchify();
        if ($switch.hasClass('insensitive'))
            return;

        $switch.bind('changed', function(e, newValue) {
            var oldState = $elem.data('state');
            if (newValue) {
                if (oldState == ExtensionState.UNINSTALLED) {
                    // If the extension is uninstalled and we
                    // flick the switch on, install.
                    dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());
                } else if (oldState == ExtensionState.DISABLED ||
                           oldState == ExtensionState.INITIALIZED) {
                    dbusProxy.EnableExtension(uuid);
                }
            } else {
                if (oldState == ExtensionState.ENABLED)
                    dbusProxy.DisableExtension(uuid);
            }
        });

        $elem.bind('state-changed', function(e, newState) {
            $elem.data('state', newState);
            $switch.switchify('insensitive', false);
            $switch.tipsy({ gravity: 'e', fade: true });
            if (newState == ExtensionState.DISABLED ||
                newState == ExtensionState.INITIALIZED ||
                newState == ExtensionState.UNINSTALLED) {
                $switch.switchify('activate', false);
            } else if (newState == ExtensionState.ENABLED) {
                $switch.switchify('activate', true);
            } else if (newState == ExtensionState.ERROR) {
                $switch.switchify('insensitive', true);
                $switch.attr('title', "This extension had an error.");
            } else if (newState == ExtensionState.OUT_OF_DATE) {
                $switch.switchify('insensitive', true);
                messages.addError("This extension is not compatible with your version of GNOME.");
            }

            if ($elem.data('uninstalled') && (newState == ExtensionState.ENABLED ||
                                              newState == ExtensionState.ERROR ||
                                              newState == ExtensionState.OUT_OF_DATE)) {
                $elem.fadeIn({ queue: false }).slideDown();
                $elem.data('uninstalled', false);
                $elem.data('undo-uninstall-message').slideUp();
            }

        });
        $elem.trigger('state-changed', _state);
        elems[uuid] = $elem;
    }

    $.fn.addLocalExtensions = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            if (extensions && Object.keys(extensions).length) {
                var extensionValues = [];
                for (var uuid in extensions) {
                    extensionValues.push(extensions[uuid]);
                }

                extensionValues.sort(function(a, b) {
                    return a.name.localeCompare(b.name);
                });

                extensionValues.forEach(function(extension) {
                    var uuid = extension.uuid;

                    function reinstall() {
                        dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());

                        // If the user clicks "Install" we need to show that we
                        // installed it by reattaching the element, but we can't do
                        // that here -- the user might click "Cancel".
                        $elem.data('uninstalled', true);
                    }

                    function uninstall() {
                        dbusProxy.UninstallExtension(uuid).done(function(result) {
                            if (result) {
                                $elem.fadeOut({ queue: false }).slideUp({ queue: false });

                                // Construct a dummy
 node as we need something
                                // to stuff everything else in...
                                var messageHTML = $("
You uninstalled
").
                                    append($('').text(extension.name)).
                                    append(". ").
                                    append($('', {'href': '#'}).text("Undo?")).html();

                                var $message = messages.addInfo(messageHTML);
                                $message.find('a').click(reinstall);
                                $elem.data('undo-uninstall-message', $message);
                            }
                        });
                    }

                    var $elem = $('
', {'class': 'extension'}).
                        append($('
', {'class': 'switch'})).
                        append($('', {'class': 'icon'})).
                        append($('
', {'class': 'extension-name'}).text(extension.name)).
                        append($('', {'class': 'author'})).
                        append($('
', {'class': 'description'}).text(extension.description));

                    $.ajax({
                        url: "/ajax/detail/",
                        dataType: "json",
                        data: { uuid: uuid },
                        type: "GET",
                    }).done(function(result) {
                        $elem.
                            find('span.author').text(" by ").append($('', {'href': "/accounts/profile/" + result.creator})).end().
                            find('img.icon').detach().end().
                            find('h3').html($('', {'href': result.link}).append($('', {'class': 'icon', 'src': result.icon})).append(extension.name)).end().
                            append($('<button>', {'class': 'uninstall', 'title': "Uninstall"}).text("Uninstall").bind('click', uninstall)).
                            data('pk', result.pk);
                    });

                    // The DOM element's CSS styles won't be fully
                    // computed, so the switch will be incorrectly
                    // positioned -- wait a bit before adding them.
                    setTimeout(function() {
                        addExtensionSwitch(uuid, extension, $elem);
                    }, 0);

                    $container.append($elem);
                });
            } else {
                $container.append("You don't have any extensions installed.");
            }
        });
    };

    $.fn.fillInErrors = function (uuid) {
        var $form = $(this);
        var $textarea = $form.find('textarea');
        dbusProxy.GetErrors(uuid).done(function(errors) {
            var errorString;

            if (errors && errors.length) {
                errorString = errors.join('\n\n================\n\n');
            } else {
                errorString = "GNOME Shell Extensions did not detect any errors with this extension.";
            }

            var template = ("What's wrong?\n\n\n" +
                            "What have I tried?\n\n\n" +
                            "Automatically detected errors:\n\n" + errorString);

            $textarea.text(template);
        });
    };

    $.fn.addExtensionsSwitches = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            $container.each(function () {
                var uuid = $(this).data('uuid');
                addExtensionSwitch(uuid, extensions[uuid], $(this));
            });
        });
    };

});
<|endoftext|>


<commit_before>import { keys } from 'd3-collection';
import { brushSelection } from 'd3-brush';

const brushExtents = (state, config, pc) => extents => {
  const { brushes } = state;

  if (typeof extents === 'undefined') {
    return keys(config.dimensions).reduce((acc, cur) => {
      const brush = brushes[cur];
      //todo: brush check
      if (brush !== undefined && brushSelection(brushNodes[cur]) !== null) {
        acc[d] = brush.extent();
      }

      return acc;
    }, {});
  } else {
    //first get all the brush selections
    const brushSelections = pc
      .g()
      .selectAll('.brush')
      .reduce(function(acc, cur) {
        acc[cur] = select(this);
        return acc;
      });

    // loop over each dimension and update appropriately (if it was passed in through extents)
    keys(config.dimensions).forEach(function(d) {
      if (extents[d] === undefined) {
        return;
      }

      const brush = brushes[d];
      if (brush !== undefined) {
        //update the extent
        brush.extent(extents[d]);

        //redraw the brush
        brushSelections[d]
          .transition()
          .duration(0)
          .call(brush);

        //fire some events
        brush.event(brushSelections[d]);
      }
    });

    //redraw the chart
    pc.renderBrushed();

    return pc;
  }
};

export default brushExtents;
<commit_msg>d3 selections are not extensions of array<commit_after>import { keys } from 'd3-collection';
import { select } from 'd3-selection';
import { brushSelection } from 'd3-brush';

const brushExtents = (state, config, pc) => extents => {
  const { brushes } = state;

  if (typeof extents === 'undefined') {
    return keys(config.dimensions).reduce((acc, cur) => {
      const brush = brushes[cur];
      //todo: brush check
      if (brush !== undefined && brushSelection(brushNodes[cur]) !== null) {
        acc[d] = brush.extent();
      }

      return acc;
    }, {});
  } else {
    //first get all the brush selections
    const brushSelections = {};
    pc.g().selectAll('.brush').each(function (d) {
        brushSelections[d] = select(this);
    });

    // loop over each dimension and update appropriately (if it was passed in through extents)
    keys(config.dimensions).forEach(function(d) {
      if (extents[d] === undefined) {
        return;
      }

      const brush = brushes[d];
      if (brush !== undefined) {
        //update the extent
        brush.extent(extents[d]);

        //redraw the brush
        brushSelections[d]
          .transition()
          .duration(0)
          .call(brush);

        //fire some events
        brush.event(brushSelections[d]);
      }
    });

    //redraw the chart
    pc.renderBrushed();

    return pc;
  }
};

export default brushExtents;
<|endoftext|>


<commit_before>//Tutorial baseado em http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4

//Pacotes usados
var express = require("express"); //importa express
var app = express(); //defina app com express
var bodyParser = require("body-parser");
var url = require('url');
var fs = require('fs');
var http = require('http');

var port = process.env.PORT || 8080; //configura porta

//Permite usar o bodyParser
// para pegar o POST
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

/*
SLAVE
*/

var dir= './downloads/',
    working = false;
var arr;
var file;

var call = function (response) {

    console.log('Downloading...');

    response.on('data', function (data) {
        file.write(data);
    })
        .on('end', function () {
            file.end();

            working = false;

            console.log('Ok...Got this ! ');

            if (arr) {
                arr.shift();

                if (arr[0]) {

                    while( arr[0] ==="" )
                        arr.shift();

                    console.log('proximo!')

                    file = fs.createWriteStream( dir+arr[0].substr(arr[0].lastIndexOf('/') + 1, arr[0].length));

                    get(arr[0]);
                }
            }
        });

}

var get = function (url) {

    var name = url.substr(url.lastIndexOf('/') + 1, url.length);

    fs.exists(name, function (err, existe) {

        working = true;

        if (err )
            working=true;

        file = fs.createWriteStream( dir+url.substr(url.lastIndexOf('/') + 1, url.length));

        http.get(url, call);

    });
};

/*
SLAVE
*/

//////////////////////////////////////////
// ROTAS DA API
//////////////////////////////////////////
var rota = express.Router(); // pega instância

// middleware para usada para todas as rotas
rota.use(function (req, rsp, nxt) {
    var fail = true;
    var add = req.url.indexOf('add') < 0,
        download = req.url.indexOf('download') < 0;

    if ( add )
        return rsp.json('Nope!');

        console.log('add');

        if (!arr)
            arr = []

        url = req.url.substr(5, req.url.length);

        arr = arr.concat(url.split('%E2%98%BA'));

        if (!working)
            get(arr[0]);

        rsp.json('Ok!');

});

//prefixa as rotas para /api
app.use('/', rota);

////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////

//inicia servidor
app.listen(port);
console.log("Ouvindo porta:[ " + port + " ] ♪");<commit_msg>inclusão de serviso de requisição HTTPS<commit_after>//Tutorial baseado em http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4

//Pacotes usados
var express = require("express"); //importa express
var app = express(); //defina app com express
var bodyParser = require("body-parser");
var url = require('url');
var fs = require('fs');
var http = require('http');
var https = require('https');

var port = process.env.PORT || 666; //configura porta

//Permite usar o bodyParser
// para pegar o POST
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

/*
SLAVE
*/

var dir= '../../../downloads/FromBot/',
    working = false;
var arr;
var file;
dir='./Download/';

var call = function (response) {

    console.log('Downloading...' );

    response.on('data', function (data) {
        file.write(data);
    })
        .on('end', function () {
            file.end();

            working = false;

            console.log('Ok...Got this ! '+ Date.now());

            if (arr) {
                arr.shift();

                if (arr[0]) {

                    while( arr[0] ==="" )
                        arr.shift();

                    console.log('proximo! '+ Date.now())

                    file = fs.createWriteStream( dir+arr[0].substr(arr[0].lastIndexOf('/') + 1, arr[0].length));

                    get(arr[0]);
//                    console.log("ok2");
                }
  //              console.log("ok1");
            }
    //        console.log("ok0");
        });
	//console.log("ok");
}

var get = function (url) {

    name = url.substr(url.lastIndexOf('/') + 1, url.length);

    fs.exists(name, function (err, existe) {

        working = true;
		console.log(1,err,'\n',existe);

        if ( err )
            working=false;

        //else
            file = fs.createWriteStream( dir+url.substr(url.lastIndexOf('/') + 1, url.length));

	if( url.match("https") )
		https.get(url, call);
	else
        	http.get(url, call);
        //console.log("ok ",dir+url.substr(url.lastIndexOf('/') + 1, url.length));
    });
};

/*
SLAVE
*/

//////////////////////////////////////////
// ROTAS DA API
//////////////////////////////////////////
var rota = express.Router(); // pega instância

// middleware para usada para todas as rotas
rota.use(function (req, rsp, nxt) {
    var fail = true;
    var add = req.url.indexOf('add') < 0;

    if ( req.url.length - req.url.indexOf('add') <5 )
        return rsp.json('Nope!' + Date.now() );

    console.log('add');

    if (!arr)
        arr = []

    url = req.url.substr(5, req.url.length);

    arr = arr.concat(url.split('!!!'));

    if (!working)
        get(arr[0]);

    rsp.json('Ok! on '+ Date.now() );
    console.log('ok');

});

//prefixa as rotas para /api
app.use('/', rota);

////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////

//inicia servidor
app.listen(port);
console.log("Ouvindo porta:[ " + port + " ] ♪");<|endoftext|>


<commit_before>import fs from "fs";
import through from "through2";
import objectAssign from "object-assign";
import autoprefixer from "autoprefixer";
import CleanCSS from "clean-css";
import cssfmt from "cssfmt";
import postcss from "postcss";
import reporter from "postcss-reporter";
import stylelint from "stylelint";
import StyleStats from "stylestats";
import defaultConfig from "./default-config";
import log from "./helper/log";

let currentConfig;

/**
 * Operate on written data, then read the result of each file
 * @param {Object} config - Kotori config object (see: ./default-config.js)
 * @returns {Stream} Transform stream
 */
export default function(config) {
  currentConfig = objectAssign(defaultConfig, config);

  if (currentConfig.env !== void 0) {
    currentConfig.environment = currentConfig.env;
  }

  return through.obj(transform);
}

/**
 * Operate on written data, then read the result of each file
 * @param {Buffer} file - chunk
 * @param {string} encode - file encode
 * @param {Function} callback - callback function
 * @private
 */
function transform(file, encode, callback) {
  if (file.isNull()) {
    callback(null, file);
    return;
  }

  if (file.isStream()) {
    callback(Error("Streaming not supported"));
    return;
  }

  const postcssPlugins = activatePostCSSPlugins(currentConfig);
  const processor = postcss(postcssPlugins)
    .process(file.contents.toString(), {
      map : file.sourceMap ? {annotation: false} : false,
      from: file.path,
      to  : file.path
    });

  processor
    .then((res) => {
      if (/product(?:ion)?/.test(currentConfig.environment)) {
        const cleanCSS = new CleanCSS();
        const minified = cleanCSS.minify(res.css);

        file.contents = new Buffer(minified.styles);
      }

      if (currentConfig.stats) {
        let stats = new StyleStats(file.path);

        stats.parse((err, result) => {
          log("log", JSON.stringify(result, null, 2));
        });
      }

      setImmediate(callback, null, file);
    })
    .catch((err) => {
      setImmediate(callback, err);
    });
}

/**
 * Activating PostCSS plugins
 * @param {Object} config - Kotori config object (see: ./default-config.js)
 * @returns {Function[]} PostCSS plugins list
 * @private
 */
function activatePostCSSPlugins(config) {
  const plugins = [];

  if (config.lintRules && config.lintRules.rules) {
    plugins.push(stylelint(config.lintRules));
  }

  if (config.browsers && config.browsers !== "") {
    plugins.push(autoprefixer(config.browsers));
  }

  plugins.push(cssfmt);
  plugins.push(reporter);

  return plugins;
}
<commit_msg>Simplify comment<commit_after>import fs from "fs";
import through from "through2";
import objectAssign from "object-assign";
import autoprefixer from "autoprefixer";
import CleanCSS from "clean-css";
import cssfmt from "cssfmt";
import postcss from "postcss";
import reporter from "postcss-reporter";
import stylelint from "stylelint";
import StyleStats from "stylestats";
import defaultConfig from "./default-config";
import log from "./helper/log";

let currentConfig;

/**
 * Kotori build based on config
 * @param {Object} config - Kotori config object (see: ./default-config.js)
 * @returns {Stream} Transform stream
 */
export default function(config) {
  currentConfig = objectAssign(defaultConfig, config);

  if (currentConfig.env !== void 0) {
    currentConfig.environment = currentConfig.env;
  }

  return through.obj(transform);
}

/**
 * Operate on written data, then read the result of each file
 * @param {Buffer} file - chunk
 * @param {string} encode - file encode
 * @param {Function} callback - callback function
 * @private
 */
function transform(file, encode, callback) {
  if (file.isNull()) {
    callback(null, file);
    return;
  }

  if (file.isStream()) {
    callback(Error("Streaming not supported"));
    return;
  }

  const postcssPlugins = activatePostCSSPlugins(currentConfig);
  const processor = postcss(postcssPlugins)
    .process(file.contents.toString(), {
      map : file.sourceMap ? {annotation: false} : false,
      from: file.path,
      to  : file.path
    });

  processor
    .then((res) => {
      if (/product(?:ion)?/.test(currentConfig.environment)) {
        const cleanCSS = new CleanCSS();
        const minified = cleanCSS.minify(res.css);

        file.contents = new Buffer(minified.styles);
      }

      if (currentConfig.stats) {
        let stats = new StyleStats(file.path);

        stats.parse((err, result) => {
          log("log", JSON.stringify(result, null, 2));
        });
      }

      setImmediate(callback, null, file);
    })
    .catch((err) => {
      setImmediate(callback, err);
    });
}

/**
 * Activating PostCSS plugins
 * @param {Object} config - Kotori config object (see: ./default-config.js)
 * @returns {Function[]} PostCSS plugins list
 * @private
 */
function activatePostCSSPlugins(config) {
  const plugins = [];

  if (config.lintRules && config.lintRules.rules) {
    plugins.push(stylelint(config.lintRules));
  }

  if (config.browsers && config.browsers !== "") {
    plugins.push(autoprefixer(config.browsers));
  }

  plugins.push(cssfmt);
  plugins.push(reporter);

  return plugins;
}
<|endoftext|>