<commit_before>;(function( win, doc ) {
	"use strict";

	var DELAY = 100,
		TEST_STRING = 'AxmTYklsjo190QW',
		TOLERANCE = 2, // px

		SANS_SERIF_FONTS = 'sans-serif',
		SERIF_FONTS = 'serif',

		// See https://github.com/typekit/webfontloader/blob/master/src/core/fontruler.js#L41
		style = [
			'display:block',
			'position:absolute',
			'top:-999px',
			'left:-999px',
			'font-size:300px',
			'width:auto',
			'height:auto',
			'line-height:normal',
			'margin:0',
			'padding:0',
			'font-variant:normal',
			'white-space:nowrap',
			'font-family:%s'
		].join(';'),
		html = '
' + TEST_STRING + '
';

	var FontFaceOnloadInstance = function() {
		this.appended = false;
		this.dimensions = undefined;
		this.serif = undefined;
		this.sansSerif = undefined;
		this.parent = undefined;
	};

	FontFaceOnloadInstance.prototype.initialMeasurements = function ( fontFamily ) {
		var sansSerif = this.sansSerif,
			serif = this.serif;

		this.dimensions = {
			sansSerif: {
				width: sansSerif.offsetWidth,
				height: sansSerif.offsetHeight
			},
			serif: {
				width: serif.offsetWidth,
				height: serif.offsetHeight
			}
		};

		// Make sure we set the new font-family after we take our initial dimensions:
		// handles the case where FontFaceOnload is called after the font has already
		// loaded.
		sansSerif.style.fontFamily = fontFamily + ', ' + SANS_SERIF_FONTS;
		serif.style.fontFamily = fontFamily + ', ' + SERIF_FONTS;
	};

	FontFaceOnloadInstance.prototype.load = function ( fontFamily, options ) {
		var startTime = new Date(),
			that = this,
			serif = that.serif,
			sansSerif = that.sansSerif,
			parent = that.parent,
			appended = that.appended,
			dimensions = that.dimensions,
			tolerance = options.tolerance || TOLERANCE,
			delay = options.delay || DELAY;

		if( !parent ) {
			parent = that.parent = doc.createElement( 'div' );
		}

		parent.innerHTML = html.replace(/\%s/, SANS_SERIF_FONTS ) + html.replace(/\%s/, SERIF_FONTS );
		sansSerif = that.sansSerif = parent.firstChild;
		serif = that.serif = sansSerif.nextSibling;

		if( options.glyphs ) {
			sansSerif.innerHTML += options.glyphs;
			serif.innerHTML += options.glyphs;
		}

		(function checkDimensions() {
			if( !appended && doc.body ) {
				appended = that.appended = true;
				doc.body.appendChild( parent );

				that.initialMeasurements( fontFamily );
			}

			dimensions = that.dimensions;

			if( appended && dimensions &&
				( Math.abs( dimensions.sansSerif.width - sansSerif.offsetWidth ) > tolerance ||
					Math.abs( dimensions.sansSerif.height - sansSerif.offsetHeight ) > tolerance ||
					Math.abs( dimensions.serif.width - serif.offsetWidth ) > tolerance ||
					Math.abs( dimensions.serif.height - serif.offsetHeight ) > tolerance ) ) {
				options.success();
			} else if( ( new Date() ).getTime() - startTime.getTime() > options.timeout ) {
				options.error();
			} else {
				setTimeout(function() {
					checkDimensions();
				}, delay );
			}
		})();
	}; // end load()

	FontFaceOnloadInstance.prototype.init = function( fontFamily, options ) {
		var that = this,
			defaultOptions = {
				glyphs: '',
				success: function() {},
				error: function() {},
				timeout: 10000
			},
			timeout;

		if( !options ) {
			options = {};
		}

		for( var j in defaultOptions ) {
			if( !options.hasOwnProperty( j ) ) {
				options[ j ] = defaultOptions[ j ];
			}
		}

		// For some reason this was failing on afontgarde + icon fonts.
		if( !options.glyphs && "fonts" in doc ) {
			doc.fonts.load( "1em " + fontFamily ).then(function() {
				options.success();

				win.clearTimeout( timeout );
			});

			if( options.timeout ) {
				timeout = win.setTimeout(function() {
					options.error();
				}, options.timeout );
			}
		} else {
			that.load( fontFamily, options );
		}
	};

	var FontFaceOnload = function( fontFamily, options ) {
		var instance = new FontFaceOnloadInstance();
		instance.init(fontFamily, options);

		return instance;
	};

	// intentional global
	win.FontFaceOnload = FontFaceOnload;
})( this, this.document );
<commit_msg>Adds reference element option, uses requestAnimationFrame for initial measurement, remove test elements after measurement completes. Change default timeout from 10 seconds to 5 seconds<commit_after>;(function( win, doc ) {
	"use strict";

	var INTERVAL = 100,
		TEST_STRING = 'AxmTYklsjo190QW',
		TOLERANCE = 2, // px

		SANS_SERIF_FONTS = 'sans-serif',
		SERIF_FONTS = 'serif',

		// See https://github.com/typekit/webfontloader/blob/master/src/core/fontruler.js#L41
		style = [
			'display:block',
			'position:absolute',
			'top:-999px',
			'left:-999px',
			'font-size:48px',
			'width:auto',
			'height:auto',
			'line-height:normal',
			'margin:0',
			'padding:0',
			'font-variant:normal',
			'white-space:nowrap',
			'font-family:%s'
		].join(';'),
		html = '
' + TEST_STRING + '
';

	var FontFaceOnloadInstance = function() {
		this.appended = false;
		this.dimensions = undefined;
		this.serif = undefined;
		this.sansSerif = undefined;
		this.parent = undefined;
	};

	FontFaceOnloadInstance.prototype.initialMeasurements = function ( fontFamily ) {
		var sansSerif = this.sansSerif,
			serif = this.serif;

		this.dimensions = {
			sansSerif: {
				width: sansSerif.offsetWidth,
				height: sansSerif.offsetHeight
			},
			serif: {
				width: serif.offsetWidth,
				height: serif.offsetHeight
			}
		};

		// Make sure we set the new font-family after we take our initial dimensions:
		// handles the case where FontFaceOnload is called after the font has already
		// loaded.
		sansSerif.style.fontFamily = fontFamily + ', ' + SANS_SERIF_FONTS;
		serif.style.fontFamily = fontFamily + ', ' + SERIF_FONTS;
	};

	FontFaceOnloadInstance.prototype.load = function ( fontFamily, options ) {
		var startTime = new Date(),
			that = this,
			serif = that.serif,
			sansSerif = that.sansSerif,
			parent = that.parent,
			appended = that.appended,
			dimensions,
			tolerance = options.tolerance || TOLERANCE,
			interval = options.delay || INTERVAL,
			ref = options.reference;

		if( !parent ) {
			parent = that.parent = doc.createElement( "div" );
		}

		parent.innerHTML = html.replace(/\%s/, SANS_SERIF_FONTS ) + html.replace(/\%s/, SERIF_FONTS );
		sansSerif = that.sansSerif = parent.firstChild;
		serif = that.serif = sansSerif.nextSibling;

		if( options.glyphs ) {
			sansSerif.innerHTML += options.glyphs;
			serif.innerHTML += options.glyphs;
		}

		(function checkDimensions() {
			if( !ref ) {
				ref = doc.body;
			}
			if( !appended && ref ) {
				ref.appendChild( parent );
				appended = that.appended = true;

				that.initialMeasurements( fontFamily );
			}

			dimensions = that.dimensions;

			if( appended && dimensions &&
				( Math.abs( dimensions.sansSerif.width - sansSerif.offsetWidth ) > tolerance ||
					Math.abs( dimensions.sansSerif.height - sansSerif.offsetHeight ) > tolerance ||
					Math.abs( dimensions.serif.width - serif.offsetWidth ) > tolerance ||
					Math.abs( dimensions.serif.height - serif.offsetHeight ) > tolerance ) ) {
				options.success();
				ref.removeChild( parent );
			} else if( ( new Date() ).getTime() - startTime.getTime() > options.timeout ) {
				options.error();
			} else {
				if( !appended && "requestAnimationFrame" in window ) {
					window.requestAnimationFrame( checkDimensions );
				} else {
					setTimeout(function() {
						checkDimensions();
					}, interval );
				}
			}
		})();
	}; // end load()

	FontFaceOnloadInstance.prototype.init = function( fontFamily, options ) {
		var that = this,
			defaultOptions = {
				glyphs: '',
				success: function() {},
				error: function() {},
				timeout: 5000
			},
			timeout;

		if( !options ) {
			options = {};
		}

		for( var j in defaultOptions ) {
			if( !options.hasOwnProperty( j ) ) {
				options[ j ] = defaultOptions[ j ];
			}
		}

		// For some reason this was failing on afontgarde + icon fonts.
		if( !options.glyphs && "fonts" in doc ) {
			doc.fonts.load( "1em " + fontFamily ).then(function() {
				options.success();

				win.clearTimeout( timeout );
			});

			if( options.timeout ) {
				timeout = win.setTimeout(function() {
					options.error();
				}, options.timeout );
			}
		} else {
			that.load( fontFamily, options );
		}
	};

	var FontFaceOnload = function( fontFamily, options ) {
		var instance = new FontFaceOnloadInstance();
		instance.init(fontFamily, options);

		return instance;
	};

	// intentional global
	win.FontFaceOnload = FontFaceOnload;
})( this, this.document );
<|endoftext|>


<commit_before>import { isLeafNode } from "../nodes";

/**
 * Parses a Newick string into an equivalent JSON representation that is
 * suitable for consumption by ``hierarchy``.
 *
 * Optionally accepts bootstrap values. Currently supports Newick strings with or without branch lengths,
 * as well as tagged trees such as
 *  ``(a,(b{TAG},(c{TAG},d{ANOTHERTAG})))``
 *
 * @param {String} nwk_str - A string representing a phylogenetic tree in Newick format.
 * @param {Object} bootstrap_values.
 * @returns {Object} An object with keys ``json`` and ``error``.
 */

function newickParser(nwk_str, options={}) {
  const bootstrap_values = true,
    int_or_float = /^-?\d+(\.\d+)?$/;
  let left_delimiter = options.left_delimiter ||  '{',
    right_delimiter = options.right_delimiter ||  '}';
  let clade_stack = [];

  function addNewTreeLevel() {
    let new_level = {
      name: null
    };

    let the_parent = clade_stack[clade_stack.length - 1];

    if (!("children" in the_parent)) {
      the_parent["children"] = [];
    }

    clade_stack.push(new_level);

    the_parent["children"].push(clade_stack[clade_stack.length - 1]);

    clade_stack[clade_stack.length - 1]["original_child_order"] =
      the_parent["children"].length;
  }

  function finishNodeDefinition() {
    let this_node = clade_stack.pop();

    this_node["name"] = current_node_name;

    if (bootstrap_values && "children" in this_node) {
      this_node["bootstrap_values"] = current_node_name;
    } else {
      this_node["name"] = current_node_name;
    }

    this_node["attribute"] = current_node_attribute;
    if(left_delimiter == "[" && current_node_annotation.includes("&&NHX")) {
      current_node_annotation
        .split(':')
        .slice(1)
        .forEach(annotation => {
          const [key, value] = annotation.split('=');
          this_node[key] = int_or_float.test(value) ? +value : value;
        });
    } else {
      this_node["annotation"] = current_node_annotation;
    }

    current_node_name = "";
    current_node_attribute = "";
    current_node_annotation = "";
  }

  function generateError(location) {
    return {
      json: null,
      error:
        "Unexpected '" +
        nwk_str[location] +
        "' in '" +
        nwk_str.substring(location - 20, location + 1) +
        "[ERROR HERE]" +
        nwk_str.substring(location + 1, location + 20) +
        "'"
    };
  }

  let automaton_state = 0;
  let current_node_name = "";
  let current_node_attribute = "";
  let current_node_annotation = "";
  let quote_delimiter = null;

  let name_quotes = {
    "'": 1,
    '"': 1
  };

  let tree_json = {
    name: "root"
  };

  clade_stack.push(tree_json);

  var space = /\s/;

  for (var char_index = 0; char_index < nwk_str.length; char_index++) {
    try {
      var current_char = nwk_str[char_index];
      switch (automaton_state) {
        case 0: {
          // look for the first opening parenthesis
          if (current_char == "(") {
            addNewTreeLevel();
            automaton_state = 1; // expecting node name
          }
          break;
        }
        case 1: // name
        case 3: {
          // branch length
          // reading name
          if (current_char == ":") {
            automaton_state = 3;
          } else if (current_char == "," || current_char == ")") {
            try {
              finishNodeDefinition();
              automaton_state = 1;
              if (current_char == ",") {
                addNewTreeLevel();
              }
            } catch (e) {
              return generateError(char_index);
            }
          } else if (current_char == "(") {
            if (current_node_name.length > 0) {
              return generateError(char_index);
            } else {
              addNewTreeLevel();
            }
          } else if (current_char in name_quotes) {
            if (
              automaton_state == 1 &&
              current_node_name.length === 0 &&
              current_node_attribute.length === 0 &&
              current_node_annotation.length === 0
            ) {
              automaton_state = 2;
              quote_delimiter = current_char;
              continue;
            }
            return generateError(char_index);
          } else {
            if (current_char == left_delimiter) {
              if (current_node_annotation.length) {
                return generateError(char_index);
              } else {
                automaton_state = 4;
              }
            } else {
              if (automaton_state == 3) {
                current_node_attribute += current_char;
              } else {
                if (space.test(current_char)) {
                  continue;
                }
                if (current_char == ";") {
                  // semicolon terminates tree definition
                  char_index = nwk_str.length;
                  break;
                }
                current_node_name += current_char;
              }
            }
          }

          break;
        }
        case 2: {
          // inside a quoted expression
          if (current_char == quote_delimiter) {
            if (char_index < nwk_str.length - 1) {
              if (nwk_str[char_index + 1] == quote_delimiter) {
                char_index++;
                current_node_name += quote_delimiter;
                continue;
              }
            }
            quote_delimiter = 0;
            automaton_state = 1;
            continue;
          } else {
            current_node_name += current_char;
          }
          break;
        }
        case 4: {
          // inside a comment / attribute
          if (current_char == right_delimiter) {
            automaton_state = 3;
          } else {
            if (current_char == left_delimiter) {
              return generateError(char_index);
            }
            current_node_annotation += current_char;
          }
          break;
        }
      }
    } catch (e) {
      return generateError(char_index);
    }
  }

  if (clade_stack.length != 1) {
    return generateError(nwk_str.length - 1);
  }

  return {
    json: tree_json,
    error: null
  };
}

/**
 * Return Newick string representation of a phylotree.
 *
 * @param {Function} annotator - Function to apply to each node, determining
 * what label is written (optional).
 * @returns {String} newick - Phylogenetic tree serialized as a Newick string.
 */

// TODO: break this out into two seperate functions
export function getNewick(annotator) {

  let self = this;

  if (!annotator) annotator = d => d.data.name;

  function nodeDisplay(n) {
    if (!isLeafNode(n)) {
      element_array.push("(");
      n.children.forEach(function(d, i) {
        if (i) {
          element_array.push(",");
        }
        nodeDisplay(d);
      });
      element_array.push(")");
    }

    element_array.push(annotator(n));

    let bl = self.branch_length_accessor(n);

    if (bl !== undefined) {
      element_array.push(":" + bl);
    }
  }

  let element_array = [];
  annotator = annotator || "";
  nodeDisplay(this.nodes);

  return element_array.join("")+";";

}

export default newickParser;
<commit_msg>newick export fix<commit_after>import { isLeafNode } from "../nodes";

/**
 * Parses a Newick string into an equivalent JSON representation that is
 * suitable for consumption by ``hierarchy``.
 *
 * Optionally accepts bootstrap values. Currently supports Newick strings with or without branch lengths,
 * as well as tagged trees such as
 *  ``(a,(b{TAG},(c{TAG},d{ANOTHERTAG})))``
 *
 * @param {String} nwk_str - A string representing a phylogenetic tree in Newick format.
 * @param {Object} bootstrap_values.
 * @returns {Object} An object with keys ``json`` and ``error``.
 */

function newickParser(nwk_str, options={}) {
  const bootstrap_values = true,
    int_or_float = /^-?\d+(\.\d+)?$/;
  let left_delimiter = options.left_delimiter ||  '{',
    right_delimiter = options.right_delimiter ||  '}';
  let clade_stack = [];

  function addNewTreeLevel() {
    let new_level = {
      name: null
    };

    let the_parent = clade_stack[clade_stack.length - 1];

    if (!("children" in the_parent)) {
      the_parent["children"] = [];
    }

    clade_stack.push(new_level);

    the_parent["children"].push(clade_stack[clade_stack.length - 1]);

    clade_stack[clade_stack.length - 1]["original_child_order"] =
      the_parent["children"].length;
  }

  function finishNodeDefinition() {
    let this_node = clade_stack.pop();

    this_node["name"] = current_node_name;

    if (bootstrap_values && "children" in this_node) {
      this_node["bootstrap_values"] = current_node_name;
    } else {
      this_node["name"] = current_node_name;
    }

    this_node["attribute"] = current_node_attribute;
    if(left_delimiter == "[" && current_node_annotation.includes("&&NHX")) {
      current_node_annotation
        .split(':')
        .slice(1)
        .forEach(annotation => {
          const [key, value] = annotation.split('=');
          this_node[key] = int_or_float.test(value) ? +value : value;
        });
    } else {
      this_node["annotation"] = current_node_annotation;
    }

    current_node_name = "";
    current_node_attribute = "";
    current_node_annotation = "";
  }

  function generateError(location) {
    return {
      json: null,
      error:
        "Unexpected '" +
        nwk_str[location] +
        "' in '" +
        nwk_str.substring(location - 20, location + 1) +
        "[ERROR HERE]" +
        nwk_str.substring(location + 1, location + 20) +
        "'"
    };
  }

  let automaton_state = 0;
  let current_node_name = "";
  let current_node_attribute = "";
  let current_node_annotation = "";
  let quote_delimiter = null;

  let name_quotes = {
    "'": 1,
    '"': 1
  };

  let tree_json = {
    name: "root"
  };

  clade_stack.push(tree_json);

  var space = /\s/;

  for (var char_index = 0; char_index < nwk_str.length; char_index++) {
    try {
      var current_char = nwk_str[char_index];
      switch (automaton_state) {
        case 0: {
          // look for the first opening parenthesis
          if (current_char == "(") {
            addNewTreeLevel();
            automaton_state = 1; // expecting node name
          }
          break;
        }
        case 1: // name
        case 3: {
          // branch length
          // reading name
          if (current_char == ":") {
            automaton_state = 3;
          } else if (current_char == "," || current_char == ")") {
            try {
              finishNodeDefinition();
              automaton_state = 1;
              if (current_char == ",") {
                addNewTreeLevel();
              }
            } catch (e) {
              return generateError(char_index);
            }
          } else if (current_char == "(") {
            if (current_node_name.length > 0) {
              return generateError(char_index);
            } else {
              addNewTreeLevel();
            }
          } else if (current_char in name_quotes) {
            if (
              automaton_state == 1 &&
              current_node_name.length === 0 &&
              current_node_attribute.length === 0 &&
              current_node_annotation.length === 0
            ) {
              automaton_state = 2;
              quote_delimiter = current_char;
              continue;
            }
            return generateError(char_index);
          } else {
            if (current_char == left_delimiter) {
              if (current_node_annotation.length) {
                return generateError(char_index);
              } else {
                automaton_state = 4;
              }
            } else {
              if (automaton_state == 3) {
                current_node_attribute += current_char;
              } else {
                if (space.test(current_char)) {
                  continue;
                }
                if (current_char == ";") {
                  // semicolon terminates tree definition
                  char_index = nwk_str.length;
                  break;
                }
                current_node_name += current_char;
              }
            }
          }

          break;
        }
        case 2: {
          // inside a quoted expression
          if (current_char == quote_delimiter) {
            if (char_index < nwk_str.length - 1) {
              if (nwk_str[char_index + 1] == quote_delimiter) {
                char_index++;
                current_node_name += quote_delimiter;
                continue;
              }
            }
            quote_delimiter = 0;
            automaton_state = 1;
            continue;
          } else {
            current_node_name += current_char;
          }
          break;
        }
        case 4: {
          // inside a comment / attribute
          if (current_char == right_delimiter) {
            automaton_state = 3;
          } else {
            if (current_char == left_delimiter) {
              return generateError(char_index);
            }
            current_node_annotation += current_char;
          }
          break;
        }
      }
    } catch (e) {
      return generateError(char_index);
    }
  }

  if (clade_stack.length != 1) {
    return generateError(nwk_str.length - 1);
  }

  return {
    json: tree_json,
    error: null
  };
}

/**
 * Return Newick string representation of a phylotree.
 *
 * @param {Function} annotator - Function to apply to each node, determining
 * what label is written (optional).
 * @returns {String} newick - Phylogenetic tree serialized as a Newick string.
 */

// TODO: break this out into two seperate functions
export function getNewick(annotator) {

  let self = this;

  if (!annotator) annotator = d => d.data.name;

  function nodeDisplay(n) {
    if (!isLeafNode(n)) {
      element_array.push("(");
      n.children.forEach(function(d, i) {
        if (i) {
          element_array.push(",");
        }
        nodeDisplay(d);
      });
      element_array.push(")");
    }

    if(n.data.name != 'root') {
      element_array.push(n.data.name);
    }
    element_array.push(annotator(n));

    let bl = self.branch_length_accessor(n);

    if (bl !== undefined) {
      element_array.push(":" + bl);
    }
  }

  let element_array = [];
  annotator = annotator || "";
  nodeDisplay(this.nodes);
  console.log(element_array);

  return element_array.join("")+";";

}

export default newickParser;
<|endoftext|>


<commit_before>import { createStore, applyMiddleware  } from 'redux';
import RootReducer from './Reducers';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger'

let middleware = [thunk];

console.log("REDUX_LOGGING", process.env.REDUX_LOGGING);
console.log("NODE_ENV", process.env.NODE_ENV);
if(process.env.NODE_ENV === 'development' || process.env.REDUX_LOGGING) {
    const logger = createLogger();
    middleware.push(logger);
}

export default createStore(
    RootReducer,
    applyMiddleware(
        ...middleware
    )
);<commit_msg>merging<commit_after>import { createStore, applyMiddleware  } from 'redux';
import RootReducer from './Reducers';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger'

let middleware = [thunk];

if(process.env.NODE_ENV === 'development') {
    const logger = createLogger();
    middleware.push(logger);
}

export default createStore(
    RootReducer,
    applyMiddleware(
        ...middleware
    )
);<|endoftext|>


<commit_before>import {isArray, formatNum} from '../core/Util';

/*
 * @class Point
 * @aka L.Point
 *
 * Represents a point with `x` and `y` coordinates in pixels.
 *
 * @example
 *
 * ```js
 * var point = L.point(200, 300);
 * ```
 *
 * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:
 *
 * ```js
 * map.panBy([200, 300]);
 * map.panBy(L.point(200, 300));
 * ```
 *
 * Note that `Point` does not inherit from Leafet's `Class` object,
 * which means new classes can't inherit from it, and new methods
 * can't be added to it with the `include` function.
 */

export function Point(x, y, round) {
	// @property x: Number; The `x` coordinate of the point
	this.x = (round ? Math.round(x) : x);
	// @property y: Number; The `y` coordinate of the point
	this.y = (round ? Math.round(y) : y);
}

var trunc = Math.trunc || function (v) {
	return v > 0 ? Math.floor(v) : Math.ceil(v);
};

Point.prototype = {

	// @method clone(): Point
	// Returns a copy of the current point.
	clone: function () {
		return new Point(this.x, this.y);
	},

	// @method add(otherPoint: Point): Point
	// Returns the result of addition of the current and the given points.
	add: function (point) {
		// non-destructive, returns a new point
		return this.clone()._add(toPoint(point));
	},

	_add: function (point) {
		// destructive, used directly for performance in situations where it's safe to modify existing point
		this.x += point.x;
		this.y += point.y;
		return this;
	},

	// @method subtract(otherPoint: Point): Point
	// Returns the result of subtraction of the given point from the current.
	subtract: function (point) {
		return this.clone()._subtract(toPoint(point));
	},

	_subtract: function (point) {
		this.x -= point.x;
		this.y -= point.y;
		return this;
	},

	// @method divideBy(num: Number): Point
	// Returns the result of division of the current point by the given number.
	divideBy: function (num) {
		return this.clone()._divideBy(num);
	},

	_divideBy: function (num) {
		this.x /= num;
		this.y /= num;
		return this;
	},

	// @method multiplyBy(num: Number): Point
	// Returns the result of multiplication of the current point by the given number.
	multiplyBy: function (num) {
		return this.clone()._multiplyBy(num);
	},

	_multiplyBy: function (num) {
		this.x *= num;
		this.y *= num;
		return this;
	},

	// @method scaleBy(scale: Point): Point
	// Multiply each coordinate of the current point by each coordinate of
	// `scale`. In linear algebra terms, multiply the point by the
	// [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
	// defined by `scale`.
	scaleBy: function (point) {
		return new Point(this.x * point.x, this.y * point.y);
	},

	// @method unscaleBy(scale: Point): Point
	// Inverse of `scaleBy`. Divide each coordinate of the current point by
	// each coordinate of `scale`.
	unscaleBy: function (point) {
		return new Point(this.x / point.x, this.y / point.y);
	},

	// @method round(): Point
	// Returns a copy of the current point with rounded coordinates.
	round: function () {
		return this.clone()._round();
	},

	_round: function () {
		this.x = Math.round(this.x);
		this.y = Math.round(this.y);
		return this;
	},

	// @method floor(): Point
	// Returns a copy of the current point with floored coordinates (rounded down).
	floor: function () {
		return this.clone()._floor();
	},

	_floor: function () {
		this.x = Math.floor(this.x);
		this.y = Math.floor(this.y);
		return this;
	},

	// @method ceil(): Point
	// Returns a copy of the current point with ceiled coordinates (rounded up).
	ceil: function () {
		return this.clone()._ceil();
	},

	_ceil: function () {
		this.x = Math.ceil(this.x);
		this.y = Math.ceil(this.y);
		return this;
	},

	// @method ceil(): Point
	// Returns a copy of the current point with truncated coordinates (rounded towards zero).
	trunc: function () {
		return this.clone()._trunc();
	},

	_trunc: function () {
		this.x = trunc(this.x);
		this.y = trunc(this.y);
		return this;
	},

	// @method distanceTo(otherPoint: Point): Number
	// Returns the cartesian distance between the current and the given points.
	distanceTo: function (point) {
		point = toPoint(point);

		var x = point.x - this.x,
		    y = point.y - this.y;

		return Math.sqrt(x * x + y * y);
	},

	// @method equals(otherPoint: Point): Boolean
	// Returns `true` if the given point has the same coordinates.
	equals: function (point) {
		point = toPoint(point);

		return point.x === this.x &&
		       point.y === this.y;
	},

	// @method contains(otherPoint: Point): Boolean
	// Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
	contains: function (point) {
		point = toPoint(point);

		return Math.abs(point.x) <= Math.abs(this.x) &&
		       Math.abs(point.y) <= Math.abs(this.y);
	},

	// @method toString(): String
	// Returns a string representation of the point for debugging purposes.
	toString: function () {
		return 'Point(' +
		        formatNum(this.x) + ', ' +
		        formatNum(this.y) + ')';
	}
};

// @factory L.point(x: Number, y: Number, round?: Boolean)
// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.

// @alternative
// @factory L.point(coords: Number[])
// Expects an array of the form `[x, y]` instead.

// @alternative
// @factory L.point(coords: Object)
// Expects a plain object of the form `{x: Number, y: Number}` instead.
export function toPoint(x, y, round) {
	if (x instanceof Point) {
		return x;
	}
	if (isArray(x)) {
		return new Point(x[0], x[1]);
	}
	if (x === undefined || x === null) {
		return x;
	}
	if (typeof x === 'object' && 'x' in x && 'y' in x) {
		return new Point(x.x, x.y);
	}
	return new Point(x, y, round);
}
<commit_msg>docs: fix Point's trunc method docs (#5987)<commit_after>import {isArray, formatNum} from '../core/Util';

/*
 * @class Point
 * @aka L.Point
 *
 * Represents a point with `x` and `y` coordinates in pixels.
 *
 * @example
 *
 * ```js
 * var point = L.point(200, 300);
 * ```
 *
 * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:
 *
 * ```js
 * map.panBy([200, 300]);
 * map.panBy(L.point(200, 300));
 * ```
 *
 * Note that `Point` does not inherit from Leafet's `Class` object,
 * which means new classes can't inherit from it, and new methods
 * can't be added to it with the `include` function.
 */

export function Point(x, y, round) {
	// @property x: Number; The `x` coordinate of the point
	this.x = (round ? Math.round(x) : x);
	// @property y: Number; The `y` coordinate of the point
	this.y = (round ? Math.round(y) : y);
}

var trunc = Math.trunc || function (v) {
	return v > 0 ? Math.floor(v) : Math.ceil(v);
};

Point.prototype = {

	// @method clone(): Point
	// Returns a copy of the current point.
	clone: function () {
		return new Point(this.x, this.y);
	},

	// @method add(otherPoint: Point): Point
	// Returns the result of addition of the current and the given points.
	add: function (point) {
		// non-destructive, returns a new point
		return this.clone()._add(toPoint(point));
	},

	_add: function (point) {
		// destructive, used directly for performance in situations where it's safe to modify existing point
		this.x += point.x;
		this.y += point.y;
		return this;
	},

	// @method subtract(otherPoint: Point): Point
	// Returns the result of subtraction of the given point from the current.
	subtract: function (point) {
		return this.clone()._subtract(toPoint(point));
	},

	_subtract: function (point) {
		this.x -= point.x;
		this.y -= point.y;
		return this;
	},

	// @method divideBy(num: Number): Point
	// Returns the result of division of the current point by the given number.
	divideBy: function (num) {
		return this.clone()._divideBy(num);
	},

	_divideBy: function (num) {
		this.x /= num;
		this.y /= num;
		return this;
	},

	// @method multiplyBy(num: Number): Point
	// Returns the result of multiplication of the current point by the given number.
	multiplyBy: function (num) {
		return this.clone()._multiplyBy(num);
	},

	_multiplyBy: function (num) {
		this.x *= num;
		this.y *= num;
		return this;
	},

	// @method scaleBy(scale: Point): Point
	// Multiply each coordinate of the current point by each coordinate of
	// `scale`. In linear algebra terms, multiply the point by the
	// [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
	// defined by `scale`.
	scaleBy: function (point) {
		return new Point(this.x * point.x, this.y * point.y);
	},

	// @method unscaleBy(scale: Point): Point
	// Inverse of `scaleBy`. Divide each coordinate of the current point by
	// each coordinate of `scale`.
	unscaleBy: function (point) {
		return new Point(this.x / point.x, this.y / point.y);
	},

	// @method round(): Point
	// Returns a copy of the current point with rounded coordinates.
	round: function () {
		return this.clone()._round();
	},

	_round: function () {
		this.x = Math.round(this.x);
		this.y = Math.round(this.y);
		return this;
	},

	// @method floor(): Point
	// Returns a copy of the current point with floored coordinates (rounded down).
	floor: function () {
		return this.clone()._floor();
	},

	_floor: function () {
		this.x = Math.floor(this.x);
		this.y = Math.floor(this.y);
		return this;
	},

	// @method ceil(): Point
	// Returns a copy of the current point with ceiled coordinates (rounded up).
	ceil: function () {
		return this.clone()._ceil();
	},

	_ceil: function () {
		this.x = Math.ceil(this.x);
		this.y = Math.ceil(this.y);
		return this;
	},

	// @method trunc(): Point
	// Returns a copy of the current point with truncated coordinates (rounded towards zero).
	trunc: function () {
		return this.clone()._trunc();
	},

	_trunc: function () {
		this.x = trunc(this.x);
		this.y = trunc(this.y);
		return this;
	},

	// @method distanceTo(otherPoint: Point): Number
	// Returns the cartesian distance between the current and the given points.
	distanceTo: function (point) {
		point = toPoint(point);

		var x = point.x - this.x,
		    y = point.y - this.y;

		return Math.sqrt(x * x + y * y);
	},

	// @method equals(otherPoint: Point): Boolean
	// Returns `true` if the given point has the same coordinates.
	equals: function (point) {
		point = toPoint(point);

		return point.x === this.x &&
		       point.y === this.y;
	},

	// @method contains(otherPoint: Point): Boolean
	// Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
	contains: function (point) {
		point = toPoint(point);

		return Math.abs(point.x) <= Math.abs(this.x) &&
		       Math.abs(point.y) <= Math.abs(this.y);
	},

	// @method toString(): String
	// Returns a string representation of the point for debugging purposes.
	toString: function () {
		return 'Point(' +
		        formatNum(this.x) + ', ' +
		        formatNum(this.y) + ')';
	}
};

// @factory L.point(x: Number, y: Number, round?: Boolean)
// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.

// @alternative
// @factory L.point(coords: Number[])
// Expects an array of the form `[x, y]` instead.

// @alternative
// @factory L.point(coords: Object)
// Expects a plain object of the form `{x: Number, y: Number}` instead.
export function toPoint(x, y, round) {
	if (x instanceof Point) {
		return x;
	}
	if (isArray(x)) {
		return new Point(x[0], x[1]);
	}
	if (x === undefined || x === null) {
		return x;
	}
	if (typeof x === 'object' && 'x' in x && 'y' in x) {
		return new Point(x.x, x.y);
	}
	return new Point(x, y, round);
}
<|endoftext|>


<commit_before>var authors = document.getElementsByClassName('author');

var doneAuthors = {};

for (var i = 0; i < authors.length; i++) {
    var author = authors[i];
    var username = author.textContent;
    if (!doneAuthors.hasOwnProperty(username)) {
        self.port.emit('getRealname', username);
    }
}

function trySetHTML() {
    for (var i = 0; i < authors.length; i++) {
        var author = authors[i];
        // Skip the repo header (e.g., the "elifoster" in "elifoster/github-real-names").
        if (author.getAttribute('itemprop') == 'author') {
            continue;
        }
        var username = author.textContent;
        authors[i].textContent = doneAuthors[username] || username;
    }
}

self.port.on('sendRealname', function(obj) {
    doneAuthors[obj['user']] = obj['real'];
    trySetHTML();
});<commit_msg>:gem: Add support for issue assignees. Close #6.<commit_after>var authors = document.getElementsByClassName('author');

var doneAuthors = {};

var i;

for (i = 0; i < authors.length; i++) {
    emitGet(authors[i]);
}

var assignees = document.getElementsByClassName('assignee');

for (i = 0; i < assignees.length; i++) {
    emitGet(assignees[i]);
}

function emitGet(person) {
    var username = person.textContent;
    if (!doneAuthors.hasOwnProperty(username)) {
        self.port.emit('getRealname', username);
    }
}

function setHTMLForAuthors(people) {
    for (var i = 0; i < people.length; i++) {
        var person = people[i];
        if (person.getAttribute('itemprop') == 'author') {
            continue;
        }

        var username = person.textContent;
        people[i].textContent = doneAuthors[username] || username;
    }
}

function trySetHTML() {
    setHTMLForAuthors(authors);
    setHTMLForAuthors(assignees);
}

self.port.on('sendRealname', function(obj) {
    doneAuthors[obj['user']] = obj['real'];
    trySetHTML();
});<|endoftext|>


<commit_before><commit_msg>AG-3547 Improve dev experience<commit_after><|endoftext|>


<commit_before>(function(exports) {
  "use strict";
  var GREATER = 1
  var LOWER = -1
  var EQUAL = 0

  function compare_debian_package_versions(v1, v2){
    var _v1 = new Version(v1)
    var _v2 = new Version(v2)

    var epoch_number_comparision = compare_epoch_number(_v1, _v2)
    if (epoch_number_comparision != EQUAL)
        return epoch_number_comparision

    var upstream_number_comparision = compare_upstream_version_numbers(_v1, _v2)
    if (upstream_number_comparision == EQUAL){
        return compare_revision_numbers(_v1, _v2)
    }
    else
        return upstream_number_comparision
  }

  function Version(raw_version){
    if(raw_version.indexOf(":") !== -1){
        this.epoch_number = parseInt(raw_version.split(":")[0])
        var without_epoch_number = raw_version.split(":")[1]
    }
    else{
        this.epoch_number = 0
        var without_epoch_number = raw_version
    }

    var upstream_numbers = without_epoch_number.split("-")[0].split(".")
    this.upstream_numbers = []
    for(var index=0; index < upstream_numbers.length; index++){
      this.upstream_numbers.push(parseInt(upstream_numbers[index]))
    }

    if(without_epoch_number.indexOf("-") !== -1){
      var revision_numbers = without_epoch_number.split("-")[1].split(".")
      this.revision_numbers = []
      for(var index=0; index < revision_numbers.length; index++){
        this.revision_numbers.push(parseInt(revision_numbers[index]))
      }
    }else{
          this.revision_numbers = []
    }
  }

  function compare_epoch_number(v1, v2){
    return compare_integer(v1.epoch_number, v2.epoch_number)
  }

  function compare_integer(i1, i2){
    if (i1 > i2)
        return GREATER
    if (i1 < i2)
        return LOWER
    return EQUAL
  }

  function compare_upstream_version_numbers(v1, v2){
    return compare_integer_lists(v1.upstream_numbers, v2.upstream_numbers)
  }

  function compare_revision_numbers(v1, v2){
    return compare_integer_lists(v1.revision_numbers, v2.revision_numbers)
  }

  function compare_integer_lists(l1, l2){
    var MAX_LENGTH = Math.max(l1.length, l2.length)
    for(var index=0; index < MAX_LENGTH; index++){
      var number_1 = l1[index]
      var number_2 = l2[index]
      if (number_2 === undefined)
          return GREATER
      if (number_1 === undefined)
          return LOWER

      var result = compare_integer(number_1, number_2)
      if(result !== EQUAL)
          return result
     }
    return EQUAL
  }

  exports.compare_debian_package_versions = compare_debian_package_versions;
})(this);

<commit_msg>use strict comparison everywhere<commit_after>(function(exports) {
  "use strict";
  var GREATER = 1
  var LOWER = -1
  var EQUAL = 0

  function compare_debian_package_versions(v1, v2){
    var _v1 = new Version(v1)
    var _v2 = new Version(v2)

    var epoch_number_comparision = compare_epoch_number(_v1, _v2)
    if (epoch_number_comparision !== EQUAL)
        return epoch_number_comparision

    var upstream_number_comparision = compare_upstream_version_numbers(_v1, _v2)
    if (upstream_number_comparision === EQUAL){
        return compare_revision_numbers(_v1, _v2)
    }
    else
        return upstream_number_comparision
  }

  function Version(raw_version){
    if(raw_version.indexOf(":") !== -1){
        this.epoch_number = parseInt(raw_version.split(":")[0])
        var without_epoch_number = raw_version.split(":")[1]
    }
    else{
        this.epoch_number = 0
        var without_epoch_number = raw_version
    }

    var upstream_numbers = without_epoch_number.split("-")[0].split(".")
    this.upstream_numbers = []
    for(var index=0; index < upstream_numbers.length; index++){
      this.upstream_numbers.push(parseInt(upstream_numbers[index]))
    }

    if(without_epoch_number.indexOf("-") !== -1){
      var revision_numbers = without_epoch_number.split("-")[1].split(".")
      this.revision_numbers = []
      for(var index=0; index < revision_numbers.length; index++){
        this.revision_numbers.push(parseInt(revision_numbers[index]))
      }
    }else{
          this.revision_numbers = []
    }
  }

  function compare_epoch_number(v1, v2){
    return compare_integer(v1.epoch_number, v2.epoch_number)
  }

  function compare_integer(i1, i2){
    if (i1 > i2)
        return GREATER
    if (i1 < i2)
        return LOWER
    return EQUAL
  }

  function compare_upstream_version_numbers(v1, v2){
    return compare_integer_lists(v1.upstream_numbers, v2.upstream_numbers)
  }

  function compare_revision_numbers(v1, v2){
    return compare_integer_lists(v1.revision_numbers, v2.revision_numbers)
  }

  function compare_integer_lists(l1, l2){
    var MAX_LENGTH = Math.max(l1.length, l2.length)
    for(var index=0; index < MAX_LENGTH; index++){
      var number_1 = l1[index]
      var number_2 = l2[index]
      if (number_2 === undefined)
          return GREATER
      if (number_1 === undefined)
          return LOWER

      var result = compare_integer(number_1, number_2)
      if(result !== EQUAL)
          return result
     }
    return EQUAL
  }

  exports.compare_debian_package_versions = compare_debian_package_versions;
})(this);

<|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.
 *
 * @emails oncall+flow
 * @format
 */

'use strict';

module.exports = {
  rules: {
    'use-indexed-access-type': require('./rules/use-indexed-access-type'),
  },
};
<commit_msg>Eslint plugin: fix exported rules<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.
 *
 * @emails oncall+flow
 * @format
 */

'use strict';

module.exports = {
  rules: {
    'flow-enums-default-if-possible': require('./rules/flow-enums-default-if-possible'),
    'no-flow-enums-object-mapping': require('./rules/no-flow-enums-object-mapping'),
    'use-exact-by-default-object-type': require('./rules/use-exact-by-default-object-type'),
    'use-flow-enums': require('./rules/use-flow-enums'),
    'use-indexed-access-type': require('./rules/use-indexed-access-type'),
  },
};
<|endoftext|>


<commit_before>angular.module("angular-growl").directive("growl", ["$rootScope", "$sce",
  function($rootScope, $sce) {
    "use strict";

    return {
      restrict: 'A',
      templateUrl: 'templates/growl/growl.html',
      replace: false,
      scope: {
        reference: '@',
        inline: '@'
      },
      controller: ['$scope', '$timeout', 'growl',
        function($scope, $timeout, growl) {
          var onlyUnique = growl.onlyUnique();
          $scope.messages = [];
          var referenceId = $scope.reference || 0;
          $scope.inlineMessage = $scope.inline || growl.inlineMessages();

          function addMessage(message) {
            message.text = $sce.trustAsHtml(message.text);
            $scope.messages.push(message);

            if (message.ttl && message.ttl !== -1) {
              $timeout(function() {
                $scope.deleteMessage(message);
              }, message.ttl);
            }
          }

          $rootScope.$on("growlMessage", function(event, message) {
            var found;
            if (parseInt(referenceId, 10) === parseInt(message.referenceId, 10)) {
              if (onlyUnique) {
                angular.forEach($scope.messages, function(msg) {
                  if (message.text === msg.text && message.severity === msg.severity) {
                    found = true;
                  }
                });

                if (!found) {
                  addMessage(message);
                }
              } else {
                addMessage(message);
              }
            }
          });

          $scope.deleteMessage = function(message) {
            var index = $scope.messages.indexOf(message);
            if (index > -1) {
              $scope.messages.splice(index, 1);
            }

          };

          $scope.alertClasses = function(message) {
            return {
              'alert-success': message.severity === "success",
              'alert-error': message.severity === "error", //bootstrap 2.3
              'alert-danger': message.severity === "error", //bootstrap 3
              'alert-info': message.severity === "info",
              'alert-warning': message.severity === "warning", //bootstrap 3, no effect in bs 2.3
              'icon' : message.disableIcons === false
            };
          };

          $scope.wrapperClasses = function(){
            var classes = {};
            classes['growl-fixed'] = !$scope.inlineMessage;
            classes[growl.position()] = true;
            return classes;
          };

          $scope.computeTitle = function(message){
            var ret = {
              'success': 'Success',
              'error': 'Error',
              'info': 'Information',
              'warn': 'Warning'
            };
            return ret[message.severity];
          };
        }
      ]
    };
  }
]);

angular.module("angular-growl").run(['$templateCache', function($templateCache) {
  "use strict";
  $templateCache.put("templates/growl/growl.html",
    '
' +
      '
' +
        '<button type="button" class="close" ng-click="deleteMessage(message)" ng-show="!message.disableCloseButton">×</button>' +
        '

' +
        '

' +
      '
' +
    '
'
  );
}]);
<commit_msg>Fixes #9 message uniqueness is now checked on message text, severity and title<commit_after>angular.module("angular-growl").directive("growl", ["$rootScope", "$sce",
  function($rootScope, $sce) {
    "use strict";

    return {
      restrict: 'A',
      templateUrl: 'templates/growl/growl.html',
      replace: false,
      scope: {
        reference: '@',
        inline: '@'
      },
      controller: ['$scope', '$timeout', 'growl',
        function($scope, $timeout, growl) {
          var onlyUnique = growl.onlyUnique();
          $scope.messages = [];
          var referenceId = $scope.reference || 0;
          $scope.inlineMessage = $scope.inline || growl.inlineMessages();

          function addMessage(message) {
            message.text = $sce.trustAsHtml(message.text);
            $scope.messages.push(message);

            if (message.ttl && message.ttl !== -1) {
              $timeout(function() {
                $scope.deleteMessage(message);
              }, message.ttl);
            }
          }

          $rootScope.$on("growlMessage", function(event, message) {
            var found;
            var msgText;
            if (parseInt(referenceId, 10) === parseInt(message.referenceId, 10)) {
              if (onlyUnique) {
                angular.forEach($scope.messages, function(msg) {
                  msgText = $sce.getTrustedHtml(msg.text);
                  if (message.text === msgText && message.severity === msg.severity && msg.title === msg.title) {
                    found = true;
                  }
                });

                if (!found) {
                  addMessage(message);
                }
              } else {
                addMessage(message);
              }
            }
          });

          $scope.deleteMessage = function(message) {
            var index = $scope.messages.indexOf(message);
            if (index > -1) {
              $scope.messages.splice(index, 1);
            }

          };

          $scope.alertClasses = function(message) {
            return {
              'alert-success': message.severity === "success",
              'alert-error': message.severity === "error", //bootstrap 2.3
              'alert-danger': message.severity === "error", //bootstrap 3
              'alert-info': message.severity === "info",
              'alert-warning': message.severity === "warning", //bootstrap 3, no effect in bs 2.3
              'icon' : message.disableIcons === false
            };
          };

          $scope.wrapperClasses = function(){
            var classes = {};
            classes['growl-fixed'] = !$scope.inlineMessage;
            classes[growl.position()] = true;
            return classes;
          };

          $scope.computeTitle = function(message){
            var ret = {
              'success': 'Success',
              'error': 'Error',
              'info': 'Information',
              'warn': 'Warning'
            };
            return ret[message.severity];
          };
        }
      ]
    };
  }
]);

angular.module("angular-growl").run(['$templateCache', function($templateCache) {
  "use strict";
  $templateCache.put("templates/growl/growl.html",
    '
' +
      '
' +
        '<button type="button" class="close" ng-click="deleteMessage(message)" ng-show="!message.disableCloseButton">×</button>' +
        '

' +
        '

' +
      '
' +
    '
'
  );
}]);
<|endoftext|>


<commit_before>'use strict';

function twiml (request, reply) {
  reply(`<Response>
<Dial callerId="">${request.query.PhoneNumber}</Dial>
</Response>`).type('text/xml');
}

export default twiml;
<commit_msg>hardcode the number<commit_after>'use strict';

function twiml (request, reply) {
  reply(`<Response>
<Dial callerId="4144090112">${request.query.PhoneNumber}</Dial>
</Response>`).type('text/xml');
}

export default twiml;
<|endoftext|>


<commit_before>import * as Sentry from "@sentry/browser";
import {version} from "../../package.json";

const invalidMessages = [
  "ResizeObserver loop limit exceeded",
  "Network error: Failed to fetch",
];
if (process.env.NODE_ENV === "production") {
  Sentry.init({
    release: `react@${version}`,
    dsn: "https://c71a50635f9b42f4a70880cce6a7ff0e@sentry.io/1323903",
    beforeSend(event) {
      if (
        event.exception.mechanism.data &&
        invalidMessages.includes(event.exception.mechanism.data.message)
      )
        return null;
      return event;
    },
  });
} else {
  // window.addEventListener("error", function(e) {
  //  // console.error(e);
  // });
}
<commit_msg>Fix a sentry error<commit_after>import * as Sentry from "@sentry/browser";
import {version} from "../../package.json";

const invalidMessages = [
  "ResizeObserver loop limit exceeded",
  "Network error: Failed to fetch",
];
if (process.env.NODE_ENV === "production") {
  Sentry.init({
    release: `react@${version}`,
    dsn: "https://c71a50635f9b42f4a70880cce6a7ff0e@sentry.io/1323903",
    beforeSend(event) {
      if (invalidMessages.includes(event?.exception?.mechanism?.data?.message))
        return null;
      return event;
    },
  });
} else {
  // window.addEventListener("error", function(e) {
  //  // console.error(e);
  // });
}
<|endoftext|>


<commit_before>/*global BigBlock, console, opera */
/**
 Log object
 Provides methods to print messages, errors, timers, profilers, etc. to the browser console.

 @author Vince Allen 08-04-2011

 Big Block Framework
 Copyright (C) 2011 Foldi, LLC

 */

BigBlock.Log = (function(){

	return {
		display: function(str) {

			if (typeof console !== "undefined") {
				console.log(str); // output error to console
			} else if (typeof opera !== "undefined" && typeof opera.wiiremote !== "undefined") { // wii uses alerts
				alert(str);
			} else if (typeof opera !== "undefined") { // opera uses error console
				opera.postError(str);
			}
		},
		/*
		Creates a new timer under the given name. Call console.timeEnd(name) with the same name to stop the timer and print the time elapsed..
		*/
		time: function (name) {
			if (console) {
				console.time(name);
			}
		},
		/*
		Stops a timer created by a call to console.time(name) and writes the time elapsed.
		*/
		timeEnd: function (name) {
			if (console) {
				console.timeEnd(name);
			}
		},
		/*
		Writes the number of times that the line of code where count was called was executed. The optional argument title will print a message in addition to the number of the count.
		*/
		count: function (name) {
			if (console) {
				console.count(name);
			}
		},
		/*
		Allows to log provided data using tabular layout. The method takes one required parameter that represents table like data (array of arrays or list of objects). The other optional parameter can be used to specify columns and/or properties to be logged.
		*/
		table: function (data, columns) {
			if (console) {
				console.table(data, columns);
			}
		}
	};

}());<commit_msg>refactored Log to check for console support before the Log object returns<commit_after>/*global BigBlock, window, console, opera */
/**
 Log object
 Provides methods to print messages, errors, timers, profilers, etc. to the browser console.

 @author Vince Allen 08-04-2011

 Big Block Framework
 Copyright (C) 2011 Foldi, LLC

 */

BigBlock.Log = (function(){

	/*
	Browsers like Camino will report they support the console object. But Camino won't support the methods in the Firebug console api.
	To be safe, test for each method. Also, because these tests are run before the Log object returns, we don't have to check them
	each time the method is invoked.
	*/

	var display, time, timeEnd, count, table;

	if (typeof console !== "undefined" && typeof console.log !== "undefined") {
		display = function(str) {
			console.log(str); // output error to console
		};
	} else {
		display = function () {};
	}

	if (typeof window.opera !== "undefined") {
		display = function(str) {
			window.opera.postError(str); // opera uses proprietary error console
		};
	}

	if (typeof console !== "undefined" && typeof console.time !== "undefined" && typeof console.timeEnd !== "undefined" && typeof console.count !== "undefined" && typeof console.table !== "undefined") {
		time = function (name) {
			if (this.timer_enabled) {
				console.time(name);
			}
		};
		timeEnd = function (name) {
			if (this.timer_enabled) {
				console.timeEnd(name);
			}
		};
		count = function (name) {
			if (this.count_enabled) {
				console.count(name);
			}
		};
		table = function (data, columns) {
			console.table(data, columns);
		};
	} else {
		time = function () {};
		timeEnd = function () {};
		count = function () {};
		table = function () {};
	}

	return {
		timer_enabled: true,
		count_enabled: true,
		display: display,
		/*
		Creates a new timer under the given name. Call console.timeEnd(name) with the same name to stop the timer and print the time elapsed..
		*/
		time: time,
		/*
		Stops a timer created by a call to console.time(name) and writes the time elapsed.
		*/
		timeEnd: timeEnd,
		/*
		Writes the number of times that the line of code where count was called was executed. The optional argument title will print a message in addition to the number of the count.
		*/
		count: count,
		/*
		Allows to log provided data using tabular layout. The method takes one required parameter that represents table like data (array of arrays or list of objects). The other optional parameter can be used to specify columns and/or properties to be logged.
		*/
		table: table
	};

}());<|endoftext|>


<commit_before>const {tokTypes: tt, parse, plugins} = require("acorn")

// FIXME Get rid of Acorn now that no actual JavaScript can appear in these files anymore?

function parseGrammar(p, node) {
  node.rules = Object.create(null)
  node.extends = null
  node.included = []

  for (;;) {
    if (p.eat(tt._extends)) {
      if (node.extends) p.raise("Can't extend multiple grammars")
      if (p.type != tt.string) p.unexpected()
      node.extends = p.value
      p.next()
    } else if (p.eatContextual("include")) {
      let node = p.startNode()
      p.expect(tt.string)
      node.value = p.value
      p.next()
      p.expectContextual("as")
      node.name = p.parseIdent(true)
      node.included.push(p.finishNode(node, "IncludeDeclaration"))
    } else {
      break
    }
  }

  while (p.type != tt.eof) {
    if (p.eatContextual("skip")) {
      let skip = parseExprChoice(p)
      p.expect(tt.braceL)
      while (!p.eat(tt.braceR))
        parseRule(p, node.rules, false, skip)
    } else if (p.eatContextual("tokens")) {
      p.expect(tt.braceL)
      while (!p.eat(tt.braceR))
        parseRule(p, node.rules, true, null)
    } else {
      parseRule(p, node.rules, false, null)
    }
  }
  return p.finishNode(node, "GrammarDeclaration")
}

function parseRule(p, rules, isToken, skip) {
  let node = p.startNode()
  node.isToken = isToken
  // FIXME Storing the same sub-ast in multiple nodes is a rather
  // weird way to build an AST
  node.skip = skip
  node.context = p.eatContextual("context")
  node.start = p.eatContextual("start")
  node.id = p.parseIdent(true)
  node.params = []
  if (p.eat(tt.parenL)) while (!p.eat(tt.parenR)) {
    if (node.params.length) p.expect(tt.comma)
    node.params.push(p.parseIdent(true))
  }
  if (isToken && node.params.length > 0)
    p.raise(node.params[0].start, "Token rules must not take parameters")
  if (node.id.name in rules)
    p.raise(node.id.start, `Duplicate rule declaration '${node.id.name}'`)
  rules[node.id.name] = node
  p.expect(tt.braceL)
  node.expr = parseExprChoice(p)
  p.expect(tt.braceR)
  node.tokenType = null
  if (!node.context && p.eat(tt.eq)) {
    if (p.type != tt.string) p.unexpected()
    node.tokenType = p.value
    p.next()
  }
  return p.finishNode(node, "RuleDeclaration")
}

function parseExprInner(p) {
  if (p.eat(tt.parenL)) {
    let expr = parseExprChoice(p)
    p.expect(tt.parenR)
    return expr
  }
  let node = p.startNode()
  if (p.type == tt.string) {
    let value = p.value
    p.next()
    if (p.type == tt.plusMin && p.value == "-" && value.length == 1) {
      p.next()
      if (p.type != tt.string || p.value.length != 1) p.unexpected()
      node.from = value
      node.to = p.value
      p.next()
      return p.finishNode(node, "CharacterRange")
    } else {
      if (value.length == 0) p.raise("Empty strings are not valid in grammars")
      node.value = value
      return p.finishNode(node, "StringMatch")
    }
  } else if (p.type == tt._super) {
    p.next()
    return p.finishNode(node, "SuperMatch")
  } else if (p.type == tt.bitwiseAND) {
    p.next()
    node.id = p.parseIdent(true)
    return p.finishNode(node, "PredicateMatch")
  } else if (p.type == tt.name && p.value == "_") {
    p.next()
    return p.finishNode(node, "AnyMatch")
  } else if (p.type == tt.dot) {
    p.next()
    return p.finishNode(node, "DotMatch")
  } else {
    node.id = p.parseIdent(true)
    node.arguments = []
    if (p.start == p.lastTokEnd && p.eat(tt.parenL)) while (!p.eat(tt.parenR)) {
      if (node.arguments.length) p.expect(tt.comma)
      node.arguments.push(parseExprChoice(p))
    }
    return p.finishNode(node, "RuleIdentifier")
  }
}

function parseExprSuffix(p) {
  let start = p.start
  let expr = parseExprInner(p)
  if (p.type == tt.star || p.type == tt.question || p.type == tt.plusMin && p.value == "+") {
    let node = p.startNodeAt(start)
    node.expr = expr
    node.kind = p.type == tt.question ? "?" : p.type == tt.star ? "*" : p.value
    p.next()
    return p.finishNode(node, "RepeatedMatch")
  }
  return expr
}

function parseExprLookahead(p) {
  if (p.type == tt.prefix && (p.value == "!" || p.value == "~")) {
    let node = p.startNode()
    node.kind = p.value
    p.next()
    node.expr = parseExprSuffix(p)
    return p.finishNode(node, "LookaheadMatch")
  } else {
    return parseExprSuffix(p)
  }
}

function endOfSequence(p) {
  return p.type == tt.braceR || p.type == tt.parenR || p.type == tt.bitwiseOR || p.type == tt.braceL || p.type == tt.comma
}

function parseExprSequence(p) {
  let start = p.start, first = parseExprLookahead(p)
  if (endOfSequence(p)) return first
  let node = p.startNodeAt(start)
  node.exprs = [first]
  do { node.exprs.push(parseExprLookahead(p)) }
  while (!endOfSequence(p))
  return p.finishNode(node, "SequenceMatch")
}

function parseExprChoice(p) {
  let start = p.start, left = parseExprSequence(p)
  if (!p.eat(tt.bitwiseOR)) return left
  let node = p.startNodeAt(start)
  node.exprs = [left]
  do { node.exprs.push(parseExprSequence(p)) }
  while (p.eat(tt.bitwiseOR))
  return p.finishNode(node, "ChoiceMatch")
}

plugins.modeGrammar = function(parser) {
  parser.extend("parseTopLevel", () => function(node) {
    return parseGrammar(this, node)
  })
}

module.exports = function(file) {
  return parse(file, {
    plugins: {modeGrammar: true}
  })
}
<commit_msg>Change syntax for token types<commit_after>const {tokTypes: tt, parse, plugins} = require("acorn")

// FIXME Get rid of Acorn now that no actual JavaScript can appear in these files anymore?

function parseGrammar(p, node) {
  node.rules = Object.create(null)
  node.extends = null
  node.included = []

  for (;;) {
    if (p.eat(tt._extends)) {
      if (node.extends) p.raise("Can't extend multiple grammars")
      if (p.type != tt.string) p.unexpected()
      node.extends = p.value
      p.next()
    } else if (p.eatContextual("include")) {
      let node = p.startNode()
      p.expect(tt.string)
      node.value = p.value
      p.next()
      p.expectContextual("as")
      node.name = p.parseIdent(true)
      node.included.push(p.finishNode(node, "IncludeDeclaration"))
    } else {
      break
    }
  }

  while (p.type != tt.eof) {
    if (p.eatContextual("skip")) {
      let skip = parseExprChoice(p)
      p.expect(tt.braceL)
      while (!p.eat(tt.braceR))
        parseRule(p, node.rules, false, skip)
    } else if (p.eatContextual("tokens")) {
      p.expect(tt.braceL)
      while (!p.eat(tt.braceR))
        parseRule(p, node.rules, true, null)
    } else {
      parseRule(p, node.rules, false, null)
    }
  }
  return p.finishNode(node, "GrammarDeclaration")
}

function parseRule(p, rules, isToken, skip) {
  let node = p.startNode()
  node.isToken = isToken
  // FIXME Storing the same sub-ast in multiple nodes is a rather
  // weird way to build an AST
  node.skip = skip
  node.context = p.eatContextual("context")
  node.start = p.eatContextual("start")
  node.id = p.parseIdent(true)
  if (node.id.name in rules)
    p.raise(node.id.start, `Duplicate rule declaration '${node.id.name}'`)
  rules[node.id.name] = node
  node.params = []
  if (p.eat(tt.parenL)) while (!p.eat(tt.parenR)) {
    if (node.params.length) p.expect(tt.comma)
    node.params.push(p.parseIdent(true))
  }
  if (isToken && node.params.length > 0)
    p.raise(node.params[0].start, "Token rules must not take parameters")
  if (p.eat(tt.eq)) {
    if (p.type != tt.string) p.unexpected()
    node.tokenType = p.value
    p.next()
    node.context = true
  } else {
    node.tokenType = null
  }
  p.expect(tt.braceL)
  node.expr = parseExprChoice(p)
  p.expect(tt.braceR)
  return p.finishNode(node, "RuleDeclaration")
}

function parseExprInner(p) {
  if (p.eat(tt.parenL)) {
    let expr = parseExprChoice(p)
    p.expect(tt.parenR)
    return expr
  }
  let node = p.startNode()
  if (p.type == tt.string) {
    let value = p.value
    p.next()
    if (p.type == tt.plusMin && p.value == "-" && value.length == 1) {
      p.next()
      if (p.type != tt.string || p.value.length != 1) p.unexpected()
      node.from = value
      node.to = p.value
      p.next()
      return p.finishNode(node, "CharacterRange")
    } else {
      if (value.length == 0) p.raise("Empty strings are not valid in grammars")
      node.value = value
      return p.finishNode(node, "StringMatch")
    }
  } else if (p.type == tt._super) {
    p.next()
    return p.finishNode(node, "SuperMatch")
  } else if (p.type == tt.bitwiseAND) {
    p.next()
    node.id = p.parseIdent(true)
    return p.finishNode(node, "PredicateMatch")
  } else if (p.type == tt.name && p.value == "_") {
    p.next()
    return p.finishNode(node, "AnyMatch")
  } else if (p.type == tt.dot) {
    p.next()
    return p.finishNode(node, "DotMatch")
  } else {
    node.id = p.parseIdent(true)
    node.arguments = []
    if (p.start == p.lastTokEnd && p.eat(tt.parenL)) while (!p.eat(tt.parenR)) {
      if (node.arguments.length) p.expect(tt.comma)
      node.arguments.push(parseExprChoice(p))
    }
    return p.finishNode(node, "RuleIdentifier")
  }
}

function parseExprSuffix(p) {
  let start = p.start
  let expr = parseExprInner(p)
  if (p.type == tt.star || p.type == tt.question || p.type == tt.plusMin && p.value == "+") {
    let node = p.startNodeAt(start)
    node.expr = expr
    node.kind = p.type == tt.question ? "?" : p.type == tt.star ? "*" : p.value
    p.next()
    return p.finishNode(node, "RepeatedMatch")
  }
  return expr
}

function parseExprLookahead(p) {
  if (p.type == tt.prefix && (p.value == "!" || p.value == "~")) {
    let node = p.startNode()
    node.kind = p.value
    p.next()
    node.expr = parseExprSuffix(p)
    return p.finishNode(node, "LookaheadMatch")
  } else {
    return parseExprSuffix(p)
  }
}

function endOfSequence(p) {
  return p.type == tt.braceR || p.type == tt.parenR || p.type == tt.bitwiseOR || p.type == tt.braceL || p.type == tt.comma
}

function parseExprSequence(p) {
  let start = p.start, first = parseExprLookahead(p)
  if (endOfSequence(p)) return first
  let node = p.startNodeAt(start)
  node.exprs = [first]
  do { node.exprs.push(parseExprLookahead(p)) }
  while (!endOfSequence(p))
  return p.finishNode(node, "SequenceMatch")
}

function parseExprChoice(p) {
  let start = p.start, left = parseExprSequence(p)
  if (!p.eat(tt.bitwiseOR)) return left
  let node = p.startNodeAt(start)
  node.exprs = [left]
  do { node.exprs.push(parseExprSequence(p)) }
  while (p.eat(tt.bitwiseOR))
  return p.finishNode(node, "ChoiceMatch")
}

plugins.modeGrammar = function(parser) {
  parser.extend("parseTopLevel", () => function(node) {
    return parseGrammar(this, node)
  })
}

module.exports = function(file) {
  return parse(file, {
    plugins: {modeGrammar: true}
  })
}
<|endoftext|>


<commit_before>import render from './render'
import virtualNodesByElement from './virtual-nodes-by-element'

export default function patch (element, newVirtualNode) {
  const oldVirtualNode = virtualNodesByElement.get(element)
  if (!oldVirtualNode) throw new Error('No virtual node found for element. You can currently only patch elements produced via the render or patch functions.')
  patchVirtualNode(oldVirtualNode, newVirtualNode)
}

function patchVirtualNode (oldVirtualNode, newVirtualNode) {
  const element = oldVirtualNode.element
  patchAttributes(element, oldVirtualNode.props, newVirtualNode.props)
  patchChildren(element, oldVirtualNode.children, newVirtualNode.children)
  newVirtualNode.element = element
}

function patchAttributes(element, oldProps, newProps) {
  for (let prop in oldProps) {
    if (!(prop in newProps)) element.removeAttribute(prop)
  }
  for (let prop in newProps) {
    const newValue = newProps[prop]
    if (newValue !== oldProps[prop]) element.setAttribute(prop, newValue)
  }
}

function patchChildren (parentElement, oldChildren, newChildren) {
  let oldStartIndex = 0
  let oldEndIndex = oldChildren.length - 1
  let oldStartChild = oldChildren[0]
  let oldEndChild = oldChildren[oldEndIndex]

  let newStartIndex = 0
  let newEndIndex = newChildren.length - 1
  let newStartChild = newChildren[0]
  let newEndChild = newChildren[newEndIndex]

  let oldIndicesByKey

  while (oldStartIndex <= oldEndIndex && newStartIndex <= newEndIndex) {
    if (!oldStartChild) {
      oldStartChild = oldChildren[++oldStartIndex]
    } else if (!oldEndChild) {
      oldEndChild = oldChildren[--oldEndIndex]
    } else if (keysEqual(oldStartChild, newStartChild)) {
      patchVirtualNode(oldStartChild, newStartChild)
      oldStartChild = oldChildren[++oldStartIndex]
      newStartChild = newChildren[++newStartIndex]
    } else if (keysEqual(oldEndChild, newEndChild)) {
      patchVirtualNode(oldEndChild, newEndChild)
      oldEndChild = oldChildren[--oldEndIndex]
      newEndChild = newChildren[--newEndIndex]
    } else if (keysEqual(oldStartChild, newEndChild)) {
      patchVirtualNode(oldStartChild, newEndChild)
      parentElement.insertBefore(oldStartChild.element, oldEndChild.element.nextSibling)
      oldStartChild = oldChildren[++oldStartIndex]
      newEndChild = newChildren[--newEndIndex]
    } else if (keysEqual(oldEndChild, newStartChild)) {
      patchVirtualNode(oldEndChild, newStartChild)
      parentElement.insertBefore(oldEndChild.element, oldStartChild.element);
      oldEndChild = oldChildren[--oldEndIndex]
      newStartChild = newChildren[++newStartIndex]
    } else {
      if (!oldIndicesByKey) oldIndicesByKey = mapOldKeysToIndices(oldChildren, oldStartIndex, oldEndIndex)
      const oldIndex = oldIndicesByKey[newStartChild.key]
      if (oldIndex == null) {
        parentElement.insertBefore(render(newStartChild), oldStartChild.element)
        newStartChild = newChildren[++newStartIndex]
      } else {
        const oldChildToMove = oldChildren[oldIndex]
        patchVirtualNode(oldChildToMove, newStartChild)
        oldChildren[oldIndex] = undefined
        parentElement.insertBefore(oldChildToMove.element, oldStartChild.element)
        newStartChild = newChildren[++newStartIndex]
      }
    }
  }

  if (oldStartIndex > oldEndIndex) {
    const subsequentElement = newChildren[newEndIndex + 1] ? newChildren[newEndIndex + 1].element : null
    for (let i = newStartIndex; i <= newEndIndex; i++) {
      parentElement.insertBefore(render(newChildren[i]), subsequentElement)
    }
  } else if (newStartIndex > newEndIndex) {
    for (let i = oldStartIndex; i <= oldEndIndex; i++) {
      oldChildren[i].element.remove()
    }
  }
}

function keysEqual (oldVirtualNode, newVirtualNode) {
  return (
    oldVirtualNode.props
      && newVirtualNode.props
      && oldVirtualNode.props.key === newVirtualNode.props.key
  )
}

function mapOldKeysToIndices (children, startIndex, endIndex) {
  let oldIndicesByKey = {}
  for (let i = startIndex; i <= endIndex; i++) {
    const key = children[i].key
    if (key) oldIndicesByKey[key] = i
  }
  return oldIndicesByKey;
}
<commit_msg>Fix key handling<commit_after>import render from './render'
import virtualNodesByElement from './virtual-nodes-by-element'

export default function patch (element, newVirtualNode) {
  const oldVirtualNode = virtualNodesByElement.get(element)
  if (!oldVirtualNode) throw new Error('No virtual node found for element. You can currently only patch elements produced via the render or patch functions.')
  patchVirtualNode(oldVirtualNode, newVirtualNode)
}

function patchVirtualNode (oldVirtualNode, newVirtualNode) {
  const element = oldVirtualNode.element
  patchAttributes(element, oldVirtualNode.props, newVirtualNode.props)
  patchChildren(element, oldVirtualNode.children, newVirtualNode.children)
  newVirtualNode.element = element
}

function patchAttributes(element, oldProps, newProps) {
  for (let prop in oldProps) {
    if (!(prop in newProps)) element.removeAttribute(prop)
  }
  for (let prop in newProps) {
    const newValue = newProps[prop]
    if (newValue !== oldProps[prop]) element.setAttribute(prop, newValue)
  }
}

function patchChildren (parentElement, oldChildren, newChildren) {
  let oldStartIndex = 0
  let oldEndIndex = oldChildren.length - 1
  let oldStartChild = oldChildren[0]
  let oldEndChild = oldChildren[oldEndIndex]

  let newStartIndex = 0
  let newEndIndex = newChildren.length - 1
  let newStartChild = newChildren[0]
  let newEndChild = newChildren[newEndIndex]

  let oldIndicesByKey

  while (oldStartIndex <= oldEndIndex && newStartIndex <= newEndIndex) {
    if (!oldStartChild) {
      oldStartChild = oldChildren[++oldStartIndex]
    } else if (!oldEndChild) {
      oldEndChild = oldChildren[--oldEndIndex]
    } else if (isEqual(oldStartChild, newStartChild)) {
      patchVirtualNode(oldStartChild, newStartChild)
      oldStartChild = oldChildren[++oldStartIndex]
      newStartChild = newChildren[++newStartIndex]
    } else if (isEqual(oldEndChild, newEndChild)) {
      patchVirtualNode(oldEndChild, newEndChild)
      oldEndChild = oldChildren[--oldEndIndex]
      newEndChild = newChildren[--newEndIndex]
    } else if (isEqual(oldStartChild, newEndChild)) {
      patchVirtualNode(oldStartChild, newEndChild)
      parentElement.insertBefore(oldStartChild.element, oldEndChild.element.nextSibling)
      oldStartChild = oldChildren[++oldStartIndex]
      newEndChild = newChildren[--newEndIndex]
    } else if (isEqual(oldEndChild, newStartChild)) {
      patchVirtualNode(oldEndChild, newStartChild)
      parentElement.insertBefore(oldEndChild.element, oldStartChild.element);
      oldEndChild = oldChildren[--oldEndIndex]
      newStartChild = newChildren[++newStartIndex]
    } else {
      if (!oldIndicesByKey) oldIndicesByKey = mapOldKeysToIndices(oldChildren, oldStartIndex, oldEndIndex)
      const key = getKey(newStartChild)
      const oldIndex = key ? oldIndicesByKey[key] : null
      if (oldIndex == null) {
        parentElement.insertBefore(render(newStartChild), oldStartChild.element)
        newStartChild = newChildren[++newStartIndex]
      } else {
        const oldChildToMove = oldChildren[oldIndex]
        patchVirtualNode(oldChildToMove, newStartChild)
        oldChildren[oldIndex] = undefined
        parentElement.insertBefore(oldChildToMove.element, oldStartChild.element)
        newStartChild = newChildren[++newStartIndex]
      }
    }
  }

  if (oldStartIndex > oldEndIndex) {
    const subsequentElement = newChildren[newEndIndex + 1] ? newChildren[newEndIndex + 1].element : null
    for (let i = newStartIndex; i <= newEndIndex; i++) {
      parentElement.insertBefore(render(newChildren[i]), subsequentElement)
    }
  } else if (newStartIndex > newEndIndex) {
    for (let i = oldStartIndex; i <= oldEndIndex; i++) {
      const child = oldChildren[i]
      if (child) child.element.remove()
    }
  }
}

function isEqual (oldVirtualNode, newVirtualNode) {
  return (
    getKey(oldVirtualNode) === getKey(newVirtualNode)
      && oldVirtualNode.tag === newVirtualNode.tag
  )
}

function getKey (virtualNode) {
  return virtualNode.props ? virtualNode.props.key : null
}

function mapOldKeysToIndices (children, startIndex, endIndex) {
  let oldIndicesByKey = {}
  for (let i = startIndex; i <= endIndex; i++) {
    const key = getKey(children[i])
    if (key) oldIndicesByKey[key] = i
  }
  return oldIndicesByKey;
}
<|endoftext|>


<commit_before>var fs = require('fs-extra')
var c = require('chalk')
var path = require('path')
var isDir = require('is-directory')
var util = require(__dirname + '/util')
var conceptsDir = process.cwd() + '/concepts'
var dialectsDir = process.cwd() + '/dialects'

module.exports = function (argv) {

  if (argv._.length < 2) {
    console.log(c.red('\n Invalid format\n'))
    console.log(' Use the format ' + c.bold('tani add <path> [content]'))
    console.log(' Ex: tani add n "Sky"')
    console.log(' Ex: tani add n/animals@2 "Mithun"')
    return console.log(' Ex: tani add n/animals "Elephant"\n')
  }

  var conceptPath
  var conceptIndex
  var fileName
  var newConceptFilePath
  var concept = argv._[2]

  var pathArray = argv._[1].split('@')
  if (pathArray.length === 2) {
    conceptPath = pathArray[0]
    conceptIndex = pathArray[1]
  } else {
    conceptPath = argv._[1]
  }

  var targetConceptDir = conceptsDir + '/' + conceptPath
  if (!conceptIndex) {
    conceptIndex = getNextFileId(targetConceptDir)
  }

  fileName = conceptIndex + '.txt'
  newConceptFilePath = targetConceptDir + '/' + fileName

  fs.ensureFileSync(newConceptFilePath)
  if (concept) fs.writeFileSync(newConceptFilePath, concept + '\n')

}

// when a file edited or added in concepts, reflect the change in the dialects
function updateDialects(conceptFilePath) {

}

// get the autoincremented next id for a file in a dir
function getNextFileId(targetDir) {

  var highestNumber = 0
  fs.readdirSync(targetDir).forEach(function (file) {
    var filePath = targetDir + '/' + file
    if (!isDir.sync(filePath)) {
      var candidate = parseInt(file)
      if (candidate > highestNumber) {
        highestNumber = candidate
      }
    }
  })

  return ++highestNumber

}
<commit_msg>add concept at an index<commit_after>var fs = require('fs-extra')
var c = require('chalk')
var path = require('path')
var isDir = require('is-directory')
var util = require(__dirname + '/util')
var conceptsDir = process.cwd() + '/concepts'
var dialectsDir = process.cwd() + '/dialects'

module.exports = function (argv) {

  if (argv._.length < 2) {
    console.log(c.red('\n Invalid format\n'))
    console.log(' Use the format ' + c.bold('tani add <path> [content]'))
    console.log(' Ex: tani add n "Sky"')
    console.log(' Ex: tani add n/animals@2 "Mithun"')
    return console.log(' Ex: tani add n/animals "Elephant"\n')
  }

  var conceptPath
  var conceptIndex
  var indexSpecified = false
  var fileName
  var newConceptFilePath
  var concept = argv._[2]

  var pathArray = argv._[1].split('@')
  if (pathArray.length === 2) {
    conceptPath = pathArray[0]
    conceptIndex = pathArray[1]
    indexSpecified = true
  } else {
    conceptPath = argv._[1]
  }

  var targetConceptDir = conceptsDir + '/' + conceptPath
  var conceptIndexCandidate = getNextFileId(targetConceptDir)

  if (indexSpecified) {
    // concept Index can't be more than the immediate highest number
    if (conceptIndex > conceptIndexCandidate) {
      conceptIndex = conceptIndexCandidate
      indexSpecified = false
    }
  } else {
    conceptIndex = conceptIndexCandidate
  }

  fileName = conceptIndex + '.txt'
  newConceptFilePath = targetConceptDir + '/' + fileName

  // if the dir does not exist
  fs.mkdirpSync(targetConceptDir)

  if (indexSpecified) {
    incrementFileNames(targetConceptDir, conceptIndex, conceptIndexCandidate - 1)
  }

  fs.ensureFileSync(newConceptFilePath)
  if (concept) fs.writeFileSync(newConceptFilePath, concept + '\n')

}

// when a file edited or added in concepts, reflect the change in the dialects
function incrementFileNames(targetDir, startingIndex, currentHighestIndex) {

  if (!currentHighestIndex) currentHighestIndex = getNextFileId(targetDir) - 1

  while (currentHighestIndex >= startingIndex) {
    //console.log(currentHighestIndex, ' to ', currentHighestIndex + 1)
    var oldName = targetDir + '/' + currentHighestIndex + '.txt'
    var newName = targetDir + '/' + (currentHighestIndex + 1) + '.txt'
    fs.renameSync(oldName, newName)
    currentHighestIndex--
  }

}

// get the autoincremented next id for a file in a dir
function getNextFileId(targetDir) {

  if (!fs.existsSync(targetDir)) return 1;

  var highestNumber = 0
  fs.readdirSync(targetDir).forEach(function (file) {
    var filePath = targetDir + '/' + file
    if (!isDir.sync(filePath)) {
      var candidate = parseInt(file)
      if (candidate > highestNumber) {
        highestNumber = candidate
      }
    }
  })

  return ++highestNumber

}
<|endoftext|>


<commit_before>var readOSMXAPI = (function() {

    function isBuilding(data) {
        var tags = data.tags;
        return (tags &&
            !tags.landuse &&
            (tags.building || tags['building:part']) &&
            (!tags.layer || tags.layer >= 0));
    }

//  living:'bricks',
//  nonliving:'tar_paper',
//  worship:'copper'

//    function getBuildingType(tags) {
//        if (tags.amenity === 'place_of_worship') {
//            return 'worship';
//        }
//
//        var type = tags.building;
//        if (type === 'yes' || type === 'roof') {
//            type = tags['building:use'];
//        }
//        if (!type) {
//            type = tags.amenity;
//        }
//
//        switch (type) {
//            case 'apartments':
//            case 'house':
//            case 'residential':
//            case 'hut':
//                return 'living';
//            case 'church':
//                return 'worship';
//        }
//
//        return 'nonliving';
//    }

    function getRelationWays(members) {
        var m, outer, inner = [];
        for (var i = 0, il = members.length; i < il; i++) {
            m = members[i];
            if (m.type !== 'way' || !ways[m.ref]) {
                continue;
            }
            if (!m.role || m.role === 'outer') {
                outer = ways[m.ref];
                continue;
            }
            if (m.role === 'inner' || m.role === 'enclave') {
                inner.push(ways[m.ref]);
                continue;
            }
        }
        if (!outer || !outer.tags) {
            return;
        }
        return { outer:outer, inner:inner };
    }

    function getFootprint(points) {
        if (!points) {
            return;
        }

        var footprint = [], p;
        for (var i = 0, il = points.length; i < il; i++) {
            p = nodes[ points[i] ];
            footprint.push(p[0], p[1]);
        }

        // do not close polygon yet
        if (footprint[footprint.length-2] !== footprint[0] && footprint[footprint.length-1] !== footprint[1]) {
            footprint.push(footprint[0], footprint[1]);
        }

        // can't span a polygon with just 2 points (+ start & end)
        if (footprint.length < 8) {
            return;
        }

        return footprint;
    }

    function mergeItems(dst, src) {
        for (var p in src) {
            if (!dst[p]) {
                dst[p] = src[p];
            }
        }
        return dst;
    }

    function filterItem(item, footprint) {
        var res = {},
            tags = item.tags;

        if (item.id) {
            res.id = item.id;
        }

        if (footprint) {
            res.footprint = Import.windOuterPolygon(footprint);
        }

        if (tags.height) {
            res.height = Import.toMeters(tags.height);
        }
        if (!res.height && tags['building:height']) {
            res.height = Import.toMeters(tags['building:height']);
        }

        if (!res.height && tags.levels) {
            res.height = tags.levels*Import.METERS_PER_LEVEL <<0;
        }
        if (!res.height && tags['building:levels']) {
            res.height = tags['building:levels']*Import.METERS_PER_LEVEL <<0;
        }

        // min_height
        if (tags.min_height) {
            res.minHeight = Import.toMeters(tags.min_height);
        }
        if (!res.minHeight && tags['building:min_height']) {
            res.minHeight = Import.toMeters(tags['building:min_height']);
        }

        if (!res.minHeight && tags.min_level) {
            res.minHeight = tags.min_level*Import.METERS_PER_LEVEL <<0;
        }
        if (!res.minHeight && tags['building:min_level']) {
            res.minHeight = tags['building:min_level']*Import.METERS_PER_LEVEL <<0;
        }

        // wall material
        if (tags['building:material']) {
            res.wallColor = Import.getMaterialColor(tags['building:material']);
        }
        if (tags['building:facade:material']) {
            res.wallColor = Import.getMaterialColor(tags['building:facade:material']);
        }
        if (tags['building:cladding']) {
            res.wallColor = Import.getMaterialColor(tags['building:cladding']);
        }
        // wall color
        if (tags['building:color']) {
            res.wallColor = tags['building:color'];
        }
        if (tags['building:colour']) {
            res.wallColor = tags['building:colour'];
        }

        // roof material
        if (tags['roof:material']) {
            res.roofColor = Import.getMaterialColor(tags['roof:material']);
        }
        if (tags['building:roof:material']) {
            res.roofColor = Import.getMaterialColor(tags['building:roof:material']);
        }
        // roof color
        if (tags['roof:color']) {
            res.roofColor = tags['roof:color'];
        }
        if (tags['roof:colour']) {
            res.roofColor = tags['roof:colour'];
        }
        if (tags['building:roof:color']) {
            res.roofColor = tags['building:roof:color'];
        }
        if (tags['building:roof:colour']) {
            res.roofColor = tags['building:roof:colour'];
        }

        res.height = res.height || Import.DEFAULT_HEIGHT;

        if (tags['roof:shape'] === 'dome' || tags['building:shape'] === 'cylinder' || tags['building:shape'] === 'sphere') {
            res.shape = 'cylinder';
            res.radius = Import.getRadius(res.footprint);
            if (tags['roof:shape'] === 'dome' && tags['roof:height']) {
                res.roofShape = 'cylinder';
                res.roofHeight = Import.toMeters(tags['roof:height']);
                res.height = max(0, res.height-res.roofHeight);
            }
        }

        return res;
    }

    function processNode(node) {
        nodes[node.id] = [node.lat, node.lon];
    }

    function processWay(way) {
        if (isBuilding(way)) {
            var item, footprint;
            if ((footprint = getFootprint(way.nodes))) {
                item = filterItem(way, footprint);
                res.push(item);
            }
            return;
        }

        var tags = way.tags;
        if (!tags || (!tags.highway && !tags.railway && !tags.landuse)) { // TODO: add more filters
            ways[way.id] = way;
        }
    }

    function processRelation(relation) {
        var relationWays, outerWay, holes = [],
            item, relItem, outerFootprint, innerFootprint;

        if (!isBuilding(relation) || (relation.tags.type !== 'multipolygon' && relation.tags.type !== 'building')) {
            return;
        }

        if ((relationWays = getRelationWays(relation.members))) {
            relItem = filterItem(relation);
            if ((outerWay = relationWays.outer)) {
                if ((outerFootprint = getFootprint(outerWay.nodes))) {
                    item = filterItem(outerWay, outerFootprint);
                    for (var i = 0, il = relationWays.inner.length; i < il; i++) {
                        if ((innerFootprint = getFootprint(relationWays.inner[i].nodes))) {
                            holes.push(Import.windInnerPolygon(innerFootprint));
                        }
                    }
                    if (holes.length) {
                        item.holes = holes;
                    }
                    res.push(mergeItems(item, relItem));
                }
            }
        }
    }

    var nodes, ways, res;

    return function(data) {
        nodes = {};
        ways = {};
        res = [];

        var item;
        for (var i = 0, il = data.length; i < il; i++) {
            item = data[i];
            switch(item.type ) {
                case 'node':     processNode(item);     break;
                case 'way':      processWay(item);      break;
                case 'relation': processRelation(item); break;
            }
        }

        return res;
    };
})();
<commit_msg>tiny cleanup<commit_after>var readOSMXAPI = (function() {

    function isBuilding(data) {
        var tags = data.tags;
        return (tags &&
            !tags.landuse &&
            (tags.building || tags['building:part']) &&
            (!tags.layer || tags.layer >= 0));
    }

//  living:'bricks',
//  nonliving:'tar_paper',
//  worship:'copper'

//    function getBuildingType(tags) {
//        if (tags.amenity === 'place_of_worship') {
//            return 'worship';
//        }
//
//        var type = tags.building;
//        if (type === 'yes' || type === 'roof') {
//            type = tags['building:use'];
//        }
//        if (!type) {
//            type = tags.amenity;
//        }
//
//        switch (type) {
//            case 'apartments':
//            case 'house':
//            case 'residential':
//            case 'hut':
//                return 'living';
//            case 'church':
//                return 'worship';
//        }
//
//        return 'nonliving';
//    }

    function getRelationWays(members) {
        var m, outer, inner = [];
        for (var i = 0, il = members.length; i < il; i++) {
            m = members[i];
            if (m.type !== 'way' || !ways[m.ref]) {
                continue;
            }
            if (!m.role || m.role === 'outer') {
                outer = ways[m.ref];
                continue;
            }
            if (m.role === 'inner' || m.role === 'enclave') {
                inner.push(ways[m.ref]);
                continue;
            }
        }
        if (outer && outer.tags) {
            return { outer:outer, inner:inner };
        }
    }

    function getFootprint(points) {
        if (!points) {
            return;
        }

        var footprint = [], p;
        for (var i = 0, il = points.length; i < il; i++) {
            p = nodes[ points[i] ];
            footprint.push(p[0], p[1]);
        }

        // do not close polygon yet
        if (footprint[footprint.length-2] !== footprint[0] && footprint[footprint.length-1] !== footprint[1]) {
            footprint.push(footprint[0], footprint[1]);
        }

        // can't span a polygon with just 2 points (+ start & end)
        if (footprint.length < 8) {
            return;
        }

        return footprint;
    }

    function mergeItems(dst, src) {
        for (var p in src) {
            if (!dst[p]) {
                dst[p] = src[p];
            }
        }
        return dst;
    }

    function filterItem(item, footprint) {
        var res = {},
            tags = item.tags;

        if (item.id) {
            res.id = item.id;
    }

        if (footprint) {
            res.footprint = Import.windOuterPolygon(footprint);
        }

        if (tags.height) {
            res.height = Import.toMeters(tags.height);
        }
        if (!res.height && tags['building:height']) {
            res.height = Import.toMeters(tags['building:height']);
        }

        if (!res.height && tags.levels) {
            res.height = tags.levels*Import.METERS_PER_LEVEL <<0;
        }
        if (!res.height && tags['building:levels']) {
            res.height = tags['building:levels']*Import.METERS_PER_LEVEL <<0;
        }

        // min_height
        if (tags.min_height) {
            res.minHeight = Import.toMeters(tags.min_height);
        }
        if (!res.minHeight && tags['building:min_height']) {
            res.minHeight = Import.toMeters(tags['building:min_height']);
        }

        if (!res.minHeight && tags.min_level) {
            res.minHeight = tags.min_level*Import.METERS_PER_LEVEL <<0;
        }
        if (!res.minHeight && tags['building:min_level']) {
            res.minHeight = tags['building:min_level']*Import.METERS_PER_LEVEL <<0;
        }

        // wall material
        if (tags['building:material']) {
            res.wallColor = Import.getMaterialColor(tags['building:material']);
        }
        if (tags['building:facade:material']) {
            res.wallColor = Import.getMaterialColor(tags['building:facade:material']);
        }
        if (tags['building:cladding']) {
            res.wallColor = Import.getMaterialColor(tags['building:cladding']);
        }
        // wall color
        if (tags['building:color']) {
            res.wallColor = tags['building:color'];
        }
        if (tags['building:colour']) {
            res.wallColor = tags['building:colour'];
        }

        // roof material
        if (tags['roof:material']) {
            res.roofColor = Import.getMaterialColor(tags['roof:material']);
        }
        if (tags['building:roof:material']) {
            res.roofColor = Import.getMaterialColor(tags['building:roof:material']);
        }
        // roof color
        if (tags['roof:color']) {
            res.roofColor = tags['roof:color'];
        }
        if (tags['roof:colour']) {
            res.roofColor = tags['roof:colour'];
        }
        if (tags['building:roof:color']) {
            res.roofColor = tags['building:roof:color'];
        }
        if (tags['building:roof:colour']) {
            res.roofColor = tags['building:roof:colour'];
        }

        res.height = res.height || Import.DEFAULT_HEIGHT;

        if (tags['roof:shape'] === 'dome' || tags['building:shape'] === 'cylinder' || tags['building:shape'] === 'sphere') {
            res.shape = 'cylinder';
            res.radius = Import.getRadius(res.footprint);
            if (tags['roof:shape'] === 'dome' && tags['roof:height']) {
                res.roofShape = 'cylinder';
                res.roofHeight = Import.toMeters(tags['roof:height']);
                res.height = max(0, res.height-res.roofHeight);
            }
        }

        return res;
    }

    function processNode(node) {
        nodes[node.id] = [node.lat, node.lon];
    }

    function processWay(way) {
        if (isBuilding(way)) {
            var item, footprint;
            if ((footprint = getFootprint(way.nodes))) {
                item = filterItem(way, footprint);
                res.push(item);
            }
            return;
        }

        var tags = way.tags;
        if (!tags || (!tags.highway && !tags.railway && !tags.landuse)) { // TODO: add more filters
            ways[way.id] = way;
        }
    }

    function processRelation(relation) {
        var relationWays, outerWay, holes = [],
            item, relItem, outerFootprint, innerFootprint;

        if (!isBuilding(relation) || (relation.tags.type !== 'multipolygon' && relation.tags.type !== 'building')) {
            return;
        }

        if ((relationWays = getRelationWays(relation.members))) {
            relItem = filterItem(relation);
            if ((outerWay = relationWays.outer)) {
                if ((outerFootprint = getFootprint(outerWay.nodes))) {
                    item = filterItem(outerWay, outerFootprint);
                    for (var i = 0, il = relationWays.inner.length; i < il; i++) {
                        if ((innerFootprint = getFootprint(relationWays.inner[i].nodes))) {
                            holes.push(Import.windInnerPolygon(innerFootprint));
                        }
                    }
                    if (holes.length) {
                        item.holes = holes;
                    }
                    res.push(mergeItems(item, relItem));
                }
            }
        }
    }

    var nodes, ways, res;

    return function(data) {
        nodes = {};
        ways = {};
        res = [];

        var item;
        for (var i = 0, il = data.length; i < il; i++) {
            item = data[i];
            switch(item.type ) {
                case 'node':     processNode(item);     break;
                case 'way':      processWay(item);      break;
                case 'relation': processRelation(item); break;
            }
        }

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


<commit_before>'use strict';

var R = require('ramda');

module.exports = function and (left, right, options) {
  if (arguments.length < 3) {
    throw new Error('The "or" helper needs two arguments.');
  }
  return R.and(left, right) ?
    options.fn(this) : options.inverse(this);
}
<commit_msg>Add comment docs for "and" helper<commit_after>'use strict';

var R = require('ramda');

/**
 * Output a block (or its inverse) based on whether or not both of the suppied
 * arguments are truthy.
 *
 * @since v0.0.1
 * @param {*} left
 * @param {*} right
 * @param {Object} options
 * @throws {Error} An error is thrown when the `right` argument is missing.
 * @return {String}
 * @example
 *
 *  var a = true;
 *  var b = 1;
 *  var c = false;
 *
 *  {{#and a b}}✔{{else}}✘{{/and}} //=> ✔
 *  {{#and b c}}✔{{else}}✘{{/and}} //=> ✘
 */

module.exports = function and (left, right, options) {
  if (arguments.length < 3) {
    throw new Error('The "or" helper needs two arguments.');
  }
  return R.and(left, right) ?
    options.fn(this) : options.inverse(this);
}
<|endoftext|>