<commit_before>/**
 * Gray theme for Highcharts JS
 * @author Torstein Honsi
 *
 * modified for elasticboard
 */

Highcharts.theme = {
	colors: ["#7798BF", "#7798BF", "#55BF3B", "#DF5353", "#aaeeee", "#ff0066", "#eeaaee",
		"#55BF3B", "#DF5353", "#DDDF0D", "#aaeeee"],
	chart: {
		backgroundColor: "rgb(31, 31, 31)",
		borderWidth: 0,
		borderRadius: 0,
		plotBackgroundColor: null,
		plotShadow: false,
		plotBorderWidth: 0
	},
	title: {
		style: {
			color: '#FFF',
			font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
		}
	},
	subtitle: {
		style: {
			color: '#DDD',
			font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
		}
	},
	xAxis: {
		gridLineWidth: 0,
		lineColor: '#999',
		tickColor: '#999',
		labels: {
			style: {
				color: '#999',
				fontWeight: 'bold'
			}
		},
		title: {
			style: {
				color: '#AAA',
				font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
			}
		}
	},
	yAxis: {
		alternateGridColor: null,
		minorTickInterval: null,
		gridLineColor: 'rgba(255, 255, 255, .1)',
		minorGridLineColor: 'rgba(255,255,255,0.07)',
		lineWidth: 0,
		tickWidth: 0,
		labels: {
			style: {
				color: '#999',
				fontWeight: 'bold'
			}
		},
		title: {
			style: {
				color: '#AAA',
				font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
			}
		}
	},
	legend: {
		itemStyle: {
			color: '#CCC'
		},
		itemHoverStyle: {
			color: '#FFF'
		},
		itemHiddenStyle: {
			color: '#333'
		}
	},
	labels: {
		style: {
			color: '#CCC'
		}
	},
	tooltip: {
		backgroundColor: {
			linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
			stops: [
				[0, 'rgba(96, 96, 96, .8)'],
				[1, 'rgba(16, 16, 16, .8)']
			]
		},
		borderWidth: 0,
		style: {
			color: '#FFF'
		}
	},

	plotOptions: {
		series: {
			shadow: true
		},
		line: {
			dataLabels: {
				color: '#CCC'
			},
			marker: {
				lineColor: '#333'
			}
		},
		spline: {
			marker: {
				lineColor: '#333'
			}
		},
		scatter: {
			marker: {
				lineColor: '#333'
			}
		},
		candlestick: {
			lineColor: 'white'
		}
	},

	toolbar: {
		itemStyle: {
			color: '#CCC'
		}
	},

	navigation: {
		buttonOptions: {
			symbolStroke: '#DDDDDD',
			hoverSymbolStroke: '#FFFFFF',
			theme: {
				fill: {
					linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
					stops: [
						[0.4, '#606060'],
						[0.6, '#333333']
					]
				},
				stroke: '#000000'
			}
		}
	},

	// scroll charts
	rangeSelector: {
		buttonTheme: {
			fill: {
				linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
				stops: [
					[0.4, '#888'],
					[0.6, '#555']
				]
			},
			stroke: '#000000',
			style: {
				color: '#CCC',
				fontWeight: 'bold'
			},
			states: {
				hover: {
					fill: {
						linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
						stops: [
							[0.4, '#BBB'],
							[0.6, '#888']
						]
					},
					stroke: '#000000',
					style: {
						color: 'white'
					}
				},
				select: {
					fill: {
						linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
						stops: [
							[0.1, '#000'],
							[0.3, '#333']
						]
					},
					stroke: '#000000',
					style: {
						color: 'yellow'
					}
				}
			}
		},
		inputStyle: {
			backgroundColor: '#333',
			color: 'silver'
		},
		labelStyle: {
			color: 'silver'
		}
	},

	navigator: {
		handles: {
			backgroundColor: '#666',
			borderColor: '#AAA'
		},
		outlineColor: '#CCC',
		maskFill: 'rgba(16, 16, 16, 0.5)',
		series: {
			color: '#7798BF',
			lineColor: '#A6C7ED'
		}
	},

	scrollbar: {
		barBackgroundColor: {
				linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
				stops: [
					[0.4, '#888'],
					[0.6, '#555']
				]
			},
		barBorderColor: '#CCC',
		buttonArrowColor: '#CCC',
		buttonBackgroundColor: {
				linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
				stops: [
					[0.4, '#888'],
					[0.6, '#555']
				]
			},
		buttonBorderColor: '#CCC',
		rifleColor: '#FFF',
		trackBackgroundColor: {
			linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
			stops: [
				[0, '#000'],
				[1, '#333']
			]
		},
		trackBorderColor: '#666'
	},

	// special colors for some of the demo examples
	legendBackgroundColor: 'rgba(48, 48, 48, 0.8)',
	legendBackgroundColorSolid: 'rgb(70, 70, 70)',
	dataLabelsColor: '#444',
	textColor: '#E0E0E0',
	maskColor: 'rgba(255,255,255,0.3)'
};

// Apply the theme
var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
<commit_msg>Distinguish colors in theme.<commit_after>/**
 * Gray theme for Highcharts JS
 * @author Torstein Honsi
 *
 * modified for elasticboard
 */

Highcharts.theme = {
	colors: ["#7798BF", "#7776FF", "#55BF3B", "#DF5353", "#aaeeee", "#ff0066", "#eeaaee",
		"#55BF3B", "#DF5353", "#DDDF0D", "#aaeebb"],
	chart: {
		backgroundColor: "rgb(31, 31, 31)",
		borderWidth: 0,
		borderRadius: 0,
		plotBackgroundColor: null,
		plotShadow: false,
		plotBorderWidth: 0
	},
	title: {
		style: {
			color: '#FFF',
			font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
		}
	},
	subtitle: {
		style: {
			color: '#DDD',
			font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
		}
	},
	xAxis: {
		gridLineWidth: 0,
		lineColor: '#999',
		tickColor: '#999',
		labels: {
			style: {
				color: '#999',
				fontWeight: 'bold'
			}
		},
		title: {
			style: {
				color: '#AAA',
				font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
			}
		}
	},
	yAxis: {
		alternateGridColor: null,
		minorTickInterval: null,
		gridLineColor: 'rgba(255, 255, 255, .1)',
		minorGridLineColor: 'rgba(255,255,255,0.07)',
		lineWidth: 0,
		tickWidth: 0,
		labels: {
			style: {
				color: '#999',
				fontWeight: 'bold'
			}
		},
		title: {
			style: {
				color: '#AAA',
				font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
			}
		}
	},
	legend: {
		itemStyle: {
			color: '#CCC'
		},
		itemHoverStyle: {
			color: '#FFF'
		},
		itemHiddenStyle: {
			color: '#333'
		}
	},
	labels: {
		style: {
			color: '#CCC'
		}
	},
	tooltip: {
		backgroundColor: {
			linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
			stops: [
				[0, 'rgba(96, 96, 96, .8)'],
				[1, 'rgba(16, 16, 16, .8)']
			]
		},
		borderWidth: 0,
		style: {
			color: '#FFF'
		}
	},

	plotOptions: {
		series: {
			shadow: true
		},
		line: {
			dataLabels: {
				color: '#CCC'
			},
			marker: {
				lineColor: '#333'
			}
		},
		spline: {
			marker: {
				lineColor: '#333'
			}
		},
		scatter: {
			marker: {
				lineColor: '#333'
			}
		},
		candlestick: {
			lineColor: 'white'
		}
	},

	toolbar: {
		itemStyle: {
			color: '#CCC'
		}
	},

	navigation: {
		buttonOptions: {
			symbolStroke: '#DDDDDD',
			hoverSymbolStroke: '#FFFFFF',
			theme: {
				fill: {
					linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
					stops: [
						[0.4, '#606060'],
						[0.6, '#333333']
					]
				},
				stroke: '#000000'
			}
		}
	},

	// scroll charts
	rangeSelector: {
		buttonTheme: {
			fill: {
				linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
				stops: [
					[0.4, '#888'],
					[0.6, '#555']
				]
			},
			stroke: '#000000',
			style: {
				color: '#CCC',
				fontWeight: 'bold'
			},
			states: {
				hover: {
					fill: {
						linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
						stops: [
							[0.4, '#BBB'],
							[0.6, '#888']
						]
					},
					stroke: '#000000',
					style: {
						color: 'white'
					}
				},
				select: {
					fill: {
						linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
						stops: [
							[0.1, '#000'],
							[0.3, '#333']
						]
					},
					stroke: '#000000',
					style: {
						color: 'yellow'
					}
				}
			}
		},
		inputStyle: {
			backgroundColor: '#333',
			color: 'silver'
		},
		labelStyle: {
			color: 'silver'
		}
	},

	navigator: {
		handles: {
			backgroundColor: '#666',
			borderColor: '#AAA'
		},
		outlineColor: '#CCC',
		maskFill: 'rgba(16, 16, 16, 0.5)',
		series: {
			color: '#7798BF',
			lineColor: '#A6C7ED'
		}
	},

	scrollbar: {
		barBackgroundColor: {
				linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
				stops: [
					[0.4, '#888'],
					[0.6, '#555']
				]
			},
		barBorderColor: '#CCC',
		buttonArrowColor: '#CCC',
		buttonBackgroundColor: {
				linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
				stops: [
					[0.4, '#888'],
					[0.6, '#555']
				]
			},
		buttonBorderColor: '#CCC',
		rifleColor: '#FFF',
		trackBackgroundColor: {
			linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
			stops: [
				[0, '#000'],
				[1, '#333']
			]
		},
		trackBorderColor: '#666'
	},

	// special colors for some of the demo examples
	legendBackgroundColor: 'rgba(48, 48, 48, 0.8)',
	legendBackgroundColorSolid: 'rgb(70, 70, 70)',
	dataLabelsColor: '#444',
	textColor: '#E0E0E0',
	maskColor: 'rgba(255,255,255,0.3)'
};

// Apply the theme
var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
<|endoftext|>


<commit_before>export const PAGE_SIZE = 10

export const RESULT_TYPES = {
    UNKNOWN: 'unknown',
    BOOKMARK: 'bookmark',
    VISIT: 'visit',
}

export const SEARCH_CONN_NAME = 'search-bg-ui-runtime-connection'

/** Commands used for BG <-> UI bi-directional communication actions */
export const CMDS = {
    SEARCH: `${SEARCH_CONN_NAME}/SEARCH`,
    RESULTS: `${SEARCH_CONN_NAME}/RESULTS`,
    ERROR: `${SEARCH_CONN_NAME}/ERROR`,
}

export const DATE_PICKER_DATE_FORMAT = 'DD-MM-YYYY'

export const SEARCH_COUNT_KEY = 'number-of-searches'

export const EGG_TITLE = 'Cheers to the awesome crew which made Memex possible'
export const EGG_URL = '/options/options.html#/acknowledgements'
export const EGG_IMG = '/../../../../img/thanks.gif'
<commit_msg>change text<commit_after>export const PAGE_SIZE = 10

export const RESULT_TYPES = {
    UNKNOWN: 'unknown',
    BOOKMARK: 'bookmark',
    VISIT: 'visit',
}

export const SEARCH_CONN_NAME = 'search-bg-ui-runtime-connection'

/** Commands used for BG <-> UI bi-directional communication actions */
export const CMDS = {
    SEARCH: `${SEARCH_CONN_NAME}/SEARCH`,
    RESULTS: `${SEARCH_CONN_NAME}/RESULTS`,
    ERROR: `${SEARCH_CONN_NAME}/ERROR`,
}

export const DATE_PICKER_DATE_FORMAT = 'DD-MM-YYYY'

export const SEARCH_COUNT_KEY = 'number-of-searches'

export const EGG_TITLE = 'Cheers to the awesome crew that made Memex possible'
export const EGG_URL = '/options/options.html#/acknowledgements'
export const EGG_IMG = '/../../../../img/thanks.gif'
<|endoftext|>


<commit_before>class Entity {
  owner = null;
  constructor(owner) {
    this.owner = owner;
  }

  /**
   * This also tracks debuffs in the exact same array. There are no parameters to filter results by debuffs. I don't think this should be necessary as debuffs and buffs usually have different spell IDs.
   */

  buffs = [];

  /**
   * @param {number} timestamp - Timestamp (in ms) to be considered, or the current timestamp if null. Won't work right for timestamps after the currentTimestamp.
   * @param {number} bufferTime - Time (in ms) after buff's expiration where it will still be included. There's a bug in the combat log where if a spell consumes a buff that buff may disappear a short time before the heal or damage event it's buffing is logged. This can sometimes go up to hundreds of milliseconds.
   * @param {number} minimalActiveTime - Time (in ms) the buff must have been active before timestamp for it to be included.
   * @returns {function} The buffs within the time period.
   */
  static activeAtTimestampFilter(timestamp, bufferTime = 0, minimalActiveTime = 0) {
    return buff => (timestamp - minimalActiveTime) >= buff.start && (buff.end === null || (buff.end + bufferTime) >= timestamp);
  }
  static spellIdFilter(spellId) {
    const nSpellId = Number(spellId);
    return buff => buff.ability.guid === nSpellId;
  }
  static sourceIdFilter(sourceID) {
    if (sourceID === null) {
      return () => true;
    }
    return buff => buff.sourceID === sourceID;
  }

  activeBuffs(forTimestamp = null, bufferTime = 0, minimalActiveTime = 0) {
    const currentTimestamp = forTimestamp !== null ? forTimestamp : this.owner.currentTimestamp;
    return this.buffs.filter(this.constructor.activeAtTimestampFilter(currentTimestamp, bufferTime, minimalActiveTime));
  }

  /**
   * @param {number} spellId buff ID to check for
   * @param {number} forTimestamp Timestamp (in ms) to be considered, or the current timestamp if null. Won't work right for timestamps after the currentTimestamp.
   * @param {number} bufferTime Time (in ms) after buff's expiration where it will still be included. There's a bug in the combat log where if a spell consumes a buff that buff may disappear a short time before the heal or damage event it's buffing is logged. This can sometimes go up to hundreds of milliseconds.
   * @param {number} minimalActiveTime - Time (in ms) the buff must have been active before timestamp for it to be included.
   * @param {number} sourceID - source ID the buff must have come from, or any source if null
   * @returns {boolean} - Whether the buff is present with the given specifications.
   */
  hasBuff(spellId, forTimestamp = null, bufferTime = 0, minimalActiveTime = 0, sourceID = null) {
    return this.getBuff(spellId, forTimestamp, bufferTime, minimalActiveTime, sourceID) !== undefined;
  }

  /**
   * @param {number} spellId - buff ID to check for
   * @param {number} forTimestamp Timestamp (in ms) to be considered, or the current timestamp if null. Won't work right for timestamps after the currentTimestamp.
   * @param {number} bufferTime Time (in ms) after buff's expiration where it will still be included. There's a bug in the combat log where if a spell consumes a buff that buff may disappear a short time before the heal or damage event it's buffing is logged. This can sometimes go up to hundreds of milliseconds.
   * @param {number} minimalActiveTime - Time (in ms) the buff must have been active before timestamp for it to be included.
   * @param {number} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {Object} - A buff with the given specifications. The buff object will have all the properties of the associated applybuff event, along with a start timestamp, an end timestamp if the buff has fallen, and an isDebuff flag. If multiple buffs meet the specifications, there's no guarantee which you'll get (this could happen if multiple spells with the same spellId but from different sources are on the same target)
   */
  getBuff(spellId, forTimestamp = null, bufferTime = 0, minimalActiveTime = 0, sourceID = null) {
    const currentTimestamp = forTimestamp !== null ? forTimestamp : this.owner.currentTimestamp;
    const isCorrectSpell = this.constructor.spellIdFilter(spellId);
    const isActive = this.constructor.activeAtTimestampFilter(currentTimestamp, bufferTime, minimalActiveTime);
    const isCorrectSource = this.constructor.sourceIdFilter(sourceID);
    return this.buffs.find(buff => isCorrectSpell(buff) && isActive(buff) && isCorrectSource(buff));
  }

  /**
   * @param {number} spellId - buff ID to check for
   * @param {number} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {array} The buff activations.
   */
  getBuffHistory(spellId, sourceID = null) {
    const isCorrectSpell = this.constructor.spellIdFilter(spellId);
    const isCorrectSource = this.constructor.sourceIdFilter(sourceID);
    return this.buffs.filter(buff => isCorrectSpell(buff) && isCorrectSource(buff));
  }
  /**
   * @param {number} spellId - buff ID to check for
   * @param {number} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {number} - Time (in ms) the specified buff has been active.
   */
  getBuffUptime(spellId, sourceID = null) {
    return this.getBuffHistory(spellId, sourceID)
      .reduce((uptime, buff) => uptime + (buff.end !== null ? buff.end : this.owner.currentTimestamp) - buff.start, 0);
  }
  /**
   * @param {number} spellId - buff ID to check for
   * @param {number|null} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {number} - The number of times the specified buff has been applied (only applications count, not stack changes or refreshes).
   */
  getBuffTriggerCount(spellId, sourceID = null) {
    return this.getBuffHistory(spellId, sourceID).length;
  }

  /**
  * @param {number} spellId - buff ID to check for
  * @param {number|null} sourceID - source ID the buff must have come from, or any source if null.
  * @returns {array} - Time (in ms) the specified buff has been active at each stack count.
  */
  getStackBuffUptimes(spellId, sourceID = null){
    const stackUptimes = {0: this.owner.fightDuration};
    this.getBuffHistory(spellId, sourceID)
      .forEach((buff, idx, arr) => {
        let startTime;
        let startStacks;
        buff.stackHistory.forEach((stack, idx, arr) => {
          if(startStacks !== undefined){
            const duration = !startTime ? 0 : (stack.timestamp - startTime);
            stackUptimes[startStacks] = (stackUptimes[startStacks] || 0) + duration;
            stackUptimes[0] -= duration; //reduce time spent at no stacks by time spent at current stack
          }

          startTime = stack.timestamp;
          startStacks = stack.stacks;
          if (buff.end === null && idx === arr.length - 1) {
            // If the buff instance didn't end (usually because it was still active at the end of the fight) we need to manually account for it
            const finalStackUptime = this.owner.currentTimestamp - startTime;
            stackUptimes[startStacks] += finalStackUptime;
            stackUptimes[0] -= finalStackUptime; //reduce time spent at no stacks by time spent at current stack
          }
        });
      });
    return stackUptimes;
  }

  /**
   * @param {number} spellId - buff ID to check for
   * @param {number|null} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {number} - Time (in ms) the specified buff has been active weighted by the number of stacks active.
   *      For example if buff was up for 10000ms with 1 stack and 20000ms with 2 stacks, would return 50000.
   */
  getStackWeightedBuffUptime(spellId, sourceID = null) {
    const stackBuffUptimes = this.getStackBuffUptimes(spellId, sourceID);
    return Object.keys(stackBuffUptimes).map(stack => stackBuffUptimes[stack] * stack).reduce((total, cur) => {
      return total + cur;
    }, 0);
  }

  applyBuff(buff) {
    this.buffs.push({
      end: null,
      stackHistory: [{ stacks: 1, timestamp: buff.timestamp }],
      stacks: 1,
      ...buff,
    });
  }
}

export default Entity;
<commit_msg>function documentation indents<commit_after>class Entity {
  owner = null;
  constructor(owner) {
    this.owner = owner;
  }

  /**
   * This also tracks debuffs in the exact same array. There are no parameters to filter results by debuffs. I don't think this should be necessary as debuffs and buffs usually have different spell IDs.
   */

  buffs = [];

  /**
   * @param {number} timestamp - Timestamp (in ms) to be considered, or the current timestamp if null. Won't work right for timestamps after the currentTimestamp.
   * @param {number} bufferTime - Time (in ms) after buff's expiration where it will still be included. There's a bug in the combat log where if a spell consumes a buff that buff may disappear a short time before the heal or damage event it's buffing is logged. This can sometimes go up to hundreds of milliseconds.
   * @param {number} minimalActiveTime - Time (in ms) the buff must have been active before timestamp for it to be included.
   * @returns {function} The buffs within the time period.
   */
  static activeAtTimestampFilter(timestamp, bufferTime = 0, minimalActiveTime = 0) {
    return buff => (timestamp - minimalActiveTime) >= buff.start && (buff.end === null || (buff.end + bufferTime) >= timestamp);
  }
  static spellIdFilter(spellId) {
    const nSpellId = Number(spellId);
    return buff => buff.ability.guid === nSpellId;
  }
  static sourceIdFilter(sourceID) {
    if (sourceID === null) {
      return () => true;
    }
    return buff => buff.sourceID === sourceID;
  }

  activeBuffs(forTimestamp = null, bufferTime = 0, minimalActiveTime = 0) {
    const currentTimestamp = forTimestamp !== null ? forTimestamp : this.owner.currentTimestamp;
    return this.buffs.filter(this.constructor.activeAtTimestampFilter(currentTimestamp, bufferTime, minimalActiveTime));
  }

  /**
   * @param {number} spellId buff ID to check for
   * @param {number} forTimestamp Timestamp (in ms) to be considered, or the current timestamp if null. Won't work right for timestamps after the currentTimestamp.
   * @param {number} bufferTime Time (in ms) after buff's expiration where it will still be included. There's a bug in the combat log where if a spell consumes a buff that buff may disappear a short time before the heal or damage event it's buffing is logged. This can sometimes go up to hundreds of milliseconds.
   * @param {number} minimalActiveTime - Time (in ms) the buff must have been active before timestamp for it to be included.
   * @param {number} sourceID - source ID the buff must have come from, or any source if null
   * @returns {boolean} - Whether the buff is present with the given specifications.
   */
  hasBuff(spellId, forTimestamp = null, bufferTime = 0, minimalActiveTime = 0, sourceID = null) {
    return this.getBuff(spellId, forTimestamp, bufferTime, minimalActiveTime, sourceID) !== undefined;
  }

  /**
   * @param {number} spellId - buff ID to check for
   * @param {number} forTimestamp Timestamp (in ms) to be considered, or the current timestamp if null. Won't work right for timestamps after the currentTimestamp.
   * @param {number} bufferTime Time (in ms) after buff's expiration where it will still be included. There's a bug in the combat log where if a spell consumes a buff that buff may disappear a short time before the heal or damage event it's buffing is logged. This can sometimes go up to hundreds of milliseconds.
   * @param {number} minimalActiveTime - Time (in ms) the buff must have been active before timestamp for it to be included.
   * @param {number} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {Object} - A buff with the given specifications. The buff object will have all the properties of the associated applybuff event, along with a start timestamp, an end timestamp if the buff has fallen, and an isDebuff flag. If multiple buffs meet the specifications, there's no guarantee which you'll get (this could happen if multiple spells with the same spellId but from different sources are on the same target)
   */
  getBuff(spellId, forTimestamp = null, bufferTime = 0, minimalActiveTime = 0, sourceID = null) {
    const currentTimestamp = forTimestamp !== null ? forTimestamp : this.owner.currentTimestamp;
    const isCorrectSpell = this.constructor.spellIdFilter(spellId);
    const isActive = this.constructor.activeAtTimestampFilter(currentTimestamp, bufferTime, minimalActiveTime);
    const isCorrectSource = this.constructor.sourceIdFilter(sourceID);
    return this.buffs.find(buff => isCorrectSpell(buff) && isActive(buff) && isCorrectSource(buff));
  }

  /**
   * @param {number} spellId - buff ID to check for
   * @param {number} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {array} The buff activations.
   */
  getBuffHistory(spellId, sourceID = null) {
    const isCorrectSpell = this.constructor.spellIdFilter(spellId);
    const isCorrectSource = this.constructor.sourceIdFilter(sourceID);
    return this.buffs.filter(buff => isCorrectSpell(buff) && isCorrectSource(buff));
  }
  /**
   * @param {number} spellId - buff ID to check for
   * @param {number} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {number} - Time (in ms) the specified buff has been active.
   */
  getBuffUptime(spellId, sourceID = null) {
    return this.getBuffHistory(spellId, sourceID)
      .reduce((uptime, buff) => uptime + (buff.end !== null ? buff.end : this.owner.currentTimestamp) - buff.start, 0);
  }
  /**
   * @param {number} spellId - buff ID to check for
   * @param {number|null} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {number} - The number of times the specified buff has been applied (only applications count, not stack changes or refreshes).
   */
  getBuffTriggerCount(spellId, sourceID = null) {
    return this.getBuffHistory(spellId, sourceID).length;
  }

  /**
   * @param {number} spellId - buff ID to check for
   * @param {number|null} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {array} - Time (in ms) the specified buff has been active at each stack count.
   */
  getStackBuffUptimes(spellId, sourceID = null){
    const stackUptimes = {0: this.owner.fightDuration};
    this.getBuffHistory(spellId, sourceID)
      .forEach((buff, idx, arr) => {
        let startTime;
        let startStacks;
        buff.stackHistory.forEach((stack, idx, arr) => {
          if(startStacks !== undefined){
            const duration = !startTime ? 0 : (stack.timestamp - startTime);
            stackUptimes[startStacks] = (stackUptimes[startStacks] || 0) + duration;
            stackUptimes[0] -= duration; //reduce time spent at no stacks by time spent at current stack
          }

          startTime = stack.timestamp;
          startStacks = stack.stacks;
          if (buff.end === null && idx === arr.length - 1) {
            // If the buff instance didn't end (usually because it was still active at the end of the fight) we need to manually account for it
            const finalStackUptime = this.owner.currentTimestamp - startTime;
            stackUptimes[startStacks] += finalStackUptime;
            stackUptimes[0] -= finalStackUptime; //reduce time spent at no stacks by time spent at current stack
          }
        });
      });
    return stackUptimes;
  }

  /**
   * @param {number} spellId - buff ID to check for
   * @param {number|null} sourceID - source ID the buff must have come from, or any source if null.
   * @returns {number} - Time (in ms) the specified buff has been active weighted by the number of stacks active.
   *      For example if buff was up for 10000ms with 1 stack and 20000ms with 2 stacks, would return 50000.
   */
  getStackWeightedBuffUptime(spellId, sourceID = null) {
    const stackBuffUptimes = this.getStackBuffUptimes(spellId, sourceID);
    return Object.keys(stackBuffUptimes).map(stack => stackBuffUptimes[stack] * stack).reduce((total, cur) => {
      return total + cur;
    }, 0);
  }

  applyBuff(buff) {
    this.buffs.push({
      end: null,
      stackHistory: [{ stacks: 1, timestamp: buff.timestamp }],
      stacks: 1,
      ...buff,
    });
  }
}

export default Entity;
<|endoftext|>


<commit_before>$(document).ready(function() {
     audio = $("#theaudio")[0];
     renders = $('#renders');
     rendersMask = $('#rendersMask');
     capcal = $('#capcal');
     capcalTotal = $('#capcalTotal');
     renderTotal = $('#renderTotal');
     zoomFactor = "";
     waveform = $('#renderTotal img');
     plButton = $("#control .plButton");
     timecode = $("#timecode");
     zooms = $(".zoom");
     // What point in seconds the left-hand side of the
     // image refers to.
     beginningOfView = 0;
     // The 900 pitch values currently on screen
     pitchvals = new Array(900);
	 waveform.click(function(e) {
	 	var offset_l = $(this).offset().left - $(window).scrollLeft();
		var left = Math.round( (e.clientX - offset_l) );
	    mouPlay(left);
	 });
     waveform.mouseenter(function() {
         if (pagesound.duration) {
             waveform.css("cursor", "pointer");
         } else {
             waveform.css("cursor", "wait");
         }
     });
     $(".zoom").click(function() {
         var level = $(this).data("length");
         zoom(level);
     });
     loaddata();

     $("#showRhythm").click(function(e) {
        drawwaveform();
     });

     soundManager.onready(function() {
         pagesound = soundManager.createSound({
               url: audiourl
         });

     });
});

function plotsa(context) {
    // Sa and sa+1 line.
    context.beginPath();
    // sa+1, dotted
    context.moveTo(0, 128);
    for (var i = 0; i < 900; i+=10) {
        context.moveTo(i, 128.5);
        context.lineTo(i+5, 128.5);
    }
    // sa, solid
    context.moveTo(0, 192.5);
    context.lineTo(900, 192.5);
    context.strokeStyle = "#eee";
    context.lineWidth = 1;
    context.stroke();
    context.closePath()
}

function spectrogram(context, view) {
    plotsa(context);
    var waszero = false;
    context.moveTo(0, 10);
    context.lineTo(10, 10);
    context.moveTo(0,0);
    var skip = secondsPerView / 4;
    // Start is in samples
    var start = (beginningOfView / secondsPerView) * 900 * skip;
    // Number of pixels we draw
    var end = Math.min(900+start, start+(view.length-start)/skip);
    var remaining = view.length-start;
    //console.debug("length " + view.length);
    //console.debug(remaining + " samples remaining");
    //console.debug("with skip, " + (remaining/skip) + " rem");
    //console.debug("skip " + skip);
    //console.debug("draw from " + start + " to " + end);
    context.beginPath();
    for (var i = start; i < end; i++) {
        // Find our point
        var xpos = i-start;
        var dataindex = start + xpos*skip;
        var data = view[dataindex];
        // Invert on canvas
        var tmp = 255-data;
        //console.debug(" at ("+xpos+","+tmp+") data " + dataindex);
        // We choose 0 if the pitch is unknown, or 255 if it's
        // higher than the 3 octaves above tonic. If so, we don't
        // want to draw something, just skip until the next value
        if (tmp == 0 || tmp == 255) {
            waszero = true;
            context.moveTo(xpos, tmp);
        } else {
            if (waszero) {
                waszero = false;
                context.moveTo(xpos, tmp);
            } else {
                context.lineTo(xpos, tmp);
            }
        }
        // Set the pitchvals so we can draw the histogram
        pitchvals[xpos] = tmp;
    }

    context.strokeStyle = "#e71d25";
    context.lineWidth = 2;
    context.stroke();
    context.closePath();
}

function plothistogram(pitch) {
    pitch = pitch || 0;
    var histogram = $("#histogramcanvas")[0];
    histogram.width = 200;
    histogram.height = 256;
    var context = histogram.getContext("2d");
    //context.moveTo(180, 10);
    //context.lineTo(200, 10);
    //context.moveTo(200, 256);
    var max = 0;
    var data = histogramdata;
    for (var i = 0; i < data.length; i++) {
        if (data[i] > max) {
            max = data[i];
        }
    }
    var factor = 150 / max;
    context.beginPath();
    for (var i = 0; i < data.length; i++) {
        v = data[i] * factor;
        context.lineTo(200-v, 256-i);
    }
    context.lineWidth = 2;
    context.strokeStyle = "#e71d25";
    context.stroke();
    context.closePath();

    // Pitch
    if (pitch > 0 && pitch < 255) {
        pitch = Math.floor(pitch) + 0.5;
        context.beginPath();
        context.moveTo(0, pitch);
        context.lineTo(200, pitch);
        context.lineWidth = 1;
        context.strokeStyle = "#000";
        context.stroke();
        context.closePath();
    }
}

function plotpitch() {
    // In order to account for slow internet connections,
    // we always load one image ahead of what we need.
    // TODO: We need to know when the final image is.
    var spec = new Image();
    spec.src = specurl;
    var view = new Uint8Array(pitchdata);
    var canvas = $("#pitchcanvas")[0];
    canvas.width = 900;
    canvas.height = 256;
    var context = canvas.getContext("2d");
    spec.onload = function() {
        context.drawImage(spec, 0, 0);
        spectrogram(context, view);
    }
}

function drawwaveform() {
    var wave = new Image();
    wave.src = waveformurl;
    var canvas = $("#rhythmcanvas")[0];
    canvas.width = 900;
    canvas.height = 256;
    var context = canvas.getContext("2d");
    wave.onload = function() {
        context.drawImage(wave, 0, 0);
        plottempo(context, aksharadata);
        plotticks(context, rhythmdata);
    }
}

function sortNumber(a,b) {
    return a - b;
}

function plotticks(context, data) {
    // TODO: it looked like for some of this data
    // we were sorting by asciibetical not numeric
    data.sort(sortNumber);
    from = data[0];
    to = data[data.length-1];
    $("#pulseFrom").html(formatseconds(from));
    $("#pulseTo").html(formatseconds(to));
    var show = $("#showRhythm").is(':checked');

    if ((secondsPerView == 8 || secondsPerView == 4) && show) {
        context.beginPath();
        //console.debug("draw ticks");
        for (var i = 0; i < data.length; i++) {
            var val = data[i];
            var endVal = beginningOfView+secondsPerView;
            if (val > beginningOfView && val < endVal) {
                //console.debug("got a tick at " + val);
                // We draw it.
                var position = (val-beginningOfView) / secondsPerView * 900;
                position = Math.floor(position) + 0.5;
                //console.debug("drawing at " + position);
                context.moveTo(position, 0);
                context.lineTo(position, 255);
            }
        context.lineWidth = 1;
        context.strokeStyle = "#e71d25";
        context.stroke();
        }
        context.closePath();
    }
}

function plottempo(context, data) {
    var low = 1;
    var high = 0;
    for (var i = 0; i < data.length; i++) {
        var val = data[i][1];
        if (val > high) {
            high = val;
        }
        if (val < low) {
            low = val;
        }
    }
    $(".tempoup").html(high*1000 + " ms");
    $(".tempodown").html(low*1000 + " ms");
    high = high * 1.2;
    low = low * 0.8;
    var factor = 128 / (high - low);

    var secPerPixel = 900 / secondsPerView;
    var moved = false;
    context.beginPath();
    for (var i = 0; i < data.length; i++) {
        var time = data[i][0];
        if (time >= beginningOfView) {
            // Data points are every 0.5 seconds
            // TODO: This doesn't draw the point at or near x=0
            var x = (time-beginningOfView) * secPerPixel;
            if (x > 900) {
                break;
            }
            var y = (data[i][1]-low) * factor;
            y = Math.floor(y) + 0.5;
            if (!moved) {
                context.moveTo(0, 256-y);
                moved = true;
            }
            context.lineTo(x, 256-y);
            //console.debug("line at position "+y);
        }
    }
    context.strokeStyle = "#eee";
    context.lineWidth = 1;
    context.stroke();
    context.closePath();
}

function loaddata() {
    // We do pitch track with manual httprequest, because
    // we want typedarray access

    histogramDone = false;
    pitchDone = false;
    var oReq = new XMLHttpRequest();
    oReq.open("GET", pitchtrackurl, true);
    oReq.responseType = "arraybuffer";
    oReq.onload = function(oEvent) {
        if (oReq.status == 200) {
            pitchdata = oReq.response;
            pitchDone = true;
            dodraw();
        }
    };
    oReq.send();
    $.ajax(histogramurl, {dataType: "json", type: "GET",
        success: function(data, textStatus, xhr) {
            histogramdata = data;
            histogramDone = true;
            dodraw();
    }});

    var ticksDone = false;
    var rhythmDone = false;

    $.ajax(rhythmurl, {dataType: "json", type: "GET",
        success: function(data, textStatus, xhr) {
            rhythmdata = data;
            ticksDone = true;
            dodraw();
    }});

    $.ajax(aksharaurl, {dataType: "json", type: "GET",
        success: function(data, textStatus, xhr) {
            aksharadata = data;
            rhythmDone = true;
            dodraw();
    }});

    function dodraw() {
        if (ticksDone && rhythmDone && pitchDone && histogramDone) {
            drawdata();
        }
    }
}

function drawdata() {
    drawwaveform();
    plotpitch();
    plothistogram();
    var start = beginningOfView;
    var skip = secondsPerView / 4;
    $(".timecode1").html(formatseconds(start));
    $(".timecode2").html(formatseconds(start+skip));
    $(".timecode3").html(formatseconds(start+skip*2));
    $(".timecode4").html(formatseconds(start+skip*3));
    $(".timecode5").html(formatseconds(start+skip*4));
}

function mouPlay(desti){
    console.debug("play click!");
	percent = desti/waveform.width();
    console.debug("percent - "+percent);

    clickseconds = recordinglengthseconds * percent
	console.log(clickseconds+" - "+ recordinglengthseconds);

    posms = clickseconds * 1000;
    part = Math.ceil(clickseconds / secondsPerView);

    if (pagesound.duration) {
        // We can only set a position if it's fully loaded
        pagesound.pause();
        pagesound.setPosition(posms);
        replacepart(part);
        pagesound.play();
    }
}

function play() {
    pagesound.play({onfinish: function() {
        window.clearInterval(int);
    }});
    int = window.setInterval(updateProgress, 30);
}
function pause() {
    pagesound.pause();
    window.clearInterval(int);
}

function formatseconds(seconds) {
    progress_seconds = Math.ceil(seconds);
    progress_minutes = Math.floor(seconds/60);
    resto = (progress_seconds-(progress_minutes*60));
    // never show :60 in seconds part
    if (resto >= 60) {
        resto = 0;
        progress_minutes += 1;
    }
    if(resto<10){
		resto = "0"+resto;
    }
    if(progress_minutes<10){
		progress_minutes = "0"+progress_minutes;
    }
    timecodeHtml = ""+progress_minutes+":"+resto;
    return timecodeHtml;
}

function replacepart(pnum) {
    waveformurl = waveformurl.replace(/part=[0-9]+/, "part="+pnum);
    specurl = specurl.replace(/part=[0-9]+/, "part="+pnum);
    drawdata();
}

function updateProgress() {
    var currentTime = pagesound.position / 1000;
    // formatseconds appears to run 1 second ahead of time,
    // so correct for it here
    formattime = formatseconds(currentTime-1);
    progress_percent = (currentTime-beginningOfView) / secondsPerView * 100;
    total_progress_frac = (currentTime/recordinglengthseconds);
	ampleMask = rendersMask.width();
	ampleRenders = renders.width();
	ampleRenderTotal = renderTotal.width();
    leftLargeView = ((ampleRenders*progress_percent)/100);
    leftSmallView = ampleRenderTotal*total_progress_frac;
    capcal.css('left', leftLargeView-5);
    capcalTotal.css('left', leftSmallView-6);

    if (leftLargeView > 900) {
        beginningOfView += secondsPerView;
        pnum = Math.floor(beginningOfView / secondsPerView + 1);
        replacepart(pnum)
    }
    timecode.html(formattime + "<span>"+recordinglengthfmt+"</span>");

    // Current pitch
    var pitchindex = Math.floor(leftLargeView);
    var p = pitchvals[pitchindex];
    plothistogram(p);
};

function zoom(level){
    secondsPerView = level;
    waveformurl = waveformurl.replace(/waveform[0-9]{1,2}/, "waveform"+level);
    specurl = specurl.replace(/spectrum[0-9]{1,2}/, "spectrum"+level);
    // When we go from a zoomed in to a zoomed out size,
    // we need to make sure that `beginningOfView` is on an
    // image boundary
    beginningOfView = Math.floor(beginningOfView / secondsPerView);
    pnum = Math.floor(beginningOfView / secondsPerView + 1);
    waveformurl = waveformurl.replace(/part=[0-9]+/, "part="+pnum);
    specurl = specurl.replace(/part=[0-9]+/, "part="+pnum);
    drawdata();
}

function playrecord(){
	if(plButton.hasClass("stop")){
		pause();
		plButton.removeClass("stop");
	}else{
		play();
		plButton.addClass("stop");
	}
}

<commit_msg>beginningofview cursor<commit_after>$(document).ready(function() {
     audio = $("#theaudio")[0];
     renders = $('#renders');
     rendersMask = $('#rendersMask');
     capcal = $('#capcal');
     capcalTotal = $('#capcalTotal');
     renderTotal = $('#renderTotal');
     zoomFactor = "";
     waveform = $('#renderTotal img');
     plButton = $("#control .plButton");
     timecode = $("#timecode");
     zooms = $(".zoom");
     // What point in seconds the left-hand side of the
     // image refers to.
     beginningOfView = 0;
     // The 900 pitch values currently on screen
     pitchvals = new Array(900);
	 waveform.click(function(e) {
	 	var offset_l = $(this).offset().left - $(window).scrollLeft();
		var left = Math.round( (e.clientX - offset_l) );
	    mouPlay(left);
	 });
     waveform.mouseenter(function() {
         if (pagesound.duration) {
             waveform.css("cursor", "pointer");
         } else {
             waveform.css("cursor", "wait");
         }
     });
     $(".zoom").click(function() {
         var level = $(this).data("length");
         zoom(level);
     });
     loaddata();

     $("#showRhythm").click(function(e) {
        drawwaveform();
     });

     soundManager.onready(function() {
         pagesound = soundManager.createSound({
               url: audiourl
         });

     });
});

function plotsa(context) {
    // Sa and sa+1 line.
    context.beginPath();
    // sa+1, dotted
    context.moveTo(0, 128);
    for (var i = 0; i < 900; i+=10) {
        context.moveTo(i, 128.5);
        context.lineTo(i+5, 128.5);
    }
    // sa, solid
    context.moveTo(0, 192.5);
    context.lineTo(900, 192.5);
    context.strokeStyle = "#eee";
    context.lineWidth = 1;
    context.stroke();
    context.closePath()
}

function spectrogram(context, view) {
    plotsa(context);
    var waszero = false;
    context.moveTo(0, 10);
    context.lineTo(10, 10);
    context.moveTo(0,0);
    var skip = secondsPerView / 4;
    // Start is in samples
    var start = (beginningOfView / secondsPerView) * 900 * skip;
    // Number of pixels we draw
    var end = Math.min(900+start, start+(view.length-start)/skip);
    var remaining = view.length-start;
    //console.debug("length " + view.length);
    //console.debug(remaining + " samples remaining");
    //console.debug("with skip, " + (remaining/skip) + " rem");
    //console.debug("skip " + skip);
    //console.debug("draw from " + start + " to " + end);
    context.beginPath();
    for (var i = start; i < end; i++) {
        // Find our point
        var xpos = i-start;
        var dataindex = start + xpos*skip;
        var data = view[dataindex];
        // Invert on canvas
        var tmp = 255-data;
        //console.debug(" at ("+xpos+","+tmp+") data " + dataindex);
        // We choose 0 if the pitch is unknown, or 255 if it's
        // higher than the 3 octaves above tonic. If so, we don't
        // want to draw something, just skip until the next value
        if (tmp == 0 || tmp == 255) {
            waszero = true;
            context.moveTo(xpos, tmp);
        } else {
            if (waszero) {
                waszero = false;
                context.moveTo(xpos, tmp);
            } else {
                context.lineTo(xpos, tmp);
            }
        }
        // Set the pitchvals so we can draw the histogram
        pitchvals[xpos] = tmp;
    }

    context.strokeStyle = "#e71d25";
    context.lineWidth = 2;
    context.stroke();
    context.closePath();
}

function plothistogram(pitch) {
    pitch = pitch || 0;
    var histogram = $("#histogramcanvas")[0];
    histogram.width = 200;
    histogram.height = 256;
    var context = histogram.getContext("2d");
    //context.moveTo(180, 10);
    //context.lineTo(200, 10);
    //context.moveTo(200, 256);
    var max = 0;
    var data = histogramdata;
    for (var i = 0; i < data.length; i++) {
        if (data[i] > max) {
            max = data[i];
        }
    }
    var factor = 150 / max;
    context.beginPath();
    for (var i = 0; i < data.length; i++) {
        v = data[i] * factor;
        context.lineTo(200-v, 256-i);
    }
    context.lineWidth = 2;
    context.strokeStyle = "#e71d25";
    context.stroke();
    context.closePath();

    // Pitch
    if (pitch > 0 && pitch < 255) {
        pitch = Math.floor(pitch) + 0.5;
        context.beginPath();
        context.moveTo(0, pitch);
        context.lineTo(200, pitch);
        context.lineWidth = 1;
        context.strokeStyle = "#000";
        context.stroke();
        context.closePath();
    }
}

function plotpitch() {
    // In order to account for slow internet connections,
    // we always load one image ahead of what we need.
    // TODO: We need to know when the final image is.
    var spec = new Image();
    spec.src = specurl;
    var view = new Uint8Array(pitchdata);
    var canvas = $("#pitchcanvas")[0];
    canvas.width = 900;
    canvas.height = 256;
    var context = canvas.getContext("2d");
    spec.onload = function() {
        context.drawImage(spec, 0, 0);
        spectrogram(context, view);
    }
}

function drawwaveform() {
    var wave = new Image();
    wave.src = waveformurl;
    var canvas = $("#rhythmcanvas")[0];
    canvas.width = 900;
    canvas.height = 256;
    var context = canvas.getContext("2d");
    wave.onload = function() {
        context.drawImage(wave, 0, 0);
        plottempo(context, aksharadata);
        plotticks(context, rhythmdata);
    }
}

function sortNumber(a,b) {
    return a - b;
}

function plotticks(context, data) {
    // TODO: it looked like for some of this data
    // we were sorting by asciibetical not numeric
    data.sort(sortNumber);
    from = data[0];
    to = data[data.length-1];
    $("#pulseFrom").html(formatseconds(from));
    $("#pulseTo").html(formatseconds(to));
    var show = $("#showRhythm").is(':checked');

    if ((secondsPerView == 8 || secondsPerView == 4) && show) {
        context.beginPath();
        //console.debug("draw ticks");
        for (var i = 0; i < data.length; i++) {
            var val = data[i];
            var endVal = beginningOfView+secondsPerView;
            if (val > beginningOfView && val < endVal) {
                //console.debug("got a tick at " + val);
                // We draw it.
                var position = (val-beginningOfView) / secondsPerView * 900;
                position = Math.floor(position) + 0.5;
                //console.debug("drawing at " + position);
                context.moveTo(position, 0);
                context.lineTo(position, 255);
            }
        context.lineWidth = 1;
        context.strokeStyle = "#e71d25";
        context.stroke();
        }
        context.closePath();
    }
}

function plottempo(context, data) {
    var low = 1;
    var high = 0;
    for (var i = 0; i < data.length; i++) {
        var val = data[i][1];
        if (val > high) {
            high = val;
        }
        if (val < low) {
            low = val;
        }
    }
    $(".tempoup").html(high*1000 + " ms");
    $(".tempodown").html(low*1000 + " ms");
    high = high * 1.2;
    low = low * 0.8;
    var factor = 128 / (high - low);

    var secPerPixel = 900 / secondsPerView;
    var moved = false;
    context.beginPath();
    for (var i = 0; i < data.length; i++) {
        var time = data[i][0];
        if (time >= beginningOfView) {
            // Data points are every 0.5 seconds
            // TODO: This doesn't draw the point at or near x=0
            var x = (time-beginningOfView) * secPerPixel;
            if (x > 900) {
                break;
            }
            var y = (data[i][1]-low) * factor;
            y = Math.floor(y) + 0.5;
            if (!moved) {
                context.moveTo(0, 256-y);
                moved = true;
            }
            context.lineTo(x, 256-y);
            //console.debug("line at position "+y);
        }
    }
    context.strokeStyle = "#eee";
    context.lineWidth = 1;
    context.stroke();
    context.closePath();
}

function loaddata() {
    // We do pitch track with manual httprequest, because
    // we want typedarray access

    histogramDone = false;
    pitchDone = false;
    var oReq = new XMLHttpRequest();
    oReq.open("GET", pitchtrackurl, true);
    oReq.responseType = "arraybuffer";
    oReq.onload = function(oEvent) {
        if (oReq.status == 200) {
            pitchdata = oReq.response;
            pitchDone = true;
            dodraw();
        }
    };
    oReq.send();
    $.ajax(histogramurl, {dataType: "json", type: "GET",
        success: function(data, textStatus, xhr) {
            histogramdata = data;
            histogramDone = true;
            dodraw();
    }});

    var ticksDone = false;
    var rhythmDone = false;

    $.ajax(rhythmurl, {dataType: "json", type: "GET",
        success: function(data, textStatus, xhr) {
            rhythmdata = data;
            ticksDone = true;
            dodraw();
    }});

    $.ajax(aksharaurl, {dataType: "json", type: "GET",
        success: function(data, textStatus, xhr) {
            aksharadata = data;
            rhythmDone = true;
            dodraw();
    }});

    function dodraw() {
        if (ticksDone && rhythmDone && pitchDone && histogramDone) {
            drawdata();
        }
    }
}

function drawdata() {
    drawwaveform();
    plotpitch();
    plothistogram();
    var start = beginningOfView;
    var skip = secondsPerView / 4;
    $(".timecode1").html(formatseconds(start));
    $(".timecode2").html(formatseconds(start+skip));
    $(".timecode3").html(formatseconds(start+skip*2));
    $(".timecode4").html(formatseconds(start+skip*3));
    $(".timecode5").html(formatseconds(start+skip*4));
}

function mouPlay(desti){
    console.debug("play click!");
	percent = desti/waveform.width();
    console.debug("percent - "+percent);

    clickseconds = recordinglengthseconds * percent
	console.log(clickseconds+" - "+ recordinglengthseconds);

    posms = clickseconds * 1000;
    part = Math.ceil(clickseconds / secondsPerView);
    // Update the internal position counter
    beginningOfView = part * secondsPerView;

    if (pagesound.duration) {
        // We can only set a position if it's fully loaded
        pagesound.pause();
        pagesound.setPosition(posms);
        replacepart(part);
        pagesound.play();
    }
}

function play() {
    pagesound.play({onfinish: function() {
        window.clearInterval(int);
    }});
    int = window.setInterval(updateProgress, 30);
}
function pause() {
    pagesound.pause();
    window.clearInterval(int);
}

function formatseconds(seconds) {
    progress_seconds = Math.ceil(seconds);
    progress_minutes = Math.floor(seconds/60);
    resto = (progress_seconds-(progress_minutes*60));
    // never show :60 in seconds part
    if (resto >= 60) {
        resto = 0;
        progress_minutes += 1;
    }
    if(resto<10){
		resto = "0"+resto;
    }
    if(progress_minutes<10){
		progress_minutes = "0"+progress_minutes;
    }
    timecodeHtml = ""+progress_minutes+":"+resto;
    return timecodeHtml;
}

function replacepart(pnum) {
    waveformurl = waveformurl.replace(/part=[0-9]+/, "part="+pnum);
    specurl = specurl.replace(/part=[0-9]+/, "part="+pnum);
    drawdata();
}

function updateProgress() {
    var currentTime = pagesound.position / 1000;
    // formatseconds appears to run 1 second ahead of time,
    // so correct for it here
    formattime = formatseconds(currentTime-1);
    progress_percent = (currentTime-beginningOfView) / secondsPerView * 100;
    total_progress_frac = (currentTime/recordinglengthseconds);
	ampleMask = rendersMask.width();
	ampleRenders = renders.width();
	ampleRenderTotal = renderTotal.width();
    leftLargeView = ((ampleRenders*progress_percent)/100);
    leftSmallView = ampleRenderTotal*total_progress_frac;
    capcal.css('left', leftLargeView-5);
    capcalTotal.css('left', leftSmallView-6);

    if (leftLargeView > 900) {
        beginningOfView += secondsPerView;
        pnum = Math.floor(beginningOfView / secondsPerView + 1);
        replacepart(pnum)
    }
    timecode.html(formattime + "<span>"+recordinglengthfmt+"</span>");

    // Current pitch
    var pitchindex = Math.floor(leftLargeView);
    var p = pitchvals[pitchindex];
    plothistogram(p);
};

function zoom(level){
    secondsPerView = level;
    waveformurl = waveformurl.replace(/waveform[0-9]{1,2}/, "waveform"+level);
    specurl = specurl.replace(/spectrum[0-9]{1,2}/, "spectrum"+level);
    // When we go from a zoomed in to a zoomed out size,
    // we need to make sure that `beginningOfView` is on an
    // image boundary
    beginningOfView = Math.floor(beginningOfView / secondsPerView);
    pnum = Math.floor(beginningOfView / secondsPerView + 1);
    waveformurl = waveformurl.replace(/part=[0-9]+/, "part="+pnum);
    specurl = specurl.replace(/part=[0-9]+/, "part="+pnum);
    drawdata();
}

function playrecord(){
	if(plButton.hasClass("stop")){
		pause();
		plButton.removeClass("stop");
	}else{
		play();
		plButton.addClass("stop");
	}
}

<|endoftext|>


<commit_before>(function(ns) {

    var namespaces = [this];

    var attachBehavior = function($element, behavior) {
        var fn = namespaces;

        behavior.replace(/([^.]+)/g, function(object) {
            if(fn === namespaces) {
                for(var nextFn, index = 0; index < fn.length; ++index) {
                    nextFn = fn[index][object];
                    if(nextFn) {
                        fn = nextFn;
                        break;
                    }
                }
            } else if(typeof fn === 'object') {
                fn = fn[object];
            }
        });

        if(typeof fn === 'function') {
            return fn($element);
        } else {
            if (window.console && console.warn) {
                console.warn("elementalJS: Unable to find behavior:", behavior);
            }
        }
    };

    ns.load = function(container) {
        var $selector;
        $selector = $('[data-behavior]', container);

        if ($(container).data('behavior')) {
            $selector = $selector.add(container);
        }

        $selector.each(function(index, element) {
            var $element = $(element);
            var behaviors = $element.data('behavior');
            behaviors.replace(/([^ ]+)/g, function(behavior) {
                attachBehavior($element, behavior);
            });
        });
    };

    ns.addNamespace = function(namespace) {
        namespaces.push(namespace);
    };

})(window.Elemental = {});
<commit_msg>Elemental.load() accepts HTML with multiple root nodes.<commit_after>(function(ns) {

    var namespaces = [this];

    var attachBehavior = function($element, behavior) {
        var fn = namespaces;

        behavior.replace(/([^.]+)/g, function(object) {
            if(fn === namespaces) {
                for(var nextFn, index = 0; index < fn.length; ++index) {
                    nextFn = fn[index][object];
                    if(nextFn) {
                        fn = nextFn;
                        break;
                    }
                }
            } else if(typeof fn === 'object') {
                fn = fn[object];
            }
        });

        if(typeof fn === 'function') {
            return fn($element);
        } else {
            if (window.console && console.warn) {
                console.warn("elementalJS: Unable to find behavior:", behavior);
            }
        }
    };

    ns.load = function(container) {
        var $selector = $('[data-behavior]', container).add($(container).filter('[data-behavior]'));

        $selector.each(function(index, element) {
            var $element = $(element);
            var behaviors = $element.data('behavior');
            behaviors.replace(/([^ ]+)/g, function(behavior) {
                attachBehavior($element, behavior);
            });
        });
    };

    ns.addNamespace = function(namespace) {
        namespaces.push(namespace);
    };

})(window.Elemental = {});
<|endoftext|>


<commit_before><commit_msg>remove version, change host and add authHost<commit_after><|endoftext|>


<commit_before><commit_msg>be standard<commit_after><|endoftext|>


<commit_before>const webpack = require('webpack');
const ora = require('ora');
const rm = require('rimraf');
const chalk = require('chalk');
const config = require('./webpack.config.js');

const env = process.env.NODE_ENV || 'development';
const target = process.env.TARGET || 'web';

const spinner = ora(env === 'production' ? 'building for production...' : 'building development version...');
spinner.start();

rm('./www/', (removeErr) => {
  if (removeErr) throw removeErr;

  webpack(config, (err, stats) => {
    if (err) throw err;
    spinner.stop();

    process.stdout.write(`${stats.toString({
      colors: true,
      modules: false,
      children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
      chunks: false,
      chunkModules: false,
    })}\n\n`);

    if (stats.hasErrors()) {
      console.log(chalk.red('Build failed with errors.\n'));
      process.exit(1);
    }

    console.log(chalk.cyan('Build complete.\n'));

	if (env == 'development')
      process.exit(0);
  });
});
<commit_msg>Fix spaces in previous commit<commit_after>const webpack = require('webpack');
const ora = require('ora');
const rm = require('rimraf');
const chalk = require('chalk');
const config = require('./webpack.config.js');

const env = process.env.NODE_ENV || 'development';
const target = process.env.TARGET || 'web';

const spinner = ora(env === 'production' ? 'building for production...' : 'building development version...');
spinner.start();

rm('./www/', (removeErr) => {
  if (removeErr) throw removeErr;

  webpack(config, (err, stats) => {
    if (err) throw err;
    spinner.stop();

    process.stdout.write(`${stats.toString({
      colors: true,
      modules: false,
      children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
      chunks: false,
      chunkModules: false,
    })}\n\n`);

    if (stats.hasErrors()) {
      console.log(chalk.red('Build failed with errors.\n'));
      process.exit(1);
    }

    console.log(chalk.cyan('Build complete.\n'));

    if (env == 'development')
      process.exit(0);
  });
});
<|endoftext|>


<commit_before><commit_msg>progress<commit_after><|endoftext|>


<commit_before><commit_msg>[fix] Handle cases where `socket.bufferSize` is `undefined`<commit_after><|endoftext|>


<commit_before>function prepareStage(type) {
	framesPainted = 0;
	currentType = type;

	switch(type) {
		case "canvas":
			var canvas = document.createElement("canvas");
			canvas.id = "canvas";
			canvas.setAttribute("width", stageWidth);
			canvas.setAttribute("height", stageHeight);
			stage.appendChild(canvas);
			context = canvas.getContext("2d");
		break;
		case "svg":
		case "svgtransforms":
		case "svgcsstransforms":
		case "svganimations":
		case "svgrebuild":
			svg = document.createElementNS(svg_ns, "svg");
			svg.id = "svgcontainer";
			svg.setAttribute("width", stageWidth);
			svg.setAttribute("height", stageHeight);
			stage.appendChild(svg);

		break;
		case "html":
			stage.style.width = stageWidth + 'px';
			stage.style.height = stageHeight + 'px';
		break;
	}

	buildStage();

}

function buildStage() {

	for (var i = 0; i < testSequence[currentTest].maxObjects; i++)
	{
		switch(testSequence[currentTest].object) {
			case 'Particle':
				stageElements.push(new Particle(currentType));
			break;
			case 'Bar':
				stageElements.push(new Bar(currentType,testSequence[currentTest].maxObjects,i));
			break;
		}

	}

	statistics.startTest();

	animateStage();

}

function animateStage() {
	tick = requestAnimationFrame(animateStage);
	var frameStartTimeStamp = setTimestamp();
	var currentTime = +new Date;

	var timeOffset = currentTime - previousTimeStamp;

	if (previousTimeStamp === null)
	{
		timeOffset = 0;
	}

	switch(currentType) {
		case 'canvas':
			context.clearRect(0, 0, stageWidth, stageHeight);
		break;
		case 'svgrebuild':
			while (svg.hasChildNodes()) {
				svg.removeChild(svg.lastChild);
			}
		break;

	}
	for (var stageElement in stageElements)
	{
		stageElements[stageElement].draw(timeOffset);
	}

	var paintTime = setTimestamp() - frameStartTimeStamp;

	++framesPainted;
	statistics.update(paintTime, previousTimeStamp);

	previousTimeStamp = currentTime;
	if (framesPainted > (testDuration -1)) {
		endAnimationTest();
	}
}

function endAnimationTest() {
		cancelAnimationFrame(tick);
		tick = null;
		clearStage();
		statistics.endTest();
		++currentTest;
		if (currentTest < testSequence.length) {
			prepareStage(testSequence[currentTest].type);
		}
		else {
			statistics.send();
		}
}

function clearStage() {
	while (stage.hasChildNodes()) {
		stage.removeChild(stage.lastChild);
	}
	framesPainted = 0, context = null, svg = null, previousTimeStamp = null, stageElements = [];
}

function Statistics() {

	var frameSmoothing = 30, minMS, maxMS, frames, breaks,
	sumMS, currentFPS, maxFPS, minFPS, prevTime, fpsSamples, sumFPS;
	var fpsNode = document.getElementById('fps'), currentTestNode = document.getElementById('currentTest'), currentTestNumber = document.getElementById('currentTestNumber'), totalTests = document.getElementById('totalTests');
	var remainingFrames = testSequence.length * testDuration, totalSkippedFrames = 0,
	remainingFramesNode = document.getElementById('remainingFrames'),
	skippedFramesNode = document.getElementById('skippedFrames'),
	testResults = [], passedTests = [];

	function killTest() {
		dnf = true;
		totalSkippedFrames += remainingFramesTest;
		remainingFrames -= remainingFramesTest;
		endAnimationTest();
		skippedFramesNode.innerHTML = "(Skipped Frames: " + totalSkippedFrames + ")";
	}

	this.startTest = function () {
	 	minMS = Infinity, maxMS = 0, frames = 0, breaks = 0,
		sumMS = 0, sumFPS = 0, fpsSamples = 0, maxFPS = 0, minFPS = Infinity, prevTime = setTimestamp(), didbreak = false;
		currentTestNode.innerHTML = testSequence[currentTest].object+ "*"+testSequence[currentTest].maxObjects +" ("+testSequence[currentTest].description+")";
		currentTestNumber.innerHTML = currentTest+1, remainingFramesTest = testDuration;
		totalTests.innerHTML = testSequence.length;
		fpsNode.innerHTML = 'Calculating Frames...';
	},
	this.update = function(frameTime) {
		minMS = Math.min(minMS, frameTime);
		maxMS = Math.max(maxMS, frameTime);

		sumMS += frameTime;

		--remainingFrames;

		--remainingFramesTest;

		++frames;
		var now = setTimestamp();

		if (frames > frameSmoothing) {

				currentFPS = Math.round((frames*1000) / (now - prevTime));
				if( currentFPS < breakUnderFPS) {
					++breaks;
					if (breaks > stopAfterBreaks) {
						killTest();
					}
				}

				if (currentFPS < breakImmediatly) {
					killTest();
				}
				sumFPS += currentFPS;
				++fpsSamples;
				maxFPS = Math.max(maxFPS, currentFPS);
				minFPS = Math.min(minFPS, currentFPS);
				prevTime = now;
				frames = 0;
				fpsNode.innerHTML = currentFPS +" fps (min "+minFPS+ " / max "+maxFPS+ ")";
		}
		remainingFramesNode.innerHTML = remainingFrames;

	},
	this.endTest = function() {

		var testResult = {
			testNumber: currentTest,
			minMS: minMS,
			maxMS: maxMS,
			sumMS: sumMS,
			minFPS: minFPS,
			maxFPS: maxFPS,
			avgFPS: sumFPS/fpsSamples,
			testDidNotFinish: didbreak
		};

		if (!didbreak) {
			passedTests.push(currentTest);
		}
		testResults.push(testResult);

	},
	this.send = function() {
 		var i = 0, points = 0;

 		while (i<passedTests.length) {
 			points += testResults[passedTests[i]].avgFPS;
 			++i;
 		}
 		points = Math.round(points);
 		var maximumPoints = testSequence.length * 60;
 		alert('your Browser archieved ' + points + ' of ' + maximumPoints + ' points')
	}
}
<commit_msg>NaN for average FPS<commit_after>function prepareStage(type) {
	framesPainted = 0;
	currentType = type;

	switch(type) {
		case "canvas":
			var canvas = document.createElement("canvas");
			canvas.id = "canvas";
			canvas.setAttribute("width", stageWidth);
			canvas.setAttribute("height", stageHeight);
			stage.appendChild(canvas);
			context = canvas.getContext("2d");
		break;
		case "svg":
		case "svgtransforms":
		case "svgcsstransforms":
		case "svganimations":
		case "svgrebuild":
			svg = document.createElementNS(svg_ns, "svg");
			svg.id = "svgcontainer";
			svg.setAttribute("width", stageWidth);
			svg.setAttribute("height", stageHeight);
			stage.appendChild(svg);

		break;
		case "html":
			stage.style.width = stageWidth + 'px';
			stage.style.height = stageHeight + 'px';
		break;
	}

	buildStage();

}

function buildStage() {

	for (var i = 0; i < testSequence[currentTest].maxObjects; i++)
	{
		switch(testSequence[currentTest].object) {
			case 'Particle':
				stageElements.push(new Particle(currentType));
			break;
			case 'Bar':
				stageElements.push(new Bar(currentType,testSequence[currentTest].maxObjects,i));
			break;
		}

	}

	statistics.startTest();

	animateStage();

}

function animateStage() {
	tick = requestAnimationFrame(animateStage);
	var frameStartTimeStamp = setTimestamp();
	var currentTime = +new Date;

	var timeOffset = currentTime - previousTimeStamp;

	if (previousTimeStamp === null)
	{
		timeOffset = 0;
	}

	switch(currentType) {
		case 'canvas':
			context.clearRect(0, 0, stageWidth, stageHeight);
		break;
		case 'svgrebuild':
			while (svg.hasChildNodes()) {
				svg.removeChild(svg.lastChild);
			}
		break;

	}
	for (var stageElement in stageElements)
	{
		stageElements[stageElement].draw(timeOffset);
	}

	var paintTime = setTimestamp() - frameStartTimeStamp;

	++framesPainted;
	statistics.update(paintTime, previousTimeStamp);

	previousTimeStamp = currentTime;
	if (framesPainted > (testDuration -1)) {
		endAnimationTest();
	}
}

function endAnimationTest() {
		cancelAnimationFrame(tick);
		tick = null;
		clearStage();
		statistics.endTest();
		++currentTest;
		if (currentTest < testSequence.length) {
			prepareStage(testSequence[currentTest].type);
		}
		else {
			statistics.send();
		}
}

function clearStage() {
	while (stage.hasChildNodes()) {
		stage.removeChild(stage.lastChild);
	}
	framesPainted = 0, context = null, svg = null, previousTimeStamp = null, stageElements = [];
}

function Statistics() {

	var frameSmoothing = 30, minMS, maxMS, frames, breaks,
	sumMS, currentFPS, maxFPS, minFPS, prevTime, fpsSamples, sumFPS;
	var fpsNode = document.getElementById('fps'), currentTestNode = document.getElementById('currentTest'), currentTestNumber = document.getElementById('currentTestNumber'), totalTests = document.getElementById('totalTests');
	var remainingFrames = testSequence.length * testDuration, totalSkippedFrames = 0,
	remainingFramesNode = document.getElementById('remainingFrames'),
	skippedFramesNode = document.getElementById('skippedFrames'),
	testResults = [], passedTests = [];

	function killTest() {
		dnf = true;
		totalSkippedFrames += remainingFramesTest;
		remainingFrames -= remainingFramesTest;
		endAnimationTest();
		skippedFramesNode.innerHTML = "(Skipped Frames: " + totalSkippedFrames + ")";
	}

	this.startTest = function () {
	 	minMS = Infinity, maxMS = 0, frames = 0, breaks = 0,
		sumMS = 0, sumFPS = 0, fpsSamples = 0, maxFPS = 0, minFPS = Infinity, prevTime = setTimestamp(), didbreak = false;
		currentTestNode.innerHTML = testSequence[currentTest].object+ "*"+testSequence[currentTest].maxObjects +" ("+testSequence[currentTest].description+")";
		currentTestNumber.innerHTML = currentTest+1, remainingFramesTest = testDuration;
		totalTests.innerHTML = testSequence.length;
		fpsNode.innerHTML = 'Calculating Frames...';
	},
	this.update = function(frameTime) {
		minMS = Math.min(minMS, frameTime);
		maxMS = Math.max(maxMS, frameTime);

		sumMS += frameTime;

		--remainingFrames;

		--remainingFramesTest;

		++frames;
		var now = setTimestamp();

		if (frames > frameSmoothing) {

				currentFPS = Math.round((frames*1000) / (now - prevTime));
				if( currentFPS < breakUnderFPS) {
					++breaks;
					if (breaks > stopAfterBreaks) {
						killTest();
					}
				}

				if (currentFPS < breakImmediatly) {
					killTest();
				}
				sumFPS += currentFPS;
				++fpsSamples;
				maxFPS = Math.max(maxFPS, currentFPS);
				minFPS = Math.min(minFPS, currentFPS);
				prevTime = now;
				frames = 0;
				fpsNode.innerHTML = currentFPS +" fps (min "+minFPS+ " / max "+maxFPS+ ")";
		}
		remainingFramesNode.innerHTML = remainingFrames;

	},
	this.endTest = function() {
		var testavgFPS = sumFPS/fpsSamples;
		if (isNaN(testavgFPS)) {testavgFPS = 0;}
		var testResult = {
			testNumber: currentTest,
			minMS: minMS,
			maxMS: maxMS,
			sumMS: sumMS,
			minFPS: minFPS,
			maxFPS: maxFPS,
			avgFPS: testavgFPS,
			testDidNotFinish: didbreak
		};

		if (!didbreak) {
			passedTests.push(currentTest);
		}
		testResults.push(testResult);

	},
	this.send = function() {
 		var i = 0, points = 0;

 		while (i<passedTests.length) {
 			points += testResults[passedTests[i]].avgFPS;
 			++i;
 		}
 		points = Math.round(points);
 		var maximumPoints = testSequence.length * 60;
 		alert('your Browser archieved ' + points + ' of ' + maximumPoints + ' points')
	}
}
<|endoftext|>


<commit_before>define({
  dom: {
    ".modal-container": {
      role: "dialog",
      "div.header": {
        "h3.title": {
          text: "Header"
        },
        "button.close.pull-right": {
          text: "x",
          type: "button"
        }
      },
      "div.body": {
        "form": {
          "h4.title": {
            text: "Please Enter Some Information"
          },
          "div.form-group.tps-item-0": {
            label: {
              "for": "name",
              text: "Name"
            },
            "input.form-control": {
              id: "name",
              name: "name",
              type: "text"
            }
          },
          "div.form-group.tps-item-1": {
            label: {
              "for": "email",
              text: "Email"
            },
            "div.input-group": {
              "span.input-group-addon": {
                text: "@"
              },
              "input.form-control": {
                id: "email",
                name: "email",
                type: "text"
              }
            }
          }
        }
      },
      "div.footer": {
        "div.form-group.pull-right": {
          events: {
            "click": {
              selector: "button",
              mid: "tuparse-shakur/tests/handles",
              method: "delegated"
            }
          },
          "button.btn.btn-success": {
            text: "OK",
            type: "button",
            events: {
              "click": {
                mid: "tuparse-shakur/tests/handles",
                method: "success"
              },
              "click-1": {
                mid: "tuparse-shakur/tests/handles",
                method: "success2"
              }
            }
          },
          "button.btn.btn-default": {
            text: "Cancel",
            type: "button"
          }
        }
      }
    }
  },
  css: {
    variables: {
      "@black": "#333",
      "@gray": "#888"
    },
    styles: {
      ".tuparse-test-container": {
        ".modal-container": {
          width: "1170px",
          margin: "0px auto",
          "margin-top": "20px",
          border: "1px solid @black",
          padding: "10px",
          ".header": {
            ".title": {
              margin: 0,
              padding: 0,
              display: "inline-block"
            },
            "border-bottom": "1px solid @black"
          },
          ".body": {
            ".form-group": {
              label: {
                color: "@gray"
              }
            }
          },
          ".footer": {
            overflow: "auto",
            "padding-top": "10px",
            "border-top": "1px solid @black",
            ".form-group": {
              margin: 0,
              padding: 0,
              ".btn": {
                margin: "5px",
                width: "100px",
                "&.btn-default": {
                  ":hover": {
                    "background-color": "#E74C3C"
                  }
                }
              }
            }
          }
        },
        ".title": {
          "font-family": "'Comic Sans MS', cursive, sans-serif"
        }
      }
    }
  }
});<commit_msg>Modify width of test container<commit_after>define({
  dom: {
    ".modal-container": {
      role: "dialog",
      "div.header": {
        "h3.title": {
          text: "Header"
        },
        "button.close.pull-right": {
          text: "x",
          type: "button"
        }
      },
      "div.body": {
        "form": {
          "h4.title": {
            text: "Please Enter Some Information"
          },
          "div.form-group.tps-item-0": {
            label: {
              "for": "name",
              text: "Name"
            },
            "input.form-control": {
              id: "name",
              name: "name",
              type: "text"
            }
          },
          "div.form-group.tps-item-1": {
            label: {
              "for": "email",
              text: "Email"
            },
            "div.input-group": {
              "span.input-group-addon": {
                text: "@"
              },
              "input.form-control": {
                id: "email",
                name: "email",
                type: "text"
              }
            }
          }
        }
      },
      "div.footer": {
        "div.form-group.pull-right": {
          events: {
            "click": {
              selector: "button",
              mid: "tuparse-shakur/tests/handles",
              method: "delegated"
            }
          },
          "button.btn.btn-success": {
            text: "OK",
            type: "button",
            events: {
              "click": {
                mid: "tuparse-shakur/tests/handles",
                method: "success"
              },
              "click-1": {
                mid: "tuparse-shakur/tests/handles",
                method: "success2"
              }
            }
          },
          "button.btn.btn-default": {
            text: "Cancel",
            type: "button"
          }
        }
      }
    }
  },
  css: {
    variables: {
      "@black": "#333",
      "@gray": "#888"
    },
    styles: {
      ".tuparse-test-container": {
        ".modal-container": {
          width: "100%",
          margin: "0px auto",
          "margin-top": "20px",
          border: "1px solid @black",
          padding: "10px",
          ".header": {
            ".title": {
              margin: 0,
              padding: 0,
              display: "inline-block"
            },
            "border-bottom": "1px solid @black"
          },
          ".body": {
            ".form-group": {
              label: {
                color: "@gray"
              }
            }
          },
          ".footer": {
            overflow: "auto",
            "padding-top": "10px",
            "border-top": "1px solid @black",
            ".form-group": {
              margin: 0,
              padding: 0,
              ".btn": {
                margin: "5px",
                width: "100px",
                "&.btn-default": {
                  ":hover": {
                    "background-color": "#E74C3C"
                  }
                }
              }
            }
          }
        },
        ".title": {
          "font-family": "'Comic Sans MS', cursive, sans-serif"
        }
      }
    }
  }
});<|endoftext|>


<commit_before><commit_msg>increased interval between json - requests (update)<commit_after><|endoftext|>


<commit_before>
describe("files", function() {
	describe("#Saving base64", function(){
		this.timeout(10000);
		it("should be saved", function(done){
			var base64 = "d29ya2luZyBhdCBhdm9zY2xvdWQgaXMgZ3JlYXQh";
			var file = new AV.File("myfile.txt", { base64: base64 });
			file.metaData('format', 'txt file');
			file.save().then(function(){
				console.log(file.url());
				console.log(file.id);
				expect(file.size()).to.be(30);
				expect(file.ownerId()).to.be.ok();
				expect(file.id).to.be.ok();
				expect(file.metaData('format')).to.be('txt file');
				file.destroy().then(function(){
					done();
				}, function(error){
					throw error;
				});
			}, function(error){
				throw error;
			});
		});
	});

	describe("#Test withURL", function(){
		this.timeout(10000);
		it("should be saved", function(done){
			var url = "http://i1.wp.com/blog.avoscloud.com/wp-content/uploads/2014/05/screen568x568-1.jpg?resize=202%2C360";
			var file = AV.File.withURL('screen.jpg', url);
			file.save().then(function(){
				console.log(file.url());
				console.log(file.id);
				expect(file.ownerId()).to.be.ok();
				expect(file.id).to.be.ok();
				expect(file.metaData('__source')).to.be('external');
                done();
			}, function(error){
				throw error;
			});
		});
	});

    describe("#Saving buffer in node.js", function(){
		it("should be saved", function(done){
			if(AV._isNode){
				var file = new AV.File('myfile.txt', new Buffer('hello world'));
				file.save().then(function(){
					console.log("saved buffer...");
					console.log(file.url());
					console.log(file.id);
					console.log(file.metaData());
					expect(file.size()).to.be(11);
					expect(file.ownerId()).to.be.ok();
					expect(file.id).to.be.ok();
                    console.log(file.thumbnailURL(200, 100));
                    expect(file.thumbnailURL(200, 100)).to.be(file.url() + "?imageView/2/w/200/h/100/q/100/format/png");
					file.destroy().then(function(){
						done();
					}, function(error){
						throw error;
					});
				}, function(error){
					throw error;
				});
			}else{
				done();
			}
		});
    });
	describe("#Saving array", function(){
		it("should be saved", function(done){
			var bytes = [ 0xBE, 0xEF, 0xCA, 0xFE ];
			var file = new AV.File("myfile.txt", bytes);
			file.save().then(function(){
				console.log(file.url());
				console.log(file.id);
				console.log(file.metaData());
				expect(file.size()).to.be(4);
				expect(file.ownerId()).to.be.ok();
				expect(file.id).to.be.ok();
				file.destroy().then(function(){
					done();
				}, function(error){
					throw error;
				});
			}, function(error){
				throw error;
			});
		});
	});
	describe("#Saving file with object", function(){
		it("should be saved", function(done){
			var bytes = [ 0xBE, 0xEF, 0xCA, 0xFE ];
			var file = new AV.File("myfile.txt", bytes);
			file.save().then(function(){
				console.log(file.url());
				console.log(file.id);
				var jobApplication = new AV.Object("JobApplication");
				jobApplication.set("applicantName", "Joe Smith");
				jobApplication.set("applicantResumeFile", file);
				jobApplication.save().then(function(result){
					expect(result.id).to.be.ok();
					var query = new AV.Query("JobApplication");
					query.get(result.id, {
						success: function(ja) {
		  					expect(ja.id).to.be.ok();
							var arf = ja.get("applicantResumeFile");
							console.log(arf.metaData());
							expect(arf).to.be.ok();
							expect(arf.size()).to.be(4);
							expect(arf.ownerId()).to.be.ok();
							console.log(ja.get("applicantResumeFile"));
							file.destroy().then(function(){
								done();
							}, function(error){
								throw error;
							});
						},
						error: function(object, error) {
							throw error;
						}
					});

				}, function(obj, error){
					throw error;
				});
			}, function(error){
				throw error;
			});
		});
	});
});
<commit_msg>Fixed file test.<commit_after>
describe("files", function() {
	describe("#Saving base64", function(){
		this.timeout(10000);
		it("should be saved", function(done){
			var base64 = "d29ya2luZyBhdCBhdm9zY2xvdWQgaXMgZ3JlYXQh";
			var file = new AV.File("myfile.txt", { base64: base64 });
			file.metaData('format', 'txt file');
			file.save().then(function(){
				console.log(file.url());
				console.log(file.id);
				expect(file.ownerId()).to.be.ok();
				expect(file.id).to.be.ok();
				expect(file.metaData('format')).to.be('txt file');
				file.destroy().then(function(){
					done();
				}, function(error){
					throw error;
				});
			}, function(error){
				throw error;
			});
		});
	});

	describe("#Test withURL", function(){
		this.timeout(10000);
		it("should be saved", function(done){
			var url = "http://i1.wp.com/blog.avoscloud.com/wp-content/uploads/2014/05/screen568x568-1.jpg?resize=202%2C360";
			var file = AV.File.withURL('screen.jpg', url);
			file.save().then(function(){
				console.log(file.url());
				console.log(file.id);
				expect(file.ownerId()).to.be.ok();
				expect(file.id).to.be.ok();
				expect(file.metaData('__source')).to.be('external');
                done();
			}, function(error){
				throw error;
			});
		});
	});

    describe("#Saving buffer in node.js", function(){
		it("should be saved", function(done){
			if(AV._isNode){
				var file = new AV.File('myfile.txt', new Buffer('hello world'));
				file.save().then(function(){
					console.log("saved buffer...");
					console.log(file.url());
					console.log(file.id);
					console.log(file.metaData());
					expect(file.size()).to.be(11);
					expect(file.ownerId()).to.be.ok();
					expect(file.id).to.be.ok();
                    console.log(file.thumbnailURL(200, 100));
                    expect(file.thumbnailURL(200, 100)).to.be(file.url() + "?imageView/2/w/200/h/100/q/100/format/png");
					file.destroy().then(function(){
						done();
					}, function(error){
						throw error;
					});
				}, function(error){
					throw error;
				});
			}else{
				done();
			}
		});
    });
	describe("#Saving array", function(){
		it("should be saved", function(done){
			var bytes = [ 0xBE, 0xEF, 0xCA, 0xFE ];
			var file = new AV.File("myfile.txt", bytes);
			file.save().then(function(){
				console.log(file.url());
				console.log(file.id);
				console.log(file.metaData());
				expect(file.size()).to.be(4);
				expect(file.ownerId()).to.be.ok();
				expect(file.id).to.be.ok();
				file.destroy().then(function(){
					done();
				}, function(error){
					throw error;
				});
			}, function(error){
				throw error;
			});
		});
	});
	describe("#Saving file with object", function(){
		it("should be saved", function(done){
			var bytes = [ 0xBE, 0xEF, 0xCA, 0xFE ];
			var file = new AV.File("myfile.txt", bytes);
			file.save().then(function(){
				console.log(file.url());
				console.log(file.id);
				var jobApplication = new AV.Object("JobApplication");
				jobApplication.set("applicantName", "Joe Smith");
				jobApplication.set("applicantResumeFile", file);
				jobApplication.save().then(function(result){
					expect(result.id).to.be.ok();
					var query = new AV.Query("JobApplication");
					query.get(result.id, {
						success: function(ja) {
		  					expect(ja.id).to.be.ok();
							var arf = ja.get("applicantResumeFile");
							console.log(arf.metaData());
							expect(arf).to.be.ok();
							expect(arf.size()).to.be(4);
							expect(arf.ownerId()).to.be.ok();
							console.log(ja.get("applicantResumeFile"));
							file.destroy().then(function(){
								done();
							}, function(error){
								throw error;
							});
						},
						error: function(object, error) {
							throw error;
						}
					});

				}, function(obj, error){
					throw error;
				});
			}, function(error){
				throw error;
			});
		});
	});
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    //requirements
    var get = require('../get');

    describe(module.id, function(){

        it('Получение неопределенного свойства', function(){

            var object = {};

            expect(get(object, 'a.b')).toBeUndefined();

        });

        it('Получение булева свойства', function(){

            var object = {
                a: {
                    b: false
                }
            };

            expect(get(object, 'a.b')).toBeFalsy();

        });

        it('Получение числового свойства', function(){

            var object = {
                a: {
                    b: 1
                }
            };

            expect(get(object, 'a.b')).toBe(1);

        });

        it('Получение строки', function(){

            var object = {
                a: {
                    b: 'b'
                }
            };

            expect(get(object, 'a.b')).toBe('b');

        });

        it('Получение значения функции', function(){

            var object = {
                a: {
                    b: function(){
                        return 'result';
                    }
                }
            };

            expect(get(object, 'a.b')).toBe('result');

        });

    });
});<commit_msg>translate test titles<commit_after>define(function(require, exports, module) {
    //requirements
    var get = require('../get');

    describe(module.id, function(){

        it('Get undefined', function(){

            var object = {};

            expect(get(object, 'a.b')).toBeUndefined();

        });

        it('Get boolean', function(){

            var object = {
                a: {
                    b: false
                }
            };

            expect(get(object, 'a.b')).toBeFalsy();

        });

        it('Get number', function(){

            var object = {
                a: {
                    b: 1
                }
            };

            expect(get(object, 'a.b')).toBe(1);

        });

        it('Get string', function(){

            var object = {
                a: {
                    b: 'b'
                }
            };

            expect(get(object, 'a.b')).toBe('b');

        });

        it('Get function result', function(){

            var object = {
                a: {
                    b: function(){
                        return 'result';
                    }
                }
            };

            expect(get(object, 'a.b')).toBe('result');

        });

    });
});<|endoftext|>


<commit_before>const JSONRPC = require("..");
const AllTests = require("./Tests/AllTests");
const os = require("os");
const cluster = require("cluster");

process.on(
	"unhandledRejection",
	(reason, promise) =>
	{
		console.log("[" + process.pid + "] Unhandled Rejection at: Promise", promise, "reason", reason);

		process.exit(1);
	}
);

process.on(
	"uncaughtException",
	(error) => {
		console.log("[" + process.pid + "] Unhandled exception.");
		console.error(error);

		process.exit(1);
	}
);

(
	async () =>
	{
		let allTests;
		const bBenchmarkMode = false;

		if(cluster.isMaster)
		{
			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ false);
			await allTests.runClusterTests();

			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ false);
			await allTests.runTests();

			// uws "Segmentation fault" on .close() in Travis (CentOS 7).
			// https://github.com/uWebSockets/uWebSockets/issues/583
			if(os.platform() === "win32")
			{
				let bUwsLoaded = false;
				try
				{
					// Requires a compilation toolset to be installed if precompiled binaries are not available.
					require("uws");
					bUwsLoaded = true;
				}
				catch(error)
				{
					console.error(error);
				}

				if(bUwsLoaded)
				{
					allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ true, require("uws"), require("uws").Server, JSONRPC.WebSocketAdapters.uws.WebSocketWrapper, /*bDisableVeryLargePacket*/ true);
					allTests.websocketServerPort = allTests.httpServerPort + 1;
					await allTests.runTests();
				}
			}

			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ true, require("ws"), require("ws").Server, undefined, /*bDisableVeryLargePacket*/ false);
			await allTests.runTests();

			console.log("[" + process.pid + "] Done!!!");
		}
		else
		{
			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ false);
			await allTests.runClusterTests();

			console.log("[" + process.pid + "] Worker done!!!");
		}

		process.exit(0);
	}
)();
<commit_msg>Green end message.<commit_after>const JSONRPC = require("..");
const AllTests = require("./Tests/AllTests");
const os = require("os");
const cluster = require("cluster");

process.on(
	"unhandledRejection",
	(reason, promise) =>
	{
		console.log("[" + process.pid + "] Unhandled Rejection at: Promise", promise, "reason", reason);

		process.exit(1);
	}
);

process.on(
	"uncaughtException",
	(error) => {
		console.log("[" + process.pid + "] Unhandled exception.");
		console.error(error);

		process.exit(1);
	}
);

(
	async () =>
	{
		let allTests;
		const bBenchmarkMode = false;

		if(cluster.isMaster)
		{
			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ false);
			await allTests.runClusterTests();

			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ false);
			await allTests.runTests();

			// uws "Segmentation fault" on .close() in Travis (CentOS 7).
			// https://github.com/uWebSockets/uWebSockets/issues/583
			if(os.platform() === "win32")
			{
				let bUwsLoaded = false;
				try
				{
					// Requires a compilation toolset to be installed if precompiled binaries are not available.
					require("uws");
					bUwsLoaded = true;
				}
				catch(error)
				{
					console.error(error);
				}

				if(bUwsLoaded)
				{
					allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ true, require("uws"), require("uws").Server, JSONRPC.WebSocketAdapters.uws.WebSocketWrapper, /*bDisableVeryLargePacket*/ true);
					allTests.websocketServerPort = allTests.httpServerPort + 1;
					await allTests.runTests();
				}
			}

			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ true, require("ws"), require("ws").Server, undefined, /*bDisableVeryLargePacket*/ false);
			await allTests.runTests();

			console.log("");
			console.log("[" + process.pid + "] \x1b[42m\x1b[30mAll tests done. No uncaught errors encountered.\x1b[0m Which means all is good or the tests are incomplete/buggy.");
			console.log("");
		}
		else
		{
			allTests = new AllTests(bBenchmarkMode, /*bWebSocketMode*/ false);
			await allTests.runClusterTests();

			console.log("[" + process.pid + "] \x1b[32mWorker done!!!\x1b[0m");
		}

		process.exit(0);
	}
)();
<|endoftext|>