<commit_before>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    element - The HTML DOM element that will be Docified.
    theme - You can optionally set the style to Dark or Light.
    doc - The elements text that will be Docified.
  @credit:
    Prism, Highlight
*/
var DocTyp = (function(exports) {
  /*============================================================
  ===========================Variable===========================
  ============================================================*/

  /*============================================================
  ============================Private===========================
  ============================================================*/

  /*============================================================
  ============================Loader============================
  ============================================================*/
  exports.LoadScript = function(url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = 'https://doctyp.github.io/src/' + url;
    document.getElementsByTagName('head')[0].appendChild(script);
  };
  exports.LoadStyle = function(url) {
    var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = 'https://doctyp.github.io/src/' + url;
    link.media = 'none';
    link.onload = function() {
      if (link.media != 'all') {
        link.media = 'all';
      }
    };
    document.getElementsByTagName('head')[0].appendChild(link);
  };

  /*============================================================
  ============================Public============================
  ============================================================*/
  exports.Docify = function(element, theme) {
    //Load Extra Files
    exports.LoadScript('https://doctyp.github.io/src/extension.js');
    //Check if element is an element
    if (element.nodeType && element.nodeType == 1) {
      //Adding class to element
      element.setAttribute('class', 'doctyp');
      //Check if user is using their own style
      if (theme !== undefined) {
        exports.theme = theme.toLowerCase();
        LoadStyle('Style/' + theme.toLowerCase() + '.css');
      } else {
        exports.theme = 'light';
      }
      //Cater for older browsers
      var doc = element.innerText ? element.innerText : element.textContent;
      //Processing
      doc = exports.Header(doc);
      doc = exports.Style(doc);
      doc = exports.Rule(doc);
      doc = exports.Block(doc);
      doc = exports.List(doc);
      doc = exports.Clean(doc);
      //Replace text with new text
      element.innerHTML = doc;
    } else {
      throw('The element is not defined or is not a DOM element.');
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})({});
<commit_msg>Update DocTyp.js<commit_after>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    element - The HTML DOM element that will be Docified.
    theme - You can optionally set the style to Dark or Light.
    doc - The elements text that will be Docified.
  @credit:
    Prism, Highlight
*/
var DocTyp = (function(exports) {
  /*============================================================
  ===========================Variable===========================
  ============================================================*/

  /*============================================================
  ============================Private===========================
  ============================================================*/

  /*============================================================
  ============================Loader============================
  ============================================================*/
  exports.LoadScript = function(url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = 'https://doctyp.github.io/src/' + url;
    document.getElementsByTagName('head')[0].appendChild(script);
  };
  exports.LoadStyle = function(url) {
    var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = 'https://doctyp.github.io/src/' + url;
    link.media = 'none';
    link.onload = function() {
      if (link.media != 'all') {
        link.media = 'all';
      }
    };
    document.getElementsByTagName('head')[0].appendChild(link);
  };

  /*============================================================
  ============================Public============================
  ============================================================*/
  exports.Docify = function(element, theme) {
    //Load Extra Files
    exports.LoadScript('extension.js');
    //Check if element is an element
    if (element.nodeType && element.nodeType == 1) {
      //Adding class to element
      element.setAttribute('class', 'doctyp');
      //Check if user is using their own style
      if (theme !== undefined) {
        exports.theme = theme.toLowerCase();
        LoadStyle('Style/' + theme.toLowerCase() + '.css');
      } else {
        exports.theme = 'light';
      }
      //Cater for older browsers
      var doc = element.innerText ? element.innerText : element.textContent;
      //Processing
      doc = exports.Header(doc);
      doc = exports.Style(doc);
      doc = exports.Rule(doc);
      doc = exports.Block(doc);
      doc = exports.List(doc);
      doc = exports.Clean(doc);
      //Replace text with new text
      element.innerHTML = doc;
    } else {
      throw('The element is not defined or is not a DOM element.');
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})({});
<|endoftext|>


<commit_before>import { Box3, Vector3 } from 'three';
import { arrayToBox } from './Utils/ArrayBoxUtilities.js';
const box1 = new Box3();
const box2 = new Box3();
const vec = new Vector3();

export class MeshBVHDebug {

	constructor( bvh, geometry ) {

		this.bvh = bvh;
		this.geometry = geometry;

	}

	validateBounds() {

		const { bvh, geometry } = this;
		const depthStack = [];
		const index = geometry.index;
		const position = geometry.getAttribute( 'position' );
		let passes = true;

		bvh.traverse( ( depth, isLeaf, boundingData, offset, count ) => {

			const info = {
				depth,
				isLeaf,
				boundingData,
				offset,
				count,
			};
			depthStack[ depth ] = info;

			arrayToBox( boundingData, box1 );
			const parent = depthStack[ depth - 1 ];

			if ( isLeaf ) {

				// check triangles
				for ( let i = offset * 3, l = ( offset + count ) * 3; i < l; i += 3 ) {

					const i0 = index.getX( i );
					const i1 = index.getX( i + 1 );
					const i2 = index.getX( i + 2 );

					let isContained = true;

					vec.fromBufferAttribute( position, i0 );
					isContained = box1.containsPoint( vec );

					vec.fromBufferAttribute( position, i1 );
					isContained = isContained && box1.containsPoint( vec );

					vec.fromBufferAttribute( position, i2 );
					isContained = isContained && box1.containsPoint( vec );

					console.assert( isContained, 'Leaf bounds does not fully contain triangle.' );
					passes = passes && isContained;

				}

			}

			if ( parent ) {

				// check if my bounds fit in my parents
				arrayToBox( boundingData, box2 );

				const isContained = box2.containsBox( box1 );
				console.assert( isContained, 'Parent bounds does not fully contain child.' );
				passes = passes && isContained;

			}

		} );

		return passes;

	}

}
<commit_msg>lgtm fix<commit_after>import { Box3, Vector3 } from 'three';
import { arrayToBox } from './Utils/ArrayBoxUtilities.js';
const box1 = new Box3();
const box2 = new Box3();
const vec = new Vector3();

export class MeshBVHDebug {

	constructor( bvh, geometry ) {

		this.bvh = bvh;
		this.geometry = geometry;

	}

	validateBounds() {

		const { bvh, geometry } = this;
		const depthStack = [];
		const index = geometry.index;
		const position = geometry.getAttribute( 'position' );
		let passes = true;

		bvh.traverse( ( depth, isLeaf, boundingData, offset, count ) => {

			const info = {
				depth,
				isLeaf,
				boundingData,
				offset,
				count,
			};
			depthStack[ depth ] = info;

			arrayToBox( boundingData, box1 );
			const parent = depthStack[ depth - 1 ];

			if ( isLeaf ) {

				// check triangles
				for ( let i = offset * 3, l = ( offset + count ) * 3; i < l; i += 3 ) {

					const i0 = index.getX( i );
					const i1 = index.getX( i + 1 );
					const i2 = index.getX( i + 2 );

					let isContained;

					vec.fromBufferAttribute( position, i0 );
					isContained = box1.containsPoint( vec );

					vec.fromBufferAttribute( position, i1 );
					isContained = isContained && box1.containsPoint( vec );

					vec.fromBufferAttribute( position, i2 );
					isContained = isContained && box1.containsPoint( vec );

					console.assert( isContained, 'Leaf bounds does not fully contain triangle.' );
					passes = passes && isContained;

				}

			}

			if ( parent ) {

				// check if my bounds fit in my parents
				arrayToBox( boundingData, box2 );

				const isContained = box2.containsBox( box1 );
				console.assert( isContained, 'Parent bounds does not fully contain child.' );
				passes = passes && isContained;

			}

		} );

		return passes;

	}

}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var dockerode = require('dockerode');
var Promise = require('bluebird');

var Docker = {
  _host: null,
  _client: null,
  setup: function(ip, name) {
    var certDir = path.join(process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'], '.docker/machine/machines', name);
    if (!fs.existsSync(certDir)) {
      return;
    }
    this._host = ip;
    this._client = new dockerode({
      protocol: 'https',
      host: ip,
      port: 2376,
      ca: fs.readFileSync(path.join(certDir, 'ca.pem')),
      cert: fs.readFileSync(path.join(certDir, 'cert.pem')),
      key: fs.readFileSync(path.join(certDir, 'key.pem'))
    });
  },
  client: function () {
    return this._client;
  },
  host: function () {
    return this._host;
  },
  waitForConnection: Promise.coroutine(function * (tries, delay) {
    tries = tries || 10;
    delay = delay || 1000;
    var tryCount = 1;
    while (true) {
      console.log('Connecting: ' + tryCount + ' tries...');
      try {
        yield new Promise((resolve, reject) => {
          this._client.listContainers((err) => {
            if (err) {
              reject(err);
            } else {
              resolve();
            }
          });
        });
        break;
      } catch (err) {
        tryCount += 1;
        yield Promise.delay(delay);
        if (tryCount > tries) {
          throw new Error('Cannot connect to the Docker Engine. Either the VM is not responding or it may be blocked by a VPN connection: ' + err.message);
        }
        continue;
      }
    }
  }),
};

module.exports = Docker;
<commit_msg>Small tweak<commit_after>var fs = require('fs');
var path = require('path');
var dockerode = require('dockerode');
var Promise = require('bluebird');

var Docker = {
  _host: null,
  _client: null,
  setup: function(ip, name) {
    var certDir = path.join(process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'], '.docker/machine/machines', name);
    if (!fs.existsSync(certDir)) {
      return;
    }
    this._host = ip;
    this._client = new dockerode({
      protocol: 'https',
      host: ip,
      port: 2376,
      ca: fs.readFileSync(path.join(certDir, 'ca.pem')),
      cert: fs.readFileSync(path.join(certDir, 'cert.pem')),
      key: fs.readFileSync(path.join(certDir, 'key.pem'))
    });
  },
  client: function () {
    return this._client;
  },
  host: function () {
    return this._host;
  },
  waitForConnection: Promise.coroutine(function * (tries, delay) {
    tries = tries || 10;
    delay = delay || 1000;
    var tryCount = 1;
    while (true) {
      console.log('Connecting: ' + tryCount + ' tries...');
      try {
        yield new Promise((resolve, reject) => {
          this._client.listContainers((err) => {
            if (err) {
              reject(err);
            } else {
              resolve();
            }
          });
        });
        break;
      } catch (err) {
        tryCount += 1;
        yield Promise.delay(delay);
        if (tryCount > tries) {
          throw new Error('Cannot connect to the Docker Engine. Either the VM is not responding or the connection may be blocked (VPN or Proxy): ' + err.message);
        }
        continue;
      }
    }
  }),
};

module.exports = Docker;
<|endoftext|>


<commit_before><commit_msg>Fixed function name typo<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Bruce Schubert.
 * The MIT License
 * http://www.opensource.org/licenses/mit-license
 */

/*global define, $, WorldWind */

define([
    'model/util/WmtUtil',
    'worldwind'],
    function (
        util,
        ww) {
        "use strict";
        /**
         * @constructor
         * @param {WorldWindow} worldWindow
         * @returns {SelectController}
         */
        var SelectController = function (worldWindow) {
            this.wwd = worldWindow;
            // Flag to signal that dragging/moving has been initiated.
            // When dragging, the mouse event is consumed, i.e., not propagated.
            this.isDragging = false;
            // Flag to signal if a touch tap has occured.
            // Used to determine single or double tap.
            this.tapped = false;
            // The time in ms to wait for a double tap
            this.DOUBLE_TAP_INTERVAL = 250;
            // The list of selected items under the mouse cursor
            this.selectedItems = [];
            // The top item in the pick list
            this.pickedItem = null;
            // Caches the clicked item for dblclick to process
            this.clickedItem = null;

            var self = this;
//            $('#globeContextMenu-popup').puimenu();

            // Listen for mouse down to select an item
            this.wwd.addEventListener("mousedown", function (event) {
                self.handlePick(event);
            });
            // Listen for mouse moves and tap gestutes to move an item
            this.wwd.addEventListener("mousemove", function (event) {
                self.handlePick(event);
            });
            // Listen for mouse up to release an item
            this.wwd.addEventListener("mouseup", function (event) {
                self.handlePick(event);
            });
            this.wwd.addEventListener("mouseout", function (event) {
                self.handlePick(event);
            });
            // Listen for single clicks to select an item
            this.wwd.addEventListener("click", function (event) {
                self.handlePick(event);
            });
            // Listen for double clicks to open an item
            this.wwd.addEventListener("dblclick", function (event) {
                self.handlePick(event);
            });
            // Listen for right clicks to open menu
            this.wwd.addEventListener("contextmenu", function (event) {
                self.handlePick(event);
            });

            // Listen for touch
            this.wwd.addEventListener("touchstart", function (event) {
                self.handlePick(event);
            });
            this.wwd.addEventListener("touchmove", function (event) {
                self.handlePick(event);
            });
            this.wwd.addEventListener("touchend", function (event) {
                self.handlePick(event);
            });
        };
        /**
         * Performs the pick apply the appropriate action on the selected item.
         * @param {Event or TapRecognizer} o The input argument is either an Event or a TapRecognizer. Both have the
         *  same properties for determiningthe mouse or tap location.
         */
        SelectController.prototype.handlePick = function (o) {
            // The input argument is either an Event or a TapRecognizer. Both have the same properties for determining
            // the mouse or tap location.
            var self = this,
                type = o.type,
                x, y,
                button = o.button,
                redrawRequired,
                pickList,
                terrainObject,
                isTouchDevice = false;

            // Get our X,Y values from the event;
            // determine if this is a touch device.
            if (type.substring(0, 5) === 'touch') {
                isTouchDevice = true;
                // Use the first touches entry
                // Note: x, y remain undefined for touchend
                if (o.touches.length > 0) {
                    x = o.touches[0].clientX;
                    y = o.touches[0].clientY;
                }
            } else {  // Mouse events...
                // Prevent handling of simulated mouse events on touch devices.
                if (isTouchDevice) {
                    return;
                }
                x = o.clientX;
                y = o.clientY;
            }
            redrawRequired = false;
            // Perform the pick. Must first convert from window coordinates to canvas coordinates, which are
            // relative to the upper left corner of the canvas rather than the upper left corner of the page.
            pickList = this.wwd.pick(this.wwd.canvasCoordinates(x, y));
            switch (type) {
                case 'touchstart':
                case 'mousedown':
                    // Handles right AND left-clicks, and touch event
                    if (pickList.hasNonTerrainObjects()) {
                        // Establish the picked item - may be used by
                        // mouse, select, and open actions
                        this.pickedItem = pickList.topPickedObject();
                        if (this.pickedItem) {
                            // Capture the initial mouse/touch points for comparison in mousemove/touchmove
                            // to detemine if whether to initiate dragging of the picked item.
                            this.startX = x;
                            this.startY = y;
                        }
                    } else {
                        this.pickedItem = null;
                    }
                    break;
                case 'touchmove':
                case 'mousemove':
                    if (this.pickedItem) {
                        // Handle left-clicks and touch device
                        if (this.isMovable(this.pickedItem) && (button === 0 || type === 'touchmove')) {
                            // To prevent confustion with clicks and taps,
                            // start dragging only if the mouse or touch
                            // point has moved a few pixels.
                            if (!this.isDragging &&
                                (Math.abs(this.startX - x) > 2 || Math.abs(this.startY - y) > 2)) {
                                this.isDragging = true;
                                this.startMove(this.pickedItem);
                            }
                            // Perform the actual move of the picked object
                            if (this.isDragging) {
                                // Get the new terrain coords at the pick point
                                terrainObject = pickList.terrainObject();
                                if (terrainObject) {
                                    this.doMove(this.pickedItem, terrainObject);
                                }
                            }
                        }
                    }
                    break;
                case 'touchend':
                case 'touchcancel':
                case 'mouseup':
                case 'mouseout':
                    if (this.pickedItem) {
                        // The end of a touch can signal either the end of a
                        // drag/move operation or a tap/double-tap.
                        // If our isDragging flag is set, then it's a given
                        // that the touch/mouse event signals a move finished.
                        if (this.isDragging) {
                            this.finishMove(this.pickedItem);
                            this.pickedItem = null;
                        } else if (type === 'touchend') {
                            // Determine if touch event is a single tap or a double tap:
                            // Capture the first tap, and if another tap doesn't come in
                            // within the alloted time, then perform single tap action.
                            if (!this.tapped) {
                                // Wait for another tap, if if doesn't happen,
                                // then perform the select action
                                this.clickedItem = this.pickedItem;
                                this.tapped = setTimeout(function () {
                                    self.tapped = null;
                                    self.doSelect(self.clickedItem);
                                }, this.DOUBLE_TAP_INTERVAL);
                            } else {
                                // A double tap has occured. Clear the pending
                                // single tap action and perform the open action
                                clearTimeout(this.tapped);
                                this.tapped = null;
                                this.doOpen(this.pickedItem);
                            }
                            this.pickedItem = null;
                        }
                    }
                    this.isDragging = false;
                    break;
                case 'click':
                    // Remember the clicked item for dblclick processing
                    this.clickedItem = this.pickedItem;
                    if (this.clickedItem) {
                        this.doSelect(this.clickedItem);
                    }
                    // Release the picked item so mousemove doesn't act on it
                    this.pickedItem = null;
                    break;
                case 'dblclick':
                    if (this.clickedItem) {
                        this.doOpen(this.clickedItem);
                        // Release the picked item so mousemove doesn't act on it
                    }
                    this.pickedItem = null;
                    break;
                case 'contextmenu':
                    this.isDragging = false;
                    if (this.pickedItem) {
                        this.doContextSensitive(this.pickedItem);
                        // Release the picked item so mousemove doesn't act on it
                        this.pickedItem = null;
                    }
                    break;
            }
            // Prevent pan/drag operations on the globe when we're dragging an object.
            if (this.isDragging) {
                o.stopImmediatePropagation();   // Try and prevent WW PanRecognizer TouchEvent from processing event
                o.preventDefault();
            }
            // Update the window if we changed anything.
            if (redrawRequired) {
                this.wwd.redraw(); // redraw to make the highlighting changes take effect on the screen
            }
        };

        SelectController.prototype.doContextSensitive = function (pickedItem) {
            if (pickedItem.userObject.showContextMenu) {
                pickedItem.userObject.showContextMenu();
            } else {
                // Otherwise, build a context menu from standard capabilities
//              $('#globeContextMenu-popup').puimenu('show');
            }
        };

        SelectController.prototype.isMovable = function (pickedItem) {
            return pickedItem.userObject.isMovable;
        };
        SelectController.prototype.startMove = function (pickedItem) {
            if (pickedItem.userObject.moveStarted) {
                // Fires EVENT_OBJECT_MOVE_STARTED
                pickedItem.userObject.moveStarted();
            }
        };
        SelectController.prototype.doMove = function (pickedItem, terrainObject) {
            if (pickedItem.userObject.moveToLatLon) {
                // Fires EVENT_OBJECT_MOVED
                pickedItem.userObject.moveToLatLon(
                    terrainObject.position.latitude,
                    terrainObject.position.longitude);
            }
// Uncomment to allow ordinary renderables to be moved.
//                            // Or, move the object (a Renderable) if it has a position object
//                            else if (this.pickedItem.userObject.position) {
//                                this.pickedItem.userObject.position =
//                                    new WorldWind.Position(
//                                        terrainObject.position.latitude,
//                                        terrainObject.position.longitude,
//                                        this.pickedItem.userObject.position.elevation);
//                                redrawRequired = true;
//                            }
        };

        SelectController.prototype.finishMove = function (pickedItem) {
            // Test for a "Movable" capability
            if (pickedItem.userObject.moveFinished) {
                // Fires EVENT_OBJECT_MOVE_FINISHED
                pickedItem.userObject.moveFinished();
            }
        };

        SelectController.prototype.doSelect = function (pickedItem) {
            if (pickedItem.userObject.select) {
                pickedItem.userObject.select();
            }
        };

        SelectController.prototype.doOpen = function (pickedItem) {
            if (pickedItem.userObject.open) {
                pickedItem.userObject.open();
            }
        };

        return SelectController;
    }
);<commit_msg>Minor edits to SelectController.<commit_after>/*
 * Copyright (c) 2016 Bruce Schubert.
 * The MIT License
 * http://www.opensource.org/licenses/mit-license
 */

/*global define, $, WorldWind */

define([
    'knockout',
    'worldwind'],
    function (
        ko,
        ww) {
        "use strict";
        /**
         * The SelectController operates on picked objects containing the Selectable,
         * Movable, Openable and/or ContextSensitive capabilites.
         * @constructor
         * @param {WorldWindow} worldWindow
         * @returns {SelectController}
         */
        var SelectController = function (worldWindow) {
            var self = this;

            this.wwd = worldWindow;
            // Flag to signal that dragging/moving has been initiated.
            // When dragging, the mouse event is consumed, i.e., not propagated.
            this.isDragging = false;
            // Flag to signal if a touch tap has occured.
            // Used to determine single or double tap.
            this.tapped = false;
            // The time in ms to wait for a double tap
            this.DOUBLE_TAP_INTERVAL = 250;
            // The list of selected items under the mouse cursor
            this.selectedItem = ko.observable(null);
            // The top item in the pick list
            this.pickedItem = null;
            // Caches the clicked item for dblclick to process
            this.clickedItem = null;

            // Listen for mouse down to select an item
            this.wwd.addEventListener("mousedown", function (event) {
                self.handlePick(event);
            });
            // Listen for mouse moves and tap gestutes to move an item
            this.wwd.addEventListener("mousemove", function (event) {
                self.handlePick(event);
            });
            // Listen for mouse up to release an item
            this.wwd.addEventListener("mouseup", function (event) {
                self.handlePick(event);
            });
            this.wwd.addEventListener("mouseout", function (event) {
                self.handlePick(event);
            });
            // Listen for single clicks to select an item
            this.wwd.addEventListener("click", function (event) {
                self.handlePick(event);
            });
            // Listen for double clicks to open an item
            this.wwd.addEventListener("dblclick", function (event) {
                self.handlePick(event);
            });
            // Listen for right clicks to open menu
            this.wwd.addEventListener("contextmenu", function (event) {
                self.handlePick(event);
            });

            // Listen for touch
            this.wwd.addEventListener("touchstart", function (event) {
                self.handlePick(event);
            });
            this.wwd.addEventListener("touchmove", function (event) {
                self.handlePick(event);
            });
            this.wwd.addEventListener("touchend", function (event) {
                self.handlePick(event);
            });
        };
        /**
         * Performs the pick apply the appropriate action on the selected item.
         * @param {Event or TapRecognizer} o The input argument is either an Event or a TapRecognizer. Both have the
         *  same properties for determiningthe mouse or tap location.
         */
        SelectController.prototype.handlePick = function (o) {
            // The input argument is either an Event or a TapRecognizer. Both have the same properties for determining
            // the mouse or tap location.
            var self = this,
                type = o.type,
                x, y,
                button = o.button,
                redrawRequired,
                pickList,
                terrainObject,
                isTouchDevice = false;

            // Get our X,Y values from the event;
            // determine if this is a touch device.
            if (type.substring(0, 5) === 'touch') {
                isTouchDevice = true;
                // Use the first touches entry
                // Note: x, y remain undefined for touchend
                if (o.touches.length > 0) {
                    x = o.touches[0].clientX;
                    y = o.touches[0].clientY;
                }
            } else {  // Mouse events...
                // Prevent handling of simulated mouse events on touch devices.
                if (isTouchDevice) {
                    return;
                }
                x = o.clientX;
                y = o.clientY;
            }
            redrawRequired = false;
            // Perform the pick. Must first convert from window coordinates to canvas coordinates, which are
            // relative to the upper left corner of the canvas rather than the upper left corner of the page.
            pickList = this.wwd.pick(this.wwd.canvasCoordinates(x, y));
            switch (type) {
                case 'touchstart':
                case 'mousedown':
                    // Handles right AND left-clicks, and touch event
                    if (pickList.hasNonTerrainObjects()) {
                        // Establish the picked item - may be used by
                        // mouse, select, and open actions
                        this.pickedItem = pickList.topPickedObject();
                        if (this.pickedItem) {
                            // Capture the initial mouse/touch points for comparison in mousemove/touchmove
                            // to detemine if whether to initiate dragging of the picked item.
                            this.startX = x;
                            this.startY = y;
                        }
                    } else {
                        this.pickedItem = null;
                    }
                    break;
                case 'touchmove':
                case 'mousemove':
                    if (this.pickedItem) {
                        // Handle left-clicks and touch device
                        if (this.isMovable(this.pickedItem) && (button === 0 || type === 'touchmove')) {
                            // To prevent confustion with clicks and taps,
                            // start dragging only if the mouse or touch
                            // point has moved a few pixels.
                            if (!this.isDragging &&
                                (Math.abs(this.startX - x) > 2 || Math.abs(this.startY - y) > 2)) {
                                this.isDragging = true;
                                this.startMove(this.pickedItem);
                            }
                            // Perform the actual move of the picked object
                            if (this.isDragging) {
                                // Get the new terrain coords at the pick point
                                terrainObject = pickList.terrainObject();
                                if (terrainObject) {
                                    this.doMove(this.pickedItem, terrainObject);
                                }
                            }
                        }
                    }
                    break;
                case 'touchend':
                case 'touchcancel':
                case 'mouseup':
                case 'mouseout':
                    if (this.pickedItem) {
                        // The end of a touch can signal either the end of a
                        // drag/move operation or a tap/double-tap.
                        // If our isDragging flag is set, then it's a given
                        // that the touch/mouse event signals a move finished.
                        if (this.isDragging) {
                            this.finishMove(this.pickedItem);
                            this.pickedItem = null;
                        } else if (type === 'touchend') {
                            // Determine if touch event is a single tap or a double tap:
                            // Capture the first tap, and if another tap doesn't come in
                            // within the alloted time, then perform single tap action.
                            if (!this.tapped) {
                                // Wait for another tap, if if doesn't happen,
                                // then perform the select action
                                this.clickedItem = this.pickedItem;
                                this.tapped = setTimeout(function () {
                                    self.tapped = null;
                                    self.doSelect(self.clickedItem);
                                }, this.DOUBLE_TAP_INTERVAL);
                            } else {
                                // A double tap has occured. Clear the pending
                                // single tap action and perform the open action
                                clearTimeout(this.tapped);
                                this.tapped = null;
                                this.doOpen(this.pickedItem);
                            }
                            this.pickedItem = null;
                        }
                    }
                    this.isDragging = false;
                    break;
                case 'click':
                    // Remember the clicked item for dblclick processing
                    this.clickedItem = this.pickedItem;
                    if (this.clickedItem) {
                        this.doSelect(this.clickedItem);
                    }
                    // Release the picked item so mousemove doesn't act on it
                    this.pickedItem = null;
                    break;
                case 'dblclick':
                    if (this.clickedItem) {
                        this.doOpen(this.clickedItem);
                    }
                    // Release the picked item so mousemove doesn't act on it
                    this.pickedItem = null;
                    break;
                case 'contextmenu':
                    this.isDragging = false;
                    if (this.pickedItem) {
                        this.doContextSensitive(this.pickedItem);
                        // Release the picked item so mousemove doesn't act on it
                        this.pickedItem = null;
                    }
                    break;
            }
            // Prevent pan/drag operations on the globe when we're dragging an object.
            if (this.isDragging) {
                o.stopImmediatePropagation();   // Try and prevent WW PanRecognizer TouchEvent from processing event
                o.preventDefault();
            }
            // Update the window if we changed anything.
            if (redrawRequired) {
                this.wwd.redraw(); // redraw to make the highlighting changes take effect on the screen
            }
        };

        SelectController.prototype.doContextSensitive = function (pickedItem) {
            if (pickedItem.userObject.showContextMenu) {
                pickedItem.userObject.showContextMenu();
            } else {
                // Otherwise, build a context menu from standard capabilities
//              $('#globeContextMenu-popup').puimenu('show');
            }
        };

        SelectController.prototype.isMovable = function (pickedItem) {
            return pickedItem.userObject.isMovable;
        };
        SelectController.prototype.startMove = function (pickedItem) {
            if (pickedItem.userObject.moveStarted) {
                // Fires EVENT_OBJECT_MOVE_STARTED
                pickedItem.userObject.moveStarted();
            }
        };
        SelectController.prototype.doMove = function (pickedItem, terrainObject) {
            if (pickedItem.userObject.moveToLatLon) {
                // Fires EVENT_OBJECT_MOVED
                pickedItem.userObject.moveToLatLon(
                    terrainObject.position.latitude,
                    terrainObject.position.longitude);
            }
// Uncomment to allow ordinary renderables to be moved.
//                            // Or, move the object (a Renderable) if it has a position object
//                            else if (this.pickedItem.userObject.position) {
//                                this.pickedItem.userObject.position =
//                                    new WorldWind.Position(
//                                        terrainObject.position.latitude,
//                                        terrainObject.position.longitude,
//                                        this.pickedItem.userObject.position.elevation);
//                                redrawRequired = true;
//                            }
        };

        SelectController.prototype.finishMove = function (pickedItem) {
            // Test for a "Movable" capability
            if (pickedItem.userObject.moveFinished) {
                // Fires EVENT_OBJECT_MOVE_FINISHED
                pickedItem.userObject.moveFinished();
            }
        };

        SelectController.prototype.doSelect = function (pickedItem) {
            if (pickedItem.userObject.select) {
                pickedItem.userObject.select();
                }
        };

        SelectController.prototype.doOpen = function (pickedItem) {
            if (pickedItem.userObject.open) {
                pickedItem.userObject.open();
            }
        };

        return SelectController;
    }
);<|endoftext|>


<commit_before>function SexualRelationshipAge(){//(LowerAge, UpperAge, FemaleAgeDistribution,RateOfSex, FemaleWeighting){
	// These results are calculated in the data folder

	var LowerAge=[15, 18, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80];
	var UpperAge=[18, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85];
	var FemaleAgeDistribution=[];

	FemaleAgeDistribution[0]=[0,65.5,29,5.5];
	FemaleAgeDistribution[1]=[1.3,63,25.2,10.5];
	FemaleAgeDistribution[2]=[4.4,60.8,19,15.8];
	FemaleAgeDistribution[3]=[19.5,44.4,18.1,18.1];
	FemaleAgeDistribution[4]=[16.8,39.2,16,28];
	FemaleAgeDistribution[5]=[19.7,34.8,16.1,29.5];
	FemaleAgeDistribution[6]=[31.4,33.4,15.9,19.3];

	var FemaleWeighting=[541788,372479.25,1054450.5,1141267.3,1149430.95,1074097,1127928.75,992706.675,984687.6,790871.1,609201,439324.2,252538.5,149010.4,78117.3];

	var RateOfSex=[0.8,0.825,0.85,0.86,0.87,0.86,0.85,0.815,0.78,0.69,0.6,0.49,0.38,0.28,0.18];

	this.LowerAge=LowerAge;
	this.UpperAge=UpperAge;

	var AgeDiff=[];

	this.MinSexAge=14;// used for the linear decline to earlier ages.
	this.MaxOlderAge=20;

	this.RateOfSex=RateOfSex;

	// Normalise the FemaleWeighting (and indicator of the relative participation of that age in the sexual population

	this.FemaleWeighting=Divide(FemaleWeighting, Sum(FemaleWeighting));

	this.FemaleAgeDistribution=FemaleAgeDistribution;
	// the linear integral

	this.MaleLookUpTable;

	this.MaleSample=[];
	this.FemaleSample=[];
}

SexualRelationshipAge.prototype.CreateSampleTable = function (){
	// Create the big population of females

	var FemaleAgeDistributionIndex=RandSampleWeightedArray(this.FemaleWeighting, 100000)
	var FemaleAge=[];
	var MaleAge=[];
	var MaleAgeArray=[];
	var FemaleAgeArray=[];
	var FemaleIndexArray=[];
	for (var FCount in FemaleAgeDistributionIndex){
		var FemaleIndex=FemaleAgeDistributionIndex[FCount];
		FemaleAge[FCount]=this.LowerAge[FemaleIndex]+(this.UpperAge[FemaleIndex]-this.LowerAge[FemaleIndex])*Rand.Value();
		//console.log("FCount " + FCount + " Index " + Index + " FemaleAge[FCount] " + FemaleAge[FCount]);
		MaleAge[FCount]=this.ChooseMaleAgeFromDistribution(FemaleAge[FCount]);

		FlooredAge=Floor(MaleAge[FCount]);
		// Add the age to a sorted array by age
		if (typeof(MaleAgeArray[FlooredAge])==="undefined"){
			MaleAgeArray[FlooredAge]=[];
		}
		MaleAgeArray[FlooredAge].push(FemaleAge[FCount]);

		FlooredAge=Floor(FemaleAge[FCount]);
		// Add the age to a sorted array by age
		if (typeof(FemaleAgeArray[FlooredAge])==="undefined"){
			FemaleAgeArray[FlooredAge]=[];
		}
		FemaleAgeArray[FlooredAge].push(MaleAge[FCount]);

		// Add the female age to the female index
		// if (typeof(FemaleIndexArray[FemaleIndex])==="undefined"){
			// FemaleIndexArray[FemaleIndex]=[];
		// }
		// FemaleIndexArray[FemaleIndex].push(MaleAge[FCount]-FemaleAge[FCount]);
	}
	// Do a histogram of the female results
	// This section is for testing of the code, and it was found that the ages were correctly generated
	// var HistResults=[];
	// var Proportion=[];
	// for (AgeIndex in FemaleIndexArray){
		// HistResults[AgeIndex]=HistogramData(FemaleIndexArray[AgeIndex], [-100, -3, 3, 6, 100]);
		// Proportion[AgeIndex]=Divide(HistResults[AgeIndex].Count, Sum(HistResults[AgeIndex].Count));
	// }
	// console.log(Proportion);

	this.MaleSample=MaleAgeArray;
	this.FemaleSample=FemaleAgeArray;

	var HistResults=[];
	var Proportion=[];
	for (AgeIndex in MaleAgeArray){
		HistResults[AgeIndex]=HistogramData(MaleAgeArray[AgeIndex], [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]);
		Proportion[AgeIndex]=Divide(HistResults[AgeIndex].Count, Sum(HistResults[AgeIndex].Count));
	}

	this.MaleLookUpTable=Proportion;
	console.log(Proportion);
	// if there is no data for an age, then it returns -1
};

SexualRelationshipAge.prototype.ChooseMaleAgeFromDistribution = function (Age){

	// Find the age group they belong to
	var AgeIndex;
	var MaleAge;
	var DiffBetweenTopAndBottomAges

	if (Age<this.LowerAge[0]){
		AgeIndex=0;
	}
	else if(Age>this.UpperAge[this.UpperAge.length-1]){
		AgeIndex=this.UpperAge.length-1;
	}
	else {
		var AgeIndexFound=false;
		AgeIndex=-1;
		while (AgeIndexFound==false && AgeIndex<6){ // the AdeIndex is hard limited to 6, because that is all the data we have
			AgeIndex++;
			if (this.LowerAge[AgeIndex]<=Age && Age <this.UpperAge[AgeIndex]){
				AgeIndexFound=true;
			}
		}
	}

	if (AgeIndexFound>6){
		AgeIndexFound=6;
	}

	// Choose the male age
	var MaleAgeIndex=RandSampleWeighted(this.FemaleAgeDistribution[AgeIndex]);

	//console.log("MaleAgeIndex" +MaleAgeIndex);

	if (MaleAgeIndex==0){// calculate from the minimum age up
		// using a linearly increasing distribution

		BaseAgeDifference=this.MinSexAge-Age;
		if (BaseAgeDifference>0){
			BaseAgeDifference=0;
		}

		TopAgeDifference=-3;

		DiffBetweenTopAndBottomAges=TopAgeDifference-BaseAgeDifference;
		if (DiffBetweenTopAndBottomAges<1){// to prevent negative values
			DiffBetweenTopAndBottomAges=1;
		}

		BaseAge=Age+BaseAgeDifference;
		MaleAge=BaseAge+DiffBetweenTopAndBottomAges*Sqrt(Rand.Value());// use the inversion of a linearly increasing probability distribution (3x as many in top half as bottom)
		// console.log("BaseAgeDifference" + BaseAgeDifference);
		// console.log("TopAgeDifference" + TopAgeDifference);
		// console.log("DiffBetweenTopAndBottomAges" + DiffBetweenTopAndBottomAges);
		// console.log("BaseAge" + BaseAge);
		// console.log("MaleAge" + MaleAge);

	}
	else if (MaleAgeIndex==3){// calculate from the max age down
		var MaxAge=Age+20;
		DiffBetweenTopAndBottomAges=20-6;
		MaleAge=MaxAge-DiffBetweenTopAndBottomAges*Sqrt(Rand.Value());// use the inversion of a linearly increasing probability distribution (3x as many in top half as bottom)
	}
	else {
		if (MaleAgeIndex==1){
			BaseAgeDifference=-3;
			TopAgeDifference=+3;
		}
		else{
			BaseAgeDifference=+3;
			TopAgeDifference=+6;
		}

		TopAge=Age+TopAgeDifference;
		BaseAge=Age+BaseAgeDifference;
		if (BaseAge<this.MinSexAge){
			BaseAge=this.MinSexAge;
		}
		AgeRange=TopAge-BaseAge;

		MaleAge=BaseAge+AgeRange*Rand.Value();
	}

	return MaleAge;
};

SexualRelationshipAge.prototype.ChooseMaleAge = function (FemaleAge){
	return this.ChooseAge(FemaleAge, this.FemaleSample);
}

SexualRelationshipAge.prototype.ChooseFemaleAge = function (MaleAge){
	return this.ChooseAge(MaleAge, this.MaleSample);
}

SexualRelationshipAge.prototype.ChooseAge = function (Age, SampleData){
	if (typeof(SampleData)==="undefined"){
		throw "The function .CreateSampleTable() must be run first";
	}

	var AgeIndex=Floor(Age);
	if (typeof(SampleData[AgeIndex])==="undefined"){
		return Age;// return the person's age if there is no age data
	}

	var IndexSelection=Floor(SampleData[AgeIndex].length*Rand.Value());

	return SampleData[AgeIndex][IndexSelection];
}

// AA= new SexualRelationshipAge();
// AA.CreateSampleTable();
// for (var Age=14; Age<85; Age++){
	// MaleAge=[];
	// FemaleAge=[];
	// for (j=0; j<100; j++){
		// MaleAge[j]=AA.ChooseMaleAge(Age);
		// FemaleAge[j]=AA.ChooseFemaleAge(Age);
	// }
	// console.log("For the age group " + Age + " Male partners have " + Round(Median(FemaleAge)) + " year old female partners and females " + Round(Median(MaleAge)));
// }<commit_msg>Change name and run auto at include script<commit_after>function SexualRelationshipAgeObject(){//(LowerAge, UpperAge, FemaleAgeDistribution,RateOfSex, FemaleWeighting){
	// These results are calculated in the data folder

	var LowerAge=[15, 18, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80];
	var UpperAge=[18, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85];
	var FemaleAgeDistribution=[];

	FemaleAgeDistribution[0]=[0,65.5,29,5.5];
	FemaleAgeDistribution[1]=[1.3,63,25.2,10.5];
	FemaleAgeDistribution[2]=[4.4,60.8,19,15.8];
	FemaleAgeDistribution[3]=[19.5,44.4,18.1,18.1];
	FemaleAgeDistribution[4]=[16.8,39.2,16,28];
	FemaleAgeDistribution[5]=[19.7,34.8,16.1,29.5];
	FemaleAgeDistribution[6]=[31.4,33.4,15.9,19.3];

	var FemaleWeighting=[541788,372479.25,1054450.5,1141267.3,1149430.95,1074097,1127928.75,992706.675,984687.6,790871.1,609201,439324.2,252538.5,149010.4,78117.3];

	var RateOfSex=[0.8,0.825,0.85,0.86,0.87,0.86,0.85,0.815,0.78,0.69,0.6,0.49,0.38,0.28,0.18];

	this.LowerAge=LowerAge;
	this.UpperAge=UpperAge;

	var AgeDiff=[];

	this.MinSexAge=14;// used for the linear decline to earlier ages.
	this.MaxOlderAge=20;

	this.RateOfSex=RateOfSex;

	// Normalise the FemaleWeighting (and indicator of the relative participation of that age in the sexual population

	this.FemaleWeighting=Divide(FemaleWeighting, Sum(FemaleWeighting));

	this.FemaleAgeDistribution=FemaleAgeDistribution;
	// the linear integral

	this.MaleLookUpTable;

	this.MaleSample=[];
	this.FemaleSample=[];
}

SexualRelationshipAgeObject.prototype.CreateSampleTable = function (){
	// Create the big population of females

	var FemaleAgeDistributionIndex=RandSampleWeightedArray(this.FemaleWeighting, 100000)
	var FemaleAge=[];
	var MaleAge=[];
	var MaleAgeArray=[];
	var FemaleAgeArray=[];
	var FemaleIndexArray=[];
	for (var FCount in FemaleAgeDistributionIndex){
		var FemaleIndex=FemaleAgeDistributionIndex[FCount];
		FemaleAge[FCount]=this.LowerAge[FemaleIndex]+(this.UpperAge[FemaleIndex]-this.LowerAge[FemaleIndex])*Rand.Value();
		//console.log("FCount " + FCount + " Index " + Index + " FemaleAge[FCount] " + FemaleAge[FCount]);
		MaleAge[FCount]=this.ChooseMaleAgeFromDistribution(FemaleAge[FCount]);

		FlooredAge=Floor(MaleAge[FCount]);
		// Add the age to a sorted array by age
		if (typeof(MaleAgeArray[FlooredAge])==="undefined"){
			MaleAgeArray[FlooredAge]=[];
		}
		MaleAgeArray[FlooredAge].push(FemaleAge[FCount]);

		FlooredAge=Floor(FemaleAge[FCount]);
		// Add the age to a sorted array by age
		if (typeof(FemaleAgeArray[FlooredAge])==="undefined"){
			FemaleAgeArray[FlooredAge]=[];
		}
		FemaleAgeArray[FlooredAge].push(MaleAge[FCount]);

		// Add the female age to the female index
		// if (typeof(FemaleIndexArray[FemaleIndex])==="undefined"){
			// FemaleIndexArray[FemaleIndex]=[];
		// }
		// FemaleIndexArray[FemaleIndex].push(MaleAge[FCount]-FemaleAge[FCount]);
	}
	// Do a histogram of the female results
	// This section is for testing of the code, and it was found that the ages were correctly generated
	// var HistResults=[];
	// var Proportion=[];
	// for (AgeIndex in FemaleIndexArray){
		// HistResults[AgeIndex]=HistogramData(FemaleIndexArray[AgeIndex], [-100, -3, 3, 6, 100]);
		// Proportion[AgeIndex]=Divide(HistResults[AgeIndex].Count, Sum(HistResults[AgeIndex].Count));
	// }
	// console.log(Proportion);

	this.MaleSample=MaleAgeArray;
	this.FemaleSample=FemaleAgeArray;

	var HistResults=[];
	var Proportion=[];
	for (AgeIndex in MaleAgeArray){
		HistResults[AgeIndex]=HistogramData(MaleAgeArray[AgeIndex], [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]);
		Proportion[AgeIndex]=Divide(HistResults[AgeIndex].Count, Sum(HistResults[AgeIndex].Count));
	}

	this.MaleLookUpTable=Proportion;
	console.log(Proportion);
	// if there is no data for an age, then it returns -1
};

SexualRelationshipAgeObject.prototype.ChooseMaleAgeFromDistribution = function (Age){

	// Find the age group they belong to
	var AgeIndex;
	var MaleAge;
	var DiffBetweenTopAndBottomAges

	if (Age<this.LowerAge[0]){
		AgeIndex=0;
	}
	else if(Age>this.UpperAge[this.UpperAge.length-1]){
		AgeIndex=this.UpperAge.length-1;
	}
	else {
		var AgeIndexFound=false;
		AgeIndex=-1;
		while (AgeIndexFound==false && AgeIndex<6){ // the AdeIndex is hard limited to 6, because that is all the data we have
			AgeIndex++;
			if (this.LowerAge[AgeIndex]<=Age && Age <this.UpperAge[AgeIndex]){
				AgeIndexFound=true;
			}
		}
	}

	if (AgeIndexFound>6){
		AgeIndexFound=6;
	}

	// Choose the male age
	var MaleAgeIndex=RandSampleWeighted(this.FemaleAgeDistribution[AgeIndex]);

	//console.log("MaleAgeIndex" +MaleAgeIndex);

	if (MaleAgeIndex==0){// calculate from the minimum age up
		// using a linearly increasing distribution

		BaseAgeDifference=this.MinSexAge-Age;
		if (BaseAgeDifference>0){
			BaseAgeDifference=0;
		}

		TopAgeDifference=-3;

		DiffBetweenTopAndBottomAges=TopAgeDifference-BaseAgeDifference;
		if (DiffBetweenTopAndBottomAges<1){// to prevent negative values
			DiffBetweenTopAndBottomAges=1;
		}

		BaseAge=Age+BaseAgeDifference;
		MaleAge=BaseAge+DiffBetweenTopAndBottomAges*Sqrt(Rand.Value());// use the inversion of a linearly increasing probability distribution (3x as many in top half as bottom)
		// console.log("BaseAgeDifference" + BaseAgeDifference);
		// console.log("TopAgeDifference" + TopAgeDifference);
		// console.log("DiffBetweenTopAndBottomAges" + DiffBetweenTopAndBottomAges);
		// console.log("BaseAge" + BaseAge);
		// console.log("MaleAge" + MaleAge);

	}
	else if (MaleAgeIndex==3){// calculate from the max age down
		var MaxAge=Age+20;
		DiffBetweenTopAndBottomAges=20-6;
		MaleAge=MaxAge-DiffBetweenTopAndBottomAges*Sqrt(Rand.Value());// use the inversion of a linearly increasing probability distribution (3x as many in top half as bottom)
	}
	else {
		if (MaleAgeIndex==1){
			BaseAgeDifference=-3;
			TopAgeDifference=+3;
		}
		else{
			BaseAgeDifference=+3;
			TopAgeDifference=+6;
		}

		TopAge=Age+TopAgeDifference;
		BaseAge=Age+BaseAgeDifference;
		if (BaseAge<this.MinSexAge){
			BaseAge=this.MinSexAge;
		}
		AgeRange=TopAge-BaseAge;

		MaleAge=BaseAge+AgeRange*Rand.Value();
	}

	return MaleAge;
};

SexualRelationshipAgeObject.prototype.ChooseMaleAge = function (FemaleAge){
	return this.ChooseAge(FemaleAge, this.FemaleSample);
}

SexualRelationshipAgeObject.prototype.ChooseFemaleAge = function (MaleAge){
	return this.ChooseAge(MaleAge, this.MaleSample);
}

SexualRelationshipAgeObject.prototype.ChooseAge = function (Age, SampleData){
	if (typeof(SampleData)==="undefined"){
		throw "The function .CreateSampleTable() must be run first";
	}

	var AgeIndex=Floor(Age);
	if (typeof(SampleData[AgeIndex])==="undefined"){
		return Age;// return the person's age if there is no age data
	}

	var IndexSelection=Floor(SampleData[AgeIndex].length*Rand.Value());

	return SampleData[AgeIndex][IndexSelection];
}

SexualRelationship=new SexualRelationshipAgeObject();
SexualRelationship.CreateSampleTable();

// AA= new SexualRelationshipAgeObject();
// AA.CreateSampleTable();
// for (var Age=14; Age<85; Age++){
	// MaleAge=[];
	// FemaleAge=[];
	// for (j=0; j<1000; j++){
		// MaleAge[j]=AA.ChooseMaleAge(Age);
		// FemaleAge[j]=AA.ChooseFemaleAge(Age);
	// }
	// console.log("For the age group " + Age + " Male partners have " + Round(Median(FemaleAge)) + " year old female partners and females " + Round(Median(MaleAge)));
// }<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 */

// ==============
// Preload script
// ==============
const {remote, ipcRenderer} = require('electron');

const flipperState = {
  mainWindowId: 0,
  isClientInit: false,
  plugins: null,
  appName: 'JS App',
};

ipcRenderer.on('parent-window-id', (event, message) => {
  flipperState.mainWindowId = message;
});

function initClient(plugins, appName) {
  if (flipperState.isClientInit) {
    return;
  }
  if (plugins) {
    flipperState.plugins = plugins;
  }
  if (appName) {
    flipperState.appName = appName;
  }
  if (flipperState.mainWindowId != 0) {
    ipcRenderer.sendTo(
      flipperState.mainWindowId,
      'from-js-emulator-init-client',
      {
        command: 'initClient',
        windowId: remote.getCurrentWebContents().id,
        payload: {
          plugins: flipperState.plugins,
          appName: flipperState.appName,
        },
      },
    );
    flipperState.isClientInit = true;
  }
}

window.FlipperWebviewBridge = {
  registerPlugins: function (plugins) {
    flipperState.plugins = plugins;
  },
  start: function (appName) {
    flipperState.appName = appName;
    initClient();
  },
  sendFlipperObject: function (plugin, method, data) {
    initClient();
    if (flipperState.mainWindowId != 0) {
      ipcRenderer.sendTo(flipperState.mainWindowId, 'from-js-emulator', {
        command: 'sendFlipperObject',
        payload: {
          api: plugin,
          method: method,
          params: data,
        },
      });
    }
  },
  isFlipperSupported: true,
  initClient: initClient,
};

ipcRenderer.on('message-to-plugin', (event, message) => {
  const flipper = window.flipper;
  if (!flipper) {
    return;
  }
  const receiver = flipper.FlipperWebviewMessageReceiver.receive;
  const {api, method, params} = message.params;
  receiver(api, method, JSON.stringify(params));
});
<commit_msg>fix plugins array serialization<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 */

// ==============
// Preload script
// ==============
const {remote, ipcRenderer} = require('electron');

const flipperState = {
  mainWindowId: 0,
  isClientInit: false,
  plugins: null,
  appName: 'JS App',
};

ipcRenderer.on('parent-window-id', (event, message) => {
  flipperState.mainWindowId = message;
});

function cleanUpGWTArray(arr) {
  const res = [];
  for (let i = 0; i < arr.length; i++) {
    res.push(arr[i]);
  }
  return res;
}

function initClient(plugins, appName) {
  if (flipperState.isClientInit) {
    return;
  }
  if (plugins) {
    flipperState.plugins = cleanUpGWTArray(plugins);
  }
  if (appName) {
    flipperState.appName = appName;
  }
  if (flipperState.mainWindowId != 0) {
    ipcRenderer.sendTo(
      flipperState.mainWindowId,
      'from-js-emulator-init-client',
      {
        command: 'initClient',
        windowId: remote.getCurrentWebContents().id,
        payload: {
          plugins: flipperState.plugins,
          appName: flipperState.appName,
        },
      },
    );
    flipperState.isClientInit = true;
  }
}

window.FlipperWebviewBridge = {
  registerPlugins: function (plugins) {
    flipperState.plugins = plugins;
  },
  start: function (appName) {
    flipperState.appName = appName;
    initClient();
  },
  sendFlipperObject: function (plugin, method, data) {
    initClient();
    if (flipperState.mainWindowId != 0) {
      ipcRenderer.sendTo(flipperState.mainWindowId, 'from-js-emulator', {
        command: 'sendFlipperObject',
        payload: {
          api: plugin,
          method: method,
          params: data,
        },
      });
    }
  },
  isFlipperSupported: true,
  initClient: initClient,
};

ipcRenderer.on('message-to-plugin', (event, message) => {
  const flipper = window.flipper;
  if (!flipper) {
    return;
  }
  const receiver = flipper.FlipperWebviewMessageReceiver.receive;
  const {api, method, params} = message.params;
  receiver(api, method, JSON.stringify(params));
});
<|endoftext|>


<commit_before>process.mixin(require('./common'));

var
  FILE = path.join(path.dirname(__filename), 'dirty.dirty'),
  EXPECTED_FLUSHES = 2,

  db = new Dirty(FILE, {flushInterval: 10}),
  testKey = 'my-key',
  testDoc = {hello: 'world'},
  testDoc2 = {another: "doc"},
  r,

  timesFLushed = 0,
  didSetCallback = false,
  didAddCallback = false,
  didCloseCallback = false;

db.set(testKey, testDoc, function(doc) {
  didSetCallback = true;
  assert.strictEqual(testDoc, doc);
});
assert.equal(testKey, testDoc._key);

r = db.get(testKey);
assert.strictEqual(r, testDoc);

r = db.add(testDoc2, function(doc) {
  didAddCallback = true;
  assert.strictEqual(testDoc2, doc);
});
assert.equal(testDoc2, db.get(r));
assert.equal(2, db.length);

r = db.filter(function(doc) {
  return ('another' in doc);
});
assert.deepEqual(r, [testDoc2]);
assert.strictEqual(r[0], testDoc2);

db.addListener('flush', function() {
  timesFLushed++;
  if (timesFLushed === EXPECTED_FLUSHES) {
    posix.unlink(FILE);
    db.close().addCallback(function() {
      didCloseCallback = true;
    });
    return;
  }

  posix.cat(FILE).addCallback(function(data) {
    var expected =
      JSON.stringify(testDoc)+"\n"+
      JSON.stringify(testDoc2)+"\n";

    assert.equal(expected, data);

    db.add({third: 'doc'});
  });
});

process.addListener('exit', function() {
  assert.equal(EXPECTED_FLUSHES, timesFLushed);
  assert.ok(didSetCallback);
  assert.ok(didAddCallback);
  assert.ok(didCloseCallback);

  puts('[done]');
});<commit_msg>Use upper case for test fixtures<commit_after>process.mixin(require('./common'));

var
  FILE = path.join(path.dirname(__filename), 'dirty.dirty'),
  EXPECTED_FLUSHES = 2,

  TEST_KEY = 'my-key',
  TEST_DOC = {hello: 'world'},
  TEST_DOC2 = {another: "doc"},

  db = new Dirty(FILE, {flushInterval: 10}),

  timesFLushed = 0,
  didSetCallback = false,
  didAddCallback = false,
  didCloseCallback = false,

  r;

db.set(TEST_KEY, TEST_DOC, function(doc) {
  didSetCallback = true;
  assert.strictEqual(TEST_DOC, doc);
});
assert.equal(TEST_KEY, TEST_DOC._key);

r = db.get(TEST_KEY);
assert.strictEqual(r, TEST_DOC);

r = db.add(TEST_DOC2, function(doc) {
  didAddCallback = true;
  assert.strictEqual(TEST_DOC2, doc);
});
assert.equal(TEST_DOC2, db.get(r));
assert.equal(2, db.length);

r = db.filter(function(doc) {
  return ('another' in doc);
});
assert.deepEqual(r, [TEST_DOC2]);
assert.strictEqual(r[0], TEST_DOC2);

db.addListener('flush', function() {
  timesFLushed++;
  if (timesFLushed === EXPECTED_FLUSHES) {
    posix.unlink(FILE);
    db.close().addCallback(function() {
      didCloseCallback = true;
    });
    return;
  }

  posix.cat(FILE).addCallback(function(data) {
    var expected =
      JSON.stringify(TEST_DOC)+"\n"+
      JSON.stringify(TEST_DOC2)+"\n";

    assert.equal(expected, data);

    db.add({third: 'doc'});
  });
});

process.addListener('exit', function() {
  assert.equal(EXPECTED_FLUSHES, timesFLushed);
  assert.ok(didSetCallback);
  assert.ok(didAddCallback);
  assert.ok(didCloseCallback);

  puts('[done]');
});<|endoftext|>


<commit_before>export default {
  // Plugin versions are sourced from the public pub.dev API
  // See website/plugins/source-versions.js for more information on how these are sourced & injected via Webpack
  plugins: {
    firebase_analytics: PUB_FIREBASE_ANALYTICS,
    firebase_analytics_ns: PUB_NS_FIREBASE_ANALYTICS,
    firebase_app_check: PUB_FIREBASE_APP_CHECK,
    firebase_app_check_ns: PUB_NS_FIREBASE_APP_CHECK,
    firebase_auth: PUB_FIREBASE_AUTH,
    firebase_auth_ns: PUB_NS_FIREBASE_AUTH,
    cloud_firestore: PUB_CLOUD_FIRESTORE,
    cloud_firestore_ns: PUB_NS_CLOUD_FIRESTORE,
    cloud_functions: PUB_CLOUD_FUNCTIONS,
    cloud_functions_ns: PUB_NS_CLOUD_FUNCTIONS,
    firebase_messaging: PUB_FIREBASE_MESSAGING,
    firebase_messaging_ns: PUB_NS_FIREBASE_MESSAGING,
    firebase_storage: PUB_FIREBASE_STORAGE,
    firebase_storage_ns: PUB_NS_FIREBASE_STORAGE,
    firebase_core: PUB_FIREBASE_CORE,
    firebase_core_ns: PUB_NS_FIREBASE_CORE,
    firebase_crashlytics: PUB_FIREBASE_CRASHLYTICS,
    firebase_crashlytics_ns: PUB_NS_FIREBASE_CRASHLYTICS,
    firebase_database: PUB_FIREBASE_DATABASE,
    firebase_database_ns: PUB_NS_FIREBASE_DATABASE,
    firebase_dynamic_links: PUB_FIREBASE_DYNAMIC_LINKS,
    firebase_dynamic_links_ns: PUB_NS_FIREBASE_DYNAMIC_LINKS,
    firebase_in_app_messaging: PUB_FIREBASE_IN_APP_MESSAGING,
    firebase_in_app_messaging_ns: PUB_NS_FIREBASE_IN_APP_MESSAGING,
    firebase_ml_vision: PUB_FIREBASE_ML_VISION,
    firebase_performance: PUB_FIREBASE_PERFORMANCE,
    firebase_performance_ns: PUB_NS_FIREBASE_PERFORMANCE,
    firebase_remote_config: PUB_FIREBASE_REMOTE_CONFIG,
    firebase_remote_config_ns: PUB_NS_FIREBASE_REMOTE_CONFIG,
    google_sign_in: "^4.4.4",
  },
  android: {
    google_services: "4.3.3", // com.google.gms:google-services
  },
  web: {
    firebase_cdn: "8.6.1", // https://firebase.google.com/support/release-notes/js
  },
  external: {
    google_sign_in: "^4.5.1",
    flutter_facebook_auth: "^1.0.0"
  }
};
<commit_msg>chore(*): tweak docs links<commit_after>export default {
  // Plugin versions are sourced from the public pub.dev API
  // See website/plugins/source-versions.js for more information on how these are sourced & injected via Webpack
  plugins: {
    firebase_analytics: PUB_FIREBASE_ANALYTICS,
    firebase_analytics_ns: PUB_NS_FIREBASE_ANALYTICS,
    // firebase_app_check: PUB_FIREBASE_APP_CHECK,
    // firebase_app_check_ns: PUB_NS_FIREBASE_APP_CHECK,
    firebase_auth: PUB_FIREBASE_AUTH,
    firebase_auth_ns: PUB_NS_FIREBASE_AUTH,
    cloud_firestore: PUB_CLOUD_FIRESTORE,
    cloud_firestore_ns: PUB_NS_CLOUD_FIRESTORE,
    cloud_functions: PUB_CLOUD_FUNCTIONS,
    cloud_functions_ns: PUB_NS_CLOUD_FUNCTIONS,
    firebase_messaging: PUB_FIREBASE_MESSAGING,
    firebase_messaging_ns: PUB_NS_FIREBASE_MESSAGING,
    firebase_storage: PUB_FIREBASE_STORAGE,
    firebase_storage_ns: PUB_NS_FIREBASE_STORAGE,
    firebase_core: PUB_FIREBASE_CORE,
    firebase_core_ns: PUB_NS_FIREBASE_CORE,
    firebase_crashlytics: PUB_FIREBASE_CRASHLYTICS,
    firebase_crashlytics_ns: PUB_NS_FIREBASE_CRASHLYTICS,
    firebase_database: PUB_FIREBASE_DATABASE,
    firebase_database_ns: PUB_NS_FIREBASE_DATABASE,
    firebase_dynamic_links: PUB_FIREBASE_DYNAMIC_LINKS,
    firebase_dynamic_links_ns: PUB_NS_FIREBASE_DYNAMIC_LINKS,
    firebase_in_app_messaging: PUB_FIREBASE_IN_APP_MESSAGING,
    firebase_in_app_messaging_ns: PUB_NS_FIREBASE_IN_APP_MESSAGING,
    firebase_ml_vision: PUB_FIREBASE_ML_VISION,
    firebase_performance: PUB_FIREBASE_PERFORMANCE,
    firebase_performance_ns: PUB_NS_FIREBASE_PERFORMANCE,
    firebase_remote_config: PUB_FIREBASE_REMOTE_CONFIG,
    firebase_remote_config_ns: PUB_NS_FIREBASE_REMOTE_CONFIG,
    google_sign_in: "^4.4.4",
  },
  android: {
    google_services: "4.3.3", // com.google.gms:google-services
  },
  web: {
    firebase_cdn: "8.6.1", // https://firebase.google.com/support/release-notes/js
  },
  external: {
    google_sign_in: "^4.5.1",
    flutter_facebook_auth: "^1.0.0"
  }
};
<|endoftext|>


<commit_before>AV.VisualizationView = Backbone.View.extend({
    el: '#visualization',
    initialize: function() {
	//var template = _.template( $("#modal_template").html());
	//this.$el.html( template );
        $("#visualization").load(_.bind(function(){
            console.log("it did a reload");
            console.log($("#visualization").contents()[0].title);
            if (!($("#visualization").contents()[0].title)) {
                console.log("RENDERING it says");
                document.getElementById('visualization')
                    .contentWindow
                    .location
                    .reload(true);
            }
        }, this));
	test("HI");
        $('#visualizationModal').on('hidden.bs.modal',function(){
            router.navigate('', {trigger: false, replace: true});
        });
    },
    sideBySide: function() {
        this.model.url = this.model.urlRoot + '/' + this.model.id;
        this.model.fetch(
            {success: _.bind(function(){
                var ids = _.pluck(this.model.get('witnesses'), 'id');
		test(ids);
                if (ids.length < 2){
                    console.log('ids.length < 2: ' + ids);
                }
                this.model.url = this.model.urlRoot + '/' + this.model.id +
                    '/view?mode=sidebyside&condensed=true&docs=' +
                    ids[0] + ',' + ids[1];

	        /*
		 * Set the Share button route located in the modal template
		 */

		var pathArray = window.location.pathname;
	        var path = $("#shareID").attr("href") +'#' + Backbone.history.fragment;
	        $("#shareID").attr("href", path);
                this.render();
            }, this)
            });

    },

    heatMap: function() {
        this.model.url = this.model.urlRoot + '/' + this.model.id +
            '/view?mode=heatmap&condensed=true';

	test(this.model.url);
	//Set the Share button route.
	var pathArray = window.location.pathname;
	var path = $("#shareID").attr("href") +'#' + Backbone.history.fragment;
	$("#shareID").attr("href", path);

	this.render();
    },

    // The rendering of the visualization will be slightly
    // different here, because there is no templating necessary:
    // The server gives back a page.

    render: function(url){

        var response = $.ajax({
            url: this.model.url,
            type: "GET"
        }).done(_.bind(function(d) {
            //If the server returns an HTML document
            if (d[0] != 'R') {
                return d;
            } else { //Rendering
                setTimeout(function(){}, 1000);
                return this.render();
            }
        }, this));
        $("#visualization").attr('src', this.model.url).load(_.bind(function() {
            var iframe = $("#visualization").contents();
            iframe.find('.menubar').remove();
	    iframe.find('#change-workspace').remove();
        }, this));

        $('#visualizationModal').modal({
            show: true
        });
    }
});
<commit_msg>fix accumulating path bug<commit_after>AV.VisualizationView = Backbone.View.extend({
    el: '#visualization',
    initialize: function() {
	//var template = _.template( $("#modal_template").html());
	//this.$el.html( template );
        $("#visualization").load(_.bind(function(){
            console.log("it did a reload");
            console.log($("#visualization").contents()[0].title);
            if (!($("#visualization").contents()[0].title)) {
                console.log("RENDERING it says");
                document.getElementById('visualization')
                    .contentWindow
                    .location
                    .reload(true);
            }
        }, this));
	test("HI");
        $('#visualizationModal').on('hidden.bs.modal',function(){
            router.navigate('', {trigger: false, replace: true});
        });
    },
    sideBySide: function() {
        this.model.url = this.model.urlRoot + '/' + this.model.id;
        this.model.fetch(
            {success: _.bind(function(){
                var ids = _.pluck(this.model.get('witnesses'), 'id');
		test(ids);
                if (ids.length < 2){
                    console.log('ids.length < 2: ' + ids);
                }
                this.model.url = this.model.urlRoot + '/' + this.model.id +
                    '/view?mode=sidebyside&condensed=true&docs=' +
                    ids[0] + ',' + ids[1];

	        /*
		 * Set the Share button route located in the modal template
		 */

		var basePath = "pages/present.html";
	        var path = basePath +'#' +
		    Backbone.history.fragment;
	        $("#shareID").attr("href", path);
                this.render();
            }, this)
            });

    },

    heatMap: function() {
        this.model.url = this.model.urlRoot + '/' + this.model.id +
            '/view?mode=heatmap&condensed=true';

	test(this.model.url);
	//Set the Share button route.
	var basePath = "pages/present.html";
	var path = basePath  +'#' + Backbone.history.fragment;
	$("#shareID").attr("href", path);

	this.render();
    },

    // The rendering of the visualization will be slightly
    // different here, because there is no templating necessary:
    // The server gives back a page.

    render: function(url){

        var response = $.ajax({
            url: this.model.url,
            type: "GET"
        }).done(_.bind(function(d) {
            //If the server returns an HTML document
            if (d[0] != 'R') {
                return d;
            } else { //Rendering
                setTimeout(function(){}, 1000);
                return this.render();
            }
        }, this));
        $("#visualization").attr('src', this.model.url).load(_.bind(function() {
            var iframe = $("#visualization").contents();
            iframe.find('.menubar').remove();
	    iframe.find('#change-workspace').remove();
        }, this));

        $('#visualizationModal').modal({
            show: true
        });
    }
});
<|endoftext|>


<commit_before>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

window.Blob = RNFetchBlob.polyfill.Blob
window.fetch = new RNFetchBlob.polyfill.Fetch({
  auto : true,
  binaryContentTypes : ['image/', 'video/', 'audio/']
}).build()

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : 'Fetch polyfill',
  run : true,
  expand : true,
  timeout : 10000,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const dirs = RNFetchBlob.fs.dirs

let prefix = ((Platform.OS === 'android') ? 'file://' : '')

describe('GET request test : unicode text -> any', (report, done) => {

  function get(fn1, fn2) {
    return fetch(`${TEST_SERVER_URL}/unicode`, { method : 'GET'})
    .then((res) => fn1(res))
    .then((data) => fn2(data))
  }

  let promises =
  [
    get((res) => res.json(), (json) => {
      report(<Assert key="json data correct" expect={'你好!'} actual={json.data}/>)
    }),
    get((res) => res.text(), (text) => {
      report(<Assert key="text data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
    }),
    get((res) => res.blob(), (blob) => {
      return blob.readBlob('utf8').then((text) => {
        report(<Assert key="blob data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
      })
    }),
    // get((res) => res.arrayBuffer(), (text) => {
    //   report(<Assert key="text data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
    // })
  ]

  Promise.all(promises).then(() => {
    done()
  })

})

describe('GET request test : path -> any', (report, done) => {

  function get(fn1, fn2, fn3) {
    fetch(`${TEST_SERVER_URL}/public/github.png`, { method : 'GET'})
      .then((res) => fn1(res))
      .then((data) => fn2(data))
      .catch((err) => fn3(err))
  }
  let contentLength = 0
  let promises = [
    get((res) => res.json(), (data) => {
      report(<Assert key="should not convert blob to JSON" expect={true} actual={false} />)
    }, (err) => {
      report(<Assert key="should not convert blob to JSON" expect={true} actual={true} />)
    }),
    get((res) => {
      contentLength = res.headers['Content-Length']
      return res.text()
    }, (data) => {
      report(
        <Assert key="should convert blob to text" expect={true} actual={true} />,
        <Assert key="content length should correct" expect={Math.floor(contentLength)} actual={data.length} />)
    }, (err) => {
      console.warn(err, err.stack)
      report(<Assert key="should convert blob to text" expect={true} actual={false} />)
    }),
    get((res) => {
      contentLength = res.headers['Content-Length']
      return res.blob()
    }, (blob) => {
      return fs.stat(blob.getRNFetchBlobRef()).then((stat) => {
        report(<Assert key="stored file size correct" expect={contentLength} actual={stat.size} />)
        return blob.readBlob('base64')
      })
      .then((b64) => {
        report(<Info key="stored image">
          <Image style={styles.image} source={{uri : 'data:image/png;BASE64 ,' + b64}}/>
        </Info>)
      })

    }, (err) => {
      console.warn(err, err.stack)
      report(<Assert key="should convert blob to blob" expect={true} actual={false} />)
    })
  ]
  Promise.all(promises).then( () => done() )

})

describe('POST different types of body', (report, done) => {

  let image = RNTest.prop('image')
  let tmpPath = dirs.DocumentDir + '/tmp-' + Date.now()

  function upload(desc, method, pBody) {
    let name = `fetch-replacement-${Platform.OS}-${Date.now()}.png`
    return pBody.then((body) =>
      fetch('https://content.dropboxapi.com/2/files/upload', {
        method : 'post',
        headers : {
          Authorization : `Bearer ${DROPBOX_TOKEN}`,
          'Dropbox-API-Arg': '{\"path\": \"/rn-upload/'+name+'\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}',
          'Content-Type' : 'application/octet-stream'
        }, body })
    )
    .then((res) => {
      return res.json()
    })
    .then((info) => {
      report(<Assert key={desc} expect={name} actual={info.name}/>)
    })
  }

  let tests = [
    upload('upload base64 encoded body', Promise.resolve(image)),
    upload('upload Blob body', Blob.build(image, 'image/png;BASE64')),
    upload('upload file path body', fs.writeFile(tmpPath, image, 'base64').then(() => Promise.resolve(RNFetchBlob.wrap(tmpPath))))
  ]

  Promise.all(tests).then(() => done())

})

describe('check HTTP body correctness', (report, done) => {

  let tmpPath = dirs.DocumentDir + '/tmp-' + Date.now()

  function upload(pBody) {
    return pBody.then((body) =>
      fetch('https://content.dropboxapi.com/2/files/upload', {
        method : 'POST',
        headers : {
          Authorization : `Bearer ${DROPBOX_TOKEN}`,
          'Dropbox-API-Arg': '{\"path\": \"/rn-upload/'+name+'\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}',
          'Content-Type' : 'application/octet-stream'
        }, body })
      .then((res) => res.json())
      .then((info) => {

      })
    )
  }

  let pUnicodeBody = fetch(`${TEST_SERVER_URL}/public/utf8-dummy`, { method : 'GET' })
    .then((res) => res.text())

  let tests = [
    upload(pUnicodeBody)
  ]

})
<commit_msg>Add test case #70<commit_after>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'

import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Platform,
  Dimensions,
  Image,
} from 'react-native';

window.Blob = RNFetchBlob.polyfill.Blob
window.File = RNFetchBlob.polyfill.File
window.fetch = new RNFetchBlob.polyfill.Fetch({
  auto : true,
  binaryContentTypes : ['image/', 'video/', 'audio/']
}).build()

const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : 'Fetch polyfill',
  run : true,
  expand : false,
  timeout : 10000,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const dirs = RNFetchBlob.fs.dirs

let prefix = ((Platform.OS === 'android') ? 'file://' : '')

describe('GET request test : unicode text -> any', (report, done) => {

  function get(fn1, fn2) {
    return fetch(`${TEST_SERVER_URL}/unicode`, { method : 'GET'})
    .then((res) => fn1(res))
    .then((data) => fn2(data))
  }

  let promises =
  [
    get((res) => res.json(), (json) => {
      report(<Assert key="json data correct" expect={'你好!'} actual={json.data}/>)
    }),
    get((res) => res.text(), (text) => {
      report(<Assert key="text data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
    }),
    get((res) => res.blob(), (blob) => {
      return blob.readBlob('utf8').then((text) => {
        report(<Assert key="blob data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
      })
    }),
    // get((res) => res.arrayBuffer(), (text) => {
    //   report(<Assert key="text data correct" expect={'你好!'} actual={JSON.parse(text).data}/>)
    // })
  ]

  Promise.all(promises).then(() => {
    done()
  })

})

describe('GET request test : path -> any', (report, done) => {

  function get(fn1, fn2, fn3) {
    fetch(`${TEST_SERVER_URL}/public/github.png`, { method : 'GET'})
      .then((res) => fn1(res))
      .then((data) => fn2(data))
      .catch((err) => fn3(err))
  }
  let contentLength = 0
  let isIOS = Platform.OS === 'ios'
  let promises = [
    // FIXME: IOS only
    // https://github.com/facebook/react-native/issues/9178
    get((res) => {
      if(isIOS)
        return res.json()
      return Promise.resolve()
    }, (data) => {
      report(<Assert key="should not convert blob to JSON (IOS only)" expect={true} actual={false} />)
    }, (err) => {
      report(<Assert key="should not convert blob to JSON (IOS only)" expect={true} actual={true} />)
    }),
    // FIXME: IOS only
    // https://github.com/facebook/react-native/issues/9178
    get((res) => {
      contentLength = res.headers['Content-Length']
      if(isIOS)
        return res.text()
      return Promise.resolve()

    }, (data) => {
      try {
        report(<Assert key="content length should correct (IOS only)" expect={Math.floor(contentLength)} actual={data ? data.length : 0} />)
      } catch(e){}
    }, (err) => {
      console.warn(err, err.stack)
    }),
    get((res) => {
      contentLength = res.headers['Content-Length']
      return res.blob()
    }, (blob) => {
      return fs.stat(blob._ref).then((stat) => {
        report(<Assert key="stored file size correct" expect={contentLength} actual={stat.size} />)
        return blob.readBlob('base64')
      })
      .then((b64) => {
        report(<Info key="stored image">
          <Image style={styles.image} source={{uri : 'data:image/png;BASE64 ,' + b64}}/>
        </Info>)
      })

    }, (err) => {
      console.warn(err, err.stack)
    })
  ]
  Promise.all(promises).then( () => done() )

})

describe('POST different kinds of body', (report, done) => {

  let image = RNTest.prop('image')
  let tmpPath = dirs.DocumentDir + '/tmp-' + Date.now()

  function upload(desc, pBody) {
    let name = `fetch-replacement-${Platform.OS}-${Date.now()}-${Math.random()}.png`
    return pBody.then((body) =>
      fetch('https://content.dropboxapi.com/2/files/upload', {
        method : 'post',
        headers : {
          Authorization : `Bearer ${DROPBOX_TOKEN}`,
          'Dropbox-API-Arg': '{\"path\": \"/rn-upload/'+name+'\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}',
          'Content-Type' : 'application/octet-stream'
        },
        body})
    )
    .then((res) => {
      return res.json()
    })
    .then((info) => {
      report(<Assert key={desc} expect={name} actual={info.name}/>)
    })
  }

  fetch(`${TEST_SERVER_URL}/public/github2.jpg`)
    .then((res) => res.blob())
    .then((b) => b.readBlob('base64'))
    .then((image) => {
      let tests = [
        upload('upload base64 encoded body', Promise.resolve(image)),
        upload('upload Blob body', Blob.build(image, 'image/png;BASE64')),
        upload('upload file path body', fs.writeFile(tmpPath, image, 'base64').then(() => Promise.resolve(RNFetchBlob.wrap(tmpPath))))
      ]
      Promise.all(tests).then(() => done())
    })

})

describe('Request header correctness', (report, done) => {

  let expect = {
    'hello' : 'world',
    'Content-Type' : 'application/json',
    'foo' : encodeURIComponent('福' + Date.now())
  }

  fetch(`${TEST_SERVER_URL}/xhr-header`, {
    method : 'GET',
    headers : expect
  })
  .then((res) => res.json())
  .then((actual) => {
    report(<Info key={JSON.stringify(actual)}/>)
    report(<Assert key="header field test #1" expect={expect.hello} actual={actual.hello}/>)
    report(<Assert key="header field test #2" expect={expect['content-type']} actual={actual['content-type']}/>)
    report(<Assert key="header field test #3" expect={expect.foo} actual={actual.foo}/>)
    done()
  })

})

describe('Upload form data ', (report, done) => {

  let form = new FormData()
  let expectName = 'fetch-replacement-test' + new Date()
  File
  .build('test-image.png', RNTest.prop('image'), { type : 'image/png;BASE64' })
  .then((file) => {

    form.append('name', expectName)
    form.append('file', file)
    return fetch(`${TEST_SERVER_URL}/upload-form`, {
      method : 'POST',
      body : form
    })

  })
  .then((res) => res.json())
  .then((json) => {
    report(
      <Assert key="form data verify" expect={expectName} actual={json.fields.name}/>,
      <Assert key="file size verify" expect={23975} actual={json.files[0].size}/>,
      <Assert key="form data file name verify" expect={'test-image.png'} actual={json.files[0].originalname}/>
    )
    done()
  })

})
<|endoftext|>


<commit_before>var fs = require('fs');
var Step = require('step');
var path = require('path');
var read = require('../lib/fsutil').read;
var readdir = require('../lib/fsutil').readdir;
var mkdirp = require('../lib/fsutil').mkdirp;
var rm = require('../lib/fsutil').rm;
var s3 = require('../lib/s3');
var config = Bones.plugin.config;
var url = require('url');

// Extensions supported by TileMill. See `carto/lib/carto/external.js` for
// the source of this list.
var ext = [
    '.zip', '.shp', '.png', '.geotiff', '.geotif', '.tiff',
    '.tif', '.vrt', '.kml', '.geojson', '.json', '.rss'
];

models.Library.prototype.sync = function(method, model, success, error) {
    if (method !== 'read') return error(new Error('Method not supported.'));

    switch (model.id) {
    case 'file':
        // @TODO: disallow .. and other nasty things.
        var location = model.get('location') || '/';
        var filepath = path.join(config.files, 'data', location);
        readdir(filepath, function(err, files) {
            if (err) return error(err);
            var data = {};
            data.id = model.id;
            data.location = location;
            data.assets = _(files).chain()
                .sortBy(function(f) {
                    var pre = f.isDirectory() ? 0 : 1;
                    return pre + f.basename;
                })
                .map(function(f) {
                    var asset = { name: f.basename };
                    var local = path.join(location, f.basename);
                    var uri = path.join(filepath, f.basename);
                    if (f.isFile() && _(ext).include(path.extname(f.basename))) {
                        asset.uri = uri;
                        return asset;
                    } else if (f.isDirectory()) {
                        asset.location = local;
                        return asset;
                    }
                })
                .compact()
                .value()
            return success(data);
        });
        break;
    case 's3':
        // @TODO:
        var data = {};
        var options = {};
        data.id = model.id;
        data.location = model.get('location') || '';
        data.assets = [];
        options.bucket = 'mapbox-geodata';
        options.prefix = data.location;
        s3.list(options, function(err, objects) {
            if (err) return error(err);

            data.assets = _(objects).chain()
                .map(function(obj) {
                    if (!obj.Key && !obj.Prefix) return;

                    var filepath, isFile;
                    if (obj.Key) {
                        filepath = obj.Key[0].text;
                        isFile = true;
                    } else {
                        filepath = obj.Prefix[0].text;
                        isFile = false;
                    }

                    if (isFile && _(ext).include(path.extname(filepath))) {
                        return {
                            uri: url.format({
                                protocol: 'http:',
                                host: options.bucket + '.s3.amazonaws.com',
                                pathname: filepath
                            }),
                            name: path.basename(filepath)
                        };
                    } else if (!isFile) {
                        return { location: filepath, name: filepath };
                    }
                })
                .compact()
                .sortBy(function(asset) {
                    var pre = asset.location ? 0 : 1;
                    return pre + asset.name;
                })
                .value();
            return success(data);
        });
        break;
    case 'favoritesFile':
    case 'favoritesPostGIS':
        (new models.Favorites({})).fetch({
            success: function(coll, resp) {
                success(coll.toLibrary(model.id));
            },
            error: function(coll, resp) { error(resp); }
        });
        break;
    default:
        return error(new Error('Model not found.'));
    }
};
<commit_msg>Display basename correctly for directories<commit_after>var fs = require('fs');
var Step = require('step');
var path = require('path');
var read = require('../lib/fsutil').read;
var readdir = require('../lib/fsutil').readdir;
var mkdirp = require('../lib/fsutil').mkdirp;
var rm = require('../lib/fsutil').rm;
var s3 = require('../lib/s3');
var config = Bones.plugin.config;
var url = require('url');

// Extensions supported by TileMill. See `carto/lib/carto/external.js` for
// the source of this list.
var ext = [
    '.zip', '.shp', '.png', '.geotiff', '.geotif', '.tiff',
    '.tif', '.vrt', '.kml', '.geojson', '.json', '.rss'
];

models.Library.prototype.sync = function(method, model, success, error) {
    if (method !== 'read') return error(new Error('Method not supported.'));

    switch (model.id) {
    case 'file':
        // @TODO: disallow .. and other nasty things.
        var location = model.get('location') || '/';
        var filepath = path.join(config.files, 'data', location);
        readdir(filepath, function(err, files) {
            if (err) return error(err);
            var data = {};
            data.id = model.id;
            data.location = location;
            data.assets = _(files).chain()
                .sortBy(function(f) {
                    var pre = f.isDirectory() ? 0 : 1;
                    return pre + f.basename;
                })
                .map(function(f) {
                    var asset = { name: f.basename };
                    var local = path.join(location, f.basename);
                    var uri = path.join(filepath, f.basename);
                    if (f.isFile() && _(ext).include(path.extname(f.basename))) {
                        asset.uri = uri;
                        return asset;
                    } else if (f.isDirectory()) {
                        asset.location = local;
                        return asset;
                    }
                })
                .compact()
                .value()
            return success(data);
        });
        break;
    case 's3':
        // @TODO:
        var data = {};
        var options = {};
        data.id = model.id;
        data.location = model.get('location') || '';
        data.assets = [];
        options.bucket = 'mapbox-geodata';
        options.prefix = data.location;
        s3.list(options, function(err, objects) {
            if (err) return error(err);

            data.assets = _(objects).chain()
                .map(function(obj) {
                    if (!obj.Key && !obj.Prefix) return;

                    var filepath, isFile;
                    if (obj.Key) {
                        filepath = obj.Key[0].text;
                        isFile = true;
                    } else {
                        filepath = obj.Prefix[0].text;
                        isFile = false;
                    }

                    if (isFile && _(ext).include(path.extname(filepath))) {
                        return {
                            uri: url.format({
                                protocol: 'http:',
                                host: options.bucket + '.s3.amazonaws.com',
                                pathname: filepath
                            }),
                            name: path.basename(filepath)
                        };
                    } else if (!isFile) {
                        return {
                            location: filepath,
                            name: path.basename(filepath)
                        };
                    }
                })
                .compact()
                .sortBy(function(asset) {
                    var pre = asset.location ? 0 : 1;
                    return pre + asset.name;
                })
                .value();
            return success(data);
        });
        break;
    case 'favoritesFile':
    case 'favoritesPostGIS':
        (new models.Favorites({})).fetch({
            success: function(coll, resp) {
                success(coll.toLibrary(model.id));
            },
            error: function(coll, resp) { error(resp); }
        });
        break;
    default:
        return error(new Error('Model not found.'));
    }
};
<|endoftext|>


<commit_before>// request animation frame

import React from 'react';
import MorphTransition from './MorphTransition';

export default
class MorphReplace extends React.Component {

    constructor(props) {
        super(props);

        this.progress = 0;
        this.state = {
            current: [],
            viewBox: props.viewBox || [0, 0, props.width, props.height].join(' '),
        };
        this.transitionElement = MorphTransition;
    }

    componentWillMount() {
        this.setState({from: this.props.children, to: this.props.children});
    }

    componentWillReceiveProps(nextProps) {
        this.setState({from: this.props.children, to: nextProps.children, progress: 0});
        this.progress = 0;
        cancelAnimationFrame(this.raf);
        this.startTime = undefined;
        this.animate();
    }

    componentWillUnmount() {
        // TODO
        // not sure should we call componentWillUnomunt on childrens
    }

    animate() {
        this.raf = requestAnimationFrame((timePassed) => {
            if (!this.startTime) {
                this.startTime = timePassed;
            }
            let progress = Math.min((timePassed - this.startTime) / this.props.duration, 1);
            progress = Math.round(progress * 100);
            this.setState({progress: progress});
            if (progress >= 100) {
                return false;
            }
            this.animate();
        });
    }

    render() {
        return (
            React.createElement(this.transitionElement, {
                ...this.props,
                progress: this.state.progress,
            }, {
                from: React.cloneElement(this.state.from),
                to: React.cloneElement(this.state.to),
            })
        );
    }
}

MorphReplace.propTypes = {
    rotation: React.PropTypes.oneOf(['clockwise', 'counterclock', 'none']),
    width: React.PropTypes.number,
    height: React.PropTypes.number,
    duration: React.PropTypes.number,
    children: React.PropTypes.element,
    viewBox: React.PropTypes.string,
};

MorphReplace.defaultProps = {
    width: 40,
    height: 40,
    duration: 350,
    rotation: 'clockwise',
};

<commit_msg>Cancel animation frame on component unmounting<commit_after>// request animation frame

import React from 'react';
import MorphTransition from './MorphTransition';

export default
class MorphReplace extends React.Component {

    constructor(props) {
        super(props);

        this.progress = 0;
        this.state = {
            current: [],
            viewBox: props.viewBox || [0, 0, props.width, props.height].join(' '),
        };
        this.transitionElement = MorphTransition;
    }

    componentWillMount() {
        this.setState({from: this.props.children, to: this.props.children});
    }

    componentWillReceiveProps(nextProps) {
        this.setState({from: this.props.children, to: nextProps.children, progress: 0});
        this.progress = 0;
        cancelAnimationFrame(this.raf);
        this.startTime = undefined;
        this.animate();
    }

    componentWillUnmount() {
        cancelAnimationFrame(this.raf);
        // TODO
        // not sure should we call componentWillUnomunt on childrens
    }

    animate() {
        this.raf = requestAnimationFrame((timePassed) => {
            if (!this.startTime) {
                this.startTime = timePassed;
            }
            let progress = Math.min((timePassed - this.startTime) / this.props.duration, 1);
            progress = Math.round(progress * 100);
            this.setState({progress: progress});
            if (progress >= 100) {
                return false;
            }
            this.animate();
        });
    }

    render() {
        return (
            React.createElement(this.transitionElement, {
                ...this.props,
                progress: this.state.progress,
            }, {
                from: React.cloneElement(this.state.from),
                to: React.cloneElement(this.state.to),
            })
        );
    }
}

MorphReplace.propTypes = {
    rotation: React.PropTypes.oneOf(['clockwise', 'counterclock', 'none']),
    width: React.PropTypes.number,
    height: React.PropTypes.number,
    duration: React.PropTypes.number,
    children: React.PropTypes.element,
    viewBox: React.PropTypes.string,
};

MorphReplace.defaultProps = {
    width: 40,
    height: 40,
    duration: 350,
    rotation: 'clockwise',
};

<|endoftext|>