<commit_before>import AdyenStrategy from './strategy/adyen';
import BraintreeStrategy from './strategy/braintree';
import CybersourceStrategy from './strategy/cybersource';
import errors from '../../errors';
import find from 'component-find';
import Promise from 'promise';
import RiskConcern from '../risk-concern';
import SagePayStrategy from './strategy/sage-pay';
import StripeStrategy from './strategy/stripe';
import TestStrategy from './strategy/test';
import WirecardStrategy from './strategy/wirecard';
import WorldpayStrategy from './strategy/worldpay';
import OrbitalStrategy from './strategy/orbital';

const debug = require('debug')('recurly:risk:three-d-secure');

export function factory (options) {
  return new ThreeDSecure({ risk: this, ...options });
}

/**
 * 3D Secure 2.0
 *
 * Usage
 *
 * ```
 * const risk = recurly.Risk();
 * const threeDSecure = risk.ThreeDSecure({ actionTokenId: 'my-action-token-id' });
 *
 * threeDSecure.on('token', token => token);
 * threeDSecure.on('error', err => err);
 *
 * threeDSecure.attach(document.querySelector('#my-checkout-3ds-container'));
 * ```
 *
 * @param {Risk} risk
 * @param {String} [actionTokenId] when given, the concern will parse any auth actions
 *                                 necessary to fulfull the action
 */
export class ThreeDSecure extends RiskConcern {
  concernName = 'three-d-secure';

  static STRATEGIES = [
    AdyenStrategy,
    BraintreeStrategy,
    CybersourceStrategy,
    SagePayStrategy,
    StripeStrategy,
    TestStrategy,
    WirecardStrategy,
    WorldpayStrategy,
    OrbitalStrategy,
  ];

  /**
   * Returns a strateggy for a given gateway type
   *
   * @param  {String} type
   * @return {ThreeDSecureStrategy}
   */
  static getStrategyForGatewayType (type) {
    return find(ThreeDSecure.STRATEGIES, s => s.strategyName === type);
  }

  /**
   * Performs preflight procedures per strategy
   *
   * @typedef  {Object} Preflights
   * @property {Object} gateway
   * @property {String} gateway.type  e.g. 'worldpay'
   * @property {Object} params        params required by the strategy
   *
   * @param {Recurly}    options.recurly
   * @param {String}     options.bin         credit card BIN
   * @param {Preflights} options.preflights
   * @return {Promise}
   */
  static preflight ({ recurly, number, month, year, preflights }) {
    const finished_preflights = [];
    return preflights.reduce((preflight, result) => {
      return preflight.then(() => {
        const { type } = result.gateway;
        const { gateway_code } = result.params;
        const strategy = ThreeDSecure.getStrategyForGatewayType(type);
        return strategy.preflight({ recurly, number, month, year, ...result.params })
          .then(results =>{
            finished_preflights.push({ processor: type, gateway_code,  results });
            return finished_preflights;
          });
      });
    }, Promise.resolve());
  }

  constructor ({ risk, actionTokenId }) {
    super({ risk });

    this.actionTokenId = actionTokenId;

    if (!actionTokenId) {
      throw errors('invalid-option', { name: 'actionTokenId', expect: 'a three_d_secure_action_token_id' });
    }

    this.recurly.request.get({ route: `/tokens/${actionTokenId}` })
      .catch(err => this.error(err))
      .then(token => {
        assertIsActionToken(token);
        this.strategy = this.getStrategyForActionToken(token);
        this.strategy.on('done', (...args) => this.onStrategyDone(...args));
        this.markReady();
      })
      .catch(err => this.error(err));

    this.report('create', { actionTokenId });
    this.whenReady(() => this.report('ready', { strategy: this.strategy.strategyName }));
  }

  /**
   * Instructs the strategy to attach, awaiting readiness of the strategy
   *
   * @param {HTMLElement} container
   */
  attach (container) {
    this.whenReady(() => {
      this.strategy.attach(container);
      this.report('attach');
    });
  }

  remove () {
    this.whenReady(() => {
      this.strategy.remove();
      this.report('remove');
    });
  }

  /**
   * Determines which strategy to employ based on an ThreeDSecureActionToken
   *
   * @private
   * @param {Object} actionToken
   */
  getStrategyForActionToken (actionToken) {
    const strategy = ThreeDSecure.getStrategyForGatewayType(actionToken.gateway.type);
    return new strategy({ threeDSecure: this, actionToken });
  }

  /**
   * Creates a ThreeDSecureActionResultToken from action results
   *
   * @private
   * @param {Object} results
   * @param {Function} done callback
   * @return {Promise} to create the token
   */
  createResultToken (results) {
    const data = {
      type: 'three_d_secure_action_result',
      three_d_secure_action_token_id: this.actionTokenId,
      results
    };
    debug('submitting results for tokenization', data);
    return this.recurly.request.post({ route: '/tokens', data });
  }

  // Listeners

  /**
   * Called when a strategy has produced results
   *
   * @param {Object} results
   */
  onStrategyDone (results) {
    this.createResultToken(results)
      .catch(cause => this.error('3ds-result-tokenization-error', { cause }))
      .then(token => {
        debug('Result token', token);
        this.emit('token', token);
        this.report('done', { actionResultTokenId: token.id });
      })
      .done();
  }
}

function assertIsActionToken (token) {
  if (token && token.type === 'three_d_secure_action') return;
  throw errors('invalid-option', { name: 'actionTokenId', expect: 'a three_d_secure_action_token_id' });
}
<commit_msg>fix return value from promise for empty preflights<commit_after>import AdyenStrategy from './strategy/adyen';
import BraintreeStrategy from './strategy/braintree';
import CybersourceStrategy from './strategy/cybersource';
import errors from '../../errors';
import find from 'component-find';
import Promise from 'promise';
import RiskConcern from '../risk-concern';
import SagePayStrategy from './strategy/sage-pay';
import StripeStrategy from './strategy/stripe';
import TestStrategy from './strategy/test';
import WirecardStrategy from './strategy/wirecard';
import WorldpayStrategy from './strategy/worldpay';
import OrbitalStrategy from './strategy/orbital';

const debug = require('debug')('recurly:risk:three-d-secure');

export function factory (options) {
  return new ThreeDSecure({ risk: this, ...options });
}

/**
 * 3D Secure 2.0
 *
 * Usage
 *
 * ```
 * const risk = recurly.Risk();
 * const threeDSecure = risk.ThreeDSecure({ actionTokenId: 'my-action-token-id' });
 *
 * threeDSecure.on('token', token => token);
 * threeDSecure.on('error', err => err);
 *
 * threeDSecure.attach(document.querySelector('#my-checkout-3ds-container'));
 * ```
 *
 * @param {Risk} risk
 * @param {String} [actionTokenId] when given, the concern will parse any auth actions
 *                                 necessary to fulfull the action
 */
export class ThreeDSecure extends RiskConcern {
  concernName = 'three-d-secure';

  static STRATEGIES = [
    AdyenStrategy,
    BraintreeStrategy,
    CybersourceStrategy,
    SagePayStrategy,
    StripeStrategy,
    TestStrategy,
    WirecardStrategy,
    WorldpayStrategy,
    OrbitalStrategy,
  ];

  /**
   * Returns a strateggy for a given gateway type
   *
   * @param  {String} type
   * @return {ThreeDSecureStrategy}
   */
  static getStrategyForGatewayType (type) {
    return find(ThreeDSecure.STRATEGIES, s => s.strategyName === type);
  }

  /**
   * Performs preflight procedures per strategy
   *
   * @typedef  {Object} Preflights
   * @property {Object} gateway
   * @property {String} gateway.type  e.g. 'worldpay'
   * @property {Object} params        params required by the strategy
   *
   * @param {Recurly}    options.recurly
   * @param {String}     options.bin         credit card BIN
   * @param {Preflights} options.preflights
   * @return {Promise}
   */
  static preflight ({ recurly, number, month, year, preflights }) {
    return preflights.reduce((preflight, result) => {
      return preflight.then((finishedPreflights) => {
        const { type } = result.gateway;
        const { gateway_code } = result.params;
        const strategy = ThreeDSecure.getStrategyForGatewayType(type);
        return strategy.preflight({ recurly, number, month, year, ...result.params })
          .then(results => {
            return finishedPreflights.concat([{ processor: type, gateway_code, results }]);
          });
      });
    }, Promise.resolve([]));
  }

  constructor ({ risk, actionTokenId }) {
    super({ risk });

    this.actionTokenId = actionTokenId;

    if (!actionTokenId) {
      throw errors('invalid-option', { name: 'actionTokenId', expect: 'a three_d_secure_action_token_id' });
    }

    this.recurly.request.get({ route: `/tokens/${actionTokenId}` })
      .catch(err => this.error(err))
      .then(token => {
        assertIsActionToken(token);
        this.strategy = this.getStrategyForActionToken(token);
        this.strategy.on('done', (...args) => this.onStrategyDone(...args));
        this.markReady();
      })
      .catch(err => this.error(err));

    this.report('create', { actionTokenId });
    this.whenReady(() => this.report('ready', { strategy: this.strategy.strategyName }));
  }

  /**
   * Instructs the strategy to attach, awaiting readiness of the strategy
   *
   * @param {HTMLElement} container
   */
  attach (container) {
    this.whenReady(() => {
      this.strategy.attach(container);
      this.report('attach');
    });
  }

  remove () {
    this.whenReady(() => {
      this.strategy.remove();
      this.report('remove');
    });
  }

  /**
   * Determines which strategy to employ based on an ThreeDSecureActionToken
   *
   * @private
   * @param {Object} actionToken
   */
  getStrategyForActionToken (actionToken) {
    const strategy = ThreeDSecure.getStrategyForGatewayType(actionToken.gateway.type);
    return new strategy({ threeDSecure: this, actionToken });
  }

  /**
   * Creates a ThreeDSecureActionResultToken from action results
   *
   * @private
   * @param {Object} results
   * @param {Function} done callback
   * @return {Promise} to create the token
   */
  createResultToken (results) {
    const data = {
      type: 'three_d_secure_action_result',
      three_d_secure_action_token_id: this.actionTokenId,
      results
    };
    debug('submitting results for tokenization', data);
    return this.recurly.request.post({ route: '/tokens', data });
  }

  // Listeners

  /**
   * Called when a strategy has produced results
   *
   * @param {Object} results
   */
  onStrategyDone (results) {
    this.createResultToken(results)
      .catch(cause => this.error('3ds-result-tokenization-error', { cause }))
      .then(token => {
        debug('Result token', token);
        this.emit('token', token);
        this.report('done', { actionResultTokenId: token.id });
      })
      .done();
  }
}

function assertIsActionToken (token) {
  if (token && token.type === 'three_d_secure_action') return;
  throw errors('invalid-option', { name: 'actionTokenId', expect: 'a three_d_secure_action_token_id' });
}
<|endoftext|>


<commit_before>"use strict";

const React = require("react");
const PropTypes = require("prop-types");
const AnimatedLogo = require("@sandhose/prettier-animated-logo");
const { MarkdownBlock, Container } = require("../../core/CompLibrary.js");

const siteConfig = require(process.cwd() + "/siteConfig.js");

const ButtonGroup = (props) => (

{props.children}

);

ButtonGroup.propTypes = {
  children: PropTypes.node,
};

class Button extends React.Component {
  render() {
    return (

          {this.props.children}

    );
  }
}

Button.defaultProps = {
  target: "_self",
};

Button.propTypes = {
  href: PropTypes.string,
  target: PropTypes.string,
  children: PropTypes.any,
};

function Tidelift() {
  return (

      PRETTIER FOR ENTERPRISE

  );
}

const HomeSplash = (props) => {
  return (

      <Tidelift />

            <AnimatedLogo version="wide" />

                  <Button href="/playground/">Try It Online</Button>
                  <Button href={"/docs/" + props.language + "/install.html"}>
                    Install Prettier
                  </Button>

  );
};

HomeSplash.propTypes = {
  language: PropTypes.string,
};

const TldrSection = ({ language }) => (

    <Container>

What is Prettier?

An opinionated code formatter

Supports many languages

Integrates with most editors

Has few options

Why?

You press save and code is formatted

No need to discuss style in code review

Saves you time and energy

              And more

    </Container>

);

TldrSection.propTypes = {
  language: PropTypes.string,
};

const Language = ({ name, nameLink, showName, image, variants }) => (

      {showName && (

          {nameLink ? {name} : name}

      )}
      {variants.map((variant) => (

          <MarkdownBlock>{variant}</MarkdownBlock>

      ))}

);

Language.propTypes = {
  name: PropTypes.string,
  nameLink: PropTypes.string,
  showName: PropTypes.bool,
  image: PropTypes.string,
  variants: PropTypes.array,
};

const LanguagesSection = () => {
  const languageChunks = siteConfig.supportedLanguages.reduce(
    (acc, language) => {
      const last = acc[acc.length - 1];
      if (
        last &&
        last.length < 2 &&
        last.reduce((sum, lang) => sum + lang.variants.length, 0) +
          language.variants.length <
          9
      ) {
        last.push(language);
      } else {
        acc.push([language]);
      }
      return acc;
    },
    []
  );

  return (

      <Container>

Works with the Tools You Use

          {languageChunks.map((languageChunk, index) => (

              {languageChunk.map((language) => (
                <Language key={language.name} {...language} />
              ))}

          ))}

      </Container>

  );
};

const Editor = ({ content = "", image, name }) => (

{name}

      <MarkdownBlock>{content.replace(/\n/g, "  \n")}</MarkdownBlock>

);

Editor.propTypes = {
  content: PropTypes.string,
  image: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
};

const EditorSupportSection = () => (

    <Container>

Editor Support

        {siteConfig.editors.map((editor) => (
          <Editor key={editor.name} {...editor} />
        ))}

    </Container>

      Got more?
      <a
        href={`${siteConfig.githubUrl}/edit/master/website/data/editors.yml`}
        className="button"
      >
        Send a PR

);

const UsersSection = ({ language }) => {
  const showcase = siteConfig.users
    .filter((user) => {
      return user.pinned;
    })
    .map((user, i) => {
      return (

      );
    });

  return (

      <Container>

Used By People You Rely On

          {showcase}

            See All Others

          <a
            className="button"
            href={`${siteConfig.githubUrl}/edit/master/website/data/users.yml`}
          >
            Add Your Project

Established in the Ecosystem

                More than{" "}
                1.8 million{" "}
                dependent repositories on GitHub

              <Button href="https://github.com/prettier/prettier/network/dependents">
                Check Them Out
              </Button>

                More than 5000{" "}
                dependent packages on npm

              <Button href="https://www.npmjs.com/browse/depended/prettier">
                See them all
              </Button>

      </Container>

  );
};

UsersSection.propTypes = {
  language: PropTypes.string,
};

class Index extends React.Component {
  render() {
    const language = this.props.language || "en";

    return (


<commit_before>"use strict";

const React = require("react");
const PropTypes = require("prop-types");

const CompLibrary = require("../../core/CompLibrary.js");
const MarkdownBlock = CompLibrary.MarkdownBlock;
const Container = CompLibrary.Container;
const AnimatedLogo = require("@sandhose/prettier-animated-logo");

const siteConfig = require(process.cwd() + "/siteConfig.js");

const ButtonGroup = props => (

{props.children}

);

ButtonGroup.propTypes = {
  children: PropTypes.node
};

class Button extends React.Component {
  render() {
    return (

          {this.props.children}

    );
  }
}

Button.defaultProps = {
  target: "_self"
};

Button.propTypes = {
  href: PropTypes.string,
  target: PropTypes.string,
  children: PropTypes.any
};

const HomeSplash = props => {
  return (

            <AnimatedLogo version="wide" />

                  <Button href="/playground/">Try It Out</Button>
                  <Button href={"/docs/" + props.language + "/install.html"}>
                    Get Started
                  </Button>
                  <Button href={"/docs/" + props.language + "/options.html"}>
                    Options
                  </Button>

  );
};

HomeSplash.propTypes = {
  language: PropTypes.string
};

const TldrSection = ({ language }) => (

    <Container>

What is Prettier?

An opinionated code formatter

Supports many languages

Integrates with most editors

Has few options

Why?

You press save and code is formatted

No need to discuss style in code review

Saves you time and energy

              And more

    </Container>

);

TldrSection.propTypes = {
  language: PropTypes.string
};

const Language = ({ name, showName, image, variants }) => (

      {showName &&
{name}
}
      {variants.map(variant => (

          <MarkdownBlock>{variant}</MarkdownBlock>

      ))}

);

Language.propTypes = {
  name: PropTypes.string,
  showName: PropTypes.bool,
  image: PropTypes.string,
  variants: PropTypes.array
};

const LanguagesSection = () => {
  const languageChunks = siteConfig.supportedLanguages.reduce(
    (acc, language) => {
      const last = acc[acc.length - 1];
      if (
        last &&
        last.length < 2 &&
        last.reduce((sum, lang) => sum + lang.variants.length, 0) +
          language.variants.length <
          5
      ) {
        last.push(language);
      } else {
        acc.push([language]);
      }
      return acc;
    },
    []
  );

  return (

      <Container>

Works with the Tools You Use

          {languageChunks.map((languageChunk, index) => (

              {languageChunk.map(language => (
                <Language key={language.name} {...language} />
              ))}

          ))}

      </Container>

  );
};

const Editor = ({ content = "", image, name }) => (

{name}

      <MarkdownBlock>{content.replace(/\n/g, "  \n")}</MarkdownBlock>

);

Editor.propTypes = {
  content: PropTypes.string,
  image: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired
};

const EditorSupportSection = () => (

    <Container>

Editor Support

        {siteConfig.editors.map(editor => (
          <Editor key={editor.name} {...editor} />
        ))}

    </Container>

      Got more?
      <a
        href={`${siteConfig.githubUrl}/edit/master/website/data/editors.yml`}
        className="button"
      >
        Send a PR

);

const bash = (...args) => `~~~bash\n${String.raw(...args)}\n~~~`;

const json = object => `~~~json\n${JSON.stringify(object, null, 2)}\n~~~`;

class GetStartedSection extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      npmClient: "yarn"
    };
  }

  render() {
    return (

        <Container>

Get Started

                  Add prettier to your project:

                    <MarkdownBlock>
                      {bash`yarn add prettier --dev --exact`}
                    </MarkdownBlock>

                    <MarkdownBlock>
                      {bash`npm install prettier --save-dev --save-exact`}
                    </MarkdownBlock>

                  Verify by running against a file:

                    <MarkdownBlock>
                      {bash`yarn prettier --write src/index.js`}
                    </MarkdownBlock>

                    <MarkdownBlock>
                      {bash`npx prettier --write src/index.js`}
                    </MarkdownBlock>

                  Run prettier when commiting files:

                    <MarkdownBlock>
                      {bash`yarn add pretty-quick husky --dev`}
                    </MarkdownBlock>

                    <MarkdownBlock>
                      {bash`npm install pretty-quick husky --save-dev`}
                    </MarkdownBlock>

                  Then edit package.json:
                  <MarkdownBlock>
                    {json({
                      scripts: {
                        precommit: "pretty-quick --staged"
                      }
                    })}
                  </MarkdownBlock>

              <ButtonGroup>

                  yarn

                  npm

              </ButtonGroup>

        </Container>

    );
  }
}

const UsersSection = ({ language }) => {
  const showcase = siteConfig.users
    .filter(user => {
      return user.pinned;
    })
    .map((user, i) => {
      return (

      );
    });

  return (

      <Container>

Used By People You Rely On

          {showcase}

            See All Others

          <a
            className="button"
            href={`${siteConfig.githubUrl}/edit/master/website/data/users.yml`}
          >
            Add Your Project

Established in the Ecosystem

More than 1250 tools and integrations on npm

              <Button href="https://www.npmjs.com/browse/depended/prettier">
                Install Them
              </Button>

More than 250,000 dependent repositories on GitHub

              <Button href="https://github.com/prettier/prettier/network/dependents">
                Check Them Out
              </Button>

      </Container>

  );
};

UsersSection.propTypes = {
  language: PropTypes.string
};

class Index extends React.Component {
  render() {
    const language = this.props.language || "en";

    return (


<commit_before>"use strict";

const React = require("react");

const CompLibrary = require("../../core/CompLibrary.js");
const MarkdownBlock = CompLibrary.MarkdownBlock;
const Container = CompLibrary.Container;
const AnimatedLogo = require("@sandhose/prettier-animated-logo");

const siteConfig = require(process.cwd() + "/siteConfig.js");

const ButtonGroup = props => (

{props.children}

);

ButtonGroup.propTypes = {
  children: React.PropTypes.node
};

class Button extends React.Component {
  render() {
    return (

          {this.props.children}

    );
  }
}

Button.defaultProps = {
  target: "_self"
};

Button.propTypes = {
  href: React.PropTypes.string,
  target: React.PropTypes.string,
  children: React.PropTypes.any
};

const HomeSplash = props => {
  return (

            <AnimatedLogo version="wide" />

                  <Button href="/playground/">Try It Out</Button>
                  <Button href={"/docs/" + props.language + "/install.html"}>
                    Get Started
                  </Button>
                  <Button href={"/docs/" + props.language + "/options.html"}>
                    Options
                  </Button>

  );
};

HomeSplash.propTypes = {
  language: React.PropTypes.string
};

const TldrSection = ({ language }) => (

    <Container>

What is Prettier?

An opinionated code formatter

Supports many languages

Integrates with most editors

Has few options

Why?

You press save and code is formatted

No need to discuss style in code review

Saves you time and energy

              And more

    </Container>

);

TldrSection.propTypes = {
  language: React.PropTypes.string
};

const Language = ({ name, showName, image, variants }) => (

      {showName &&
{name}
}
      {variants.map(variant => (

          <MarkdownBlock>{variant}</MarkdownBlock>

      ))}

);

Language.propTypes = {
  name: React.PropTypes.string,
  showName: React.PropTypes.boolean,
  image: React.PropTypes.string,
  variants: React.PropTypes.array
};

const LanguagesSection = () => {
  const languageChunks = siteConfig.supportedLanguages.reduce(
    (acc, language) => {
      const last = acc[acc.length - 1];
      if (
        last &&
        last.length < 2 &&
        last.reduce((sum, lang) => sum + lang.variants.length, 0) +
          language.variants.length <
          5
      ) {
        last.push(language);
      } else {
        acc.push([language]);
      }
      return acc;
    },
    []
  );

  return (

      <Container>

Works with the Tools You Use

          {languageChunks.map((languageChunk, index) => (

              {languageChunk.map(language => (
                <Language key={language.name} {...language} />
              ))}

          ))}

      </Container>

  );
};

const Editor = ({ content = "", image, name }) => (

{name}

      <MarkdownBlock>{content.replace(/\n/g, "  \n")}</MarkdownBlock>

);

Editor.propTypes = {
  content: React.PropTypes.string,
  image: React.PropTypes.string.isRequired,
  name: React.PropTypes.string.isRequired
};

const EditorSupportSection = () => (

    <Container>

Editor Support

        {siteConfig.editors.map(editor => (
          <Editor key={editor.name} {...editor} />
        ))}

    </Container>

      Got more?
      <a
        href={`${siteConfig.githubUrl}/edit/master/website/data/editors.yml`}
        className="button"
      >
        Send a PR

);

const bash = (...args) => `~~~bash\n${String.raw(...args)}\n~~~`;

const json = object => `~~~json\n${JSON.stringify(object, null, 2)}\n~~~`;

class GetStartedSection extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      npmClient: "yarn"
    };
  }

  render() {
    return (

        <Container>

Get Started

                  Add prettier to your project:

                    <MarkdownBlock>
                      {bash`yarn add prettier --dev --exact`}
                    </MarkdownBlock>

                    <MarkdownBlock>
                      {bash`npm install prettier --save-dev --save-exact`}
                    </MarkdownBlock>

                  Verify by running against a file:

                    <MarkdownBlock>
                      {bash`yarn prettier --write src/index.js`}
                    </MarkdownBlock>

                    <MarkdownBlock>
                      {bash`npx prettier --write src/index.js`}
                    </MarkdownBlock>

                  Run prettier when commiting files:

                    <MarkdownBlock>
                      {bash`yarn add pretty-quick husky --dev`}
                    </MarkdownBlock>

                    <MarkdownBlock>
                      {bash`npm install pretty-quick husky --save-dev`}
                    </MarkdownBlock>

                  Then edit package.json:
                  <MarkdownBlock>
                    {json({
                      scripts: {
                        precommit: "pretty-quick --staged"
                      }
                    })}
                  </MarkdownBlock>

              <ButtonGroup>

                  yarn

                  npm

              </ButtonGroup>

        </Container>

    );
  }
}

const UsersSection = ({ language }) => {
  const showcase = siteConfig.users
    .filter(user => {
      return user.pinned;
    })
    .map((user, i) => {
      return (

      );
    });

  return (

      <Container>

Used By People You Rely On

          {showcase}

            See All Others

          <a
            className="button"
            href={`${siteConfig.githubUrl}/edit/master/website/data/users.yml`}
          >
            Add Your Project

Established in the Ecosystem

More than 500 tools and integrations on npm

              <Button href="https://www.npmjs.com/browse/depended/prettier">
                Install Them
              </Button>

More than 70,000 dependent repositories on GitHub

              <Button href="https://github.com/prettier/prettier/network/dependents">
                Check Them Out
              </Button>

      </Container>

  );
};

UsersSection.propTypes = {
  language: React.PropTypes.string
};

class Index extends React.Component {
  render() {
    const language = this.props.language || "en";

    return (


<commit_before>function compareTimes(time1, time2) {
    // Determine if two objects' start and end times are equal.
    if (time1 == undefined || time2 == undefined){
        return false;
    }
    else if (time1.start_time != time2.start_time){
        return false;
    }
    else if (time1.end_time != time2.end_time){
        return false;
    }
    return true;
}

function dispalyInfo(restaurant) {
    // Display restaurant info in the info-body without bracketed locations
    $('#info-name').text(restaurant.name.replace(/ ?\[(.+)\]/, ''));
    if (restaurant.location == '') {
       $('#info-location').hide();
    }
    else {
       $('#info-location').html('Location:  ' + restaurant.location).show();
    }
    if (restaurant.open){
        $('#info-status').html('Status:  Open');
        var closing = Date.parse(restaurant.current_time.end_time);
        // Print the time the restaurant closes in local format with the seconds removed via regex
        $('#info-next').html('Open Till: ' + closing.toLocaleTimeString().replace(/(\d+:\d{2})(:\d+ )/, "$1 ")).show();
    }
    else {
        $('#info-status').html('Status:  Closed');
        $('#info-next').empty().hide()
    }
    // Display all open times for the main schedule
    var open_times = restaurant.current_schedule.open_times;
    var element = '';
    $('#info-schedule').empty();
    for(var i = 0; i < open_times.length; i++){
        if (!compareTimes(open_times[i], open_times[i-1])){
            element += '
';
        }
        if (!compareTimes(open_times[i], open_times[i-1]) &&
            // Add: "StartDay - "
            compareTimes(open_times[i], open_times[i+1])){
            element += days[open_times[i].start_day] + ' - ';
        }
        if (!compareTimes(open_times[i], open_times[i+1])){
            // Add "EndDay: OpenTime - CloseTime"
            opening = Date.parse(open_times[i].start_time);
            closing = Date.parse(open_times[i].end_time);
            element += days[open_times[i].start_day] + ': ' +
            opening.toLocaleTimeString().replace(/(\d+:\d{2})(:\d+ )/, "$1 ") + ' - ' +
            closing.toLocaleTimeString().replace(/(\d+:\d{2})(:\d+ )/, "$1 ") + '
';
            $("#info-schedule").append(element);
            element = '';
        }
    }
}

days = {
    0:"Mon",
    1:"Tues",
    2:"Wed",
    3:"Thu",
    4:"Fri",
    5:"Sat",
    6:"Sun"
}

$(document).ready(function() {
    var lastClicked = null;
    $('#info-body').click(function() {
        // Only allow closing the info pane via click on larger screens
        if ($(window).width() >= 992) {
            $(this).slideUp(350);
        }
    });
    // Displays more info about a restaurant on-click
    $(document).on('click', '.grid-box', function() {
        grid_id = $(this).attr('id');
        // Keep track of the users vertical position so it can be scolled back
        //to when the window is closed
        position = $(window).scrollTop();
        // Search though the restaurnts object to find the selected restaurant's info
        var restaurant;
        $.each(restaurants, function(idx, restaurant_i) {
            if (restaurant_i.id == grid_id) {
                restaurant = restaurant_i;
                return false;
            }
        });
        dispalyInfo(restaurant);
        // If the user clicks on the same box twice it will close the info menu
        if (lastClicked == grid_id){
            $('#info-body').slideToggle(300)
        }
        else {
            $('#info-body').slideDown(300);
            lastClicked = grid_id;
        }
        if ($(window).width() < 992) {
            // On mobile displays, hide grid to disable scrolling when info body is active
            // The delay prevents buggy scrolling on some mobile browsers
            window.setTimeout(function() { $('.main-container').toggle() }, 350);
        }
    });
    $('#info-close').click(function() {
        $('#info-body').slideUp(350);
        $('body').removeClass('clip');
        $('.main-container').show();
        $('html, body').animate({
            scrollTop: position
        }, 350);
    });
});<commit_msg>Fix bug consecutive open_times bug<commit_after>function compareTimes(time1, time2) {
    // Determine if two objects' start and end times are equal.
    if (time1 == undefined || time2 == undefined){
        return false;
    }
    else if (time1.start_time != time2.start_time){
        return false;
    }
    else if (time1.end_time != time2.end_time){
        return false;
    }
    return true;
}

function areConsecutiveDays(time1, time2) {
    if (time1 === undefined || time2 === undefined) {
        return false;
    }
    else if (time1.start_day !== time2.start_day - 1) {
        return false;
    }
    return true;

}

$.fn.displaySchedule = function(open_times){
    /* Display each open time in a concise format. The following loop will
     * determine if two consecutive days have the same open and closing times.
     * If that is the case, the time will be shown as a range.
     * (ie. Mon - Sat: 10:00 AM - 6:00 PM")
     * Otherwise, each date is displayed for its individual day.
     *  (ie. Sun: "4:00 PM - 12:00 AM
     */
    var element = '';
    for(var i = 0; i < open_times.length; i++){
        if (!compareTimes(open_times[i], open_times[i-1]) ||
                !areConsecutiveDays(open_times[i-1], open_times[i])) {
            element += '
';
        }
        if ((!compareTimes(open_times[i], open_times[i-1])
                || !areConsecutiveDays(open_times[i-1], open_times[i]))
                && compareTimes(open_times[i], open_times[i+1])
                && areConsecutiveDays(open_times[i], open_times[i+1])) {
            // Add: "StartDay - "
            element += days[open_times[i].start_day] + ' - ';
        }
        if (!compareTimes(open_times[i], open_times[i+1]) ||
                open_times[i].start_day !== (open_times[i+1].start_day - 1)) {
            // Add "EndDay: OpenTime - CloseTime"
            opening = Date.parse(open_times[i].start_time);
            closing = Date.parse(open_times[i].end_time);
            element += days[open_times[i].start_day] + ': ' +
            opening.toLocaleTimeString().replace(/(\d+:\d{2})(:\d+ )/, "$1 ") + ' - ' +
            closing.toLocaleTimeString().replace(/(\d+:\d{2})(:\d+ )/, "$1 ") + '
';
            $(this).append(element);
            element = '';
        }
    }
}

function dispalyInfo(restaurant) {
    // Display restaurant info in the info-body without bracketed locations
    $('#info-name').text(restaurant.name.replace(/ ?\[(.+)\]/, ''));
    if (restaurant.location == '') {
       $('#info-location').hide();
    }
    else {
       $('#info-location').html('Location:  ' + restaurant.location).show();
    }
    if (restaurant.open){
        $('#info-status').html('Status:  Open');
        var closing = Date.parse(restaurant.current_time.end_time);
        // Print the time the restaurant closes in local format with the seconds removed via regex
        $('#info-next').html('Open Till: ' + closing.toLocaleTimeString().replace(/(\d+:\d{2})(:\d+ )/, "$1 ")).show();
    }
    else {
        $('#info-status').html('Status:  Closed');
        $('#info-next').empty().hide()
    }
    $('#info-schedule').empty();
    // Display all open times for the main schedule
    var open_times = restaurant.current_schedule.open_times;
    $('#info-schedule').displaySchedule(open_times);
}

days = {
    0:"Mon",
    1:"Tues",
    2:"Wed",
    3:"Thu",
    4:"Fri",
    5:"Sat",
    6:"Sun"
}

$(document).ready(function() {
    var lastClicked = null;
    $('#info-body').click(function() {
        // Only allow closing the info pane via click on larger screens
        if ($(window).width() >= 992) {
            $(this).slideUp(350);
        }
    });
    // Displays more info about a restaurant on-click
    $(document).on('click', '.grid-box', function() {
        grid_id = $(this).attr('id');
        // Keep track of the users vertical position so it can be scolled back
        //to when the window is closed
        position = $(window).scrollTop();
        // Search though the restaurnts object to find the selected restaurant's info
        var restaurant;
        $.each(restaurants, function(idx, restaurant_i) {
            if (restaurant_i.id == grid_id) {
                restaurant = restaurant_i;
                return false;
            }
        });
        dispalyInfo(restaurant);
        // If the user clicks on the same box twice it will close the info menu
        if (lastClicked == grid_id){
            $('#info-body').slideToggle(300)
        }
        else {
            $('#info-body').slideDown(300);
            lastClicked = grid_id;
        }
        if ($(window).width() < 992) {
            // On mobile displays, hide grid to disable scrolling when info body is active
            // The delay prevents buggy scrolling on some mobile browsers
            window.setTimeout(function() { $('.main-container').toggle() }, 350);
        }
    });
    $('#info-close').click(function() {
        $('#info-body').slideUp(350);
        $('body').removeClass('clip');
        $('.main-container').show();
        $('html, body').animate({
            scrollTop: position
        }, 350);
    });
});<|endoftext|>


<commit_before>"use strict";

var keen = require('keen-js');
var oop = require('js/oop');
var $ = require('jquery');
var uuid = require('uuid');

var KeenTracker = oop.defclass({
    constructor: function(keenProjectId, keenWriteKey) {
        this.keenClient = new keen({
            projectId: keenProjectId,
            writeKey: keenWriteKey
        });
        this.init();
    },

    createOrUpdateKeenSession: function() {
        var date = new Date();
        var expiresInMinutes = 25;
        var expDate = date.setTime(date.getTime() + (expiresInMinutes*60*1000));
        if(!$.cookie('keenSessionId')){
            $.cookie('keenSessionId', uuid.v1(), {expires: expDate, path: '/'});
        } else {
            var sessionId = $.cookie('keenSessionId');
            $.cookie('keenSessionId', sessionId, {expires: expDate, path: '/'});
        }
    },

    getOrCreateKeenId: function() {
        if(!$.cookie('keenUserId')){
            $.cookie('keenUserId', uuid.v1(), {expires: 365, path: '/'});
        }

        return $.cookie('keenUserId');
    },

    trackPageView: function(){
        this.createOrUpdateKeenSession();
        var ctx = window.contextVars;
        var returning = $.cookie('keenUserId') ? true : false;
        var pageView = {
            'pageUrl': document.URL,
            'keenUserId': this.getOrCreateKeenId(),
            'sessionId': $.cookie('keenSessionId'),
            'pageTitle': document.title,
            'userAgent': '${keen.user_agent}',
            'referrer': {
                'url': document.referrer
            },
            'ipAddress': '${keen.ip}',
            'returning': returning,
            'keen': {
                'addons': [
                    {
                        'name': 'keen:ip_to_geo',
                        'input': {
                            'ip': 'ipAddress'
                        },
                        'output': 'ipGeoInfo'
                    },
                    {
                        'name': 'keen:ua_parser',
                        'input': {
                            'ua_string': 'userAgent'
                        },
                        'output': 'parsedUserAgent'
                    },
                    {
                        'name': 'keen:referrer_parser',
                        'input': {
                            'referrer_url': 'referrer.url',
                            'page_url': 'pageUrl'
                        },
                        'output': 'referrer.info'
                    },
                    {
                        'name' : 'keen:url_parser',
                        'input' : {
                            'url' : 'pageUrl'
                        },
                        'output' : 'parsedPageUrl'
                    }
                ]
            }
            // 'daysSinceFirstVisit':'',
            // 'daysSinceLastVisit': '',
            //'resolution': '' //temp user agent stuff
            //'generation_time': ''
            //'timeSpend': ''
        };
        if(ctx.node){
            pageView.node = {
                'id': ctx.node.id,
                'title': ctx.node.title,
                'type': ctx.node.category,
                'tags': ctx.node.tags
            };
        }
        if(ctx.currentUser){
            pageView.user = ctx.currentUser;
        }

        this.keenClient.addEvent('pageviews', pageView, function(err){
            if(err){
                throw new Error('Error sending Keen data: ' + err);
            }
        });
    },

    init: function(){
        this.trackPageView();
    }
});

module.exports = KeenTracker;
<commit_msg>JSHint fix<commit_after>'use strict';

var keen = require('keen-js');
var oop = require('js/oop');
var $ = require('jquery');
var uuid = require('uuid');

var KeenTracker = oop.defclass({
    constructor: function(keenProjectId, keenWriteKey) {
        this.keenClient = new keen({
            projectId: keenProjectId,
            writeKey: keenWriteKey
        });
        this.init();
    },

    createOrUpdateKeenSession: function() {
        var date = new Date();
        var expiresInMinutes = 25;
        var expDate = date.setTime(date.getTime() + (expiresInMinutes*60*1000));
        if(!$.cookie('keenSessionId')){
            $.cookie('keenSessionId', uuid.v1(), {expires: expDate, path: '/'});
        } else {
            var sessionId = $.cookie('keenSessionId');
            $.cookie('keenSessionId', sessionId, {expires: expDate, path: '/'});
        }
    },

    getOrCreateKeenId: function() {
        if(!$.cookie('keenUserId')){
            $.cookie('keenUserId', uuid.v1(), {expires: 365, path: '/'});
        }

        return $.cookie('keenUserId');
    },

    trackPageView: function(){
        this.createOrUpdateKeenSession();
        var ctx = window.contextVars;
        var returning = $.cookie('keenUserId') ? true : false;
        var pageView = {
            'pageUrl': document.URL,
            'keenUserId': this.getOrCreateKeenId(),
            'sessionId': $.cookie('keenSessionId'),
            'pageTitle': document.title,
            'userAgent': '${keen.user_agent}',
            'referrer': {
                'url': document.referrer
            },
            'ipAddress': '${keen.ip}',
            'returning': returning,
            'keen': {
                'addons': [
                    {
                        'name': 'keen:ip_to_geo',
                        'input': {
                            'ip': 'ipAddress'
                        },
                        'output': 'ipGeoInfo'
                    },
                    {
                        'name': 'keen:ua_parser',
                        'input': {
                            'ua_string': 'userAgent'
                        },
                        'output': 'parsedUserAgent'
                    },
                    {
                        'name': 'keen:referrer_parser',
                        'input': {
                            'referrer_url': 'referrer.url',
                            'page_url': 'pageUrl'
                        },
                        'output': 'referrer.info'
                    },
                    {
                        'name' : 'keen:url_parser',
                        'input' : {
                            'url' : 'pageUrl'
                        },
                        'output' : 'parsedPageUrl'
                    }
                ]
            }
            // 'daysSinceFirstVisit':'',
            // 'daysSinceLastVisit': '',
            //'resolution': '' //temp user agent stuff
            //'generation_time': ''
            //'timeSpend': ''
        };
        if(ctx.node){
            pageView.node = {
                'id': ctx.node.id,
                'title': ctx.node.title,
                'type': ctx.node.category,
                'tags': ctx.node.tags
            };
        }
        if(ctx.currentUser){
            pageView.user = ctx.currentUser;
        }

        this.keenClient.addEvent('pageviews', pageView, function(err){
            if(err){
                throw new Error('Error sending Keen data: ' + err);
            }
        });
    },

    init: function(){
        this.trackPageView();
    }
});

module.exports = KeenTracker;
<|endoftext|>


<commit_before>/* eslint-disable react/no-danger */
import React, { Component } from 'react';
import { Container } from 'flux/utils';
import AppStore from '../events/AppStore';
import { focusSearchBox, errorSignIn, setToaster } from '../events/AppActions';

class SearchBox extends Component {
	static getStores() {
		return [AppStore];
	}

	static calculateState(/*prevState*/) {
		return {
			focusSearchBox: AppStore.getState()['focusSearchBox'],
			isSignIn: AppStore.getState()['isSignIn'],
			currentRoom: AppStore.getState()['currentRoom'],
		};
	}

	state = {
		searchResult: [],
		selectedIndex: -1,
	};

	componentDidMount() {
		document.addEventListener('click', this.onDocumentClick);
	}

	componentWillUnmount() {
		document.removeEventListener('click', this.onDocumentClick);
	}

	onDocumentClick = e => {
		const $target = $(e.target);
		if (!$target.closest('.search-box').length) {
			this.blurSearchBox();
		}
	};

	onFormSubmit = e => {
		if (e) {
			e.preventDefault();
		}
		const { selectedIndex, searchResult } = this.state;
		if (selectedIndex >= 0) {
			this.submitSong(searchResult[selectedIndex].originalURL);

			return;
		}

		if (this.searchInput && this.searchInput.value) {
			this.submitSong(this.searchInput.value);
		}
	};

	onSearchResultClick = e => {
		const songUrl = e.currentTarget.dataset.href;
		if (songUrl) {
			this.submitSong(songUrl);
		}
	};

	keyUpSearchSong = e => {
		const { selectedIndex, searchResult, currentRoom } = this.state;
		switch (e.keyCode) {
			case 38:
				this.setState({ selectedIndex: Math.max(selectedIndex - 1, 0) });
				break;
			case 40:
				this.setState({ selectedIndex: Math.min(selectedIndex + 1, searchResult.length - 1) });
				break;
			case 27:
				this.setState({ searchResult: [], selectedIndex: -1 });
				break;
			case 13:
				this.onFormSubmit();
				break;
			default:
				if (e.keyCode !== 13 && currentRoom) {
					Meteor.call('searchSong', this.searchInput.value, (err, result) => {
						if (err) {
							console.log(err);
						} else {
							this.setState({ searchResult: result, selectedIndex: -1 });
						}
					});
				}
				break;
		}
	};

	submitSong = songUrl => {
		const userId = Meteor.userId();
		const { currentRoom } = this.state;

		if (!userId) {
			errorSignIn();

			return;
		}

		if (!currentRoom) {
			return;
		}

		Meteor.call('getSongInfo', songUrl, userId, currentRoom._id, (error /*, result*/) => {
			if (error) {
				setToaster(true, `Cannot add the song at:\n${songUrl}\nReason: ${error.reason}`, 'error');
			} else {
				setToaster(true, `Song's added successfully`, 'success');
			}
		});

		// clear input field after inserting has done
		this.searchInput.value = '';
		this.setState({ searchResult: [], selectedIndex: -1 });
	};

	focusSearchBox = () => {
		const { currentRoom } = this.state;
		if (this.searchInput.value) {
			Meteor.call('searchSong', this.searchInput.value, currentRoom._id, (err, result) => {
				if (err) {
					console.log(err);
				} else {
					this.setState({ searchResult: result, selectedIndex: -1 });
				}
			});
		}
		focusSearchBox(true);
	};

	blurSearchBox = () => {
		this.setState({ searchResult: [], selectedIndex: -1 });
		focusSearchBox(false);
	};

	refSearchInput = ref => {
		this.searchInput = ref;
	};

	render() {
		const { selectedIndex } = this.state;

		return (

				<form
					onSubmit={this.onFormSubmit}
					className={`search-box ${this.state.focusSearchBox ? 'search-box--focus' : ''} ${
						this.state.searchResult ? 'search-box--active' : ''
					}`}
				>

							<input
								type="text"
								className="search-box__input"
								placeholder="Search old song or add new NCT, Zing, YouTube, SoundClound URL"
								onKeyUp={this.keyUpSearchSong}
								onFocus={this.focusSearchBox}
								ref={this.refSearchInput}
							/>

						<button type="submit" className="search-box__submit" />

					{this.state.searchResult && this.state.searchResult.length ? (

								{this.state.searchResult.map((song, index) => (
									<li
										key={song._id}
										className={`song-result__item ${selectedIndex === index ? 'song-result__item--selected' : null}`}
										onClick={this.onSearchResultClick}
										data-href={song.originalURL}
										dangerouslySetInnerHTML={{ __html: `${song.name} • ${song.artist} • ${song.origin}` }}
									/>
								))}

					) : null}
				</form>

		);
	}
}

export default Container.create(SearchBox);
<commit_msg>fix search empty string<commit_after>/* eslint-disable react/no-danger */
import React, { Component } from 'react';
import { Container } from 'flux/utils';
import AppStore from '../events/AppStore';
import { focusSearchBox, errorSignIn, setToaster } from '../events/AppActions';

class SearchBox extends Component {
	static getStores() {
		return [AppStore];
	}

	static calculateState(/*prevState*/) {
		return {
			focusSearchBox: AppStore.getState()['focusSearchBox'],
			isSignIn: AppStore.getState()['isSignIn'],
			currentRoom: AppStore.getState()['currentRoom'],
		};
	}

	state = {
		searchResult: [],
		selectedIndex: -1,
	};

	componentDidMount() {
		document.addEventListener('click', this.onDocumentClick);
	}

	componentWillUnmount() {
		document.removeEventListener('click', this.onDocumentClick);
	}

	onDocumentClick = e => {
		const $target = $(e.target);
		if (!$target.closest('.search-box').length) {
			this.blurSearchBox();
		}
	};

	onFormSubmit = e => {
		if (e) {
			e.preventDefault();
		}
		const { selectedIndex, searchResult } = this.state;
		if (selectedIndex >= 0) {
			this.submitSong(searchResult[selectedIndex].originalURL);

			return;
		}

		if (this.searchInput && this.searchInput.value) {
			this.submitSong(this.searchInput.value);
		}
	};

	onSearchResultClick = e => {
		const songUrl = e.currentTarget.dataset.href;
		if (songUrl) {
			this.submitSong(songUrl);
		}
	};

	keyUpSearchSong = e => {
		const { selectedIndex, searchResult, currentRoom } = this.state;
		switch (e.keyCode) {
			case 38:
				this.setState({ selectedIndex: Math.max(selectedIndex - 1, 0) });
				break;
			case 40:
				this.setState({ selectedIndex: Math.min(selectedIndex + 1, searchResult.length - 1) });
				break;
			case 27:
				this.setState({ searchResult: [], selectedIndex: -1 });
				break;
			case 13:
				this.onFormSubmit();
				break;
			default:
				if (e.keyCode !== 13 && currentRoom) {
					if (!this.searchInput.value) {
						this.setState({ searchResult: [], selectedIndex: -1 });
					} else {
						Meteor.call('searchSong', this.searchInput.value, (err, result) => {
							if (err) {
								console.log(err);
							} else {
								this.setState({ searchResult: result, selectedIndex: -1 });
							}
						});
					}
				}
				break;
		}
	};

	submitSong = songUrl => {
		const userId = Meteor.userId();
		const { currentRoom } = this.state;

		if (!userId) {
			errorSignIn();

			return;
		}

		if (!currentRoom) {
			return;
		}

		Meteor.call('getSongInfo', songUrl, userId, currentRoom._id, (error /*, result*/) => {
			if (error) {
				setToaster(true, `Cannot add the song at:\n${songUrl}\nReason: ${error.reason}`, 'error');
			} else {
				setToaster(true, `Song's added successfully`, 'success');
			}
		});

		// clear input field after inserting has done
		this.searchInput.value = '';
		this.setState({ searchResult: [], selectedIndex: -1 });
	};

	focusSearchBox = () => {
		const { currentRoom } = this.state;
		if (this.searchInput.value) {
			Meteor.call('searchSong', this.searchInput.value, currentRoom._id, (err, result) => {
				if (err) {
					console.log(err);
				} else {
					this.setState({ searchResult: result, selectedIndex: -1 });
				}
			});
		}
		focusSearchBox(true);
	};

	blurSearchBox = () => {
		this.setState({ searchResult: [], selectedIndex: -1 });
		focusSearchBox(false);
	};

	refSearchInput = ref => {
		this.searchInput = ref;
	};

	render() {
		const { selectedIndex } = this.state;

		return (

				<form
					onSubmit={this.onFormSubmit}
					className={`search-box ${this.state.focusSearchBox ? 'search-box--focus' : ''} ${
						this.state.searchResult ? 'search-box--active' : ''
					}`}
				>

							<input
								type="text"
								className="search-box__input"
								placeholder="Search old song or add new NCT, Zing, YouTube, SoundClound URL"
								onKeyUp={this.keyUpSearchSong}
								onFocus={this.focusSearchBox}
								ref={this.refSearchInput}
							/>

						<button type="submit" className="search-box__submit" />

					{this.state.searchResult && this.state.searchResult.length ? (

								{this.state.searchResult.map((song, index) => (
									<li
										key={song._id}
										className={`song-result__item ${selectedIndex === index ? 'song-result__item--selected' : null}`}
										onClick={this.onSearchResultClick}
										data-href={song.originalURL}
										dangerouslySetInnerHTML={{ __html: `${song.name} • ${song.artist} • ${song.origin}` }}
									/>
								))}

					) : null}
				</form>

		);
	}
}

export default Container.create(SearchBox);
<|endoftext|>


<commit_before>/**
 * The Analysis view.
 *
 * @return Analysis view (extends Widget.View)
 */
define([
  'underscore',
  'handlebars',
  'views/Widget',
  'presenters/AnalysisResultsPresenter',
  'text!templates/analysisResults.handlebars'
], function(_, Handlebars, Widget, Presenter, tpl) {

  'use strict';

  var AnalysisResultsView = Widget.extend({

    className: 'widget widget-analysis-results',

    template: Handlebars.compile(tpl),

    options: {
      hidden: false,
      boxHidden: true,
      boxClosed: false
    },

    events: function(){
      return _.extend({}, AnalysisResultsView.__super__.events, {
        'click .delete-analysis': '_deleteAnalysis'
      });
    },

    initialize: function() {
      this.presenter = new Presenter(this);
      AnalysisResultsView.__super__.initialize.apply(this);
    },

    _cacheSelector: function() {
      AnalysisResultsView.__super__._cacheSelector.apply(this);
    },

    renderAnalysis: function(results, layer) {
      var p = {};

      p[layer.slug] = true;
      p.totalAlerts = results.value || 0;
      p.totalArea = (results.params.geojson) ? this._calcAreaPolygon(results.params.geojson) : 0;
      p.timescale = results.meta.timescale;
      p.downloadUrls = results.download_urls;
      p.layer = layer;
      // p.dateRange = '{0} to {1}'.format(layer.mindate.format('MMM-YYYY'),
      //   layer.maxdate.format('MMM-YYYY'));
      this._update(this.template(p));
      this.model.set('boxHidden', false);
    },

    /**
     * Render failure analysis request message.
     */
    renderFailure: function() {
      var p = {};
      p.failure = true;
      this._update(this.template(p));
      this.model.set('boxHidden', false);
    },

    _deleteAnalysis: function() {
      this.presenter.deleteAnalysis();
    },

    _calcAreaPolygon: function(polygon) {
      // https://github.com/maxogden/geojson-js-utils
      var area = 0;
      var points = polygon.coordinates;

      var j = points.length - 1;
      var p1, p2;

      for (var i = 0; i < points.length; j = i++) {
        p1 = {
          x: points[i][1],
          y: points[i][0]
        };
        p2 = {
          x: points[j][1],
          y: points[j][0]
        };
        area += p1.x * p2.y;
        area -= p1.y * p2.x;
      }

      area /= 2;
      area = Math.abs(area);

      return (Math.ceil((area*1000000) * 10) / 10).toLocaleString();
    }
  });

  return AnalysisResultsView;

});
<commit_msg>calc area polygon with the new API<commit_after>/**
 * The Analysis view.
 *
 * @return Analysis view (extends Widget.View)
 */
define([
  'underscore',
  'handlebars',
  'views/Widget',
  'presenters/AnalysisResultsPresenter',
  'text!templates/analysisResults.handlebars'
], function(_, Handlebars, Widget, Presenter, tpl) {

  'use strict';

  var AnalysisResultsView = Widget.extend({

    className: 'widget widget-analysis-results',

    template: Handlebars.compile(tpl),

    options: {
      hidden: false,
      boxHidden: true,
      boxClosed: false
    },

    events: function(){
      return _.extend({}, AnalysisResultsView.__super__.events, {
        'click .delete-analysis': '_deleteAnalysis'
      });
    },

    initialize: function() {
      this.presenter = new Presenter(this);
      AnalysisResultsView.__super__.initialize.apply(this);
    },

    _cacheSelector: function() {
      AnalysisResultsView.__super__._cacheSelector.apply(this);
    },

    renderAnalysis: function(results, layer) {
      var p = {};

      p[layer.slug] = true;
      p.totalAlerts = results.value || 0;
      p.totalArea = (results.params.geojson) ? this._calcAreaPolygon(results.params.geojson) : 0;
      p.timescale = results.meta.timescale;
      p.downloadUrls = results.download_urls;
      p.layer = layer;
      // p.dateRange = '{0} to {1}'.format(layer.mindate.format('MMM-YYYY'),
      //   layer.maxdate.format('MMM-YYYY'));
      this._update(this.template(p));
      this.model.set('boxHidden', false);
    },

    /**
     * Render failure analysis request message.
     */
    renderFailure: function() {
      var p = {};
      p.failure = true;
      this._update(this.template(p));
      this.model.set('boxHidden', false);
    },

    _deleteAnalysis: function() {
      this.presenter.deleteAnalysis();
    },

    _calcAreaPolygon: function(polygon) {
      // https://github.com/maxogden/geojson-js-utils
      var area = 0;
      var points = polygon.coordinates;

      var j = points.length - 1;
      var p1, p2;

      for (var i = 0; i < points.length; j = i++) {
        var pt = points[i]
        if (Array.isArray(pt[0])){
          pt[1] = pt[0][1];
          pt[0] = pt[0][0];
        }
        p1 = {
          x: pt[1],
          y: pt[0]
        };
        p2 = {
          x: points[j][1],
          y: points[j][0]
        };
        area += p1.x * p2.y;
        area -= p1.y * p2.x;
      }

      area /= 2;
      area = Math.abs(area);

      return (Math.ceil((area*1000000) * 10) / 10).toLocaleString();
    }
  });

  return AnalysisResultsView;

});
<|endoftext|>


<commit_before>'use strict';

angular.module('Expertise').
    controller('evaluationController', function ($scope, $http, ExpertiseService, $mdToast, MarkService) {
      $scope.expertise_list = ExpertiseService.query();
      $scope.evaluation = {};
      $scope.status = [ { open: true } ];
      $scope.result = function (item) {
        $http.get("/api/marks/result/" + item._id).success(function (res) {
          $scope.marks = res.marks;
          $scope.usersMap = res.users;
          var scale = $scope.expertise.setting.scale == 'percentages'? '%': '';
          $scope.resultMarks = $scope.expertise.criterions.map(function (value, index) {
            var index = index;
            return {
              name: value.name,
              users: $scope.marks.map(function (user) {
                return $scope.usersMap[user.account];
              }),
              alternatives: $scope.expertise.alternatives.map(function (alternative, i) {
                var sum = 0;
                return {
                  name: alternative.name,
                  users: $scope.marks.map(function (marks) {
                    var mark = marks.criterions[index].alternatives[i].mark;
                    sum += mark;
                    return { mark: mark + scale }
                  }),
                  sum: (sum/$scope.marks.length) + scale
                }
              })
            }
          });
        });
      };

      $scope.show = function(item) {
        $scope.expertise = item;
        MarkService.get({ id: item._id }, function (res) {
          if (!res.criterions) {
            $scope.evaluation.criterions = item.criterions.map(function (value) {
              return {
                criterionName: value.name,
                alternatives: item.alternatives.map(function (i) {
                  return { name: i.name,  mark: 0 }
                })
              }
            });
            $scope.evaluation.expertise = item._id;
          }
          else
            $scope.evaluation = res;
        });

      };

      $scope.complexToastIt = function() {
        $mdToast.show({
          controller: function($scope, $mdToast) {
            $scope.closeToast = function() {
              $mdToast.hide();
            };
          },
          templateUrl: 'views/toast-template.html',
          hideDelay: 5000,
          position: "top right"
        });
      };

      $scope.save = function (evaluation) {
        MarkService.save(evaluation, function (res) {
          $scope.complexToastIt();
        });
      }
    });
<commit_msg>fix sum<commit_after>'use strict';

angular.module('Expertise').
    controller('evaluationController', function ($scope, $http, ExpertiseService, $mdToast, MarkService) {
      $scope.expertise_list = ExpertiseService.query();
      $scope.evaluation = {};
      $scope.status = [ { open: true } ];
      $scope.result = function (item) {
        $http.get("/api/marks/result/" + item._id).success(function (res) {
          $scope.marks = res.marks;
          $scope.usersMap = res.users;
          var scale = $scope.expertise.setting.scale == 'percentages'? '%': '';
          $scope.resultMarks = $scope.expertise.criterions.map(function (value, index) {
            var index = index;
            return {
              name: value.name,
              users: $scope.marks.map(function (user) {
                return $scope.usersMap[user.account];
              }),
              alternatives: $scope.expertise.alternatives.map(function (alternative, i) {
                var sum = 0;
                return {
                  name: alternative.name,
                  users: $scope.marks.map(function (marks) {
                    var mark = marks.criterions[index].alternatives[i].mark;
                    sum += mark;
                    return { mark: mark + scale }
                  }),
                  sum: (Number(sum/$scope.marks.length).toFixed(2)) + scale
                }
              })
            }
          });
        });
      };

      $scope.show = function(item) {
        $scope.expertise = item;
        MarkService.get({ id: item._id }, function (res) {
          if (!res.criterions) {
            $scope.evaluation.criterions = item.criterions.map(function (value) {
              return {
                criterionName: value.name,
                alternatives: item.alternatives.map(function (i) {
                  return { name: i.name,  mark: 0 }
                })
              }
            });
            $scope.evaluation.expertise = item._id;
          }
          else
            $scope.evaluation = res;
        });

      };

      $scope.complexToastIt = function() {
        $mdToast.show({
          controller: function($scope, $mdToast) {
            $scope.closeToast = function() {
              $mdToast.hide();
            };
          },
          templateUrl: 'views/toast-template.html',
          hideDelay: 5000,
          position: "top right"
        });
      };

      $scope.save = function (evaluation) {
        MarkService.save(evaluation, function (res) {
          $scope.complexToastIt();
        });
      }
    });
<|endoftext|>


<commit_before>/* For datatable view */

var datatableview = {
    auto_initialize: true,
    defaults: {
        "bServerSide": true
    },

    make_xeditable: function(options) {
        var options = $.extend({}, options);
        if (!options.ajaxOptions) {
            options.ajaxOptions = {}
        }
        if (!options.ajaxOptions.headers) {
            options.ajaxOptions.headers = {}
        }
        options.ajaxOptions.headers['X-CSRFToken'] = datatableview.getCookie('csrftoken');
        options.success = function (response, newValue) {
            if (response.status == 'error') {
                return response.msg;
            }
        }
        return function(nRow, mData, iDisplayIndex) {
            $('td a[data-xeditable]', nRow).editable(options);
            return nRow;
        }
    },

    getCookie: function(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    },

    initialize: function($$, opts) {
        if (typeof window.console === "undefined" || typeof window.console.log === "undefined") {
            console = {
                log: function(){},
                info: function(){}
            };
        }
        var options_name_map = {
            'sortable': 'bSortable',
            'sorting': 'aaSorting',
            'visible': 'bVisible'
        };

        var template_clear_button = $('Clear');

        var initialized_datatables = [];
        $$.each(function(){
            var datatable = $(this);
            var column_options = [];
            var sorting_options = [];

            datatable.find('thead th').each(function(){
                var header = $(this);
                var options = {};
                for (var i = 0; i < header[0].attributes.length; i++) {
                    var attr = header[0].attributes[i];
                    if (attr.specified && /^data-/.test(attr.name)) {
                        var name = attr.name.replace(/^data-/, '');
                        var value = attr.value;

                        // Typecasting out of string
                        name = options_name_map[name];
                        if (/^b/.test(name)) {
                            value = (value === 'true');
                        }

                        if (name == 'aaSorting') {
                            // This doesn't go in the column_options
                            var sort_info = value.split(',');
                            sort_info[1] = parseInt(sort_info[1]);
                            sorting_options.push(sort_info);
                            continue;
                        }

                        options[name] = value;
                    }
                }
                column_options.push(options);
            });

            // Arrange the sorting column requests and strip the priority information
            sorting_options.sort(function(a, b){ return a[0] - b[0] });
            for (var i = 0; i < sorting_options.length; i++) {
                sorting_options[i] = sorting_options[i].slice(1);
            }

            options = $.extend({}, datatableview.defaults, opts, {
                "aaSorting": sorting_options,
                "aoColumns": column_options,
                "sAjaxSource": datatable.attr('data-source-url'),
                "fnInfoCallback": function(oSettings, iStart, iEnd, iMax, iTotal, sPre){
                    $("#" + datatable.attr('data-result-counter-id')).html(iTotal);
                    var infoString = "Showing "+iStart +" to "+ iEnd+" of "+iTotal+" entries";
                    if (iMax != iTotal) {
                        infoString +=  " (filtered from "+iMax+" total entries)";
                    }
                    return infoString;
                }
            });
            try {
                options = confirm_datatable_options(options, datatable);
            } catch (e) {

            }

            var initialized_datatable = datatable.dataTable(options);
            initialized_datatables.push(initialized_datatable[0]);

            try {
                initialized_datatable.fnSetFilteringDelay();
            } catch (e) {
                console.info("datatable plugin fnSetFilteringDelay not available");
            }

            var search_input = initialized_datatable.closest('.dataTables_wrapper').find('.dataTables_filter input');
            var clear_button = template_clear_button.clone().click(function(){
                $(this).trigger('clear.datatable', [initialized_datatable]);
                return false;
            }).bind('clear.datatable', function(){
                search_input.val('').keyup();
            });
            search_input.after(clear_button).after(' ');
        });
        return $(initialized_datatables).dataTable();
    }
}

$(function(){
    if (datatableview.auto_initialize) {
        datatableview.initialize($('.datatable'));
    }
});
<commit_msg>Emptying the div that the results string is in, will make it update every time.<commit_after>/* For datatable view */

var datatableview = {
    auto_initialize: true,
    defaults: {
        "bServerSide": true
    },

    make_xeditable: function(options) {
        var options = $.extend({}, options);
        if (!options.ajaxOptions) {
            options.ajaxOptions = {}
        }
        if (!options.ajaxOptions.headers) {
            options.ajaxOptions.headers = {}
        }
        options.ajaxOptions.headers['X-CSRFToken'] = datatableview.getCookie('csrftoken');
        options.success = function (response, newValue) {
            if (response.status == 'error') {
                return response.msg;
            }
        }
        return function(nRow, mData, iDisplayIndex) {
            $('td a[data-xeditable]', nRow).editable(options);
            return nRow;
        }
    },

    getCookie: function(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    },

    initialize: function($$, opts) {
        if (typeof window.console === "undefined" || typeof window.console.log === "undefined") {
            console = {
                log: function(){},
                info: function(){}
            };
        }
        var options_name_map = {
            'sortable': 'bSortable',
            'sorting': 'aaSorting',
            'visible': 'bVisible'
        };

        var template_clear_button = $('Clear');

        var initialized_datatables = [];
        $$.each(function(){
            var datatable = $(this);
            var column_options = [];
            var sorting_options = [];

            datatable.find('thead th').each(function(){
                var header = $(this);
                var options = {};
                for (var i = 0; i < header[0].attributes.length; i++) {
                    var attr = header[0].attributes[i];
                    if (attr.specified && /^data-/.test(attr.name)) {
                        var name = attr.name.replace(/^data-/, '');
                        var value = attr.value;

                        // Typecasting out of string
                        name = options_name_map[name];
                        if (/^b/.test(name)) {
                            value = (value === 'true');
                        }

                        if (name == 'aaSorting') {
                            // This doesn't go in the column_options
                            var sort_info = value.split(',');
                            sort_info[1] = parseInt(sort_info[1]);
                            sorting_options.push(sort_info);
                            continue;
                        }

                        options[name] = value;
                    }
                }
                column_options.push(options);
            });

            // Arrange the sorting column requests and strip the priority information
            sorting_options.sort(function(a, b){ return a[0] - b[0] });
            for (var i = 0; i < sorting_options.length; i++) {
                sorting_options[i] = sorting_options[i].slice(1);
            }

            options = $.extend({}, datatableview.defaults, opts, {
                "aaSorting": sorting_options,
                "aoColumns": column_options,
                "sAjaxSource": datatable.attr('data-source-url'),
                "fnInfoCallback": function(oSettings, iStart, iEnd, iMax, iTotal, sPre){
                    $("#" + datatable.attr('data-result-counter-id')).html(iTotal);
                    var infoString = "Showing "+iStart +" to "+ iEnd+" of "+iTotal+" entries";
                    if (iMax != iTotal) {
                        infoString +=  " (filtered from "+iMax+" total entries)";
                    }
                    /******************************************************************
                     * ##########       ###       ######         ###
                     * ##########     ###  ##     ###   ##     ###  ##
                     *    ###        ###   ###    ###   ##    ###   ###
                     *    ###        ###   ###    ###   ##    ###   ###
                     *    ###        ###   ###    ###   ##    ###   ###
                     *    ###         ######      ######       ######
                     * ===============================================================
                     * The string at the bottom of the table showing entries being
                     * looked at is always updated, but not always rendered in all
                     * browsers *cough cough* Chrome, Safari.
                     * This makes it so that results string always updates.
                     *****************************************************************/
                     var n = oSettings.aanFeatures.i;
                     for(var i=0, iLen=n.length; i<j; i++){
                        $(n[i]).empty();
                     }
                    return infoString;
                }
            });
            try {
                options = confirm_datatable_options(options, datatable);
            } catch (e) {

            }

            var initialized_datatable = datatable.dataTable(options);
            initialized_datatables.push(initialized_datatable[0]);

            try {
                initialized_datatable.fnSetFilteringDelay();
            } catch (e) {
                console.info("datatable plugin fnSetFilteringDelay not available");
            }

            var search_input = initialized_datatable.closest('.dataTables_wrapper').find('.dataTables_filter input');
            var clear_button = template_clear_button.clone().click(function(){
                $(this).trigger('clear.datatable', [initialized_datatable]);
                return false;
            }).bind('clear.datatable', function(){
                search_input.val('').keyup();
            });
            search_input.after(clear_button).after(' ');
        });
        return $(initialized_datatables).dataTable();
    }
}

$(function(){
    if (datatableview.auto_initialize) {
        datatableview.initialize($('.datatable'));
    }
});
<|endoftext|>


<commit_before>// Prefetching
user_pref("browser.urlbar.speculativeConnect.enabled", true);
user_pref("network.dns.disablePrefetch", false);
user_pref("network.prefetch-next", true);
user_pref("network.predictor.enabled", true);

// Tracking
user_pref("app.shield.optoutstudies.enabled", false);
user_pref("beacon.enabled", false);
user_pref("browser.safebrowsing.appRepURL", "");
user_pref("browser.safebrowsing.enabled", false);
user_pref("browser.safebrowsing.malware.enabled", false);
user_pref("browser.safebrowsing.phishing.enabled", false);
user_pref("browser.selfsupport.url", "");
user_pref("browser.send_pings", false);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("dom.battery.enabled", false);
user_pref("extensions.getAddons.cache.enabled", false);
user_pref("extensions.getAddons.showPane", false);
user_pref("extensions.webservice.discoverURL", "");
user_pref("geo.enabled", false);
user_pref("media.navigator.enabled", false);
user_pref("media.peerconnection.enabled", false);
user_pref("media.video_stats.enabled", false);
user_pref("toolkit.telemetry.enabled", false);

// Breaks too many things
user_pref("privacy.resistFingerprinting", false);

// Cookies
// https://feeding.cloud.geek.nz/posts/tweaking-cookies-for-privacy-in-firefox/
user_pref("privacy.firstparty.isolate", true);
user_pref("network.cookie.cookieBehavior", 0);
user_pref("network.cookie.lifetimePolicy", 3);
user_pref("network.cookie.lifetime.days", 90);
user_pref("network.cookie.thirdparty.sessionOnly", true);

// Referer Headers
// https://feeding.cloud.geek.nz/posts/tweaking-referrer-for-privacy-in-firefox/
user_pref("network.http.referer.XOriginPolicy", 1);

// Behavior
// https://www.reddit.com/r/firefox/wiki/aboutconfig
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.newtabpage.introShown", true);
user_pref("browser.newtabpage.activity-stream.telemetry", false);
user_pref("browser.newtabpage.activity-stream.showSponsored", false);
user_pref("browser.newtabpage.activity-stream.default.sites", "https://www.wikipedia.org/,https://duckduckgo.com/")
user_pref("browser.newtabpage.activity-stream.feeds.telemetry", false);
user_pref("browser.newtabpage.activity-stream.feeds.snippets", false);
user_pref("browser.onboarding.notification.finished", true);
user_pref("browser.tabs.closeWindowWithLastTab", false);
user_pref("browser.urlbar.trimURLs", false);
user_pref("general.warnOnAboutConfig", false);
user_pref("media.autoplay.enabled", false);
user_pref("signon.rememberSignons", false);
user_pref("security.webauth.u2f", true);

// Superfluous with uBlock Origin
user_pref("privacy.trackingprotection.enabled", false);

// uBlock Origin fixes the leaks
user_pref("webgl.disabled", false);

// Breaks GitHub Gist
user_pref("dom.event.clipboardevents.enabled", true);

// Breaks AMO
user_pref("dom.storage.enabled", true);

// Breaks Twitter
user_pref("dom.indexedDB.enabled", true);
<commit_msg>Fix Firefox preferences<commit_after>// Tracking
user_pref("app.shield.optoutstudies.enabled", false);
user_pref("beacon.enabled", false);
user_pref("browser.safebrowsing.enabled", false);
user_pref("browser.safebrowsing.malware.enabled", false);
user_pref("browser.safebrowsing.phishing.enabled", false);
user_pref("browser.send_pings", false);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("dom.battery.enabled", false);
user_pref("extensions.getAddons.cache.enabled", false);
user_pref("extensions.getAddons.showPane", false);
user_pref("extensions.webservice.discoverURL", "");
user_pref("geo.enabled", false);
user_pref("media.navigator.enabled", false);
user_pref("media.peerconnection.enabled", false);
user_pref("media.video_stats.enabled", false);
user_pref("toolkit.telemetry.enabled", false);

// Breaks too many things
user_pref("privacy.resistFingerprinting", false);

// Cookies
// https://feeding.cloud.geek.nz/posts/tweaking-cookies-for-privacy-in-firefox/
user_pref("privacy.firstparty.isolate", true);
user_pref("network.cookie.cookieBehavior", 0);
user_pref("network.cookie.lifetimePolicy", 3);
user_pref("network.cookie.lifetime.days", 90);
user_pref("network.cookie.thirdparty.sessionOnly", true);

// Referer Headers
// https://feeding.cloud.geek.nz/posts/tweaking-referrer-for-privacy-in-firefox/
user_pref("network.http.referer.XOriginPolicy", 1);

// Behavior
// https://www.reddit.com/r/firefox/wiki/aboutconfig
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.newtabpage.introShown", true);
user_pref("browser.newtabpage.activity-stream.telemetry", false);
user_pref("browser.newtabpage.activity-stream.showSponsored", false);
user_pref("browser.newtabpage.activity-stream.default.sites", "https://www.wikipedia.org/,https://duckduckgo.com/")
user_pref("browser.newtabpage.activity-stream.feeds.telemetry", false);
user_pref("browser.newtabpage.activity-stream.feeds.snippets", false);
user_pref("browser.onboarding.notification.finished", true);
user_pref("general.warnOnAboutConfig", false);
user_pref("signon.rememberSignons", false);

// Breaks Google Play Music
user_pref("media.autoplay.enabled", true);

// Superfluous with uBlock Origin
user_pref("privacy.trackingprotection.enabled", false);

// uBlock Origin fixes the leaks
user_pref("webgl.disabled", false);

// Breaks GitHub Gist
user_pref("dom.event.clipboardevents.enabled", true);

// Breaks AMO
user_pref("dom.storage.enabled", true);

// Breaks Twitter
user_pref("dom.indexedDB.enabled", true);
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Accounts } from 'meteor/accounts-base';
import { Roles } from 'meteor/alanning:roles';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { ROLE } from '/imports/api/role/Role';
import { SessionState, sessionKeys } from '/imports/startup/client/session-state';

Accounts.ui.config({
  passwordSignupFields: 'USERNAME_ONLY',
});

Tracker.autorun(function loggedIn() {
  if (Meteor.userId()) {
    const id = Meteor.userId();
    if (Roles.userIsInRole(id, ROLE.ADMIN)) {
      SessionState.set(sessionKeys.CURRENT_ROLE, ROLE.ADMIN);
      SessionState.set(sessionKeys.CURRENT_ADMIN_ID, id);
      FlowRouter.go('/admin');
    } else if (Roles.userIsInRole(id, ROLE.ADVISOR)) {
      SessionState.set(sessionKeys.CURRENT_ROLE, ROLE.ADVISOR);
      SessionState.set(sessionKeys.CURRENT_ADVISOR_ID, id);
      FlowRouter.go('/advisor');
    } else if (Roles.userIsInRole(id, ROLE.FACULTY)) {
      SessionState.set(sessionKeys.CURRENT_ROLE, ROLE.FACULTY);
      SessionState.set(sessionKeys.CURRENT_FACULTY_ID, id);
      FlowRouter.go('/faculty');
    } else if (Roles.userIsInRole(id, ROLE.STUDENT)) {
      SessionState.set(sessionKeys.CURRENT_ROLE, ROLE.STUDENT);
      SessionState.set(sessionKeys.CURRENT_STUDENT_ID, id);
      FlowRouter.go('/student');
    }
  } else {
    FlowRouter.go('/');
  }
});
<commit_msg>Stopping the routing when refresh.<commit_after>import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Accounts } from 'meteor/accounts-base';
import { Roles } from 'meteor/alanning:roles';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { ROLE } from '/imports/api/role/Role';
import { SessionState, sessionKeys } from '/imports/startup/client/session-state';

Accounts.ui.config({
  passwordSignupFields: 'USERNAME_ONLY',
});

Accounts.onLogin(function onLogin() {
  const currPath = FlowRouter.current().path;
  if (Meteor.userId()) {
    const id = Meteor.userId();
    if (Roles.userIsInRole(id, ROLE.ADMIN)) {
      SessionState.set(sessionKeys.CURRENT_ROLE, ROLE.ADMIN);
      SessionState.set(sessionKeys.CURRENT_ADMIN_ID, id);
      if (currPath && currPath === '/') {
        FlowRouter.go('/admin');
      }
    } else
      if (Roles.userIsInRole(id, ROLE.ADVISOR)) {
        SessionState.set(sessionKeys.CURRENT_ROLE, ROLE.ADVISOR);
        SessionState.set(sessionKeys.CURRENT_ADVISOR_ID, id);
        if (currPath && currPath === '/') {
          FlowRouter.go('/advisor');
        }
      } else
        if (Roles.userIsInRole(id, ROLE.FACULTY)) {
          SessionState.set(sessionKeys.CURRENT_ROLE, ROLE.FACULTY);
          SessionState.set(sessionKeys.CURRENT_FACULTY_ID, id);
          if (currPath && currPath === '/') {
            FlowRouter.go('/faculty');
          }
        } else
          if (Roles.userIsInRole(id, ROLE.STUDENT)) {
            SessionState.set(sessionKeys.CURRENT_ROLE, ROLE.STUDENT);
            SessionState.set(sessionKeys.CURRENT_STUDENT_ID, id);
            if (currPath && currPath === '/') {
              FlowRouter.go('/student');
            }
          }
  } else {
    FlowRouter.go('/');
  }
});
<|endoftext|>


<commit_before>"use strict";

module.exports = ($scope, $interval, BMA, UIUtils, summary, bmapi, ws) => {

  let co = require('co');
  let moment = require('moment');

  bindBlockWS();
  const UD = summary.parameters.c * summary.current.monetaryMass / summary.current.membersCount;
  $scope.current = summary.current;
  $scope.monetaryMass = parseInt(summary.current.monetaryMass / UD);
  $scope.server_started = true;
  $scope.server_stopped = false;
  $scope.phones = [];
  $scope.abc = 'abcdef';
  $scope.newIdentities = 2;

  $(".dropdown-button").dropdown({ constrainwidth: false });

  $scope.sync_state = 'home.pulling.state.unkown';
  $scope.network_percent = 0;
  $scope.peer_percent = 0;
  $scope.has_pulled = false;
  $scope.is_pulling = false;
  $scope.last_pulling = 0;
  let start_block = 0;

  $interval(() => {
    if ($scope.last_pulling) {
      $scope.sync_state = $scope.is_pulling ? 'home.pulling.state.syncing' : 'home.pulling.state.synced';
      $scope.sync_time = moment($scope.last_pulling).fromNow();
    }
  }, 1000);

  ws.on(undefined, (data) => {
    if (data.type === 'started') {
      $scope.server_started = true;
      $scope.server_stopped = false;
      bindBlockWS();
      UIUtils.toast('general.server.started');
      $scope.$apply();
    }
    if (data.type === 'stopped') {
      $scope.server_stopped = true;
      $scope.server_started = false;
      UIUtils.toast('general.server.stopped');
      $scope.$apply();
    }
    if (data.type === 'pulling') {
      $scope.is_pulling = true;
      $scope.has_pulled = true;
      const event = data.value;
      if (($scope.last_pulling && event.type === 'start') || (!$scope.last_pulling && event.type !== 'end')) {
        $scope.last_pulling = moment();
      }
      if (event.type === 'peer') {
        $scope.network_percent = parseInt((event.data.number + 1) / event.data.length * 100);
        $scope.peer_percent = 100;
        start_block = 0;
      }
      if (event.type === 'applying') {
        if (!start_block) {
          start_block = event.data.number;
        }
        const total = event.data.last - start_block;
        const doneCount = event.data.number - start_block;
        $scope.peer_percent = parseInt(doneCount / total * 100);
      }
      if (event.type === 'end') {
        $scope.is_pulling = false;
        $scope.network_percent = 0;
        $scope.peer_percent = 0;
        start_block = 0;
      }
    }
  });

  function bindBlockWS() {
    bmapi.websocket.block().on(undefined, (block) => {
      $scope.current = block;
      $scope.$apply();
    });
  }

  $scope.reconfigure_network = () => co(function *() {
    $scope.reconfiguring = true;
    let delay = Q.delay(1000);
    try {
      let netinferfaces = yield BMA.webmin.network.interfaces();
      let conf = {};
      conf.local_ipv4 = netinferfaces.auto.local.ipv4 || '';
      conf.local_ipv6 = netinferfaces.auto.local.ipv6 || '';
      conf.remote_ipv4 = netinferfaces.auto.remote.ipv4 || '';
      conf.remote_ipv6 = netinferfaces.auto.remote.ipv6 || '';
      conf.lport = netinferfaces.auto.local.port || 9330;
      conf.rport = netinferfaces.auto.remote.port || 9330;
      conf.upnp = netinferfaces.auto.remote.upnp || false;
      conf.dns = netinferfaces.auto.remote.dns || '';
      yield BMA.webmin.server.netConf({
        conf: conf
      });
      yield delay;
      $scope.should_reconfigure = false;
      UIUtils.toast('general.network.reconf_ok');
      $scope.$apply();
    } catch (e) {
      yield delay;
      $scope.reconfiguring = false;
      $scope.$apply();
    }
  });

  return co(function *() {
    yield $scope.startServer();
    try {
      yield bmapi.origin.network.peering.self();
    } catch (e) {
      console.log(e);
      $scope.should_reconfigure = true;
    }
  });
};
<commit_msg>Fixing duniter/duniter#401 Websocket for block still using BMA<commit_after>"use strict";

module.exports = ($scope, $interval, BMA, UIUtils, summary, bmapi, ws) => {

  let co = require('co');
  let moment = require('moment');

  bindBlockWS();
  const UD = summary.parameters.c * summary.current.monetaryMass / summary.current.membersCount;
  $scope.current = summary.current;
  $scope.monetaryMass = parseInt(summary.current.monetaryMass / UD);
  $scope.server_started = true;
  $scope.server_stopped = false;
  $scope.phones = [];
  $scope.abc = 'abcdef';
  $scope.newIdentities = 2;

  $(".dropdown-button").dropdown({ constrainwidth: false });

  $scope.sync_state = 'home.pulling.state.unkown';
  $scope.network_percent = 0;
  $scope.peer_percent = 0;
  $scope.has_pulled = false;
  $scope.is_pulling = false;
  $scope.last_pulling = 0;
  let start_block = 0;

  $interval(() => {
    if ($scope.last_pulling) {
      $scope.sync_state = $scope.is_pulling ? 'home.pulling.state.syncing' : 'home.pulling.state.synced';
      $scope.sync_time = moment($scope.last_pulling).fromNow();
    }
  }, 1000);

  ws.on(undefined, (data) => {
    if (data.type === 'started') {
      $scope.server_started = true;
      $scope.server_stopped = false;
      bindBlockWS();
      UIUtils.toast('general.server.started');
      $scope.$apply();
    }
    if (data.type === 'stopped') {
      $scope.server_stopped = true;
      $scope.server_started = false;
      UIUtils.toast('general.server.stopped');
      $scope.$apply();
    }
    if (data.type === 'pulling') {
      $scope.is_pulling = true;
      $scope.has_pulled = true;
      const event = data.value;
      if (($scope.last_pulling && event.type === 'start') || (!$scope.last_pulling && event.type !== 'end')) {
        $scope.last_pulling = moment();
      }
      if (event.type === 'peer') {
        $scope.network_percent = parseInt((event.data.number + 1) / event.data.length * 100);
        $scope.peer_percent = 100;
        start_block = 0;
      }
      if (event.type === 'applying') {
        if (!start_block) {
          start_block = event.data.number;
        }
        const total = event.data.last - start_block;
        const doneCount = event.data.number - start_block;
        $scope.peer_percent = parseInt(doneCount / total * 100);
      }
      if (event.type === 'end') {
        $scope.is_pulling = false;
        $scope.network_percent = 0;
        $scope.peer_percent = 0;
        start_block = 0;
      }
    }
  });

  function bindBlockWS() {
    BMA.websocket.block().on(undefined, (block) => {
      $scope.current = block;
      $scope.$apply();
    });
  }

  $scope.reconfigure_network = () => co(function *() {
    $scope.reconfiguring = true;
    let delay = Q.delay(1000);
    try {
      let netinferfaces = yield BMA.webmin.network.interfaces();
      let conf = {};
      conf.local_ipv4 = netinferfaces.auto.local.ipv4 || '';
      conf.local_ipv6 = netinferfaces.auto.local.ipv6 || '';
      conf.remote_ipv4 = netinferfaces.auto.remote.ipv4 || '';
      conf.remote_ipv6 = netinferfaces.auto.remote.ipv6 || '';
      conf.lport = netinferfaces.auto.local.port || 9330;
      conf.rport = netinferfaces.auto.remote.port || 9330;
      conf.upnp = netinferfaces.auto.remote.upnp || false;
      conf.dns = netinferfaces.auto.remote.dns || '';
      yield BMA.webmin.server.netConf({
        conf: conf
      });
      yield delay;
      $scope.should_reconfigure = false;
      UIUtils.toast('general.network.reconf_ok');
      $scope.$apply();
    } catch (e) {
      yield delay;
      $scope.reconfiguring = false;
      $scope.$apply();
    }
  });

  return co(function *() {
    yield $scope.startServer();
    try {
      yield bmapi.origin.network.peering.self();
    } catch (e) {
      console.log(e);
      $scope.should_reconfigure = true;
    }
  });
};
<|endoftext|>