<commit_before>"use strict";

class BruteForce {

    constructor(gameEngine){
        this.gameEngine = gameEngine;

        this.collisionPairs = {};

        this.gameEngine.on("poststep",this.updateObjects.bind(this));
    };

    updateObjects(){

        for(let objAId in this.gameEngine.world.objects){
            for(let objBId in this.gameEngine.world.objects){
                if (objBId == objAId) continue;
                let x1 = this.gameEngine.world.objects[objAId].x;
                let y1 = this.gameEngine.world.objects[objAId].y;

                let x2 = this.gameEngine.world.objects[objBId].x;
                let y2 = this.gameEngine.world.objects[objBId].y;

                // console.log(objAId, objB, x1,y1, x2,y2);
                let distance = Math.sqrt( (x2-=x1)*x2 + (y2-=y1)*y2 );
                let pairId =[objAId, objBId].sort().join(",");

                if (distance < 50){
                    if (!(pairId in this.collisionPairs)){
                        this.collisionPairs[pairId] = true;
                        this.gameEngine.emit("collisionStart", {
                            a: this.gameEngine.world.objects[objAId],
                            b: this.gameEngine.world.objects[objBId]
                        });
                        // console.log("collision start", pairId);
                    }
                }
                else{
                    if (pairId in this.collisionPairs){
                        this.gameEngine.emit("collisionStop", {
                            a: this.gameEngine.world.objects[objAId],
                            b: this.gameEngine.world.objects[objBId]
                        });
                        delete this.collisionPairs[pairId];
                        // console.log("collision stop", pairId);
                    }
                }
            }
        }

    }

}

module.exports = BruteForce;<commit_msg>bruteForce: change collision distance<commit_after>"use strict";

class BruteForce {

    constructor(gameEngine){
        this.gameEngine = gameEngine;

        this.collisionPairs = {};

        this.gameEngine.on("poststep",this.updateObjects.bind(this));
    };

    updateObjects(){

        for(let objAId in this.gameEngine.world.objects){
            for(let objBId in this.gameEngine.world.objects){
                if (objBId == objAId) continue;
                let x1 = this.gameEngine.world.objects[objAId].x;
                let y1 = this.gameEngine.world.objects[objAId].y;

                let x2 = this.gameEngine.world.objects[objBId].x;
                let y2 = this.gameEngine.world.objects[objBId].y;

                // console.log(objAId, objB, x1,y1, x2,y2);
                let distance = Math.sqrt( (x2-=x1)*x2 + (y2-=y1)*y2 );
                let pairId =[objAId, objBId].sort().join(",");

                if (distance < 28){
                    if (!(pairId in this.collisionPairs)){
                        this.collisionPairs[pairId] = true;
                        this.gameEngine.emit("collisionStart", {
                            a: this.gameEngine.world.objects[objAId],
                            b: this.gameEngine.world.objects[objBId]
                        });
                        // console.log("collision start", pairId);
                    }
                }
                else{
                    if (pairId in this.collisionPairs){
                        this.gameEngine.emit("collisionStop", {
                            a: this.gameEngine.world.objects[objAId],
                            b: this.gameEngine.world.objects[objBId]
                        });
                        delete this.collisionPairs[pairId];
                        // console.log("collision stop", pairId);
                    }
                }
            }
        }

    }

}

module.exports = BruteForce;<|endoftext|>


<commit_before>import React from 'react'
import Img from "gatsby-image"
import "./index.sass"

export default class PhotoGalleryBlock extends React.Component {
    render() {
        return (

                <ul className={`layout-${this.props.style}`}>
                    {this.props.photos.map((image) => (

                            {this.props.linkToFullSize ? (
                                {this.renderImg(image)}
                            ) : this.renderImg(image)}

                            {['comic', 'staff-bios', 'staff-titles'].includes(this.props.style) ? this.renderBio(image) : null}

                    ))}

        )
    }

    renderImg(image) {
        let src = image.med;
        if (this.props.style === 'staff-titles') src = image.sml;
        if (this.props.style === 'gallery-small') src = image.smc;

        return (
            src.src ? (

            ) : (

            )
        );
    }

    renderBio(image) {
        return (

                {['staff-bios', 'staff-titles'].includes(this.props.style) ? ([

{image.title.split(', ')[0]}
,

{image.title.split(', ')[1] || null}

                ]) : ''}

{image.description}

        );
    }
}

export const query = graphql`
    fragment PhotoGalleryBlockItems on ContentfulLayoutBlockPhotoGallery {
        style
        linkToFullSize
        photos {
            id
            title
            description
            file {
                url
            }
            smc: sizes(maxWidth: 300, maxHeight: 200, quality: 90) {
                ...GatsbyContentfulSizes_withWebp
            }
            sml: sizes(maxWidth: 300, quality: 90) {
                ...GatsbyContentfulSizes_withWebp
            }
            med: sizes(maxWidth: 910, quality: 90) {
                ...GatsbyContentfulSizes_withWebp
            }
        }
    }
`;
<commit_msg>Update photo gallery size to crop medium<commit_after>import React from 'react'
import Img from "gatsby-image"
import "./index.sass"

export default class PhotoGalleryBlock extends React.Component {
    render() {
        return (

                <ul className={`layout-${this.props.style}`}>
                    {this.props.photos.map((image) => (

                            {this.props.linkToFullSize ? (
                                {this.renderImg(image)}
                            ) : this.renderImg(image)}

                            {['comic', 'staff-bios', 'staff-titles'].includes(this.props.style) ? this.renderBio(image) : null}

                    ))}

        )
    }

    renderImg(image) {
        let src = image.med;
        if (this.props.style === 'staff-titles') src = image.sml;
        if (this.props.style === 'gallery-small') src = image.smc;

        return (
            src.src ? (

            ) : (

            )
        );
    }

    renderBio(image) {
        return (

                {['staff-bios', 'staff-titles'].includes(this.props.style) ? ([

{image.title.split(', ')[0]}
,

{image.title.split(', ')[1] || null}

                ]) : ''}

{image.description}

        );
    }
}

export const query = graphql`
    fragment PhotoGalleryBlockItems on ContentfulLayoutBlockPhotoGallery {
        style
        linkToFullSize
        photos {
            id
            title
            description
            file {
                url
            }
            smc: sizes(maxWidth: 300, maxHeight: 200, quality: 90) {
                ...GatsbyContentfulSizes_withWebp
            }
            sml: sizes(maxWidth: 300, quality: 90) {
                ...GatsbyContentfulSizes_withWebp
            }
            med: sizes(maxWidth: 500, maxHeight: 281, quality: 90) {
                ...GatsbyContentfulSizes_withWebp
            }
        }
    }
`;
<|endoftext|>


<commit_before>/**
 * Created by PolarisChen on 16/8/10.
 */

import React, { Component, PropTypes } from 'react';
import $ from 'jquery';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './RepoFlowItem.scss';

import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';
import FontIcon from 'material-ui/FontIcon';
import Chip from 'material-ui/Chip';

import Code from 'material-ui/svg-icons/action/code';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import Star from 'material-ui/svg-icons/toggle/star';

const styles = {
  title: {
    fontSize: '16px',
    color: '#74C2CE'
  },
  subtitle: {
    fontSize: '12px',
    fontWeight: 300,
    color: '#666'
  },
  chipLabel: {
    fontSize: '12px',
    fontWeight: 300,
    color: '#666'
  },
  chip: {
    marginRight: 6,
    marginBottom: 6
  },
  cardText: {
    paddingTop: 6,
    paddingBottom: 6
  },
  cardActions: {
    display: 'flex',
    flexDirection: 'row',
    marginLeft: 10,
    paddingTop: 16,
    paddingBottom: 6
  },
  mainActions: {
    display: 'flex',
    flexDirection: 'row',
    flexBasis: 0,
    flexGrow: 1
  },
  optionalAction: {
    flexBasis: 1,
    flexGrow: 'auto',
    color: '#CCC'
  },
  iconButton: {
    color: '#BBB'
  }
};

class RepoFlowItem extends Component {
  constructor(props) {
    super(props);
    this.state = {hovering: false};
  }
  handleStar() {
    let user = this.props.currentUser;
    let repo = this.props.repo.owner+'/'+this.props.repo.name;
    let url = `/api/repo/star?user=${user}&repo=${repo}`;
    console.log('###',url);
    $.ajax(url)
      .done(((data) => {
        console.log("$$$",data);
      }).bind(this))
      .fail(((xhr, status, err) => {
        console.error(url, status, err.toString());
      }).bind(this));
  }
  handleUnlike() {
    let param = {
      type: 1,
      name: this.props.repo.owner+'/'+this.props.repo.name
    };
    console.log('UNLIKE', param);
    this.props.handleUnlike(param);
  }
  handleMouseOver() {
    this.setState({hovering: true});
  }
  handleMouseOut() {
    this.setState({hovering: false});
  }
  renderStarButton() {
    if (this.props.repo.set) {
      return (
        <RaisedButton
          className={s.mainButton}
          icon={<Star />}
          label={this.props.repo.set || 'UNGROUPED'}
          labelColor="#F2DF83"
          onTouchTap={this.handleStar.bind(this)} />
      )
    }
    return (
      <RaisedButton
        className={s.mainButton}
        icon={<Star />}
        label={'Star (' + this.props.repo.star + ')'}
        secondary={true}
        onTouchTap={this.handleStar.bind(this)} />
    )
  }
  renderNotInterestedButton() {
    if (this.props.optional && this.state.hovering) {
      return (
        <FlatButton
          style={styles.optionalAction}
          label='Not interested'
          onTouchTap={this.handleUnlike.bind(this)}
        />
      );
    }
  }
  render() {
    return (
      <Card className={s.item} onMouseEnter={this.handleMouseOver.bind(this)} onMouseLeave={this.handleMouseOut.bind(this)}>
        <CardHeader
          title={this.props.repo.owner + '/' + this.props.repo.name}
          titleStyle={styles.title}
          subtitle={'Updated on ' + this.props.repo.update}
          subtitleStyle={styles.subtitle}
          avatar={this.props.repo.avatarUrl || require('./avatar-default-s.png')}
        />
        <CardText style={styles.cardText}>
          {this.props.repo.description}
        </CardText>
        <CardText style={styles.cardText}>

            {
              this.props.repo.tags.map((tag, i) => {
                return (
                  <Chip
                    key={i}
                    labelStyle={styles.chipLabel}
                    style={styles.chip}
                    onTouchTap={this.handleTouchTap}
                  >
                    {tag}
                  </Chip>
                );
              })
            }

        </CardText>
        <CardActions style={styles.cardActions}>

            {this.renderStarButton()}
            <RaisedButton
              className={s.mainButton}
              icon={}
              label="View Related"
              labelColor="#666"
              href={`/related?fullName=${this.props.repo.owner}/${this.props.repo.name}`}
            />

            {this.renderNotInterestedButton()}

        </CardActions>

          <IconButton
            iconClassName="muidocs-icon-custom-github"
            iconStyle={styles.iconButton}
            href={'https://github.com/'+this.props.repo.owner+'/'+this.props.repo.name}
          />

      </Card>
    );
  }
}

export default withStyles(RepoFlowItem, s);
<commit_msg>Update single state of repo item<commit_after>/**
 * Created by PolarisChen on 16/8/10.
 */

import React, { Component, PropTypes } from 'react';
import $ from 'jquery';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './RepoFlowItem.scss';

import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';
import FontIcon from 'material-ui/FontIcon';
import Chip from 'material-ui/Chip';

import Code from 'material-ui/svg-icons/action/code';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import Star from 'material-ui/svg-icons/toggle/star';

const styles = {
  title: {
    fontSize: '16px',
    color: '#74C2CE'
  },
  subtitle: {
    fontSize: '12px',
    fontWeight: 300,
    color: '#666'
  },
  chipLabel: {
    fontSize: '12px',
    fontWeight: 300,
    color: '#666'
  },
  chip: {
    marginRight: 6,
    marginBottom: 6
  },
  cardText: {
    paddingTop: 6,
    paddingBottom: 6
  },
  cardActions: {
    display: 'flex',
    flexDirection: 'row',
    marginLeft: 10,
    paddingTop: 16,
    paddingBottom: 6
  },
  mainActions: {
    display: 'flex',
    flexDirection: 'row',
    flexBasis: 0,
    flexGrow: 1
  },
  optionalAction: {
    flexBasis: 1,
    flexGrow: 'auto',
    color: '#CCC'
  },
  iconButton: {
    color: '#BBB'
  }
};

class RepoFlowItem extends Component {
  constructor(props) {
    super(props);
    this.state = {hovering: false};
  }
  handleStar() {
    let user = this.props.currentUser;
    let repo = this.props.repo.owner+'/'+this.props.repo.name;
    let url = `/api/repo/star?user=${user}&repo=${repo}`;
    console.log('###',url);
    $.ajax(url)
      .done(((data) => {
        console.log("$$$",data);
      }).bind(this))
      .fail(((xhr, status, err) => {
        console.error(url, status, err.toString());
      }).bind(this));
  }
  handleUnlike() {
    let param = {
      type: 1,
      name: this.props.repo.owner+'/'+this.props.repo.name
    };
    console.log('UNLIKE', param);
    this.props.handleUnlike(param);
  }
  handleMouseOver() {
    this.setState({hovering: true});
  }
  handleMouseOut() {
    this.setState({hovering: false});
  }
  renderStarButton() {
    if (this.props.repo.set) {
      return (
        <RaisedButton
          className={s.mainButton}
          icon={<Star />}
          label={this.props.repo.set || 'UNGROUPED'}
          labelColor="#F2DF83"
          onTouchTap={this.handleStar.bind(this)} />
      )
    }
    return (
      <RaisedButton
        className={s.mainButton}
        icon={<Star />}
        label={'Star (' + this.props.repo.star + ')'}
        secondary={true}
        onTouchTap={this.handleStar.bind(this)} />
    )
  }
  renderNotInterestedButton() {
    if (this.props.optional && this.state.hovering) {
      return (
        <FlatButton
          style={styles.optionalAction}
          label='Not interested'
          onTouchTap={this.handleUnlike.bind(this)}
        />
      );
    }
  }
  renderRelatedButton() {
    if (!this.props.single) {
      return (
        <RaisedButton
          className={s.mainButton}
          icon={}
          label="View Related"
          labelColor="#666"
          href={`/related?fullName=${this.props.repo.owner}/${this.props.repo.name}`}
        />
      )
    }
  }
  render() {
    return (
      <Card className={s.item} onMouseEnter={this.handleMouseOver.bind(this)} onMouseLeave={this.handleMouseOut.bind(this)}>
        <CardHeader
          title={this.props.repo.owner + '/' + this.props.repo.name}
          titleStyle={styles.title}
          subtitle={'Updated on ' + this.props.repo.update}
          subtitleStyle={styles.subtitle}
          avatar={this.props.repo.avatarUrl || require('./avatar-default-s.png')}
        />
        <CardText style={styles.cardText}>
          {this.props.repo.description}
        </CardText>
        <CardText style={styles.cardText}>

            {
              this.props.repo.tags.map((tag, i) => {
                return (
                  <Chip
                    key={i}
                    labelStyle={styles.chipLabel}
                    style={styles.chip}
                    onTouchTap={this.handleTouchTap}
                  >
                    {tag}
                  </Chip>
                );
              })
            }

        </CardText>
        <CardActions style={styles.cardActions}>

            {this.renderStarButton()}
            {this.renderRelatedButton()}

            {this.renderNotInterestedButton()}

        </CardActions>

          <IconButton
            iconClassName="muidocs-icon-custom-github"
            iconStyle={styles.iconButton}
            href={'https://github.com/'+this.props.repo.owner+'/'+this.props.repo.name}
          />

      </Card>
    );
  }
}

export default withStyles(RepoFlowItem, s);
<|endoftext|>


<commit_before>import React from 'react';
import API from '../../SpreadsheetData';
import { observer, inject } from 'mobx-react';
import { FlavorText, Rarity, Unique, Name, Element, Mugic, Discipline, Ability, Tribe } from '../../Snippets';

@inject((stores, props, context) => props) @observer
export default class Creature extends React.Component {

  render() {
    const { card, stats } = this.props;

    const mugic = [];
    for (let i = 0; i < card.gsx$mugicability; i++) {
      mugic.push(<Mugic key={i} tribe={card.gsx$tribe} />);
    }

    const TribeLine = () => {
      const tribe = card.gsx$tribe;
      let types = card.gsx$types;
      let past = false;
      if (types.toLowerCase().includes("past")) {
        past = true;
        types = types.replace(/past /i, '');
      }

      // <past> <tribe> <types>
      const line = " " + (past ? "Past " : "") + types;

      return <Tribe tribe={tribe} />{line};
    };

    const stat_range = (stat, name) => {
      if (name && name == "Aa'une the Oligarch, Avatar") return Number(stat);
      if (stats == "min") return Number(stat) - 10;
      if (stats == "max") return Number(stat) + 10;
      return Number(stat);
    };

    const energy_range = (energy, name) => {
      if (name && name == "Aa'une the Oligarch, Avatar") return Number(energy);
      if (stats == "min") return Number(energy) - 5;
      if (stats == "max") return Number(energy) + 5;
      return Number(energy);
    };

    if (this.props.ext == false) return (

         this.props.setImage(API.cardImage(card))} />

          <Name name={card.gsx$name} />
          <Rarity set={card.gsx$set} rarity={card.gsx$rarity} />

          <TribeLine />

            <Element element="fire" value={card.gsx$elements.toLowerCase().indexOf("fire") >=0} />
            <Element element="air" value={card.gsx$elements.toLowerCase().indexOf("air") >=0} />
            <Element element="earth" value={card.gsx$elements.toLowerCase().indexOf("earth") >=0} />
            <Element element="water" value={card.gsx$elements.toLowerCase().indexOf("water") >=0} />

          {mugic}

          <Ability ability={card.gsx$ability} tribe={card.gsx$tribe} />
          { card.gsx$brainwashed && (
            <>

Brainwashed

              <Ability type="brainwashed" tribe={card.gsx$tribe} ability={card.gsx$brainwashed} />
            </>
          )}
          <Unique data={{ unique: card.gsx$unique, loyal: card.gsx$loyal, legendary: card.gsx$legendary, tribe: card.gsx$tribe }} />
          {/*chieftain*/
            card.gsx$types.includes("Chieftain") &&

(Minions use Brainwashed text. Minions may only play Generic Mugic.)

          }
          <FlavorText flavortext={card.gsx$flavortext} />

            {stat_range(card.gsx$courage, card.gsx$name)}<Discipline discipline="courage" />

            {stat_range(card.gsx$power, card.gsx$name)}<Discipline discipline="power" />

            {stat_range(card.gsx$wisdom, card.gsx$name)}<Discipline discipline="wisdom" />

            {stat_range(card.gsx$speed, card.gsx$name)}<Discipline discipline="speed" />

{energy_range(card.gsx$energy, card.gsx$name)}

    );
    else return (

          {/* style={{ backgroundImage: `url("${API.cardImage(card)}")` }} */}

              = 100 ? { className: "long" } : null)}>{stat_range(card.gsx$courage, card.gsx$name)}
              = 100 ? { className: "long" } : null)}>{stat_range(card.gsx$power, card.gsx$name)}
              = 100 ? { className: "long" } : null)}>{stat_range(card.gsx$wisdom, card.gsx$name)}
              = 100 ? { className: "long" } : null)}>{stat_range(card.gsx$speed, card.gsx$name)}
              = 100 ? { className: "long" } : null)}>{energy_range(card.gsx$energy, card.gsx$name)}

          <Name name={card.gsx$name} />
          {stat_range(card.gsx$courage, card.gsx$name)} <Discipline discipline="courage" />
          {stat_range(card.gsx$power, card.gsx$name)} <Discipline discipline="power" />
          {stat_range(card.gsx$wisdom, card.gsx$name)} <Discipline discipline="wisdom" />
          {stat_range(card.gsx$speed, card.gsx$name)} <Discipline discipline="speed" />
          {energy_range(card.gsx$energy, card.gsx$name)}

          <Ability ability={card.gsx$ability} tribe={card.gsx$tribe} />
          { card.gsx$brainwashed && (
            <>

Brainwashed

              <Ability type="brainwashed" tribe={card.gsx$tribe} ability={card.gsx$brainwashed} />
            </>
          )}
          <Unique data={{ unique: card.gsx$unique, loyal: card.gsx$loyal, legendary: card.gsx$legendary, tribe: card.gsx$tribe }} />
          {/*chieftain*/
            card.gsx$types.includes("Chieftain") &&

(Minions use Brainwashed text. Minions may only play Generic Mugic.)

          }
          <FlavorText flavortext={card.gsx$flavortext} />

Art By: {card.gsx$artist}

    );
  }
}

<commit_msg>fix db entries<commit_after>import React from 'react';
import API from '../../SpreadsheetData';
import { observer, inject } from 'mobx-react';
import { FlavorText, Rarity, Unique, Name, Element, Mugic, Discipline, Ability, Tribe } from '../../Snippets';

@inject((stores, props, context) => props) @observer
export default class Creature extends React.Component {

  render() {
    const { card, stats } = this.props;

    const mugic = [];
    for (let i = 0; i < card.gsx$mugicability; i++) {
      mugic.push(<Mugic key={i} tribe={card.gsx$tribe} />);
    }

    const TribeLine = () => {
      let types = card.gsx$types;

      // Moves "Past" in front of tribe due to db entry order
      let past = false;
      if (types.toLowerCase().includes("past")) {
        past = true;
        types = types.replace(/past /i, '');
      }
      const line = " " + (past ? "Past " : "") + types;

      return <Tribe tribe={card.gsx$tribe} />{line};
    };

    const stat_range = (stat, name) => {
      if (name && name == "Aa'une the Oligarch, Avatar") return Number(stat);
      if (stats == "min") return Number(stat) - 10;
      if (stats == "max") return Number(stat) + 10;
      return Number(stat);
    };

    const energy_range = (energy, name) => {
      if (name && name == "Aa'une the Oligarch, Avatar") return Number(energy);
      if (stats == "min") return Number(energy) - 5;
      if (stats == "max") return Number(energy) + 5;
      return Number(energy);
    };

    if (this.props.ext == false) return (

         this.props.setImage(API.cardImage(card))} />

          <Name name={card.gsx$name} />
          <Rarity set={card.gsx$set} rarity={card.gsx$rarity} />

          <TribeLine />

            <Element element="fire" value={card.gsx$elements.toLowerCase().indexOf("fire") >=0} />
            <Element element="air" value={card.gsx$elements.toLowerCase().indexOf("air") >=0} />
            <Element element="earth" value={card.gsx$elements.toLowerCase().indexOf("earth") >=0} />
            <Element element="water" value={card.gsx$elements.toLowerCase().indexOf("water") >=0} />

          {mugic}

          <Ability ability={card.gsx$ability} tribe={card.gsx$tribe} />
          { card.gsx$brainwashed && (
            <>

Brainwashed

              <Ability type="brainwashed" tribe={card.gsx$tribe} ability={card.gsx$brainwashed} />
            </>
          )}
          <Unique data={{ unique: card.gsx$unique, loyal: card.gsx$loyal, legendary: card.gsx$legendary, tribe: card.gsx$tribe }} />
          {/*chieftain*/
            card.gsx$types.includes("Chieftain") &&

(Minions use Brainwashed text. Minions may only play Generic Mugic.)

          }
          <FlavorText flavortext={card.gsx$flavortext} />

            {stat_range(card.gsx$courage, card.gsx$name)}<Discipline discipline="courage" />

            {stat_range(card.gsx$power, card.gsx$name)}<Discipline discipline="power" />

            {stat_range(card.gsx$wisdom, card.gsx$name)}<Discipline discipline="wisdom" />

            {stat_range(card.gsx$speed, card.gsx$name)}<Discipline discipline="speed" />

{energy_range(card.gsx$energy, card.gsx$name)}

    );
    else return (

          {/* style={{ backgroundImage: `url("${API.cardImage(card)}")` }} */}

              = 100 ? { className: "long" } : null)}>{stat_range(card.gsx$courage, card.gsx$name)}
              = 100 ? { className: "long" } : null)}>{stat_range(card.gsx$power, card.gsx$name)}
              = 100 ? { className: "long" } : null)}>{stat_range(card.gsx$wisdom, card.gsx$name)}
              = 100 ? { className: "long" } : null)}>{stat_range(card.gsx$speed, card.gsx$name)}
              = 100 ? { className: "long" } : null)}>{energy_range(card.gsx$energy, card.gsx$name)}

          <Name name={card.gsx$name} />
          {stat_range(card.gsx$courage, card.gsx$name)} <Discipline discipline="courage" />
          {stat_range(card.gsx$power, card.gsx$name)} <Discipline discipline="power" />
          {stat_range(card.gsx$wisdom, card.gsx$name)} <Discipline discipline="wisdom" />
          {stat_range(card.gsx$speed, card.gsx$name)} <Discipline discipline="speed" />
          {energy_range(card.gsx$energy, card.gsx$name)}

          <Ability ability={card.gsx$ability} tribe={card.gsx$tribe} />
          { card.gsx$brainwashed && (
            <>

Brainwashed

              <Ability type="brainwashed" tribe={card.gsx$tribe} ability={card.gsx$brainwashed} />
            </>
          )}
          <Unique data={{ unique: card.gsx$unique, loyal: card.gsx$loyal, legendary: card.gsx$legendary, tribe: card.gsx$tribe }} />
          {/*chieftain*/
            card.gsx$types.includes("Chieftain") &&

(Minions use Brainwashed text. Minions may only play Generic Mugic.)

          }
          <FlavorText flavortext={card.gsx$flavortext} />

Art By: {card.gsx$artist}

    );
  }
}

<|endoftext|>


<commit_before>import Controller from '../../../lib/controller';
import nunjucks from 'nunjucks';
import { getUsefulContents } from '../../../lib/ajax';
import objectAssign from 'object-assign';
import $ from 'jquery';
import jQuery from 'jquery';
import window from 'window-shim';
import fs from 'file-system';
import myfuckingdata from './data.json';
// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;

if (window.jQuery) {
    console.log('jquery')
} else {
    console.log('no jquery')
}

function onClick(e) {
  console.log(e.currentTarget);
}

function getData(context) {
 let name = myfuckingdata;

 return name;
}

getUsefulContents("http://localhost:8001/data.json", data => {
  // console.log(data);
  let name = data;

  console.log(name);
  return name;
});

export default class HomeController extends Controller {

  index(application, request, reply, callback) {
    this.context.cookie.set('random', '_' + (Math.floor(Math.random() * 1000) + 1), { path: '/' });
    this.context.data = { random: Math.floor(Math.random() * 1000) + 1 };
    callback(null);
  }

  toString(callback) {
    // this can be handled more eloquently using Object.assign
    // but we are not including the polyfill dependency
    // for the sake of simplicity
    let context = getData(this.context);
    context.data = this.context.data;

    nunjucks.render('components/pages/Home/home.html', context, (err, html) => {
      if (err) {
        return callback(err, null);
      }

      callback(null, html);
    });
  }

  attach(el) {
    console.log(this.context.data.random);
    this.clickHandler = el.addEventListener('click', onClick, false);
  }

  detach(el) {
    el.removeEventListener('click', onClick, false);
  }

}<commit_msg>renamed myfuckingdata to data. sorry parents<commit_after>import Controller from '../../../lib/controller';
import nunjucks from 'nunjucks';
import { getUsefulContents } from '../../../lib/ajax';
import objectAssign from 'object-assign';
import $ from 'jquery';
import jQuery from 'jquery';
import window from 'window-shim';
import data from './data.json';
// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;

if (window.jQuery) {
    console.log('jquery')
} else {
    console.log('no jquery')
}

function onClick(e) {
  console.log(e.currentTarget);
}

function getData(context) {
 let name = data;

 return name;
}

export default class HomeController extends Controller {

  index(application, request, reply, callback) {
    this.context.cookie.set('random', '_' + (Math.floor(Math.random() * 1000) + 1), { path: '/' });
    this.context.data = { random: Math.floor(Math.random() * 1000) + 1 };
    callback(null);
  }

  toString(callback) {
    // this can be handled more eloquently using Object.assign
    // but we are not including the polyfill dependency
    // for the sake of simplicity
    let context = getData(this.context);
    context.data = this.context.data;

    nunjucks.render('components/pages/Home/home.html', context, (err, html) => {
      if (err) {
        return callback(err, null);
      }

      callback(null, html);
    });
  }

  attach(el) {
    console.log(this.context.data.random);
    this.clickHandler = el.addEventListener('click', onClick, false);
  }

  detach(el) {
    el.removeEventListener('click', onClick, false);
  }

}<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { escapeRegExp, set } from 'lodash';
import { List, AutoSizer } from 'react-virtualized';

import SecretListItem from 'components/secrets/SecretListItem';
import SecretListFolderInfo from 'components/secrets/SecretListFolderInfo';

class SecretListContent extends Component {
  static propTypes = {
    filtered: PropTypes.bool,
    secrets: PropTypes.array,
    isDragging: PropTypes.bool,
    folders: PropTypes.array,
    searchQuery: PropTypes.string,
    endDecrypt: PropTypes.bool,
    currentUser: PropTypes.object,
    allFolders: PropTypes.array,
  };

  shouldComponentUpdate(nextProps, nextState) {
    return (
      nextProps.endDecrypt ||
      nextProps.searchQuery !== this.props.searchQuery ||
      nextProps.filtered !== this.props.filtered ||
      nextProps.folders.length !== this.props.folders.length ||
      nextProps.isDragging !== this.props.isDragging
    );
  }

  render() {
    const { allFolders, currentUser } = this.props;
    const className = classNames('secret-list-content-table', {
      'secret-list-content-table--is-dragging': this.props.isDragging,
    });
    const fuzzyRegexp = new RegExp(
      this.props.searchQuery
        .split('')
        .map(c => escapeRegExp(c))
        .join('.*'),
      'i'
    );

    let filteredSecrets = this.props.secrets.filter(secret =>
      fuzzyRegexp.test(secret.title)
    );

    let filteredFolders = {};
    let sortedFolders = [];

    const getUser = (users, username) =>
      users.find(user => user.id === username);

    if (this.props.filtered) {
      filteredSecrets.forEach(secret => {
        let folder = 'ROOT';
        const user = getUser(secret.users, currentUser.username);
        if (user) folder = Object.keys(user.folders)[0];
        if (typeof folder === 'undefined') {
          folder = 'ROOT';
        }
        set(filteredFolders, `${folder}.secrets.${secret.id}`, secret);
        if (folder === 'ROOT') {
          filteredFolders[folder].name = '';
          filteredFolders[folder].root = true;
        } else {
          let root = false;
          let breadcrumb = [];
          let fullName = [];
          let currentFolder = folder;
          while (!root) {
            const currentFolderDetails = allFolders.find(
              fold => fold.id === currentFolder
            );
            fullName.unshift(currentFolderDetails.title);
            root = Object.keys(
              getUser(currentFolderDetails.users, currentUser.username).folders
            ).includes('ROOT');

            breadcrumb.unshift(currentFolder);
            currentFolder = Object.keys(
              getUser(currentFolderDetails.users, currentUser.username).folders
            )[0];
          }
          filteredFolders[folder].name = fullName.join('/');
          filteredFolders[folder].breadcrumb = breadcrumb;
        }
      });
      sortedFolders = Object.entries(filteredFolders).map(([id, folder]) => ({
        ...folder,
        id,
      }));
      sortedFolders.sort((a, b) =>
        a.name.toLowerCase().localeCompare(b.name.toLowerCase())
      );
      sortedFolders.sort((a, b) => a.root);
    } else {
      filteredSecrets.sort((a, b) =>
        a.title.toLowerCase().localeCompare(b.title.toLowerCase())
      );
    }

    const renderFilteredRow = ({ index, key, style }) => {
      const folder = sortedFolders[index];
      return (

          <SecretListFolderInfo key={folder.id} folder={folder} />

      );
    };

    const renderStandardRow = ({ index, key, style }) => {
      const secret = filteredSecrets[index];
      if (secret.type === 'folder') console.log('rendering folder');
      return (

          <SecretListItem
            key={secret.id}
            secret={secret}
            folders={this.props.folders}
          />

      );
    };

    return (

          <AutoSizer>
            {({ width, height }) => {
              return (
                <List
                  width={width}
                  height={height}
                  rowHeight={50}
                  rowRenderer={
                    this.props.filtered ? renderFilteredRow : renderStandardRow
                  }
                  rowCount={
                    this.props.filtered
                      ? sortedFolders.length
                      : filteredSecrets.length
                  }
                />
              );
            }}
          </AutoSizer>

    );
  }
}

const mapStateToProps = state => {
  const { currentUser } = state.AppUI;
  const allFolders =
    Object.values(state.Metadata.metadata).filter(
      secret => secret.type === 'folder'
    ) || [];

  return {
    currentUser,
    allFolders,
  };
};

export default connect(mapStateToProps)(SecretListContent);
<commit_msg>remove buggy shouldComponentUpdate from SecretListContent<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { escapeRegExp, set } from 'lodash';
import { List, AutoSizer } from 'react-virtualized';

import SecretListItem from 'components/secrets/SecretListItem';
import SecretListFolderInfo from 'components/secrets/SecretListFolderInfo';

class SecretListContent extends Component {
  static propTypes = {
    filtered: PropTypes.bool,
    secrets: PropTypes.array,
    isDragging: PropTypes.bool,
    folders: PropTypes.array,
    searchQuery: PropTypes.string,
    endDecrypt: PropTypes.bool,
    currentUser: PropTypes.object,
    allFolders: PropTypes.array,
  };

  render() {
    const { allFolders, currentUser } = this.props;
    const className = classNames('secret-list-content-table', {
      'secret-list-content-table--is-dragging': this.props.isDragging,
    });
    const fuzzyRegexp = new RegExp(
      this.props.searchQuery
        .split('')
        .map(c => escapeRegExp(c))
        .join('.*'),
      'i'
    );

    let filteredSecrets = this.props.secrets.filter(secret =>
      fuzzyRegexp.test(secret.title)
    );

    let filteredFolders = {};
    let sortedFolders = [];

    const getUser = (users, username) =>
      users.find(user => user.id === username);

    if (this.props.filtered) {
      filteredSecrets.forEach(secret => {
        let folder = 'ROOT';
        const user = getUser(secret.users, currentUser.username);
        if (user) folder = Object.keys(user.folders)[0];
        if (typeof folder === 'undefined') {
          folder = 'ROOT';
        }
        set(filteredFolders, `${folder}.secrets.${secret.id}`, secret);
        if (folder === 'ROOT') {
          filteredFolders[folder].name = '';
          filteredFolders[folder].root = true;
        } else {
          let root = false;
          let breadcrumb = [];
          let fullName = [];
          let currentFolder = folder;
          while (!root) {
            const currentFolderDetails = allFolders.find(
              fold => fold.id === currentFolder
            );
            fullName.unshift(currentFolderDetails.title);
            root = Object.keys(
              getUser(currentFolderDetails.users, currentUser.username).folders
            ).includes('ROOT');

            breadcrumb.unshift(currentFolder);
            currentFolder = Object.keys(
              getUser(currentFolderDetails.users, currentUser.username).folders
            )[0];
          }
          filteredFolders[folder].name = fullName.join('/');
          filteredFolders[folder].breadcrumb = breadcrumb;
        }
      });
      sortedFolders = Object.entries(filteredFolders).map(([id, folder]) => ({
        ...folder,
        id,
      }));
      sortedFolders.sort((a, b) =>
        a.name.toLowerCase().localeCompare(b.name.toLowerCase())
      );
      sortedFolders.sort((a, b) => a.root);
    } else {
      filteredSecrets.sort((a, b) =>
        a.title.toLowerCase().localeCompare(b.title.toLowerCase())
      );
    }

    const renderFilteredRow = ({ index, key, style }) => {
      const folder = sortedFolders[index];
      return (

          <SecretListFolderInfo key={folder.id} folder={folder} />

      );
    };

    const renderStandardRow = ({ index, key, style }) => {
      const secret = filteredSecrets[index];
      if (secret.type === 'folder') console.log('rendering folder');
      return (

          <SecretListItem
            key={secret.id}
            secret={secret}
            folders={this.props.folders}
          />

      );
    };

    return (

          <AutoSizer>
            {({ width, height }) => {
              return (
                <List
                  width={width}
                  height={height}
                  rowHeight={50}
                  rowRenderer={
                    this.props.filtered ? renderFilteredRow : renderStandardRow
                  }
                  rowCount={
                    this.props.filtered
                      ? sortedFolders.length
                      : filteredSecrets.length
                  }
                />
              );
            }}
          </AutoSizer>

    );
  }
}

const mapStateToProps = state => {
  const { currentUser } = state.AppUI;
  const allFolders =
    Object.values(state.Metadata.metadata).filter(
      secret => secret.type === 'folder'
    ) || [];

  return {
    currentUser,
    allFolders,
  };
};

export default connect(mapStateToProps)(SecretListContent);
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket 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.
*/

'use strict';

var React = require('react');
var filesize = require('filesize');

var MatrixClientPeg = require('../../../MatrixClientPeg');
var Modal = require('../../../Modal');
var sdk = require('../../../index');

module.exports = React.createClass({
    displayName: 'MVideoBody',

    thumbScale: function(fullWidth, fullHeight, thumbWidth, thumbHeight) {
        if (!fullWidth || !fullHeight) {
            // Cannot calculate thumbnail height for image: missing w/h in metadata. We can't even
            // log this because it's spammy
            return undefined;
        }
        if (fullWidth < thumbWidth && fullHeight < thumbHeight) {
            // no scaling needs to be applied
            return fullHeight;
        }
        var widthMulti = thumbWidth / fullWidth;
        var heightMulti = thumbHeight / fullHeight;
        if (widthMulti < heightMulti) {
            // width is the dominant dimension so scaling will be fixed on that
            return widthMulti;
        }
        else {
            // height is the dominant dimension so scaling will be fixed on that
            return heightMulti;
        }
    },

    render: function() {
        var content = this.props.mxEvent.getContent();
        var cli = MatrixClientPeg.get();

        var height = null;
        var width = null;
        var poster = null;
        var preload = "metadata";
        if (content.info) {
            var scale = this.thumbScale(content.info.w, content.info.h, 480, 360);
            if (scale) {
                width = Math.floor(content.info.w * scale);
                height = Math.floor(content.info.h * scale);
            }

            if (content.info.thumbnail_url) {
                poster = cli.mxcUrlToHttp(content.info.thumbnail_url);
                preload = "none";
            }
        }

        return (

                <video className="mx_MVideoBody" src={cli.mxcUrlToHttp(content.url)} alt={content.body}
                    controls preload={preload} autoPlay={false}
                    height={height} width={width} poster={poster}>
                </video>

        );
    },
});
<commit_msg>Fix enourmous video bug<commit_after>/*
Copyright 2015, 2016 OpenMarket 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.
*/

'use strict';

var React = require('react');
var filesize = require('filesize');

var MatrixClientPeg = require('../../../MatrixClientPeg');
var Modal = require('../../../Modal');
var sdk = require('../../../index');

module.exports = React.createClass({
    displayName: 'MVideoBody',

    thumbScale: function(fullWidth, fullHeight, thumbWidth, thumbHeight) {
        if (!fullWidth || !fullHeight) {
            // Cannot calculate thumbnail height for image: missing w/h in metadata. We can't even
            // log this because it's spammy
            return undefined;
        }
        if (fullWidth < thumbWidth && fullHeight < thumbHeight) {
            // no scaling needs to be applied
            return 1;
        }
        var widthMulti = thumbWidth / fullWidth;
        var heightMulti = thumbHeight / fullHeight;
        if (widthMulti < heightMulti) {
            // width is the dominant dimension so scaling will be fixed on that
            return widthMulti;
        }
        else {
            // height is the dominant dimension so scaling will be fixed on that
            return heightMulti;
        }
    },

    render: function() {
        var content = this.props.mxEvent.getContent();
        var cli = MatrixClientPeg.get();

        var height = null;
        var width = null;
        var poster = null;
        var preload = "metadata";
        if (content.info) {
            var scale = this.thumbScale(content.info.w, content.info.h, 480, 360);
            if (scale) {
                width = Math.floor(content.info.w * scale);
                height = Math.floor(content.info.h * scale);
            }

            if (content.info.thumbnail_url) {
                poster = cli.mxcUrlToHttp(content.info.thumbnail_url);
                preload = "none";
            }
        }

        return (

                <video className="mx_MVideoBody" src={cli.mxcUrlToHttp(content.url)} alt={content.body}
                    controls preload={preload} autoPlay={false}
                    height={height} width={width} poster={poster}>
                </video>

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


<commit_before>import { HotModuleReplacementPlugin } from 'webpack'
import HappyPack from 'happypack'
import path from 'path'
import fileExtensions from '../../file-extensions'
import actions from '../../actions'

export default {
  name: 'javaScript',
  configure ({ action, projectPath, javaScript = {}, coverage, browsers }) {
    return {
      plugins: [
        new HappyPack({
          id: 'babel',
          cache: false,
          verbose: false,
          tempDir: path.resolve(projectPath, '.sagui/happypack'),
          loaders: [{
            path: 'babel-loader',
            query: {
              babelrc: false,
              presets: [
                [require.resolve('babel-preset-env'), {
                  // Replaces require("babel-polyfill")
                  // with only the polyfills you need
                  // for the target browsers
                  useBuiltIns: true,

                  // Disables ES6 module transformation
                  // which Webpack2 can understand
                  // except while running tests
                  // to support inject-loader
                  modules: action === actions.TEST_UNIT ? 'commonjs' : false,

                  targets: {
                    // Unfortunately we are bound to what UglifyJS
                    // currently supports as language features
                    // https://github.com/babel/babel-preset-env#targetsuglify
                    uglify: true,

                    browsers
                  }
                }],
                require.resolve('babel-preset-flow'),
                require.resolve('babel-preset-react'),
                require.resolve('babel-preset-stage-3')
              ],
              plugins: [
                // Better React warnings and stack traces in development and testing
                // Might no longer be needed in the future
                // see: https://github.com/babel/babel/issues/4702
                ...(action === actions.DEVELOP || action === actions.TEST_UNIT ? [
                  [require.resolve('babel-plugin-transform-react-jsx-source'), {}],
                  [require.resolve('babel-plugin-transform-react-jsx-self'), {}]
                ] : []),

                ...(action === actions.TEST_UNIT && coverage ? [
                  [require.resolve('babel-plugin-istanbul'), {
                    exclude: [
                      '**/*.spec.*',
                      '**/node_modules/**/*'
                    ]
                  }]
                ] : [])
              ]
            }
          }]
        }),
        ...(action === actions.DEVELOP ? [new HotModuleReplacementPlugin()] : [])
      ],

      module: {
        rules: [
          {
            test: fileExtensions.test.JAVASCRIPT,
            enforce: 'pre',
            loader: 'eslint-loader',
            exclude: /node_modules/,
            options: {
              configFile: path.join(projectPath, '.eslintrc'),
              useEslintrc: false,
              cwd: projectPath
            }
          },
          {
            test: fileExtensions.test.JAVASCRIPT,
            exclude: javaScript.transpileDependencies && javaScript.transpileDependencies.length > 0
              ? buildExcludeCheck(javaScript.transpileDependencies)
              : /node_modules/,
            loader: 'happypack/loader?id=babel'
          }
        ]
      }
    }
  }
}

/**
 * Take into consideration if the user wants any dependency
 * to be transpiled with Babel and returns an exclude check
 * function that can be used by Webpack
 */
function buildExcludeCheck (transpileDependencies = []) {
  const dependencyChecks = transpileDependencies.map((dependency) => (
    new RegExp(`node_modules.${dependency}`)
  ))

  // see: https://webpack.js.org/configuration/module/#condition
  return function (assetPath) {
    const shouldTranspile = dependencyChecks
      .reduce((result, check) => result || assetPath.match(check), false)

    if (shouldTranspile) { return false }
    return !!assetPath.match(/node_modules/)
  }
}
<commit_msg>Enable cache of transliped code<commit_after>import { HotModuleReplacementPlugin } from 'webpack'
import HappyPack from 'happypack'
import path from 'path'
import fileExtensions from '../../file-extensions'
import actions from '../../actions'

export default {
  name: 'javaScript',
  configure ({ action, projectPath, javaScript = {}, coverage, browsers }) {
    return {
      plugins: [
        new HappyPack({
          id: 'babel',
          cache: false,
          verbose: false,
          tempDir: path.resolve(projectPath, '.sagui/happypack'),
          loaders: [{
            path: 'babel-loader',
            query: {
              babelrc: false,
              cacheDirectory: path.resolve(projectPath, '.sagui/babel'),
              presets: [
                [require.resolve('babel-preset-env'), {
                  // Replaces require("babel-polyfill")
                  // with only the polyfills you need
                  // for the target browsers
                  useBuiltIns: true,

                  // Disables ES6 module transformation
                  // which Webpack2 can understand
                  // except while running tests
                  // to support inject-loader
                  modules: action === actions.TEST_UNIT ? 'commonjs' : false,

                  targets: {
                    // Unfortunately we are bound to what UglifyJS
                    // currently supports as language features
                    // https://github.com/babel/babel-preset-env#targetsuglify
                    uglify: true,

                    browsers
                  }
                }],
                require.resolve('babel-preset-flow'),
                require.resolve('babel-preset-react'),
                require.resolve('babel-preset-stage-3')
              ],
              plugins: [
                // Better React warnings and stack traces in development and testing
                // Might no longer be needed in the future
                // see: https://github.com/babel/babel/issues/4702
                ...(action === actions.DEVELOP || action === actions.TEST_UNIT ? [
                  [require.resolve('babel-plugin-transform-react-jsx-source'), {}],
                  [require.resolve('babel-plugin-transform-react-jsx-self'), {}]
                ] : []),

                ...(action === actions.TEST_UNIT && coverage ? [
                  [require.resolve('babel-plugin-istanbul'), {
                    exclude: [
                      '**/*.spec.*',
                      '**/node_modules/**/*'
                    ]
                  }]
                ] : [])
              ]
            }
          }]
        }),
        ...(action === actions.DEVELOP ? [new HotModuleReplacementPlugin()] : [])
      ],

      module: {
        rules: [
          {
            test: fileExtensions.test.JAVASCRIPT,
            enforce: 'pre',
            loader: 'eslint-loader',
            exclude: /node_modules/,
            options: {
              configFile: path.join(projectPath, '.eslintrc'),
              useEslintrc: false,
              cwd: projectPath
            }
          },
          {
            test: fileExtensions.test.JAVASCRIPT,
            exclude: javaScript.transpileDependencies && javaScript.transpileDependencies.length > 0
              ? buildExcludeCheck(javaScript.transpileDependencies)
              : /node_modules/,
            loader: 'happypack/loader?id=babel'
          }
        ]
      }
    }
  }
}

/**
 * Take into consideration if the user wants any dependency
 * to be transpiled with Babel and returns an exclude check
 * function that can be used by Webpack
 */
function buildExcludeCheck (transpileDependencies = []) {
  const dependencyChecks = transpileDependencies.map((dependency) => (
    new RegExp(`node_modules.${dependency}`)
  ))

  // see: https://webpack.js.org/configuration/module/#condition
  return function (assetPath) {
    const shouldTranspile = dependencyChecks
      .reduce((result, check) => result || assetPath.match(check), false)

    if (shouldTranspile) { return false }
    return !!assetPath.match(/node_modules/)
  }
}
<|endoftext|>


<commit_before>define(['angular', '../../moduleDef'], function (angular, module) {
	module.directive('inlineLookup', ['$timeout', function($timeout) {
		return {
			restrict: 'E',
			replace: true,
			transclude: true,
			template: function(elm, attr) {
				var viewTmpl = attr.hasOwnProperty('multiple')
					? '

'
					: '{{ ' + attr.model + '.text }}';

				var editTmpl = '<input type="text" ng-model="emodel.value" ng-readonly="waiting"' +
					' lookup="' + attr.inputLookup + '"' +
					' class="form-control ' + (attr.inputClass ? attr.inputClass + '"' : '"') +
					(attr.hasOwnProperty('required')
						? (attr.hasOwnProperty('multiple') ? ' required-multiple="true"' : ' ng-required="true"')
						: '') +
					(attr.hasOwnProperty('multiple') ? ' multiple="multiple"' : '') +
					' lookup-options="{openOnEnter: false' +
						(attr.inputLookupOptions ?  + ', ' + attr.inputLookupOptions : '') + '}"></input>';

				//margin-bottom in form is hack - strange margin from top on enter in edit mode
				//can't fix another
				var tmpl =
	'
' +
	'	' + viewTmpl + '<inline-none></inline-none>' +
	'	<form name="editForm" ng-show="editMode" ng-class="{\'has-error\': editForm.$invalid}" style="width: 100%; margin-bottom: 0px" novalidate>' +
	'
' +
	editTmpl +
	'		<inline-buttons class="input-group-btn" style="vertical-align: top"></inline-buttons>' +
	'
' +
	'	</form>' +
	'
'; return tmpl;
			},
			link: function(scope, elm, attr) {
				//select2 not initialized if call without timeout
				$timeout(function() {
					//inplaceEdit use this for focus() when enter in edit mode
					scope.elInput = attr.hasOwnProperty('multiple')
						? $('input.select2-input', elm)
						: $('.select2-focusser', elm);

					var $input = $('input', elm);
					//select2 has self specific blur
					$input.off('blur', scope.onBlur);

					$input.on('select2-blur', scope.onBlur);
					$input.on('select2-opening', function(e) {
						$input.off('select2-blur', scope.onBlur);
					});
					$input.on('select2-close', function(e) {
						//if attach without timeout, blur handled right after close
						$timeout(function() {
							$input.on('select2-blur', scope.onBlur);
							//console.log('lookup focused: %s', $input.is(':focus'));
							if (!attr.hasOwnProperty('multiple')) {
								scope.onBlur();
							} else {
								// $timeout(function() {
								// 	console.log('close select2Change: %s', scope.select2Change);
								// 	if (!angular.isDefined(scope.select2Change) || scope.select2Change === false) {
								// 		//scope.onBlur();
								// 	}
								// }, 10);
								//console.log('lookup focused: %s', $input.is(':focus'));
							}
						});
						return false;
					});
					$input.on('select2-focus', function(e) {
						$(this).select2('open');
					});
					// $input.on('change', function(e) {
					// 	scope.select2Change = true;
					// 	console.log('change select2Change: %s', scope.select2Change);
					// });
					//enter and esc handling does not work, because of killEvent in select2 code
				}, 50);
			}
		};
	}]);
});<commit_msg>fix лукапов в задачах<commit_after>define(['angular', '../../moduleDef'], function (angular, module) {
	module.directive('inlineLookup', ['$timeout', function($timeout) {
		return {
			restrict: 'E',
			replace: true,
			transclude: true,
			template: function(elm, attr) {
				var viewTmpl = attr.hasOwnProperty('multiple') ?
					'

'	: '{{ ' + attr.model + '.text }}';

				var editTmpl = '<input type="text" ng-model="emodel.value" ng-readonly="waiting"' +
					' lookup="' + attr.inputLookup + '"' +
					' class="form-control ' + (attr.inputClass ? attr.inputClass + '"' : '"') +
					(attr.hasOwnProperty('required') ? (attr.hasOwnProperty('multiple') ?
						' required-multiple="true"' : ' ng-required="true"') : '') +
					(attr.hasOwnProperty('multiple') ? ' multiple="multiple"' : '') +
					' lookup-options="{openOnEnter: false' +
						(attr.inputLookupOptions ?  + ', ' + attr.inputLookupOptions : '') + '}"></input>';

				//margin-bottom in form is hack - strange margin from top on enter in edit mode
				//can't fix another
				var tmpl =
	'
' +
	'	' + viewTmpl + '<inline-none></inline-none>' +
	'	<form name="editForm" ng-show="editMode" ng-class="{\'has-error\': editForm.$invalid}" style="width: 100%; margin-bottom: 0px" novalidate>' +
	'
' +
	editTmpl +
	'		<inline-buttons class="input-group-btn" style="vertical-align: top"></inline-buttons>' +
	'
' +
	'	</form>' +
	'
'; return tmpl;
			},
			link: function(scope, elm, attr) {
				//select2 not initialized if call without timeout
				$timeout(function() {
					//inplaceEdit use this for focus() when enter in edit mode
					scope.elInput = attr.hasOwnProperty('multiple')	?
						$('input.select2-input', elm) : $('.select2-focusser', elm);

					scope.onFocus = function() {
						$(this).select2('open');
					};

					var $input = $('input', elm);
					//select2 has self specific blur
					$input.off('blur', scope.onBlur);

					$input.on('select2-blur', scope.onBlur);
					$input.on('select2-focus', scope.onFocus);

					$input.on('select2-opening', function(e) {
						$input.off('select2-blur', scope.onBlur);
						$input.off('select2-focus', scope.onFocus);
					});
					$input.on('select2-close', function(e) {
						$timeout(function() {
							$input.on('select2-blur', scope.onBlur);
							$input.on('select2-focus', scope.onFocus);

							if (!attr.hasOwnProperty('multiple')) {
								scope.onBlur();
							}
						});
						return false;
					});
				}, 50);
			}
		};
	}]);
});<|endoftext|>


<commit_before>/**
 * Sustainable Solutions (NZ) Ltd. 2020
 * mSupply Mobile
 */

import Realm from 'realm';
import moment from 'moment';

export class TemperatureBreach extends Realm.Object {
  get maximumTemperature() {
    return this.temperatureLogs.max('temperature');
  }

  get minimumTemperature() {
    return this.temperatureLogs.min('temperature');
  }

  get temperatureExposure() {
    const { maximumTemperature, minimumTemperature } = this;
    return { maximumTemperature, minimumTemperature };
  }

  get duration() {
    return moment
      .duration(moment(this.endTimestamp).diff(moment(this.startTimestamp)))
      .asMilliseconds();
  }

  affectedBatches(database) {
    return this.location.batchesAtTime(database, this.endTimestamp);
  }

  numberOfAffectedBatches(database) {
    return this.affectedBatches(database)?.length ?? 0;
  }

  affectedQuantity(database) {
    const affectedBatches = this.affectedBatches(database);

    if (!affectedBatches?.length) return 0;

    const itemBatchQuery = affectedBatches.map(({ id }) => `itemBatch.id == "${id}"`).join(' OR ');
    const transactionBatches = database.objects('TransactionBatch').filtered(itemBatchQuery);

    const incomingStock = transactionBatches.filtered(
      'transaction.confirmDate < $0 && (transaction.type == $1 || transaction.type == $2)',
      this.endTimestamp,
      'supplier_invoice',
      'customer_credit'
    );

    const outgoingStock = transactionBatches.filtered(
      'transaction.confirmDate < $0 && (transaction.type == $1 || transaction.type == $2)',
      this.endTimestamp,
      'customer_invoice',
      'supplier_credit'
    );

    return incomingStock.sum('numberOfPacks') ?? 0 - outgoingStock.sum('numberOfPacks') ?? 0;
  }

  willContinueBreach(temperatureLog) {
    const { minimumTemperature, maximumTemperature } = this.temperatureBreachConfiguration;
    const { temperature } = temperatureLog;

    return temperature >= minimumTemperature && temperature <= maximumTemperature;
  }
}

TemperatureBreach.schema = {
  name: 'TemperatureBreach',
  primaryKey: 'id',
  properties: {
    id: 'string',
    temperatureLogs: { type: 'linkingObjects', objectType: 'TemperatureLog', property: 'breach' },
    startTimestamp: { type: 'date', optional: true },
    endTimestamp: { type: 'date', optional: true },
    location: { type: 'Location', optional: true },
    temperatureBreachConfiguration: { type: 'TemperatureBreachConfiguration', optional: false },
  },
};

export default TemperatureBreach;
<commit_msg>Add couple of TemperatureBreach getters for VaccineChart<commit_after>/**
 * Sustainable Solutions (NZ) Ltd. 2020
 * mSupply Mobile
 */

import Realm from 'realm';
import moment from 'moment';

export class TemperatureBreach extends Realm.Object {
  get maximumTemperature() {
    return this.temperatureLogs.max('temperature');
  }

  get minimumTemperature() {
    return this.temperatureLogs.min('temperature');
  }

  get temperatureExposure() {
    const { maximumTemperature, minimumTemperature } = this;
    return { maximumTemperature, minimumTemperature };
  }

  get temperature() {
    return this.temperatureLogs?.[0]?.temperature ?? 0;
  }

  get timestamp() {
    return this.temperatureLogs?.[0]?.timestamp ?? new Date(null);
  }

  get duration() {
    return moment
      .duration(moment(this.endTimestamp).diff(moment(this.startTimestamp)))
      .asMilliseconds();
  }

  affectedBatches(database) {
    return this.location.batchesAtTime(database, this.endTimestamp);
  }

  numberOfAffectedBatches(database) {
    return this.affectedBatches(database)?.length ?? 0;
  }

  affectedQuantity(database) {
    const affectedBatches = this.affectedBatches(database);

    if (!affectedBatches?.length) return 0;

    const itemBatchQuery = affectedBatches.map(({ id }) => `itemBatch.id == "${id}"`).join(' OR ');
    const transactionBatches = database.objects('TransactionBatch').filtered(itemBatchQuery);

    const incomingStock = transactionBatches.filtered(
      'transaction.confirmDate < $0 && (transaction.type == $1 || transaction.type == $2)',
      this.endTimestamp,
      'supplier_invoice',
      'customer_credit'
    );

    const outgoingStock = transactionBatches.filtered(
      'transaction.confirmDate < $0 && (transaction.type == $1 || transaction.type == $2)',
      this.endTimestamp,
      'customer_invoice',
      'supplier_credit'
    );

    return incomingStock.sum('numberOfPacks') ?? 0 - outgoingStock.sum('numberOfPacks') ?? 0;
  }

  willContinueBreach(temperatureLog) {
    const { minimumTemperature, maximumTemperature } = this.temperatureBreachConfiguration;
    const { temperature } = temperatureLog;

    return temperature >= minimumTemperature && temperature <= maximumTemperature;
  }
}

TemperatureBreach.schema = {
  name: 'TemperatureBreach',
  primaryKey: 'id',
  properties: {
    id: 'string',
    temperatureLogs: { type: 'linkingObjects', objectType: 'TemperatureLog', property: 'breach' },
    startTimestamp: { type: 'date', optional: true },
    endTimestamp: { type: 'date', optional: true },
    location: { type: 'Location', optional: true },
    temperatureBreachConfiguration: { type: 'TemperatureBreachConfiguration', optional: false },
  },
};

export default TemperatureBreach;
<|endoftext|>


<commit_before>/*!
 * zepto.fullpage.js v0.3.1 (https://github.com/yanhaijing/zepto.fullpage)
 * API https://github.com/yanhaijing/zepto.fullpage/blob/master/doc/api.md
 * Copyright 2014 yanhaijing. All Rights Reserved
 * Licensed under MIT (https://github.com/yanhaijing/zepto.fullpage/blob/master/LICENSE)
 */
(function(window) {
    document.addEventListener('touchmove', function(e) {
        e.preventDefault();
    });
    var d = {
        page: '.page',
        start: 0,
        duration: 500,
        loop: false,
        drag: false,
        dir: 'v',
        change: function(data) {},
        beforeChange: function(data) {},
        afterChange: function(data) {},
        orientationchange: function(orientation) {}
    };

    function fix(cur, pagesLength, loop) {
        if (cur < 0) {
            return !!loop ? pagesLength - 1 : 0;
        }

        if (cur >= pagesLength) {
            return !!loop ? 0 : pagesLength - 1;
        }

        return cur;
    }

    function move(ele, dir, dist) {
        var xPx = "0px" , yPx = "0px";
        if(dir === 'v') yPx = dist+"px";
        else xPx = dist + "px";
        ele.style.cssText += (';-webkit-transform : translate3d(' + xPx + ', ' + yPx + ', 0px);' +
                                'transform : translate3d(' + xPx + ', ' + yPx + ', 0px);');
    }

    function init(option) {
        var o = option ? option : {};
        for (var key in d) {
            if(!o.hasOwnProperty(key)){
                o[key] = d[key];
            }
        }

        var that = this;
        that.curIndex = -1;
        that.o = o;

        that.startY = 0;
        that.movingFlag = false;

        that.ele.classList.add('fullPage-wp');
        that.parentEle = that.ele.parentNode;

        var query = o.page;
        if(query.indexOf(".")==0){
            query = query.substring(1, query.length);
        }
        that.pageEles = that.ele.getElementsByClassName(query);
        for (var i = 0; i < that.pageEles.length; i++) {
            var pageEle = that.pageEles[i];
            pageEle.classList.add('fullPage-page');
            pageEle.classList.add('fullPage-dir-' + o.dir);
        }

        that.pagesLength = that.pageEles.length;
        that.update();
        that.initEvent();
        that.status = 1;
    }

    function Fullpage(ele, option) {
        this.ele = ele;
        init.call(this, option);
    }
    Fullpage.prototype.update = function() {
        if (this.o.dir === 'h') {
            this.width = this.parentEle.offsetWidth;
            for (var i = 0; i < this.pageEles.length; i++) {
                var pageEle = this.pageEles[i];
                pageEle.style.width = this.width+ "px";
            }
            this.ele.style.width = (this.width * this.pagesLength)+ "px";
        }

        this.height = this.parentEle.offsetHeight;
        for (var i = 0; i < this.pageEles.length; i++) {
            var pageEle = this.pageEles[i];
            pageEle.style.height = this.height + "px";
        }

        this.moveTo(this.curIndex < 0 ? this.o.start : this.curIndex);
    };

    Fullpage.prototype.initEvent = function() {
        var that = this;
        var ele = that.ele;

        ele.addEventListener('touchstart', function(e) {
            if (!that.status) {return 1;}
            //e.preventDefault();
            if (that.movingFlag) {
                return 0;
            }

            that.startX = e.targetTouches[0].pageX;
            that.startY = e.targetTouches[0].pageY;
        });
        ele.addEventListener('touchend', function(e) {
            if (!that.status) {return 1;}
            //e.preventDefault();
            if (that.movingFlag) {
                return 0;
            }

            var sub = that.o.dir === 'v' ? e.changedTouches[0].pageY - that.startY : e.changedTouches[0].pageX - that.startX;
            var der = (sub > 30 || sub < -30) ? sub > 0 ? -1 : 1 : 0;

            that.moveTo(that.curIndex + der, true);
        });
        if (that.o.drag) {
            ele.addEventListener('touchmove', function(e) {
                if (!that.status) {return 1;}
                //e.preventDefault();
                if (that.movingFlag) {
                    that.startX = e.targetTouches[0].pageX;
                    that.startY = e.targetTouches[0].pageY;
                    return 0;
                }

                var y = e.changedTouches[0].pageY - that.startY;
                if( (that.curIndex==0 && y>0) || (that.curIndex===that.pagesLength-1 && y<0) ) y/=2;
                var x = e.changedTouches[0].pageX - that.startX;
                if( (that.curIndex==0 && x>0) || (that.curIndex===that.pagesLength-1 && x<0) ) x/=2;
                var dist = (that.o.dir === 'v' ? (-that.curIndex * that.height + y) : (-that.curIndex * that.width + x));
                ele.classList.remove('anim');
                move(ele, that.o.dir, dist);
            });
        }

        // 翻转屏幕提示
        // ==============================
        window.addEventListener("orientationchange", function() {
            if (window.orientation === 180 || window.orientation === 0) {
                that.o.orientationchange('portrait');
            }
            if (window.orientation === 90 || window.orientation === -90) {
                that.o.orientationchange('landscape');
            }
        }, false);

        window.addEventListener("resize", function() {
            that.update();
        }, false);
    };

    Fullpage.prototype.start = function() {
        this.status = 1;
    };
    Fullpage.prototype.stop = function() {
        this.status = 0;
    };
    Fullpage.prototype.moveTo = function(next, anim) {
        var that = this;
        var ele = that.ele;
        var cur = that.curIndex;
        next = fix(next, that.pagesLength, that.o.loop);

        if (anim) {
            ele.classList.add('anim');
        } else {
            ele.classList.remove('anim');
        }

        if (next !== cur) {
            that.o.beforeChange({
                next: next,
                cur: cur
            });
        }

        that.movingFlag = true;
        that.curIndex = next;
        move(ele, that.o.dir, -next * (that.o.dir === 'v' ? that.height : that.width));

        if (next !== cur) {
            that.o.change({
                prev: cur,
                cur: next
            });
        }

        window.setTimeout(function() {
            that.movingFlag = false;
            if (next !== cur) {
                that.o.afterChange({
                    prev: cur,
                    cur: next
                });
                for (var i = 0; i < that.pageEles.length; i++) {
                    var pageEle = that.pageEles[i];
                    if(i === next){
                        pageEle.classList.add("cur");
                    }else{
                        pageEle.classList.remove("cur");
                    }
                }
            }
        }, that.o.duration);
    };
    Fullpage.prototype.movePrev = function(anim) {
        this.moveTo(this.curIndex - 1, anim);
    };
    Fullpage.prototype.moveNext = function(anim) {
        this.moveTo(this.curIndex + 1, anim);
    };

    Element.prototype.fullpage = function(option) {
        return new Fullpage(this, option);
    };
}(window));
<commit_msg>增加滑动阈值判断<commit_after>/*!
 * zepto.fullpage.js v0.3.1 (https://github.com/yanhaijing/zepto.fullpage)
 * API https://github.com/yanhaijing/zepto.fullpage/blob/master/doc/api.md
 * Copyright 2014 yanhaijing. All Rights Reserved
 * Licensed under MIT (https://github.com/yanhaijing/zepto.fullpage/blob/master/LICENSE)
 */
(function(window) {
    document.addEventListener('touchmove', function(e) {
        e.preventDefault();
    });
    var d = {
        page: '.page',
        start: 0,
        duration: 500,
        loop: false,
        drag: false,
        dir: 'v',
        der: 0.1,
        change: function(data) {},
        beforeChange: function(data) {},
        afterChange: function(data) {},
        orientationchange: function(orientation) {}
    };

    function fix(cur, pagesLength, loop) {
        if (cur < 0) {
            return !!loop ? pagesLength - 1 : 0;
        }

        if (cur >= pagesLength) {
            return !!loop ? 0 : pagesLength - 1;
        }

        return cur;
    }

    function move(ele, dir, dist) {
        var xPx = "0px" , yPx = "0px";
        if(dir === 'v') yPx = dist+"px";
        else xPx = dist + "px";
        ele.style.cssText += (';-webkit-transform : translate3d(' + xPx + ', ' + yPx + ', 0px);' +
                                'transform : translate3d(' + xPx + ', ' + yPx + ', 0px);');
    }

    function init(option) {
        var o = option ? option : {};
        for (var key in d) {
            if(!o.hasOwnProperty(key)){
                o[key] = d[key];
            }
        }

        var that = this;
        that.curIndex = -1;
        that.o = o;

        that.startY = 0;
        that.movingFlag = false;

        that.ele.classList.add('fullPage-wp');
        that.parentEle = that.ele.parentNode;

        var query = o.page;
        if(query.indexOf(".")==0){
            query = query.substring(1, query.length);
        }
        that.pageEles = that.ele.getElementsByClassName(query);
        for (var i = 0; i < that.pageEles.length; i++) {
            var pageEle = that.pageEles[i];
            pageEle.classList.add('fullPage-page');
            pageEle.classList.add('fullPage-dir-' + o.dir);
        }

        that.pagesLength = that.pageEles.length;
        that.update();
        that.initEvent();
        that.status = 1;
    }

    function Fullpage(ele, option) {
        this.ele = ele;
        init.call(this, option);
    }
    Fullpage.prototype.update = function() {
        if (this.o.dir === 'h') {
            this.width = this.parentEle.offsetWidth;
            for (var i = 0; i < this.pageEles.length; i++) {
                var pageEle = this.pageEles[i];
                pageEle.style.width = this.width+ "px";
            }
            this.ele.style.width = (this.width * this.pagesLength)+ "px";
        }

        this.height = this.parentEle.offsetHeight;
        for (var i = 0; i < this.pageEles.length; i++) {
            var pageEle = this.pageEles[i];
            pageEle.style.height = this.height + "px";
        }

        this.moveTo(this.curIndex < 0 ? this.o.start : this.curIndex);
    };

    Fullpage.prototype.initEvent = function() {
        var that = this;
        var ele = that.ele;

        ele.addEventListener('touchstart', function(e) {
            if (!that.status) {return 1;}
            //e.preventDefault();
            if (that.movingFlag) {
                return 0;
            }

            that.startX = e.targetTouches[0].pageX;
            that.startY = e.targetTouches[0].pageY;
        });
        ele.addEventListener('touchend', function(e) {
            if (!that.status) {return 1;}
            //e.preventDefault();
            if (that.movingFlag) {
                return 0;
            }

            var sub = that.o.dir === 'v' ? (e.changedTouches[0].pageY - that.startY)/that.height : (e.changedTouches[0].pageX - that.startX)/that.width;
            var der = (sub > that.o.der || sub < -that.o.der) ? sub > 0 ? -1 : 1 : 0;

            that.moveTo(that.curIndex + der, true);
        });
        if (that.o.drag) {
            ele.addEventListener('touchmove', function(e) {
                if (!that.status) {return 1;}
                //e.preventDefault();
                if (that.movingFlag) {
                    that.startX = e.targetTouches[0].pageX;
                    that.startY = e.targetTouches[0].pageY;
                    return 0;
                }

                var y = e.changedTouches[0].pageY - that.startY;
                if( (that.curIndex==0 && y>0) || (that.curIndex===that.pagesLength-1 && y<0) ) y/=2;
                var x = e.changedTouches[0].pageX - that.startX;
                if( (that.curIndex==0 && x>0) || (that.curIndex===that.pagesLength-1 && x<0) ) x/=2;
                var dist = (that.o.dir === 'v' ? (-that.curIndex * that.height + y) : (-that.curIndex * that.width + x));
                ele.classList.remove('anim');
                move(ele, that.o.dir, dist);
            });
        }

        // 翻转屏幕提示
        // ==============================
        window.addEventListener("orientationchange", function() {
            if (window.orientation === 180 || window.orientation === 0) {
                that.o.orientationchange('portrait');
            }
            if (window.orientation === 90 || window.orientation === -90) {
                that.o.orientationchange('landscape');
            }
        }, false);

        window.addEventListener("resize", function() {
            that.update();
        }, false);
    };

    Fullpage.prototype.start = function() {
        this.status = 1;
    };
    Fullpage.prototype.stop = function() {
        this.status = 0;
    };
    Fullpage.prototype.moveTo = function(next, anim) {
        var that = this;
        var ele = that.ele;
        var cur = that.curIndex;
        next = fix(next, that.pagesLength, that.o.loop);

        if (anim) {
            ele.classList.add('anim');
        } else {
            ele.classList.remove('anim');
        }

        if (next !== cur) {
            that.o.beforeChange({
                next: next,
                cur: cur
            });
        }

        that.movingFlag = true;
        that.curIndex = next;
        move(ele, that.o.dir, -next * (that.o.dir === 'v' ? that.height : that.width));

        if (next !== cur) {
            that.o.change({
                prev: cur,
                cur: next
            });
        }

        window.setTimeout(function() {
            that.movingFlag = false;
            if (next !== cur) {
                that.o.afterChange({
                    prev: cur,
                    cur: next
                });
                for (var i = 0; i < that.pageEles.length; i++) {
                    var pageEle = that.pageEles[i];
                    if(i === next){
                        pageEle.classList.add("cur");
                    }else{
                        pageEle.classList.remove("cur");
                    }
                }
            }
        }, that.o.duration);
    };
    Fullpage.prototype.movePrev = function(anim) {
        this.moveTo(this.curIndex - 1, anim);
    };
    Fullpage.prototype.moveNext = function(anim) {
        this.moveTo(this.curIndex + 1, anim);
    };

    Element.prototype.fullpage = function(option) {
        return new Fullpage(this, option);
    };
}(window));
<|endoftext|>