<commit_before>import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import moment from 'moment'

import { Footer, Button } from 'rebass'

import { getPath } from '../../utils/router'

import Loader from '../Loader/Loader'
import FavoriteIcon from '../../icons/Favorite'

import { Balance, User } from '../../selectors'

import { getTotalTime } from '../../actions'

import styles from './App.scss'

function formatBalance (balance) {
  const balanceDuration = moment.duration(Math.abs(balance))

  const h = (balanceDuration.days() * 24) + balanceDuration.hours()
  const m = balanceDuration.minutes()
  const s = balanceDuration.seconds()

  return `${balance > 0 ? '+' : '-'} ${h} : ${m} : ${s}`
}

/* eslint-disable max-len */
const WelcomeScreen = () => (

Hey, Toggl Balance is an app that helps you check how much work you did toward your goal.

To do that you need to go through some steps to provide access to your tracked time on Toggl and setup your goal.

Click below to proceed to setup

    <Link to={getPath('/setup/token')}>
      <Button>Setup</Button>
    </Link>

)
/* eslint-enable max-len */

export class App extends Component {
  static propTypes = {
    ...Balance.propTypes,
    dispatch: PropTypes.func.isRequired,
  }

  componentDidMount () {
    this.fetchTime(this.props)
  }

  componentWillReceiveProps (props) {
    this.fetchTime(props)
  }

  fetchTime (props) {
    const { balance, status, user, location, dispatch } = props

    if (
      location.pathname === '/' &&
      user.status === 'SUCCESS' &&
      status === null &&
      balance === null
    ) {
      dispatch(getTotalTime())
    }
  }

  render () {
    const { children, status, balance, user } = this.props

    let content
    if (status === 'LOADING') {
      content = <Loader />
    } else if (user.status === 'SUCCESS' && status === 'SUCCESS' && balance) {
      content =
{formatBalance(balance)}

    } else {
      content = <WelcomeScreen />
    }

    return (

          {children || content}

            {'Made with '}
            <FavoriteIcon className={styles.icon} />
            {' by '}
            Łukasz Strączyński

    )
  }
}

function mapStateToProps (state) {
  return {
    user: User.select(state),
    ...Balance.select(state),
  }
}

export default connect(mapStateToProps)(App)
<commit_msg>Change base path to take into account production env<commit_after>import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import moment from 'moment'

import { Footer, Button } from 'rebass'

import { getBasePath, getPath } from '../../utils/router'

import Loader from '../Loader/Loader'
import FavoriteIcon from '../../icons/Favorite'

import { Balance, User } from '../../selectors'

import { getTotalTime } from '../../actions'

import styles from './App.scss'

function formatBalance (balance) {
  const balanceDuration = moment.duration(Math.abs(balance))

  const h = (balanceDuration.days() * 24) + balanceDuration.hours()
  const m = balanceDuration.minutes()
  const s = balanceDuration.seconds()

  return `${balance > 0 ? '+' : '-'} ${h} : ${m} : ${s}`
}

/* eslint-disable max-len */
const WelcomeScreen = () => (

Hey, Toggl Balance is an app that helps you check how much work you did toward your goal.

To do that you need to go through some steps to provide access to your tracked time on Toggl and setup your goal.

Click below to proceed to setup

    <Link to={getPath('/setup/token')}>
      <Button>Setup</Button>
    </Link>

)
/* eslint-enable max-len */

export class App extends Component {
  static propTypes = {
    ...Balance.propTypes,
    dispatch: PropTypes.func.isRequired,
  }

  componentDidMount () {
    this.fetchTime(this.props)
  }

  componentWillReceiveProps (props) {
    this.fetchTime(props)
  }

  fetchTime (props) {
    const { balance, status, user, location, dispatch } = props

    if (
      location.pathname === `${getBasePath()}/` &&
      user.status === 'SUCCESS' &&
      status === null &&
      balance === null
    ) {
      dispatch(getTotalTime())
    }
  }

  render () {
    const { children, status, balance, user } = this.props

    let content
    if (status === 'LOADING') {
      content = <Loader />
    } else if (user.status === 'SUCCESS' && status === 'SUCCESS' && balance) {
      content =
{formatBalance(balance)}

    } else {
      content = <WelcomeScreen />
    }

    return (

          {children || content}

            {'Made with '}
            <FavoriteIcon className={styles.icon} />
            {' by '}
            Łukasz Strączyński

    )
  }
}

function mapStateToProps (state) {
  return {
    user: User.select(state),
    ...Balance.select(state),
  }
}

export default connect(mapStateToProps)(App)
<|endoftext|>


<commit_before>/**
 * Created by carl.hand on 31/03/2017.
 */
import React from 'react';

const Counter = (props) => {

    return (

                <button className="counter-action decrement" onClick={props.onDecrementScore}> - </button>

 {props.score}

                <button className="counter-action increment" onClick={props.onIncrementScore}> + </button>

    );
};

Counter.PropTypes = {
    score: React.PropTypes.number.isRequired,
    onIncrement: React.PropTypes.func.isRequired,
    onDecrement: React.PropTypes.func.isRequired
};

export default Counter;
<commit_msg>renamed Counter PropTypes<commit_after>/**
 * Created by carl.hand on 31/03/2017.
 */
import React from 'react';

const Counter = (props) => {

    return (

                <button className="counter-action decrement" onClick={props.onDecrementScore}> - </button>

 {props.score}

                <button className="counter-action increment" onClick={props.onIncrementScore}> + </button>

    );
};

Counter.PropTypes = {
    score: React.PropTypes.number.isRequired,
    onIncrementScore: React.PropTypes.func.isRequired,
    onDecrementScore: React.PropTypes.func.isRequired
};

export default Counter;
<|endoftext|>


<commit_before>/*
 * This file is part of Indico.
 * Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

(function(global) {
    'use strict';

    global.eventChatInfo = function eventChatInfo() {
        var menu = null;
        var links = $('#chat-info-container').data('chatLinks');

        $('.chat-toggle-details').on('click', function(e) {
            e.preventDefault();
            $(this).siblings('.chat-details').slideToggle();
        });

        $('.js-chat-join').on('click', function(e) {
            e.preventDefault();
            var $this = $(this);
            var menuItems = {};
            $.each(links, function(i, link) {
                var action = link.link;
                action = action.replace(/\{server\}/g, $this.data('server'));
                action = action.replace(/\{room\}/g, $this.data('room'));
                menuItems[i] = {display: link.title, action: action};
            });

            if (menu && menu.isOpen()) {
                menu.close();
                if (menu._link == this) {
                    return;
                }
            }
            menu = new PopupMenu(menuItems, [$E(this)], 'categoryDisplayPopupList', true, false, null, null, true);
            menu._link = this;
            var pos = $this.offset();
            menu.open(pos.left - 3, pos.top + $this.height());
        });
    };

    global.eventManageChat = function eventManageChat() {
        $('.js-chat-remove-room').on('click', function(e) {
            e.preventDefault();
            var $this = $(this);
            var msg = $T('Do you really want to remove this chatroom from the event?');
            if ($this.data('numEvents') == 1) {
                msg += '
' + $T('Since it is only used in this event, it will be deleted from the Jabber server, too!');
            }
            new ConfirmPopup($T('Delete this chatroom?'), msg, function(confirmed) {
                if (!confirmed) {
                    return;
                }

                $('<form>', {
                    action: $this.data('href'),
                    method: 'post'
                }).appendTo('body').submit();
            }).open();
        });

        $('.js-chat-refresh-room').on('click', function(e) {
            e.preventDefault();
            $.ajax({
                url: $(this).data('href'),
                type: 'POST',
                complete: IndicoUI.Dialogs.Util.progress(),
                success: function(data) {
                    if (handleAjaxError(data)) {
                        return;
                    }
                    if (data.result == 'not-found') {
                        new AlertPopup($T('Chatroom not found'), $T('The chatroom does noe exist on the Jabber server anymore. We recommend you to delete it chatroom from Indico as well.')).open();
                    } else if (data.result == 'changed') {
                        new AlertPopup($T('Chatroom updated'), $T('The chatroom data has been updated.'), function() {
                            window.location.href = window.location.href;
                        }).open();
                    }
                }
            });
        });
    };
})(window);
<commit_msg>Fix typo<commit_after>/*
 * This file is part of Indico.
 * Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

(function(global) {
    'use strict';

    global.eventChatInfo = function eventChatInfo() {
        var menu = null;
        var links = $('#chat-info-container').data('chatLinks');

        $('.chat-toggle-details').on('click', function(e) {
            e.preventDefault();
            $(this).siblings('.chat-details').slideToggle();
        });

        $('.js-chat-join').on('click', function(e) {
            e.preventDefault();
            var $this = $(this);
            var menuItems = {};
            $.each(links, function(i, link) {
                var action = link.link;
                action = action.replace(/\{server\}/g, $this.data('server'));
                action = action.replace(/\{room\}/g, $this.data('room'));
                menuItems[i] = {display: link.title, action: action};
            });

            if (menu && menu.isOpen()) {
                menu.close();
                if (menu._link == this) {
                    return;
                }
            }
            menu = new PopupMenu(menuItems, [$E(this)], 'categoryDisplayPopupList', true, false, null, null, true);
            menu._link = this;
            var pos = $this.offset();
            menu.open(pos.left - 3, pos.top + $this.height());
        });
    };

    global.eventManageChat = function eventManageChat() {
        $('.js-chat-remove-room').on('click', function(e) {
            e.preventDefault();
            var $this = $(this);
            var msg = $T('Do you really want to remove this chatroom from the event?');
            if ($this.data('numEvents') == 1) {
                msg += '
' + $T('Since it is only used in this event, it will be deleted from the Jabber server, too!');
            }
            new ConfirmPopup($T('Delete this chatroom?'), msg, function(confirmed) {
                if (!confirmed) {
                    return;
                }

                $('<form>', {
                    action: $this.data('href'),
                    method: 'post'
                }).appendTo('body').submit();
            }).open();
        });

        $('.js-chat-refresh-room').on('click', function(e) {
            e.preventDefault();
            $.ajax({
                url: $(this).data('href'),
                type: 'POST',
                complete: IndicoUI.Dialogs.Util.progress(),
                success: function(data) {
                    if (handleAjaxError(data)) {
                        return;
                    }
                    if (data.result == 'not-found') {
                        new AlertPopup($T('Chatroom not found'), $T('The chatroom does not exist on the Jabber server anymore. We recommend you to delete it chatroom from Indico as well.')).open();
                    } else if (data.result == 'changed') {
                        new AlertPopup($T('Chatroom updated'), $T('The chatroom data has been updated.'), function() {
                            window.location.href = window.location.href;
                        }).open();
                    }
                }
            });
        });
    };
})(window);
<|endoftext|>


<commit_before>import React from 'react';

function reloadPage() {
  if ( typeof window !== 'undefined' ) window.location.reload();
}

const ErrorNotice = ( { error, key } ) => {
  return
{ error }
;
};

ErrorNotice.propTypes = {
  error: React.PropTypes.string.isRequired,
  key: React.PropTypes.number.isRequired,
};

const Notices = ( { errors, onClearNotices } ) => {
  if ( ! errors || errors.length === 0 ) return null;
  return (

Sorry! Something went wrong!

If the problem was temporary, you can try to keep working. Otherwise you can try to reload and see if that helps.

If you keep seeing errors, send an email to payton+voyageurhelp@foolord.com and I'll see what I can do.

        <button className="notices__clear btn btn-block btn-primary" onClick={ onClearNotices }>keep going</button>
        <button className="notices__reload btn btn-block btn-warning" onClick={ reloadPage }>try reloading</button>

Here's the raw error I saw:

Don't worry if you don't understand it; if it keeps happening just send it to me in an email.

        { errors.map( ( error, key ) => <ErrorNotice error={ error } key={ key } /> ) }

  );
};

Notices.propTypes = {
  errors: React.PropTypes.array,
  onClearNotices: React.PropTypes.func.isRequired,
};

export default Notices;
<commit_msg>Remove key prop from ErrorNotice<commit_after>import React from 'react';

function reloadPage() {
  if ( typeof window !== 'undefined' ) window.location.reload();
}

const ErrorNotice = ( { error } ) => {
  return
{ error }
;
};

ErrorNotice.propTypes = {
  error: React.PropTypes.string.isRequired,
};

const Notices = ( { errors, onClearNotices } ) => {
  if ( ! errors || errors.length === 0 ) return null;
  return (

Sorry! Something went wrong!

If the problem was temporary, you can try to keep working. Otherwise you can try to reload and see if that helps.

If you keep seeing errors, send an email to payton+voyageurhelp@foolord.com and I'll see what I can do.

        <button className="notices__clear btn btn-block btn-primary" onClick={ onClearNotices }>keep going</button>
        <button className="notices__reload btn btn-block btn-warning" onClick={ reloadPage }>try reloading</button>

Here's the raw error I saw:

Don't worry if you don't understand it; if it keeps happening just send it to me in an email.

        { errors.map( ( error, key ) => <ErrorNotice error={ error } key={ key } /> ) }

  );
};

Notices.propTypes = {
  errors: React.PropTypes.array,
  onClearNotices: React.PropTypes.func.isRequired,
};

export default Notices;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import style from './Pos.module.css';
import PosTableItem from './PosTableItem'
import PosProductItem from './PosProductItem';
import axios from 'axios';
import { API_URL } from '../../api/apiconfig';
import PaymentDialog from './Payment';

export default class Pos extends Component {
    state = {
        products: [],
        total: 0,
        isPaymentModalOpen: false
    };

    componentDidMount() {
        this.props.fetchTablesDispatch();
    }

    calculateTotal = (items) => {
        var total = 0;
        for (var i = 0; i < items.length; i++) {
            total += items[i].quantity * items[i].product.price
        }

        this.setState({ total: total});
    };

    getProduct = (tableId) => {
        axios({
            url: API_URL + 'carts/' + tableId,
            timeout: 20000,
            method: 'get',
            responseType: 'json'
        })
        .then((response) => {
            this.setState({ products: response.data.data.items});
            this.calculateTotal(response.data.data.items);
        })
        .catch(function(response){
            console.log(response);
            console.log('ERROR ON GETTING CART');
        });
    };

    render() {
        const { tables } = this.props;

        return (

Tables

                                Table
                                Status

                                {tables.data.map((table, i) => {
                                    return <PosTableItem key={i} status={table.status} name={table.name} tableId={table.id} getProduct={this.getProduct} />
                                })}

Products

                                Quantity
                                Product
                                Unit Price

                                {this.state.products.map(function(product, i) {
                                    return <PosProductItem key={i} item={product} />
                                })}

                                     Net Total

                                    {this.state.total} PHP

                                     Tax

                                    {this.state.total} PHP

                                     Discount

                                    {this.state.total} PHP

                                     Total

                                    {this.state.total} PHP

                    <button className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">Make Selected Table Available</button>
                    <button className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Send Invoice</button>
                    <button className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored">Apply Discount</button>
                    <button onClick={() => {this.setState({isPaymentModalOpen: true})}} className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored">Proceed to Payment</button>

                    <PaymentDialog open={this.state.isPaymentModalOpen} />

        )
    }
}<commit_msg>updated pos table footer<commit_after>import React, { Component } from 'react';
import style from './Pos.module.css';
import PosTableItem from './PosTableItem'
import PosProductItem from './PosProductItem';
import axios from 'axios';
import { API_URL } from '../../api/apiconfig';
import PaymentDialog from './Payment';

export default class Pos extends Component {
    state = {
        products: [],
        total: 0,
        isPaymentModalOpen: false
    };

    componentDidMount() {
        this.props.fetchTablesDispatch();
    }

    calculateTotal = (items) => {
        var total = 0;
        for (var i = 0; i < items.length; i++) {
            total += items[i].quantity * items[i].product.price
        }

        this.setState({ total: total});
    };

    getProduct = (tableId) => {
        axios({
            url: API_URL + 'carts/' + tableId,
            timeout: 20000,
            method: 'get',
            responseType: 'json'
        })
        .then((response) => {
            this.setState({ products: response.data.data.items});
            this.calculateTotal(response.data.data.items);
        })
        .catch(function(response){
            console.log(response);
            console.log('ERROR ON GETTING CART');
        });
    };

    render() {
        const { tables } = this.props;

        return (

Tables

                                Table
                                Status

                                {tables.data.map((table, i) => {
                                    return <PosTableItem key={i} status={table.status} name={table.name} tableId={table.id} getProduct={this.getProduct} />
                                })}

Products

                                Quantity
                                Product
                                Unit Price

                                {this.state.products.map(function(product, i) {
                                    return <PosProductItem key={i} item={product} />
                                })}

                                     Net Total

                                    {this.state.total} PHP

                                     Tax

                                    {this.state.total} PHP

                                     Discount

                                    {this.state.total} PHP

                                     Total

                                    {this.state.total} PHP

                    <button className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">Make Selected Table Available</button>
                    <button className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Send Invoice</button>
                    <button className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored">Apply Discount</button>
                    <button onClick={() => {this.setState({isPaymentModalOpen: true})}} className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored">Proceed to Payment</button>

                    <PaymentDialog open={this.state.isPaymentModalOpen} />

        )
    }
}<|endoftext|>


<commit_before>define( [
            'dojo/_base/declare',
            'dojo/_base/array',
            'dojo/dom-construct',
            'dojo/dom-attr',
            'dojo/dom',
            'jquery'
],
    function( declare,
        array,
        domConstruct,
        domAttr,
        dom,
        $ ) {

return declare(null, {
constructor: function(contextPath) {
    this.contextPath = contextPath;
},

setRedirectCallback: function(callback) {
    this.redirectCallback = callback;
},

setErrorCallback: function(callback) {
    this.errorCallback = callback;
},

searchSequence: function(trackName, refSeqName, starts) {
    var operation = "search_sequence";
    var contextPath = this.contextPath;
    var redirectCallback = this.redirectCallback;
    var errorCallback = this.errorCallback;
    /*

            <select class="search_sequence_tools_select" />

Enter sequence

<textarea class="search_sequence_input"></textarea>

                <input type="checkbox" class="search_all_ref_seqs_checkbox">Search all genomic sequences

<button>Search</button>

No matches found

    */

    var content = dojo.create("div", { className: "search_sequence" });
    var sequenceToolsDiv = dojo.create("div", { className: "search_sequence_tools" }, content);
    var sequenceToolsSelect = dojo.create("select", {className: "search_sequence_tools_select"}, sequenceToolsDiv);
    var sequenceDiv = dojo.create("div", { className: "search_sequence_area" }, content);
    var sequenceLabel = dojo.create("div", { className: "search_sequence_label", innerHTML: "Enter sequence" }, sequenceDiv);
    var sequenceFieldDiv = dojo.create("div", { }, sequenceDiv);
    var sequenceField = dojo.create("textarea", { className: "search_sequence_input" }, sequenceFieldDiv);
    var searchAllRefSeqsDiv = dojo.create("div", { className: "search_all_ref_seqs_area" }, sequenceDiv);
    var searchAllRefSeqsCheckbox = dojo.create("input", { className: "search_all_ref_seqs_checkbox", type: "checkbox" }, searchAllRefSeqsDiv);
    var searchAllRefSeqsLabel = dojo.create("span", { className: "search_all_ref_seqs_label", innerHTML: "Search all genomic sequences" }, searchAllRefSeqsDiv);
    var sequenceButtonDiv = dojo.create("div", { }, sequenceDiv);
    var sequenceButton = dojo.create("button", { innerHTML: "Search" }, sequenceButtonDiv);
    var messageDiv = dojo.create("div", { className: "search_sequence_message", innerHTML: "No matches found" }, content);
    var waitingDiv = dojo.create("div", { innerHTML: ""}, content);
    var headerDiv = dojo.create("div", { className: "search_sequence_matches_header" }, content);
    dojo.create("span", { innerHTML: "ID", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "Start", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "End", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "Score", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "Significance", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "Identity", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    var matchDiv = dojo.create("div", { className: "search_sequence_matches" }, content);
    var matches = dojo.create("div", { }, matchDiv);

    dojo.style(messageDiv, { display: "none" });
    dojo.style(matchDiv, { display: "none" });
    dojo.style(headerDiv, { display: "none" });
    dojo.style(waitingDiv, { display: "none" });
    if (!refSeqName) {
        dojo.style(searchAllRefSeqsDiv, { display: "none" });
    }

    var getSequenceSearchTools = function() {
        var ok = false;
        var operation = "get_sequence_search_tools";
        var request={
            "track": trackName,
            "operation": operation
        };
        dojo.xhrPost( {
            postData: JSON.stringify(request),
            url: contextPath + "/AnnotationEditorService",
            sync: true,
            handleAs: "json",
            timeout: 5000 * 1000, // Time in milliseconds
            load: function(response, ioArgs) {
                if(response.error) {
                    ok = false;
                    alert(response.error);
                }
                if (response.sequence_search_tools.length == 0) {
                    ok = false;
                    return;
                }
                ok = true;
                for(var key in response.sequence_search_tools) {
                    if (response.sequence_search_tools.hasOwnProperty(key)) {
                        dojo.create("option", { innerHTML: response.sequence_search_tools[key].name, id: key }, sequenceToolsSelect);
                    }
                }
            },
            error: function(response, ioArgs) {
                errorCallback(response);
                return response;
            }
        });
        return ok;
    };

    var search = function() {
        var residues = dojo.attr(sequenceField, "value").toUpperCase();
        var ok = true;
        if (residues.length == 0) {
            alert("No sequence entered");
            ok = false;
        }
        else if (residues.match(/[^ACDEFGHIKLMNPQRSTVWXY\n]/)) {
            alert("The sequence should only contain non redundant IUPAC nucleotide or amino acid codes (except for N/X)");
            ok = false;
        }
        var searchAllRefSeqs = dojo.attr(searchAllRefSeqsCheckbox, "checked");
        if (ok) {
            dojo.style(waitingDiv, { display: "block"} );
            dojo.style(matchDiv, { display: "none"} );
            dojo.style(headerDiv, { display: "none" });
            var postobj={
                "track": trackName,
                "search": {
                    "key": sequenceToolsSelect.options[sequenceToolsSelect.selectedIndex].id,
                    "residues": residues.replace(/(\r\n|\n|\r)/gm,"")
                },
                "operation": operation
            };
            if(!searchAllRefSeqs) {
                postobj.search.database_id=refSeqName;
            }

            dojo.xhrPost( {
                postData: JSON.stringify(postobj),
                url: contextPath + "/AnnotationEditorService",
                handleAs: "json",
                timeout: 5000 * 1000, // Time in milliseconds
                load: function(response, ioArgs) {
                    dojo.style(waitingDiv, { display: "none"} );
                    if(response.error) {
                        alert(response.error);
                        return;
                    }
                    while (matches.hasChildNodes()) {
                        matches.removeChild(matches.lastChild);
                    }
                    if (response.matches.length == 0) {
                        dojo.style(messageDiv, { display: "block" });
                        dojo.style(matchDiv, { display: "none" });
                        dojo.style(headerDiv, { display: "none" });
                        return;
                    }
                    dojo.style(messageDiv, { display: "none" });
                    dojo.style(headerDiv, { display: "block"} );
                    dojo.style(matchDiv, { display: "block"} );

                    var returnedMatches = response.matches;
                    returnedMatches.sort(function(match1, match2) {
                        return match2.rawscore - match1.rawscore;
                    });
                    var maxNumberOfHits = 100;

                    for (var i = 0; i < returnedMatches.length && i < maxNumberOfHits; ++i) {
                        var match = returnedMatches[i];
                        var query = match.query;
                        var subject = match.subject;
                        var refSeqStart = starts[subject.feature.uniquename] || 0;
                        var refSeqEnd = starts[subject.feature.uniquename] || 0;
                        subject.location.fmin += refSeqStart;
                        subject.location.fmax += refSeqStart;
                        var subjectStart = subject.location.fmin + 1;
                        var subjectEnd = subject.location.fmax + 1;
                        if (subject.location.strand == -1) {
                            var tmp = subjectStart;
                            subjectStart = subjectEnd;
                            subjectEnd = tmp;
                        }
                        var rawscore = match.rawscore;
                        var significance = match.significance;
                        var identity = match.identity;
                        var row = dojo.create("div", { className: "search_sequence_matches_row" }, matches);
                        var subjectIdColumn = dojo.create("span", { innerHTML: subject.feature.uniquename, className: "search_sequence_matches_field search_sequence_matches_generic_field", title: subject.feature.uniquename }, row);
                        var subjectStartColumn = dojo.create("span", { innerHTML: subjectStart, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        var subjectEndColumn = dojo.create("span", { innerHTML: subjectEnd, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        var scoreColumn = dojo.create("span", { innerHTML: match.rawscore, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        var significanceColumn = dojo.create("span", { innerHTML: match.significance, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        var identityColumn = dojo.create("span", { innerHTML : match.identity, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        dojo.connect(row, "onclick", function(id, fmin, fmax) {
                            return function() {
                                redirectCallback(id, fmin, fmax);
                            };
                        }(subject.feature.uniquename, subject.location.fmin, subject.location.fmax));
                    }
                },
                // The ERROR function will be called in an error case.
                error: function(response, ioArgs) { //
                    errorCallback(response);
                    return response;
                }

            });
        }
    };

    dojo.connect(sequenceField, "onkeypress", function(event) {
        if (event.keyCode == dojo.keys.ENTER) {
            event.preventDefault();
            search();
        }
    });
    dojo.connect(sequenceButton, "onclick", search);
    dojo.connect(searchAllRefSeqsLabel, "onclick", function() {
        dojo.attr(searchAllRefSeqsCheckbox, "checked", !searchAllRefSeqsCheckbox.checked);
    });

    if (!getSequenceSearchTools()) {
        alert("No search plugins setup");
        return null;
    }

    return content;
}

});

});

<commit_msg>Fix bug where subjectStart and subjectEnd was incorrectly being incremented by 1; BLAT returns tab delimited results with 1-based coordinates (#1383)<commit_after>define( [
            'dojo/_base/declare',
            'dojo/_base/array',
            'dojo/dom-construct',
            'dojo/dom-attr',
            'dojo/dom',
            'jquery'
],
    function( declare,
        array,
        domConstruct,
        domAttr,
        dom,
        $ ) {

return declare(null, {
constructor: function(contextPath) {
    this.contextPath = contextPath;
},

setRedirectCallback: function(callback) {
    this.redirectCallback = callback;
},

setErrorCallback: function(callback) {
    this.errorCallback = callback;
},

searchSequence: function(trackName, refSeqName, starts) {
    var operation = "search_sequence";
    var contextPath = this.contextPath;
    var redirectCallback = this.redirectCallback;
    var errorCallback = this.errorCallback;
    /*

            <select class="search_sequence_tools_select" />

Enter sequence

<textarea class="search_sequence_input"></textarea>

                <input type="checkbox" class="search_all_ref_seqs_checkbox">Search all genomic sequences

<button>Search</button>

No matches found

    */

    var content = dojo.create("div", { className: "search_sequence" });
    var sequenceToolsDiv = dojo.create("div", { className: "search_sequence_tools" }, content);
    var sequenceToolsSelect = dojo.create("select", {className: "search_sequence_tools_select"}, sequenceToolsDiv);
    var sequenceDiv = dojo.create("div", { className: "search_sequence_area" }, content);
    var sequenceLabel = dojo.create("div", { className: "search_sequence_label", innerHTML: "Enter sequence" }, sequenceDiv);
    var sequenceFieldDiv = dojo.create("div", { }, sequenceDiv);
    var sequenceField = dojo.create("textarea", { className: "search_sequence_input" }, sequenceFieldDiv);
    var searchAllRefSeqsDiv = dojo.create("div", { className: "search_all_ref_seqs_area" }, sequenceDiv);
    var searchAllRefSeqsCheckbox = dojo.create("input", { className: "search_all_ref_seqs_checkbox", type: "checkbox" }, searchAllRefSeqsDiv);
    var searchAllRefSeqsLabel = dojo.create("span", { className: "search_all_ref_seqs_label", innerHTML: "Search all genomic sequences" }, searchAllRefSeqsDiv);
    var sequenceButtonDiv = dojo.create("div", { }, sequenceDiv);
    var sequenceButton = dojo.create("button", { innerHTML: "Search" }, sequenceButtonDiv);
    var messageDiv = dojo.create("div", { className: "search_sequence_message", innerHTML: "No matches found" }, content);
    var waitingDiv = dojo.create("div", { innerHTML: ""}, content);
    var headerDiv = dojo.create("div", { className: "search_sequence_matches_header" }, content);
    dojo.create("span", { innerHTML: "ID", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "Start", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "End", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "Score", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "Significance", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    dojo.create("span", { innerHTML: "Identity", className: "search_sequence_matches_header_field search_sequence_matches_generic_field" }, headerDiv);
    var matchDiv = dojo.create("div", { className: "search_sequence_matches" }, content);
    var matches = dojo.create("div", { }, matchDiv);

    dojo.style(messageDiv, { display: "none" });
    dojo.style(matchDiv, { display: "none" });
    dojo.style(headerDiv, { display: "none" });
    dojo.style(waitingDiv, { display: "none" });
    if (!refSeqName) {
        dojo.style(searchAllRefSeqsDiv, { display: "none" });
    }

    var getSequenceSearchTools = function() {
        var ok = false;
        var operation = "get_sequence_search_tools";
        var request={
            "track": trackName,
            "operation": operation
        };
        dojo.xhrPost( {
            postData: JSON.stringify(request),
            url: contextPath + "/AnnotationEditorService",
            sync: true,
            handleAs: "json",
            timeout: 5000 * 1000, // Time in milliseconds
            load: function(response, ioArgs) {
                if(response.error) {
                    ok = false;
                    alert(response.error);
                }
                if (response.sequence_search_tools.length == 0) {
                    ok = false;
                    return;
                }
                ok = true;
                for(var key in response.sequence_search_tools) {
                    if (response.sequence_search_tools.hasOwnProperty(key)) {
                        dojo.create("option", { innerHTML: response.sequence_search_tools[key].name, id: key }, sequenceToolsSelect);
                    }
                }
            },
            error: function(response, ioArgs) {
                errorCallback(response);
                return response;
            }
        });
        return ok;
    };

    var search = function() {
        var residues = dojo.attr(sequenceField, "value").toUpperCase();
        var ok = true;
        if (residues.length == 0) {
            alert("No sequence entered");
            ok = false;
        }
        else if (residues.match(/[^ACDEFGHIKLMNPQRSTVWXY\n]/)) {
            alert("The sequence should only contain non redundant IUPAC nucleotide or amino acid codes (except for N/X)");
            ok = false;
        }
        var searchAllRefSeqs = dojo.attr(searchAllRefSeqsCheckbox, "checked");
        if (ok) {
            dojo.style(waitingDiv, { display: "block"} );
            dojo.style(matchDiv, { display: "none"} );
            dojo.style(headerDiv, { display: "none" });
            var postobj={
                "track": trackName,
                "search": {
                    "key": sequenceToolsSelect.options[sequenceToolsSelect.selectedIndex].id,
                    "residues": residues.replace(/(\r\n|\n|\r)/gm,"")
                },
                "operation": operation
            };
            if(!searchAllRefSeqs) {
                postobj.search.database_id=refSeqName;
            }

            dojo.xhrPost( {
                postData: JSON.stringify(postobj),
                url: contextPath + "/AnnotationEditorService",
                handleAs: "json",
                timeout: 5000 * 1000, // Time in milliseconds
                load: function(response, ioArgs) {
                    dojo.style(waitingDiv, { display: "none"} );
                    if(response.error) {
                        alert(response.error);
                        return;
                    }
                    while (matches.hasChildNodes()) {
                        matches.removeChild(matches.lastChild);
                    }
                    if (response.matches.length == 0) {
                        dojo.style(messageDiv, { display: "block" });
                        dojo.style(matchDiv, { display: "none" });
                        dojo.style(headerDiv, { display: "none" });
                        return;
                    }
                    dojo.style(messageDiv, { display: "none" });
                    dojo.style(headerDiv, { display: "block"} );
                    dojo.style(matchDiv, { display: "block"} );

                    var returnedMatches = response.matches;
                    returnedMatches.sort(function(match1, match2) {
                        return match2.rawscore - match1.rawscore;
                    });
                    var maxNumberOfHits = 100;

                    for (var i = 0; i < returnedMatches.length && i < maxNumberOfHits; ++i) {
                        var match = returnedMatches[i];
                        var query = match.query;
                        var subject = match.subject;
                        var refSeqStart = starts[subject.feature.uniquename] || 0;
                        var refSeqEnd = starts[subject.feature.uniquename] || 0;
                        subject.location.fmin += refSeqStart;
                        subject.location.fmax += refSeqStart;
                        var subjectStart = subject.location.fmin;
                        var subjectEnd = subject.location.fmax;
                        if (subject.location.strand == -1) {
                            var tmp = subjectStart;
                            subjectStart = subjectEnd;
                            subjectEnd = tmp;
                        }
                        var rawscore = match.rawscore;
                        var significance = match.significance;
                        var identity = match.identity;
                        var row = dojo.create("div", { className: "search_sequence_matches_row" }, matches);
                        var subjectIdColumn = dojo.create("span", { innerHTML: subject.feature.uniquename, className: "search_sequence_matches_field search_sequence_matches_generic_field", title: subject.feature.uniquename }, row);
                        var subjectStartColumn = dojo.create("span", { innerHTML: subjectStart, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        var subjectEndColumn = dojo.create("span", { innerHTML: subjectEnd, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        var scoreColumn = dojo.create("span", { innerHTML: match.rawscore, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        var significanceColumn = dojo.create("span", { innerHTML: match.significance, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        var identityColumn = dojo.create("span", { innerHTML : match.identity, className: "search_sequence_matches_field search_sequence_matches_generic_field" }, row);
                        dojo.connect(row, "onclick", function(id, fmin, fmax) {
                            return function() {
                                redirectCallback(id, fmin, fmax);
                            };
                        }(subject.feature.uniquename, subject.location.fmin, subject.location.fmax));
                    }
                },
                // The ERROR function will be called in an error case.
                error: function(response, ioArgs) { //
                    errorCallback(response);
                    return response;
                }

            });
        }
    };

    dojo.connect(sequenceField, "onkeypress", function(event) {
        if (event.keyCode == dojo.keys.ENTER) {
            event.preventDefault();
            search();
        }
    });
    dojo.connect(sequenceButton, "onclick", search);
    dojo.connect(searchAllRefSeqsLabel, "onclick", function() {
        dojo.attr(searchAllRefSeqsCheckbox, "checked", !searchAllRefSeqsCheckbox.checked);
    });

    if (!getSequenceSearchTools()) {
        alert("No search plugins setup");
        return null;
    }

    return content;
}

});

});

<|endoftext|>


<commit_before>var grid = angular.module('game.grid');

grid.controller('gridCtrl', function($scope, TileModel, GridService, Player) {
  // Declare our controller wide dependencies
  var grid = GridService.matrix;
  var meeplePlaced = false;
  var tilePlaced = false;

  $scope.orientation = 0;
  $scope.meepmeep = 'assets/img/Meeples/meeple_' + Player.getColor() + '.png';

  socket.on('nextTurn', function(gamestate) {
    if (!gamestate.lastTile) {
      $scope.currentTile = new TileModel(gamestate.nextTile);
    } else {
      $scope.currentTile = new TileModel(gamestate.nextTile);
      GridService.updateGrid(gamestate.lastTile.x, gamestate.lastTile.y, gamestate.lastTile);
      GridService.setCell(gamestate.lastTile, 'lastTile');
    }
    $scope.src = $scope.currentTile.img;
    $scope.$apply();
  });

  socket.on('meepDataRes', function(data) {
    $scope.numMeeps = data.numMeeps;
  });

  $scope.range = function() {
    return new Array(GridService.gridSize);
  };

  $scope.rotate = function() {
    if (Player.isCurrentPlayer() && !tilePlaced) {
      $scope.orientation = ($scope.orientation + 1) % 4;
      $scope.currentTile.rotateRight();
    }
  };

  $scope.clickCell = function(event, x, y) {
    if (tilePlaced) {
      setMeeple(event, x, y);
    } else {
      setTile(x, y, $scope.currentTile);
    }
  };

  $scope.endTurn = function() {
    if (tilePlaced) {
      tilePlaced = false;
      meeplePlaced = false;
      // Need to pass state of meeple placement to others
      $scope.currentTile.meeple.color = Player.getColor();
      $scope.orientation = 0;
      socket.emit('endTurn', $scope.currentTile);
    } else {
      console.log('Cannot end your turn');
    }
  };

  // TODO: Factor out meeple stuff
  var setMeeple = function(event, x, y) {
    if ($scope.numMeeps > 0 && !meeplePlaced) {
      if ($scope.currentTile.x === x && $scope.currentTile.y === y) {
        $scope.currentTile.meeple.location = 1;
        var meepClass = 'meep-x-' + x + '-y-' + y;
        angular.element(event.target).append('');
        $scope.currentMeeple = angular.element(document.querySelector('.'+meepClass));
        $scope.numMeeps--;
        socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: $scope.numMeeps });
        meeplePlaced = true;
      } else {
        console.log('Can only place meeple on last tile');
      }
    } else {
      console.log('All outta meeps');
    }
  };

  $scope.cycleMeeple = function(item) {
    if (Player.isCurrentPlayer() && $scope.currentMeeple && meeplePlaced) {
      var itemID = angular.element(item.target).attr('id');
      $scope.currentMeeple.attr('class', itemID);
      $scope.currentTile.meeple.location = +$scope.currentMeeple.attr('class').slice(-1);
    }
  };

  var setTile = function(x, y, tile) {
    GridService.setTile(x, y, tile, function() {
      tilePlaced = true;
      meeplePlaced = false;
    });
  };

  // Initialize
  (function() {
    GridService.placeInitialTile();
    GridService.resizeGrid();
    socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: 7 });
  })();

});<commit_msg>got meeple removing for only one player<commit_after>var grid = angular.module('game.grid');

grid.controller('gridCtrl', function($scope, TileModel, GridService, Player) {
  // Declare our controller wide dependencies
  var grid = GridService.matrix;
  var meeplePlaced = false;
  var tilePlaced = false;

  $scope.orientation = 0;
  $scope.meepmeep = 'assets/img/Meeples/meeple_' + Player.getColor() + '.png';

  socket.on('nextTurn', function(gamestate) {
    console.log(gamestate.board);
    if (!gamestate.lastTile) {
      $scope.currentTile = new TileModel(gamestate.nextTile);
    } else {
      $scope.currentTile = new TileModel(gamestate.nextTile);
      GridService.updateGrid(gamestate.lastTile.x, gamestate.lastTile.y, gamestate.lastTile);
      GridService.setCell(gamestate.lastTile, 'lastTile');
    }
    $scope.src = $scope.currentTile.img;
    $scope.$apply();
  });

  socket.on('meepDataRes', function(data) {
    $scope.numMeeps = data.numMeeps;
  });

  $scope.range = function() {
    return new Array(GridService.gridSize);
  };

  $scope.rotate = function() {
    if (Player.isCurrentPlayer() && !tilePlaced) {
      $scope.orientation = ($scope.orientation + 1) % 4;
      $scope.currentTile.rotateRight();
    }
  };

  $scope.clickCell = function(event, x, y) {
    if (tilePlaced) {
      setMeeple(event, x, y);
    } else {
      setTile(x, y, $scope.currentTile);
    }
  };

  $scope.endTurn = function() {
    if (tilePlaced) {
      tilePlaced = false;
      meeplePlaced = false;
      // Need to pass state of meeple placement to others
      $scope.currentTile.meeple.color = Player.getColor();
      $scope.orientation = 0;
      socket.emit('endTurn', $scope.currentTile);
    } else {
      console.log('Cannot end your turn');
    }
  };

  // TODO: Factor out meeple stuff
  var setMeeple = function(event, x, y) {
    if ($scope.numMeeps > 0 && !meeplePlaced) {
      if ($scope.currentTile.x === x && $scope.currentTile.y === y) {
        $scope.currentTile.meeple.location = 1;
        var meepClass = 'meep-x-' + x + '-y-' + y;
        angular.element(event.target).append('')
          .on('click',  pickupMeeple);
        $scope.currentMeeple = angular.element(document.querySelector('.'+meepClass));
        $scope.numMeeps--;
        socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: $scope.numMeeps });
        meeplePlaced = true;
      } else {
        console.log('Can only place meeple on last tile');
      }
    } else {
      console.log('All outta meeps');
    }
  };

  var pickupMeeple = function(event) {
    event.stopPropagation();
    if (event.ctrlKey) {
      var imageSrc = angular.element(this).children('img').attr('src');
      // Check player's color matches the meep
      if (Player.getColor() === imageSrc.match(/_(.*)\.png/)[1]) {
        console.log('picking up a meeple');
        angular.element(event.target).remove();
        $scope.numMeeps++;
        socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: $scope.numMeeps });
      }
    }
  };

  $scope.cycleMeeple = function(item) {
    if (Player.isCurrentPlayer() && $scope.currentMeeple && meeplePlaced) {
      var itemID = angular.element(item.target).attr('id');
      $scope.currentMeeple.attr('class', itemID);
      $scope.currentTile.meeple.location = +$scope.currentMeeple.attr('class').slice(-1);
    }
  };

  var setTile = function(x, y, tile) {
    GridService.setTile(x, y, tile, function() {
      tilePlaced = true;
      meeplePlaced = false;
    });
  };

  // Initialize
  (function() {
    GridService.placeInitialTile();
    GridService.resizeGrid();
    socket.emit('meepDataReq', { username: Player.getUsername(), numMeeps: 7 });
  })();

});<|endoftext|>


<commit_before>angular
    .module('app')
    .factory('apiService', [
        '$http',
        function($http) {
            return {
                client: $http.get('/api/bower'),
                server: $http.get('/api/package'),
                changelog: $http.get('/api/changelog')
            };
        }
    ]);
<commit_msg>Remove missing api references.<commit_after>angular
    .module('app')
    .factory('apiService', [
        '$http',
        function($http) {
            return {
                changelog: $http.get('/api/changelog')
            };
        }
    ]);
<|endoftext|>


<commit_before>import './Subnav.scss';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { Menu } from 'antd';

class Subnav extends Component {
  constructor(props) {
    super(props)
  }

  static propTypes = {
    data: PropTypes.array,
    default: PropTypes.string
  }

  render () {
    return (

        <Menu
          onClick={this.handleClick}
          defaultSelectedKeys={[this.props.default]}
          mode="horizontal"
          className="g-row m-subnav-menu"
        >
          {this.props.data.map((item, index) => {
            // 若导航标题为两个字，则自动在中间加个空格
            if (item.name.length === 2) {
              item.name = item.name[0] + ' ' + item.name[1];
            }
            return (
              <Menu.Item className="item" key={item.name}>
                <Link to={item.path}>{this.props.data[index].name}</Link>
              </Menu.Item>
            )
          })}
        </Menu>

    )
  }
}

export default Subnav;
<commit_msg>fix: tab<commit_after>import './Subnav.scss';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { Menu } from 'antd';

class Subnav extends Component {
  constructor(props) {
    super(props)
  }

  static propTypes = {
    data: PropTypes.array,
    default: PropTypes.string
  }

  render () {
    return (

        <Menu
          onClick={this.handleClick}
          selectedKeys={[this.props.default]}
          mode="horizontal"
          className="g-row m-subnav-menu"
        >
          {this.props.data.map((item, index) => {
            // 若导航标题为两个字，则自动在中间加个空格
            if (item.name.length === 2) {
              item.name = item.name[0] + ' ' + item.name[1];
            }
            return (
              <Menu.Item className="item" key={item.name.replace(' ', '')}>
                <Link to={item.path}>{this.props.data[index].name}</Link>
              </Menu.Item>
            )
          })}
        </Menu>

    )
  }
}

export default Subnav;
<|endoftext|>


<commit_before>/**
 * @author   Fabrice Sommavilla <fs@physalix.com>
 * @company  Physalix
 * @version  0.1
 * @date     22/01/2017
 */

"use strict";

import React, {Component} from 'react';
import Helmet from 'react-helmet';
import {Footer} from 'components';
import auth from '../utils/auth'
import 'whatwg-fetch';
import dateFormat from 'dateformat';
import {FormControl, ControlLabel, FormGroup, Panel, Button} from 'react-bootstrap';

/**
 * Manage all users profiles.
 */
export default class Profiles extends Component {

    /**
     *
     * @param props
     */
    constructor(props) {
        super(props);
        this.state = {profile: {}, message: ""};
        this.handleChange = this.handleChange.bind(this);
    }

    /**
     *
     */
    componentWillMount() {
        this.fetchProfileData((data) => {
            this.setState({profile: data});
        });
    }

    /**
     *
     * @param cb
     */
    fetchProfileData(cb) {
        fetch(`${auth.getServerUrl()}/users/${this.props.params.id}?api_key=${auth.getToken()}`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        }).then(function (res) {
            return res.json().then(function (data) {
                if (res.status === 200) {
                    cb(data);
                }
            });
        });
    }

    handleChange(e) {
        let profile = {};
        profile[e.target.name] = e.target.value;
        this.setState({profile: profile});
    }

    /**
     *
     * @returns {*}
     */
    displayPageTitle() {
        if (this.props.params.id === auth.getUserId()) {
            return "Your Profile";
        }

        return `Profile: ${this.state.profile.firstname} ${this.state.profile.lastname}`;
    }

    /**
     *
     * @returns {XML}
     */
    renderMessage() {
        if (this.state.message.length > 0) {
            return (

{this.state.message}

            );
        }
    }

    /**
     *
     * @returns {XML}
     */
    render() {
        const styles = require('./styles.css');
        return (

                <Helmet title={this.displayPageTitle()}/>

{this.displayPageTitle()}

                        <Panel header="Panel heading without title">

                                        {this.state.profile.group}
                                        {this.state.profile.active ? "Yes" : "No"}
                                        {this.state.profile.gender === 'm' ? 'Male' : 'Female'}
                                        {dateFormat(this.state.profile.createdAt, "dd/mm/yyyy, HH:MM:ss")}
                                        {dateFormat(this.state.profile.updatedAt, "dd/mm/yyyy, HH:MM:ss")}
                                        <form id="loginForm" name="loginForm" onSubmit={this.onSubmit}>
                                            <FormGroup controlId="formControlsEmail">
                                                <ControlLabel>Email address</ControlLabel>
                                                <FormControl
                                                    type="email"
                                                    name="email"
                                                    value={this.state.profile.email}
                                                    placeholder="Your email"
                                                    onChange={this.handleChange}
                                                />
                                                <FormControl.Feedback />
                                            </FormGroup>
                                            <FormGroup controlId="formControlsUsername">
                                                <ControlLabel>Username</ControlLabel>
                                                <FormControl
                                                    type="text"
                                                    name="username"
                                                    value={this.state.profile.username}
                                                    placeholder="Your username"
                                                    onChange={this.handleChange}
                                                />
                                                <FormControl.Feedback />
                                            </FormGroup>
                                            <FormGroup controlId="formControlsFirstname">
                                                <ControlLabel>Firstname</ControlLabel>
                                                <FormControl
                                                    type="text"
                                                    name="firstname"
                                                    value={this.state.profile.firstname}
                                                    placeholder="Your firstname"
                                                    onChange={this.handleChange}
                                                />
                                                <FormControl.Feedback />
                                            </FormGroup>
                                            <FormGroup controlId="formControlsLastname">
                                                <ControlLabel>Firstname</ControlLabel>
                                                <FormControl
                                                    type="text"
                                                    name="lastname"
                                                    value={this.state.profile.lastname}
                                                    placeholder="Your lastname"
                                                    onChange={this.handleChange}
                                                />
                                                <FormControl.Feedback />
                                            </FormGroup>
                                            { this.renderMessage() }
                                            <Button type="submit" className="btn btn-primary">Update</Button>
                                        </form>

                        </Panel>

        );

    }

}<commit_msg>test react boostrap<commit_after>/**
 * @author   Fabrice Sommavilla <fs@physalix.com>
 * @company  Physalix
 * @version  0.1
 * @date     22/01/2017
 */

"use strict";

import React, {Component} from 'react';
import Helmet from 'react-helmet';
import {Footer} from 'components';
import auth from '../utils/auth'
import 'whatwg-fetch';
import dateFormat from 'dateformat';
import {FormControl, ControlLabel, FormGroup, Panel, Button} from 'react-bootstrap';

/**
 * Manage all users profiles.
 */
export default class Profiles extends Component {

    /**
     *
     * @param props
     */
    constructor(props) {
        super(props);
        this.state = {profile: {}, message: ""};
        this.handleChange = this.handleChange.bind(this);
    }

    /**
     *
     */
    componentWillMount() {
        this.fetchProfileData((data) => {
            this.setState({profile: data});
        });
    }

    /**
     *
     * @param cb
     */
    fetchProfileData(cb) {
        fetch(`${auth.getServerUrl()}/users/${this.props.params.id}?api_key=${auth.getToken()}`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        }).then(function (res) {
            return res.json().then(function (data) {
                if (res.status === 200) {
                    cb(data);
                }
            });
        });
    }

    handleChange(e) {
        let update = {};
        update[e.target.name] = e.target.value;
        this.setState({profile: update});
    }

    /**
     *
     * @returns {*}
     */
    displayPageTitle() {
        if (this.props.params.id === auth.getUserId()) {
            return "Your Profile";
        }

        return `Profile: ${this.state.profile.firstname} ${this.state.profile.lastname}`;
    }

    /**
     *
     * @returns {XML}
     */
    renderMessage() {
        if (this.state.message.length > 0) {
            return (

{this.state.message}

            );
        }
    }

    /**
     *
     * @returns {XML}
     */
    render() {
        const styles = require('./styles.css');
        return (

                <Helmet title={this.displayPageTitle()}/>

{this.displayPageTitle()}

                        <Panel header="Panel heading without title">

                                        {this.state.profile.group}
                                        {this.state.profile.active ? "Yes" : "No"}
                                        {this.state.profile.gender === 'm' ? 'Male' : 'Female'}
                                        {dateFormat(this.state.profile.createdAt, "dd/mm/yyyy, HH:MM:ss")}
                                        {dateFormat(this.state.profile.updatedAt, "dd/mm/yyyy, HH:MM:ss")}
                                        <form id="loginForm" name="loginForm" onSubmit={this.onSubmit}>
                                            <FormGroup controlId="formControlsEmail">
                                                <ControlLabel>Email address</ControlLabel>
                                                <FormControl
                                                    type="email"
                                                    name="email"
                                                    value={this.state.profile.email}
                                                    placeholder="Your email"
                                                    onChange={this.handleChange}
                                                />
                                                <FormControl.Feedback />
                                            </FormGroup>
                                            <FormGroup controlId="formControlsUsername">
                                                <ControlLabel>Username</ControlLabel>
                                                <FormControl
                                                    type="text"
                                                    name="username"
                                                    value={this.state.profile.username}
                                                    placeholder="Your username"
                                                    onChange={this.handleChange}
                                                />
                                                <FormControl.Feedback />
                                            </FormGroup>
                                            <FormGroup controlId="formControlsFirstname">
                                                <ControlLabel>Firstname</ControlLabel>
                                                <FormControl
                                                    type="text"
                                                    name="firstname"
                                                    value={this.state.profile.firstname}
                                                    placeholder="Your firstname"
                                                    onChange={this.handleChange}
                                                />
                                                <FormControl.Feedback />
                                            </FormGroup>
                                            <FormGroup controlId="formControlsLastname">
                                                <ControlLabel>Firstname</ControlLabel>
                                                <FormControl
                                                    type="text"
                                                    name="lastname"
                                                    value={this.state.profile.lastname}
                                                    placeholder="Your lastname"
                                                    onChange={this.handleChange}
                                                />
                                                <FormControl.Feedback />
                                            </FormGroup>
                                            { this.renderMessage() }
                                            <Button type="submit" className="btn btn-primary">Update</Button>
                                        </form>

                        </Panel>

        );

    }

}<|endoftext|>


<commit_before>'use strict';

angular.module('phoenixeye')
.controller('ImageCtrl', [
	'$scope',
	'$http',
	'ngToast',
	'$stateParams',
	'$timeout',
	'PollSvc',
	function ImageCtrl($scope, $http, ngToast, $stateParams, $timeout, PollSvc) {
		console.log('stateParams', $stateParams);

		$scope.image = $stateParams.image;
		$scope.displayedImage = $stateParams.image;
		$scope.displayedHSV = null;
		$scope.displayedLab = null;

		$scope.analyses = {
			ela: [],
			lg: [],
			avgdist: [],
			copymove: []
		};

		$scope.histograms = {
			hsv: [],
			lab_fast: []
		};

		$scope.collapsedPanels = {};

		//poll for jobId if its a fresh submission
		if( $stateParams.jobId ) {
			PollSvc.pollUntil({
				method: 'get',
				url: 'api/jobs/' + $stateParams.jobId
			}, function (resp) {
				return resp.job.status == 'complete';
			}).promise.then(function (resp) {
				console.log('job poll resolved', resp);
				getAnalyses();
			});
		}

		//poll until image metadata gathering is complete
		PollSvc.pollUntil({
			method: 'get',
			url: 'api/images/' + $stateParams.permalink
		}, function (resp) {
			return resp.image.metaComplete;
		}).promise.then(function (resp) {
			console.log('image poll resolved', resp);
			$scope.image = resp.image;
			$scope.displayedImage = resp.image;
			getAnalyses();
		});

		$scope.$watch('image', function (newV) {
			if( ! newV ) return;

			$scope.metaList = {};
			if( newV.xmp ) {
				$scope.metaList.xmp = newV.xmp;
			}

			if( newV.exif ) {
				$scope.metaList.exif = newV.exif;
			}

			if( newV.iptc ) {
				$scope.metaList.iptc = newV.iptc;
			}

			}
		});
		//get analyses and separate them by type between histograms/analyses
		function getAnalyses() {
			$http({
				method: 'get',
				url: 'api/analyses/' + $scope.image._id
			}).success(function (resp, status) {
				console.log('analyses', resp);
				resp.analyses.forEach(function (analysis) {
					if( analysis.type == 'hsv' || analysis.type == 'lab_fast' ) {
						$scope.histograms[analysis.type].push(analysis);
					} else {
						$scope.analyses[analysis.type].push(analysis);
					}
				});

				//sort by most recent created date
				for( var type in $scope.analyses ) {
					$scope.analyses[type] = $scope.analyses[type].sort(function (a, b) {
						return a.created < b.created;
					});
				}

				//sort by most recent created date
				for( var type in $scope.histograms ) {
					$scope.histograms[type] = $scope.histograms[type].sort(function (a, b) {
						return a.created < b.created;
					});
				}

				$scope.displayedHSV = $scope.histograms.hsv[0];
				$scope.displayedLab = $scope.histograms.lab_fast[0];
			}).error(function (resp, status) {
				console.log('error analyses', resp);
			});
		}

		//switch displayed image
		$scope.displayImage = function(image) {
			$scope.displayedImage = image;
		};
	}
]);<commit_msg>get qtables after analyses are loaded<commit_after>'use strict';

angular.module('phoenixeye')
.controller('ImageCtrl', [
	'$scope',
	'$http',
	'ngToast',
	'$stateParams',
	'$timeout',
	'PollSvc',
	function ImageCtrl($scope, $http, ngToast, $stateParams, $timeout, PollSvc) {
		console.log('stateParams', $stateParams);

		$scope.image = $stateParams.image;
		$scope.displayedImage = $stateParams.image;
		$scope.displayedHSV = null;
		$scope.displayedLab = null;

		$scope.analyses = {
			ela: [],
			lg: [],
			avgdist: [],
			copymove: []
		};

		$scope.histograms = {
			hsv: [],
			lab_fast: []
		};

		$scope.collapsedPanels = {};

		//poll for jobId if its a fresh submission
		if( $stateParams.jobId ) {
			PollSvc.pollUntil({
				method: 'get',
				url: 'api/jobs/' + $stateParams.jobId
			}, function (resp) {
				return resp.job.status == 'complete';
			}).promise.then(function (resp) {
				console.log('job poll resolved', resp);
				getAnalyses();
			});
		}

		//poll until image metadata gathering is complete
		PollSvc.pollUntil({
			method: 'get',
			url: 'api/images/' + $stateParams.permalink
		}, function (resp) {
			return resp.image.metaComplete;
		}).promise.then(function (resp) {
			console.log('image poll resolved', resp);
			$scope.image = resp.image;
			$scope.displayedImage = resp.image;
			getAnalyses();
		});

		$scope.$watch('image', function (newV) {
			if( ! newV ) return;

			$scope.metaList = {};
			if( newV.xmp ) {
				$scope.metaList.xmp = newV.xmp;
			}

			if( newV.exif ) {
				$scope.metaList.exif = newV.exif;
			}

			if( newV.iptc ) {
				$scope.metaList.iptc = newV.iptc;
			}

			}
		});
		//get analyses and separate them by type between histograms/analyses
		function getAnalyses() {
			$http({
				method: 'get',
				url: 'api/analyses/' + $scope.image._id
			}).success(function (resp, status) {
				console.log('analyses', resp);
				resp.analyses.forEach(function (analysis) {
					if( analysis.type == 'hsv' || analysis.type == 'lab_fast' ) {
						$scope.histograms[analysis.type].push(analysis);
					} else {
						$scope.analyses[analysis.type].push(analysis);
					}
				});

				//sort by most recent created date
				for( var type in $scope.analyses ) {
					$scope.analyses[type] = $scope.analyses[type].sort(function (a, b) {
						return a.created < b.created;
					});
				}

				//sort by most recent created date
				for( var type in $scope.histograms ) {
					$scope.histograms[type] = $scope.histograms[type].sort(function (a, b) {
						return a.created < b.created;
					});
				}

				$scope.displayedHSV = $scope.histograms.hsv[0];
				$scope.displayedLab = $scope.histograms.lab_fast[0];

				//get qtables for jpg after analysis complete
				if( $scope.image.type == 'jpg' && Object.keys($scope.image.qtables).length == 0 ) {
					$http({
						method: 'get',
						url: 'api/images/' + $stateParams.permalink
					}).then(function (resp) {
						$scope.image = resp.data.image;
					});
				}
			}).error(function (resp, status) {
				console.log('error analyses', resp);
			});
		}

		//switch displayed image
		$scope.displayImage = function(image) {
			$scope.displayedImage = image;
		};
	}
]);<|endoftext|>


<commit_before>'use strict';

/**
 * @constructor
 */
var EffectManager = function()
{
};

EffectManager._createEmitter = function(data)
{
  var emitter = new ParticleEmitter();

  // Set initial particle properties
  emitter.alignType      = data.alignType;
  emitter.coordType      = data.coordType;
  emitter.emitRate       = data.emitRate;
  emitter.emitRadius     = data.emitRadius;
  emitter.gravity        = data.gravity;
  emitter.lifeTime       = data.lifeTime;
  emitter.loopCount      = data.loopCount;
  emitter.particleCount  = data.particleCount;
  emitter.spawnDirection = data.spawnDirection;
  emitter.spriteCols     = data.spriteCols;
  emitter.spriteRows     = data.spriteRows;

  // Load texture
  emitter.texture = TextureManager.load(data.texturePath);
  emitter.texture.repeat.set(1 / data.spriteCols, 1 / data.spriteRows);

  // Set material properties
  emitter.material = ShaderManager.get('particle').clone();
  emitter.material.uniforms = {
    texture1: {type: 't', value: null },
    uvScale:  {type: 'v2', value: new THREE.Vector2(1, 1)},
    uvOffset: {type: 'v2', value: new THREE.Vector2(0, 0)},
    vColor:   {type: 'c', value: new THREE.Color(0, 0, 0)},
    vAlpha:   {type: 'f', value: 1}
  };

  emitter.material.blending = THREE.CustomBlending;
  emitter.material.blendSrc = convertZnzinBlendType(data.blendSrc);
  emitter.material.blendDst = convertZnzinBlendType(data.blendDst);
  emitter.material.blendEquation = convertZnzinBlendOp(data.blendOp);

  // Set events
  for (var i = 0; i < data.events.length; ++i) {
    var eventData = data.events[i];
    var event = {
      time: eventData.time.getValueInRange(),
      type: eventData.type,
      fade: eventData.blended,
      fadeEvent: null
    };

    switch (event.type) {
      case ParticleSystemData.EVENT_TYPE.SIZE:
        event.size = eventData.size;
        break;
      case ParticleSystemData.EVENT_TYPE.TIMER:
        event.timer = eventData.timer;
        break;
      case ParticleSystemData.EVENT_TYPE.RED:
        event.red = eventData.red;
        break;
      case ParticleSystemData.EVENT_TYPE.GREEN:
        event.green = eventData.green;
        break;
      case ParticleSystemData.EVENT_TYPE.BLUE:
        event.blue = eventData.blue;
        break;
      case ParticleSystemData.EVENT_TYPE.ALPHA:
        event.alpha = eventData.alpha;
        break;
      case ParticleSystemData.EVENT_TYPE.COLOR:
        event.color = eventData.color;
        break;
      case ParticleSystemData.EVENT_TYPE.VELOCITY_X:
        event.velocityX = eventData.velocityX;
        break;
      case ParticleSystemData.EVENT_TYPE.VELOCITY_Y:
        event.velocityY = eventData.velocityY;
        break;
      case ParticleSystemData.EVENT_TYPE.VELOCITY_Z:
        event.velocityZ = eventData.velocityZ;
        break;
      case ParticleSystemData.EVENT_TYPE.VELOCITY:
        event.velocity = eventData.velocity;
        break;
      case ParticleSystemData.EVENT_TYPE.TEXTURE:
        event.textureIndex = eventData.textureIndex;
        break;
      case ParticleSystemData.EVENT_TYPE.ROTATION:
        event.rotation = eventData.rotation;
        break;
      default:
        throw 'Unexpected particle event type!';
    }

    emitter.events.push(event);
  }

  // Sort events
  emitter.events.sort(function(left, right) {
    return left.time - right.time;
  });

  // Link fade events
  for (var i = 0; i < emitter.events.length; ++i) {
    var event = emitter.events[i];

    for (var j = i + 1; j < emitter.events.length; ++j) {
      var other = emitter.events[j];

      if (other.fade && other.type === event.type) {
        event.fadeEvent = other;
        break;
      }
    }
  }

  return emitter;
};

/**
 * @constructor
 */
var Effect = function(rootObj)
{
  this.rootObj  = new THREE.Object3D();
  this.rootObj2 = new THREE.Object3D();

  this.particleEffects = [];
  this.animations =[];
};

Effect.prototype.resetBlendWeights = function() {
  // Needed for THREE.AnimationHandler
};

Effect.prototype.play = function() {
  THREE.AnimationHandler.play(this);

  for (var i = 0; i < this.particleEffects.length; ++i) {
    this.particleEffects[i].play();
  }

  for (var i = 0; i < this.animations.length; ++i) {
    this.animations[i].play();
  }
};

Effect.prototype.stop = function() {
  THREE.AnimationHandler.stop(this);

  for (var i = 0; i < this.particleEffects.length; ++i) {
    this.particleEffects[i].stop();
  }

  for (var i = 0; i < this.animations.length; ++i) {
    this.animations[i].stop();
  }
};

Effect.prototype.update = function(delta) {
  for (var i = 0; i < this.particleEffects.length; ++i) {
    this.particleEffects[i].update(delta);
  }

  for (var i = 0; i < this.animations.length; ++i) {
    this.animations[i].update(delta);
  }
};

Effect.STATE = {
  READY_TO_PLAY: 0,
  PLAYING: 1,
  STOPPED: 2
};

/**
 * @constructor
 */
var ParticleEffect = function()
{
  this.rootObj = new THREE.Object3D();
  this.emitters = [];
  this.startDelay = 0;
  this.animation = null;
  this.state = Effect.STATE.READY_TO_PLAY;
};

ParticleEffect.prototype.play = function() {
  // Initialise stuff to play
};

ParticleEffect.prototype.stop = function() {
  // Make shit stop
};

ParticleEffect.prototype.update = function(delta) {
  if (this.state === Effect.STATE.READY_TO_PLAY) {
    this.startDelay -= delta;

    if (this.startDelay < 0) {
      this.state = Effect.STATE.PLAYING;

      if (this.animation) {
        this.animation.play();
      }

      delta = -this.startDelay;
    }
  }

  if (this.state === Effect.STATE.PLAYING) {
    for (var i = 0; i < this.emitters.length; ++i) {
      this.emitters[i].update(delta);
    }
  }
};

EffectManager._loadParticleEffect = function(path, callback) {
  var effect = new ParticleEffect();
  effect.path = path;

  ParticleSystemData.load(path, function(particleSystem) {
    for (var i = 0; i < particleSystem.emitters.length; ++i) {
      var emitter = EffectManager._createEmitter(particleSystem.emitters[i]);
      effect.emitters.push(emitter);
      effect.rootObj.add(emitter.rootObj);
    }

    if (callback) {
      callback();
    }
  });

  return effect;
};

EffectManager._loadMeshAnimation = function(data, callback) {
  var animation = new Effect.Animation();
  var texture = TextureManager.load(data.texturePath);

  // Set animation properties
  animation.name = data.name;

  // Create material
  var material = ShaderManager.get('partmesh').clone();

  material.uniforms = {
    texture1: { type: 't', value: texture }
  };

  material.transparent   = true;
  material.depthTest     = data.depthTestEnabled;
  material.depthWrite    = data.depthWriteEnabled;
  material.blending      = THREE.CustomBlending;
  material.blendEquation = convertZnzinBlendOp(data.blendOp);
  material.blendSrc      = convertZnzinBlendType(data.blendSrc);
  material.blendDst      = convertZnzinBlendType(data.blendDst);

  if (data.twoSideEnabled) {
    material.side = THREE.DoubleSide;
  }

  if (data.alphaEnabled) {
    if (data.alphaTestEnabled) {
      material.alphaTest = 0.5;
    }
  }

  // TODO: Remove this once Three.js properly copies the default attribs.
  material.defaultAttributeValues['alpha'] = 1;

  Mesh.load(data.meshPath, function(geometry) {
    animation.mesh = new THREE.Mesh(geometry, animation.material);

    // ROSE, you suck...
    if (data.animationPath && data.animationPath !== 'NULL') {
      AnimationData.load(data.animationPath, function (animData) {
        animation.meshAnimation = new GeometryAnimator(geometry, animData);
        callback();
      });
    } else {
      callback();
    }
  });

  return animation;
};

/**
 * @constructor
 */
Effect.Animation = function() {
  this.rootObj = new THREE.Object3D();
  this.state = Effect.STATE.READY_TO_PLAY;
  this.startDelay = 0;
  this.animation = null;
  this.material = null;
  this.mesh = null;
  this.meshAnimation = null;
};

Effect.Animation.prototype.play = function() {
  // Initialise stuff to play
};

Effect.Animation.prototype.stop = function() {
  // Make shit stop
};

Effect.Animation.prototype.update = function(delta) {
  if (this.state === Effect.STATE.READY_TO_PLAY) {
    this.startDelay -= delta;

    if (this.startDelay < 0) {
      this.state = Effect.STATE.PLAYING;

      if (this.animation) {
        this.animation.play();
      }

      if (this.meshAnimation) {
        this.meshAnimation.play();
      }

      delta = -this.startDelay;
    }
  }

  // Check loopCount related shit
};

EffectManager.loadEffectByIdx = function(index, callback) {
  var effect = new Effect();

  GDM.get('file_effect', function (effectFileTable) {
    var effectRow = effectFileTable.row(index);
    EffectManager.loadEffect(effectRow[1], callback, effect);
  });

  return effect;
};

EffectManager.loadEffect = function(path, callback, effect) {
  var waitAll = new MultiWait();
  var effectWait = waitAll.one();
  effect = effect || new Effect();

  EffectData.load(path, function (effectData) {
    if (config.noeffects) {
      // Don't load effects if they are disabled by configuration.
      return;
    }

    effect.path = path;
    effect.loopCount = effectData.loopCount;

    effect.rootObj.name = effectData.name + ".rootObj";
    effect.rootObj2.name = effectData.name +  ".rootObj2";
    // TODO: Effect sound - data.soundEnabled, data.soundPath

    for (var i = 0; i < effectData.particles.length; ++i) {
      var data = effectData.particles[i];
      var particle = EffectManager._loadParticleEffect(data.particlePath, waitAll.one());

      // Set initial properties
      particle.startDelay = data.delay / 1000;
      particle.rootObj.position.copy(data.position);
      particle.rootObj.quaternion.copy(data.rotation);

      if (data.linkRoot) {
        effect.rootObj.add(particle.rootObj);
      } else {
        effect.rootObj2.add(particle.rootObj);
      }

      if (data.animation.enabled) {
        if (data.animation.name && data.animation.name !== "NULL") {
          (function(_particle, _data) {
            var particleAnimWait = waitAll.one();
            AnimationData.load(data.animation.name, function (animData)
            {
              _particle.animation = new ObjectAnimator(_particle.rootObj, animData);
              _particle.animationLoopCount = _data.animation.loopCount;
              particleAnimWait();
            });
          })(particle, data);
        }
      }

      effect.particleEffects.push(particle);
    }

    for (var i = 0; i < effectData.animations.length; ++i) {
      var data = effectData.animations[i];
      var meshAnimation = EffectManager._loadMeshAnimation(data, waitAll.one());

      // Set initial properties
      meshAnimation.startDelay = data.delay / 1000;
      meshAnimation.loopCount = data.loopCount;
      meshAnimation.rootObj.position.copy(data.position);
      meshAnimation.rootObj.quaternion.copy(data.rotation);

      if (data.linkRoot) {
        effect.rootObj.add(meshAnimation.rootObj);
      } else {
        effect.rootObj2.add(meshAnimation.rootObj);
      }

      if (data.animation.enabled) {
        if (data.animation.name && data.animation.name !== "NULL") {
          (function(_meshAnimation, _data) {
            var meshAnimationWait = waitAll.one();
            AnimationData.load(data.animation.name, function (animData) {
              _meshAnimation.animation = new ObjectAnimator(_meshAnimation.rootObj, animData);
              _meshAnimation.animationLoopCount = _data.animation.loopCount;
              meshAnimationWait();
            });
          })(meshAnimation, data);
        }
      }

      effect.animations.push(meshAnimation);
    }

    effectWait();
  });

  waitAll.wait(callback);
  return effect;
};
<commit_msg>Fix bug causing effect animated meshs to fail to be displayed.<commit_after>'use strict';

/**
 * @constructor
 */
var EffectManager = function()
{
};

EffectManager._createEmitter = function(data)
{
  var emitter = new ParticleEmitter();

  // Set initial particle properties
  emitter.alignType      = data.alignType;
  emitter.coordType      = data.coordType;
  emitter.emitRate       = data.emitRate;
  emitter.emitRadius     = data.emitRadius;
  emitter.gravity        = data.gravity;
  emitter.lifeTime       = data.lifeTime;
  emitter.loopCount      = data.loopCount;
  emitter.particleCount  = data.particleCount;
  emitter.spawnDirection = data.spawnDirection;
  emitter.spriteCols     = data.spriteCols;
  emitter.spriteRows     = data.spriteRows;

  // Load texture
  emitter.texture = TextureManager.load(data.texturePath);
  emitter.texture.repeat.set(1 / data.spriteCols, 1 / data.spriteRows);

  // Set material properties
  emitter.material = ShaderManager.get('particle').clone();
  emitter.material.uniforms = {
    texture1: {type: 't', value: null },
    uvScale:  {type: 'v2', value: new THREE.Vector2(1, 1)},
    uvOffset: {type: 'v2', value: new THREE.Vector2(0, 0)},
    vColor:   {type: 'c', value: new THREE.Color(0, 0, 0)},
    vAlpha:   {type: 'f', value: 1}
  };

  emitter.material.blending = THREE.CustomBlending;
  emitter.material.blendSrc = convertZnzinBlendType(data.blendSrc);
  emitter.material.blendDst = convertZnzinBlendType(data.blendDst);
  emitter.material.blendEquation = convertZnzinBlendOp(data.blendOp);

  // Set events
  for (var i = 0; i < data.events.length; ++i) {
    var eventData = data.events[i];
    var event = {
      time: eventData.time.getValueInRange(),
      type: eventData.type,
      fade: eventData.blended,
      fadeEvent: null
    };

    switch (event.type) {
      case ParticleSystemData.EVENT_TYPE.SIZE:
        event.size = eventData.size;
        break;
      case ParticleSystemData.EVENT_TYPE.TIMER:
        event.timer = eventData.timer;
        break;
      case ParticleSystemData.EVENT_TYPE.RED:
        event.red = eventData.red;
        break;
      case ParticleSystemData.EVENT_TYPE.GREEN:
        event.green = eventData.green;
        break;
      case ParticleSystemData.EVENT_TYPE.BLUE:
        event.blue = eventData.blue;
        break;
      case ParticleSystemData.EVENT_TYPE.ALPHA:
        event.alpha = eventData.alpha;
        break;
      case ParticleSystemData.EVENT_TYPE.COLOR:
        event.color = eventData.color;
        break;
      case ParticleSystemData.EVENT_TYPE.VELOCITY_X:
        event.velocityX = eventData.velocityX;
        break;
      case ParticleSystemData.EVENT_TYPE.VELOCITY_Y:
        event.velocityY = eventData.velocityY;
        break;
      case ParticleSystemData.EVENT_TYPE.VELOCITY_Z:
        event.velocityZ = eventData.velocityZ;
        break;
      case ParticleSystemData.EVENT_TYPE.VELOCITY:
        event.velocity = eventData.velocity;
        break;
      case ParticleSystemData.EVENT_TYPE.TEXTURE:
        event.textureIndex = eventData.textureIndex;
        break;
      case ParticleSystemData.EVENT_TYPE.ROTATION:
        event.rotation = eventData.rotation;
        break;
      default:
        throw 'Unexpected particle event type!';
    }

    emitter.events.push(event);
  }

  // Sort events
  emitter.events.sort(function(left, right) {
    return left.time - right.time;
  });

  // Link fade events
  for (var i = 0; i < emitter.events.length; ++i) {
    var event = emitter.events[i];

    for (var j = i + 1; j < emitter.events.length; ++j) {
      var other = emitter.events[j];

      if (other.fade && other.type === event.type) {
        event.fadeEvent = other;
        break;
      }
    }
  }

  return emitter;
};

/**
 * @constructor
 */
var Effect = function(rootObj)
{
  this.rootObj  = new THREE.Object3D();
  this.rootObj2 = new THREE.Object3D();

  this.particleEffects = [];
  this.animations =[];
};

Effect.prototype.resetBlendWeights = function() {
  // Needed for THREE.AnimationHandler
};

Effect.prototype.play = function() {
  THREE.AnimationHandler.play(this);

  for (var i = 0; i < this.particleEffects.length; ++i) {
    this.particleEffects[i].play();
  }

  for (var i = 0; i < this.animations.length; ++i) {
    this.animations[i].play();
  }
};

Effect.prototype.stop = function() {
  THREE.AnimationHandler.stop(this);

  for (var i = 0; i < this.particleEffects.length; ++i) {
    this.particleEffects[i].stop();
  }

  for (var i = 0; i < this.animations.length; ++i) {
    this.animations[i].stop();
  }
};

Effect.prototype.update = function(delta) {
  for (var i = 0; i < this.particleEffects.length; ++i) {
    this.particleEffects[i].update(delta);
  }

  for (var i = 0; i < this.animations.length; ++i) {
    this.animations[i].update(delta);
  }
};

Effect.STATE = {
  READY_TO_PLAY: 0,
  PLAYING: 1,
  STOPPED: 2
};

/**
 * @constructor
 */
var ParticleEffect = function()
{
  this.rootObj = new THREE.Object3D();
  this.emitters = [];
  this.startDelay = 0;
  this.animation = null;
  this.state = Effect.STATE.READY_TO_PLAY;
};

ParticleEffect.prototype.play = function() {
  // Initialise stuff to play
};

ParticleEffect.prototype.stop = function() {
  // Make shit stop
};

ParticleEffect.prototype.update = function(delta) {
  if (this.state === Effect.STATE.READY_TO_PLAY) {
    this.startDelay -= delta;

    if (this.startDelay < 0) {
      this.state = Effect.STATE.PLAYING;

      if (this.animation) {
        this.animation.play();
      }

      delta = -this.startDelay;
    }
  }

  if (this.state === Effect.STATE.PLAYING) {
    for (var i = 0; i < this.emitters.length; ++i) {
      this.emitters[i].update(delta);
    }
  }
};

EffectManager._loadParticleEffect = function(path, callback) {
  var effect = new ParticleEffect();
  effect.path = path;

  ParticleSystemData.load(path, function(particleSystem) {
    for (var i = 0; i < particleSystem.emitters.length; ++i) {
      var emitter = EffectManager._createEmitter(particleSystem.emitters[i]);
      effect.emitters.push(emitter);
      effect.rootObj.add(emitter.rootObj);
    }

    if (callback) {
      callback();
    }
  });

  return effect;
};

EffectManager._loadMeshAnimation = function(data, callback) {
  var animation = new Effect.Animation();
  var texture = TextureManager.load(data.texturePath);

  // Set animation properties
  animation.name = data.name;

  // Create material
  var material = ShaderManager.get('partmesh').clone();

  material.uniforms = {
    texture1: { type: 't', value: texture }
  };

  material.transparent   = true;
  material.depthTest     = data.depthTestEnabled;
  material.depthWrite    = data.depthWriteEnabled;
  material.blending      = THREE.CustomBlending;
  material.blendEquation = convertZnzinBlendOp(data.blendOp);
  material.blendSrc      = convertZnzinBlendType(data.blendSrc);
  material.blendDst      = convertZnzinBlendType(data.blendDst);

  if (data.twoSideEnabled) {
    material.side = THREE.DoubleSide;
  }

  if (data.alphaEnabled) {
    if (data.alphaTestEnabled) {
      material.alphaTest = 0.5;
    }
  }

  // TODO: Remove this once Three.js properly copies the default attribs.
  material.defaultAttributeValues['alpha'] = 1;

  animation.material = material;

  Mesh.load(data.meshPath, function(geometry) {
    animation.mesh = new THREE.Mesh(geometry, animation.material);
    animation.rootObj.add(animation.mesh);

    // ROSE, you suck...
    if (data.animationPath && data.animationPath !== 'NULL') {
      AnimationData.load(data.animationPath, function (animData) {
        animation.meshAnimation = new GeometryAnimator(geometry, animData);
        // If we take a while to load, its possible we've already started.
        if (animation.state === Effect.STATE.PLAYING) {
          animation.meshAnimation.play();
        }
        callback();
      });
    } else {
      callback();
    }
  });

  return animation;
};

/**
 * @constructor
 */
Effect.Animation = function() {
  this.rootObj = new THREE.Object3D();
  this.state = Effect.STATE.READY_TO_PLAY;
  this.startDelay = 0;
  this.animation = null;
  this.material = null;
  this.mesh = null;
  this.meshAnimation = null;
};

Effect.Animation.prototype.play = function() {
  // Initialise stuff to play
};

Effect.Animation.prototype.stop = function() {
  // Make shit stop
};

Effect.Animation.prototype.update = function(delta) {
  if (this.state === Effect.STATE.READY_TO_PLAY) {
    this.startDelay -= delta;

    if (this.startDelay < 0) {
      this.state = Effect.STATE.PLAYING;

      if (this.animation) {
        this.animation.play();
      }

      if (this.meshAnimation) {
        this.meshAnimation.play();
      }

      delta = -this.startDelay;
    }
  }

  // Check loopCount related shit
};

EffectManager.loadEffectByIdx = function(index, callback) {
  var effect = new Effect();

  GDM.get('file_effect', function (effectFileTable) {
    var effectRow = effectFileTable.row(index);
    EffectManager.loadEffect(effectRow[1], callback, effect);
  });

  return effect;
};

EffectManager.loadEffect = function(path, callback, effect) {
  var waitAll = new MultiWait();
  var effectWait = waitAll.one();
  effect = effect || new Effect();

  EffectData.load(path, function (effectData) {
    if (config.noeffects) {
      // Don't load effects if they are disabled by configuration.
      return;
    }

    effect.path = path;
    effect.loopCount = effectData.loopCount;

    effect.rootObj.name = effectData.name + ".rootObj";
    effect.rootObj2.name = effectData.name +  ".rootObj2";
    // TODO: Effect sound - data.soundEnabled, data.soundPath

    for (var i = 0; i < effectData.particles.length; ++i) {
      var data = effectData.particles[i];
      var particle = EffectManager._loadParticleEffect(data.particlePath, waitAll.one());

      // Set initial properties
      particle.startDelay = data.delay / 1000;
      particle.rootObj.position.copy(data.position);
      particle.rootObj.quaternion.copy(data.rotation);

      if (data.linkRoot) {
        effect.rootObj.add(particle.rootObj);
      } else {
        effect.rootObj2.add(particle.rootObj);
      }

      if (data.animation.enabled) {
        if (data.animation.name && data.animation.name !== "NULL") {
          (function(_particle, _data) {
            var particleAnimWait = waitAll.one();
            AnimationData.load(data.animation.name, function (animData)
            {
              _particle.animation = new ObjectAnimator(_particle.rootObj, animData);
              _particle.animationLoopCount = _data.animation.loopCount;
              particleAnimWait();
            });
          })(particle, data);
        }
      }

      effect.particleEffects.push(particle);
    }

    for (var i = 0; i < effectData.animations.length; ++i) {
      var data = effectData.animations[i];
      var meshAnimation = EffectManager._loadMeshAnimation(data, waitAll.one());

      // Set initial properties
      meshAnimation.startDelay = data.delay / 1000;
      meshAnimation.loopCount = data.loopCount;
      meshAnimation.rootObj.position.copy(data.position);
      meshAnimation.rootObj.quaternion.copy(data.rotation);

      if (data.linkRoot) {
        effect.rootObj.add(meshAnimation.rootObj);
      } else {
        effect.rootObj2.add(meshAnimation.rootObj);
      }

      if (data.animation.enabled) {
        if (data.animation.name && data.animation.name !== "NULL") {
          (function(_meshAnimation, _data) {
            var meshAnimationWait = waitAll.one();
            AnimationData.load(data.animation.name, function (animData) {
              _meshAnimation.animation = new ObjectAnimator(_meshAnimation.rootObj, animData);
              _meshAnimation.animationLoopCount = _data.animation.loopCount;
              meshAnimationWait();
            });
          })(meshAnimation, data);
        }
      }

      effect.animations.push(meshAnimation);
    }

    effectWait();
  });

  waitAll.wait(callback);
  return effect;
};
<|endoftext|>


<commit_before>define([], function() {

    return {
        opts: function() {
            return _.map(this.list, function(v,s) { return '<option value="'+v+'">'+s+'</option>' }).join()
        },
        obj: function() {
            return _.invert(this.list)
        },

        key: function(value) {
            return _.invert(this.list)[value]
        },

        list: {
            '': '',
            'native': 'OSC',
            'phasing': 'SAD',
            'ligand': 'Ligand binding',
        }

    }

})<commit_msg>Added stepped transmission as experiment kind for autocollect, SCI-8965<commit_after>define([], function() {

    return {
        opts: function() {
            return _.map(this.list, function(v,s) { return '<option value="'+v+'">'+s+'</option>' }).join()
        },
        obj: function() {
            return _.invert(this.list)
        },

        key: function(value) {
            return _.invert(this.list)[value]
        },

        list: {
            '': '',
            'native': 'OSC',
            'phasing': 'SAD',
            'ligand': 'Ligand binding',
            'stepped': 'Stepped transmission',
        }

    }

})<|endoftext|>