<commit_before>import React, { Component, PropTypes } from "react";
import { findDOMNode } from "react-dom";
import { observer } from "mobx-react";
import { zipWith } from "lodash";
// Nesting the ElementList here so drag and drop state is controlled by this component
import { ElementTypes } from "../../constants";
import { getPointsToSnap, snap } from "../../utils";
import ElementList from "../element-list";
import Elements from "../../elements";
import CanvasElement from "./canvas-element";
import Slide from "./slide";
import styles from "./index.css";

const padding = 40;

@observer
class SlideList extends Component {
  static contextTypes = {
    store: PropTypes.object
  };

  constructor(props) {
    super(props);

    this.state = {
      isOverPosition: null,
      isOverSlide: false,
      isDragging: false
    };
  }

  componentDidMount() {
    this.resize();

    window.addEventListener("load", this.resize);
    window.addEventListener("resize", this.resize);
  }

  componentWillUnmount() {
    window.removeEventListener("load", this.resize);
    window.removeEventListener("resize", this.resize);
  }

  showGridLine() {}

  changeIsOverState = (newIsOverPosition, dragElementType, isOverSlide) => {
    if (newIsOverPosition === null) {
      this.setState({
        isOverSlide,
        dragElementType,
        isOverPosition: null
      });

      return;
    }

    const element = Elements[dragElementType];
    const height = element.defaultHeight || element.props.height;
    const width = element.defaultWidth || element.props.width;
    const position = newIsOverPosition.concat();
    const snapOffset = [0, 0];

    position[0] -= width / 2;
    position[1] -= height / 2;

    if (!this.gridLines) {
      this.gridLines = this.context.store.gridLines;
    }

    // If position is relative to the slide add slide left and top to the values.
    if (isOverSlide) {
      position[0] += this.context.store.left;
      position[1] += this.context.store.top;

      const createSnapCallback = (isVertical, length) => (line, index) => {
        if (line === null) {
          this.refs.slide.hideGridLine(isVertical);

          return;
        }

        this.refs.slide.showGridLine(line, isVertical);

        // Index 0 = starting edge, 1 = middle, 2 = ending edge
        snapOffset[isVertical ? 0 : 1] = (length / 2 * index);

        // Set either x or y
        position[isVertical ? 0 : 1] = line + (
          isVertical ?
          // Extra pixel added for slide border
          this.context.store.left + 1 :
          this.context.store.top + 1
        );
      };

      snap(
        this.gridLines.horizontal,
        getPointsToSnap(newIsOverPosition[1], height, height / -2),
        createSnapCallback(false, height)
      );

      snap(
        this.gridLines.vertical,
        getPointsToSnap(newIsOverPosition[0], width, width / -2),
        createSnapCallback(true, width)
      );
    } else {
      this.refs.slide.hideGridLine(true);
      this.refs.slide.hideGridLine(false);
    }

    this.setState({
      isOverPosition: zipWith(position, snapOffset, (a, b) => a - b),
      isOverSlide,
      dragElementType
    });
  }

  // Keep a 4:3 ratio with the inner element centered, 30px padding
  resize = () => {
    const { offsetWidth, offsetHeight } = findDOMNode(this.refs.container);

    const effectiveWidth = Math.floor(offsetWidth - (padding * 2));
    const effectiveHeight = Math.floor(offsetHeight - (padding * 2));

    const isWidthConstrained = effectiveHeight / effectiveWidth > 0.75;

    const width = isWidthConstrained ? effectiveWidth : Math.floor(effectiveHeight / 0.75);
    const height = isWidthConstrained ? Math.floor(effectiveWidth * 0.75) : effectiveHeight;

    const left = isWidthConstrained ? padding : Math.floor((offsetWidth - width) / 2);
    const top = isWidthConstrained ? Math.floor((offsetHeight - height) / 2) : padding;

    // TODO: need better logic for handling scale and content scale
    const scale = 1;

    this.context.store.setCanvasSize({ width, height, left, top, scale });
  }

  dropElement = (elementType, position) => {
    this.refs.slide.hideGridLine(true);
    this.refs.slide.hideGridLine(false);
    this.gridLines = null;

    if (!position) {
      const slideElement = findDOMNode(this.refs.slide);
      const element = Elements[elementType];
      const height = element.defaultHeight || element.props.height;
      const width = element.defaultWidth || element.props.width;

      this.context.store.dropElement(elementType, {
        style: {
          whiteSpace: "nowrap",
          position: "absolute",
          left: (slideElement.clientWidth / 2) - (width / 2),
          top: (slideElement.clientHeight / 2) - (height / 2)
        }
      });

      return;
    }

    let [x, y] = this.state.isOverPosition;
    const { left, top } = this.context.store;

    // Extra pixel added for slide border
    x -= left + 1;
    y -= top + 1;

    this.context.store.dropElement(elementType, /* props */{
      style: {
        position: "absolute",
        left: x,
        top: y,
        whiteSpace: "nowrap"
      }
    });
  }

  render() {
    const {
      isOverPosition,
      dragElementType
    } = this.state;

    const {
      isDraggingElement,
      isDraggingSlide,
      scale,
      width,
      height,
      top,
      left
     } = this.context.store;

    const PreviewElementType = dragElementType === ElementTypes.PLOTLY ?
      ElementTypes.PLOTY_PLACEHOLDER_IMAGE :
      dragElementType;

    const component = Elements[PreviewElementType];

    return (

          <div
            style={{
              position: "absolute",
              transform: `scale(${scale})`,
              width, // Hardcoded to 1100:850 aspect ratio
              height,
              top,
              left,
              backgroundColor: "#999"
            }}
          >
            <Slide ref="slide" isOver={isOverPosition} />

          {isOverPosition &&
            <CanvasElement
              mousePosition={isOverPosition}
              scale={scale}
              component={component}
            />
          }

        <ElementList
          scale={scale}
          onIsOverCanvasChange={this.changeIsOverState}
          onDropElement={this.dropElement}
        />

    );
  }
}

export default SlideList;
<commit_msg>have new elements offset if it will overlay a sibling<commit_after>import React, { Component, PropTypes } from "react";
import { findDOMNode } from "react-dom";
import { observer } from "mobx-react";
import { zipWith } from "lodash";
// Nesting the ElementList here so drag and drop state is controlled by this component
import { ElementTypes } from "../../constants";
import { getPointsToSnap, snap } from "../../utils";
import ElementList from "../element-list";
import Elements from "../../elements";
import CanvasElement from "./canvas-element";
import Slide from "./slide";
import styles from "./index.css";

const padding = 40;

@observer
class SlideList extends Component {
  static contextTypes = {
    store: PropTypes.object
  };

  constructor(props) {
    super(props);

    this.state = {
      isOverPosition: null,
      isOverSlide: false,
      isDragging: false
    };
  }

  componentDidMount() {
    this.resize();

    window.addEventListener("load", this.resize);
    window.addEventListener("resize", this.resize);
  }

  componentWillUnmount() {
    window.removeEventListener("load", this.resize);
    window.removeEventListener("resize", this.resize);
  }

  showGridLine() {}

  changeIsOverState = (newIsOverPosition, dragElementType, isOverSlide) => {
    if (newIsOverPosition === null) {
      this.setState({
        isOverSlide,
        dragElementType,
        isOverPosition: null
      });

      return;
    }

    const element = Elements[dragElementType];
    const height = element.defaultHeight || element.props.height;
    const width = element.defaultWidth || element.props.width;
    const position = newIsOverPosition.concat();
    const snapOffset = [0, 0];

    position[0] -= width / 2;
    position[1] -= height / 2;

    if (!this.gridLines) {
      this.gridLines = this.context.store.gridLines;
    }

    // If position is relative to the slide add slide left and top to the values.
    if (isOverSlide) {
      position[0] += this.context.store.left;
      position[1] += this.context.store.top;

      const createSnapCallback = (isVertical, length) => (line, index) => {
        if (line === null) {
          this.refs.slide.hideGridLine(isVertical);

          return;
        }

        this.refs.slide.showGridLine(line, isVertical);

        // Index 0 = starting edge, 1 = middle, 2 = ending edge
        snapOffset[isVertical ? 0 : 1] = (length / 2 * index);

        // Set either x or y
        position[isVertical ? 0 : 1] = line + (
          isVertical ?
          // Extra pixel added for slide border
          this.context.store.left + 1 :
          this.context.store.top + 1
        );
      };

      snap(
        this.gridLines.horizontal,
        getPointsToSnap(newIsOverPosition[1], height, height / -2),
        createSnapCallback(false, height)
      );

      snap(
        this.gridLines.vertical,
        getPointsToSnap(newIsOverPosition[0], width, width / -2),
        createSnapCallback(true, width)
      );
    } else {
      this.refs.slide.hideGridLine(true);
      this.refs.slide.hideGridLine(false);
    }

    this.setState({
      isOverPosition: zipWith(position, snapOffset, (a, b) => a - b),
      isOverSlide,
      dragElementType
    });
  }

  // Keep a 4:3 ratio with the inner element centered, 30px padding
  resize = () => {
    const { offsetWidth, offsetHeight } = findDOMNode(this.refs.container);

    const effectiveWidth = Math.floor(offsetWidth - (padding * 2));
    const effectiveHeight = Math.floor(offsetHeight - (padding * 2));

    const isWidthConstrained = effectiveHeight / effectiveWidth > 0.75;

    const width = isWidthConstrained ? effectiveWidth : Math.floor(effectiveHeight / 0.75);
    const height = isWidthConstrained ? Math.floor(effectiveWidth * 0.75) : effectiveHeight;

    const left = isWidthConstrained ? padding : Math.floor((offsetWidth - width) / 2);
    const top = isWidthConstrained ? Math.floor((offsetHeight - height) / 2) : padding;

    // TODO: need better logic for handling scale and content scale
    const scale = 1;

    this.context.store.setCanvasSize({ width, height, left, top, scale });
  }

  dropElement = (elementType, position) => {
    this.refs.slide.hideGridLine(true);
    this.refs.slide.hideGridLine(false);
    this.gridLines = null;

    if (!position) {
      const slideElement = findDOMNode(this.refs.slide);
      const element = Elements[elementType];
      const height = element.defaultHeight || element.props.height;
      const width = element.defaultWidth || element.props.width;

      let left = (slideElement.clientWidth / 2) - (width / 2);
      let top = (slideElement.clientHeight / 2) - (height / 2);

      const positions =
        this.context.store.currentSlide.children.reduce((positionHashMap, child) => {
          const key = `${child.props.style.left}x${child.props.style.top}`;
          positionHashMap[key] = true; // eslint-disable-line no-param-reassign

          return positionHashMap;
        }, {});

      while (positions[`${left}x${top}`]) {
        left += 10;
        top += 10;
      }

      this.context.store.dropElement(elementType, {
        style: {
          whiteSpace: "nowrap",
          position: "absolute",
          left,
          top
        }
      });

      return;
    }

    let [x, y] = this.state.isOverPosition;
    const { left, top } = this.context.store;

    // Extra pixel added for slide border
    x -= left + 1;
    y -= top + 1;

    this.context.store.dropElement(elementType, /* props */{
      style: {
        position: "absolute",
        left: x,
        top: y,
        whiteSpace: "nowrap"
      }
    });
  }

  render() {
    const {
      isOverPosition,
      dragElementType
    } = this.state;

    const {
      isDraggingElement,
      isDraggingSlide,
      scale,
      width,
      height,
      top,
      left
     } = this.context.store;

    const PreviewElementType = dragElementType === ElementTypes.PLOTLY ?
      ElementTypes.PLOTY_PLACEHOLDER_IMAGE :
      dragElementType;

    const component = Elements[PreviewElementType];

    return (

          <div
            style={{
              position: "absolute",
              transform: `scale(${scale})`,
              width, // Hardcoded to 1100:850 aspect ratio
              height,
              top,
              left,
              backgroundColor: "#999"
            }}
          >
            <Slide ref="slide" isOver={isOverPosition} />

          {isOverPosition &&
            <CanvasElement
              mousePosition={isOverPosition}
              scale={scale}
              component={component}
            />
          }

        <ElementList
          scale={scale}
          onIsOverCanvasChange={this.changeIsOverState}
          onDropElement={this.dropElement}
        />

    );
  }
}

export default SlideList;
<|endoftext|>


<commit_before>'use strict';

const React = require('react');
const PropTypes = React.PropTypes;

const ResumePropTypes = require('../prop_types/resume');

function mapIcon(socialMedia) {
    const media = socialMedia.replace(/ /g, '-');
    switch (socialMedia) {
        case 'email':
            return (

            );
        case 'quora':
            return (

                    Q

            );
        default:
            return (

            );
    }
}

const SocialMedia = React.createClass({
    propTypes: {
        ulClass: PropTypes.string.isRequired,
        profiles: ResumePropTypes.profiles
    },

    render: function () {
        return (

                {this.props.profiles.map(function (profile, index) {
                    const icon = mapIcon(profile.network.toLowerCase());
                    return (

                                {icon}

 LinkedIn Profile

                    );
                })}

        );
    }
});

module.exports = SocialMedia;
<commit_msg>Update social_media.js<commit_after>'use strict';

const React = require('react');
const PropTypes = React.PropTypes;

const ResumePropTypes = require('../prop_types/resume');

function mapIcon(socialMedia) {
    const media = socialMedia.replace(/ /g, '-');
    switch (socialMedia) {
        case 'email':
            return (

            );
        case 'quora':
            return (

                    Q

            );
        default:
            return (

            );
    }
}

const SocialMedia = React.createClass({
    propTypes: {
        ulClass: PropTypes.string.isRequired,
        profiles: ResumePropTypes.profiles
    },

    render: function () {
        return (

                {this.props.profiles.map(function (profile, index) {
                    const icon = mapIcon(profile.network.toLowerCase());
                    return (

                                {icon}

                    );
                })}

        );
    }
});

module.exports = SocialMedia;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { fromJS } from 'immutable'

import { newGame } from '../actions.js'
import { toFenSelector } from '../selectors.js'
import { isValidFen } from '../fen.js'

const FenInput = styled.input.attrs({
  type: 'text'
})`
  width: 100%;
  color: ${props => props.isDefault ? 'DarkGray' : 'Black'};
  border-color: ${props => props.isValid ? 'Black' : 'Red'};
  border-width: 1px;
`

const Form = styled.form`
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(2, minmax(10em, 1fr));
`

const Caption = styled.h1`
  grid-column-start: 1;
  grid-column-end: span 2;
  place-self: center;
  margin: 10px 0 10px 0;
  font-weight: 500;
`

const Group = styled.fieldset`
  border-radius: 5px;
  border-width: 1px;
  border-color: DarkGray;
`

const FenGroup = Group.extend`
  grid-column-start: 1;
  grid-column-end: span 2;
`

const SubmitGroup = styled.fieldset`
  grid-column-start: 1;
  grid-column-end: span 2;
  justify-self: end;
  border-width: 0;
`

const BlockLabel = styled.label`
  display: block;
`

const TypeSelect = (props) => {
  const {name, value, onChange} = props

  return (
    <BlockLabel>
      Type:
      <select name={name} value={value} onChange={onChange}>
        <option value='human'>Human</option>
        <option value='ai-random'>Random</option>
        <option value='ai-minmax'>MinMax</option>
      </select>
    </BlockLabel>
  )
}

const NameSelect = (props) => {
  const {name, value, onChange} = props

  return (
    <BlockLabel>
      Name:
      <input name={name} value={value} onChange={onChange} />
    </BlockLabel>
  )
}

const DepthSelect = (props) => {
  const {name, value, onChange} = props

  return (
    <BlockLabel>
      Depth:
      <input type='number' min='1' max='9' name={name} value={value} onChange={onChange} />
    </BlockLabel>
  )
}

class NewGameDlg extends Component {
  constructor (props) {
    super(props)
    this.state = {
      data: fromJS({
        white: {
          name: props.white.name,
          type: props.white.type,
          depth: props.white.depth
        },
        black: {
          name: props.black.name,
          type: props.black.type,
          depth: props.black.depth
        },
        fen: props.fen
      })
    }

    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleChange = this.handleChange.bind(this)
  }

  handleSubmit (event) {
    const data = this.state.data

    this.props.onSubmit(data.get('white').toJS(), data.get('black').toJS(), data.get('fen'))
    event.preventDefault()
  }

  handleChange (event) {
    const target = event.target
    let value = target.value
    const name = target.name

    if (value === '' && name === 'fen') {
      value = this.props.fen
    }

    this.setState(({data}) => ({
      data: data.setIn(name.split('.'), value)
    }))

    event.preventDefault()
  }

  componentDidUpdate (prevProps, prevState) {
    if (prevProps.fen !== this.props.fen) {
      this.setState(({data}) => ({
        data: data.set('fen', this.props.fen)
      }))
    }
  }

  render () {
    const data = this.state.data

    const fen = data.get('fen')

    const isFenDefault = fen === this.props.fen
    const isFenValid = isValidFen(fen)

    const getParams = (color) => {
      switch (data.getIn([color, 'type'])) {
        case 'human': {
          return (
            <NameSelect
              name={color + '.name'}
              value={data.getIn([color, 'name'])}
              onChange={this.handleChange}
            />
          )
        }
        case 'ai-minmax': {
          return (
            <DepthSelect
              name={color + '.depth'}
              value={data.getIn([color, 'depth'])}
              onChange={this.handleChange}
            />
          )
        }
        default: {
          return null
        }
      }
    }

    const whiteParams = getParams('white')
    const blackParams = getParams('black')

    return (
      <Form onSubmit={this.handleSubmit}>

Start new game

        <Group>
          <legend>White</legend>
          <TypeSelect
            name='white.type'
            value={data.getIn(['white', 'type'])}
            onChange={this.handleChange}
          />
          { whiteParams }
        </Group>
        <Group>
          <legend>Black</legend>
          <TypeSelect
            name='black.type'
            value={data.getIn(['black', 'type'])}
            onChange={this.handleChange}
          />
          { blackParams }
        </Group>
        <FenGroup>
          <legend>FEN</legend>
          <FenInput
            name='fen'
            value={fen}
            onChange={this.handleChange}
            isDefault={isFenDefault}
            isValid={isFenValid}
          />
        </FenGroup>
        <SubmitGroup>
          <input type='submit' value='OK' />
        </SubmitGroup>
      </Form>
    )
  }
}

NewGameDlg.propTypes = {
  white: PropTypes.shape({
    name: PropTypes.string,
    type: PropTypes.string,
    depth: PropTypes.number
  }).isRequired,
  black: PropTypes.shape({
    name: PropTypes.string,
    type: PropTypes.string,
    depth: PropTypes.number
  }).isRequired,
  fen: PropTypes.string.isRequired,
  onSubmit: PropTypes.func.isRequired
}

function mapDispatchToProps (dispatch) {
  return {
    onSubmit: (white, black, fen) => {
      return dispatch(newGame(white, black, fen))
    }
  }
}

function mapStateToProps (state, ownProps) {
  return {
    white: state.white,
    black: state.black,
    fen: toFenSelector(state)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(NewGameDlg)
<commit_msg>Added missing file + fixed empty string in depth dialog<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { fromJS } from 'immutable'

import { newGame } from '../actions.js'
import { toFenSelector } from '../selectors.js'
import { isValidFen } from '../fen.js'

const FenInput = styled.input.attrs({
  type: 'text'
})`
  width: 100%;
  color: ${props => props.isDefault ? 'DarkGray' : 'Black'};
  border-color: ${props => props.isValid ? 'Black' : 'Red'};
  border-width: 1px;
`

const Form = styled.form`
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(2, minmax(10em, 1fr));
`

const Caption = styled.h1`
  grid-column-start: 1;
  grid-column-end: span 2;
  place-self: center;
  margin: 10px 0 10px 0;
  font-weight: 500;
`

const Group = styled.fieldset`
  border-radius: 5px;
  border-width: 1px;
  border-color: DarkGray;
`

const FenGroup = Group.extend`
  grid-column-start: 1;
  grid-column-end: span 2;
`

const SubmitGroup = styled.fieldset`
  grid-column-start: 1;
  grid-column-end: span 2;
  justify-self: end;
  border-width: 0;
`

const BlockLabel = styled.label`
  display: block;
`

const TypeSelect = (props) => {
  const {name, value, onChange} = props

  return (
    <BlockLabel>
      Type:
      <select name={name} value={value} onChange={onChange}>
        <option value='human'>Human</option>
        <option value='ai-random'>Random</option>
        <option value='ai-minmax'>MinMax</option>
      </select>
    </BlockLabel>
  )
}

const NameSelect = (props) => {
  const {name, value, onChange} = props

  return (
    <BlockLabel>
      Name:
      <input name={name} value={value} onChange={onChange} />
    </BlockLabel>
  )
}

const DepthSelect = (props) => {
  const {name, value, onChange} = props

  return (
    <BlockLabel>
      Depth:
      <input type='number' min='1' max='9' name={name} value={value} onChange={onChange} />
    </BlockLabel>
  )
}

class NewGameDlg extends Component {
  constructor (props) {
    super(props)
    this.state = {
      data: fromJS({
        white: {
          name: props.white.name,
          type: props.white.type,
          depth: props.white.depth
        },
        black: {
          name: props.black.name,
          type: props.black.type,
          depth: props.black.depth
        },
        fen: props.fen
      })
    }

    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleChange = this.handleChange.bind(this)
  }

  handleSubmit (event) {
    const data = this.state.data

    this.props.onSubmit(data.get('white').toJS(), data.get('black').toJS(), data.get('fen'))
    event.preventDefault()
  }

  handleChange (event) {
    const target = event.target
    let value = target.value
    const name = target.name

    if (value === '' && name === 'fen') {
      value = this.props.fen
    }

    if (name.endsWith('depth')) {
      value = parseInt(value)
      value = isNaN(value) ? 4 : value
    }

    this.setState(({data}) => ({
      data: data.setIn(name.split('.'), value)
    }))

    event.preventDefault()
  }

  componentDidUpdate (prevProps, prevState) {
    if (prevProps.fen !== this.props.fen) {
      this.setState(({data}) => ({
        data: data.set('fen', this.props.fen)
      }))
    }
  }

  render () {
    const data = this.state.data

    const fen = data.get('fen')

    const isFenDefault = fen === this.props.fen
    const isFenValid = isValidFen(fen)

    const getParams = (color) => {
      switch (data.getIn([color, 'type'])) {
        case 'human': {
          return (
            <NameSelect
              name={color + '.name'}
              value={data.getIn([color, 'name'])}
              onChange={this.handleChange}
            />
          )
        }
        case 'ai-minmax': {
          return (
            <DepthSelect
              name={color + '.depth'}
              value={data.getIn([color, 'depth'])}
              onChange={this.handleChange}
            />
          )
        }
        default: {
          return null
        }
      }
    }

    const whiteParams = getParams('white')
    const blackParams = getParams('black')

    return (
      <Form onSubmit={this.handleSubmit}>

Start new game

        <Group>
          <legend>White</legend>
          <TypeSelect
            name='white.type'
            value={data.getIn(['white', 'type'])}
            onChange={this.handleChange}
          />
          { whiteParams }
        </Group>
        <Group>
          <legend>Black</legend>
          <TypeSelect
            name='black.type'
            value={data.getIn(['black', 'type'])}
            onChange={this.handleChange}
          />
          { blackParams }
        </Group>
        <FenGroup>
          <legend>FEN</legend>
          <FenInput
            name='fen'
            value={fen}
            onChange={this.handleChange}
            isDefault={isFenDefault}
            isValid={isFenValid}
          />
        </FenGroup>
        <SubmitGroup>
          <input type='submit' value='OK' />
        </SubmitGroup>
      </Form>
    )
  }
}

NewGameDlg.propTypes = {
  white: PropTypes.shape({
    name: PropTypes.string,
    type: PropTypes.string,
    depth: PropTypes.number
  }).isRequired,
  black: PropTypes.shape({
    name: PropTypes.string,
    type: PropTypes.string,
    depth: PropTypes.number
  }).isRequired,
  fen: PropTypes.string.isRequired,
  onSubmit: PropTypes.func.isRequired
}

function mapDispatchToProps (dispatch) {
  return {
    onSubmit: (white, black, fen) => {
      return dispatch(newGame(white, black, fen))
    }
  }
}

function mapStateToProps (state, ownProps) {
  return {
    white: state.white,
    black: state.black,
    fen: toFenSelector(state)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(NewGameDlg)
<|endoftext|>


<commit_before>'use strict';

angular.module('mean.project').controller('ProjectController', ['$scope', '$http', 'Users', 'Global', 'Project',
  function($scope, $http, Users, Global, Project) {
    $scope.global = Global;
    $scope.package = {
      name: 'project'
    };
  }
])
.controller('CreateProjectCtrl', ['$scope', '$rootScope', '$http', '$location', 'Global', 'Users',
  function($scope,  $rootScope, $http, $location, Global, Users) {
    $scope.global = Global;
    if (!$scope.global.authenticated)
      return $location.url('/');

    // This will be the object filled in by the form data
    $scope.project = {};
    $scope.createError = false;

    /* Extra initialization */
    // TODO: should not hard code permissions (they'll be used else-where)
    $scope.permissionLevels = ['admin', 'general', 'view_only'];

    // make current user the project owner
    $scope.project.owner = $scope.global.user._id;

    // add starting current user as first admin user
    $scope.project.members = [
        {
            _id: $scope.global.user._id,
            name: $scope.global.user.name,
            permission: $scope.permissionLevels[0]
        }
    ];

    function validProject() {
      $scope.createError = false;
      if ($scope.project.name === undefined) {
        $scope.createError = 'Project must have a name';
        return false;
      }
      return true;
    }

    $scope.createProject = function() {
      event.preventDefault();
      if(validProject()) {
        $http.post('/projects', $scope.project)
          .success(function(res) {
            console.log(res);
            $location.url('/project/'+res._id);
          })
          .error(function() {
            alert('Could not create your project. Check network connection and try again');
          });
      }
    };

    // if the browser isn't chrome, use jquery-ui for input type date
    if (!window.chrome) {
      if($('input[type=date]')) {
        $('input[type=date]').each(function() {
          $(this).datepicker().datepicker('option', 'dateFormat', 'yy-mm-dd');
        });
      }
    }
  }
])
.controller('TeamMemberCtrl', ['$scope', '$rootScope', '$http', 'Global',
  function($scope, $rootScope, $http, $parent, Global){
    $scope.global = Global;
    $scope.searchText = '';
    $scope.searchError = false;
    $scope.searchUsersResults = [];

    function arrayObjectIndexOf(arr, obj){
      for(var i = 0; i < arr.length; i+=1){
          if(arr[i]._id === obj._id){
              return i;
          }
      }
      return false;
    }

    function filterResults() {
      $scope.project.members.forEach(function (member) {
        var index = arrayObjectIndexOf($scope.searchUsersResults, member);
        if (index !== false) {
          // remove existing members from results
          $scope.searchUsersResults.splice(index, 1);
        }
      });
    }

    $scope.searchForTeamMembers = function() {
      if(!!$scope.searchText) {
        $http({
          url: '/users',
          method: 'GET',
          params: {q: $scope.searchText}
        })
          .success(function(res) {
            $scope.searchError = false;
            $scope.searchUsersResults = res;
            if (!res.length) {
              $scope.searchError = 'No results found';
            } else {
              filterResults();
            }
          })
          .error(function() {
            $scope.searchError = 'Errors occured making your request :(';
          });
      }
    };

    $scope.removeTeamMember = function(member) {
      $scope.project.members.splice(member, 1);
    };

    $scope.addTeamMember = function(member) {
      event.preventDefault();
      $scope.project.members.push({
        _id: member._id,
        name: member.name,
        permission: $scope.permissionLevels[$scope.permissionLevels.indexOf('general')]
      });
      $scope.searchUsersResults.splice(arrayObjectIndexOf($scope.searchUsersResults, member), 1);
    };
}])
.directive('crnMessageBoard', function () {
  return {
    restrict: 'A',
    templateUrl: 'project/views/message-board.html'
  };
}
.directive('crnTeamModifer', function(){
  // Runs during compile
  return {
    restrict: 'A',
    templateUrl: 'project/views/team-finder.html'
  };
});
<commit_msg>Fixed controller error<commit_after>'use strict';

angular.module('mean.project').controller('ProjectController', ['$scope', '$http', 'Users', 'Global', 'Project',
  function($scope, $http, Users, Global, Project) {
    $scope.global = Global;
    $scope.package = {
      name: 'project'
    };
  }
])
.controller('CreateProjectCtrl', ['$scope', '$rootScope', '$http', '$location', 'Global', 'Users',
  function($scope,  $rootScope, $http, $location, Global, Users) {
    $scope.global = Global;
    if (!$scope.global.authenticated)
      return $location.url('/');

    // This will be the object filled in by the form data
    $scope.project = {};
    $scope.createError = false;

    /* Extra initialization */
    // TODO: should not hard code permissions (they'll be used else-where)
    $scope.permissionLevels = ['admin', 'general', 'view_only'];

    // make current user the project owner
    $scope.project.owner = $scope.global.user._id;

    // add starting current user as first admin user
    $scope.project.members = [
        {
            _id: $scope.global.user._id,
            name: $scope.global.user.name,
            permission: $scope.permissionLevels[0]
        }
    ];

    function validProject() {
      $scope.createError = false;
      if ($scope.project.name === undefined) {
        $scope.createError = 'Project must have a name';
        return false;
      }
      return true;
    }

    $scope.createProject = function() {
      event.preventDefault();
      if(validProject()) {
        $http.post('/projects', $scope.project)
          .success(function(res) {
            console.log(res);
            $location.url('/project/'+res._id);
          })
          .error(function() {
            alert('Could not create your project. Check network connection and try again');
          });
      }
    };

    // if the browser isn't chrome, use jquery-ui for input type date
    if (!window.chrome) {
      if($('input[type=date]')) {
        $('input[type=date]').each(function() {
          $(this).datepicker().datepicker('option', 'dateFormat', 'yy-mm-dd');
        });
      }
    }
  }
])
.controller('TeamMemberCtrl', ['$scope', '$rootScope', '$http', 'Global',
  function($scope, $rootScope, $http, $parent, Global){
    $scope.global = Global;
    $scope.searchText = '';
    $scope.searchError = false;
    $scope.searchUsersResults = [];

    function arrayObjectIndexOf(arr, obj){
      for(var i = 0; i < arr.length; i+=1){
          if(arr[i]._id === obj._id){
              return i;
          }
      }
      return false;
    }

    function filterResults() {
      $scope.project.members.forEach(function (member) {
        var index = arrayObjectIndexOf($scope.searchUsersResults, member);
        if (index !== false) {
          // remove existing members from results
          $scope.searchUsersResults.splice(index, 1);
        }
      });
    }

    $scope.searchForTeamMembers = function() {
      if(!!$scope.searchText) {
        $http({
          url: '/users',
          method: 'GET',
          params: {q: $scope.searchText}
        })
          .success(function(res) {
            $scope.searchError = false;
            $scope.searchUsersResults = res;
            if (!res.length) {
              $scope.searchError = 'No results found';
            } else {
              filterResults();
            }
          })
          .error(function() {
            $scope.searchError = 'Errors occured making your request :(';
          });
      }
    };

    $scope.removeTeamMember = function(member) {
      $scope.project.members.splice(member, 1);
    };

    $scope.addTeamMember = function(member) {
      event.preventDefault();
      $scope.project.members.push({
        _id: member._id,
        name: member.name,
        permission: $scope.permissionLevels[$scope.permissionLevels.indexOf('general')]
      });
      $scope.searchUsersResults.splice(arrayObjectIndexOf($scope.searchUsersResults, member), 1);
    };
}])
.controller('TeamMemberCtrl', ['$scope', '$rootScope', '$http', 'Global',
  function($scope, $rootScope, $http, $parent, Global) {
    $scope.global = Global;
    console.log($scope.project);

}])
.directive('crnMessageBoard', function () {
  return {
    restrict: 'A',
    templateUrl: 'project/views/message-board.html'
  };
})
.directive('crnTeamModifer', function(){
  // Runs during compile
  return {
    restrict: 'A',
    templateUrl: 'project/views/team-finder.html'
  };
});
<|endoftext|>


<commit_before>//get calling params
var args = arguments[0];
var siteID = args.siteID;

//validate form before inserting to database
function doneBtn(){
	if ($.tsctName.value == "") {
		alert('No transect name entered');
		return;
	} else if ($.srvyName.value == "") {
		alert('No survey name entered');
		return;
	//otherSrvyName skipped, other surveyors is probably optional
	} else if ($.pickStake.index == null) {
		alert('Stake orientation not selected');
		return;
	} else if ($.plotDist.value == "") {
		alert('Select a plot distance');
		return;
	//skipping comments,
	//skipping photo for now
	} else {
		//set stake orientation text
		var stakeText;
		if ($.pickStake.index == 0) {
			stakeText = "Top Left / Bottom Right";
		} else {
			stakeText = "Top Right / Bottom Left";
		}

		//Connect to database
		var db = Ti.Database.open('ltemaDB');

		//Insert Query - add row to transect table
		db.execute(	'INSERT INTO transect (transect_name,surveyor,plot_distance,stake_orientation,comments,site_id) VALUES (?,?,?,?,?,?)',
					$.tsctName.value, $.srvyName.value, $.plotDist.value, stakeText, $.comments.value, siteID);
		//Close the database
		db.close();
		//refresh and close
		Ti.App.fireEvent("app:refreshTransects");
		$.addTransect.close();
	}
}

function takePhoto() {

	//call camera module and set thumbnail
	var pic = require('camera');
	pic.getPhoto(function(myPhoto, UTMEasting, UTMNorthing, n_UTMZone) {
		//Set thumbnail
		$.transectThumbnail.image = myPhoto;

		alert("UTMEasting: " + UTMEasting + "\nUTMNorthing: " + UTMNorthing + "\nUTMZone: " + n_UTMZone);

	});
}
<commit_msg>Added other_surveyors to insert statement<commit_after>//get calling params
var args = arguments[0];
var siteID = args.siteID;

//validate form before inserting to database
function doneBtn(){
	if ($.tsctName.value == "") {
		alert('No transect name entered');
		return;
	} else if ($.srvyName.value == "") {
		alert('No survey name entered');
		return;
	//otherSrvyName skipped, other surveyors is probably optional
	} else if ($.pickStake.index == null) {
		alert('Stake orientation not selected');
		return;
	} else if ($.plotDist.value == "") {
		alert('Select a plot distance');
		return;
	//skipping comments,
	//skipping photo for now
	} else {
		//set stake orientation text
		var stakeText;
		if ($.pickStake.index == 0) {
			stakeText = "Top Left / Bottom Right";
		} else {
			stakeText = "Top Right / Bottom Left";
		}

		//Connect to database
		var db = Ti.Database.open('ltemaDB');

		//Insert Query - add row to transect table
		db.execute(	'INSERT INTO transect (transect_name,surveyor,other_surveyors,plot_distance,stake_orientation,comments,site_id) VALUES (?,?,?,?,?,?,?)',
					$.tsctName.value, $.srvyName.value, $.otherSrvyName.value, $.plotDist.value, stakeText, $.comments.value, siteID);
		//Close the database
		db.close();
		//refresh and close
		Ti.App.fireEvent("app:refreshTransects");
		$.addTransect.close();
	}
}

function takePhoto() {

	//call camera module and set thumbnail
	var pic = require('camera');
	pic.getPhoto(function(myPhoto, UTMEasting, UTMNorthing, n_UTMZone) {
		//Set thumbnail
		$.transectThumbnail.image = myPhoto;

		alert("UTMEasting: " + UTMEasting + "\nUTMNorthing: " + UTMNorthing + "\nUTMZone: " + n_UTMZone);

	});
}
<|endoftext|>


<commit_before>/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import {
  withExperimentalFeatures,
  visitDashboard,
  createNewStory,
  insertStoryTitle,
  publishStory,
  visitAdminPage,
  takeSnapshot,
  withPlugin,
} from '@web-stories-wp/e2e-test-utils';

const percyCSS = `.dashboard-grid-item-date { display: none; }`;

const storyTitle = 'Test post lock';

describe('Post Locking', () => {
  withExperimentalFeatures(['enablePostLocking']);
  withPlugin('e2e-tests-post-lock-mock');

  beforeAll(async () => {
    await createNewStory();

    await insertStoryTitle(storyTitle);

    await publishStory();
  });

  it('should be able to open the dashboard with locked story', async () => {
    await visitDashboard();

    await expect(page).toMatch('Test post lock');
    await page.hover('[data-test-id="lock-user-avatar"]');
    await expect(page).toMatch('test_locker is currently editing this story');
    await takeSnapshot(page, 'Stories Dashboard with lock', { percyCSS });
  });

  it('should be able to open the editor with locked story', async () => {
    await visitAdminPage('edit.php', 'post_type=web-story');

    await expect(page).toMatch(storyTitle);

    await Promise.all([
      page.waitForNavigation(),
      expect(page).toClick('a', { text: storyTitle }),
    ]);

    await page.waitForSelector('.ReactModal__Content');

    await expect(page).toMatch('Story is locked');

    await takeSnapshot(page, 'Stories editor with lock dialog');
  });
});
<commit_msg>Fix story locking e2e test (#10901)<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import {
  withExperimentalFeatures,
  visitDashboard,
  createNewStory,
  insertStoryTitle,
  publishStory,
  visitAdminPage,
  activatePlugin,
  deactivatePlugin,
  takeSnapshot,
} from '@web-stories-wp/e2e-test-utils';

const percyCSS = `.dashboard-grid-item-date { display: none; }`;

const storyTitle = 'Test post lock';

describe('Post Locking', () => {
  withExperimentalFeatures(['enablePostLocking']);

  beforeAll(async () => {
    await createNewStory();

    await insertStoryTitle(storyTitle);

    await publishStory();

    // Not using the withPlugin() here because this plugin
    // needs to be activated *after* creating this story.
    await activatePlugin('e2e-tests-post-lock-mock');
  });

  afterAll(async () => {
    await deactivatePlugin('e2e-tests-post-lock-mock');
  });

  it('should be able to open the dashboard with locked story', async () => {
    await visitDashboard();

    await expect(page).toMatch('Test post lock');
    await page.hover('[data-test-id="lock-user-avatar"]');
    await expect(page).toMatch('test_locker is currently editing this story');
    await takeSnapshot(page, 'Stories Dashboard with lock', { percyCSS });
  });

  it('should be able to open the editor with locked story', async () => {
    await visitAdminPage('edit.php', 'post_type=web-story');

    await expect(page).toMatch(storyTitle);

    await Promise.all([
      page.waitForNavigation(),
      expect(page).toClick('a', { text: storyTitle }),
    ]);

    await page.waitForSelector('.ReactModal__Content');

    await expect(page).toMatch('Story is locked');

    await takeSnapshot(page, 'Stories editor with lock dialog');
  });
});
<|endoftext|>


<commit_before>import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import run from "ember-metal/run_loop";

import EmberView from "ember-views/views/view";
import ContainerView from "ember-views/views/container_view";

var parentView, view;

QUnit.module("Ember.View#element", {
  teardown() {
    run(function() {
      if (parentView) { parentView.destroy(); }
      view.destroy();
    });
  }
});

QUnit.test("returns null if the view has no element and no parent view", function() {
  view = EmberView.create();
  equal(get(view, 'parentView'), null, 'precond - has no parentView');
  equal(get(view, 'element'), null, 'has no element');
});

QUnit.test("returns null if the view has no element and parent view has no element", function() {
  expectDeprecation("Setting `childViews` on a Container is deprecated.");

  parentView = ContainerView.create({
    childViews: [EmberView.extend()]
  });
  view = get(parentView, 'childViews').objectAt(0);

  equal(get(view, 'parentView'), parentView, 'precond - has parent view');
  equal(get(parentView, 'element'), null, 'parentView has no element');
  equal(get(view, 'element'), null, ' has no element');
});

QUnit.test("returns element if you set the value", function() {
  view = EmberView.create();
  equal(get(view, 'element'), null, 'precond- has no element');

  var dom = document.createElement('div');
  set(view, 'element', dom);

  equal(get(view, 'element'), dom, 'now has set element');
});

Ember.runInDebug(function() {
  QUnit.test("should not allow the elementId to be changed after inserted", function() {
    view = EmberView.create({
      elementId: 'one'
    });

    run(function() {
      view.appendTo('#qunit-fixture');
    });

    throws(function() {
      view.set('elementId', 'two');
    }, "raises elementId changed exception");

    equal(view.get('elementId'), 'one', 'elementId is still "one"');
  });
});

<commit_msg>Exclude debug only tests in production builds.<commit_after>/*globals EmberDev */

import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import run from "ember-metal/run_loop";

import EmberView from "ember-views/views/view";
import ContainerView from "ember-views/views/container_view";

var parentView, view;

QUnit.module("Ember.View#element", {
  teardown() {
    run(function() {
      if (parentView) { parentView.destroy(); }
      view.destroy();
    });
  }
});

QUnit.test("returns null if the view has no element and no parent view", function() {
  view = EmberView.create();
  equal(get(view, 'parentView'), null, 'precond - has no parentView');
  equal(get(view, 'element'), null, 'has no element');
});

QUnit.test("returns null if the view has no element and parent view has no element", function() {
  expectDeprecation("Setting `childViews` on a Container is deprecated.");

  parentView = ContainerView.create({
    childViews: [EmberView.extend()]
  });
  view = get(parentView, 'childViews').objectAt(0);

  equal(get(view, 'parentView'), parentView, 'precond - has parent view');
  equal(get(parentView, 'element'), null, 'parentView has no element');
  equal(get(view, 'element'), null, ' has no element');
});

QUnit.test("returns element if you set the value", function() {
  view = EmberView.create();
  equal(get(view, 'element'), null, 'precond- has no element');

  var dom = document.createElement('div');
  set(view, 'element', dom);

  equal(get(view, 'element'), dom, 'now has set element');
});

if (EmberDev && !EmberDev.runningProdBuild) {
  QUnit.test("should not allow the elementId to be changed after inserted", function() {
    view = EmberView.create({
      elementId: 'one'
    });

    run(function() {
      view.appendTo('#qunit-fixture');
    });

    throws(function() {
      view.set('elementId', 'two');
    }, "raises elementId changed exception");

    equal(view.get('elementId'), 'one', 'elementId is still "one"');
  });
}
<|endoftext|>


<commit_before>var os = require('os');

var Sem, Name, Batch, Examination, Institution, InstitutionCode, final = [], len = 0;	// Globals for same set of students.
var currentSubjects = [];	// Stores the names and subject codes for current set of students.
var previousResult = {};

module.exports = function (data, subjectArray, db, cb) {
	var regexForStudentsLinux = /\d{11}([^]*?)\n\w?\*?(\(.?\))?\n\w\w?\n\r/g;
	var regexForStudentsWindows = /\n\d{11}([^]*?)\n\w\w?\*?(\(..?\))?\r\n\w\w?\r/g;
	// console.log(data)
	// process.exit()
	var regexForStudents;
	if (os.platform() === 'linux') {
		regexForStudents = regexForStudentsLinux;
	} else {
		regexForStudents = regexForStudentsWindows;
	}
	data.forEach((students) => {
		// console.log(students)
		var studentList = students.match(regexForStudents);
		if (studentList) {
			studentList = studentList.map((ele) => (ele.split(os.EOL)));
			// console.log(studentList)
			Sem = students.match(/Sem\.\/Year: (\d+)/)[1];
			Name = students.match(/Programme Name: ([^]*?) Sem/)[1];
			if (students.match(/Batch: ([^]*?) Exa/)) {
				Batch = students.match(/Batch: ([^]*?) Exa/)[1];
				// if (parseInt(Batch) < 2013) {
				// 	return;
				// }
			} else {
				return;
			}
			// Institution = students.match(/Institution: ([^]*?)\r/)[1];
			Institution = students.match(new RegExp('Institution: ([^]*?)' + os.EOL))[1];
			InstitutionCode = students.match(/Institution Code: (\d+)/)[1];
			// Examination = students.match(/Examination: ([^]*?)\r\n/)[1];
			Examination = students.match(new RegExp('Examination: ([^]*?)' + os.EOL))[1];
			if (matchSubjectList()) {
				currentSubjects = subjectArray.shift();
			}
			studentList.forEach((student) => {
				console.log(student)
				if (os.platform() === 'linux') {
					// student.shift();
					student.pop();
				}
				var obj = studentBlueprint();
				if (os.platform() === 'linux') {
					obj.EnrollmentNumber = student.shift();
				} else {
					obj.EnrollmentNumber = student.shift().substr(1);
				}
				obj.Name = student.shift();
				obj.CreditsSecured = student.pop().match(/(\w+)/);
				try {
					obj.CreditsSecured = obj.CreditsSecured[1];
				} catch (e) {
					obj.CreditsSecured = '';
				}
				var present = false;
				while (student.length) {
					var marks = marksBlueprint();
					var id = student.shift();
					marks.Id = id.match(/\w+/)[0];
					marks.Name = getNameFromCurrentList(marks.Id);
					try {
						marks.Credits = id.match(/\((\w+)\)/)[1];
					} catch (e) {  }
					if (student.length) {
						marksValue = student.shift().split(' ');
					} else {
						return;
					}
					marks.Internal = marksValue[0];
					marks.External = marksValue[1];
					var total = student.shift();
					if (!total) continue;
					marks.Total = parseInt(total.match(/\w+/)[0]);
					if (isNaN(marks.Total)) {
						marks.Total = 0;
					} else {
						present = true;
					}
					if (total.match(/\((.+)\)/)) {
						marks.Grade = total.match(/\((.+)\)/)[1];
					}
					obj.Marks.push(marks);
				}
				if (!present) {
					return;
				}
				db.collection('Student').insert(obj, function (err) {
					if (err) {
						console.error(err);
					}
				});
				final[len++] = obj;
			});
		}
	});
	cb(final);
}

var studentBlueprint = function () {
	return {
		'Semester': Sem,
		'Programme': Name,
		'Batch': Batch,
		'Examination': Examination,
		'Institution': Institution,
		'CollegeCode': InstitutionCode,
		'EnrollmentNumber': null,
		'Name': null,
		'Marks': [],
		'CreditsSecured': null
	}
}

var marksBlueprint = function () {
	return {
		'Id': null,
		'Credits': null,
		'Internal': null,
		'External': null,
		'Total': null,
		'Grade': null
	}
}

var matchSubjectList = function () {
	var currentResult = studentBlueprint();
	if (JSON.stringify(currentResult) === JSON.stringify(previousResult)) {
		return false;
	}
	previousResult = currentResult;
	return true;
}

var getNameFromCurrentList = function (id) {
	// console.log('Required', id)
	for (var i = 0; i < currentSubjects.length; i++) {
		// console.log('Current', currentSubjects[i]['_id'])
		if (currentSubjects[i]['_id'] === id) {
			return currentSubjects[i]['Name'];
		}
	}
}<commit_msg>Fixing regex for linux.<commit_after>var os = require('os');

var Sem, Name, Batch, Examination, Institution, InstitutionCode, final = [], len = 0;	// Globals for same set of students.
var currentSubjects = [];	// Stores the names and subject codes for current set of students.
var previousResult = {};

module.exports = function (data, subjectArray, db, cb) {
	var regexForStudentsLinux = /\d{11}([^]*?)\n\w?\*?(\(..?\))?\n\w\w?\n\r/g;
	var regexForStudentsWindows = /\n\d{11}([^]*?)\n\w\w?\*?(\(..?\))?\r\n\w\w?\r/g;
	// console.log(data)
	// process.exit()
	var regexForStudents;
	if (os.platform() === 'linux') {
		regexForStudents = regexForStudentsLinux;
	} else {
		regexForStudents = regexForStudentsWindows;
	}
	data.forEach((students) => {
		// console.log(students)
		var studentList = students.match(regexForStudents);
		if (studentList) {
			studentList = studentList.map((ele) => (ele.split(os.EOL)));
			// console.log(studentList)
			Sem = students.match(/Sem\.\/Year: (\d+)/)[1];
			Name = students.match(/Programme Name: ([^]*?) Sem/)[1];
			if (students.match(/Batch: ([^]*?) Exa/)) {
				Batch = students.match(/Batch: ([^]*?) Exa/)[1];
				// if (parseInt(Batch) < 2013) {
				// 	return;
				// }
			} else {
				return;
			}
			// Institution = students.match(/Institution: ([^]*?)\r/)[1];
			Institution = students.match(new RegExp('Institution: ([^]*?)' + os.EOL))[1];
			InstitutionCode = students.match(/Institution Code: (\d+)/)[1];
			// Examination = students.match(/Examination: ([^]*?)\r\n/)[1];
			Examination = students.match(new RegExp('Examination: ([^]*?)' + os.EOL))[1];
			if (matchSubjectList()) {
				currentSubjects = subjectArray.shift();
			}
			studentList.forEach((student) => {
				console.log(student)
				if (os.platform() === 'linux') {
					// student.shift();
					student.pop();
				}
				var obj = studentBlueprint();
				if (os.platform() === 'linux') {
					obj.EnrollmentNumber = student.shift();
				} else {
					obj.EnrollmentNumber = student.shift().substr(1);
				}
				obj.Name = student.shift();
				obj.CreditsSecured = student.pop().match(/(\w+)/);
				try {
					obj.CreditsSecured = obj.CreditsSecured[1];
				} catch (e) {
					obj.CreditsSecured = '';
				}
				var present = false;
				while (student.length) {
					var marks = marksBlueprint();
					var id = student.shift();
					marks.Id = id.match(/\w+/)[0];
					marks.Name = getNameFromCurrentList(marks.Id);
					try {
						marks.Credits = id.match(/\((\w+)\)/)[1];
					} catch (e) {  }
					if (student.length) {
						marksValue = student.shift().split(' ');
					} else {
						return;
					}
					marks.Internal = marksValue[0];
					marks.External = marksValue[1];
					var total = student.shift();
					if (!total) continue;
					marks.Total = parseInt(total.match(/\w+/)[0]);
					if (isNaN(marks.Total)) {
						marks.Total = 0;
					} else {
						present = true;
					}
					if (total.match(/\((.+)\)/)) {
						marks.Grade = total.match(/\((.+)\)/)[1];
					}
					obj.Marks.push(marks);
				}
				if (!present) {
					return;
				}
				db.collection('Student').insert(obj, function (err) {
					if (err) {
						console.error(err);
					}
				});
				final[len++] = obj;
			});
		}
	});
	cb(final);
}

var studentBlueprint = function () {
	return {
		'Semester': Sem,
		'Programme': Name,
		'Batch': Batch,
		'Examination': Examination,
		'Institution': Institution,
		'CollegeCode': InstitutionCode,
		'EnrollmentNumber': null,
		'Name': null,
		'Marks': [],
		'CreditsSecured': null
	}
}

var marksBlueprint = function () {
	return {
		'Id': null,
		'Credits': null,
		'Internal': null,
		'External': null,
		'Total': null,
		'Grade': null
	}
}

var matchSubjectList = function () {
	var currentResult = studentBlueprint();
	if (JSON.stringify(currentResult) === JSON.stringify(previousResult)) {
		return false;
	}
	previousResult = currentResult;
	return true;
}

var getNameFromCurrentList = function (id) {
	// console.log('Required', id)
	for (var i = 0; i < currentSubjects.length; i++) {
		// console.log('Current', currentSubjects[i]['_id'])
		if (currentSubjects[i]['_id'] === id) {
			return currentSubjects[i]['Name'];
		}
	}
}<|endoftext|>


<commit_before>

angular.module("detailedBlock", ["ngRoute","d3"])
.controller('DetailedBlockController',  ['$scope','$http', '$routeParams', function($scope,$http, $routeParams) {
    var controller=this;
    var currentBlock;
    $scope.scoreData;

    $http.get('https://blockexplorer.com/api/block/'+$routeParams.blockid).success(function(data) {
      controller.currentBlock = data;
      $scope.scoreData=data.tx;
    });
  }])
  .directive('d3Bars', ['$window', '$timeout', 'd3Service',
    function($window, $timeout, d3Service) {
      return {
        restrict: 'EA',
        scope: {
          data:'='
        },
        link: function(scope, ele, attrs) {

          var width = 640,
          height = 480;

          var nodes = [];

          var links = [];

          var generateLinksAndNodes = function(data){
              var numOfTxs=data.length;
              for(var i = 0; i < numOfTxs; i++){
                var obj={source:i,target:i+1};

                var emptyObj={x:(i+1)*10,y:i+1};
                nodes.push(emptyObj);
                if(i<numOfTxs-1){
                  links.push(obj);
                }
              }
          }

          d3Service.d3().then(function(d3) {

          scope.render = function(data) {
            if(!(!data)){
              generateLinksAndNodes(data);

              var svg = d3.select(ele[0]).append('svg')
              .attr("width", width)
              .attr("height", height)
              .call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom))
              .append("g");

              function zoom() {
                  svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
              }

              var force = d3.layout.force()
                  .size([width, height])
                  .nodes(nodes)
                  .links(links);

              force.linkDistance(10);

              var link = svg.selectAll('.link')
                  .data(links)
                  .enter().append('line')
                  .attr('class', 'link');

              var node = svg.selectAll('.node')
                  .data(nodes)
                  .enter().append('circle')
                  .attr('class', 'node');

              force.on('tick', function() {

                  node.attr('r', width/100)
                      .attr('cx', function(d) { return d.x; })
                      .attr('cy', function(d) { return d.y; });

                  link.attr('x1', function(d) { return d.source.x; })
                      .attr('y1', function(d) { return d.source.y; })
                      .attr('x2', function(d) { return d.target.x; })
                      .attr('y2', function(d) { return d.target.y; });

              });

              force.start();
          }

          };

           //Watch 'data' and run scope.render(newVal) whenever it changes
           //Use true for 'objectEquality' property so comparisons are done on equality and not reference
            scope.$watch('data', function(){
                scope.render(scope.data);
            }, true);

          });
        }}
  }]);

  angular.module('d3', [])
  .factory('d3Service', ['$document', '$window', '$q', '$rootScope',
    function($document, $window, $q, $rootScope) {
      var d = $q.defer(),
          d3service = {
            d3: function() { return d.promise; }
          };
    function onScriptLoad() {
      // Load client in the browser
      $rootScope.$apply(function() { d.resolve($window.d3); });
    }
    var scriptTag = $document[0].createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.async = true;
    scriptTag.src = 'http://d3js.org/d3.v3.min.js';
    scriptTag.onreadystatechange = function () {
      if (this.readyState == 'complete') onScriptLoad();
    }
    scriptTag.onload = onScriptLoad;

    var s = $document[0].getElementsByTagName('body')[0];
    s.appendChild(scriptTag);

    return d3service;
  }]);
<commit_msg>Renders transactions in a straight line<commit_after>

angular.module("detailedBlock", ["ngRoute","d3"])
.controller('DetailedBlockController',  ['$scope','$http', '$routeParams', function($scope,$http, $routeParams) {
    var controller=this;
    var currentBlock;
    $scope.scoreData;

    $http.get('https://blockexplorer.com/api/block/'+$routeParams.blockid).success(function(data) {
      controller.currentBlock = data;
      $scope.scoreData=data.tx;
    });
  }])
  .directive('d3Bars', ['$window', '$timeout', 'd3Service',
    function($window, $timeout, d3Service) {
      return {
        restrict: 'EA',
        scope: {
          data:'='
        },
        link: function(scope, ele, attrs) {

          var width = 640,
          height = 480;

          var nodes = [];

          var links = [];

          var generateLinksAndNodes = function(data){
              var numOfTxs=data.length;
              for(var i = 0; i < numOfTxs; i++){
                var obj={source:i,target:i+1};
                console.log("Height "+i*height/3)
                var emptyObj={x:width/2,y:i*height/3};
                nodes.push(emptyObj);
                if(i<numOfTxs-1){
                  links.push(obj);
                }
              }
          }

          d3Service.d3().then(function(d3) {

          scope.render = function(data) {
            if(!(!data)){
              generateLinksAndNodes(data);

              var svg = d3.select(ele[0]).append('svg')
              .attr("width", width)
              .attr("height", height)
              .call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom))
              .append("g");

              function zoom() {
                  svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
              }

              var force = d3.layout.force()
                  .size([width, height])
                  .nodes(nodes)
                  .links(links);

              force.gravity(0);
              force.linkDistance(140);

              var link = svg.selectAll('.link')
                  .data(links)
                  .enter().append('line')
                  .attr('class', 'link');

              var node = svg.selectAll('.node')
                  .data(nodes)
                  .enter().append('circle')
                  .attr('class', 'node');

              force.on('tick', function() {

                  node.attr('r', width/100)
                      .attr('cx', function(d) { return d.x; })
                      .attr('cy', function(d) { return d.y; });

                  link.attr('x1', function(d) { return d.source.x; })
                      .attr('y1', function(d) { return d.source.y; })
                      .attr('x2', function(d) { return d.target.x; })
                      .attr('y2', function(d) { return d.target.y; });

              });

              force.start();
          }

          };

           //Watch 'data' and run scope.render(newVal) whenever it changes
           //Use true for 'objectEquality' property so comparisons are done on equality and not reference
            scope.$watch('data', function(){
                scope.render(scope.data);
            }, true);

          });
        }}
  }]);

  angular.module('d3', [])
  .factory('d3Service', ['$document', '$window', '$q', '$rootScope',
    function($document, $window, $q, $rootScope) {
      var d = $q.defer(),
          d3service = {
            d3: function() { return d.promise; }
          };
    function onScriptLoad() {
      // Load client in the browser
      $rootScope.$apply(function() { d.resolve($window.d3); });
    }
    var scriptTag = $document[0].createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.async = true;
    scriptTag.src = 'http://d3js.org/d3.v3.min.js';
    scriptTag.onreadystatechange = function () {
      if (this.readyState == 'complete') onScriptLoad();
    }
    scriptTag.onload = onScriptLoad;

    var s = $document[0].getElementsByTagName('body')[0];
    s.appendChild(scriptTag);

    return d3service;
  }]);
<|endoftext|>


<commit_before>module.exports = {
  extends: [
    'eslint-config-airbnb-base',
  ],

  parser: 'babel-eslint',

  parserOptions: {
    ecmaVersion: 6,
  },

  rules: {
    // Airbnb rules overrides
    'comma-dangle': ['warn', 'always-multiline'],
    'no-use-before-define': ['error', 'nofunc'],
    'object-curly-spacing': ['error', 'never'],
    'space-before-function-paren': 'off',
    'block-spacing': ['error', 'never'],
    'semi': ['error', 'always', {omitLastInOneLineBlock: true}],
    'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
    'one-var': 'off',
    'class-methods-use-this': 'off',

    // Custom rules
    'no-shadow': 'off', // to avoid warnings for mapped from redux properties
  },
};
<commit_msg>Increase max line length to 120 symbols<commit_after>module.exports = {
  extends: [
    'eslint-config-airbnb-base',
  ],

  parser: 'babel-eslint',

  parserOptions: {
    ecmaVersion: 6,
  },

  rules: {
    // Airbnb rules overrides
    'comma-dangle': ['warn', 'always-multiline'],
    'no-use-before-define': ['error', 'nofunc'],
    'object-curly-spacing': ['error', 'never'],
    'space-before-function-paren': 'off',
    'block-spacing': ['error', 'never'],
    'semi': ['error', 'always', {omitLastInOneLineBlock: true}],
    'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
    'one-var': 'off',
    'class-methods-use-this': 'off',
    'max-len': ['error', 120, 2, {
      ignoreUrls: true,
      ignoreComments: false,
      ignoreRegExpLiterals: true,
      ignoreStrings: true,
      ignoreTemplateLiterals: true,
    }],

    // Custom rules
    'no-shadow': 'off', // to avoid warnings for mapped from redux properties
  },
};
<|endoftext|>


<commit_before>var fontawesome = require('lib/IconicFont').IconicFont({
	font : 'lib/FontAwesome'
});

var font = 'FontAwesome';

if (OS_ANDROID) {
	font = 'fontawesome-webfont';
}
Ti.API.info(Ti.App.Properties.getString('profileNameSetting'));

var mainView = Ti.UI.createScrollView({
	class : "topView",
	height : "100%",
	width : "100%",
	top : 0,
	backgroundColor : "transparent",
	layout : "vertical"
});

var groupLabel = Ti.UI.createLabel({
	text : Alloy.Globals.PHRASES.createGroupTxt,
	textAlign : "center",
	top : 10,
	font : {
		fontSize : 22,
		fontFamily : "Impact"
	},
	color : "#FFF"
});
mainView.add(groupLabel);

var groupNameLabel = Ti.UI.createLabel({
	text : Alloy.Globals.PHRASES.stateGroupNameTxt,
	textAlign : "center",
	top : '4%',
	font : {
		fontSize : 18,
		fontFamily : "Impact"
	},
	color : "#FFF"
});
mainView.add(groupNameLabel);

var groupName = Ti.UI.createTextField({
	color : '#336699',
	backgroundColor : '#ccc',
	borderColor : '#ff0000',
	top : '1%',
	left : '20%',
	width : '60%',
	height : 40,
	tintColor : '#000',
	keyboardType : Titanium.UI.KEYBOARD_DEFAULT,
	returnKeyType : Titanium.UI.RETURNKEY_DEFAULT,
	borderStyle : Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
mainView.add(groupName);

groupName.addEventListener('return', function(e) {
	if (e.source.value.length > 2) {
		groupName.borderColor = '#00ff00';
	} else if (e.source.value.length < 3) {
		groupName.borderColor = '#ff0000';
	}
});
var saveName = Ti.UI.createButton({
	height : 40,
	width : '60%',
	left : '20%',
	top : '0.5%',
	title : Alloy.Globals.PHRASES.pickFriendsTxt,
	backgroundColor : '#FFF',
	color : '#000',
	borderRadius : 5
});
mainView.add(saveName);

//saves groupname
saveName.addEventListener('click', function(e) {
	if (groupName.value.length > 2) {
		var gName = Ti.Network.createHTTPClient();
		gName.onload = function() {
			Ti.API.info(this.responseText);
			if (this.responseText == "namnet finns redan-1") {
				alert(Alloy.Globals.PHRASES.groupNameExistsTxt);
			} else {
				groupName.visible = false;
				saveName.visible = false;
				//adds label with groupname
				groupNameLabel.text = groupName.value;
				var groupId = JSON.parse(this.responseText);
				var addMe = Ti.Network.createHTTPClient();
				addMe.open("POST", Alloy.Globals.BETKAMPENADDGROUPMEMBERSURL + '&lang=' + Alloy.Globals.LOCALE);
				var params = {
					group_id : groupId,
					id : Alloy.Globals.BETKAMPENUID,
					name : Ti.App.Properties.getString('profileNameSetting'),
			};
			addMe.send(params);

			getFriends(groupId);

			}
		};
		gName.open("POST", Alloy.Globals.BETKAMPENCREATEGROUPURL + '&lang=' + Alloy.Globals.LOCALE);
		var params = {
			id : Alloy.Globals.BETKAMPENUID,
			group_name : groupName.value
		};
		gName.send(params);

	} else if (groupName.value.length < 3) {
		alert(Alloy.Globals.PHRASES.shortGroupNameTxt);
	}
});

l = 0;

//get all your friends
function createFriendGUI(obj, groupId) {
	l++;
	if (l == 1) {
		var line = Ti.UI.createView({
			width : '100%',
			height : '1%',
			top : '-15%',
			backgroundColor : '#fff'
		});
		mainView.add(line);

		var memberLabel = Ti.UI.createLabel({
			text : Alloy.Globals.PHRASES.addMembersTxt,
			textAlign : "center",
			top : '1%',
			font : {
				fontSize : 18,
				fontFamily : "Impact"
			},
			color : "#FFF"
		});
		mainView.add(memberLabel);
	}

	var row = Ti.UI.createView({
		width : '100%',
		height : 35,
		top : '0.3%'
	});
	mainView.add(row);

	var member = Ti.UI.createView({
		width : '79%',
		backgroundColor : '#fff',
		color : '#000',
		opacity : 0.7,
		borderRadius : 5,
		left : '1%'
	});
	row.add(member);

	//profilepicture
	var image;
	if(typeof obj.fbid !== 'undefined') {
		image = "https://graph.facebook.com/"+ obj.fbid +"/picture?type=large";
	} else {
		// get betkampen image
		image = Alloy.Globals.BETKAMPENURL + '/profile_images/' + obj.id + '.png';
	}

	var profilePic = Titanium.UI.createImageView({
	image : image,
		height : 25,
		width : 25,
		left : '2%'
	});
	profilePic.addEventListener('error',function(e){
		// fallback for image
		profilePic.image = '/images/no_pic.png';
	});
	member.add(profilePic);

	boardName = obj.name.toString();
	if (boardName.length > 26) {
		boardName = boardName.substring(0, 26);
	}
	var name = Ti.UI.createLabel({
		text : boardName,
		left : '15%',
		font : {
			fontSize : 16,
			fontFamily : "Impact"
		},
	});
	member.add(name);
	//add button to select member
	var addBtn = Ti.UI.createButton({
		width : '18%',
		left : '81%',
		id : obj.id,
		name : obj.name,
		gid : groupId,
		font : {
			fontFamily : font,
			fontSize : 27
		},
		title : fontawesome.icon('fa-plus'),
		backgroundColor : '#fff',
		color : '#000',
		opacity : 0.7,
		borderRadius : 5,
	});
	row.add(addBtn);
	var click = 0;
	addBtn.addEventListener('click', function(e) {
		//click once add person to group
		if (click == 0) {
			addBtn.backgroundColor = '#00ff00';
			addBtn.title = fontawesome.icon('fa-check');
			member.borderColor = '#00ff00';
			var addMember = Ti.Network.createHTTPClient();
			addMember.open("POST", Alloy.Globals.BETKAMPENADDGROUPMEMBERSURL + '&lang=' + Alloy.Globals.LOCALE);
			var params = {
				group_id : e.source.gid,
				id : e.source.id,
				name : e.source.name,
			};
			addMember.send(params);
			Ti.API.info(params);
			click++;
			//click again to remove friend from group
		} else if (click == 1) {
			addBtn.backgroundColor = '#fff';
			addBtn.title = fontawesome.icon('fa-plus');
			member.borderColor = '#fff';

			var removeMember = Ti.Network.createHTTPClient();
			removeMember.open("POST", Alloy.Globals.BETKAMPENREMOVEGROUPMEMBERURL + '&lang=' + Alloy.Globals.LOCALE);
			var params = {
				group_id : e.source.gid,
				id : Alloy.Globals.BETKAMPENUID,
				member_to_remove : e.source.id,
			};
			removeMember.send(params);

			Ti.API.info(params);
			click--;
		}

	});

}

//get friends from db
function getFriends(groupId) {
	var xhr = Ti.Network.createHTTPClient({
		// function called when the response data is available
		onload : function(e) {
			//Ti.API.info("Received text: " + this.responseText);
			var friends = JSON.parse(this.responseText);

			for (var i = 0; i < friends.length; i++) {
				//send friends and group id to friend selector
				createFriendGUI(friends[i], groupId);
			}
			//create button to save group when you have selected friends
			var saveGroupBtn = Ti.UI.createButton({
			height : 40,
			width : '60%',
			left : '20%',
			top : '2%',
			id:groupId,
			name: groupName.value,
			title : Alloy.Globals.PHRASES.saveTxt,
			backgroundColor : '#FFF',
			color : '#000',
			borderRadius : 5
		});
		mainView.add(saveGroupBtn);

		//close down window when you are finished
		saveGroupBtn.addEventListener('click', function(e){
			var win = Alloy.createController('myGroups').getView();
			if (OS_IOS) {
				Alloy.Globals.NAV.openWindow(win, {
					animated : true
				});
			} else {
				win.open({
					fullScreen : true
				});
				win = null;
			}
			$.createGroup.close();
		});
		},
		// function called when an error occurs, including a timeout
		onerror : function(e) {
			Ti.API.debug(e.error);
			//alert('error');
		},
		timeout : Alloy.Globals.TIMEOUT // in milliseconds
	});
	// Prepare the connection.
	xhr.open('GET', Alloy.Globals.BETKAMPENGETFRIENDSURL + '?uid=' + Alloy.Globals.BETKAMPENUID + '&lang=' + Alloy.Globals.LOCALE);

	xhr.setRequestHeader("content-type", "application/json");
	xhr.setRequestHeader("Authorization", Alloy.Globals.BETKAMPEN.token);
	xhr.setTimeout(Alloy.Globals.TIMEOUT);

	xhr.send();
}

$.createGroup.add(mainView);
<commit_msg>groupfix<commit_after>var fontawesome = require('lib/IconicFont').IconicFont({
	font : 'lib/FontAwesome'
});

var font = 'FontAwesome';

if (OS_ANDROID) {
	font = 'fontawesome-webfont';
}
Ti.API.info(Ti.App.Properties.getString('profileNameSetting'));

var mainView = Ti.UI.createScrollView({
	class : "topView",
	height : "100%",
	width : "100%",
	top : 0,
	backgroundColor : "transparent",
	layout : "vertical"
});

var groupLabel = Ti.UI.createLabel({
	text : Alloy.Globals.PHRASES.createGroupTxt,
	textAlign : "center",
	top : 10,
	font : {
		fontSize : 22,
		fontFamily : "Impact"
	},
	color : "#FFF"
});
mainView.add(groupLabel);

var groupNameLabel = Ti.UI.createLabel({
	text : Alloy.Globals.PHRASES.stateGroupNameTxt,
	textAlign : "center",
	top : '4%',
	font : {
		fontSize : 18,
		fontFamily : "Impact"
	},
	color : "#FFF"
});
mainView.add(groupNameLabel);

var groupName = Ti.UI.createTextField({
	color : '#336699',
	backgroundColor : '#ccc',
	borderColor : '#ff0000',
	top : '1%',
	left : '20%',
	width : '60%',
	height : 40,
	tintColor : '#000',
	keyboardType : Titanium.UI.KEYBOARD_DEFAULT,
	returnKeyType : Titanium.UI.RETURNKEY_DEFAULT,
	borderStyle : Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
mainView.add(groupName);

groupName.addEventListener('return', function(e) {
	if (e.source.value.length > 2) {
		groupName.borderColor = '#00ff00';
	} else if (e.source.value.length < 3) {
		groupName.borderColor = '#ff0000';
	}
});
var saveName = Ti.UI.createButton({
	height : 40,
	width : '60%',
	left : '20%',
	top : '0.5%',
	title : Alloy.Globals.PHRASES.pickFriendsTxt,
	backgroundColor : '#FFF',
	color : '#000',
	borderRadius : 5
});
mainView.add(saveName);

//saves groupname
saveName.addEventListener('click', function(e) {
	if (groupName.value.length > 2) {
		var gName = Ti.Network.createHTTPClient();
		gName.onload = function() {
			Ti.API.info(this.responseText);
			if (this.responseText == "namnet finns redan-1") {
				alert(Alloy.Globals.PHRASES.groupNameExistsTxt);
			} else {
				groupName.visible = false;
				saveName.visible = false;
				//adds label with groupname
				groupNameLabel.text = groupName.value;
				var groupId = JSON.parse(this.responseText);
				var addMe = Ti.Network.createHTTPClient();
				addMe.open("POST", Alloy.Globals.BETKAMPENADDGROUPMEMBERSURL);
				var params = {
					group_id : groupId,
					id : Alloy.Globals.BETKAMPENUID,
					name : Ti.App.Properties.getString('profileNameSetting'),
			};
			addMe.send(params);

			getFriends(groupId);

			}
		};
		gName.open("POST", Alloy.Globals.BETKAMPENCREATEGROUPURL);
		var params = {
			id : Alloy.Globals.BETKAMPENUID,
			group_name : groupName.value
		};
		gName.send(params);

	} else if (groupName.value.length < 3) {
		alert(Alloy.Globals.PHRASES.shortGroupNameTxt);
	}
});

l = 0;

//get all your friends
function createFriendGUI(obj, groupId) {
	l++;
	if (l == 1) {
		var line = Ti.UI.createView({
			width : '100%',
			height : '1%',
			top : '-15%',
			backgroundColor : '#fff'
		});
		mainView.add(line);

		var memberLabel = Ti.UI.createLabel({
			text : Alloy.Globals.PHRASES.addMembersTxt,
			textAlign : "center",
			top : '1%',
			font : {
				fontSize : 18,
				fontFamily : "Impact"
			},
			color : "#FFF"
		});
		mainView.add(memberLabel);
	}

	var row = Ti.UI.createView({
		width : '100%',
		height : 35,
		top : '0.3%'
	});
	mainView.add(row);

	var member = Ti.UI.createView({
		width : '79%',
		backgroundColor : '#fff',
		color : '#000',
		opacity : 0.7,
		borderRadius : 5,
		left : '1%'
	});
	row.add(member);

	//profilepicture
	var image;
	if(typeof obj.fbid !== 'undefined') {
		image = "https://graph.facebook.com/"+ obj.fbid +"/picture?type=large";
	} else {
		// get betkampen image
		image = Alloy.Globals.BETKAMPENURL + '/profile_images/' + obj.id + '.png';
	}

	var profilePic = Titanium.UI.createImageView({
	image : image,
		height : 25,
		width : 25,
		left : '2%'
	});
	profilePic.addEventListener('error',function(e){
		// fallback for image
		profilePic.image = '/images/no_pic.png';
	});
	member.add(profilePic);

	boardName = obj.name.toString();
	if (boardName.length > 26) {
		boardName = boardName.substring(0, 26);
	}
	var name = Ti.UI.createLabel({
		text : boardName,
		left : '15%',
		font : {
			fontSize : 16,
			fontFamily : "Impact"
		},
	});
	member.add(name);
	//add button to select member
	var addBtn = Ti.UI.createButton({
		width : '18%',
		left : '81%',
		id : obj.id,
		name : obj.name,
		gid : groupId,
		font : {
			fontFamily : font,
			fontSize : 27
		},
		title : fontawesome.icon('fa-plus'),
		backgroundColor : '#fff',
		color : '#000',
		opacity : 0.7,
		borderRadius : 5,
	});
	row.add(addBtn);
	var click = 0;
	addBtn.addEventListener('click', function(e) {
		//click once add person to group
		if (click == 0) {
			addBtn.backgroundColor = '#00ff00';
			addBtn.title = fontawesome.icon('fa-check');
			member.borderColor = '#00ff00';
			var addMember = Ti.Network.createHTTPClient();
			addMember.open("POST", Alloy.Globals.BETKAMPENADDGROUPMEMBERSURL + '&lang=' + Alloy.Globals.LOCALE);
			var params = {
				group_id : e.source.gid,
				id : e.source.id,
				name : e.source.name,
			};
			addMember.send(params);
			Ti.API.info(params);
			click++;
			//click again to remove friend from group
		} else if (click == 1) {
			addBtn.backgroundColor = '#fff';
			addBtn.title = fontawesome.icon('fa-plus');
			member.borderColor = '#fff';

			var removeMember = Ti.Network.createHTTPClient();
			removeMember.open("POST", Alloy.Globals.BETKAMPENREMOVEGROUPMEMBERURL + '&lang=' + Alloy.Globals.LOCALE);
			var params = {
				group_id : e.source.gid,
				id : Alloy.Globals.BETKAMPENUID,
				member_to_remove : e.source.id,
			};
			removeMember.send(params);

			Ti.API.info(params);
			click--;
		}

	});

}

//get friends from db
function getFriends(groupId) {
	var xhr = Ti.Network.createHTTPClient({
		// function called when the response data is available
		onload : function(e) {
			//Ti.API.info("Received text: " + this.responseText);
			var friends = JSON.parse(this.responseText);

			for (var i = 0; i < friends.length; i++) {
				//send friends and group id to friend selector
				createFriendGUI(friends[i], groupId);
			}
			//create button to save group when you have selected friends
			var saveGroupBtn = Ti.UI.createButton({
			height : 40,
			width : '60%',
			left : '20%',
			top : '2%',
			id:groupId,
			name: groupName.value,
			title : Alloy.Globals.PHRASES.saveTxt,
			backgroundColor : '#FFF',
			color : '#000',
			borderRadius : 5
		});
		mainView.add(saveGroupBtn);

		//close down window when you are finished
		saveGroupBtn.addEventListener('click', function(e){
			var win = Alloy.createController('myGroups').getView();
			if (OS_IOS) {
				Alloy.Globals.NAV.openWindow(win, {
					animated : true
				});
			} else {
				win.open({
					fullScreen : true
				});
				win = null;
			}
			$.createGroup.close();
		});
		},
		// function called when an error occurs, including a timeout
		onerror : function(e) {
			Ti.API.debug(e.error);
			//alert('error');
		},
		timeout : Alloy.Globals.TIMEOUT // in milliseconds
	});
	// Prepare the connection.
	xhr.open('GET', Alloy.Globals.BETKAMPENGETFRIENDSURL + '?uid=' + Alloy.Globals.BETKAMPENUID + '&lang=' + Alloy.Globals.LOCALE);

	xhr.setRequestHeader("content-type", "application/json");
	xhr.setRequestHeader("Authorization", Alloy.Globals.BETKAMPEN.token);
	xhr.setTimeout(Alloy.Globals.TIMEOUT);

	xhr.send();
}

$.createGroup.add(mainView);
<|endoftext|>