<commit_before>var defaultServerOptions = {
  port: 5080,
  host: '127.0.0.1',
  path: '/',
  strict: true
};

var defaultClientOptions = {
  port: 80,
  host: '127.0.0.1',
  path: '/',
  strict: true
};

var rpcMethods = {
  'steam': [
    { method: 'getProperty' },
    { method: 'gamesPlayed' },
    { method: 'setPersonaName' },
    { method: 'setPersonaState' },
    { method: 'sendMessage' },
    { method: 'addFriend' },
    { method: 'removeFriend' },
    { method: 'joinChat' },
    { method: 'leaveChat' },
    { method: 'lockChat' },
    { method: 'unlockChat' },
    { method: 'setModerated' },
    { method: 'setUnmoderated' },
    { method: 'kick' },
    { method: 'ban' },
    { method: 'unban' },
    { method: 'trade' },
    { method: 'respondToTrade' },
    { method: 'cancelTrade' },
    { method: 'toGC' }
  ],
  'trade': [
    { method: 'getProperty' },
    { method: 'loadInventory', callback: 2 },
    { method: 'getContexts', callback: 0 },
    { method: 'open', callback: 1 },
    { method: 'addItem', callback: 1 },
    { method: 'removeItem', callback: 1 },
    { method: 'ready', callback: 0 },
    { method: 'unready', callback: 0 },
    { method: 'confirm', callback: 0 },
    { method: 'cancel', callback: 0 },
    { method: 'chatMsg', callback: 1 }
  ],
  'tradeOffers': [
    { method: 'loadMyInventory', callback: 2 },
    { method: 'loadPartnerInventory', callback: 3 },
    { method: 'makeOffer', callback: 1 },
    { method: 'getOffers', callback: 1 },
    { method: 'getOffer', callback: 1 },
    { method: 'declineOffer', callback: 1 },
    { method: 'acceptOffer', callback: 1 },
    { method: 'cancelOffer', callback: 1 }
  ]
};
var rpcEvents = {
  'steam': [
    'chatInvite',
    'user',
    // 'richPresence',
    'relationships',
    'friend',
    'group',
    'friendMsg',
    'chatMsg',
    'chatStateChange',
    'tradeOffers',
    'tradeProposed',
    'tradeResult',
    'sessionStart',
    'announcement',
    'fromGC'
  ],
  'trade': [
    'end',
    'offerChanged',
    'ready',
    'unready',
    'chatMsg'
  ],
  'tradeOffers': []
};

module.exports = {
  rpcMethods: rpcMethods,
  rpcEvents: rpcEvents,
  defaultServerOptions: defaultServerOptions,
  defaultClientOptions: defaultClientOptions
};<commit_msg>fix getProperty for tradeOffers<commit_after>var defaultServerOptions = {
  port: 5080,
  host: '127.0.0.1',
  path: '/',
  strict: true
};

var defaultClientOptions = {
  port: 80,
  host: '127.0.0.1',
  path: '/',
  strict: true
};

var rpcMethods = {
  'steam': [
    { method: 'getProperty' },
    { method: 'gamesPlayed' },
    { method: 'setPersonaName' },
    { method: 'setPersonaState' },
    { method: 'sendMessage' },
    { method: 'addFriend' },
    { method: 'removeFriend' },
    { method: 'joinChat' },
    { method: 'leaveChat' },
    { method: 'lockChat' },
    { method: 'unlockChat' },
    { method: 'setModerated' },
    { method: 'setUnmoderated' },
    { method: 'kick' },
    { method: 'ban' },
    { method: 'unban' },
    { method: 'trade' },
    { method: 'respondToTrade' },
    { method: 'cancelTrade' },
    { method: 'toGC' }
  ],
  'trade': [
    { method: 'getProperty' },
    { method: 'loadInventory', callback: 2 },
    { method: 'getContexts', callback: 0 },
    { method: 'open', callback: 1 },
    { method: 'addItem', callback: 1 },
    { method: 'removeItem', callback: 1 },
    { method: 'ready', callback: 0 },
    { method: 'unready', callback: 0 },
    { method: 'confirm', callback: 0 },
    { method: 'cancel', callback: 0 },
    { method: 'chatMsg', callback: 1 }
  ],
  'tradeOffers': [
    { method: 'getProperty' },
    { method: 'loadMyInventory', callback: 2 },
    { method: 'loadPartnerInventory', callback: 3 },
    { method: 'makeOffer', callback: 1 },
    { method: 'getOffers', callback: 1 },
    { method: 'getOffer', callback: 1 },
    { method: 'declineOffer', callback: 1 },
    { method: 'acceptOffer', callback: 1 },
    { method: 'cancelOffer', callback: 1 }
  ]
};
var rpcEvents = {
  'steam': [
    'chatInvite',
    'user',
    // 'richPresence',
    'relationships',
    'friend',
    'group',
    'friendMsg',
    'chatMsg',
    'chatStateChange',
    'tradeOffers',
    'tradeProposed',
    'tradeResult',
    'sessionStart',
    'announcement',
    'fromGC'
  ],
  'trade': [
    'end',
    'offerChanged',
    'ready',
    'unready',
    'chatMsg'
  ],
  'tradeOffers': []
};

module.exports = {
  rpcMethods: rpcMethods,
  rpcEvents: rpcEvents,
  defaultServerOptions: defaultServerOptions,
  defaultClientOptions: defaultClientOptions
};<|endoftext|>


<commit_before>// Write a function that returns the average of the numbers in an array

function average(arr) {
  let numbers = 0;

  let sum = arr.reduce((a, b) => {
    if(Number.isInteger(b)){
      numbers++;
      return a + b;
    }else{
      return a;
    }
  }, 0);

  if(!numbers){
    return undefined;
  }else{
    return sum / numbers;
  }
}

module.exports = average;
<commit_msg>Update average.js (#230)<commit_after>/**
 * Takes an array and returns the average of the numbers in it
 * @param {Array} arr
 * @return {Int or decimal} sum
 **/
function average(arr) {
  let numbers = 0;

  let sum = arr.reduce((a, b) => {
    if(Number.isInteger(b)){
      numbers++;
      return a + b;
    }else{
      return a;
    }
  }, 0);

  if(!numbers){
    return undefined;
  }else{
    return sum / numbers;
  }
}

module.exports = average;
<|endoftext|>


<commit_before>import React, { Component } from "react";
import { graphql, withApollo } from "react-apollo";
import { Container, Row, Col } from "reactstrap";
import gql from "graphql-tag";
import "./style.scss";

const MESSAGES_SUB = gql`
  subscription LRDecoding($simulatorId: ID) {
    longRangeCommunicationsUpdate(simulatorId: $simulatorId) {
      id
      simulatorId
      name
      messages(crew: false) {
        id
        sender
        sent
        deleted
        message
        datestamp
        encrypted
        approved
      }
    }
  }
`;

class LRCommCore extends Component {
  constructor(props) {
    super(props);
    this.decodeSubscription = null;
    this.state = {
      selectedMessage: null
    };
  }
  componentWillReceiveProps(nextProps) {
    if (!this.decodeSubscription && !nextProps.data.loading) {
      this.decodeSubscription = nextProps.data.subscribeToMore({
        document: MESSAGES_SUB,
        variables: {
          simulatorId: nextProps.simulator.id
        },
        updateQuery: (previousResult, { subscriptionData }) => {
          return Object.assign({}, previousResult, {
            longRangeCommunications:
              subscriptionData.data.longRangeCommunicationsUpdate
          });
        }
      });
    }
  }
  componentWillUnmount() {
    this.decodeSubscription && this.decodeSubscription();
  }
  render() {
    if (this.props.data.loading || !this.props.data.longRangeCommunications)
      return null;
    let selectedMessage = null;
    if (this.state.selectedMessage) {
      selectedMessage = this.props.data.longRangeCommunications[0].messages.find(
        m => m.id === this.state.selectedMessage
      );
    }
    return (

        {this.props.data.longRangeCommunications.length > 0 ? (
          <Container style={{ height: "calc(100% - 16px)" }}>
            <Row
              className="comm-messages"
              style={{ height: "100%", minHeight: "30vh" }}
            >
              <Col sm={3}>

                  {this.props.data.longRangeCommunications[0].messages.map(
                    m => (
                      <li
                        key={m.id}
                        className={`${
                          this.state.selectedMessage === m.id ? "active" : ""
                        } ${m.sent === true ? "text-success" : ""} ${
                          m.deleted === true ? "text-danger" : ""
                        } ${
                          m.approved === true && !m.sent && !m.deleted
                            ? "text-warning"
                            : ""
                        } `}
                        onClick={() => this.setState({ selectedMessage: m.id })}
                      >
                        {m.datestamp} - {m.sender}

                    )
                  )}

              </Col>
              <Col sm={9}>
                {selectedMessage && (

{`${selectedMessage.datestamp}${
                    selectedMessage.encrypted ? ` - Encrypted` : ""
                  }${selectedMessage.approved ? ` - Approved` : ""}
From: ${selectedMessage.sender}
${selectedMessage.message}`}

                )}
              </Col>
            </Row>
          </Container>
        ) : (
          "No Long Range Comm"
        )}

    );
  }
}

const MESSAGES_QUERY = gql`
  query LRDecoding($simulatorId: ID) {
    longRangeCommunications(simulatorId: $simulatorId) {
      id
      simulatorId
      name
      messages(crew: false) {
        id
        sender
        message
        sent
        deleted
        datestamp
        encrypted
        approved
      }
    }
  }
`;

export default graphql(MESSAGES_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: { simulatorId: ownProps.simulator.id }
  })
})(withApollo(LRCommCore));
<commit_msg>Fix scrolling on long range comm core<commit_after>import React, { Component } from "react";
import { graphql, withApollo } from "react-apollo";
import { Container, Row, Col } from "reactstrap";
import gql from "graphql-tag";
import "./style.scss";

const MESSAGES_SUB = gql`
  subscription LRDecoding($simulatorId: ID) {
    longRangeCommunicationsUpdate(simulatorId: $simulatorId) {
      id
      simulatorId
      name
      messages(crew: false) {
        id
        sender
        sent
        deleted
        message
        datestamp
        encrypted
        approved
      }
    }
  }
`;

class LRCommCore extends Component {
  constructor(props) {
    super(props);
    this.decodeSubscription = null;
    this.state = {
      selectedMessage: null
    };
  }
  componentWillReceiveProps(nextProps) {
    if (!this.decodeSubscription && !nextProps.data.loading) {
      this.decodeSubscription = nextProps.data.subscribeToMore({
        document: MESSAGES_SUB,
        variables: {
          simulatorId: nextProps.simulator.id
        },
        updateQuery: (previousResult, { subscriptionData }) => {
          return Object.assign({}, previousResult, {
            longRangeCommunications:
              subscriptionData.data.longRangeCommunicationsUpdate
          });
        }
      });
    }
  }
  componentWillUnmount() {
    this.decodeSubscription && this.decodeSubscription();
  }
  render() {
    if (this.props.data.loading || !this.props.data.longRangeCommunications)
      return null;
    let selectedMessage = null;
    if (this.state.selectedMessage) {
      selectedMessage = this.props.data.longRangeCommunications[0].messages.find(
        m => m.id === this.state.selectedMessage
      );
    }
    return (

        {this.props.data.longRangeCommunications.length > 0 ? (
          <Container style={{ height: "calc(100% - 16px)" }}>
            <Row className="comm-messages" style={{ height: "100%" }}>
              <Col sm={3}>

                  {this.props.data.longRangeCommunications[0].messages.map(
                    m => (
                      <li
                        key={m.id}
                        className={`${
                          this.state.selectedMessage === m.id ? "active" : ""
                        } ${m.sent === true ? "text-success" : ""} ${
                          m.deleted === true ? "text-danger" : ""
                        } ${
                          m.approved === true && !m.sent && !m.deleted
                            ? "text-warning"
                            : ""
                        } `}
                        onClick={() => this.setState({ selectedMessage: m.id })}
                      >
                        {m.datestamp} - {m.sender}

                    )
                  )}

              </Col>
              <Col sm={9}>
                {selectedMessage && (

{`${selectedMessage.datestamp}${
                    selectedMessage.encrypted ? ` - Encrypted` : ""
                  }${selectedMessage.approved ? ` - Approved` : ""}
From: ${selectedMessage.sender}
${selectedMessage.message}`}

                )}
              </Col>
            </Row>
          </Container>
        ) : (
          "No Long Range Comm"
        )}

    );
  }
}

const MESSAGES_QUERY = gql`
  query LRDecoding($simulatorId: ID) {
    longRangeCommunications(simulatorId: $simulatorId) {
      id
      simulatorId
      name
      messages(crew: false) {
        id
        sender
        message
        sent
        deleted
        datestamp
        encrypted
        approved
      }
    }
  }
`;

export default graphql(MESSAGES_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: { simulatorId: ownProps.simulator.id }
  })
})(withApollo(LRCommCore));
<|endoftext|>


<commit_before>import React, { Component } from "react";
import { Container, Row, Col, Card, CardBody } from "reactstrap";
import gql from "graphql-tag";
import { graphql, withApollo } from "react-apollo";
import Measure from "react-measure";
import Tour from "reactour";

import "./style.css";

function d2r(deg) {
  return deg * Math.PI / 180;
}

const trainingSteps = [
  {
    selector: ".nothing",
    content:
      "Once constructed, a probe network gives you access to a vast amount of information about what surrounds your ship. It augments the information provided by your sensor grid. Creating a probe network is done on the Probe Construction screen. Building probes with a 'Probe Network Package' prepares everything the probe needs to be added to the probe network."
  },
  {
    selector: ".network-grid",
    content:
      "This grid shows you the current status of your probe network. Each of the nodes around the edge is where a probe will be located. A circle inside of the node indicates a probe that has been launched to that location. If all of the probes in the network have been launched, you will see the datagrams sent from the probes to your ship."
  },
  {
    selector: ".processedData",
    content:
      "Your probe network will collect and summarize important information here. If you ever see new information in this box, be sure to read it to your captain."
  }
];

const datagramImage = require(`./datagram.svg`);

const PROBES_SUB = gql`
  subscription ProbesSub($simulatorId: ID!) {
    probesUpdate(simulatorId: $simulatorId) {
      id
      processedData
      probes(network: true) {
        id
        name
        launched
      }
    }
  }
`;

class ProbeNetwork extends Component {
  state = {};
  subscription = null;
  componentWillReceiveProps(nextProps) {
    if (!this.subscription && !nextProps.data.loading) {
      this.subscription = nextProps.data.subscribeToMore({
        document: PROBES_SUB,
        variables: {
          simulatorId: nextProps.simulator.id
        },
        updateQuery: (previousResult, { subscriptionData }) => {
          return Object.assign({}, previousResult, {
            probes: subscriptionData.data.probesUpdate
          });
        }
      });
    }
  }
  componentWillUnmount() {
    this.subscription && this.subscription();
  }
  render() {
    if (this.props.data.loading || !this.props.data.probes) return null;
    const probes = this.props.data.probes[0];
    const { processedData, probes: network } = probes;
    return (
      <Container className="probe-network" style={{ height: "100%" }}>
        <Row style={{ height: "100%" }}>
          <Col sm={8} style={{ height: "100%" }} className="network-grid">
            <Measure
              bounds
              onResize={contentRect => {
                this.setState({ dimensions: contentRect.bounds });
              }}
            >
              {({ measureRef }) => (

                  {this.state.dimensions && (
                    <Grid
                      dimensions={this.state.dimensions}
                      network={network}
                    />
                  )}

              )}
            </Measure>
          </Col>
          <Col sm={{ size: 3, offset: 1 }}>

Processed Data

            <Card className="processedData">
              <CardBody>

{processedData}

              </CardBody>
            </Card>
          </Col>
        </Row>
        <Tour
          steps={trainingSteps}
          isOpen={this.props.clientObj.training}
          onRequestClose={this.props.stopTraining}
        />
      </Container>
    );
  }
}

const PROBE_NETWORK_QUERY = gql`
  query Probes($simulatorId: ID!) {
    probes(simulatorId: $simulatorId) {
      id
      processedData
      probes(network: true) {
        id
        name
        launched
      }
    }
  }
`;

export default graphql(PROBE_NETWORK_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: {
      simulatorId: ownProps.simulator.id
    }
  })
})(withApollo(ProbeNetwork));

class Grid extends Component {
  constructor(props) {
    super(props);
    this.looping = true;
    this.state = {
      datagrams: Array(props.lines || 8)
        .fill(0)
        .map((_, i, array) => ({
          angle: d2r(i / array.length * 360),
          x: 0,
          y: 0
        }))
    };
  }
  componentWillUnmount() {
    this.looping = false;
    clearTimeout(this.frame);
  }
  loop = () => {
    if (!this.looping) return;
    const totalFrames = 200;
    const speedyFrames = 100;
    const datagrams = this.state.datagrams.map(({ angle, x, y }, i) => {
      const speedX =
        Math.cos(angle) / (i % 2 === 1 ? totalFrames : speedyFrames);
      const speedY =
        Math.sin(angle) / (i % 2 === 1 ? totalFrames : speedyFrames);
      let distX = x + speedX;
      let distY = y + speedY;
      if (
        Math.abs(distX) > Math.abs(Math.cos(angle)) ||
        Math.abs(distY) > Math.abs(Math.sin(angle))
      ) {
        distX = 0;
        distY = 0;
      }
      return {
        angle,
        x: distX,
        y: distY
      };
    });
    // Calculate the speed of the contact by it's angle
    this.setState({
      datagrams
    });
    this.frame = setTimeout(this.loop, 30);
  };
  componentDidMount() {
    this.looping = true;
    this.loop();
  }
  render() {
    const { dimensions, rings = 3, lines = 8, network } = this.props;
    const connected =
      network.filter((p, i, a) => a.findIndex(e => e.name === p.name) === i)
        .length >= 8;
    const { datagrams } = this.state;
    const radius = dimensions.width;
    return (
      <div className={`grid`} style={{ width: radius, height: radius }}>
        {Array(lines)
          .fill(0)
          .map((_, i, array) => (
            <div
              key={`line-${i}`}
              className="line"
              style={{
                transform: `rotate(${(i + 0.5) / array.length * 360}deg)`
              }}
            />
          ))}
        {Array(rings)
          .fill(0)
          .map((_, i, array) => (
            <div
              key={`ring-${i}`}
              className="ring"
              style={{
                width: `${(i + 1) / array.length * 100}%`,
                height: `${(i + 1) / array.length * 100}%`,
                backgroundColor: i < 2 ? "black" : "transparent"
              }}
            />
          ))}
        {Array(lines)
          .fill(0)
          .map((_, i, array) => (
            <div
              key={`box-${i}`}
              className="box"
              style={{
                transform: `translate(${Math.cos(d2r(i / array.length * 360)) *
                  radius /
                  2}px, ${Math.sin(d2r(i / array.length * 360)) *
                  radius /
                  2}px)`
              }}
            />
          ))}
        {network.map(({ name, launched }) => {
          if (launched) {
            const i = parseInt(name, 10);
            if (i) {
              return (
                <div
                  key={`probe-${i}`}
                  className="probe"
                  style={{
                    transform: `translate(${Math.cos(
                      d2r((i - 3) / lines * 360)
                    ) *
                      radius /
                      2}px, ${Math.sin(d2r((i - 3) / lines * 360)) *
                      radius /
                      2}px)`
                  }}
                />
              );
            }
          }
          return null;
        })}
        {connected &&
          datagrams.map((d, i) => (
            <img
              alt="datagram"
              key={`datagram-${i}`}
              className="datagram"
              src={datagramImage}
              style={{
                transform: `translate(
              ${d.x * radius / 2}px,
              ${d.y * radius / 2}px)`
              }}
            />
          ))}

    );
  }
}
<commit_msg>Improve sizing of probe network grid. Closes #713<commit_after>import React, { Component } from "react";
import { Container, Row, Col, Card, CardBody } from "reactstrap";
import gql from "graphql-tag";
import { graphql, withApollo } from "react-apollo";
import Measure from "react-measure";
import Tour from "reactour";

import "./style.css";

function d2r(deg) {
  return deg * Math.PI / 180;
}

const trainingSteps = [
  {
    selector: ".nothing",
    content:
      "Once constructed, a probe network gives you access to a vast amount of information about what surrounds your ship. It augments the information provided by your sensor grid. Creating a probe network is done on the Probe Construction screen. Building probes with a 'Probe Network Package' prepares everything the probe needs to be added to the probe network."
  },
  {
    selector: ".network-grid",
    content:
      "This grid shows you the current status of your probe network. Each of the nodes around the edge is where a probe will be located. A circle inside of the node indicates a probe that has been launched to that location. If all of the probes in the network have been launched, you will see the datagrams sent from the probes to your ship."
  },
  {
    selector: ".processedData",
    content:
      "Your probe network will collect and summarize important information here. If you ever see new information in this box, be sure to read it to your captain."
  }
];

const datagramImage = require(`./datagram.svg`);

const PROBES_SUB = gql`
  subscription ProbesSub($simulatorId: ID!) {
    probesUpdate(simulatorId: $simulatorId) {
      id
      processedData
      probes(network: true) {
        id
        name
        launched
      }
    }
  }
`;

class ProbeNetwork extends Component {
  state = {};
  subscription = null;
  componentWillReceiveProps(nextProps) {
    if (!this.subscription && !nextProps.data.loading) {
      this.subscription = nextProps.data.subscribeToMore({
        document: PROBES_SUB,
        variables: {
          simulatorId: nextProps.simulator.id
        },
        updateQuery: (previousResult, { subscriptionData }) => {
          return Object.assign({}, previousResult, {
            probes: subscriptionData.data.probesUpdate
          });
        }
      });
    }
  }
  componentWillUnmount() {
    this.subscription && this.subscription();
  }
  render() {
    if (this.props.data.loading || !this.props.data.probes) return null;
    const probes = this.props.data.probes[0];
    const { processedData, probes: network } = probes;
    return (
      <Container fluid className="probe-network" style={{ height: "100%" }}>
        <Row style={{ height: "100%" }}>
          <Col
            sm={{ size: 6, offset: 1 }}
            style={{ height: "100%" }}
            className="network-grid"
          >
            <Measure
              bounds
              onResize={contentRect => {
                this.setState({ dimensions: contentRect.bounds });
              }}
            >
              {({ measureRef }) => (

                  {this.state.dimensions && (
                    <Grid
                      dimensions={this.state.dimensions}
                      network={network}
                    />
                  )}

              )}
            </Measure>
          </Col>
          <Col sm={{ size: 3, offset: 2 }}>

Processed Data

            <Card className="processedData">
              <CardBody>

{processedData}

              </CardBody>
            </Card>
          </Col>
        </Row>
        <Tour
          steps={trainingSteps}
          isOpen={this.props.clientObj.training}
          onRequestClose={this.props.stopTraining}
        />
      </Container>
    );
  }
}

const PROBE_NETWORK_QUERY = gql`
  query Probes($simulatorId: ID!) {
    probes(simulatorId: $simulatorId) {
      id
      processedData
      probes(network: true) {
        id
        name
        launched
      }
    }
  }
`;

export default graphql(PROBE_NETWORK_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: {
      simulatorId: ownProps.simulator.id
    }
  })
})(withApollo(ProbeNetwork));

class Grid extends Component {
  constructor(props) {
    super(props);
    this.looping = true;
    this.state = {
      datagrams: Array(props.lines || 8)
        .fill(0)
        .map((_, i, array) => ({
          angle: d2r(i / array.length * 360),
          x: 0,
          y: 0
        }))
    };
  }
  componentWillUnmount() {
    this.looping = false;
    clearTimeout(this.frame);
  }
  loop = () => {
    if (!this.looping) return;
    const totalFrames = 200;
    const speedyFrames = 100;
    const datagrams = this.state.datagrams.map(({ angle, x, y }, i) => {
      const speedX =
        Math.cos(angle) / (i % 2 === 1 ? totalFrames : speedyFrames);
      const speedY =
        Math.sin(angle) / (i % 2 === 1 ? totalFrames : speedyFrames);
      let distX = x + speedX;
      let distY = y + speedY;
      if (
        Math.abs(distX) > Math.abs(Math.cos(angle)) ||
        Math.abs(distY) > Math.abs(Math.sin(angle))
      ) {
        distX = 0;
        distY = 0;
      }
      return {
        angle,
        x: distX,
        y: distY
      };
    });
    // Calculate the speed of the contact by it's angle
    this.setState({
      datagrams
    });
    this.frame = setTimeout(this.loop, 30);
  };
  componentDidMount() {
    this.looping = true;
    this.loop();
  }
  render() {
    const { dimensions, rings = 3, lines = 8, network } = this.props;
    const connected =
      network.filter((p, i, a) => a.findIndex(e => e.name === p.name) === i)
        .length >= 8;
    const { datagrams } = this.state;
    const radius = dimensions.width;
    return (
      <div className={`grid`} style={{ width: radius, height: radius }}>
        {Array(lines)
          .fill(0)
          .map((_, i, array) => (
            <div
              key={`line-${i}`}
              className="line"
              style={{
                transform: `rotate(${(i + 0.5) / array.length * 360}deg)`
              }}
            />
          ))}
        {Array(rings)
          .fill(0)
          .map((_, i, array) => (
            <div
              key={`ring-${i}`}
              className="ring"
              style={{
                width: `${(i + 1) / array.length * 100}%`,
                height: `${(i + 1) / array.length * 100}%`,
                backgroundColor: i < 2 ? "black" : "transparent"
              }}
            />
          ))}
        {Array(lines)
          .fill(0)
          .map((_, i, array) => (
            <div
              key={`box-${i}`}
              className="box"
              style={{
                transform: `translate(${Math.cos(d2r(i / array.length * 360)) *
                  radius /
                  2}px, ${Math.sin(d2r(i / array.length * 360)) *
                  radius /
                  2}px)`
              }}
            />
          ))}
        {network.map(({ name, launched }) => {
          if (launched) {
            const i = parseInt(name, 10);
            if (i) {
              return (
                <div
                  key={`probe-${i}`}
                  className="probe"
                  style={{
                    transform: `translate(${Math.cos(
                      d2r((i - 3) / lines * 360)
                    ) *
                      radius /
                      2}px, ${Math.sin(d2r((i - 3) / lines * 360)) *
                      radius /
                      2}px)`
                  }}
                />
              );
            }
          }
          return null;
        })}
        {connected &&
          datagrams.map((d, i) => (
            <img
              alt="datagram"
              key={`datagram-${i}`}
              className="datagram"
              src={datagramImage}
              style={{
                transform: `translate(
              ${d.x * radius / 2}px,
              ${d.y * radius / 2}px)`
              }}
            />
          ))}

    );
  }
}
<|endoftext|>


<commit_before>/*
Copyright 2017 Vector Creations Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';

import { KeyCode } from '../../../Keyboard';
import AccessibleButton from '../elements/AccessibleButton';
import sdk from '../../../index';

/**
 * Basic container for modal dialogs.
 *
 * Includes a div for the title, and a keypress handler which cancels the
 * dialog on escape.
 */
export default React.createClass({
    displayName: 'BaseDialog',

    propTypes: {
        // onFinished callback to call when Escape is pressed
        onFinished: React.PropTypes.func.isRequired,

        // callback to call when Enter is pressed
        onEnterPressed: React.PropTypes.func,

        // CSS class to apply to dialog div
        className: React.PropTypes.string,

        // Title for the dialog.
        // (could probably actually be something more complicated than a string if desired)
        title: React.PropTypes.string.isRequired,

        // children should be the content of the dialog
        children: React.PropTypes.node,
    },

    _onKeyDown: function(e) {
        if (e.keyCode === KeyCode.ESCAPE) {
            e.stopPropagation();
            e.preventDefault();
            this.props.onFinished();
        } else if (e.keyCode === KeyCode.ENTER) {
            if (this.props.onEnterPressed) {
                e.stopPropagation();
                e.preventDefault();
                this.props.onEnterPressed(e);
            }
        }
    },

    _onCancelClick: function(e) {
        this.props.onFinished();
    },

    render: function() {
        const TintableSvg = sdk.getComponent("elements.TintableSvg");

        return (

                <AccessibleButton onClick={this._onCancelClick}
                    className="mx_Dialog_cancelButton"
                >
                    <TintableSvg src="img/icons-close-button.svg" width="35" height="35" />
                </AccessibleButton>

                    { this.props.title }

                { this.props.children }

        );
    },
});
<commit_msg>Allow BaseDialog to take a class for the title
<commit_after>/*
Copyright 2017 Vector Creations Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';

import { KeyCode } from '../../../Keyboard';
import AccessibleButton from '../elements/AccessibleButton';
import sdk from '../../../index';

/**
 * Basic container for modal dialogs.
 *
 * Includes a div for the title, and a keypress handler which cancels the
 * dialog on escape.
 */
export default React.createClass({
    displayName: 'BaseDialog',

    propTypes: {
        // onFinished callback to call when Escape is pressed
        onFinished: React.PropTypes.func.isRequired,

        // callback to call when Enter is pressed
        onEnterPressed: React.PropTypes.func,

        // CSS class to apply to dialog div
        className: React.PropTypes.string,

        // Title for the dialog.
        // (could probably actually be something more complicated than a string if desired)
        title: React.PropTypes.string.isRequired,

        // children should be the content of the dialog
        children: React.PropTypes.node,
    },

    _onKeyDown: function(e) {
        if (e.keyCode === KeyCode.ESCAPE) {
            e.stopPropagation();
            e.preventDefault();
            this.props.onFinished();
        } else if (e.keyCode === KeyCode.ENTER) {
            if (this.props.onEnterPressed) {
                e.stopPropagation();
                e.preventDefault();
                this.props.onEnterPressed(e);
            }
        }
    },

    _onCancelClick: function(e) {
        this.props.onFinished();
    },

    render: function() {
        const TintableSvg = sdk.getComponent("elements.TintableSvg");

        return (

                <AccessibleButton onClick={this._onCancelClick}
                    className="mx_Dialog_cancelButton"
                >
                    <TintableSvg src="img/icons-close-button.svg" width="35" height="35" />
                </AccessibleButton>

                    { this.props.title }

                { this.props.children }

        );
    },
});
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs');
var path = require('path');
var xutil = require('./xutil');
var commons = require('./commons');
var methods = require('./methods');
var services = require('./services');

var template = xutil.readFileText('code.html');
var codetexts = (function() {
    var texts = {};
    var jsontext = xutil.readFileText('codes.json');
    xutil.eachObject(JSON.parse(jsontext), function(message, code) {
        texts[code] = xutil.renderTemplateText(template, {
            code: code,
            message: message
        });
    });
    return texts;
})();

function ishttperr(err) {
    return err && (err.statusCode && err.status) && (err.statusCode == err.status) && (err.status >= 100 && err.status < 600);
}

function textcode(code) {
    return codetexts[code] || xutil.renderTemplateText(template, {
        code: code,
        message: 'Unexpected Error'
    });
}

function options(opts) {
    if (!opts)
        opts = {};
    if (!opts.limits)
        opts.limits = {};
    if (!opts.basepath)
        opts.basepath = process.cwd();
    if (!opts.services)
        opts.services = "services";
    opts._privates = {
        default_failure: function(req, res, name, type) {
            res.status(400).send(opts.debug ? ("[" + name + ":" + type + "] " + req.path) : textcode(400));
        }
    };
    return opts;
}

function present(opts) {
    var _brcommons_ = {};
    commons.setup(_brcommons_, path.join(opts.basepath, "commons"));
    global.brcx = global.brcommons = _brcommons_;
    var _brmethods_ = {};
    methods.setup(_brmethods_, path.join(opts.basepath, "methods"));
    global.brmx = global.brmethods = _brmethods_;
}

function weblike(opts) {
    var express = require('express');
    var bodyParser = require('body-parser');
    var cookieParser = require('cookie-parser');
    var multiparty = require('connect-multiparty');
    var compression = require('compression');

    present(opts);

    var app = express();
    if (!opts.etag)
        app.disable('etag');
    app.disable('x-powered-by');
    app.enable('trust proxy');
    if (opts.compression) {
        var compressionOptions = {};
        if (opts.compression !== true)
            compressionOptions = opts.compression;
        app.use(compression(compressionOptions));
    }
    if (opts.viewer) {
        var renderType = typeof opts.viewer.render;
        if (["string", "function"].indexOf(renderType) == -1)
            throw new Error("Bad option: viewer.render");
        if (typeof opts.viewer.filepath != 'string')
            throw new Error("Bad option: viewer.filepath");
        app.set('views', opts.viewer.filepath);
        if (renderType == 'string')
            app.set('view engine', opts.viewer.render);
        else {
            app.set('view engine', 'html');
            app.engine('html', opts.viewer.render);
        }
        app.set('view cache', xutil.optBoolean(opts.viewer.cache, !opts.debug));
    }
    var bodySize = opts.limits.bodySize || (2 * 1024 * 1024);
    app.use(bodyParser.json({
        limit: bodySize
    }));
    app.use(bodyParser.urlencoded({
        extended: false,
        limit: bodySize
    }));
    app.use(multiparty({
        maxFieldsSize: bodySize,
        uploadDir: opts.limits.uploadDir,
        maxFilesSize: opts.limits.uploadSize || (50 * 1024 * 1024)
    }));
    app.use(cookieParser());
    xutil.eachArray(opts.middlewares, function(middleware) {
        app.use(middleware);
    });
    app.use(function(req, res, next) {
        res.setHeader('Server', 'nginx');
        req.param = function(name, defaultValue) {
            var params = this.params;
            if (params && null != params[name] && params.hasOwnProperty(name))
                return params[name];
            var body = this.body;
            if (body && null != body[name])
                return body[name];
            var query = this.query;
            if (query && null != query[name])
                return query[name];
            return defaultValue;
        };
        var fks = req.files ? Object.keys(req.files) : [];
        if (fks.length > 0)
            res.on('finish', function() {
                xutil.eachArray(fks, function(k) {
                    fs.unlink(req.files[k].path);
                });
            });
        next();
    });
    if (opts.rootwork) {
        app.all("/", opts.rootwork);
    }
    xutil.eachArray(xutil.parseArray(opts.services), function(dirname) {
        services.setup(app, path.join(opts.basepath, dirname), xutil.objExtend({
            visitor: opts.visitor
        }, opts._privates));
    });
    if (opts.statics || opts.static) {
        xutil.eachArray(xutil.parseArray(options.statics || opts.static), function(row) {
            if (typeof row.urlpath != 'string')
                throw new Error("Bad option: static.urlpath");
            if (typeof row.filepath != 'string')
                throw new Error("Bad option: static.filepath");
            app.use(row.urlpath, express.static(row.filepath, row.options || {}));
        });
    }
    if (opts.r404work) {
        app.use(opts.r404work);
    }
    app.use(function(req, res) {
        res.status(404).send(opts.debug ? (req.method + " " + req.path) : textcode(404));
    });
    app.use(function(err, req, res, next) {
        // Add error entry lock
        if (req.__bigrest_error_lock)
            next(err);
        else {
            req.__bigrest_error_lock = true;

            if (res.headersSent)
                next(err);
            else {
                var errors = [];
                var recatch = false;
                try {
                    var statusCode = 500;
                    if (!ishttperr(err))
                        errors.push(err);
                    else
                        statusCode = err.statusCode;
                    res.status(statusCode).send(opts.debug ? (err.stack || err.message) : textcode(statusCode));
                } catch (e) {
                    errors.push(e);
                    recatch = true;
                }
                if (opts.catcher && errors.length > 0) {
                    try {
                        opts.catcher(errors, req, res);
                    } catch (e) {
                        recatch = true;
                    }
                }
                // Use the default handler when error again
                if (recatch) {
                    next(err);
                }
            }
        }
    });
    return app;
}

exports.present = function(opts) {
    present(options(opts));
};

exports.listen = function(port, opts) {
    opts = options(opts);
    var http = require('http');
    var https = require('https');

    var server;
    var webapp = weblike(opts);
    if (!opts.https)
        server = http.createServer(webapp);
    else
        server = https.createServer(opts.https, webapp);
    var new_arguments = [port];
    for (var i = 2; i < arguments.length; ++i)
        new_arguments.push(arguments[i]);
    server.listen.apply(server, new_arguments);
};

exports.simulator = function(opts) {
    opts = xutil.objExtend({
        debug: true
    }, options(opts));

    var http = require('http');
    var qs = require('querystring');

    var webapp = weblike(opts);
    return {
        request: function(method, url, params, callback) {
            var fakereq = (function() {
                var qss = qs.stringify(params);
                var req = new http.IncomingMessage();
                req.url = url;
                req.method = method.toUpperCase();
                if (req.method == 'GET') {
                    if (req.url.indexOf('?') == -1)
                        req.url += '?';
                    else
                        req.url += '&';
                    req.url += qss;
                } else {
                    var readed = false;
                    var buffer = new Buffer(qss);
                    req.headers['content-type'] = 'application/x-www-form-urlencoded';
                    req.headers['content-length'] = buffer.length;
                    req._read = function() {
                        if (readed)
                            req.push(null);
                        else {
                            readed = true;
                            req.push(buffer);
                        }
                    };
                }
                req.ip = xutil.getFakeIp();
                req.ips = [req.ip];
                return req;
            })();
            var fakeres = (function() {
                var resend = false;
                var res = new http.ServerResponse(fakereq);
                res.send = function(data) {
                    if (resend)
                        return;
                    resend = true;
                    process.nextTick(function() {
                        callback(res.statusCode, data);
                    });
                };
                return res;
            })();
            webapp(fakereq, fakeres);
        }
    };
};
<commit_msg>Ignore error when unlink failed<commit_after>"use strict";

var fs = require('fs');
var path = require('path');
var xutil = require('./xutil');
var commons = require('./commons');
var methods = require('./methods');
var services = require('./services');

var template = xutil.readFileText('code.html');
var codetexts = (function() {
    var texts = {};
    var jsontext = xutil.readFileText('codes.json');
    xutil.eachObject(JSON.parse(jsontext), function(message, code) {
        texts[code] = xutil.renderTemplateText(template, {
            code: code,
            message: message
        });
    });
    return texts;
})();

function ishttperr(err) {
    return err && (err.statusCode && err.status) && (err.statusCode == err.status) && (err.status >= 100 && err.status < 600);
}

function textcode(code) {
    return codetexts[code] || xutil.renderTemplateText(template, {
        code: code,
        message: 'Unexpected Error'
    });
}

function options(opts) {
    if (!opts)
        opts = {};
    if (!opts.limits)
        opts.limits = {};
    if (!opts.basepath)
        opts.basepath = process.cwd();
    if (!opts.services)
        opts.services = "services";
    opts._privates = {
        default_failure: function(req, res, name, type) {
            res.status(400).send(opts.debug ? ("[" + name + ":" + type + "] " + req.path) : textcode(400));
        }
    };
    return opts;
}

function present(opts) {
    var _brcommons_ = {};
    commons.setup(_brcommons_, path.join(opts.basepath, "commons"));
    global.brcx = global.brcommons = _brcommons_;
    var _brmethods_ = {};
    methods.setup(_brmethods_, path.join(opts.basepath, "methods"));
    global.brmx = global.brmethods = _brmethods_;
}

function weblike(opts) {
    var express = require('express');
    var bodyParser = require('body-parser');
    var cookieParser = require('cookie-parser');
    var multiparty = require('connect-multiparty');
    var compression = require('compression');

    present(opts);

    var app = express();
    if (!opts.etag)
        app.disable('etag');
    app.disable('x-powered-by');
    app.enable('trust proxy');
    if (opts.compression) {
        var compressionOptions = {};
        if (opts.compression !== true)
            compressionOptions = opts.compression;
        app.use(compression(compressionOptions));
    }
    if (opts.viewer) {
        var renderType = typeof opts.viewer.render;
        if (["string", "function"].indexOf(renderType) == -1)
            throw new Error("Bad option: viewer.render");
        if (typeof opts.viewer.filepath != 'string')
            throw new Error("Bad option: viewer.filepath");
        app.set('views', opts.viewer.filepath);
        if (renderType == 'string')
            app.set('view engine', opts.viewer.render);
        else {
            app.set('view engine', 'html');
            app.engine('html', opts.viewer.render);
        }
        app.set('view cache', xutil.optBoolean(opts.viewer.cache, !opts.debug));
    }
    var bodySize = opts.limits.bodySize || (2 * 1024 * 1024);
    app.use(bodyParser.json({
        limit: bodySize
    }));
    app.use(bodyParser.urlencoded({
        extended: false,
        limit: bodySize
    }));
    app.use(multiparty({
        maxFieldsSize: bodySize,
        uploadDir: opts.limits.uploadDir,
        maxFilesSize: opts.limits.uploadSize || (50 * 1024 * 1024)
    }));
    app.use(cookieParser());
    xutil.eachArray(opts.middlewares, function(middleware) {
        app.use(middleware);
    });
    app.use(function(req, res, next) {
        res.setHeader('Server', 'nginx');
        req.param = function(name, defaultValue) {
            var params = this.params;
            if (params && null != params[name] && params.hasOwnProperty(name))
                return params[name];
            var body = this.body;
            if (body && null != body[name])
                return body[name];
            var query = this.query;
            if (query && null != query[name])
                return query[name];
            return defaultValue;
        };
        var fks = req.files ? Object.keys(req.files) : [];
        if (fks.length > 0)
            res.on('finish', function() {
                xutil.eachArray(fks, function(k) {
                    try {
                        fs.unlinkSync(req.files[k].path);
                    } catch (e) {}
                });
            });
        next();
    });
    if (opts.rootwork) {
        app.all("/", opts.rootwork);
    }
    xutil.eachArray(xutil.parseArray(opts.services), function(dirname) {
        services.setup(app, path.join(opts.basepath, dirname), xutil.objExtend({
            visitor: opts.visitor
        }, opts._privates));
    });
    if (opts.statics || opts.static) {
        xutil.eachArray(xutil.parseArray(options.statics || opts.static), function(row) {
            if (typeof row.urlpath != 'string')
                throw new Error("Bad option: static.urlpath");
            if (typeof row.filepath != 'string')
                throw new Error("Bad option: static.filepath");
            app.use(row.urlpath, express.static(row.filepath, row.options || {}));
        });
    }
    if (opts.r404work) {
        app.use(opts.r404work);
    }
    app.use(function(req, res) {
        res.status(404).send(opts.debug ? (req.method + " " + req.path) : textcode(404));
    });
    app.use(function(err, req, res, next) {
        // Add error entry lock
        if (req.__bigrest_error_lock)
            next(err);
        else {
            req.__bigrest_error_lock = true;

            if (res.headersSent)
                next(err);
            else {
                var errors = [];
                var recatch = false;
                try {
                    var statusCode = 500;
                    if (!ishttperr(err))
                        errors.push(err);
                    else
                        statusCode = err.statusCode;
                    res.status(statusCode).send(opts.debug ? (err.stack || err.message) : textcode(statusCode));
                } catch (e) {
                    errors.push(e);
                    recatch = true;
                }
                if (opts.catcher && errors.length > 0) {
                    try {
                        opts.catcher(errors, req, res);
                    } catch (e) {
                        recatch = true;
                    }
                }
                // Use the default handler when error again
                if (recatch) {
                    next(err);
                }
            }
        }
    });
    return app;
}

exports.present = function(opts) {
    present(options(opts));
};

exports.listen = function(port, opts) {
    opts = options(opts);
    var http = require('http');
    var https = require('https');

    var server;
    var webapp = weblike(opts);
    if (!opts.https)
        server = http.createServer(webapp);
    else
        server = https.createServer(opts.https, webapp);
    var new_arguments = [port];
    for (var i = 2; i < arguments.length; ++i)
        new_arguments.push(arguments[i]);
    server.listen.apply(server, new_arguments);
};

exports.simulator = function(opts) {
    opts = xutil.objExtend({
        debug: true
    }, options(opts));

    var http = require('http');
    var qs = require('querystring');

    var webapp = weblike(opts);
    return {
        request: function(method, url, params, callback) {
            var fakereq = (function() {
                var qss = qs.stringify(params);
                var req = new http.IncomingMessage();
                req.url = url;
                req.method = method.toUpperCase();
                if (req.method == 'GET') {
                    if (req.url.indexOf('?') == -1)
                        req.url += '?';
                    else
                        req.url += '&';
                    req.url += qss;
                } else {
                    var readed = false;
                    var buffer = new Buffer(qss);
                    req.headers['content-type'] = 'application/x-www-form-urlencoded';
                    req.headers['content-length'] = buffer.length;
                    req._read = function() {
                        if (readed)
                            req.push(null);
                        else {
                            readed = true;
                            req.push(buffer);
                        }
                    };
                }
                req.ip = xutil.getFakeIp();
                req.ips = [req.ip];
                return req;
            })();
            var fakeres = (function() {
                var resend = false;
                var res = new http.ServerResponse(fakereq);
                res.send = function(data) {
                    if (resend)
                        return;
                    resend = true;
                    process.nextTick(function() {
                        callback(res.statusCode, data);
                    });
                };
                return res;
            })();
            webapp(fakereq, fakeres);
        }
    };
};
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

module.exports = function findAndroidAppFolder(folder) {
  if (!fs.existsSync(path.join(folder, 'android'))) {
    return null;
  }

  if (fs.existsSync(path.join(folder, 'android', 'app'))) {
    return path.join('android', 'app');
  }

  return 'android';
};
<commit_msg>Added coments to findAndroidAppFolder<commit_after>const fs = require('fs');
const path = require('path');

/**
 * @param  {String} folder Folder to seek in
 * @return {String}
 */
module.exports = function findAndroidAppFolder(folder) {
  if (!fs.existsSync(path.join(folder, 'android'))) {
    return null;
  }

  if (fs.existsSync(path.join(folder, 'android', 'app'))) {
    return path.join('android', 'app');
  }

  return 'android';
};
<|endoftext|>


<commit_before>var sys = require('sys')
var exec = require('child_process').exec;
var config= require("./../../config.json");
var lang;

const Discord = require('discord.js');
const client = new Discord.Client();
var responses={};
var tokens = {};

if(config.rolesID.verify == null){
  console.log("need to know role to set at verify member");
  process.exit();
}

client.on('ready', () => {
    console.log('I am ready!');
});

client.on('message', message => {
  var fragments= message.content.split(" ");
  if (fragments[0] === "!UB") {
    if(responses[fragments[1]]){
      responses[fragments[1]](message, fragments);
    }else{
      message.reply(lang.unknowCommand);
    }
  }else if(fragments[0] === "!me"){
    fragments[0] =;
    beautifyMe(message, fragments);
  }
});

exports.run=function (){
  client.login(config.token);
  lang= require(__dirname + "/lang/"+(config.lang || "fr-fr")+".json");
}

function beautifyMe(message, fragments){
  fragments[0] = message.author.username;
  message.reply( '__**'+fragments.join(' ')+'**__');
}

responses["token"]= function(message, fragments){
   if(tokens[message.author.username]!= null && (tokens[message.author.username].key=fragments[2]) ){
     userGuild=message.guild.member(message.author);
     userGuild.setNickname(tokens[message.author.username].nick);
     userGuild.addRole(config.rolesID.verify)//message.guild.roles.get("name",config.roles.verify).id);
     delete tokens[name];
     message.reply(lang.validation);
   }else{
     message.reply(lang.invalidToken);
   }
}

responses["identifie-moi-comme"]= function(message, fragments){
  token =generateToken();
  nick=message.content.substring(24)
  if(fragments[2]){
    child = exec("phantomjs --web-security=false ./lib/bot/phantomCtrl.js '"+nick+"' "+token, function (error, stdout, stderr) {
      // use this to say at user if there an error in send mp
      /*console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
        console.log('exec error: ' + error);
      }*/
    });
    tokens[message.author.username]= {
      key: token,
      nick: nick
    };
    setTimeout(function(name){
      if(tokens[name])
        delete tokens[name]
      }, 1800,message.author.username);
    message.reply(lang.tokenSend);
  }else {
    message.reply(lang.pseudoNeeded);
  }
}

function generateToken() {
    return Math.random().toString(36).substr(2);
};
<commit_msg>correct reply to edit for me<commit_after>var sys = require('sys')
var exec = require('child_process').exec;
var config= require("./../../config.json");
var lang;

const Discord = require('discord.js');
const client = new Discord.Client();
var responses={};
var tokens = {};

if(config.rolesID.verify == null){
  console.log("need to know role to set at verify member");
  process.exit();
}

client.on('ready', () => {
    console.log('I am ready!');
});

client.on('message', message => {
  var fragments= message.content.split(" ");
  if (fragments[0] === "!UB") {
    if(responses[fragments[1]]){
      responses[fragments[1]](message, fragments);
    }else{
      message.reply(lang.unknowCommand);
    }
  }else if(fragments[0] === "!me"){
    beautifyMe(message, fragments);
  }
});

exports.run=function (){
  client.login(config.token);
  lang= require(__dirname + "/lang/"+(config.lang || "fr-fr")+".json");
}

function beautifyMe(message, fragments){
  fragments[0] = message.author.username;
  message.edit( '__**'+fragments.join(' ')+'**__');
}

responses["token"]= function(message, fragments){
   if(tokens[message.author.username]!= null && (tokens[message.author.username].key=fragments[2]) ){
     userGuild=message.guild.member(message.author);
     userGuild.setNickname(tokens[message.author.username].nick);
     userGuild.addRole(config.rolesID.verify)//message.guild.roles.get("name",config.roles.verify).id);
     delete tokens[name];
     message.reply(lang.validation);
   }else{
     message.reply(lang.invalidToken);
   }
}

responses["identifie-moi-comme"]= function(message, fragments){
  token =generateToken();
  nick=message.content.substring(24)
  if(fragments[2]){
    child = exec("phantomjs --web-security=false ./lib/bot/phantomCtrl.js '"+nick+"' "+token, function (error, stdout, stderr) {
      // use this to say at user if there an error in send mp
      /*console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
        console.log('exec error: ' + error);
      }*/
    });
    tokens[message.author.username]= {
      key: token,
      nick: nick
    };
    setTimeout(function(name){
      if(tokens[name])
        delete tokens[name]
      }, 1800,message.author.username);
    message.reply(lang.tokenSend);
  }else {
    message.reply(lang.pseudoNeeded);
  }
}

function generateToken() {
    return Math.random().toString(36).substr(2);
};
<|endoftext|>


<commit_before>import $ from 'dom7';
import { window, document } from 'ssr-window';
import Utils from '../../utils/utils';
import Device from '../../utils/device';

const Statusbar = {
  hide() {
    if (Device.cordova && window.StatusBar) {
      window.StatusBar.hide();
    }
  },
  show() {
    if (Device.cordova && window.StatusBar) {
      window.StatusBar.show();
    }
  },
  onClick() {
    const app = this;
    let pageContent;
    if ($('.popup.modal-in').length > 0) {
      // Check for opened popup
      pageContent = $('.popup.modal-in').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    } else if ($('.panel.panel-opened').length > 0) {
      // Check for opened panel
      pageContent = $('.panel.panel-opened').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    } else if ($('.views > .view.tab-active').length > 0) {
      // View in tab bar app layout
      pageContent = $('.views > .view.tab-active').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    } else if ($('.views').length > 0) {
      pageContent = $('.views').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    } else {
      pageContent = app.root.children('.view').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    }

    if (pageContent && pageContent.length > 0) {
      // Check for tab
      if (pageContent.hasClass('tab')) {
        pageContent = pageContent.parent('.tabs').children('.page-content.tab-active');
      }
      if (pageContent.length > 0) pageContent.scrollTop(0, 300);
    }
  },
  setTextColor(color) {
    if (Device.cordova && window.StatusBar) {
      if (color === 'white') {
        window.StatusBar.styleLightContent();
      } else {
        window.StatusBar.styleDefault();
      }
    }
  },
  setBackgroundColor(color) {
    if (Device.cordova && window.StatusBar) {
      window.StatusBar.backgroundColorByHexString(color);
    }
  },
  isVisible() {
    if (Device.cordova && window.StatusBar) {
      return window.StatusBar.isVisible;
    }
    return false;
  },
  overlaysWebView(overlays = true) {
    if (Device.cordova && window.StatusBar) {
      window.StatusBar.overlaysWebView(overlays);
    }
  },
  init() {
    const app = this;
    const params = app.params.statusbar;
    if (!params.enabled) return;

    if (Device.cordova && window.StatusBar) {
      if (params.scrollTopOnClick) {
        $(window).on('statusTap', Statusbar.onClick.bind(app));
      }
      if (Device.ios) {
        if (params.iosOverlaysWebView) {
          window.StatusBar.overlaysWebView(true);
        } else {
          window.StatusBar.overlaysWebView(false);
        }
        if (params.iosTextColor === 'white') {
          window.StatusBar.styleLightContent();
        } else {
          window.StatusBar.styleDefault();
        }
      }
      if (Device.android) {
        if (params.androidOverlaysWebView) {
          window.StatusBar.overlaysWebView(true);
        } else {
          window.StatusBar.overlaysWebView(false);
        }
        if (params.androidTextColor === 'white') {
          window.StatusBar.styleLightContent();
        } else {
          window.StatusBar.styleDefault();
        }
      }
    }
    if (params.iosBackgroundColor && Device.ios) {
      Statusbar.setBackgroundColor(params.iosBackgroundColor);
    }
    if (params.androidBackgroundColor && Device.android) {
      Statusbar.setBackgroundColor(params.androidBackgroundColor);
    }
  },
};

export default {
  name: 'statusbar',
  params: {
    statusbar: {
      enabled: true,

      scrollTopOnClick: true,

      iosOverlaysWebView: true,
      iosTextColor: 'black',
      iosBackgroundColor: null,

      androidOverlaysWebView: false,
      androidTextColor: 'black',
      androidBackgroundColor: null,
    },
  },
  create() {
    const app = this;
    Utils.extend(app, {
      statusbar: {
        hide: Statusbar.hide,
        show: Statusbar.show,
        overlaysWebView: Statusbar.overlaysWebView,
        setTextColor: Statusbar.setTextColor,
        setBackgroundColor: Statusbar.setBackgroundColor,
        isVisible: Statusbar.isVisible,
        init: Statusbar.init.bind(app),
      },
    });
  },
  on: {
    init() {
      const app = this;
      Statusbar.init.call(app);
    },
  },
};
<commit_msg>Update statusbar.js<commit_after>import $ from 'dom7';
import { window } from 'ssr-window';
import Utils from '../../utils/utils';
import Device from '../../utils/device';

const Statusbar = {
  hide() {
    if (Device.cordova && window.StatusBar) {
      window.StatusBar.hide();
    }
  },
  show() {
    if (Device.cordova && window.StatusBar) {
      window.StatusBar.show();
    }
  },
  onClick() {
    const app = this;
    let pageContent;
    if ($('.popup.modal-in').length > 0) {
      // Check for opened popup
      pageContent = $('.popup.modal-in').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    } else if ($('.panel.panel-opened').length > 0) {
      // Check for opened panel
      pageContent = $('.panel.panel-opened').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    } else if ($('.views > .view.tab-active').length > 0) {
      // View in tab bar app layout
      pageContent = $('.views > .view.tab-active').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    } else if ($('.views').length > 0) {
      pageContent = $('.views').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    } else {
      pageContent = app.root.children('.view').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
    }

    if (pageContent && pageContent.length > 0) {
      // Check for tab
      if (pageContent.hasClass('tab')) {
        pageContent = pageContent.parent('.tabs').children('.page-content.tab-active');
      }
      if (pageContent.length > 0) pageContent.scrollTop(0, 300);
    }
  },
  setTextColor(color) {
    if (Device.cordova && window.StatusBar) {
      if (color === 'white') {
        window.StatusBar.styleLightContent();
      } else {
        window.StatusBar.styleDefault();
      }
    }
  },
  setBackgroundColor(color) {
    if (Device.cordova && window.StatusBar) {
      window.StatusBar.backgroundColorByHexString(color);
    }
  },
  isVisible() {
    if (Device.cordova && window.StatusBar) {
      return window.StatusBar.isVisible;
    }
    return false;
  },
  overlaysWebView(overlays = true) {
    if (Device.cordova && window.StatusBar) {
      window.StatusBar.overlaysWebView(overlays);
    }
  },
  init() {
    const app = this;
    const params = app.params.statusbar;
    if (!params.enabled) return;

    if (Device.cordova && window.StatusBar) {
      if (params.scrollTopOnClick) {
        $(window).on('statusTap', Statusbar.onClick.bind(app));
      }
      if (Device.ios) {
        if (params.iosOverlaysWebView) {
          window.StatusBar.overlaysWebView(true);
        } else {
          window.StatusBar.overlaysWebView(false);
        }
        if (params.iosTextColor === 'white') {
          window.StatusBar.styleLightContent();
        } else {
          window.StatusBar.styleDefault();
        }
      }
      if (Device.android) {
        if (params.androidOverlaysWebView) {
          window.StatusBar.overlaysWebView(true);
        } else {
          window.StatusBar.overlaysWebView(false);
        }
        if (params.androidTextColor === 'white') {
          window.StatusBar.styleLightContent();
        } else {
          window.StatusBar.styleDefault();
        }
      }
    }
    if (params.iosBackgroundColor && Device.ios) {
      Statusbar.setBackgroundColor(params.iosBackgroundColor);
    }
    if (params.androidBackgroundColor && Device.android) {
      Statusbar.setBackgroundColor(params.androidBackgroundColor);
    }
  },
};

export default {
  name: 'statusbar',
  params: {
    statusbar: {
      enabled: true,

      scrollTopOnClick: true,

      iosOverlaysWebView: true,
      iosTextColor: 'black',
      iosBackgroundColor: null,

      androidOverlaysWebView: false,
      androidTextColor: 'black',
      androidBackgroundColor: null,
    },
  },
  create() {
    const app = this;
    Utils.extend(app, {
      statusbar: {
        hide: Statusbar.hide,
        show: Statusbar.show,
        overlaysWebView: Statusbar.overlaysWebView,
        setTextColor: Statusbar.setTextColor,
        setBackgroundColor: Statusbar.setBackgroundColor,
        isVisible: Statusbar.isVisible,
        init: Statusbar.init.bind(app),
      },
    });
  },
  on: {
    init() {
      const app = this;
      Statusbar.init.call(app);
    },
  },
};
<|endoftext|>


<commit_before>// @flow

import React, { Fragment, useCallback, useState } from 'react';
import Button from './Button';
import ButtonIcon from './ButtonIcon';
import { getMetaValueLabel } from './utils';
import { meta } from '../../hydration';
import styles from './InspectedElementTree.css';

type OverrideValueFn = (path: Array<string | number>, value: any) => void;

type Props = {|
  data: Object | null,
  label: string,
  overrideValueFn?: ?OverrideValueFn,
  showWhenEmpty?: boolean,
|};

export default function InspectedElementTree({
  data,
  label,
  overrideValueFn,
  showWhenEmpty = false,
}: Props) {
  const isEmpty = data === null || Object.keys(data).length === 0;

  if (isEmpty && !showWhenEmpty) {
    return null;
  } else {
    // TODO Add click and key handlers for toggling element open/close state.
    return (

{label}

        {isEmpty &&
None
}
        {!isEmpty &&
          Object.keys((data: any)).map(name => (
            <KeyValue
              key={name}
              depth={1}
              name={name}
              overrideValueFn={overrideValueFn}
              path={[name]}
              value={(data: any)[name]}
            />
          ))}

    );
  }
}

type KeyValueProps = {|
  depth: number,
  name: string,
  nameClassName?: string,
  overrideValueFn?: ?OverrideValueFn,
  path?: Array<any>,
  value: any,
|};

export function KeyValue({
  depth,
  name,
  nameClassName = styles.Name,
  overrideValueFn,
  path = [],
  value,
}: KeyValueProps) {
  const dataType = typeof value;
  const isSimpleType =
    dataType === 'number' ||
    dataType === 'string' ||
    dataType === 'boolean' ||
    value == null;

  const paddingLeft = `${depth * 0.75}rem`;

  let children = null;
  if (isSimpleType) {
    let displayValue = value;
    if (dataType === 'string') {
      displayValue = `"${value}"`;
    } else if (dataType === 'boolean') {
      displayValue = value ? 'true' : 'false';
    } else if (value === null) {
      displayValue = 'null';
    } else if (value === undefined) {
      displayValue = 'undefined';
    }

    children = (

        {name}
        {typeof overrideValueFn === 'function' ? (
          <EditableValue
            dataType={dataType}
            overrideValueFn={overrideValueFn}
            path={path}
            value={value}
          />
        ) : (
          {displayValue}
        )}

    );
  } else if (value.hasOwnProperty(meta.type)) {
    // TODO Is this type even necessary? Can we just drop it?
    children = (

        {name}
        {getMetaValueLabel(value)}

    );
  } else {
    if (Array.isArray(value)) {
      children = value.map((innerValue, index) => (
        <KeyValue
          key={index}
          depth={depth + 1}
          name={index}
          overrideValueFn={overrideValueFn}
          path={path.concat(index)}
          value={value[index]}
        />
      ));
      children.unshift(
        <div
          key={`${depth}-root`}
          className={styles.Item}
          style={{ paddingLeft }}
        >
          {name}
          Array

      );
    } else {
      // $FlowFixMe "Missing type annotation for U" whatever that means
      children = Object.entries(value).map(([name, value]) => (
        <KeyValue
          key={name}
          depth={depth + 1}
          name={name}
          overrideValueFn={overrideValueFn}
          path={path.concat(name)}
          value={value}
        />
      ));
      children.unshift(
        <div
          key={`${depth}-root`}
          className={styles.Item}
          style={{ paddingLeft }}
        >
          {name}
          Object

      );
    }
  }

  return children;
}

type EditableValueProps = {|
  dataType: string,
  overrideValueFn: OverrideValueFn,
  path: Array<string | number>,
  value: any,
|};

export function EditableValue({
  dataType,
  overrideValueFn,
  path,
  value,
}: EditableValueProps) {
  const [hasPendingChanges, setHasPendingChanges] = useState(false);
  const [editableValue, setEditableValue] = useState(value);

  if (hasPendingChanges && editableValue === value) {
    setHasPendingChanges(false);
  }

  const handleChange = useCallback(
    ({ target }) => {
      if (dataType === 'boolean') {
        setEditableValue(target.checked);
        overrideValueFn(path, target.checked);
      } else if (dataType === 'number') {
        setEditableValue(parseFloat(target.value));
      } else {
        setEditableValue(target.value);
      }
      setHasPendingChanges(true);
    },
    [dataType, overrideValueFn, path]
  );

  const handleReset = useCallback(() => {
    setEditableValue(value);
    setHasPendingChanges(false);
  }, [value]);

  const handleKeyDown = useCallback(
    event => {
      // Prevent keydown events from e.g. change selected element in the tree
      event.stopPropagation();

      const { key } = event;

      if (key === 'Enter') {
        overrideValueFn(path, editableValue);

        // Don't reset the pending change flag here.
        // The inspected fiber won't be updated until after the next "inspectElement" message.
        // We'll reset that flag during a subsequent render.
      } else if (key === 'Escape') {
        setEditableValue(value);
        setHasPendingChanges(false);
      }
    },
    [path, editableValue, overrideValueFn, value]
  );

  // Render different input types based on the dataType
  let type = 'text';
  if (dataType === 'boolean') {
    type = 'checkbox';
  } else if (dataType === 'number') {
    type = 'number';
  }

  let inputValue = value == null ? '' : value;
  if (hasPendingChanges) {
    inputValue = editableValue == null ? '' : editableValue;
  }

  return (
    <Fragment>

        <input
          checked={dataType === 'boolean' ? inputValue : undefined}
          className={styles.ValueInput}
          onChange={handleChange}
          onKeyDown={handleKeyDown}
          type={type}
          value={dataType === 'boolean' ? undefined : inputValue}
        />

      {hasPendingChanges && dataType !== 'boolean' && (
        <Button
          className={styles.ResetButton}
          onClick={handleReset}
          title="Reset value"
        >
          <ButtonIcon type="undo" />
        </Button>
      )}
    </Fragment>
  );
}
<commit_msg>Restore input focus after clicking reset value button<commit_after>// @flow

import React, { Fragment, useCallback, useRef, useState } from 'react';
import Button from './Button';
import ButtonIcon from './ButtonIcon';
import { getMetaValueLabel } from './utils';
import { meta } from '../../hydration';
import styles from './InspectedElementTree.css';

type OverrideValueFn = (path: Array<string | number>, value: any) => void;

type Props = {|
  data: Object | null,
  label: string,
  overrideValueFn?: ?OverrideValueFn,
  showWhenEmpty?: boolean,
|};

export default function InspectedElementTree({
  data,
  label,
  overrideValueFn,
  showWhenEmpty = false,
}: Props) {
  const isEmpty = data === null || Object.keys(data).length === 0;

  if (isEmpty && !showWhenEmpty) {
    return null;
  } else {
    // TODO Add click and key handlers for toggling element open/close state.
    return (

{label}

        {isEmpty &&
None
}
        {!isEmpty &&
          Object.keys((data: any)).map(name => (
            <KeyValue
              key={name}
              depth={1}
              name={name}
              overrideValueFn={overrideValueFn}
              path={[name]}
              value={(data: any)[name]}
            />
          ))}

    );
  }
}

type KeyValueProps = {|
  depth: number,
  name: string,
  nameClassName?: string,
  overrideValueFn?: ?OverrideValueFn,
  path?: Array<any>,
  value: any,
|};

export function KeyValue({
  depth,
  name,
  nameClassName = styles.Name,
  overrideValueFn,
  path = [],
  value,
}: KeyValueProps) {
  const dataType = typeof value;
  const isSimpleType =
    dataType === 'number' ||
    dataType === 'string' ||
    dataType === 'boolean' ||
    value == null;

  const paddingLeft = `${depth * 0.75}rem`;

  let children = null;
  if (isSimpleType) {
    let displayValue = value;
    if (dataType === 'string') {
      displayValue = `"${value}"`;
    } else if (dataType === 'boolean') {
      displayValue = value ? 'true' : 'false';
    } else if (value === null) {
      displayValue = 'null';
    } else if (value === undefined) {
      displayValue = 'undefined';
    }

    children = (

        {name}
        {typeof overrideValueFn === 'function' ? (
          <EditableValue
            dataType={dataType}
            overrideValueFn={overrideValueFn}
            path={path}
            value={value}
          />
        ) : (
          {displayValue}
        )}

    );
  } else if (value.hasOwnProperty(meta.type)) {
    // TODO Is this type even necessary? Can we just drop it?
    children = (

        {name}
        {getMetaValueLabel(value)}

    );
  } else {
    if (Array.isArray(value)) {
      children = value.map((innerValue, index) => (
        <KeyValue
          key={index}
          depth={depth + 1}
          name={index}
          overrideValueFn={overrideValueFn}
          path={path.concat(index)}
          value={value[index]}
        />
      ));
      children.unshift(
        <div
          key={`${depth}-root`}
          className={styles.Item}
          style={{ paddingLeft }}
        >
          {name}
          Array

      );
    } else {
      // $FlowFixMe "Missing type annotation for U" whatever that means
      children = Object.entries(value).map(([name, value]) => (
        <KeyValue
          key={name}
          depth={depth + 1}
          name={name}
          overrideValueFn={overrideValueFn}
          path={path.concat(name)}
          value={value}
        />
      ));
      children.unshift(
        <div
          key={`${depth}-root`}
          className={styles.Item}
          style={{ paddingLeft }}
        >
          {name}
          Object

      );
    }
  }

  return children;
}

type EditableValueProps = {|
  dataType: string,
  overrideValueFn: OverrideValueFn,
  path: Array<string | number>,
  value: any,
|};

export function EditableValue({
  dataType,
  overrideValueFn,
  path,
  value,
}: EditableValueProps) {
  const [hasPendingChanges, setHasPendingChanges] = useState(false);
  const [editableValue, setEditableValue] = useState(value);
  const inputRef = useRef<HTMLInputElement | null>(null);

  if (hasPendingChanges && editableValue === value) {
    setHasPendingChanges(false);
  }

  const handleChange = useCallback(
    ({ target }) => {
      if (dataType === 'boolean') {
        setEditableValue(target.checked);
        overrideValueFn(path, target.checked);
      } else if (dataType === 'number') {
        setEditableValue(parseFloat(target.value));
      } else {
        setEditableValue(target.value);
      }
      setHasPendingChanges(true);
    },
    [dataType, overrideValueFn, path]
  );

  const handleReset = useCallback(() => {
    setEditableValue(value);
    setHasPendingChanges(false);

    if (inputRef.current !== null) {
      inputRef.current.focus();
    }
  }, [value]);

  const handleKeyDown = useCallback(
    event => {
      // Prevent keydown events from e.g. change selected element in the tree
      event.stopPropagation();

      const { key } = event;

      if (key === 'Enter') {
        overrideValueFn(path, editableValue);

        // Don't reset the pending change flag here.
        // The inspected fiber won't be updated until after the next "inspectElement" message.
        // We'll reset that flag during a subsequent render.
      } else if (key === 'Escape') {
        setEditableValue(value);
        setHasPendingChanges(false);
      }
    },
    [path, editableValue, overrideValueFn, value]
  );

  // Render different input types based on the dataType
  let type = 'text';
  if (dataType === 'boolean') {
    type = 'checkbox';
  } else if (dataType === 'number') {
    type = 'number';
  }

  let inputValue = value == null ? '' : value;
  if (hasPendingChanges) {
    inputValue = editableValue == null ? '' : editableValue;
  }

  return (
    <Fragment>

        <input
          checked={dataType === 'boolean' ? inputValue : undefined}
          className={styles.ValueInput}
          onChange={handleChange}
          onKeyDown={handleKeyDown}
          ref={inputRef}
          type={type}
          value={dataType === 'boolean' ? undefined : inputValue}
        />

      {hasPendingChanges && dataType !== 'boolean' && (
        <Button
          className={styles.ResetButton}
          onClick={handleReset}
          title="Reset value"
        >
          <ButtonIcon type="undo" />
        </Button>
      )}
    </Fragment>
  );
}
<|endoftext|>


<commit_before>/*!
 * backbone.layoutmanager.js v0.5.2
 * Copyright 2012, Tim Branyen (@tbranyen)
 * backbone.layoutmanager.js may be freely distributed under the MIT license.
 */
(function(a){"use strict";var b=a.Backbone,c=a._,d=a.$,e=b.View.prototype._configure,f=b.View.prototype.render,g=b.View.extend({constructor:function(a){a=a||{},this._render=function(a){return a(this).render()},g.setupView(this,a),a.paths&&(this._prefix=a.paths.layout||""),b.View.call(this,a)},insertView:function(a,b){return b?this.setView(a,b,!0):this.setView(a,!0)},insertViews:function(a){return c.each(a,function(b,c){a[c]=[].concat(b)}),this.setViews(a)},getView:function(a){return this.getViews(a).first().value()},getViews:function(a){var b=c.chain(this.views).map(function(a){return[].concat(a)},this).flatten().value();return c.chain(c.filter(b,a?a:c.identity))},setView:function(a,b,d){var e,f,h=this;return c.isString(a)||(d=b,b=a,a=""),this.views=this.views||{},!d&&this.views[a]&&(c.isArray(this.views[a])?c.each(this.views[a],function(a){a.remove()}):this.views[a].remove()),f=b._options(),g.setupView(b,f),b.render.__fake__&&(b._render=function(a){return a(this).render()}),b.render=function(e){function j(){b.__manager__.hasRendered||(f.partial(h.el,a,b.el,d)&&(b.__manager__.hasRendered=!0),b.delegateEvents()),b.__manager__.handler.resolveWith(b,[b.el]),i.resolveWith(b,[b.el]),c.isFunction(e)&&e.call(b,b.el)}var i=f.deferred();return g.prototype.render.call(b).then(j),i.promise()},d||(b.__manager__.isManaged=!0),!b._prefix&&f.paths&&(b._prefix=f.paths.template||""),d?(e=this.views[a]=this.views[a]||[],c.isArray(this.views[a])||(e=this.views[a]=[this.views[a]]),e.push(b),b):this.views[a]=b},setViews:function(a){return c.each(a,function(a,b){if(c.isArray(a))return c.each(a,function(a){this.insertView(b,a)},this);this.setView(b,a)},this),this},render:function(a){var b=this,d=this._options(),e=d.deferred();return b.__manager__.renderDeferred?b.__manager__.renderDeferred:(c.each(this.views,function(a,b){if(!c.isArray(a))return;c.each(c.clone(a),function(b,d){var e=b.keep;!c.isBoolean(e)&&b.options&&(e=b.options.keep),b.__manager__.hasRendered&&!e&&(b.remove(),a.splice(d,1))})},this),this._render(g._viewRender).fetch.then(function(){b.__manager__.renderDeferred=e;var a=c.map(b.views,function(a){function e(a,b){if(!a.length)return b();var c=a.shift();c.__manager__.isManaged=!0,c.render(function(){e(a,b)})}var b;return c.isArray(a)?(b=d.deferred(),e(c.clone(a),function(){b.resolve()}),b.promise()):(a.__manager__.isManaged=!0,a.render())});d.when(a).then(function(){e.resolveWith(b,[b.el])})}),e.then(function(){c.isFunction(a)&&a.call(b,b.el),delete b.__manager__.renderDeferred}).promise())},remove:function(){return g.cleanViews(this),this._remove.apply(this,arguments)},_options:function(){return c.extend({},g.prototype.options,this.options)}},{_cache:{},_makeAsync:function(a,b){var c=a.deferred();return c.async=function(){return c._isAsync=!0,b},c},_viewRender:function(a){function h(c,d){g.cache(b,d),d&&f.html(a.el,f.render(d,c)),e.fetch.resolveWith(a,[a.el])}var b,d,e,f=a._options();return{render:function(i){var j=a.template||f.template;return a.serialize&&(f.serialize=a.serialize),!i&&c.isFunction(f.serialize)?i=f.serialize.call(a):!i&&c.isObject(f.serialize)&&(i=f.serialize),e=g._makeAsync(f,c.bind(h,a,i)),e.fetch=f.deferred(),a.__manager__.handler=e,c.isString(j)&&(b=a._prefix+j),(d=g.cache(b))?(h(i,d,b),e):(c.isString(j)?d=f.fetch.call(e,a._prefix+j):j!=null&&(d=f.fetch.call(e,j)),e._isAsync||h(i,d),e)}}},cleanViews:function(a){c.each([].concat(a),function(a){a.unbind(),a.views&&c.each(a.views,function(a){g.cleanViews(a)}),c.isFunction(a.cleanup)&&a.cleanup.call(a)})},cache:function(a,b){if(a in this._cache)return this._cache[a];if(a!=null&&b!=null)return this._cache[a]=b},configure:function(a){c.extend(g.prototype.options,a)},setupView:function(a,d){var e=b.LayoutManager.prototype,f=c.keys(g.prototype.options);d=a.options=c.defaults(d||{},e.options),c.defaults(a,{views:{},__manager__:{}}),c.extend(d,c.pick(this,f)),a._remove=b.View.prototype.remove,a instanceof g||(a.options.render=g.prototype.options.render),a.remove!==e.remove&&(a._remove=a.remove,a.remove=e.remove),a._prefix="",d.views&&a.setViews(d.views),a.template&&(d.template=a.template)},removeView:function(a,b){c.isObject(a)||(a=a||this,b=a),c.each(a.views,function(a){if(b&&!c.isArray(a))return;c.each([].concat(a),function(a){a.remove(),a.getViews().each(function(a){g.removeView(a,b)})})})}});c.each(["get","set","insert"],function(a){var c=b.View.prototype,d=g.prototype;c[a+"View"]=d[a+"View"],c[a+"Views"]=d[a+"Views"]}),c.extend(b.View.prototype,{removeView:g.removeView,_options:g.prototype._options,_configure:function(){var a=e.apply(this,arguments),b;return this.__manager__||(this._render=this.options.render||this.render,b=this.render=function(){return this.render!==b?this.render.apply(this,arguments):this._render.apply(this,arguments)},this._render===f&&(this.render.__fake__=!0)),a}}),b.Layout=b.LayoutManager=g,g.prototype.options={paths:{},deferred:function(){return d.Deferred()},fetch:function(a){return c.template(d(a).html())},partial:function(a,b,c,e){var f=b?d(a).find(b):d(a);return f.length?(this[e?"append":"html"](f,c),!0):!1},html:function(a,b){d(a).html(b)},append:function(a,b){d(a).append(b)},when:function(a){return d.when.apply(null,a)},render:function(a,b){return a(b)}}})(this)<commit_msg>oh god<commit_after>/*!
 * backbone.layoutmanager.js v0.5.2
 * Copyright 2012, Tim Branyen (@tbranyen)
 * backbone.layoutmanager.js may be freely distributed under the MIT license.
 */
(function(a){"use strict";var b=a.Backbone,c=a._,d=a.$,e=b.View.prototype._configure,f=b.View.prototype.render,g=b.View.extend({constructor:function(a){a=a||{},this._render=function(a){return a(this).render()},g.setupView(this,a),a.paths&&(this._prefix=a.paths.layout||""),b.View.call(this,a)},insertView:function(a,b){return b?this.setView(a,b,!0):this.setView(a,!0)},insertViews:function(a){return c.each(a,function(b,c){a[c]=[].concat(b)}),this.setViews(a)},getView:function(a){return this.getViews(a).first().value()},getViews:function(a){var b=c.chain(this.views).map(function(a){return[].concat(a)},this).flatten().value();return c.chain(c.filter(b,a?a:c.identity))},setView:function(a,b,d){var e,f,h=this;return c.isString(a)||(d=b,b=a,a=""),this.views=this.views||{},!d&&this.views[a]&&(c.isArray(this.views[a])?c.each(this.views[a],function(a){a.remove()}):this.views[a].remove()),f=b._options(),g.setupView(b,f),b.render.__fake__&&(b._render=function(a){return a(this).render()}),b.render=function(e){function j(){b.__manager__.hasRendered||(f.partial(h.el,a,b.el,d)&&(b.__manager__.hasRendered=!0),b.delegateEvents()),b.__manager__.handler.resolveWith(b,[b.el]),i.resolveWith(b,[b.el]),c.isFunction(e)&&e.call(b,b.el)}var i=f.deferred();return g.prototype.render.call(b).then(j),i.promise()},d||(b.__manager__.isManaged=!0),!b._prefix&&f.paths&&(b._prefix=f.paths.template||""),d?(e=this.views[a]=this.views[a]||[],c.isArray(this.views[a])||(e=this.views[a]=[this.views[a]]),e.push(b),b):this.views[a]=b},setViews:function(a){return c.each(a,function(a,b){if(c.isArray(a))return c.each(a,function(a){this.insertView(b,a)},this);this.setView(b,a)},this),this},render:function(a){var b=this,d=this._options(),e=d.deferred();return b.__manager__.renderDeferred?b.__manager__.renderDeferred:(c.each(this.views,function(a,b){if(!c.isArray(a))return;c.each(c.clone(a),function(b,d){var e=b.keep;!c.isBoolean(e)&&b.options&&(e=b.options.keep),b.__manager__.hasRendered&&!e&&(b.remove(),a.splice(d,1))})},this),this._render(g._viewRender).fetch.then(function(){b.__manager__.renderDeferred=e;var a=c.map(b.views,function(a){function e(a,b){if(!a.length)return b();var c=a.shift();c.__manager__.isManaged=!0,c.render(function(){e(a,b)})}var b;return c.isArray(a)?(b=d.deferred(),e(c.clone(a),function(){b.resolve()}),b.promise()):(a.__manager__.isManaged=!0,a.render())});d.when(a).then(function(){e.resolveWith(b,[b.el])})}),e.then(function(){c.isFunction(a)&&a.call(b,b.el),delete b.__manager__.renderDeferred}).promise())},remove:function(){return g.cleanViews(this),this._remove.apply(this,arguments)},_options:function(){return c.extend({},g.prototype.options,this.options)}},{_cache:{},_makeAsync:function(a,b){var c=a.deferred();return c.async=function(){return c._isAsync=!0,b},c},_viewRender:function(a){function h(c,d){g.cache(b,d),d&&f.html(a.el,f.render(d,c)),e.fetch.resolveWith(a,[a.el])}var b,d,e,f=a._options();return{render:function(i){var j=a.template||f.template;return a.serialize&&(f.serialize=a.serialize),!i&&c.isFunction(f.serialize)?i=f.serialize.call(a):!i&&c.isObject(f.serialize)&&(i=f.serialize),e=g._makeAsync(f,c.bind(h,a,i)),e.fetch=f.deferred(),a.__manager__.handler=e,c.isString(j)&&(b=a._prefix+j),(d=g.cache(b))?(h(i,d,b),e):(c.isString(j)?d=f.fetch.call(e,a._prefix+j):j!=null&&(d=f.fetch.call(e,j)),e._isAsync||h(i,d),e)}}},cleanViews:function(a){c.each([].concat(a),function(a){a.unbind(),a.views&&c.each(a.views,function(a){g.cleanViews(a)}),c.isFunction(a.cleanup)&&a.cleanup.call(a)})},cache:function(a,b){if(a in this._cache)return this._cache[a];if(a!=null&&b!=null)return this._cache[a]=b},configure:function(a){c.extend(g.prototype.options,a)},setupView:function(a,d){var e=b.LayoutManager.prototype,f=c.keys(g.prototype.options);d=a.options=c.defaults(d||{},e.options),c.defaults(a,{views:{},__manager__:{}}),c.extend(d,c.pick(this,f)),a._remove=b.View.prototype.remove,a instanceof g||(a.options.render=g.prototype.options.render),a.remove!==e.remove&&(a._remove=a.remove,a.remove=e.remove),a._prefix="",d.views&&a.setViews(d.views),a.template&&(d.template=a.template)},removeView:function(a,b){c.isObject(a)||(a=a||this,b=a),c.each(a.views,function(a){if(b&&!c.isArray(a))return;c.each([].concat(a),function(a){a.remove(),a.getViews().each(function(a){g.removeView(a,b)})})})}});c.each(["get","set","insert"],function(a){var c=b.View.prototype,d=g.prototype;c[a+"View"]=d[a+"View"],c[a+"Views"]=d[a+"Views"]}),c.extend(b.View.prototype,{removeView:g.removeView,_options:g.prototype._options,_configure:function(){var a=e.apply(this,arguments),b;return this.__manager__||(this._render=this.options.render||this.render,b=this.render=function(){return this.render!==b?this.render.apply(this,arguments):this._render.apply(this,arguments)},this._render===f&&(this.render.__fake__=!0)),a}}),b.Layout=b.LayoutManager=g,g.prototype.options={paths:{},deferred:function(){return d.Deferred()},fetch:function(a){return c.template(d(a).html())},partial:function(a,b,c,e){var f=b?d(a).find(b):d(a);return f.length?(this[e?"append":"html"](f,c),!0):!1},html:function(a,b){d(a).html(b)},append:function(a,b){d(a).append(b)},when:function(a){return d.when.apply(null,a)},render:function(a,b){return a(b)}}})(this);<|endoftext|>