language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class TweenUtils {
/**
* Tweens a sprite to a certain tint value
* @param {PIXI.Sprite} subject - The subject you want to tint
* @param {Number} tint - The destination tint value
* @param {Number} duration - Duration in seconds
* @param {(Phaser.Easing|string)} [easing=Phaser.Easing.Default] - The easing function
* @param {boolean} [autostart=false] - Auto-start the tween immediately
* @param {Number} [delay=0] - Tween delay
* @param {Number} [repeat=0] - Number of times should the tween be repeated. (-1 = forever)
* @param {Number} [yoyo=false] - Yoyo repeat
*/
static tint(
subject, tint, duration, easing = Phaser.Easing.Default,
autostart = false, delay = 0, repeat = 0, yoyo = false,
) {
const colorBlend = { step: 0 };
const initialTint = subject.tint;
return subject.game.add.tween(colorBlend)
.to({ step: 100 }, duration, easing, autostart, delay, repeat, yoyo)
.onUpdateCallback(() => {
subject.tint = Phaser.Color.interpolateColor(initialTint, tint, 100, colorBlend.step, 1);
});
}
} |
JavaScript | class Painter {
// Create constructor
constructor() {
this.id = arguments[0];
this.coords = arguments[1];
}
setCanvasId(id) {
this.id = id;
}
setCoordinates(coords) {
this.coords = coords;
}
draw() {
var can = document.getElementById(this.id);
var cx = can.getContext("2d");
var N = arguments.length;
var objs = arguments;
for(var i = 0; i < N; i++) {
var o = objs[i];
if(o instanceof Point) {
cx.beginPath();
cx.strokeStyle = o.color;
var q = this.coords.transform(o);
cx.arc(q.x, q.y, o.size, 0, 2 * Math.PI);
cx.fillStyle = o.color;
cx.fill();
cx.stroke();
}
if(o instanceof Connector) {
cx.beginPath();
cx.strokeStyle = o.color;
var qbeg = this.coords.transform(o.rbeg);
cx.moveTo(qbeg.x, qbeg.y);
var qend = this.coords.transform(o.rend);
cx.lineTo(qend.x, qend.y);
cx.stroke();
}
if(o instanceof Capacitor) {
cx.beginPath();
cx.strokeStyle = o.color;
cx.fillStyle = o.color;
var w = 2 * o.plateThickness + o.plateGap;
var qbeg = this.coords.transform(o.rbeg);
var qend = this.coords.transform(o.rend);
var Dx = qend.x - qbeg.x;
var Dy = qend.y - qbeg.y;
var L = Math.sqrt(Dx * Dx + Dy * Dy);
var cosq = Dx / L;
var sinq = Dy / L;
var l = 0.5 * (L - w);
var q1 = {};
q1.x = qbeg.x + l * cosq;
q1.y = qbeg.y + l * sinq;
var q2 = {};
q2.x = qend.x - l * cosq;
q2.y = qend.y - l * sinq;
cx.moveTo(qbeg.x, qbeg.y);
cx.lineTo(q1.x, q1.y);
cx.moveTo(qend.x, qend.y);
cx.lineTo(q2.x, q2.y);
var q1u = {};
q1u.x = q1.x - 0.5 * o.size * sinq;
q1u.y = q1.y + 0.5 * o.size * cosq;
var q1d = {};
q1d.x = q1.x + 0.5 * o.size * sinq;
q1d.y = q1.y - 0.5 * o.size * cosq
var q11u = {};
q11u.x = q1u.x + o.plateThickness * cosq;
q11u.y = q1u.y + o.plateThickness * sinq;
var q11d = {};
q11d.x = q1d.x + o.plateThickness * cosq;
q11d.y = q1d.y + o.plateThickness * sinq;
cx.moveTo(q1u.x, q1u.y);
cx.lineTo(q11u.x, q11u.y);
cx.lineTo(q11d.x, q11d.y);
cx.lineTo(q1d.x, q1d.y);
cx.closePath();
var q2u = {};
q2u.x = q2.x - 0.5 * o.size * sinq;
q2u.y = q2.y + 0.5 * o.size * cosq
var q2d = {};
q2d.x = q2.x + 0.5 * o.size * sinq;
q2d.y = q2.y - 0.5 * o.size * cosq;
var q22u = {};
q22u.x = q2u.x - o.plateThickness * cosq;
q22u.y = q2u.y - o.plateThickness * sinq;
var q22d = {};
q22d.x = q2d.x - o.plateThickness * cosq;
q22d.y = q2d.y - o.plateThickness * sinq
cx.moveTo(q2u.x, q2u.y);
cx.lineTo(q22u.x, q22u.y);
cx.lineTo(q22d.x, q22d.y);
cx.lineTo(q2d.x, q2d.y);
cx.closePath();
cx.fill();
cx.stroke();
}
}
}
} |
JavaScript | class SpanLittleBigQueryBase extends SpanQueryBase {
/**
* Sets the `little` clause.
*
* @param {SpanQueryBase} spanQry Any span type query
* @returns {SpanLittleBigQueryBase} returns `this` so that calls can be chained.
*/
little(spanQry) {
checkType(spanQry, SpanQueryBase);
this._queryOpts.little = spanQry;
return this;
}
/**
* Sets the `big` clause.
*
* @param {SpanQueryBase} spanQry Any span type query
* @returns {SpanLittleBigQueryBase} returns `this` so that calls can be chained.
*/
big(spanQry) {
checkType(spanQry, SpanQueryBase);
this._queryOpts.big = spanQry;
return this;
}
} |
JavaScript | class LabelledInput extends Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onChangeArray = this.onChangeArray.bind(this);
this.onMultiSelectChange = this.onMultiSelectChange.bind(this);
this.onChangeDatePicker = this.onChangeDatePicker.bind(this);
this.state = {
isValid: true,
labelText: alt(props.labelText),
inputval: alt(props.inputval),
options: props.options,
placeholder: alt(props.placeholder),
required: alt(props.required),
visibleStyle: alt(props.isVisible)
};
}
onChange(e) {
const value = e.target.value;
this.setState({
inputval: value,
selected: value,
isValid: hasData(value) || this.props.required !== REQUIRED
});
if (e.target.name === "showDateTimePicker") {
this.props.toggleDateTimePicker(e.target.value);
}
this.props.callback(e.target);
if (hasData(this.props.onChange)) {
this.props.onChange(e.target);
}
}
onChangeArray(e, label) {
this.setState({
inputval: e.value,
isValid: hasData(e) || this.props.required !== REQUIRED
});
this.props.callback(e);
}
onMultiSelectChange(e) {
this.setState({
inputval: e,
isValid: hasData(e) || this.props.required !== REQUIRED
});
this.props.callback({ value: e, name: this.props.name });
}
onChangeDatePicker(e) {
this.setState({
inputval: e,
isValid: hasData(e) || this.props.required !== REQUIRED
});
this.props.callback({ value: e, name: this.props.name });
}
//APB - REFACTOR
getInputByType() {
const type = this.props.inputtype;
const inputStyle = `${alt(type)} ${alt(this.props.className)}`;
if (type === textareaType) {
return (
<TextareaInput
className={inputStyle}
alt={this.props.alt}
name={this.props.name}
inputtype={this.props.inputtype}
inputval={alt(this.state.inputval)}
callback={this.onChange}
required={this.state.required}
placeholder={this.state.placeholder}
readOnly={this.props.readOnly}
/>
);
}
if (type === "label") {
return (
<LabelInput
className={inputStyle}
alt={this.props.alt}
name={this.props.name}
inputval={this.props.inputval}
inline={this.props.inline}
/>
);
}
if (textTypes.includes(type)) {
return (
<TextInput
autoFocus={this.props.autoFocus}
pattern={this.props.pattern}
className={this.props.className}
alt={this.props.alt}
name={this.props.name}
inputtype={this.props.inputtype}
inputval={alt(this.state.inputval)}
required={this.state.required}
placeholder={this.state.placeholder}
maxLength={this.props.maxlength}
readOnly={this.props.readOnly}
callback={this.onChange}
validateInput={this.props.validateInput}
/>
);
}
if (selectType.includes(type)) {
return (
<SelectInput
autoFocus={this.props.autoFocus}
className={inputStyle}
alt={this.props.alt}
name={this.props.name}
inputtype={this.props.inputtype}
selected={this.props.inputval}
callback={type === "select" ? this.onChange : this.onMultiSelectChange}
required={this.state.required}
placeholder={this.state.placeholder}
options={this.state.options}
readOnly={this.props.readOnly}
/>
);
}
if (boolTypes.includes(type)) {
return (
<React.Fragment>
{this.props.labelText && <br />}
<CheckboxInput
className={inputStyle}
name={this.props.name}
key={this.props.name}
inputtype={this.props.inputtype}
inputval={this.props.inputval}
callback={this.onChange}
required={this.state.required}
selected={this.props.selected}
placeholder={this.state.placeholder}
alt={this.props.alt}
readOnly={this.props.readOnly}
/>
</React.Fragment>
);
}
if (checkboxGroup === type) {
return (
<React.Fragment>
{this.props.labelText && <br />}
<CheckboxGroup
collection={this.props.collection}
className={inputStyle}
name={this.props.name}
label={this.props.labelText}
key={this.props.name}
inputtype="checkbox"
inputval={this.props.inputval}
callback={this.onChangeArray}
required={this.state.required}
selected={this.props.selected}
placeholder={this.state.placeholder}
alt={this.props.alt}
readOnly={this.props.readOnly}
/>
</React.Fragment>
);
}
if (type === fileType) {
return (
<FileInput
className={inputStyle}
name={this.props.name}
inputtype={this.props.inputtype}
inputval={this.props.inputval}
options={this.state.options}
callback={this.onChange}
required={this.state.required}
placeholder={this.state.placeholder}
alt={this.props.alt}
/>
);
}
if (type === dateTime) {
return (
<ReactDateTimePicker
className={inputStyle}
name={this.props.name}
inputval={this.props.inputval}
callback={this.onChangeDatePicker}
required={this.state.required}
readOnly={this.props.readOnly}
format={this.props.format}
disableCalendar={this.props.disableCalendar}
/>
);
}
return null;
}
render() {
const sb = !!this.props.spacebetween ? " space-between" : "";
const sbw = !!this.props.spacebetweenwrap ? " space-between-wrap" : "";
const inline = !!this.props.inline ? " input-group-append" : "";
const textlabelStyle = this.props.inputtype === "multiSelect" ? "" : "txtlabel";
return (
<FormGroup className={`${this.state.visibleStyle}${sb}${sbw}${inline}`}>
<label className={textlabelStyle}>{this.state.labelText}</label>
{this.getInputByType()}
</FormGroup>
);
}
} |
JavaScript | class RecentPosts extends React.Component {
componentWillMount() {
this.props.fetchLatestPublishedPosts();
}
render() {
return (
<div className="recent-posts _flex _flex-direction-column _flex-horizontal-align-center">
<Title>Recent Posts</Title>
<div className="_narrow">
<div className="section-title">Recent Posts</div>
{
this.props.recentPosts.latestPublishedPosts.map((post, key) =>
<MediumPost key={ key } { ...post } />
)
}
</div>
</div>
);
}
} |
JavaScript | class Navbar extends React.Component {
constructor() {
super()
this.state = {
selected: '',
home: false,
accountInfo: false,
pong: false,
lobby: false,
br: false
}
this.handleToggle = this.handleToggle.bind(this)
this.baseState = this.state
}
handleToggle(event) {
event.preventDefault()
if (this.state.selected === '') {
// console.log(event.target.name, 'is this a thing?')
this.setState({
selected: event.target.name,
[event.target.name]: event.target.checked
})
} else {
this.setState(this.baseState)
this.setState({
selected: event.target.name,
[event.target.name]: event.target.checked
})
}
}
render() {
return (
<div id="navbar">
{/* <h1 className="gradient-text atariFont">Audtari</h1> */}
<nav>
<div className="switchboard">
<div className="left-side">
<Link to="/home">
<Switch
checked={this.state.home}
name="home"
onChange={this.handleToggle}
color="default"
/>
</Link>
<Link to="/accountInfo">
<Switch
checked={this.state.accountInfo}
name="accountInfo"
onChange={this.handleToggle}
color="default"
/>
</Link>
</div>
<div className="right-side">
<Link to="/pong">
<Switch
checked={this.state.pong}
name="pong"
onChange={this.handleToggle}
color="default"
/>
</Link>
<Link to="/lobby">
<Switch
checked={this.state.lobby}
name="lobby"
onChange={this.handleToggle}
color="default"
/>
</Link>
<Link to="/br">
<Switch
checked={this.state.br}
name="br"
onChange={this.handleToggle}
color="default"
/>
</Link>
</div>
{/* The navbar will show these links before you log in */}
{/* <Link to="/home">Home</Link>
<Link to="/accountInfo">Account Info</Link>
<Link to="/pong">Pong SP</Link>
<Link to="/lobby">Pong MP</Link>
<Link to="/br">Breakout</Link> */}
</div>
</nav>
{/* <hr /> */}
</div>
)
}
} |
JavaScript | class BasicController {
constructor() {
this.HTTP = toweran.CONST.HTTP
}
} |
JavaScript | class GTM {
constructor(ctx, options) {
this.ctx = ctx
this.options = options
}
init() {
// insert scripts on client side if it not preseted on server side
if (!this.options.presetScriptsOnServerSide) {
const headScriptId = 'google-tag-manager-script'
const bodyScriptId = 'google-tag-manager-noscript'
let headScript = document.querySelector(`script#${headScriptId}`)
let bodyScript = document.querySelector(`script#${bodyScriptId}`)
if (!headScript && !bodyScript) {
headScript = document.createElement('script')
headScript.id = headScriptId
headScript.src = this.options.head.script[0].src
headScript.async = this.options.head.script[0].async
bodyScript = document.createElement('noscript')
bodyScript.id = bodyScriptId
bodyScript.innerHTML = this.options.head.noscript[0].innerHTML
document.querySelector('head').append(headScript)
document.querySelector('body').append(bodyScript)
}
}
window[this.options.layer] = window[this.options.layer] || []
this.pushEvent({
event: 'gtm.js',
'gtm.start': new Date().getTime()
})
if (this.options.pageTracking && (!this.options.respectDoNotTrack || !this.hasDNT())) {
this.initPageTracking()
}
}
initPageTracking() {
this.ctx.app.router.afterEach((to, from) => {
setTimeout(() => {
window[this.options.layer]
.push(to.gtm || {
routeName: to.name,
pageType: 'PageView',
pageUrl: to.fullPath,
event: this.options.pageViewEventName
})
}, 0)
})
}
pushEvent(obj) {
try {
if (!window || !window[this.options.layer]) {
throw new Error('missing GTM dataLayer')
}
if (typeof obj !== 'object') {
throw new Error('event should be an object')
}
if (!obj.hasOwnProperty('event')) {
throw new Error('missing event property')
}
window[this.options.layer].push(obj)
} catch (err) {
console.error('[ERROR] [GTM]', err)
}
}
pushData(obj) {
try {
if (!window || !window[this.options.layer]) {
throw new Error('missing GTM dataLayer')
}
if (typeof obj !== 'object') {
throw new Error('data should be an object')
}
window[this.options.layer].push(obj)
} catch (err) {
console.error('[ERROR] [GTM]', err)
}
}
hasDNT() {
return (
window.doNotTrack === '1' ||
navigator.doNotTrack === 'yes' ||
navigator.doNotTrack === '1' ||
navigator.msDoNotTrack === '1' ||
(
window.external &&
window.external.msTrackingProtectionEnabled &&
window.external.msTrackingProtectionEnabled()
)
)
}
} |
JavaScript | class RsaCryptographyProvider {
constructor(key) {
/**
* The set of algorithms this provider supports
*/
this.applicableAlgorithms = [
"RSA1_5",
"RSA-OAEP",
"PS256",
"RS256",
"PS384",
"RS384",
"PS512",
"RS512",
];
/**
* The set of operations this provider supports
*/
this.applicableOperations = [
"encrypt",
"wrapKey",
"verifyData",
];
/**
* Mapping between signature algorithms and their corresponding hash algorithms. Externally used for testing.
* @internal
*/
this.signatureAlgorithmToHashAlgorithm = {
PS256: "SHA256",
RS256: "SHA256",
PS384: "SHA384",
RS384: "SHA384",
PS512: "SHA512",
RS512: "SHA512",
};
this.key = key;
}
isSupported(algorithm, operation) {
return (this.applicableAlgorithms.includes(algorithm) && this.applicableOperations.includes(operation));
}
encrypt(encryptParameters, _options) {
this.ensureValid();
const keyPEM = convertJWKtoPEM(this.key);
const padding = encryptParameters.algorithm === "RSA1_5" ? RSA_PKCS1_PADDING : RSA_PKCS1_OAEP_PADDING;
return Promise.resolve({
algorithm: encryptParameters.algorithm,
keyID: this.key.kid,
result: publicEncrypt({ key: keyPEM, padding: padding }, Buffer.from(encryptParameters.plaintext)),
});
}
decrypt(_decryptParameters, _options) {
throw new LocalCryptographyUnsupportedError("Decrypting using a local JsonWebKey is not supported.");
}
wrapKey(algorithm, keyToWrap, _options) {
this.ensureValid();
const keyPEM = convertJWKtoPEM(this.key);
const padding = algorithm === "RSA1_5" ? RSA_PKCS1_PADDING : RSA_PKCS1_OAEP_PADDING;
return Promise.resolve({
algorithm: algorithm,
result: publicEncrypt({ key: keyPEM, padding }, Buffer.from(keyToWrap)),
keyID: this.key.kid,
});
}
unwrapKey(_algorithm, _encryptedKey, _options) {
throw new LocalCryptographyUnsupportedError("Unwrapping a key using a local JsonWebKey is not supported.");
}
sign(_algorithm, _digest, _options) {
throw new LocalCryptographyUnsupportedError("Signing a digest using a local JsonWebKey is not supported.");
}
signData(_algorithm, _data, _options) {
throw new LocalCryptographyUnsupportedError("Signing a block of data using a local JsonWebKey is not supported.");
}
async verify(_algorithm, _digest, _signature, _options) {
throw new LocalCryptographyUnsupportedError("Verifying a digest using a local JsonWebKey is not supported.");
}
verifyData(algorithm, data, signature, _options) {
this.ensureValid();
const keyPEM = convertJWKtoPEM(this.key);
const verifier = createVerify(algorithm, data);
return Promise.resolve({
result: verifier.verify(keyPEM, Buffer.from(signature)),
keyID: this.key.kid,
});
}
ensureValid() {
var _a, _b;
if (this.key &&
((_a = this.key.kty) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== "RSA" &&
((_b = this.key.kty) === null || _b === void 0 ? void 0 : _b.toUpperCase()) !== "RSA-HSM") {
throw new Error("Key type does not match the algorithm RSA");
}
}
} |
JavaScript | class JsonFileWriter {
/**
* @param {Object} config
* @param {string} config.path
*/
constructor(config) {
this._outputPath = path.join(process.cwd(), config.path);
debug('JsonFileWriter instance created.');
debug('config', config);
}
/**
* @param {Object[]} results
* @return {Promise.<Object[]>|Promise.<Error>|Promise.<string>}
*/
run(results) {
debug('Writing JSON file "%s"...', this._outputPath);
return new Promise((resolve, reject) => {
if (!results) {
debug('No results to write!');
resolve(results);
return;
}
const json = JSON.stringify(results);
fs.writeFile(this._outputPath, json, error => {
if (error) {
debug(error.message);
return reject(error);
}
debug('Wrote %d chars.', json.length);
resolve(this._outputPath);
});
});
}
} |
JavaScript | class CountStream extends Transform {
constructor() {
super({objectMode: true})
this._count = 0
}
static build() {
return new CountStream()
}
_transform(data, encoding, callback) {
try {
this.push(data)
this._count += 1
callback()
} catch(e) {
callback(e)
}
}
count() {
return this._count
}
reset(i) {
this._count = i || 0
}
} |
JavaScript | class CheckoutClickCollector extends AbstractCollector {
constructor(clickSelector, contentSelector, resolvers, listenerType) {
super("checkout");
this.clickSelector = clickSelector
this.contentSelector = contentSelector;
this.idResolver = resolvers.idResolver;
this.priceResolver = resolvers.priceResolver;
this.amountResolver = resolvers.amountResolver;
this.listenerType = listenerType;
}
/**
* Add click event listeners to the identified elements, write the data
* when the event occurs
*
* @param {object} writer - The writer to send the data to
*/
attach(writer) {
var doc = this.getDocument();
// Activates on click of the element selected using the clickSelector
var handler = element => {
var items = doc.querySelectorAll(this.contentSelector);
items.forEach(item => {
let id = this.idResolver(item);
if (id) {
let data = {
"id" : id
}
if (this.priceResolver) {
data.price = this.priceResolver(item);
}
if (this.amountResolver) {
data.amount = this.amountResolver(item);
}
// We write each item separately - they may be coming from different queries
// thus when we try to resolve the trail for each of them we need to have them
// as separate records
writer.write({
"type" : this.getType(),
"data" : data
});
}
})
}
// The Sentiel library uses animationstart event listeners which may interfere with
// animations attached on elemenets. The in-library provided workaround mechanism does not work
// 100%, thus we provide the listenerType choice below. The tradeoffs
// "dom" - no animation interference, only onclick attached, but does not handle elements inserted in the DOM later
// "sentinel (default)" - works on elements inserted in the DOM anytime, but interferes with CSS animations on these elements
if (this.listenerType == "dom") {
var nodeList = doc.querySelectorAll(this.clickSelector);
nodeList.forEach(el => el.addEventListener("click", handler));
} else {
var sentinel = new Sentinel(this.getDocument());
sentinel.on(this.clickSelector, el => el.addEventListener("click", ev => handler(el)));
}
}
} |
JavaScript | class WT_G3x5_MapViewFlightPlanLegCanvasStyler extends WT_MapViewFlightPlanLegCanvasStyler {
constructor() {
super();
this._initLegRenderers();
this._initOptionChangeFuncs();
this._optsManager.addOptions(WT_G3x5_MapViewFlightPlanLegCanvasStyler.OPTIONS_DEF);
}
_initLegRenderersHelper(active) {
let renderers = [];
renderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD] = new WT_MapViewFlightPlanLegCanvasLineRenderer();
renderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN] = new WT_MapViewFlightPlanLegCanvasLineRenderer();
renderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED] = new WT_MapViewFlightPlanLegCanvasLineRenderer();
renderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD] = new WT_MapViewFlightPlanLegCanvasArrowRenderer();
renderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT] = new WT_MapViewFlightPlanLegCanvasArrowRenderer();
return renderers;
}
_initLegRenderers() {
this._inactiveLegRenderers = this._initLegRenderersHelper(false);
this._activeLegRenderers = this._initLegRenderersHelper(true);
}
_initOptionChangeFuncs() {
this._optionChangeFuncs = [];
this._optionChangeFuncs["standardLineStrokeWidth"] = this._setStandardLineStrokeWidth.bind(this);
this._optionChangeFuncs["standardLineOutlineWidth"] = this._setStandardLineOutlineWidth.bind(this);
this._optionChangeFuncs["thinLineStrokeWidth"] = this._setThinLineStrokeWidth.bind(this);
this._optionChangeFuncs["thinLineOutlineWidth"] = this._setThinLineOutlineWidth.bind(this);
this._optionChangeFuncs["dottedLineStrokeWidth"] = this._setDottedLineStrokeWidth.bind(this);
this._optionChangeFuncs["dottedLineOutlineWidth"] = this._setDottedLineOutlineWidth.bind(this);
this._optionChangeFuncs["dottedLineDash"] = this._setDottedLineDash.bind(this);
this._optionChangeFuncs["standardArrowWidth"] = this._setStandardArrowWidth.bind(this);
this._optionChangeFuncs["standardArrowHeight"] = this._setStandardArrowHeight.bind(this);
this._optionChangeFuncs["standardArrowSpacing"] = this._setStandardArrowSpacing.bind(this);
this._optionChangeFuncs["standardArrowOutlineWidth"] = this._setStandardArrowOutlineWidth.bind(this);
this._optionChangeFuncs["altArrowWidth"] = this._setAltArrowWidth.bind(this);
this._optionChangeFuncs["altArrowHeight"] = this._setAltArrowHeight.bind(this);
this._optionChangeFuncs["altArrowSpacing"] = this._setAltArrowSpacing.bind(this);
this._optionChangeFuncs["altArrowOutlineWidth"] = this._setAltArrowOutlineWidth.bind(this);
this._optionChangeFuncs["inactiveColor"] = this._setInactiveColor.bind(this);
this._optionChangeFuncs["inactiveOutlineColor"] = this._setInactiveOutlineColor.bind(this);
this._optionChangeFuncs["activeColor"] = this._setActiveColor.bind(this);
this._optionChangeFuncs["activeOutlineColor"] = this._setActiveOutlineColor.bind(this);
}
_setStandardLineStrokeWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD].strokeWidth = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD].strokeWidth = value;
}
_setStandardLineOutlineWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD].outlineWidth = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD].outlineWidth = value;
}
_setThinLineStrokeWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN].strokeWidth = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN].strokeWidth = value;
}
_setThinLineOutlineWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN].outlineWidth = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN].outlineWidth = value;
}
_setDottedLineStrokeWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].strokeWidth = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].strokeWidth = value;
}
_setDottedLineOutlineWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].outlineWidth = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].outlineWidth = value;
}
_setDottedLineDash(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].dash = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].dash = value;
}
_setStandardArrowWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].width = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].width = value;
}
_setStandardArrowHeight(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].height = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].height = value;
}
_setStandardArrowSpacing(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].spacing = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].spacing = value;
}
_setStandardArrowOutlineWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].outlineWidth = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].outlineWidth = value;
}
_setAltArrowWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].width = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].width = value;
}
_setAltArrowHeight(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].height = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].height = value;
}
_setAltArrowSpacing(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].spacing = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].spacing = value;
}
_setAltArrowOutlineWidth(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].outlineWidth = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].outlineWidth = value;
}
_setInactiveColor(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD].strokeColor = value;
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN].strokeColor = value;
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].strokeColor = value;
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].fillColor = value;
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].fillColor = value;
}
_setInactiveOutlineColor(value) {
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD].outlineColor = value;
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN].outlineColor = value;
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].outlineColor = value;
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].outlineColor = value;
this._inactiveLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].outlineColor = value;
}
_setActiveColor(value) {
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD].strokeColor = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN].strokeColor = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].strokeColor = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].fillColor = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].fillColor = value;
}
_setActiveOutlineColor(value) {
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD].outlineColor = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN].outlineColor = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED].outlineColor = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD].outlineColor = value;
this._activeLegRenderers[WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT].outlineColor = value;
}
/**
* @param {String} name - the name of the option that changed.
* @param {*} oldValue - the old value of the option.
* @param {*} newValue - the new value of the option.
*/
onOptionChanged(name, oldValue, newValue) {
let func = this._optionChangeFuncs[name];
if (func) {
func(newValue);
}
}
/**
* Selects a style with which to render a flight plan leg.
* @param {WT_FlightPlanLeg} leg - the flight plan leg to render.
* @param {WT_FlightPlanLeg} activeLeg - the active leg in the flight plan, or null if there is no active leg.
* @param {Boolean} discontinuity - whether the previous flight plan leg ended in a discontinuity.
* @returns {WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle} the style with which to render the flight plan leg.
*/
_chooseStyle(leg, activeLeg, discontinuity) {
let activeIndexDelta = activeLeg ? leg.index - activeLeg.index : undefined;
if (discontinuity) {
if (activeLeg && activeIndexDelta >= 0) {
if (activeIndexDelta <= 1) {
return WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_ALT;
} else {
return WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_DOTTED;
}
}
return WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.NONE;
}
if (leg instanceof WT_FlightPlanProcedureLeg) {
switch (leg.procedureLeg.type) {
case WT_ProcedureLeg.Type.FLY_HEADING_UNTIL_DISTANCE_FROM_REFERENCE:
case WT_ProcedureLeg.Type.FLY_HEADING_UNTIL_REFERENCE_RADIAL_CROSSING:
case WT_ProcedureLeg.Type.FLY_HEADING_TO_INTERCEPT:
case WT_ProcedureLeg.Type.FLY_HEADING_TO_ALTITUDE:
return WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.ARROW_STANDARD;
}
}
if (activeLeg && leg.segment === activeLeg.segment && activeIndexDelta >= 0) {
return WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_STANDARD;
} else {
return WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.LINE_THIN;
}
}
/**
* Selects an appropriate leg renderer to render a flight plan leg.
* @param {WT_FlightPlanLeg} leg - the flight plan leg to render.
* @param {WT_FlightPlanLeg} activeLeg - the active leg in the flight plan, or null if there is no active leg.
* @param {Boolean} discontinuity - whether the previous flight plan leg ended in a discontinuity.
* @returns {WT_MapViewFlightPlanLegCanvasRenderer} a leg renderer, or null if the leg should not be rendered.
*/
chooseRenderer(leg, activeLeg, discontinuity) {
let style = this._chooseStyle(leg, activeLeg, discontinuity);
if (style === WT_G3x5_MapViewFlightPlanLegCanvasStyler.LegStyle.NONE) {
return null;
} else {
return leg === activeLeg ? this._activeLegRenderers[style] : this._inactiveLegRenderers[style];
}
}
} |
JavaScript | class EventBase {
constructor(target) {
this.target = target;
this.offFunctions = [];
return {
on: this.on.bind(this),
off: this.off.bind(this),
onOff: this.onOff.bind(this),
one: this.one.bind(this),
};
}
on(event, fn, opts = {}) {
this.target.addEventListener(event, fn, opts);
this.offFunctions.push(() => {
this.off(event, fn);
});
return this;
}
off(event, fn) {
if (typeof event !== 'string') {
this.offFunctions.forEach(fn => fn());
this.offFunctions = [];
} else {
this.target.removeEventListener(event, fn);
}
return this;
}
onOff(event, fn) {
this.on(event, fn);
return () => {
this.off(event, fn);
};
}
one(event, fn) {
this.on(event, fn, {once: true});
return this;
}
} |
JavaScript | class DSChannelWithFilter {
/**
* @param {DSChannel} channel
* @param {(DSUser) => boolean} filter
*/
constructor (channel, filter) {
this._emitter = new DSEventEmitter()
this._channel = channel
this._filter = filter
this._onMessageReceived = (...args) => this._handleMessage(...args).then()
}
get events () {
return this._emitter
}
async join () {
this._channel.events.on('message-received', this._onMessageReceived)
await this._channel.join()
}
async leave () {
this._channel.events.off('message-received', this._onMessageReceived)
await this._channel.leave()
}
/**
* Send message to the channel if not filtered.
*/
async send (message, to) {
if (to && !this._filter(to)) {
throw new Error('cannot send message to a filtered user')
}
await this._channel.send(message, to)
}
/**
* Emit the message if it is not filtered.
* @param {DSUser} from
* @param {DSMessage} message
*/
async _handleMessage (from, message) {
if (!this._filter(from)) {
return
}
this._emitter.emit('message-received', from, message)
}
} |
JavaScript | class Graph {
/**
* @brief Constructor.
*
* @param id_or_guid The key to identify this graph uniquely.
*/
constructor(id_or_guid, graphOptions) {
if ((graphOptions === undefined) || (graphOptions === null)) {
let titleOpts = make_textBoxOptions(
true,
'text',
'#FFFFFF',
'#404040',
'#000000',
1,
14,
'top');
let bannerOpts = make_textBoxOptions(
true,
'text',
'#FFFFFF',
'#404040',
'#000000',
1,
14,
'top');
let legendOpts = make_textBoxOptions(
true,
'text',
'#FFFFFF',
'#404040',
'#000000',
1,
14,
'top');
let x_axisOpts = make_axisOptions(
true,
'axis',
false,
undefined,
'#202020',
'#808080',
'dash',
6,
'#000000',
11);
let y_axisOpts = make_axisOptions(
true,
'axis',
false,
undefined,
'#202020',
'#808080',
'dash',
6,
'#000000',
11);
let y2_axisOpts = make_axisOptions(
true,
'axis',
false,
undefined,
'#202020',
'#808080',
'dash',
6,
'#000000',
11);
let z_axisOpts = make_axisOptions(
true,
'axis',
false,
undefined,
'#202020',
'#808080',
'dash',
6,
'#000000',
11);
graphOptions = make_graphOptions(
'#FFFFFF',
'#404040',
'#000000',
11, // Text size.
4, // Margin
titleOpts, bannerOpts, legendOpts,
x_axisOpts, y_axisOpts, undefined, z_axisOpts);
}
this.guid = id_or_guid; // Unique HTML wide ID of this thing.
this.series = []; // The series to graph.
this.graphOptions = graphOptions; // Options for the graph.
this.lastBounds = {'x': null, 'y': null, 'y2': null, 'z': null, 'w': null, 'h': null};
this.maxBounds = undefined; // Max bounds for scrolling.
this.lastLayout = {};
this.lastXY = {x:0, y: 0};
this._legendCalcs = undefined;
this.zoom = [];
let $topEl = $(this.guid);
// Quick lookup caching of the things we check during drawing repeatedly.
this.graphElements = {
$top: $topEl,
$canvas: $topEl.find('.ggGraph_canvas'),
$overlay: $topEl.find('.ggGraph_overlay'),
$elements: $topEl.find('.ggGraph_elements'),
$zoomReset: $topEl.find('.ggGraph_stepReset'),
$zoomOut: $topEl.find('.ggGraph_stepOut')
};
// Save off by ID.
ggGraph_Graphs[id_or_guid] = this;
}
/**
* @brief Compute axis markers.
*
* @param ctx Context for string measurement.
* @param isHorizontal Is horizontal vs. vertical axis.
* @param min Minimum value.
* @param max Maximum value.
* @param w Width in pixels.
* @param h Height in pixels.
* @param margin Margin in pixels between things.
* @param opt Options.
*/
_computeAxisMarkers(ctx, isHorizontal, min, max, w, h, margin, opt) {
// To measure things.
ctx.font = "" + opt.textSizePx + "px Verdana";
// We need to see the scope of things, lnMin, max are the bounds.
// How much we care is lnDel.
// Examples:
// min, max | scale
// 0.1 10.2 |
// 0.09 0.4 |
let lw = min < max ? min : max;
let hg = max > min ? max : min;
let rn = hg - lw;
rn = rn > 0 ? rn : 0.001;
let divs = Math.pow(10, Math.floor(Math.log10(rn)));
let rndDown = (Math.floor(lw /divs) * divs);
// Walk from rndDown up, keep when within lw and hg.
// divs are 0.1, 1, 10, etc. we need to allow 2,3,4,5 to get different numbers of ticks.
let remaining = isHorizontal ? w - margin : h - margin;
let best = [{p: isHorizontal ? 0: 1, t: lw}, {p: 1, t: hg}];
let scales = [0.25, 0.5, 1, 2, 4, 5];
for (let s_ii = 1; s_ii < 7; s_ii++){
let tmp = rndDown;
let proposed = [];
let rem = remaining;
let step = divs * scales[s_ii];
if (isHorizontal) {
while ((tmp <= hg) && rem > 0) {
if ((tmp <= hg) && (tmp >= lw)) {
let pos = (tmp - lw) / rn;
let v_str = roundToString(tmp, divs);
proposed.push({ p: pos, t: v_str});
rem -= margin + ctx.measureText(v_str).width;
}
tmp += step;
}
} else {
let rm_down = margin + opt.textSizePx;
while ((tmp <= hg) && rem > 0) {
if ((tmp <= hg) && (tmp >= lw)) {
let pos = (tmp - lw) / rn;
let v_str = roundToString(tmp, divs);
proposed.push({ p: 1 - pos, t: v_str});
rem -= rm_down;
}
tmp += step;
}
}
if (rem > 0) {
best = proposed;
break;
}
}
return best;
}
/**
* @brief Compute all axis min, max and axis markers.
*
* @param ctx Context.
* @param canvas_layout Size/spacing for the axis.
* @param dataBoundsX X bounds.
* @param dataBoundsY Y bounds.
* @param useMain If true, use main else summary.
*/
_computeAxis(ctx, canvas_layout, dataBoundsX, dataBoundsY, useMain) {
// Compute the bounds for x, y on the axis
// Determine the labels to use.
// Give some bounds or none, find the min/max for each axis.
let lx = objectExists(dataBoundsX) ? dataBoundsX.min : null;
let hx = objectExists(dataBoundsX) ? dataBoundsX.max : null;
let ly = objectExists(dataBoundsY) ? dataBoundsY.min : null;
let hy = objectExists(dataBoundsY) ? dataBoundsY.max : null;
let lxf = !objectExists(lx);
let hxf = !objectExists(hx);
let lyf = !objectExists(ly);
let hyf = !objectExists(hy);
if (lxf || hxf || lyf || hyf) {
for (let ii = 0; ii < this.series.length; ii++) {
let slx = this.series[ii].min('x');
let shx = this.series[ii].max('x');
let sly = this.series[ii].min('y');
let shy = this.series[ii].max('y');
if (this.graphOptions.main.graphType === '2DPolar') {
sly = sly > 0 ? 0 : sly;
}
if (lxf && objectExists(slx)) {
lx = objectExists(lx) ? (slx < lx ? slx : lx) : slx;
}
if (hxf && objectExists(shx)) {
hx = objectExists(hx) ? (shx > hx ? shx : hx) : shx;
}
if (lyf && objectExists(sly)) {
ly = objectExists(ly) ? (sly < ly ? sly : ly) : sly;
}
if (hyf && objectExists(shy)) {
hy = objectExists(hy) ? (shy > hy ? shy : hy) : shy;
}
}
}
// Now figure out the markers and scale.
let mx = [ lx, 0, hx, 1]; // left to right.
let my = [ hy, 0, ly, 1]; // bottom to top.
if (useMain) {
mx = this._computeAxisMarkers(ctx, true, lx, hx, canvas_layout.xAxis.w,
canvas_layout.xAxis.h, this.graphOptions.main.marginPx, this.graphOptions.xAxis);
// If this is polar, canvas_layout.yAxis.h = -1, instead use main graph.
let yAxis_h = canvas_layout.yAxis.h;
if (this.graphOptions.main.graphType === '2DPolar') {
yAxis_h = 0.5 * (canvas_layout.graph.w < canvas_layout.graph.h ?
canvas_layout.graph.w : canvas_layout.graph.h);
}
my = this._computeAxisMarkers(ctx, false, ly, hy, canvas_layout.yAxis.w,
yAxis_h, this.graphOptions.main.marginPx, this.graphOptions.yAxis);
} else {
mx = this._computeAxisMarkers(ctx, true, lx, hx, canvas_layout.xAxisSum.w,
canvas_layout.xAxisSum.h, this.graphOptions.main.marginPx, this.graphOptions.xAxis);
my = this._computeAxisMarkers(ctx, false, ly, hy, canvas_layout.yAxisSum.w,
canvas_layout.yAxisSum.h, this.graphOptions.main.marginPx, this.graphOptions.yAxis);
}
return {
// Marker values.
xBounds: { min: lx, max: hx, marks: mx},
yBounds: { min: ly, max: hy, marks: my},
yBounds2: undefined};
}
/**
* @brief Given a possible option, compute the layout within the bounding box.
*
* @param ctx Context 2d.
* @param box Bounding box: x,y,w,h
* @param opt Possible option.
* @param kind Is this an axis, legend or normal
*/
_computeBox(ctx, box, opt, kind) {
let isAxis = kind === 'axis';
let isLegend = kind === 'legend';
if (isAxis && (this.graphOptions.main.graphType === '2DPolar')) {
// unused, don't alter the box.
return [{
x: box.x,
y: box.y,
w: 0,
h: 0}, {
x: box.x,
y: box.y,
w: box.w,
h: box.h}];
}
let margin = defaultObject(this.graphOptions.main.marginPx, 2);
if ((this.graphOptions) && (opt) && (opt.show)) {
// Either way, both need this.
let textSize = defaultObject(opt.textSizePx, 11);
if ((opt.loc == 'top') || (opt.loc == 'bottom')) {
// Textbox, top/bottom:
// margin + textSizePx + margin
// Axis no text:
// marker + margin + textSizePx + margin
// Axis & text:
// marker + margin + textSizePx + margin + textSizePx + margin
// Legend no text:
// margin + rows * (margin + textSizePx)
// Legend & text:
// margin + (rows + 1) * (margin + textSizePx)
//
// It's mostly just about the rows ...
// Kind Rows Size
// Textbox no text 0 margin
// Textbox text 1 margin + rows * (textSizePx + margin)
// Axis no text 1 marker + margin + rows * (textSizePx + margin)
// Axis & text 2 marker + margin + rows * (textSizePx + margin)
// Legend no text crows margin + rows * (textSizePx + margin)
// Legend & text crows + 1 margin + rows * (textSizePx + margin)
//
// Always += 2*opt.borderSizePx if it exists.
let rows = 0;
// Calculate rows for legend, if it's a legend.
if (isLegend) {
let ws = [];
let w = 0;
ctx.font = "" + textSize + "px Verdana";
let items = this.series.length;
for (let ii = 0; ii < items; ii++) {
let seriesName = defaultObject(this.series[ii].seriesOptions.name, '').trim();
let wi = ctx.measureText(seriesName).width;
w = w > wi ? w : wi;
ws.push(wi);
}
w += (margin + textSize) * 2;
let maxCols = 0;
if (items > 1) {
// name, margin symbology,
maxCols = Math.floor(box.w / w);
maxCols = maxCols < 1 ? 1 : maxCols;
rows = Math.ceil(items / maxCols);
} else {
rows = 1;
}
maxCols = maxCols > items ? items : maxCols;
this._legendCalcs = {r: rows, c: maxCols, w: ws, mc : w};
}
// Add in any text label.
let hadLabel = objectExists(opt.textStr) && (opt.textStr.length > 0);
if (hadLabel) {
rows += 1;
}
// Axis add on.
let h = margin + rows * (textSize + margin);
if (isAxis) {
h += defaultObject(opt.markerSizePx, 6);
if (!hadLabel) {
h += margin;
}
}
// Border.
h += (objectExists(opt.borderSizePx) ? parseInt(opt.borderSizePx) * 2 : 0) + margin;
// Ensure minimum size.
if (objectExists(opt.minSize)) {
h = h > opt.minSize ? h : opt.minSize;
}
// If it has text,
//let h = offset + opt.markerSizePx + (isAxis ? 2 * opt.textSizePx : opt.textSizePx);
return [{
x: box.x,
y: opt.loc === 'top' ? box.y : box.y + box.h - h,
w: box.w,
h: h}, {
x: box.x,
y: opt.loc === 'top' ? box.y + h : box.y,
w: box.w,
h: box.h - h}];
} else {
// Textbox, left/right:
//
// tw = max text width.
//
// Textbox or legend:
// margin + tw + (margin * (tw != 0))
// Axis:
// += marker + margin.
let tw = 0;
ctx.font = "" + textSize + "px Verdana";
// Legend.
if (isLegend) {
// Calculate largest width.
let ws = [];
for (let ii = 0; ii < this.series.length; ii++) {
let seriesName = defaultObject(this.series[ii].seriesOptions.name, '').trim();
let wi = ctx.measureText(seriesName).width;
tw = tw > wi ? tw : wi;
ws.push(tw);
}
this._legendCalcs = {
r: this.series.length,
c: 1,
w: ws,
mc : tw + (margin + textSize) * 2};
}
// Text if it exists.
let wi = 0;
if (objectExists(opt.textStr) &&
objectExists(opt.textColor) &&
(opt.textSizePx > 0)) {
wi = ctx.measureText(opt.textStr.trim()).width;
}
tw = tw > wi ? tw : wi;
wi = ctx.measureText('01234').width;
tw = tw > wi ? tw : wi;
let w = margin + ((tw === 0) ? 0 : tw + margin);
// If axis...
if (isAxis) {
w += defaultObject(opt.markerSizePx, 6);
}
// Border.
w += margin + parseInt(defaultObject(opt.borderSizePx, 0));
// Minimum check.
if (objectExists(opt.minSize)) {
w = w > opt.minSize ? w : opt.minSize;
}
return [{
x: opt.loc === 'left' ? box.x : box.x + box.w - w,
y: box.y,
w: w,
h: box.h}, {
x: opt.loc === 'left' ? box.x + w : box.x,
y: box.y,
w: box.w - w,
h: box.h}];
}
}
return [undefined, box];
}
/**
* @brief Compute the layout for this graph.
*
* @param ctx Canvas context.
* @param width Canvas width.
* @param height Canvas height.
*/
_computeLayout(ctx, width, height) {
// Banner is used to be either top or bottom outermost box.
let go = this.graphOptions;
if (!objectExists(go)) {
return {
banner: undefined,
title: undefined,
legend: undefined,
graph: {x: 0, y: 0, w: width, h: height},
xSummary: undefined,
xAxisSum: undefined,
yAxisSum: undefined,
xAxis: undefined,
yAxis: undefined,
yAxis2: undefined};
}
let banner = undefined;
let title = undefined;
let legend = undefined;
let xSummary = undefined;
let margin = defaultObject(this.graphOptions.main.marginPx, 2);
let box = {x: 0, y: 0, w: width, h: height};
[banner, box] = this._computeBox(ctx, box, go.banner);
[title, box] = this._computeBox(ctx, box, go.title);
[legend, box] = this._computeBox(ctx, box, go.legend, 'legend');
let xopt = deepCopy(go.xAxis);
let yopt = deepCopy(go.yAxis);
let yopt2 = deepCopy(go.yAxis2);
if (xopt && (!xopt.loc)) {
xopt.loc = 'bottom';
}
if (yopt && (!yopt.loc)) {
yopt.loc = 'left';
}
if (yopt2 && (!yopt2.loc)) {
yopt2.loc = 'right';
}
let xAxis = undefined;
let yAxis = undefined;
let yAxis2 = undefined;
[xAxis, box] = this._computeBox(ctx, box, xopt, 'axis');
[yAxis, box] = this._computeBox(ctx, box, yopt, 'axis');
[yAxis2, box] = this._computeBox(ctx, box, yopt2, 'axis');
if (yAxis) {
yAxis.y += 1;
yAxis.h -= 1;
}
if (yAxis2) {
yAxis2.y += 1;
yAxis2.h -= 1;
}
// Adjust x to be inbetween the y's
if (xAxis) {
xAxis.w -= 1;
if (yAxis) {
xAxis.x = yAxis.x + yAxis.w;
xAxis.w -= yAxis.w;
}
if (yAxis2) {
xAxis.w -= yAxis2.w;
}
}
let xAxisSum = undefined;
let yAxisSum = undefined;
if (objectExists(go.main) && objectExists(go.main.xSummary)) {
let behavior = defaultObject(go.main.xSummary.behavior, 'onzoom');
if (((this.zoom.length > 0) && (behavior === 'onzoom')) || behavior === 'always') {
// Doing a zoom.
let percent = defaultObject(go.main.xSummary.sizePercent, 25);
percent = percent < 1 ? 1 : (percent > 100 ? 100 : percent);
let alignment = defaultObject(go.main.xSummary.alignment, 'top');
let xSumHeight = box.h * percent / 100;
let minPixels = defaultObject(go.main.xSummary.minSizePx, 0);
xSumHeight = xSumHeight > minPixels ? xSumHeight : minPixels;
if (objectExists(go.main.xSummary.maxSizePx)) {
xSumHeight = xSumHeight < go.main.xSummary.maxSizePx ?
xSumHeight : go.main.xSummary.maxSizePx;
}
[xSummary, box] = this._computeBox(
ctx,
box,
{borderSizePx: 0, loc: alignment, show: true, minSize: xSumHeight});
yAxis.h -= xSummary.h;
if (alignment === 'top') {
yAxis.y = xSummary.y + xSummary.h;
xAxisSum = {x: xAxis.x, w: xAxis.w, h: xAxis.h, y: xSummary.y + xSummary.h - xAxis.h };
xSummary.h -= xAxisSum.h;
yAxisSum = {x: yAxis.x, w: yAxis.w, h: xSummary.h, y: xSummary.y};
} else if (alignment === 'bottom') {
/* box: y 102, h 381
xsum: y 483, h 98
xaxis: y 611, h 29
xaxissum: y 582, h 29
xsum += xaxis
*/
xSummary.y += xAxis.h;
xSummary.h -= xAxis.h;
xAxis.y = xSummary.y - xAxis.h;
xAxisSum = {x: xAxis.x, w: xAxis.w, h: xAxis.h, y: xSummary.y + xSummary.h };
//xSummary.h -= xAxisSum.h;
yAxisSum = {x: yAxis.x, w: yAxis.w, h: xSummary.h, y: xSummary.y};
} else {
xAxisSum = {x: xAxis.x, w: xAxis.w, h: xAxis.h, y: xSummary.y + xSummary.h - xAxis.h };
xSummary.h -= xAxisSum.h;
yAxisSum = {x: yAxis.x, w: yAxis.w, h: xSummary.h, y: xSummary.y};
}
}
}
return {
banner: banner,
title: title,
legend: legend,
graph: box,
xSummary: xSummary,
xAxisSum: xAxisSum,
yAxisSum: yAxisSum,
xAxis: xAxis,
yAxis: yAxis,
yAxis2: yAxis};
}
/**
* @brief Resize event handler.
*/
handleResize() {
this._drawCanvas(this.lastBounds.x, this.lastBounds.y, true);
}
/**
* @brief Update graph options.
*/
updateOptions(graphOptions) {
this.graphOptions = graphOptions;
this._drawCanvas(this.lastBounds.x, this.lastBounds.y, false);
}
/**
* @brief Update graph options.
*/
redraw() {
this._drawCanvas(this.lastBounds.x, this.lastBounds.y, false);
}
/**
* @brief Draw the graph.
*
* @param dataBoundsX Data x bounds.
* @param dataBoundsY Data y bounds.
*/
draw(dataBoundsX, dataBoundsY) {
this._drawCanvas(dataBoundsX, dataBoundsY, false);
}
/**
* @brief Draw the graph.
*
* @param dataBoundsX Data x bounds.
* @param dataBoundsY Data y bounds.
* @param resizingFlag Is this due to a resize?
*/
_drawCanvas(dataBoundsX, dataBoundsY, resizingFlag) {
if (this.graphElements.$top.length === 0) {
// Didn't quite exist at graph construction, normal expected, fill it in now.
let $topEl = $('#' + this.guid);
this.graphElements = {
$top: $topEl,
$canvas: $topEl.find('.ggGraph_canvas'),
$overlay: $topEl.find('.ggGraph_overlay'),
$elements: $topEl.find('.ggGraph_elements'),
$zoomReset: $topEl.find('.ggGraph_stepReset'),
$zoomOut: $topEl.find('.ggGraph_stepOut')
};
}
let canvas = this.graphElements.$canvas[0];
let overlay = this.graphElements.$overlay[0];
let cw = canvas.clientWidth;
let ch = canvas.clientHeight;
if (cw === undefined || ch === undefined) {
return;
}
if (resizingFlag && (this.lastBounds.w === cw) && (this.lastBounds.h === ch)) {
return;
}
canvas.width = cw;
canvas.height = ch;
overlay.width = cw;
overlay.height = ch;
this.lastBounds = {'x': dataBoundsX, 'y': dataBoundsY, 'y2': null, 'z': null, 'w': cw, 'h': ch};
let ctx = canvas.getContext("2d");
let canvas_layout = this._computeLayout(ctx, cw, ch);
this.lastLayout = canvas_layout;
let axisInfo = this._computeAxis(ctx, canvas_layout, dataBoundsX, dataBoundsY, true);
let summaryAxisInfo = (canvas_layout.xSummary !== undefined) ?
this._computeAxis(ctx, canvas_layout, undefined, undefined, false) : undefined;
this.lastBounds.x = { min: axisInfo.xBounds.min, max: axisInfo.xBounds.max};
this.lastBounds.y = { min: axisInfo.yBounds.min, max: axisInfo.yBounds.max};
this.graphElements.$zoomOut.css('top', canvas_layout.graph.y);
this.graphElements.$zoomReset.css('top', canvas_layout.graph.y);
if (this.maxBounds === undefined) {
// Do once, for pan max bounds.
this.maxBounds = {
'x': { min: axisInfo.xBounds.min, max: axisInfo.xBounds.max},
'y': { min: axisInfo.yBounds.min, max: axisInfo.yBounds.max}, 'y2': null, 'z': null, 'w': cw, 'h': ch};
}
if (!objectExists(this.graphOptions)) {
return;
}
let graphOptions = this.graphOptions;
// Paint the series.
ctx.fillStyle = graphOptions.main.backgroundColor;
ctx.clearRect(0, 0, cw, ch);
ctx.fillRect(0, 0, cw, ch);
// 2D polar graphs.
if (graphOptions.main.graphType === '2DPolar') {
// Back in the graph layout slightly.
let ltmp = canvas_layout.graph;
let sx = ltmp.x + (0.5 * ltmp.w);
let sy = ltmp.y + (0.5 * ltmp.h);
let r = -1 + 0.5 * (ltmp.w < ltmp.h ? ltmp.w : ltmp.h);
canvas_layout.graph = {x: sx - r, y: sy -r, w: r + r, h: r + r};
if (objectExists(graphOptions.events) &&
objectExists(graphOptions.events.onBackground)) {
ctx.save();
graphOptions.events.onBackground(this, ctx, canvas_layout.graph)
ctx.restore();
}
let ymarks = objectExists(axisInfo.yBounds) ? axisInfo.yBounds.marks : undefined;
ctx.save();
this.drawGridPolar(ctx, true, canvas_layout.graph, undefined, sx, sy, r, graphOptions.xAxis);
this.drawGridPolar(ctx, false, canvas_layout.graph, ymarks, sx, sy, r, graphOptions.yAxis);
ctx.restore();
ctx.save();
for (let ii = 0; ii < this.series.length; ii++) {
this.series[ii].draw2DPolar(ctx, axisInfo, canvas_layout.graph);
}
ctx.restore();
// Clear out around the graph.
let right = canvas_layout.graph.x + canvas_layout.graph.w;
let bot = canvas_layout.graph.y + canvas_layout.graph.h;
ctx.clearRect(0, 0, canvas_layout.graph.x, ch); // Left.
ctx.clearRect(right, 0, cw - right, ch); // Right.
ctx.clearRect(0, 0, cw, canvas_layout.graph.y); // Top.
ctx.clearRect(0, bot, cw, ch - bot); // Bottom.
// Paint the legend, title, banner.
this.drawLegend(ctx, graphOptions.legend, canvas_layout.legend);
this.drawTextOption(ctx, graphOptions.title, canvas_layout.title);
this.drawTextOption(ctx, graphOptions.banner, canvas_layout.banner);
}
// 2D graphs.
if (graphOptions.main.graphType === '2D') {
let xmarks = objectExists(axisInfo.xBounds) ? axisInfo.xBounds.marks : undefined;
let ymarks = objectExists(axisInfo.yBounds) ? axisInfo.yBounds.marks : undefined;
let ymarks2 = objectExists(axisInfo.yBounds2) ? axisInfo.yBounds2.marks : undefined;
ctx.save();
this.drawGrid(ctx, true, canvas_layout.graph, xmarks, graphOptions.xAxis);
this.drawGrid(ctx, false, canvas_layout.graph, ymarks, graphOptions.yAxis);
this.drawGrid(ctx, false, canvas_layout.graph, ymarks2, graphOptions.yAxis2);
ctx.restore();
if (objectExists(graphOptions.events) &&
objectExists(graphOptions.events.onBackground)) {
ctx.save();
graphOptions.events.onBackground(this, ctx, canvas_layout.graph)
ctx.restore();
}
ctx.save();
for (let ii = 0; ii < this.series.length; ii++) {
this.series[ii].draw2D(ctx, axisInfo, canvas_layout.graph);
}
ctx.restore();
// Clear out around the graph.
let right = canvas_layout.graph.x + canvas_layout.graph.w;
let bot = canvas_layout.graph.y + canvas_layout.graph.h;
ctx.clearRect(0, 0, canvas_layout.graph.x, ch); // Left.
ctx.clearRect(right, 0, cw - right, ch); // Right.
ctx.clearRect(0, 0, cw, canvas_layout.graph.y); // Top.
ctx.clearRect(0, bot, cw, ch - bot); // Bottom.
if (canvas_layout.xSummary !== undefined) {
let xmarksS = objectExists(summaryAxisInfo.xBounds) ? summaryAxisInfo.xBounds.marks : undefined;
let ymarksS = objectExists(summaryAxisInfo.yBounds) ? summaryAxisInfo.yBounds.marks : undefined;
ctx.save();
this.drawGrid(ctx, true, canvas_layout.xSummary, xmarksS, graphOptions.xAxis);
this.drawGrid(ctx, false, canvas_layout.xSummary, ymarksS, graphOptions.yAxis);
ctx.restore();
ctx.save();
for (let ii = 0; ii < this.series.length; ii++) {
this.series[ii].draw2D(
ctx,
summaryAxisInfo,
canvas_layout.xSummary);
}
ctx.restore();
// Draw the zoomed box.
// data to screen, so dividing by the data range, multiply by screen range.
// the box is defined by: axisInfo.xBounds.min .max
ctx.strokeStyle = defaultObject(graphOptions.main.xSummary.markerColor, '#808080');
let xg = canvas_layout.xSummary.w / (summaryAxisInfo.xBounds.max - summaryAxisInfo.xBounds.min);
let yg = canvas_layout.xSummary.h / (summaryAxisInfo.yBounds.max - summaryAxisInfo.yBounds.min);
let xo = -summaryAxisInfo.xBounds.min * xg + canvas_layout.xSummary.x;
let yo = -summaryAxisInfo.yBounds.min * yg + canvas_layout.xSummary.y;
let dxr = (axisInfo.xBounds.max - axisInfo.xBounds.min) * xg;
let dyr = (axisInfo.yBounds.max - axisInfo.yBounds.min) * yg;
ctx.lineWidth = 2;
dxr = dxr < 8 ? 8 : dxr;
dyr = dyr < 8 ? 8 : dyr;
ctx.strokeRect(
axisInfo.xBounds.min * xg + xo,
axisInfo.yBounds.min * yg + yo,
dxr, dyr);
// Do the zoom axis.
ctx.strokeStyle = defaultObject(graphOptions.xAxis.markerColor, '#000000');
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(canvas_layout.xSummary.x, canvas_layout.xSummary.y);
ctx.lineTo(canvas_layout.xSummary.x, canvas_layout.xSummary.y + canvas_layout.xSummary.h);
ctx.lineTo(canvas_layout.xSummary.x + canvas_layout.xSummary.w,
canvas_layout.xSummary.y + canvas_layout.xSummary.h);
ctx.stroke();
// Draw the two summary axises.
this.drawAxis(ctx, true, graphOptions.xAxis, canvas_layout.xAxisSum, xmarksS, true);
this.drawAxis(ctx, false, graphOptions.yAxis, canvas_layout.yAxisSum, ymarksS, true);
}
// Fill behind the axises.
ctx.fillStyle = graphOptions.main.backgroundColor;
let axiss = [canvas_layout.xAxis, canvas_layout.yAxis, canvas_layout.xAxis];
for (let ii = 0; ii < 3; ii++) {
if (objectExists(axiss[ii])) {
ctx.fillRect(0, axiss[ii].y, axiss[ii].w, axiss[ii].h);
}
}
// Paint the axis.
this.drawAxis(ctx, true, graphOptions.xAxis, canvas_layout.xAxis, xmarks, false);
this.drawAxis(ctx, false, graphOptions.yAxis, canvas_layout.yAxis, ymarks, false);
this.drawAxis(ctx, false, graphOptions.yAxis2, canvas_layout.yAxis2, ymarks2, false);
// Paint the legend, title, banner.
this.drawLegend(ctx, graphOptions.legend, canvas_layout.legend);
this.drawTextOption(ctx, graphOptions.title, canvas_layout.title);
this.drawTextOption(ctx, graphOptions.banner, canvas_layout.banner);
if (objectExists(graphOptions.main.boxEdgeColor)) {
let lw = defaultObject(graphOptions.main.boxEdgeSizePx, 1);
ctx.lineWidth = lw;
let lw2 = 0.5 * lw;
ctx.save();
ctx.strokeStyle = graphOptions.main.boxEdgeColor;
ctx.strokeRect(
canvas_layout.graph.x + lw2,
canvas_layout.graph.y + lw2,
canvas_layout.graph.w - lw,
canvas_layout.graph.h - lw);
if (canvas_layout.xSummary !== undefined) {
ctx.strokeRect(
canvas_layout.xSummary.x + lw2,
canvas_layout.xSummary.y + lw2,
canvas_layout.xSummary.w - lw,
canvas_layout.xSummary.h - lw);
}
ctx.restore();
}
}
if (objectExists(graphOptions.events) &&
objectExists(graphOptions.events.onPainted)) {
ctx.save();
graphOptions.events.onPainted(this, ctx, canvas_layout)
ctx.restore();
}
}
/**
* @brief Draw the grid lines, if any.
*
* @param ctx Context.
* @param isAngle Is it horizontal or vertical?
* @param layout Layout.
* @param marks Where the marks go, an array.
* @param sx Center X.
* @param sy Center Y.
* @param r radius.
* @param opts Options for how to do it.
*/
drawGridPolar(ctx, isAngle, layout, marks, sx, sy, r, opts) {
if ((!objectExists(opts)) || (!objectExists(opts.graphlineColor))) {
return;
}
ctx.beginPath();
let clr = opts.graphlineColor;
clr = (clr === undefined) || (clr === null) ? '#000000' : clr;
ctx.strokeStyle = clr;
ctx.setLineDash(toCanvasDash(opts.graphLineDash));
// In case we do the text.
let hasText = objectExists(opts.textColor) && (opts.textSizePx > 0);
if (hasText) {
ctx.fillStyle = opts.textColor;
}
if (isAngle) {
let angleStyle = objectExists(this.graphOptions.xAxisOptions) ?
defaultObject(this.graphOptions.xAxisOptions.polarAngle, 'deg') :
'deg';
let angleMarkers =
angleStyle === 'nsew' ? ['N', 'NW', 'W', 'SW', 'S', 'SE', 'E', 'NE']:
angleStyle === 'deg' ? [ 0, 45, 90, 135, 180, 225, 270, 315]:
angleStyle === 'mills' ? [ 0, 450, 900, 1350, 1800, 2250, 2700, 3150]:
angleStyle === 'rad' ? [ 0, 0.785, 1.57, 2.356, 3.14, 3.926, 4.71, 5.497]:
angleStyle === 'sdeg' ? [ 0, 45, 90, 135, 180, -135, -90, -45]:
angleStyle === 'smills' ? [ 0, 450, 900, 1350, 1800, -1350, -900, -450]:
/*srad*/ [ 0, 0.785, 1.57, 2.356, 3.14, -2.356, -1.57, -0.785];
for (let ii = 0; ii < 8; ii++) {
let a = Math.PI * ii / 4;
ctx.moveTo(sx, sy);
let ex = sx + (r * Math.sin(a));
let ey = sy + (r * Math.cos(a));
ctx.lineTo(ex, ey);
if (hasText && (ii % 2 === 1)) {
// Only the odd ones.
let tw = ctx.measureText(angleMarkers[ii]).width;
ex += ex > sx ? opts.textSizePx : -tw - opts.textSizePx;
ey += ey < sy ? 0 : opts.textSizePx;
ctx.fillText(angleMarkers[ii], ex, ey);
}
}
} else {
for (let ii = 0; ii < marks.length; ii++) {
// Draw the circles.
let rp = r * marks[ii].p;
ctx.arc(sx, sy, rp, 0, 2*Math.PI);
if (!hasText) {
continue;
}
let offset = 0.5 * opts.textSizePx;
// Draw the text.
if (ii > 0) {
ctx.fillText(marks[ii].t, sx, sy + r - rp + offset - 1); // Lower.
ctx.fillText(marks[ii].t, sx, sy - r + rp - offset); // Upper
}
}
}
ctx.stroke();
ctx.setLineDash([]);
}
/**
* @brief Draw the grid lines, if any.
*
* @param ctx Context.
* @param isHorizontal Is it horizontal or vertical?
* @param layout Layout.
* @param marks Where the marks go, an array.
* @param opts Options for how to do it.
*/
drawGrid(ctx, isHorizontal, layout, marks, opts) {
if ((!objectExists(opts)) || (!objectExists(opts.graphlineColor))) {
return;
}
ctx.beginPath();
let clr = opts.graphlineColor;
clr = (clr === undefined) || (clr === null) ? '#000000' : clr;
ctx.strokeStyle = clr;
ctx.setLineDash(toCanvasDash(opts.graphLineDash));
if (isHorizontal) {
for (let ii = 0; ii < marks.length; ii++) {
let x = layout.x + layout.w * marks[ii].p;
ctx.moveTo(x, layout.y);
ctx.lineTo(x, layout.y + layout.h);
}
} else {
for (let ii = 0; ii < marks.length; ii++) {
let y = layout.y + layout.h * marks[ii].p;
ctx.moveTo(layout.x, y);
ctx.lineTo(layout.x + layout.w, y);
}
}
ctx.stroke();
ctx.setLineDash([]);
}
/**
* @brief Draw an axis.
*
* @param ctx Context.
* @param isHorizontal Is horizontal or vertical.
* @param opt Options.
* @param loc Location layout.
* @param marks Axis markings array.
* @param skipAxisText Flag, if true no axis text.
*/
drawAxis(ctx, isHorizontal, opt, loc, marks, skipAxisText) {
if ((!objectExists(opt)) || (!objectExists(loc)) || (opt.show === false)) {
return;
}
ctx.save();
let hasMarker = objectExists(opt.markerColor);
let hasText = objectExists(opt.textColor) && (opt.textSizePx > 0);
if (objectExists(opt.backgroundColor)) {
ctx.fillStyle = opt.backgroundColor;
ctx.fillRect(loc.x, loc.y, loc.w, loc.h);
}
if (objectExists(opt.textStr) && hasText && (!skipAxisText)) {
if (isHorizontal) {
drawCenteredFloorText(ctx, opt.textColor, 'Verdana', opt.textSizePx, loc, opt.textStr);
} else {
drawCenteredText(ctx, opt.textColor, 'Verdana', opt.textSizePx, loc, opt.textStr);
}
}
// Any more to do?
if (!(hasText || hasMarker)) {
ctx.restore();
return;
}
// Note:
// loc is the bounding box, axis is min, max, marks = array
ctx.beginPath();
ctx.setLineDash([]);
ctx.strokeStyle = hasMarker ? opt.markerColor : '#000000';
ctx.lineWidth = 2;
ctx.fillStyle = opt.textColor;
let margin = defaultObject(this.graphOptions.main.marginPx, 2);
let mark = objectExists(opt.markerSizePx) ? opt.markerSizePx : 6;
if (isHorizontal) {
let txt_min = loc.x + loc.w * 2;
let txt_max = txt_min + 1;
if (hasText && (loc.h <= mark + margin + margin + opt.textStr * 2)) {
if (objectExists(opt.textStr) && opt.textStr.length > 0) {
let titleWidth = ctx.measureText(opt.textStr.trim()).width;
txt_min = loc.x + (loc.w - titleWidth)/2 - margin;
txt_max = txt_min + titleWidth + margin;
}
}
// Line.
if (hasMarker) {
ctx.moveTo(loc.x, loc.y);
ctx.lineTo(loc.x + loc.w, loc.y);
}
let textY = loc.y + mark + margin + (opt.textSizePx *0.5);
// Marks and or Text.
let min_x = loc.x;
let max_x = loc.x + loc.w;
for (let ii = 0; ii < marks.length; ii++) {
// Value then (0-1) interval of location.
let m = min_x + loc.w * marks[ii].p;
if (hasMarker && (m > min_x + 4) && (m < max_x - 4)) {
ctx.moveTo(m, loc.y + mark);
ctx.lineTo(m, loc.y);
}
if (hasText) {
let tw = ctx.measureText(marks[ii].t).width;
let x_pos = m - (tw / 2);
x_pos = x_pos > min_x + margin ? x_pos : min_x + margin;
x_pos = x_pos < max_x - tw ? x_pos : max_x - tw;
if ((x_pos + tw < txt_min) || (x_pos > txt_max)) {
ctx.fillText(marks[ii].t, x_pos, textY);
}
}
}
} else {
let right = loc.x + loc.w;
if (hasMarker) {
ctx.moveTo(right, loc.y);
ctx.lineTo(right, loc.y + loc.h);
}
for (let ii = 0; ii < marks.length; ii++) {
let m = loc.y + loc.h * marks[ii].p;
if (hasMarker) {
ctx.moveTo(right - mark, m);
ctx.lineTo(right, m);
}
let tw = ctx.measureText(marks[ii].t).width;
if (hasText) {
ctx.fillStyle = opt.textColor;
ctx.fillText(marks[ii].t, loc.x + loc.w - tw - margin - mark, m + (ii == 0 ? opt.textSizePx : 0));
}
}
}
ctx.stroke();
ctx.restore();
}
/**
* @brief Draw the legend
*
* @param ctx Context 2d.
* @param opt Options structure.
* @param loc Location structure.
*/
drawLegend(ctx, opt, loc) {
if (objectNotExist(opt) || objectNotExist(loc) || (opt.show === false)) {
return;
}
ctx.save();
let margin = defaultObject(this.graphOptions.main.marginPx, 2);
// Background.
if (objectExists(opt.backgroundColor)) {
ctx.fillStyle = opt.backgroundColor;
ctx.fillRect(loc.x, loc.y, loc.w, loc.h);
}
// Border.
if (objectExists(opt.boxEdgeColor) && (opt.borderSizePx > 0)) {
ctx.strokeStyle = opt.boxEdgeColor;
ctx.lineWidth = opt.borderSizePx;
ctx.strokeRect(loc.x, loc.y, loc.w, loc.h);
}
// Vertical or horizontal it is the same, calculate the row,
// determine offset and step, and go for it.
// Compute the rows.
let textSize = defaultObject(opt.textSizePx, 11);
let items = this.series.length;
let rows = this._legendCalcs.r;
let widths = this._legendCalcs.w
let maxCols = this._legendCalcs.c;
let maxColWidth = this._legendCalcs.mc;
let hasText = objectExists(opt.textStr) && (opt.textStr.length > 0);
if (hasText) {
rows += 1
let w = ctx.measureText(opt.textStr.trim()).width;
widths.push(w);
}
// Center vertically.
let idealHeight = (margin + textSize) * rows + margin;
let vertical_margin = margin;
let offset = 0;
if (loc.h < idealHeight) {
// Not big enough, shrink margin.
vertical_margin = (loc.h - textSize * rows) / (rows + 1);
vertical_margin = vertical_margin < 1 ? 1 : vertical_margin;
idealHeight = (vertical_margin + textSize) * rows + vertical_margin;
}
offset = 0.5 * (loc.h - idealHeight) + textSize - 1;
// Draw the title text if it exists.
ctx.fillStyle = defaultObject(opt.textColor, '#000000');
if (hasText) {
ctx.fillText(
opt.textStr.trim(),
loc.x + (loc.w - widths[widths.length-1]) / 2,
loc.y + offset);
offset += textSize + vertical_margin;
}
let row = 0;
let col = 0;
let colSize = loc.w / maxCols;
let xAlign = (colSize - maxColWidth) * 0.5;
for (let ii = 0; ii < items; ii++) {
this.series[ii].draw_legend_item(
ctx, textSize, widths[ii], maxColWidth, margin,
margin + loc.x + col * colSize + xAlign,
loc.y + offset + row * (textSize + vertical_margin));
col += 1;
if (col >= maxCols) {
col = 0;
row += 1;
}
}
ctx.restore();
}
/**
* @brief Draw a text box.
*
* @param ctx Context 2d.
* @param opt Options structure.
* @param loc Location structure.
*/
drawTextOption(ctx, opt, loc) {
if ((opt === undefined) || (opt === null) || (loc === undefined) ||(loc === null) || (opt.show === false)) {
return;
}
ctx.save();
if (objectExists(opt.backgroundColor)) {
ctx.fillStyle = opt.backgroundColor;
ctx.fillRect(loc.x, loc.y, loc.w, loc.h);
}
if (objectExists(opt.boxEdgeColor) && (opt.borderSizePx > 0)) {
ctx.strokeStyle = opt.boxEdgeColor;
ctx.lineWidth = defaultObject(opt.borderSizePx, 1);
ctx.strokeRect(loc.x, loc.y, loc.w, loc.h);
}
if (objectExists(opt.textStr) && objectExists(opt.textColor) && (opt.textSizePx > 0)) {
drawCenteredText(ctx, opt.textColor, 'Verdana', opt.textSizePx, loc, opt.textStr);
}
ctx.restore();
}
/**
* @brief Using "this" and mouse offset x,y, do a pan operation.
*
* @param offsetX Event's offsetX mouse value.
* @param offsetY Event's offsetY mouse value.
*/
_doPan(offsetX, offsetY) {
// If not valid state of things, return.
if ((this.lastXY.x === -1) ||
(this.lastXY.y === -1) ||
(!objectExists(this.lastLayout)) ||
(!objectExists(this.lastLayout.graph)) ||
(!objectExists(this.lastBounds)) ||
(!objectExists(this.lastBounds.x)) ||
(!objectExists(this.lastBounds.y)) ||
(this.graphOptions.main.graphType === '2DPolar')) {
return;
}
let bounds = this.lastBounds;
let layout = this.lastLayout.graph;
let sign = 1;
if (inBox(this.lastXY.x, this.lastXY.y, this.lastLayout.xSummary)) {
bounds = this.maxBounds;
layout = this.lastLayout.xSummary;
sign = -1;
}
// dlx, dly is the screen to data scaling of the given
// summary or graph region for the change in x,y
let sx = (bounds.x.max - bounds.x.min) / layout.w;
let sy = (bounds.y.max - bounds.y.min) / layout.h;
let dlx = sign * sx * (this.lastXY.x - offsetX);
let dly = sign * sy * (this.lastXY.y - offsetY);
if ((dlx === 0) && (dly === 0)) {
// nothing to do.
return;
}
let lx = this.lastBounds.x.min + dlx;
let gx = this.lastBounds.x.max - this.lastBounds.x.min;
let ly = this.lastBounds.y.min + dly;
let gy = this.lastBounds.y.max - this.lastBounds.y.min;
this.lastXY.x = offsetX;
this.lastXY.y = offsetY;
if (objectExists(this.maxBounds)) {
lx = (lx + gx < this.maxBounds.x.max) ? lx : this.maxBounds.x.max - gx;
lx = (lx > this.maxBounds.x.min) ? lx : this.maxBounds.x.min;
ly = (ly + gy < this.maxBounds.y.max) ? ly : this.maxBounds.y.max - gy;
ly = (ly > this.maxBounds.y.min) ? ly : this.maxBounds.y.min;
// Limit to data bounds.
lx = minMax(lx, this.maxBounds.x.min, this.maxBounds.x.max);
ly = minMax(ly, this.maxBounds.y.min, this.maxBounds.y.max);
}
this.graphElements.$zoomOut.css('display', 'block');
this.graphElements.$zoomReset.css('display', 'block');
if (objectExists(this.graphOptions.events) &&
objectExists(this.graphOptions.events.onPanStart)) {
if (!this.graphOptions.events.onPanStart(this, dlx, lx, lx + gx, dly, ly, ly + gy)){
return;
}
}
this.draw({min: lx, max: lx + gx}, {min: ly, max : ly + gy});
if (objectExists(this.graphOptions.events) &&
objectExists(this.graphOptions.events.onPanEnd)) {
this.graphOptions.events.onPanEnd(this, dlx, lx, lx + gx, dly, ly, ly + gy);
}
}
/**
* @brief Using "this" and mouse offset x,y, do a pan operation.
*
* @param ctx 2D overlay context.
* @param offsetX Event's offsetX mouse value.
* @param offsetY Event's offsetY mouse value.
*/
_doMouseOver(ctx, offsetX, offsetY) {
if ((offsetX < this.lastLayout.graph.x) ||
(offsetY < this.lastLayout.graph.y) ||
(offsetX > this.lastLayout.graph.x + this.lastLayout.graph.w) ||
(offsetY > this.lastLayout.graph.y + this.lastLayout.graph.h)) {
return;
}
// Look for hover over, sx,sy scales screen to data, px,py is data space x,y.
let sx = (this.lastBounds.x.max - this.lastBounds.x.min) / this.lastLayout.graph.w;
let sy = (this.lastBounds.y.max - this.lastBounds.y.min) / this.lastLayout.graph.h;
let px = ((offsetX - this.lastLayout.graph.x) * sx) + this.lastBounds.x.min;
let py = ((offsetY - this.lastLayout.graph.y) * sy) + this.lastBounds.y.min;
// Not over anything if not +/- 20 pixels.
let dx = 20 * sx;
let dy = 20 * sy;
// We use inverse sx and sy in the loop.
sx = 1 / sx;
sy = 1 / sy;
let best = {range: undefined, series: undefined, cache: -1, index: -1 };
if (this.graphOptions.main.graphType === '2D') {
for (let ii = 0; ii < this.series.length; ii++) {
best = this.series[ii].mouseOver2D(px, py, dx, dy, sx, sy, best);
}
if (best.series !== undefined) {
// Show it.
best.series.drawMouseOver2D(ctx, this.lastLayout.graph, this.lastBounds, best);
}
}
}
/**
* @brief Canvas event.
*
* @param eventId What the event is.
* @param eventObj The UI event.
* @param $canvasParent Parent of canvases.
*/
canvasEvent(eventId, eventObj, $canvasParent) {
if (this.graphElements.$overlay.length === 0) {
return;
}
let overlayCanvas = this.graphElements.$overlay[0];
let ctx = overlayCanvas.getContext("2d");
if (eventObj.target.nodeName === 'BUTTON'){
return;
}
let wasButton = eventObj.which;
let dragKey = eventObj.shiftKey;
if (eventId > 10) {
let evtStr = (eventId === 14)? 'move' : eventId === 15 ? 'down' : eventId === 16 ? 'up' : eventId;
console.log("Touch event: " + eventId + ' ' + evtStr);
eventId -= 10;
eventObj.preventDefault();
if (objectExists(eventObj.touches) &&
(eventObj.touches.length > 1)) {
// Treat as drag.
dragKey = true;
}
if (objectExists(eventObj.targetTouches) &&
(eventObj.targetTouches.length > 0)) {
eventObj.offsetX = eventObj.targetTouches[0].clientX;
eventObj.offsetY = eventObj.targetTouches[0].clientY;
eventObj.buttons = 1;
} else {
if (objectExists(eventObj.changedTouches) &&
(eventObj.changedTouches.length > 0)) {
// Touch release.
eventObj.offsetX = eventObj.changedTouches[0].clientX;
eventObj.offsetY = eventObj.changedTouches[0].clientY;
eventObj.buttons = 1;
wasButton = 1;
}
}
}
switch(eventId){
case 0: // click.
break;
case 1: // dblclick.
break;
case 2: // mouse enter.
this.graphElements.$elements.css('opacity', 1);
break;
case 3: // mouse leave.
this.graphElements.$elements.css('opacity', 0.2);
ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
this.lastXY = {x: -1, y: -1};
break;
case 4: // mouse move.
if (eventObj.buttons === 0) {
// No mouse button.
this.lastXY = {x: -1, y: -1};
ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
this._doMouseOver(ctx, eventObj.offsetX, eventObj.offsetY);
break;
}
if (eventObj.buttons === 1) {
if ((this.lastXY.x === -1) || (this.lastXY.y === -1)) {
return; // Do nothing.
}
let in_normal =
inBox(this.lastXY.x, this.lastXY.y, this.lastLayout.graph) &&
inBox(eventObj.offsetX, eventObj.offsetY, this.lastLayout.graph);
let in_summary =
inBox(this.lastXY.x, this.lastXY.y, this.lastLayout.xSummary) &&
inBox(eventObj.offsetX, eventObj.offsetY, this.lastLayout.xSummary);
if ((!in_normal) && (!in_summary)) {
// One of the points is out of bounds, don't do anything.
return;
}
if (!dragKey) {
// left move zoom.
// Going to do something, so clear.
ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
let lx = this.lastXY.x;
let wi = eventObj.offsetX - this.lastXY.x;
let ly = this.lastXY.y;
let he = eventObj.offsetY - this.lastXY.y;
let mode = 'auto';
ctx.fillStyle = '#80808080'; // Default.
let strokeColor = '';
if (objectExists(this.graphOptions.main.zoom)) {
mode = defaultObject(this.graphOptions.main.zoom.currentMode, 'auto');
ctx.fillStyle = defaultObject(this.graphOptions.main.zoom.fillColor, '#80808080');
strokeColor = defaultObject(this.graphOptions.main.zoom.strokeColor, '');
}
let wi_abs = Math.abs(wi);
let he_abs = Math.abs(he);
if (mode === 'auto') {
if ((wi_abs < 10) && (he_abs > 100)) {
mode = 'x';
}
if ((he_abs < 10) && (wi_abs > 100)) {
mode = 'y';
}
}
let layoutInside = in_normal ? this.lastLayout.graph : this.lastLayout.xSummary;
if (mode === 'x') {
// x only zoom.
ly = layoutInside.y;
he = layoutInside.h;
}
if (mode === 'y') {
lx = layoutInside.x;
wi = layoutInside.w;
}
ctx.fillRect(lx, ly, wi, he);
if (strokeColor !== '') {
ctx.lineWidth = 1;
ctx.strokeStyle = strokeColor;
ctx.strokeRect(lx, ly, wi, he);
}
} else {
// Pan.
this._doPan(eventObj.offsetX, eventObj.offsetY);
}
}
break;
case 5: // down.
ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
if (eventObj.buttons === 1) {
this.lastXY = {x: eventObj.offsetX, y: eventObj.offsetY};
}
break;
case 6: // up.
ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
if ((this.lastXY.x === -1) || (this.lastXY.y === -1)) {
return;
}
if ((!objectExists(this.lastLayout)) ||
(!objectExists(this.lastLayout.graph)) ||
(!objectExists(this.lastBounds)) ||
(!objectExists(this.lastBounds.x)) ||
(!objectExists(this.lastBounds.y))) {
return;
}
let lx = eventObj.offsetX;
let hx = this.lastXY.x;
let ly = eventObj.offsetY;
let hy = this.lastXY.y;
if (this.lastXY.x < eventObj.offsetX) {
lx = this.lastXY.x;
hx = eventObj.offsetX;
}
if (this.lastXY.y < eventObj.offsetY) {
ly = this.lastXY.y;
hy = eventObj.offsetY;
}
if (wasButton === 1) {
let in_normal =
inBox(this.lastXY.x, this.lastXY.y, this.lastLayout.graph) &&
inBox(eventObj.offsetX, eventObj.offsetY, this.lastLayout.graph);
inBox(this.lastXY.x, this.lastXY.y, this.lastLayout.xSummary);
let in_summary =
inBox(this.lastXY.x, this.lastXY.y, this.lastLayout.xSummary) &&
inBox(eventObj.offsetX, eventObj.offsetY, this.lastLayout.xSummary);
if ((!in_normal) && (!in_summary)) {
// One of the points is out of bounds, don't do anything.
return;
}
if (!dragKey) {
if ((hx - lx < 4) || (hy - ly < 4)) {
return;
}
let mode = 'auto';
if (objectExists(this.graphOptions.main.zoom)) {
mode = defaultObject(this.graphOptions.main.zoom.currentMode, 'auto');
}
let wi = Math.abs(hx - lx);
let he = Math.abs(hy - ly);
if (mode === 'auto') {
if ((wi < 10) && (he > 100)) {
mode = 'x';
}
if ((he < 10) && (wi > 100)) {
mode = 'y';
}
}
let layoutInside = in_normal ? this.lastLayout.graph : this.lastLayout.xSummary;
let bounds = in_normal ? this.lastBounds : this.maxBounds;
if (mode === 'x') {
// x only zoom.
ly = layoutInside.y;
hy = layoutInside.h + ly;
}
if (mode === 'y') {
lx = layoutInside.x;
hx = layoutInside.w + lx;
}
// Release of left click, no shift key so, zoom!
// Compute the data lx, hx, ly, hy from screen.
let sx = (bounds.x.max - bounds.x.min) / layoutInside.w;
let sy = (bounds.y.max - bounds.y.min) / layoutInside.h;
lx = ((lx - layoutInside.x) * sx) + bounds.x.min;
hx = ((hx - layoutInside.x) * sx) + bounds.x.min;
ly = ((ly - layoutInside.y) * sy) + bounds.y.min;
hy = ((hy - layoutInside.y) * sy) + bounds.y.min;
// Limit to data bounds.
lx = minMax(lx, this.maxBounds.x.min, this.maxBounds.x.max);
hx = minMax(hx, this.maxBounds.x.min, this.maxBounds.x.max);
ly = minMax(ly, this.maxBounds.y.min, this.maxBounds.y.max);
hy = minMax(hy, this.maxBounds.y.min, this.maxBounds.y.max);
this.zoom.push( {x:{min: lx, max: hx}, y:{min: ly, max : hy}});
this.graphElements.$zoomOut.css('display', 'block');
this.graphElements.$zoomReset.css('display', 'block');
if (objectExists(this.graphOptions.events) &&
objectExists(this.graphOptions.events.onZoomStart)) {
if (!this.graphOptions.events.onZoomStart(this, lx, hx, ly, hy)){
return;
}
}
this.draw({min: lx, max: hx}, {min: ly, max : hy});
if (objectExists(this.graphOptions.events) &&
objectExists(this.graphOptions.events.onZoomEnd)) {
this.graphOptions.events.onZoomEnd(this, lx, hx, ly, hy);
}
} else {
// On mouse up push the pan change.
this.zoom.push( {
x:{min: this.lastBounds.x.min, max: this.lastBounds.x.max},
y:{min: this.lastBounds.y.min, max: this.lastBounds.y.max}});
}
}
break;
default: //
break;
}
}
/**
* @brief Zoom out one step.
*/
zoomOut() {
if (this.zoom.length > 0) {
this.zoom.pop();
}
if (this.zoom.length > 0) {
let lvl = this.zoom[this.zoom.length-1];
this.draw(lvl.x, lvl.y);
} else {
this.zoomReset();
}
}
/**
* @brief Reset the zoom.
*/
zoomReset() {
this.zoom = [];
let $el = $('#' + this.guid);
$el.find('.ggGraph_stepOut').css('display', 'none');
$el.find('.ggGraph_stepReset').css('display', 'none');
this.draw(undefined, undefined);
}
/**
* @brief Add series to the graph and update it.
*
* @param series Series to add.
*/
addSeries(series) {
this.series.push(series);
ggGraph_Graphs[this.guid] = this;
}
} |
JavaScript | class CommonMetric {
static __projections() {
return {
counter: (y, value) => value + 1,
last_value: (y) => y,
sum: (y, value) => value + y
}
}
static getConfig(options) {
return {
class: options.kind,
title: options.title,
width: options.width,
height: options.height,
series: [
{ ...XSeriesValue() },
newSeriesConfig(options, 0)
],
scales: {
x: {
min: options.now - 60,
max: options.now
},
y: {
min: 0,
max: 1
},
},
axes: [
XAxis(),
YAxis(options)
]
}
}
static initialData() {
return [[], []]
}
constructor(chart, options) {
this.__callback = this.constructor.__projections()[options.metric]
this.chart = chart
this.datasets = [{ key: "|x|", data: [] }]
this.options = options
this.pruneThreshold = getPruneThreshold(options)
if (options.tagged) {
this.chart.delSeries(1)
this.__handler = nextTaggedValueForCallback
} else {
this.datasets.push({ key: options.label, data: [] })
this.__handler = nextValueForCallback
}
}
handleMeasurements(measurements) {
// prune datasets when we reach the max number of events
measurements.forEach((measurement) => this.__handler.call(this, measurement, this.__callback))
let currentSize = this.datasets[0].data.length
if (currentSize >= this.pruneThreshold) {
this.datasets = this.datasets.map(({ data, ...rest }) => {
return { data: data.slice(-this.pruneThreshold), ...rest }
})
}
this.chart.setData(dataForDatasets(this.datasets))
}
} |
JavaScript | class Summary {
constructor(options, chartEl) {
// TODO: Get percentiles from options
let config = this.constructor.getConfig(options)
// Bind the series `values` callback to this instance
config.series[1].values = this.__seriesValues.bind(this)
this.datasets = [{ key: "|x|", data: [] }]
this.chart = new uPlot(config, this.constructor.initialData(options), chartEl)
this.pruneThreshold = getPruneThreshold(options)
this.options = options
if (options.tagged) {
this.chart.delSeries(1)
this.__handler = this.handleTaggedMeasurement.bind(this)
} else {
this.datasets.push(this.constructor.newDataset(options.label))
this.__handler = this.handleMeasurement.bind(this)
}
}
handleMeasurements(measurements) {
measurements.forEach((measurement) => this.__handler(measurement))
this.__maybePruneDatasets()
this.chart.setData(dataForDatasets(this.datasets))
}
handleTaggedMeasurement(measurement) {
let seriesIndex = this.findOrCreateSeries(measurement.x)
this.handleMeasurement(measurement, seriesIndex)
}
handleMeasurement(measurement, sidx = 1) {
let { z: timestamp } = measurement
this.datasets = this.datasets.map((dataset, index) => {
if (dataset.key === "|x|") {
dataset.data.push(timestamp)
} else if (index === sidx) {
this.pushToDataset(dataset, measurement)
} else {
this.pushToDataset(dataset, null)
}
return dataset
})
}
findOrCreateSeries(label) {
let seriesIndex = this.datasets.findIndex(({ key }) => label === key)
if (seriesIndex === -1) {
seriesIndex = this.datasets.push(
this.constructor.newDataset(label, this.datasets[0].data.length)
) - 1
let config = {
values: this.__seriesValues.bind(this),
...newSeriesConfig({ label }, seriesIndex - 1)
}
this.chart.addSeries(config, seriesIndex)
}
return seriesIndex
}
pushToDataset(dataset, measurement) {
if (measurement === null) {
dataset.data.push(null)
dataset.agg.avg.push(null)
dataset.agg.max.push(null)
dataset.agg.min.push(null)
return
}
let { y } = measurement
// Increment the new overall totals
dataset.agg.count++
dataset.agg.total += y
// Push the value
dataset.data.push(y)
// Push min/max/avg
if (dataset.last.min === null || y < dataset.last.min) { dataset.last.min = y }
dataset.agg.min.push(dataset.last.min)
if (dataset.last.max === null || y > dataset.last.max) { dataset.last.max = y }
dataset.agg.max.push(dataset.last.max)
dataset.agg.avg.push((dataset.agg.total / dataset.agg.count))
return dataset
}
__maybePruneDatasets() {
let currentSize = this.datasets[0].data.length
if (currentSize > this.pruneThreshold) {
let start = -this.pruneThreshold;
this.datasets = this.datasets.map(({ key, data, agg }) => {
let dataPruned = data.slice(start)
if (!agg) {
return { key, data: dataPruned }
}
let { avg, count, max, min, total } = agg
let minPruned = min.slice(start)
let maxPruned = max.slice(start)
return {
key,
data: dataPruned,
agg: {
avg: avg.slice(start),
count,
min: minPruned,
max: maxPruned,
total
},
last: {
min: findLastNonNullValue(minPruned),
max: findLastNonNullValue(maxPruned)
}
}
})
}
}
__seriesValues(u, sidx, idx) {
let dataset = this.datasets[sidx]
if (dataset && dataset.data && dataset.data[idx]) {
let { agg: { avg, max, min }, data } = dataset
return {
Value: data[idx].toFixed(3),
Min: min[idx].toFixed(3),
Max: max[idx].toFixed(3),
Avg: avg[idx].toFixed(3)
}
} else {
return { Value: "--", Min: "--", Max: "--", Avg: "--" }
}
}
static initialData() { return [[], []] }
static getConfig(options) {
return {
class: options.kind,
title: options.title,
width: options.width,
height: options.height,
series: [
{ ...XSeriesValue() },
newSeriesConfig(options, 0)
],
scales: {
x: {
min: options.now - 60,
max: options.now
},
y: {
min: 0,
max: 1
},
},
axes: [
XAxis(),
YAxis(options)
]
}
}
static newDataset(key, length = 0) {
let nils = length > 0 ? Array(length).fill(null) : []
return {
key,
data: [...nils],
agg: { avg: [...nils], count: 0, max: [...nils], min: [...nils], total: 0 },
last: { max: null, min: null }
}
}
} |
JavaScript | class Container extends React.Component {
constructor(props) {
super(props)
// This doesnt get auto-binded in ES6, therefore:
// This state is the main state of the app, and data can be sent to child components by storing it in props
this.state = {
}
}
render() {
return (
<div>
<p>hoiiiiiii</p>
</div>
)
}
} |
JavaScript | class CanvasWrapper {
constructor(data) {
this.data = data;
this.view = new Uint32Array(this.data.data.buffer);
}
getAddr32(i, j) {
return i + this.data.width * j
}
fillRectWith(color, op, x, y, w, h) {
assert(_.isNumber(color));
assert(_.isString(op));
if (x < 0) {
x = 0;
}
if (x >= this.data.width) {
x = this.data.width - 1;
}
if (y < 0) {
y = 0;
}
if (y >= this.data.height) {
y = this.data.height - 1;
}
if (x + w >= this.data.width) {
w = this.data.width - x;
}
if (y + h >= this.data.height) {
h = this.data.height - y;
}
for (let i = 0; i < w; ++i) {
for (let j = 0; j < h; ++j) {
if (op === 'or') {
this.view[this.getAddr32(i + x, j + y)] |= color;
} else {
assert(op === 'set');
this.view[this.getAddr32(i + x, j + y)] = color;
}
}
}
}
orRect(color, x, y, w, h) {
return this.fillRectWith(color, 'or', x, y, w, h);
}
fillRect(color, x, y, w, h) {
return this.fillRectWith(color, 'set', x, y, w, h);
}
strokeRect(color, x, y, w, h) {
if (x < 0) {
x = 0;
}
if (x >= this.data.width) {
x = this.data.width - 1;
}
if (y < 0) {
y = 0;
}
if (y >= this.data.height) {
y = this.data.height - 1;
}
if (x + w >= this.data.width) {
w = this.data.width - x;
}
if (y + h >= this.data.height) {
h = this.data.height - y;
}
--w; --h;
for (let i = 0; i < w; ++i) {
this.view[this.getAddr32(i + x, y)] = color;
this.view[this.getAddr32(i + x, y + h)] = color;
}
for (let j = 0; j <= h; ++j) {
this.view[this.getAddr32(x, j + y)] = color;
this.view[this.getAddr32(x + w, j + y)] = color;
}
}
fillBitmap(x, y, message, key) {
assert(x >= 0);
assert(y >= 0);
for (let j = 0; j < message.length; ++j) {
assert(y + j < this.data.height);
let line = message[j];
for (let i = 0; i < line.length; ++i) {
assert(x + i < this.data.width);
assert(message[j][i] in key)
this.view[this.getAddr32(i + x, j + y)] = key[message[j][i]];
}
}
}
} |
JavaScript | class SmoMeasureModifierBase {
constructor(ctor) {
this.ctor = ctor;
if (!this['attrs']) {
this.attrs = {
id: VF.Element.newID(),
type: ctor
};
} else {
console.log('inherit attrs');
}
}
static deserialize(jsonObj) {
const ctor = eval(jsonObj.ctor);
const rv = new ctor(jsonObj);
return rv;
}
} |
JavaScript | class SmoTempoText extends SmoMeasureModifierBase {
static get tempoModes() {
return {
durationMode: 'duration',
textMode: 'text',
customMode: 'custom'
};
}
static get tempoTexts() {
return {
larghissimo: 'Larghissimo',
grave: 'Grave',
lento: 'Lento',
largo: 'Largo',
larghetto: 'Larghetto',
adagio: 'Adagio',
adagietto: 'Adagietto',
andante_moderato: 'Andante moderato',
andante: 'Andante',
andantino: 'Andantino',
moderator: 'Moderato',
allegretto: 'Allegretto',
allegro: 'Allegro',
vivace: 'Vivace',
presto: 'Presto',
prestissimo: 'Prestissimo'
};
}
static get defaults() {
return {
tempoMode: SmoTempoText.tempoModes.durationMode,
bpm: 120,
beatDuration: 4096,
tempoText: SmoTempoText.tempoTexts.allegro,
yOffset: 0,
display: false,
customText: ''
};
}
static get attributes() {
return ['tempoMode', 'bpm', 'display', 'beatDuration', 'tempoText', 'yOffset', 'customText'];
}
compare(instance) {
var rv = true;
SmoTempoText.attributes.forEach((attr) => {
if (this[attr] != instance[attr]) {
rv = false;
}
});
return rv;
}
_toVexTextTempo() {
return { name: this.tempoText };
}
// ### eq
// Return equality wrt the tempo marking, e.g. 2 allegro in textMode will be equal but
// an allegro and duration 120bpm will not.
static eq (t1,t2) {
if (t1.tempoMode !== t2.tempoMode) {
return false;
}
if (t1.tempoMode === SmoTempoText.tempoModes.durationMode) {
return t1.bpm === t2.bpm && t1.beatDuration === t2.beatDuration;
}
if (t1.tempoMode === SmoTempoText.tempoModes.textMode) {
return t1.tempoText === t2.tempoText;
} else {
return t1.bpm === t2.bpm && t1.beatDuration === t2.beatDuration &&
t1.tempoText === t2.tempoText;
}
}
static get bpmFromText() {
// TODO: learn these
var rv = {};
rv[SmoTempoText.tempoTexts.larghissimo] = 24;
rv[SmoTempoText.tempoTexts.grave] = 40;
rv[SmoTempoText.tempoTexts.lento] = 45;
rv[SmoTempoText.tempoTexts.largo] = 40;
rv[SmoTempoText.tempoTexts.larghetto] = 60;
rv[SmoTempoText.tempoTexts.adagio] = 72;
rv[SmoTempoText.tempoTexts.adagietto] = 72;
rv[SmoTempoText.tempoTexts.andante_moderato] = 72;
rv[SmoTempoText.tempoTexts.andante] = 84;
rv[SmoTempoText.tempoTexts.andantino] = 92;
rv[SmoTempoText.tempoTexts.moderator] = 96;
rv[SmoTempoText.tempoTexts.allegretto] = 96;
rv[SmoTempoText.tempoTexts.allegro] = 120;
rv[SmoTempoText.tempoTexts.vivace] = 144;
rv[SmoTempoText.tempoTexts.presto] = 168;
rv[SmoTempoText.tempoTexts.prestissimo] = 240;
return rv;
}
_toVexDurationTempo() {
var vd = smoMusic.ticksToDuration[this.beatDuration];
var dots = (vd.match(/d/g) || []).length;
vd = vd.replace(/d/g, '');
const rv = { duration: vd, dots: dots, bpm: this.bpm };
if (this.customText.length) {
rv.name = this.customText;
}
return rv;
}
toVexTempo() {
if (this.tempoMode === SmoTempoText.tempoModes.durationMode ||
this.tempoMode === SmoTempoText.tempoModes.customMode) {
return this._toVexDurationTempo();
}
return this._toVexTextTempo();
}
backupOriginal() {
this.backup = {};
smoSerialize.serializedMerge(SmoTempoText.attributes, this, this.backup);
}
restoreOriginal() {
smoSerialize.serializedMerge(SmoTempoText.attributes, this.backup, this);
}
serialize() {
var params = {};
smoSerialize.serializedMergeNonDefault(SmoTempoText.defaults, SmoTempoText.attributes, this, params)
params.ctor = 'SmoTempoText';
return params;
}
constructor(parameters) {
super('SmoTempoText');
parameters = typeof(parameters) !== 'undefined' ? parameters : {};
smoSerialize.serializedMerge(SmoTempoText.attributes, SmoTempoText.defaults, this);
smoSerialize.serializedMerge(SmoTempoText.attributes, parameters, this);
}
} |
JavaScript | class FCMClient {
constructor(firebase, pushManager) {
this.FCM = firebase.messaging();
this.FCN = firebase.notifications();
this.pushManager = pushManager;
}
serviceName = 'fcm';
async init() {
// set up the notification handlers and handle any pending notifications
const self = this;
self.onNotificationOpened = this.FCN.onNotificationOpened((notification) => {
// Listen for a Notification getting opened if we are in the background
// eg, tap from notification bar
this.pushManager.onNotificationOpened(notification);
});
self.notificationListener = this.FCN.onNotification((notification) => {
// Listen for a Notification if we are in the foreground
this.pushManager.onNotification(notification);
});
}
async register() {
// the FCM token might change over time so we register here for updates and push them through
// to the pushManager
this.refreshTokenListener = this.FCM.onTokenRefresh((token) => {
this.didRegister(token);
});
// here we return a Promise that fulfills once the token becomes available but we're still
// responsible for sending it through to the pushManager
this.FCM.getToken().then((token) => {
this.didRegister(token);
});
// block until we get a push token
await new Promise((resolve, reject) => {
this.gotToken = resolve;
this.failedToGetToken = reject;
});
}
didRegister = (token) => {
console.log('Registered for push: ', token);
this.pushManager.updateToken(this.serviceName, token);
this.gotToken(token);
};
// eslint-disable-next-line
clear() {
// NYI: here we stop accepting push notifications and unsubscribe ourselves from callbacks
// if (this.notificationListener) {
// this.notificationListener.remove();
// }
}
async deregister() {
// here we tell firebase we don't care about further updates to the push token
if (this.refreshTokenListener) {
this.refreshTokenListener = null;
}
}
} |
JavaScript | class CoursesController {
/**
* @constructor
* @param {object} TitleService - Controlling our title.
*/
constructor(TitleService, Courses, UsersService, $uibModal) {
"ngInject";
Object.assign(this, {$uibModal, UsersService});
TitleService.setTitle({
newTitle: 'Courses List'
});
this.courses = Courses;
}
manageCourseCandidates(course) {
const modalInstance = this.$uibModal.open({
template: require('./../views/manageCandidates.jade')(),
controller: 'ManageCourseCandidatesController as ManageCandidatesCtrl',
resolve: {
Course: () => {
return course;
},
Users: () => {
return this.UsersService.getAll().then((response) => response.users);
}
}
});
}
} |
JavaScript | class ChildProcessWithCloseEvent extends AsyncObject {
constructor (childProcess, event) {
super(childProcess, event)
}
// event is an Event with body(code, signal)
syncCall () {
return (childProcess, event) => {
childProcess.on('close', event)
return childProcess
}
}
} |
JavaScript | class RowLarge extends React.Component {
constructor(props) {
super(props);
this.renderKeyValue = this.renderKeyValue.bind(this);
}
renderKeyValue(field, fieldIndex) {
const { index, parent } = this.props;
const rawContent = getRowData(parent, index);
const dataKey = getDataKey(field);
const value = rawContent[dataKey];
if (value == null) {
return null;
}
const cellContent = renderCell(index, parent, field);
const tooltip = typeof cellContent === 'string' ? cellContent : null;
const label = getLabel(field);
return (
<div className={theme['field-group']} role="group" key={label || index}>
<dt key={fieldIndex} className={theme['field-label']}>
{label}
{this.props.t('COLON', { defaultValue: ':' })}
</dt>
<dd className={theme['field-value']} title={tooltip}>
{cellContent}
</dd>
</div>
);
}
render() {
const { className, index, onKeyDown, parent, style } = this.props;
const { titleField, selectionField, otherFields } = extractSpecialFields(parent);
const parentId = getId(parent);
const id = parentId && `${parentId}-${index}`;
const titleCell = titleField && renderCell(index, parent, titleField, LARGE);
const selectionCell = selectionField && renderCell(index, parent, selectionField);
const rowData = getRowData(parent, index);
let onRowClick;
let onRowDoubleClick;
if (parent.props.onRowClick) {
onRowClick = event => parent.props.onRowClick({ event, rowData });
}
if (parent.props.onRowDoubleClick) {
onRowDoubleClick = event => parent.props.onRowDoubleClick({ event, rowData });
}
return (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
className={classNames(
'tc-list-item',
'tc-list-large-row',
rowThemes,
rowData.className,
className,
)}
id={id}
onClick={onRowClick}
onDoubleClick={onRowDoubleClick}
onKeyDown={e => onKeyDown(e, this.ref)}
style={style}
ref={ref => {
this.ref = ref;
}}
role="listitem"
tabIndex="0"
aria-posinset={index + 1}
aria-setsize={parent.props.rowCount}
aria-label={titleField && getCellData(titleField, parent, index)}
>
<div className={`tc-list-large-inner-box ${theme['inner-box']}`} key="inner-box">
{isEmpty(rowData) ? (
<MemoLargeInnerRowLoading
columns={LOADING_ROW_COLUMNS_COUNT}
rows={Math.floor(otherFields.length / LOADING_ROW_COLUMNS_COUNT) + 1}
/>
) : (
<React.Fragment>
<div className={theme.header} key="header">
{titleCell}
{selectionCell}
</div>
<dl className={`tc-list-large-content ${theme.content}`} key="content">
{otherFields.map(this.renderKeyValue)}
</dl>
</React.Fragment>
)}
</div>
</div>
);
}
} |
JavaScript | class AbstractStep {
/**
*
* @param {Reporter} reporter
* @param {BenchmarkBuffer} buffer
* @param {BenchmarkConfiguration} config
* @param {string} name of the step
* @param {string} description of the step
*/
constructor (reporter, buffer, config, name, description) {
this.reporter = reporter;
this.buffer = buffer;
this.config = config;
this.name = name;
this.description = description;
this.rooms = [];
this.log = {
update: config.benchmark.silent ? () => {} : logUpdate,
done: config.benchmark.silent ? () => {} : logUpdate.done
};
}
/**
* Launches this benchmark step
* @param {function} callback
*/
run(callback) { // eslint-disable-line no-unused-vars
if (!this.config.benchmark.silent) {
console.log('='.repeat(79));
console.log(`=== ${this.description}`);
}
}
/**
* Run the benchmark, using the provided "fn" function with the
* following expected prototype:
* fn(client, payload, callback)
*
* Options:
* * maxRequests:
* override this.config.documents.count (used to limit the
* batch size for slow steps)
* * maxClients:
* override this.config.benchmark.clients (used to control
* the kuzzle stack capabilities on small-size environements)
* @param {Function} fn
* @param {Function} callback - nodeback resolution
* @param {Object} opts
*/
benchmark(fn, callback, opts = {}) {
const
batchSize = opts.maxRequests || this.config.documents.count,
clients = opts.maxClients || this.buffer.clients.length,
packet = Math.max(1, Math.round(batchSize / clients));
let
total = 0,
notifications = 0,
errored = false,
waitingForRunners = clients;
if (!this.config.benchmark.silent) {
if (Object.keys(opts).length > 0) {
console.log(`(limits: ${batchSize} requests, ${clients} clients)`);
}
}
const runner = (client, docno, done, runnercb) => fn(client, this.buffer.documents[docno % this.buffer.documents.length], response => {
if (response.status !== 200) {
errored = true;
return runnercb(response);
}
if (response.type === 'document') {
notifications++;
return;
}
if (errored || total >= batchSize || done >= packet) {
return runnercb();
}
total++;
runner(client, docno+1, done+1, runnercb);
});
for(let i = 0; i < clients; i++) {
runner(this.buffer.clients[i], i * clients, 0, err => {
if (err) {
console.log(err);
return callback(err);
}
waitingForRunners--;
});
}
let lastNotifCount = notifications;
const
start = Date.now(),
timer = setInterval(() => {
const
elapsed = Date.now() - start,
requestsRate = Math.round(total / elapsed * 1000);
this.log.update(`${Math.round(total*100/batchSize)}% | Requests completed: ${total} | Elapsed: ${Math.round(elapsed / 1000)}s | ${requestsRate} requests/s | ${notifications} notifications received`);
if (errored || (lastNotifCount === notifications && waitingForRunners === 0)) {
clearInterval(timer);
this.log.done();
if (!errored) {
this.reporter.append(this.name, {
elapsed,
requestsRate,
notifications,
clients,
requests: total,
description: this.description,
}, callback);
}
}
lastNotifCount = notifications;
}, 200);
}
subscribe(generateFilters, callback) {
const
start = Date.now(),
subPerClient = Math.round(
this.config.subscriptions.count / this.buffer.clients.length),
currySubscribe = client => {
let remaining = subPerClient;
const send = () => client.send(JSON.stringify({
index: this.config.kuzzle.index,
collection: this.config.kuzzle.collection,
controller: 'realtime',
action: 'subscribe',
body: generateFilters()
}));
return cb => {
client.benchmarkListener = payload => {
if (payload.status === 200) {
this.rooms.push(payload.result.roomId);
remaining--;
if (remaining > 0) {
send();
}
else {
client.benchmarkListener = null;
cb();
}
}
else {
cb(payload);
}
};
send();
};
};
console.log('Starting subscriptions...');
const tasks = [];
for (let i = 0; i < subPerClient; i++) {
tasks.push(currySubscribe(this.buffer.clients[i]));
}
async.parallel(tasks, err => {
if (err) {
return callback(err);
}
const
elapsed = Date.now() - start,
total = tasks.length * subPerClient;
console.log(`${total} subscriptions done (took: ${elapsed}ms)`);
callback();
});
}
unsubscribe(callback) {
const
start = Date.now(),
currySubscribe = idx => {
return cb => {
this.buffer.clients[idx].benchmarkListener = () => {
this.buffer.clients[idx].benchmarkListener = null;
cb();
};
this.buffer.clients[idx].send(JSON.stringify({
controller: 'realtime',
action: 'unsubscribe',
body: {
roomId: this.rooms[idx]
}
}));
};
};
console.log('Unsubscribing...');
const tasks = [];
for(let i = 0; i < this.buffer.clients.length; i++) {
tasks.push(currySubscribe(i));
}
async.parallel(tasks, err => {
if (err) {
return callback(err);
}
console.log(`Unsubscriptions done (took: ${Date.now() - start}ms)`);
this.rooms = [];
callback();
});
}
} |
JavaScript | class Ambrosus {
deploy() {
throw new NotImplementedError();
}
at(address) {
this.contract.address = address;
return this;
}
get address() {
return this.contract.options.address.toLowerCase();
}
get web3() {
return Configuration.web3;
}
} |
JavaScript | class AutoText extends React.PureComponent {
/* New autotext is cached inside the internal state to avoid flooding the persistent store. */
state = {
abbr: "",
full: "",
selected: [],
};
/* Selections and autotext are cached until they are passed to the action creators for persistent changes. */
render() {
const {formatMessage} = this.props.intl;
return (
<Dictionary
id="abbr"
entries={this.props.abbrs}
keyLabel={formatMessage(messages.abbreviation)}
valueLabel={formatMessage(messages.fullForm)}
onSelect={(keys) => this.setState({selected: keys})}
onDelete={this.props.delRegex.bind(this, this.state.selected)}
onAdd={this.props.addRegex.bind(this, this.state.abbr, this.state.full)}
onKeyChange={(evt, val) => this.setState({abbr: val})}
onValueChange={(evt, val) => this.setState({full: val})}
height={this.props.height}/>
);
}
} |
JavaScript | class FMouseInputEditor {
/**
* called when an actor in the scene gain focus
* editConfig is defined in app\system/supGame/plugins\sparklinlabs\scene\editors\scene.ts:createComponentElement()
*/
constructor(tbody, config, projectClient, editConfig) {
this.editConfig = editConfig;
this.projectClient = projectClient;
let textRow = SupClient.table.appendRow(tbody, "Camera");
let textField = SupClient.table.appendTextField(textRow.valueCell, config.cameraActorName);
this.cameraActorNameField = textField;
this.cameraActorNameField.addEventListener("change", (event) => {
this.editConfig("setProperty", "cameraActorName", event.target.value.trim());
});
}
config_setProperty(path, value) {
if (this.projectClient.entries == null)
return;
switch (path) {
case "cameraActorName":
this.cameraActorNameField.value = value;
break;
}
}
/* tslint:disable:no-empty */
// empty methods necessary to prevent errors when in the scene editor
destroy() { }
onEntriesReceived(entries) { }
onEntryAdded(entry, parentId, index) { }
onEntryMoved(id, parentId, index) { }
onSetEntryProperty(id, key, value) { }
onEntryTrashed(id) { }
} |
JavaScript | class CoordinatesHelper {
constructor() {
throw new Error('StaticClassError');
}
/**
* Given a source and destination graphic, it returns the coordinates of `source`
* related to the `destination` coordinate system
* @param {(Phaser.Sprite|Phaser.Group)} source - The Sprite or Group to be dragged
* @param {(Phaser.Sprite|Phaser.Group)} destination - The Sprite or Group to be dragged
* @returns {Phaser.Point} The computed point
*/
static transformCoordinates(source, destination, reference = new Phaser.Point(0.5, 0.5)) {
const sourceTree = this.getTree(source);
const destinationTree = this.getTree(destination);
const commonAncestor = this.findCommonAncestor(sourceTree, destinationTree);
const parentPosition = this.pointInAncestor(source, commonAncestor, reference);
const toPosition = this.pointInDescendant(parentPosition, commonAncestor, destination);
return toPosition;
}
/**
* Checks if a point is contained inside a sprite
* @param {Phaser.Point} point - A Point
* @param {(Phaser.Sprite|Phaser.Group)} sprite - A Sprite or Group
* @returns {boolean}
*/
static contains(point, sprite) {
return point.x >= (sprite.x - (sprite.anchor.x * sprite.width)) &&
point.x < (sprite.x + (sprite.anchor.x * sprite.width)) &&
point.y >= (sprite.y - (sprite.anchor.y * sprite.height)) &&
point.y <= (sprite.y + (sprite.anchor.y * sprite.height));
}
/**
* Given a sprite and one of its ancestors, it returns the coordinates of the sprite
* relative to its ancestor coordinate system
* @param {Phaser.Sprite} sprite - A Sprite
* @param {(Phaser.Sprite|Phaser.Group)} ancestor - A Sprite's ancestor
* @param {Phaser.Point} [pivot=new Phaser.Point(0.5, 0.5)] - The pivot
* @returns {Phaser.Point} The computed point
*/
static pointInAncestor(sprite, ancestor, pivot = new Phaser.Point(0.5, 0.5)) {
const coordinates = new Phaser.Point(
this.getPositionX(sprite, pivot.x, true),
this.getPositionY(sprite, pivot.y, true),
);
let current = sprite;
while (current.parent !== ancestor) {
current = current.parent;
const withScale = current.parent !== ancestor;
coordinates.x += this.getPositionX(current, pivot.x, withScale);
coordinates.y += this.getPositionY(current, pivot.y, withScale);
}
return coordinates;
}
/**
* Converts a point in an element coordinate system in one of it's descendant coordinates
* @param {Phaser.Point} point - A Point in `reference` coordinate system
* @param {(Phaser.Sprite|Phaser.Group)} reference - A reference Sprite or Group
* @param {(Phaser.Sprite|Phaser.Group)} descendant - A descendant Sprite or Group
* @returns {Phaser.Point} The computed point
*/
static pointInDescendant(point, reference, descendant) {
const coordinates = new Phaser.Point(point.x, point.y);
const tree = [];
let current = descendant.parent;
while (current !== reference) {
tree.push(current);
current = current.parent;
if (!current) {
throw new Error('`reference` is not an ancestor of `descendant`');
}
}
for (let i = tree.length - 1; i >= 0; i -= 1) {
const element = tree[i];
coordinates.x = (coordinates.x - element.x) / element.scale.x;
coordinates.y = (coordinates.y - element.y) / element.scale.y;
}
return coordinates;
}
static sizeInAncestor(sprite, ancestor) {
const size = new Phaser.Point(sprite.width, sprite.height);
let current = sprite;
while (current.parent !== ancestor) {
size.x *= current.parent.scale.x;
size.y *= current.parent.scale.y;
current = current.parent;
}
return size;
}
/**
* Given an object, it returns the list of its ancestors, from the nearest to the farest
* @param {(Phaser.Sprite|Phaser.Group)} element - The Sprite or Group
*/
static getTree(element) {
const parents = [];
while (element.parent != null) {
element = element.parent;
parents.push(element);
}
return parents;
}
/**
* Given an object, it returns the list of its ancestors, from the nearest to the farest
* @param {(Phaser.Sprite|Phaser.Group)} element - The Sprite or Group
*/
static findCommonAncestor(tree1, tree2) {
for (let i = 0; i < tree1.length; i += 1) {
const el1 = tree1[i];
for (let j = 0; j < tree2.length; j += 1) {
const el2 = tree2[j];
if (el1 === el2) {
return el1;
}
}
}
return null;
}
static getPositionX(object, referenceX, withScale = false) {
const x = object.x + ((object.anchor ? referenceX - object.anchor.x : 0) * object.width);
if (withScale && object.parent) {
return x * object.parent.scale.x;
}
return x;
}
static getPositionY(object, referenceY, withScale = false) {
const y = object.y + ((object.anchor ? referenceY - object.anchor.y : 0) * object.height);
if (withScale && object.parent) {
return y * object.parent.scale.y;
}
return y;
}
} |
JavaScript | class LiveEventPreviewAccessControl {
/**
* Create a LiveEventPreviewAccessControl.
* @member {object} [ip] The IP access control properties.
* @member {array} [ip.allow] The IP allow list.
*/
constructor() {
}
/**
* Defines the metadata of LiveEventPreviewAccessControl
*
* @returns {object} metadata of LiveEventPreviewAccessControl
*
*/
mapper() {
return {
required: false,
serializedName: 'LiveEventPreviewAccessControl',
type: {
name: 'Composite',
className: 'LiveEventPreviewAccessControl',
modelProperties: {
ip: {
required: false,
serializedName: 'ip',
type: {
name: 'Composite',
className: 'IPAccessControl'
}
}
}
}
};
}
} |
JavaScript | class Batch extends Component {
constructor() {
super();
this.state = {
batchNum: "",
bagNum: "",
species: "",
bagSize: "",
growthStage: "",
uniqueID: ""
}
}
handleFormSubmit = event => {
event.preventDefault();
API.startBatch(this.state.batchNum, this.state.bagNum, this.state.species, this.state.bagSize, this.state.growthStage, this.state.uniqueID)
.then(res => {
alert(`Added: ${res.data.species}`)
this.setState({
batch: res.data,
bag: res.data,
species: res.data,
bagSize: res.data,
growth: res.data,
uniqueID: res.data
})
})
.catch(err => {
alert(err.response.data.message)
});
};
handleChange = event => {
const {name, value} = event.target;
this.setState({
[name]: value
});
};
// Kat Search Batch --------------------
searchBatch = () => {
let { searchNumber } = this.state;
searchNumber = "";
axios
.get(`/api/batch/${searchNumber}`)
.then(data => {
this.setState({ batches: data.data });
})
.catch(err => console.log(err));
};
// Kat Search Batch --------------------
render() {
// Kat Search Batch --------------------
const { batches } = this.state;
let batchRows;
if (batches) {
batchRows = batches.map(batch => {
return (
// batch.toString removes error log in console
<div key={batch._id}
style={{
border: "1px solid #ced4da",
backgroundColor: "white",
borderRadius: ".25rem",
color: "#007bff",
textDecoration: "underline",
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 10,
marginBottom: 5
}}
>
<div>
<div className="row">
<div className="col-sm-1"></div>
{`Species: ${batch.species}`}
</div>
<div className="row">
<div className="col-sm-1"></div>
{`Batch Number: ${batch.batchNum}`}
</div>
<div className="row">
<div className="col-sm-1"></div>
{`Bag Number: ${batch.bagNum}`}
</div>
<div className="row">
<div className="col-sm-1"></div>
{`Bag Size: ${batch.bagSize}`}
</div>
<div className="row">
<div className="col-sm-1"></div>
{`Growth Stage: ${batch.growthStage}`}
</div>
<div className="row">
<div className="col-sm-1"></div>
{`Batch ID: ${batch.batchNum.toString() + batch.bagNum.toString()}`}
</div>
</div>
</div>
);
});
} else {
batchRows = <p>Loading...</p>;
}
// Kat Search Batch --------------------
return (
<div className="container">
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<h1 className="AdminpageTitle">Batch Information</h1>
<div className="row">
<div className="col-sm-4">
<form onSubmit={this.handleFormSubmit}>
<div className="form-group">
<label htmlFor="batchNum">Batch Number:</label>
<input className="form-control"
placeholder="20190204"
name="batchNum"
type="number"
id="batchNum"
onChange={this.handleChange}/>
</div>
<div className="form-group">
<label htmlFor="bagNum">Bag Number:</label>
<input className="form-control"
placeholder="Enter Bag Number"
name="bagNum"
type="number"
id="bagNum"
onChange={this.handleChange}/>
</div>
<div className="form-group">
<label htmlFor="species">Species:</label>
<input className="form-control"
placeholder="Enter Species Here"
name="species"
type="text"
id="species"
onChange={this.handleChange}/>
</div>
<div className="form-group">
<label htmlFor="bagSize">Bag Size:</label>
<input className="form-control"
placeholder="Enter Bag Size"
name="bagSize"
type="number"
id="bagSize"
onChange={this.handleChange}/>
</div>
<div className="form-group">
<label htmlFor="growthStage">Growth Stage:</label>
<input className="form-control"
placeholder="Enter Growth Stage"
name="growthStage"
type="number"
id="growthStage"
onChange={this.handleChange}/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
{/* <p><Link to="/signup">Go to Signup</Link></p> */}
<div className="col-sm-4">
{/* Kat Search Batch -------------------- */}
<div style={{marginBottom: "10px"}}>
<label htmlFor="bagSize">Search all batches: </label>
<br/>
<button onClick={this.searchBatch} className="btn btn-primary">Search</button>
</div>
{batchRows}
{/* Kat Search Batch -------------------- */}
</div>
</div>
</div>
);
}
} |
JavaScript | class Line extends List {
static getModel() {
return Sign
}
/**
* Diff the line-model against the provided string (usually from the DOM representation
* of this line). Therefore, inserts/deletes to the data will be to bring it into
* alignment with the given string
*
* @public
* @instance
*
* @param {string} str a string to synchronize this line to
*/
synchronizeTo(str) {
// TODO: handle whitespace chars more consistently.
// Note: for the purpose of synchronization algorithm, it is important that the
// the whitespace char be a single char (rather than or something)
let diffs = diff(this.toString().replace(/\s/g, ' '), str.replace(/\s/g, ' '))
let diffIndex = 0
for (let i = 0, n = diffs.length; i < n; i++) {
// each diff in the array takes this shape:
// [code = 0, 1, -1, change = 'string difference']
let d = diffs[i]
switch (d[0]) {
// no change, simply increment up our string index
case diff.EQUAL:
diffIndex = diffIndex + d[1].length
break
// there's been (a) sign(s) inserted
case diff.INSERT:
d[1].split('').forEach(char => {
this.insert(
new Sign({
chars: [
{
sign_char: char,
},
],
}),
diffIndex
)
diffIndex++
})
break
// there's been a sign deleted
case diff.DELETE:
d[1].split('').forEach(() => this.delete(diffIndex))
break
}
}
}
toDOMString() {
let str = ''
this.forEach(sign => {
let classes = ''
const attrs = sign.attributes()
attrs.forEach(attribute => {
const name = attribute.attribute_name === '' ? '' : attribute.attribute_name + '_'
attribute.values.forEach(value => {
classes += value.attribute_value === '' ? '' : name + value.attribute_value + ' '
})
})
classes += classes.indexOf('is_reconstructed_TRUE') === -1 ? 'is_reconstructed_FALSE' : ''
str += `<span class="${classes}">${sign.toDOMString()}</span>`
}, this)
return `<p data-line-id="${this.getID()}">${str}</p>`
}
/**
* @returns {string} a plain string with all signs
*/
toString() {
let str = ''
this.forEach(sign => {
str += sign.toString()
}, this)
return str
}
} |
JavaScript | class CharUpgrade extends GData {
toJSON(){
let p = super.toJSON();
if ( this.char ) {
if ( !p ) p = {};
p.char = this.char;
}
return p;
}
/**
* @property {boolean} charlock - indicates upgrade locked to a single character.
*/
get charlock(){ return this._charlock }
set charlock(v){
this._charlock=v;
}
/**
* @property {string} char - id of character bound to upgrade.
*/
get char(){ return this._char }
set char(v){ this._char = v;}
constructor(vars=null){
super(vars);
}
/**
*
* @param {Game} g
* @param {number} amt
* @returns {boolean}
*/
changed( g, amt ) {
if ( this.charlock && amt > 0 ) {
this.char = g.state.player.hid;
}
return super.changed( g, amt );
}
/**
*
* @param {GameState} gs
*/
revive( gs ) {
let p = gs.player;
if ( this.char && p.hid !== this.char ) {
this.disabled = true;
console.log( this.id + ' DISABLED FOR ' + p.hid );
}
}
} |
JavaScript | class PluginTester {
constructor(config = {}, docpadConfig = {}) {
/**
* The DocPad instance
* @private
* @type {DocPad}
*/
this.docpad = null
/**
* Default plugin config
* @type {TesterConfig}
*/
this.config = {
DocPad: null,
testerName: null,
pluginName: null,
pluginPath: null,
PluginClass: null,
testPath: null,
outExpectedPath: null,
whitespace: 'trim',
contentRemoveRegex: null,
autoExit: 'safe',
...config,
}
// Ensure plugin name
if (!this.config.pluginName) {
this.config.pluginName = pathUtil
.basename(this.config.pluginPath)
.replace('docpad-plugin-', '')
}
// Ensure tester name
if (!this.config.testerName) {
this.config.testerName = `${this.config.pluginName} plugin`
}
// Prepare test paths
if (!this.config.testPath) {
this.config.testPath = pathUtil.join(this.config.pluginPath, 'test')
}
if (!this.config.outExpectedPath) {
this.config.outExpectedPath = pathUtil.join(
this.config.testPath,
'out-expected'
)
}
/**
* Default DocPad config
* @type {DocPadConfig}
*/
this.docpadConfig = {
global: true,
port: ++pluginPort,
logLevel:
process.argv.includes('-d') || process.argv.includes('--debug') ? 7 : 5,
rootPath: null,
outPath: null,
srcPath: null,
pluginPaths: null,
catchExceptions: false,
environment: null,
...docpadConfig,
}
// Extend DocPad Configuration
if (!this.docpadConfig.rootPath) {
this.docpadConfig.rootPath = this.config.testPath
}
if (!this.docpadConfig.outPath) {
this.docpadConfig.outPath = pathUtil.join(
this.docpadConfig.rootPath,
'out'
)
}
if (!this.docpadConfig.srcPath) {
this.docpadConfig.srcPath = pathUtil.join(
this.docpadConfig.rootPath,
'src'
)
}
}
/**
* Get tester Configuration
* @return {TesterConfig}
*/
getConfig() {
return this.config
}
/**
* Get the plugin instance
* @return {BasePlugin} the plugin instance
*/
getPlugin() {
return this.docpad.getPlugin(this.getConfig().pluginName)
}
/**
* Test creating DocPad instance with the plugin
* @returns {PluginTester} this
* @chainable
*/
testInit() {
// Prepare
const tester = this
const { DocPad, pluginPath, pluginName, PluginClass } = this.config
// Prepare plugin options
const pluginOpts = {
pluginPath,
pluginName,
PluginClass,
}
// Prepare docpad configuration
const docpadConfig = this.docpadConfig
docpadConfig.events = docpadConfig.events || {}
// Create Instance
this.suite('init', function (suite, test) {
// create docpad and load the plugin
test('create', function (done) {
// Prepare
docpadConfig.events.loadPlugins = function ({ plugins }) {
console.log('Adding the plugin with the configuration:', pluginOpts)
plugins.add(pluginOpts)
}
// Create
console.log('Creating DocPad with the configuration:', docpadConfig)
tester.docpad = new DocPad(docpadConfig, done)
})
// clean up the docpad out directory
test('clean', function (done) {
tester.docpad.action('clean', done)
})
// install anything on the website that needs to be installed
test('install', function (done) {
tester.docpad.action('install', done)
})
})
// Chain
return this
}
/**
* Test generation
* @returns {PluginTester} this
* @chainable
*/
testGenerate() {
// Prepare
const tester = this
const {
outExpectedPath,
removeWhitespace,
whitespace,
contentRemoveRegex,
} = this.config
const { outPath } = this.docpadConfig
// Test
this.suite('generate', function (suite, test) {
// action
test('action', function (done) {
tester.docpad.action('generate', function (err) {
return done(err)
})
})
suite('results', function (suite, test, done) {
safefs.exists(outExpectedPath, function (exists) {
if (!exists) {
console.warn(
`skipping results comparison, as outExpectedPath:[${outExpectedPath}] doesn't exist`
)
return done()
}
// Get actual results
balUtil.scanlist(outPath, function (err, outResults) {
if (err) return done(err)
// Get expected results
balUtil.scanlist(outExpectedPath, function (
err,
outExpectedResults
) {
if (err) return done(err)
// Prepare
const outResultsKeys = Object.keys(outResults)
const outExpectedResultsKeys = Object.keys(outExpectedResults)
// Check we have the same files
test('same files', function () {
const outDifferenceKeysA = difference(
outExpectedResultsKeys,
outResultsKeys
)
deepEqual(
outDifferenceKeysA,
[],
'The following file(s) should have been generated'
)
const outDifferenceKeysB = difference(
outResultsKeys,
outExpectedResultsKeys
)
deepEqual(
outDifferenceKeysB,
[],
'The following file(s) should not have been generated'
)
})
// Check the contents of those files match
outResultsKeys.forEach(function (key) {
test(`same file content for: ${key}`, function () {
// Fetch file value
let actual = outResults[key]
let expected = outExpectedResults[key]
let message = 'content comparison'
// Remove all whitespace
if (whitespace === 'remove' || removeWhitespace) {
message += ' with whitespace removed'
actual = actual.replace(removeWhitespaceRegex, '')
expected = expected.replace(removeWhitespaceRegex, '')
}
// Trim whitespace from the start and end of each line, and remove empty lines
else if (whitespace === 'trim') {
message += ' with whitespace trimmed'
actual = actual
.split('\n')
.map((i) => i.replace(trimRegex, ''))
.join('\n')
.replace(removeLineRegex, '\n')
.replace(trimRegex, '')
expected = expected
.split('\n')
.map((i) => i.replace(trimRegex, ''))
.join('\n')
.replace(removeLineRegex, '\n')
.replace(trimRegex, '')
}
// Content regex
if (contentRemoveRegex) {
message += ' with content regex applied'
actual = actual.replace(contentRemoveRegex, '')
expected = expected.replace(contentRemoveRegex, '')
}
// Compare
equal(actual, expected, message)
})
})
done() // complete suite results
}) // scanlist
}) // scanlist
}) // exists
}) // start suite results
}) // suite generate
// Chain
return this
}
/**
* Test custom
* @returns {PluginTester} this
* @chainable
*/
testCustom() {
return this
}
/**
* Test everything
* @returns {PluginTester} this
* @chainable
*/
test() {
const tester = this
const { testerName } = this.config
// Create the test suite for the plugin
kava.suite(testerName, function (suite, test) {
tester.suite = suite
tester.test = test
// ignore chaining in case custom extension forgot to chain
tester.testInit()
tester.testGenerate()
tester.testCustom()
tester.finish()
})
}
/**
* Finish
* @returns {PluginTester} this
* @chainable
*/
finish() {
const tester = this
const { autoExit } = this.config
if (autoExit) {
this.test('finish up', function (next) {
tester.docpad.action('destroy', next)
})
}
return this
}
/**
* Run the tester with the specific configuration
* @static
* @param {ExtendedTesterConfig} [testerConfig]
* @param {DocPadConfig} [docpadConfig]
* @returns {PluginTester} the created instance
*/
static test(testerConfig = {}, docpadConfig = {}) {
// Notify about testerPath deprecation
if (testerConfig.testerPath) {
throw new Error(
'The testerPath property has been removed in favour of the TesterClass property.\n' +
'The resolution may be as easy as replacing it with:\n' +
`TesterClass: require('./${testerConfig.testerPath}')\n` +
'For more details refer to: https://github.com/docpad/docpad-plugintester'
)
}
if (testerConfig.testerClass) {
console.warn(
'The testerClass property is no longer required, and will not be used.\n' +
'For more details refer to: https://github.com/docpad/docpad-plugintester'
)
delete testerConfig.testerClass
}
// Ensure and resolve pluginPath
testerConfig.pluginPath = pathUtil.resolve(
testerConfig.pluginPath || process.cwd()
)
// Ensure DocPad class
if (!testerConfig.DocPad) {
try {
// handle npm install cases
testerConfig.DocPad = require('docpad')
} catch (err) {
// handle npm link cases
testerConfig.DocPad = require(pathUtil.resolve(
testerConfig.pluginPath,
'node_modules',
'docpad'
))
}
}
// Ensure testerClass
const TesterClass = testerConfig.TesterClass || this
// Create our tester and run its tests
new TesterClass(testerConfig, docpadConfig).test()
// Return this, so that we can do .test().test().test()
return this
}
} |
JavaScript | class Console extends Helper {
/**
* Console constructor.
*
* @param fileSystemManager
* Expects the current file system.
*/
constructor(fileSystemManager) {
super(fileSystemManager);
}
/**
* Console debug wrapper.
*
* @param data
* Expects any data.
*/
log(...data) {
console.debug(data.join('\n'));
}
} |
JavaScript | class Queue {
constructor() {
this._head = this._tail = null;
this._length = 0; // ro
}
//----------------------------------------------------------------------------
// queue (push tail) an entry
queue(data) {
this._tail = new QueueEntry(data, this._tail);
this._head = this._head || this._tail;
++this._length;
}
//----------------------------------------------------------------------------
// dequeue (pop head) entry
dequeue() {
if (!this._head) {
return null;
}
--this._length;
var entry = this._head;
this._head = this._head.next;
entry.next = null;
return entry.data;
}
} |
JavaScript | class HandlerSet {
constructor() {
this.handler = new Set();
}
//------------------------------------------------------------------------------
// method add
add(handler) {
if (this.handler.has(handler)) {
return;
}
this.handler.add(handler);
}
//------------------------------------------------------------------------------
// method remove
remove(handler) {
this.handler.delete(handler);
}
//------------------------------------------------------------------------------
// method invoke
invoke(args) {
// The handler function is invoked with as many arguments as were passed to
// `send()` or `post()`, where the first argument (action) becomes the last
// for the call.
for (let handler of this.handler) {
let ret = handler(...args);
// remove the handler when explicitly false is returned
if (false === ret) {
this.handler.delete(handler);
}
}
};
} |
JavaScript | class HandlerMap {
constructor() {
this.handlerSets = new Map();
}
//------------------------------------------------------------------------------
// method add
add(handler, action) {
var handlerSet = this.handlerSets.get(action);
if (!handlerSet) {
handlerSet = new HandlerSet();
this.handlerSets.set(action, handlerSet);
}
handlerSet.add(handler);
}
//------------------------------------------------------------------------------
// method remove
remove(handler, action) {
var handlerSet = this.handlerSets.get(action);
if (handlerSet) {
handlerSet.remove(handler);
}
}
//------------------------------------------------------------------------------
// method dispatch
dispatch(args) {
var handlerSet = this.handlerSets.get(args[args.length-1]);
if (handlerSet) {
handlerSet.invoke(args);
}
}
} |
JavaScript | class Dispatcher {
constructor() {
var _privates = {
_strict: false,
_map: new HandlerMap(),
_messageQueue: new Queue(),
_actions: new Map()
};
// extend: for dispatcher extensions
this.extend = (name, fn) => {
if ('object' === typeof name) {
// name is object with functions
Object.keys(name).forEach(function(key) {
this.extend(key, name[key]);
}.bind(this));
}
else if (('function' === typeof name) && ('object' === typeof name.prototype)) {
// name is assumed to be a constructor
const pt = name.prototype;
name.call(_privates);
Object.keys(pt).forEach(function(key) {
this.extend(key, pt[key]);
}.bind(this));
}
else if (name && ('function' === typeof fn)) {
// standard case: name and function
this[name] = _privates[name] = fn.bind(_privates);
}
// ignore other values gracefully
return this;
}
// Own prototype first
this.extend(DispatcherImplementation);
// proxy - can be used by extensions
_privates._dispatch = (args) => {
_privates._map.dispatch(args);
};
// strictmode check
_privates._check = (action) => {
if (this._strict && !this.isRegistered(action)) {
throw new Error('Dispatcher: Action "' + action + '" not registered.');
}
};
// init loop
_privates._postpone = _createPostpone(_runQueue.bind(_privates));
}
} |
JavaScript | class Navbarz extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
/**
* Toggels the Navbar actions if if the screen can't hold all the actions next
* to each other
*/
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
/**
* If opens a new Inshape page on the default browser
*/
static handleInshapeClick() {
electron.shell.openExternal('https://inshape.shapeways.com/');
}
/**
* Renders the Navbar to the window. This includes the home button that will
* take the user back to the start screen, The refresh button and timer for
* refreshing the table's data, an external Inshape link, and
* manufacturer-process info
* @return {HTML} render of component
*/
render() {
const manufacturer = this.props.manufacturer;
const process = this.props.process;
const result = this.props.result;
const authorized = this.props.authorized;
const refreshButton = this.props.refresh;
const refreshTime = this.props.refreshTimer;
return (
<div>
<Navbar color="inverse" inverse toggleable>
<NavbarToggler right onClick={this.toggle} />
<NavbarBrand href="">Inshape Move Tool</NavbarBrand>
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
{process ? (
<NavItem>
<NavLink onClick={refreshButton}>Refresh({refreshTime})</NavLink>
</NavItem>
) : (
<NavLink></NavLink>
)}
<NavItem>
<NavLink onClick={Navbarz.handleInshapeClick}>Inshape</NavLink>
</NavItem>
<NavItem>
{authorized ? (
<NavLink disabled >Authorized</NavLink>
) : (
<NavLink disabled >Unauthorized</NavLink>
)}
</NavItem>
<NavItem>
{process ? (
<NavLink disabled >
Manufacturer: {manufacturer} - {process.display_name}
</NavLink>
) : (
<NavLink></NavLink>
)}
</NavItem>
</Nav>
</Collapse>
</Navbar>
<MoveAlert result={result} />
</div>
);
}
} |
JavaScript | class TimeSpan {
constructor(millionseconds, isPositive = false) {
this.totalMillionseconds = millionseconds;
this.totalSeconds = millionseconds / 1000;
this.totalMinutes = this.totalSeconds / 60;
this.totalHours = this.totalMinutes / 60;
this.totalDays = this.totalHours / 24;
this.day = Math.floor(millionseconds / (1000 * 60 * 60 * 24));
let surplus = millionseconds % (1000 * 60 * 60 * 24);
this.hour = surplus / (1000 * 60 * 60);
surplus = surplus % (1000 * 60 * 60);
this.minute = surplus / (1000 * 60);
surplus = surplus % (1000 * 60);
this.second = surplus / (1000);
surplus = surplus % (1000);
this.millionsecond = surplus;
this.isPositive = isPositive;
}
} |
JavaScript | class Aqua {
/**
* judge an object is a JSON object or not
* 判断一个对象是否是Json对象
* @param {any} obj
* @returns {bool}
*/
isJson(obj) {
return typeof (obj) === "object" &&
Object.prototype.toString.call(obj).toLowerCase() === "[object object]" &&
!obj.length;
}
/**
* add or subtract some time to a Date object
* 在一个日期上加减时间
* @param {Date} date 日期对象
* @param {number} diff 差值(毫秒)
* @returns {Data} 作差之后的日期对象
*/
diffDate(date, diff) {
return new Date(date.getTime() + diff);
}
/**
* format a Date object
* 将 Date 转化为指定格式的String
* @param {Date} date 源日期对象
* @param {string} pattern 匹配模式
* @returns {string} 格式化结果
*/
fmtDate(date, pattern) {
return pattern
.replace(/yyyy/, date.getFullYear().toString())
.replace(/MM/, this.fillZero(date.getMonth() + 1, 'l', 2))
.replace(/dd/, this.fillZero(date.getDate(), 'l', 2))
.replace(/hh/, this.fillZero(date.getHours(), 'l', 2))
.replace(/mm/, this.fillZero(date.getMinutes(), 'l', 2))
.replace(/ss/, this.fillZero(date.getSeconds(), 'l', 2))
.replace(/S/, date.getMilliseconds().toString());
}
/**
* compare to two date ,caculate the difference
* 对比两个日期,计算他们的差值
* @param {Date} date1
* @param {Date} date2
* @returns {TimeSpan}
*/
compareDate(date1, date2) {
let number1 = date1.getTime();
let number2 = date2.getTime();
let isPositive = number2 > number1;
number1 = Math.abs(number1);
number2 = Math.abs(number2);
let res = new TimeSpan(Math.abs(number2 - number1));
res.isPositive = isPositive;
return res;
}
/**
* fill 0 to a number
* 数字补零
* @param {number} src 源数字
* @param {string} direction 方向 l r
* @param {number} digit 补零后的总位数
* @returns {string} 结果
*/
fillZero(src, direction, digit) {
let count = digit - src.toString().length;
let os = new Array(count + 1).join('0');
if (direction !== 'r') {
return os + src;
}
return src + os;
}
/**
*
*
* @param {string} src
* @param {number} [or=0]
* @returns
*
* @memberOf Aqua
*/
intOr(src, or = 0) {
let res = Number.parseInt(src);
return Number.isNaN(res) ? or : res;
}
} |
JavaScript | class Exchange {
/**
* ctor
* @param credentials
*/
constructor(credentials) {
this.name = 'none';
this.credentials = credentials;
this.refCount = 1;
this.minOrderSize = 0.002;
this.minPollingDelay = 5;
this.maxPollingDelay = 60;
this.sessionOrders = [];
this.algorithicOrders = [];
this.api = null;
this.support = {
scaledOrderSize,
ticker,
accountBalances,
};
this.commands = {
// Algorithmic Orders
icebergOrder,
scaledOrder,
twapOrder,
pingPongOrder,
steppedMarketOrder: twapOrder, // duplicate using legacy name
accDisOrder: icebergOrder, // duplicate for common names
// Regular orders
limitOrder,
marketOrder,
stopMarketOrder,
// Other commands
cancelOrders,
wait,
notify,
balance,
};
this.commandWhiteList = [
'icebergOrder', 'scaledOrder', 'twapOrder', 'pingPongOrder',
'steppedMarketOrder', 'accDisOrder',
'limitOrder', 'marketOrder', 'stopMarketOrder',
'cancelOrders', 'wait', 'notify', 'balance'];
}
/**
* Adds a reference
*/
addReference() {
this.refCount += 1;
}
/**
* Removes a reference
*/
removeReference() {
this.refCount -= 1;
return this.refCount;
}
/**
* Determine if this exchange is a match of the details given
* @param name
* @param credentials
* @returns {boolean}
*/
matches(name, credentials) {
if (name !== this.name) return false;
return JSON.stringify(credentials) === JSON.stringify(this.credentials);
}
/**
* Called after the exchange has been created, but before it has been used.
*/
init() {
// nothing
}
/**
* Called before the exchange is destroyed
*/
terminate() {
// chance for any last minute shutdown stuff
}
/**
* Adds the order to the session
* @param session
* @param tag
* @param order
*/
addToSession(session, tag, order) {
this.sessionOrders.push({
session,
tag,
order,
});
}
/**
* Given a session id and tag, find everything that matches
* @param session
* @param tag
* @returns {*[]}
*/
findInSession(session, tag) {
return this.sessionOrders
.filter(entry => entry.session === session && (tag === null || entry.tag === tag))
.map(entry => entry.order);
}
/**
* Register an algorithmic order
* @param id
* @param side
* @param session
* @param tag
*/
startAlgoOrder(id, side, session, tag) {
this.algorithicOrders.push({ id, side, session, tag, cancelled: false });
}
/**
* Remove an order from the list
* @param id
*/
endAlgoOrder(id) {
this.algorithicOrders = this.algorithicOrders.filter(item => item.id !== id);
}
/**
* Determine if an algorithmic order has been cancelled or not
* @param id
* @returns {boolean|*}
*/
isAlgoOrderCancelled(id) {
const order = this.algorithicOrders.find(item => item.id === id);
return order.cancelled;
}
/**
* Ask some of the algorithmic orders to cancel
* @param which
* @param tag
* @param session
*/
cancelAlgorithmicOrders(which, tag, session) {
this.algorithicOrders = this.algorithicOrders.map((item) => {
const all = which === 'all';
const buy = which === 'buy' && item.side === which;
const sell = which === 'sell' && item.side === which;
const tagged = which === 'tagged' && item.tag === tag;
const cancelSession = which === 'session' && item.session === session;
if (all || buy || sell || tagged || cancelSession) {
item.cancelled = true;
}
return item;
});
}
/**
* Converts a time string (12, 12s, 12h, 12m) to an int number of seconds
* @param time
* @param defValue
* @returns {number}
*/
timeToSeconds(time, defValue = 10) {
const regex = /([0-9]+)(d|h|m|s)?/;
const m = regex.exec(time);
if (m !== null) {
const delay = parseInt(m[1], 10);
switch (m[2]) {
case 'm':
return delay * 60;
case 'h':
return delay * 60 * 60;
case 'd':
return delay * 60 * 60 * 24;
default:
return delay;
}
}
return defValue;
}
/**
* Look for valid units of quantity...
* 12, 12btc, 12usd, 12% (% of total funds) or 12%% (% of available funds)
* @param qty
* @returns {*}
*/
parseQuantity(qty) {
const regex = /^([0-9]+(\.[0-9]+)?)\s*([a-zA-Z]+|%{1,2})?$/;
const m = regex.exec(qty);
if (m) {
return { value: parseFloat(m[1]), units: m[3] === undefined ? '' : m[3] };
}
// Does not look like a valid quantity, so treat it as zero, as that is safest
return { value: 0, units: '' };
}
/**
* Treat a number as a number or percentage. (0.01 or 1% both return 0.01)
* @param value
* @returns {number}
*/
parsePercentage(value) {
const regex = /^([0-9]+(\.[0-9]+)?)\s*(%{1,2})?$/;
const m = regex.exec(value);
if (m) {
return parseFloat(m[1]) * (m[3] === '%' ? 0.01 : 1);
}
// Does not look like a valid quantity, so treat it as zero, as that is safest
return 0;
}
/**
* Support for named params
* @param expected - map of expected values, with default {name: default}
* @param named - the input argument list
* @returns map of the arguments { name: value }
*/
assignParams(expected, named) {
const result = {};
Object.keys(expected).forEach((item, i) => {
result[item] = named.reduce((best, p) => {
if ((p.name.toLowerCase() === item.toLowerCase()) || (p.name === '' && p.index === i)) {
return p.value;
}
return best;
}, expected[item]);
});
return result;
}
/**
* Execute a command on an exchange.
* symbol - the symbol we are trading on
* name - name of the command to execute
* params - an array of arguments to pass the command
*/
executeCommand(symbol, name, params, session) {
// Look up the command, ignoring case
const toExecute = this.commandWhiteList.find(el => (el.toLowerCase() === name.toLowerCase()));
if ((!toExecute) || (typeof this.commands[toExecute] !== 'function')) {
logger.error(`Unknown command: ${name}`);
return Promise.reject('unknown command');
}
// Call the function
return this.commands[toExecute]({ ex: this, symbol, session }, params);
}
/**
* Given a symbol (like BTCUSD), figure out the pair (btc & usd)
* @param symbol
* @returns {*}
*/
splitSymbol(symbol) {
const regex = /^(.{3,4})(.{3})/u;
const m = regex.exec(symbol.toLowerCase());
if (m) {
return { asset: m[1], currency: m[2] };
}
// Default to btc / usd - not sure about this...
// should really just throw an error
return { asset: 'btc', currency: 'usd' };
}
/**
* Works out the current value of the portfolio by looking
* at the amount of BTC and USD, and using the current price
* Returns the value, in BTC
* @param symbol
* @param balances
* @param price
*/
balanceTotalAsset(symbol, balances, price) {
// Work out the total value of the portfolio
const asset = this.splitSymbol(symbol);
const total = balances.reduce((t, item) => {
if (item.currency === asset.currency) {
return t + (parseFloat(item.amount) / price);
} else if (item.currency === asset.asset) {
return t + parseFloat(item.amount);
}
return t;
}, 0);
const roundedTotal = util.roundDown(total, 4);
logger.results(`Total @ ${price}: ${roundedTotal} ${asset.asset}`);
return roundedTotal;
}
/**
* Get the balance total in the fiat currency
* @param symbol
* @param balances
* @param price
* @returns {*}
*/
balanceTotalFiat(symbol, balances, price) {
// Work out the total value of the portfolio
const asset = this.splitSymbol(symbol);
const total = balances.reduce((t, item) => {
if (item.currency === asset.currency) {
return t + parseFloat(item.amount);
} else if (item.currency === asset.asset) {
return t + (parseFloat(item.amount) * price);
}
return t;
}, 0);
const roundedTotal = util.roundDown(total, 4);
logger.results(`Total @ ${price}: ${roundedTotal} ${asset.currency}`);
return roundedTotal;
}
/**
* Returns the available balance of the account, in BTC
* This is the amount of the account that can actually be traded.
* If it is less that the total amount, some of the value will be
* locked up in orders, or is on the wrong side of the account
* (eg, if you want to buy BTC, then only the available USD will
* be taken into account).
* @param symbol - eg BTCUSD
* @param balances
* @param price
* @param side
*/
balanceAvailableAsset(symbol, balances, price, side) {
const asset = this.splitSymbol(symbol);
const spendable = balances.reduce((total, item) => {
if (side === 'buy') {
// looking to buy BTC, so need to know USD available
if (item.currency === asset.currency) {
return total + (parseFloat(item.available) / price);
}
} else if (item.currency === asset.asset) {
return total + parseFloat(item.available);
}
return total;
}, 0);
const roundedTotal = util.roundDown(spendable, 4);
logger.results(`Asset balance @ ${price}: ${roundedTotal}`);
return roundedTotal;
}
/**
* Calculate the size of the order, taking into account available balance
* @param symbol
* @param side
* @param amount - an amount as a number of coins or % of total worth
* @param balances
* @param price
* @returns {{total: *, available: *, isAllAvailable: boolean, orderSize: *}}
*/
calcOrderSize(symbol, side, amount, balances, price) {
const asset = this.splitSymbol(symbol);
const total = this.balanceTotalAsset(symbol, balances, price);
const available = this.balanceAvailableAsset(symbol, balances, price, side);
// calculate the order size (% or absolute, within limits, rounded)
let orderSize = amount.value;
if (amount.units === '%') orderSize = total * (amount.value / 100);
if (amount.units === '%%') orderSize = available * (amount.value / 100);
if (amount.units.toLowerCase() === asset.currency) orderSize = amount.value / price;
// make sure it's no more than what we have available.
orderSize = orderSize > available ? available : orderSize;
// Prevent silly small orders
if (orderSize < this.minOrderSize) {
orderSize = 0;
}
return {
total,
available,
isAllAvailable: (orderSize === available),
orderSize: util.roundDown(orderSize, 4),
};
}
/**
* Figure out the absolute price to trade at, given an offset from the current price
* @param symbol
* @param side
* @param offsetStr
* @returns {Promise<any>}
*/
async offsetToAbsolutePrice(symbol, side, offsetStr) {
// Look for an absolute price (eg @6250.23)
const regex = /@([0-9]+(\.[0-9]*)?)/;
const m = regex.exec(offsetStr);
if (m) {
return Promise.resolve(util.roundDown(parseFloat(m[1]), 4));
}
// must be a regular offset or % offset, so we'll need to know the current price
const orderbook = await this.support.ticker({ ex: this, symbol });
const offset = this.parseQuantity(offsetStr);
if (side === 'buy') {
const currentPrice = parseFloat(orderbook.bid);
const finalOffset = offset.units === '%' ? currentPrice * (offset.value / 100) : offset.value;
return util.roundDown(currentPrice - finalOffset, 2);
}
const currentPrice = parseFloat(orderbook.ask);
const finalOffset = offset.units === '%' ? currentPrice * (offset.value / 100) : offset.value;
return util.roundDown(currentPrice + finalOffset, 2);
}
/**
* Find the order size from the amount
* @param symbol
* @param side
* @param orderPrice
* @param amountStr
* @returns {Promise<{total: *, available: *, isAllAvailable: boolean, orderSize: *}>}
*/
async orderSizeFromAmount(symbol, side, orderPrice, amountStr) {
const balances = await this.support.accountBalances({ ex: this, symbol });
const amount = this.parseQuantity(amountStr);
// Finally, work out the size of the order
return this.calcOrderSize(symbol, side, amount, balances, orderPrice);
}
/**
* Converts a target position size to an amount to trade
* Default behaviour here is just to use the amount. Leveraged exchanges
* might work out the diff needed to get to the target position and use that instead.
* @param symbol
* @param position - positive for long positions, negative for short positions
* @param side
* @param amount
* @returns {*}
*/
async positionToAmount(symbol, position, side, amount) {
// First see if we work using a target position, or a fixed amount
if (position === '') {
// use the amount as an absolute change (units not support here)
return Promise.resolve({ side, amount: this.parseQuantity(amount) });
}
// They asked for a position, instead of a side / amount compbo,
// so work out the side and amount
const balances = await this.support.accountBalances({ ex: this, symbol });
// Add up all the coins on the asset side
const asset = this.splitSymbol(symbol);
const total = balances.reduce((t, item) => {
if (item.currency === asset.asset) {
return t + parseFloat(item.amount);
}
return t;
}, 0);
// We want `position`, but have `total`
const target = parseFloat(position);
const change = util.roundDown(target - total, 4);
return { side: change < 0 ? 'sell' : 'buy', amount: { value: Math.abs(change), units: '' } };
}
/**
* Just wait for a file, with no output
* @param delay
* @returns {Promise<any>}
*/
waitSeconds(delay) {
return new Promise((resolve) => {
setTimeout(() => resolve({}), delay * 1000);
});
}
} |
JavaScript | class StatsDigest {
constructor() {
this.n = null;
this.range = new NRange();
this.mean = null;
this.m2 = null;
this.reset();
}
reset() {
this.n = 0;
this.range.reset();
this.mean = 0.0;
this.m2 = 0.0;
}
add(x) {
this.n += 1;
const delta = x - this.mean;
this.mean += delta / this.n;
const delta2 = x - this.mean;
this.m2 += delta * delta2;
this.range.add(x);
}
variance() {
return this.n > 2 ? this.m2 / (this.n - 1) : 0.0;
}
} |
JavaScript | class BaseService extends EventEmitter {
constructor (options = {}, defaultOptions = {}) {
super()
this.options = Object.assign({}, defaultOptions, options)
this.app = options.app
this.started = false
}
/**
* Convenience method for accessing debug loggers.
* @return {Object} An object that houses loggers.
*/
get loggers () {
return this.app.loggers
}
/**
* Returns a default logger based on the service's name.
* @return {Logger} A logger instance.
*/
get logger () {
return this.loggers[`service:${this.name}`]
}
/**
* Returns a debug logger based on the service's name.
* @return {Logger} A logger instance.
*/
get debug () {
return this.loggers[`debug:service:${this.name}`]
}
/**
* Convenience method for getting available services.
*/
get services () {
return new Proxy(this.app.services, {
get: (obj, prop) => {
// Block services from trying to access inactive services.
if (!obj[prop].started) {
throw new Error(`Service not started: ${prop}`)
}
return obj[prop]
}
})
}
/**
* Returns the name of this service.
* @return {string} Name of the service.
*/
get name () {
throw new Error(
'Classes that extend BaseService must implement this method'
)
}
/**
* List of services this service depends on, identified by name.
* @return {Array<string>} List of dependencies.
*/
get dependencies () {
return []
}
/**
* Checks whether the service and all of its dependencies are started.
* @return {boolean} `true` if all started, `false` otherwise.
*/
get healthy () {
return (
this.started &&
this.dependencies.every((dependency) => {
return this.app.services[dependency].started
})
)
}
/**
* Starts the service.
*/
async start () {
this.started = true
await this._onStart()
}
/**
* Called once the service has been started.
*/
async _onStart () {
return true
}
/**
* Stops the service.
*/
async stop () {
this.started = false
await this._onStop()
}
/**
* Called once the service has been stopped.
*/
async _onStop () {
return true
}
} |
JavaScript | class App extends Component {
constructor(props){
super(props);
this.state = {videos: []};
YTSearch({key: API_KEY, term: 'bollywood'}, (videos) => {
this.setState({videos: videos});
});
}
render() {
return(
<div>
<SearchBar />
</div>
)
}
} |
JavaScript | class ImageToImageFilter extends Filter {
constructor(){
super();
}
/**
* Check if all input image have the same size.
* @return {Boolean} true is same size, false if not.
*/
hasSameSizeInput(){
var that = this;
var inputCategories = Object.keys( this._input );
var sameSize = true;
var widths = [];
var heights = [];
inputCategories.forEach( function(key){
widths.push( that._getInput( key ).getWidth() );
heights.push( that._getInput( key ).getHeight() );
});
// if all input have the same size
if(widths.length){
widths.sort();
heights.sort();
sameSize = (widths[ 0 ] == widths[ widths.length -1 ] ) &&
(heights[ 0 ] == heights[ heights.length -1 ] );
if( !sameSize ){
console.warn("Input image do not all have the same size. Filter not valid");
}
}
return sameSize;
}
/**
* Check if all the inputs have the same number of component per pixel.
* @return {Boolean} true if the ncpp are the same for all input image
*/
hasSameNcppInput(){
var inputCategories = Object.keys( this._input );
// if no input, return false
if(!inputCategories.length)
return false;
var ncpp = this._getInput( inputCategories[0] ).getComponentsPerPixel();
for(var i=0; i<inputCategories.length; i++){
if( ncpp != this._getInput( inputCategories[i] ).getComponentsPerPixel()){
console.warn("Input image do not all have the same number of components per pixel. Filter not valid");
return false;
}
}
return true;
}
} /* END class ImageToImageFilter */ |
JavaScript | class AudioPlugin extends AbstractPlugin {
/**
* Constructor.
*/
constructor() {
super();
this.id = 'audio';
}
/**
* @inheritDoc
*/
init() {
// register the audio import UI
const im = ImportManager.getInstance();
im.registerImportDetails('Audio files for application sounds.');
im.registerImportUI(TYPE, new AudioImportUI());
}
} |
JavaScript | class CardCover extends React.Component {
render() {
const _this$props = this.props,
{
index,
total,
style,
theme
} = _this$props,
rest = _objectWithoutProperties(_this$props, ["index", "total", "style", "theme"]);
const {
roundness
} = theme;
let coverStyle;
if (index === 0) {
if (total === 1) {
coverStyle = {
borderRadius: roundness
};
} else {
coverStyle = {
borderTopLeftRadius: roundness,
borderTopRightRadius: roundness
};
}
} else if (typeof total === 'number' && index === total - 1) {
coverStyle = {
borderBottomLeftRadius: roundness
};
}
return /*#__PURE__*/React.createElement(View, {
style: [styles.container, coverStyle, style]
}, /*#__PURE__*/React.createElement(Image, _extends({}, rest, {
style: [styles.image, coverStyle]
})));
}
} |
JavaScript | class ThreeTextureLoader extends Loader {
constructor(asset) {
super();
this.asset = asset;
this.isCube = asset.type === Loader.threeCubeTexture ? true : false;
}
load = () => {
const loader = this.isCube ? new CubeTextureLoader() : new TextureLoader();
const onLoaded = texture => {
this.asset.data = texture;
this.emit('loaded', this.asset);
};
/**
*
*
* @returns
*/
function onProgress() {
return;
}
const onError = () => {
this.emit('error', `Failed to load ${this.asset.src}`);
};
if (this.isCube) {
loader.setPath(this.asset.args.path);
loader.load(this.asset.src, onLoaded, onProgress, onError);
} else {
loader.load(this.asset.src, onLoaded, onProgress, onError);
}
};
} |
JavaScript | class OrderSearchRequest {
/**
* Constructs a new <code>OrderSearchRequest</code>.
* Document representing an order search request.
* @alias module:models/OrderSearchRequest
* @class
* @param query {module:models/Query} The query to apply
*/
constructor(query) {
this.query = query
}
/**
* Constructs a <code>OrderSearchRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:models/OrderSearchRequest} obj Optional instance to populate.
* @return {module:models/OrderSearchRequest} The populated <code>OrderSearchRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new OrderSearchRequest()
if (data.hasOwnProperty('count')) {
obj.count = ApiClient.convertToType(data.count, 'Number')
}
if (data.hasOwnProperty('db_start_record_')) {
obj.db_start_record_ = ApiClient.convertToType(data.db_start_record_, 'Number')
}
if (data.hasOwnProperty('expand')) {
obj.expand = ApiClient.convertToType(data.expand, ['String'])
}
if (data.hasOwnProperty('query')) {
obj.query = Query.constructFromObject(data.query)
}
if (data.hasOwnProperty('select')) {
obj.select = ApiClient.convertToType(data.select, 'String')
}
if (data.hasOwnProperty('sorts')) {
obj.sorts = ApiClient.convertToType(data.sorts, [Sort])
}
if (data.hasOwnProperty('start')) {
obj.start = ApiClient.convertToType(data.start, 'Number')
}
}
return obj
}
/**
* The number of returned documents
* @member {Number} count
*/
count = undefined;
/**
* The zero-based index of the record that we want to start with, used to optimize special handling
* @member {Number} db_start_record_
*/
db_start_record_ = undefined;
/**
* List of expansions to be applied to each search results. Expands are optional
* @member {Array.<String>} expand
*/
expand = undefined;
/**
* The query to apply
* @member {module:models/Query} query
*/
query = undefined;
/**
* The field to be selected.
* @member {String} select
*/
select = undefined;
/**
* The list of sort clauses configured for the search request. Sort clauses are optional.
* @member {Array.<module:models/Sort>} sorts
*/
sorts = undefined;
/**
* The zero-based index of the first search hit to include in the result.
* @member {Number} start
*/
start = undefined;
} |
JavaScript | class Media extends Application {
constructor(element, options = {}) {
super(options);
// 在 htmlElement 容器的第一个子节点上创建 canvas
document.getElementById(element).appendChild(this.view);
this.view.id = 'Media'; // 设置 canvas ID
const { forceRotation } = Store.getState().Renderer;
// 保存原始设备尺寸
// 初始尺寸,由 new 传入
if (
forceRotation &&
(window.orientation === 0 || window.orientation === 180)
) {
Store.dispatch(
updateInitDevice({
width: this._options.height,
height: this._options.width
})
);
} else {
Store.dispatch(
updateInitDevice({
width: this._options.width,
height: this._options.height
})
);
}
// 监听 resize
window.addEventListener('resize', this.resizeHandler.bind(this));
this.resizeHandler();
}
/**
* 保存原始画布尺寸
* 紧跟 new Game 后调用
* 构造函数中加入横屏控制后,已废弃
* @return {null}
*/
updateInitDevice() {
// 初始尺寸,由 new 传入
const { width, height } = this._options;
Store.dispatch(
updateInitDevice({
width: width,
height: height
})
);
}
resizeHandler() {
// 渲染器resize成新的尺寸
this.renderer.resize(window.innerWidth, window.innerHeight);
// 更新状态,设备最新的尺寸 newDeviceWidth newDeviceHeight
Store.dispatch(resize());
}
} |
JavaScript | class Pricing extends React.Component {
constructor(props) {
super(props);
this.state = { pricing: 'monthly' };
}
selectionChanged = (e) => {
this.setState({
pricing: e.currentTarget.value,
});
}
render() {
// get the properties
const { pricing } = this.props;
// return the component html
return (
<>
<div className="is-pricing is-feature-wave">
<div className="hero-body mb-20">
<div className="container">
<div className="columns is-vcentered">
<div className="column is-6 is-offset-3 is-hero-title has-text-centered">
<h1 className="title is-1 is-medium is-spaced">
{pricing.heading}
</h1>
<h2 className="subtitle is-4">
{pricing.description}
</h2>
</div>
</div>
</div>
</div>
</div>
<div className="section section-secondary" style={{top: '-1px'}}>
<div className="container">
{/* <!-- Pricing wrapper --> */}
<div className="switch-pricing-wrapper">
<div className="pricing-container">
{/* <!-- Pricing Switcher --> */}
<div className="pricing-switcher">
<p className="fieldset">
<input type="radio" name="duration-1" id="monthly-1"
value='monthly' onChange={this.selectionChanged} checked={this.state.pricing === 'monthly'}
/>
<label htmlFor="monthly-1">Monthly</label>
<input type="radio" name="duration-1" id="yearly-1"
value='yearly' onChange={this.selectionChanged} checked={this.state.pricing === 'yearly'}/>
<label htmlFor="yearly-1">Yearly</label>
<span className="switch"></span>
</p>
</div>
<div className="columns is-4 tables-wrap">
{
pricing.plans.map(price => (
<div key={price.plan} className="column">
<div className="flex-card">
{/* <!-- Pricing image --> */}
<div className="pricing-image-container">
{ (price.image && !price.image.childImageSharp && price.image.extension === 'svg') &&
<img src={price.image.publicURL} alt={price.plan} />
}
<div className={`plan-price is-monthly ${this.state.pricing === 'monthly' ? 'is-active' : ''}`}>
<span>{price.monthly_price}</span>
</div>
<div className={`plan-price is-yearly ${this.state.pricing === 'yearly' ? 'is-active' : ''}`}>
<span>{price.yearly_price}</span>
</div>
</div>
{/* <!-- Pricing plan name --> */}
<div className="plan-name has-text-centered">
<h3>{price.plan}</h3>
<p>{price.description}</p>
</div>
{/* <!-- Pricing plan features --> */}
<ul className="plan-features">
{price.items.map(item => (
<li key={item} className="">
{item}
</li>
))}
</ul>
{/* <!-- Pricing action --> */}
<div className="button-wrapper">
<a href="https://app.bluprnts.com" className="button secondary-btn is-fullwidth">Sign up</a>
{/* is-fullwidth raised is-bold btn-upper */}
</div>
</div>
</div>
))}
</div>
</div>
</div>
{/* <!-- Clients --> */}
{/* <div className="hero-foot pt-10 pb-10">
<div className="container">
<div className="tabs partner-tabs is-centered">
<ul>
<li><img className="partner-logo" src="assets/images/logos/custom/covenant.svg" alt="" /></li>
<li><img className="partner-logo" src="assets/images/logos/custom/infinite.svg" alt="" /></li>
<li><img className="partner-logo" src="assets/images/logos/custom/kromo.svg" alt="" /></li>
<li><img className="partner-logo" src="assets/images/logos/custom/grubspot.svg" alt="" /></li>
<li><img className="partner-logo" src="assets/images/logos/custom/systek.svg" alt="" /></li>
</ul>
</div>
</div>
</div> */}
{/* <!-- /Clients --> */}
</div>
</div>
</>
)
}
} |
JavaScript | class Mutable extends __1.AbstractResident {
constructor() {
super(...arguments);
this.$receivers = [];
}
init(c) {
c.flags = c.flags | flags_1.FLAG_BUFFERED;
return c;
}
/**
* select the next message in the mailbox using the provided case classes.
*
* If the message cannot be handled by any of them, it will be dropped.
*/
select(cases) {
this.$receivers.push(new function_1.CaseFunction(cases));
this.notify();
return this;
}
} |
JavaScript | class TrashCollectionAlertEventBuilder extends EventBuilder_1.EventBuilder {
constructor() {
super("AMAZON.TrashCollectionAlert.Activated");
this.alert = {};
}
setAlert(collectionDayOfWeek, ...garbageTypes) {
this.alert = {
collectionDayOfWeek,
garbageTypes,
};
return this;
}
getPayload() {
return { alert: this.alert };
}
} |
JavaScript | class Dnet {
// actionHandlers are the functions to be executed for the particular action from the server
_actionHandlers = [];
//isActive tells whether the dnet connection is active or not
isActive = false;
// url to connect to the websocket
url = "";
// onOpenHandler is called when the ws connection gets opened (The first action to fire)
_onOpenHandler = () => {
console.info(`Dnet: Successfully opened connection to ${this.url}`);
};
// onCloseHandler is called when the ws connection gets closed
_onCloseHandler = () => {
console.info("Dnet: dnet closed");
};
// onErrorHandler is called when there is an error in the connection
_onErrorHandler = (ev) => {
console.error(`Dnet: ${ev.data}`);
};
// initialize the connection
init(url = "") {
if (url === "") {
throw new Error("Dnet: url cannot be empty");
}
if (this.isActive) {
console.info("Dnet: connection is still active no need to reconnect");
return;
}
this.url = url;
this._conn = new WebSocket(this.url);
this._route();
}
// _route initializes the routing process
_route() {
router(this);
}
// onopen sets the onOpenHandler which is called when the ws is opened
onopen(handler = this.onOpenHandler) {
//validate the handler
if (typeof handler != "function") {
throw new Error("Dnet: handler must be of type function");
}
this._onOpenHandler = handler;
}
//onclose set the oonCloseHandler which is called when ws connection gets closed
onclose(handler = this.onCloseHandler) {
if (typeof handler != "function") {
throw new Error("Dnet: handler must be of type function");
}
this._onCloseHandler = handler;
}
//onclose set the oonCloseHandler which is called when ws connection gets closed
onerror(handler = this._onErrorHandler) {
if (typeof handler != "function") {
throw new Error("Dnet: handler must be of type function");
}
this._onCloseHandler = handler;
}
// On method adds the actionHandler to the actionHandlers slice
on(action = "", handler) {
if (action == "") {
console.error("Dnet: action cannot be empty ");
return;
}
//validate the handler
if (typeof handler != "function") {
console.error("Dnet: handler must be of type function with one argument");
return;
}
this._actionHandlers.push(new ActionHandler(action, handler));
}
// _asyncOn is and asynchronous version of the on() method
_asyncOn(action = "", handler) {
if (action == "") {
console.error("Dnet: action cannot be empty ");
return;
}
//validate the handler
if (typeof handler != "function") {
console.error("Dnet: handler must be of type function with one argument");
return;
}
this._actionHandlers.push(new ActionHandler(action, handler, true));
}
// fire emits an action that is propagated to the server
// and returns a promise which resolves on success and rejects on bad status code
fire(action = "", data, rec = "") {
if (action == "") {
console.error("Dnet: action cannot be empty ");
return;
}
// set the defualt data
if (!data) {
data = "";
}
// create the new message
const message = new Message(action, data, rec);
//covert message to json
const messageJSON = JSON.stringify(message);
// send the data to the server
this._conn.send(messageJSON);
// return the promise for synchronous programming
return new Promise((resolve, reject) => {
this._asyncOn(action, (res) => {
const { ok } = res;
//resolve if everyting is fine
if (ok) resolve(res);
else reject(res);
});
});
}
// resets dnet before actionHandlers are loaded again
// when root component is revisited again before ws connection get closed
refresh() {
const handlers = this._actionHandlers;
handlers.length = 0;
}
// router creates a subrouter
router(prefix) {
return new Subrouter(prefix, this);
}
} |
JavaScript | class RateLimiter {
constructor(interval, set_num) {
this.interval = interval;
this.set_num = set_num-1;
this.map = new Map();
}
// given id and timestamp check the bucket. If
// no bucket exists, create one.
check_limit(id, timestamp) {
const item = this.map.get(id);
if (item) {
if (timestamp > item.timestamp) {
item.timestamp = timestamp + this.interval;
item.num = this.set_num;
this.map.set(id, item);
return true;
} else if (item.num > 0) {
item.num -= 1;
return true;
} else {
return false;
}
} else {
this.map.set(id, {
timestamp: timestamp+this.interval,
num: this.set_num
})
// console.log({
// timestamp: timestamp+this.interval,
// num: this.set_num+1
// })
return true;
}
}
// clean cache. It will only clean records that are
// irrelevant.
clean_cache(timestamp) {
this.map.forEach((value, key) => {
if (timestamp > value.timestamp) {
this.map.delete(key);
}
})
}
} |
JavaScript | class Manager extends Employee {
constructor(name, id, email, officeNumber) {
super(name, id, email);
this.officeNumber = officeNumber;
}
getRole() {
return "Manager";
}
getOfficeNumber() {
return this.officeNumber;
}
} |
JavaScript | class Camion extends PointInteret {
/**
* Constructeur de la classe Camion.
* @param {number} p_longitude longitude de la position du camion.
* @param {number} p_latitude latitude de la position du camion.
* @param {number} p_no numéro du camion.
* @param {string} p_temps temps dans le camion.
* @param {string} p_statut statut du camion.
* @constructor
*/
constructor(p_longitude, p_latitude, p_no, p_temps, p_statut) {
super(p_longitude, p_latitude);
this.no = p_no;
this.temps = p_temps;
this.statut = p_statut;
this.marqueur = new MarqueurCamion(this.getCoordonnees(), this.no, this.statut);
}
/**
* Retourne le marqueur spécifique pour le camion.
* @returns {MarqueurCamion} Marqueur pour le camion.
*/
getMarqueur() {
return this.marqueur;
}
/**
* Permet d'obtenir le numéro du camion.
* @returns {number} Le numéro du camion.
*/
getNumero() {
return this.no;
}
/**
* Permet d'obtenir le statut du camion.
* @returns {string} Le statut du camion.
*/
getStatut() {
return this.statut;
}
/**
* Update le camion avec les informations d'un autre camion.
* @param {Camion} p_camion le camions avec les bonnes valeurs
* @returns {void}
*/
updateInformations(p_camion) {
this.longitude = p_camion.longitude;
this.latitude = p_camion.latitude;
this.temps = p_camion.temps;
this.statut = p_camion.statut;
}
} |
JavaScript | class BaseIcon extends AuroElement {
constructor() {
super();
this.onDark = false;
}
// function to define props used within the scope of this component
static get properties() {
return {
...super.properties,
onDark: {
type: Boolean,
reflect: true
},
/**
* @private
*/
svg: {
attribute: false,
reflect: true
}
};
}
static get styles() {
return css`
${styleCss}
`;
}
/**
* @private async function to fetch requested icon from npm CDN
* @param {string} category icon category
* @param {string} name icon name
* @returns {dom} DOM ready HTML to be appended
*/
async fetchIcon(category, name) {
let iconHTML = '';
if (category === 'logos') {
iconHTML = await cacheFetch(`${this.uri}/${category}/${name}.svg`);
} else {
iconHTML = await cacheFetch(`${this.uri}/icons/${category}/${name}.svg`);
}
const dom = new DOMParser().parseFromString(iconHTML, 'text/html');
return dom.body.querySelector('svg');
}
// lifecycle function
async firstUpdated() {
const svg = await this.fetchIcon(this.category, this.name);
if (svg) {
this.svg = svg;
} else if (!svg) {
const penDOM = new DOMParser().parseFromString(penguin.svg, 'text/html');
this.svg = penDOM.body.firstChild;
}
}
} |
JavaScript | class Product extends Component {
/**
* Initializing State variable and binding functions
*/
constructor(props) {
super(props);
/**
* Contains product data and cart data that is to displayed on product page
*
* @var {array}
*/
this.state = {
soapData: [
{
id: "0",
soapPrice: "$10.99",
soapImgUrl: WineSoap,
soapName: "Wine Soap with golden goodness",
SoapDes:
"With its Anti-oxidant property, wine soap helps in anti-aging and firmness of the skin.",
},
{
id: "1",
soapPrice: "$12.99",
soapImgUrl: ClaySoap,
soapName: "Clay soap",
SoapDes:
"with goodness of ash clay, this soap contains skin softening benefits",
},
{
id: "2",
soapPrice: "$10.99",
soapImgUrl: CinaSoap,
soapName: "Cinnamon roll soaps with coffee exfoliation",
SoapDes: "A little coffee, a lot cinnamon frangrance for your skin",
},
{
id: "3",
soapPrice: "$15.99",
soapImgUrl: CoffTeaSoap,
soapName: "Coffee and Tea exfoliation bar",
SoapDes:
"Wake your skin very morning with tea and coffee exfoliation bar",
},
{
id: "4",
soapPrice: "$12.99",
soapImgUrl: OceanSoap,
soapName: "OceanSoap",
SoapDes: "Feel refreshed with methonal, its like a ocean in a bar",
},
{
id: "5",
soapPrice: "$9.99",
soapImgUrl: MacronSoap,
soapName: "Macron Soaps",
SoapDes:
"with vanilla fragrance, these tiny hand soaps make the perfect gift",
},
{
id: "6",
soapPrice: "$13.99",
soapImgUrl: WaterMelonSoap,
soapName: "Watermelon Soaps",
SoapDes:
"Not just look like watermelon, but smells the same and exfolites with watermelon seeds",
},
{
id: "7",
soapPrice: "$14.99",
soapImgUrl: HoneylemonSoap,
soapName: "Honey Lemon Soap",
SoapDes: "A set of honey and lemon soap to keep your skin hydrated",
},
{
id: "8",
soapPrice: "$10.99",
soapImgUrl: RainbowSoap,
soapName: "Oat milk Rainbow Soap",
SoapDes: "Soap made with oat milk, treat to your skin and eye",
},
{
id: "9",
soapPrice: "$11.99",
soapImgUrl: LavenderSoap,
soapName: "Lavender Swirl soap",
SoapDes: "with goodness of lavender, to calm your skin",
},
{
id: "10",
soapPrice: "$13.99",
soapImgUrl: GradientSoap,
soapName: "Gradient Soaps",
SoapDes: "Gifting soaps made with goat milk and glycerin",
},
{
id: "11",
soapPrice: "$54.99",
soapImgUrl: BtsSoap,
soapName: "BTS Themed Soaps",
SoapDes: "For the BTS fan in you, BTS themed curated soaps",
},
],
cartData: [],
isOpen: false,
sObj: {},
};
//binding all methods
this.addItemToCart = this.addItemToCart.bind(this);
this.togglePopup = this.togglePopup.bind(this);
this.handleChange = this.handleChange.bind(this);
this.calculateCost = this.calculateCost.bind(this);
this.buyNow = this.buyNow.bind(this);
}
/**
* opens the cart popup on click
*
* @return {void}
*/
togglePopup() {
this.setState({
isOpen: !this.state.isOpen,
});
}
/**
* Handles adding items to cart when clicked on "Add to cart button"
*/
addItemToCart(val) {
let arr = [...this.state.cartData, this.state.soapData[val]];
this.setState({
cartData: arr,
});
console.log("my cart is", arr);
}
/**
* Stores values when user selects color and shape from customize option
*/
handleChange(e, key) {
this.setState({
sObj: {
...this.state.sObj,
[key]: e.target.value,
},
});
}
/**
* converting hexadecimal color value to RGB value
*
* @param {object} hex [Hexadecimal value]
*
* @return {object} [returns an array of object]
*/
hexToRgb(hex) {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? [
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16),
]
: [];
}
/**
* Caluculated the cost of the object in the customiable section
*
* @param {object} sobj [Object array containing color and shape value]
*
* @return {object} [returns the cost value]
*/
calculateCost(sobj) {
if (Object.keys(sobj).length > 0) {
let rgbObj = [];
rgbObj = this.hexToRgb(sobj?.sColor || "");
console.log("rgbobj", rgbObj);
let colorSum = 0;
(rgbObj || []).forEach((elem) => {
colorSum += elem;
});
let priceFromShape = 0;
let shapPriceObj = {
square: 4.99,
rectangle: 6.99,
circle: 5.99,
"": 0,
};
console.log("sobj", sobj);
priceFromShape = shapPriceObj[sobj?.sShapes || ""];
console.log("shap price", priceFromShape);
return `$${priceFromShape + Math.round(colorSum / 100)}`;
}
}
/**
* Shows an alert when user clicks on Buy now
*/
buyNow() {
alert("Thank you for shopping with us");
}
render() {
return (
<React.Fragment>
<button className="cart-button" onClick={() => this.togglePopup()}>
Cart
</button>
{this.state.isOpen && (
<Popup
content={
<>
{this.state.cartData.length > 0 ? (
this.state.cartData.map((e) => {
return <Cartitems cartObj={e} />;
})
) : (
<h1 className="empty-cart">
The cart is empty, please shop with us
</h1>
)}
</>
}
handleClose={() => this.togglePopup()}
/>
)}
<div className="customize">
<form>
<h3>Customize with us:</h3>
<h5>
Let us know your color and shape choice for our Shea butter Soaps
</h5>
<br />
<label>Please pick a color:</label>
<input
type="color"
name="sColor"
value={this.state.sColor}
onChange={(e) => this.handleChange(e, "sColor")}
/>
<br />
<label>Please pick a Shape:</label>
<select
name="shapes"
id="shapes"
value={this.state.sShapes}
onChange={(e) => this.handleChange(e, "sShapes")}
>
<option value="">Please Select an option</option>
<option value="circle">circle</option>
<option value="rectangle">Rectangle</option>
<option value="square">square</option>
</select>
<br />
<label>Your Cost will be: </label>
<label>{this.calculateCost(this.state.sObj)}</label>
<div className="soap-cart-btn">
<button className="soap-cart-text" onClick={this.buyNow}>
Buy now
</button>
</div>
</form>
</div>
<div>
{this.state.soapData.map((e) => {
return (
<ProductIndividual
soapObj={e}
addItemToCart={this.addItemToCart}
/>
);
})}
</div>
</React.Fragment>
);
}
} |
JavaScript | class TokenCompanyUser extends ModelBase {
/**
* Constructor
*
* @augments ModelBase
*
* @constructor
*/
constructor() {
super({ dbName: dbName });
const oThis = this;
oThis.tableName = 'token_company_users';
}
/**
* This method inserts an entry in the table.
*
* @param {Object} params
* @param {String} params.tokenId
* @param {String} params.userUuid
*
* @returns {*}
*/
async insertRecord(params) {
const oThis = this;
// Perform validations.
if (!params.hasOwnProperty('tokenId') || !params.hasOwnProperty('userUuid')) {
throw 'Mandatory parameters are missing. Expected an object with the following keys: {tokenId, userUuid}';
}
let insertResponse = await oThis
.insert({
token_id: params.tokenId,
user_uuid: params.userUuid
})
.fire();
await TokenCompanyUser.flushCache(params.tokenId);
return Promise.resolve(responseHelper.successWithData(insertResponse.insertId));
}
/**
* Get user_uuid from table for given token id
*
* @param {String} tokenId
*
* @returns {*}
*/
async getDetailsByTokenId(tokenId) {
const oThis = this;
let userUuids = [],
whereClause = ['token_id = ?', tokenId];
let dbRows = await oThis
.select('*')
.where(whereClause)
.fire();
if (dbRows.length === 0) {
return responseHelper.successWithData({ userUuids: [] });
}
for (let i = 0; i < dbRows.length; i++) {
userUuids.push(dbRows[i].user_uuid);
}
return responseHelper.successWithData({
userUuids: userUuids
});
}
/***
*
* flush cache
*
* @param tokenId
* @returns {Promise<*>}
*/
static flushCache(tokenId) {
const TokenCompanyUserCache = require(rootPrefix + '/lib/cacheManagement/kitSaas/TokenCompanyUserDetail');
return new TokenCompanyUserCache({
tokenId: tokenId
}).clear();
}
} |
JavaScript | class IdmWorkspace {
/**
* Constructs a new <code>IdmWorkspace</code>.
* A Workspace is composed of a set of nodes UUIDs and is used to provide accesses to the tree via ACLs.
* @alias module:model/IdmWorkspace
* @class
*/
constructor() {
}
/**
* Constructs a <code>IdmWorkspace</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/IdmWorkspace} obj Optional instance to populate.
* @return {module:model/IdmWorkspace} The populated <code>IdmWorkspace</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new IdmWorkspace();
if (data.hasOwnProperty('UUID')) {
obj['UUID'] = ApiClient.convertToType(data['UUID'], 'String');
}
if (data.hasOwnProperty('Label')) {
obj['Label'] = ApiClient.convertToType(data['Label'], 'String');
}
if (data.hasOwnProperty('Description')) {
obj['Description'] = ApiClient.convertToType(data['Description'], 'String');
}
if (data.hasOwnProperty('Slug')) {
obj['Slug'] = ApiClient.convertToType(data['Slug'], 'String');
}
if (data.hasOwnProperty('Scope')) {
obj['Scope'] = IdmWorkspaceScope.constructFromObject(data['Scope']);
}
if (data.hasOwnProperty('LastUpdated')) {
obj['LastUpdated'] = ApiClient.convertToType(data['LastUpdated'], 'Number');
}
if (data.hasOwnProperty('Policies')) {
obj['Policies'] = ApiClient.convertToType(data['Policies'], [ServiceResourcePolicy]);
}
if (data.hasOwnProperty('Attributes')) {
obj['Attributes'] = ApiClient.convertToType(data['Attributes'], 'String');
}
if (data.hasOwnProperty('RootUUIDs')) {
obj['RootUUIDs'] = ApiClient.convertToType(data['RootUUIDs'], ['String']);
}
if (data.hasOwnProperty('RootNodes')) {
obj['RootNodes'] = ApiClient.convertToType(data['RootNodes'], {'String': TreeNode});
}
if (data.hasOwnProperty('PoliciesContextEditable')) {
obj['PoliciesContextEditable'] = ApiClient.convertToType(data['PoliciesContextEditable'], 'Boolean');
}
}
return obj;
}
/**
* @member {String} UUID
*/
UUID = undefined;
/**
* @member {String} Label
*/
Label = undefined;
/**
* @member {String} Description
*/
Description = undefined;
/**
* @member {String} Slug
*/
Slug = undefined;
/**
* @member {module:model/IdmWorkspaceScope} Scope
*/
Scope = undefined;
/**
* @member {Number} LastUpdated
*/
LastUpdated = undefined;
/**
* @member {Array.<module:model/ServiceResourcePolicy>} Policies
*/
Policies = undefined;
/**
* @member {String} Attributes
*/
Attributes = undefined;
/**
* @member {Array.<String>} RootUUIDs
*/
RootUUIDs = undefined;
/**
* @member {Object.<String, module:model/TreeNode>} RootNodes
*/
RootNodes = undefined;
/**
* @member {Boolean} PoliciesContextEditable
*/
PoliciesContextEditable = undefined;
} |
JavaScript | class Connector {
/**
* Creates an instance of Connector.
* @memberof Connector
*/
constructor() {
}
/**
* Connects two boxes via a line.
*
* @param {Box} A
* @param {Box} B
* @memberof Connector
*/
connect(A, B) {
if (!A) throw "A cannot be null or undefined";
if (!B) throw "B cannot be null or undefined";
if (B.y >= A.y + A.height && B.x >= A.x + A.width) {
console.log("connector", "running B.y >= A.y + A.height && B.x >= A.x + A.widt");
let element = connect_a_top_left_b_bottom_right(A, B);
return;
}
if (B.y >= A.y + A.height && B.x >= A.x) {
console.log("connector", "running B.y >= A.y + A.height && B.x >= A.x + A.widt");
let element = connect_a_top_left_b_bottom_right(A, B);
return;
}
if (B.y >= A.y + A.height && B.x + B.width <= A.x) {
console.log("connector", "running B.y >= A.y + A.height && B.x + B.width <= A.x");
let element = connect_a_top_right_b_bottom_left(A, B);
return;
}
if (B.y >= A.y + A.height && B.x <= A.x) {
console.log("connector", "running B.y >= A.y + A.height && B.x + B.width <= A.x");
let element = connect_a_top_right_b_bottom_left(A, B);
return;
}
if (B.y + B.height <= A.y && B.x + B.width <= A.x) {
console.log("connector", "running B.y + B.height <= A.y && B.x + B.width <= A.xx");
let element = connect_a_bottom_right_b_top_left(A, B);
return;
}
if (B.y + B.height <= A.y && B.x <= A.x) {
console.log("connector", "running B.y + B.height <= A.y && B.x + B.width <= A.xx");
let element = connect_a_bottom_right_b_top_left(A, B);
return;
}
if (B.y + B.height < A.y && B.x >= A.x + A.width) {
console.log("connector", "running B.y + B.height < A.y && B.x >= A.x + A.width");
let element = connect_a_bottom_left_b_top_right(A, B);
return;
}
if (B.y + B.height < A.y && B.x >= A.x) {
console.log("connector", "running B.y + B.height < A.y && B.x >= A.x + A.width");
let element = connect_a_bottom_left_b_top_right(A, B);
return;
}
if (B.x >= A.x + A.width && B.y < A.y + A.height) {
console.log("connector", "running B.x >= A.x + A.width && B.y < A.y + A.height");
let element = connect_a_left_b_right(A, B);
return;
}
if (B.x >= A.x + A.width && B.y + B.height < A.y) { // Useless, covered by previous, here for safety
console.log("connector", "running B.x >= A.x + A.width && B.y + B.height < A.y ! 2");
let element = connect_a_left_b_right(A, B);
return;
}
if (B.x + B.width <= A.x && B.y < A.y + A.height) {
console.log("connector", "running B.x + B.width <= A.x && B.y < A.y + A.height");
let element = connect_a_right_b_left(A, B);
return;
}
if (B.x + B.width <= A.x && B.y + B.height < A.y) { // Useless, covered by previous, here for safety
console.log("connector", "running B.x + B.width <= A.x && B.y + B.height < A.y");
let element = connect_a_right_b_left(A, B);
return;
}
console.log("connector", "unsupported configuration");
}
} |
JavaScript | class myClient {
constructor() {
//The below function is never used
this.reportBusyWhile = async (title, f) => {
this.logger.info(`[Started] ${title}`);
let res;
try {
res = await f();
}
finally {
this.logger.info(`[Finished] ${title}`);
}
return res;
};
}
//function to get the initiliazing parameters for the server
getInitializeParams(projectPath, process) {
return {
processId: process.pid,
rootPath: projectPath,
rootUri: pathToUri(projectPath),
capabilities: {
workspace: {
applyEdit: true,
workspaceEdit: {
documentChanges: true,
},
didChangeConfiguration: {
dynamicRegistration: false,
},
didChangeWatchedFiles: {
dynamicRegistration: false,
},
symbol: {
dynamicRegistration: false,
},
executeCommand: {
dynamicRegistration: false,
},
workspaceFolders: true,
configuration: false,
},
textDocument: {
synchronization: {
dynamicRegistration: false,
willSave: false,
willSaveWaitUntil: false,
didSave: false,
},
completion: {
dynamicRegistration: false,
completionItem: {
snippetSupport: false,
commitCharactersSupport: false,
},
contextSupport: false,
},
hover: {
dynamicRegistration: true,
},
signatureHelp: {
dynamicRegistration: false,
},
references: {
dynamicRegistration: false,
},
documentHighlight: {
dynamicRegistration: true,
},
documentSymbol: {
dynamicRegistration: false,
},
formatting: {
dynamicRegistration: false,
},
rangeFormatting: {
dynamicRegistration: false,
},
onTypeFormatting: {
dynamicRegistration: false,
},
definition: {
dynamicRegistration: true,
},
codeAction: {
dynamicRegistration: false,
},
codeLens: {
dynamicRegistration: false,
},
documentLink: {
dynamicRegistration: false,
},
rename: {
dynamicRegistration: false,
},
implementation: {
dynamicRegistration: false,
},
typeDefinition: {
dynamicRegistration: false,
},
colorProvider: {
dynamicRegistration: false,
}
},
experimental: {},
},
workspaceFolders: null,
};
}
/**
*Function called to start the language server
*@async
*@function
*@param {string} ProjectPath the path in which the server will be initiated
*/
async startServer(projectPath) {
//The below command starts the server using childProcess
const process = await this.spawnServerWithSocket().then((result) => { return result; });
;
this.captureServerErrors(process, projectPath);
//the Directory where the server repos are
let serverHome = path.join(__dirname, 'server');
//creating a connection using sockets (part of lsp)
const connection = new languageclient_1.LanguageClientConnection(this.createRpcConnection());
//getting the initiliazing params for the project path
const initializeParams = this.getInitializeParams(projectPath, process);
//initializing the server with the params
const initialization = connection.initialize(initializeParams);
//waiting for the server to initialize
const initializeResponse = await initialization;
this._connection = connection;
//below is a implementation of the ActiveServer defined above
const newServer = {
projectPath,
process,
connection,
capabilities: initializeResponse.capabilities,
};
connection.initialized();
process.on('exit', () => { console.log("process exit"); });
console.log("server started");
//returning the ActiveServer interface object
return newServer;
}
//Function to create a socket connection
//Following the language server protocol
createRpcConnection() {
let reader;
let writer;
reader = new rpc.SocketMessageReader(this.socket);
writer = new rpc.SocketMessageWriter(this.socket);
return rpc.createMessageConnection(reader, writer);
}
/**
*creates a local server at 3000 and calls the function to spawn the language server
*@function spawnServerWithSocket
*/
spawnServerWithSocket() {
return new Promise((resolve, reject) => {
let childProcess;
let server;
//below server is started at port 3000
server = net.createServer(socket => {
// When the language server connects, grab socket, stop listening and resolve
this.socket = socket;
server.close();
//resolving the process
resolve(childProcess);
}).listen(3000);
const pro2 = new Promise((resolve2, reject) => {
// Once we have a port assigned spawn the Language Server with the port
childProcess = this.spawnServer([``]); //--tcp=127.0.0.1:${server.address().port}
//if the childProcess exits with a crash then delete the server temp files and try again
childProcess.on('exit', exitCode => {
if (!childProcess.killed) {
console.log("childProcess exit but not killed");
}
console.log(exitCode);
//Deleting the temp files to fix the crash
shell.exec("rm -r -f ./server_0.9/.metadata");
shell.exec("rm -r -f ./server_0.9/jdt.ls-java-project");
//Spawning the server again after the removal of temp files
childProcess = this.spawnServer([``]);
console.log("again childprocess started after the crash");
});
//});
});
});
}
/**
*starting the language server using the childProcess
*@function spawnServer
*/
spawnServer(extraArgs) {
const command = "java";
//const serverHome = path.join(__dirname,'server');
const serverHome = path.join(__dirname, 'server_0.9');
//getting the platform on which the program is running
var platform = os.platform();
//variabel for the argument to start the server
var variable;
console.log("platform: " + platform);
if (platform == "linux") {
variable = "linux";
}
else if (platform == "win32") {
variable = "win";
}
else if (platform == "darwin") {
variable = "mac";
}
variable = "config_" + variable;
//putting all the arg for the starting of the language server
//if using different server then change the launcher argument
const args = ['-jar', 'plugins/org.eclipse.equinox.launcher_1.5.0.v20180512-1130.jar', '-configuration', variable, '-data']; //launcher_1.5.0.v20180119-0753.jar for old server
if (extraArgs) {
args.push(extraArgs);
}
//using cp.spawn to start server
const childProcess = cp.spawn(command, args, { cwd: serverHome });
return childProcess;
}
/**
*Gets the definition result from the server connection using function defined in languageclient.ts
*@function getDefinitions
*/
async getDefinition(params) {
const definitionLocation = this._connection.gotoDefinition(params);
return definitionLocation;
}
/**
*capturing server errors
*@function captureServerErrors
*/
captureServerErrors(childProcess, projectPath) {
childProcess.on('error', (err) => console.log("o1"));
childProcess.on('exit', (code, signal) => console.log("o2"));
childProcess.stderr.setEncoding('utf8');
childProcess.stderr.on('data', (chunk) => {
const errorString = chunk.toString();
});
}
} |
JavaScript | class AlternativeStorage {
constructor() {
this.storageMap = {};
}
/*
* Returns an integer representing the number of data items stored in the storageMap object.
*/
get length() {
return Object.keys(this.storageMap).length;
}
/*
* Remove all keys out of the storage.
*/
clear() {
this.storageMap = {};
}
/*
* Return the key's value
*
* @param key - name of the key to retrieve the value of.
* @return The key's value
*/
getItem(key) {
if (typeof this.storageMap[key] !== 'undefined') {
return this.storageMap[key];
}
return null;
}
/*
* Return the nth key in the storage
*
* @param index - the number of the key you want to get the name of.
* @return The name of the key.
*/
key(index) {
return Object.keys(this.storageMap)[index] || null;
}
/*
* Remove a key from the storage.
*
* @param key - the name of the key you want to remove.
*/
removeItem(key) {
this.storageMap[key] = undefined;
}
/*
* Add a key to the storage, or update a key's value if it already exists.
*
* @param key - the name of the key.
* @param value - the value you want to give to the key.
*/
setItem(key, value) {
this.storageMap[key] = value;
}
} |
JavaScript | class JarClassContentProvider {
constructor(client) {
this.client = client;
}
setClient(client) {
this.client = client;
}
provideTextDocumentContent(uri) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this.client.sendRequest(lspExtensions_1.JarClassContentsRequest.type, { uri: uri.toString() });
if (result == null) {
vscode.window.showErrorMessage(`Could not fetch class file contents of '${uri}' from the language server. Make sure that it conforms to the format 'kls:file:///path/to/myJar.jar!/path/to/myClass.class'!`);
return "";
}
else {
return result;
}
});
}
} |
JavaScript | class NonValidatingClass extends Core.mix(
"Core.abstract.BaseClass",
"Core.util.mixin.Configurable"
) {
} |
JavaScript | class UserService {
static get parameters() {
return [[Http], [IonicApp], [NavController], [Util]];
}
constructor(http, app, nav, util) {
this.http = http;
this.app = app;
this.nav = nav;
this.sso = null;
this.util = util;
}
initializeSSO() {
return new Promise(resolve => {
let url = this.app.config.get("BASE_URL") + this.app.config.get("PRE_LOGIN_INFO_URL");
this.util.callCordysWebserviceWithUrl(url, null).then(data => {
let xmlConfigData = this.util.parseXml(data);
this.sso = new SSO(this.util, this.app.config);
resolve(this.sso);
});
});
}
getSSO() {
if (!this.sso) {
return this.initializeSSO();
} else {
return Promise.resolve(this.sso);
}
}
loggedOn() {
return new Promise(resolve => {
this.getSSO()
.then(sso => {
resolve(sso.loggedOn());
});
});
}
authenticate(user) {
return new Promise(resolve => {
this.getSSO()
.then(sso => {
return sso.authenticate(user.loginId, user.password);
})
.then(authenticationResult => {
if (authenticationResult || !authenticationResult) {
resolve(authenticationResult);
} else {
this.app.translate.get(["app.blog.message.error.title", "app.message.error.systemError", "app.action.ok"]).subscribe(message => {
let title = message['app.blog.message.error.title'];
let ok = message['app.action.ok'];
let content = message['app.message.error.systemError'];
let alert = Alert.create({
title: title,
subTitle: content,
buttons: [ok]
});
this.nav.present(alert);
});
}
});
});
}
getUserDetail() {
if (this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.util.getRequestXml('./assets/requests/get_user_details.xml').then(req => {
let objRequest = this.util.parseXml(req);
req = this.util.xml2string(objRequest);
this.util.callCordysWebservice(req).then(data => {
let objResponse = this.util.parseXml(data);
let userOutput = this.util.selectXMLNode(objResponse, ".//*[local-name()='user']");
let user = this.util.xml2json(userOutput).user;
let userId = this.util.getUserIdFromAuthUserDn(user.authuserdn);
let userAvatarUrl = this.util.getUserAvatarUrlByUserId(userId);
let returnData = {
"userAvatar": userAvatarUrl,
"userName": user.description,
"userId": userId
}
resolve(returnData);
});
});
});
}
updateProfile(user) {
return new Promise(resolve => {
if (this.validateUserPassword(user.newPassword, user.confirmPassword)) {
this.util.getRequestXml('./assets/requests/set_password.xml').then(req => {
let objRequest = this.util.parseXml(req);
this.util.setNodeText(objRequest, ".//*[local-name()='OldPassword']", user.oldPassword);
this.util.setNodeText(objRequest, ".//*[local-name()='NewPassword']", user.newPassword);
req = this.util.xml2string(objRequest);
this.util.callCordysWebservice(req).then(data => {
resolve("true");
});
});
}
});
}
validateUserPassword(newPassword, confirmPassword) {
let passwordEmptyFault = newPassword == "" && confirmPassword == "";
let arePasswordsSame = newPassword == confirmPassword;
if (passwordEmptyFault) {
this.app.translate.get(["app.profile.message.error.title", "app.profile.message.error.emptyPassword", "app.action.ok"]).subscribe(message => {
let title = message['app.profile.message.error.title'];
let ok = message['app.action.ok'];
let content = message['app.profile.message.error.emptyPassword'];
let alert = Alert.create({
title: title,
subTitle: content,
buttons: [ok]
});
this.nav.present(alert);
});
} else if (!arePasswordsSame) {
this.app.translate.get(["app.profile.message.error.title", "app.profile.message.error.mismatchPassword", "app.action.ok"]).subscribe(message => {
let title = message['app.profile.message.error.title'];
let ok = message['app.action.ok'];
let content = message['app.profile.message.error.mismatchPassword'];
let alert = Alert.create({
title: title,
subTitle: content,
buttons: [ok]
});
this.nav.present(alert);
});
}
return !passwordEmptyFault && arePasswordsSame;
}
} |
JavaScript | class ValidateUser {
/**
* @method signUpDetails
* @description Validates user sign in details
* @param {object} req - The Request Object
* @param {object} res - The Response Object
* @returns {object} JSON API Response
*/
static signUpDetails(req, res, next) {
const validate = Helper.validate();
const {
firstname, lastname, phonenumber, email, password, passporturl,
} = req.body;
let error;
if (!validate.name.test(firstname)) {
error = 'invalid firstname';
}
if (!firstname || !firstname.trim()) {
error = 'Firstname field is required';
}
if (!validate.name.test(lastname)) {
error = 'invalid last name';
}
if (!lastname || !lastname.trim()) {
error = 'Lastname field is required';
}
if (!email || !validate.email.test(email)) {
error = 'email is invalid, please use a valid email';
}
if (!email || !email.trim()) {
error = 'Email field is required';
}
if (!validate.phonenumber.test(phonenumber)) {
error = 'phone number is invalid';
}
if (!phonenumber || !phonenumber.trim()) {
error = 'phonenumber field is required';
}
if (!passporturl || !validate.logoUrl.test(passporturl)) {
error = 'Please include a valid passport';
}
if (!password.trim()) {
error = 'Password field cannot be empty';
}
if (!validate.hqAddress.test(password)) {
error = 'Password is invalid';
}
if (error) {
return res.status(400).json({ status: 400, error });
}
if (password.length < 5) {
error = 'Password should not be less than 6 characters';
return res.status(400).json({ status: 400, error });
}
return next();
}
/**
* @method loginDetails
* @description Validates login details
* @param {object} req - The Request Object
* @param {object} res - The Response Object
* @returns {object} JSON API Response
*/
static loginDetails(req, res, next) {
const validate = Helper.validate();
const { email, password } = req.body;
const path = req.url.trim().split('/')[2];
let error;
let status;
const query = 'SELECT id, email, password, isadmin FROM users WHERE email = $1';
if (!validate.email.test(email)) {
error = 'The email you provided is invalid';
} if (!password) {
error = 'Please provide a password';
} if (error) {
status = 404;
return res.status(status).json({ status, error });
}
if (path === 'login') {
return client.query(query, [email], (err, dbRes) => {
if (dbRes.rowCount < 1) {
return res.status(400).json({
status: 400,
error: 'Email or password is incorrect',
});
}
const hashedPassword = dbRes.rows[0].password;
const verifyPassword = Helper.verifyPassword(`${password}`, hashedPassword);
if (!verifyPassword) {
error = 'Email or password is incorrect';
status = 401;
}
if (error) {
return res.status(status).json({ status, error });
}
const userReq = dbRes.rows[0];
req.user = { id: userReq.id, email: userReq.email, isadmin: userReq.isadmin };
return next();
});
}
return next();
}
/**
* @method userExists
* @description Validates existing user
* @param {object} req - The Request Object
* @param {object} res - The Response Object
* @returns {object} JSON API Response
*/
static userExists(req, res, next) {
const userEmail = {
text: 'SELECT * FROM users WHERE email = $1;',
values: [req.body.email],
};
return client.query(userEmail, (error, dbRes) => {
if (dbRes.rows[0]) {
return res.status(409).json({
status: 409,
error: 'email aleady exists, please choose another email',
});
}
return next();
});
}
} |
JavaScript | class GetPattern {
/**
* @param {BrowscapCache} cache
*/
constructor(cache) {
this.cache = cache;
}
/**
* Gets some possible patterns that have to be matched against the user agent. With the given
* user agent string, we can optimize the search for potential patterns:
* - We check the first characters of the user agent (or better: a hash, generated from it)
* - We compare the length of the pattern with the length of the user agent
* (the pattern cannot be longer than the user agent!)
*
* @param {string} userAgent
*
* @return {array}
*/
getPatterns(userAgent) {
const starts = PatternHelper.getHashForPattern(userAgent, true);
const length = PatternHelper.getPatternLength(userAgent);
// get patterns, first for the given browser and if that is not found,
// for the default browser (with a special key)
return SynchronousPromise.all(
starts.map((tmpStart) => {
const tmpSubkey = SubKey.getPatternCacheSubkey(tmpStart);
return SynchronousPromise.resolve(this.cache.getItem('browscap.patterns.' + tmpSubkey, true));
})
).then((files) => {
return files
.map(
(file, i) => {
return {
file: file,
index: i,
start: starts[i]
};
},
starts
).filter(
(map) => {
if (!map.file.success) {
return false;
}
if (!Array.isArray(map.file.content) && typeof map.file.content !== 'object') {
return false;
}
return map.file.content.length !== 0;
}
).map(
(map) => {
let start = map.start;
let found = false;
let patternListInner = [];
for (let j = 0; j < map.file.content.length; j++) {
const buffer = map.file.content[j];
const split = buffer.split("\t");
const tmpBuffer = split.shift();
if (tmpBuffer === start) {
const len = split.shift();
if (len <= length) {
found = true;
patternListInner.push(split);
} else if (found === true) {
break;
}
}
}
return patternListInner;
}
).reduce(
(patternListInner, result) => {
return patternListInner.concat(result);
}, []
);
});
}
} |
JavaScript | class CommandClient extends Client {
/**
* Create a CommandClient
* @arg {String} token bot token
* @arg {Object} [options] Eris options (same as Client)
* @arg {Object} [commandOptions] Command options
* @arg {Object} [commandOptions.defaultHelpCommand=true] Whether to register the default help command or not
* @arg {Object} [commandOptions.description="An Eris-based Discord bot"] The description to show in the default help command
* @arg {Object} [commandOptions.ignoreBots=true] Whether to ignore bot accounts or not
* @arg {Object} [commandOptions.name="<Bot username>"] The bot name to show in the default help command
* @arg {Object} [commandOptions.owner="an unknown user"] The owner to show in the default help command
* @arg {Object} [commandOptions.prefix="@mention "] The bot prefix. "@mention" will be automatically replaced with the bot's actual mention
*/
constructor(token, options, commandOptions) {
super(token, options);
this.commandOptions = {
defaultHelpCommand: true,
description: "An Eris-based Discord bot",
ignoreBots: true,
name: null,
owner: "an unknown user",
prefix: "@mention " // TODO multi-prefix
};
if(typeof commandOptions === "object") {
for(var property of Object.keys(commandOptions)) {
this.commandOptions[property] = commandOptions[property];
}
}
this.commands = {};
this.commandAliases = {};
this.once("shardPreReady", () => {
if(!this.commandOptions.name) {
this.commandOptions.name = `**${this.user.username}**`;
}
this.commandOptions.prefix = this.commandOptions.prefix.replace(/@mention/g, `<@${this.user.id}>`);
});
this.on("messageCreate", (msg) => {
if(!this.ready) {
return;
}
if(msg.author.id !== this.user.id && (!this.commandOptions.ignoreBots || !msg.author.bot) && msg.content.startsWith(this.commandOptions.prefix)) {
var args = msg.content.substring(this.commandOptions.prefix.length).split(" ");
var label = args.shift();
label = this.commandAliases[label] || label;
var command;
if((command = this.commands[label]) !== undefined) {
var resp = (command.process(args, msg) || "").toString();
if(resp != "") {
this.createMessage(msg.channel.id, {
content: resp
});
}
if(command.deleteCommand) {
this.deleteMessage(msg.channel.id, msg.id);
}
}
}
});
if(this.commandOptions.defaultHelpCommand) {
this.registerCommand("help", (msg, args) => {
var result = "";
if(args.length > 0) {
var cur = this.commands[this.commandAliases[args[0]] || args[0]];
if(!cur) {
return "Command not found";
}
var label = cur.label;
for(var i = 1; i < args.length; i++) {
cur = cur.subcommands[cur.subcommandAliases[args[i]] || args[i]];
if(!cur) {
return "Command not found";
}
label += " " + cur.label;
}
result += `**${this.commandOptions.prefix}${label}** ${cur.usage}\n${cur.fullDescription}`;
if(Object.keys(cur.aliases).length > 0) {
result += `\n\n**Aliases:** ${cur.aliases.join(", ")}`;
}
if(Object.keys(cur.subcommands).length > 0) {
result += "\n\n**Subcommands:**";
for(var subLabel in cur.subcommands) {
if(cur.subcommands[subLabel].permissionCheck(args, msg)) {
result += `\n **${subLabel}** - ${cur.subcommands[subLabel].description}`;
}
}
}
} else {
result += `${this.commandOptions.name} - ${this.commandOptions.description}\n`;
if(this.commandOptions.owner) {
result += `by ${this.commandOptions.owner}\n`;
}
result += "\n";
result += "**Commands:**\n";
for(label in this.commands) {
if(this.commands[label].permissionCheck(args, msg)) {
result += ` **${this.commandOptions.prefix}${label}** - ${this.commands[label].description}\n`;
}
}
result += `\nType ${this.commandOptions.prefix}help <command> for more info on a command.`;
if(this.commandOptions.suffix) {
result += `\n\n${this.commandOptions.suffix}\n`;
}
}
return result;
}, {
description: "This help text",
fullDescription: "This command is used to view information of different bot commands, including this one."
});
}
}
/**
* Register an alias for a command
* @arg {String} alias The alias
* @arg {String} label The original command label
*/
registerCommandAlias(alias, label) {
if(!this.commands[label]) {
throw new Error("No command registered for " + label);
}
if(this.commandAliases[alias]) {
throw new Error(`Alias ${label} already registered`);
}
this.commandAliases[alias] = label;
this.commands[label].aliases.push(alias);
}
/**
* Register a command
* @arg {String} label The command label
* @arg {Function|String} generator A response string, or function that generates a String when called.
* If a function is passed, the function will be passed a Message object and an array of command arguments
* <pre><code>generator(msg, args)</code></pre>
* @arg {Object} [options] Command options
* @arg {Array<String>} [options.aliases] An array of command aliases
* @arg {String} [options.deleteCommand=false] Whether to delete the user command message or not
* @arg {String} [options.serverOnly=false] Whether to prevent the command from being used in Direct Messages or not
* @arg {String} [options.description="No description"] A short description of the command to show in the default help command
* @arg {String} [options.fullDescription="No full description"] A detailed description of the command to show in the default help command
* @arg {String} [options.usage] Details on how to call the command to show in the default help command
* @arg {String} [options.requirements] A set of factors that limit who can call the command
* @arg {String} [options.requirements.userIDs] A set of user IDs representing users that can call the command
* @arg {String} [options.requirements.permissions] An array of permission keys the user must have to use the command
* i.e.:
* ```
* {
* "administrator": false,
* "manageMessages": true
* }```
* In the above example, the user must not have administrator permissions, but must have manageMessages to use the command
* @arg {String} [options.requirements.roleIDs] An array of role IDs that would allow a user to use the command
* @arg {String} [options.requirements.roleNames] An array of role names that would allow a user to use the command
* @returns {Command}
*/
registerCommand(label, generator, options) {
if(label.includes(" ")) {
throw new Error("Command label may not have spaces");
}
if(this.commands[label]) {
throw new Error("You have already registered a command for " + label);
}
options = options || {};
this.commands[label] = new Command(label, generator, options);
if(options.aliases) {
options.aliases.forEach((alias) => {
this.commandAliases[alias] = label;
});
}
return this.commands[label];
}
/**
* Unregister a command
* @arg {String} label The command label
*/
unregisterCommand(label) {
var original = this.commandAliases[label];
if(original) {
this.commands[original].aliases.splice(this.commands[original].aliases.indexOf(label), 1);
this.commandAliases[label] = undefined;
} else {
this.commands[label] = undefined;
}
}
} |
JavaScript | class TableVisualizer extends Visualizer {
/**
* Visualizes the given
* story part as JSON.
* @return {[type]} [description]
*/
visualize(part, container) {
// get the part's output section
const {
output
} = part;
try {
let {data} = output;
// append it to the container
const $cnt = $(container);
$cnt.append('<table class="ui table"></table>');
$('table', $cnt).addClass('ui padded celled table');
let columns = [];
if (_.isArray(data)) {
// if result is an array,
// flatten all entries
_.each(data, (o, idx) => {
const flat = flatten(o, {delimiter: '_'});
data[idx] = flat;
});
columns = _.map(data[0], (value, key) => ({
data: key,
name: key,
title: key
}));
} else {
// if result is an object,
// flatten it first
const flat = flatten(data, {delimiter: '_'});
data = [flat];
columns = _.map(flat, (value, key) => ({
data: key,
name: key,
title: key
}));
}
$('.table', $cnt).DataTable({
paging: false,
info: false,
responsive: true,
dom: 'fBrt',
data,
columns,
buttons: [
{
className: 'ui basic button',
extend: 'copy',
text: 'Copy'
},
{
className: 'ui basic button',
extend: 'csv',
text: 'CSV'
}
]
});
} catch (e) {
console.error(e);
}
// emit an event
this.emit('rendered');
}
} |
JavaScript | class Board extends React.Component
{
constructor()
{
super();
debugger;
this.update = this.update.bind(this);
this.eachNote = this.eachNote.bind(this);
this.remove = this.remove.bind(this);
this.add = this.add.bind(this);
this.state = {
notesStringArray : []
}
}
//Event methods
nextId()
{
this.uniqueId = this.uniqueId || 0;
return this.uniqueId++;
}
update(newText, i)
{
var arr = this.state.notesStringArray;
arr[i].note = newText;
this.setState({notesStringArray : arr});
}
eachNote(element, i)
{
return (
<Note key={element.id}
index={i}
onChange={this.update}
onRemove={this.remove}
>{element.note}</Note>
);
}
remove(index)
{
var arr = this.state.notesStringArray;
var elm = arr[index];
arr.splice(index, 1);
this.setState({notesStringArray : arr});
return elm;
}
componentWillMount()
{
// var self = this;
// if(this.props.count)
// {
// $.getJSON('http://baconipsom.com/api/?type=all-meat&sentences=' + this.props.count + '&start-with-lorem=1&callback=?', function(results){
// var data = results[0].split('. ').forEach(function(sentence){
// self.add(sentence.substring(0, 40));
// });
// });
// }
}
add(text)
{
var arr = this.state.notesStringArray;
arr.push({
id : this.nextId(),
note : text
});
JSON.stringify(arr);
this.setState({notesStringArray : arr});
}
render()
{
return(
<div className='board'> {this.state.notesStringArray.map(this.eachNote)}
<button className='btn btn-sm glyphicon glyphicon-plus btn-success' onClick={this.add.bind(null, "New Note!")}>+</button>
</div>
);
}
} |
JavaScript | class FixedCircle {
constructor (id, origin, radius) {
this.id = id
this.origin = origin
this.radius = radius
this.velocity = new Vector(0, 0)
this.angularVelocity = 0
}
collide (collidingBody, timestep, restitution) {
let collision = null
// check if corner is inside
let foundCollision = false
for (let corner = 0; corner < 4; corner++) {
const vertexX = collidingBody.cornerX[corner]
const vertexY = collidingBody.cornerY[corner]
const diffX = vertexX - this.origin.x
const diffY = vertexY - this.origin.y
const distance = Vector.length(diffX, diffY)
if (distance <= this.radius) {
if (collision === null) {
collision = new Collision(restitution)
}
const separation = this.radius - distance
// Vector normal = Vector.unitVector(origin, vertex);
let normalX = vertexX - this.origin.x
let normalY = vertexY - this.origin.y
const normalLen = Vector.length(normalX, normalY)
normalX /= normalLen
normalY /= normalLen
const collisionPoint = new CollisionPoint(
collidingBody,
this,
normalX,
normalY,
vertexX,
vertexY,
separation
)
collision.collisionPoints.push(collisionPoint)
foundCollision = true
}
}
// check if edge collides
for (let edge = 0; edge < 4 && !foundCollision; edge++) {
const bodyCorner1 = edge
const bodyCorner2 = edge === 3 ? 0 : edge + 1
const p1X = collidingBody.cornerX[bodyCorner1]
const p1Y = collidingBody.cornerY[bodyCorner1]
const p2X = collidingBody.cornerX[bodyCorner2]
const p2Y = collidingBody.cornerY[bodyCorner2]
// Vector normal = Vector.normal(p1, p2);
let normalX = p2X - p1X
let normalY = p2Y - p1Y
const div = 1.0 / Math.sqrt(normalX * normalX + normalY * normalY)
normalX *= div
normalY *= div
const tmp = normalX
normalX = -normalY
normalY = tmp
const q1X = this.origin.x
const q1Y = this.origin.y
// Vector q2 = Vector.scale(normal, radius);
let q2X = normalX * this.radius
let q2Y = normalY * this.radius
// q2.add(origin);
q2X += this.origin.x
q2Y += this.origin.y
// Vector cp = Vector.intersectLineSegments(p1, p2, q1, q2);
let cpX = NaN
let cpY = NaN
// solve A * x = b
const a11 = p2X - p1X
const a12 = q1X - q2X
const a21 = p2Y - p1Y
const a22 = q1Y - q2Y
const b1 = q1X - p1X
const b2 = q1Y - p1Y
let det = a11 * a22 - a12 * a21
det = 1.0 / det
const r = det * (a22 * b1 - a12 * b2)
const t = det * (a11 * b2 - a21 * b1)
if (r >= 0 && r <= 1 && t >= 0 && t <= 1) {
const cX = p2X - p1X
const cY = p2Y - p1Y
cpX = cX * r + p1X
cpY = cY * r + p1Y
}
if (!isNaN(cpX)) {
if (collision == null) {
collision = new Collision(restitution)
}
const collisionPoint = new CollisionPoint(
collidingBody,
this,
normalX,
normalY,
cpX,
cpY,
0
)
collision.collisionPoints.push(collisionPoint)
foundCollision = true
}
}
return collision
}
// this is a fixed entity
invertedMass () {
return 0
}
// this is a fixed entity
invertedInertia () {
return 0
}
// fixed entity has no velocity
addVelocity (velocity) {}
// fixed entity has no angular velocity
addAngularVelocity (angularVelocity) {}
} |
JavaScript | class ProjectGallery extends react__WEBPACK_IMPORTED_MODULE_0__["Component"] {
render() {
const settings = {
dots: false,
infinite: true,
speed: 300,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
fade: true,
arrows: false,
rtl: false
};
const {
slides
} = this.props;
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCard__WEBPACK_IMPORTED_MODULE_2__["RctCard"], null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCard__WEBPACK_IMPORTED_MODULE_2__["RctCardContent"], null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h5", {
className: "mb-20"
}, "Project Gallery"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_slick__WEBPACK_IMPORTED_MODULE_1___default.a, settings, slides && slides.map((slide, index) => {
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
key: index,
className: "gallery-item"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
className: "gallery-img"
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", {
src: __webpack_require__("./resources/js/assets/img sync recursive ^\\.\\/.*$")(`./${slide}`),
height: "252",
alt: "gallery",
className: "img-fluid d-block"
})));
})))));
}
// @ts-ignore
__reactstandin__regenerateByEval(key, code) {
// @ts-ignore
this[key] = eval(code);
}
} |
JavaScript | class Document {
/** */
constructor() {
Object.defineProperties( this, {
/**
* Exposes list of document's pages.
*
* @name Document#pages
* @property {Page[]}
* @readonly
*/
pages: { value: [] },
} );
}
/**
* Adds another page to the document.
*
* @param {Page|int} insertBefore index of page or reference on page to become
* successor of inserted one, null is for appending new page
* @return {Page} created and added page
*/
addPage( insertBefore = null ) {
const { pages } = this;
const numPages = pages.length;
let _index = -1;
if ( insertBefore instanceof Page ) {
for ( let i = 0; i < numPages; i++ ) {
if ( pages[i] === insertBefore ) {
_index = i;
break;
}
}
} else if ( insertBefore == null ) {
_index = numPages;
} else if ( !isNaN( insertBefore ) ) {
_index = Math.max( 0, Math.min( numPages - 1, parseInt( insertBefore ) ) );
}
if ( _index < 0 ) {
throw new Error( "invalid reference/index for inserting page" );
}
const page = new Page( this );
pages.splice( _index, 0, page );
return page;
}
/**
* Removes selected page from document returning reference on removed page.
*
* @param {Page|int} page reference on page or index of page to remove
* @return {Page} removed page
* @throws Error on invalid selection of a page
*/
removePage( page ) {
const { pages } = this;
const numPages = pages.length;
if ( page instanceof Page ) {
for ( let i = 0; i < numPages; i++ ) {
if ( pages[i] === page ) {
pages.splice( i, 1 );
return page;
}
}
throw new TypeError( "page not found in current document" );
}
const _index = parseInt( page );
if ( _index > -1 && _index < numPages ) {
const removedPage = pages[_index];
pages.splice( _index, 1 );
return removedPage;
}
throw new TypeError( "invalid index for selecting page to remove" );
}
} |
JavaScript | class MessageManager extends BaseManager {
constructor(client, iterable) {
if (!Message) Message = require('../structures/Message');
super(client, iterable, Message, client.options.messageCacheMaxSize);
}
/**
* The cache of this manager
* @type {Collection<Message>}
* @name MessageManager#cache
*/
} |
JavaScript | @customElement('ids-text')
@scss(styles)
class IdsText extends IdsElement {
constructor() {
super();
}
/**
* Return the properties we handle as getters/setters
* @returns {Array} The properties in an array
*/
static get properties() {
return [props.TYPE, props.FONT_SIZE, props.AUDIBLE];
}
/**
* Inner template contents
* @returns {string} The template
*/
template() {
const tag = this.type || 'span';
let classList = 'ids-text';
classList += this.audible ? ' audible' : '';
classList += this.fontSize ? ` ids-text-${this.fontSize}` : '';
classList = ` class="${classList}"`;
return `<${tag}${classList}><slot></slot></${tag}>`;
}
/**
* Rerender the component template
* @private
*/
rerender() {
const template = document.createElement('template');
this.shadowRoot?.querySelector('.ids-text')?.remove();
template.innerHTML = this.template();
this.shadowRoot?.appendChild(template.content.cloneNode(true));
}
/**
* Set the font size/style of the text with a class.
* @param {string | null} value The font size in the font scheme
* i.e. 10, 12, 16 or xs, sm, base, lg, xl
*/
set fontSize(value) {
if (value) {
this.setAttribute(props.FONT_SIZE, value);
this.container.classList.add(`ids-text-${value}`);
return;
}
this.removeAttribute(props.FONT_SIZE);
this.container.className = '';
this.container.classList.add('ids-text');
}
get fontSize() { return this.getAttribute(props.FONT_SIZE); }
/**
* Set the type of element it is (h1-h6, span (default))
* @param {string | null} value The type of element
*/
set type(value) {
if (value) {
this.setAttribute(props.TYPE, value);
this.rerender();
return;
}
this.removeAttribute(props.TYPE);
this.rerender();
}
get type() { return this.getAttribute(props.TYPE); }
/**
* Set `audible` string (screen reader only text)
* @param {string | null} value The `audible` attribute
*/
set audible(value) {
if (value) {
this.setAttribute(props.AUDIBLE, value);
this.rerender();
return;
}
this.removeAttribute(props.AUDIBLE);
this.rerender();
}
get audible() { return this.getAttribute(props.AUDIBLE); }
} |
JavaScript | class Video extends models['Codec'] {
/**
* Create a Video.
* @property {moment.duration} [keyFrameInterval] The distance between two
* key frames, thereby defining a group of pictures (GOP). The value should
* be a non-zero integer in the range [1, 30] seconds, specified in ISO 8601
* format. The default is 2 seconds (PT2S).
* @property {string} [stretchMode] The resizing mode - how the input video
* will be resized to fit the desired output resolution(s). Default is
* AutoSize. Possible values include: 'None', 'AutoSize', 'AutoFit'
*/
constructor() {
super();
}
/**
* Defines the metadata of Video
*
* @returns {object} metadata of Video
*
*/
mapper() {
return {
required: false,
serializedName: '#Microsoft.Media.Video',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '@odata.type',
clientName: 'odatatype'
},
uberParent: 'Codec',
className: 'Video',
modelProperties: {
label: {
required: false,
serializedName: 'label',
type: {
name: 'String'
}
},
odatatype: {
required: true,
serializedName: '@odata\\.type',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
keyFrameInterval: {
required: false,
serializedName: 'keyFrameInterval',
type: {
name: 'TimeSpan'
}
},
stretchMode: {
required: false,
serializedName: 'stretchMode',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class Store {
// get books from local storage
static getBooks() {
// check if books is already in local storage
let books;
if(localStorage.getItem('books') === null){
// if not create a new empty array for books
books = [];
} else {
// if exist get current array
books = JSON.parse(localStorage.getItem('books'));
};
// return whatever is in books
return books;
};
// add book to local storage
static addBook(book) {
// get books from local storage
const books = Store.getBooks();
// push on whatever is passed on books
books.push(book);
// set it to localstorage
localStorage.setItem('books', JSON.stringify(books));
};
// remove book from local storage by their isbn since it's their unique id
static removeBook(isbn) {
const books = Store.getBooks();
// loop through books
books.forEach((book, index) => {
// if isbn matches one input to remove
if(book.isbn === isbn){
// slice matched book out of the array using index
books.splice(index, 1);
};
});
localStorage.setItem('books', JSON.stringify(books));
};
} |
JavaScript | class APIHandler {
constructor(baseURL) {
this.baseURL = baseURL;
}
sortCategory(category, filter) {
return axios.get(`${this.baseURL}/categories/${category}?sorting_by=${filter}`);
}
} |
JavaScript | class InteractiveSession {
constructor(term) {
this.localEmulator = new LocalEchoController(term);
this.term = term;
this.ws = null;
this.mode = "busy";
this.resizeTimer = 0;
this.localEmulator.addAutocompleteHandler(() => {
const args = [];
for (let i = 0; i < 101; i++) {
args.push("bash");
}
return args;
});
this._handleTermData = this._handleTermData.bind(this);
this._handleSessionData = this._handleSessionData.bind(this);
this._handleResize = this._handleResize.bind(this);
term.on("data", this._handleTermData.bind(this));
window.addEventListener("resize", this._handleResize);
}
connect(url) {
this.ws = new WebSocket(url);
this._showInfo("starting session...");
this.ws.addEventListener("message", e => {
const data = JSON.parse(e.data);
console.log("incoming: ", data);
this._handleSessionData(data);
});
this.ws.addEventListener("open", e => {
console.log("connected");
this._handleResize();
});
this.ws.addEventListener("close", e => {
this._setMode("disabled");
});
}
_setMode(mode) {
this.mode = mode;
console.log("mode=", mode);
switch (mode) {
case "busy":
this.localEmulator.abortRead();
break;
case "idle":
this._promptForInput();
break;
case "disabled":
this.localEmulator.abortRead();
this._showError("session terminated");
break;
case "interactive":
this.localEmulator.abortRead();
break;
}
}
_showError(message) {
term.write("\x1B[1;31mERROR:\x1B[0m " + message + "\r\n");
}
_showInfo(message) {
term.write("\x1B[1;34mINFO:\x1B[0m " + message + "\r\n");
}
/**
* Handle user for input and submit it's response to the server
*/
_promptForInput() {
this.localEmulator
.read("~$ ")
.then(command => this._handleStartCommand(command))
.catch(e => {});
}
/**
* Start a command
*/
_handleStartCommand(command) {
if (!this.ws) {
this._showError("Connection not established");
this._promptForInput();
}
this.ws.send(
JSON.stringify({
type: "run",
data: {
command: command,
env: {}
}
})
);
}
/**
* Handle terminal resize
*/
_handleResize() {
const { ws, term } = this;
// De-bounce resize events
if (this.resizeTimer) clearTimeout(this.resizeTimer);
this.resizeTimer = setTimeout(() => {
var ret = term.fit();
console.log(ret, term.rows, term.cols);
if (!ws) return;
ws.send(
JSON.stringify({
type: "tty",
data: {
resize: {
width: term.cols,
height: term.rows
}
}
})
);
}, 250);
}
/**
* Handle session messages
*/
_handleSessionData(data) {
switch (data.type) {
case "session":
this._setMode(data.data.mode);
break;
case "error":
if (data.data.message != null) {
this._showError(data.data.message);
}
break;
case "tty":
if (data.data.output != null) {
term.write(data.data.output);
}
break;
}
}
/**
* Send terminal input to the server, if we are in interactive mode
*/
_handleTermData(data) {
if (this.mode !== "interactive" || this.ws == null) return;
this.ws.send(
JSON.stringify({
type: "tty",
data: {
input: data
}
})
);
}
} |
JavaScript | class ztime {
constructor(time) {
if (typeof time === "undefined")
time = Date.now();
else if (typeof(time) === 'string')
time = parseTimeSpec(time);
const debug=_debug("ztime:ztime");
this._time = +time;
if (Number.isNaN(this._time)) {
throw { message: "Invalid value: "+time, what: time };
}
}
get time() {
return this._time;
}
get date() {
return new Date(this._time);
}
valueOf() {
return this._time;
}
toString() {
return this.date.toISOString();
}
toJSON(_) {
return this.date.toISOString();
}
plus(delta) {
return new ztime(this._time + toMilliseconds(delta));
}
/**
The jitter is expressed as the amplitude netween min and max possible values.
*/
jitter(amplitude) {
let milliseconds = toMilliseconds(amplitude);
// Find a number between (-jitter;+jitter) -- EXCLUSIVE on both sides
let offset = 0;
if (milliseconds) {
while(offset == 0) {
offset = Math.random()*milliseconds;
}
}
offset -= milliseconds/2;
return new ztime(this._time+offset);
}
wait(value) {
const time = this;
if (typeof value === 'undefined')
value = time;
return Promise.delay(time-Date.now(), this);
}
loop(fn) {
let schedule = this;
const coroutine = Promise.coroutine(function*() {
let doItAgain = true;
let result = undefined;
function next(date) {
if (date)
schedule = date;
doItAgain = true;
}
while(doItAgain) {
doItAgain = false;
debug("Waiting for", schedule);
yield schedule.wait();
result = yield Promise.resolve(fn(schedule, next));
}
return result;
});
return coroutine();
}
} |
JavaScript | class Timer {
/**
* By defaults, creates a timer that updates every second, and displays that time in a given element.
* @param {String} _element_selector the jQuery selector of the DOM element displaying the timer.
* @param {Number} start_time opt - def: 0. Used to offset the starting time of the timer to 'start_time'.
* @param {Number} _accuracy opt - def: 1000. The time interval at which the timer updates, in milliseconds.
* @param {Number} _format opt - def: 0. TODO: have differents formats in which the timer can be displayed.
*/
constructor(_element_selector, start_time = 0, _accuracy = 1000, _format = 0) {
this.element_selector = _element_selector;
this.time = start_time;
this.ACCURACY = _accuracy;
this.format = _format;
}
addTime(milliseconds) {
this.time += milliseconds;
this.updateDisplay();
}
getTime() {
return this.time / 1000 + "s";
}
updateDisplay() {
$(this.element_selector).text("Time: " + (this.time / 1000));
}
reset() {
this.time = 0;
this.updateDisplay();
this.stop();
let ref = this;
this.interval = setInterval(function () {
ref.addTime(ref.ACCURACY)
}, ref.ACCURACY);
}
stop() {
clearInterval(this.interval);
return this.time;
}
} |
JavaScript | class FeatureBuilder {
constructor(feature) {
this.feature = feature;
this.article = document.createElement('article');
this.div = document.createElement('div');
this.img = document.createElement('img');
this.heading2 = document.createElement('h2');
this.paragraph = document.createElement('p');
// call the associated methods sequentially
this.constructArticle();
this.constructDiv();
this.constructHeading();
this.constructParagraph();
}
constructArticle() {
this.article.classList.add('features');
}
constructDiv() {
this.div.classList.add('img-box');
this.img.src = this.feature.src;
this.img.alt = this.feature.alt;
this.div.appendChild(this.img);
this.article.appendChild(this.div);
}
constructHeading() {
this.heading2.textContent = this.feature.heading2;
this.article.appendChild(this.heading2);
}
constructParagraph() {
this.paragraph.textContent = this.feature.paragraph;
this.article.appendChild(this.paragraph);
}
} |
JavaScript | class TeamBuilder {
constructor(member) {
this.member = member;
this.article = document.createElement("article");
this.div = document.createElement("div");
this.img = document.createElement("img");
this.heading3 = document.createElement("h3");
this.paragraph = document.createElement("p");
// call the associated methods sequentially
this.constructArticle();
this.constructDiv();
this.constructHeading();
this.constructParagraph();
}
constructArticle() {
this.article.classList.add('team-member');
}
constructDiv() {
this.div.classList.add('img-box');
this.img.src = this.member.src;
this.img.alt = this.member.alt;
this.div.appendChild(this.img);
this.article.appendChild(this.div);
}
constructHeading() {
this.heading3.textContent = this.member.heading3;
this.article.appendChild(this.heading3);
}
constructParagraph() {
this.paragraph.textContent = this.member.paragraph;
this.article.appendChild(this.paragraph);
}
} |
JavaScript | class Transformation {
/**
* @param {Object} options - Options
* @param {string} options.label - LUT Label
* @param {number} options.firstValueMapped - First value mapped by LUT
* @param {number} options.lastValueMapped - Last value mapped by LUT
* @param {lut} options.lut - LUT data
* @param {number} options.intercept - Intercept of linear function
* @param {number} options.slope - Slope of linear function
*/
constructor ({
label,
firstValueMapped,
lastValueMapped,
lut,
intercept,
slope
}) {
if (label === undefined) {
throw new Error('LUT Label is required.')
}
this[_attrs].label = label
if (firstValueMapped === undefined) {
throw new Error('Real World Value First Value Mapped is required.')
}
this[_attrs].firstValueMapped = firstValueMapped
if (lastValueMapped === undefined) {
throw new Error('Real World Value Last Value Mapped is required.')
}
this[_attrs].lastValueMapped = lastValueMapped
if ((intercept === undefined || slope === undefined) && lut === undefined) {
throw new Error(
'Either LUT Data or Real World Value Slope and ' +
'Real World Value Intercept must be provided.'
)
}
if (slope === undefined) {
throw new Error('Real World Value Slope is required.')
}
this[_attrs].slope = slope
if (intercept === undefined) {
throw new Error('Real World Value Intercept is required.')
}
this[_attrs].intercept = intercept
if (lut === undefined) {
throw new Error('LUT Data is required.')
}
this[_attrs].lut = lut
}
} |
JavaScript | class ParameterMapping {
/**
* @param {Object} options
* @param {string} options.uid - Unique tracking identifier
* @param {number} options.number - Mapping Number (one-based index value)
* @param {string} options.label - Mapping Label
* @param {string} options.studyInstanceUID - Study Instance UID of DICOM
* Parametric Map instances
* @param {string} options.seriesInstanceUID - Series Instance UID of DICOM
* Parametric Map instances
* @param {string[]} options.sopInstanceUIDs - SOP Instance UIDs of DICOM
* Parametric Map instances
* @param {string|undefined} options.paletteColorLookupTableUID - Palette
* Color Lookup Table UID
*/
constructor ({
uid,
number,
label,
studyInstanceUID,
seriesInstanceUID,
sopInstanceUIDs,
paletteColorLookupTableUID
}) {
this[_attrs] = {}
if (uid === undefined) {
throw new Error('Unique Tracking Identifier is required.')
} else {
this[_attrs].uid = uid
}
if (number === undefined) {
throw new Error('Mapping Number is required.')
}
this[_attrs].number = number
if (label === undefined) {
throw new Error('Mapping Label is required.')
}
this[_attrs].label = label
if (studyInstanceUID === undefined) {
throw new Error('Study Instance UID is required.')
}
this[_attrs].studyInstanceUID = studyInstanceUID
if (seriesInstanceUID === undefined) {
throw new Error('Series Instance UID is required.')
}
this[_attrs].seriesInstanceUID = seriesInstanceUID
if (sopInstanceUIDs === undefined) {
throw new Error('SOP Instance UIDs are required.')
}
this[_attrs].sopInstanceUIDs = sopInstanceUIDs
this[_attrs].paletteColorLookupTableUID = paletteColorLookupTableUID
Object.freeze(this)
}
/**
* Unique Tracking Identifier
*
* @type string
*/
get uid () {
return this[_attrs].uid
}
/**
* Mapping Number.
*
* @type number
*/
get number () {
return this[_attrs].number
}
/**
* Mapping Label
*
* @type string
*/
get label () {
return this[_attrs].label
}
/**
* Study Instance UID of DICOM Parametric Map instances.
*
* @type string
*/
get studyInstanceUID () {
return this[_attrs].studyInstanceUID
}
/**
* Series Instance UID of DICOM Parametric Map instances.
*
* @type string
*/
get seriesInstanceUID () {
return this[_attrs].seriesInstanceUID
}
/**
* SOP Instance UIDs of DICOM Parametric Map instances.
*
* @type string[]
*/
get sopInstanceUIDs () {
return this[_attrs].sopInstanceUIDs
}
/**
* Palette Color Lookup Table UID.
*
* @type string
*/
get paletteColorLookupTableUID () {
return this[_attrs].paletteColorLookupTableUID
}
} |
JavaScript | class Users {
static get PATH() {
return "/beta/users";
}
static get BETA2_PATH() {
return "/beta2/users";
}
/**
* @param {Credentials} credentials
* credentials to be used when interacting with the API.
* @param {Object} options
* Additional Users options.
*/
constructor(credentials) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.creds = credentials;
this.options = options;
}
/**
* Create a new user.
*
* @param {Object} params - Parameters used when creating the user. See https://ea.developer.nexmo.com/api/conversation#create-a-user for more information.
* @param {function} callback - function to be called when the request completes.
*/
create(params, callback) {
params = JSON.stringify(params);
var config = {
host: this.options.apiHost || "api.nexmo.com",
path: Users.PATH,
method: "POST",
body: params,
headers: {
"Content-Type": "application/json",
Authorization: "Bearer ".concat(this.creds.generateJwt())
}
};
this.options.httpClient.request(config, callback);
}
/**
* Get an existing user.
*
* @param {string|object} query - The unique identifier for the user to retrieve
* or a set of filter parameters for the query. For more information
* see https://ea.developer.nexmo.com/api/conversation#retrieve-all-users
* @param {function} callback - function to be called when the request completes.
*/
get(query, callback) {
var config = {
host: this.options.apiHost || "api.nexmo.com",
path: _Utils.default.createPathWithQuery(Users.BETA2_PATH, query),
method: "GET",
body: undefined,
headers: {
"Content-Type": "application/json",
Authorization: "Bearer ".concat(this.creds.generateJwt())
}
};
this.options.httpClient.request(config, callback);
}
/**
* Get next page of users or conversations for a user.
*
* @param {object} response - The response from a paginated users or conversations list
* see https://ea.developer.nexmo.com/api/conversation#retrieve-all-users
* @param {function} callback - function to be called when the request completes.
*/
next(response, callback) {
if (response._links.next) {
var userId = response._links.next.href.match(/USR-[^/]*/g);
if (userId) {
this.getConversations(userId[0], _Utils.default.getQuery(response._links.next.href), callback);
} else {
this.get(_Utils.default.getQuery(response._links.next.href), callback);
}
} else {
var error = new Error("The response doesn't have a next page.");
callback(error, null);
}
}
/**
* Get previous page of users or conversations for a user.
*
* @param {object} response - The response from a paginated users or conversations list
* see https://ea.developer.nexmo.com/api/conversation#retrieve-all-users
* @param {function} callback - function to be called when the request completes.
*/
prev(response, callback) {
if (response._links.prev) {
var userId = response._links.prev.href.match(/USR-[^/]*/g);
if (userId) {
this.getConversations(userId[0], _Utils.default.getQuery(response._links.prev.href), callback);
} else {
this.get(_Utils.default.getQuery(response._links.prev.href), callback);
}
} else {
var error = new Error("The response doesn't have a previous page.");
callback(error, null);
}
}
/**
* Get an conversations for an existing user.
*
* @param {string} userId - The unique identifier for the user to retrieve conversations for
* @param {function} callback - function to be called when the request completes.
*/
getConversations(userId, query, callback) {
// backwards compatibility to 2.5.4-beta-1. Remove for 3.0.0
if (typeof query === "function") {
callback = query;
query = {};
}
var config = {
host: this.options.apiHost || "api.nexmo.com",
path: _Utils.default.createPathWithQuery("".concat(Users.BETA2_PATH, "/").concat(userId, "/conversations"), query),
method: "GET",
body: undefined,
headers: {
"Content-Type": "application/json",
Authorization: "Bearer ".concat(this.creds.generateJwt())
}
};
this.options.httpClient.request(config, callback);
}
/**
* Update an existing user.
*
* @param {string} userId - The unique identifier for the user to update.
* @param {Object} params - Parameters used when updating the conversation.
* @param {function} callback - function to be called when the request completes.
*/
update(userId, params, callback) {
params = JSON.stringify(params);
var config = {
host: this.options.apiHost || "api.nexmo.com",
path: "".concat(Users.PATH, "/").concat(userId),
method: "PUT",
body: params,
headers: {
"Content-Type": "application/json",
Authorization: "Bearer ".concat(this.creds.generateJwt())
}
};
this.options.httpClient.request(config, callback);
}
/**
* Deleta an existing user.
*
* @param {string} userId - The unique identifier for the user to delete.
* @param {function} callback - function to be called when the request completes.
*/
delete(userId, callback) {
var config = {
host: this.options.apiHost || "api.nexmo.com",
path: "".concat(Users.PATH, "/").concat(userId),
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer ".concat(this.creds.generateJwt())
}
};
this.options.httpClient.request(config, callback);
}
} |
JavaScript | class Reticle extends THREE.Object3D {
/**
* @param {XRSession} xrSession
* @param {THREE.Camera} camera
*/
constructor(xrSession, camera) {
super();
this.loader = new THREE.TextureLoader();
let geometry = new THREE.RingGeometry(0.1, 0.11, 24, 1);
let material = new THREE.MeshBasicMaterial({
color: 0xffffff
});
// Orient the geometry so its position is flat on a horizontal surface
geometry.applyMatrix(new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(-90)));
this.ring = new THREE.Mesh(geometry, material);
geometry = new THREE.PlaneBufferGeometry(0.15, 0.15);
// Orient the geometry so its position is flat on a horizontal surface,
// as well as rotate the image so the anchor is facing the user
geometry.applyMatrix(new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(-90)));
geometry.applyMatrix(new THREE.Matrix4().makeRotationY(THREE.Math.degToRad(0)));
material = new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0
});
this.icon = new THREE.Mesh(geometry, material);
// Load the anchor texture and apply it to our material
// once loaded
this.loader.load('../common/Anchor.png', texture => {
this.icon.material.opacity = 1;
this.icon.material.map = texture;
});
this.add(this.ring);
this.add(this.icon);
this.session = xrSession;
this.visible = false;
this.camera = camera;
}
/**
* Fires a hit test in the middle of the screen and places the reticle
* upon the surface if found.
*
* @param {XRCoordinateSystem} frameOfRef
*/
async update(frameOfRef) {
this.raycaster = this.raycaster || new THREE.Raycaster();
this.raycaster.setFromCamera({
x: 0,
y: 0
}, this.camera);
const ray = this.raycaster.ray;
const origin = new Float32Array(ray.origin.toArray());
const direction = new Float32Array(ray.direction.toArray());
try {
const hits = await this.session.requestHitTest(origin,
direction,
frameOfRef);
if (hits.length) {
const hit = hits[0];
const hitMatrix = new THREE.Matrix4().fromArray(hit.hitMatrix);
// Now apply the position from the hitMatrix onto our model
this.position.setFromMatrixPosition(hitMatrix);
DemoUtils.lookAtOnY(this, this.camera);
this.visible = true;
}
} catch(e) {
console.log(e)
}
}
} |
JavaScript | class GLPKSolver {
static _generateProblemDescription(gapInstance) {
var model = "Minimize\n";
var n_agents = gapInstance.getAgentsNumber();
var n_jobs = gapInstance.getJobsNumber();
model += "obj: ";
for (let agent = 0; agent < n_agents; agent++)
for (let job = 0; job < n_jobs; job++) {
let cost = gapInstance.getCost(agent, job);
model += "+ " + cost + "x" + (agent * n_jobs + job);
}
model += "\nSubject To\ncap: ";
for (let job = 0; job < n_jobs; job++) {
for (let agent = 0; agent < n_agents; agent++){
model += "+ x" + (agent * n_jobs + job);
}
model += " = 1\n";
}
for (let agent = 0; agent < n_agents; agent++) {
for (let job = 0; job < n_jobs; job++) {
let res = gapInstance.getResourcesConsumption(agent, job);
model += "+ " + res + " x" + (agent * n_jobs + job);
}
model += " <= " + gapInstance.getResourcesLimit(agent) + "\n";
}
model += "Bounds\n";
for (let agent = 0; agent < n_agents; agent++) {
for (let job = 0; job < n_jobs; job++) {
model += "0 <= x" + (agent * n_jobs + job) + " <= 1\n";
}
}
model += "Generals\n";
for (let agent = 0; agent < n_agents; agent++) {
for (let job = 0; job < n_jobs; job++) {
model += "x" + (agent * n_jobs + job) +"\n";
}
}
model += "End\n";
return model;
}
static solve(text, onDone) {
var gapInstance = JSON.parse(text);
Object.setPrototypeOf(gapInstance, GAPInstance.prototype);
var bestCost = Infinity;
GLPKSolver.job = new Worker("js/GLPK/GLPKSolverWorker.js");
GLPKSolver.job.onmessage = function (e) {
var obj = e.data;
switch (obj.action) {
case 'log':
//console.log(obj.message);
//bestCost = Math.min(bestCost, obj.message);
//onMessage(obj.message);
//log(obj.message);
break;
case 'done':
console.log(obj.result);
onDone(GLPKSolver._getCost(gapInstance, obj.result));
stop();
//log(JSON.stringify(obj.result));
break;
}
};
GLPKSolver.job.postMessage({
action: 'load',
data: GLPKSolver._generateProblemDescription(gapInstance),
mip: false
});
}
static stop() {
if (GLPKSolver.job !== null)
GLPKSolver.job.terminate();
GLPKSolver.job = null;
}
static _getCost(gapInstance, solution) {
var ret = 0;
var n_agents = gapInstance.getAgentsNumber();
var n_jobs = gapInstance.getJobsNumber();
for (let agent = 0; agent < n_agents; agent++)
for (let job = 0; job < n_jobs; job++) {
let cost = gapInstance.getCost(agent, job);
let variable = "x" + (agent * n_jobs + job);
ret += solution[variable] * cost;
}
return ret;
}
} |
JavaScript | class Modulator extends Transform {
static createTransformStream(){
return new this(...arguments);
}
/**
* @param {object} options
* @param {array} options.frequencies - Frequencies used to encode a signal.
* @param {string='32f'} options.bitDepth - The bit-depth to output. Defaults to 32f.
* @param {number} options.sampleRate - The sample rate of the signal.
* @param {number} options.samplesPerSymbol - The number of samples used to encode each symbol.
* @param {number} options.sweep - The number of samples where a sweep will occur between frequency changes.
*/
constructor(options={}){
super();
this.options = options;
this.mixer = new Mixer();
this.oscillators = this.mixer.sources;
options.bitDepth = options.bitDepth || DEFAULT_BIT_DEPTH;
options.frequencies = options.frequencies || DEFAULT_FREQUENCIES;
options.samplesPerSymbol = options.samplesPerSymbol || DEFAULT_SAMPLES_PER_SYMBOL;
this.addOscillator({
frequency: options.frequencies[0],
sampleRate: options.sampleRate,
amplitude: options.amplitude,
sweep: options.sweep || options.ease
});
}
/**
* A hook for modulating the oscillator. Override to provide your own encoding logic.
* The built-in function does extremely basic encoding, modulating bits into two distinct frequencies.
* @param {*} value - A value or set of values to be used to modulate the signal.
*/
willModulate(value){
// 🛠️ Extend me!
const { frequencies } = this.options,
modulate = this.modulate.bind(this);
if(value === 1) modulate(0, frequencies[1]);
if(value === 0) modulate(0, frequencies[0]);
}
/**
* Adds an oscillator to the modulator. Takes an options object or an Oscillator instance directly.
* @param {object|Oscillator} options
* @param {number} options.frequency - The starting frequency of the oscillator. Defaults to 0.
* @param {number} options.sampleRate - The sample rate of the oscillator. Defaults to 44100.
* @param {number} options.amplitude - The stating amplitude of the oscillator. Defalts to 1.
* @param {number} options.sweep - The amount of sweep or "ease" between frequency and amplitude changes. 1 means full-sweep and 0 means no sweep. Defaults to 0.001 to prevent noise artifacts.
* @returns {Soundrive.Oscillator}
*/
addOscillator(options={}){
const mixer = this.mixer;
let oscillator;
if(options.constructor === Oscillator) {
oscillator = options;
} else {
oscillator = Oscillator.create({
frequency: {
value: options.frequency || 0,
ease: options.sweep || DEFAULT_SWEEP
},
sampleRate: options.sampleRate || DEFAULT_SAMPLE_RATE,
amplitude: {
value: options.amplitude || 1,
ease: options.sweep || DEFAULT_SWEEP
}
});
}
this.mixer.mix(oscillator);
return oscillator;
}
/**
* Removes an oscillator from the modulator.
* @param {number|Soundrive.Oscillator} oscillator - An oscillator object or the index of an oscillator to be removed.
*/
removeOscillator(oscillator){
const mixer = this.mixer,
sources = mixer.sources;
let index;
if(oscillator > -1) {
index = oscillator;
} else {
index = sources.indexOf(oscillator);
}
mixer.sources.splice(index, 1);
}
/**
* Perform an oscillation for the specified samplesPerSymbol, writing
* samples to `this.samples`. Always use this method to render samples
* after you have modulated the signal(i.e. changed the frequency
* of an oscillator).
*/
oscillate(){
const samples = this.samples,
mixer = this.mixer,
{ samplesPerSymbol } = this.options;
let n = 0;
while(n<samplesPerSymbol) samples[this.cursor] = mixer.process(), n++, this.cursor++;
}
/**
* Modulates the frequency of an oscillator.
* @param {number|Soundrive.Oscillator} oscillator - An oscillator index or object to be modulated.
* @param {number} frequency - A target frequency to modulate to.
* @param {number} amplitude - A target amplitude to modulate to.
*/
modulate(oscillator, frequency, amplitude){
if(oscillator > -1) oscillator = this.oscillators[oscillator];
if(frequency) oscillator.changeFrequency(frequency);
if(amplitude) oscillator.changeAmplitude(frequency);
this.oscillate();
}
/**
* Preprocess input chunks into a format that the modulator
* will iterate over. Built-in function will return an
* array representing bits. You can override this function to return
* anything that is iterable, so long as it's something
* that willModulate() will understand.
*
* Yes, you can even return a string if that's what floats
* your boat.
*
* Why not just do this in willModulate? Well, _transform()
* needs to know the number of individual symbols being encoded
* in order to output the right number of audio samples.
*
* @param {Uint8Array} bytes
*/
preprocess(bytes){
return new Uint1Array(bytes.buffer);
}
_transform(chunk, encoding, next){
const bytes = new Uint8Array(chunk),
symbols = this.preprocess(bytes),
len = symbols.length,
{ frequency,
deviation,
samplesPerSymbol,
bitDepth } = this.options,
samples = new Float32Array(len * samplesPerSymbol * 2),
willModulate = this.willModulate.bind(this);
this.samples = samples;
this.cursor = 0;
let i = 0;
while(i<len) willModulate(symbols[i]), i++;
const output = (bitDepth == '32f' || bitDepth == '32') ? samples : convertBitDepth(samples, '32f', bitDepth);
// 👆 Don't write a new array of converted bit depths if our samples already match the bit depth specified.
// We're going with 32 bit depth because 64 bit input from mic hardware doesn't seem common.
this.push(new Buffer(output.buffer)), next();
}
} |
JavaScript | class ScrollIntoView extends React.Component {
static propTypes = {
children: PropTypes.node,
id: PropTypes.string,
}
constructor(props) {
super(props)
hashFragment = props.id
}
componentDidMount() {
scroll()
}
componentDidUpdate() {
scroll()
}
render() {
return this.props.children || null
}
} |
JavaScript | class HashLink extends React.Component {
static propTypes = {
children: PropTypes.node,
to: PropTypes.oneOfType([
PropTypes.string,
PropTypes.shape({
pathname: PropTypes.string,
search: PropTypes.string,
hash: PropTypes.string,
state: PropTypes.object,
}),
]),
}
handleClick = () => {
reset()
const { to } = this.props
if (isString(to)) {
hashFragment = to.split('#').slice(1)[0]
} else if (isObject(to) && isString(to.hash)) {
hashFragment = to.hash.slice(1)
}
if (hashFragment) {
scroll()
}
}
render() {
const { children, ...props} = this.props
return (
<Link {...props} onClick={this.handleClick}>
{children}
</Link>
)
}
} |
JavaScript | class StartSpeechSynthesisTaskCommand extends smithy_client_1.Command {
// Start section: command_properties
// End section: command_properties
constructor(input) {
// Start section: command_constructor
super();
this.input = input;
// End section: command_constructor
}
/**
* @internal
*/
resolveMiddleware(clientStack, configuration, options) {
this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const clientName = "PollyClient";
const commandName = "StartSpeechSynthesisTaskCommand";
const handlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog: models_0_1.StartSpeechSynthesisTaskInput.filterSensitiveLog,
outputFilterSensitiveLog: models_0_1.StartSpeechSynthesisTaskOutput.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
}
serialize(input, context) {
return Aws_restJson1_1.serializeAws_restJson1StartSpeechSynthesisTaskCommand(input, context);
}
deserialize(output, context) {
return Aws_restJson1_1.deserializeAws_restJson1StartSpeechSynthesisTaskCommand(output, context);
}
} |
JavaScript | class SendMultipartInterceptor extends Interceptor {
static get name() {
return 'transport-send-multipart';
}
async receive(ctx) {
const request = {
info: {
request: ctx.request
},
payload: ctx.req
};
const newMessage = transformMessageToRequestMessage(request);
const response = await this.connected.receive(newMessage, ctx);
if (response.status === 200) {
ctx.set('content-type', response.headers._headers['content-type'][0]);
return unpackToMessage(response.body, {});
} else {
throw new Error(`Error in connection. Status = ${response.status}`);
}
}
} |
JavaScript | class ReceiveMultipartInterceptor extends Interceptor {
static get name() {
return 'transport-receive-multipart';
}
get type() {
return ReceiveMultipartInterceptor.name;
}
async receive(ctx) {
// only parse 'application/json'
if (
ctx.method === 'POST' &&
ctx.req &&
ctx.request.header['content-type'].startsWith('multipart/form-data')
) {
const value = await unpackToMessage(ctx.req, this.connected.receive);
if (value && value.info) {
ctx.body = transformMessageToRequestMessage(value);
}
}
return this.connected.receive(ctx);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.