<commit_before>define(["Tone/effect/Convolver", "helper/Basic", "helper/EffectTests", "Tone/core/Buffer"],
function (Convolver, Basic, EffectTests, Buffer) {

	if (window.__karma__){
		Buffer.baseUrl = "/base/test/";
	}

	describe("Effect", function(){

		Basic(Convolver);

		var ir = new Buffer();

		var testFile = "./audio/sineStereo.wav";

		before(function(done){
			ir.load(testFile, function(){
				done();
			});
		});

		EffectTests(Convolver, ir);

		context("API", function(){

			it ("can pass in options in the constructor", function(){
				var convolver = new Convolver({
					"url" : testFile,
				});
				convolver.dispose();
			});

			it ("invokes the onload function when loaded", function(done){
				var convolver = new Convolver({
					"url" : testFile,
					"onload" : function(){
						convolver.dispose();
						done();
					}
				});
			});
		});
	});
});<commit_msg>updated convolved name<commit_after>define(["Tone/effect/Convolver", "helper/Basic", "helper/EffectTests", "Tone/core/Buffer"],
function (Convolver, Basic, EffectTests, Buffer) {

	if (window.__karma__){
		Buffer.baseUrl = "/base/test/";
	}

	describe("Convolver", function(){

		Basic(Convolver);

		var ir = new Buffer();

		var testFile = "./audio/sineStereo.wav";

		before(function(done){
			ir.load(testFile, function(){
				done();
			});
		});

		EffectTests(Convolver, ir);

		context("API", function(){

			it ("can pass in options in the constructor", function(){
				var convolver = new Convolver({
					"url" : testFile,
				});
				convolver.dispose();
			});

			it ("invokes the onload function when loaded", function(done){
				var convolver = new Convolver({
					"url" : testFile,
					"onload" : function(){
						convolver.dispose();
						done();
					}
				});
			});
		});
	});
});<|endoftext|>


<commit_before>/*

Created by:
Zack Rauen

*/

var playerVShaderID = "vertexShader";
var playerFShaderID = "green";
var numOfPoints = 0;

var Player = function (gl) {
	this.gl = gl;
	this.points = [vec2( -.15,-.925),vec2( .15,-.925),vec2( .15,-.975),vec2( -.15,-.975)];
	this.leftTopMax = 0;
	this.rightBottomMax = 2;
	numOfPoints = this.points.length;
	this.shiftX = 0;
	this.shiftY = 0;
	this.deltaTrans = 0.05;
	this.buffer = gl.createBuffer();
	gl.bindBuffer( gl.ARRAY_BUFFER, this.buffer );
	gl.bufferData( gl.ARRAY_BUFFER,	flatten(this.points), gl.STATIC_DRAW );
	this.velocity = 0;

	this.attachShaders();
}

Player.prototype.attachShaders = function() {
	var vertexShader = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vertexShader, document.getElementById(playerVShaderID).text);
    gl.compileShader(vertexShader);

	var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
	gl.shaderSource(fragShader, document.getElementById(playerFShaderID).text);
	gl.compileShader(fragShader);

	this.shaderProgram = gl.createProgram();
	this.gl.attachShader(this.shaderProgram, vertexShader);
    this.gl.attachShader(this.shaderProgram, fragShader);
	this.gl.linkProgram(this.shaderProgram);
}

Player.prototype.attachVariables = function() {
	var myPosition = this.gl.getAttribLocation(this.shaderProgram, "myPosition");
	this.gl.vertexAttribPointer( myPosition, 2, this.gl.FLOAT, false, 0, 0 );
	this.gl.enableVertexAttribArray( myPosition );

	this.xshiftLoc = this.gl.getUniformLocation(this.shaderProgram,"xshift");
	this.gl.uniform1f(this.xshiftLoc,this.shiftX);
	this.yshiftLoc = this.gl.getUniformLocation(this.shaderProgram,"yshift");
}

Player.prototype.moveX = function(forward) {
	this.velocity = 0.3;
	this.velocity *= forward ? 1 : -1;
}

Player.prototype.movePlayer = function(forward) {
	var change = forward ? this.deltaTrans : -this.deltaTrans;
	change *= Math.abs(this.velocity);
	if (this.points[this.leftTopMax][0] + change >= -1.01 && this.points[this.rightBottomMax][0] + change < 1.01) {
		this.shiftX += change;
		for (var i=0; i<this.points.length;i++) {
		this.points[i][0] = this.points[i][0]+change;
		}
	}
}

Player.prototype.moveY = function(forward) {
//	var change = forward ? this.deltaTrans : -this.deltaTrans;
//	if (this.points[this.leftTopMax][1] + change <= 1.01 && this.points[this.rightBottomMax][1] + change >= -1.01) {
//	this.shiftY += change;
//	for (var i=0; i<this.points.length;i++) {
//		this.points[i][1] = this.points[i][1]+change;
//	}
//	this.gl.uniform1f(this.yshiftLoc,this.shiftY);
//	}
//	else {
//		console.log(this.points);
//	}
}

Player.prototype.render = function() {
	var diff = 0.009;
	this.movePlayer(this.velocity > 0.0);
	gl.useProgram(this.shaderProgram);
	gl.bindBuffer( gl.ARRAY_BUFFER, this.buffer );
	this.attachVariables();
	this.gl.drawArrays(this.gl.TRIANGLE_FAN, 0, this.points.length);
	if (this.velocity > 0.0 && this.velocity - diff > 0.0)
		this.velocity = this.velocity - diff;
	else if (this.velocity < 0.0 && this.velocity + diff < 0.0)
		this.velocity = this.velocity + diff;
	else
		this.velocity=0.0;
	//window.requestAnimFrame(this.render);
}<commit_msg>Updated controls<commit_after>/*

Created by:
Zack Rauen

*/

var playerVShaderID = "vertexShader";
var playerFShaderID = "green";
var numOfPoints = 0;

var Player = function (gl) {
	this.gl = gl;
	this.points = [vec2( -.15,-.925),vec2( .15,-.925),vec2( .15,-.975),vec2( -.15,-.975)];
	this.leftTopMax = 0;
	this.rightBottomMax = 2;
	numOfPoints = this.points.length;
	this.shiftX = 0;
	this.shiftY = 0;
	this.deltaTrans = 0.05;
	this.buffer = gl.createBuffer();
	gl.bindBuffer( gl.ARRAY_BUFFER, this.buffer );
	gl.bufferData( gl.ARRAY_BUFFER,	flatten(this.points), gl.STATIC_DRAW );

	this.attachShaders();
}

Player.prototype.attachShaders = function() {
	var vertexShader = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vertexShader, document.getElementById(playerVShaderID).text);
    gl.compileShader(vertexShader);

	var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
	gl.shaderSource(fragShader, document.getElementById(playerFShaderID).text);
	gl.compileShader(fragShader);

	this.shaderProgram = gl.createProgram();
	this.gl.attachShader(this.shaderProgram, vertexShader);
    this.gl.attachShader(this.shaderProgram, fragShader);
	this.gl.linkProgram(this.shaderProgram);
}

Player.prototype.attachVariables = function() {
	var myPosition = this.gl.getAttribLocation(this.shaderProgram, "myPosition");
	this.gl.vertexAttribPointer( myPosition, 2, this.gl.FLOAT, false, 0, 0 );
	this.gl.enableVertexAttribArray( myPosition );

	this.xshiftLoc = this.gl.getUniformLocation(this.shaderProgram,"xshift");
	this.gl.uniform1f(this.xshiftLoc,this.shiftX);
	this.yshiftLoc = this.gl.getUniformLocation(this.shaderProgram,"yshift");
}

Player.prototype.moveX = function(forward) {
	var change = forward ? this.deltaTrans : -this.deltaTrans;
	if (this.points[this.leftTopMax][0] + change >= -1.01 && this.points[this.rightBottomMax][0] + change < 1.01) {
		this.shiftX += change;
		for (var i=0; i<this.points.length;i++) {
		this.points[i][0] = this.points[i][0]+change;
		}
	}
}

Player.prototype.moveY = function(forward) {
//	var change = forward ? this.deltaTrans : -this.deltaTrans;
//	if (this.points[this.leftTopMax][1] + change <= 1.01 && this.points[this.rightBottomMax][1] + change >= -1.01) {
//	this.shiftY += change;
//	for (var i=0; i<this.points.length;i++) {
//		this.points[i][1] = this.points[i][1]+change;
//	}
//	this.gl.uniform1f(this.yshiftLoc,this.shiftY);
//	}
//	else {
//		console.log(this.points);
//	}
}

Player.prototype.render = function() {
	gl.useProgram(this.shaderProgram);
	gl.bindBuffer( gl.ARRAY_BUFFER, this.buffer );
	this.attachVariables();
	this.gl.drawArrays(this.gl.TRIANGLE_FAN, 0, this.points.length);
	//window.requestAnimFrame(this.render);
}<|endoftext|>


<commit_before>import React, { memo } from 'react';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { FormattedMessage } from 'react-intl';
import { AttributeIcon, IconLinks } from '@buffetjs/core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import pluginId from '../../pluginId';
import useDataManager from '../../hooks/useDataManager';
import getAttributeDisplayedType from '../../utils/getAttributeDisplayedType';
import getTrad from '../../utils/getTrad';
import Curve from '../../icons/Curve';
import UpperFist from '../UpperFirst';
import Wrapper from './Wrapper';

function ListRow({
  configurable,
  name,
  dzName,
  nature,
  onClick,
  plugin,
  target,
  targetUid,
  type,
  mainTypeName,
  editTarget,
  firstLoopComponentName,
  firstLoopComponentUid,
  isFromDynamicZone,
  repeatable,
  secondLoopComponentName,
  secondLoopComponentUid,
  isNestedInDZComponent,
}) {
  const { contentTypes, isInDevelopmentMode, modifiedData, removeAttribute } = useDataManager();
  const isMorph = target === '*';
  const ico = ['integer', 'biginteger', 'float', 'decimal'].includes(type) ? 'number' : type;

  let readableType = type;

  if (['integer', 'biginteger', 'float', 'decimal'].includes(type)) {
    readableType = 'number';
  } else if (['string'].includes(type)) {
    readableType = 'text';
  }

  const contentTypeFriendlyName = get(contentTypes, [target, 'schema', 'name'], '');
  const src = target ? 'relation' : ico;

  const handleClick = () => {
    if (isMorph) {
      return;
    }

    if (configurable !== false) {
      const firstComponentCategory = get(
        modifiedData,
        ['components', firstLoopComponentUid, 'category'],
        null
      );
      const secondComponentCategory = get(
        modifiedData,
        ['components', secondLoopComponentUid, 'category'],
        null
      );

      const attrType = nature ? 'relation' : type;
      const icoType = getAttributeDisplayedType(attrType);

      let firstHeaderObject = {
        header_label_1: mainTypeName,
        header_icon_name_1: icoType,
        header_icon_isCustom_1: false,
        header_info_category_1: null,
        header_info_name_1: null,
      };
      let secondHeaderObject = {
        header_label_2: name,
        header_icon_name_2: null,
        header_icon_isCustom_2: false,
        header_info_category_2: null,
        header_info_name_2: null,
      };
      let thirdHeaderObject = {
        header_icon_name_3: 'component',
        header_icon_isCustom_3: false,
        header_info_category_3: null,
        header_info_name_3: null,
      };
      let fourthHeaderObject = {
        header_icon_name_4: null,
        header_icon_isCustom_4: false,
        header_info_category_4: null,
        header_info_name_4: null,
      };
      let fifthHeaderObject = {
        header_icon_name_5: null,
        header_icon_isCustom_5: false,
        header_info_category_5: null,
        header_info_name_5: null,
      };

      if (firstLoopComponentName) {
        secondHeaderObject = {
          header_label_2: firstLoopComponentName,
          header_icon_name_2: 'component',
          header_icon_isCustom_2: false,
          header_info_category_2: firstComponentCategory,
          header_info_name_2: firstLoopComponentName,
        };

        thirdHeaderObject = {
          ...thirdHeaderObject,
          header_label_3: name,
          header_icon_name_3: null,
        };
      }

      if (secondLoopComponentUid) {
        thirdHeaderObject = {
          ...thirdHeaderObject,
          header_label_3: secondLoopComponentName,
          header_icon_name_3: 'component',
          header_info_category_3: secondComponentCategory,
          header_info_name_3: secondLoopComponentName,
        };
        fourthHeaderObject = {
          ...fourthHeaderObject,
          header_label_4: name,
          header_icon_name_4: null,
        };
      }

      if (isFromDynamicZone || isNestedInDZComponent) {
        secondHeaderObject = {
          header_label_2: dzName,
          header_icon_name_2: 'dynamiczone',
          header_icon_isCustom_2: false,
          header_info_name_2: null,
          header_info_category_2: null,
        };
        thirdHeaderObject = {
          header_icon_name_3: 'component',
          header_label_3: firstLoopComponentName,
          header_info_name_3: firstComponentCategory,
          header_info_category_3: firstComponentCategory,
        };

        if (!isNestedInDZComponent) {
          fourthHeaderObject = {
            header_icon_name_4: null,
            header_icon_isCustom_4: false,
            header_info_category_4: null,
            header_label_4: name,
          };
        } else {
          fourthHeaderObject = {
            header_icon_name_4: 'components',
            header_icon_isCustom_4: false,
            header_info_category_4: secondComponentCategory,
            header_info_name_4: secondLoopComponentName,
            header_label_4: secondLoopComponentName,
          };

          fifthHeaderObject = {
            ...fifthHeaderObject,
            header_label_5: name,
          };
        }
      }

      onClick(
        // Tells where the attribute is located in the main modifiedData object : contentType, component or components
        editTarget,
        // main data type uid
        secondLoopComponentUid || firstLoopComponentUid || targetUid,
        // Name of the attribute
        name,
        // Type of the attribute
        attrType,
        firstHeaderObject,
        secondHeaderObject,
        thirdHeaderObject,
        fourthHeaderObject,
        fifthHeaderObject
      );
    }
  };
  let loopNumber;

  if (secondLoopComponentUid && firstLoopComponentUid) {
    loopNumber = 2;
  } else if (firstLoopComponentUid) {
    loopNumber = 1;
  } else {
    loopNumber = 0;
  }

  return (
    <Wrapper
      onClick={handleClick}
      className={[target ? 'relation-row' : '', configurable ? 'clickable' : '']}
      loopNumber={loopNumber}
    >

        <AttributeIcon key={src} type={src} />
        <Curve fill={isFromDynamicZone ? '#AED4FB' : '#f3f4f4'} />

{name}

        {target ? (

            <FormattedMessage
              id={`${pluginId}.modelPage.attribute.${
                isMorph ? 'relation-polymorphic' : 'relationWith'
              }`}
            />

            <FormattedMessage id={`${pluginId}.from`}>
              {msg => (

                  <UpperFist content={contentTypeFriendlyName} />

                  {plugin && `(${msg}: ${plugin})`}

              )}
            </FormattedMessage>

        ) : (
          <>
            <FormattedMessage id={`${pluginId}.attribute.${readableType}`} />

            {repeatable && <FormattedMessage id={getTrad('component.repeatable')} />}
          </>
        )}

        {isInDevelopmentMode && (
          <>
            {configurable ? (
              <>
                {!isMorph ? (
                  <IconLinks
                    links={[
                      {
                        icon: <FontAwesomeIcon icon="pencil-alt" />,
                        onClick: () => handleClick(),
                      },
                      {
                        icon: <FontAwesomeIcon icon="trash-alt" />,
                        onClick: e => {
                          e.stopPropagation();
                          removeAttribute(
                            editTarget,
                            name,
                            secondLoopComponentUid || firstLoopComponentUid || ''
                          );
                        },
                      },
                    ]}
                  />
                ) : (
                  <IconLinks
                    links={[
                      {
                        icon: <FontAwesomeIcon icon="trash-alt" />,
                        onClick: e => {
                          e.stopPropagation();
                          removeAttribute(
                            editTarget,
                            name,
                            secondLoopComponentUid || firstLoopComponentUid || ''
                          );
                        },
                      },
                    ]}
                  />
                )}
              </>
            ) : (
              <button type="button">
                <FontAwesomeIcon icon="lock" />
              </button>
            )}
          </>
        )}

    </Wrapper>
  );
}

ListRow.defaultProps = {
  configurable: true,
  dzName: null,
  firstLoopComponentName: null,
  firstLoopComponentUid: null,
  isFromDynamicZone: false,
  isNestedInDZComponent: false,
  nature: null,
  onClick: () => {},
  plugin: null,
  repeatable: false,
  secondLoopComponentName: null,
  secondLoopComponentUid: null,
  target: null,
  targetUid: null,
  type: null,
};

ListRow.propTypes = {
  configurable: PropTypes.bool,
  dzName: PropTypes.string,
  editTarget: PropTypes.string.isRequired,
  firstLoopComponentName: PropTypes.string,
  firstLoopComponentUid: PropTypes.string,
  isFromDynamicZone: PropTypes.bool,
  isNestedInDZComponent: PropTypes.bool,
  mainTypeName: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  nature: PropTypes.string,
  onClick: PropTypes.func,
  plugin: PropTypes.string,
  repeatable: PropTypes.bool,
  secondLoopComponentName: PropTypes.string,
  secondLoopComponentUid: PropTypes.string,
  target: PropTypes.string,
  targetUid: PropTypes.string,
  type: PropTypes.string,
};

export default memo(ListRow);
export { ListRow };
<commit_msg>Fixes #10187 (#10193)<commit_after>import React, { memo } from 'react';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { FormattedMessage } from 'react-intl';
import { AttributeIcon, IconLinks } from '@buffetjs/core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import pluginId from '../../pluginId';
import useDataManager from '../../hooks/useDataManager';
import getAttributeDisplayedType from '../../utils/getAttributeDisplayedType';
import getTrad from '../../utils/getTrad';
import Curve from '../../icons/Curve';
import UpperFist from '../UpperFirst';
import Wrapper from './Wrapper';

function ListRow({
  configurable,
  name,
  dzName,
  nature,
  onClick,
  plugin,
  target,
  targetUid,
  type,
  mainTypeName,
  editTarget,
  firstLoopComponentName,
  firstLoopComponentUid,
  isFromDynamicZone,
  repeatable,
  secondLoopComponentName,
  secondLoopComponentUid,
  isNestedInDZComponent,
}) {
  const { contentTypes, isInDevelopmentMode, modifiedData, removeAttribute } = useDataManager();
  const isMorph = target === '*';
  const ico = ['integer', 'biginteger', 'float', 'decimal'].includes(type) ? 'number' : type;

  let readableType = type;

  if (['integer', 'biginteger', 'float', 'decimal'].includes(type)) {
    readableType = 'number';
  } else if (['string'].includes(type)) {
    readableType = 'text';
  }

  const contentTypeFriendlyName = get(contentTypes, [target, 'schema', 'name'], '');
  const src = target ? 'relation' : ico;

  const handleClick = () => {
    if (isMorph) {
      return;
    }

    if (configurable !== false) {
      const firstComponentCategory = get(
        modifiedData,
        ['components', firstLoopComponentUid, 'category'],
        null
      );
      const secondComponentCategory = get(
        modifiedData,
        ['components', secondLoopComponentUid, 'category'],
        null
      );

      const attrType = nature ? 'relation' : type;
      const icoType = getAttributeDisplayedType(attrType);

      let firstHeaderObject = {
        header_label_1: mainTypeName,
        header_icon_name_1: icoType,
        header_icon_isCustom_1: false,
        header_info_category_1: null,
        header_info_name_1: null,
      };
      let secondHeaderObject = {
        header_label_2: name,
        header_icon_name_2: null,
        header_icon_isCustom_2: false,
        header_info_category_2: null,
        header_info_name_2: null,
      };
      let thirdHeaderObject = {
        header_icon_name_3: 'component',
        header_icon_isCustom_3: false,
        header_info_category_3: null,
        header_info_name_3: null,
      };
      let fourthHeaderObject = {
        header_icon_name_4: null,
        header_icon_isCustom_4: false,
        header_info_category_4: null,
        header_info_name_4: null,
      };
      let fifthHeaderObject = {
        header_icon_name_5: null,
        header_icon_isCustom_5: false,
        header_info_category_5: null,
        header_info_name_5: null,
      };

      if (firstLoopComponentName) {
        secondHeaderObject = {
          header_label_2: firstLoopComponentName,
          header_icon_name_2: 'component',
          header_icon_isCustom_2: false,
          header_info_category_2: firstComponentCategory,
          header_info_name_2: firstLoopComponentName,
        };

        thirdHeaderObject = {
          ...thirdHeaderObject,
          header_label_3: name,
          header_icon_name_3: null,
        };
      }

      if (secondLoopComponentUid) {
        thirdHeaderObject = {
          ...thirdHeaderObject,
          header_label_3: secondLoopComponentName,
          header_icon_name_3: 'component',
          header_info_category_3: secondComponentCategory,
          header_info_name_3: secondLoopComponentName,
        };
        fourthHeaderObject = {
          ...fourthHeaderObject,
          header_label_4: name,
          header_icon_name_4: null,
        };
      }

      if (isFromDynamicZone || isNestedInDZComponent) {
        secondHeaderObject = {
          header_label_2: dzName,
          header_icon_name_2: 'dynamiczone',
          header_icon_isCustom_2: false,
          header_info_name_2: null,
          header_info_category_2: null,
        };
        thirdHeaderObject = {
          header_icon_name_3: 'component',
          header_label_3: firstLoopComponentName,
          header_info_name_3: firstComponentCategory,
          header_info_category_3: firstComponentCategory,
        };

        if (!isNestedInDZComponent) {
          fourthHeaderObject = {
            header_icon_name_4: null,
            header_icon_isCustom_4: false,
            header_info_category_4: null,
            header_label_4: name,
          };
        } else {
          fourthHeaderObject = {
            header_icon_name_4: 'components',
            header_icon_isCustom_4: false,
            header_info_category_4: secondComponentCategory,
            header_info_name_4: secondLoopComponentName,
            header_label_4: secondLoopComponentName,
          };

          fifthHeaderObject = {
            ...fifthHeaderObject,
            header_label_5: name,
          };
        }
      }

      onClick(
        // Tells where the attribute is located in the main modifiedData object : contentType, component or components
        editTarget,
        // main data type uid
        secondLoopComponentUid || firstLoopComponentUid || targetUid,
        // Name of the attribute
        name,
        // Type of the attribute
        attrType,
        firstHeaderObject,
        secondHeaderObject,
        thirdHeaderObject,
        fourthHeaderObject,
        fifthHeaderObject
      );
    }
  };
  let loopNumber;

  if (secondLoopComponentUid && firstLoopComponentUid) {
    loopNumber = 2;
  } else if (firstLoopComponentUid) {
    loopNumber = 1;
  } else {
    loopNumber = 0;
  }

  return (
    <Wrapper
      onClick={handleClick}
      className={[target ? 'relation-row' : '', configurable ? 'clickable' : '']}
      loopNumber={loopNumber}
    >

        <AttributeIcon key={src} type={src} />
        <Curve fill={isFromDynamicZone ? '#AED4FB' : '#f3f4f4'} />

{name}

        {target ? (

            <FormattedMessage
              id={`${pluginId}.modelPage.attribute.${
                isMorph ? 'relation-polymorphic' : 'relationWith'
              }`}
            />

            <FormattedMessage id={`${pluginId}.from`}>
              {msg => (

                  <UpperFist content={contentTypeFriendlyName} />

                  {plugin && `(${msg}: ${plugin})`}

              )}
            </FormattedMessage>

        ) : (
          <>
            <FormattedMessage id={`${pluginId}.attribute.${readableType}`} defaultMessage={type} />

            {repeatable && <FormattedMessage id={getTrad('component.repeatable')} />}
          </>
        )}

        {isInDevelopmentMode && (
          <>
            {configurable ? (
              <>
                {!isMorph ? (
                  <IconLinks
                    links={[
                      {
                        icon: <FontAwesomeIcon icon="pencil-alt" />,
                        onClick: () => handleClick(),
                      },
                      {
                        icon: <FontAwesomeIcon icon="trash-alt" />,
                        onClick: e => {
                          e.stopPropagation();
                          removeAttribute(
                            editTarget,
                            name,
                            secondLoopComponentUid || firstLoopComponentUid || ''
                          );
                        },
                      },
                    ]}
                  />
                ) : (
                  <IconLinks
                    links={[
                      {
                        icon: <FontAwesomeIcon icon="trash-alt" />,
                        onClick: e => {
                          e.stopPropagation();
                          removeAttribute(
                            editTarget,
                            name,
                            secondLoopComponentUid || firstLoopComponentUid || ''
                          );
                        },
                      },
                    ]}
                  />
                )}
              </>
            ) : (
              <button type="button">
                <FontAwesomeIcon icon="lock" />
              </button>
            )}
          </>
        )}

    </Wrapper>
  );
}

ListRow.defaultProps = {
  configurable: true,
  dzName: null,
  firstLoopComponentName: null,
  firstLoopComponentUid: null,
  isFromDynamicZone: false,
  isNestedInDZComponent: false,
  nature: null,
  onClick: () => {},
  plugin: null,
  repeatable: false,
  secondLoopComponentName: null,
  secondLoopComponentUid: null,
  target: null,
  targetUid: null,
  type: null,
};

ListRow.propTypes = {
  configurable: PropTypes.bool,
  dzName: PropTypes.string,
  editTarget: PropTypes.string.isRequired,
  firstLoopComponentName: PropTypes.string,
  firstLoopComponentUid: PropTypes.string,
  isFromDynamicZone: PropTypes.bool,
  isNestedInDZComponent: PropTypes.bool,
  mainTypeName: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  nature: PropTypes.string,
  onClick: PropTypes.func,
  plugin: PropTypes.string,
  repeatable: PropTypes.bool,
  secondLoopComponentName: PropTypes.string,
  secondLoopComponentUid: PropTypes.string,
  target: PropTypes.string,
  targetUid: PropTypes.string,
  type: PropTypes.string,
};

export default memo(ListRow);
export { ListRow };
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  'use strict';

  grunt.initConfig({

    /**
     * Pull in the package.json file so we can read its metadata.
     */
    pkg: grunt.file.readJSON('package.json'),

    /**
     *
     *  Pull in environment-specific vars
     *
     */
    env: grunt.file.readJSON('config.json'),

    /**
     * https://github.com/gruntjs/grunt-contrib-less
     */
    less: {
        development: {
            options: {
                paths: ['front_end/css/less', 'front_end/css/less/module'],
                yuicompress: true
            },
            files: {
                "front_end/css/style.min.css": "front_end/css/less/main.less"
            }
        }
    },

    docco: {
        src: ['front_end/js/source/*.js', 'front_end/js/source/views/*.js'],
        options: {
            output: 'front_end/docs'
        }
    },

    /**
     * JSHint: https://github.com/gruntjs/grunt-contrib-jshint
     *
     * Validate files with JSHint.
     * Below are options that conform to idiomatic.js standards.
     * Feel free to add/remove your favorites: http://www.jshint.com/docs/#options
     */
    jshint: {
      options: {
        camelcase: true,
        curly: true,
        eqeqeq: true,
        forin: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        quotmark: true,
        undef: true,
        strict: true,
        unused: true,
        boss: true,
        browser: true,
        globalstrict: true,
        sub: true,
        globals: {
          jQuery: true,
          $: true,
          Backbone: true,
          _: true,
          require: true,
          define: true,
          subhead: true,
          toc: true,
          sidebar: true,
          regContent: true
        }
      },
      all: ['front_end/js/source/*.js', 'front_end/js/source/views/*.js', '!front_end/js/source/build.js', '!front_end/js/source/require.config.js']
    },

    /**
     * Jasmine: https://github.com/gruntjs/grunt-contrib-jasmine
     *
     * Run jasmine specs headlessly through PhantomJS.
     * jQuery and Jasmine jQuery is included for your pleasure: https://github.com/velesin/jasmine-jquery
     */
    jasmine: {
      all: {
        src: 'front_end/js/source',
        options: {
          template: require('grunt-template-jasmine-requirejs'),
          specs: 'front_end/js/tests/specs/*.js',
          templateOptions: {
            requireConfig: {
              baseUrl: 'front_end/js/source',
              paths: {
                underscore: './lib/underscore',
                backbone: './lib/backbone',
                jquery: './lib/jquery-1.9.1',
                samplejson: '../tests/grunt/js/fixtures/sample-json',
                'jquery-scrollstop': './lib/jquery.scrollstop',
                'jquery-hoverIntent': './lib/jquery.hoverIntent',
                'definition-view': './views/definition-view',
                'interpretation-view': './views/interpretation-view',
                'regs-fixed-el-view': './views/regs-fixed-el-view',
                'sub-head-view': './views/sub-head-view',
                'regs-view': './views/regs-view',
                'toc-view': './views/toc-view',
                'sidebar-view': './views/sidebar-view',
                'sidebar-head-view': './views/sidebar-head-view',
                'content-view': './views/content-view',
                'konami': './lib/konami'
              },
              shim: {
                underscore: {
                  exports: '_'
                },
                backbone: {
                  deps: ['underscore'],
                  exports: 'Backbone'
                },
                konami: {
                    exports: 'Konami'
                }
              }
            }
          }
        }
      }
    },

    /**
     * Watch: https://github.com/gruntjs/grunt-contrib-watch
     *
     * Run predefined tasks whenever watched file patterns are added, changed or deleted.
     * Add files to monitor below.
     */
    watch: {
      gruntfile: {
        files: ['Gruntfile.js', '<%= recess.dist.src %>', 'front_end/css/*.less', '<%= jasmine.options.specs %>'],
        tasks: ['build']
      }
    },

    /**
     *
     * https://npmjs.org/package/grunt-ghost
     *
     * Functional testing w/ Phantom, Casper
     *
     */
    ghost: {
        dist: {
            filesSrc: ['front_end/js/tests/functional/*.js'],
            options: {
                args: {
                    testUrl: '<%= env.testUrl %>'
                },
                direct: true,
                verbose: true,
                logLevel: 'debug'
            }
        }
    },

    requirejs: {
        compile: {
            options: {
                baseUrl: 'front_end/js/source',
                mainConfigFile: 'front_end/js/source/build.js',
                dir: "front_end/js/built",
                modules: [ {name: "regulations"} ],
                paths: {
                    jquery: './lib/jquery-1.9.1',
                    underscore: './lib/underscore',
                    backbone: './lib/backbone',
                    'jquery-scrollstop': './lib/jquery.scrollstop',
                    'definition-view': './views/definition-view',
                    'interpretation-view': './views/interpretation-view',
                    'regs-fixed-el-view': './views/regs-fixed-el-view',
                    'sub-head-view': './views/sub-head-view',
                    'regs-view': './views/regs-view',
                    'toc-view': './views/toc-view',
                    'sidebar-view': './views/sidebar-view',
                    'sidebar-head-view': './views/sidebar-head-view',
                    'content-view': './views/content-view',
                    'konami': './lib/konami'
                },
                shim: {
                    underscore: {
                        deps: ['jquery'],
                        exports: '_'
                    },
                    backbone: {
                        deps: ['underscore', 'jquery'],
                        exports: 'Backbone'
                    },
                    konami: {
                        exports: 'Konami'
                    }
                }
            }
        }
    }
  });

  /**
   * The above tasks are loaded here.
   */
    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-notify');
    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-ghost');
    grunt.loadNpmTasks('grunt-docco2');

    /**
    * Create task aliases by registering new tasks
    */
    grunt.registerTask('test', ['jshint', 'jasmine']);
    grunt.registerTask('build', ['test', 'requirejs', 'less']);
    grunt.registerTask('squish', ['requirejs', 'less']);
};
<commit_msg>docco gruntfile<commit_after>module.exports = function(grunt) {

  'use strict';

  grunt.initConfig({

    /**
     * Pull in the package.json file so we can read its metadata.
     */
    pkg: grunt.file.readJSON('package.json'),

    /**
     *
     *  Pull in environment-specific vars
     *
     */
    env: grunt.file.readJSON('config.json'),

    /**
     * https://github.com/gruntjs/grunt-contrib-less
     */
    less: {
        development: {
            options: {
                paths: ['front_end/css/less', 'front_end/css/less/module'],
                yuicompress: true
            },
            files: {
                "front_end/css/style.min.css": "front_end/css/less/main.less"
            }
        }
    },

    /**
     * Docco is that nifty biz that Backbone has for its annotated source
     *
     * https://github.com/eliias/grunt-docco
     */
    docco: {
        src: ['front_end/js/source/*.js', 'front_end/js/source/views/*.js'],
        options: {
            output: 'front_end/docs/v/head'
        }
    },

    /**
     * JSHint: https://github.com/gruntjs/grunt-contrib-jshint
     *
     * Validate files with JSHint.
     * Below are options that conform to idiomatic.js standards.
     * Feel free to add/remove your favorites: http://www.jshint.com/docs/#options
     */
    jshint: {
      options: {
        camelcase: true,
        curly: true,
        eqeqeq: true,
        forin: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        quotmark: true,
        undef: true,
        strict: true,
        unused: true,
        boss: true,
        browser: true,
        globalstrict: true,
        sub: true,
        globals: {
          jQuery: true,
          $: true,
          Backbone: true,
          _: true,
          require: true,
          define: true,
          subhead: true,
          toc: true,
          sidebar: true,
          regContent: true
        }
      },
      all: ['front_end/js/source/*.js', 'front_end/js/source/views/*.js', '!front_end/js/source/build.js', '!front_end/js/source/require.config.js']
    },

    /**
     * Jasmine: https://github.com/gruntjs/grunt-contrib-jasmine
     *
     * Run jasmine specs headlessly through PhantomJS.
     * jQuery and Jasmine jQuery is included for your pleasure: https://github.com/velesin/jasmine-jquery
     */
    jasmine: {
      all: {
        src: 'front_end/js/source',
        options: {
          template: require('grunt-template-jasmine-requirejs'),
          specs: 'front_end/js/tests/specs/*.js',
          templateOptions: {
            requireConfig: {
              baseUrl: 'front_end/js/source',
              paths: {
                underscore: './lib/underscore',
                backbone: './lib/backbone',
                jquery: './lib/jquery-1.9.1',
                samplejson: '../tests/grunt/js/fixtures/sample-json',
                'jquery-scrollstop': './lib/jquery.scrollstop',
                'jquery-hoverIntent': './lib/jquery.hoverIntent',
                'definition-view': './views/definition-view',
                'interpretation-view': './views/interpretation-view',
                'regs-fixed-el-view': './views/regs-fixed-el-view',
                'sub-head-view': './views/sub-head-view',
                'regs-view': './views/regs-view',
                'toc-view': './views/toc-view',
                'sidebar-view': './views/sidebar-view',
                'sidebar-head-view': './views/sidebar-head-view',
                'content-view': './views/content-view',
                'konami': './lib/konami'
              },
              shim: {
                underscore: {
                  exports: '_'
                },
                backbone: {
                  deps: ['underscore'],
                  exports: 'Backbone'
                },
                konami: {
                    exports: 'Konami'
                }
              }
            }
          }
        }
      }
    },

    /**
     * Watch: https://github.com/gruntjs/grunt-contrib-watch
     *
     * Run predefined tasks whenever watched file patterns are added, changed or deleted.
     * Add files to monitor below.
     */
    watch: {
      gruntfile: {
        files: ['Gruntfile.js', '<%= recess.dist.src %>', 'front_end/css/*.less', '<%= jasmine.options.specs %>'],
        tasks: ['build']
      }
    },

    /**
     *
     * https://npmjs.org/package/grunt-ghost
     *
     * Functional testing w/ Phantom, Casper
     *
     */
    ghost: {
        dist: {
            filesSrc: ['front_end/js/tests/functional/*.js'],
            options: {
                args: {
                    testUrl: '<%= env.testUrl %>'
                },
                direct: true,
                verbose: true,
                logLevel: 'debug'
            }
        }
    },

    requirejs: {
        compile: {
            options: {
                baseUrl: 'front_end/js/source',
                mainConfigFile: 'front_end/js/source/build.js',
                dir: "front_end/js/built",
                modules: [ {name: "regulations"} ],
                paths: {
                    jquery: './lib/jquery-1.9.1',
                    underscore: './lib/underscore',
                    backbone: './lib/backbone',
                    'jquery-scrollstop': './lib/jquery.scrollstop',
                    'definition-view': './views/definition-view',
                    'interpretation-view': './views/interpretation-view',
                    'regs-fixed-el-view': './views/regs-fixed-el-view',
                    'sub-head-view': './views/sub-head-view',
                    'regs-view': './views/regs-view',
                    'toc-view': './views/toc-view',
                    'sidebar-view': './views/sidebar-view',
                    'sidebar-head-view': './views/sidebar-head-view',
                    'content-view': './views/content-view',
                    'konami': './lib/konami'
                },
                shim: {
                    underscore: {
                        deps: ['jquery'],
                        exports: '_'
                    },
                    backbone: {
                        deps: ['underscore', 'jquery'],
                        exports: 'Backbone'
                    },
                    konami: {
                        exports: 'Konami'
                    }
                }
            }
        }
    }
  });

  /**
   * The above tasks are loaded here.
   */
    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-notify');
    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-ghost');
    grunt.loadNpmTasks('grunt-docco2');

    /**
    * Create task aliases by registering new tasks
    */
    grunt.registerTask('test', ['jshint', 'jasmine']);
    grunt.registerTask('build', ['test', 'requirejs', 'less']);
    grunt.registerTask('squish', ['requirejs', 'less']);
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);

  var browsers = [
    {
      browserName: 'chrome',
      version: '46',
      platform: 'Mac'
    },
    {
      browserName: 'internet explorer',
      version: '8',
      platform: 'Windows 7'
    },
    {
      browserName: 'internet explorer',
      version: '9',
      platform: 'Windows 7'
    },
    {
      browserName: 'internet explorer',
      version: '10',
      platform: 'Windows 7'
    },
    {
      browserName: 'internet explorer',
      version: '11',
      platform: 'Windows 7'
    },
    {
      browserName: 'firefox',
      version: '4',
      platform: 'Windows 7'
    },
    {
      browserName: 'firefox',
      version: '47',
      platform: 'Windows 7'
    }
  ];

  grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),
      uglify: {
        options: {
          banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
        },
        build: {
          src: 'dist/scion.js',
          dest: 'dist/scion.min.js'
        }
      },
      babel: {
          options: {
              sourceMap: true,
              presets: ['es2015'],
              plugins : ['transform-es2015-modules-umd']
          },
          dist: {
              files: {
                  'dist/scion.js' : 'lib/scion.js'
              }
          }
      },
      nodeunit: {
        all : ['test/harness/node/index.js']
      },
      browserify : {
        dev: {
          options: {
            debug : true,
            browserifyOptions : {
              standalone: 'scion_tests'
            }
          },
          src: ['test/harness/common/setup-nodeunit-tests.js'],
          dest: 'test/harness/browser/build/nodeunit-tests-bundle.js'
        }
      },
      connect: {
        server: {
          options: {
            base: '',
            port: 9999
          }
        }
      },
      'saucelabs-custom': {
        all: {
          options: {
            urls: [
              'http://127.0.0.1:9999/test/harness/browser/harness.html'
            ],
            browsers: browsers,
            //build: process.env.TRAVIS_JOB_ID,
            testname: 'custom tests',
            throttled: 3,
            sauceConfig: {
              'video-upload-on-pass': false
            }
          }
        }
      }
  });

  grunt.registerTask('replace-reserved-words', 'String replace reserved words in built JavaScript.', function() {
    var fs = require('fs');
    var fileContents = fs.readFileSync('dist/scion.js','utf8');
    ['return','delete'].forEach(function(s){
      fileContents = fileContents.replace(new RegExp('\\.\\b' + s + '\\b','g'), '["' + s + '"]');
    });
    fs.writeFileSync('dist/scion.js', fileContents);
  });

  //TODO: copy babel-polyfill and nodeunit-browser into test/harness/browser/lib. I wish these were published via bower.

  grunt.registerTask('build-tests', ['browserify:dev']);
  grunt.registerTask('test', ['build', 'build-tests', 'run-tests']);
  grunt.registerTask('run-tests', ['nodeunit', 'run-browser-tests' ]);
  grunt.registerTask('run-browser-tests', ['connect', 'saucelabs-custom' ]);
  grunt.registerTask('build', ['babel', 'replace-reserved-words', 'uglify']);
  grunt.registerTask('default', ['build']);
};
<commit_msg>Tweaks<commit_after>module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);

  var browsers = [
    {
      browserName: 'chrome',
      version: '46',
      platform: 'Mac'
    },
    {
      browserName: 'internet explorer',
      version: '8',
      platform: 'Windows 7'
    },
    {
      browserName: 'internet explorer',
      version: '9',
      platform: 'Windows 7'
    },
    {
      browserName: 'internet explorer',
      version: '10',
      platform: 'Windows 7'
    },
    {
      browserName: 'internet explorer',
      version: '11',
      platform: 'Windows 7'
    },
    {
      browserName: 'firefox',
      version: '4',
      platform: 'Windows 7'
    },
    {
      browserName: 'firefox',
      version: '47',
      platform: 'Windows 7'
    }
  ];

  grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),
      uglify: {
        options: {
          banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
        },
        build: {
          src: 'dist/scion.js',
          dest: 'dist/scion.min.js'
        }
      },
      babel: {
          options: {
              sourceMap: true,
              presets: ['es2015'],
              plugins : ['transform-es2015-modules-umd']
          },
          dist: {
              files: {
                  'dist/scion.js' : 'lib/scion.js'
              }
          }
      },
      nodeunit: {
        all : ['test/harness/node/index.js']
      },
      browserify : {
        dev: {
          options: {
            debug : true,
            browserifyOptions : {
              standalone: 'scion_tests'
            }
          },
          src: ['test/harness/common/setup-nodeunit-tests.js'],
          dest: 'test/harness/browser/build/nodeunit-tests-bundle.js'
        }
      },
      connect: {
        server: {
          options: {
            base: '',
            port: 9999
          }
        }
      },
      'saucelabs-custom': {
        all: {
          options: {
            urls: [
              'http://127.0.0.1:9999/test/harness/browser/harness.html'
            ],
            browsers: browsers,
            build: process.env.TRAVIS_JOB_ID,
            testname: 'custom tests',
            throttled: 5,
            sauceConfig: {
              'video-upload-on-pass': false
            }
          }
        }
      }
  });

  grunt.registerTask('replace-reserved-words', 'String replace reserved words in built JavaScript.', function() {
    var fs = require('fs');
    var fileContents = fs.readFileSync('dist/scion.js','utf8');
    ['return','delete'].forEach(function(s){
      fileContents = fileContents.replace(new RegExp('\\.\\b' + s + '\\b','g'), '["' + s + '"]');
    });
    fs.writeFileSync('dist/scion.js', fileContents);
  });

  //TODO: copy babel-polyfill and nodeunit-browser into test/harness/browser/lib. I wish these were published via bower.

  grunt.registerTask('build-tests', ['browserify:dev']);
  grunt.registerTask('test', ['build', 'build-tests', 'run-tests']);
  grunt.registerTask('run-tests', ['nodeunit', 'run-browser-tests' ]);
  grunt.registerTask('run-browser-tests', ['connect', 'saucelabs-custom' ]);
  grunt.registerTask('build', ['babel', 'replace-reserved-words', 'uglify']);
  grunt.registerTask('default', ['build']);
};
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
/**
 * @module geo
 */
//////////////////////////////////////////////////////////////////////////////

/*global File*/

//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of class jsonReader
 *
 * @class
 * @returns {geo.fileReader}
 */
//////////////////////////////////////////////////////////////////////////////
geo.jsonReader = function (arg) {
  'use strict';
  if (!(this instanceof geo.jsonReader)) {
    return new geo.jsonReader(arg);
  }

  var m_this = this, m_style = arg.style || {};

  geo.fileReader.call(this, arg);

  this.canRead = function (file) {
    if (file instanceof File) {
      return (file.type === 'application/json' || file.name.match(/\.json$/));
    } else if (typeof file === 'string') {
      try {
        JSON.parse(file);
      } catch (e) {
        return false;
      }
      return true;
    }
    try {
      if (Array.isArray(m_this._featureArray(file))) {
        return true;
      }
    } catch (e) {}
    return false;
  };

  this._readObject = function (file, done, progress) {
    var object;
    function onDone(fileString) {
      if (typeof fileString !== 'string') {
        done(false);
      }

      // We have two possibilities here:
      // 1) fileString is a JSON string or is
      // a URL.
      try {
        object = JSON.parse(fileString);
        done(object);
      } catch (e) {
        if (!object) {
          $.ajax({
            type : 'GET',
            url : fileString,
            dataType : 'text'
          }).done(function (data) {
            object = JSON.parse(data);
            done(object);
          }).fail(function () {
            done(false);
          });
        }
      }
    }

    if (file instanceof File) {
      m_this._getString(file, onDone, progress);
    } else if (typeof file === 'string') {
      onDone(file);
    } else {
      done(file);
    }
  };

  this._featureArray = function (spec) {
    if (spec.type === 'FeatureCollection') {
      return spec.features || [];
    }
    if (spec.type === 'GeometryCollection') {
      throw 'GeometryCollection not yet implemented.';
    }
    if (Array.isArray(spec.coordinates)) {
      return spec;
    }
    throw 'Unsupported collection type: ' + spec.type;
  };

  this._featureType = function (spec) {
    var geometry = spec.geometry || {};
    if (geometry.type === 'Point' || geometry.type === 'MultiPoint') {
      return 'point';
    }
    if (geometry.type === 'LineString') {
      return 'line';
    }
    return null;
  };

  this._getCoordinates = function (spec) {
    var geometry = spec.geometry || {},
        coordinates = geometry.coordinates || [], elv;

    if ((coordinates.length === 2 || coordinates.length === 3) &&
        (isFinite(coordinates[0]) && isFinite(coordinates[1]))) {

      // Do we have a elevation component
      if (isFinite(coordinates[2])) {
        elv = coordinates[2];
      }

      // special handling for single point coordinates
      return [geo.latlng(coordinates[1], coordinates[0], elv)];
    }

    // return an array of latlng's for LineString, MultiPoint, etc...
    return coordinates.map(function (c) {
      return geo.latlng(c[1], c[0], c[2]);
    });
  };

  this._getStyle = function () {
    // TODO: convert json style object for features
    //return spec.properties || {};
    return {};
  };

  this.read = function (file, done, progress) {

    function _done(object) {
      var features, allFeatures = [];

      features = m_this._featureArray(object);

      features.forEach(function (feature) {
        var type = m_this._featureType(feature),
            coordinates = m_this._getCoordinates(feature),
            style = m_this._getStyle(feature);
        if (type) {
          if (type === 'line') {
            allFeatures.push(m_this._addFeature(type, [coordinates], style));
          } else {
            allFeatures.push(m_this._addFeature(type, coordinates, style));
          }
        } else {
          console.log('unsupported feature type: ' + feature.geometry.type);
        }
      });

      if (done) {
        done(allFeatures);
      }
    }

    m_this._readObject(file, _done, progress);
  };

  this._addFeature = function (type, coordinates, style) {
    var _style = $.extend({}, m_style, style);
    return m_this.layer().createFeature(type)
      .data(coordinates)
      .position(function (d) {
        return {
          x: d.x(),
          y: d.y(),
          z: d.z()
        };
      })
      .style(_style);
  };

};

inherit(geo.jsonReader, geo.fileReader);

geo.registerFileReader('jsonReader', geo.jsonReader);
<commit_msg>Assume sea-level if no value is given<commit_after>//////////////////////////////////////////////////////////////////////////////
/**
 * @module geo
 */
//////////////////////////////////////////////////////////////////////////////

/*global File*/

//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of class jsonReader
 *
 * @class
 * @returns {geo.fileReader}
 */
//////////////////////////////////////////////////////////////////////////////
geo.jsonReader = function (arg) {
  'use strict';
  if (!(this instanceof geo.jsonReader)) {
    return new geo.jsonReader(arg);
  }

  var m_this = this, m_style = arg.style || {};

  geo.fileReader.call(this, arg);

  this.canRead = function (file) {
    if (file instanceof File) {
      return (file.type === 'application/json' || file.name.match(/\.json$/));
    } else if (typeof file === 'string') {
      try {
        JSON.parse(file);
      } catch (e) {
        return false;
      }
      return true;
    }
    try {
      if (Array.isArray(m_this._featureArray(file))) {
        return true;
      }
    } catch (e) {}
    return false;
  };

  this._readObject = function (file, done, progress) {
    var object;
    function onDone(fileString) {
      if (typeof fileString !== 'string') {
        done(false);
      }

      // We have two possibilities here:
      // 1) fileString is a JSON string or is
      // a URL.
      try {
        object = JSON.parse(fileString);
        done(object);
      } catch (e) {
        if (!object) {
          $.ajax({
            type : 'GET',
            url : fileString,
            dataType : 'text'
          }).done(function (data) {
            object = JSON.parse(data);
            done(object);
          }).fail(function () {
            done(false);
          });
        }
      }
    }

    if (file instanceof File) {
      m_this._getString(file, onDone, progress);
    } else if (typeof file === 'string') {
      onDone(file);
    } else {
      done(file);
    }
  };

  this._featureArray = function (spec) {
    if (spec.type === 'FeatureCollection') {
      return spec.features || [];
    }
    if (spec.type === 'GeometryCollection') {
      throw 'GeometryCollection not yet implemented.';
    }
    if (Array.isArray(spec.coordinates)) {
      return spec;
    }
    throw 'Unsupported collection type: ' + spec.type;
  };

  this._featureType = function (spec) {
    var geometry = spec.geometry || {};
    if (geometry.type === 'Point' || geometry.type === 'MultiPoint') {
      return 'point';
    }
    if (geometry.type === 'LineString') {
      return 'line';
    }
    return null;
  };

  this._getCoordinates = function (spec) {
    var geometry = spec.geometry || {},
        coordinates = geometry.coordinates || [], elv;

    if ((coordinates.length === 2 || coordinates.length === 3) &&
        (isFinite(coordinates[0]) && isFinite(coordinates[1]))) {

      // Do we have a elevation component
      if (isFinite(coordinates[2])) {
        elv = coordinates[2];
      }

      // special handling for single point coordinates
      return [geo.latlng(coordinates[1], coordinates[0], elv)];
    }

    // return an array of latlng's for LineString, MultiPoint, etc...
    return coordinates.map(function (c) {
      return geo.latlng(c[1], c[0], c[2]);
    });
  };

  this._getStyle = function () {
    // TODO: convert json style object for features
    //return spec.properties || {};
    return {};
  };

  this.read = function (file, done, progress) {

    function _done(object) {
      var features, allFeatures = [];

      features = m_this._featureArray(object);

      features.forEach(function (feature) {
        var type = m_this._featureType(feature),
            coordinates = m_this._getCoordinates(feature),
            style = m_this._getStyle(feature);
        if (type) {
          if (type === 'line') {
            allFeatures.push(m_this._addFeature(type, [coordinates], style));
          } else {
            allFeatures.push(m_this._addFeature(type, coordinates, style));
          }
        } else {
          console.log('unsupported feature type: ' + feature.geometry.type);
        }
      });

      if (done) {
        done(allFeatures);
      }
    }

    m_this._readObject(file, _done, progress);
  };

  this._addFeature = function (type, coordinates, style) {
    var _style = $.extend({}, m_style, style);
    return m_this.layer().createFeature(type)
      .data(coordinates)
      .position(function (d) {
        return {
          x: d.x(),
          y: d.y(),
          z: d.z() || 0
        };
      })
      .style(_style);
  };

};

inherit(geo.jsonReader, geo.fileReader);

geo.registerFileReader('jsonReader', geo.jsonReader);
<|endoftext|>


<commit_before>var async = require('async');
var gulp = require('gulp');
var install = require('gulp-install');
var jshint = require('gulp-jshint');
var jshintReporter = require('jshint-stylish');
var livereload = require('gulp-livereload');
var minifyCss = require('gulp-cssnano');
var nodemon = require('gulp-nodemon');
var path = require('path');
var rename = require('gulp-rename');
var sass = require('gulp-sass');

// single reference point for all relevant paths.

/*
NOTE: Use paths to limit the number of files being watched by any single stream.
Requiring streams to poll irrelevant files will eat up CPU useage, and if
legacyWatch is enabled within nodemon, can block the event loop.
*/
var paths = {
  'package': './package.json',
  'src': ['./models/**/*.js', './routes/**/*.js', './app.js'],
  'static': ['./templates/**/*.jade', './client/js', './public/images/**/*',
    './public/fonts/**/*', './public/js/**/*'
  ],
  'style': {
    sass: './public/styles/**/*.scss',
    compiled: './public/dist/site.min.css',
    dist: './public/dist/'
  }

};

// any child processes that need to be run (particularly within nodemon) that
// don't need a standalone gulp task
var subProcess = {
  // filepaths that need some update on change but don't require a full restart
  watch: function() {
    console.log('Gulp is now watching static files.');
    // watch sass and run compile task on change
    gulp.watch(paths.style.sass, ['sass']);
    // watch static file dirs (templates, images, etc.) and do a simple page
    //reload on change
    gulp.watch(paths.static, ['reload']);
    gulp.watch(paths.package, ['install']);
  }
};

// checks the node_modules dir for differences from the current package.json
// and runs an npm install when differences are found
/* TODO: figure out some way to set the loglevel. It's super chatty.*/
gulp.task('install', function() {
  gulp.src(paths.package)
    // NOTE: currently points to a node_modules dir in the parent.
    // a 'typical' confiruation would would use './'
    .pipe(gulp.dest('../'))
    .pipe(install({
      ignoreScripts: true
    }));
});
/*
NOTE: the install task is async on purpose. If it's run synchronously, it slows
the build/restart process dramatically due to npm's post-install checks that take
several seconds.

If a large install occurs when nodemon starts, the app may crash with a
'module not found' error. If this occurs, just wait for install to print
'npm info is okay' and then emit a restart by simply touching any file nodemon
is watching.
*/

// reads the the source javascript and return a report of any errors.
gulp.task('lint', function() {
  gulp.src(paths.src)
    .pipe(jshint())
    .pipe(jshint.reporter(jshintReporter));
});

// sass compilation process
gulp.task('sass', function(cb) {
  gulp.src(paths.style.sass)
    //compile the sass and announce any errors
    .pipe(sass()
      .on('error', function() {
        sass.logError();
        cb();
      }))
    // save an un-minified version at dist.
    // uncomment the next line if you'd like a human-readable version.
    // .pipe(gulp.dest(paths.style.dist))

  // add the standard '.min' suffix to file name, denoting minified css.
  .pipe(rename({
      suffix: '.min'
    }))
    // crunch it up
    .pipe(minifyCss({
      compatibility: 'ie9'
    }))
    .pipe(gulp.dest(paths.style.dist))
    // wait til the new file is saved before reloading the page or moving on.
    .on('end', function(err) {
      livereload.reload(); //page reload
      if (err) cb(err);
      cb();
    });
});

// simple page refresh
gulp.task('reload', function() {
  return livereload.reload();
});

// core task. monitors/restarts app automatically, and handles crashes without
// killing the container.
/*
NOTE re legacyWatch: by default, nodemon uses inotify to get updates on file
changes, but since nodemon and the files in question are on different servers,
it's:
A) unlikely that the system clocks will start or stay in sync.
B) impossible for a docker container running a boot2docker image stream intotify
messages.
to solve this problem, we simply set legacyWatch to true, thereby instructing
nodemon to poll necessary files and identify changes.
*/
gulp.task('nodemon', ['install', 'lint'], function() {
  // start the livereload server.
  livereload.listen();
  nodemon({
      script: './app.js',
      watch: paths.src,
      legacyWatch: true,
      ext: 'js',
      tasks: function(changedFiles) {
        var tasks = [];
        console.log('file changed');
        async.each(changedFiles, function(file, callback) {
          if (path.extname(file) === '.js') {
            tasks.push('lint');
          }
          callback();
        }, function(err) {
          if (err) console.log(err);
          console.log(tasks);
          return tasks;
        });
      }
    })
    // start the child watch processes. also runs on restart.
    .on('start', function() {
      subProcess.watch();
    })
    // On start/restart, watit til stdout and stdin streams are ready,
    // test to see if  livereload is listening, and then fire a page reload.
    .on('readable', function() {
      this.stdout.on('data', function(chunk) {
        if (/^listening/.test(chunk)) {
          livereload.reload();
        }
        process.stdout.write(chunk);
      });
    });
});

// default task (also the command Docker passes when the container starts,
// so DON'T REMOVE IT.)
gulp.task('default', ['nodemon']);

/*
TODO:
- synchronous build task for client components (currently using browserify middleware)
*/
<commit_msg>accounts for nodemon bug in file refs<commit_after>var async = require('async');
var gulp = require('gulp');
var install = require('gulp-install');
var jshint = require('gulp-jshint');
var jshintReporter = require('jshint-stylish');
var livereload = require('gulp-livereload');
var minifyCss = require('gulp-cssnano');
var nodemon = require('gulp-nodemon');
var path = require('path');
var rename = require('gulp-rename');
var sass = require('gulp-sass');

// single reference point for all relevant paths.

/*
NOTE: Use paths to limit the number of files being watched by any single stream.
Requiring streams to poll irrelevant files will eat up CPU useage, and if
legacyWatch is enabled within nodemon, can block the event loop.
*/
var paths = {
  'package': './package.json',
  'src': ['models/**/*.js', 'routes/**/*.js', 'app.js'],
  'static': ['./templates/**/*.jade', './client/js', './public/images/**/*',
    './public/fonts/**/*', './public/js/**/*'
  ],
  'style': {
    sass: './public/styles/**/*.scss',
    compiled: './public/dist/site.min.css',
    dist: './public/dist/'
  }

};

// any child processes that need to be run (particularly within nodemon) that
// don't need a standalone gulp task
var subProcess = {
  // filepaths that need some update on change but don't require a full restart
  watch: function() {
    console.log('Gulp is now watching static files.');
    // watch sass and run compile task on change
    gulp.watch(paths.style.sass, ['sass']);
    // watch static file dirs (templates, images, etc.) and do a simple page
    //reload on change
    gulp.watch(paths.static, ['reload']);
    gulp.watch(paths.package, ['install']);
  }
};

// checks the node_modules dir for differences from the current package.json
// and runs an npm install when differences are found
/* TODO: figure out some way to set the loglevel. It's super chatty.*/
gulp.task('install', function() {
  gulp.src(paths.package)
    // NOTE: currently points to a node_modules dir in the parent.
    // a 'typical' confiruation would would use './'
    .pipe(gulp.dest('../'))
    .pipe(install({
      ignoreScripts: true
    }));
});
/*
NOTE: the install task is async on purpose. If it's run synchronously, it slows
the build/restart process dramatically due to npm's post-install checks that take
several seconds.

If a large install occurs when nodemon starts, the app may crash with a
'module not found' error. If this occurs, just wait for install to print
'npm info is okay' and then emit a restart by simply touching any file nodemon
is watching.
*/

// reads the the source javascript and return a report of any errors.
gulp.task('lint', function() {
  var stream = gulp.src(paths.src)
    .pipe(jshint())
    .pipe(jshint.reporter(jshintReporter));
  return stream;
});

// sass compilation process
gulp.task('sass', function(cb) {
  gulp.src(paths.style.sass)
    //compile the sass and announce any errors
    .pipe(sass()
      .on('error', function() {
        sass.logError();
        cb();
      }))
    // save an un-minified version at dist.
    // uncomment the next line if you'd like a human-readable version.
    // .pipe(gulp.dest(paths.style.dist))

  // add the standard '.min' suffix to file name, denoting minified css.
  .pipe(rename({
      suffix: '.min'
    }))
    // crunch it up
    .pipe(minifyCss({
      compatibility: 'ie9'
    }))
    .pipe(gulp.dest(paths.style.dist))
    // wait til the new file is saved before reloading the page or moving on.
    .on('end', function(err) {
      livereload.reload(); //page reload
      if (err) cb(err);
      cb();
    });
});

// simple page refresh
gulp.task('reload', function(cb) {
  livereload.reload();
  cb();
});

// core task. monitors/restarts app automatically, and handles crashes without
// killing the container.
/*
NOTE re legacyWatch: by default, nodemon uses inotify to get updates on file
changes, but since nodemon and the files in question are on different servers,
it's:
A) unlikely that the system clocks will start or stay in sync.
B) impossible for a docker container running a boot2docker image stream intotify
messages.
to solve this problem, we simply set legacyWatch to true, thereby instructing
nodemon to poll necessary files and identify changes.
*/
gulp.task('nodemon', ['install', 'lint'], function() {
  // start the livereload server.
  livereload.listen();
  nodemon({
      script: './app.js',
      watch: paths.src,
      legacyWatch: true,
      ext: 'js',
      tasks: function(changedFiles) {
        var tasks = [];
        console.log('file changed');
        async.each(changedFiles, function(file, callback) {
          if (path.extname(file) === '.js') {
            tasks.push('lint');
          }
          callback();
        }, function(err) {
          if (err) console.log(err);
          console.log(tasks);
          return tasks;
        });
      }
    })
    // start the child watch processes. also runs on restart.
    .on('start', function() {
      subProcess.watch();
    })
    // On start/restart, watit til stdout and stdin streams are ready,
    // test to see if  livereload is listening, and then fire a page reload.
    .on('readable', function() {
      this.stdout.on('data', function(chunk) {
        if (/^listening/.test(chunk)) {
          livereload.reload();
        }
        process.stdout.write(chunk);
      });
    });
});

// default task (also the command Docker passes when the container starts,
// so DON'T REMOVE IT.)
gulp.task('default', ['nodemon']);

/*
TODO:
- synchronous build task for client components (currently using browserify middleware)
*/
<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 5000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

/*
  Set up mongo
*/

const mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.connect('mongodb://sam:pass@ds145312.mlab.com:45312/heroku_gbvm74zg');

var Schema = mongoose.Schema;

/**
  Datapoints
*/

const dataPointSchema = new Schema({
  value: Number,
  created_at: Date,
});

const DataPoint = mongoose.model('DataPoint', dataPointSchema);

const roomSchema = new Schema({
  data_points: [{
    value: Number,
    created_at: Date
  }],
  room_name: String
});

const Room = mongoose.model('Room', roomSchema);

app.post('/api/roomdata', (req, res) => {
  res.set('Content-Type', 'application/json');

  const roomName = req.body.room_name;

  // const dp = DataPoint({
  //   value: req.body.value,
  //   created_at: new Date()
  // });

  const dp = {
    value: req.body.value,
    created_at: new Date()
  };

  Room.findOneAndUpdate({room_name: roomName}, {$push:{data_points: dp}}, {safe: true, upsert: true}, (err, model) => {
    if (err) {
      console.log("err");
      res.send({message:"error"});
    }
    console.log("Success");
    res.send({message: "Success"});
  });
});

// app.post('/api/roomdata', (req, res) => {
//   res.set('Content-Type', 'application/json');
//   console.log('got da dp');
//   console.log(req.body);
//   const dp = DataPoint({
//     value: req.body.value,
//     created_at: new Date()
//   });

//   dp.save(err => {
//     if (err) {
//       throw err;
//       res.send({message: "Error"});
//     }
//     console.log("saved dat bitch");
//     res.send({message: "Success"});
//   });
// });

app.get('/api/roomdata/:room_name', (req, res) => {
  res.set('Content-Type', 'application/json');
  const roomName = req.params.room_name;
  Room.find({room_name: roomName}, (err, room) => {
    if (err) throw err;
    res.send(room);
  });
});

app.get('/api/rooms', (req, res) => {
  res.set('Content-Type', 'application/json');
  Room.find({}, (err, rooms) => {
    if (err) throw err;
    console.log(rooms);
    const roomData = rooms.map(room => {
      return {
        roomName: room.room_name,
        status: Math.random() > .5 ? 1 : 0
      }
    });
    console.log(roomData)
    res.send(roomData);
  })
});

// app.get('/api/currentWeekDataPoints', (req, res) => {
//   res.set('Content-Type', 'application/json');
//   //User.find({ admin: true }).where('updated_at').gt(monthAgo).exec(function(err, users) {
//   DataPoint.find({}).where('value').gt(5).exec((err, dataPoints) => {
//     if (err) throw err;
//     res.send(dataPoints);
//   })
// })

/**
 End Datapoints
*/

/**

*/

// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));

// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
  response.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
});

app.listen(PORT, function () {
  console.log(`Listening on port ${PORT}`);
});
<commit_msg>logic for weekly data<commit_after>const express = require('express');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 5000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

/*
  Set up mongo
  */

  const mongoose = require('mongoose');
  mongoose.Promise = Promise;
  mongoose.connect('mongodb://sam:pass@ds145312.mlab.com:45312/heroku_gbvm74zg');

  var Schema = mongoose.Schema;

/**
  Datapoints
  */

  const dataPointSchema = new Schema({
    value: Number,
    created_at: Date,
  });

  const DataPoint = mongoose.model('DataPoint', dataPointSchema);

  const roomSchema = new Schema({
    data_points: [{
      value: Number,
      created_at: Date
    }],
    room_name: String,
    daily_graph: {
      data:[Number],
      updated_at: Date
    }
  });

  const Room = mongoose.model('Room', roomSchema);

  app.post('/api/roomdata', (req, res) => {
    res.set('Content-Type', 'application/json');

    const roomName = req.body.room_name;

  // const dp = DataPoint({
  //   value: req.body.value,
  //   created_at: new Date()
  // });

  const dp = {
    value: req.body.value,
    created_at: new Date()
  };

  Room.findOneAndUpdate({room_name: roomName}, {$push:{data_points: dp}}, {safe: true, upsert: true}, (err, model) => {
    if (err) {
      console.log("err");
      res.send({message:"error"});
    }
    Room.findOne({'room_name':roomName}, (err, room) =>{
      if(!room.daily_graph){
        const graph = [0.0, 0.2, 0.5, 0.5, 0.6, 0.75, 0.4, 0.2, 0.0, 0.2, 0.5, 0.5, 0.6, 0.75, 0.4, 0.2, 0.0, 0.2, 0.5, 0.5, 0.6, 0.75, 0.4, 0.2];
        room.daily_graph.data = graph;
        room.daily_graph.last_update = new Date();
        room.save((err) =>{
          if(err){
            console.log("Error updating new data");
          }
        })
      }
      else{
        const current_date = new Date()
        if(((current_date.getTime() - room.daily_graph.last_update.getTime())/1000.0)>3600){

          const datapoints = room.datapoints;
          const count = 0;
          const total = 0;
          for (var i =0; i < datapoints.length; i++){
            if(datapoints[i].created_at > room.daily_graph.last_update){
              total+= datapoints[i].value;
              count++;
            }
          }
          const average = count / float(total);
          var new_data = room.daily_graph.slice(1);
          new_data.add(average);
          room.daily_graph.data = new_data;
          room.daily_graph.last_update = current_date;
          room.save((err)=>{
            console.log("Error updating new data");
          });
        }
      }
      console.log("Success");
      res.send({message: "Success"});
    });
  });

// app.post('/api/roomdata', (req, res) => {
//   res.set('Content-Type', 'application/json');
//   console.log('got da dp');
//   console.log(req.body);
//   const dp = DataPoint({
//     value: req.body.value,
//     created_at: new Date()
//   });

//   dp.save(err => {
//     if (err) {
//       throw err;
//       res.send({message: "Error"});
//     }
//     console.log("saved dat bitch");
//     res.send({message: "Success"});
//   });
// });

app.get('/api/roomdata/:room_name', (req, res) => {
  res.set('Content-Type', 'application/json');
  const roomName = req.params.room_name;
  Room.find({room_name: roomName}, (err, room) => {
    if (err) throw err;
    res.send(room);
  });
});

app.get('/api/rooms', (req, res) => {
  res.set('Content-Type', 'application/json');
  Room.find({}, (err, rooms) => {
    if (err) throw err;
    console.log(rooms);
    const roomData = rooms.map(room => {
      return {
        roomName: room.room_name,
        status: Math.random() > .5 ? 1 : 0
      }
    });
    console.log(roomData)
    res.send(roomData);
  })
});

// app.get('/api/currentWeekDataPoints', (req, res) => {
//   res.set('Content-Type', 'application/json');
//   //User.find({ admin: true }).where('updated_at').gt(monthAgo).exec(function(err, users) {
//   DataPoint.find({}).where('value').gt(5).exec((err, dataPoints) => {
//     if (err) throw err;
//     res.send(dataPoints);
//   })
// })

app.get('api/:room_name/dailygraph', (req, res)=>{
  res.set('Content-Type', 'application/json');
  const roomName = req.params.room_name;
  const query = {
    'room_name':roomName,
  }
  Room.findOne({'room_name':roomName}, (err, room) =>{
    if(!room.daily_graph){
      const graph = [0.0, 0.2, 0.5, 0.5, 0.6, 0.75, 0.4, 0.2];
      room.daily_graph.data = graph;
      room.daily_graph.last_update = new Date();
      room.save((err) =>{
        if(err){
          console.log("Error updating new data");
        }
      })
    }
    else{
      current_date = new Date()
      if(((current_date.getTime() - last_update.getTime())/1000.0)>3600){
        genNewDailyGraph()
      }
    }
    const last_update = room.daily_graph.last_update;
    const current_date = new Date()
    if(!last_update){

    } else if (((current_date.getTime() - last_update.getTime())/1000.0)>3600){ //3600 seconds in a hour

    }
  })
});

function genNewDailyGraph(data, cb){

  cb()
}

/**
 End Datapoints
 */

/**

*/

// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));

// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
  response.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
});

app.listen(PORT, function () {
  console.log(`Listening on port ${PORT}`);
});
<|endoftext|>


<commit_before>// prettier-ignore
// Prettier disabled due to trailing comma not working in IE10/11
(function(
  _window,
  _document,
  _script,
  _onerror,
  _onunhandledrejection,
  _namespace,
  _publicKey,
  _sdkBundleUrl,
  _config
) {
  var lazy = true;
  var forceLoad = false;

  for (var i = 0; i < document.scripts.length; i++) {
    if (document.scripts[i].src.indexOf(_publicKey) > -1) {
      lazy = !(document.scripts[i].getAttribute('data-lazy') === 'no');
      break;
    }
  }

  var injected = false;
  var onLoadCallbacks = [];

  // Create a namespace and attach function that will store captured exception
  // Because functions are also objects, we can attach the queue itself straight to it and save some bytes
  var queue = function(content) {
    // content.e = error
    // content.p = promise rejection
    // content.f = function call the Sentry
    if (
      (content.e ||
        content.p ||
        (content.f && content.f.indexOf('capture') > -1) ||
        (content.f && content.f.indexOf('showReportDialog') > -1)) &&
      lazy
    ) {
      // We only want to lazy inject/load the sdk bundle if
      // an error or promise rejection occured
      // OR someone called `capture...` on the SDK
      injectSdk(onLoadCallbacks);
    }
    queue.data.push(content);
  };
  queue.data = [];

  function injectSdk(callbacks) {
    if (injected) {
      return;
    }
    injected = true;

    // Create a `script` tag with provided SDK `url` and attach it just before the first, already existing `script` tag
    // Scripts that are dynamically created and added to the document are async by default,
    // they don't block rendering and execute as soon as they download, meaning they could
    // come out in the wrong order. Because of that we don't need async=1 as GA does.
    // it was probably(?) a legacy behavior that they left to not modify few years old snippet
    // https://www.html5rocks.com/en/tutorials/speed/script-loading/
    var _newScriptTag = _document.createElement(_script);
    _newScriptTag.src = _sdkBundleUrl;
    _newScriptTag.crossorigin = 'anonymous';

    // Once our SDK is loaded
    _newScriptTag.addEventListener('load', function() {
      try {
        // Restore onerror/onunhandledrejection handlers
        _window[_onerror] = _oldOnerror;
        _window[_onunhandledrejection] = _oldOnunhandledrejection;

        var SDK = _window[_namespace];

        var oldInit = SDK.init;

        // Configure it using provided DSN and config object
        SDK.init = function(options) {
          var target = _config;
          for (var key in options) {
            if (Object.prototype.hasOwnProperty.call(options, key)) {
              target[key] = options[key];
            }
          }
          oldInit(target);
        };

        sdkLoaded(callbacks, SDK);
      } catch (o_O) {
        console.error(o_O);
      }
    });

    // We append the script to the body because if you use an `onload` callback it could happen that
    // the `onLoad` of the already injected SDK will be called, which breaks the setup flow.
    document.body.appendChild(_newScriptTag);
  }

  function sdkLoaded(callbacks, SDK) {
    try {
      var data = queue.data;

      // We have to make sure to call all callbacks first
      for (var i = 0; i < callbacks.length; i++) {
        if (typeof callbacks[i] === 'function') {
          callbacks[i]();
        }
      }

      var initAlreadyCalled = false;
      // If there is a global __SENTRY__ that means that in any of the callbacks init() was already invoked
      if (!(typeof _window['__SENTRY__'] === 'undefined')) {
        initAlreadyCalled = true;
      }

      // We want to replay all calls to Sentry and also make sure that `init` is called if it wasn't already
      // We replay all calls to `Sentry.*` now
      var calledSentry = false;
      for (var i = 0; i < data.length; i++) {
        if (data[i].f) {
          calledSentry = true;
          var call = data[i];
          if (initAlreadyCalled === false && call.f !== 'init') {
            // First call always has to be init, this is a conveniece for the user so call to init is optional
            SDK.init();
          }
          initAlreadyCalled = true;
          SDK[call.f].apply(SDK, call.a);
        }
      }
      if (initAlreadyCalled === false && calledSentry === false) {
        // Sentry has never been called but we need Sentry.init() so call it
        SDK.init();
      }

      // Because we installed the SDK, at this point we have an access to TraceKit's handler,
      // which can take care of browser differences (eg. missing exception argument in onerror)
      var tracekitErrorHandler = _window[_onerror];
      var tracekitUnhandledRejectionHandler = _window[_onunhandledrejection];

      // And now capture all previously caught exceptions
      for (var i = 0; i < data.length; i++) {
        if (data[i].e && tracekitErrorHandler) {
          tracekitErrorHandler.apply(_window, data[i].e);
        } else if (data[i].p && tracekitUnhandledRejectionHandler) {
          tracekitUnhandledRejectionHandler.apply(_window, [data[i].p]);
        }
      }
    } catch (o_O) {
      console.error(o_O);
    }
  }

  // We don't want to _window.Sentry = _window.Sentry || { ... } since we want to make sure
  // that the first Sentry "instance" is our with onLoad
  _window[_namespace] = {
    onLoad: function (callback) {
      onLoadCallbacks.push(callback);
      if (lazy && !forceLoad) {
        return;
      }
      injectSdk(onLoadCallbacks);
    },
    forceLoad: function() {
      forceLoad = true;
      if (lazy) {
        setTimeout(function() {
          injectSdk(onLoadCallbacks);
        });
      }
    }
  };

  [
    'init',
    'addBreadcrumb',
    'captureMessage',
    'captureException',
    'captureEvent',
    'configureScope',
    'withScope',
    'showReportDialog'
  ].forEach(function(f) {
    _window[_namespace][f] = function() {
      queue({ f: f, a: arguments });
    };
  });

  // Store reference to the old `onerror` handler and override it with our own function
  // that will just push exceptions to the queue and call through old handler if we found one
  var _oldOnerror = _window[_onerror];
  _window[_onerror] = function(message, source, lineno, colno, exception) {
    // Use keys as "data type" to save some characters"
    queue({
      e: [].slice.call(arguments)
    });

    if (_oldOnerror) _oldOnerror.apply(_window, arguments);
  };

  // Do the same store/queue/call operations for `onunhandledrejection` event
  var _oldOnunhandledrejection = _window[_onunhandledrejection];
  _window[_onunhandledrejection] = function(exception) {
    queue({
      p: exception.reason
    });
    if (_oldOnunhandledrejection) _oldOnunhandledrejection.apply(_window, arguments);
  };

  if (!lazy) {
    setTimeout(function () {
      injectSdk(onLoadCallbacks);
    });
  }
})(window, document, 'script', 'onerror', 'onunhandledrejection', 'Sentry', 'loader.js', '../../build/bundle.js', {
  dsn: 'https://public@example.com/1'
});
<commit_msg>fix: Revert that bundle will be appended to body (#1943)<commit_after>// prettier-ignore
// Prettier disabled due to trailing comma not working in IE10/11
(function(
  _window,
  _document,
  _script,
  _onerror,
  _onunhandledrejection,
  _namespace,
  _publicKey,
  _sdkBundleUrl,
  _config
) {
  var lazy = true;
  var forceLoad = false;

  for (var i = 0; i < document.scripts.length; i++) {
    if (document.scripts[i].src.indexOf(_publicKey) > -1) {
      lazy = !(document.scripts[i].getAttribute('data-lazy') === 'no');
      break;
    }
  }

  var injected = false;
  var onLoadCallbacks = [];

  // Create a namespace and attach function that will store captured exception
  // Because functions are also objects, we can attach the queue itself straight to it and save some bytes
  var queue = function(content) {
    // content.e = error
    // content.p = promise rejection
    // content.f = function call the Sentry
    if (
      (content.e ||
        content.p ||
        (content.f && content.f.indexOf('capture') > -1) ||
        (content.f && content.f.indexOf('showReportDialog') > -1)) &&
      lazy
    ) {
      // We only want to lazy inject/load the sdk bundle if
      // an error or promise rejection occured
      // OR someone called `capture...` on the SDK
      injectSdk(onLoadCallbacks);
    }
    queue.data.push(content);
  };
  queue.data = [];

  function injectSdk(callbacks) {
    if (injected) {
      return;
    }
    injected = true;

    // Create a `script` tag with provided SDK `url` and attach it just before the first, already existing `script` tag
    // Scripts that are dynamically created and added to the document are async by default,
    // they don't block rendering and execute as soon as they download, meaning they could
    // come out in the wrong order. Because of that we don't need async=1 as GA does.
    // it was probably(?) a legacy behavior that they left to not modify few years old snippet
    // https://www.html5rocks.com/en/tutorials/speed/script-loading/
    var _currentScriptTag = _document.getElementsByTagName(_script)[0];
    var _newScriptTag = _document.createElement(_script);
    _newScriptTag.src = _sdkBundleUrl;
    _newScriptTag.crossorigin = 'anonymous';

    // Once our SDK is loaded
    _newScriptTag.addEventListener('load', function() {
      try {
        // Restore onerror/onunhandledrejection handlers
        _window[_onerror] = _oldOnerror;
        _window[_onunhandledrejection] = _oldOnunhandledrejection;

        var SDK = _window[_namespace];

        var oldInit = SDK.init;

        // Configure it using provided DSN and config object
        SDK.init = function(options) {
          var target = _config;
          for (var key in options) {
            if (Object.prototype.hasOwnProperty.call(options, key)) {
              target[key] = options[key];
            }
          }
          oldInit(target);
        };

        sdkLoaded(callbacks, SDK);
      } catch (o_O) {
        console.error(o_O);
      }
    });

    _currentScriptTag.parentNode.insertBefore(_newScriptTag, _currentScriptTag);
  }

  function sdkLoaded(callbacks, SDK) {
    try {
      var data = queue.data;

      // We have to make sure to call all callbacks first
      for (var i = 0; i < callbacks.length; i++) {
        if (typeof callbacks[i] === 'function') {
          callbacks[i]();
        }
      }

      var initAlreadyCalled = false;
      var __sentry = _window['__SENTRY__'];
      // If there is a global __SENTRY__ that means that in any of the callbacks init() was already invoked
      if (!(typeof __sentry === 'undefined') && __sentry.hub && __sentry.hub.getClient()) {
        initAlreadyCalled = true;
      }

      // We want to replay all calls to Sentry and also make sure that `init` is called if it wasn't already
      // We replay all calls to `Sentry.*` now
      var calledSentry = false;
      for (var i = 0; i < data.length; i++) {
        if (data[i].f) {
          calledSentry = true;
          var call = data[i];
          if (initAlreadyCalled === false && call.f !== 'init') {
            // First call always has to be init, this is a conveniece for the user so call to init is optional
            SDK.init();
          }
          initAlreadyCalled = true;
          SDK[call.f].apply(SDK, call.a);
        }
      }
      if (initAlreadyCalled === false && calledSentry === false) {
        // Sentry has never been called but we need Sentry.init() so call it
        SDK.init();
      }

      // Because we installed the SDK, at this point we have an access to TraceKit's handler,
      // which can take care of browser differences (eg. missing exception argument in onerror)
      var tracekitErrorHandler = _window[_onerror];
      var tracekitUnhandledRejectionHandler = _window[_onunhandledrejection];

      // And now capture all previously caught exceptions
      for (var i = 0; i < data.length; i++) {
        if (data[i].e && tracekitErrorHandler) {
          tracekitErrorHandler.apply(_window, data[i].e);
        } else if (data[i].p && tracekitUnhandledRejectionHandler) {
          tracekitUnhandledRejectionHandler.apply(_window, [data[i].p]);
        }
      }
    } catch (o_O) {
      console.error(o_O);
    }
  }

  // We don't want to _window.Sentry = _window.Sentry || { ... } since we want to make sure
  // that the first Sentry "instance" is our with onLoad
  _window[_namespace] = {
    onLoad: function (callback) {
      onLoadCallbacks.push(callback);
      if (lazy && !forceLoad) {
        return;
      }
      injectSdk(onLoadCallbacks);
    },
    forceLoad: function() {
      forceLoad = true;
      if (lazy) {
        setTimeout(function() {
          injectSdk(onLoadCallbacks);
        });
      }
    }
  };

  [
    'init',
    'addBreadcrumb',
    'captureMessage',
    'captureException',
    'captureEvent',
    'configureScope',
    'withScope',
    'showReportDialog'
  ].forEach(function(f) {
    _window[_namespace][f] = function() {
      queue({ f: f, a: arguments });
    };
  });

  // Store reference to the old `onerror` handler and override it with our own function
  // that will just push exceptions to the queue and call through old handler if we found one
  var _oldOnerror = _window[_onerror];
  _window[_onerror] = function(message, source, lineno, colno, exception) {
    // Use keys as "data type" to save some characters"
    queue({
      e: [].slice.call(arguments)
    });

    if (_oldOnerror) _oldOnerror.apply(_window, arguments);
  };

  // Do the same store/queue/call operations for `onunhandledrejection` event
  var _oldOnunhandledrejection = _window[_onunhandledrejection];
  _window[_onunhandledrejection] = function(exception) {
    queue({
      p: exception.reason
    });
    if (_oldOnunhandledrejection) _oldOnunhandledrejection.apply(_window, arguments);
  };

  if (!lazy) {
    setTimeout(function () {
      injectSdk(onLoadCallbacks);
    });
  }
})(window, document, 'script', 'onerror', 'onunhandledrejection', 'Sentry', 'loader.js', '../../build/bundle.js', {
  dsn: 'https://public@example.com/1'
});
<|endoftext|>


<commit_before>'use strict';

/* Directives */

angular.module('krissyosheaApp.directives', []).directive('responsive', function () {
    return {
        link: function(scope, element, attrs) {
        	var width = (window.innerWidth > 0) ? window.innerWidth : screen.width
			xAxis = parseInt(scope.photo.width_o, 10),
			dimension = width >= xAxis ? 'url_o' : 'url_m';
            element[0].src = scope.photo[dimension];
        }
    };
});<commit_msg>Per issue #21 - Missing semicolon<commit_after>'use strict';

/* Directives */

angular.module('krissyosheaApp.directives', []).directive('responsive', function () {
    return {
        link: function(scope, element, attrs) {
        	var width = (window.innerWidth > 0) ? window.innerWidth : screen.width,
			xAxis = parseInt(scope.photo.width_o, 10),
			dimension = width >= xAxis ? 'url_o' : 'url_m';
            element[0].src = scope.photo[dimension];
        }
    };
});<|endoftext|>


<commit_before>module.exports = {
	AGALMiniAssembler: require("./AGALMiniAssembler").default,
	AssetCache: require("./AssetCache").default,
	AssetLibrary: require("./AssetLibrary").default,
	AssetManifest: require("./AssetManifest").default,
	Assets: require("./Assets").default,
	AssetType: require("./AssetType").default,
	ByteArray: require("./ByteArray").default,
	CompressionAlgorithm: require("./CompressionAlgorithm").default,
	Dictionary: require("./Dictionary").default,
	Endian: require("./Endian").default,
	Future: require("./Future").default,
	IAssetCache: require("./IAssetCache").default,
	IDataInput: require("./IDataInput").default,
	IDataOutput: require("./IDataOutput").default,
	// IExternalizable: require("./IExternalizable").default,
	// Object: require("./Object").default,
	Timer: require("./Timer").default,
	getDefinitionByName: require("./getDefinitionByName").default,
	getQualifiedClassName: require("./getQualifiedClassName").default,
	getQualifiedSuperclassName: require("./getQualifiedSuperclassName").default,
	getTimer: require("./getTimer").default,
	setTimeout: require("./setTimeout").default,
	clearTimeout: require("./clearTimeout").default,
}
<commit_msg>Update index.js<commit_after>module.exports = {
	AGALMiniAssembler: require("./AGALMiniAssembler").default,
	AssetCache: require("./AssetCache").default,
	AssetLibrary: require("./AssetLibrary").default,
	AssetManifest: require("./AssetManifest").default,
	Assets: require("./Assets").default,
	AssetType: require("./AssetType").default,
	ByteArray: require("./ByteArray").default,
	CompressionAlgorithm: require("./CompressionAlgorithm").default,
	Dictionary: require("./Dictionary").default,
	Endian: require("./Endian").default,
	Future: require("./Future").default,
	IAssetCache: require("./IAssetCache").default,
	IDataInput: require("./IDataInput").default,
	IDataOutput: require("./IDataOutput").default,
	// IExternalizable: require("./IExternalizable").default,
	// Object: require("./Object").default,
	Timer: require("./Timer").default,
	clearTimeout: require("./clearTimeout").default,
	getDefinitionByName: require("./getDefinitionByName").default,
	getQualifiedClassName: require("./getQualifiedClassName").default,
	getQualifiedSuperclassName: require("./getQualifiedSuperclassName").default,
	getTimer: require("./getTimer").default,
	setTimeout: require("./setTimeout").default,
}
<|endoftext|>


<commit_before>module.exports = {
  "extends": "airbnb",
  "plugins": [
    "react"
  ],
  "env": {
    "browser": true,
    "node": true,
    "jasmine": true,
    "worker": true
  },
  "globals": {
    "PIXI": true
  },
  "rules": {
    "no-use-before-define": "off",
    "no-param-reassign": "off"
  }
};<commit_msg>Modified eslintrc<commit_after>module.exports = {
  "extends": "airbnb",
  "env": {
    "browser": true,
    "node": true,
    "jasmine": true,
    "worker": true
  },
  "globals": {
    "PIXI": true
  },
  "rules": {
    "no-use-before-define": "off",
    "no-param-reassign": "off"
  }
};<|endoftext|>


<commit_before>const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const DashboardPlugin = require('webpack-dashboard/plugin');

const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './client/public/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: {
    app: [
      'babel-polyfill',
      'webpack-hot-middleware/client',
      './client/src/index.jsx',
    ]
  },
  output: {
    path: `${__dirname}/client/build`,
    filename: 'js/bundle.js',
    publicPath: '/static/',
  },
  resolve: {
    // you can now require("file") instead of require("file.coffee")
    extensions: ['.js', '.json', '.jsx']
  },
  node: {
    net: 'empty',
    tls: 'empty',
    dns: 'empty'
  },
  module: {
    loaders: [
      {
        test: /\.jsx*$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader'],
        }),
      },
      { test: /\.(woff|woff2)$/, loader: 'url-loader?prefix=font/&limit=5000&name=[path][name].[ext]' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=[path][name].[ext]' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader?limit=10000&mimetype=application/octet-stream&name=[path][name].[ext]' },
      {
        test: /\.(jpe?g|gif|png|svg)$/i,
        loader: 'url-loader?limit=10000&name=[path][name].[ext]',
      },

    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    HtmlWebpackPluginConfig,
    new ExtractTextPlugin({
      filename: 'css/style.css',
    }),
    new HtmlWebpackPlugin({
      title: 'more-recipes',
      template: './client/public/index.html',
      filename: 'index.html',
      inject: 'body'
    })
    // new CopyWebpackPlugin([
    //   { from: 'client/public/js/custom.js', to: 'client/build' }
    // ]),
    // new DashboardPlugin()
  ]
};
<commit_msg>refactor code to pass tests<commit_after>const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// const CopyWebpackPlugin = require('copy-webpack-plugin');
// const DashboardPlugin = require('webpack-dashboard/plugin');

const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './client/public/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: {
    app: [
      'babel-polyfill',
      'webpack-hot-middleware/client',
      './client/src/index.jsx',
    ]
  },
  output: {
    path: `${__dirname}/client/build`,
    filename: 'js/bundle.js',
    publicPath: '/static/',
  },
  resolve: {
    // you can now require("file") instead of require("file.coffee")
    extensions: ['.js', '.json', '.jsx']
  },
  node: {
    net: 'empty',
    tls: 'empty',
    dns: 'empty'
  },
  module: {
    loaders: [
      {
        test: /\.jsx*$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader'],
        }),
      },
      { test: /\.(woff|woff2)$/, loader: 'url-loader?prefix=font/&limit=5000&name=[path][name].[ext]' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=[path][name].[ext]' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader?limit=10000&mimetype=application/octet-stream&name=[path][name].[ext]' },
      {
        test: /\.(jpe?g|gif|png|svg)$/i,
        loader: 'url-loader?limit=10000&name=[path][name].[ext]',
      },

    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    HtmlWebpackPluginConfig,
    new ExtractTextPlugin({
      filename: 'css/style.css',
    }),
    new HtmlWebpackPlugin({
      title: 'more-recipes',
      template: './client/public/index.html',
      filename: 'index.html',
      inject: 'body'
    })
    // new CopyWebpackPlugin([
    //   { from: 'client/public/js/custom.js', to: 'client/build' }
    // ]),
    // new DashboardPlugin()
  ]
};
<|endoftext|>