<commit_before>/**
 * Exchange rate of NBU widget.
 * Displayed in the main menu.
 */

(function(){

    var course = {

        dom_obj : {},
        map     : [],

        init : function(){

            this.dom_obj = create_block_element('course_block', main_menu.dom_obj);

            var title = create_inline_element('', this.dom_obj);
            title.setClass('course_title');
            title.innerHTML = word['course_title'];

            this.date_obj = create_inline_element('', this.dom_obj);
            this.date_obj.setClass('course_date');

            for(var i=0; i<3; i++){
                var item = {};

                var ul = document.createElement('ul');

                var currency = document.createElement('li');
                currency.setClass('course_currency');
                ul.appendChild(currency);

                item['currency_dom_obj'] = currency;

                var value = document.createElement('li');
                value.setClass('course_value');
                ul.appendChild(value);

                item['value_dom_obj'] = value;

                var trend = document.createElement('li');
                trend.setClass('course_trend');

                var uarr = create_inline_element('uarr', trend);
                uarr.innerHTML = '↑';
                uarr.hide();

                var darr = create_inline_element('darr', trend);
                darr.innerHTML = '↓';
                darr.hide();

                item['uarr'] = uarr;

                item['darr'] = darr;

                var trend_val = create_inline_element('trend_val', trend);

                item['trend_val'] = trend_val;

                ul.appendChild(trend);

                //item['trend_dom_obj'] = trend;

                this.map.push(item);

                this.dom_obj.appendChild(ul);
            }

            this.dom_obj.hide();
        },

        set : function(data){
            _debug('course.set', data);

            this.current = data;

            if (!empty(this.current)){
                this.dom_obj.show();
            }

            this.date_obj.innerHTML = data.on_date || '';

            for(var i=0; i<this.map.length; i++){

                if (data['data'].hasOwnProperty(i)){

                    this.map[i].currency_dom_obj.innerHTML = data['data'][i].currency;
                    this.map[i].value_dom_obj.innerHTML    = data['data'][i].value;

                    if (parseFloat(data['data'][i].trend) == -1){
                        this.map[i].darr.show();
                        this.map[i].uarr.hide();
                        this.map[i].trend_val.innerHTML = data['data'][i].diff;
                    }else if (parseFloat(data['data'][i].trend) == 1){
                        this.map[i].darr.hide();
                        this.map[i].uarr.show();
                        this.map[i].trend_val.innerHTML = data['data'][i].diff;
                    }else{
                        this.map[i].darr.hide();
                        this.map[i].uarr.hide();
                        this.map[i].trend_val.innerHTML = '';
                    }
                }else{
                    this.map[i].currency_dom_obj.innerHTML = '';
                    this.map[i].value_dom_obj.innerHTML    = '';
                    this.map[i].trend_val.innerHTML = '';
                    this.map[i].darr.hide();
                    this.map[i].uarr.hide();
                }
            }
        }
    }

    course.init();

    module.course = course;

    loader.next();

})();<commit_msg>"Remove comment"<commit_after>/**
 * Exchange rate of NBU widget.
 * Displayed in the main menu.
 */

(function(){

    var course = {

        dom_obj : {},
        map     : [],

        init : function(){

            this.dom_obj = create_block_element('course_block', main_menu.dom_obj);

            var title = create_inline_element('', this.dom_obj);
            title.setClass('course_title');
            title.innerHTML = word['course_title'];

            this.date_obj = create_inline_element('', this.dom_obj);
            this.date_obj.setClass('course_date');

            for(var i=0; i<3; i++){
                var item = {};

                var ul = document.createElement('ul');

                var currency = document.createElement('li');
                currency.setClass('course_currency');
                ul.appendChild(currency);

                item['currency_dom_obj'] = currency;

                var value = document.createElement('li');
                value.setClass('course_value');
                ul.appendChild(value);

                item['value_dom_obj'] = value;

                var trend = document.createElement('li');
                trend.setClass('course_trend');

                var uarr = create_inline_element('uarr', trend);
                uarr.innerHTML = '↑';
                uarr.hide();

                var darr = create_inline_element('darr', trend);
                darr.innerHTML = '↓';
                darr.hide();

                item['uarr'] = uarr;

                item['darr'] = darr;

                var trend_val = create_inline_element('trend_val', trend);

                item['trend_val'] = trend_val;

                ul.appendChild(trend);

                this.map.push(item);

                this.dom_obj.appendChild(ul);
            }

            this.dom_obj.hide();
        },

        set : function(data){
            _debug('course.set', data);

            this.current = data;

            if (!empty(this.current)){
                this.dom_obj.show();
            }

            this.date_obj.innerHTML = data.on_date || '';

            for(var i=0; i<this.map.length; i++){

                if (data['data'].hasOwnProperty(i)){

                    this.map[i].currency_dom_obj.innerHTML = data['data'][i].currency;
                    this.map[i].value_dom_obj.innerHTML    = data['data'][i].value;

                    if (parseFloat(data['data'][i].trend) == -1){
                        this.map[i].darr.show();
                        this.map[i].uarr.hide();
                        this.map[i].trend_val.innerHTML = data['data'][i].diff;
                    }else if (parseFloat(data['data'][i].trend) == 1){
                        this.map[i].darr.hide();
                        this.map[i].uarr.show();
                        this.map[i].trend_val.innerHTML = data['data'][i].diff;
                    }else{
                        this.map[i].darr.hide();
                        this.map[i].uarr.hide();
                        this.map[i].trend_val.innerHTML = '';
                    }
                }else{
                    this.map[i].currency_dom_obj.innerHTML = '';
                    this.map[i].value_dom_obj.innerHTML    = '';
                    this.map[i].trend_val.innerHTML = '';
                    this.map[i].darr.hide();
                    this.map[i].uarr.hide();
                }
            }
        }
    }

    course.init();

    module.course = course;

    loader.next();

})();<|endoftext|>


<commit_before>'use strict';

/**
 * @file
 * Creates a list of tokens
 *
 * This component is only used internally for the TokenSearchField
 *
 * Properties:
 * query: array of strings
 * remove: callback function for removing elements with a certain index
 *
 */

import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
import Token from './Token.component.js';

/**
 * Get a random color. This function is used for development only.
 * Should be exchanged with a colorscheme
 *
 * @returns {string}
 * @private
 */
function _getRandomColor() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

/**
 * Return a color depending on the type
 *
 * @param type
 * @returns {*}
 */
function getColor(type) {
  switch (type) {
    case 'text':
      return '#222';
    default:
      return '#61b6d9';
  }
}

export default React.createClass({
  displayName: 'TokenList.component',
  propTypes: {
    hasFocus: PropTypes.bool,
    setFocus: PropTypes.func,
    query: PropTypes.array.isRequired,
    remove: PropTypes.func.isRequired,
    translations: PropTypes.object
  },

  getInitialState() {
    let queries = this.props.query.map((query)=> {
      return {
        text: query,
        color: _getRandomColor()
      };
    });
    return {
      query: queries
    };
  },
  getTranslation(type, text) {
    if (this.props.translations && type !== 'text' && this.props.translations[text]) {
      return this.props.translations[text];
    }

    return text;
  },

  replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
  },

  getListWidth(tokens) {
    const padding = 4;
    const emptySpace = 75;
    return tokens
        .map(element => element && ReactDOM.findDOMNode(element).offsetWidth)
        .reduce((sum, width) => sum + width + padding) + emptySpace;
  },

  scrollToEnd(scrollWrapper) {
    ReactDOM.findDOMNode(scrollWrapper).scrollLeft = 10000;
  },

  containsClass(className, list) {
    return Array.prototype.filter.call(list, (listClassName) => className === listClassName).length && true || false;
  },

  onEventListClick(event) {
    if (this.containsClass('tokenlist', event.target.classList) && this.props.setFocus) {
      this.props.setFocus(true);
    }
  },

  updateListWidth(listWidth) {
    if (listWidth !== this.state.listWidth) {
      this.setState({listWidth});
    }
  },

  componentDidUpdate() {
    this.scrollToEnd(this.refs.tokenList);
    this.updateListWidth(this.getListWidth(this._tokens));
  },

  componentDidMount() {
    this.scrollToEnd(this.refs.tokenList);
  },

  render() {
    // _tokens contains a list of Token Components.
    this._tokens = [];
    const {query, remove} = this.props;
    const tokenClasses = !this.props.hasFocus && 'tokens-wrapper' || 'tokens-wrapper hide';

    const tokens = query.map((element, index)=> {
      return (
        <Token
          ref={component => this._tokens.push(component)}
          color={getColor(element.type)}
          index={element.index}
          key={index}
          remove={remove.bind(null, element)}
          text={this.getTranslation(element.type, this.replaceAll(element.value.toString(), ',', ' eller '))}
          />
      );
    });

    return (

 this.onEventListClick(event)}
          >
          {tokens}

    );
  }
});
<commit_msg>Fix error when no tokens exists<commit_after>'use strict';

/**
 * @file
 * Creates a list of tokens
 *
 * This component is only used internally for the TokenSearchField
 *
 * Properties:
 * query: array of strings
 * remove: callback function for removing elements with a certain index
 *
 */

import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
import Token from './Token.component.js';

/**
 * Get a random color. This function is used for development only.
 * Should be exchanged with a colorscheme
 *
 * @returns {string}
 * @private
 */
function _getRandomColor() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

/**
 * Return a color depending on the type
 *
 * @param type
 * @returns {*}
 */
function getColor(type) {
  switch (type) {
    case 'text':
      return '#222';
    default:
      return '#61b6d9';
  }
}

export default React.createClass({
  displayName: 'TokenList.component',
  propTypes: {
    hasFocus: PropTypes.bool,
    setFocus: PropTypes.func,
    query: PropTypes.array.isRequired,
    remove: PropTypes.func.isRequired,
    translations: PropTypes.object
  },

  getInitialState() {
    let queries = this.props.query.map((query)=> {
      return {
        text: query,
        color: _getRandomColor()
      };
    });
    return {
      query: queries
    };
  },
  getTranslation(type, text) {
    if (this.props.translations && type !== 'text' && this.props.translations[text]) {
      return this.props.translations[text];
    }

    return text;
  },

  replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
  },

  getListWidth(tokens) {
    if (!tokens.length) {
      return 0;
    }
    const padding = 4;
    const emptySpace = 75;
    return tokens
        .map(element => element && ReactDOM.findDOMNode(element).offsetWidth)
        .reduce((sum, width) => sum + width + padding) + emptySpace;
  },

  scrollToEnd(scrollWrapper) {
    ReactDOM.findDOMNode(scrollWrapper).scrollLeft = 10000;
  },

  containsClass(className, list) {
    return Array.prototype.filter.call(list, (listClassName) => className === listClassName).length && true || false;
  },

  onEventListClick(event) {
    if (this.containsClass('tokenlist', event.target.classList) && this.props.setFocus) {
      this.props.setFocus(true);
    }
  },

  updateListWidth(listWidth) {
    if (listWidth !== this.state.listWidth) {
      this.setState({listWidth});
    }
  },

  componentDidUpdate() {
    this.scrollToEnd(this.refs.tokenList);
    this.updateListWidth(this.getListWidth(this._tokens));
  },

  componentDidMount() {
    this.scrollToEnd(this.refs.tokenList);
  },

  render() {
    // _tokens contains a list of Token Components.
    this._tokens = [];
    const {query, remove} = this.props;
    const tokenClasses = !this.props.hasFocus && 'tokens-wrapper' || 'tokens-wrapper hide';

    const tokens = query.map((element, index)=> {
      return (
        <Token
          ref={component => this._tokens.push(component)}
          color={getColor(element.type)}
          index={element.index}
          key={index}
          remove={remove.bind(null, element)}
          text={this.getTranslation(element.type, this.replaceAll(element.value.toString(), ',', ' eller '))}
          />
      );
    });

    return (

 this.onEventListClick(event)}
          >
          {tokens}

    );
  }
});
<|endoftext|>


<commit_before><commit_msg>Update Sights.js<commit_after><|endoftext|>


<commit_before>/**
 * GetHeaderRest.js
 *
 * This file has all the methods to get PR_TRANSPORT_MESSAGE_HEADERS
 * from the current message via REST.
 *
 * To use this file, your page JS needs to implement the following methods:
 *
 * - updateStatus(message): Should be a method that displays a status to the user,
 *   preferably with some sort of activity indicator (spinner)
 * - hideStatus: Method to hide the status displays
 * - showError(error, message): Method to communicate an error to the user.
 * - getHeadersComplete(headers): Callback to receive headers.
 *
 * Requirement Sets and Permissions
 * getCallbackTokenAsync requires 1.5 and ReadItem
 * convertToRestId requires 1.3 and Restricted
 * restUrl requires 1.5 and ReadItem
 */

function sendHeadersRequestRest() {
    updateStatus(ImportedStrings.mha_RequestSent);

    Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function (result) {
        if (result.status === "succeeded") {
            var accessToken = result.value;
            getHeaders(accessToken);
        } else {
            showError(null, 'Unable to obtain callback token.\n' + result.error);
        }
    });
}

function getItemRestId() {
    // Currently the only Outlook Mobile version that supports add-ins
    // is Outlook for iOS.
    if (Office.context.mailbox.diagnostics.hostName === "OutlookIOS") {
        // itemId is already REST-formatted
        return Office.context.mailbox.item.itemId;
    } else {
        // Convert to an item ID for API v2.0
        return Office.context.mailbox.convertToRestId(
            Office.context.mailbox.item.itemId,
            Office.MailboxEnums.RestVersion.v2_0
        );
    }
}

function getBaseUrl(url) {
    var parts = url.split("/");

    return parts[0] + "//" + parts[2];
}

function getRestUrl(accessToken) {
    // Shim function to workaround
    // mailbox.restUrl == null case
    if (Office.context.mailbox.restUrl) {
        return getBaseUrl(Office.context.mailbox.restUrl);
    }

    // parse the token
    var jwt = window.jwt_decode(accessToken);

    // 'aud' parameter from token can be in a couple of
    // different formats.

    // Format 1: It's just the URL
    if (jwt.aud.match(/https:\/\/([^@]*)/)) {
        return jwt.aud;
    }

    // Format 2: GUID/hostname@GUID
    var match = jwt.aud.match(/\/([^@]*)@/);
    if (match && match[1]) {
        return "https://" + match[1];
    }

    // Couldn't find what we expected, default to
    // outlook.office.com
    return "https://outlook.office.com";
}

function getHeaders(accessToken) {
    if (!accessToken) {
        LogError(null, "No access token?");
    }

    // Get the item's REST ID
    var itemId = getItemRestId();

    var getMessageUrl = getRestUrl(accessToken) +
        "/api/v2.0/me/messages/" +
        itemId +
        // PR_TRANSPORT_MESSAGE_HEADERS
        "?$select=SingleValueExtendedProperties&$expand=SingleValueExtendedProperties($filter=PropertyId eq 'String 0x007D')";

    $.ajax({
        url: getMessageUrl,
        dataType: "json",
        headers: {
            "Authorization": "Bearer " + accessToken,
            "Accept": "application/json; odata.metadata=none"
        }
    }).done(function (item) {
        if (item.SingleValueExtendedProperties !== undefined) {
            getHeadersComplete(item.SingleValueExtendedProperties[0].Value);
        } else {
            showError(null, ImportedStrings.mha_headersMissing);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        showError(null, "textStatus: " + textStatus + '\nerrorThrown: ' + errorThrown + "\njqXHR: " + JSON.stringify(jqXHR, null, 2));
    }).always(function () {
        hideStatus();
    });
}<commit_msg>Hacky fix for #43 - when rest fails, fall back to EWS<commit_after>/**
 * GetHeaderRest.js
 *
 * This file has all the methods to get PR_TRANSPORT_MESSAGE_HEADERS
 * from the current message via REST.
 *
 * To use this file, your page JS needs to implement the following methods:
 *
 * - updateStatus(message): Should be a method that displays a status to the user,
 *   preferably with some sort of activity indicator (spinner)
 * - hideStatus: Method to hide the status displays
 * - showError(error, message): Method to communicate an error to the user.
 * - getHeadersComplete(headers): Callback to receive headers.
 *
 * Requirement Sets and Permissions
 * getCallbackTokenAsync requires 1.5 and ReadItem
 * convertToRestId requires 1.3 and Restricted
 * restUrl requires 1.5 and ReadItem
 */

function sendHeadersRequestRest() {
    updateStatus(ImportedStrings.mha_RequestSent);

    Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function (result) {
        if (result.status === "succeeded") {
            var accessToken = result.value;
            getHeaders(accessToken);
        } else {
            showError(null, 'Unable to obtain callback token.\n' + result.error);
        }
    });
}

function getItemRestId() {
    // Currently the only Outlook Mobile version that supports add-ins
    // is Outlook for iOS.
    if (Office.context.mailbox.diagnostics.hostName === "OutlookIOS") {
        // itemId is already REST-formatted
        return Office.context.mailbox.item.itemId;
    } else {
        // Convert to an item ID for API v2.0
        return Office.context.mailbox.convertToRestId(
            Office.context.mailbox.item.itemId,
            Office.MailboxEnums.RestVersion.v2_0
        );
    }
}

function getBaseUrl(url) {
    var parts = url.split("/");

    return parts[0] + "//" + parts[2];
}

function getRestUrl(accessToken) {
    // Shim function to workaround
    // mailbox.restUrl == null case
    if (Office.context.mailbox.restUrl) {
        return getBaseUrl(Office.context.mailbox.restUrl);
    }

    // parse the token
    var jwt = window.jwt_decode(accessToken);

    // 'aud' parameter from token can be in a couple of
    // different formats.

    // Format 1: It's just the URL
    if (jwt.aud.match(/https:\/\/([^@]*)/)) {
        return jwt.aud;
    }

    // Format 2: GUID/hostname@GUID
    var match = jwt.aud.match(/\/([^@]*)@/);
    if (match && match[1]) {
        return "https://" + match[1];
    }

    // Couldn't find what we expected, default to
    // outlook.office.com
    return "https://outlook.office.com";
}

function getHeaders(accessToken) {
    if (!accessToken) {
        LogError(null, "No access token?");
    }

    // Get the item's REST ID
    var itemId = getItemRestId();

    var getMessageUrl = getRestUrl(accessToken) +
        "/api/v2.0/me/messages/" +
        itemId +
        // PR_TRANSPORT_MESSAGE_HEADERS
        "?$select=SingleValueExtendedProperties&$expand=SingleValueExtendedProperties($filter=PropertyId eq 'String 0x007D')";

    $.ajax({
        url: getMessageUrl,
        dataType: "json",
        headers: {
            "Authorization": "Bearer " + accessToken,
            "Accept": "application/json; odata.metadata=none"
        }
    }).done(function (item) {
        if (item.SingleValueExtendedProperties !== undefined) {
            getHeadersComplete(item.SingleValueExtendedProperties[0].Value);
        } else {
            showError(null, ImportedStrings.mha_headersMissing);
        }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            if (textStatus === "error" && jqXHR.status === 0) {
                sendHeadersRequestEWS();
            } else {
                showError(null, "textStatus: " + textStatus + '\nerrorThrown: ' + errorThrown + "\nState: " + jqXHR.state() + "\njqXHR: " + JSON.stringify(jqXHR, null, 2));
            }
    }).always(function () {
        hideStatus();
    });
}<|endoftext|>


<commit_before>'use strict';

var React   = require('react-native');
var Button  = require('react-native-button');
var Modal   = require('react-native-modalbox');

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var styles = StyleSheet.create({

  wrapper: {
    paddingTop: 50,
    flex: 1
  },

  modal: {
    justifyContent: 'center',
    alignItems: 'center'
  },

  modal1: {
    flex: 1
  },

  modal2: {
    height: 230,
    backgroundColor: "#3B5998"
  },

  modal3: {
    height: 300,
    width: 300
  },

  modal4: {
    height: 300
  },

  btn: {
    margin: 10,
    backgroundColor: "#3B5998",
    color: "white",
    padding: 10
  },

  btnModal: {
    position: "absolute",
    top: 0,
    right: 0,
    width: 50,
    height: 50,
    backgroundColor: "transparent"
  },

  text: {
    color: "black",
    fontSize: 22
  }

});

var Example = React.createClass({

  openModal1: function(id) {
    this.refs.modal1.open();
  },

  openModal2: function(id) {
    this.refs.modal2.open();
  },

  openModal3: function(id) {
    this.refs.modal3.open();
  },

  openModal4: function(id) {
    this.refs.modal4.open();
  },

  openModal5: function(id) {
    this.refs.modal5.open();
  },

  closeModal5: function(id) {
    this.refs.modal5.close();
  },

  onClose: function() {
    console.log('Modal just closed');
  },

  onOpen: function() {
    console.log('Modal just openned');
  },

  onClosingState: function(state) {
    console.log('the open/close of the swipeToClose just changed');
  },

  render: function() {

    var BContent = <Button onPress={this.closeModal5} style={[styles.btn, styles.btnModal]}>X</Button>;

    return (
      <View style={styles.wrapper}>
        <Button onPress={this.openModal1} style={styles.btn}>Basic modal</Button>
        <Button onPress={this.openModal2} style={styles.btn}>Position top</Button>
        <Button onPress={this.openModal3} style={styles.btn}>Position centered + backdrop</Button>
        <Button onPress={this.openModal4} style={styles.btn}>Position bottom + backdrop</Button>
        <Button onPress={this.openModal5} style={styles.btn}>Backdrop + backdropContent</Button>

        <Modal style={[styles.modal, styles.modal1]} ref={"modal1"} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
          <Text style={styles.text}>Basic modal</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal2]} backdrop={false}  position={"top"} ref={"modal2"}>
          <Text style={[styles.text, {color: "white"}]}>Modal on top</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal3]} position={"center"} ref={"modal3"}>
          <Text style={styles.text}>Modal centered</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal4]} position={"bottom"} ref={"modal4"}>
          <Text style={styles.text}>Modal on bottom with backdrop</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal4]} position={"center"} backdropContent={BContent} ref={"modal5"}>
          <Text style={styles.text}>Modal with backdrop content</Text>
        </Modal>
      </View>
    );
  }
});

AppRegistry.registerComponent('Example', () => Example);
<commit_msg>Example updated with the use of the isOpen property<commit_after>'use strict';

var React   = require('react-native');
var Button  = require('react-native-button');
var Modal   = require('react-native-modalbox');

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var styles = StyleSheet.create({

  wrapper: {
    paddingTop: 50,
    flex: 1
  },

  modal: {
    justifyContent: 'center',
    alignItems: 'center'
  },

  modal1: {
    flex: 1
  },

  modal2: {
    height: 230,
    backgroundColor: "#3B5998"
  },

  modal3: {
    height: 300,
    width: 300
  },

  modal4: {
    height: 300
  },

  btn: {
    margin: 10,
    backgroundColor: "#3B5998",
    color: "white",
    padding: 10
  },

  btnModal: {
    position: "absolute",
    top: 0,
    right: 0,
    width: 50,
    height: 50,
    backgroundColor: "transparent"
  },

  text: {
    color: "black",
    fontSize: 22
  }

});

var Example = React.createClass({

  getInitialState: function() {
    return {
      isOpen: false
    };
  },

  openModal1: function(id) {
    this.refs.modal1.open();
  },

  openModal2: function(id) {
    this.refs.modal2.open();
  },

  openModal3: function(id) {
    this.refs.modal3.open();
  },

  openModal4: function(id) {
    this.refs.modal4.open();
  },

  openModal5: function(id) {
    this.setState({isOpen: true});
  },

  closeModal5: function(id) {
    this.setState({isOpen: false});
  },

  onClose: function() {
    console.log('Modal just closed');
  },

  onOpen: function() {
    console.log('Modal just openned');
  },

  onClosingState: function(state) {
    console.log('the open/close of the swipeToClose just changed');
  },

  render: function() {

    var BContent = <Button onPress={this.closeModal5} style={[styles.btn, styles.btnModal]}>X</Button>;

    return (
      <View style={styles.wrapper}>
        <Button onPress={this.openModal1} style={styles.btn}>Basic modal</Button>
        <Button onPress={this.openModal2} style={styles.btn}>Position top</Button>
        <Button onPress={this.openModal3} style={styles.btn}>Position centered + backdrop</Button>
        <Button onPress={this.openModal4} style={styles.btn}>Position bottom + backdrop</Button>
        <Button onPress={this.openModal5} style={styles.btn}>Backdrop + backdropContent</Button>

        <Modal style={[styles.modal, styles.modal1]} ref={"modal1"} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
          <Text style={styles.text}>Basic modal</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal2]} backdrop={false}  position={"top"} ref={"modal2"}>
          <Text style={[styles.text, {color: "white"}]}>Modal on top</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal3]} position={"center"} ref={"modal3"}>
          <Text style={styles.text}>Modal centered</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal4]} position={"bottom"} ref={"modal4"}>
          <Text style={styles.text}>Modal on bottom with backdrop</Text>
        </Modal>

        <Modal isOpen={this.state.isOpen} onClosed={this.closeModal5} style={[styles.modal, styles.modal4]} position={"center"} backdropContent={BContent}>
          <Text style={styles.text}>Modal with backdrop content</Text>
        </Modal>
      </View>
    );
  }
});

AppRegistry.registerComponent('Example', () => Example);
<|endoftext|>


<commit_before>/**
 * @Author: Wahaj Shamim <wahaj>
 * @Date:   2018-02-15T15:05:45+11:00
 * @Email:  inbox.wahaj@gmail.com
 * @Last modified by:   wahaj
 * @Last modified time: 2018-02-15T17:12:16+11:00
 *
 * dbKoda - a modern, open source code editor, for MongoDB.
 * Copyright (C) 2017-2018 Southbank Software
 *
 * This file is part of dbKoda.
 *
 * dbKoda is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * dbKoda 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with dbKoda.  If not, see <http://www.gnu.org/licenses/>.
 */

function timescale(num, a, b) {
  if (isNaN(num)) {
    throw new TypeError('expected a number');
  }
  return num * unitTimeValue(a) / unitTimeValue(b);
}

function unitTimeValue(name) {
  switch (name) {
    case 'ns':
      return 1;
    case 'μs':
    case 'us':
      return 1e3;
    case 'ms':
      return 1e6;
    case 's':
      return 1e9;
    case 'm':
      return 6e10;
    case 'h':
      return 36e11;
    case 'd':
      return 864e11;
    case 'w':
      return 6048e11;
    default: {
      throw new Error('"' + name + '" is not a valid unit of time.');
    }
  }
}
export const convertTime = (value, unit, length) => {
  const result = {
    value,
    unit
  };
  if (String(Math.round(value)).length > length) {
    switch (unit) {
      case '/μs':
        result.unit = '/ms';
        result.value = timescale(value, 'μs', 'ms').toFixed(2);
        break;
      case '/ms':
        result.unit = '/s';
        result.value = timescale(value, 'ms', 's').toFixed(2);
        break;
      case '/s':
        result.unit = '/m';
        result.value = timescale(value, 's', 'm').toFixed(2);
        break;
      case '/m':
        result.unit = '/h';
        result.value = timescale(value, 'm', 'h').toFixed(2);
        break;
      case '/h':
        result.unit = '/d';
        result.value = timescale(value, 'h', 'd').toFixed(2);
        break;
      default: {
        console.error('"' + unit + '" is not a valid unit of time.');
        return result;
      }
    }
    return convertTime(result.value, result.unit, length);
  }
  result.value = (String(value).indexOf('.') >= 0) ? Number(value).toFixed(2) : value;
  return result;
};

export const convertBytes = (value, unit, length) => {
  const result = {
    value,
    unit
  };
  if (String(Math.round(value)).length > length) {
    switch (unit) {
      case 'b':
        result.unit = 'kb';
        break;
      case 'kb':
        result.unit = 'mb';
        break;
      case 'mb':
        result.unit = 'gb';
        break;
      case 'gb':
        result.unit = 'tb';
        break;
      case 'tb':
        result.unit = 'pb';
        break;
      case 'pb':
        result.unit = 'eb';
        break;
      default: {
        console.error('"' + unit + '" is the maximum supported unit of bytes.');
        return result;
      }
    }
    result.value = (value / 1024).toFixed(2);
    return convertBytes(result.value, result.unit, length);
  }
  return result;
};

export const convertUnits = (value, unit, length) => {
  if ('/μs|/us|/ms|/s|/m|/h'.indexOf(unit) >= 0) {
    return convertTime(value, unit, length);
  } else if ('b|kb|mb|gb|tb|pb|eb'.indexOf(unit) >= 0) {
    return convertBytes(value, unit, length);
  }
  console.log('Unknown unit is provided for conversion!!!');
  return {
    value: (String(value).indexOf('.') >= 0) ? Number(value).toFixed(2) : value,
    unit
  };
};
<commit_msg><commit_after>/**
 * @Author: Wahaj Shamim <wahaj>
 * @Date:   2018-02-15T15:05:45+11:00
 * @Email:  inbox.wahaj@gmail.com
 * @Last modified by:   wahaj
 * @Last modified time: 2018-02-16T11:32:14+11:00
 *
 * dbKoda - a modern, open source code editor, for MongoDB.
 * Copyright (C) 2017-2018 Southbank Software
 *
 * This file is part of dbKoda.
 *
 * dbKoda is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * dbKoda 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with dbKoda.  If not, see <http://www.gnu.org/licenses/>.
 */

function timescale(num, a, b) {
  if (isNaN(num)) {
    throw new TypeError('expected a number');
  }
  return num * unitTimeValue(a) / unitTimeValue(b);
}

function unitTimeValue(name) {
  switch (name) {
    case 'ns':
      return 1;
    case 'μs':
    case 'us':
      return 1e3;
    case 'ms':
      return 1e6;
    case 's':
      return 1e9;
    case 'm':
      return 6e10;
    case 'h':
      return 36e11;
    case 'd':
      return 864e11;
    case 'w':
      return 6048e11;
    default: {
      throw new Error('"' + name + '" is not a valid unit of time.');
    }
  }
}
export const convertTime = (value, unit, length) => {
  const result = {
    value,
    unit
  };
  if (String(Math.round(value)).length > length) {
    switch (unit) {
      case '/μs':
        result.unit = '/ms';
        result.value = timescale(value, 'μs', 'ms').toFixed(2);
        break;
      case '/ms':
        result.unit = '/s';
        result.value = timescale(value, 'ms', 's').toFixed(2);
        break;
      case '/s':
        result.unit = '/m';
        result.value = timescale(value, 's', 'm').toFixed(2);
        break;
      case '/m':
        result.unit = '/h';
        result.value = timescale(value, 'm', 'h').toFixed(2);
        break;
      case '/h':
        result.unit = '/d';
        result.value = timescale(value, 'h', 'd').toFixed(2);
        break;
      default: {
        console.error('"' + unit + '" is not a valid unit of time.');
        return result;
      }
    }
    return convertTime(result.value, result.unit, length);
  }
  result.value = (String(value).indexOf('.') >= 0) ? Number(value).toFixed(2) : value;
  return result;
};

export const convertBytes = (value, unit, length) => {
  const result = {
    value,
    unit
  };
  if (String(Math.round(value)).length > length) {
    switch (unit) {
      case 'b':
        result.unit = 'kb';
        break;
      case 'kb':
        result.unit = 'mb';
        break;
      case 'mb':
        result.unit = 'gb';
        break;
      case 'gb':
        result.unit = 'tb';
        break;
      case 'tb':
        result.unit = 'pb';
        break;
      case 'pb':
        result.unit = 'eb';
        break;
      default: {
        console.error('"' + unit + '" is the maximum supported unit of bytes.');
        return result;
      }
    }
    result.value = (value / 1024).toFixed(2);
    return convertBytes(result.value, result.unit, length);
  }
  return result;
};

export const convertUnits = (value, unit, length) => {
  if ('/μs|/us|/ms|/s|/m|/h'.indexOf(unit) >= 0) {
    return convertTime(value, unit, length);
  } else if ('b|kb|mb|gb|tb|pb|eb'.indexOf(unit) >= 0) {
    return convertBytes(value, unit, length);
  }
  console.log('Unknown unit is provided for conversion!!!');
  return {
    value: (String(value).indexOf('.') >= 0) ? Number(value).toFixed(2) : value,
    unit
  };
};

export const hofUnitFormatter = (unit, length) => {
  const unitFormatter = (value) => {
    const result = convertUnits(value, unit, length);
    return result.value + ' ' + result.unit;
  };
  return unitFormatter;
};
<|endoftext|>


<commit_before>/**
 * @author biud436
 * @help
 *
 * 기본적으로는 초고속으로 다운로드를 할 수 있는 Aria2c를 사용합니다.
 * node Downloader.js v0.44.1
 *
 * /f라는 명령행 옵션을 추가하면 기본 노드 API로 다운로드를 수행합니다.
 * node Downloader.js v0.44.1 /f
 *
 * Aria2c가 없으면 기본 API로 다운로드가 수행됩니다.
 */

const Aria2c = require('./Aria2c');
const fs = require('fs-extra');
const path = require('path');
const readline = require('readline');
const DecompressZip = require('decompress-zip');
const fileGet = require("./fileGet");
const async = require('async');
const {
    promisify
} = require('util');

const readdirAsync = promisify(fs.readdir);

const args = process.argv.slice(2);

const VERSION = args[0];
const option = args[1];

let mainPath = process.cwd().replace( /\\/g, '/' );
let outputPath = `${mainPath}/${VERSION}`.replace( /\\/g, '/' );

let Color = {
    Reset : "\x1b[0m",
    Bright : "\x1b[1m",
    Dim : "\x1b[2m",
    Underscore : "\x1b[4m",
    Blink : "\x1b[5m",
    Reverse : "\x1b[7m",
    Hidden : "\x1b[8m",

    FgBlack : "\x1b[30m",
    FgRed : "\x1b[31m",
    FgGreen : "\x1b[32m",
    FgYellow : "\x1b[33m",
    FgBlue : "\x1b[34m",
    FgMagenta : "\x1b[35m",
    FgCyan : "\x1b[36m",
    FgWhite : "\x1b[37m",

    BgBlack : "\x1b[40m",
    BgRed : "\x1b[41m",
    BgGreen : "\x1b[42m",
    BgYellow : "\x1b[43m",
    BgBlue : "\x1b[44m",
    BgMagenta : "\x1b[45m",
    BgCyan : "\x1b[46m",
    BgWhite : "\x1b[47m",
};

let config = {
    referrer : `https://dl.nwjs.io/`,
    userAgent : `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36`,
    inputFile : "input.txt",
    logFile : "log.txt",
};

String.prototype.splitOnLast = function (e) {
    var t = this.lastIndexOf(e) + 1;
    return 0 > t ? this : this.substr(t);
};

class Downloader {

    constructor() {
        this._output = [];
        this._isAria2c = false;

        this.checkAria2c();
    }

    processLine(line) {
        const filename = line.splitOnLast("/");
        this._output.push(line);
        this._output.push(`  dir=${outputPath}`);
        this._output.push(`  out=${filename}`);
    }

    checkAria2c() {

        if(option === "/f") {
            this._isAria2c = false;
            return;
        }

        const env = process.env["PATH"].split(";");
        const needed = env.filter(dir => dir.indexOf("aria") >= 0);
        console.log(needed);
        needed.forEach(i => {
            if(fs.existsSync(path.join(i.replace(/\\/g, "/"), "aria2c.exe"))) {
                console.log("aria2c.exe 파일을 찾았습니다.")
                this._isAria2c = true;
            }
        });
    }

    removeFiles() {
        const files = {
            input: path.join(mainPath, "input.txt").replace( /\\/g, '/' ),
            log: path.join(mainPath, "log.txt").replace( /\\/g, '/' ),
        };

        if(fs.existsSync(files.input)) fs.removeSync(files.input);
        if(fs.existsSync(files.log)) fs.removeSync(files.log);
    }

    async *readOutputFolder() {
        try {
            const dir = await readdirAsync(outputPath);
            for (const file of dir) {
                yield file;
            }
        } catch(e) {
            throw new Error(e);
        }
    }

    async unzip() {

        const files = await this.readOutputFolder();

        for await (const file of files) {
            const realPath = path.join(outputPath, file);
            const unzipper = new DecompressZip(realPath);

            if(fs.existsSync(realPath)) {
                unzipper.on('error', (err) => console.log(err));
                unzipper.on('extract', function (log) {
                    console.log('압축 해제를 완료하였습니다.');
                    fs.removeSync(realPath);
                });
                unzipper.on('progress', function (fileIndex, fileCount) {
                    console.log('압축 해제 중 : ' + (fileIndex + 1) + ' of ' + fileCount);
                });
                unzipper.extract({
                    path: path.join(outputPath),
                    filter: function (file) {
                        return file.type !== "SymbolicLink";
                    }
                });
            }

        }

    }

    start() {

        try  {

            const version = VERSION;

            if(!version) {
                throw new Error(`버전 텍스트가 없습니다.`);
            }

            const needed_files = [
                `https://dl.nwjs.io/${version}/nwjs-sdk-${version}-win-x64.zip`,
                `https://dl.nwjs.io/${version}/nwjs-${version}-win-x64.zip`,
            ]

            if(this._isAria2c) {

                needed_files.forEach(line => {
                    this.processLine(line);
                });

                let outputRaw = this._output.join("\r\n");

                fs.writeFileSync(config.inputFile, outputRaw, "utf8");

                let header = {
                    referrer : config.referrer,
                    userAgent : config.userAgent,
                    inputFile : `${config.inputFile}`,
                    logFile : `${mainPath}/${config.logFile}`,
                };

                // Create Aria2c
                let aria2cProcess = new Aria2c(header, function(err, stdout, stderr) {
                    if(err) {
                        console.log(err);
                        return;
                    }
                });

                aria2cProcess.onExit((code, signal) => {
                    console.log(`${Color.FgRed}다운로드가 완료되었습니다${Color.Reset}`);

                    this.removeFiles();
                    this.unzip();
                });

                aria2cProcess.pendingTerminate();

            } else {

                if(!fs.existsSync(outputPath)) {
                    fs.mkdirSync(outputPath);
                }

                const matched_data = needed_files.filter(i => {
                    return i.indexOf("github.com") >= 0;
                });

                if(matched_data.length > 0) {
                    throw new Error("github.com는 현재 인증서 처리의 기술적인 문제로 인해 다운로드가 불가능합니다.");
                }

                let functionTables = [];
                let counter = 0;

                needed_files.forEach(e => {
                    functionTables.push((callback) => {
                        const fileUrl = needed_files[counter];
                        const filename = needed_files[counter++].splitOnLast("/");

                        console.log(`동시 다운로드 시작 : ${fileUrl}, ${filename}`);

                        fileGet(fileUrl, path.join(outputPath, filename)).then(res => {
                            callback(null, fileUrl);
                        }).catch(err => {
                            callback(err, null);
                        });
                    });
                });

                async.parallel(functionTables, (err, results) => {
                    if(err) {
                        throw new Error(err);
                    }

                    console.log(`${Color.FgRed}다운로드가 완료되었습니다${Color.Reset}`);

                    this.unzip();
                });

            }

        } catch(e) {
            throw new Error(e);
        }

    }

}

let downloader = new Downloader();
downloader.start();

<commit_msg>missing semicolon in checkAria2c()<commit_after>/**
 * @author biud436
 * @help
 *
 * 기본적으로는 초고속으로 다운로드를 할 수 있는 Aria2c를 사용합니다.
 * node Downloader.js v0.44.1
 *
 * /f라는 명령행 옵션을 추가하면 기본 노드 API로 다운로드를 수행합니다.
 * node Downloader.js v0.44.1 /f
 *
 * Aria2c가 없으면 기본 API로 다운로드가 수행됩니다.
 */

const Aria2c = require('./Aria2c');
const fs = require('fs-extra');
const path = require('path');
const readline = require('readline');
const DecompressZip = require('decompress-zip');
const fileGet = require("./fileGet");
const async = require('async');
const {
    promisify
} = require('util');

const readdirAsync = promisify(fs.readdir);

const args = process.argv.slice(2);

const VERSION = args[0];
const option = args[1];

let mainPath = process.cwd().replace( /\\/g, '/' );
let outputPath = `${mainPath}/${VERSION}`.replace( /\\/g, '/' );

let Color = {
    Reset : "\x1b[0m",
    Bright : "\x1b[1m",
    Dim : "\x1b[2m",
    Underscore : "\x1b[4m",
    Blink : "\x1b[5m",
    Reverse : "\x1b[7m",
    Hidden : "\x1b[8m",

    FgBlack : "\x1b[30m",
    FgRed : "\x1b[31m",
    FgGreen : "\x1b[32m",
    FgYellow : "\x1b[33m",
    FgBlue : "\x1b[34m",
    FgMagenta : "\x1b[35m",
    FgCyan : "\x1b[36m",
    FgWhite : "\x1b[37m",

    BgBlack : "\x1b[40m",
    BgRed : "\x1b[41m",
    BgGreen : "\x1b[42m",
    BgYellow : "\x1b[43m",
    BgBlue : "\x1b[44m",
    BgMagenta : "\x1b[45m",
    BgCyan : "\x1b[46m",
    BgWhite : "\x1b[47m",
};

let config = {
    referrer : `https://dl.nwjs.io/`,
    userAgent : `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36`,
    inputFile : "input.txt",
    logFile : "log.txt",
};

String.prototype.splitOnLast = function (e) {
    var t = this.lastIndexOf(e) + 1;
    return 0 > t ? this : this.substr(t);
};

class Downloader {

    constructor() {
        this._output = [];
        this._isAria2c = false;

        this.checkAria2c();
    }

    processLine(line) {
        const filename = line.splitOnLast("/");
        this._output.push(line);
        this._output.push(`  dir=${outputPath}`);
        this._output.push(`  out=${filename}`);
    }

    checkAria2c() {

        if(option === "/f") {
            this._isAria2c = false;
            return;
        }

        const env = process.env["PATH"].split(";");
        const needed = env.filter(dir => dir.indexOf("aria") >= 0);
        console.log(needed);
        needed.forEach(i => {
            if(fs.existsSync(path.join(i.replace(/\\/g, "/"), "aria2c.exe"))) {
                console.log("aria2c.exe 파일을 찾았습니다.");
                this._isAria2c = true;
            }
        });
    }

    removeFiles() {
        const files = {
            input: path.join(mainPath, "input.txt").replace( /\\/g, '/' ),
            log: path.join(mainPath, "log.txt").replace( /\\/g, '/' ),
        };

        if(fs.existsSync(files.input)) fs.removeSync(files.input);
        if(fs.existsSync(files.log)) fs.removeSync(files.log);
    }

    async *readOutputFolder() {
        try {
            const dir = await readdirAsync(outputPath);
            for (const file of dir) {
                yield file;
            }
        } catch(e) {
            throw new Error(e);
        }
    }

    async unzip() {

        const files = await this.readOutputFolder();

        for await (const file of files) {
            const realPath = path.join(outputPath, file);
            const unzipper = new DecompressZip(realPath);

            if(fs.existsSync(realPath)) {
                unzipper.on('error', (err) => console.log(err));
                unzipper.on('extract', function (log) {
                    console.log('압축 해제를 완료하였습니다.');
                    fs.removeSync(realPath);
                });
                unzipper.on('progress', function (fileIndex, fileCount) {
                    console.log('압축 해제 중 : ' + (fileIndex + 1) + ' of ' + fileCount);
                });
                unzipper.extract({
                    path: path.join(outputPath),
                    filter: function (file) {
                        return file.type !== "SymbolicLink";
                    }
                });
            }

        }

    }

    start() {

        try  {

            const version = VERSION;

            if(!version) {
                throw new Error(`버전 텍스트가 없습니다.`);
            }

            const needed_files = [
                `https://dl.nwjs.io/${version}/nwjs-sdk-${version}-win-x64.zip`,
                `https://dl.nwjs.io/${version}/nwjs-${version}-win-x64.zip`,
            ]

            if(this._isAria2c) {

                needed_files.forEach(line => {
                    this.processLine(line);
                });

                let outputRaw = this._output.join("\r\n");

                fs.writeFileSync(config.inputFile, outputRaw, "utf8");

                let header = {
                    referrer : config.referrer,
                    userAgent : config.userAgent,
                    inputFile : `${config.inputFile}`,
                    logFile : `${mainPath}/${config.logFile}`,
                };

                // Create Aria2c
                let aria2cProcess = new Aria2c(header, function(err, stdout, stderr) {
                    if(err) {
                        console.log(err);
                        return;
                    }
                });

                aria2cProcess.onExit((code, signal) => {
                    console.log(`${Color.FgRed}다운로드가 완료되었습니다${Color.Reset}`);

                    this.removeFiles();
                    this.unzip();
                });

                aria2cProcess.pendingTerminate();

            } else {

                if(!fs.existsSync(outputPath)) {
                    fs.mkdirSync(outputPath);
                }

                const matched_data = needed_files.filter(i => {
                    return i.indexOf("github.com") >= 0;
                });

                if(matched_data.length > 0) {
                    throw new Error("github.com는 현재 인증서 처리의 기술적인 문제로 인해 다운로드가 불가능합니다.");
                }

                let functionTables = [];
                let counter = 0;

                needed_files.forEach(e => {
                    functionTables.push((callback) => {
                        const fileUrl = needed_files[counter];
                        const filename = needed_files[counter++].splitOnLast("/");

                        console.log(`동시 다운로드 시작 : ${fileUrl}, ${filename}`);

                        fileGet(fileUrl, path.join(outputPath, filename)).then(res => {
                            callback(null, fileUrl);
                        }).catch(err => {
                            callback(err, null);
                        });
                    });
                });

                async.parallel(functionTables, (err, results) => {
                    if(err) {
                        throw new Error(err);
                    }

                    console.log(`${Color.FgRed}다운로드가 완료되었습니다${Color.Reset}`);

                    this.unzip();
                });

            }

        } catch(e) {
            throw new Error(e);
        }

    }

}

let downloader = new Downloader();
downloader.start();

<|endoftext|>


<commit_before>'use strict';

import Sprite from './sprite';

export default class TiledMap {
	constructor(graphics, content) {
		this.graphics = graphics;
		this.content = content;
		this.sprite = new Sprite(0, 0, null);
		this.textures = {};
	}
	update(deltaTime) {
		// TODO update the animations
	}
	draw() {
		for (let layer of this.content.layers) {
			if (layer.type === 'tilelayer') {
				this.drawTileLayer(layer);
			}
		}
	}
	drawTileLayer(layer) {
		this.sprite.setColor(1.0, 1.0, 1.0, layer.opacity);
		for (let x = 0; x < layer.width; ++x) {
			for (let y = 0; y < layer.height; ++y) {
				let gid = layer.data[y * layer.width + x];
				this.drawTile(gid, x, y);
			}
		}
	}
	drawTile(gid, tileX, tileY) {
		if (gid === 0) return;

		for (let tileset of this.content.tilesets) {
			if (gid >= tileset.firstgid && gid <= tileset.firstgid + tileset.tilecount) {
				this.sprite.texture = this.textures[tileset.image];
				this.sprite.width = tileset.tilewidth;
				this.sprite.height = tileset.tileheight;
				this.sprite.setPosition(
					this.content.tilewidth * tileX,
					this.content.tileheight * tileY
				);

				let tilesetIndex = gid - tileset.firstgid;
				let tilesetX = tilesetIndex % tileset.columns;
				let tilesetY = Math.floor(tilesetIndex / tileset.columns);

				let textureX = tilesetX * tileset.tilewidth;
				let textureY = tilesetY * tileset.tileheight;
				this.sprite.setTextureCoordinates(
					textureX / tileset.imagewidth,
					textureY / tileset.imageheight,
					(textureX + tileset.tilewidth) / tileset.imagewidth,
					(textureY + tileset.tileheight) / tileset.imageheight
				);

				this.graphics.draw(this.sprite);
			}
		}
	}
	registerTexture(name, texture) {
		this.textures[name] = texture;
	}
}
<commit_msg>Add animated tiles support to TiledMap<commit_after>'use strict';

import Sprite from './sprite';

export default class TiledMap {
	constructor(graphics, content) {
		this.graphics = graphics;
		this.content = content;
		this.sprite = new Sprite(0, 0, null);
		this.textures = {};
		this.animationTime = 0;
	}
	update(deltaTime) {
		this.animationTime += deltaTime * 1000;
	}
	draw() {
		for (let layer of this.content.layers) {
			if (layer.type === 'tilelayer') {
				this.drawTileLayer(layer);
			}
		}
	}
	drawTileLayer(layer) {
		this.sprite.setColor(1.0, 1.0, 1.0, layer.opacity);
		for (let x = 0; x < layer.width; ++x) {
			for (let y = 0; y < layer.height; ++y) {
				let gid = layer.data[y * layer.width + x];
				this.drawTile(gid, x, y);
			}
		}
	}
	drawTile(gid, tileX, tileY) {
		if (gid === 0) return;

		for (let tileset of this.content.tilesets) {
			if (gid >= tileset.firstgid && gid <= tileset.firstgid + tileset.tilecount) {
				this.sprite.texture = this.textures[tileset.image];
				this.sprite.width = tileset.tilewidth;
				this.sprite.height = tileset.tileheight;
				this.sprite.setPosition(
					this.content.tilewidth * tileX,
					this.content.tileheight * tileY
				);

				let tileId = this.getEffectiveTileId(tileset, gid);
				let tilesetX = tileId % tileset.columns;
				let tilesetY = Math.floor(tileId / tileset.columns);

				let textureX = tilesetX * tileset.tilewidth;
				let textureY = tilesetY * tileset.tileheight;
				this.sprite.setTextureCoordinates(
					textureX / tileset.imagewidth,
					textureY / tileset.imageheight,
					(textureX + tileset.tilewidth) / tileset.imagewidth,
					(textureY + tileset.tileheight) / tileset.imageheight
				);

				this.graphics.draw(this.sprite);
			}
		}
	}
	getEffectiveTileId(tileset, gid) {
		let tileId = gid - tileset.firstgid;
		if (tileset.tiles) {
			let tiledata = tileset.tiles[tileId];
			if (tiledata) {
				let animation = tiledata.animation;
				if (animation) {
					let totalTime = 0;
					for (let frame of animation) {
						totalTime += frame.duration;
					}
					let currentTime = Math.floor(this.animationTime) % totalTime;
					totalTime = 0;
					for (let frame of animation) {
						totalTime += frame.duration;
						if (totalTime >= currentTime) {
							return frame.tileid;
						}
					}
				}
			}
		}
		return tileId;
	}
	registerTexture(name, texture) {
		this.textures[name] = texture;
	}
}
<|endoftext|>


<commit_before>import React from 'react';

/* eslint-disable camelcase */
export const hearingTypeContent = {
  virtual_hearing: (
    <>
      A tele-hearing online

        You can attend your hearing on a computer, mobile phone, or tablet from
        a location you choose. You just need to be somewhere that has a Wi-Fi
        connection. Your accredited representative can be with you or in a
        separate location. The Veterans Law Judge will be located in a separate
        location.

    </>
  ),

  video_conference: (
    <>

        A Regional Office hearing at a VA Regional Office near you

        You and your accredited representative can attend your hearing by video
        at a VA regional office near you. The Veterans Law Judge will be located
        in a separate location.

    </>
  ),

  central_office: (
    <>
      An in-person hearing at the Board in Washington, D.C.

        You can attend an in-person hearing with a Veterans Law Judge.

    </>
  ),
};

export const missingHearingTypeErrorMessage = 'Please choose a conference type';
<commit_msg>Add virtual prefix (#20846)<commit_after>import React from 'react';

/* eslint-disable camelcase */
export const hearingTypeContent = {
  virtual_hearing: (
    <>
      A virtual tele-hearing online

        You can attend your hearing on a computer, mobile phone, or tablet from
        a location you choose. You just need to be somewhere that has a Wi-Fi
        connection. Your accredited representative can be with you or in a
        separate location. The Veterans Law Judge will be located in a separate
        location.

    </>
  ),

  video_conference: (
    <>

        A Regional Office hearing at a VA Regional Office near you

        You and your accredited representative can attend your hearing by video
        at a VA regional office near you. The Veterans Law Judge will be located
        in a separate location.

    </>
  ),

  central_office: (
    <>
      An in-person hearing at the Board in Washington, D.C.

        You can attend an in-person hearing with a Veterans Law Judge.

    </>
  ),
};

export const missingHearingTypeErrorMessage = 'Please choose a conference type';
<|endoftext|>


<commit_before>// Wrapper for the leaflet.js map control with methods
// to manage the map layers.
function createMapControl(elementName) {
    'use strict';

    var map = L.map(elementName);

    var mapQuestAttribution = ' | Tiles Courtesy of MapQuest ';
    var mapLayers = {
        openStreetMap: L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpg', {
            attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA' +
                         mapQuestAttribution,
            maxZoom: 18
        }),

        photo: L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg', {
            attribution: 'Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency' +
                         mapQuestAttribution,
            maxZoom: 11
        })
    };

    var layersControl = L.control.layers({
        'MapQuest OpenStreetMap': mapLayers.openStreetMap,
        'MapQuest Open Aerial (Photo)': mapLayers.photo
    });

    mapLayers.openStreetMap.addTo(map);
            layersControl.addTo(map);

    return {
        reset: function () {
            // Clear any existing track data so that a new file can be loaded.
            if (mapLayers.track) {
                map.removeLayer(mapLayers.track);
                layersControl.removeLayer(mapLayers.track);
            }

            if (mapLayers.task) {
                map.removeLayer(mapLayers.task);
                layersControl.removeLayer(mapLayers.task);
            }
        },

        addTrack: function (latLong) {
            var trackLine = L.polyline(latLong, { color: 'red' });
            mapLayers.track = L.layerGroup([
                trackLine,
                L.marker(latLong[0]).bindPopup('Takeoff'),
                L.marker(latLong[latLong.length - 1]).bindPopup('Landing')
            ]).addTo(map);
            layersControl.addOverlay(mapLayers.track, 'Flight path');

            map.fitBounds(trackLine.getBounds());
        },

        addTask: function (coordinates, names) {
            //Clearer if we don't show track to and from start line and finish line, as we are going to show lines
            var taskLayers = [L.polyline(coordinates, { color: 'blue' })];
             var taskDrawOptions = {
               color: 'green',
               weight: 3,
               opacity: 0.8
             };
             //definitions from BGA rules
             //defined here as any future changes will be easier
             var startLineRadius= 5;
             var finishLineRadius= 1;
             var tpCircleRadius= 500;
             var tpSectorRadius= 20000;
             var tpSectorAngle = 90;
            var j;
            for (j = 0; j  < coordinates.length; j++) {
                taskLayers.push(L.marker(coordinates[j]).bindPopup(names[j]));
                 switch(j)   {
                    case 0:
                         var startline=this.getline(coordinates[0],coordinates[1],startLineRadius,taskDrawOptions);
                        taskLayers.push(startline);
                        break;
                    case (coordinates.length-1):
                       var finishline= this.getline(coordinates[j], coordinates[j-1], finishLineRadius,taskDrawOptions);
                        taskLayers.push(finishline);
                        break;
                    default:
                        taskLayers.push(L.circle(coordinates[j], tpCircleRadius, taskDrawOptions));
                         var tpsector=this.getTpSector(coordinates[j], coordinates[j-1],coordinates[j+1],tpSectorRadius,tpSectorAngle,taskDrawOptions);
                        taskLayers.push(tpsector);
                }
            }
            mapLayers.task = L.layerGroup(taskLayers).addTo(map);
            layersControl.addOverlay(mapLayers.task, 'Task');
        },

    getline: function(pt1,pt2,linerad,drawOptions) {
      //returns line through pt1, at right angles to line between pt1 and pt2, length linerad.
     //Use Pythogoras- accurate enough on this scale
      var latdiff=pt2[0] - pt1[0];
      //need radians for cosine function
      var northmean=(pt1[0] + pt2[0]) *Math.PI / 360;
      var startrads=pt1[0]*Math.PI/180;
     var longdiff=(pt1[1] - pt2[1])  * Math.cos( northmean);
     var hypotenuse = Math.sqrt(latdiff*latdiff + longdiff * longdiff);
     //assume earth is a sphere circumference 40030 Km
     var latdelta= linerad * longdiff / hypotenuse / 111.1949269;
     var longdelta = linerad * latdiff / hypotenuse /111.1949269/Math.cos(startrads);
    var linestart = new L.LatLng(pt1[0] - latdelta,pt1[1] - longdelta);
    var lineend= new L.LatLng(pt1[0] + latdelta, longdelta + pt1[1]);
    var polylinePoints = [linestart,lineend];
         var polylineOptions = {
               color: 'green',
               weight: 3,
               opacity: 0.8
             };

     return new  L.Polyline(polylinePoints,drawOptions);
},

getTpSector: function(centrept,pt1,pt2,sectorRadius,sectorAngle,drawOptions)  {
    var headingIn= getBearing(pt1,centrept);
    var bearingOut= getBearing(pt2,centrept);
    var bisector= headingIn + (bearingOut-headingIn)/2;
    if(Math.abs(bearingOut-headingIn) > 180)  {
        bisector = (bisector + 180) % 360;
    }
   var beginangle= bisector -sectorAngle/2;
    if (beginangle < 0) {
       beginangle += 360;
    }
   var endangle=(bisector + sectorAngle/2) % 360;
   var sectorOptions= jQuery.extend({},drawOptions,{startAngle:beginangle,stopAngle:endangle});
   return L.circle(centrept,sectorRadius,sectorOptions);

}

    };
}

function getBearing(pt1,pt2)    {
    //get bearing from pt1 to pt2 in degrees
    //need radians for cosine function
      //Use Pythogoras
      var northmean=(pt1[0] + pt2[0]) *Math.PI / 360;
     var longdiff=(pt2[1] - pt1[1])  * Math.cos( northmean);
     var latdiff= pt2[0]-pt1[0];
     return (Math.atan2(longdiff,latdiff) *180/Math.PI +360) % 360;
}

<commit_msg>Use more accurate formula to calculate bearings.<commit_after>// Wrapper for the leaflet.js map control with methods
// to manage the map layers.
function createMapControl(elementName) {
    'use strict';

    var map = L.map(elementName);

    var mapQuestAttribution = ' | Tiles Courtesy of MapQuest ';
    var mapLayers = {
        openStreetMap: L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpg', {
            attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA' +
                         mapQuestAttribution,
            maxZoom: 18
        }),

        photo: L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg', {
            attribution: 'Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency' +
                         mapQuestAttribution,
            maxZoom: 11
        })
    };

    var layersControl = L.control.layers({
        'MapQuest OpenStreetMap': mapLayers.openStreetMap,
        'MapQuest Open Aerial (Photo)': mapLayers.photo
    });

    mapLayers.openStreetMap.addTo(map);
            layersControl.addTo(map);

    return {
        reset: function () {
            // Clear any existing track data so that a new file can be loaded.
            if (mapLayers.track) {
                map.removeLayer(mapLayers.track);
                layersControl.removeLayer(mapLayers.track);
            }

            if (mapLayers.task) {
                map.removeLayer(mapLayers.task);
                layersControl.removeLayer(mapLayers.task);
            }
        },

        addTrack: function (latLong) {
            var trackLine = L.polyline(latLong, { color: 'red' });
            mapLayers.track = L.layerGroup([
                trackLine,
                L.marker(latLong[0]).bindPopup('Takeoff'),
                L.marker(latLong[latLong.length - 1]).bindPopup('Landing')
            ]).addTo(map);
            layersControl.addOverlay(mapLayers.track, 'Flight path');

            map.fitBounds(trackLine.getBounds());
        },

        addTask: function (coordinates, names) {
            //Clearer if we don't show track to and from start line and finish line, as we are going to show lines
            var taskLayers = [L.polyline(coordinates, { color: 'blue' })];
             var taskDrawOptions = {
               color: 'green',
               weight: 3,
               opacity: 0.8
             };
             //definitions from BGA rules
             //defined here as any future changes will be easier
             var startLineRadius= 5;
             var finishLineRadius= 1;
             var tpCircleRadius= 500;
             var tpSectorRadius= 20000;
             var tpSectorAngle = 90;
            var j;
            for (j = 0; j  < coordinates.length; j++) {
                taskLayers.push(L.marker(coordinates[j]).bindPopup(names[j]));
                 switch(j)   {
                    case 0:
                         var startline=this.getline(coordinates[0],coordinates[1],startLineRadius,taskDrawOptions);
                        taskLayers.push(startline);
                        break;
                    case (coordinates.length-1):
                       var finishline= this.getline(coordinates[j], coordinates[j-1], finishLineRadius,taskDrawOptions);
                        taskLayers.push(finishline);
                        break;
                    default:
                        taskLayers.push(L.circle(coordinates[j], tpCircleRadius, taskDrawOptions));
                         var tpsector=this.getTpSector(coordinates[j], coordinates[j-1],coordinates[j+1],tpSectorRadius,tpSectorAngle,taskDrawOptions);
                        taskLayers.push(tpsector);
                }
            }
            mapLayers.task = L.layerGroup(taskLayers).addTo(map);
            layersControl.addOverlay(mapLayers.task, 'Task');
        },

    getline: function(pt1,pt2,linerad,drawOptions) {
      //returns line through pt1, at right angles to line between pt1 and pt2, length linerad.
     //Use Pythogoras- accurate enough on this scale
      var latdiff=pt2[0] - pt1[0];
      //need radians for cosine function
      var northmean=(pt1[0] + pt2[0]) *Math.PI / 360;
      var startrads=pt1[0]*Math.PI/180;
     var longdiff=(pt1[1] - pt2[1])  * Math.cos( northmean);
     var hypotenuse = Math.sqrt(latdiff*latdiff + longdiff * longdiff);
     //assume earth is a sphere circumference 40030 Km
     var latdelta= linerad * longdiff / hypotenuse / 111.1949269;
     var longdelta = linerad * latdiff / hypotenuse /111.1949269/Math.cos(startrads);
    var linestart = new L.LatLng(pt1[0] - latdelta,pt1[1] - longdelta);
    var lineend= new L.LatLng(pt1[0] + latdelta, longdelta + pt1[1]);
    var polylinePoints = [linestart,lineend];
         var polylineOptions = {
               color: 'green',
               weight: 3,
               opacity: 0.8
             };

     return new  L.Polyline(polylinePoints,drawOptions);
},

getTpSector: function(centrept,pt1,pt2,sectorRadius,sectorAngle,drawOptions)  {
    var headingIn= getBearing(pt1,centrept);
    var bearingOut= getBearing(pt2,centrept);
    var bisector= headingIn + (bearingOut-headingIn)/2;
    if(Math.abs(bearingOut-headingIn) > 180)  {
        bisector = (bisector + 180) % 360;
    }
   var beginangle= bisector -sectorAngle/2;
    if (beginangle < 0) {
       beginangle += 360;
    }
   var endangle=(bisector + sectorAngle/2) % 360;
   var sectorOptions= jQuery.extend({},drawOptions,{startAngle:beginangle,stopAngle:endangle});
   return L.circle(centrept,sectorRadius,sectorOptions);

}

    };
}

function getBearing(pt1,pt2)    {
    // Get bearing from pt1 to pt2 in degrees
    // Formula from: http://www.movable-type.co.uk/scripts/latlong.html
    // Start by converting to radians.
    var degToRad = Math.PI / 180.0;
    var lat1 = pt1[0] * degToRad;
    var lon1 = pt1[1] * degToRad;
    var lat2 = pt2[0] * degToRad;
    var lon2 = pt2[1] * degToRad;

    var y = Math.sin(lon2 - lon1) * Math.cos(lat2);
    var x = Math.cos(lat1) * Math.sin(lat2) -
        Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);

    var bearing = Math.atan2(y, x) / degToRad;
    bearing = (bearing + 360.0) % 360.0;
    return bearing;
}

<|endoftext|>


<commit_before>window.LightningQuery = (function () {
    if (window.LightningQuery)
        return window.LightningQuery;

    var $this = {};

    var _query = null;
    var _queryTask = null;
    var _timeExtent = null;
    var _geometryService = null;
    var _bufferParameters = null;
    var _unwrapFunctions = [];

    function init(urlUtils, query, queryTask, timeExtent, geometryService, bufferParameters) {
        urlUtils.addProxyRule({
            proxyUrl: "http://pq/arcgisproxynew/proxy.ashx",
            urlPrefix: "https://gis.tva.gov/arcgis/rest/services/"
        });

        _query = query;
        _queryTask = queryTask;
        _timeExtent = timeExtent;
        _geometryService = geometryService;
        _bufferParameters = bufferParameters;

        for (var i = 0; i < _unwrapFunctions.length; i++)
            _unwrapFunctions[i]();
    }

    require(["esri/urlUtils", "esri/tasks/query", "esri/tasks/QueryTask", "esri/TimeExtent", "esri/tasks/GeometryService", "esri/tasks/BufferParameters"], init);

    function exportFunction(key, apiFunction) {
        var pendingCalls = [];

        $this[key] = function () {
            pendingCalls.push(arguments);
        };

        _unwrapFunctions.push(function () {
            $this[key] = apiFunction;

            for (var i = 0; i < pendingCalls.length; i++)
                apiFunction(pendingCalls[i]);
        });
    }

    exportFunction("queryLineGeometry", function (lineKey, callback) {
        var lineQueryTask = new _queryTask("https://gis.tva.gov/arcgis/rest/services/EGIS_Transmission/Transmission_Grid_Restricted_2/MapServer/6");

        var lineQuery = new _query();
        lineQuery.returnGeometry = true;
        lineQuery.outFields = ["LINENAME"];
        lineQuery.where = "UPPER(LINENAME) like '%" + lineKey.toUpperCase() + "%'";

        lineQueryTask.execute(query, function (results) {
            var totalLine = results.features.map(function (feature) { return feature.geometry; });
            callback(totalLine);
        });
    });

    exportFunction("queryLineBufferGeometry", function (lineGeometry, callback) {
        var geometryService = new _geometryService("https://gis.tva.gov/arcgis/rest/services/Utilities/Geometry/GeometryServer");

        var bufferParameters = new _bufferParameters();
        bufferParameters.geometries = lineGeometry;
        bufferParameters.unionResults = true;
        bufferParameters.distances = [0.5];
        bufferParameters.unit = _geometryService.UNIT_STATUTE_MILE;

        geometryService.buffer(bufferParameters, function (geometries) {
            callback(geometries[0]);
        });
    });

    exportFunction("queryLightningData", function (lineBufferGeometry, startTime, endTime, callback) {
        var lightningQueryTask = new _queryTask("https://gis.tva.gov/arcgis/rest/services/EGIS/LightningQuery/MapServer/0");
        var timeExtent = new _timeExtent(startTime, endTime);

        var lightningQuery = new _query();
        //lightningQuery.returnGeometry = true;
        lightningQuery.outFields = ["DISPLAYTIME", "LATITUDE", "LONGITUDE", "AMPLITUDE"];
        lightningQuery.timeExtent = timeExtent;
        lightningQuery.geometry = lineBufferGeometry;
        lightningQuery.spatialrelationship = _query.SPATIAL_REL_INTERSECTS;

        lightningQueryTask.execute(lightningQuery, function (results) {
            var lightningData = results.features.map(function (feature) { return feature.attributes; });
            callback(lightningData);
        });
    });

    return $this;
})();<commit_msg>Fixed JavaScript variable reference in lightning API call to query line data.<commit_after>window.LightningQuery = (function () {
    if (window.LightningQuery)
        return window.LightningQuery;

    var $this = {};

    var _query = null;
    var _queryTask = null;
    var _timeExtent = null;
    var _geometryService = null;
    var _bufferParameters = null;
    var _unwrapFunctions = [];

    function init(urlUtils, query, queryTask, timeExtent, geometryService, bufferParameters) {
        urlUtils.addProxyRule({
            proxyUrl: "http://pq/arcgisproxynew/proxy.ashx",
            urlPrefix: "https://gis.tva.gov/arcgis/rest/services/"
        });

        _query = query;
        _queryTask = queryTask;
        _timeExtent = timeExtent;
        _geometryService = geometryService;
        _bufferParameters = bufferParameters;

        for (var i = 0; i < _unwrapFunctions.length; i++)
            _unwrapFunctions[i]();
    }

    require(["esri/urlUtils", "esri/tasks/query", "esri/tasks/QueryTask", "esri/TimeExtent", "esri/tasks/GeometryService", "esri/tasks/BufferParameters"], init);

    function exportFunction(key, apiFunction) {
        var pendingCalls = [];

        $this[key] = function () {
            pendingCalls.push(arguments);
        };

        _unwrapFunctions.push(function () {
            $this[key] = apiFunction;

            for (var i = 0; i < pendingCalls.length; i++)
                apiFunction(pendingCalls[i]);
        });
    }

    exportFunction("queryLineGeometry", function (lineKey, callback) {
        var lineQueryTask = new _queryTask("https://gis.tva.gov/arcgis/rest/services/EGIS_Transmission/Transmission_Grid_Restricted_2/MapServer/6");

        var lineQuery = new _query();
        lineQuery.returnGeometry = true;
        lineQuery.outFields = ["LINENAME"];
        lineQuery.where = "UPPER(LINENAME) like '%" + lineKey.toUpperCase() + "%'";

        lineQueryTask.execute(lineQuery, function (results) {
            var totalLine = results.features.map(function (feature) { return feature.geometry; });
            callback(totalLine);
        });
    });

    exportFunction("queryLineBufferGeometry", function (lineGeometry, callback) {
        var geometryService = new _geometryService("https://gis.tva.gov/arcgis/rest/services/Utilities/Geometry/GeometryServer");

        var bufferParameters = new _bufferParameters();
        bufferParameters.geometries = lineGeometry;
        bufferParameters.unionResults = true;
        bufferParameters.distances = [0.5];
        bufferParameters.unit = _geometryService.UNIT_STATUTE_MILE;

        geometryService.buffer(bufferParameters, function (geometries) {
            callback(geometries[0]);
        });
    });

    exportFunction("queryLightningData", function (lineBufferGeometry, startTime, endTime, callback) {
        var lightningQueryTask = new _queryTask("https://gis.tva.gov/arcgis/rest/services/EGIS/LightningQuery/MapServer/0");
        var timeExtent = new _timeExtent(startTime, endTime);

        var lightningQuery = new _query();
        //lightningQuery.returnGeometry = true;
        lightningQuery.outFields = ["DISPLAYTIME", "LATITUDE", "LONGITUDE", "AMPLITUDE"];
        lightningQuery.timeExtent = timeExtent;
        lightningQuery.geometry = lineBufferGeometry;
        lightningQuery.spatialrelationship = _query.SPATIAL_REL_INTERSECTS;

        lightningQueryTask.execute(lightningQuery, function (results) {
            var lightningData = results.features.map(function (feature) { return feature.attributes; });
            callback(lightningData);
        });
    });

    return $this;
})();<|endoftext|>


<commit_before>/**
 * FastPriorityQueue.js : a fast heap-based priority queue  in JavaScript.
 * (c) the authors
 * Licensed under the Apache License, Version 2.0.
 *
 * Speed-optimized heap-based priority queue for modern browsers and JavaScript engines.
 *
 * Usage :
         Installation (in shell, if you use node):
         $ npm install fastpriorityqueue

         Running test program (in JavaScript):

         // var FastPriorityQueue = require("fastpriorityqueue");// in node
         var x = new FastPriorityQueue();
         x.add(1);
         x.add(0);
         x.add(5);
         x.add(4);
         x.add(3);
         x.peek(); // should return 0, leaves x unchanged
         x.size; // should return 5, leaves x unchanged
         while(!x.isEmpty()) {
           console.log(x.poll());
         } // will print 0 1 3 4 5
         x.trim(); // (optional) optimizes memory usage
 */
'use strict';

var defaultcomparator = function(a, b) {
    return a < b;
};

// the provided comparator function should take a, b and return *true* when a < b
function FastPriorityQueue(comparator) {
    this.array = [];
    this.size = 0;
    this.compare =  comparator || defaultcomparator;
}

// Add an element the the queue
// runs in O(log n) time
FastPriorityQueue.prototype.add = function(myval) {
    var i = this.size;
    this.array[this.size++] = myval;
    while ( i > 0) {
        var p = (i - 1) >> 1;
        var ap = this.array[p];
        if(!this.compare(myval, ap )) break;
        this.array[i] = ap;
        i = p;
    }
    this.array[i] = myval;
};

// replace the content of the heap by provided array and "heapifies it"
FastPriorityQueue.prototype.heapify = function(arr) {
    this.array = arr;
    this.size = arr.length;
    for (var i = (this.size >> 1); i >= 0; i--) {
        this._percolateDown(i);
    }
};

// for internal use
FastPriorityQueue.prototype._percolateUp = function(i) {
    var myval = this.array[i];
    while ( i > 0) {
        var p = (i - 1) >> 1;
        var ap = this.array[p];
        if(!this.compare(myval, ap )) break;
        this.array[i] = ap;
        i = p;
    }
    this.array[i] = myval;
};

// for internal use
FastPriorityQueue.prototype._percolateDown = function(i) {
    var size = this.size;
    var hsize = this.size >>> 1;
    var ai = this.array[i];
    while (i < hsize) {
        var l = (i << 1) + 1;
        var r = l + 1;
        var bestc = this.array[l];
        if (r < size) {
            if (this.compare(this.array[r], bestc)) {
                l = r;
                bestc = this.array[r];
            }
        }
        if (!this.compare(bestc,ai)) {
          break;
        }
        this.array[i] = bestc;
        i = l;
    }
    this.array[i] = ai;
};

// Look at the top of the queue (a smallest element)
// executes in constant time
//
// This function assumes that the priority queue is
// not empty and the caller is resposible for the check.
// You can use an expression such as
// "isEmpty() ? undefined : peek()"
// if you expect to be calling peek on an empty priority queue.
//
FastPriorityQueue.prototype.peek = function(t) {
    return this.array[0];
};

// remove the element on top of the heap (a smallest element)
// runs in logarithmic time
//
//
// This function assumes that the priority queue is
// not empty, and the caller is responsible for the check.
// You can use an expression such as
// "isEmpty() ? undefined : poll()"
// if you expect to be calling poll on an empty priority queue.
//
// For long-running and large priority queues, or priority queues
// storing large objects, you may  want to call the trim function
// at strategic times to recover allocated memory.
FastPriorityQueue.prototype.poll = function(i) {
    var ans = this.array[0];
    if(this.size>1) {
        this.array[0] = this.array[--this.size];
        this._percolateDown(0 | 0);
    } else --this.size;
    return ans;
};

// recover unused memory (for long-running priority queues)
FastPriorityQueue.prototype.trim = function() {
    this.array = this.array.slice(0,this.size);
};

// Check whether the heap is empty
FastPriorityQueue.prototype.isEmpty = function(i) {
    return this.size == 0;
};

// just for illustration purposes
var main = function() {
    // main code
    var x = new FastPriorityQueue(function(a, b) {
        return a < b;
    });
    x.add(1);
    x.add(0);
    x.add(5);
    x.add(4);
    x.add(3);
    while (!x.isEmpty()) {
        console.log(x.poll());
    }
};

if (require.main === module) {
    main();
}

module.exports = FastPriorityQueue;
<commit_msg>Minor reformatting.<commit_after>/**
 * FastPriorityQueue.js : a fast heap-based priority queue  in JavaScript.
 * (c) the authors
 * Licensed under the Apache License, Version 2.0.
 *
 * Speed-optimized heap-based priority queue for modern browsers and JavaScript engines.
 *
 * Usage :
         Installation (in shell, if you use node):
         $ npm install fastpriorityqueue

         Running test program (in JavaScript):

         // var FastPriorityQueue = require("fastpriorityqueue");// in node
         var x = new FastPriorityQueue();
         x.add(1);
         x.add(0);
         x.add(5);
         x.add(4);
         x.add(3);
         x.peek(); // should return 0, leaves x unchanged
         x.size; // should return 5, leaves x unchanged
         while(!x.isEmpty()) {
           console.log(x.poll());
         } // will print 0 1 3 4 5
         x.trim(); // (optional) optimizes memory usage
 */
"use strict";

var defaultcomparator = function (a, b) {
    return a < b;
};

// the provided comparator function should take a, b and return *true* when a < b
function FastPriorityQueue(comparator) {
    this.array = [];
    this.size = 0;
    this.compare = comparator || defaultcomparator;
}

// Add an element the the queue
// runs in O(log n) time
FastPriorityQueue.prototype.add = function (myval) {
    var i = this.size;
    this.array[this.size] = myval;
    this.size += 1;
    var p;
    var ap;
    while (i > 0) {
        p = (i - 1) >> 1;
        ap = this.array[p];
        if (!this.compare(myval, ap)) {
             break;
        }
        this.array[i] = ap;
        i = p;
    }
    this.array[i] = myval;
};

// replace the content of the heap by provided array and "heapifies it"
FastPriorityQueue.prototype.heapify = function (arr) {
    this.array = arr;
    this.size = arr.length;
    var i;
    for (i = (this.size >> 1); i >= 0; i--) {
        this._percolateDown(i);
    }
};

// for internal use
FastPriorityQueue.prototype._percolateUp = function (i) {
    var myval = this.array[i];
    var p;
    var ap;
    while (i > 0) {
        p = (i - 1) >> 1;
        ap = this.array[p];
        if (!this.compare(myval, ap)) {
            break;
        }
        this.array[i] = ap;
        i = p;
    }
    this.array[i] = myval;
};

// for internal use
FastPriorityQueue.prototype._percolateDown = function (i) {
    var size = this.size;
    var hsize = this.size >>> 1;
    var ai = this.array[i];
    var l;
    var r;
    var bestc;
    while (i < hsize) {
        l = (i << 1) + 1;
        r = l + 1;
        bestc = this.array[l];
        if (r < size) {
            if (this.compare(this.array[r], bestc)) {
                l = r;
                bestc = this.array[r];
            }
        }
        if (!this.compare(bestc, ai)) {
            break;
        }
        this.array[i] = bestc;
        i = l;
    }
    this.array[i] = ai;
};

// Look at the top of the queue (a smallest element)
// executes in constant time
//
// This function assumes that the priority queue is
// not empty and the caller is resposible for the check.
// You can use an expression such as
// "isEmpty() ? undefined : peek()"
// if you expect to be calling peek on an empty priority queue.
//
FastPriorityQueue.prototype.peek = function () {
    return this.array[0];
};

// remove the element on top of the heap (a smallest element)
// runs in logarithmic time
//
//
// This function assumes that the priority queue is
// not empty, and the caller is responsible for the check.
// You can use an expression such as
// "isEmpty() ? undefined : poll()"
// if you expect to be calling poll on an empty priority queue.
//
// For long-running and large priority queues, or priority queues
// storing large objects, you may  want to call the trim function
// at strategic times to recover allocated memory.
FastPriorityQueue.prototype.poll = function () {
    var ans = this.array[0];
    if (this.size > 1) {
        this.array[0] = this.array[--this.size];
        this._percolateDown(0 | 0);
    } else {
        this.size -= 1;
    }
    return ans;
};

// recover unused memory (for long-running priority queues)
FastPriorityQueue.prototype.trim = function () {
    this.array = this.array.slice(0, this.size);
};

// Check whether the heap is empty
FastPriorityQueue.prototype.isEmpty = function () {
    return this.size === 0;
};

// just for illustration purposes
var main = function () {
    // main code
    var x = new FastPriorityQueue(function (a, b) {
        return a < b;
    });
    x.add(1);
    x.add(0);
    x.add(5);
    x.add(4);
    x.add(3);
    while (!x.isEmpty()) {
        console.log(x.poll());
    }
};

if (require.main === module) {
    main();
}

module.exports = FastPriorityQueue;
<|endoftext|>


<commit_before>$(function(){
	var toggle_dropdown = function (e) {
		var $this = $(this),
			dropdown_parent = $this.parent();
			dropdown_target = dropdown_parent.children('[data-dropdown-target]');
		if($this.data('open')){
			dropdown_target.hide()
			dropdown_parent.removeClass('open')
			$this.data('open', false)
		}else{
			dropdown_target.show()
			dropdown_parent.addClass('open')
			$this.data('open', true)
		}
		e.preventDefault()
	};
	$('[data-dropdown] > a').on('click', toggle_dropdown);
})<commit_msg>Better dropdown behavior.<commit_after>$(function(){
	var toggle_dropdown = function (e) {
			var $this = $(this),
				dropdown_parent = $this.parent();
				dropdown_target = dropdown_parent.children('[data-dropdown-target]');
			if($this.attr('data-dropdown-open')==='true'){
				dropdown_target.hide()
				dropdown_parent.removeClass('open')
				$this.attr('data-dropdown-open', 'false')
			}else{
				dropdown_target.show()
				dropdown_parent.addClass('open')
				$this.attr('data-dropdown-open', 'true')
			}
			e.preventDefault();
			e.stopPropagation();
		},
		close_dropdowns = function (e){
			$('[data-dropdown-open="true"]').click()
		};
	$(document.body).click(close_dropdowns)
	$('[data-dropdown] > a').on('click', toggle_dropdown);
})<|endoftext|>


<commit_before>const extend = require('extend');

const uniq = require('./lib/uniq');
const parseOptions = require('./lib/parse_options');
const extract = require('./lib/extract');

function Request(opts) {
  extend(this, parseOptions(opts));
}

Request.prototype.filters = function (request) {
  return extract({
    context: request,
    contextKeysToSearch: this.requestKeysToSearch,
    // named params in the route are automatically included with the
    // user-supplied list of valid params. given a route /resource/:id
    // the param 'id' will be considered valid even if it isn't listed
    // in the paramsForfilters property.
    find: this.allowedFilters.concat(Object.keys(request.params)),
    normalizer: this.paramNormalizer
  });
};

Request.prototype.relations = function (request) {
  var result = extract({
    context: request,
    contextKeysToSearch: this.requestKeysToSearch,
    find: this.relationKey,
    normalizer: this.paramNormalizer
  }) || [];
  if (result && !Array.isArray(result)) {
    result = [result];
  }
  return uniq(result);
};

Request.prototype.responder = function (response, code, data) {
  // cheap heuristics to detect the server type
  var isExpress = !!response.send;
  var isHapi = !!response.request;
  if (!isExpress && !isHapi) {
    throw new Error('Unsupported server type!');
  }

  var prettyPrint = JSON.stringify(data, null, 2);
  var contentType = 'application/json';

  // both of these should never happen, right?
  if (isExpress) {
    response.set('content-type', contentType).status(code).send(prettyPrint);
  }
  if (isHapi) {
    response(prettyPrint).type(contentType).code(code);
  }
};

Request.prototype.create = function (opts) {
  if (!opts) {
    opts = {};
  }
  var method = opts.method || 'create';
  var responder = this.responder;
  var source = this.source;

  return function (request, response) {
    source.create(method, request.body, function (err, data) {
      var code = 201;
      if (err) {
        code = 422;
        data = {
          errors: {
            title: 'Unprocessable Entity',
            detail: err.message
          }
        };
      }
      responder(response, code, data);
    });
  };
};

Request.prototype.read = function (opts) {
  if (!opts) {
    opts = {};
  }
  var format = this.format.bind(this);
  var responder = this.responder;
  var getFilters = this.filters.bind(this);
  var getRelations = this.relations.bind(this);
  var source = this.source;
  var include = opts.include||[];
  var passMode = !!opts.pass;
  var rawMode = !!opts.raw;
  return function (request, response, next) {
    var filters = getFilters(request);
    var relations = getRelations(request).concat(include);
    source.read(filters, relations, opts, function (err, data) {
      var code = 200;
      if (err) {
        code = 400;
        data = {
          errors: {
            title: 'Bad Request',
            detail: err.message
          }
        };
      }
      if (!rawMode) {
        data = format(data, opts);
      }
      if (passMode) {
        response.data = data;
        response.code = code;
        next();
      } else {
        responder(response, code, data);
      }
    });
  };
};

Request.prototype.update = function (opts) {
  if (!opts) {
    opts = {};
  }
  var responder = this.responder;
  var source = this.source;

  return function (request, response) {
    source.byId(request.param('id'), function (err, model) {
      if (!model) {
        responder(response, 500, {
          title: 'Internal Server Error',
          detail: 'No resource by that id found.'
        });
      } else {
        source.update(model, request.body, function (err, data) {
          var code = 200;
          if (err) {
            code = 422;
            data = {
              title: 'Unprocessable Entity',
              detail: err.message
            };
          }
          responder(response, code, data);
        });
      }
    });
  };
};

Request.prototype.destroy = function (opts) {
  if (!opts) {
    opts = {};
  }
  var responder = this.responder;
  var source = this.source;

  return function (request, response) {
    source.byId(request.param('id'), function (err, model) {
      if (!model) {
        responder(response, 500, {
          title: 'Internal Server Error',
          detail: 'No resource by that id found.'
        });
      } else {
        source.destroy(model, function (err, data) {
          var code = 200;
          if (err) {
            code = 422;
            data = {
              title: 'Unprocessable Entity',
              detail: err.message
            };
          }
          responder(response, code, data);
        });
      }
    });
  };
};

Request.prototype.format = function (data, opts) {
  if (!opts) {
    opts = {};
  }
  var singleResource = !!opts.one;
  var primaryResourceName = this.source.resourceName();
  var primaryResource = data[primaryResourceName];
  var hasLinks = (Object.keys(data).length > 1);
  var output = {};
  if (hasLinks) {
    output.linked = data;
  }
  if (singleResource) {
    output[primaryResourceName] = primaryResource[0];
  } else {
    output[primaryResourceName] = primaryResource;
  }

  delete data[primaryResourceName];
  return output;
};

module.exports = Request;
<commit_msg>remove formatting entirely<commit_after>const extend = require('extend');

const uniq = require('./lib/uniq');
const parseOptions = require('./lib/parse_options');
const extract = require('./lib/extract');

function Request(opts) {
  extend(this, parseOptions(opts));
}

Request.prototype.filters = function (request) {
  return extract({
    context: request,
    contextKeysToSearch: this.requestKeysToSearch,
    // named params in the route are automatically included with the
    // user-supplied list of valid params. given a route /resource/:id
    // the param 'id' will be considered valid even if it isn't listed
    // in the paramsForfilters property.
    find: this.allowedFilters.concat(Object.keys(request.params)),
    normalizer: this.paramNormalizer
  });
};

Request.prototype.relations = function (request) {
  var result = extract({
    context: request,
    contextKeysToSearch: this.requestKeysToSearch,
    find: this.relationKey,
    normalizer: this.paramNormalizer
  }) || [];
  if (result && !Array.isArray(result)) {
    result = [result];
  }
  return uniq(result);
};

Request.prototype.responder = function (response, code, data) {
  // cheap heuristics to detect the server type
  var isExpress = !!response.send;
  var isHapi = !!response.request;
  if (!isExpress && !isHapi) {
    throw new Error('Unsupported server type!');
  }

  var prettyPrint = JSON.stringify(data, null, 2);
  var contentType = 'application/json';

  // both of these should never happen, right?
  if (isExpress) {
    response.set('content-type', contentType).status(code).send(prettyPrint);
  }
  if (isHapi) {
    response(prettyPrint).type(contentType).code(code);
  }
};

Request.prototype.create = function (opts) {
  if (!opts) {
    opts = {};
  }
  var method = opts.method || 'create';
  var responder = this.responder;
  var source = this.source;

  return function (request, response) {
    source.create(method, request.body, function (err, data) {
      var code = 201;
      if (err) {
        code = 422;
        data = {
          errors: {
            title: 'Unprocessable Entity',
            detail: err.message
          }
        };
      }
      responder(response, code, data);
    });
  };
};

Request.prototype.read = function (opts) {
  if (!opts) {
    opts = {};
  }
  var responder = this.responder;
  var getFilters = this.filters.bind(this);
  var getRelations = this.relations.bind(this);
  var source = this.source;
  var include = opts.include||[];
  var passMode = !!opts.pass;
  return function (request, response, next) {
    var filters = getFilters(request);
    var relations = getRelations(request).concat(include);
    source.read(filters, relations, opts, function (err, data) {
      var code = 200;
      if (err) {
        code = 400;
        data = {
          errors: {
            title: 'Bad Request',
            detail: err.message
          }
        };
      }
      if (passMode) {
        response.data = data;
        response.code = code;
        next();
      } else {
        responder(response, code, data);
      }
    });
  };
};

Request.prototype.update = function (opts) {
  if (!opts) {
    opts = {};
  }
  var responder = this.responder;
  var source = this.source;

  return function (request, response) {
    source.byId(request.param('id'), function (err, model) {
      if (!model) {
        responder(response, 500, {
          title: 'Internal Server Error',
          detail: 'No resource by that id found.'
        });
      } else {
        source.update(model, request.body, function (err, data) {
          var code = 200;
          if (err) {
            code = 422;
            data = {
              title: 'Unprocessable Entity',
              detail: err.message
            };
          }
          responder(response, code, data);
        });
      }
    });
  };
};

Request.prototype.destroy = function (opts) {
  if (!opts) {
    opts = {};
  }
  var responder = this.responder;
  var source = this.source;

  return function (request, response) {
    source.byId(request.param('id'), function (err, model) {
      if (!model) {
        responder(response, 500, {
          title: 'Internal Server Error',
          detail: 'No resource by that id found.'
        });
      } else {
        source.destroy(model, function (err, data) {
          var code = 200;
          if (err) {
            code = 422;
            data = {
              title: 'Unprocessable Entity',
              detail: err.message
            };
          }
          responder(response, code, data);
        });
      }
    });
  };
};

module.exports = Request;
<|endoftext|>