<commit_before>import PropTypes from 'prop-types'
import React, { Component, Fragment } from 'react'
import ReactPlayer from 'react-player'
import { Color } from 'constants/css'
import { connect } from 'react-redux'
import { auth } from 'redux/constants'
import {
  addVideoView,
  fillCurrentVideoSlot,
  emptyCurrentVideoSlot
} from 'redux/actions/VideoActions'
import { changeUserXP } from 'redux/actions/UserActions'
import request from 'axios'
import StarMark from 'components/StarMark'
import { URL } from 'constants/URL'
import ErrorBoundary from 'components/Wrappers/ErrorBoundary'
import ProgressBar from 'components/ProgressBar'
import Spinner from 'components/Spinner'
import { css } from 'emotion'

const CONTENT_URL = `${URL}/content`
const VIDEO_URL = `${URL}/video`
const intervalLength = 2000
const denominator = 3

class VideoPlayer extends Component {
  static propTypes = {
    addVideoView: PropTypes.func.isRequired,
    autoplay: PropTypes.bool,
    chatMode: PropTypes.bool,
    emptyCurrentVideoSlot: PropTypes.func,
    fillCurrentVideoSlot: PropTypes.func,
    hasHqThumb: PropTypes.number,
    changeUserXP: PropTypes.func,
    isStarred: PropTypes.bool,
    minimized: PropTypes.bool,
    stretch: PropTypes.bool,
    onEdit: PropTypes.bool,
    pageVisible: PropTypes.bool,
    currentVideoSlot: PropTypes.number,
    style: PropTypes.object,
    userId: PropTypes.number,
    videoCode: PropTypes.string.isRequired,
    videoId: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
      .isRequired
  }

  interval = null
  isMobile = false
  Player = null
  rewardingXP = false

  state = {
    playing: false,
    timeWatched: 0,
    totalDuration: 0,
    xpEarned: false,
    justEarned: false,
    imageUrl: ''
  }

  async componentDidMount() {
    const {
      autoplay,
      hasHqThumb,
      isStarred,
      userId,
      videoCode,
      videoId
    } = this.props
    this.mounted = true
    this.isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent)
    if (typeof hasHqThumb !== 'number') {
      try {
        const {
          data: { payload }
        } = await request.put(`${CONTENT_URL}/videoThumb`, {
          videoCode,
          videoId
        })
        if (this.mounted) {
          this.setState({
            imageUrl:
              payload || `https://img.youtube.com/vi/${videoCode}/mqdefault.jpg`
          })
        }
      } catch (error) {
        console.error(error.response || error)
      }
    } else {
      const imageName = hasHqThumb ? 'maxresdefault' : 'mqdefault'
      this.setState({
        imageUrl: `https://img.youtube.com/vi/${videoCode}/${imageName}.jpg`
      })
    }

    if (isStarred && userId) {
      try {
        const {
          data: { xpEarned }
        } = await request.get(
          `${VIDEO_URL}/xpEarned?videoId=${videoId}`,
          auth()
        )
        if (this.mounted) this.setState(() => ({ xpEarned: !!xpEarned }))
      } catch (error) {
        console.error(error.response || error)
      }
    }

    if (autoplay || this.isMobile) {
      this.setState({ playing: true })
    }
  }

  async componentDidUpdate(prevProps) {
    const {
      onEdit,
      chatMode,
      currentVideoSlot,
      hasHqThumb,
      isStarred,
      pageVisible,
      userId,
      videoCode,
      videoId
    } = this.props
    const { playing, xpEarned, justEarned } = this.state
    if (prevProps.onEdit !== onEdit) {
      if (onEdit === true) this.onVideoStop()
      this.setState({ playing: false })
    }
    const userWatchingMultipleVideo =
      currentVideoSlot &&
      currentVideoSlot !== prevProps.currentVideoSlot &&
      currentVideoSlot !== Number(videoId)
    const alreadyEarned = xpEarned || justEarned

    if (prevProps.userId && !userId) {
      this.setState(state => ({
        ...state,
        timeWatched: 0,
        xpEarned: false,
        justEarned: false
      }))
    }

    if (prevProps.videoCode !== videoCode) {
      const newImageName = hasHqThumb ? 'maxresdefault' : 'mqdefault'
      this.setState({
        imageUrl: `https://img.youtube.com/vi/${videoCode}/${newImageName}.jpg`
      })
    }

    if (isStarred && userId && userId !== prevProps.userId) {
      try {
        const {
          data: { xpEarned }
        } = await request.get(
          `${VIDEO_URL}/xpEarned?videoId=${videoId}`,
          auth()
        )
        if (xpEarned && this.mounted) {
          this.setState(() => ({ xpEarned: !!xpEarned }))
        }
      } catch (error) {
        console.error(error.response || error)
      }
    }

    if (playing && userWatchingMultipleVideo) {
      this.onVideoStop()
      if (this.Player) this.Player.getInternalPlayer().pauseVideo()
    }

    if (
      playing &&
      isStarred &&
      pageVisible !== prevProps.pageVisible &&
      !alreadyEarned
    ) {
      this.onVideoStop()
      if (this.Player) this.Player.getInternalPlayer().pauseVideo()
    }

    if (
      playing &&
      isStarred &&
      chatMode !== prevProps.chatMode &&
      !alreadyEarned
    ) {
      this.onVideoStop()
      if (this.Player) this.Player.getInternalPlayer().pauseVideo()
    }
  }

  componentWillUnmount() {
    this.onVideoStop()
    this.Player = undefined
    this.mounted = false
  }

  render() {
    const {
      isStarred,
      minimized,
      stretch,
      onEdit,
      videoCode,
      style = {},
      userId
    } = this.props
    const {
      imageUrl,
      playing,
      timeWatched,
      totalDuration,
      xpEarned,
      justEarned
    } = this.state
    const requiredViewDuration = totalDuration / denominator
    const progress = xpEarned
      ? 100
      : requiredViewDuration > 0
        ? Math.floor(
            Math.min(timeWatched, requiredViewDuration) *
              100 /
              requiredViewDuration
          )
        : 0
    return (
      <ErrorBoundary style={style}>
        <div
          className={`${css`
            position: relative;
            padding-top: 56.25%;
          `}${minimized ? ' desktop' : ''}`}
          style={{
            display: minimized && !playing && 'none',
            width: playing && minimized && '39rem',
            paddingTop: playing && minimized && '22rem',
            position: playing && minimized && 'absolute',
            bottom: playing && minimized && '1rem',
            right: playing && minimized && '1rem',
            cursor: !onEdit && !playing && 'pointer'
          }}
          onClick={() => {
            if (!onEdit && !playing) {
              this.setState({ playing: true })
            }
          }}
        >
          {!minimized &&
            !playing && (
              <Fragment>
                <img
                  alt=""
                  src={imageUrl}
                  className={css`
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    top: 0;
                    right: 0;
                    left: 0;
                    bottom: 0;
                  `}
                />
                {isStarred && (
                  <StarMark
                    style={{
                      top: '1rem',
                      left: '1rem'
                    }}
                  />
                )}
              </Fragment>
            )}
          {!onEdit &&
            playing && (
              <ReactPlayer
                ref={ref => {
                  this.Player = ref
                }}
                className={css`
                  position: absolute;
                  top: 0;
                  left: 0;
                  z-index: 1;
                `}
                width="100%"
                height="100%"
                url={`https://www.youtube.com/watch?v=${videoCode}`}
                playing={playing}
                controls
                config={{
                  youtube: { preload: true }
                }}
                onReady={this.onVideoReady}
                onPlay={this.onVideoPlay}
                onPause={this.onVideoStop}
                onEnded={this.onVideoStop}
              />
            )}
          {!onEdit && !minimized && playing ? (
            <div
              className={css`
                position: absolute;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                font-size: 3rem;
                display: flex;
                align-items: center;
                justify-content: center;
              `}
              style={style}
            >
              <Spinner />
            </div>
          ) : !onEdit ? (
            <a
              className={css`
                position: absolute;
                display: block;
                background: url('/img/play-button-image.png');
                background-size: contain;
                height: 5rem;
                width: 5rem;
                top: 50%;
                left: 50%;
                margin: -2.5rem 0 0 -2.5rem;
              `}
            />
          ) : null}
        </div>
        {isStarred &&
          !!userId && (
            <ProgressBar
              progress={progress}
              noBorderRadius={stretch}
              color={
                justEarned
                  ? Color.green()
                  : xpEarned
                    ? Color.lightBlue()
                    : Color.blue()
              }
              text={
                justEarned
                  ? 'Twinkle XP earned!'
                  : xpEarned
                    ? 'You have already earned this XP'
                    : ''
              }
            />
          )}
      </ErrorBoundary>
    )
  }

  onVideoReady = () => {
    this.setState(() => ({
      totalDuration: this.Player.getDuration()
    }))
  }

  onVideoPlay = () => {
    const {
      currentVideoSlot,
      isStarred,
      videoId,
      userId,
      addVideoView,
      fillCurrentVideoSlot
    } = this.props
    const { justEarned, xpEarned } = this.state
    const time = this.Player.getCurrentTime()
    if (Math.floor(time) === 0) {
      addVideoView({ videoId, userId })
    }
    if (!currentVideoSlot) {
      fillCurrentVideoSlot(Number(videoId))
      if (userId) {
        this.interval = setInterval(this.increaseProgress, intervalLength)
      }
    }
    const authorization = auth()
    const authExists = !!authorization.headers.authorization
    if (authExists && isStarred && !(justEarned || xpEarned)) {
      try {
        request.put(
          `${VIDEO_URL}/currentlyWatching`,
          { videoId },
          authorization
        )
      } catch (error) {
        console.error(error.response || error)
      }
    }
  }

  onVideoStop = () => {
    const { emptyCurrentVideoSlot } = this.props
    clearInterval(this.interval)
    emptyCurrentVideoSlot()
    const authorization = auth()
    const authExists = !!authorization.headers.authorization
    if (authExists) {
      try {
        request.put(
          `${VIDEO_URL}/currentlyWatching`,
          { videoId: null },
          authorization
        )
      } catch (error) {
        console.error(error.response || error)
      }
    }
  }

  increaseProgress = async() => {
    const { justEarned, xpEarned, timeWatched, totalDuration } = this.state
    const { changeUserXP, isStarred, videoId } = this.props
    if (isStarred && !xpEarned && !justEarned && this.Player) {
      if (this.Player.getInternalPlayer().isMuted()) {
        this.Player.getInternalPlayer().unMute()
      }
      if (this.Player.getInternalPlayer().getVolume() < 30) {
        this.Player.getInternalPlayer().setVolume(30)
      }
    }
    if (
      isStarred &&
      timeWatched >= totalDuration / denominator &&
      !this.rewardingXP
    ) {
      this.rewardingXP = true
      try {
        await request.put(`${VIDEO_URL}/xpEarned`, { videoId }, auth())
        await changeUserXP({
          type: 'increase',
          action: 'watch',
          target: 'video',
          targetId: videoId,
          amount: 100
        })
        if (this.mounted) {
          this.setState(() => ({
            justEarned: true,
            xpEarned: true
          }))
        }
        this.rewardingXP = false
      } catch (error) {
        console.error(error.response || error)
      }
    }
    if (!xpEarned && this.mounted) {
      this.setState(state => ({
        timeWatched: state.timeWatched + intervalLength / 1000
      }))
    }
    const authorization = auth()
    const authExists = !!authorization.headers.authorization
    if (authExists) {
      try {
        const {
          data: { currentlyWatchingAnotherVideo, success }
        } = await request.put(
          `${VIDEO_URL}/duration`,
          { videoId, isStarred, xpEarned },
          authorization
        )
        if (success) return
        if (currentlyWatchingAnotherVideo) {
          if (this.Player) this.Player.getInternalPlayer().pauseVideo()
        }
      } catch (error) {
        console.error(error.response || error)
      }
    }
  }
}

export default connect(
  state => ({
    chatMode: state.ChatReducer.chatMode,
    userId: state.UserReducer.userId,
    pageVisible: state.ViewReducer.pageVisible,
    currentVideoSlot: state.VideoReducer.currentVideoSlot
  }),
  {
    addVideoView,
    changeUserXP,
    fillCurrentVideoSlot,
    emptyCurrentVideoSlot
  }
)(VideoPlayer)
<commit_msg>cancel autoplay for mobile<commit_after>import PropTypes from 'prop-types'
import React, { Component, Fragment } from 'react'
import ReactPlayer from 'react-player'
import { Color } from 'constants/css'
import { connect } from 'react-redux'
import { auth } from 'redux/constants'
import {
  addVideoView,
  fillCurrentVideoSlot,
  emptyCurrentVideoSlot
} from 'redux/actions/VideoActions'
import { changeUserXP } from 'redux/actions/UserActions'
import request from 'axios'
import StarMark from 'components/StarMark'
import { URL } from 'constants/URL'
import ErrorBoundary from 'components/Wrappers/ErrorBoundary'
import ProgressBar from 'components/ProgressBar'
import Spinner from 'components/Spinner'
import { css } from 'emotion'

const CONTENT_URL = `${URL}/content`
const VIDEO_URL = `${URL}/video`
const intervalLength = 2000
const denominator = 3

class VideoPlayer extends Component {
  static propTypes = {
    addVideoView: PropTypes.func.isRequired,
    autoplay: PropTypes.bool,
    chatMode: PropTypes.bool,
    emptyCurrentVideoSlot: PropTypes.func,
    fillCurrentVideoSlot: PropTypes.func,
    hasHqThumb: PropTypes.number,
    changeUserXP: PropTypes.func,
    isStarred: PropTypes.bool,
    minimized: PropTypes.bool,
    stretch: PropTypes.bool,
    onEdit: PropTypes.bool,
    pageVisible: PropTypes.bool,
    currentVideoSlot: PropTypes.number,
    style: PropTypes.object,
    userId: PropTypes.number,
    videoCode: PropTypes.string.isRequired,
    videoId: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
      .isRequired
  }

  interval = null
  Player = null
  rewardingXP = false

  state = {
    playing: false,
    timeWatched: 0,
    totalDuration: 0,
    xpEarned: false,
    justEarned: false,
    imageUrl: ''
  }

  async componentDidMount() {
    const {
      autoplay,
      hasHqThumb,
      isStarred,
      userId,
      videoCode,
      videoId
    } = this.props
    this.mounted = true

    if (typeof hasHqThumb !== 'number') {
      try {
        const {
          data: { payload }
        } = await request.put(`${CONTENT_URL}/videoThumb`, {
          videoCode,
          videoId
        })
        if (this.mounted) {
          this.setState({
            imageUrl:
              payload || `https://img.youtube.com/vi/${videoCode}/mqdefault.jpg`
          })
        }
      } catch (error) {
        console.error(error.response || error)
      }
    } else {
      const imageName = hasHqThumb ? 'maxresdefault' : 'mqdefault'
      this.setState({
        imageUrl: `https://img.youtube.com/vi/${videoCode}/${imageName}.jpg`
      })
    }

    if (isStarred && userId) {
      try {
        const {
          data: { xpEarned }
        } = await request.get(
          `${VIDEO_URL}/xpEarned?videoId=${videoId}`,
          auth()
        )
        if (this.mounted) this.setState(() => ({ xpEarned: !!xpEarned }))
      } catch (error) {
        console.error(error.response || error)
      }
    }

    if (autoplay) {
      this.setState({ playing: true })
    }
  }

  async componentDidUpdate(prevProps) {
    const {
      onEdit,
      chatMode,
      currentVideoSlot,
      hasHqThumb,
      isStarred,
      pageVisible,
      userId,
      videoCode,
      videoId
    } = this.props
    const { playing, xpEarned, justEarned } = this.state
    if (prevProps.onEdit !== onEdit) {
      if (onEdit === true) this.onVideoStop()
      this.setState({ playing: false })
    }
    const userWatchingMultipleVideo =
      currentVideoSlot &&
      currentVideoSlot !== prevProps.currentVideoSlot &&
      currentVideoSlot !== Number(videoId)
    const alreadyEarned = xpEarned || justEarned

    if (prevProps.userId && !userId) {
      this.setState(state => ({
        ...state,
        timeWatched: 0,
        xpEarned: false,
        justEarned: false
      }))
    }

    if (prevProps.videoCode !== videoCode) {
      const newImageName = hasHqThumb ? 'maxresdefault' : 'mqdefault'
      this.setState({
        imageUrl: `https://img.youtube.com/vi/${videoCode}/${newImageName}.jpg`
      })
    }

    if (isStarred && userId && userId !== prevProps.userId) {
      try {
        const {
          data: { xpEarned }
        } = await request.get(
          `${VIDEO_URL}/xpEarned?videoId=${videoId}`,
          auth()
        )
        if (xpEarned && this.mounted) {
          this.setState(() => ({ xpEarned: !!xpEarned }))
        }
      } catch (error) {
        console.error(error.response || error)
      }
    }

    if (playing && userWatchingMultipleVideo) {
      this.onVideoStop()
      if (this.Player) this.Player.getInternalPlayer().pauseVideo()
    }

    if (
      playing &&
      isStarred &&
      pageVisible !== prevProps.pageVisible &&
      !alreadyEarned
    ) {
      this.onVideoStop()
      if (this.Player) this.Player.getInternalPlayer().pauseVideo()
    }

    if (
      playing &&
      isStarred &&
      chatMode !== prevProps.chatMode &&
      !alreadyEarned
    ) {
      this.onVideoStop()
      if (this.Player) this.Player.getInternalPlayer().pauseVideo()
    }
  }

  componentWillUnmount() {
    this.onVideoStop()
    this.Player = undefined
    this.mounted = false
  }

  render() {
    const {
      isStarred,
      minimized,
      stretch,
      onEdit,
      videoCode,
      style = {},
      userId
    } = this.props
    const {
      imageUrl,
      playing,
      timeWatched,
      totalDuration,
      xpEarned,
      justEarned
    } = this.state
    const requiredViewDuration = totalDuration / denominator
    const progress = xpEarned
      ? 100
      : requiredViewDuration > 0
        ? Math.floor(
            Math.min(timeWatched, requiredViewDuration) *
              100 /
              requiredViewDuration
          )
        : 0
    return (
      <ErrorBoundary style={style}>
        <div
          className={`${css`
            position: relative;
            padding-top: 56.25%;
          `}${minimized ? ' desktop' : ''}`}
          style={{
            display: minimized && !playing && 'none',
            width: playing && minimized && '39rem',
            paddingTop: playing && minimized && '22rem',
            position: playing && minimized && 'absolute',
            bottom: playing && minimized && '1rem',
            right: playing && minimized && '1rem',
            cursor: !onEdit && !playing && 'pointer'
          }}
          onClick={() => {
            if (!onEdit && !playing) {
              this.setState({ playing: true })
            }
          }}
        >
          {!minimized &&
            !playing && (
              <Fragment>
                <img
                  alt=""
                  src={imageUrl}
                  className={css`
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    top: 0;
                    right: 0;
                    left: 0;
                    bottom: 0;
                  `}
                />
                {isStarred && (
                  <StarMark
                    style={{
                      top: '1rem',
                      left: '1rem'
                    }}
                  />
                )}
              </Fragment>
            )}
          {!onEdit &&
            playing && (
              <ReactPlayer
                ref={ref => {
                  this.Player = ref
                }}
                className={css`
                  position: absolute;
                  top: 0;
                  left: 0;
                  z-index: 1;
                `}
                width="100%"
                height="100%"
                url={`https://www.youtube.com/watch?v=${videoCode}`}
                playing={playing}
                controls
                config={{
                  youtube: { preload: true }
                }}
                onReady={this.onVideoReady}
                onPlay={this.onVideoPlay}
                onPause={this.onVideoStop}
                onEnded={this.onVideoStop}
              />
            )}
          {!onEdit && !minimized && playing ? (
            <div
              className={css`
                position: absolute;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                font-size: 3rem;
                display: flex;
                align-items: center;
                justify-content: center;
              `}
              style={style}
            >
              <Spinner />
            </div>
          ) : !onEdit ? (
            <a
              className={css`
                position: absolute;
                display: block;
                background: url('/img/play-button-image.png');
                background-size: contain;
                height: 5rem;
                width: 5rem;
                top: 50%;
                left: 50%;
                margin: -2.5rem 0 0 -2.5rem;
              `}
            />
          ) : null}
        </div>
        {isStarred &&
          !!userId && (
            <ProgressBar
              progress={progress}
              noBorderRadius={stretch}
              color={
                justEarned
                  ? Color.green()
                  : xpEarned
                    ? Color.lightBlue()
                    : Color.blue()
              }
              text={
                justEarned
                  ? 'Twinkle XP earned!'
                  : xpEarned
                    ? 'You have already earned this XP'
                    : ''
              }
            />
          )}
      </ErrorBoundary>
    )
  }

  onVideoReady = () => {
    this.setState(() => ({
      totalDuration: this.Player.getDuration()
    }))
  }

  onVideoPlay = () => {
    const {
      currentVideoSlot,
      isStarred,
      videoId,
      userId,
      addVideoView,
      fillCurrentVideoSlot
    } = this.props
    const { justEarned, xpEarned } = this.state
    const time = this.Player.getCurrentTime()
    if (Math.floor(time) === 0) {
      addVideoView({ videoId, userId })
    }
    if (!currentVideoSlot) {
      fillCurrentVideoSlot(Number(videoId))
      if (userId) {
        this.interval = setInterval(this.increaseProgress, intervalLength)
      }
    }
    const authorization = auth()
    const authExists = !!authorization.headers.authorization
    if (authExists && isStarred && !(justEarned || xpEarned)) {
      try {
        request.put(
          `${VIDEO_URL}/currentlyWatching`,
          { videoId },
          authorization
        )
      } catch (error) {
        console.error(error.response || error)
      }
    }
  }

  onVideoStop = () => {
    const { emptyCurrentVideoSlot } = this.props
    clearInterval(this.interval)
    emptyCurrentVideoSlot()
    const authorization = auth()
    const authExists = !!authorization.headers.authorization
    if (authExists) {
      try {
        request.put(
          `${VIDEO_URL}/currentlyWatching`,
          { videoId: null },
          authorization
        )
      } catch (error) {
        console.error(error.response || error)
      }
    }
  }

  increaseProgress = async() => {
    const { justEarned, xpEarned, timeWatched, totalDuration } = this.state
    const { changeUserXP, isStarred, videoId } = this.props
    if (isStarred && !xpEarned && !justEarned && this.Player) {
      if (this.Player.getInternalPlayer().isMuted()) {
        this.Player.getInternalPlayer().unMute()
      }
      if (this.Player.getInternalPlayer().getVolume() < 30) {
        this.Player.getInternalPlayer().setVolume(30)
      }
    }
    if (
      isStarred &&
      timeWatched >= totalDuration / denominator &&
      !this.rewardingXP
    ) {
      this.rewardingXP = true
      try {
        await request.put(`${VIDEO_URL}/xpEarned`, { videoId }, auth())
        await changeUserXP({
          type: 'increase',
          action: 'watch',
          target: 'video',
          targetId: videoId,
          amount: 100
        })
        if (this.mounted) {
          this.setState(() => ({
            justEarned: true,
            xpEarned: true
          }))
        }
        this.rewardingXP = false
      } catch (error) {
        console.error(error.response || error)
      }
    }
    if (!xpEarned && this.mounted) {
      this.setState(state => ({
        timeWatched: state.timeWatched + intervalLength / 1000
      }))
    }
    const authorization = auth()
    const authExists = !!authorization.headers.authorization
    if (authExists) {
      try {
        const {
          data: { currentlyWatchingAnotherVideo, success }
        } = await request.put(
          `${VIDEO_URL}/duration`,
          { videoId, isStarred, xpEarned },
          authorization
        )
        if (success) return
        if (currentlyWatchingAnotherVideo) {
          if (this.Player) this.Player.getInternalPlayer().pauseVideo()
        }
      } catch (error) {
        console.error(error.response || error)
      }
    }
  }
}

export default connect(
  state => ({
    chatMode: state.ChatReducer.chatMode,
    userId: state.UserReducer.userId,
    pageVisible: state.ViewReducer.pageVisible,
    currentVideoSlot: state.VideoReducer.currentVideoSlot
  }),
  {
    addVideoView,
    changeUserXP,
    fillCurrentVideoSlot,
    emptyCurrentVideoSlot
  }
)(VideoPlayer)
<|endoftext|>


<commit_before>'use strict';

/* global Connector */

Connector.playerSelector = $('#tracks-async').length ? '#tracks-async' : ($('.band-col-right').length ? '.band-col-right' : '.album-tracks');

Connector.getArtistTrack = function () {
	var text = $('.play').attr('download');
	var separator = this.findSeparator(text);

	var artist = null;
	var track = null;

	if (separator !== null) {
		artist = text.substr(0, separator.index);
		track = text.substr(separator.index + separator.length);
	}

	return {artist: artist, track: track};
};

Connector.isPlaying = function () {
	return $('.play:contains("ll")').length;
};
<commit_msg>Fix Sullen-Ural connector<commit_after>'use strict';

/* global Connector */

Connector.playerSelector = $('#tracks-async').length ? '#tracks-async' : ($('.band-col-right').length ? '.band-col-right' : '.album-tracks');

Connector.getArtistTrack = function () {
	var text = $('.play:contains("ll")').attr('download');
	var separator = this.findSeparator(text);

	var artist = null;
	var track = null;

	if (separator !== null) {
		artist = text.substr(0, separator.index);
		track = text.substr(separator.index + separator.length);
	}

	return {artist: artist, track: track};
};

Connector.isPlaying = function () {
	return $('.play:contains("ll")').length;
};
<|endoftext|>


<commit_before>'use strict';

// Requirements
const JspConfiguration = require('entoj-export-jsp').export.JspConfiguration;
const co = require('co');

/**
 * @memberOf export.fluid
 * @extends export.Configuration
 */
class CmConfiguration extends JspConfiguration
{
    /**
     * @inheritDoc
     */
    static get className()
    {
        return 'export/CmConfiguration';
    }

    /**
     * @inheritDoc
     */
    generateType(configuration, overrides)
    {
        // Override type via settings
        if (overrides && typeof overrides.type === 'string')
        {
            configuration.type = overrides.type;
        }

        // add namespace
        configuration.namespace = '';
        if (configuration.type)
        {
            const typeParts = configuration.type.split('.');
            if (typeParts.length > 1)
            {
                configuration.type = typeParts.pop();
                configuration.namespace = typeParts.join('.');
            }
        }

        return configuration;
    }

    /**
     * @inheritDoc
     */
    generateViewProperties(configuration, overrides)
    {
        // get export configs
        const exportConfigs = (configuration.macro && this.macro && configuration.macro.name !== this.macro.name)
            ? configuration.entity.properties.getByPath('export.' + this.identifier + '', [])
            : [];
        let macroConfigurationAvailable = false;

        // add view
        if (typeof configuration.view !== 'string')
        {
            if (exportConfigs.length)
            {
                // use the view settings for the designated macro
                if (configuration.macro)
                {
                    const item = this.filterExportConfigByMacroName(exportConfigs, configuration.macro.name);
                    if (item)
                    {
                        configuration.view = item.view;
                        configuration.viewVariant = item.viewVariant || false;
                        macroConfigurationAvailable = true;
                    }
                    // if there is no match use the settings of the first config
                    else
                    {
                        configuration.view = exportConfigs[0].view || false;
                    }
                }
                // if there is no match use the settings of the first config
                else{
                    configuration.view = exportConfigs[0].view || false;
                }
            }
            // when we have a mscoe generate from name
            if (!configuration.view && configuration.macro)
            {
                configuration.view = configuration.macro.name.dasherize();
            }
            // otherwise generate from entity name
            if (!configuration.view)
            {
                configuration.view = configuration.entity.idString.dasherize();
            }
        }

        // Override view via settings
        if (overrides && typeof overrides.view === 'string')
        {
            configuration.view = overrides.view;
        }

        // add viewVariant
        if (!configuration.viewVariant && !macroConfigurationAvailable)
        {
            // if possible get the viewVariant of the first export
            if (exportConfigs && exportConfigs.length)
            {
                configuration.viewVariant = exportConfigs[0].viewVariant || false;
            }
        }

        // Override viewVariant via settings
        if (overrides && typeof overrides.viewVariant === 'string')
        {
            configuration.viewVariant = overrides.viewVariant;
        }

        return configuration;
    }

    /**
     * filters the configuration, provided by the entity.json, for the designated marco
     * @param exportConfig
     * @param macroName
     */
    filterExportConfigByMacroName(exportConfig, macroName)
    {
        return exportConfig.find(item =>
        {
            if (item.macro && item.macro == macroName)
            {
                return item;
            }
        });
    }

    /**
     * @inheritDocs
     */
    generateFilename(configuration)
    {
        if (!this.settings.filename)
        {
            configuration.filename = '';
            if (configuration.namespace)
            {
                configuration.filename = configuration.namespace + '/';
            }
            configuration.filename+= configuration.type + '.' + configuration.view;
            if (configuration.viewVariant)
            {
                configuration.filename+= '[' + configuration.viewVariant + ']';
            }
            if (!configuration.filename.endsWith('.jsp'))
            {
                configuration.filename+= '.jsp';
            }
        }

        return configuration;
    }

    /**
     * @inheritDocs
     */
    refineConfiguration(configuration)
    {
        const superPromise = super.refineConfiguration(configuration);
        const scope = this;
        const promise = co(function*()
        {
            let result = yield superPromise;

            // defaults
            result.includeMode = 'jsp-include';

            // refine macros
            if (result.macro)
            {
                // get macro settings
                const macroSettings = (scope.settings.settings && scope.settings.settings[result.macro.name])
                    ? scope.settings.settings[result.macro.name]
                    : {};

                // add modelParameter
                result.modelParameter = result.macro.parameters.find(param => param.name === 'model');

                // add type based on modelParameter
                if (!result.type)
                {
                    if (result.modelParameter &&
                        result.modelParameter.type.length &&
                        result.modelParameter.type[0] != '*')
                    {
                        result.type = result.modelParameter.type[0];
                    }
                    else
                    {
                        result.type = 'Object';
                    }
                }

                // generate type
                result = scope.generateType(result, macroSettings);

                // set includeMode
                if (result.namespace.length || result.macro.name.endsWith('_dispatcher'))
                {
                    result.includeMode = 'cm-include';
                }

                // set cm specifics
                if (result.includeMode == 'cm-include')
                {
                    result = scope.generateViewProperties(result, macroSettings);
                    result = scope.generateFilename(result, macroSettings);
                }
            }
            // refine templates
            else
            {
                result = scope.generateType(result);
                result = scope.generateViewProperties(result);
                result = scope.generateFilename(result);
            }
            return result;
        });
        return promise;
    }
}

// Exports
module.exports.CmConfiguration = CmConfiguration;
<commit_msg>fix: corrects linter warnings<commit_after>'use strict';

// Requirements
const JspConfiguration = require('entoj-export-jsp').export.JspConfiguration;
const co = require('co');

/**
 * @memberOf export.fluid
 * @extends export.Configuration
 */
class CmConfiguration extends JspConfiguration
{
    /**
     * @inheritDoc
     */
    static get className()
    {
        return 'export/CmConfiguration';
    }

    /**
     * @inheritDoc
     */
    generateType(configuration, overrides)
    {
        // Override type via settings
        if (overrides && typeof overrides.type === 'string')
        {
            configuration.type = overrides.type;
        }

        // add namespace
        configuration.namespace = '';
        if (configuration.type)
        {
            const typeParts = configuration.type.split('.');
            if (typeParts.length > 1)
            {
                configuration.type = typeParts.pop();
                configuration.namespace = typeParts.join('.');
            }
        }

        return configuration;
    }

    /**
     * @inheritDoc
     */
    generateViewProperties(configuration, overrides)
    {
        // get export configs
        const exportConfigs = (configuration.macro && this.macro && configuration.macro.name !== this.macro.name)
            ? configuration.entity.properties.getByPath('export.' + this.identifier + '', [])
            : [];
        let macroConfigurationAvailable = false;

        // add view
        if (typeof configuration.view !== 'string')
        {
            if (exportConfigs.length)
            {
                // use the view settings for the designated macro
                if (configuration.macro)
                {
                    const item = this.filterExportConfigByMacroName(exportConfigs, configuration.macro.name);
                    if (item)
                    {
                        configuration.view = item.view;
                        configuration.viewVariant = item.viewVariant || false;
                        macroConfigurationAvailable = true;
                    }
                    // if there is no match use the settings of the first config
                    else
                    {
                        configuration.view = exportConfigs[0].view || false;
                    }
                }
                // if there is no match use the settings of the first config
                else
                {
                    configuration.view = exportConfigs[0].view || false;
                }
            }
            // when we have a mscoe generate from name
            if (!configuration.view && configuration.macro)
            {
                configuration.view = configuration.macro.name.dasherize();
            }
            // otherwise generate from entity name
            if (!configuration.view)
            {
                configuration.view = configuration.entity.idString.dasherize();
            }
        }

        // Override view via settings
        if (overrides && typeof overrides.view === 'string')
        {
            configuration.view = overrides.view;
        }

        // add viewVariant
        if (!configuration.viewVariant && !macroConfigurationAvailable)
        {
            // if possible get the viewVariant of the first export
            if (exportConfigs && exportConfigs.length)
            {
                configuration.viewVariant = exportConfigs[0].viewVariant || false;
            }
        }

        // Override viewVariant via settings
        if (overrides && typeof overrides.viewVariant === 'string')
        {
            configuration.viewVariant = overrides.viewVariant;
        }

        return configuration;
    }

    /**
     * filters the configuration, provided by the entity.json, for the designated marco
     * @param exportConfig
     * @param macroName
     */
    filterExportConfigByMacroName(exportConfig, macroName)
    {
        return exportConfig.find(item =>
        {
            if (item.macro && item.macro == macroName)
            {
                return item;
            }
        });
    }

    /**
     * @inheritDocs
     */
    generateFilename(configuration)
    {
        if (!this.settings.filename)
        {
            configuration.filename = '';
            if (configuration.namespace)
            {
                configuration.filename = configuration.namespace + '/';
            }
            configuration.filename+= configuration.type + '.' + configuration.view;
            if (configuration.viewVariant)
            {
                configuration.filename+= '[' + configuration.viewVariant + ']';
            }
            if (!configuration.filename.endsWith('.jsp'))
            {
                configuration.filename+= '.jsp';
            }
        }

        return configuration;
    }

    /**
     * @inheritDocs
     */
    refineConfiguration(configuration)
    {
        const superPromise = super.refineConfiguration(configuration);
        const scope = this;
        const promise = co(function*()
        {
            let result = yield superPromise;

            // defaults
            result.includeMode = 'jsp-include';

            // refine macros
            if (result.macro)
            {
                // get macro settings
                const macroSettings = (scope.settings.settings && scope.settings.settings[result.macro.name])
                    ? scope.settings.settings[result.macro.name]
                    : {};

                // add modelParameter
                result.modelParameter = result.macro.parameters.find(param => param.name === 'model');

                // add type based on modelParameter
                if (!result.type)
                {
                    if (result.modelParameter &&
                        result.modelParameter.type.length &&
                        result.modelParameter.type[0] != '*')
                    {
                        result.type = result.modelParameter.type[0];
                    }
                    else
                    {
                        result.type = 'Object';
                    }
                }

                // generate type
                result = scope.generateType(result, macroSettings);

                // set includeMode
                if (result.namespace.length || result.macro.name.endsWith('_dispatcher'))
                {
                    result.includeMode = 'cm-include';
                }

                // set cm specifics
                if (result.includeMode == 'cm-include')
                {
                    result = scope.generateViewProperties(result, macroSettings);
                    result = scope.generateFilename(result, macroSettings);
                }
            }
            // refine templates
            else
            {
                result = scope.generateType(result);
                result = scope.generateViewProperties(result);
                result = scope.generateFilename(result);
            }
            return result;
        });
        return promise;
    }
}

// Exports
module.exports.CmConfiguration = CmConfiguration;
<|endoftext|>


<commit_before>import { alias } from '@ember/object/computed';
import Component from '@ember/component';
import NewOrEdit from 'shared/mixins/new-or-edit';
import ModalBase from 'shared/mixins/modal-base';
import layout from './template';
import { inject as service } from '@ember/service';
import {
  computed, set, get, observer, setProperties
} from '@ember/object';
import { next } from '@ember/runloop';

export default Component.extend(ModalBase, NewOrEdit, {
  scope: service(),

  layout,
  classNames:    ['large-modal'],
  editing:       true,
  model:         null,

  allNamespaces:     null,
  allProjects:       null,
  tags:              null,

  originalModel:  alias('modalService.modalOpts'),
  init() {
    this._super(...arguments);

    const orig  = get(this, 'originalModel');
    const clone = orig.clone();

    delete clone.services;

    setProperties(this, {
      model:         clone,
      tags:          (get(this, 'primaryResource.tags') || []).join(','),
      allNamespaces: get(this, 'clusterStore').all('namespace'),
      allProjects:   get(this, 'globalStore').all('project')
        .filterBy('clusterId', get(this, 'scope.currentCluster.id')),
    })
  },

  actions: {
    addTag(tag) {
      const tags = get(this, 'primaryResource.tags') || [];

      tags.addObject(tag);

      set(this, 'tags', tags.join(','));
    },

    updateNsQuota(quota) {
      if ( quota ) {
        set(this, 'primaryResource.resourceQuota', { limit: quota });
      } else {
        set(this, 'primaryResource.resourceQuota', null);
      }
    },
  },

  projectDidChange: observer('primaryResource.project.id', function() {
    set(this, 'switchingProject', true);
    next(() => {
      set(this, 'switchingProject', false);
    });
    if ( !get(this, 'primaryResource.project.resourceQuota') ) {
      set(this, 'primaryResource.resourceQuota', null);
    }
  }),

  tagsDidChanged: observer('tags', function() {
    set(this, 'primaryResource.tags', get(this, 'tags').split(',') || []);
  }),

  projectLimit: computed('primaryResource.resourceQuota.{limit}', 'primaryResource.projectId', function() {
    const projectId = get(this, 'primaryResource.projectId');
    const project   = get(this, 'allProjects').findBy('id', projectId);

    return get(project, 'resourceQuota.limit');
  }),

  projectUsedLimit: computed('primaryResource.resourceQuota.{limit}', 'primaryResource.projectId', function() {
    const projectId = get(this, 'primaryResource.projectId');
    const project   = get(this, 'allProjects').findBy('id', projectId);

    return get(project, 'resourceQuota.usedLimit');
  }),

  nsDefaultQuota: computed('primaryResource.resourceQuota.{limit}', 'primaryResource.projectId', function() {
    const projectId = get(this, 'primaryResource.projectId');
    const project   = get(this, 'allProjects').findBy('id', projectId);

    return get(project, 'namespaceDefaultResourceQuota.limit');
  }),

  validate() {
    this._super();

    const errors      = get(this, 'errors') || [];
    const quotaErrors = get(this, 'primaryResource').validateResourceQuota(get(this, 'originalModel.resourceQuota.limit'));

    if ( quotaErrors.length > 0 ) {
      errors.pushObjects(quotaErrors);
    }

    set(this, 'errors', errors);

    return get(this, 'errors.length') === 0;
  },

  doneSaving() {
    this.send('cancel');
  }
});
<commit_msg>Fix edit namespace cannot change project https://github.com/rancher/rancher/issues/16617<commit_after>import { alias } from '@ember/object/computed';
import Component from '@ember/component';
import NewOrEdit from 'shared/mixins/new-or-edit';
import ModalBase from 'shared/mixins/modal-base';
import layout from './template';
import { inject as service } from '@ember/service';
import {
  computed, set, get, observer, setProperties
} from '@ember/object';
import { next } from '@ember/runloop';

export default Component.extend(ModalBase, NewOrEdit, {
  scope: service(),

  layout,
  classNames:    ['large-modal'],
  editing:       true,
  model:         null,

  allNamespaces:     null,
  allProjects:       null,
  tags:              null,
  beforeSaveModel:   null,

  originalModel:  alias('modalService.modalOpts'),
  init() {
    this._super(...arguments);

    const orig  = get(this, 'originalModel');
    const clone = orig.clone();

    delete clone.services;

    setProperties(this, {
      model:         clone,
      tags:          (get(this, 'primaryResource.tags') || []).join(','),
      allNamespaces: get(this, 'clusterStore').all('namespace'),
      allProjects:   get(this, 'globalStore').all('project')
        .filterBy('clusterId', get(this, 'scope.currentCluster.id')),
    })
  },

  actions: {
    addTag(tag) {
      const tags = get(this, 'primaryResource.tags') || [];

      tags.addObject(tag);

      set(this, 'tags', tags.join(','));
    },

    updateNsQuota(quota) {
      if ( quota ) {
        set(this, 'primaryResource.resourceQuota', { limit: quota });
      } else {
        set(this, 'primaryResource.resourceQuota', null);
      }
    },
  },

  projectDidChange: observer('primaryResource.project.id', function() {
    set(this, 'switchingProject', true);
    next(() => {
      set(this, 'switchingProject', false);
    });
    if ( !get(this, 'primaryResource.project.resourceQuota') ) {
      set(this, 'primaryResource.resourceQuota', null);
    }
  }),

  tagsDidChanged: observer('tags', function() {
    set(this, 'primaryResource.tags', get(this, 'tags').split(',') || []);
  }),

  projectLimit: computed('primaryResource.resourceQuota.{limit}', 'primaryResource.projectId', function() {
    const projectId = get(this, 'primaryResource.projectId');
    const project   = get(this, 'allProjects').findBy('id', projectId);

    return get(project, 'resourceQuota.limit');
  }),

  projectUsedLimit: computed('primaryResource.resourceQuota.{limit}', 'primaryResource.projectId', function() {
    const projectId = get(this, 'primaryResource.projectId');
    const project   = get(this, 'allProjects').findBy('id', projectId);

    return get(project, 'resourceQuota.usedLimit');
  }),

  nsDefaultQuota: computed('primaryResource.resourceQuota.{limit}', 'primaryResource.projectId', function() {
    const projectId = get(this, 'primaryResource.projectId');
    const project   = get(this, 'allProjects').findBy('id', projectId);

    return get(project, 'namespaceDefaultResourceQuota.limit');
  }),

  validate() {
    this._super();

    const errors      = get(this, 'errors') || [];
    const quotaErrors = get(this, 'primaryResource').validateResourceQuota(get(this, 'originalModel.resourceQuota.limit'));

    if ( quotaErrors.length > 0 ) {
      errors.pushObjects(quotaErrors);
    }

    set(this, 'errors', errors);

    return get(this, 'errors.length') === 0;
  },

  willSave() {
    set(this, 'beforeSaveModel', get(this, 'originalModel').clone());

    return this._super(...arguments);
  },

  didSave(pr) {
    const { projectId } = pr;

    if ( projectId !== get(this, 'beforeSaveModel.projectId') ) {
      return pr.doAction('move', { projectId }).then((pr) => pr);
    }
  },

  doneSaving() {
    this.send('cancel');
  }
});
<|endoftext|>


<commit_before>var csrftoken = $('meta[name=csrf-token]').attr('content');
var searchFilter = $('#search-filter').val();

$(document).ready(function () {
    $('#li-job').addClass('active');

    $('body').tooltip({
        'selector': '[rel=tooltip]',
        'placement': 'auto'
    });

    $('#table-div').hide();

    var table = $('#jobstable').dataTable({
        'dom': '<"row"<"col-xs-6 col-sm-6 col-md-6 col-lg-6"<"length-menu"l>>' +
            '<"col-xs-4 col-sm-4 col-md-4 col-lg-4 col-lg-offset-2"f>r' +
            '<"col-xs-12 col-sm-12 col-md-12 col-lg-12"t>>' +
            '<"row"<"col-xs-6 col-sm-6 col-md-6 col-lg-6"i>' +
            '<"col-xs-6 col-sm-6 col-md-6 col-lg-6"p>>',
        'language': {
            'lengthMenu': '_MENU_ jobs per page',
            'zeroRecords': '
No jobs to display.
',
            'search': '
_INPUT_
'
        },
        'initComplete': function (settings, data) {
            $("#table-loading").remove();
            $("#table-div").fadeIn("slow", "linear");

            if (searchFilter !== null && searchFilter.length > 0) {
                var api = this.api();
                api.search(searchFilter, true).draw();
            }
        },
        'lengthMenu': [25, 50, 75, 100],
        'deferRender': true,
        'ordering': true,
        'processing': true,
        'stateDuration': -1,
        'stateSave': true,
        'order': [1, 'desc'],
        'search': {
            'regex': true
        },
        'ajax': {
            'url': '/_ajax/job',
            'traditional': true,
            'cache': true,
            'dataType': 'json',
            'dataSrc': 'result',
            'dataFilter': function (data, type) {
                if (type === 'json') {
                    data.result = JSON.stringify(data.result)
                    return data;
                }
                return data;
            },
            'beforeSend': function (xhr) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            'data': {
                'aggregate': 'job',
                'sort': 'created_on',
                'sort_order': -1,
                'field': [
                    'job', 'created_on', 'status', 'metadata'
                ]
            }
        },
        'columns': [
            {
                'data': 'job',
                'title': 'Tree ‐ Branch',
                'type': 'string',
                'render': function (data, type, object) {
                    return '' +
                        data + ' ‐ ' +
                        object.metadata.git_branch + '';
                }
            },
            {
                'data': 'created_on',
                'title': 'Date',
                'type': 'date',
                'render': function (data) {
                    var created = new Date(data['$date']);
                    return created.getCustomISODate();
                }
            },
            {
                'data': 'status',
                'title': 'Status',
                'type': 'string',
                'render': function (data) {
                    var displ;
                    switch (data) {
                        case 'BUILD':
                            displ = '' +
                                '' +
                                '';
                            break;
                        case 'PASS':
                            displ = '' +
                                '' +
                                '';
                            break;
                        case 'FAIL':
                            displ = '' +
                                '' +
                                '' +
                                '';
                            break;
                        default:
                            displ = '' +
                                '' +
                                '' +
                                '';
                            break;
                    }
                    return displ;
                }
            },
            {
                'data': 'job',
                'title': '',
                'searchable': false,
                'orderable': false,
                'width': '30px',
                'className': 'pull-center',
                'render': function (data) {
                    return '' +
                        '' +
                        '';
                }
            }
        ]
    });

    $(document).on("click", "#jobstable tbody tr", function () {
        var data = table.fnGetData(this);
        if (data) {
            window.location = '/job/' + data.job + '/';
        }
    });

    $('#search-area > .input-sm').attr('placeholder', 'Filter the results');
    $('.input-sm').keyup(function (key) {
        // Remove focus from input when Esc is pressed.
        if (key.keyCode === 27) {
            $(this).blur();
        }
    });
});
<commit_msg>jobs: Use batch API to count.<commit_after>var csrftoken = $('meta[name=csrf-token]').attr('content');
var searchFilter = $('#search-filter').val();

$(document).ready(function () {
    "use strict";

    $('#li-job').addClass('active');

    $('body').tooltip({
        'selector': '[rel=tooltip]',
        'placement': 'auto'
    });

    $('#table-div').hide();

    function failedAjaxCall() {
        // TODO
    }

    function countFailCallback() {
        // TODO
        $('.count-badge').each(function () {
            $(this).empty().append('∞');
        });
    }

    function batchCountElements(data) {
        var localData = data.result,
            i = 0,
            j = 0,
            batchElements = 4,
            jobName = '',
            dateRange = $('#date-range').val(),
            len = localData.length,
            queriesLen = len * 4,
            batchQueries = new Array(queriesLen);

        if (len > 0) {
            for (i; i < queriesLen; i += batchElements) {
                j = i;
                jobName = localData[i / batchElements].job;

                // Get successful defconfig count.
                batchQueries[i] = {
                    'method': 'GET',
                    'operation_id': '#defconf-success-count-' + jobName,
                    'collection': 'count',
                    'document_id': 'defconfig',
                    'query': 'status=PASS&date_range=' + dateRange +
                        '&job=' + jobName
                };

                // Get failed defconfig count.
                batchQueries[j + 1] = {
                    'method': 'GET',
                    'operation_id': '#defconf-fail-count-' + jobName,
                    'collection': 'count',
                    'document_id': 'defconfig',
                    'query': 'status=FAIL&date_range=' + dateRange +
                        '&job=' + jobName
                };

                // Get successful boot reports count.
                batchQueries[j + 2] = {
                    'method': 'GET',
                    'operation_id': '#boot-success-count-' + jobName,
                    'collection': 'count',
                    'document_id': 'boot',
                    'query': 'status=FAIL&date_range=' + dateRange +
                        '&job=' + jobName
                };

                // Get failed boot reports count.
                batchQueries[j + 3] = {
                    'method': 'GET',
                    'operation_id': '#boot-fail-count-' + jobName,
                    'collection': 'count',
                    'document_id': 'boot',
                    'query': 'status=FAIL&date_range=' + dateRange +
                        '&job=' + jobName
                };
            }

            $.ajax({
                'url': '/_ajax/batch',
                'type': 'POST',
                'traditional': true,
                'dataType': 'json',
                'headers': {
                    'Content-Type': 'application/json'
                },
                'beforeSend': function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                },
                'data': JSON.stringify({
                    'batch': batchQueries
                }),
                'error': countFailCallback
            }).done(function (data) {
                var batchData = data.result,
                    batchLen = batchData.length,
                    batchResult = null,
                    idx = 0;

                if (batchLen > 0) {
                    for (idx; idx < batchLen; idx++) {
                        batchResult = batchData[idx].result[0];
                        $(batchData[idx].operation_id).empty().append(
                            batchResult.count);
                    }
                }
            });
        }
    }

    function createJobsTable(data) {
        var localData = data.result,
            table = $('#jobstable').dataTable({
            'dom': '<"row"<"col-xs-6 col-sm-6 col-md-6 col-lg-6"<"length-menu"l>>' +
                '<"col-xs-4 col-sm-4 col-md-4 col-lg-4 col-lg-offset-2"f>r' +
                '<"col-xs-12 col-sm-12 col-md-12 col-lg-12"t>>' +
                '<"row"<"col-xs-6 col-sm-6 col-md-6 col-lg-6"i>' +
                '<"col-xs-6 col-sm-6 col-md-6 col-lg-6"p>>',
            'language': {
                'lengthMenu': '_MENU_ jobs per page',
                'zeroRecords': '
No jobs to display.
',
                'search': '
_INPUT_
'
            },
            'initComplete': function (settings, data) {
                $("#table-loading").remove();
                $("#table-div").fadeIn("slow", "linear");

                if (searchFilter !== null && searchFilter.length > 0) {
                    var api = this.api();
                    api.search(searchFilter, true).draw();
                }
            },
            'lengthMenu': [25, 50, 75, 100],
            'deferRender': true,
            'ordering': true,
            'processing': true,
            'stateDuration': -1,
            'stateSave': true,
            'order': [3, 'desc'],
            'search': {
                'regex': true
            },
            'data': localData,
            'columns': [
                {
                    'data': 'job',
                    'title': 'Tree ‐ Branch',
                    'type': 'string',
                    'render': function (data, type, object) {
                        return '' +
                            data + ' ‐ ' +
                            object.metadata.git_branch + '';
                    }
                },
                {
                    'data': 'job',
                    'title': '' +
                        'Build Status',
                    'type': 'String',
                    'searchable': false,
                    'orderable': false,
                    'className': 'pull-center',
                    'render': function(data) {
                        return '' +
                            '' +
                            '' +
                            '' +
                            ' ' +
                            '' +
                            '' +
                            '' +
                            '';
                    }
                },
                {
                    'data': 'job',
                    'title': '' +
                        'Boot Status',
                    'type': 'string',
                    'searchable': false,
                    'orderable': false,
                    'className': 'pull-center',
                    'render': function(data) {
                        return '' +
                            '' +
                            '' +
                            '' +
                            ' ' +
                            '' +
                            '' +
                            '' +
                            '';
                    }
                },
                {
                    'data': 'created_on',
                    'title': 'Date',
                    'type': 'date',
                    'render': function (data) {
                        var created = new Date(data['$date']);
                        return created.getCustomISODate();
                    }
                },
                {
                    'data': 'status',
                    'title': 'Status',
                    'type': 'string',
                    'className': 'pull-center',
                    'render': function (data) {
                        var displ;
                        switch (data) {
                            case 'BUILD':
                                displ = '' +
                                    '' +
                                    '';
                                break;
                            case 'PASS':
                                displ = '' +
                                    '' +
                                    '';
                                break;
                            case 'FAIL':
                                displ = '' +
                                    '' +
                                    '' +
                                    '';
                                break;
                            default:
                                displ = '' +
                                    '' +
                                    '' +
                                    '';
                                break;
                        }
                        return displ;
                    }
                },
                {
                    'data': 'job',
                    'title': '',
                    'searchable': false,
                    'orderable': false,
                    'width': '30px',
                    'className': 'pull-center',
                    'render': function (data) {
                        return '' +
                            '' +
                            '';
                    }
                }
            ]
        });

        $(document).on("click", "#jobstable tbody tr", function () {
            var tableData = table.fnGetData(this);
            if (tableData) {
                window.location = '/job/' + tableData.job + '/';
            }
        });

        $('#search-area > .input-sm').attr('placeholder', 'Filter the results');
        $('.input-sm').keyup(function (key) {
            // Remove focus from input when Esc is pressed.
            if (key.keyCode === 27) {
                $(this).blur();
            }
        });

        return data;
    }

    function updateJobsPage(data) {
        // Simple function needed to wrap another deferred call.
        // Create the table, then update it with the batch count operation.
        $.when(createJobsTable(data)).then(batchCountElements);
    }

    var getDataAjax = $.ajax({
        'url': '/_ajax/job',
        'traditional': true,
        'cache': true,
        'dataType': 'json',
        'dataSrc': 'result',
        'beforeSend': function (xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        'data': {
            'aggregate': 'job',
            'sort': 'created_on',
            'sort_order': -1,
            'date_range': $('#date-range').val(),
            'field': [
                'job', 'created_on', 'status', 'metadata'
            ]
        }
    });

    $.when(getDataAjax).then(updateJobsPage, failedAjaxCall);
});
<|endoftext|>


<commit_before>import upperFirst from 'lodash/upperFirst';
import PropTypes from 'prop-types';
import React from 'react';
import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';

import injectT from '../../../i18n/injectT';
import WrappedText from '../../../shared/wrapped-text/WrappedText';
import { getServiceMapUrl } from '../../../utils/unitUtils';
import ReservationInfo from '../reservation-info/ReservationInfo';
import Equipment from '../resource-equipment/ResourceEquipment';
import ResourcePanel from './ResourcePanel';

function ResourceInfo({
  isLoggedIn, resource, unit, t
}) {
  const serviceMapUrl = getServiceMapUrl(unit);

  return (

      {resource.description && (
        <ResourcePanel header={t('ResourceInfo.descriptionTitle')}>

            {resource.description && <WrappedText openLinksInNewTab text={resource.description} />}

        </ResourcePanel>
      )}

      <ResourcePanel header={t('ResourceInfo.reservationTitle')}>
        <ReservationInfo isLoggedIn={isLoggedIn} resource={resource} />
      </ResourcePanel>

      {resource.specificTerms && (
        <ResourcePanel header={t('ResourcePage.specificTerms')}>

{resource.specificTerms}

        </ResourcePanel>
      )}
      <ResourcePanel header={t('ResourceInfo.additionalInfoTitle')}>
        <Row>
          <Col className="app-ResourceInfo__address" xs={6}>
            {unit && unit.name && {unit.name}}
            {unit && unit.streetAddress && {unit.streetAddress}}
            {unit && {`${unit.addressZip} ${upperFirst(unit.municipality)}`.trim()}}
          </Col>
          <Col className="app-ResourceInfo__web" xs={6}>
            {serviceMapUrl && (

                  {t('ResourceInfo.serviceMapLink')}

            )}
            {unit && unit.wwwUrl && (

                  {unit.wwwUrl}

            )}
          </Col>
        </Row>
      </ResourcePanel>

      { resource.equipment.length > 0 && (<Equipment equipment={resource.equipment} />) }

  );
}

ResourceInfo.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  resource: PropTypes.object.isRequired,
  t: PropTypes.func.isRequired,
  unit: PropTypes.object.isRequired,
};

ResourceInfo = injectT(ResourceInfo); // eslint-disable-line

export default ResourceInfo;
<commit_msg>Remove redundant condition check from Resource Description<commit_after>import upperFirst from 'lodash/upperFirst';
import PropTypes from 'prop-types';
import React from 'react';
import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';

import injectT from '../../../i18n/injectT';
import WrappedText from '../../../shared/wrapped-text/WrappedText';
import { getServiceMapUrl } from '../../../utils/unitUtils';
import ReservationInfo from '../reservation-info/ReservationInfo';
import Equipment from '../resource-equipment/ResourceEquipment';
import ResourcePanel from './ResourcePanel';

function ResourceInfo({
  isLoggedIn, resource, unit, t
}) {
  const serviceMapUrl = getServiceMapUrl(unit);

  return (

      {resource.description && (
        <ResourcePanel header={t('ResourceInfo.descriptionTitle')}>

            <WrappedText openLinksInNewTab text={resource.description} />

        </ResourcePanel>
      )}

      <ResourcePanel header={t('ResourceInfo.reservationTitle')}>
        <ReservationInfo isLoggedIn={isLoggedIn} resource={resource} />
      </ResourcePanel>

      {resource.specificTerms && (
        <ResourcePanel header={t('ResourcePage.specificTerms')}>

{resource.specificTerms}

        </ResourcePanel>
      )}
      <ResourcePanel header={t('ResourceInfo.additionalInfoTitle')}>
        <Row>
          <Col className="app-ResourceInfo__address" xs={6}>
            {unit && unit.name && {unit.name}}
            {unit && unit.streetAddress && {unit.streetAddress}}
            {unit && {`${unit.addressZip} ${upperFirst(unit.municipality)}`.trim()}}
          </Col>
          <Col className="app-ResourceInfo__web" xs={6}>
            {serviceMapUrl && (

                  {t('ResourceInfo.serviceMapLink')}

            )}
            {unit && unit.wwwUrl && (

                  {unit.wwwUrl}

            )}
          </Col>
        </Row>
      </ResourcePanel>

      { resource.equipment.length > 0 && (<Equipment equipment={resource.equipment} />) }

  );
}

ResourceInfo.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  resource: PropTypes.object.isRequired,
  t: PropTypes.func.isRequired,
  unit: PropTypes.object.isRequired,
};

ResourceInfo = injectT(ResourceInfo); // eslint-disable-line

export default ResourceInfo;
<|endoftext|>


<commit_before>import template from './project-create.html';

const projectCreate = {
  template: template,
  controller: ProjectAddController,
  controllerAs: 'ProjectAdd',
};

export default projectCreate;

// @ngInject
function ProjectAddController(
  projectsService,
  currentStateService,
  certificationsService,
  baseControllerAddClass,
  $q,
  $rootScope,
  $state,
  ncUtils,
  ncUtilsFlash) {
  var controllerScope = this;
  var ProjectController = baseControllerAddClass.extend({
    userRole: 'admin',
    init: function() {
      this.service = projectsService;
      this.controllerScope = controllerScope;
      this._super();
      this.detailsState = 'project.details';
      this.redirectToDetailsPage = true;
      this.project = this.instance;
      this.certifications = [];
    },
    activate: function() {
      this.loading = true;
      $q.all([
        this.loadCustomer(),
        this.loadCertificates()
      ]).finally(() => this.loading = false);
    },
    loadCustomer: function() {
      return currentStateService.getCustomer().then(customer => {
        this.project.customer = customer.url;
        if (ncUtils.isCustomerQuotaReached(customer, 'project')) {
          $state.go('errorPage.limitQuota');
        }
      });
    },
    loadCertificates: function() {
      return certificationsService.getAll().then(certifications => {
        this.certifications = certifications;
      });
    },
    beforeSave: function() {
      this.project.certifications = this.projectCertifications.map(item => ({url: item.url}));
    },
    afterSave: function(project) {
      $rootScope.$broadcast('refreshProjectList', {
        model: project, new: true, current: true
      });
      this._super();
    },
    onError: function(errorObject) {
      ncUtilsFlash.error(errorObject.data.detail);
    },
    cancel: function() {
      currentStateService.getCustomer().then(function(customer) {
        $state.go('organization.projects', {uuid: customer.uuid});
      });
    }
  });

  controllerScope.__proto__ = new ProjectController();
}
<commit_msg>Fix SENTRY-626.<commit_after>import template from './project-create.html';

const projectCreate = {
  template: template,
  controller: ProjectAddController,
  controllerAs: 'ProjectAdd',
};

export default projectCreate;

// @ngInject
function ProjectAddController(
  projectsService,
  currentStateService,
  certificationsService,
  baseControllerAddClass,
  $q,
  $rootScope,
  $state,
  ncUtils,
  ncUtilsFlash) {
  var controllerScope = this;
  var ProjectController = baseControllerAddClass.extend({
    userRole: 'admin',
    init: function() {
      this.service = projectsService;
      this.controllerScope = controllerScope;
      this._super();
      this.detailsState = 'project.details';
      this.redirectToDetailsPage = true;
      this.project = this.instance;
      this.certifications = [];
      this.projectCertifications = [];
    },
    activate: function() {
      this.loading = true;
      $q.all([
        this.loadCustomer(),
        this.loadCertificates()
      ]).finally(() => this.loading = false);
    },
    loadCustomer: function() {
      return currentStateService.getCustomer().then(customer => {
        this.project.customer = customer.url;
        if (ncUtils.isCustomerQuotaReached(customer, 'project')) {
          $state.go('errorPage.limitQuota');
        }
      });
    },
    loadCertificates: function() {
      return certificationsService.getAll().then(certifications => {
        this.certifications = certifications;
      });
    },
    beforeSave: function() {
      this.project.certifications = this.projectCertifications.map(item => ({url: item.url}));
    },
    afterSave: function(project) {
      $rootScope.$broadcast('refreshProjectList', {
        model: project, new: true, current: true
      });
      this._super();
    },
    onError: function(errorObject) {
      ncUtilsFlash.error(errorObject.data.detail);
    },
    cancel: function() {
      currentStateService.getCustomer().then(function(customer) {
        $state.go('organization.projects', {uuid: customer.uuid});
      });
    }
  });

  controllerScope.__proto__ = new ProjectController();
}
<|endoftext|>


<commit_before>/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 */

var _lut = [];

for ( var i = 0; i < 256; i ++ ) {

	_lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );

}

var MathUtils = {

	DEG2RAD: Math.PI / 180,
	RAD2DEG: 180 / Math.PI,

	generateUUID: function () {

		// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136

		var d0 = Math.random() * 0xffffffff | 0;
		var d1 = Math.random() * 0xffffffff | 0;
		var d2 = Math.random() * 0xffffffff | 0;
		var d3 = Math.random() * 0xffffffff | 0;
		var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
			_lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
			_lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
			_lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];

		// .toUpperCase() here flattens concatenated strings to save heap memory space.
		return uuid.toUpperCase();

	},

	clamp: function ( value, min, max ) {

		return Math.max( min, Math.min( max, value ) );

	},

	// compute euclidian modulo of m % n
	// https://en.wikipedia.org/wiki/Modulo_operation

	euclideanModulo: function ( n, m ) {

		return ( ( n % m ) + m ) % m;

	},

	// Linear mapping from range <a1, a2> to range <b1, b2>

	mapLinear: function ( x, a1, a2, b1, b2 ) {

		return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );

	},

	// https://en.wikipedia.org/wiki/Linear_interpolation

	lerp: function ( x, y, t ) {

		return ( 1 - t ) * x + t * y;

	},

	// http://en.wikipedia.org/wiki/Smoothstep

	smoothstep: function ( x, min, max ) {

		if ( x <= min ) return 0;
		if ( x >= max ) return 1;

		x = ( x - min ) / ( max - min );

		return x * x * ( 3 - 2 * x );

	},

	smootherstep: function ( x, min, max ) {

		if ( x <= min ) return 0;
		if ( x >= max ) return 1;

		x = ( x - min ) / ( max - min );

		return x * x * x * ( x * ( x * 6 - 15 ) + 10 );

	},

	// Random integer from <low, high> interval

	randInt: function ( low, high ) {

		return low + Math.floor( Math.random() * ( high - low + 1 ) );

	},

	// Random float from <low, high> interval

	randFloat: function ( low, high ) {

		return low + Math.random() * ( high - low );

	},

	// Random float from <-range/2, range/2> interval

	randFloatSpread: function ( range ) {

		return range * ( 0.5 - Math.random() );

	},

	degToRad: function ( degrees ) {

		return degrees * MathUtils.DEG2RAD;

	},

	radToDeg: function ( radians ) {

		return radians * MathUtils.RAD2DEG;

	},

	isPowerOfTwo: function ( value ) {

		return ( value & ( value - 1 ) ) === 0 && value !== 0;

	},

	ceilPowerOfTwo: function ( value ) {

		return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );

	},

	floorPowerOfTwo: function ( value ) {

		return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );

	},

	setQuaternionFromProperEuler: function ( q, a, b, c, order ) {

		// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles

		// rotations are applied to the axes in the order specified by 'order'
		// rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
		// angles are in radians

		var cos = Math.cos;
		var sin = Math.sin;

		var c2 = cos( b / 2 );
		var s2 = sin( b / 2 );

		var c13 = cos( ( a + c ) / 2 );
		var s13 = sin( ( a + c ) / 2 );

		var c1_3 = cos( ( a - c ) / 2 );
		var s1_3 = sin( ( a - c ) / 2 );

		var c3_1 = cos( ( c - a ) / 2 );
		var s3_1 = sin( ( c - a ) / 2 );

		if ( order === 'XYX' ) {

			q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );

		} else if ( order === 'YZY' ) {

			q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );

		} else if ( order === 'ZXZ' ) {

			q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );

		} else if ( order === 'XZX' ) {

			q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );

		} else if ( order === 'YXY' ) {

			q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );

		} else if ( order === 'ZYZ' ) {

			q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );

		} else {

			console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.' );

		}

	}

};

export { MathUtils };
<commit_msg>Restore attribution<commit_after>/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author thezwap
 */

var _lut = [];

for ( var i = 0; i < 256; i ++ ) {

	_lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );

}

var MathUtils = {

	DEG2RAD: Math.PI / 180,
	RAD2DEG: 180 / Math.PI,

	generateUUID: function () {

		// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136

		var d0 = Math.random() * 0xffffffff | 0;
		var d1 = Math.random() * 0xffffffff | 0;
		var d2 = Math.random() * 0xffffffff | 0;
		var d3 = Math.random() * 0xffffffff | 0;
		var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
			_lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
			_lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
			_lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];

		// .toUpperCase() here flattens concatenated strings to save heap memory space.
		return uuid.toUpperCase();

	},

	clamp: function ( value, min, max ) {

		return Math.max( min, Math.min( max, value ) );

	},

	// compute euclidian modulo of m % n
	// https://en.wikipedia.org/wiki/Modulo_operation

	euclideanModulo: function ( n, m ) {

		return ( ( n % m ) + m ) % m;

	},

	// Linear mapping from range <a1, a2> to range <b1, b2>

	mapLinear: function ( x, a1, a2, b1, b2 ) {

		return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );

	},

	// https://en.wikipedia.org/wiki/Linear_interpolation

	lerp: function ( x, y, t ) {

		return ( 1 - t ) * x + t * y;

	},

	// http://en.wikipedia.org/wiki/Smoothstep

	smoothstep: function ( x, min, max ) {

		if ( x <= min ) return 0;
		if ( x >= max ) return 1;

		x = ( x - min ) / ( max - min );

		return x * x * ( 3 - 2 * x );

	},

	smootherstep: function ( x, min, max ) {

		if ( x <= min ) return 0;
		if ( x >= max ) return 1;

		x = ( x - min ) / ( max - min );

		return x * x * x * ( x * ( x * 6 - 15 ) + 10 );

	},

	// Random integer from <low, high> interval

	randInt: function ( low, high ) {

		return low + Math.floor( Math.random() * ( high - low + 1 ) );

	},

	// Random float from <low, high> interval

	randFloat: function ( low, high ) {

		return low + Math.random() * ( high - low );

	},

	// Random float from <-range/2, range/2> interval

	randFloatSpread: function ( range ) {

		return range * ( 0.5 - Math.random() );

	},

	degToRad: function ( degrees ) {

		return degrees * MathUtils.DEG2RAD;

	},

	radToDeg: function ( radians ) {

		return radians * MathUtils.RAD2DEG;

	},

	isPowerOfTwo: function ( value ) {

		return ( value & ( value - 1 ) ) === 0 && value !== 0;

	},

	ceilPowerOfTwo: function ( value ) {

		return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );

	},

	floorPowerOfTwo: function ( value ) {

		return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );

	},

	setQuaternionFromProperEuler: function ( q, a, b, c, order ) {

		// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles

		// rotations are applied to the axes in the order specified by 'order'
		// rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
		// angles are in radians

		var cos = Math.cos;
		var sin = Math.sin;

		var c2 = cos( b / 2 );
		var s2 = sin( b / 2 );

		var c13 = cos( ( a + c ) / 2 );
		var s13 = sin( ( a + c ) / 2 );

		var c1_3 = cos( ( a - c ) / 2 );
		var s1_3 = sin( ( a - c ) / 2 );

		var c3_1 = cos( ( c - a ) / 2 );
		var s3_1 = sin( ( c - a ) / 2 );

		if ( order === 'XYX' ) {

			q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );

		} else if ( order === 'YZY' ) {

			q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );

		} else if ( order === 'ZXZ' ) {

			q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );

		} else if ( order === 'XZX' ) {

			q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );

		} else if ( order === 'YXY' ) {

			q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );

		} else if ( order === 'ZYZ' ) {

			q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );

		} else {

			console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.' );

		}

	}

};

export { MathUtils };
<|endoftext|>


<commit_before>// Some test here
<commit_msg>Add scaffolding components test<commit_after>describe('{{nameUpper}} component', function() {
  var $compile,
      $rootScope;

  beforeEach(module('app'));

  beforeEach(inject(function(_$compile_, _$rootScope_){
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  it('should set some component', function() {
    // Compile a piece of HTML containing the directive
    var element = $compile("<{{nameSlugified}}></{{nameSlugified}}>")($rootScope);
    // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
    $rootScope.$digest();
    // Check that the compiled element contains the templated content
    //expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
  });
});
<|endoftext|>


<commit_before>const Discord = require('discord.js');
module.exports = member => {
    const modlog = member.guild.channels.find('name', 'pie-log');
    var role = "SendMessage"
const send = member.guild.roles.find('name', 'SendMessage');
const PTE = member.guild.roles.find('name', 'Private (PTE)');
const LCP = member.guild.roles.find('name', 'Lance Corporal (LCP)');
const CPL = member.guild.roles.find('name', 'Corporal (CPL)');

const SG = member.guild.roles.find('name', 'Sergeant (SG)');
const SSG = member.guild.roles.find('name', 'Staff Sergeant (SSG)');
const MSG = member.guild.roles.find('name', 'Master Sergeant (MSG)');

const WO = member.guild.roles.find('name', 'Warrant Officer (WO)');
const SWO = member.guild.roles.find('name', 'Senior Warrant Officer (SWO)');
const CWO = member.guild.roles.find('name', 'Chief Warrant Officer (CWO)');

const TWOLT = member.guild.roles.find('name', '2nd Lieutenant (2LT)');
const LTA = member.guild.roles.find('name', 'Lieutenant (LTA)');
const CPT = member.guild.roles.find('name', 'Captain (CPT)');

const MAJ = member.guild.roles.find('name', 'Major (MAJ)');
const LTC = member.guild.roles.find('name', 'Lieutenant Colonel (LTC)');
const COL = member.guild.roles.find('name', 'Colonel (COL)');

const BG = member.guild.roles.find('name', 'Brigadier/Major General (BG/MG)');
const LG = member.guild.roles.find('name', 'Lieutenant-General (LG)');

const VCDF = member.guild.roles.find('name', 'Vice Chief of Defence Force (VCDF)');
const CDF = member.guild.roles.find('name', 'Chief of Defense Force (CDF)');

if (member.guild.member(member.user).roles.has(send.id)) {
  role = "SendMessage"
} else {
  if (member.guild.member(member.user).roles.has(PTE.id)) {
    role = "Private (PTE)"
} else {
  if (member.guild.member(member.user).roles.has(LCP.id)) {
    role = "Lance Corporal (LCP)"
}  else {
  if (member.guild.member(member.user).roles.has(CPL.id)) {
    role = "Corporal (CPL)"
}  else {
  if (member.guild.member(member.user).roles.has(SG.id)) {
    role = "Sergeant (SG)"
} else {
  if (member.guild.member(member.user).roles.has(SSG.id)) {
    role = "Staff Sergeant (SSG)"
} else {
  if (member.guild.member(member.user).roles.has(MSG.id)) {
    role = "Master Sergeant (MSG)"
} else {
  if (member.guild.member(member.user).roles.has(WO.id)) {
    role = "Warrant Officer (WO)"
} else {
  if (member.guild.member(member.user).roles.has(SWO.id)) {
    role = "Senior Warrant Officer (SWO)"
  } else {
    if (member.guild.member(member.user).roles.has(CWO.id)) {
      role = "Chief Warrant Officer (CWO)"
    } else {
      if (member.guild.member(member.user).roles.has(TWOLT.id)) {
        role = "2nd Lieutenant (2LT)"
      } else {
        if (member.guild.member(member.user).roles.has(LTA.id)) {
          role = "Lieutenant (LTA)"
        } else {
          if (member.guild.member(member.user).roles.has(CPT.id)) {
            role = "Captain (CPT)"
          } else {
            if (member.guild.member(member.user).roles.has(MAJ.id)) {
              role = "Major (MAJ)"
            } else {
              if (member.guild.member(member.user).roles.has(LTC.id)) {
                role = "Lieutenant Colonel (LTC)"
              } else {
                if (member.guild.member(member.user).roles.has(COL.id)) {
                  role = "Colonel (COL)"
                } else {
                  if (member.guild.member(member.user).roles.has(BG.id)) {
                    role = "Brigadier/Major General (BG/MG)"
                  } else {
                    if (member.guild.member(member.user).roles.has(LG.id)) {
                      role = "Lieutenant General (LG)"
                    } else {
                      if (member.guild.member(member.user).roles.has(VCDF.id)) {
                        role = "Vice Chief of Defense (VCDF)"
                      } else {
                        if (member.guild.member(member.user).roles.has(CDF.id)) {
                          role = "Chief of Defense (VCDF)"
                        }
                      }
                    }
                  }
                }
              }
            }            }
          }
        }
      }
    }
  }
}            }
}
}
}
}
    //${member.user.username}
    const embed = new Discord.RichEmbed()
    .setTimestamp()
    .setColor(0xff0000)
    .setTitle("User Left")
    .setThumbnail(`${member.user.avatarURL}`)
    .setDescription(`\n`)
    .addField("Username:",`${member.user.username} (${member.user})`,true)
    .addField("Highest Role:",`${role}`,false)
  .setFooter(`User: ${member.user.username}`,`${member.user.avatarURL}`);
  member.guild.channels.get(modlog.id).send({embed}).catch(console.error);
  };

};

/*
Major (MAJ)
Lieutenant Colonel (LTC)
Colonel (COL)
Brigadier/Major General (BG/MG)
Lieutenant-General (LG)
Vice Chief of Defence Force (VCDF)
Chief of Defense Force (CDF)*/
<commit_msg>Update guildMemberRemove.js<commit_after>const Discord = require('discord.js');
module.exports = member => {
    const modlog = member.guild.channels.find('name', 'pie-log');
    //${member.user.username}
    const embed = new Discord.RichEmbed()
    .setTimestamp()
    .setColor(0xff0000)
    .setTitle("User Left")
    .setThumbnail(`${member.user.avatarURL}`)
    .setDescription(`\n`)
    .addField("Username:",`${member.user.username} (${member.user})`,true)
    .addField("Highest Role:",`${member.user.get(highestRole)}`,false)
  .setFooter(`User: ${member.user.username}`,`${member.user.avatarURL}`);
  member.guild.channels.get(modlog.id).send({embed}).catch(console.error);
  };
<|endoftext|>


<commit_before>var assert = require('assert');
var _ = require('@sailshq/lodash');
var Adapter = require('../../../lib/adapter');
var Support = require('../../support/bootstrap');

describe('Unit Tests ::', function() {
  describe('Create', function() {
    // Test Setup
    before(function(done) {
      Support.Setup('test_create', done);
    });

    after(function(done) {
      Support.Teardown('test_create', done);
    });

    // Attributes for the test table
    var attributes = {
      fieldA: 'foo',
      fieldB: 'bar'
    };

    it('should insert a record into the database and return it\'s fields', function(done) {
      var query = {
        using: 'test_create',
        newRecord: attributes,
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, result) {
        if (err) {
          return done(err);
        }

        assert(_.isObject(result));
        assert(!_.isFunction(result));
        assert(!_.isArray(result));
        assert.equal(result.fieldA, 'foo');
        assert.equal(result.fieldB, 'bar');
        assert(result.id);

        return done();
      });
    });

    // Create Auto-Incremented ID
    it('should create an auto-incremented id field', function(done) {
      var query = {
        using: 'test_create',
        newRecord: attributes,
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, result) {
        if (err) {
          return done(err);
        }

        assert(_.isObject(result));
        assert(!_.isFunction(result));
        assert(!_.isArray(result));
        assert(result.id);

        return done();
      });
    });

    it('should keep case', function(done) {
      var query = {
        using: 'test_create',
        newRecord: {
          fieldA: 'Foo',
          fieldB: 'bAr'
        },
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, result) {
        if (err) {
          return done(err);
        }

        assert.equal(result.fieldA, 'Foo');
        assert.equal(result.fieldB, 'bAr');

        return done();
      });
    });

    it('should pass through buffers for `ref` type attributes', function(done) {
      var query = {
        using: 'test_create',
        newRecord: {
          fieldC: new Buffer([1, 2, 3])
        },
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, record) {
        if (err) {
          return done(err);
        }
        assert(record.fieldC instanceof Buffer);
        assert.equal(record.fieldC.length, 3);
        return done();
      });
    });

    it('should pass through date objects for `ref` type attributes', function(done) {
      var query = {
        using: 'test_create',
        newRecord: {
          fieldD: new Date('2001-06-15 12:00:00')
        },
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, record) {
        if (err) {
          return done(err);
        }
        assert(record.fieldD instanceof Date);
        assert.equal(record.fieldD.getFullYear(), '2001');
        return done();
      });
    });

    // Look into the bowels of the PG Driver and ensure the Create function handles
    // it's connections properly.
    it('should release it\'s connection when completed', function(done) {
      var manager = Adapter.datastores.test.manager;
      var preConnectionsAvailable = manager.pool.pool.availableObjectsCount();

      var query = {
        using: 'test_create',
        newRecord: attributes,
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err) {
        if (err) {
          return done(err);
        }

        var postConnectionsAvailable = manager.pool.pool.availableObjectsCount();
        assert.equal(preConnectionsAvailable, postConnectionsAvailable);

        return done();
      });
    });
  });
});
<commit_msg>it's => its<commit_after>var assert = require('assert');
var _ = require('@sailshq/lodash');
var Adapter = require('../../../lib/adapter');
var Support = require('../../support/bootstrap');

describe('Unit Tests ::', function() {
  describe('Create', function() {
    // Test Setup
    before(function(done) {
      Support.Setup('test_create', done);
    });

    after(function(done) {
      Support.Teardown('test_create', done);
    });

    // Attributes for the test table
    var attributes = {
      fieldA: 'foo',
      fieldB: 'bar'
    };

    it('should insert a record into the database and return its fields', function(done) {
      var query = {
        using: 'test_create',
        newRecord: attributes,
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, result) {
        if (err) {
          return done(err);
        }

        assert(_.isObject(result));
        assert(!_.isFunction(result));
        assert(!_.isArray(result));
        assert.equal(result.fieldA, 'foo');
        assert.equal(result.fieldB, 'bar');
        assert(result.id);

        return done();
      });
    });

    // Create Auto-Incremented ID
    it('should create an auto-incremented id field', function(done) {
      var query = {
        using: 'test_create',
        newRecord: attributes,
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, result) {
        if (err) {
          return done(err);
        }

        assert(_.isObject(result));
        assert(!_.isFunction(result));
        assert(!_.isArray(result));
        assert(result.id);

        return done();
      });
    });

    it('should keep case', function(done) {
      var query = {
        using: 'test_create',
        newRecord: {
          fieldA: 'Foo',
          fieldB: 'bAr'
        },
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, result) {
        if (err) {
          return done(err);
        }

        assert.equal(result.fieldA, 'Foo');
        assert.equal(result.fieldB, 'bAr');

        return done();
      });
    });

    it('should pass through buffers for `ref` type attributes', function(done) {
      var query = {
        using: 'test_create',
        newRecord: {
          fieldC: new Buffer([1, 2, 3])
        },
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, record) {
        if (err) {
          return done(err);
        }
        assert(record.fieldC instanceof Buffer);
        assert.equal(record.fieldC.length, 3);
        return done();
      });
    });

    it('should pass through date objects for `ref` type attributes', function(done) {
      var query = {
        using: 'test_create',
        newRecord: {
          fieldD: new Date('2001-06-15 12:00:00')
        },
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err, record) {
        if (err) {
          return done(err);
        }
        assert(record.fieldD instanceof Date);
        assert.equal(record.fieldD.getFullYear(), '2001');
        return done();
      });
    });

    // Look into the bowels of the PG Driver and ensure the Create function handles
    // it's connections properly.
    it('should release it\'s connection when completed', function(done) {
      var manager = Adapter.datastores.test.manager;
      var preConnectionsAvailable = manager.pool.pool.availableObjectsCount();

      var query = {
        using: 'test_create',
        newRecord: attributes,
        meta: {
          fetch: true
        }
      };

      Adapter.create('test', query, function(err) {
        if (err) {
          return done(err);
        }

        var postConnectionsAvailable = manager.pool.pool.availableObjectsCount();
        assert.equal(preConnectionsAvailable, postConnectionsAvailable);

        return done();
      });
    });
  });
});
<|endoftext|>