<commit_before>/*
 * FirebugUJS Client-side Library
 *
 *
 * Overview:
 *
 *   To keep track of DOM elements that have events bound to them,
 *   we override the event binding method(s) used by different
 *   javascript libraries and keep track of the DOM elements and
 *   the events that get bound to them.
 *
 *   To do this (and to make this information safely accessible to
 *   the firefox extension), we add a custom attribute to all DOM
 *   elements with events, which holds the event information.
 *
 *
 * To Do:
 *
 *   Instead of overriding the event binding methods of different
 *   javascript libraries, we should try to override the native
 *   javascript functions, if possible, so this is more library agnostic.
 *
 */
if ( FirebugUJS == null ) {

  console.log('FirebugUJS: loading client-side javascript');

  // global

  var FirebugUJS = {

    event_bound_to_element: function( element, event_type, event_function ) {
      if ( element && event_type && event_function ) {
        if (event_function.the_function != null)
          event_function = event_function.the_function;
        //console.log('event_bound_to_element: ' + element + ':' + event_type + ' => ' + event_function );
        console.log('FirebugUJS: event_bound_to_element: ' + element + ':' + event_type );
        if ( element.getAttribute('ujs') == null )
          element.setAttribute('ujs', '');
        element.setAttribute('ujs', element.getAttribute('ujs') + event_type + ':' + event_function + '|' );
      }
    }

  };

  // jQuery

  if ( window.jQuery ) {
    console.log('FirebugUJS: loading jQuery module');
    jQuery.fn.original_bind = jQuery.fn.bind;

    jQuery.fn.extend({
        bind: function( type, data, fn ) {
          FirebugUJS.event_bound_to_element( this[0], type, data );
          return this.original_bind( type, data, fn );
        }
      });
  }

  // LowPro

  if ( window.Event && window.Event.addBehavior ) {
    console.log('FirebugUJS: loading LowPro module');

    FirebugUJS.LowPro = {
      original: {
        _wrapObserver: window.Event.addBehavior._wrapObserver
      }
    };

    window.Event.addBehavior._wrapObserver = function(observer) {
      var wrapped_observer = FirebugUJS.LowPro.original._wrapObserver(observer);
      wrapped_observer.the_function = (observer.the_function == null) ? observer : observer.the_function;
      return wrapped_observer;
    }

    Event.observe_old = Event.observe;
    Element.addMethods({
        observe: function(element, eventName, handler) {
          FirebugUJS.event_bound_to_element( element, eventName, handler );
          Event.observe_old( element, eventName, handler );
        }
      });
  }

  // Prototype

  if ( window.Prototype ) {
    console.log('FiregubUJS: loading Prototype module');

    Event.observe_old = Event.observe;
    Element.addMethods({
        observe: function(element, eventName, handler) {
          FirebugUJS.event_bound_to_element( element, eventName, handler );
          Event.observe_old( element, eventName, handler );
        }
      });
  }

}
<commit_msg>basically added some more logging to help with debugging.  sorry, there isn't a way to disable the logging at the moment!  i will try to get Firebug options working (and this debugging will be off by default)<commit_after>/*
 * FirebugUJS Client-side Library
 *
 *
 * Overview:
 *
 *   To keep track of DOM elements that have events bound to them,
 *   we override the event binding method(s) used by different
 *   javascript libraries and keep track of the DOM elements and
 *   the events that get bound to them.
 *
 *   To do this (and to make this information safely accessible to
 *   the firefox extension), we add a custom attribute to all DOM
 *   elements with events, which holds the event information.
 *
 *
 * To Do:
 *
 *   Instead of overriding the event binding methods of different
 *   javascript libraries, we should try to override the native
 *   javascript functions, if possible, so this is more library agnostic.
 *
 */
if ( FirebugUJS == null ) {

  // sometimes this code gets executed by the browser before Firebug
  // has loaded the console object - there might be a way to fix this
  // but, for now, just define a mock console.log function
  if (window.console == null) {
    window.console = {
      log: function(){ /* do nothing */ }
    };
  }

  console.log('FirebugUJS: loading client-side javascript');

  // global

  var FirebugUJS = {

    event_bound_to_element: function( element, event_type, event_function ) {
      if ( element && event_type && event_function ) {
        if (event_function.the_function != null)
          event_function = event_function.the_function;

        console.log('FirebugUJS: ' + event_type + ' event bound to element: ' + element);

        // console.log('FirebugUJS: ' + event_type + ' event bound to element: ' );
        // console.log( element );
        // console.log('');

        if ( element.getAttribute('ujs') == null )
          element.setAttribute('ujs', '');
        element.setAttribute('ujs', element.getAttribute('ujs') + event_type + ':' + event_function + '|' );
      }
    }

  };

  // jQuery

  if ( window.jQuery ) {
    console.log('FirebugUJS: loading jQuery module');
    jQuery.fn.original_bind = jQuery.fn.bind;

    jQuery.fn.extend({
        bind: function( type, data, fn ) {
          console.log('FirebugUJS:   [jQuery] ' + type + ' event bound to ' + this[0]);
          FirebugUJS.event_bound_to_element( this[0], type, data );
          return this.original_bind( type, data, fn );
        }
      });
  }

  // Prototype

  if ( window.Prototype ) {
    console.log('FiregubUJS: loading Prototype module');

    Event.observe_old = Event.observe;
    Element.addMethods({
        observe: function(element, eventName, handler) {
          console.log('FirebugUJS:   [Prototype] ' + eventName + ' event bound to ' + element);
          FirebugUJS.event_bound_to_element( element, eventName, handler );
          Event.observe_old( element, eventName, handler );
        }
      });
  }

  // LowPro

  if ( window.Event && window.Event.addBehavior ) {
    console.log('FirebugUJS: loading LowPro module');

    FirebugUJS.LowPro = {
      original: {
        _wrapObserver: window.Event.addBehavior._wrapObserver
      }
    };

    window.Event.addBehavior._wrapObserver = function(observer) {
      var wrapped_observer = FirebugUJS.LowPro.original._wrapObserver(observer);
      wrapped_observer.the_function = (observer.the_function == null) ? observer : observer.the_function;
      return wrapped_observer;
    }
  }

}
<|endoftext|>


<commit_before>this.CAL = this.CAL || {};

this.CAL.gamex = this.CAL.gamex || {};

(function(undefined) {
	"use strict";

	CAL.gamex.TARGET_FPS = CAL.gamex.TARGET_FPS || 60;
	CAL.gamex.TARGET_UPDATE_FPS = CAL.gamex.TARGET_UPDATE_FPS || 1000;
	CAL.gamex.ASPECT_RATIO_Y = 16;
	CAL.gamex.ASPECT_RATIO_X = 9;
	CAL.gamex.ASPECT_RATIO = CAL.gamex.ASPECT_RATIO_Y / CAL.gamex.ASPECT_RATIO_X;

	var Keys = {
		DELTA: "delta",
		UPDATEPARAMS: "update_params",
		FPS_TIME: "fps_time",
		FONT: "font",
		SPRITE_MANAGER: "sprite_manager",
		Sprites: {
			SKY: "sky",
			SOIL: "soil",
			GROUND: "ground",
			GROUND_2: "ground2"
		},
	};

	var Game = function(resources) {
		CAL.lang.extend(this, new CAL.lang.CachingObject());
		this._lastFPSUpdate = CAL.gamex.TARGET_UPDATE_FPS;
		this.cache[Keys.DELTA] = 0;
	}

	var p = Game.prototype;

	p.update = function(updateParams) {
		var delta = updateParams.tickEvent.delta;
		this.cache[Keys.UPDATEPARAMS] = updateParams;
		var canvas = updateParams.canvas;

		if (updateParams.first) {
			jQuery(canvas).css("background-color", CAL.graphics.Colors.BLACK);

			var sm = this.cache[Keys.SPRITE_MANAGER] = new CAL.graphics.SpriteManager();

			sm.pushSprite(new CAL.graphics.Sprite({
				image: updateParams.resources.getResult("sky"),
			}), Keys.Sprites.SKY);

			sm.pushSprite(new CAL.graphics.Sprite({
				image: updateParams.resources.getResult("dirt_soil_1"),
			}), Keys.Sprites.SOIL);

			sm.pushSprite(new CAL.graphics.Sprite({
				image: updateParams.resources.getResult("grass_ground_1"),
			}), Keys.Sprites.GROUND);

			sm.pushSprite(sm.getSprite(Keys.Sprites.GROUND).clone(), Keys.Sprites.GROUND_2);

			var fps = CAL.gamex.TARGET_UPDATE_FPS;
			this.cache[Keys.FPS_TIMER] = new CAL.util.DeltaTimer(fps, fps)
				.postCallback(
					function() {
						this.cache[Keys.DELTA] = this.cache[Keys.UPDATEPARAMS].tickEvent.delta;
					},
					this);
			this.cache[Keys.FONT] = CAL.graphics.getFont("Ubuntu Mono", 50, [CAL.graphics.FontStyles.BOLD, CAL.graphics.FontStyles.ITALIC]);
		}

		var sm = this.cache[Keys.SPRITE_MANAGER];

		this.cache[Keys.FPS_TIMER].update(delta);
		var viewport = updateParams.viewport;

		var skySprite = sm.getSprite(Keys.Sprites.SKY);
		skySprite.scaleTo(updateParams.viewport);

		var soilSprite = sm.getSprite(Keys.Sprites.SOIL);
		soilSprite.scaleWidthTo(viewport.x);
		soilSprite.scaleHeightTo(viewport.y / 4);
		soilSprite.setY(viewport.y - soilSprite.getHeight());

		var groundSprite = sm.getSprite(Keys.Sprites.GROUND);
		groundSprite.scaleWidthTo(viewport.x / 2);
		groundSprite.scaleHeightTo(viewport.y / 50);
		groundSprite.setY(soilSprite.getY() - groundSprite.getHeight());

		var groundSprite2 = sm.getSprite(Keys.Sprites.GROUND_2);
		groundSprite2.scaleWidthTo(viewport.x / 2);
		groundSprite2.scaleHeightTo(viewport.y / 50);
		groundSprite2.setY(groundSprite.getY());
		groundSprite2.setX(groundSprite.getX() + groundSprite.getWidth() + 1);
	}

	p.draw = function(renderParams) {
		var canvas = renderParams.canvas;
		var context = canvas.getContext("2d");

		// Clear screen
		context.fillStyle = CAL.graphics.Colors.BLACK;
		context.fillRect(0, 0, canvas.width, canvas.height);

		this.cache[Keys.SPRITE_MANAGER].draw(context);

		context.font = this.cache[Keys.FONT];
		context.fillStyle = CAL.graphics.Colors.BLACK;
		var delta = this.cache[Keys.DELTA];
		context.fillText(delta == 0 ? "Infinite" : Math.floor(1000 / delta).toString(), 50, 50);
	};

	CAL.gamex.Game = Game;

})();<commit_msg>Fixed misaligned grass bug<commit_after>this.CAL = this.CAL || {};

this.CAL.gamex = this.CAL.gamex || {};

(function(undefined) {
	"use strict";

	CAL.gamex.TARGET_FPS = CAL.gamex.TARGET_FPS || 60;
	CAL.gamex.TARGET_UPDATE_FPS = CAL.gamex.TARGET_UPDATE_FPS || 1000;
	CAL.gamex.ASPECT_RATIO_Y = 16;
	CAL.gamex.ASPECT_RATIO_X = 9;
	CAL.gamex.ASPECT_RATIO = CAL.gamex.ASPECT_RATIO_Y / CAL.gamex.ASPECT_RATIO_X;

	var Keys = {
		DELTA: "delta",
		UPDATEPARAMS: "update_params",
		FPS_TIME: "fps_time",
		FONT: "font",
		SPRITE_MANAGER: "sprite_manager",
		Sprites: {
			SKY: "sky",
			SOIL: "soil",
			GROUND: "ground",
			GROUND_2: "ground2"
		},
	};

	var Game = function(resources) {
		CAL.lang.extend(this, new CAL.lang.CachingObject());
		this._lastFPSUpdate = CAL.gamex.TARGET_UPDATE_FPS;
		this.cache[Keys.DELTA] = 0;
	}

	var p = Game.prototype;

	p.update = function(updateParams) {
		var delta = updateParams.tickEvent.delta;
		this.cache[Keys.UPDATEPARAMS] = updateParams;
		var canvas = updateParams.canvas;

		if (updateParams.first) {
			jQuery(canvas).css("background-color", CAL.graphics.Colors.BLACK);

			var sm = this.cache[Keys.SPRITE_MANAGER] = new CAL.graphics.SpriteManager();

			sm.pushSprite(new CAL.graphics.Sprite({
				image: updateParams.resources.getResult("sky"),
			}), Keys.Sprites.SKY);

			sm.pushSprite(new CAL.graphics.Sprite({
				image: updateParams.resources.getResult("dirt_soil_1"),
			}), Keys.Sprites.SOIL);

			sm.pushSprite(new CAL.graphics.Sprite({
				image: updateParams.resources.getResult("grass_ground_1"),
			}), Keys.Sprites.GROUND);

			sm.pushSprite(sm.getSprite(Keys.Sprites.GROUND).clone(), Keys.Sprites.GROUND_2);

			var fps = CAL.gamex.TARGET_UPDATE_FPS;
			this.cache[Keys.FPS_TIMER] = new CAL.util.DeltaTimer(fps, fps)
				.postCallback(
					function() {
						this.cache[Keys.DELTA] = this.cache[Keys.UPDATEPARAMS].tickEvent.delta;
					},
					this);
			this.cache[Keys.FONT] = CAL.graphics.getFont("Ubuntu Mono", 50, [CAL.graphics.FontStyles.BOLD, CAL.graphics.FontStyles.ITALIC]);
		}

		var sm = this.cache[Keys.SPRITE_MANAGER];

		this.cache[Keys.FPS_TIMER].update(delta);
		var viewport = updateParams.viewport;

		var skySprite = sm.getSprite(Keys.Sprites.SKY);
		skySprite.scaleTo(updateParams.viewport);

		var soilSprite = sm.getSprite(Keys.Sprites.SOIL);
		soilSprite.scaleWidthTo(viewport.x);
		soilSprite.scaleHeightTo(viewport.y / 4);
		soilSprite.setY(viewport.y - soilSprite.getHeight());

		var groundSprite = sm.getSprite(Keys.Sprites.GROUND);
		groundSprite.scaleWidthTo(viewport.x / 2);
		groundSprite.scaleHeightTo(viewport.y / 50);
		groundSprite.setY(soilSprite.getY() - groundSprite.getHeight());

		var groundSprite2 = sm.getSprite(Keys.Sprites.GROUND_2);
		groundSprite2.scaleWidthTo(viewport.x / 2);
		groundSprite2.scaleHeightTo(viewport.y / 50);
		groundSprite2.setY(groundSprite.getY());
		groundSprite2.setX(groundSprite.getX() + groundSprite.getWidth());
	}

	p.draw = function(renderParams) {
		var canvas = renderParams.canvas;
		var context = canvas.getContext("2d");

		// Clear screen
		context.fillStyle = CAL.graphics.Colors.BLACK;
		context.fillRect(0, 0, canvas.width, canvas.height);

		this.cache[Keys.SPRITE_MANAGER].draw(context);

		context.font = this.cache[Keys.FONT];
		context.fillStyle = CAL.graphics.Colors.BLACK;
		var delta = this.cache[Keys.DELTA];
		context.fillText(delta == 0 ? "Infinite" : Math.floor(1000 / delta).toString(), 50, 50);
	};

	CAL.gamex.Game = Game;

})();<|endoftext|>


<commit_before>import React from 'react'

import styled from 'styled'

export default class HeaderContainer extends React.PureComponent {
  state = { scrollY: 0 }

  listener = null

  startLoop = () => {
    if (window && !this.frameId) {
      this.frameId = window.requestAnimationFrame(this.loop)
    }
  }

  loop = () => {
    const { height, subheader } = this.props
    const { scrollY } = this.state

    const HeaderFlowHeight = 64 + height

    let prevState = 0
    let breakpoint = 0
    let position = 'fixed'
    let top = 0
    let stuck = false
    let prevTop = 0
    let prevPosition = 'fixed'

    const headerElement = document.getElementById('header')

    const task = () => {
      // task cancelled
      if (this.frameId === -1) {
        return
      }

      const state = (window && window.pageYOffset) || 0

      if (state !== prevState) {
        // automatic scroll or jump to section, ignore scrolling up
        // only with subheader
        if (Math.abs(prevState - state) > 300 && state > 0) {
          if (subheader) {
            position = 'absolute'
            top = Math.max(state - HeaderFlowHeight, 0)
            breakpoint = Math.max(state - HeaderFlowHeight, 0)
            stuck = true
          } else {
            position = 'fixed'
            top = 0
            breakpoint = state
            stuck = false
          }
        }

        if (state > prevState) {
          if (!stuck) {
            // start flow
            if (position === 'fixed') {
              breakpoint = state
              position = 'absolute'
              top = state
            }
            if (
              position === 'absolute' &&
              state >= breakpoint + HeaderFlowHeight
            ) {
              stuck = true
              position = 'fixed'
              top = -HeaderFlowHeight
            }
          }
        } else {
          // unstick after scrolling up
          if (stuck) {
            stuck = false
            position = 'absolute'
            top = Math.max(0, state - HeaderFlowHeight)
            breakpoint = Math.max(0, state - HeaderFlowHeight)
          }
          if (position === 'absolute' && state <= breakpoint) {
            position = 'fixed'
            top = 0
            breakpoint = 0
          }
        }
      }

      const ternaryScrollState = state && (state > 64 ? 65 : 64)
      if (
        scrollY !== ternaryScrollState
        /* || this.state.position !== position
             || this.state.top !== top */
      ) {
        this.setState({
          scrollY: ternaryScrollState
          // position,
          // top
        })
      }

      // manual DOM manipulation because of one frame latency with React setState
      if (prevPosition !== position) {
        headerElement.style.position = position
        prevPosition = position
      }
      if (prevTop !== top) {
        headerElement.style.top = `${top}px`
        prevTop = top
      }
      // end of manual DOM manipulation

      prevState = state

      if (this.frameId !== -1) {
        this.frameId = window && window.requestAnimationFrame(task)
      }
    }

    task()
  }

  stopLoop = () => {
    if (window) {
      window.cancelAnimationFrame(this.frameId)
    }
    this.frameId = -1
  }

  componentDidMount() {
    this.startLoop()
  }

  componentWillUnmount() {
    this.stopLoop()
  }

  render() {
    const { scrollY } = this.state
    const { header, subheader } = this.props
    const hasSubheader = subheader !== undefined
    return (
      <styled.HeaderContainer
        id="header"
        tag="header"
        has-subheader={hasSubheader}
      >
        <styled.MainHeader>{header && header(scrollY)}</styled.MainHeader>
        {subheader && (
          <styled.SecondaryHeader>{subheader(scrollY)}</styled.SecondaryHeader>
        )}
      </styled.HeaderContainer>
    )
  }
}
<commit_msg>Fix header disappearing on Safari while scrolling up<commit_after>import React from 'react'

import styled from 'styled'

export default class HeaderContainer extends React.PureComponent {
  state = { scrollY: 0 }

  listener = null

  startLoop = () => {
    if (window && !this.frameId) {
      this.frameId = window.requestAnimationFrame(this.loop)
    }
  }

  loop = () => {
    const { height, subheader } = this.props
    const { scrollY } = this.state

    const HeaderFlowHeight = 64 + height

    let prevState = 0
    let breakpoint = 0
    let position = 'fixed'
    let top = 0
    let stuck = false
    let prevTop = 0
    let prevPosition = 'fixed'

    const headerElement = document.getElementById('header')

    const task = () => {
      // task cancelled
      if (this.frameId === -1) {
        return
      }

      const state = Math.max(0, (window && window.pageYOffset) || 0)

      if (state !== prevState) {
        // automatic scroll or jump to section, ignore scrolling up
        // only with subheader
        if (Math.abs(prevState - state) > 300 && state > 0) {
          if (subheader) {
            position = 'absolute'
            top = Math.max(state - HeaderFlowHeight, 0)
            breakpoint = Math.max(state - HeaderFlowHeight, 0)
            stuck = true
          } else {
            position = 'fixed'
            top = 0
            breakpoint = state
            stuck = false
          }
        }

        if (state > prevState) {
          if (!stuck) {
            // start flow
            if (position === 'fixed') {
              breakpoint = state
              position = 'absolute'
              top = state
            }
            if (
              position === 'absolute' &&
              state >= breakpoint + HeaderFlowHeight
            ) {
              stuck = true
              position = 'fixed'
              top = -HeaderFlowHeight
            }
          }
        } else {
          // unstick after scrolling up
          if (stuck) {
            stuck = false
            position = 'absolute'
            top = Math.max(0, state - HeaderFlowHeight)
            breakpoint = Math.max(0, state - HeaderFlowHeight)
          }
          if (position === 'absolute' && state <= breakpoint) {
            position = 'fixed'
            top = 0
            breakpoint = 0
          }
        }
      }

      const ternaryScrollState = state && (state > 64 ? 65 : 64)
      if (
        scrollY !== ternaryScrollState
        /* || this.state.position !== position
             || this.state.top !== top */
      ) {
        this.setState({
          scrollY: ternaryScrollState
          // position,
          // top
        })
      }

      // manual DOM manipulation because of one frame latency with React setState
      if (prevPosition !== position) {
        headerElement.style.position = position
        prevPosition = position
      }
      if (prevTop !== top) {
        headerElement.style.top = `${top}px`
        prevTop = top
      }
      // end of manual DOM manipulation

      prevState = state

      if (this.frameId !== -1) {
        this.frameId = window && window.requestAnimationFrame(task)
      }
    }

    task()
  }

  stopLoop = () => {
    if (window) {
      window.cancelAnimationFrame(this.frameId)
    }
    this.frameId = -1
  }

  componentDidMount() {
    this.startLoop()
  }

  componentWillUnmount() {
    this.stopLoop()
  }

  render() {
    const { scrollY } = this.state
    const { header, subheader } = this.props
    const hasSubheader = subheader !== undefined
    return (
      <styled.HeaderContainer
        id="header"
        tag="header"
        has-subheader={hasSubheader}
      >
        <styled.MainHeader>{header && header(scrollY)}</styled.MainHeader>
        {subheader && (
          <styled.SecondaryHeader>{subheader(scrollY)}</styled.SecondaryHeader>
        )}
      </styled.HeaderContainer>
    )
  }
}
<|endoftext|>


<commit_before>var Plotly = require('@lib');
var Lib = require('@src/lib');
var BADNUM = require('@src/constants/numerical').BADNUM;

var ScatterGeo = require('@src/traces/scattergeo');

var d3 = require('d3');
var createGraphDiv = require('../assets/create_graph_div');
var destroyGraphDiv = require('../assets/destroy_graph_div');
var mouseEvent = require('../assets/mouse_event');

var customAssertions = require('../assets/custom_assertions');
var assertHoverLabelStyle = customAssertions.assertHoverLabelStyle;
var assertHoverLabelContent = customAssertions.assertHoverLabelContent;
var fail = require('../assets/fail_test');
var supplyAllDefaults = require('../assets/supply_defaults');

describe('Test scattergeo defaults', function() {
    var traceIn,
        traceOut;

    var defaultColor = '#444',
        layout = {};

    beforeEach(function() {
        traceOut = {};
    });

    it('should slice lat if it it longer than lon', function() {
        traceIn = {
            lon: [-75],
            lat: [45, 45, 45]
        };

        ScatterGeo.supplyDefaults(traceIn, traceOut, defaultColor, layout);
        expect(traceOut.lat).toEqual([45]);
        expect(traceOut.lon).toEqual([-75]);
    });

    it('should slice lon if it it longer than lat', function() {
        traceIn = {
            lon: [-75, -75, -75],
            lat: [45]
        };

        ScatterGeo.supplyDefaults(traceIn, traceOut, defaultColor, layout);
        expect(traceOut.lat).toEqual([45]);
        expect(traceOut.lon).toEqual([-75]);
    });

    it('should not coerce lat and lon if locations is valid', function() {
        traceIn = {
            locations: ['CAN', 'USA'],
            lon: [20, 40],
            lat: [20, 40]
        };

        ScatterGeo.supplyDefaults(traceIn, traceOut, defaultColor, layout);
        expect(traceOut.lon).toBeUndefined();
        expect(traceOut.lat).toBeUndefined();
    });

    it('should make trace invisible if lon or lat is omitted and locations not given', function() {
        function testOne() {
            ScatterGeo.supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.visible).toBe(false);
        }

        traceIn = {
            lat: [45, 45, 45]
        };
        testOne();

        traceIn = {
            lon: [-75, -75, -75]
        };
        traceOut = {};
        testOne();

        traceIn = {};
        traceOut = {};
        testOne();
    });
});

describe('Test scattergeo calc', function() {

    function _calc(opts) {
        var base = { type: 'scattermapbox' };
        var trace = Lib.extendFlat({}, base, opts);
        var gd = { data: [trace] };

        supplyAllDefaults(gd);

        var fullTrace = gd._fullData[0];
        return ScatterGeo.calc(gd, fullTrace).map(function(obj) {
            delete obj.i;
            delete obj.t;
            return obj;
        });
    }

    it('should place lon/lat data in lonlat pairs', function() {
        var calcTrace = _calc({
            lon: [10, 20, 30],
            lat: [20, 30, 10]
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20] },
            { lonlat: [20, 30] },
            { lonlat: [30, 10] }
        ]);
    });

    it('should coerce numeric strings lon/lat data into numbers', function() {
        var calcTrace = _calc({
            lon: [10, 20, '30', '40'],
            lat: [20, '30', 10, '50']
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20] },
            { lonlat: [20, 30] },
            { lonlat: [30, 10] },
            { lonlat: [40, 50] }
        ]);
    });

    it('should set non-numeric values lon/lat pairs to BADNUM', function() {
        var calcTrace = _calc({
            lon: [null, 10, null, null, 20, '30', null, '40', null, 10],
            lat: [10, 20, '30', null, 10, '50', null, 60, null, null]
        });

        expect(calcTrace).toEqual([
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [10, 20] },
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [20, 10] },
            { lonlat: [30, 50] },
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [40, 60] },
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [BADNUM, BADNUM] }
        ]);
    });

    it('should fill array text (base case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, 30, null, 40],
            lat: [20, 30, 10, 'no-good', 50],
            text: ['A', 'B', 'C', 'D', 'E']
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], tx: 'A' },
            { lonlat: [20, 30], tx: 'B' },
            { lonlat: [30, 10], tx: 'C' },
            { lonlat: [BADNUM, BADNUM], tx: 'D' },
            { lonlat: [40, 50], tx: 'E' }
        ]);
    });

    it('should fill array text (invalid entry case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, 30, null, 40],
            lat: [20, 30, 10, 'no-good', 50],
            text: ['A', null, 'C', 'D', {}]
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], tx: 'A' },
            { lonlat: [20, 30], tx: null },
            { lonlat: [30, 10], tx: 'C' },
            { lonlat: [BADNUM, BADNUM], tx: 'D' },
            { lonlat: [40, 50], tx: {} }
        ]);
    });

    it('should fill array marker attributes (base case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, null, 30],
            lat: [20, 30, null, 10],
            marker: {
                color: ['red', 'blue', 'green', 'yellow'],
                size: [10, 20, 8, 10]
            }
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], mc: 'red', ms: 10 },
            { lonlat: [20, 30], mc: 'blue', ms: 20 },
            { lonlat: [BADNUM, BADNUM], mc: 'green', ms: 8 },
            { lonlat: [30, 10], mc: 'yellow', ms: 10 }
        ]);
    });

    it('should fill array marker attributes (invalid scale case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, null, 30],
            lat: [20, 30, null, 10],
            marker: {
                color: [0, null, 5, 10],
                size: [10, NaN, 8, 10],
                colorscale: [
                    [0, 'blue'], [0.5, 'red'], [1, 'green']
                ]
            }
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], mc: 0, ms: 10 },
            { lonlat: [20, 30], mc: null, ms: NaN },
            { lonlat: [BADNUM, BADNUM], mc: 5, ms: 8 },
            { lonlat: [30, 10], mc: 10, ms: 10 }
        ]);
    });

    it('should fill marker attributes (symbol case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, null, 30],
            lat: [20, 30, null, 10],
            marker: {
                symbol: ['cross', 'square', 'diamond', null]
            }
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], mx: 'cross' },
            { lonlat: [20, 30], mx: 'square' },
            { lonlat: [BADNUM, BADNUM], mx: 'diamond' },
            { lonlat: [30, 10], mx: null }
        ]);
    });
});

describe('Test scattergeo hover', function() {
    var gd;

    beforeEach(function(done) {
        gd = createGraphDiv();

        Plotly.plot(gd, [{
            type: 'scattergeo',
            lon: [10, 20, 30],
            lat: [10, 20, 30],
            text: ['A', 'B', 'C']
        }])
        .catch(fail)
        .then(done);
    });

    afterEach(destroyGraphDiv);

    function check(pos, content, style) {
        mouseEvent('mousemove', pos[0], pos[1]);

        style = style || {
            bgcolor: 'rgb(31, 119, 180)',
            bordercolor: 'rgb(255, 255, 255)',
            fontColor: 'rgb(255, 255, 255)',
            fontSize: 13,
            fontFamily: 'Arial'
        };

        assertHoverLabelContent({
            nums: content[0],
            name: content[1]
        });
        assertHoverLabelStyle(
            d3.select('g.hovertext'),
            style
        );
    }

    it('should generate hover label info (base case)', function() {
        check([381, 221], ['(10°, 10°)\nA', null]);
    });

    it('should generate hover label info (with trace name)', function(done) {
        Plotly.restyle(gd, 'hoverinfo', 'lon+lat+text+name').then(function() {
            check([381, 221], ['(10°, 10°)\nA', 'trace 0']);
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label info (\'text\' single value case)', function(done) {
        Plotly.restyle(gd, 'text', 'text').then(function() {
            check([381, 221], ['(10°, 10°)\ntext', null]);
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label info (\'hovertext\' single value case)', function(done) {
        Plotly.restyle(gd, 'hovertext', 'hovertext').then(function() {
            check([381, 221], ['(10°, 10°)\nhovertext', null]);
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label info (\'hovertext\' array case)', function(done) {
        Plotly.restyle(gd, 'hovertext', ['Apple', 'Banana', 'Orange']).then(function() {
            check([381, 221], ['(10°, 10°)\nApple', null]);
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label with custom styling', function(done) {
        Plotly.restyle(gd, {
            'hoverlabel.bgcolor': 'red',
            'hoverlabel.bordercolor': [['blue', 'black', 'green']]
        })
        .then(function() {
            check([381, 221], ['(10°, 10°)\nA', null], {
                bgcolor: 'rgb(255, 0, 0)',
                bordercolor: 'rgb(0, 0, 255)',
                fontColor: 'rgb(0, 0, 255)',
                fontSize: 13,
                fontFamily: 'Arial'
            });
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label with arrayOk \'hoverinfo\' settings', function(done) {
        Plotly.restyle(gd, 'hoverinfo', [['lon', null, 'lat+name']]).then(function() {
            check([381, 221], ['lon: 10°', null]);
        })
        .catch(fail)
        .then(done);
    });
});

describe('scattergeo bad data', function() {
    var gd;

    beforeEach(function() {
        gd = createGraphDiv();
    });

    afterEach(destroyGraphDiv);

    it('should not throw an error with bad locations', function(done) {
        spyOn(Lib, 'log');
        Plotly.newPlot(gd, [{
            locations: ['canada', 0, null, '', 'utopia'],
            locationmode: 'country names',
            type: 'scattergeo'
        }])
        .then(function() {
            // only utopia logs - others are silently ignored
            expect(Lib.log).toHaveBeenCalledTimes(1);
        })
        .catch(fail)
        .then(done);
    });
});
<commit_msg>update scattergeo test<commit_after>var Plotly = require('@lib');
var Lib = require('@src/lib');
var BADNUM = require('@src/constants/numerical').BADNUM;

var ScatterGeo = require('@src/traces/scattergeo');

var d3 = require('d3');
var createGraphDiv = require('../assets/create_graph_div');
var destroyGraphDiv = require('../assets/destroy_graph_div');
var mouseEvent = require('../assets/mouse_event');

var customAssertions = require('../assets/custom_assertions');
var assertHoverLabelStyle = customAssertions.assertHoverLabelStyle;
var assertHoverLabelContent = customAssertions.assertHoverLabelContent;
var fail = require('../assets/fail_test');
var supplyAllDefaults = require('../assets/supply_defaults');

describe('Test scattergeo defaults', function() {
    var traceIn,
        traceOut;

    var defaultColor = '#444',
        layout = {};

    beforeEach(function() {
        traceOut = {};
    });

    it('should not slice lat if it it longer than lon', function() {
        // this is handled at the calc step now via _length.
        traceIn = {
            lon: [-75],
            lat: [45, 45, 45]
        };

        ScatterGeo.supplyDefaults(traceIn, traceOut, defaultColor, layout);
        expect(traceOut.lat).toEqual([45, 45, 45]);
        expect(traceOut.lon).toEqual([-75]);
        expect(traceOut._length).toBe(1);
    });

    it('should slice lon if it it longer than lat', function() {
        // this is handled at the calc step now via _length.
        traceIn = {
            lon: [-75, -75, -75],
            lat: [45]
        };

        ScatterGeo.supplyDefaults(traceIn, traceOut, defaultColor, layout);
        expect(traceOut.lat).toEqual([45]);
        expect(traceOut.lon).toEqual([-75, -75, -75]);
        expect(traceOut._length).toBe(1);
    });

    it('should not coerce lat and lon if locations is valid', function() {
        traceIn = {
            locations: ['CAN', 'USA'],
            lon: [20, 40],
            lat: [20, 40]
        };

        ScatterGeo.supplyDefaults(traceIn, traceOut, defaultColor, layout);
        expect(traceOut.lon).toBeUndefined();
        expect(traceOut.lat).toBeUndefined();
    });

    it('should make trace invisible if lon or lat is omitted and locations not given', function() {
        function testOne() {
            ScatterGeo.supplyDefaults(traceIn, traceOut, defaultColor, layout);
            expect(traceOut.visible).toBe(false);
        }

        traceIn = {
            lat: [45, 45, 45]
        };
        testOne();

        traceIn = {
            lon: [-75, -75, -75]
        };
        traceOut = {};
        testOne();

        traceIn = {};
        traceOut = {};
        testOne();
    });
});

describe('Test scattergeo calc', function() {

    function _calc(opts) {
        var base = { type: 'scattermapbox' };
        var trace = Lib.extendFlat({}, base, opts);
        var gd = { data: [trace] };

        supplyAllDefaults(gd);

        var fullTrace = gd._fullData[0];
        return ScatterGeo.calc(gd, fullTrace).map(function(obj) {
            delete obj.i;
            delete obj.t;
            return obj;
        });
    }

    it('should place lon/lat data in lonlat pairs', function() {
        var calcTrace = _calc({
            lon: [10, 20, 30],
            lat: [20, 30, 10]
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20] },
            { lonlat: [20, 30] },
            { lonlat: [30, 10] }
        ]);
    });

    it('should coerce numeric strings lon/lat data into numbers', function() {
        var calcTrace = _calc({
            lon: [10, 20, '30', '40'],
            lat: [20, '30', 10, '50']
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20] },
            { lonlat: [20, 30] },
            { lonlat: [30, 10] },
            { lonlat: [40, 50] }
        ]);
    });

    it('should set non-numeric values lon/lat pairs to BADNUM', function() {
        var calcTrace = _calc({
            lon: [null, 10, null, null, 20, '30', null, '40', null, 10],
            lat: [10, 20, '30', null, 10, '50', null, 60, null, null]
        });

        expect(calcTrace).toEqual([
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [10, 20] },
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [20, 10] },
            { lonlat: [30, 50] },
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [40, 60] },
            { lonlat: [BADNUM, BADNUM] },
            { lonlat: [BADNUM, BADNUM] }
        ]);
    });

    it('should fill array text (base case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, 30, null, 40],
            lat: [20, 30, 10, 'no-good', 50],
            text: ['A', 'B', 'C', 'D', 'E']
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], tx: 'A' },
            { lonlat: [20, 30], tx: 'B' },
            { lonlat: [30, 10], tx: 'C' },
            { lonlat: [BADNUM, BADNUM], tx: 'D' },
            { lonlat: [40, 50], tx: 'E' }
        ]);
    });

    it('should fill array text (invalid entry case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, 30, null, 40],
            lat: [20, 30, 10, 'no-good', 50],
            text: ['A', null, 'C', 'D', {}]
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], tx: 'A' },
            { lonlat: [20, 30], tx: null },
            { lonlat: [30, 10], tx: 'C' },
            { lonlat: [BADNUM, BADNUM], tx: 'D' },
            { lonlat: [40, 50], tx: {} }
        ]);
    });

    it('should fill array marker attributes (base case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, null, 30],
            lat: [20, 30, null, 10],
            marker: {
                color: ['red', 'blue', 'green', 'yellow'],
                size: [10, 20, 8, 10]
            }
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], mc: 'red', ms: 10 },
            { lonlat: [20, 30], mc: 'blue', ms: 20 },
            { lonlat: [BADNUM, BADNUM], mc: 'green', ms: 8 },
            { lonlat: [30, 10], mc: 'yellow', ms: 10 }
        ]);
    });

    it('should fill array marker attributes (invalid scale case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, null, 30],
            lat: [20, 30, null, 10],
            marker: {
                color: [0, null, 5, 10],
                size: [10, NaN, 8, 10],
                colorscale: [
                    [0, 'blue'], [0.5, 'red'], [1, 'green']
                ]
            }
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], mc: 0, ms: 10 },
            { lonlat: [20, 30], mc: null, ms: NaN },
            { lonlat: [BADNUM, BADNUM], mc: 5, ms: 8 },
            { lonlat: [30, 10], mc: 10, ms: 10 }
        ]);
    });

    it('should fill marker attributes (symbol case)', function() {
        var calcTrace = _calc({
            lon: [10, 20, null, 30],
            lat: [20, 30, null, 10],
            marker: {
                symbol: ['cross', 'square', 'diamond', null]
            }
        });

        expect(calcTrace).toEqual([
            { lonlat: [10, 20], mx: 'cross' },
            { lonlat: [20, 30], mx: 'square' },
            { lonlat: [BADNUM, BADNUM], mx: 'diamond' },
            { lonlat: [30, 10], mx: null }
        ]);
    });
});

describe('Test scattergeo hover', function() {
    var gd;

    beforeEach(function(done) {
        gd = createGraphDiv();

        Plotly.plot(gd, [{
            type: 'scattergeo',
            lon: [10, 20, 30],
            lat: [10, 20, 30],
            text: ['A', 'B', 'C']
        }])
        .catch(fail)
        .then(done);
    });

    afterEach(destroyGraphDiv);

    function check(pos, content, style) {
        mouseEvent('mousemove', pos[0], pos[1]);

        style = style || {
            bgcolor: 'rgb(31, 119, 180)',
            bordercolor: 'rgb(255, 255, 255)',
            fontColor: 'rgb(255, 255, 255)',
            fontSize: 13,
            fontFamily: 'Arial'
        };

        assertHoverLabelContent({
            nums: content[0],
            name: content[1]
        });
        assertHoverLabelStyle(
            d3.select('g.hovertext'),
            style
        );
    }

    it('should generate hover label info (base case)', function() {
        check([381, 221], ['(10°, 10°)\nA', null]);
    });

    it('should generate hover label info (with trace name)', function(done) {
        Plotly.restyle(gd, 'hoverinfo', 'lon+lat+text+name').then(function() {
            check([381, 221], ['(10°, 10°)\nA', 'trace 0']);
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label info (\'text\' single value case)', function(done) {
        Plotly.restyle(gd, 'text', 'text').then(function() {
            check([381, 221], ['(10°, 10°)\ntext', null]);
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label info (\'hovertext\' single value case)', function(done) {
        Plotly.restyle(gd, 'hovertext', 'hovertext').then(function() {
            check([381, 221], ['(10°, 10°)\nhovertext', null]);
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label info (\'hovertext\' array case)', function(done) {
        Plotly.restyle(gd, 'hovertext', ['Apple', 'Banana', 'Orange']).then(function() {
            check([381, 221], ['(10°, 10°)\nApple', null]);
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label with custom styling', function(done) {
        Plotly.restyle(gd, {
            'hoverlabel.bgcolor': 'red',
            'hoverlabel.bordercolor': [['blue', 'black', 'green']]
        })
        .then(function() {
            check([381, 221], ['(10°, 10°)\nA', null], {
                bgcolor: 'rgb(255, 0, 0)',
                bordercolor: 'rgb(0, 0, 255)',
                fontColor: 'rgb(0, 0, 255)',
                fontSize: 13,
                fontFamily: 'Arial'
            });
        })
        .catch(fail)
        .then(done);
    });

    it('should generate hover label with arrayOk \'hoverinfo\' settings', function(done) {
        Plotly.restyle(gd, 'hoverinfo', [['lon', null, 'lat+name']]).then(function() {
            check([381, 221], ['lon: 10°', null]);
        })
        .catch(fail)
        .then(done);
    });
});

describe('scattergeo bad data', function() {
    var gd;

    beforeEach(function() {
        gd = createGraphDiv();
    });

    afterEach(destroyGraphDiv);

    it('should not throw an error with bad locations', function(done) {
        spyOn(Lib, 'log');
        Plotly.newPlot(gd, [{
            locations: ['canada', 0, null, '', 'utopia'],
            locationmode: 'country names',
            type: 'scattergeo'
        }])
        .then(function() {
            // only utopia logs - others are silently ignored
            expect(Lib.log).toHaveBeenCalledTimes(1);
        })
        .catch(fail)
        .then(done);
    });
});
<|endoftext|>


<commit_before>var audioContext = null;
var myBuffer = null;

var osc = null;
function setDutyCycle(amt) {
	this.delay.delayTime.value = amt/this.frequency;
	this.dcGain.gain.value = 1.7*(0.5-amt);
}
function start(time) {
	this.osc1.start(time);
	this.osc2.start(time);
	this.dcOffset.start(time);
}
function stop(time) {
	this.osc1.stop(time);
	this.osc2.stop(time);
	this.dcOffset.stop(time);
}

function createDCOffset() {
	var buffer=audioContext.createBuffer(1,1024,audioContext.sampleRate);
	var data = buffer.getChannelData(0);
	for (var i=0; i<1024; i++)
		data[i]=1.0;
	var bufferSource=audioContext.createBufferSource();
	bufferSource.buffer=buffer;
	bufferSource.loop=true;
	return bufferSource;
}

function createPWMOsc(freq, dutyCycle) {
	var pwm = new Object();
	var osc1 = audioContext.createOscillator();
	var osc2 = audioContext.createOscillator();
	var inverter = audioContext.createGain();
	var output = audioContext.createGain();
	var delay = audioContext.createDelay();
	inverter.gain.value=-1;
	osc1.type="sawtooth";
	osc2.type="sawtooth";
	osc1.frequency.value=freq;
	osc1.frequency.value=freq;
	osc1.connect(output);
	osc2.connect(inverter);
	inverter.connect(delay);
	delay.connect(output);
	var dcOffset = createDCOffset();
	var dcGain = audioContext.createGain();
	dcOffset.connect(dcGain);
	dcGain.connect(output);

	output.gain.value = 0.5;  // purely for debugging.

	pwm.osc1=osc1;
	pwm.osc2=osc2;
	pwm.output=output;
	pwm.delay=delay;
	pwm.frequency = freq;
	pwm.dcGain=dcGain;
	pwm.dcOffset=dcOffset;
	pwm.setDutyCycle = setDutyCycle;
	pwm.start=start;
	pwm.stop=stop;

	pwm.setDutyCycle(dutyCycle);
	return pwm;
}

var pwmOsc;

function setupAudio( obj ) {
	window.AudioContext = window.AudioContext || window.webkitAudioContext;
	audioContext = new AudioContext();

	obj.analyser = audioContext.createAnalyser();
	obj.analyser.fftSize = 2048;

	myOscilloscope = new Oscilloscope(obj.analyser, 512, 256);

/*
	osc = audioContext.createOscillator();
	osc.type = "sawtooth";
	*/

	pwmOsc=createPWMOsc(440,.5);

	pwmOsc.output.connect(audioContext.destination);
	pwmOsc.output.connect(obj.analyser);
	pwmOsc.start(audioContext.currentTime+0.05);

/*
	var request = new XMLHttpRequest();
	request.open("GET", "sounds/techno.wav", true);
	request.responseType = "arraybuffer";
	request.onload = function() {
	  audioContext.decodeAudioData( request.response, function(buffer) {
	    	myBuffer = buffer;
	    	appendOutput( "Sound ready." );
		} );
	}
	request.send();
*/

}<commit_msg>Only need a 1-sample buffer.<commit_after>var audioContext = null;
var myBuffer = null;

var osc = null;
function setDutyCycle(amt) {
	this.delay.delayTime.value = amt/this.frequency;
	this.dcGain.gain.value = 1.7*(0.5-amt);
}
function start(time) {
	this.osc1.start(time);
	this.osc2.start(time);
	this.dcOffset.start(time);
}
function stop(time) {
	this.osc1.stop(time);
	this.osc2.stop(time);
	this.dcOffset.stop(time);
}

function createDCOffset() {
	var buffer=audioContext.createBuffer(1,1,audioContext.sampleRate);
	var data = buffer.getChannelData(0);
	for (var i=0; i<1; i++)
		data[i]=1;
	var bufferSource=audioContext.createBufferSource();
	bufferSource.buffer=buffer;
	bufferSource.loop=true;
	return bufferSource;
}

function createPWMOsc(freq, dutyCycle) {
	var pwm = new Object();
	var osc1 = audioContext.createOscillator();
	var osc2 = audioContext.createOscillator();
	var inverter = audioContext.createGain();
	var output = audioContext.createGain();
	var delay = audioContext.createDelay();
	inverter.gain.value=-1;
	osc1.type="sawtooth";
	osc2.type="sawtooth";
	osc1.frequency.value=freq;
	osc1.frequency.value=freq;
	osc1.connect(output);
	osc2.connect(inverter);
	inverter.connect(delay);
	delay.connect(output);
	var dcOffset = createDCOffset();
	var dcGain = audioContext.createGain();
	dcOffset.connect(dcGain);
	dcGain.connect(output);

	output.gain.value = 0.5;  // purely for debugging.

	pwm.osc1=osc1;
	pwm.osc2=osc2;
	pwm.output=output;
	pwm.delay=delay;
	pwm.frequency = freq;
	pwm.dcGain=dcGain;
	pwm.dcOffset=dcOffset;
	pwm.setDutyCycle = setDutyCycle;
	pwm.start=start;
	pwm.stop=stop;

	pwm.setDutyCycle(dutyCycle);
	return pwm;
}

var pwmOsc;

function setupAudio( obj ) {
	window.AudioContext = window.AudioContext || window.webkitAudioContext;
	audioContext = new AudioContext();

	obj.analyser = audioContext.createAnalyser();
	obj.analyser.fftSize = 2048;

	myOscilloscope = new Oscilloscope(obj.analyser, 512, 256);

/*
	osc = audioContext.createOscillator();
	osc.type = "sawtooth";
	*/

	pwmOsc=createPWMOsc(440,.5);

	pwmOsc.output.connect(audioContext.destination);
	pwmOsc.output.connect(obj.analyser);
	pwmOsc.start(audioContext.currentTime+0.05);

/*
	var request = new XMLHttpRequest();
	request.open("GET", "sounds/techno.wav", true);
	request.responseType = "arraybuffer";
	request.onload = function() {
	  audioContext.decodeAudioData( request.response, function(buffer) {
	    	myBuffer = buffer;
	    	appendOutput( "Sound ready." );
		} );
	}
	request.send();
*/

}<|endoftext|>


<commit_before>import { default as React } from "react";
import { renderToString } from "react-dom/server";
import { range } from "lodash";

import { render } from "../src";
import { time } from "./_util";

// Make sure React is in production mode.
process.env.NODE_ENV = "production";

const CONCURRENCY = 10;
const DEPTH = 7;
const CACHE_DIVS = "CACHE_DIVS";
const CACHE_COMPONENT = "CACHE_COMPONENT";

const Component = ({ depth, leafText, cacheMe }) => {
  if (depth === 1) {
    return (

        {leafText}

    );
  }

  const newDepth = depth - 1;
  return (
    <div
      cacheKey={
        cacheMe === CACHE_DIVS ?
          `Div:${depth}` :
          null
      }
    >
      {
        range(depth).map(idx => (
          <Component
            depth={newDepth}
            leafText={leafText}
            key={idx}
            cacheKey={
              cacheMe === CACHE_COMPONENT ?
                `Component:${depth}` :
                null
            }
          />
        ))
      }

  );
};

console.log(`Starting benchmark for ${CONCURRENCY} concurrent render operations...`);

let baseTime;
Promise.resolve()
  .then(() =>
    time(
      "renderToString",
      () => range(CONCURRENCY).forEach(() =>
        renderToString(
          <Component
            depth={DEPTH}
            leafText="hi there! © <"
          />
        )
      ),
      _baseTime => baseTime = _baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, no caching",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, caching DIVs",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
              cacheMe={CACHE_DIVS}
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, caching DIVs (second time)",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
              cacheMe={CACHE_DIVS}
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, caching Components",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
              cacheMe={CACHE_COMPONENT}
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, caching Components (second time)",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
              cacheMe={CACHE_COMPONENT}
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  );
<commit_msg>Give benchmark a bit more work to do.<commit_after>import { default as React } from "react";
import { renderToString } from "react-dom/server";
import { range } from "lodash";

import { render } from "../src";
import { time } from "./_util";

// Make sure React is in production mode.
process.env.NODE_ENV = "production";

const CONCURRENCY = 10;
const DEPTH = 8;
const CACHE_DIVS = "CACHE_DIVS";
const CACHE_COMPONENT = "CACHE_COMPONENT";

const Component = ({ depth, leafText, cacheMe }) => {
  if (depth === 1) {
    return (

        {leafText}

    );
  }

  const newDepth = depth - 1;
  return (
    <div
      cacheKey={
        cacheMe === CACHE_DIVS ?
          `Div:${depth}` :
          null
      }
    >
      {
        range(depth).map(idx => (
          <Component
            depth={newDepth}
            leafText={leafText}
            key={idx}
            cacheKey={
              cacheMe === CACHE_COMPONENT ?
                `Component:${depth}` :
                null
            }
          />
        ))
      }

  );
};

console.log(`Starting benchmark for ${CONCURRENCY} concurrent render operations...`);

let baseTime;
Promise.resolve()
  .then(() =>
    time(
      "renderToString",
      () => range(CONCURRENCY).forEach(() =>
        renderToString(
          <Component
            depth={DEPTH}
            leafText="hi there! © <"
          />
        )
      ),
      _baseTime => baseTime = _baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, no caching",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, caching DIVs",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
              cacheMe={CACHE_DIVS}
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, caching DIVs (second time)",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
              cacheMe={CACHE_DIVS}
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, caching Components",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
              cacheMe={CACHE_COMPONENT}
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  )
  .then(() =>
    time(
      "rapscallion, caching Components (second time)",
      () => Promise.all(
        range(CONCURRENCY).map(() =>
          render(
            <Component
              depth={DEPTH}
              leafText="hi there! © <"
              cacheMe={CACHE_COMPONENT}
            />
          ).toPromise()
        )
      ),
      baseTime
    )
  );
<|endoftext|>


<commit_before>var compiler = require('google-closure-compiler-js').compile;
var fs = require('fs');
var path = require('path');

module.exports = function makeClosure(sourcePath) {
  var source = fs.readFileSync(sourcePath, 'utf8');

  var compilerFlags = {
    jsCode: [{src: source}],
    languageIn: 'ES2015',
    createSourceMap: true,
  };

  var output = compiler(compilerFlags);

  var dest = sourcePath.replace(/.js$/, '.min.js');
  var sourceMapDest = dest + '.map';
  output.compiledCode = output.compiledCode + '\n//# sourceMappingURL=' + path.basename(sourceMapDest);

  fs.writeFileSync(dest, output.compiledCode, 'utf8');
  fs.writeFileSync(sourceMapDest, output.sourceMap, 'utf8');
};
<commit_msg>fix(bundle): closure to not rewrite polyfills for minification (#4487)<commit_after>var compiler = require('google-closure-compiler-js').compile;
var fs = require('fs');
var path = require('path');

module.exports = function makeClosure(sourcePath) {
  var source = fs.readFileSync(sourcePath, 'utf8');

  var compilerFlags = {
    jsCode: [{src: source}],
    languageIn: 'ES2015',
    createSourceMap: true,
    rewritePolyfills: false,
  };

  var output = compiler(compilerFlags);

  var dest = sourcePath.replace(/.js$/, '.min.js');
  var sourceMapDest = dest + '.map';
  output.compiledCode = output.compiledCode + '\n//# sourceMappingURL=' + path.basename(sourceMapDest);

  fs.writeFileSync(dest, output.compiledCode, 'utf8');
  fs.writeFileSync(sourceMapDest, output.sourceMap, 'utf8');
};
<|endoftext|>


<commit_before>$(document).foundation();

var App = {

    buildElement: function(options) {
        if(options) {
            // Create the HTML element options.what.
            if(options.what) {
                var element = document.createElement(options.what);

                // Set the id attribute.
                if(options.id) { element.setAttribute('id', options.id); }

                // Set the inner text.
                if(options.text) { element.innerText = options.text; }

                // Set the url that the href will point to.
                if(options.url) { element.href = options.url; }

                // Set the function that gets called when the element is clicked.
                if(options.func) { element.onclick = options.func; }

                // Return the element.
                return element;
            }
        }
    },

    buildListItemFunctions: function(li) {
        if(li) {
            // Remove
            li.appendChild(this.buildElement({
                what:'a', id:'remove-link', href:'#', text:'Remove', func:function() {
                    li.parentNode.removeChild(li);
                }
            }));

            // Up
            li.appendChild(this.buildElement({
                what:'a', id:'up-link', href:'#', text:'Up', func:function() {
                    if(li.previousSibling) {
                        li.parentNode.insertBefore(li, li.previousSibling);
                    }
                }
            }));

            // Down
            li.appendChild(this.buildElement({
                what:'a', id:'down-link', href:'#', text:'Down', func:function() {
                    if(li.nextSibling) {
                        li.parentNode.insertBefore(li.nextSibling, li);
                    }
                }
            }));

            // Top
            li.appendChild(this.buildElement({
                what:'a', id:'top-link', href:'#', text:'Top', func:function() {
                    if(li.parentNode.firstChild !== li) {
                        li.parentNode.insertBefore(li, li.parentNode.firstChild);
                    }
                }
            }));

            // Bottom
            li.appendChild(this.buildElement({
                what:'a', id:'bottom-link', href:'#', text:'Bottom', func:function() {
                    if(li.parentNode.lastChild !== li) {
                        li.parentNode.appendChild(li);
                    }
                }
            }));

            return li;
        }
    },

    buildListItem: function(data) {
        if(data) {
            // Create the list element.
            var li = this.buildElement({ what:'li' });

            // Append a span HTML element as a child of li.
            li.appendChild(this.buildElement({ what:'span', id:'entryContents', text:data }));

            return li;
        }
    },

    newEntry: function(event) {
        event.preventDefault();

        // We used bind to retain `this` so we use event.currentTarget
        // to grab the event objects data.
        var f = event.currentTarget;

        // Set the entryContents to the content of the form input.
        var formData = f.inputForm.value;

        // Create the list item.
        var listItem = this.buildListItemFunctions(this.buildListItem(formData));

        // Grab the unsorted list HTML element we wish to append child nodes to.
        var unsortedList = document.querySelector('#dynamic-unsorted-list');

        // Prepend new list items to the unsorted list element.
        unsortedList.insertBefore(listItem, unsortedList.firstChild);

        // Clear the inputForm after each usage.
        f.reset();

        // Retain focus on the inputForm.
        f.inputForm.focus();
    },

    setupEventListeners: function() {
        document.querySelector('#entryForm').onsubmit = this.newEntry.bind(this);
    },

    init: function() {
        this.setupEventListeners();
    },
};

App.init();
<commit_msg>editable<commit_after>$(document).foundation();

var App = {

    buildElement: function(options) {
        if(options) {
            // Create the HTML element options.what.
            if(options.what) {
                var element = document.createElement(options.what);

                // Set the id attribute.
                if(options.id) { element.setAttribute('id', options.id); }

                // Set the inner text.
                if(options.text) { element.innerText = options.text; }

                // Set the url that the href will point to.
                if(options.url) { element.href = options.url; }

                // Set the function that gets called when the element is clicked.
                if(options.func) { element.onclick = options.func; }

                // Return the element.
                return element;
            }
        }
    },

    buildListItemFunctions: function(li) {
        if(li) {
            // Remove
            li.appendChild(this.buildElement({
                what:'a', id:'remove-link', href:'#', text:'Remove', func:function() {
                    li.parentNode.removeChild(li);
                }
            }));

            // Up
            li.appendChild(this.buildElement({
                what:'a', id:'up-link', href:'#', text:'Up', func:function() {
                    if(li.previousSibling) {
                        li.parentNode.insertBefore(li, li.previousSibling);
                    }
                }
            }));

            // Down
            li.appendChild(this.buildElement({
                what:'a', id:'down-link', href:'#', text:'Down', func:function() {
                    if(li.nextSibling) {
                        li.parentNode.insertBefore(li.nextSibling, li);
                    }
                }
            }));

            // Top
            li.appendChild(this.buildElement({
                what:'a', id:'top-link', href:'#', text:'Top', func:function() {
                    if(li.parentNode.firstChild !== li) {
                        li.parentNode.insertBefore(li, li.parentNode.firstChild);
                    }
                }
            }));

            // Bottom
            li.appendChild(this.buildElement({
                what:'a', id:'bottom-link', href:'#', text:'Bottom', func:function() {
                    if(li.parentNode.lastChild !== li) {
                        li.parentNode.appendChild(li);
                    }
                }
            }));

            // Edit
            li.appendChild(this.buildElement({
                what:'a', id:'editable-link', href:'#', text:'Edit', func:function() {
                    var span = li.querySelector('#entryContents');
                    var spanModifierLink = span.parentNode.querySelector('#editable-link');
                    if(span.contentEditable === 'true') {
                        span.contentEditable = 'false';
                        spanModifierLink.innerText = 'Edit';
                    } else {
                        span.contentEditable = 'true';
                        spanModifierLink.innerText = 'Update';
                        span.focus();
                    }
                }
            }));

            return li;
        }
    },

    buildListItem: function(data) {
        if(data) {
            // Create the list element.
            var li = this.buildElement({ what:'li' });

            // Append a span HTML element as a child of li.
            li.appendChild(this.buildElement({ what:'span', id:'entryContents', text:data }));

            return li;
        }
    },

    newEntry: function(event) {
        event.preventDefault();

        // We used bind to retain `this` so we use event.currentTarget
        // to grab the event objects data.
        var f = event.currentTarget;

        // Set the formData to the content of the form input.
        var formData = f.inputForm.value;

        // Create the list item.
        var listItem = this.buildListItemFunctions(this.buildListItem(formData));

        // Grab the unsorted list HTML element we wish to append child nodes to.
        var unsortedList = document.querySelector('#dynamic-unsorted-list');

        // Prepend new list items to the unsorted list element.
        unsortedList.insertBefore(listItem, unsortedList.firstChild);

        // Clear the inputForm after each usage.
        f.reset();

        // Retain focus on the inputForm.
        f.inputForm.focus();
    },

    setupEventListeners: function() {
        document.querySelector('#entryForm').onsubmit = this.newEntry.bind(this);
    },

    init: function() {
        this.setupEventListeners();
    },
};

App.init();
<|endoftext|>


<commit_before>

$(function(){

  function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint16Array(buf));
  }
  function str2ab(str) {
    var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
    var bufView = new Uint16Array(buf);
    for (var i=0, strLen=str.length; i<strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }

  function sendSign(signMsg){
    $.ajax({
      type: "POST",
      url:window.location,
			data:"'" + JSON.stringify(signMsg) + "'",
			dataType: 'json',
			contentType: 'application/json',
			charset:'UTF-8',
			success: function(data) {
			  console.log(data);
			}
    });

  }
  function signToken(privateKey) {
    var token = localStorage.getItem('swc.login.token');
    var abToken = str2ab(token);
    window.crypto.subtle.sign(
    {
        name: "RSASSA-PKCS1-v1_5",
    },
    privateKey, //from generateKey or importKey above
    abToken //ArrayBuffer of data you want to sign
    )
    .then(function(signature){
      //returns an ArrayBuffer containing the signature
      //console.log(signature);
      var jsonSign = {'token':token,'signature':ab2str(new Uint8Array(signature))};
      //console.log(JSON.stringify(jsonSign));
      sendSign(jsonSign)
    })
    .catch(function(err){
      console.error(err);
    });
  }
  function sendPublicKey(keydata){
    $.ajax({
      type: "POST",
      url:window.location,
			data:"'" + JSON.stringify(keydata) + "'",
			dataType: 'json',
			contentType: 'application/json',
			charset:'UTF-8',
			success: function(data) {
			  console.log(data);
			  if (data && data['token']) {
			    localStorage.setItem('swc.login.token',data['token']);
			    globalToken = data['token'];
			    signToken();
			  }
			}
    });
  }

  var savePublicKey = function(key,tag,send) {
    window.crypto.subtle.exportKey(
      "spki", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
      key //can be a publicKey or privateKey, as long as extractable was true
      )
      .then(function(keydata){
        //returns the exported key data
        //console.log(keydata);
        var name= 'swc.login.publicKey';
        localStorage.setItem(name,JSON.stringify(keydata));
        sendPublicKey(keydata);
      })
      .catch(function(err){
        console.error(err);
      });
  }
  var savePrivateKey = function(key) {
    window.crypto.subtle.exportKey(
      "jwk", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
      key //can be a publicKey or privateKey, as long as extractable was true
      )
      .then(function(keydata){
        //returns the exported key data
        //console.log(keydata);
        var name= 'swc.login.privateKey';
        localStorage.setItem(name,JSON.stringify(keydata));
      })
      .catch(function(err){
        console.error(err);
      });
  }
  function createKeyPair() {
    window.crypto.subtle.generateKey({
      name: "RSASSA-PKCS1-v1_5",
      modulusLength: 4096, //can be 1024, 2048, or 4096
      publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
      hash: {name: "SHA-512"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
      },
      true, //whether the key is extractable (i.e. can be used in exportKey)
      ["sign", "verify"] //can be any combination of "sign" and "verify"
    )
    .then(function(key){
      //returns a keypair object
      //console.log(key);
      console.log(key.publicKey);
      console.log(key.privateKey);
      savePublicKey(key.publicKey);
      savePrivateKey(key.privateKey);
    })
    .catch(function(err){
      console.error(err);
    });
  }
  function importKey(privateKey) {
    window.crypto.subtle.importKey(
      "jwk", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
      privateKey,
      {   //these are the algorithm options
      name: "RSASSA-PKCS1-v1_5",
      hash: {name: "SHA-512"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
      },
      false, //whether the key is extractable (i.e. can be used in exportKey)
      ["sign"] //"sign" for private key imports
    )
    .then(function(privateKey){
      //returns a publicKey (or privateKey if you are importing a private key)
      console.log(privateKey);
      signToken(privateKey);
    })
    .catch(function(err){
      console.error(err);
    });
  }

  var privateKey = localStorage.getItem('swc.login.privateKey');
  //console.log(privateKey);
  if (privateKey && 'string'== typeof privateKey) {
    var keyJson= JSON.parse(privateKey);
    importKey(keyJson);
  } else {
      createKeyPair();
  }
});
<commit_msg>Update login.js<commit_after>

$(function(){

  function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint16Array(buf));
  }
  function str2ab(str) {
    var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
    var bufView = new Uint16Array(buf);
    for (var i=0, strLen=str.length; i<strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }

  function sendSign(signMsg){
    $.ajax({
      type: "POST",
      url:window.location,
			data:"'" + JSON.stringify(signMsg) + "'",
			dataType: 'json',
			contentType: 'application/json',
			charset:'UTF-8',
			success: function(data) {
			  console.log(data);
			}
    });

  }
  function signToken(privateKey) {
    var token = localStorage.getItem('swc.login.token');
    var abToken = str2ab(token);
    window.crypto.subtle.sign(
    {
        name: "RSASSA-PKCS1-v1_5",
    },
    privateKey, //from generateKey or importKey above
    abToken //ArrayBuffer of data you want to sign
    )
    .then(function(signature){
      //returns an ArrayBuffer containing the signature
      //console.log(signature);
      var jsonSign = {'token':token,'signature':ab2str(new Uint8Array(signature))};
      //console.log(JSON.stringify(jsonSign));
      sendSign(jsonSign)
    })
    .catch(function(err){
      console.error(err);
    });
  }
  function sendPublicKey(keydata){
    $.ajax({
      type: "POST",
      url:window.location,
			data:"'" + JSON.stringify(keydata) + "'",
			dataType: 'json',
			contentType: 'application/json',
			charset:'UTF-8',
			success: function(data) {
			  console.log(data);
			  if (data && data['token']) {
			    localStorage.setItem('swc.login.token',data['token']);
			    globalToken = data['token'];
			    signToken();
			  }
			}
    });
  }

  var savePublicKey = function(key,tag,send) {
    window.crypto.subtle.exportKey(
      "spki", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
      key //can be a publicKey or privateKey, as long as extractable was true
      )
      .then(function(keydata){
        //returns the exported key data
        console.log(keydata);
        var name= 'swc.login.publicKey';
        localStorage.setItem(name,JSON.stringify(keydata));
        sendPublicKey(keydata);
      })
      .catch(function(err){
        console.error(err);
      });
  }
  var savePrivateKey = function(key) {
    window.crypto.subtle.exportKey(
      "jwk", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
      key //can be a publicKey or privateKey, as long as extractable was true
      )
      .then(function(keydata){
        //returns the exported key data
        //console.log(keydata);
        var name= 'swc.login.privateKey';
        localStorage.setItem(name,JSON.stringify(keydata));
      })
      .catch(function(err){
        console.error(err);
      });
  }
  function createKeyPair() {
    window.crypto.subtle.generateKey({
      name: "RSASSA-PKCS1-v1_5",
      modulusLength: 4096, //can be 1024, 2048, or 4096
      publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
      hash: {name: "SHA-512"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
      },
      true, //whether the key is extractable (i.e. can be used in exportKey)
      ["sign", "verify"] //can be any combination of "sign" and "verify"
    )
    .then(function(key){
      //returns a keypair object
      //console.log(key);
      console.log(key.publicKey);
      console.log(key.privateKey);
      savePublicKey(key.publicKey);
      savePrivateKey(key.privateKey);
    })
    .catch(function(err){
      console.error(err);
    });
  }
  function importKey(privateKey) {
    window.crypto.subtle.importKey(
      "jwk", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
      privateKey,
      {   //these are the algorithm options
      name: "RSASSA-PKCS1-v1_5",
      hash: {name: "SHA-512"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
      },
      false, //whether the key is extractable (i.e. can be used in exportKey)
      ["sign"] //"sign" for private key imports
    )
    .then(function(privateKey){
      //returns a publicKey (or privateKey if you are importing a private key)
      console.log(privateKey);
      signToken(privateKey);
    })
    .catch(function(err){
      console.error(err);
    });
  }

  var privateKey = localStorage.getItem('swc.login.privateKey');
  //console.log(privateKey);
  if (privateKey && 'string'== typeof privateKey) {
    var keyJson= JSON.parse(privateKey);
    importKey(keyJson);
  } else {
      createKeyPair();
  }
});
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import { saveVmsFilters } from '_/actions'
import { withMsg } from '_/intl'
import { RouterPropTypeShapes } from '_/propTypeShapes'
import { filterVms } from '_/utils'

import {
  Toolbar,
  ToolbarItem,
  ToolbarContent,
} from '@patternfly/react-core'
import { AddVmButton } from '_/components/CreateVmWizard'
import VmFilters from './VmFilters'
import VmSort from './VmSort'

import { toJS } from '_/helpers'

const VmsListToolbar = ({ match, vms, pools, filters = {}, onClearFilters, msg }) => {
  const { name, status, os } = filters
  const hasFilters = name?.length || status?.length || os?.length

  const total = vms.size + pools.size
  const available = vms.filter(vm => filterVms(vm, filters)).size +
    pools.filter(vm => filterVms(vm, filters)).size

  return (
    <>
      <Toolbar className='vm-list-toolbar' clearAllFilters={onClearFilters}>
        <ToolbarContent>
          <VmFilters/>
          <VmSort />
          <ToolbarItem>

              {
            hasFilters
              ? msg.resultsOf({ total, available })
              : msg.results({ total })
          }

          </ToolbarItem>
          <ToolbarItem alignment={{ default: 'alignRight' }}>
            <AddVmButton key='addbutton' id='route-add-vm' />
          </ToolbarItem>
        </ToolbarContent>
      </Toolbar>
    </>
  )
}

VmsListToolbar.propTypes = {
  vms: PropTypes.object.isRequired,
  pools: PropTypes.object.isRequired,
  filters: PropTypes.object.isRequired,

  match: RouterPropTypeShapes.match.isRequired,
  onClearFilters: PropTypes.func.isRequired,
  msg: PropTypes.object.isRequired,
}

export default connect(
  ({ vms }) => ({
    vms: vms.get('vms'),
    pools: vms.get('pools'),
    filters: toJS(vms.get('filters')),
  }),

  (dispatch) => ({
    onClearFilters: () => dispatch(saveVmsFilters({ filters: {} })),
  })
)(withMsg(VmsListToolbar))
<commit_msg>Keep the xpath selector used by OST to check VM count<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import { saveVmsFilters } from '_/actions'
import { withMsg } from '_/intl'
import { RouterPropTypeShapes } from '_/propTypeShapes'
import { filterVms } from '_/utils'

import {
  Toolbar,
  ToolbarItem,
  ToolbarContent,
} from '@patternfly/react-core'
import { AddVmButton } from '_/components/CreateVmWizard'
import VmFilters from './VmFilters'
import VmSort from './VmSort'

import { toJS } from '_/helpers'

const VmsListToolbar = ({ match, vms, pools, filters = {}, onClearFilters, msg }) => {
  const { name, status, os } = filters
  const hasFilters = name?.length || status?.length || os?.length

  const total = vms.size + pools.size
  const available = vms.filter(vm => filterVms(vm, filters)).size +
    pools.filter(vm => filterVms(vm, filters)).size

  return (
    <>
      <Toolbar className='vm-list-toolbar' clearAllFilters={onClearFilters}>
        <ToolbarContent>
          <VmFilters/>
          <VmSort />
          <ToolbarItem>
            {
            /* integration tests (OST) expect VM count under xpath //div[@class='col-sm-12']/h5
            preserve this path:
            keep the class 'col-sm-12' as marker class
            keep the structure
 followed by
 */
            }

                {
            hasFilters
              ? msg.resultsOf({ total, available })
              : msg.results({ total })
          }

          </ToolbarItem>
          <ToolbarItem alignment={{ default: 'alignRight' }}>
            <AddVmButton key='addbutton' id='route-add-vm' />
          </ToolbarItem>
        </ToolbarContent>
      </Toolbar>
    </>
  )
}

VmsListToolbar.propTypes = {
  vms: PropTypes.object.isRequired,
  pools: PropTypes.object.isRequired,
  filters: PropTypes.object.isRequired,

  match: RouterPropTypeShapes.match.isRequired,
  onClearFilters: PropTypes.func.isRequired,
  msg: PropTypes.object.isRequired,
}

export default connect(
  ({ vms }) => ({
    vms: vms.get('vms'),
    pools: vms.get('pools'),
    filters: toJS(vms.get('filters')),
  }),

  (dispatch) => ({
    onClearFilters: () => dispatch(saveVmsFilters({ filters: {} })),
  })
)(withMsg(VmsListToolbar))
<|endoftext|>


<commit_before>(function(BANTP) {
	BANTP.Workspace = Backbone.View.extend({
		el : "body",
		events : {
			"click .sidebar a" : "activateModule",
			"click .app-launch" : "launchApp"
		},
		initialize : function() {
			this.model = new BANTP.WorkspaceData();
		},
		render : function() {
			// Put the thing on the page!
			var self = this;

			// Populate and render the quick application launcher
			// Parse locally stored precompiled list of applications for quick launcher

			// Instantiate only the necessary dashboard module
			var DashboardModule = loader.module('dashboard');
			var Dashboard = new DashboardModule.Workspace();

			Dashboard.render();

			return this;
		},
		activateModule : function(e) {
			e.preventDefault();

			var data = $(e.currentTarget).data();
			var toLoad = "";
			var name = data.module || data.app || data.helper;

			if( _.has(data, "module") || _.has(data, "app")) {
				if(_.has(data, "module")) {
					toLoad = loader.module( data.module );
				} else if(_.has(data, "app")) {
					toLoad = loader.app( data.app );
				}

				this.model.set({ currentModule : name });

				var IncomingModule = new toLoad.Workspace();
				IncomingModule.render();
			} else if(_.has(data, "helper")){

				var bg = chrome.extension.getBackgroundPage();
				log("Background page:", bg);
				bg[data.helper]();
				/*
				switch(data.helper) {
					case "logStorage":
						logStorage();
						break;
					case "processInstall":
						processInstall();
						break;
					case "resetLinks":
					case "hardReset":
					default:
						break;
				}
				*/
			}
		},
		launchApp : function(e) {
			e.preventDefault();
			var id = $(e.currentTarget).data("app");
			chrome.management.launchApp(id, function() {
				window.close();
			});
		}
	});

	BANTP.WorkspaceData = Backbone.Model.extend({
		idAttribute : '_id',
		defaults : {
			currentModule : "dashboard"
		},
		initialize : function() {
			// Initialization
			this.on('change', function() {
				log("BANTP Workspace data update", this.toJSON() );
			});
		}
	});

})(loader.module('bantp'));<commit_msg>Fixed broken quick launch bug<commit_after>(function(BANTP) {
	BANTP.Workspace = Backbone.View.extend({
		el : "body",
		events : {
			"click .sidebar a" : "activateModule",
			"click .app-launch" : "launchApp"
		},
		initialize : function() {
			this.model = new BANTP.WorkspaceData();
		},
		render : function() {
			// Put the thing on the page!
			var self = this;

			// Populate and render the quick application launcher
			getLocalData("quickLaunchApps", function(apps) {
				log("Building quick launch apps:", apps);
				_.each(apps, function(app) {
					log("Adding app to quick launcher", app);
					var template = Handlebars.templates['quick_launch_single'];
					$("#quick_launch_target").append( template( app ) );
				});
			});

			// Instantiate only the necessary dashboard module
			var DashboardModule = loader.module('dashboard');
			var Dashboard = new DashboardModule.Workspace();

			Dashboard.render();

			return this;
		},
		activateModule : function(e) {
			e.preventDefault();

			var data = $(e.currentTarget).data();
			var toLoad = "";
			var name = data.module || data.app || data.helper;

			if( _.has(data, "module") || _.has(data, "app")) {
				if(_.has(data, "module")) {
					toLoad = loader.module( data.module );
				} else if(_.has(data, "app")) {
					toLoad = loader.app( data.app );
				}

				this.model.set({ currentModule : name });

				var IncomingModule = new toLoad.Workspace();
				IncomingModule.render();
			} else if(_.has(data, "helper")){
				var bg = chrome.extension.getBackgroundPage();
				bg[data.helper]();
			}
		},
		launchApp : function(e) {
			e.preventDefault();
			var id = $(e.currentTarget).data("app");
			chrome.management.launchApp(id, function() {
				window.close();
			});
		}
	});

	BANTP.WorkspaceData = Backbone.Model.extend({
		idAttribute : '_id',
		defaults : {
			currentModule : "dashboard"
		},
		initialize : function() {
			// Initialization
			this.on('change', function() {
				log("BANTP Workspace data update", this.toJSON() );
			});
		}
	});

})(loader.module('bantp'));<|endoftext|>