language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Fissure extends WorldstateObject {
/**
* @param {Object} data The fissure data
* @param {Object} deps The dependencies object
* @param {Translator} deps.translator The string translator
* @param {TimeDateFunctions} deps.timeDate The time and date functions
* @param {string} deps.locale Locale to use for translations
*/
constructor(data, { translator, timeDate, locale }) {
super(data, { timeDate });
/**
* The time and date functions
* @type {TimeDateFunctions}
* @private
*/
this.timeDate = timeDate;
Object.defineProperty(this, 'timeDate', { enumerable: false, configurable: false });
/**
* The node where the fissure has appeared
* @type {string}
*/
this.node = translator.node(data.Node, locale);
/**
* The fissure mission type
* @type {string}
*/
this.missionType = data.MissionType
? translator.missionType(data.MissionType, locale)
: translator.nodeMissionType(data.Node, locale);
/**
* The fissure mission type key
* @type {string}
*/
this.missionKey = data.MissionType
? translator.missionType(data.MissionType)
: translator.nodeMissionType(data.Node);
/**
* The faction controlling the node where the fissure has appeared
* @type {string}
*/
this.enemy = translator.nodeEnemy(data.Node, locale);
/**
* Faction enum for the faction controlling the node where the fissure has appeared
* @type {string}
*/
this.enemyKey = translator.nodeEnemy(data.Node);
/**
* The node key where the fissure has appeared
* @type {string}
*/
this.nodeKey = translator.node(data.Node);
/**
* The fissure's tier
* @type {string}
*/
this.tier = translator.fissureModifier(data.Modifier || data.ActiveMissionTier, locale);
/**
* The fissure's tier as a number
* @type {number}
*/
this.tierNum = translator.fissureTier(data.Modifier || data.ActiveMissionTier, locale);
/**
* The date and time at which the fissure appeared
* @type {Date}
*/
this.activation = timeDate.parseDate(data.Activation);
/**
* The date and time at which the fissure will disappear
* @type {Date}
*/
this.expiry = timeDate.parseDate(data.Expiry);
/**
* Whether or not this is expired (at time of object creation)
* @type {boolean}
*/
this.expired = this.getExpired();
/**
* ETA string (at time of object creation)
* @type {String}
*/
this.eta = this.getETAString();
/**
* Whether or not this fissure corresponds to a RailJack Void Storm
* @type {Boolean}
*/
this.isStorm = !!data.ActiveMissionTier;
}
/**
* Get whether or not this deal has expired
* @returns {boolean}
*/
getExpired() {
return this.timeDate.fromNow(this.expiry) < 0;
}
/**
* Get a string representation of how long the void fissure will remain active
* @returns {string}
*/
getETAString() {
return this.timeDate.timeDeltaToString(this.timeDate.fromNow(this.expiry));
}
/**
* Returns a string representation of the fissure
* @returns {string}
*/
toString() {
return `[${this.getETAString()}] ${this.tier} fissure at ${this.node} - ${this.enemy} ${this.missionType}`;
}
} |
JavaScript | class Prolink {
constructor(element) { // click = former prolink
this.element = element;
this.selection = this.getData('selection', null); // compulsory
// todo. Why is this a case?
if (typeof selection === 'number') {
this.selection = this.selection.toString();
}
}
showDomain() {} //etc.
getData(key, blank) { //data attribute
// blank => value (return that) or null (raise error) or undefined (tolerate)
const value = this.element.dataset[key];
if (value !== undefined) {return value} // present
else if (blank === null) {throw `Expected value for data-${key}`;} // raise
else {return blank} // tolerate
}
get target () {
let target = getData('target');
if (target !== undefined) {return target}
else if (this.element.hasAttribute('href')) {
target = this.element.getAttribute('href').replace('#', '');
if (target === '') {return 'viewport'}
else {return target}
}
else {return 'viewport'}
}
get numberAlts() {
let i = 1;
while (this.getData('selection-alt' + i) !== undefined) {
i++;
}
return i - 1;
}
getMultiselection() {
// range(1, this.numberAlts() )
const range = [...Array(this.numberAlts()).keys()].map(i => i + 1);
return range.map(i => {
let f = this.getData('focus-alt' + i, 'residue');
//residue is the only focus mode that will work as intended...
let c = this.getData('color-alt' + i, NGL.specialOps.colorDefaults[f]);
return [f, this.getData('selection-alt' + i, null), c]
});
}
static enableDOMProlinks() {
// still requires $.prototype.protein function. protein is listener. prolink is on click
//activate prolinks
$('[data-toggle="protein"]:not([role="NGL"])').protein();
//activate viewport
$('[role="NGL"],[role="proteinViewport"],[role="proteinviewport"],[role="protein_viewport"]').viewport();
}
} |
JavaScript | class PrecomputeReactRenderer {
constructor(reactClass, el, loggit, options = {}) {
this.reactClass = reactClass;
this.el = el;
this.loggit = loggit;
this.options = options;
this.optimizer = options.optimizer;
this._loop = this._loop.bind(this);
this._lastCompute = {};
this._rootComponent = null;
this.timer = new Timer('PrecomputeReactRenderer.render', {
logFn: this.logMsg.bind(this)
});
}
logMsg(...params) {
// console.log(...params);
}
start() {
this._wasDestroyed = false;
this._isDirty = true;
this._loop();
}
notify() {
this._isDirty = true;
}
destroy() {
// this._rootComponent = null;
this._wasDestroyed = true;
return undefined;
}
_loop() {
if (this._wasDestroyed) return;
if (this._isDirty) {
this.timer.time(() => {
this._render();
});
this._isDirty = false;
}
window.requestAnimationFrame(this._loop);
}
// additional API for optimizer/renderer cooperation
// we're trying to improve over naive top-down rendering
notifyAboutCompute(component, computations, computedValues) {
const reactNodeId = ReactInterpreter.nodeId(component);
this.logMsg('PrecomputeReactRenderer#notifyAboutCompute', reactNodeId, computedValues);
this._lastCompute[reactNodeId] = {computedValues}
}
// instead of top-down rendering, we'll walk the tree ourselves, calling
// render as we need to when a copmutedValue has changed, only in order to
// discover lower branches of the tree.
_render() {
this.logMsg('PrecomputeReactRenderer#render');
if (!this._rootComponent) {
return this._initialRender();
}
// discover what parts of the tree need to be rendered.
const dirtyComponents = this._findDirtyComponents(this._rootComponent);
// console.info('PrecomputeReactRenderer:dirtyComponents:', dirtyComponents);
// do something about it to update components.
// could use heuristics here to batch further.
// we could also optimize this if child components under a 'dirty' component
// end up computing the same data for their component. that's an additional
// step, where we essentially want to short-circuit like `shouldComponentUpdate`.
// could work by setState into each component, might be straightforward.
dirtyComponents.forEach((dirtyComponent) => {
this.logMsg('PrecomputeReactRenderer:forceUpdate', dirtyComponent);
dirtyComponent.forceUpdate();
});
}
// This is important since it also collects the
// information about compute for optimizing in
// subsequent passes.
_initialRender() {
this._rootComponent = React.render(
<this.reactClass loggit={this.loggit} />,
this.el
);
}
// Computes and checks whether value changed and we should render.
_shouldRender(component) {
const reactNodeId = ReactInterpreter.nodeId(component);
const lastCompute = this._lastCompute[reactNodeId];
const computations = ReactInterpreter.computations(component);
this.logMsg('computations:', computations);
if (_.isEmpty(computations)) {
return false;
}
// immutability would help here
const prevComputedValues = lastCompute.computedValues || {};
const nextComputedValues = this.optimizer.compute(computations);
this.logMsg('prev:', prevComputedValues, 'next:', nextComputedValues);
const shouldRender = !_.isEqual(prevComputedValues, nextComputedValues);
this.logMsg('shouldRender:', shouldRender);
return shouldRender;
}
// this is a little slipperty, using the loggit seam to make calls
// to the optimizer that aren't tracked.
_findDirtyComponents(component) {
const reactNodeId = ReactInterpreter.nodeId(component);
this.logMsg('PrecomputeReactRenderer#_findDirtyComponents', reactNodeId);
// don't have to render that component if none of its data
// has changed. but we do have to keep walking the tree since
// child components might compute something different (ie, it's not
// really top-down at all anymore).
const shouldRender = this._shouldRender(component);
if (shouldRender) {
// we need to render the rest of the tree under this component, since
// its data has changed and we can't know the effects on the react component
// tree. this is where the strength of writing plain code in `render` hurts,
// since we can inspect further inside that function to do any optimizations.
//
// return this node and everythign under it as dirty.
this.logMsg('PrecomputeReactRenderer.shouldRender', reactNodeId);
return [component];
}
// we don't need to render this node, it's all set, so the next step
// is to descend into its children. this reaches into react internals,
// so those bits are factored out into ReactInterpreter.
// this recurs through the tree.
const childComponents = ReactInterpreter.childComponents(component);
return _.flatten(childComponents.map((childComponent) => {
return this._findDirtyComponents(childComponent);
}));
}
} |
JavaScript | class Stack {
constructor() {
this.stack = [];
// First In First Out
// front --> Array[] <-- end
}
// **** METHODS ****
// adds to the [] <-- end of stack array
add(value) {
this.stack.push(value);
}
// removes from front --> [] of stack array
remove() {
return this.stack.shift();
}
size() {
return this.stack.length;
}
} |
JavaScript | class Queue {
constructor() {
this.queue = [];
// Last In First Out
// end --> [] <-- front
}
// **** METHODS ****
// ADDS to the [] <-- front of queue array
enqueue(value) {
this.queue.push(value);
}
// REMOVES from the [] <-- front of queue array
dequeue() {
return this.queue.pop();
}
size() {
return this.queue.length;
}
} |
JavaScript | class Model {
class() {
return "Model";
}
constructor(dbName) {
// Model name, must be the same as the IDB store name
this.dbName = dbName;
// Lazy load model primary key
this.id = -1;
// Lazy loaded model data
this.data = undefined;
}
/**
* Load model from cache or API with id
* @param state State to access
* @throws {CheckFailedError} On argument checks fail
*/
load(state) {
if (state.db.get()[this.dbName] === undefined) {
throw new Error(`No IndexedDB collection with name of "${this.dbName}"`);
}
if (this.id === -1) {
throw new Error("Can not load model with no id");
}
checkAndThrow(arguments, {typ: "State"});
var collection = state.db.get()[this.dbName];
collection.get(this.id)
.then((model) => {
console.log("ok", model);
})
.catch((err) => {
console.log("err", err);
});
}
} |
JavaScript | class CampaignView {
constructor(){
}
/**
* Returns HTML for the 'campaign index' screen
* @param {Array.<Campaign>} campaigns An array of campaign objects
* @return {String} The HTML string for display
*/
getIndex(campaigns) {
let campaignHTML = `${getBreadcrumbs('campaign_index')}
<h2>Your Campaigns</h2>`;
campaignHTML += `<div class="row">
<div class='column'>
<button id='campaign_new'>Add New Campaign</button>
</div>
</div>
<div class="row">
<div class='column'>
<hr />
</div>
</div>
<div class="row">
`;
// dont start at zero to avoid modulus division funnyness
for(let i = 1; i < campaigns.length + 1; i++) {
campaignHTML += `<div class="column">
<p>${campaigns[i -1].name}</p>
<p>${campaigns[i -1].description}</p>
<button class='campaign_show' data-id='${campaigns[i -1].campaignID}'>View Campaign</button>
</div>
`;
if (i % 3 === 0) {
campaignHTML += `</div><hr /><div class="row">`;
}
}
campaignHTML += `</div></div>`;
return campaignHTML;
}
/**
* Returns HTML for the 'new campaign' screen
* @return {String} The HTML string for display
*/
new() {
return `${getBreadcrumbs('campaign_new')}
<h1>New Campaign</h1>
<p>Create a new campaign<p>
${this.form()}
`;
}
/**
* Returns HTML for the 'new campaign' screen. If no campaign is passed an
* empty object is generated.
* @param {Campaign} [campaign] A campaign object
* @return {String} The HTML string for display
*/
form(campaign = new Campaign()) {
let exists = campaign.name !== undefined ? true : false;
let html = `<form name='form_campaign_new'>
<label for='name'>Campaign Name</label>
<input name='name' id='name' type="text" autofocus required
value="${exists ? campaign.name : ''}"
/>
<label for='description'>Description</label>
<textarea name='description' required
id='description'>${exists ? campaign.description : ''}</textarea>
<div class="half-width">
<label for='expiry'>Expiry Date</label>
<input name='expiry' id='expiry' type='date' required
value="${exists ? convertDateForInput(campaign.expiry) : ''}"/>
</div>
<div class="half-width second">
<label for='dailyPosts'>Daily Posts</label>
<input name='dailyPosts' id='dailyPosts' type='number' min='0'
required max='10' value='${exists ? campaign.dailyPosts : 1}'/>
</div>
<button id="${!exists ? 'campaign_save' : 'campaign_save_edit'}"
data-id="${campaign.campaignID}">Save</button>
<button id="${!exists ? 'campaign_index' : ''}"
class="${exists ? 'campaign_show' : ''} danger"
data-id="${campaign.campaignID}">Cancel</button>
</form>
`;
return html;
}
/**
* Returns HTML for the 'show campaign' screen
* @param {Campaign} campaign A Campaign object to generate html for
* @return {String} The HTML string for display
*/
show(campaign) {
let date = convertDateToLocale(campaign.expiry);
return `${getBreadcrumbs('campaign_show')}
<h2 id="name">${campaign.name}</h2>
<p>${campaign.description}</p>
<div class="row stat-container">
<div class="column stats">
<span>${campaign.dailyPosts}</span>
<span>Daily Posts</span>
</div>
<div class="column stats">
<span>${campaign.buckets.length}</span>
<span class="green">Buckets</span>
</div>
<div class="column stats">
<span>${campaign.getNumberOfPosts()}</span>
<span class="purple">Posts</span>
</div>
<div class="column stats">
<span>${date}</span>
<span class="orange">Expiry</span>
</div>
</div>
<div class="row">
<div class="column">
<button id="campaign_edit" data-campaignid="${campaign.campaignID}">Edit Campaign</button>
<button id="bucket_new" data-campaignid="${campaign.campaignID}">Add Bucket</button>
<button id="campaign_delete" data-campaignid="${campaign.campaignID}" class="danger">Delete Campaign</button>
</div>
</div>
<div class="row">
<div class="column">
<h3>Campaign Buckets</h3>
</div>
</div>
${app.bucketView.bucketList(campaign.buckets)}
`;
}
/**
* Returns HTML for the 'edit campaign' screen
* @param {Campaign} campaign - A Campaign object to generate html for
* @return {String} The HTML string for display
*/
edit(campaign) {
return `${getBreadcrumbs('campaign_edit')}
<h2>Edit: ${campaign.name} campaign</h2>
<p>Update campaign details<p>
${this.form(campaign)}`;
}
} |
JavaScript | class CategoryButton extends PureComponent {
static propTypes = {
category: PropTypes.object.isRequired,
onCategoryClick: PropTypes.func.isRequired,
}
componentWillMount() {
this.state = { isActive: false }
}
onClick = () => {
const { category, onCategoryClick } = this.props
this.setState({ isActive: !this.state.isActive })
onCategoryClick(category.get('id'))
}
render() {
const { category } = this.props
const { isActive } = this.state
return (
<button
onClick={this.onClick}
className={classNames(`${categoryLinkStyle}`, { isActive })}
style={{ backgroundImage: `url("${category.getIn(['tileImage', 'large', 'url'])}")` }}
>
<span className={categoryLinkTextStyle}>
{isActive ? <CheckIconSM /> : null}
{category.get('name')}
</span>
</button>
)
}
} |
JavaScript | class Bar{
//Defining Bar
constructor(w){
//W is the weight,
this.W = w
this.H = w*20
//H is height for display, based on W [not technically required, but still nice]
}
} |
JavaScript | class SshPublicKey {
/**
* Create a SshPublicKey.
* @member {string} [path] Specifies the full path on the created VM where
* ssh public key is stored. If the file already exists, the specified key is
* appended to the file. Example: /home/user/.ssh/authorized_keys
* @member {string} [keyData] SSH public key certificate used to authenticate
* with the VM through ssh. The key needs to be at least 2048-bit and in
* ssh-rsa format. <br><br> For creating ssh keys, see [Create SSH keys on
* Linux and Mac for Linux VMs in
* Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-mac-create-ssh-keys?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json).
*/
constructor() {
}
/**
* Defines the metadata of SshPublicKey
*
* @returns {object} metadata of SshPublicKey
*
*/
mapper() {
return {
required: false,
serializedName: 'SshPublicKey',
type: {
name: 'Composite',
className: 'SshPublicKey',
modelProperties: {
path: {
required: false,
serializedName: 'path',
type: {
name: 'String'
}
},
keyData: {
required: false,
serializedName: 'keyData',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class ChainMethod {
constructor(
{
methodName,
api,
params = [],
request
}
) {
this.methodName = methodName;
this.api = api;
this.params = params;
this.request = request;
this.run = this.run.bind(this);
}
run(...args) {
const params = {
apiPath: this.api,
methodName: this.methodName,
arguments: args.map((v, i) => ({
name: this.params[i],
value: v
}))
};
return this.request.api(params);
}
} |
JavaScript | class Devicev2Otabinaryurl {
/**
* Constructs a new <code>Devicev2Otabinaryurl</code>.
* @alias module:model/Devicev2Otabinaryurl
* @param binaryKey {String} The object key of the binary
*/
constructor(binaryKey) {
Devicev2Otabinaryurl.initialize(this, binaryKey);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, binaryKey) {
obj['binary_key'] = binaryKey;
}
/**
* Constructs a <code>Devicev2Otabinaryurl</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/Devicev2Otabinaryurl} obj Optional instance to populate.
* @return {module:model/Devicev2Otabinaryurl} The populated <code>Devicev2Otabinaryurl</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new Devicev2Otabinaryurl();
if (data.hasOwnProperty('async')) {
obj['async'] = ApiClient.convertToType(data['async'], 'Boolean');
}
if (data.hasOwnProperty('binary_key')) {
obj['binary_key'] = ApiClient.convertToType(data['binary_key'], 'String');
}
if (data.hasOwnProperty('expire_in_mins')) {
obj['expire_in_mins'] = ApiClient.convertToType(data['expire_in_mins'], 'Number');
}
}
return obj;
}
} |
JavaScript | class CacheServiceWorker {
static async cacheSite(type) {
//let images = await imagens()
return await site
if (type == 'admin')
return await admin
else if(type == 'mobile')
return await mobile
else
return await site
}
static listAdmin() {
//return admin
}
} |
JavaScript | class CardText extends PureComponent {
static propTypes = {
/**
* An optional style to apply.
*/
style: PropTypes.object,
/**
* An optional className to apply.
*/
className: PropTypes.string,
/**
* The children to display.
*/
children: PropTypes.node,
/**
* The component to render as.
*/
component: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
PropTypes.object,
]).isRequired,
/**
* Boolean if this component should be expandable when there is a `CardExpander`
* above it in the `Card`.
*/
expandable: PropTypes.bool,
};
static defaultProps = {
component: 'section',
};
render() {
const {
component: Component,
className,
expandable, // eslint-disable-line no-unused-vars
...props
} = this.props;
return <Component {...props} className={cn('md-card-text', className)} />;
}
} |
JavaScript | class Singleton {
constructor(implementation) {
this.implementation = implementation;
// Note: private[symbol] is enforced by clang-format.
this[_a] = null;
}
create(config, logger) {
if (!this[exports.kSingleton] || config[exports.FORCE_NEW]) {
const s = this[exports.kSingleton];
if (s && s.disable) {
s.disable();
}
this[exports.kSingleton] = new this.implementation(config, logger);
return this[exports.kSingleton];
}
else {
throw new Error(`${this.implementation.name} has already been created.`);
}
}
get() {
if (!this[exports.kSingleton]) {
throw new Error(`${this.implementation.name} has not yet been created.`);
}
return this[exports.kSingleton];
}
exists() {
return !!this[exports.kSingleton];
}
} |
JavaScript | class SvgRenderer {
/**
* Create a quirks-mode SVG renderer for a particular canvas.
* @param {HTMLCanvasElement} [canvas] An optional canvas element to draw to. If this is not provided, the renderer
* will create a new canvas.
* @constructor
*/
constructor (canvas) {
/**
* The canvas that this SVG renderer will render to.
* @type {HTMLCanvasElement}
* @private
*/
this._canvas = canvas || document.createElement('canvas');
this._context = this._canvas.getContext('2d');
/**
* A measured SVG "viewbox"
* @typedef {object} SvgRenderer#SvgMeasurements
* @property {number} x - The left edge of the SVG viewbox.
* @property {number} y - The top edge of the SVG viewbox.
* @property {number} width - The width of the SVG viewbox.
* @property {number} height - The height of the SVG viewbox.
*/
/**
* The measurement box of the currently loaded SVG.
* @type {SvgRenderer#SvgMeasurements}
* @private
*/
this._measurements = {x: 0, y: 0, width: 0, height: 0};
/**
* The `<img>` element with the contents of the currently loaded SVG.
* @type {?HTMLImageElement}
* @private
*/
this._cachedImage = null;
/**
* True if this renderer's current SVG is loaded and can be rendered to the canvas.
* @type {boolean}
*/
this.loaded = false;
}
/**
* @returns {!HTMLCanvasElement} this renderer's target canvas.
*/
get canvas () {
return this._canvas;
}
/**
* @return {Array<number>} the natural size, in Scratch units, of this SVG.
*/
get size () {
return [this._measurements.width, this._measurements.height];
}
/**
* @return {Array<number>} the offset (upper left corner) of the SVG's view box.
*/
get viewOffset () {
return [this._measurements.x, this._measurements.y];
}
/**
* Load an SVG string and normalize it. All the steps before drawing/measuring.
* @param {!string} svgString String of SVG data to draw in quirks-mode.
* @param {?boolean} fromVersion2 True if we should perform conversion from
* version 2 to version 3 svg.
*/
loadString (svgString, fromVersion2) {
// New svg string invalidates the cached image
this._cachedImage = null;
const svgTag = loadSvgString(svgString, fromVersion2);
this._svgTag = svgTag;
this._measurements = {
width: svgTag.viewBox.baseVal.width,
height: svgTag.viewBox.baseVal.height,
x: svgTag.viewBox.baseVal.x,
y: svgTag.viewBox.baseVal.y
};
}
/**
* Load an SVG string, normalize it, and prepare it for (synchronous) rendering.
* @param {!string} svgString String of SVG data to draw in quirks-mode.
* @param {?boolean} fromVersion2 True if we should perform conversion from version 2 to version 3 svg.
* @param {Function} [onFinish] - An optional callback to call when the SVG is loaded and can be rendered.
*/
loadSVG (svgString, fromVersion2, onFinish) {
this.loadString(svgString, fromVersion2);
this._createSVGImage(onFinish);
}
/**
* Creates an <img> element for the currently loaded SVG string, then calls the callback once it's loaded.
* @param {Function} [onFinish] - An optional callback to call when the <img> has loaded.
*/
_createSVGImage (onFinish) {
if (this._cachedImage === null) this._cachedImage = new Image();
const img = this._cachedImage;
img.onload = () => {
this.loaded = true;
if (onFinish) onFinish();
};
const svgText = this.toString(true /* shouldInjectFonts */);
img.src = `data:image/svg+xml;utf8,${encodeURIComponent(svgText)}`;
this.loaded = false;
}
/**
* Serialize the active SVG DOM to a string.
* @param {?boolean} shouldInjectFonts True if fonts should be included in the SVG as
* base64 data.
* @returns {string} String representing current SVG data.
* @deprecated Use the standalone `serializeSvgToString` export instead.
*/
toString (shouldInjectFonts) {
return serializeSvgToString(this._svgTag, shouldInjectFonts);
}
/**
* Synchronously draw the loaded SVG to this renderer's `canvas`.
* @param {number} [scale] - Optionally, also scale the image by this factor.
*/
draw (scale) {
if (!this.loaded) throw new Error('SVG image has not finished loading');
this._drawFromImage(scale);
}
/**
* Draw to the canvas from a loaded image element.
* @param {number} [scale] - Optionally, also scale the image by this factor.
**/
_drawFromImage (scale) {
if (this._cachedImage === null) return;
const ratio = Number.isFinite(scale) ? scale : 1;
const bbox = this._measurements;
this._canvas.width = bbox.width * ratio;
this._canvas.height = bbox.height * ratio;
// Even if the canvas at the current scale has a nonzero size, the image's dimensions are floored pre-scaling.
// e.g. if an image has a width of 0.4 and is being rendered at 3x scale, the canvas will have a width of 1, but
// the image's width will be rounded down to 0 on some browsers (Firefox) prior to being drawn at that scale.
if (
this._canvas.width <= 0 ||
this._canvas.height <= 0 ||
this._cachedImage.naturalWidth <= 0 ||
this._cachedImage.naturalHeight <= 0
) return;
this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
this._context.setTransform(ratio, 0, 0, ratio, 0, 0);
this._context.drawImage(this._cachedImage, 0, 0);
}
} |
JavaScript | class ArgResolver extends Resolver {
/**
* Resolves a piece
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Command}
*/
async piece(arg, currentUsage, possible, repeat, msg) {
const piece = this.client.commands.get(arg) ||
this.client.events.get(arg) ||
this.client.extendables.get(arg) ||
this.client.finalizers.get(arg) ||
this.client.inhibitors.get(arg) ||
this.client.languages.get(arg) ||
this.client.monitors.get(arg) ||
this.client.providers.get(arg);
if (piece) return piece;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'piece');
}
/**
* Resolves a command
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Command}
*/
async command(...args) {
return this.cmd(...args);
}
/**
* Resolves a command
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Command}
*/
async cmd(arg, currentUsage, possible, repeat, msg) {
const command = this.client.commands.get(arg);
if (command) return command;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'command');
}
/**
* Resolves an event
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Event}
*/
async event(arg, currentUsage, possible, repeat, msg) {
const event = this.client.events.get(arg);
if (event) return event;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'event');
}
/**
* Resolves an extendable
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Event}
*/
async extendable(arg, currentUsage, possible, repeat, msg) {
const extendable = this.client.extendables.get(arg);
if (extendable) return extendable;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'extendable');
}
/**
* Resolves a finalizer
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Finalizer}
*/
async finalizer(arg, currentUsage, possible, repeat, msg) {
const finalizer = this.client.finalizers.get(arg);
if (finalizer) return finalizer;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'finalizer');
}
/**
* Resolves a inhibitor
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Inhibitor}
*/
async inhibitor(arg, currentUsage, possible, repeat, msg) {
const inhibitor = this.client.inhibitors.get(arg);
if (inhibitor) return inhibitor;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'inhibitor');
}
/**
* Resolves a monitor
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Monitor}
*/
async monitor(arg, currentUsage, possible, repeat, msg) {
const monitor = this.client.monitors.get(arg);
if (monitor) return monitor;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'monitor');
}
/**
* Resolves a language
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Language}
*/
async language(arg, currentUsage, possible, repeat, msg) {
const language = this.client.languages.get(arg);
if (language) return language;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'language');
}
/**
* Resolves a provider
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {Provider}
*/
async provider(arg, currentUsage, possible, repeat, msg) {
const provider = this.client.providers.get(arg);
if (provider) return provider;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_PIECE', currentUsage.possibles[possible].name, 'provider');
}
/**
* Resolves a message
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {external:Message}
*/
message(...args) {
return this.msg(...args);
}
/**
* Resolves a message
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {external:Message}
*/
async msg(arg, currentUsage, possible, repeat, msg) {
const message = await super.msg(arg, msg.channel);
if (message) return message;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_MSG', currentUsage.possibles[possible].name);
}
/**
* Resolves a user
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {external:User}
*/
mention(...args) {
return this.user(...args);
}
/**
* Resolves a user
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {external:User}
*/
async user(arg, currentUsage, possible, repeat, msg) {
const user = await super.user(arg);
if (user) return user;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_USER', currentUsage.possibles[possible].name);
}
/**
* Resolves a member
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {external:GuildMember}
*/
async member(arg, currentUsage, possible, repeat, msg) {
const member = await super.member(arg, msg.guild);
if (member) return member;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_MEMBER', currentUsage.possibles[possible].name);
}
/**
* Resolves a channel
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {external:Channel}
*/
async channel(arg, currentUsage, possible, repeat, msg) {
const channel = await super.channel(arg);
if (channel) return channel;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_CHANNEL', currentUsage.possibles[possible].name);
}
/**
* Resolves a guild
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {external:Guild}
*/
async guild(arg, currentUsage, possible, repeat, msg) {
const guild = await super.guild(arg);
if (guild) return guild;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_GUILD', currentUsage.possibles[possible].name);
}
/**
* Resolves a role
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {external:Role}
*/
async role(arg, currentUsage, possible, repeat, msg) {
const role = await super.role(arg, msg.guild);
if (role) return role;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_ROLE', currentUsage.possibles[possible].name);
}
/**
* Resolves a literal
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {string}
*/
async literal(arg, currentUsage, possible, repeat, msg) {
if (arg.toLowerCase() === currentUsage.possibles[possible].name.toLowerCase()) return arg.toLowerCase();
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_LITERAL', currentUsage.possibles[possible].name);
}
/**
* Resolves a boolean
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {boolean}
*/
boolean(...args) {
return this.bool(...args);
}
/**
* Resolves a boolean
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {boolean}
*/
async bool(arg, currentUsage, possible, repeat, msg) {
const boolean = await super.boolean(arg);
if (boolean !== null) return boolean;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_BOOL', currentUsage.possibles[possible].name);
}
/**
* Resolves a string
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {string}
*/
string(...args) {
return this.str(...args);
}
/**
* Resolves a string
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {string}
*/
async str(arg, currentUsage, possible, repeat, msg) {
const { min, max } = currentUsage.possibles[possible];
if (this.constructor.minOrMax(arg.length, min, max, currentUsage, possible, repeat, msg, msg.language.get('RESOLVER_STRING_SUFFIX'))) return arg;
return null;
}
/**
* Resolves a integer
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {number}
*/
integer(...args) {
return this.int(...args);
}
/**
* Resolves a integer
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {number}
*/
async int(arg, currentUsage, possible, repeat, msg) {
const { min, max } = currentUsage.possibles[possible];
arg = await super.integer(arg);
if (arg === null) {
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_INT', currentUsage.possibles[possible].name);
}
if (this.constructor.minOrMax(arg, min, max, currentUsage, possible, repeat, msg)) return arg;
return null;
}
/**
* Resolves a number
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {number}
*/
num(...args) {
return this.float(...args);
}
/**
* Resolves a number
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {number}
*/
number(...args) {
return this.float(...args);
}
/**
* Resolves a number
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {number}
*/
async float(arg, currentUsage, possible, repeat, msg) {
const { min, max } = currentUsage.possibles[possible];
arg = await super.float(arg);
if (arg === null) {
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_FLOAT', currentUsage.possibles[possible].name);
}
if (this.constructor.minOrMax(arg, min, max, currentUsage, possible, repeat, msg)) return arg;
return null;
}
/**
* Resolves an argument based on a regular expression
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {string}
*/
async reg(arg, currentUsage, possible, repeat, msg) {
const results = currentUsage.possibles[possible].regex.exec(arg);
if (results !== null) return results;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_REGEX_MATCH', currentUsage.possibles[possible].name, currentUsage.possibles[possible].regex.toString());
}
/**
* Resolves an argument based on a regular expression
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {string}
*/
regex(...args) {
return this.reg(...args);
}
/**
* Resolves an argument based on a regular expression
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {string}
*/
regexp(...args) {
return this.reg(...args);
}
/**
* Resolves a hyperlink
* @param {string} arg This arg
* @param {Object} currentUsage This current usage
* @param {number} possible This possible usage id
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @returns {string}
*/
async url(arg, currentUsage, possible, repeat, msg) {
const hyperlink = await super.url(arg);
if (hyperlink !== null) return hyperlink;
if (currentUsage.type === 'optional' && !repeat) return null;
throw msg.language.get('RESOLVER_INVALID_URL', currentUsage.possibles[possible].name);
}
/**
* Checks min and max values
* @param {number} value The value to check against
* @param {?number} min The minimum value
* @param {?number} max The maxiumum value
* @param {Object} currentUsage The current usage
* @param {number} possible The id of the current possible usage
* @param {boolean} repeat If it is a looping/repeating arg
* @param {external:Message} msg The message that triggered the command
* @param {string} suffix An error suffix
* @returns {boolean}
*/
static minOrMax(value, min, max, currentUsage, possible, repeat, msg, suffix = '') {
if (min && max) {
if (value >= min && value <= max) return true;
if (currentUsage.type === 'optional' && !repeat) return false;
if (min === max) throw msg.language.get('RESOLVER_MINMAX_EXACTLY', currentUsage.possibles[possible].name, min, suffix);
throw msg.language.get('RESOLVER_MINMAX_BOTH', currentUsage.possibles[possible].name, min, max, suffix);
} else if (min) {
if (value >= min) return true;
if (currentUsage.type === 'optional' && !repeat) return false;
throw msg.language.get('RESOLVER_MINMAX_MIN', currentUsage.possibles[possible].name, min, suffix);
} else if (max) {
if (value <= max) return true;
if (currentUsage.type === 'optional' && !repeat) return false;
throw msg.language.get('RESOLVER_MINMAX_MAX', currentUsage.possibles[possible].name, max, suffix);
}
return true;
}
} |
JavaScript | class Queue {
/**
* @constructor
*/
constructor() {
this.queue = [];
}
/**
* Get an item from the queue
* @method get
* @param {number} index - index of the item to be retrieved
* @return {*}
*/
get(index) {
var obj = this.queue[index];
if (obj !== undefined) return obj.content;
}
/**
* Add an item to the queue
* @method add
* @param {*} item - item to be added to the queue
* @return {number} length of the queue
*/
add(item) {
var curObj = { previous: null, content: item, next: null };
var lastObj = null;
var l = this.queue.length;
if (l > 0) {
lastObj = this.queue[l - 1];
lastObj.next = curObj;
curObj.previous = lastObj;
}
this.queue.push(curObj);
return this.queue.length;
}
/**
* Add an array of items to the queue
* @method addArray
* @param {Object} items - array of items to be added to the queue
* @return {number} length of the queue
*/
addArray(items) {
var self = this;
var lastObj = null;
var l = this.queue.length;
var n, curObj, item;
if (l > 0) {
lastObj = this.queue[l - 1];
}
if (items instanceof Array) {
for (n = 0, l = items.length; n < l; n++) {
item = items[n];
curObj = {
previous: lastObj,
content: item,
next: null
};
if (lastObj !== null) {
lastObj.next = curObj;
}
self.queue.push(curObj);
lastObj = curObj;
}
}
return this.queue.length;
}
/**
* Update an item in the queue
* @method update
* @param {number} index - index of the item to be updated
* @param {*} item - new item
* @return {*} item updated
*/
update(index, item) {
var obj = this.queue[index];
if (this.queue.length > 0) {
if (obj !== undefined) {
obj.content = item;
return item;
}
}
}
/**
* Remove an item from the queue
* @method remove
* @param {number} index - index of the item to be removed
* @return {*} item removed
*/
remove(index) {
var obj = this.queue[index];
if (obj !== undefined) {
if (obj.previous !== null) {
obj.previous.next = obj.next;
}
if (obj.next !== null) {
obj.next.previous = obj.previous;
}
this.queue.splice(index, 1);
return obj.content;
}
}
/**
* Iterate all items in the queue
* @method forEach
* @param {function} cb - function(item) callback function that stop the iteration when returning false
*/
forEach(cb) {
if (!types.isFunction(cb)) return;
var obj;
if (this.queue.length > 0) {
obj = this.queue[0];
do {
if (cb.call(this, obj.content) === false) break;
obj = obj.next;
} while (obj !== null);
}
}
/**
* Return the length of the queue
* @method getSize
* @return {number}
*/
getSize() {
return this.queue.length;
}
/**
* Get the first item of the queue
* @method first
* @return {*}
*/
first() {
if (this.queue.length > 0) {
return this.queue[0].content;
}
}
/**
* Get the last item of the queue
* @method last
* @return {*}
*/
last() {
var l = this.queue.length;
if (l > 0) {
return this.queue[l - 1].content;
}
}
/**
* Return all items in the queue
* @method toArray
* @return {Array}
*/
toArray() {
var n, l, array = [];
for (n = 0, l = this.queue.length; n < l; n++) {
array.push(this.queue[n].content);
}
return array;
}
/**
* Serialize the array to JSON
* @method toJSON
* @return {Array}
*/
toJSON() {
return this.toArray();
}
/**
* Get an array slice
* @method getSlice
* @param {number} start - first index of the selection
* @param {number} end - last index of the selection
* @return {Array}
*/
getSlice(start, end) {
var queueLength = this.queue.length;
var array = [];
var n, l;
if (queueLength !== 0 && start <= end) {
n = start < queueLength ? start : queueLength - 1;
l = end < queueLength ? end : queueLength - 1;
for (; n <= l; n++) {
array.push(this.queue[n].content);
}
}
return array;
}
/**
* Remove all items from the array
* @method clear
*/
clear() {
this.queue.length = 0;
}
} |
JavaScript | class Parser {
/**
* @constructor
* @param {Array} tokens List of tokens to parse
*/
constructor(tokens) {
this.tokens = tokens;
this.length = tokens.length;
this.current = 0;
}
/**
* Check if the parser is at the end the list of tokens
* @returns {boolean} true if at the end
*/
end() {
return this.current === this.length;
}
/**
* Retrieve the next symbol without moving the pointer
* @returns {null|Symbol}
*/
peek_symbol() {
return this.end() ? null : this.tokens[this.current];
}
/**
* Retrieve the next token without moving the pointer
* @returns {null|Token}
*/
peek() {
return this.peek_symbol() ? this.peek_symbol().token : null;
}
/**
* Move the pointer to the next token, if there is one
*
* If the first argument is provided, only move the pointer if the tokens match
*
* @param {Token|null} [token] Only advance the pointer if the next token matches this
* @returns {boolean} Whether the pointer was advanced
*/
next(token = null) {
if (this.end() || token && this.peek() !== token) {
return false;
}
++this.current;
return true;
}
/**
* Parse the tokens and return the root node
* @throws {ParseError} if extra content is found at the end of input
* @returns {Node} the Node at the root of the tree
*/
parse() {
if (this.end()) {
throw new InvalidInputError('No input detected');
}
let node = this._parse();
if (!this.end()) {
console.log('tokens: ' + this.tokens);
console.log('pointer: ' + this.current);
throw new InvalidInputError('Expression contains malformed syntax');
}
return node;
}
/**
* Internal parse method to be overridden by subclass
*
* @abstract
* @private
* @returns {Node}
*/
_parse() {
throw new TypeError('_parse() method not implemented');
}
} |
JavaScript | class BotLists extends EventEmitter {
#postRetryAfterTimer = undefined
#autoPostedTimerId = undefined
#autoPostCaches = undefined
/**
* @constructor
* @param {string | void} webhookEndpoint -> Webhook Endpoint for "https://ipaddress:port/webhookEndpoint" to make selective path for Webhook's HTTP Post Request
* @param {Object} botlistData -> Botlists Data as ' { "topgg" : { authorizationToken: "xxx-secrettokenhere-xxx",authorizationValue: "xxx-selfmade-AuthorizationValue-xxx", } } ' for comparing fetching token and Json data from resourcess
* @param {string | number | void | "8080"} listenerPortNumber -> Port Number for Express's App to listen , By Default it listens in 8080 as default HTTP port
* @param {string | number | void | "localhost"} ipAddress -> Ip Adddress as "127.0.0.1" or "www.google.com" | No need to add http or https Protocol , just the domain or IP value for it
* @param {string | void | "https://github.com/SidisLiveYT/discord-botlists"} redirectUrl -> Redirect Url for get Request on Webhook Post Url for making it more cooler , By Default -> Github Repo
*/
constructor(
webhookEndpoint = undefined,
botlistData = undefined,
listenerPortNumber = 8080,
ipAddress = 'localhost',
redirectUrl = 'https://github.com/SidisLiveYT/discord-botlists',
) {
super()
this.webhookEndpoint = webhookEndpoint
this.redirectUrl = redirectUrl
this.ipAddress = ipAddress
this.botlistData = botlistData ?? botlistCache.Botlists
this.listenerPortNumber =
Number.isNaN(listenerPortNumber) &&
Number(listenerPortNumber) > 0 &&
Number(listenerPortNumber) < 65535
? 8080
: Number(listenerPortNumber)
this.expressApp = Express()
this.expressApp.use(
urlencoded({
extended: true,
}),
)
}
/**
* start() -> Starting Webhook for Vote Event Trigger
* @param {string | void} webhookEndpoint Webhook Endpoint for "https://ipaddress:port/webhookEndpoint" to make selective path for Webhook's HTTP Post Request
* @param {string | void | 'https://github.com/SidisLiveYT/discord-botlists'} redirectUrl -> Redirect Url for get Request on Webhook Post Url for making it more cooler , By Default -> Github Repo
* @param {boolean | void | true} eventTrigger -> Event Trigger for console.log() function | By Default = true
* @returns {any} Depends on Incomplete Body or Request , it can return false or complete request.body in Json Format
*/
async start(
webhookEndpoint = undefined,
redirectUrl = 'https://github.com/SidisLiveYT/discord-botlists',
eventTrigger = true,
) {
/**
* Express App listening on a Particular Port for Ignoring other Invalid Requests | For example containers of Pterodactyl Server
*/
this.expressApp.listen(Number(this.listenerPortNumber), () => (eventTrigger
? console.log(
`🎬 "discord-botlists" expressApp is Listening at Port: ${this.listenerPortNumber}`,
)
: undefined))
/**
* @var {apiUrl} -> Apiurl for WebhookEndPoint as for this.expressApp.post() request
*/
const apiUrl = `/${
webhookEndpoint ?? this.webhookEndpoint ?? 'discord-botlists'
}`
eventTrigger
? console.log(
`🎬 Webhook-Server is accepting votes Webhooks at - http://${this.ipAddress}:${this.listenerPortNumber}${apiUrl}`,
)
: undefined
/**
* Redirect Any Request to redirectUrl for skipping Error Message
*/
this.expressApp.get(apiUrl, (request, response) => {
this.emit('request', 'Get-Redirect', request, response, new Date())
response.redirect(redirectUrl ?? this.redirectUrl)
return undefined
})
/**
* Post Request for any Upcoming Webhook Request from /webhook-endpoint
*/
this.expressApp.post(
apiUrl,
(request, response) => new Promise((resolve) => {
try {
this.emit('request', 'Post-Votes', request, response, new Date())
let bodyJson
/**
* parsing Auth Secret Token present in Orignal Webhook page for comparing actual request if its okay
*/
const AuthParsingResults = this.#parseAuthorization(request)
// Invalid or Un-Authorized UnHandShake Request from Server to Client Side
if (!AuthParsingResults && AuthParsingResults === undefined) {
this.emit(
'error',
'UnAuthoization/Invalid-AuOth Code is Detected',
AuthParsingResults,
new Date(),
)
return response.status(400).send({
ok: false,
status: 400,
message: 'Invalid/Un-Authorized Authorization token',
})
}
/**
* if Body went brr.. then Body should be fetched from Stream.<Readable> from request
* Check if any error and send 422 for Incomplete Body
*/
if (!(request.body && Object.entries(request?.body)?.length > 0)) {
return RawBody(request, {}, (error, actualBody) => {
if (error)
return response.status(422).send({
ok: false,
status: 422,
message: 'Malformed Request Received',
})
try {
// Body Json Parsing from Actual Body as in String
bodyJson = JSON.parse(actualBody?.toString('utf8'))
this.emit(
'vote',
AuthParsingResults.name,
{ ...bodyJson },
new Date(),
)
response.status(200).send({
ok: true,
status: 200,
message: 'Webhook has been Received',
})
return resolve({ ...bodyJson })
} catch (err) {
response.status(400).send({
ok: false,
status: 400,
message: 'Invalid Body Received',
})
resolve(false)
}
return false
})
} else bodyJson = JSON.parse(request?.body?.toString('utf8'))
/**
* "vote" event trigger for Event Emitter Category
*/
this.emit(
'vote',
AuthParsingResults?.name,
{ ...bodyJson },
new Date(),
)
response.status(200).send({
ok: true,
status: 200,
message: 'Webhook has been Received',
})
return resolve({ ...bodyJson })
} catch (error) {
response.status(500).send({
ok: false,
status: 500,
message: 'Internal error',
})
resolve(false)
}
return false
}),
)
return this.expressApp
}
/**
* post() -> Posting Stats of the Current Bot to Multiple Botlists mentioned by
* @param {postApiBody} apiBody Api-Body for Posting Data as per params for API requirements and strictly for if required
* @param {boolean | void | true} eventOnPost What if event to be triggered on Post or should be closed
* @param {Object | void } AxioshttpConfigs To Add Proxies to avoid Ratelimit
* @param {boolean | void | false} forcePosting Force Posting and ignoring in-built Ratelimit function | Users can face un-expected ratelimit from API
* @param {Boolean | void | true} IgnoreErrors Boolean Value for Ignoring Request Handling Errors
* @returns {Promise<Boolean>} Booelan Response on success or failure
*/
async poststats(
apiBody = postApiBody,
eventOnPost = true,
AxioshttpConfigs = undefined,
forcePosting = false,
IgnoreErrors = true,
) {
if (
!(
apiBody?.bot_id &&
typeof apiBody?.bot_id === 'string' &&
apiBody?.bot_id?.length > 0
) ||
!(apiBody?.server_count && parseInt(apiBody?.server_count ?? 0) > 0) ||
Object.entries(apiBody)?.length <= 1
)
return void !IgnoreErrors
? this.emit(
'error',
'Failure: Invalid bot_id or server_count is Detected',
apiBody,
new Date(),
)
: undefined
else if (this.#autoPostedTimerId) {
return void !IgnoreErrors
? this.emit(
'error',
'Failure: Auto-Poster is Already in Progress',
this.#autoPostedTimerId,
new Date(),
)
: undefined
} else if (
!forcePosting &&
this.#postRetryAfterTimer &&
(this.#postRetryAfterTimer - new Date().getTime()) / 1000 > 0
) {
return void !IgnoreErrors
? this.emit(
'error',
`Failure: There is a Cooldown on Bot Stats Post Method | Retry After -> "${
(this.#postRetryAfterTimer - new Date().getTime()) / 1000
} Seconds"`,
apiBody,
new Date(),
)
: undefined
}
apiBody = { ...postApiBody, ...apiBody }
apiBody.server_count = parseInt(apiBody?.server_count ?? 0)
apiBody.shard_count =
apiBody?.shard_count &&
typeof apiBody?.shard_count === 'number' &&
parseInt(apiBody?.shard_count) > 0
? parseInt(apiBody?.shard_count)
: undefined
apiBody.shard_id =
apiBody?.shard_id &&
typeof apiBody?.shard_id === 'string' &&
apiBody?.shard_id?.length > 0
? apiBody?.shard_id
: undefined
apiBody.shards =
apiBody?.shards &&
Array.isArray(apiBody?.shards) &&
apiBody?.shards?.length > 0
? apiBody?.shards
: undefined
const Cached = await this.#poststats(
Utils.PostBodyParse(apiBody, this.botlistData),
AxioshttpConfigs ?? undefined,
IgnoreErrors,
)
if (!Cached) return false
else if (eventOnPost) this.emit('posted', Cached, new Date())
return true
}
/**
* autoPoster() -> Auto-osting Stats of the Current Bot to Multiple Botlists mentioned
* @param {postApiBody} apiBody Api-Body for Posting Data as per params for API requirements and strictly for if required
* @param {Object | void} AxioshttpConfigs To Add Proxies to avoid Ratelimit
* @param {number | void} Timer Time in Milli-Seconds to Post at every Interval Gap
* @param {boolean | void} eventOnPost What if event to be triggered on Post or should be closed
* @param {Boolean | void} IgnoreErrors Boolean Value for Ignoring Request Handling Errors
* @returns {NodeJS.Timer} Node Timer Id to Cancel for further purposes
*/
autoPoster(
apiBody = postApiBody,
AxioshttpConfigs = undefined,
Timer = 2 * 60 * 1000,
eventOnPost = true,
IgnoreErrors = true,
) {
if (
!(
apiBody?.bot_id &&
typeof apiBody?.bot_id === 'string' &&
apiBody?.bot_id?.length > 0
) ||
!(apiBody?.server_count && parseInt(apiBody?.server_count ?? 0) > 0) ||
Object.entries(apiBody)?.length <= 1
)
return void this.emit(
'error',
'Failure: Invalid bot_id or server_count is Detected',
apiBody,
new Date(),
)
else if (
!(
Timer &&
!Number.isNaN(Timer) &&
parseInt(Timer) >= 2 * 60 * 1000 &&
parseInt(Timer) <= 24 * 60 * 60 * 1000
)
) {
return void this.emit(
'error',
'Failure: Invalid Timer Value is Detected | Timer should be less than a Day and greater than 2 * 60 * 1000 milliseconds and Value should be in Milli-Seconds or leave undefined for defualt Timer Value',
apiBody,
new Date(),
)
}
if (this.#autoPostedTimerId) {
return void !IgnoreErrors
? this.emit(
'error',
'Failure: Auto-Poster is Already in Progress',
this.#autoPostedTimerId,
new Date(),
)
: undefined
} else if (
this.#postRetryAfterTimer &&
(this.#postRetryAfterTimer - new Date().getTime()) / 1000 > 0
) {
return void !IgnoreErrors
? this.emit(
'error',
`Failure: There is a Cooldown on Bot Stats Post Method | Retry After -> "${
(this.#postRetryAfterTimer - new Date().getTime()) / 1000
} Seconds"`,
apiBody,
new Date(),
)
: undefined
}
apiBody = { ...postApiBody, ...apiBody }
apiBody.server_count = parseInt(apiBody?.server_count ?? 0)
apiBody.shard_count =
apiBody?.shard_count &&
typeof apiBody?.shard_count === 'number' &&
parseInt(apiBody?.shard_count) > 0
? parseInt(apiBody?.shard_count)
: undefined
apiBody.shard_id =
apiBody?.shard_id &&
typeof apiBody?.shard_id === 'string' &&
apiBody?.shard_id?.length > 0
? apiBody?.shard_id
: undefined
apiBody.shards =
apiBody?.shards &&
Array.isArray(apiBody?.shards) &&
apiBody?.shards?.length > 0
? apiBody?.shards
: undefined
return this.#customTimeout(
apiBody,
eventOnPost ?? false,
AxioshttpConfigs,
Timer,
IgnoreErrors,
)
}
/**
* @private
* @param {postApiBody} postData Api-Body for Posting Data as per params for API requirements and strictly for if required
* @param {Object} AxioshttpConfigs Axios HTTP Post Request Config
* @param {Boolean | void | false} IgnoreErrors Boolean Value for Ignoring Request Handling Errors
* @returns {Object | void} Returns success and failure data formated or undefined on failure
*/
async #poststats(
postData,
AxioshttpConfigs = undefined,
IgnoreErrors = false,
) {
if (!postData) return undefined
const AxiosResponse = await Axios.post(
botlistCache?.apiPostUrl,
postData,
AxioshttpConfigs
? Utils.parseHTTPRequestOption(AxioshttpConfigs)
: undefined,
).catch((error) => {
this.emit(
'request',
'Post-Bot-Stats',
undefined,
error?.message,
new Date(),
)
if (error.response?.status > 200 && error.response?.status < 429) {
!IgnoreErrors
? this.emit(
'error',
`Received Response Status Error | Status Code -> ${
error?.response?.status
} Message from API Server : ${
error?.message ?? '<Hidden Message>'
}`,
error?.response?.data ?? error?.message,
new Date(),
)
: undefined
this.#autoPostedTimerId
? this.#customTimeout(
undefined,
undefined,
undefined,
undefined,
IgnoreErrors,
true,
)
: undefined
} else if (error?.response?.status === 429) {
!IgnoreErrors
? this.emit(
'error',
`Received Response Status Error | Status Code -> 429 | Message from API Server : "Ratelimited IP [${
error?.response?.data?.ratelimit_ip ?? '127.0.0.1'
}] and Retry Post Stats After -> ${
parseInt(error?.response?.data?.retry_after) ?? 80
} Seconds"`,
error?.response?.data ?? error?.message,
new Date(),
)
: undefined
this.#postRetryAfterTimer = error?.response?.data?.retry_after
? parseInt(error?.response?.data?.retry_after) * 1000 +
new Date().getTime()
: undefined
this.#autoPostedTimerId
? this.#customTimeout(
undefined,
undefined,
undefined,
undefined,
IgnoreErrors,
true,
parseInt(error?.response?.data?.retry_after ?? 0) * 1000,
)
: undefined
}
return undefined
})
this.emit('request', 'Post-Bot-Stats', undefined, AxiosResponse, new Date())
if (!AxiosResponse) return undefined
else if (AxiosResponse?.status > 200 && AxiosResponse?.status < 429) {
!IgnoreErrors
? this.emit(
'error',
`Received Response Status Error | Status Code -> ${
AxiosResponse?.status
} Message from API Server : ${
AxiosResponse?.data?.message ?? '<Hidden Message>'
}`,
AxiosResponse?.data,
new Date(),
)
: undefined
this.#autoPostedTimerId
? this.#customTimeout(
undefined,
undefined,
undefined,
undefined,
IgnoreErrors,
true,
)
: undefined
} else if (AxiosResponse?.status === 429) {
!IgnoreErrors
? this.emit(
'error',
`Received Response Status Error | Status Code -> 429 | Message from API Server : "Ratelimited IP [${
AxiosResponse?.data?.ratelimit_ip ?? '127.0.0.1'
}] and Retry Post Stats After -> ${
parseInt(AxiosResponse?.data?.retry_after) ?? 80
} Seconds"`,
AxiosResponse?.data,
new Date(),
)
: undefined
this.#postRetryAfterTimer = AxiosResponse?.data?.retry_after
? parseInt(AxiosResponse?.data?.retry_after) * 1000 +
new Date().getTime()
: undefined
this.#autoPostedTimerId
? this.#customTimeout(
undefined,
undefined,
undefined,
undefined,
IgnoreErrors,
true,
parseInt(AxiosResponse?.data?.retry_after) * 1000,
)
: undefined
} else if (
(AxiosResponse?.status === 200 && AxiosResponse?.data) ||
AxiosResponse?.data?.success ||
AxiosResponse?.data?.failure
) {
this.#postRetryAfterTimer = undefined
return Utils.PostResponseParse(
AxiosResponse?.data?.success ?? [],
AxiosResponse?.data?.failure ?? [],
)
}
return undefined
}
/**
*
* @param {postApiBody} apiBody Api-Body for Posting Data as per params for API requirements and strictly for if required
* @param {boolean | void} eventOnPost What if event to be triggered on Post or should be closed
* @param {Object | void} AxioshttpConfigs To Add Proxies to avoid Ratelimit
* @param {number | void} Timer Time in Milli-Seconds to Post at every Interval Gap
* @param {boolean} clearTimeoutBoolean Clear Timedout Boolean for renewing the Auto-Posting Interval
* @param {number | void} extraTime Extra Time in Milli-Seconds for 429 Error Data
* @returns {string | void}
*/
#customTimeout(
apiBody,
eventOnPost,
AxioshttpConfigs,
Timer = 2 * 60 * 1000,
IgnoreErrors = true,
clearTimeoutBoolean = false,
extraTime = 0,
) {
if (apiBody && Timer)
this.#autoPostCaches = {
apiBody,
eventOnPost,
AxioshttpConfigs,
Timer,
IgnoreErrors,
}
if (clearTimeoutBoolean && this.#autoPostedTimerId)
clearTimeout(this.#autoPostedTimerId)
this.#autoPostedTimerId = setInterval(async () => {
const Cached = await this.#poststats(
Utils.PostBodyParse(this.#autoPostCaches?.apiBody, this.botlistData),
this.#autoPostCaches?.AxioshttpConfigs,
this.#autoPostCaches?.IgnoreErrors,
)
if (!Cached) return false
else if (this.#autoPostCaches?.eventOnPost)
this.emit('posted', Cached, new Date())
return undefined
}, this.#autoPostCaches.Timer + extraTime)
return this.#autoPostedTimerId
}
/**
* @private
* @param {JSON} request Axios Request Data from GET-Votes location Function
* @returns {Object | boolean | void} Returns Auth Success Rate or false on failure
*/
#parseAuthorization(request) {
let count = 0
while (count < CacheObjectkeys.length) {
if (
this.botlistData[CacheObjectkeys[count]] &&
(this.botlistData[CacheObjectkeys[count]]?.authorizationValue ||
this.botlistData[CacheObjectkeys[count]]?.authorizationToken) &&
(((this.botlistData[CacheObjectkeys[count]]?.tokenHeadername &&
request.get(
`${this.botlistData[CacheObjectkeys[count]]?.tokenHeadername}`,
)) ??
(botlistCache.Botlists[CacheObjectkeys[count]]?.tokenHeadername &&
request.get(
`${
botlistCache.Botlists[CacheObjectkeys[count]]?.tokenHeadername
}`,
)) ??
request.get('Authorization')) ===
this.botlistData[CacheObjectkeys[count]]?.authorizationValue ||
((this.botlistData[CacheObjectkeys[count]]?.tokenHeadername &&
request.get(
`${this.botlistData[CacheObjectkeys[count]]?.tokenHeadername}`,
)) ??
(botlistCache.Botlists[CacheObjectkeys[count]]?.tokenHeadername &&
request.get(
`${
botlistCache.Botlists[CacheObjectkeys[count]]?.tokenHeadername
}`,
)) ??
request.get('Authorization')) ===
this.botlistData[CacheObjectkeys[count]]?.authorizationToken)
)
return botlistCache.Botlists[CacheObjectkeys[count]]
else ++count
}
return false
}
} |
JavaScript | class CourseController {
/**
* Show a list of all courses.
* GET courses
*
* @param {object} ctx
* @param {Response} ctx.response
* @param {Auth} ctx.auth
*/
async index({
response,
auth
}) {
return await Course.all()
}
/**
* Create/save a new course.
* POST courses
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {Auth} ctx.auth
*/
async store({
request,
response,
auth
}) {
if (!auth.user.id) {
return response.status(401)
}
const data = request.post()
let category = await Category.findOrFail(data['category_id'])
data['category_label'] = category['category']
let type = await Type.findOrFail(data['type_id'])
data['type_label'] = type['type']
let speaker = await Speaker.findOrFail(data['speaker_id'])
data['speaker_label'] = speaker['name']
if (data['base_amount']) {
data['base_amount'] = parseFloat(data['base_amount']).toFixed(2)
}
if (data['discount_amount']) {
data['discount_amount'] = parseFloat(data['discount_amount']).toFixed(2)
}
const course = await Course.create({
...data
})
return course
}
/**
* Display a single course.
* GET courses/:id
*
* @param {object} ctx
* @param {Params} ctx.params
* @param {Response} ctx.response
* @param {Auth} ctx.auth
*/
async show({
params,
response,
auth
}) {
let course = await Course.findOrFail(params.id)
return course
}
/**
* Update course details.
* PUT or PATCH courses/:id
*
* @param {object} ctx
* @param {Params} ctx.params
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {Auth} ctx.auth
*/
async update({
params,
request,
response,
auth
}) {
if (!auth.user.id) {
return response.status(401)
}
const course = await Course.findOrFail(params.id)
const data = request.post()
let category = await Category.findOrFail(data['category_id'])
data['category_label'] = category['category']
let type = await Type.findOrFail(data['type_id'])
data['type_label'] = type['type']
let speaker = await Speaker.findOrFail(data['speaker_id'])
data['speaker_label'] = speaker['name']
course.merge(data)
await course.save()
return course
}
/**
* Save Course image.
* POST courses-image/:id
*
* @param {object} ctx
* @param {Params} ctx.params
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {Auth} ctx.auth
*/
async saveImage({
params,
request,
response,
auth
}) {
if (!auth.user.id) {
return response.status(401)
}
try {
const image = request.file('image', {
types: ['image'],
size: '2mb'
})
await image.move(Helpers.publicPath('img/course'), {
name: `${Date.now()}-${image.clientName}`
})
if (!image.moved()) {
return image.errors()
}
let course = await Course
.query()
.where('id', params.id)
.update({ image_path: `${image.fileName}` })
return course
} catch (err) {
Logger.info(err)
return err
}
}
/**
* Delete a course with id.
* DELETE courses/:id
*
* @param {object} ctx
* @param {Params} ctx.params
* @param {Response} ctx.response
* @param {Auth} ctx.auth
*/
async destroy({
params,
response,
auth
}) {
if (!auth.user.id) {
return response.status(401)
}
const course = await Course.findOrFail(params.id)
await course.delete()
}
/**
* Get courses with name-asc.
* name-asc
*
* @param {object} ctx
* @param {Auth} ctx.request
* @param {Response} ctx.response
*/
async getNameAsc({
auth,
response,
params
}) {
let courses = await Database
.from('courses')
.where({
active: 1
})
.orderBy('name', 'asc')
.paginate(params.pages, params.limit)
return await courses
}
/**
* Get courses with name-asc.
* name-asc
*
* @param {object} ctx
* @param {Auth} ctx.request
* @param {Response} ctx.response
*/
async getNameAscNotActive({
auth,
response,
params
}) {
let courses = await Database
.from('courses')
.where({
active: 0
})
.orderBy('name', 'asc')
.paginate(params.pages, params.limit)
return await courses
}
/**
* Get courses with filters.
*
*
* @param {object} ctx
* @param {Auth} ctx.request
* @param {Response} ctx.response
*/
async getCoursesFilter({
request,
params,
response,
auth
}) {
const filterRequest = request.post()
var filters = {}
var order = 'name'
var orderDirection = 'asc'
var courseName
if (filterRequest.category_id != undefined && filterRequest.category_id != null) {
filters.category_id = filterRequest.category_id
}
if (filterRequest.type_id != undefined && filterRequest.type_id != null) {
filters.type_id = filterRequest.type_id
}
if (filterRequest.speaker_id != undefined && filterRequest.speaker_id != null) {
filters.speaker_id = filterRequest.speaker_id
}
if (filterRequest.name != undefined && filterRequest.name != null) {
courseName = filterRequest.name
}
if (filterRequest.order) {
order = filterRequest.order.field
orderDirection = filterRequest.order.direction
}
let courses = {}
if (courseName) {
courses = await Database
.from('courses')
.where(filters)
.where(Database.raw("UPPER(name)"), 'LIKE', '%' + courseName + '%')
.orderBy(order, orderDirection)
.paginate(params.pages, params.limit)
} else {
courses = await Database
.from('courses')
.where(filters)
.orderBy(order, orderDirection)
.paginate(params.pages, params.limit)
}
return courses
}
/**
* Get courses with highlight.
*
*
* @param {object} ctx
* @param {Auth} ctx.request
* @param {Response} ctx.response
*/
async getHighlight({
auth,
response,
params
}) {
let courses = await Database
.from('courses')
.where({
highlight: 1
})
.where({
active: 1
})
.paginate(params.pages, params.limit)
return await courses
}
/**
* Get courses with recorded.
*
*
* @param {object} ctx
* @param {Auth} ctx.request
* @param {Response} ctx.response
*/
async getRecorded({
auth,
response,
params
}) {
let courses = await Database
.from('courses')
.where({
recorded: 1
})
.where({
active: 1
})
.paginate(params.pages, params.limit)
return await courses
}
async downloadImage({
params,
response
}) {
return response.download(Helpers.publicPath(`img/course/${params.path}`))
}
} |
JavaScript | class Sprite extends Entity {
constructor(id, parent, props) {
super(id, parent);
this.x = 0;
this.y = 0;
this.bgTop = 0;
this.bgLeft = 0;
this.width = 0;
this.height = 0;
this.speed = 0;
this.horzSpeed = 0; // pixels per second
this.vertSpeed = 0; // pixels per second
this.lastMoveTime = 0; // unix time
this.lastUpdateTime = 0; // unix time
this.classUpdated = false;
this.styleDataUpdated = false;
this.styleData = {};
this.className = '';
this.mounted = false;
this.tagName = 'div';
this.elm = null;
if (props) { this.init(props); }
}
build() {
this.elm = document.createElement(this.tagName || 'div');
this.elm.id = this.id;
this.log(this.type + '.build():', this.id, '- Done,', this.elm);
return this;
}
mountChild(id, elm) {
if ( ! elm) {
elm = document.createElement('div');
elm.id = id;
}
this.addChild(elm);
this.elm.appendChild(elm); // i.e. mount!
return elm;
}
mount(parentElm, props) {
if ( ! parentElm) {
this.elm = document.getElementById(this.id);
if (this.elm) {
if (props) { this.init(props); }
this.mounted = true;
this.log(this.type + '.mount():', this.id, '- Element already mounted!', this.elm);
return this;
}
parentElm = this.engine.view.elm;
}
if ( ! this.elm) { this.build(); }
parentElm.appendChild(this.elm);
if (props) { this.init(props); }
this.mounted = true;
this.log(this.type + '.mount():', this.id, '- Done, parentElm =', parentElm);
return this;
}
dismount() {
this.elm.remove();
this.mounted = false;
return this.elm;
}
render() {
if (this.valueChanged) { this.updateElementContent(); }
if (this.stateChanged || this.classUpdated) { this.updateElementClass(); }
if (this.styleDataUpdated) { this.updateElementStyle(); }
this.classUpdated = false;
this.styleDataUpdated = false;
}
update(now, dt) {
if (this.animator) {
let animation = this.animator.update(now, dt);
if (animation) {
let frame = animation.currentFrame;
this.bgTop = frame.top;
this.bgLeft = frame.left;
this.width = frame.width;
this.height = frame.height;
this.hw = (this.width / 2)|0;
this.hh = (this.height / 2)|0;
if (this.animator.animationChanged || animation.frameChanged || this.firstRender) {
this.className = animation.className;
if (frame.flipH) { this.className += ' flipH'; }
if (frame.flipV) { this.className += ' flipV'; }
this.classUpdated = true;
//this.log('frame.flipH =', frame.flipH, ', sprite.id:', this.id,
// ', sprite.className:', this.className);
}
}
}
this.updateElementStyleData();
}
updateElementStyleData() {
if (this.styleDataNeedsUpdate()) {
this.styleData = {
x : this.x,
y : this.y,
width : this.width,
bgTop : this.bgTop,
bgLeft : this.bgLeft,
width : this.width,
height : this.height
};
this.styleDataUpdated = true;
}
}
styleDataNeedsUpdate() {
let styleData = this.styleData;
return (
styleData.x !== this.x ||
styleData.y !== this.y ||
styleData.width !== this.width ||
styleData.bgTop !== this.bgTop ||
styleData.bgLeft !== this.bgLeft
);
}
updateElementContent(content) {
this.elm.innerHTML = content || this.value;
}
updateElementStyle() {
let styleStr = 'left:' + this.x + 'px;top:' + this.y + 'px;'
+ 'height:' + this.height + 'px;width:' + this.width + 'px;';
if (this.animator) {
styleStr += 'background-position:-' + this.bgLeft + 'px ' + this.bgTop + 'px;';
}
this.elm.style = styleStr;
}
updateElementClass() {
this.elm.className = this.className + ' ' + this.state;
}
} // End: Sprite Class |
JavaScript | class Application {
constructor() {
// Default values
this.identifier = Lime.Guid();
this.compression = Lime.SessionCompression.NONE;
this.encryption = Lime.SessionEncryption.NONE;
this.instance = 'default';
this.domain = 'msging.net';
this.scheme = 'wss';
this.hostName = 'ws.msging.net';
this.port = 443;
this.presence = {
status: 'available',
routingRule: 'identity'
};
this.notifyConsumed = true;
this.authentication = new Lime.GuestAuthentication();
this.commandTimeout = 6000;
}
} |
JavaScript | class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
accessToken: ''
};
}
handleEmailChange = (e) => {
if (!e.target.value.trim()) {
return
}
this.setState({
email: e.target.value
});
};
handlePasswordChange = (e) => {
if (!e.target.value.trim()) {
return
}
this.setState({
password: e.target.value
});
};
handleLogin = (e) => {
e.preventDefault();
console.log("Email: " + this.state.email);
console.log("Password: " + this.state.password);
window.localStorage.setItem('userEmail', this.state.email);
// store.dispatch(saveUser(this.state.email,this.state.password));
// console.log("Redux Store State: ",store.getState());
// Sets the new href (URL) for the current window.
const client = new GraphQLClient('http://localhost:4005/graphql', {
// credentials: 'include',
mode: 'cors'
})
const query = `query findUser($userEmail:String!) {
userloginDetails(userEmail:$userEmail) {
userEmail
userPassword
accessToken
}
}`;
const queryvariables = {
"userEmail":`${this.state.email}`
}
client.request(query,queryvariables).then(data => {
const { userloginDetails } = data;
userloginDetails.forEach(element => {
const { userEmail, userPassword, accessToken } = element;
window.localStorage.setItem(accessToken,'jwt');
this.setState({
accessToken: accessToken
});
window.localStorage.setItem('accessToken', accessToken);
// store.dispatch(saveaccessToken(accessToken));
if( userPassword === this.state.password ) {
console.log("E> ",userEmail," P> ",userPassword);
} else {
this.setState({
password: ''
})
}
});
if((userloginDetails.length === 1 && this.state.password !== '')) {
this.setState({
email: '',
password: ''
})
window.location.assign("http://localhost:3000/dashboard");
} else {
this.setState({
email: '',
password: ''
})
console.log("Invalid Login...");
}
})
}
render() {
return (
<div className='login-form'>
<style>{`
body > div,
body > div > div,
body > div > div > div.login-form {
height: 100%;
}
`}</style>
<Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
<Grid.Column style={{ maxWidth: 450 }}>
<Header as='h2' color='teal' textAlign='center'>
<Image src='/logo.png' /> Log-in to your account
</Header>
<Form size='large' >
<Segment stacked>
<Form.Input fluid icon='user' iconPosition='left' placeholder='E-mail address'
value={this.state.email}
onChange={e => this.handleEmailChange(e)} />
<Form.Input
fluid
icon='lock'
iconPosition='left'
placeholder='Password'
type='password'
value={this.state.password}
onChange={e => this.handlePasswordChange(e)}
/>
<Button color='teal' fluid size='large' onClick={(e) => this.handleLogin(e)} >
Login
</Button>
</Segment>
</Form>
<Message>
New to us? <a href='http://localhost:3000/signup'>Sign Up</a>
</Message>
</Grid.Column>
</Grid>
</div>
);
}
} |
JavaScript | class ProtectYourAccount extends PureComponent {
static propTypes = {
/**
/* navigation object required to push and pop other views
*/
navigation: PropTypes.object
};
goNext = () => {
this.props.navigation.navigate('ChoosePassword');
};
render() {
return (
<SafeAreaView style={styles.mainWrapper}>
<ScrollView
contentContainerStyle={styles.wrapper}
style={styles.mainWrapper}
testID={'protect-your-account-screen'}
>
<View style={styles.content}>
<Emoji name="closed_lock_with_key" style={styles.emoji} />
<Text style={styles.title}>{strings('secure_your_wallet.title')}</Text>
<View style={styles.text}>
<Text style={styles.label}>{strings('secure_your_wallet.step_1')}</Text>
</View>
<View style={styles.text}>
<Text style={[styles.label, styles.step]}>
{strings('secure_your_wallet.step_1_description')}
</Text>
</View>
<View style={styles.text}>
<Text style={styles.label}>{strings('secure_your_wallet.step_2')}</Text>
</View>
<View style={styles.text}>
<Text style={[styles.label, styles.step]}>
{strings('secure_your_wallet.step_2_description')}
</Text>
</View>
<View style={styles.text}>
<Text style={styles.label}>{strings('secure_your_wallet.info_text_1')}</Text>
</View>
<View style={styles.text}>
<Text style={styles.label}>{strings('secure_your_wallet.info_text_2')}</Text>
</View>
</View>
<View style={styles.buttonWrapper}>
<StyledButton
containerStyle={styles.button}
type={'confirm'}
onPress={this.goNext}
testID={'submit-button'}
>
{strings('secure_your_wallet.cta_text')}
</StyledButton>
</View>
</ScrollView>
{Device.isAndroid() && <AndroidBackHandler customBackPress={this.props.navigation.pop} />}
</SafeAreaView>
);
}
} |
JavaScript | class CacheableResponse {
/**
* To construct a new CacheableResponse instance you must provide at least
* one of the `config` properties.
*
* If both `statuses` and `headers` are specified, then both conditions must
* be met for the `Response` to be considered cacheable.
*
* @param {Object} config
* @param {Array<number>} [config.statuses] One or more status codes that a
* `Response` can have and be considered cacheable.
* @param {Object<string,string>} [config.headers] A mapping of header names
* and expected values that a `Response` can have and be considered cacheable.
* If multiple headers are provided, only one needs to be present.
*/
constructor(config = {}) {
if (process.env.NODE_ENV !== 'production') {
if (!(config.statuses || config.headers)) {
throw new WorkboxError('statuses-or-headers-required', {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'constructor',
});
}
if (config.statuses) {
assert.isArray(config.statuses, {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'constructor',
paramName: 'config.statuses',
});
}
if (config.headers) {
assert.isType(config.headers, 'object', {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'constructor',
paramName: 'config.headers',
});
}
}
this._statuses = config.statuses;
this._headers = config.headers;
}
/**
* Checks a response to see whether it's cacheable or not, based on this
* object's configuration.
*
* @param {Response} response The response whose cacheability is being
* checked.
* @return {boolean} `true` if the `Response` is cacheable, and `false`
* otherwise.
*/
isResponseCacheable(response) {
if (process.env.NODE_ENV !== 'production') {
assert.isInstance(response, Response, {
moduleName: 'workbox-cacheable-response',
className: 'CacheableResponse',
funcName: 'isResponseCacheable',
paramName: 'response',
});
}
let cacheable = true;
if (this._statuses) {
cacheable = this._statuses.includes(response.status);
}
if (this._headers && cacheable) {
cacheable = Object.keys(this._headers).some((headerName) => {
return response.headers.get(headerName) === this._headers[headerName];
});
}
if (process.env.NODE_ENV !== 'production') {
if (!cacheable) {
logger.groupCollapsed(`The request for ` +
`'${getFriendlyURL(response.url)}' returned a response that does ` +
`not meet the criteria for being cached.`);
logger.groupCollapsed(`View cacheability criteria here.`);
logger.log(`Cacheable statuses: ` +
JSON.stringify(this._statuses));
logger.log(`Cacheable headers: ` +
JSON.stringify(this._headers, null, 2));
logger.groupEnd();
const logFriendlyHeaders = {};
response.headers.forEach((value, key) => {
logFriendlyHeaders[key] = value;
});
logger.groupCollapsed(`View response status and headers here.`);
logger.log(`Response status: ` + response.status);
logger.log(`Response headers: ` +
JSON.stringify(logFriendlyHeaders, null, 2));
logger.groupEnd();
logger.groupCollapsed(`View full response details here.`);
logger.log(response.headers);
logger.log(response);
logger.groupEnd();
logger.groupEnd();
}
}
return cacheable;
}
} |
JavaScript | class Scratch3Griffpatch {
constructor (runtime) {
/**
* The runtime instantiating this block package.
* @type {Runtime}
*/
this.runtime = runtime;
// Clear target motion state values when the project starts.
this.runtime.on(Runtime.PROJECT_START, this.reset.bind(this));
world = new b2World(
new b2Vec2(0, -10), // gravity (10)
true // allow sleep
);
zoom = 50; // scale;
this.map = {};
fixDef.density = 1.0; // 1.0
fixDef.friction = 0.5; // 0.5
fixDef.restitution = 0.2; // 0.2
_setStageType(STAGE_TYPE_OPTIONS.BOXED);
}
reset () {
for (const body in bodies) {
if (pinned[body.uid]) {
world.DestroyJoint(pinned[body.uid]);
delete pinned[body.uid];
}
world.DestroyBody(bodies[body]);
delete bodies[body];
delete prevPos[body];
}
// todo: delete joins?
}
/**
* The key to load & store a target's music-related state.
* @type {string}
*/
static get STATE_KEY () {
return 'Scratch.Griffpatch';
}
/**
* @returns {object} metadata for this extension and its blocks.
*/
getInfo () {
return {
id: 'griffpatch',
name: formatMessage({
id: 'griffpatch.categoryName',
default: 'Physics',
description: 'Label for the Griffpatch extension category'
}),
menuIconURI: menuIconURI,
blockIconURI: blockIconURI,
blocks: [
// Global Setup ------------------
{
opcode: 'setStage',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.setStage',
default: 'setup stage [stageType]',
description: 'Set the stage type'
}),
arguments: {
stageType: {
type: ArgumentType.STRING,
menu: 'StageTypes',
defaultValue: STAGE_TYPE_OPTIONS.BOXED
}
}
},
{
opcode: 'setGravity',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.setGravity',
default: 'set gravity to x: [gx] y: [gy]',
description: 'Set the gravity'
}),
arguments: {
gx: {
type: ArgumentType.NUMBER,
defaultValue: 0
},
gy: {
type: ArgumentType.NUMBER,
defaultValue: -10
}
}
},
'---',
{
opcode: 'setPhysics',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.setPhysics',
default: 'enable for [shape] mode [mode]',
description: 'Enable Physics for this Sprite'
}),
arguments: {
shape: {
type: ArgumentType.STRING,
menu: 'ShapeTypes',
defaultValue: 'costume'
},
mode: {
type: ArgumentType.STRING,
menu: 'EnableModeTypes',
defaultValue: 'normal'
}
}
},
// {
// opcode: 'setPhysics',
// blockType: BlockType.COMMAND,
// text: formatMessage({
// id: 'griffpatch.setPhysics',
// default: 'enable physics for sprite [shape]',
// description: 'Enable Physics for this Sprite'
// }),
// arguments: {
// shape: {
// type: ArgumentType.STRING,
// menu: 'ShapeTypes',
// defaultValue: 'costume'
// }
// }
// },
// {
// opcode: 'setPhysicsAll',
// blockType: BlockType.COMMAND,
// text: formatMessage({
// id: 'griffpatch.setPhysicsAll',
// default: 'enable physics for all sprites',
// description: 'Enable Physics For All Sprites'
// })
// },
//
'---',
{
opcode: 'doTick',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.doTick',
default: 'step simulation',
description: 'Run a single tick of the physics simulation'
})
},
'---',
{
opcode: 'setPosition',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.setPosition',
default: 'go to x: [x] y: [y] [space]',
description: 'Position Sprite'
}),
arguments: {
x: {
type: ArgumentType.NUMBER,
defaultValue: 0
},
y: {
type: ArgumentType.NUMBER,
defaultValue: 0
},
space: {
type: ArgumentType.STRING,
menu: 'SpaceTypes',
defaultValue: 'world'
}
}
},
'---',
// applyForce (target, ftype, x, y, dir, pow) {
// applyAngForce (target, pow) {
{
opcode: 'setVelocity',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.setVelocity',
default: 'set velocity to sx: [sx] sy: [sy]',
description: 'Set Velocity'
}),
arguments: {
sx: {
type: ArgumentType.NUMBER,
defaultValue: 0
},
sy: {
type: ArgumentType.NUMBER,
defaultValue: 0
}
}
},
{
opcode: 'changeVelocity',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.changeVelocity',
default: 'change velocity by sx: [sx] sy: [sy]',
description: 'Change Velocity'
}),
arguments: {
sx: {
type: ArgumentType.NUMBER,
defaultValue: 0
},
sy: {
type: ArgumentType.NUMBER,
defaultValue: 0
}
}
},
{
opcode: 'getVelocityX',
text: formatMessage({
id: 'griffpatch.getVelocityX',
default: 'x velocity',
description: 'get the x velocity'
}),
blockType: BlockType.REPORTER
},
{
opcode: 'getVelocityY',
text: formatMessage({
id: 'griffpatch.getVelocityY',
default: 'y velocity',
description: 'get the y velocity'
}),
blockType: BlockType.REPORTER
},
'---',
{
opcode: 'applyForce',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.applyForce',
default: 'push with force [force] in direction [dir]',
description: 'Push this object in a given direction'
}),
arguments: {
force: {
type: ArgumentType.NUMBER,
defaultValue: 25
},
dir: {
type: ArgumentType.NUMBER,
defaultValue: 0
}
}
},
{
opcode: 'applyAngForce',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.applyAngForce',
default: 'spin with force [force]',
description: 'Push this object in a given direction'
}),
arguments: {
force: {
type: ArgumentType.NUMBER,
defaultValue: 500
}
}
},
'---',
{
opcode: 'setStatic',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.setStatic',
default: 'set fixed [static]',
description: 'Sets whether this block is static or dynamic'
}),
arguments: {
static: {
type: ArgumentType.STRING,
menu: 'StaticTypes',
defaultValue: 'static'
}
}
},
// {
// opcode: 'setDensity',
// blockType: BlockType.COMMAND,
// text: formatMessage({
// id: 'griffpatch.setDensity',
// default: 'set density [density]',
// description: 'Set the density of the object'
// }),
// arguments: {
// density: {
// type: ArgumentType.NUMBER,
// defaultValue: 1
// }
// }
// },
{
opcode: 'setProperties',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.setProperties',
default: 'set density [density] roughness [friction] bounce [restitution]',
description: 'Set the density of the object'
}),
arguments: {
density: {
type: ArgumentType.NUMBER,
menu: 'DensityTypes',
defaultValue: 100
},
friction: {
type: ArgumentType.NUMBER,
menu: 'FrictionTypes',
defaultValue: 50
},
restitution: {
type: ArgumentType.NUMBER,
menu: 'RestitutionTypes',
defaultValue: 20
}
}
},
// {
// opcode: 'pinSprite',
// blockType: BlockType.COMMAND,
// text: formatMessage({
// id: 'griffpatch.pinSprite',
// default: 'pin to world at sprite\'s x: [x] y: [y]',
// description: 'Pin the sprite'
// }),
// arguments: {
// x: {
// type: ArgumentType.NUMBER,
// defaultValue: 0
// },
// y: {
// type: ArgumentType.NUMBER,
// defaultValue: 0
// }
// }
// },
'---',
{
opcode: 'getTouching',
text: formatMessage({
id: 'griffpatch.getTouching',
default: 'touching [where]',
description: 'get the name of any sprites we are touching'
}),
blockType: BlockType.REPORTER,
arguments: {
where: {
type: ArgumentType.STRING,
menu: 'WhereTypes',
defaultValue: 'any'
}
}
},
// Scene Scrolling -------------------
'---',
{
opcode: 'setScroll',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.setScroll',
default: 'set scroll x: [ox] y: [oy]',
description: 'Sets whether this block is static or dynamic'
}),
arguments: {
ox: {
type: ArgumentType.NUMBER,
defaultValue: 0
},
oy: {
type: ArgumentType.NUMBER,
defaultValue: 0
}
}
},
{
opcode: 'changeScroll',
blockType: BlockType.COMMAND,
text: formatMessage({
id: 'griffpatch.changeScroll',
default: 'change scroll by x: [ox] y: [oy]',
description: 'Sets whether this block is static or dynamic'
}),
arguments: {
ox: {
type: ArgumentType.NUMBER,
defaultValue: 0
},
oy: {
type: ArgumentType.NUMBER,
defaultValue: 0
}
}
},
{
opcode: 'getScrollX',
text: formatMessage({
id: 'griffpatch.getScrollX',
default: 'x scroll',
description: 'get the x scroll'
}),
blockType: BlockType.REPORTER
},
{
opcode: 'getScrollY',
text: formatMessage({
id: 'griffpatch.getScrollY',
default: 'y scroll',
description: 'get the y scroll'
}),
blockType: BlockType.REPORTER
}
// {
// opcode: 'getStatic',
// text: formatMessage({
// id: 'griffpatch.getStatic',
// default: 'Static?',
// description: 'get whether this sprite is static'
// }),
// blockType: BlockType.BOOLEAN
// }
],
menus: {
StageTypes: this.STAGE_TYPE_MENU,
SpaceTypes: this.SPACE_TYPE_MENU,
WhereTypes: this.WHERE_TYPE_MENU,
ShapeTypes: this.SHAPE_TYPE_MENU,
EnableModeTypes: this.ENABLE_TYPES_TYPE_MENU,
StaticTypes: this.STATIC_TYPE_MENU,
FrictionTypes: this.FRICTION_TYPE_MENU,
RestitutionTypes: this.RESTITUTION_TYPE_MENU,
DensityTypes: this.DENSITY_TYPE_MENU
}
};
}
get STAGE_TYPE_MENU () {
return [
{text: 'boxed stage', value: STAGE_TYPE_OPTIONS.BOXED},
{text: 'open (with floor)', value: STAGE_TYPE_OPTIONS.FLOOR},
{text: 'open (no floor)', value: STAGE_TYPE_OPTIONS.OPEN}
];
}
get SPACE_TYPE_MENU () {
return [
{text: 'in world', value: SPACE_TYPE_OPTIONS.WORLD},
{text: 'on stage', value: SPACE_TYPE_OPTIONS.STAGE},
{text: 'relative', value: SPACE_TYPE_OPTIONS.RELATIVE}
];
}
get WHERE_TYPE_MENU () {
return [
{text: 'any', value: WHERE_TYPE_OPTIONS.ANY},
{text: 'feet', value: WHERE_TYPE_OPTIONS.FEET}
];
}
get SHAPE_TYPE_MENU () {
return [
{text: 'this costume', value: SHAPE_TYPE_OPTIONS.COSTUME},
{text: 'this circle', value: SHAPE_TYPE_OPTIONS.CIRCLE},
{text: 'this polygon', value: SHAPE_TYPE_OPTIONS.SVG_POLYGON},
{text: 'all sprites', value: SHAPE_TYPE_OPTIONS.ALL}
];
}
get ENABLE_TYPES_TYPE_MENU () {
return [
{text: 'normal', value: 'normal'},
{text: 'precision', value: 'bullet'}
];
}
get STATIC_TYPE_MENU () {
return [
{text: 'free', value: 'dynamic'},
{text: 'fixed in place', value: 'static'},
{text: 'fixed (but can rotate)', value: 'pinned'}
];
}
get DENSITY_TYPE_MENU () {
return [
{text: 'very light', value: '25'},
{text: 'light', value: '50'},
{text: 'normal', value: '100'},
{text: 'heavy', value: '200'},
{text: 'very heavy', value: '400'}
];
}
get FRICTION_TYPE_MENU () {
return [
{text: 'none', value: '0'},
{text: 'smooth', value: '20'},
{text: 'normal', value: '50'},
{text: 'rough', value: '75'},
{text: 'extremely rough', value: '100'}
];
}
get RESTITUTION_TYPE_MENU () {
return [
{text: 'none', value: '0'},
{text: 'little', value: '10'},
{text: 'normal', value: '20'},
{text: 'quite bouncy', value: '40'},
{text: 'very bouncy', value: '70'},
{text: 'unstable', value: '100'}
];
}
/**
* Play a drum sound for some number of beats.
* @property {number} x - x offset.
* @property {number} y - y offset.
*/
doTick () { // args, util) {
// this._playDrumForBeats(args.DRUM, args.BEATS, util);
// if (util.runtime.audioEngine === null) return;
// if (util.target.sprite.soundBank === null) return;
// const dx = Cast.toNumber(args.x);
// const dy = Cast.toNumber(args.y);
// const allTargets = this.runtime.targets;
// if (allTargets === null) return;
// for (let i = 0; i < allTargets.length; i++) {
// const target = allTargets[i];
// if (!target.isStage) {
// target.setXY(target.x + dx, target.y + dy);
// }
// }
// util.target.setXY(util.target.x + dx, util.target.y + dy);
// Matter.Engine.update(this.engine, 1000 / 30);
this._checkMoved();
// world.Step(1 / 30, 10, 10);
world.Step(1 / 30, 10, 10);
world.ClearForces();
for (const targetID in bodies) {
const body = bodies[targetID];
const target = this.runtime.getTargetById(targetID);
if (!target) {
// Drop target from simulation
world.DestroyBody(body);
delete bodies[targetID];
delete prevPos[targetID];
continue;
}
const position = body.GetPosition();
_setXY(target, (position.x * zoom) - _scroll.x, (position.y * zoom) - _scroll.y);
if (target.rotationStyle === RenderedTarget.ROTATION_STYLE_ALL_AROUND) {
target.setDirection(90 - (body.GetAngle() / toRad));
}
prevPos[targetID] = {x: target.x, y: target.y, dir: target.direction};
}
}
_checkMoved () {
for (const targetID in bodies) {
const body = bodies[targetID];
const target = this.runtime.getTargetById(targetID);
if (!target) {
// Drop target from simulation
world.DestroyBody(body);
delete bodies[targetID];
delete prevPos[targetID];
continue;
}
const prev = prevPos[targetID];
const fixedRotation = target.rotationStyle !== RenderedTarget.ROTATION_STYLE_ALL_AROUND;
if (prev && (prev.x !== target.x || prev.y !== target.y)) {
const pos = new b2Vec2((target.x + _scroll.x) / zoom, (target.y + _scroll.y) / zoom);
this._setPosition(body, pos);
if (!fixedRotation) {
body.SetAngle((90 - target.direction) * toRad);
}
body.SetAwake(true);
} else if (!fixedRotation && prev && prev.dir !== target.direction) {
body.SetAngle((90 - target.direction) * toRad);
body.SetAwake(true);
}
}
}
/**
* Play a drum sound for some number of beats.
* @property {number} x - x offset.
* @property {number} y - y offset.
*/
setPhysicsAll () {
const allTargets = this.runtime.targets;
if (allTargets === null) return;
for (let i = 0; i < allTargets.length; i++) {
const target = allTargets[i];
if (!target.isStage && !bodies[target.id]) {
this.setPhysicsFor(target);
}
}
}
/**
* Play a drum sound for some number of beats.
* @param {object} args - the block arguments.
* @param {object} util - utility object provided by the runtime.
* @property {string} shape - the shape
*/
setPhysics (args, util) {
// this._playDrumForBeats(args.DRUM, args.BEATS, util);
// if (util.runtime.audioEngine === null) return;
// if (util.target.sprite.soundBank === null) return;
// const dx = Cast.toNumber(args.x);
// const dy = Cast.toNumber(args.y);
if (args.shape === SHAPE_TYPE_OPTIONS.ALL) {
this.setPhysicsAll();
return;
}
const target = util.target;
const body = this.setPhysicsFor(target, args.shape);
if (body) {
body.SetBullet(args.mode === 'bullet');
}
}
setPhysicsFor (target, shape) {
const r = this.runtime.renderer;
const drawable = r._allDrawables[target.drawableID];
// Tell the Drawable about its updated convex hullPoints, if necessary.
if (drawable.needsConvexHullPoints()) {
const points = r._getConvexHullPointsForDrawable(target.drawableID);
drawable.setConvexHullPoints(points);
}
// if (drawable._transformDirty) {
// drawable._calculateTransform();
// }
// const points = drawable._getTransformedHullPoints();
//
// const hullPoints = [];
// for (const i in points) {
// hullPoints.push({x: points[i][0] - target.x, y: points[i][1] - target.y});
// }
const points = drawable._convexHullPoints;
const scaleX = drawable.scale[0] / 100;
const scaleY = drawable.scale[1] / -100; // Flip Y for hulls
const offset = drawable.skin.rotationCenter;
let allHulls = null;
if (shape === SHAPE_TYPE_OPTIONS.CIRCLE) {
fixDef.shape = new b2CircleShape();
const size = drawable.skin.size;
fixDef.shape.SetRadius((((size[0] * Math.abs(scaleX)) + (size[1] * Math.abs(scaleY))) / 4.0) / zoom);
// fixDef.shape.SetRadius((drawable.getBounds().width / 2) / zoom);
} else if (shape === SHAPE_TYPE_OPTIONS.SVG_POLYGON) {
const svg = drawable._skin._svgRenderer._svgTag;
// recurse through childNodes of type 'g', looking for type 'path'
const hullPoints = [];
if (svg) {
this._fetchPolygonPointsFromSVG(svg, hullPoints, offset[0], offset[1], scaleX, scaleY);
}
_definePolyFromHull(hullPoints[0]);
allHulls = hullPoints;
} else {
const hullPoints = [];
for (const i in points) {
hullPoints.push({x: (points[i][0] - offset[0]) * scaleX, y: (points[i][1] - offset[1]) * scaleY});
}
_definePolyFromHull(hullPoints);
}
const fixedRotation = target.rotationStyle !== RenderedTarget.ROTATION_STYLE_ALL_AROUND;
const body = _placeBody(target.id, target.x, target.y, fixedRotation ? 90 : target.direction);
if (target.rotationStyle !== RenderedTarget.ROTATION_STYLE_ALL_AROUND) {
body.SetFixedRotation(true);
}
if (allHulls) {
for (let i = 1; i < allHulls.length; i++) {
_definePolyFromHull(allHulls[i]);
body.CreateFixture(fixDef);
}
}
return body;
}
/**
*
* @param svg the svg element
* @param {Array} hullPointsList array of points
* @private
*/
_fetchPolygonPointsFromSVG (svg, hullPointsList, ox, oy, scaleX, scaleY) {
if (svg.tagName === 'g' || svg.tagName === 'svg') {
if (svg.hasChildNodes()) {
for (const node of svg.childNodes) {
this._fetchPolygonPointsFromSVG(node, hullPointsList, ox, oy, scaleX, scaleY);
}
}
return;
}
if (svg.tagName !== 'path') {
return;
}
// This is it boys! Get that svg data :)
// <path xmlns="http://www.w3.org/2000/svg" d="M 1 109.7118 L 1 1.8097 L 60.3049 38.0516 L 117.9625 1.8097 L 117.9625 109.7118 L 59.8931 73.8817 Z "
// data-paper-data="{"origPos":null}" stroke-width="2" fill="#9966ff"/>
let fx; let fy;
const hullPoints = [];
hullPointsList.push(hullPoints);
const tokens = svg.getAttribute('d').split(' ');
for (let i = 0; i < tokens.length;) {
const token = tokens[i++];
if (token === 'M' || token === 'L') {
const x = Cast.toNumber(tokens[i++]);
const y = Cast.toNumber(tokens[i++]);
hullPoints.push({x: (x - ox) * scaleX, y: (y - oy) * scaleY});
if (token === 'M') {
fx = x;
fy = y;
}
}
if (token === 'Z') {
hullPoints.push({x: (fx - ox) * scaleX, y: (fy - oy) * scaleY});
}
}
}
applyForce (args, util) {
_applyForce(util.target.id, 'Impulse', 0, 0,
Cast.toNumber(args.dir), Cast.toNumber(args.force));
}
applyAngForce (args, util) {
let body = bodies[util.target.id];
if (!body) {
body = this.setPhysicsFor(util.target);
}
body.ApplyTorque(-Cast.toNumber(args.force));
}
setDensity (args, util) {
let body = bodies[util.target.id];
if (!body) {
body = this.setPhysicsFor(util.target);
}
body.GetFixtureList().SetDensity(Cast.toNumber(args.density));
body.ResetMassData();
}
setProperties (args, util) {
let body = bodies[util.target.id];
if (!body) {
body = this.setPhysicsFor(util.target);
}
body.GetFixtureList().SetDensity(Cast.toNumber(args.density) / 100.0);
body.GetFixtureList().SetFriction(Cast.toNumber(args.friction) / 100.0);
body.GetFixtureList().SetRestitution(Cast.toNumber(args.restitution) / 100.0);
body.ResetMassData();
}
pinSprite (args, util) {
if (!bodies[util.target.id]) {
this.setPhysicsFor(util.target);
}
const x = Cast.toNumber(args.x);
const y = Cast.toNumber(args.y);
_createJointOfType(null, 'Rotating', util.target.id, x, y, null, null, null);
}
/**
* Set's the sprites position.
* @param {object} args - the block arguments.
* @param {object} util - utility object provided by the runtime.
* @property {number} x - x offset.
* @property {number} y - y offset.
* @property {string} space - Space type (SPACE_TYPE_OPTIONS)
*/
setPosition (args, util) {
const x = Cast.toNumber(args.x);
const y = Cast.toNumber(args.y);
const body = bodies[util.target.id];
switch (args.space) {
case SPACE_TYPE_OPTIONS.STAGE:
_setXY(util.target, x, y); // Position on stage (after scroll)
if (body) {
this._setPosition(body, new b2Vec2((x + _scroll.x) / zoom, (y + _scroll.y) / zoom));
}
break;
case SPACE_TYPE_OPTIONS.RELATIVE: {
_setXY(util.target, util.target.x + x, util.target.x + y);
if (body) {
const pos = body.GetPosition();
const pos2 = new b2Vec2(pos.x + (x / zoom), pos.y + (y / zoom));
this._setPosition(body, pos2);
}
break;
}
default:
_setXY(util.target, x - _scroll.x, y - _scroll.y);
if (body) {
this._setPosition(body, new b2Vec2(x / zoom, y / zoom));
}
}
}
_setPosition (body, pos2) {
const md = pinned[body.uid];
if (md) {
world.DestroyJoint(md);
pinned[body.uid] = _createJointOfType(null, 'Rotating', body.uid, 0, 0, null, pos2.x * zoom, pos2.y * zoom);
}
body.SetPosition(pos2);
// if (md) {
// pinned[body.uid] = _createJointOfType(null, 'Rotating', body.uid, 0, 0, null, null, null);
// }
}
/**
* Set the sprites velocity.
* @param {object} args - the block arguments.
* @param {object} util - utility object provided by the runtime.
* @property {number} sx - speed x.
* @property {number} sy - speed y.
*/
setVelocity (args, util) {
let body = bodies[util.target.id];
if (!body) {
body = this.setPhysicsFor(util.target);
}
body.SetAwake(true);
const x = Cast.toNumber(args.sx);
const y = Cast.toNumber(args.sy);
const force = new b2Vec2(x, y);
force.Multiply(30 / zoom);
body.SetLinearVelocity(force);
}
/**
* Change the sprites velocity.
* @param {object} args - the block arguments.
* @param {object} util - utility object provided by the runtime.
* @property {number} sx - speed x.
* @property {number} sy - speed y.
*/
changeVelocity (args, util) {
let body = bodies[util.target.id];
if (!body) {
body = this.setPhysicsFor(util.target);
}
body.SetAwake(true);
const x = Cast.toNumber(args.sx);
const y = Cast.toNumber(args.sy);
const force = new b2Vec2(x, y);
force.Multiply(30 / zoom);
force.Add(body.GetLinearVelocity());
body.SetLinearVelocity(force);
}
/**
* Get the current tempo.
* @param {object} args - the block arguments.
* @param {object} util - utility object provided by the runtime.
* @return {boolean} - the current tempo, in beats per minute.
*/
getStatic (args, util) {
const body = bodies[util.target.id];
if (!body) {
return false;
}
const type = body.GetType();
return type === b2Body.b2_staticBody;
}
/**
* Get the current tempo.
* @param {object} args - the block arguments.
* @param {object} util - utility object provided by the runtime.
* @return {number} - the current x velocity.
*/
getVelocityX (args, util) {
const body = bodies[util.target.id];
if (!body) {
return 0;
}
const x = body.GetLinearVelocity().x;
return (x * zoom) / 30;
}
/**
* Get the current tempo.
* @param {object} args - the block arguments.
* @param {object} util - utility object provided by the runtime.
* @return {boolean} - the current y velocity.
*/
getVelocityY (args, util) {
const body = bodies[util.target.id];
if (!body) {
return 0;
}
const y = body.GetLinearVelocity().y;
return (y * zoom) / 30;
}
/**
* Sets the static property
* @param {object} args - the block arguments.
* @param {object} util - utility object provided by the runtime.
* @property {string} static - static or not
*/
setStatic (args, util) {
const target = util.target;
let body = bodies[util.target.id];
if (!body) {
body = this.setPhysicsFor(target);
}
body.SetType(args.static === 'static' ? b2Body.b2_staticBody : b2Body.b2_dynamicBody);
const pos = new b2Vec2((target.x + _scroll.x) / zoom, (target.y + _scroll.y) / zoom);
const fixedRotation = target.rotationStyle !== RenderedTarget.ROTATION_STYLE_ALL_AROUND;
body.SetPositionAndAngle(pos, fixedRotation ? 0 : ((90 - target.direction) * toRad));
if (args.static === 'pinned') {
// Find what's behind the sprite (pin to that)
const point = new b2AABB();
point.lowerBound.SetV(pos);
point.upperBound.SetV(pos);
let body2ID = null;
world.QueryAABB(fixture => {
const body2 = fixture.GetBody();
if (body2 !== body && fixture.TestPoint(pos.x, pos.y)){
body2ID = body2.uid;
return false;
}
return true;
}, point);
pinned[target.id] = _createJointOfType(null, 'Rotating', target.id, 0, 0, body2ID, null, null);
} else {
const pin = pinned[target.id];
if (pin) {
world.DestroyJoint(pin);
// delete joints[pin.I];
delete pinned[target.id];
}
}
}
/**
* Sets the sprite offset
* @param {object} args - the block arguments.
* @property {number} ox - x offset.
* @property {number} oy - y offset.
*/
setScroll (args) {
this._checkMoved();
_scroll.x = Cast.toNumber(args.ox);
_scroll.y = Cast.toNumber(args.oy);
this._repositionBodies();
}
/**
* Sets the sprite offset
* @param {object} args - the block arguments.
* @property {number} ox - x offset.
* @property {number} oy - y offset.
*/
changeScroll (args) {
this._checkMoved();
_scroll.x += Cast.toNumber(args.ox);
_scroll.y += Cast.toNumber(args.oy);
this._repositionBodies();
}
/**
* Get the scroll x.
* @return {number} - the current x velocity.
*/
getScrollX () {
return _scroll.x;
}
/**
* Get the scroll x.
* @return {number} - the current x velocity.
*/
getScrollY () {
return _scroll.y;
}
_repositionBodies () {
for (const targetID in bodies) {
const body = bodies[targetID];
const target = this.runtime.getTargetById(targetID);
if (target) {
const position = body.GetPosition();
_setXY(target, (position.x * zoom) - _scroll.x, (position.y * zoom) - _scroll.y);
prevPos[targetID] = {x: target.x, y: target.y, dir: target.direction};
}
}
}
getTouching (args, util) {
const target = util.target;
const body = bodies[target.id];
if (!body) {
return '';
}
const where = args.where;
let touching = '';
const contacts = body.GetContactList();
for (let ce = contacts; ce; ce = ce.next) {
// noinspection JSBitwiseOperatorUsage
if (ce.contact.m_flags & b2Contact.e_islandFlag) {
continue;
}
if (ce.contact.IsSensor() === true ||
ce.contact.IsEnabled() === false ||
ce.contact.IsTouching() === false) {
continue;
}
const contact = ce.contact;
const fixtureA = contact.GetFixtureA();
const fixtureB = contact.GetFixtureB();
const bodyA = fixtureA.GetBody();
const bodyB = fixtureB.GetBody();
// const myFix = touchingB ? fixtureA : fixtureB;
const touchingB = bodyA === body;
if (where !== 'any') {
const man = new Box2D.Collision.b2WorldManifold();
contact.GetWorldManifold(man);
// man.m_points
// const mx = man.m_normal.x;
// const my = man.m_normal.y;
if (where === 'feet') {
// if (my > -0.6) {
// continue;
// }
const fixture = body.GetFixtureList();
const y = man.m_points[0].y;
if (y > (fixture.m_aabb.lowerBound.y * 0.75) + (fixture.m_aabb.upperBound.y * 0.25)) {
continue;
}
// const lp = body.GetLocalPoint(man.m_points[0]).Normalize();
// if (lp.y)
}
}
const other = touchingB ? bodyB : bodyA;
const uid = other.uid;
const target2 = uid ? this.runtime.getTargetById(uid) : this.runtime.getTargetForStage();
if (target2) {
const name = target2.sprite.name;
if (touching.length === 0) {
touching = name;
} else {
touching += `,${name}`;
}
}
}
return touching;
}
/**
* Sets the stage
* @param {object} args - the block arguments.
* @property {number} stageType - Stage Type.
*/
setStage (args) {
_setStageType(args.stageType);
}
/**
* Sets the gravity
* @param {object} args - the block arguments.
* @property {number} gx - Gravity x.
* @property {number} gy - Gravity y.
*/
setGravity (args) {
world.SetGravity(new b2Vec2(Cast.toNumber(args.gx), Cast.toNumber(args.gy)));
for (const bodyID in bodies) {
bodies[bodyID].SetAwake(true);
}
}
} |
JavaScript | class HapiPlugin {
/**
* Creates an instance of HapiPlugin.
* @param {object} [config={}]
* @memberof HapiPlugin
*/
constructor(values = {}) {
storage.set(this, { config: Object.assign({}, values) });
}
/**
* Obtain the current configuration
*
* @readonly
* @memberof HapiPlugin
*/
get config() {
const { config } = storage.get(this);
return config;
}
/**
* Obtain the plugin name
*
* @memberof HapiPlugin
*/
get name() {
const { name } = this.config;
return name;
}
/**
* Set the plugin name
*
* @memberof HapiPlugin
*/
set name(value) {
this.config.name = value;
}
/**
* Obtain the version
*
* @memberof HapiPlugin
*/
get version() {
const { version } = this.config;
return version;
}
/**
* Set the version
*
* @memberof HapiPlugin
*/
set version(value) {
this.config.version = value;
}
/**
* Obtain the register method
*
* @memberof HapiPlugin
*/
get register() {
const { register } = this.config;
const invoke = register
? register
: async () => {
throw new Error(
`HapiPlugin "${this.name}" has no register method`
);
};
return invoke;
}
/**
* Set the register method
*
* @memberof HapiPlugin
*/
set register(value) {
this.config.register = value;
}
/**
* Obtain the dependencies
*
* @memberof HapiPlugin
*/
get dependencies() {
const { config } = this;
if (!('dependencies' in config)) {
config.dependencies = [];
}
return config.dependencies;
}
/**
* Set the dependencies
*
* @memberof HapiPlugin
*/
set dependencies(value) {
this.config.dependencies = value;
}
/**
* Obtain the options
*
* @memberof HapiPlugin
*/
get options() {
const { config } = this;
if (!('options' in config)) {
config.options = {};
}
return config.options;
}
/**
* Set the options
*
* @memberof HapiPlugin
*/
set options(value) {
const { options } = this.config;
this.config.options = { ...options, ...(value || {}) };
}
/**
* Obtain the routes config
*
* @memberof HapiPlugin
*/
get routes() {
const { config } = this;
if (!('routes' in config)) {
config.routes = {};
}
return config.routes;
}
/**
* Set the routes config
*
* @memberof HapiPlugin
*/
set routes(value) {
const { routes } = this.config;
this.config.routes = { ...routes, ...(value || {}) };
}
/**
* Obtain the routes.prefix value
*
* @memberof HapiPlugin
*/
get prefix() {
return this.routes.prefix;
}
/**
* Set the routes.prefix value
*
* @memberof HapiPlugin
*/
set prefix(value) {
this.routes = { ...this.routes, prefix: value };
}
/**
* Obtain the routes.vhost value
*
* @memberof HapiPlugin
*/
get vhost() {
return this.routes.vhost;
}
/**
* Set the routes.vhost value
*
* @memberof HapiPlugin
*/
set vhost(value) {
this.routes = { ...this.routes, vhost: value };
}
/**
* Export the plugin configuration
*
* @readonly
* @memberof HapiPlugin
*/
get exports() {
const {
name,
version,
dependencies: depends,
options,
register,
routes
} = this;
const dependencies = depends.length ? depends : undefined;
if (Object.keys(routes).length || Object.keys(options).length) {
return {
plugin: { name, version, dependencies, register },
options,
routes
};
}
return { name, version, dependencies, register };
}
} |
JavaScript | class ProvisionedThroughputBuilder {
constructor(read, write) {
assert.argumentIsOptional(read, 'read', Number);
assert.argumentIsOptional(write, 'write', Number);
this._provisionedThroughput = new ProvisionedThroughput(read, write);
}
/**
* The {@link ProvisionedThroughput}, given all the information provided thus far.
*
* @public
* @returns {ProvisionedThroughput}
*/
get provisionedThroughput() {
return this._provisionedThroughput;
}
/**
* Sets the read capacity units and returns the current instance.
*
* @public
* @param {Number} value
* @returns {ProvisionedThroughputBuilder}
*/
withRead(value) {
assert.argumentIsRequired(value, 'value', Number);
this._provisionedThroughput = new ProvisionedThroughput(value, this._provisionedThroughput.write);
return this;
}
/**
* Sets the write capacity units and returns the current instance.
*
* @public
* @param {Number} value
* @returns {ProvisionedThroughputBuilder}
*/
withWrite(value) {
assert.argumentIsRequired(value, 'value', Number);
this._provisionedThroughput = new ProvisionedThroughput(this._provisionedThroughput.read, value);
return this;
}
toString() {
return '[ProvisionedThroughputBuilder]';
}
} |
JavaScript | class Modal extends React.Component {
constructor(props){
super(props);
this.state={
username: '',
avatar: '',
description: ''
}
this.handleSubmit = ev => {
ev.preventDefault();
this.props.onSubmitForm({Name: this.state.username, Avatar: this.state.avatar, Description: this.state.description})
}
}
render(){
return (
<div className="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel">Add new user</h5>
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
<form onSubmit={this.handleSubmit}>
<fieldset>
<fieldset className="form-group">
<input placeholder="Username" value={this.state.username} onChange={ev => this.setState({username: ev.target.value})} className="form-control"/>
</fieldset>
<fieldset className="form-group">
<input placeholder="Description" value={this.state.description} onChange={ev => this.setState({description: ev.target.value})} className="form-control"/>
</fieldset>
<fieldset className="form-group">
<input placeholder="Picture" value={this.state.avatar} onChange={ev => this.setState({avatar: ev.target.value})} className="form-control"/>
</fieldset>
<fieldset className="form-group">
<button className="btn btn-primary">Save</button>
</fieldset>
</fieldset>
</form>
</div>
</div>
</div>
</div>
);
}
} |
JavaScript | class QueenAnt extends Combat {
constructor(character) {
super(character);
this.lastActionThreshold = 10000; // Due to the nature of the AoE attack
this.character = Object.assign(character, {
spawnDistance: 18,
});
this.aoeTimeout = null;
this.aoeCountdown = 5;
this.aoeRadius = 2;
this.lastAoE = 0;
this.minionCount = 7;
this.lastSpawn = 0;
this.minions = [];
this.frozen = false;
/**
* This is to prevent the boss from dealing
* any powerful AoE attack after dying.
*/
this.character.onDeath(() => {
this.lastSpawn = 0;
if (this.aoeTimeout) {
clearTimeout(this.aoeTimeout);
this.aoeTimeout = null;
}
const listCopy = this.minions.slice();
for (let i = 0; i < listCopy.length; i += 1) {
this.world.kill(listCopy[i]);
}
});
this.character.onReturn(() => {
clearTimeout(this.aoeTimeout);
this.aoeTimeout = null;
});
}
begin(attacker) {
this.resetAoE();
super.begin(attacker);
}
hit(attacker, target, hitInfo) {
if (this.frozen) {
return;
}
if (this.canCastAoE()) {
this.doAoE();
return;
}
if (this.canSpawn()) {
this.spawnMinions();
}
if (this.isAttacked()) {
this.beginMinionAttack();
}
super.hit(attacker, target, hitInfo);
}
/**
* The reason this function does not use its superclass
* representation is because of the setTimeout function
* which does not allow us to call super().
*/
doAoE() {
this.resetAoE();
this.lastHit = this.getTime();
this.pushFreeze(true);
this.pushCountdown(this.aoeCountdown);
this.aoeTimeout = setTimeout(() => {
this.dealAoE(this.aoeRadius, true);
this.pushFreeze(false);
}, 5000);
}
spawnMinions() {
this.lastSpawn = new Date().getTime();
for (let i = 0; i < this.minionCount; i += 1) {
this.minions.push(
this.world.spawnMob(13, this.character.x, this.character.y),
);
}
_.each(this.minions, (minion) => {
minion.aggressive = true;
minion.spawnDistance = 12;
minion.onDeath(() => {
if (this.isLast()) {
this.lastSpawn = new Date().getTime();
}
this.minions.splice(this.minions.indexOf(minion), 1);
});
if (this.isAttacked()) {
this.beginMinionAttack();
}
});
}
beginMinionAttack() {
if (!this.hasMinions()) {
return;
}
_.each(this.minions, (minion) => {
const randomTarget = this.getRandomTarget();
if (!minion.hasTarget() && randomTarget) {
minion.combat.begin(randomTarget);
}
});
}
resetAoE() {
this.lastAoE = new Date().getTime();
}
getRandomTarget() {
if (this.isAttacked()) {
const keys = Object.keys(this.attackers);
const randomAttacker = this.attackers[keys[Utils.randomInt(0, keys.length)]];
if (randomAttacker) {
return randomAttacker;
}
}
if (this.character.hasTarget()) {
return this.character.target;
}
return null;
}
pushFreeze(state) {
this.character.frozen = state;
this.character.stunned = state;
}
pushCountdown(count) {
this.world.pushToAdjacentGroups(
this.character.group,
new Messages.NPC(Packets.NPCOpcode.Countdown, {
id: this.character.instance,
countdown: count,
}),
);
}
getMinions() {
this.world.getGrids();
}
isLast() {
return this.minions.length === 1;
}
hasMinions() {
return this.minions.length > 0;
}
canCastAoE() {
return new Date().getTime() - this.lastAoE > 30000;
}
canSpawn() {
return (
new Date().getTime() - this.lastSpawn > 45000
&& !this.hasMinions()
&& this.isAttacked()
);
}
} |
JavaScript | class View extends CompostMixin(HTMLElement) {
static get properties() {
return {
// data about current view
current: {
type: Object,
value: {
id: null,
subId: null,
},
observer: 'observeCurrent',
},
// cache to hold stories / lists
cache: {
type: Object,
value: {},
},
};
}
render() {
return `
<style>
:host {
contain: content;
display: block;
padding: 1rem;
}
.view.hide {
display: none;
}
</style>
<x-view-top class="view" id="top"></x-view-top>
<x-view-new class="view" id="new"></x-view-new>
<x-view-show class="view" id="show"></x-view-show>
<x-view-ask class="view" id="ask"></x-view-ask>
<x-view-job class="view" id="job"></x-view-job>
<x-view-story class="view" id="story"></x-view-story>
<x-view-about class="view" id="about"></x-view-about>
`;
}
// fired when current view changes
observeCurrent(oldValue, newValue) {
[...this.$$('.view')].forEach((view) => {
if (view.id === newValue.id) {
view.cache = this.cache;
if (view.id === 'story') {
this.$id[newValue.id].storyId = newValue.subId;
} else {
this.$id[newValue.id].startIndex = newValue.subId;
}
view.classList.remove('hide');
view.active = true;
} else {
view.classList.add('hide');
view.active = false;
}
});
}
} |
JavaScript | class ScoreResolver{
constructor(){
this.score = 0;
this.lines = 0;
this._lastAction = undefined;
this.lastAutoActions = []; // keep last two auto actions
this.onScoreUpdateCallback = undefined;
}
set lastUserAction(action){
this._lastAction = action;
this.lastAutoActions = [];
}
set lastAutoAction(action){
const length = this.lastAutoActions.length;
if (length === 2)
return;
this.lastAutoActions.push(action);
}
resetScore(){
this.score = 0;
}
resolve (numLines) {
let res = numLines * DEFAULT_FACTOR;
switch (this._lastAction){
case BlockActionsConsts.MOVE_LEFT:
case BlockActionsConsts.MOVE_RIGHT:
if (this.lastAutoActions.length === 1) // user input was just before lock
res = numLines * MOVE_ACTION_FACTOR;
break;
case BlockActionsConsts.DROP:
res = numLines * DROP_ACTION_FACTOR;
break;
}
this.score += res + DEFAULT_FACTOR; // add one point per piece placement on board
this.lines += numLines;
if (this.onScoreUpdateCallback)
this.onScoreUpdateCallback(this.score, this.lines);
return this.score;
}
} |
JavaScript | class Post {
/**
* The option template to compile.
*
* @return {function}
*/
get optionTemplate() {
return window.wp.template('papi-property-post-option');
}
/**
* The option placeholder template to compile.
*
* @return {function}
*/
get optionPlaceholderTemplate() {
return window.wp.template('papi-property-post-option-placeholder');
}
/**
* Initialize Property Post.
*/
static init() {
new Post().binds();
}
/**
* Bind elements with functions.
*/
binds() {
$(document).on('papi/property/repeater/added', '[data-property="post"]', this.update.bind(this));
$(document).on('change', '.papi-property-post-left', this.change.bind(this));
$(document).on('papi/iframe/submit', this.iframeSubmit.bind(this));
}
/**
* Change post dropdown when selecting
* a different post type.
*
* @param {object} e
*/
change(e) {
e.preventDefault();
const self = this;
const $this = $(e.currentTarget);
const query = $this.data('post-query').length
? $this.data('post-query')
: {};
query.post_type = $this.val();
const params = {
'action': 'get_posts',
'fields': ['ID', 'post_title', 'post_type'],
'query': query
};
const $prop = $this.closest('.papi-property-post');
const $select = $prop.find('.papi-property-post-right');
$('[for="' + $select.attr('id') + '"]')
.parent()
.find('label')
.text($this.data('select-item').replace('%s', $this.find('option:selected').text()));
$.get(papi.ajaxUrl + '?' + $.param(params), function(posts) {
$select.empty();
if ($select.data('placeholder').length && posts.length) {
const optionPlaceholderTemplate = self.optionPlaceholderTemplate;
const template1 = window._.template($.trim(optionPlaceholderTemplate()));
$select.append(template1({
type: posts[0].post_type
}));
}
const optionTemplate = self.optionTemplate;
const template2 = window._.template($.trim(optionTemplate()));
$.each(posts, function(index, post) {
$select.append(template2({
id: post.ID,
title: post.post_title,
type: post.post_type
}));
});
if ($select.hasClass('papi-component-select2') && 'select2' in $.fn) {
$select.trigger('change');
}
});
}
/**
* Update select when iframe is submitted.
*
* @param {object} e
* @param {object} data
*/
iframeSubmit(e, data) {
if (!data.iframe) {
return;
}
const $elm = $(data.iframe);
const title = $elm.find('[name="post_title"]').val();
const id = $elm.find('[name="post_ID"]').val();
const $select = $('[name=' + data.selector + ']');
if (data.url.indexOf('post-new') !== -1) {
// new
const optionTemplate = this.optionTemplate;
const template = window._.template($.trim(optionTemplate()));
if ($select.find('option[value=' + id + ']').length) {
return;
}
$select.append(template({
id: id,
title: title,
}));
} else {
// edit
const $option = $select.find('option[data-edit-url="' + data.url + '"]');
$option.removeData('data');
$option.text(title);
}
$select.trigger('change');
$select.val(id);
}
/**
* Initialize select2 field when added to repeater.
*
* @param {object} e
*/
update(e) {
e.preventDefault();
const $select = $(e.currentTarget).parent().find('select');
if ($select.hasClass('papi-component-select2') && 'select2' in $.fn) {
$select.select2(select2Options($select[0]));
}
}
} |
JavaScript | class SettingsPage extends Component {
static propTypes = {
gameEngine: PropTypes.object.isRequired,
gameState: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
/*
* toggle the music, either muted or playing
*/
toggleSound = ()=>{
this.props.gameEngine.toggleSound();
};
/*
* clear the local leader store asynchronously
*/
onClearHistory = ()=>{
this.props.gameEngine.clearStorage();
};
/*
* close the navigation page by navigating to the game board
*/
onClose = ()=>this.props.history.push({pathname: '/'});
render(){
const {muted} = this.props.gameState;
const icon = muted ? ICONS.VOLUME_MUTE : ICONS.VOLUME_HIGH;
return(
<div className="settings">
<div className="settings__header">
<h2 className='title'>Settings</h2>
</div>
<div className="settings__options">
<ul className="settings-list">
<li className="settings-item">
<div className="settings-item__text">
Clear Local Storage
</div>
<div className="settings-item__btn">
<Button text="clear" onAction={this.onClearHistory} className='btn-clear'/>
</div>
</li>
<li className="settings-item">
<div className="settings-item__text">
Background Music
</div>
<div className="settings-item__btn">
<Icon icon={icon} className="settings__icon" onClick={this.toggleSound}/>
</div>
</li>
</ul>
</div>
<div className="settings__footer">
<Button text="close" onAction={this.onClose} className="btn-save"/>
</div>
</div>
);
}
} |
JavaScript | class ActivityResult {
/**
* @param {!ActivityResultCode} code
* @param {*} data
* @param {!ActivityMode} mode
* @param {string} origin
* @param {boolean} originVerified
* @param {boolean} secureChannel
*/
constructor(code, data, mode, origin, originVerified, secureChannel) {
/** @const {!ActivityResultCode} */
this.code = code;
/** @const {*} */
this.data = code == ActivityResultCode.OK ? data : null;
/** @const {!ActivityMode} */
this.mode = mode;
/** @const {string} */
this.origin = origin;
/** @const {boolean} */
this.originVerified = originVerified;
/** @const {boolean} */
this.secureChannel = secureChannel;
/** @const {boolean} */
this.ok = code == ActivityResultCode.OK;
/** @const {?Error} */
this.error = code == ActivityResultCode.FAILED ?
new Error(String(data) || '') :
null;
}
} |
JavaScript | class ActivityHost {
/**
* Returns the mode of the activity: iframe, popup or redirect.
* @return {!ActivityMode}
*/
getMode() {}
/**
* The request string that the host was started with. This value can be
* passed around while the target host is navigated.
*
* Not always available; in particular, this value is not available for
* iframe hosts.
*
* See `ActivityRequest` for more info.
*
* @return {?string}
*/
getRequestString() {}
/**
* The client's origin. The connection to the client must first succeed
* before the origin can be known with certainty.
* @return {string}
*/
getTargetOrigin() {}
/**
* Whether the client's origin has been verified. This depends on the type of
* the client connection. When window messaging is used (for iframes and
* popups), the origin can be verified. In case of redirects, where state is
* passed in the URL, the verification is not fully possible.
* @return {boolean}
*/
isTargetOriginVerified() {}
/**
* Whether the client/host communication is done via a secure channel such
* as messaging, or an open and easily exploitable channel, such redirect URL.
* Iframes and popups use a secure channel, and the redirect mode does not.
* @return {boolean}
*/
isSecureChannel() {}
/**
* Signals to the host to accept the connection. Before the connection is
* accepted, no other calls can be made, such as `ready()`, `result()`, etc.
*
* Since the result of the activity could be sensitive, the host API requires
* you to verify the connection. The host can use the client's origin,
* verified flag, whether the channel is secure, activity arguments, and other
* properties to confirm whether the connection should be accepted.
*
* The client origin is verifiable in popup and iframe modes, but may not
* be verifiable in the redirect mode. The channel is secure for iframes and
* popups and not secure for redirects.
*/
accept() {}
/**
* The arguments the activity was started with. The connection to the client
* must first succeed before the origin can be known with certainty.
* @return {?Object}
*/
getArgs() {}
/**
* Signals to the opener that the host is ready to be interacted with.
*/
ready() {}
/**
* Whether the supplemental messaging suppored for this host mode. Only iframe
* hosts can currently send and receive messages.
* @return {boolean}
*/
isMessagingSupported() {}
/**
* Sends a message to the client. Notice that only iframe hosts can send and
* receive messages.
* @param {!Object} payload
*/
message(payload) {}
/**
* Registers a callback to receive messages from the client. Notice that only
* iframe hosts can send and receive messages.
* @param {function(!Object)} callback
*/
onMessage(callback) {}
/**
* Creates a new supplemental communication channel or returns an existing
* one. Notice that only iframe hosts can send and receive messages.
* @param {string=} opt_name
* @return {!Promise<!MessagePort>}
*/
messageChannel(opt_name) {}
/**
* Signals to the activity client the result of the activity.
* @param {*} data
*/
result(data) {}
/**
* Signals to the activity client that the activity has been canceled by the
* user.
*/
cancel() {}
/**
* Signals to the activity client that the activity has unrecoverably failed.
* @param {!Error|string} reason
*/
failed(reason) {}
/**
* Set the size container. This element will be used to measure the
* size needed by the iframe. Not required for non-iframe hosts. The
* needed height is calculated as `sizeContainer.scrollHeight`.
* @param {!Element} element
*/
setSizeContainer(element) {}
/**
* Signals to the activity client that the activity's size needs might have
* changed. Not required for non-iframe hosts.
*/
resized() {}
/**
* The callback the activity implementation can implement to react to changes
* in size. Normally, this callback is called in reaction to the `resized()`
* method.
* @param {function(number, number, boolean)} callback
*/
onResizeComplete(callback) {}
/**
* Disconnect the activity implementation and cleanup listeners.
*/
disconnect() {}
} |
JavaScript | class Messenger {
/**
* @param {!Window} win
* @param {!Window|function():?Window} targetOrCallback
* @param {?string} targetOrigin
*/
constructor(win, targetOrCallback, targetOrigin) {
/** @private @const {!Window} */
this.win_ = win;
/** @private @const {!Window|function():?Window} */
this.targetOrCallback_ = targetOrCallback;
/**
* May start as unknown (`null`) until received in the first message.
* @private {?string}
*/
this.targetOrigin_ = targetOrigin;
/** @private {?Window} */
this.target_ = null;
/** @private {boolean} */
this.acceptsChannel_ = false;
/** @private {?MessagePort} */
this.port_ = null;
/** @private {?function(string, ?Object)} */
this.onCommand_ = null;
/** @private {?function(!Object)} */
this.onCustomMessage_ = null;
/**
* @private {?Object<string, !ChannelHolder>}
*/
this.channels_ = null;
/** @private @const */
this.boundHandleEvent_ = this.handleEvent_.bind(this);
}
/**
* Connect the port to the host or vice versa.
* @param {function(string, ?Object)} onCommand
*/
connect(onCommand) {
if (this.onCommand_) {
throw new Error('already connected');
}
this.onCommand_ = onCommand;
this.win_.addEventListener('message', this.boundHandleEvent_);
}
/**
* Disconnect messenger.
*/
disconnect() {
if (this.onCommand_) {
this.onCommand_ = null;
if (this.port_) {
closePort(this.port_);
this.port_ = null;
}
this.win_.removeEventListener('message', this.boundHandleEvent_);
if (this.channels_) {
for (const k in this.channels_) {
const channelObj = this.channels_[k];
if (channelObj.port1) {
closePort(channelObj.port1);
}
if (channelObj.port2) {
closePort(channelObj.port2);
}
}
this.channels_ = null;
}
}
}
/**
* Returns whether the messenger has been connected already.
* @return {boolean}
*/
isConnected() {
return this.targetOrigin_ != null;
}
/**
* Returns the messaging target. Only available when connection has been
* establihsed.
* @return {!Window}
*/
getTarget() {
const target = this.getOptionalTarget_();
if (!target) {
throw new Error('not connected');
}
return target;
}
/**
* @return {?Window}
* @private
*/
getOptionalTarget_() {
if (this.onCommand_ && !this.target_) {
if (typeof this.targetOrCallback_ == 'function') {
this.target_ = this.targetOrCallback_();
} else {
this.target_ = /** @type {!Window} */ (this.targetOrCallback_);
}
}
return this.target_;
}
/**
* Returns the messaging origin. Only available when connection has been
* establihsed.
* @return {string}
*/
getTargetOrigin() {
if (this.targetOrigin_ == null) {
throw new Error('not connected');
}
return this.targetOrigin_;
}
/**
* The host sends this message to the client to indicate that it's ready to
* start communicating. The client is expected to respond back with the
* "start" command. See `sendStartCommand` method.
*/
sendConnectCommand() {
// TODO: MessageChannel is critically necessary for IE/Edge,
// since window messaging doesn't always work. It's also preferred as an API
// for other browsers: it's newer, cleaner and arguably more secure.
// Unfortunately, browsers currently do not propagate user gestures via
// MessageChannel, only via window messaging. This should be re-enabled
// once browsers fix user gesture propagation.
// See:
// Safari: https://bugs.webkit.org/show_bug.cgi?id=186593
// Chrome: https://bugs.chromium.org/p/chromium/issues/detail?id=851493
// Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1469422
const acceptsChannel = isIeBrowser(this.win_) || isEdgeBrowser(this.win_);
this.sendCommand('connect', {'acceptsChannel': acceptsChannel});
}
/**
* The client sends this message to the host upon receiving the "connect"
* message to start the main communication channel. As a payload, the message
* will contain the provided start arguments.
* @param {?Object} args
*/
sendStartCommand(args) {
let channel = null;
if (this.acceptsChannel_ && typeof this.win_.MessageChannel == 'function') {
channel = new this.win_.MessageChannel();
}
if (channel) {
this.sendCommand('start', args, [channel.port2]);
// It's critical to switch to port messaging only after "start" has been
// sent. Otherwise, it won't be delivered.
this.switchToChannel_(channel.port1);
} else {
this.sendCommand('start', args);
}
}
/**
* Sends the specified command from the port to the host or vice versa.
* @param {string} cmd
* @param {?Object=} opt_payload
* @param {?Array=} opt_transfer
*/
sendCommand(cmd, opt_payload, opt_transfer) {
const data = {
'sentinel': SENTINEL,
'cmd': cmd,
'payload': opt_payload || null,
};
if (this.port_) {
this.port_.postMessage(data, opt_transfer || undefined);
} else {
const target = this.getTarget();
// Only "connect" command is allowed to use `targetOrigin == '*'`
const targetOrigin =
cmd == 'connect' ?
(this.targetOrigin_ != null ? this.targetOrigin_ : '*') :
this.getTargetOrigin();
target.postMessage(data, targetOrigin, opt_transfer || undefined);
}
}
/**
* Sends a message to the client.
* @param {!Object} payload
*/
customMessage(payload) {
this.sendCommand('msg', payload);
}
/**
* Registers a callback to receive messages from the client.
* @param {function(!Object)} callback
*/
onCustomMessage(callback) {
this.onCustomMessage_ = callback;
}
/**
* @param {string=} opt_name
* @return {!Promise<!MessagePort>}
*/
startChannel(opt_name) {
const name = opt_name || '';
const channelObj = this.getChannelObj_(name);
if (!channelObj.port1) {
const channel = new this.win_.MessageChannel();
channelObj.port1 = channel.port1;
channelObj.port2 = channel.port2;
channelObj.resolver(channelObj.port1);
}
if (channelObj.port2) {
// Not yet sent.
this.sendCommand('cnset', {'name': name}, [channelObj.port2]);
channelObj.port2 = null;
}
return channelObj.promise;
}
/**
* @param {string=} opt_name
* @return {!Promise<!MessagePort>}
*/
askChannel(opt_name) {
const name = opt_name || '';
const channelObj = this.getChannelObj_(name);
if (!channelObj.port1) {
this.sendCommand('cnget', {'name': name});
}
return channelObj.promise;
}
/**
* @param {string} name
* @param {!MessagePort} port
* @private
*/
receiveChannel_(name, port) {
const channelObj = this.getChannelObj_(name);
channelObj.port1 = port;
channelObj.resolver(port);
}
/**
* @param {string} name
* @return {!ChannelHolder}
*/
getChannelObj_(name) {
if (!this.channels_) {
this.channels_ = {};
}
let channelObj = this.channels_[name];
if (!channelObj) {
let resolver;
const promise = new Promise(resolve => {
resolver = resolve;
});
channelObj = {
port1: null,
port2: null,
resolver,
promise,
};
this.channels_[name] = channelObj;
}
return channelObj;
}
/**
* @param {!MessagePort} port
* @private
*/
switchToChannel_(port) {
if (this.port_) {
closePort(this.port_);
}
this.port_ = port;
this.port_.onmessage = event => {
const data = event.data;
const cmd = data && data['cmd'];
const payload = data && data['payload'] || null;
if (cmd) {
this.handleCommand_(cmd, payload, event);
}
};
// Even though all messaging will switch to ports, the window-based message
// listener will be preserved just in case the host is refreshed and needs
// another connection.
}
/**
* @param {!Event} event
* @private
*/
handleEvent_(event) {
const data = event.data;
if (!data || data['sentinel'] != SENTINEL) {
return;
}
const cmd = data['cmd'];
if (this.port_ && cmd != 'connect' && cmd != 'start') {
// Messaging channel has already taken over. However, the "connect" and
// "start" commands are allowed to proceed in case re-connection is
// requested.
return;
}
const origin = /** @type {string} */ (event.origin);
const payload = data['payload'] || null;
if (this.targetOrigin_ == null && cmd == 'start') {
this.targetOrigin_ = origin;
}
if (this.targetOrigin_ == null && event.source) {
if (this.getOptionalTarget_() == event.source) {
this.targetOrigin_ = origin;
}
}
// Notice that event.source may differ from the target because of
// friendly-iframe intermediaries.
if (origin != this.targetOrigin_) {
return;
}
this.handleCommand_(cmd, payload, event);
}
/**
* @param {string} cmd
* @param {?Object} payload
* @param {!Event} event
* @private
*/
handleCommand_(cmd, payload, event) {
if (cmd == 'connect') {
if (this.port_) {
// In case the port has already been open - close it to reopen it
// again later.
closePort(this.port_);
this.port_ = null;
}
this.acceptsChannel_ = payload && payload['acceptsChannel'] || false;
this.onCommand_(cmd, payload);
} else if (cmd == 'start') {
const port = event.ports && event.ports[0];
if (port) {
this.switchToChannel_(port);
}
this.onCommand_(cmd, payload);
} else if (cmd == 'msg') {
if (this.onCustomMessage_ != null && payload != null) {
this.onCustomMessage_(payload);
}
} else if (cmd == 'cnget') {
const name = payload['name'];
this.startChannel(name);
} else if (cmd == 'cnset') {
const name = payload['name'];
const port = event.ports[0];
this.receiveChannel_(name, /** @type {!MessagePort} */ (port));
} else {
this.onCommand_(cmd, payload);
}
}
} |
JavaScript | class ActivityIframeHost {
/**
* @param {!Window} win
*/
constructor(win) {
/** @private @const {!Window} */
this.win_ = win;
/** @private {!Window} */
this.target_ = win.parent;
/** @private @const {!Messenger} */
this.messenger_ = new Messenger(
this.win_,
this.target_,
/* targetOrigin */ null);
/** @private {?Object} */
this.args_ = null;
/** @private {boolean} */
this.connected_ = false;
/** @private {?function(!ActivityHost)} */
this.connectedResolver_ = null;
/** @private @const {!Promise<!ActivityHost>} */
this.connectedPromise_ = new Promise(resolve => {
this.connectedResolver_ = resolve;
});
/** @private {boolean} */
this.accepted_ = false;
/** @private {?function(number, number, boolean)} */
this.onResizeComplete_ = null;
/** @private {?Element} */
this.sizeContainer_ = null;
/** @private {number} */
this.lastMeasuredWidth_ = 0;
/** @private {number} */
this.lastRequestedHeight_ = 0;
/** @private @const {function()} */
this.boundResizeEvent_ = this.resizeEvent_.bind(this);
}
/**
* Connects the activity to the client.
* @return {!Promise<!ActivityHost>}
*/
connect() {
this.connected_ = false;
this.accepted_ = false;
this.messenger_.connect(this.handleCommand_.bind(this));
this.messenger_.sendConnectCommand();
return this.connectedPromise_;
}
/** @override */
disconnect() {
this.connected_ = false;
this.accepted_ = false;
this.messenger_.disconnect();
this.win_.removeEventListener('resize', this.boundResizeEvent_);
}
/** @override */
getRequestString() {
this.ensureConnected_();
// Not available for iframes.
return null;
}
/** @override */
getMode() {
return ActivityMode.IFRAME;
}
/** @override */
getTargetOrigin() {
this.ensureConnected_();
return this.messenger_.getTargetOrigin();
}
/** @override */
isTargetOriginVerified() {
this.ensureConnected_();
// The origin is always verified via messaging.
return true;
}
/** @override */
isSecureChannel() {
return true;
}
/** @override */
accept() {
this.ensureConnected_();
this.accepted_ = true;
}
/** @override */
getArgs() {
this.ensureConnected_();
return this.args_;
}
/**
* Signals to the opener that the iframe is ready to be interacted with.
* At this point, the host will start tracking iframe's size.
* @override
*/
ready() {
this.ensureAccepted_();
this.messenger_.sendCommand('ready');
this.resized_();
this.win_.addEventListener('resize', this.boundResizeEvent_);
}
/** @override */
setSizeContainer(element) {
this.sizeContainer_ = element;
}
/** @override */
onResizeComplete(callback) {
this.onResizeComplete_ = callback;
}
/** @override */
resized() {
setTimeout(() => this.resized_(), 50);
}
/** @override */
isMessagingSupported() {
return true;
}
/** @override */
message(payload) {
this.ensureAccepted_();
this.messenger_.customMessage(payload);
}
/** @override */
onMessage(callback) {
this.ensureAccepted_();
this.messenger_.onCustomMessage(callback);
}
/** @override */
messageChannel(opt_name) {
this.ensureAccepted_();
return this.messenger_.startChannel(opt_name);
}
/** @override */
result(data) {
this.sendResult_(ActivityResultCode.OK, data);
}
/** @override */
cancel() {
this.sendResult_(ActivityResultCode.CANCELED, /* data */ null);
}
/** @override */
failed(reason) {
this.sendResult_(ActivityResultCode.FAILED, String(reason));
}
/** @private */
ensureConnected_() {
if (!this.connected_) {
throw new Error('not connected');
}
}
/** @private */
ensureAccepted_() {
if (!this.accepted_) {
throw new Error('not accepted');
}
}
/**
* @param {!ActivityResultCode} code
* @param {*} data
* @private
*/
sendResult_(code, data) {
// Only require "accept" for successful return.
if (code == ActivityResultCode.OK) {
this.ensureAccepted_();
} else {
this.ensureConnected_();
}
this.messenger_.sendCommand('result', {
'code': code,
'data': data,
});
// Do not disconnect, wait for "close" message to ack the result receipt.
}
/**
* @param {string} cmd
* @param {?Object} payload
* @private
*/
handleCommand_(cmd, payload) {
if (cmd == 'start') {
// Response to "connect" command.
this.args_ = payload;
this.connected_ = true;
this.connectedResolver_(this);
this.connectedResolver_ = null;
} else if (cmd == 'close') {
this.disconnect();
} else if (cmd == 'resized') {
const allowedHeight = payload['height'];
if (this.onResizeComplete_) {
this.onResizeComplete_(
allowedHeight,
this.lastRequestedHeight_,
allowedHeight < this.lastRequestedHeight_);
}
}
}
/** @private */
resized_() {
if (this.sizeContainer_) {
const requestedHeight = this.sizeContainer_.scrollHeight;
if (requestedHeight != this.lastRequestedHeight_) {
this.lastRequestedHeight_ = requestedHeight;
this.messenger_.sendCommand('resize', {
'height': this.lastRequestedHeight_,
});
}
}
}
/** @private */
resizeEvent_() {
const width = this.win_./*OK*/innerWidth;
if (this.lastMeasuredWidth_ != width) {
this.lastMeasuredWidth_ = width;
this.resized();
}
}
} |
JavaScript | class ActivityWindowPopupHost {
/**
* @param {!Window} win
*/
constructor(win) {
if (!win.opener || win.opener == win) {
throw new Error('No window.opener');
}
/** @private @const {!Window} */
this.win_ = win;
/** @private {!Window} */
this.target_ = win.opener;
/** @private @const {!Messenger} */
this.messenger_ = new Messenger(
this.win_,
this.target_,
/* targetOrigin */ null);
/** @private {?Object} */
this.args_ = null;
/** @private {boolean} */
this.connected_ = false;
/** @private {?function(!ActivityHost)} */
this.connectedResolver_ = null;
/** @private @const {!Promise<!ActivityHost>} */
this.connectedPromise_ = new Promise(resolve => {
this.connectedResolver_ = resolve;
});
/** @private {boolean} */
this.accepted_ = false;
/** @private {?function(number, number, boolean)} */
this.onResizeComplete_ = null;
/** @private {?Element} */
this.sizeContainer_ = null;
/** @private @const {!ActivityWindowRedirectHost} */
this.redirectHost_ = new ActivityWindowRedirectHost(this.win_);
/** @private @const {!Function} */
this.boundUnload_ = this.unload_.bind(this);
}
/**
* Connects the activity to the client.
* @param {(?ActivityRequest|?string)=} opt_request
* @return {!Promise<!ActivityHost>}
*/
connect(opt_request) {
this.connected_ = false;
this.accepted_ = false;
return this.redirectHost_.connect(opt_request).then(() => {
this.messenger_.connect(this.handleCommand_.bind(this));
this.messenger_.sendConnectCommand();
// Give the popup channel ~5 seconds to connect and if it can't,
// assume that the client is offloaded and proceed with redirect.
setTimeout(() => {
if (this.connectedResolver_) {
this.connectedResolver_(this.redirectHost_);
this.connectedResolver_ = null;
}
}, 5000);
return this.connectedPromise_;
});
}
/** @override */
disconnect() {
this.connected_ = false;
this.accepted_ = false;
this.messenger_.disconnect();
this.win_.removeEventListener('unload', this.boundUnload_);
// Try to close the window. A similar attempt will be made by the client
// port.
try {
this.win_.close();
} catch (e) {
// Ignore.
}
// TODO: consider an optional "failed to close" callback. Wait
// for ~5s and check `this.win_.closed`.
}
/** @override */
getRequestString() {
this.ensureConnected_();
return this.redirectHost_.getRequestString();
}
/** @override */
getMode() {
return ActivityMode.POPUP;
}
/** @override */
getTargetOrigin() {
this.ensureConnected_();
return this.messenger_.getTargetOrigin();
}
/** @override */
isTargetOriginVerified() {
this.ensureConnected_();
// The origin is always verified via messaging.
return true;
}
/** @override */
isSecureChannel() {
return true;
}
/** @override */
accept() {
this.ensureConnected_();
this.accepted_ = true;
}
/** @override */
getArgs() {
this.ensureConnected_();
return this.args_;
}
/** @override */
ready() {
this.ensureAccepted_();
this.messenger_.sendCommand('ready');
}
/** @override */
setSizeContainer(element) {
this.sizeContainer_ = element;
}
/** @override */
onResizeComplete(callback) {
this.onResizeComplete_ = callback;
}
/** @override */
resized() {
setTimeout(() => this.resized_(), 50);
}
/** @override */
isMessagingSupported() {
return false;
}
/** @override */
message() {
this.ensureAccepted_();
// Not supported for compatibility with redirect mode.
}
/** @override */
onMessage() {
this.ensureAccepted_();
// Not supported for compatibility with redirect mode.
}
/** @override */
messageChannel(opt_name) {
this.ensureAccepted_();
throw new Error('not supported');
}
/** @override */
result(data) {
this.sendResult_(ActivityResultCode.OK, data);
}
/** @override */
cancel() {
this.sendResult_(ActivityResultCode.CANCELED, /* data */ null);
}
/** @override */
failed(reason) {
this.sendResult_(ActivityResultCode.FAILED, String(reason));
}
/** @private */
ensureConnected_() {
if (!this.connected_) {
throw new Error('not connected');
}
}
/** @private */
ensureAccepted_() {
if (!this.accepted_) {
throw new Error('not accepted');
}
}
/**
* @param {!ActivityResultCode} code
* @param {*} data
* @private
*/
sendResult_(code, data) {
// Only require "accept" for successful return.
if (code == ActivityResultCode.OK) {
this.ensureAccepted_();
} else {
this.ensureConnected_();
}
this.messenger_.sendCommand('result', {
'code': code,
'data': data,
});
// Do not disconnect, wait for "close" message to ack the result receipt.
this.win_.removeEventListener('unload', this.boundUnload_);
// TODO: Consider taking an action if result acknowledgement
// does not arrive in some time (3-5s). For instance, we can redirect
// back or ask the host implementer to take an action.
}
/**
* @param {string} cmd
* @param {?Object} payload
* @private
*/
handleCommand_(cmd, payload) {
if (cmd == 'start') {
// Response to "connect" command.
this.args_ = payload;
this.connected_ = true;
this.connectedResolver_(this);
this.win_.addEventListener('unload', this.boundUnload_);
} else if (cmd == 'close') {
this.disconnect();
}
}
/** @private */
resized_() {
if (this.sizeContainer_) {
const requestedHeight = this.sizeContainer_.scrollHeight;
const allowedHeight = this.win_./*OK*/innerHeight;
if (this.onResizeComplete_) {
this.onResizeComplete_(
allowedHeight,
requestedHeight,
allowedHeight < requestedHeight);
}
}
}
/** @private */
unload_() {
this.messenger_.sendCommand('check', {});
}
} |
JavaScript | class ActivityWindowRedirectHost {
/**
* @param {!Window} win
*/
constructor(win) {
/** @private @const {!Window} */
this.win_ = win;
/** @private {?string} */
this.requestId_ = null;
/** @private {?string} */
this.returnUrl_ = null;
/** @private {?string} */
this.targetOrigin_ = null;
/** @private {boolean} */
this.targetOriginVerified_ = false;
/** @private {?Object} */
this.args_ = null;
/** @private {boolean} */
this.connected_ = false;
/** @private {boolean} */
this.accepted_ = false;
/** @private {?function(number, number, boolean)} */
this.onResizeComplete_ = null;
/** @private {?Element} */
this.sizeContainer_ = null;
}
/**
* Connects the activity to the client.
*
* Notice, if `opt_request` parameter is specified, the host explicitly
* trusts all fields encoded in this request.
*
* @param {(?ActivityRequest|?string)=} opt_request
* @return {!Promise}
*/
connect(opt_request) {
return Promise.resolve().then(() => {
this.connected_ = false;
this.accepted_ = false;
let request;
if (opt_request && typeof opt_request == 'object') {
request = opt_request;
} else {
let requestTrusted = false;
let requestString;
if (opt_request && typeof opt_request == 'string') {
// When request is passed as an argument, it's parsed as "trusted".
requestTrusted = true;
requestString = opt_request;
} else {
const fragmentRequestParam =
getQueryParam(this.win_.location.hash, '__WA__');
if (fragmentRequestParam) {
requestString = decodeURIComponent(fragmentRequestParam);
}
}
if (requestString) {
request = parseRequest(requestString, requestTrusted);
}
}
if (!request || !request.requestId || !request.returnUrl) {
throw new Error('Request must have requestId and returnUrl');
}
this.requestId_ = request.requestId;
this.args_ = request.args;
this.returnUrl_ = request.returnUrl;
if (request.origin) {
// Trusted request: trust origin and verified flag explicitly.
this.targetOrigin_ = request.origin;
this.targetOriginVerified_ = request.originVerified || false;
} else {
// Otherwise, infer the origin/verified from other parameters.
this.targetOrigin_ = getOriginFromUrl(request.returnUrl);
// Use referrer to conditionally verify the origin. Notice, that
// the channel security will remain "not secure".
const referrerOrigin = (this.win_.document.referrer &&
getOriginFromUrl(this.win_.document.referrer));
this.targetOriginVerified_ = (referrerOrigin == this.targetOrigin_);
}
this.connected_ = true;
return this;
});
}
/** @override */
disconnect() {
this.connected_ = false;
this.accepted_ = false;
}
/** @override */
getRequestString() {
this.ensureConnected_();
return serializeRequest({
requestId: /** @type {string} */ (this.requestId_),
returnUrl: /** @type {string} */ (this.returnUrl_),
args: this.args_,
origin: /** @type {string} */ (this.targetOrigin_),
originVerified: this.targetOriginVerified_,
});
}
/** @override */
getMode() {
return ActivityMode.REDIRECT;
}
/** @override */
getTargetOrigin() {
this.ensureConnected_();
return /** @type {string} */ (this.targetOrigin_);
}
/** @override */
isTargetOriginVerified() {
this.ensureConnected_();
return this.targetOriginVerified_;
}
/** @override */
isSecureChannel() {
return false;
}
/** @override */
accept() {
this.ensureConnected_();
this.accepted_ = true;
}
/** @override */
getArgs() {
this.ensureConnected_();
return this.args_;
}
/** @override */
ready() {
this.ensureAccepted_();
}
/** @override */
setSizeContainer(element) {
this.sizeContainer_ = element;
}
/** @override */
onResizeComplete(callback) {
this.onResizeComplete_ = callback;
}
/** @override */
resized() {
setTimeout(() => this.resized_(), 50);
}
/** @override */
isMessagingSupported() {
return false;
}
/** @override */
message() {
this.ensureAccepted_();
// Not supported. Infeasible.
}
/** @override */
onMessage() {
this.ensureAccepted_();
// Not supported. Infeasible.
}
/** @override */
messageChannel(opt_name) {
this.ensureAccepted_();
throw new Error('not supported');
}
/** @override */
result(data) {
this.sendResult_(ActivityResultCode.OK, data);
}
/** @override */
cancel() {
this.sendResult_(ActivityResultCode.CANCELED, /* data */ null);
}
/** @override */
failed(reason) {
this.sendResult_(ActivityResultCode.FAILED, String(reason));
}
/** @private */
ensureConnected_() {
if (!this.connected_) {
throw new Error('not connected');
}
}
/** @private */
ensureAccepted_() {
if (!this.accepted_) {
throw new Error('not accepted');
}
}
/**
* @param {!ActivityResultCode} code
* @param {*} data
* @private
*/
sendResult_(code, data) {
// Only require "accept" for successful return.
if (code == ActivityResultCode.OK) {
this.ensureAccepted_();
} else {
this.ensureConnected_();
}
const response = {
'requestId': this.requestId_,
'origin': getWindowOrigin(this.win_),
'code': code,
'data': data,
};
const returnUrl =
this.returnUrl_ +
(this.returnUrl_.indexOf('#') == -1 ? '#' : '&') +
'__WA_RES__=' + encodeURIComponent(JSON.stringify(response));
this.redirect_(returnUrl);
}
/**
* @param {string} returnUrl
* @private
*/
redirect_(returnUrl) {
if (this.win_.location.replace) {
this.win_.location.replace(returnUrl);
} else {
this.win_.location.assign(returnUrl);
}
}
/** @private */
resized_() {
if (this.sizeContainer_) {
const requestedHeight = this.sizeContainer_.scrollHeight;
const allowedHeight = this.win_./*OK*/innerHeight;
if (this.onResizeComplete_) {
this.onResizeComplete_(
allowedHeight,
requestedHeight,
allowedHeight < requestedHeight);
}
}
}
} |
JavaScript | class ActivityHosts {
/**
* @param {!Window} win
*/
constructor(win) {
/** @const {string} */
this.version = '1.12';
/** @private @const {!Window} */
this.win_ = win;
}
/**
* Start activity implementation handler (host).
* @param {(?ActivityRequest|?string)=} opt_request
* @return {!Promise<!ActivityHost>}
*/
connectHost(opt_request) {
let host;
if (this.win_.top != this.win_) {
// Iframe host.
host = new ActivityIframeHost(this.win_);
} else if (this.win_.opener && this.win_.opener != this.win_ &&
!this.win_.opener.closed) {
// Window host: popup.
host = new ActivityWindowPopupHost(this.win_);
} else {
// Window host: redirect.
host = new ActivityWindowRedirectHost(this.win_);
}
return host.connect(opt_request);
}
} |
JavaScript | class MessageSource {
nickname_ = null;
username_ = null;
hostname_ = null;
isServer_ = false;
isUser_ = false;
// Gets the nickname, if any, associated with this source.
get nickname() { return this.nickname_; }
// Gets the username, if any, associated with this source.
get username() { return this.username_; }
// Gets the hostname, if any, associated with this source.
get hostname() { return this.hostname_; }
// Returns whether this source represents a server.
isServer() { return this.isServer_; }
// Returns whether this source represents a user.
isUser() { return this.isUser_; }
// Parses the |source| string into a MessageSource structure. An exception will be thrown
// on invalid formats.
constructor(source) {
if (typeof source !== 'string' || !source.length)
throw new Error('Invalid source given: ' + source);
const dotPosition = source.indexOf('.');
const userPosition = source.indexOf('!');
const hostPosition = source.indexOf('@');
if (userPosition !== -1) {
if (hostPosition === -1)
throw new Error('Invalid source given (missing host): ' + source);
this.nickname_ = source.substring(0, userPosition);
this.username_ = source.substring(userPosition + 1, hostPosition);
this.hostname_ = source.substring(hostPosition + 1);
this.isUser_ = true;
return;
}
if (hostPosition !== -1) {
this.nickname_ = source.substring(0, hostPosition);
this.hostname_ = source.substring(hostPosition + 1);
this.isUser_ = true;
return;
}
if (dotPosition !== -1) {
this.hostname_ = source;
this.isServer_ = true;
return;
}
this.nickname_ = source;
this.isUser_ = true;
}
// Converts the source back to a string object. This should be identical to the input string
// given, but no guarantees will be made.
toString() {
if (this.isServer_)
return this.hostname_;
let output = this.nickname_;
if (this.username_)
output += '!' + this.username_;
if (this.hostname_)
output += '@' + this.hostname_;
return output;
}
} |
JavaScript | class AnimateMovePromo extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
let logo = new Image(16, 16);
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
logo.src = "/favicon.ico";
logo.onload = () => {
console.log("Image was loaded");
context.drawImage(logo, 0, 0, 16, 16);
// Let's extract each pixel of Inferno logo
let imageData = context.getImageData(0, 0, 16, 16);
const pixelsRGBA = Array.from(imageData.data);
// ^ It's [r0, g0, b0, a0, r1, g1, ...]
const pixelLength = 4; // It's RGBA. right?
// Let's group RGBA numbers into arrays of length `pixelLength`
const groupedPixels = pixelsRGBA.map((_, index) => {
if (index % pixelLength == 0) return pixelsRGBA.slice(index, index+4);
}).filter(p => Boolean(p));
this.setState({
items: Array.from(
groupedPixels.map((numbers) => {
return "#" + numbers.map((number) => {
let s = number.toString(16);
return s.length == 1? "0" + s : s;
}).join("") + "-" + generateRandomId();
})
)
});
};
}
doShuffle = (e) => {
e.preventDefault();
this.setState({
items: shuffle(this.state.items)
});
}
render() {
const { items } = this.state;
return (
<div className="animate-move-promo">
<div className="button-wrapper" $HasVNodeChildren>
<button
className="button second small"
onClick={this.doShuffle}
$HasTextChildren
>
Shuffle
</button>
</div>
<div className="animate-grid" $HasKeyedChildren>
{items.map(item => <GridItem
key={item.split("-")[1]}
color={item.split("-")[0]}
animation="AnimateMove"
onComponentWillMove={componentWillMove} />)}
</div>
</div>
);
}
} |
JavaScript | class PhotoGrid extends Component {
render() {
return (
<div className="photo-grid">
{this.props.posts.map((post, i) => <Photo {...this.props} key={post.id} i={i} post={post}/>)}
</div>
);
}
} |
JavaScript | class YMultiAxisController extends YFunction
{
constructor(obj_yapi, str_func)
{
//--- (YMultiAxisController constructor)
super(obj_yapi, str_func);
/** @member {string} **/
this._className = 'MultiAxisController';
/** @member {number} **/
this._nAxis = YMultiAxisController.NAXIS_INVALID;
/** @member {number} **/
this._globalState = YMultiAxisController.GLOBALSTATE_INVALID;
/** @member {string} **/
this._command = YMultiAxisController.COMMAND_INVALID;
//--- (end of YMultiAxisController constructor)
}
//--- (YMultiAxisController implementation)
imm_parseAttr(name, val)
{
switch(name) {
case 'nAxis':
this._nAxis = parseInt(val);
return 1;
case 'globalState':
this._globalState = parseInt(val);
return 1;
case 'command':
this._command = val;
return 1;
}
return super.imm_parseAttr(name, val);
}
/**
* Returns the number of synchronized controllers.
*
* @return {number} an integer corresponding to the number of synchronized controllers
*
* On failure, throws an exception or returns YMultiAxisController.NAXIS_INVALID.
*/
async get_nAxis()
{
/** @type {number} **/
let res;
if (this._cacheExpiration <= this._yapi.GetTickCount()) {
if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) {
return YMultiAxisController.NAXIS_INVALID;
}
}
res = this._nAxis;
return res;
}
/**
* Changes the number of synchronized controllers.
*
* @param newval {number} : an integer corresponding to the number of synchronized controllers
*
* @return {number} YAPI.SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
async set_nAxis(newval)
{
/** @type {string} **/
let rest_val;
rest_val = String(newval);
return await this._setAttr('nAxis',rest_val);
}
/**
* Returns the stepper motor set overall state.
*
* @return {number} a value among YMultiAxisController.GLOBALSTATE_ABSENT,
* YMultiAxisController.GLOBALSTATE_ALERT, YMultiAxisController.GLOBALSTATE_HI_Z,
* YMultiAxisController.GLOBALSTATE_STOP, YMultiAxisController.GLOBALSTATE_RUN and
* YMultiAxisController.GLOBALSTATE_BATCH corresponding to the stepper motor set overall state
*
* On failure, throws an exception or returns YMultiAxisController.GLOBALSTATE_INVALID.
*/
async get_globalState()
{
/** @type {number} **/
let res;
if (this._cacheExpiration <= this._yapi.GetTickCount()) {
if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) {
return YMultiAxisController.GLOBALSTATE_INVALID;
}
}
res = this._globalState;
return res;
}
async get_command()
{
/** @type {string} **/
let res;
if (this._cacheExpiration <= this._yapi.GetTickCount()) {
if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) {
return YMultiAxisController.COMMAND_INVALID;
}
}
res = this._command;
return res;
}
async set_command(newval)
{
/** @type {string} **/
let rest_val;
rest_val = newval;
return await this._setAttr('command',rest_val);
}
/**
* Retrieves a multi-axis controller for a given identifier.
* The identifier can be specified using several formats:
* <ul>
* <li>FunctionLogicalName</li>
* <li>ModuleSerialNumber.FunctionIdentifier</li>
* <li>ModuleSerialNumber.FunctionLogicalName</li>
* <li>ModuleLogicalName.FunctionIdentifier</li>
* <li>ModuleLogicalName.FunctionLogicalName</li>
* </ul>
*
* This function does not require that the multi-axis controller is online at the time
* it is invoked. The returned object is nevertheless valid.
* Use the method YMultiAxisController.isOnline() to test if the multi-axis controller is
* indeed online at a given time. In case of ambiguity when looking for
* a multi-axis controller by logical name, no error is notified: the first instance
* found is returned. The search is performed first by hardware name,
* then by logical name.
*
* If a call to this object's is_online() method returns FALSE although
* you are certain that the matching device is plugged, make sure that you did
* call registerHub() at application initialization time.
*
* @param func {string} : a string that uniquely characterizes the multi-axis controller
*
* @return {YMultiAxisController} a YMultiAxisController object allowing you to drive the multi-axis controller.
*/
static FindMultiAxisController(func)
{
/** @type {YFunction} **/
let obj;
obj = YFunction._FindFromCache('MultiAxisController', func);
if (obj == null) {
obj = new YMultiAxisController(YAPI, func);
YFunction._AddToCache('MultiAxisController', func, obj);
}
return obj;
}
/**
* Retrieves a multi-axis controller for a given identifier in a YAPI context.
* The identifier can be specified using several formats:
* <ul>
* <li>FunctionLogicalName</li>
* <li>ModuleSerialNumber.FunctionIdentifier</li>
* <li>ModuleSerialNumber.FunctionLogicalName</li>
* <li>ModuleLogicalName.FunctionIdentifier</li>
* <li>ModuleLogicalName.FunctionLogicalName</li>
* </ul>
*
* This function does not require that the multi-axis controller is online at the time
* it is invoked. The returned object is nevertheless valid.
* Use the method YMultiAxisController.isOnline() to test if the multi-axis controller is
* indeed online at a given time. In case of ambiguity when looking for
* a multi-axis controller by logical name, no error is notified: the first instance
* found is returned. The search is performed first by hardware name,
* then by logical name.
*
* @param yctx {YAPIContext} : a YAPI context
* @param func {string} : a string that uniquely characterizes the multi-axis controller
*
* @return {YMultiAxisController} a YMultiAxisController object allowing you to drive the multi-axis controller.
*/
static FindMultiAxisControllerInContext(yctx,func)
{
/** @type {YFunction} **/
let obj;
obj = YFunction._FindFromCacheInContext(yctx, 'MultiAxisController', func);
if (obj == null) {
obj = new YMultiAxisController(yctx, func);
YFunction._AddToCache('MultiAxisController', func, obj);
}
return obj;
}
async sendCommand(command)
{
/** @type {string} **/
let url;
/** @type {Uint8Array} **/
let retBin;
/** @type {number} **/
let res;
url = 'cmd.txt?X='+command;
//may throw an exception
retBin = await this._download(url);
res = retBin[0];
if (res == 49) {
if (!(res == 48)) {
return this._throw(this._yapi.DEVICE_BUSY,'Motor command pipeline is full, try again later',this._yapi.DEVICE_BUSY);
}
} else {
if (!(res == 48)) {
return this._throw(this._yapi.IO_ERROR,'Motor command failed permanently',this._yapi.IO_ERROR);
}
}
return this._yapi.SUCCESS;
}
/**
* Reinitialize all controllers and clear all alert flags.
*
* @return {number} YAPI.SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
async reset()
{
return await this.sendCommand('Z');
}
/**
* Starts all motors backward at the specified speeds, to search for the motor home position.
*
* @param speed {number[]} : desired speed for all axis, in steps per second.
*
* @return {number} YAPI.SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
async findHomePosition(speed)
{
/** @type {string} **/
let cmd;
/** @type {number} **/
let i;
/** @type {number} **/
let ndim;
ndim = speed.length;
cmd = 'H'+String(Math.round(Math.round(1000*speed[0])));
i = 1;
while (i < ndim) {
cmd = cmd+','+String(Math.round(Math.round(1000*speed[i])));
i = i + 1;
}
return await this.sendCommand(cmd);
}
/**
* Starts all motors synchronously to reach a given absolute position.
* The time needed to reach the requested position will depend on the lowest
* acceleration and max speed parameters configured for all motors.
* The final position will be reached on all axis at the same time.
*
* @param absPos {number[]} : absolute position, measured in steps from each origin.
*
* @return {number} YAPI.SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
async moveTo(absPos)
{
/** @type {string} **/
let cmd;
/** @type {number} **/
let i;
/** @type {number} **/
let ndim;
ndim = absPos.length;
cmd = 'M'+String(Math.round(Math.round(16*absPos[0])));
i = 1;
while (i < ndim) {
cmd = cmd+','+String(Math.round(Math.round(16*absPos[i])));
i = i + 1;
}
return await this.sendCommand(cmd);
}
/**
* Starts all motors synchronously to reach a given relative position.
* The time needed to reach the requested position will depend on the lowest
* acceleration and max speed parameters configured for all motors.
* The final position will be reached on all axis at the same time.
*
* @param relPos {number[]} : relative position, measured in steps from the current position.
*
* @return {number} YAPI.SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
async moveRel(relPos)
{
/** @type {string} **/
let cmd;
/** @type {number} **/
let i;
/** @type {number} **/
let ndim;
ndim = relPos.length;
cmd = 'm'+String(Math.round(Math.round(16*relPos[0])));
i = 1;
while (i < ndim) {
cmd = cmd+','+String(Math.round(Math.round(16*relPos[i])));
i = i + 1;
}
return await this.sendCommand(cmd);
}
/**
* Keep the motor in the same state for the specified amount of time, before processing next command.
*
* @param waitMs {number} : wait time, specified in milliseconds.
*
* @return {number} YAPI.SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
async pause(waitMs)
{
return await this.sendCommand('_'+String(Math.round(waitMs)));
}
/**
* Stops the motor with an emergency alert, without taking any additional precaution.
*
* @return {number} YAPI.SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
async emergencyStop()
{
return await this.sendCommand('!');
}
/**
* Stops the motor smoothly as soon as possible, without waiting for ongoing move completion.
*
* @return {number} YAPI.SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
async abortAndBrake()
{
return await this.sendCommand('B');
}
/**
* Turn the controller into Hi-Z mode immediately, without waiting for ongoing move completion.
*
* @return {number} YAPI.SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
async abortAndHiZ()
{
return await this.sendCommand('z');
}
/**
* Continues the enumeration of multi-axis controllers started using yFirstMultiAxisController().
*
* @return {YMultiAxisController} a pointer to a YMultiAxisController object, corresponding to
* a multi-axis controller currently online, or a null pointer
* if there are no more multi-axis controllers to enumerate.
*/
nextMultiAxisController()
{
/** @type {object} **/
let resolve = this._yapi.imm_resolveFunction(this._className, this._func);
if(resolve.errorType != YAPI.SUCCESS) return null;
/** @type {string|null} **/
let next_hwid = this._yapi.imm_getNextHardwareId(this._className, resolve.result);
if(next_hwid == null) return null;
return YMultiAxisController.FindMultiAxisControllerInContext(this._yapi, next_hwid);
}
/**
* Starts the enumeration of multi-axis controllers currently accessible.
* Use the method YMultiAxisController.nextMultiAxisController() to iterate on
* next multi-axis controllers.
*
* @return {YMultiAxisController} a pointer to a YMultiAxisController object, corresponding to
* the first multi-axis controller currently online, or a null pointer
* if there are none.
*/
static FirstMultiAxisController()
{
/** @type {string|null} **/
let next_hwid = YAPI.imm_getFirstHardwareId('MultiAxisController');
if(next_hwid == null) return null;
return YMultiAxisController.FindMultiAxisController(next_hwid);
}
/**
* Starts the enumeration of multi-axis controllers currently accessible.
* Use the method YMultiAxisController.nextMultiAxisController() to iterate on
* next multi-axis controllers.
*
* @param yctx {YAPIContext} : a YAPI context.
*
* @return {YMultiAxisController} a pointer to a YMultiAxisController object, corresponding to
* the first multi-axis controller currently online, or a null pointer
* if there are none.
*/
static FirstMultiAxisControllerInContext(yctx)
{
/** @type {string|null} **/
let next_hwid = yctx.imm_getFirstHardwareId('MultiAxisController');
if(next_hwid == null) return null;
return YMultiAxisController.FindMultiAxisControllerInContext(yctx, next_hwid);
}
static imm_Const()
{
return Object.assign(super.imm_Const(), {
NAXIS_INVALID : YAPI.INVALID_UINT,
GLOBALSTATE_ABSENT : 0,
GLOBALSTATE_ALERT : 1,
GLOBALSTATE_HI_Z : 2,
GLOBALSTATE_STOP : 3,
GLOBALSTATE_RUN : 4,
GLOBALSTATE_BATCH : 5,
GLOBALSTATE_INVALID : -1,
COMMAND_INVALID : YAPI.INVALID_STRING
});
}
//--- (end of YMultiAxisController implementation)
} |
JavaScript | class EditMask {
constructor(pattern, options={ }) {
const opts = defaults({}, options, defaultOptions);
this.appendLiterals = opts.appendLiterals;
this.eatInvalid = opts.eatInvalid;
this.lookahead = opts.lookahead;
this.pattern = pattern;
this.postprocess = opts.postprocess;
this.preprocess = opts.preprocess;
}
processForElt(value, elt) {
return this.process(value, elt.selectionStart, elt.selectionEnd)
}
process(value, selStart=0, selEnd=0) {
var config = {
pattern: this.pattern,
pidx: 0, // index into the pattern
vidx: 0, // index into the value
text: "", // the processed text
selectionStart: selStart,
selectionEnd: selEnd,
usedLookahead: false,
groups: [], // the matched groups
complete: false, // did evaluation of value utilize entire pattern
// scratch variables used by pattern processing
// counter for number of reads using current pattern symbol when repeating operator
// attached (+ or *)
conseqReads: 0,
//text for the current grouping
currGroup: "",
// count group depth recursion
iters: 0,
captureGroup() {
if (this.currGroup) {
this.groups.push(this.currGroup);
this.currGroup = "";
}
}
}
value = this.preprocess(value, config);
this._evaluate(value, config);
this.postprocess(config);
//truncated text handling
var truncatedValue;
var truncatedCursor;
if (config.vidx < value.length) {
truncatedValue = value.substring(config.vidx);
truncatedCursor = config.selectionStart;
}
// make sure selection is not greater than text length. This can happen when pattern finishes
// before end of text that contains the cursor
config.selectionStart = Math.min(config.selectionStart, config.text.length);
config.selectionEnd = Math.min(config.selectionEnd, config.text.length);
return {
text: config.text,
complete: config.complete,
selectionStart: config.selectionStart,
selectionEnd: config.selectionEnd,
groups: config.groups,
truncatedValue: truncatedValue,
truncatedCursor: truncatedCursor,
}
}
/*
Evaluates a value against
*/
_evaluate(value, config) {
config.iters++;
try {
if (value == null || value == undefined) {
config.text = value;
config.complete = false;
return;
}
var pattern = config.pattern;
var plen = pattern.length;
var lastPidx, token, countSpec;
var processing = true;
// Note: this loop will keep going even if value has been exceeded so can handle literal values
// at end of pattern
while (config.pidx < plen && processing) {
// only parse tokens when pattern index changes
if (config.pidx != lastPidx) {
token = nextToken(config.pidx, pattern);
countSpec = new CountSpec(token);
}
let ch = value[config.vidx];
// flag to indicate processing before the cursor. note, always true if appending literals
// because no input string characters remaining and cursor was at end of input value
let posBeforeSelStart = config.text.length < config.selectionStart
|| (!ch && config.text.length==config.selectionStart);
// handy line for debugging jest tests
// console.log(`sym=${sym}, ch=${ch}, isNumber=${isNumber} pidx=${pidx}, vidx=${vidx}`)
if (ch && config.iters==1 && !isValidPatternCharacter(ch, pattern, config.pidx, this.eatInvalid)) {
if (this.eatInvalid) {
eatInvalid(config, posBeforeSelStart);
continue;
} else {
config.captureGroup();
config.complete = !config.usedLookahead && config.pidx >= pattern.length;
return;
}
}
switch(token[0]) {
case '.': // any characater
processing = this._evaluateAnyChar(ch, token, countSpec, posBeforeSelStart, config);
break;
case '(': // capture group
processing = this._evaluateCaptureGroup(value, token, countSpec, posBeforeSelStart, config);
break;
case 'd': // digit
processing = this._evaluateDigit(ch, token, countSpec, posBeforeSelStart, config);
break;
default: // literal
processing = this._evaluateLiteral(ch, token, countSpec, posBeforeSelStart, config);
}
}
config.captureGroup();
config.complete = !config.usedLookahead && config.pidx >= pattern.length;
} finally {
config.iters--;
}
}
_evaluateCaptureGroup(value, token, countSpec, posBeforeSelStart, config) {
var oneOrMore = countSpec.isOneOrMore();
var zeroOrMore = countSpec.isZeroOrMore();
var repeatable = zeroOrMore || oneOrMore;
var origConfig = clone(config); // used to reset properties to value before capture
var iterations = 0; // count number of time capture group evaluated
var prevConfig; // used for multiple iteration reset support
// reconfigure the state object for recursive use
config.groups = []; // all groups from this capture groups will be stored in an array
config.pattern = extractGroupPattern(token); //config.pidx, config.pattern);
config.usedLookahead = false; // turn off lookahead
do {
prevConfig = clone(config);
config.complete = false;
config.pidx = 0; // recursively evaluating the capture group's pattern
this._evaluate(value, config);
if (config.complete) {
iterations++;
}
} while (config.complete && repeatable);
var capturedGroups = config.groups;
// update config values
config.pidx = origConfig.pidx + token.length; // update the pattern index first since used in calcs
config.groups = origConfig.groups; // further updated based on operator
config.pattern = origConfig.pattern;
config.usedLookahead = origConfig.usedLookahead;
var keepProcessing;
if (oneOrMore) {
keepProcessing = iterations;
// reset selection and text to previous iteration location
config.selectionStart = prevConfig.selectionStart;
config.selectionEnd = prevConfig.selectionEnd;
config.text = prevConfig.text;
if (keepProcessing) {
// going to continue processing value from location of last capture group iteration
config.vidx = prevConfig.vidx; // reset the value index
config.groups.push(prevConfig.groups); // add the groups processed through prev iteration
} else {
config.vidx = origConfig.vidx; // reset the value index
config.groups.push(undefined); // indicated capture group got nothing
}
} else if (zeroOrMore) {
keepProcessing = true;
// reset selection and text to previous iteration location
config.selectionStart = prevConfig.selectionStart;
config.selectionEnd = prevConfig.selectionEnd;
config.text = prevConfig.text;
if (iterations) {
// going to continue processing value from location of last capture group iteration
config.vidx = prevConfig.vidx; // reset the value index
config.groups.push(prevConfig.groups); // add the groups processed through prev iteration
} else {
config.vidx = origConfig.vidx; // reset the value index
config.groups.push(undefined); // indicated capture group got nothing
}
} else if (countSpec.isOptional()) {
keepProcessing = true;
if (config.complete) {
config.groups.push(capturedGroups);
} else {
// going to continue processing value from location of last capture group iteration
// so reset selection to original iteration location
config.selectionStart = origConfig.selectionStart;
config.selectionEnd = origConfig.selectionEnd;
// reset the value index and text
config.text = origConfig.text;
config.vidx = origConfig.vidx;
// indicated capture group got nothing
config.groups.push(undefined);
}
} else {
keepProcessing = config.complete;
if (keepProcessing) {
config.groups.push(capturedGroups);
} else {
// ate some characters and no more processing so move cursor back to original position
config.selectionStart = origConfig.selectionStart;
config.selectionEnd = origConfig.selectionEnd;
// reset the value index and text
config.text = origConfig.text;
config.vidx = origConfig.vidx;
// indicated capture group got nothing
config.groups.push(undefined);
}
}
config.complete = keepProcessing && config.pidx >= config.pattern.length;
assert( a => a.not(isUndefined(keepProcessing), "keepProcessing must be explicitly set"));
return keepProcessing;
}
_evaluateDigit(ch, token, countSpec, posBeforeSelStart, config) {
return this._evaluationChar(ch, token, countSpec, posBeforeSelStart, config, digitTestFn);
}
_evaluateAnyChar(ch, token, countSpec, posBeforeSelStart, config) {
return this._evaluationChar(ch, token, countSpec, posBeforeSelStart, config, anyCharTestFn);
}
_evaluationChar(nextCh, token, countSpec, posBeforeSelStart, config, testFn) {
var ch = testFn(nextCh);
var optional = countSpec.isOptional();
var zeroOrMore = countSpec.isZeroOrMore();
var oneOrMore = countSpec.isOneOrMore();
var pinc = token.length;
var lidx;
if (!nextCh) {
if (optional) {
config.pidx += pinc;
} else if (zeroOrMore) {
config.conseqReads = 0;
config.pidx += pinc;
} else if (oneOrMore) {
if (config.conseqReads) {
config.conseqReads = 0;
config.pidx += pinc;
} else {
return false;
}
} else {
return false;
}
} else if (ch) {
config.text += ch;
config.currGroup += ch;
config.vidx++;
if (oneOrMore || zeroOrMore) {
config.conseqReads++;
} else {
config.pidx += pinc;
}
} else if (optional) {
config.pidx += pinc;
} else if (zeroOrMore) {
config.conseqReads = 0;
config.pidx += pinc;
} else if (oneOrMore) {
if (config.conseqReads) {
config.conseqReads = 0;
config.pidx += pinc;
} else {
return false;
}
} else if (this.lookahead && (lidx=doLookahead(config.pidx+pinc, nextCh, config.pattern))) {
config.pidx = lidx;
config.usedLookahead = true;
} else if (this.eatInvalid) {
eatInvalid(config, posBeforeSelStart);
} else {
return false;
}
return true; // more to do
}
_evaluateLiteral(ch, token, countSpec, posBeforeSelStart, config) {
var sym = token[0];
var pinc = token.length;
var optional = countSpec.isOptional()
var oneOrMore = countSpec.isOneOrMore();
var zeroOrMore = countSpec.isZeroOrMore();
var required = countSpec.isRequired();
// if patterns symbol is the literal escape character then update the pattern
// symbol info to account
if (sym == '/') {
if (token.length === 1) {
throw new Error("/ literal escape character cannot terminate a pattern");
}
// side effects of accounting for literal escape character
sym = token[1];
}
if (sym == ch) { // symbol and value character match
config.captureGroup();
config.text += sym;
config.vidx++;
if (oneOrMore || zeroOrMore) {
config.conseqReads++;
} else {
config.pidx += pinc;
}
} else if (countSpec.isDefault() && (ch || this.appendLiterals)) {
// value character is not a match and no multiplicity operator so append the current
// literal token and keep processing
config.captureGroup();
// do not increment value index
config.text += sym;
config.pidx += pinc;
if (posBeforeSelStart) {
config.selectionStart++;
config.selectionEnd++;
}
} else {
if (ch && optional) {
// still have input and literal was optional so go to next token
config.pidx += pinc;
} else if (zeroOrMore) {
// not a match and match not necessary so go to next token
config.conseqReads = 0;
config.pidx += pinc;
} else if (ch && oneOrMore) {
// not a match and only continue if matched literal at least once
if (config.conseqReads) {
config.conseqReads = 0;
config.pidx += pinc;
} else {
return false;
}
} else if (!ch && oneOrMore && config.conseqReads) {
// handle case where no more characters and + at end and have read at least
// one macthing character
config.conseqReads = 0;
config.pidx += pinc;
} else {
// done processing
return false;
}
}
return true; // more to do
}
} |
JavaScript | class DataExplorer extends Component {
/**
* Constructor function
*/
constructor( props ) {
super( props );
let data = props.data;
let quantitative;
let categorical;
let groupVars;
if ( props.data ) {
quantitative = props.quantitative;
categorical = props.categorical;
groupVars = props.categorical.slice();
} else {
quantitative = [];
categorical = [];
groupVars = [];
}
let ready = false;
let validVariables = true;
if (
isObject( data ) &&
( quantitative.length > 0 || categorical.length > 0 )
) {
ready = true;
validVariables = checkVariables( data, quantitative.concat( categorical ) );
}
this.id = props.id || uid( props );
this.state = {
data: data,
quantitative: quantitative,
categorical: categorical,
validVariables,
output: [],
groupVars,
ready,
showStudentPlots: false,
openedNav: props.opened || ( !isNull( props.questions ) ? 'questions' : 'data' ),
studentPlots: [],
subsetFilters: null,
unaltered: {
data: props.data,
quantitative: props.quantitative,
categorical: props.categorical
},
filters: []
};
this.logAction = ( type, value ) => {
if ( this.state.subsetFilters ) {
value = { ...value, filters: this.state.subsetFilters };
}
const session = this.context;
const recipients = this.props.reportMode !== 'individual' ? 'members' : 'owners';
session.log({
id: this.id,
type,
value
}, recipients );
};
}
static getDerivedStateFromProps( nextProps, prevState ) {
if ( !nextProps.data ) {
return null;
}
const newState = {};
if (
nextProps.data !== prevState.unaltered.data
) {
newState.data = nextProps.data;
}
if ( nextProps.quantitative !== prevState.unaltered.quantitative ) {
newState.quantitative = nextProps.quantitative;
}
if ( nextProps.categorical !== prevState.unaltered.categorical ) {
newState.categorical = nextProps.categorical;
}
newState.validVariables = checkVariables(
nextProps.data,
nextProps.quantitative.concat( nextProps.categorical )
);
if ( !isEmptyObject( newState ) ) {
newState.unaltered = {
data: nextProps.data,
quantitative: nextProps.quantitative,
categorical: nextProps.categorical
};
return newState;
}
return null;
}
componentDidMount() {
const session = this.context;
if ( !this.props.data ) {
if ( session.metadata.store[ this.id ] ) {
const meta = session.metadata.store[ this.id ];
json( meta ).then( res => {
const groupVars = ( res.categorical || [] ).slice();
this.setState({
data: res.data,
quantitative: res.quantitative,
categorical: res.categorical,
groupVars,
ready: true,
unaltered: {
data: res.data,
quantitative: res.quantitative,
categorical: res.categorical
}
});
});
} else {
session.store.getItem( this.id ).then( ({ quantitative = [], categorical = [], data = null }) => {
let ready = false;
if ( isEmptyObject( data ) ) {
data = null;
}
if ( !isNull( data ) ) {
ready = true;
}
const groupVars = ( categorical || [] ).slice();
this.setState({
data,
quantitative,
categorical,
groupVars,
ready,
unaltered: {
data,
quantitative,
categorical
}
});
})
.catch( ( err ) => {
debug( err );
});
}
}
if ( session.currentUserActions ) {
const actions = session.currentUserActions[ this.id ];
if ( this.props.data && isObjectArray( actions ) ) {
this.restoreTransformations( actions );
}
}
this.unsubscribe = session.subscribe( ( type, action ) => {
if ( type === RETRIEVED_CURRENT_USER_ACTIONS ) {
const currentUserActions = action;
const actions = currentUserActions[ this.id ];
if ( this.props.data && isObjectArray( actions ) ) {
this.restoreTransformations( actions );
}
}
else if ( type === RECEIVED_LESSON_INFO ) {
if ( session.metadata.store[ this.id ] ) {
const meta = session.metadata.store[ this.id ];
json( meta ).then( res => {
const groupVars = ( res.categorical || [] ).slice();
this.setState({
data: res.data,
quantitative: res.quantitative,
categorical: res.categorical,
groupVars,
ready: true
});
});
}
}
else if ( type === MEMBER_ACTION ) {
if (
action.id !== this.id ||
action.email === session.user.email ||
this.props.reportMode === 'individual'
) {
return;
}
else if ( this.props.reportMode === 'group' ) {
if ( !session.group ) {
return;
}
const members = session.group.members;
let inGroup = false;
for ( let i = 0; i < members.length; i++ ) {
if ( members[ i ].email === action.email ) {
inGroup = true;
break;
}
}
if ( !inGroup ) {
return;
}
}
// Case: `collaborative` or `group` mode
if (
action.type === DATA_EXPLORER_VARIABLE_TRANSFORMER ||
action.type === DATA_EXPLORER_BIN_TRANSFORMER ||
action.type === DATA_EXPLORER_CAT_TRANSFORMER ||
action.type === DATA_EXPLORER_DELETE_VARIABLE
) {
this.restoreTransformations( [ action ] );
}
this.context.currentUserActions[ this.id ].unshift( action );
}
});
}
componentDidUpdate( prevProps, prevState ) {
debug( 'Component did update...' );
if ( this.state.output !== prevState.output && this.outputPanel ) {
this.outputPanel.scrollToBottom();
}
}
componentWillUnmount() {
if ( this.unsubscribe ) {
this.unsubscribe();
}
}
restoreOutputs = ( state, actions ) => {
debug( 'Restore elements in output pane...' );
const candidates = [];
const skip = [];
for ( let i = 0; i < actions.length; i++ ) {
const action = actions[ i ];
if ( action.type === DATA_EXPLORER_CLEAR_OUTPUT_PANE ) {
break;
}
else if ( action.type === DATA_EXPLORER_DELETE_OUTPUT ) {
skip.push( action.value );
}
candidates.push( action );
}
const output = [];
const outputProps = {
logAction: this.logAction,
session: this.context,
data: state.data,
quantitative: state.quantitative,
categorical: state.categorical
};
for ( let i = candidates.length - 1; i >= 0; i-- ) {
const idx = candidates.length - 1 - i;
if ( contains( skip, idx ) ) {
continue;
}
const action = candidates[ i ];
const filters = action.value.filters;
if ( filters ) {
outputProps.data = filterCreate( state.data, filters );
}
const node = recreateOutput( action, outputProps );
if ( node ) {
const element = createOutputElement( node, output.length, this.clearOutput, filters || state.subsetFilters, this.onFilters, this.props.t );
output.push( element );
}
}
debug( `Restored ${output.length} elements.` );
state.output = output;
this.setState( state );
};
applyTransformation = ( state, action ) => {
switch ( action.type ) {
case DATA_EXPLORER_VARIABLE_TRANSFORMER:
debug( `Should add transformed variable ${action.value.name}` );
if ( !hasProp( this.props.data, action.value.name ) ) {
const values = valuesFromFormula( action.value.code, state.data );
state = this.transformVariable( action.value.name, values, state );
}
break;
case DATA_EXPLORER_BIN_TRANSFORMER: {
const { name, variable, breaks, categories } = action.value;
debug( `Should add binned variable ${name}` );
if ( !hasProp( this.props.data, name ) ) {
const rawData = state.data[ variable ];
const values = retrieveBinnedValues( rawData, categories, breaks );
const orderedName = factor( name, categories );
state = this.transformVariable( orderedName, values, state );
}
}
break;
case DATA_EXPLORER_CAT_TRANSFORMER: {
const { name, firstVar, secondVar, nameMappings, castNumeric } = action.value;
debug( `Should add recoded variable ${name}` );
if ( !hasProp( this.props.data, name ) ) {
if ( state.data[ firstVar ]) {
const values = recodeCategorical( firstVar, secondVar, nameMappings, state.data, castNumeric );
state = this.transformVariable( name, values, state );
}
}
}
break;
case DATA_EXPLORER_DELETE_VARIABLE:
state = this.deleteVariable( action.value, state );
break;
case DATA_EXPLORER_RANDOM_TRANSFORMER: {
const { name, distribution, params, asCategorical, nObs, seed } = action.value;
debug( `Should add random variable ${name}` );
const out = drawRandomVariates({ name, distribution, params, asCategorical, nObs, seed });
if ( isArray( out[ 0 ] ) ) {
for ( let i = 0; i < out[ 0 ].length; i++ ) {
if ( !hasProp( this.props.data, out[ 0 ][ i ] ) ) {
state = this.transformVariable( out[ 0 ][ i ], out[ 1 ][ i ], state );
}
}
}
else if ( !hasProp( this.props.data, name ) ) {
state = this.transformVariable( out[ 0 ], out[ 1 ], state );
}
}
break;
}
return state;
};
restoreTransformations = ( actions ) => {
let state = this.state;
debug( 'Restoring transformations...' );
for ( let i = actions.length - 1; i >= 0; i-- ) {
const action = actions[ i ];
state = this.applyTransformation( state, action );
}
state.data = copy( state.data, 1 );
setTimeout( () => {
this.restoreOutputs( state, actions );
}, 1500 );
};
resetStorage = () => {
const session = this.context;
session.store.removeItem( this.id );
this.setState({
data: null,
categorical: [],
quantitative: [],
ready: false
});
};
shareData = () => {
const session = this.context;
if ( session.metadata.store[ this.id ] ) {
session.updateMetadata( 'store', this.id, null );
this.forceUpdate();
} else {
const internalData = {
data: this.state.data,
quantitative: this.state.quantitative,
categorical: this.state.categorical
};
const blob = new Blob([ JSON.stringify( internalData ) ], {
type: 'application/json'
});
const fileToSave = new File( [ blob ], 'data.json' );
const formData = new FormData();
formData.append( 'file', fileToSave );
session.uploadFile({
formData,
callback: ( error, res ) => {
const filename = res.filename;
const link = session.server + '/' + filename;
session.updateMetadata( 'store', this.id, link );
this.forceUpdate();
},
showNotification: false
});
}
};
/**
* Display gallery of recently created plots by the students.
*/
toggleStudentPlots = () => {
this.setState({
showStudentPlots: !this.state.showStudentPlots
});
};
/**
* Remove output element at the specified index.
*/
clearOutput = ( idx ) => {
const session = this.context;
session.log({
id: this.id,
type: DATA_EXPLORER_DELETE_OUTPUT,
value: idx
}, 'owners' );
const newOutputs = this.state.output.slice();
newOutputs[ idx ] = null;
this.setState({
output: newOutputs
});
};
/**
* Remove all currently saved student plots.
*/
clearPlots = () => {
this.setState({
studentPlots: []
});
};
/**
* Stores all plot actions in the internal state.
*/
onUserAction = ( action ) => {
let config;
let value = action.value;
if ( isJSON( value ) ) {
value = JSON.parse( value );
}
switch ( action.type ) {
case 'DATA_EXPLORER_SHARE_BARCHART':
config = generateBarchartConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_BOXPLOT':
config = generateBoxplotConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_CONTOURCHART':
config = generateContourChart({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_HEATMAP':
config = generateHeatmapConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_HISTOGRAM':
config = generateHistogramConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_LINEPLOT':
config = generateLineplotConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_MAP':
config = generateMapConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_MOSAIC':
config = generateMosaicPlotCode({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_PIECHART':
config = generatePiechartConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_QQPLOT':
config = generateQQPlotConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_SCATTERPLOT':
config = generateScatterplotConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_SPLOM':
config = generateScatterplotMatrixConfig({ data: this.state.data, ...value });
break;
case 'DATA_EXPLORER_SHARE_VIOLINPLOT':
config = generateViolinplotConfig({ data: this.state.data, ...value });
}
if ( config ) {
const newStudentPlots = this.state.studentPlots.slice();
const configString = JSON.stringify( config );
let found = false;
for ( let i = 0; i < newStudentPlots.length; i++ ) {
if ( newStudentPlots[ i ].config === configString ) {
newStudentPlots[ i ].count += 1;
found = true;
break;
}
}
if ( !found ) {
newStudentPlots.push({
config: configString,
count: 1
});
}
this.setState({
studentPlots: newStudentPlots
});
}
};
onFilters = ( newFilters ) => {
this.setState({
filters: newFilters
}, this.onFilterCreate );
};
/**
* Adds the supplied element to the array of outputs.
*/
addToOutputs = ( val ) => {
const newOutput = this.state.output.slice();
if ( isArray( val ) ) {
for ( let i = 0; i < val.length; i++ ) {
const element = createOutputElement( val[ i ], newOutput.length, this.clearOutput, this.state.subsetFilters, this.onFilters, this.props.t );
newOutput.push( element );
}
} else {
const element = createOutputElement( val, newOutput.length, this.clearOutput, this.state.subsetFilters, this.onFilters, this.props.t );
newOutput.push( element );
}
this.setState({
output: newOutput
});
};
transformVariable = ( name, values, varState ) => {
let newQuantitative;
let newCategorical;
let groupVars;
let newData;
debug( `Attach transformed variable ${name} to data...` );
if ( !varState ) {
newData = copy( this.state.data, 1 );
newQuantitative = this.state.quantitative.slice();
newCategorical = this.state.categorical.slice();
groupVars = this.state.groupVars.slice();
} else {
newData = copy( varState.data, 1 );
newQuantitative = varState.quantitative.slice();
newCategorical = varState.categorical.slice();
groupVars = varState.groupVars.slice();
}
newData[ name ] = values;
let previous;
if ( isNumberArray( values ) ) {
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
previous = newCategorical.indexOf( name );
if ( previous > 0 ) {
newCategorical.splice( previous, 1 );
groupVars = newCategorical.slice();
}
}
} else {
if ( !contains( newCategorical, name ) ) {
newCategorical.push( name );
previous = newQuantitative.indexOf( name );
if ( previous > 0 ) {
newQuantitative.splice( previous, 1 );
}
}
groupVars = newCategorical.slice();
}
const newVarState = {
data: newData,
categorical: newCategorical,
quantitative: newQuantitative,
groupVars: groupVars
};
return newVarState;
};
onGenerateTransformedVariable = ( name, values ) => {
const session = this.context;
if ( isArray( name ) ) {
let newVarState;
for ( let i = 0; i < name.length; i++ ) {
newVarState = this.transformVariable( name[ i ], values[ i ], newVarState );
}
session.addNotification({
title: this.props.t( 'variables-created' ),
message: this.props.t( 'variables-created-msg', {
name: name.join( ', ' )
}),
level: 'success',
position: 'tr'
});
return this.setState( newVarState );
}
if ( hasProp( this.props.data, name ) ) {
return session.addNotification({
title: this.props.t( 'variable-exists' ),
message: this.props.t( 'variable-exists-msg' ),
level: 'error',
position: 'tr'
});
}
session.addNotification({
title: this.props.t( 'variable-created' ),
message: this.props.t( 'variable-created-msg', {
name
}),
level: 'success',
position: 'tr'
});
this.setState({ ...this.transformVariable( name, values ) });
};
onColumnDelete = ( variable ) => {
debug( 'Should remove variable with name '+variable );
const session = this.context;
this.logAction( DATA_EXPLORER_DELETE_VARIABLE, variable );
session.addNotification({
title: this.props.t('variable-removed'),
message: this.props.t('variable-removed-msg', {
variable
}),
level: 'success',
position: 'tr'
});
const varState = this.deleteVariable( variable );
varState.data = copy( varState.data, 1 );
this.setState( varState );
};
onColumnNameChange = ( oldName, newName ) => {
const state = this.state;
const keys = objectKeys( this.state.data );
const newData = {};
for ( let i = 0; i < keys.length; i++ ) {
const key = keys[ i ];
if ( key === oldName ) {
newData[ newName ] = this.state.data[ oldName ];
} else {
newData[ key ] = this.state.data[ key ];
}
}
const newQuantitative = state.quantitative.map( x => x === oldName ? newName : x );
const newCategorical = state.categorical.map( x => x === oldName ? newName : x );
const newGroupVars = state.groupVars.map( x => x === oldName ? newName : x );
this.setState({
data: newData,
quantitative: newQuantitative,
categorical: newCategorical,
groupVars: newGroupVars
});
};
onColumnDrag = ( vars ) => {
const state = this.state;
const sorter = ( a, b ) => {
a = vars.indexOf( String( a ) );
b = vars.indexOf( String( b ) );
if ( a === -1 || b === -1 ) {
return 0;
}
if ( a < b ) {
return -1;
} else if ( a > b ) {
return 1;
}
return 0;
};
const newQuantitative = state.quantitative.slice().sort( sorter );
const newCategorical = state.categorical.slice().sort( sorter );
const newGroupVars = state.groupVars.slice().sort( sorter );
this.setState({
quantitative: newQuantitative,
categorical: newCategorical,
groupVars: newGroupVars
});
};
deleteVariable = ( variable, varState ) => {
let state = varState || this.state;
let newData;
if ( !varState ) {
newData = copy( this.state.data, 1 );
} else {
newData = varState.data;
}
delete newData[ variable ];
let newQuantitative = state.quantitative.filter( x => x !== variable );
let newCategorical = state.categorical.filter( x => x !== variable );
let newGroupVars = state.groupVars.filter( x => x !== variable );
let filters = ( state.filters || [] ).filter( x => x.id !== variable );
return {
data: newData,
quantitative: newQuantitative,
categorical: newCategorical,
groupVars: newGroupVars,
filters
};
};
onFileUpload = ( err, output ) => {
const session = this.context;
if ( !err ) {
const data = {};
const columnNames = objectKeys( output[ 0 ] ).filter( x => x !== '' );
for ( let j = 0; j < columnNames.length; j++ ) {
let col = columnNames[ j ];
data[ col ] = new Array( output.length );
}
for ( let i = 0; i < output.length; i++ ) {
for ( let j = 0; j < columnNames.length; j++ ) {
let col = columnNames[ j ];
data[ col ][ i ] = output[ i ][ col ];
}
}
const categoricalGuesses = [];
const quantitativeGuesses = [];
columnNames.forEach( variable => {
if ( isNumberArray( data[ variable ]) ) {
quantitativeGuesses.push( variable );
} else {
categoricalGuesses.push( variable );
}
});
this.setState({
quantitative: quantitativeGuesses,
categorical: categoricalGuesses,
data
}, () => {
session.store.setItem( this.id, {
data: this.state.data,
quantitative: quantitativeGuesses,
categorical: categoricalGuesses
});
});
}
};
onFilterCreate = () => {
const newData = filterCreate( this.state.data, this.state.filters );
const newState = {
data: newData,
oldData: this.state.data,
subsetFilters: this.state.filters
};
this.setState( newState );
};
onFilterAdd = () => {
const data = this.restoreData();
const newData = filterCreate( data, this.state.filters );
const newState = {
data: newData,
oldData: data,
subsetFilters: this.state.filters
};
this.setState( newState );
};
restoreData = () => {
const newVars = objectKeys( this.state.data );
const oldVars = objectKeys( this.state.oldData );
let originalData;
let data;
if ( this.props.data ) {
originalData = this.props.data;
data = copy( this.props.data, 1 );
} else {
originalData = this.state.unaltered.data;
data = copy( originalData, 1 );
}
const originalVariables = [];
for ( let i = 0; i < this.props.quantitative.length; i++ ) {
originalVariables.push( String( this.props.quantitative[ i ] ) );
}
for ( let i = 0; i < this.props.categorical.length; i++ ) {
originalVariables.push( String( this.props.categorical[ i ] ) );
}
const ids = this.state.data.id;
const nOriginal = originalData[ oldVars[ 0 ] ].length;
const oldIds = this.state.oldData.id || incrspace( 1, nOriginal+1, 1 );
for ( let i = 0; i < oldVars.length; i++ ) {
const name = oldVars[ i ];
if ( name !== 'id' && !contains( originalVariables, name ) ) {
data[ name ] = new Array( nOriginal ).fill( null );
for ( let j = 0; j < oldIds.length; j++ ) {
const idx = oldIds[ j ] - 1;
data[ name ][ idx ] = this.state.oldData[ name ][ j ];
}
}
}
for ( let i = 0; i < newVars.length; i++ ) {
const name = newVars[ i ];
if ( name !== 'id' && !contains( originalVariables, name ) ) {
debug( 'Handle inserted variable: '+name );
if ( !data[ name ] ) {
data[ name ] = new Array( nOriginal ).fill( null );
}
for ( let j = 0; j < ids.length; j++ ) {
const idx = ids[ j ] - 1;
data[ name ][ idx ] = this.state.data[ name ][ j ];
}
}
}
return data;
};
onPredict = {
'decision-tree': ( tree, counter ) => {
const newData = copy( this.state.data, 1 );
const newCategorical = this.state.categorical.slice();
const newQuantitative = this.state.quantitative.slice();
if ( tree.type === 'classification' ) {
const yhat = tree.predict( newData ).map( x => String( x ) );
let name = 'pred_tree' + counter;
newData[ name ] = yhat;
if ( !contains( newCategorical, name ) ) {
newCategorical.push( name );
}
name = 'correct_tree' + counter;
const yvalues = newData[ tree.response ];
newData[ name ] = yhat.map( ( x, i ) => x === String( yvalues[ i ] ) ? 'Yes' : 'No' );
if ( !contains( newCategorical, name ) ) {
newCategorical.push( name );
}
}
else {
const yhat = tree.predict( newData );
let name = 'pred_tree' + counter;
newData[ name ] = yhat;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
name = 'resid_tree' + counter;
newData[ name ] = subtract( yhat, newData[ tree.response ] );
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
}
this.setState({
categorical: newCategorical,
quantitative: newQuantitative,
data: newData
});
},
'lasso': ( predict, counter ) => {
const newData = copy( this.state.data, 1 );
const newQuantitative = this.state.quantitative.slice();
let name = 'pred_lasso' + counter;
const { fitted, residuals } = predict( newData );
newData[ name ] = fitted;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
name = 'resid_lasso' + counter;
newData[ name ] = residuals;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
this.setState({
quantitative: newQuantitative,
data: newData
});
},
'logistic': ( predict, counter ) => {
const newData = copy( this.state.data, 1 );
const newQuantitative = this.state.quantitative.slice();
const newCategorical = this.state.categorical.slice();
const { yhat, probs, residuals } = predict( newData );
let name = 'probs_logis' + counter;
newData[ name ] = probs;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
name = 'pred_logis' + counter;
newData[ name ] = yhat;
if ( !contains( newCategorical, name ) ) {
newCategorical.push( name );
}
name = 'resid_logis' + counter;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
newData[ name ] = residuals;
this.setState({
categorical: newCategorical,
quantitative: newQuantitative,
data: newData
});
},
'multiple-linear-regression': ( predict, counter ) => {
const newData = copy( this.state.data, 1 );
const newQuantitative = this.state.quantitative.slice();
const { fitted, residuals } = predict( newData );
let name = 'pred_lm'+counter;
newData[ name ] = fitted;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
name = 'resid_lm'+counter;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
newData[ name ] = residuals;
this.setState({
quantitative: newQuantitative,
data: newData
});
},
'random-forest': ( forest, counter ) => {
const newData = copy( this.state.data, 1 );
const newCategorical = this.state.categorical.slice();
if ( forest.type === 'classification' ) {
const yhat = forest.predict( newData ).map( x => String( x ) );
let name = 'pred_forest' + counter;
newData[ name ] = yhat;
if ( !contains( newCategorical, name ) ) {
newCategorical.push( name );
}
name = 'correct_forest' + counter;
const yvalues = this.state.data[ forest.response ];
newData[ name ] = yhat.map( ( x, i ) => x === String( yvalues[ i ] ) ? 'Yes' : 'No' );
if ( !contains( newCategorical, name ) ) {
newCategorical.push( name );
}
}
this.setState({
categorical: newCategorical,
data: newData
});
},
'simple-linear-regression': ( predict, counter ) => {
const newData = copy( this.state.data, 1 );
const { fitted, residuals } = predict( newData );
const newQuantitative = this.state.quantitative.slice();
let name = 'pred_slm'+counter;
newData[ name ] = fitted;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
name = 'resid_slm'+counter;
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
newData[ name ] = residuals;
this.setState({
quantitative: newQuantitative,
data: newData
});
},
'naive-bayes': ( predict, counter ) => {
const newData = copy( this.state.data, 1 );
const newQuantitative = this.state.quantitative.slice();
const { fitted, classProbs } = predict( newData );
const keys = Object.keys( classProbs );
for ( let i = 0; i < keys.length; i++ ) {
const name = keys[ i ];
newData[ name ] = classProbs[ name ];
if ( !contains( newQuantitative, name ) ) {
newQuantitative.push( name );
}
}
const name = 'pred_bayes'+ counter;
newData[ name ] = fitted;
const newCategorical = this.state.categorical.slice();
if ( !contains( newCategorical, name ) ) {
newCategorical.push( name );
}
this.setState({
categorical: newCategorical,
quantitative: newQuantitative,
data: newData
});
}
};
onRestoreData = () => {
const data = this.restoreData();
this.setState({
data,
subsetFilters: null,
filters: []
});
};
on2dSelection = ( names, selected ) => {
const newFilters = this.state.filters.filter(
x => x.id !== names.x && x.id !== names.y
);
newFilters.push({
id: names.x,
value: {
min: selected.range.x[ 0 ],
max: selected.range.x[ 1 ]
}
});
newFilters.push({
id: names.y,
value: {
min: selected.range.y[ 0 ],
max: selected.range.y[ 1 ]
}
});
this.setState({
filters: newFilters
});
};
onQQPlotSelection = ( name, selected ) => {
if ( selected.range && selected.range.y ) {
const newFilters = this.state.filters.filter(
x => x.id !== name
);
const y = selected.range.y;
newFilters.push({
id: name,
value: {
min: y[ 0 ],
max: y[ 1 ]
}
});
this.setState({
filters: newFilters
});
}
};
onBarchartSelection = ( name, selected ) => {
const newFilters = this.state.filters.filter(
x => x.id !== name
);
newFilters.push({
id: name,
value: selected.range.x
});
this.setState({
filters: newFilters
});
};
onHistogramSelection = ( name, selected ) => {
if ( selected.points && selected.points[ 0 ] ) {
const first = selected.points[ 0 ];
const binSize = first.fullData.xbins.size;
const last = selected.points[ selected.points.length-1 ];
const newFilters = this.state.filters.filter(
x => x.id !== name
);
newFilters.push({
id: name,
value: {
min: first.x - binSize/2,
max: last.x + binSize/2
}
});
this.setState({
filters: newFilters
});
}
};
render() {
debug( 'Render component...' );
if ( !this.state.data ) {
return (
<SpreadsheetUpload
title={this.props.t('data-explorer')}
onUpload={this.onFileUpload}
/>
);
}
if ( !this.state.ready ) {
const variableNames = objectKeys( this.state.data );
return ( <Card>
<Card.Header as="h3">
{this.props.t('data-explorer')}
</Card.Header>
<Card.Body>
<h4>{this.props.t('select-quantitative-categorical')}:</h4>
<SelectInput
legend={this.props.t('quantitative')}
options={variableNames}
defaultValue={this.state.quantitative}
multi
onChange={( quantitative ) => {
this.setState({
quantitative: quantitative || []
});
}}
/>
<SelectInput
legend={this.props.t('categorical')}
options={variableNames}
defaultValue={this.state.categorical}
multi
onChange={( categorical ) => {
this.setState({
categorical: categorical || []
});
}}
/>
<Button disabled={isEmptyArray( this.state.categorical ) && isEmptyArray( this.state.quantitative )} onClick={() => {
this.setState({
groupVars: this.state.categorical.slice(),
ready: true
}, () => {
const session = this.context;
const internalData = {
data: this.state.data,
quantitative: this.state.quantitative,
categorical: this.state.categorical
};
session.store.setItem( this.id, internalData );
this.setState({
unaltered: internalData
});
});
}}>{this.props.t('submit')}</Button>
<DataTable data={this.state.data} id={this.id + '_table'} />
</Card.Body>
</Card> );
}
if ( isEmptyObject( this.state.data ) ) {
return <Alert variant="danger">{this.props.t('data-empty')}</Alert>;
}
if ( !this.state.validVariables ) {
return ( <Alert variant="danger">
<Trans i18nKey="variables-invalid-alert" ns="DataExplorer" >
The <b>quantitative</b> or <b>categorical</b> data arrays contain variable names not present in the <b>data</b> object.
</Trans>
</Alert> );
}
const session = this.context;
const hasQuestions = !isNull( this.props.questions );
const questionProps = isArray( this.props.questions ) ?
{ children: this.props.questions } :
this.props.questions;
const pagesHeight = this.props.style.height || ( window.innerHeight*0.9 ) - 165;
const mainContainer = <Row className="no-gutter data-explorer" style={this.props.style} >
<Col xs={6} md={6} >
<Card style={{ height: this.props.style.height, minHeight: this.props.style.height || window.innerHeight*0.9, padding: 0 }} >
<Navbar className="data-explorer-navbar" value={this.state.openedNav} onSelect={( eventKey => this.setState({ openedNav: eventKey }))}>
<Nav>
{ hasQuestions ? <Nav.Item className="explorer-data-nav">
<Nav.Link title={`${this.props.t('questions')} ${KEYS[ 'questions' ]}`} eventKey="questions" active={this.state.openedNav === 'questions'}>
{this.props.t('questions')}
</Nav.Link>
</Nav.Item> : null }
{ this.props.dataTable ? <Nav.Item className="explorer-data-nav" >
<Nav.Link title={`${this.props.t('data')} ${KEYS[ 'data' ]}`} eventKey="data" active={this.state.openedNav === 'data'}>
{this.props.t('data')}
</Nav.Link>
</Nav.Item> : null }
{ this.props.editor ?
<Nav.Item className="explorer-editor-nav">
<Nav.Link
title={`${this.props.editorTitle ? this.props.editorTitle : this.props.t('report')} ${KEYS[ 'editor' ]}`}
active={this.state.openedNav === 'editor'}
eventKey="editor"
>{this.props.editorTitle ? this.props.editorTitle : this.props.t('report')}</Nav.Link>
</Nav.Item> : null
}
{ this.props.history ?
<Nav.Item className="explorer-editor-nav">
<Nav.Link
title={`${this.props.t('history')} ${KEYS[ 'history' ]}`}
active={this.state.openedNav === 'history'}
eventKey="history"
>
{this.props.t('history')}
</Nav.Link>
</Nav.Item> : null
}
{ this.props.tabs.length > 0 ? this.props.tabs.map( ( e, i ) => {
return (
<Nav.Item key={i} className="explorer-tabs-nav">
<Nav.Link
active={this.state.openedNav === e.title}
eventKey={e.title}
>{e.title}</Nav.Link>
</Nav.Item>
);
}) : null }
</Nav>
<Suspense fallback={<Button
variant="secondary" size="sm" className="hide-toolbox-button"
disabled
>
Loading...
</Button>} >
<ToolboxButton
id={`${this.id}-toolbox`}
models={this.props.models}
tables={this.props.tables}
statistics={this.props.statistics}
plots={this.props.plots}
tests={this.props.tests}
quantitative={this.state.quantitative}
originalQuantitative={this.props.quantitative}
categorical={this.state.categorical}
logAction={this.logAction}
onCreated={this.addToOutputs}
data={this.state.data}
showTestDecisions={this.props.showTestDecisions}
onPlotDone={this.outputPanel ? this.outputPanel.scrollToBottom : noop}
groupingVariables={this.state.groupVars}
on2dSelection={this.on2dSelection}
onQQPlotSelection={this.onQQPlotSelection}
transformer={this.props.transformer}
onBarchartSelection={this.onBarchartSelection}
showHistogramDensityOption={this.props.histogramDensities}
onGenerateTransformedVariable={this.onGenerateTransformedVariable}
onHistogramSelection={this.onHistogramSelection}
onCategoricalGenerate={( categorical, data ) => {
const groupVars = categorical.slice();
this.setState({
categorical,
groupVars,
data
});
}}
onQuantitativeGenerate={( quantitative, data ) => {
this.setState({
quantitative,
data
});
}}
onTutorialStart={this.props.onTutorialStart}
onTutorialCompletion={this.props.onTutorialCompletion}
onPredict={this.onPredict}
/>
</Suspense>
</Navbar>
<Card.Body style={{ overflowY: 'auto' }}>
{ hasQuestions ? <Pages
id={this.id + '_questions'}
height={pagesHeight}
className="data-explorer-questions"
style={{
display: this.state.openedNav !== 'questions' ? 'none' : null
}}
{...questionProps}
/> : null }
<div
style={{
display: this.state.openedNav !== 'data' ? 'none' : null
}}
>
{ !this.props.data && !session.metadata.store[ this.id ] ? <Button
size="small" onClick={this.resetStorage}
style={{ position: 'absolute', top: '80px', zIndex: 2 }}
>{this.props.t('clear-data')}</Button> : null }
{ !this.props.data ? <Gate owner banner={null} >
<Button
size="small" onClick={this.shareData}
style={{ position: 'absolute', top: '80px', left: '140px', zIndex: 2 }}
>{!session.metadata.store[ this.id ] ? this.props.t('share') : this.props.t('unshare')}</Button>
</Gate>: null }
<DataTable
{...this.props.dataTableProps}
data={this.state.data}
dataInfo={this.props.dataInfo}
undeletableVars={objectKeys( this.props.data )}
filters={this.state.filters}
onFilteredChange={( filtered ) => {
debug( 'Filters have changed...' );
this.setState({
filters: filtered
});
}}
onColumnDelete={this.onColumnDelete}
onColumnNameChange={this.onColumnNameChange}
onColumnDrag={this.onColumnDrag}
deletable
id={this.id + '_table'}
headerButtons={<Fragment>
{this.state.filters.length > 0 && this.state.subsetFilters !== this.state.filters ?
<OverlayTrigger placement="top" overlay={<Tooltip>{this.props.t('create-filtered-dataset-tooltip')}</Tooltip>} >
<Button
onClick={() => {
if ( this.state.subsetFilters ) {
// Case: Dataset is already filtered
this.onFilterAdd();
} else {
this.onFilterCreate();
}
}}
variant="secondary"
size="xsmall"
className="mb-1"
>
{this.props.t('create-filtered-dataset')}
</Button>
</OverlayTrigger> : null
}
{this.state.subsetFilters ? <div className="data-explorer-subset-filter-display">
<Collapse headerClassName="data-explorer-collapsible-filters" header={<div>
<OverlayTrigger
placement="top"
overlay={<Tooltip>
{this.props.t('filtered-data-tooltip')}
</Tooltip>}
>
<span>
<i className="fa-solid fa-caret-down mx-2" />
{this.props.t('filtered-data')}
<i className="fa-solid fa-caret-down mx-2" />
</span>
</OverlayTrigger>
{ this.state.subsetFilters ? <OverlayTrigger placement="top" overlay={<Tooltip>
{this.props.t('restore-original-dataset-tooltip')}
</Tooltip>} >
<Button
onClick={this.onRestoreData}
variant="secondary"
size="small"
style={{ float: 'right' }}
>
{this.props.t('restore-original-dataset')}
</Button>
</OverlayTrigger> : null }
</div>} >
<FilterList
filters={this.state.subsetFilters}
removeButtons
onRemove={( idx ) => {
debug( 'Removing filter at position '+idx );
const newSubsetFilters = this.state.subsetFilters.slice();
newSubsetFilters.splice( idx, 1 );
if ( newSubsetFilters.length > 0 ) {
this.setState({
data: this.state.oldData,
filters: newSubsetFilters
}, this.onFilterCreate );
} else {
this.onRestoreData();
}
}}
/>
</Collapse>
</div> : null}
</Fragment>}
/>
</div>
{ this.props.history && this.state.openedNav === 'history' ?
<History
explorerID={this.id}
actions={this.context.currentUserActions[ this.id ]}
onCreated={this.addToOutputs}
onTransformation={( action ) => {
const state = this.applyTransformation( this.state, action );
session.addNotification({
title: this.props.t( 'variable-created' ),
message: this.props.t( 'variable-created-msg', {
name: action.value.name
}),
level: 'success',
position: 'tr'
});
this.setState( state );
}}
logAction={this.logAction}
session={this.context}
data={this.state.data}
quantitative={this.state.quantitative}
categorical={this.state.categorical}
t={this.props.t}
reportMode={this.props.reportMode}
/> : null
}
{ this.props.editor ?
<TextEditor
{...this.props.editorProps}
mode={this.props.reportMode}
id={this.id + '_editor'}
style={{ display: this.state.openedNav !== 'editor' ? 'none' : null }}
submitButton
/> : null
}
{this.props.tabs.map( ( e, i ) => {
return ( this.state.openedNav === e.title ?
e.content : null );
})}
</Card.Body>
</Card>
</Col>
<Col xs={6} md={6}>
<div className="card card-default" style={{ height: this.props.style.height, minHeight: this.props.style.height || window.innerHeight*0.9, padding: 0 }} >
<OutputPanel
output={this.state.output}
ref={( div ) => {
this.outputPanel = div;
}}
session={this.context}
header={<Gate owner banner={null} >
<Modal
show={this.state.showStudentPlots}
onHide={this.toggleStudentPlots}
dialogClassName="modal-100w"
>
<Modal.Header closeButton >
<Modal.Title>{this.props.t('plots')}</Modal.Title>
</Modal.Header>
<Modal.Body style={{ height: 0.80 * window.innerHeight, overflowY: 'scroll' }}>
{ this.state.studentPlots.length > 0 ?
<GridLayout>
{this.state.studentPlots.map( ( elem, idx ) => {
const config = JSON.parse( elem.config );
return (
<div key={idx} style={{ height: '450px' }}>
{
isString( config ) ?
<RPlot
code={config}
libraries={[ 'MASS' ]}
/>:
<Plotly
data={config.data}
layout={config.layout}
removeButtons
/>
}
<span>
<b>{this.props.t('count')}: </b>{elem.count}
</span>
</div>
);
})}
</GridLayout> :
<Card body className="bg-light">
{this.props.t('no-plots-yet')}
</Card>
}
</Modal.Body>
<Modal.Footer>
<Button variant="danger" onClick={this.clearPlots}>
{this.props.t('clear-plots')}
</Button>
<Button onClick={this.toggleStudentPlots}>
{this.props.t('close')}
</Button>
</Modal.Footer>
</Modal>
<Button
variant="secondary" size="sm"
style={{ float: 'right' }}
onClick={this.toggleStudentPlots}
>{this.props.t('open-shared-plots')}</Button>
<RealtimeMetrics returnFullObject for={[ this.id ]} onDatum={this.onUserAction} />
</Gate>}
clearOutput={() => {
session.log({
id: this.id,
type: DATA_EXPLORER_CLEAR_OUTPUT_PANE,
value: null
}, 'owners' );
this.setState({
output: []
});
}}
reportMode={this.props.reportMode}
t={this.props.t}
/>
<KeyControls
actions={{
'shift+alt+r': () => this.setState({ openedNav: 'editor' }),
'shift+alt+h': () => this.setState({ openedNav: 'history' }),
'shift+alt+d': () => this.setState({ openedNav: 'data' }),
'shift+alt+q': () => this.setState({ openedNav: 'questions' })
}}
/>
</div>
</Col>
</Row>;
return mainContainer;
}
} |
JavaScript | class RallfFS {
constructor(cwd = '') {
this._cwd = path.resolve(cwd) || null;
}
/**
* Save a JSON object to a file
* @param {string} filepath
* @param {object} data
* @param {{fs?: object, replacer?: any, spaces?: number | string, EOL?: string}} options?
*/
saveJSON(filepath, data, options = null) {
if (!fs.existsSync(this._cwd)) {
throw new Error('Oopsy, the robot cwd does not exist: ' + this._cwd);
}
filepath = path.join(this._cwd, filepath);
fs.writeJsonSync(filepath, data, options);
}
/**
* Save data to a file
* @param {string} filepath
* @param {any} data
* @param {string|{encoding?:string, mode?:string|number, flag?:string}} options?
*/
saveFile(filepath, data, options = null) {
if (!fs.existsSync(this._cwd)) {
throw new Error('Oopsy, the robot cwd does not exist: ' + this._cwd);
}
filepath = path.join(this._cwd, filepath);
fs.writeFileSync(filepath, data, options);
}
/**
* Ensures a file exists, if not it creates it recursively
* @param {string} filepath
*/
ensureFile(filepath) {
if (!fs.existsSync(this._cwd)) {
throw new Error('Oopsy, the robot cwd does not exist: ' + this._cwd);
}
filepath = path.join(this._cwd, filepath);
return fs.ensureFileSync(filepath);
}
/**
* Ensures a dir exists, if not it creates it recursively
* @param {string} dirpath
*/
ensureDir(dirpath) {
if (!fs.existsSync(this._cwd)) {
throw new Error('Oopsy, the robot cwd does not exist: ' + this._cwd);
}
dirpath = path.join(this._cwd, dirpath);
return fs.ensureDirSync(dirpath);
}
/**
* Read data from a file
* @param {string} filepath
* @param {{encoding?:string, flag?:string}} options?
*/
readFile(filepath, options = null) {
if (!fs.existsSync(this._cwd)) {
throw new Error('Oopsy, the robot cwd does not exist: ' + this._cwd);
}
filepath = path.join(this._cwd, filepath);
fs.readFileSync(filepath);
}
/**
* Read JSON from file
* @param {string} filepath
* @param {{throws?: boolean, fs?: object, reviver?: any, encoding?: string,flag?: string}} options?
* @return {object}
*/
readJSON(filepath, options = null) {
if (!fs.existsSync(this._cwd)) {
throw new Error('Oopsy, the robot cwd does not exist: ' + this._cwd);
}
filepath = path.join(this._cwd, filepath);
return fs.readJsonSync(filepath, options);
}
/**
* Check if a file or directory exists synchronously
* @param {string} filepath
* @return {boolean}
*/
existsSync(filepath) {
filepath = path.join(this._cwd, filepath);
return fs.existsSync(filepath);
}
/**
* Check if a file or directory exists asynchronously
* @param {string} filepath
* @param {function (boolean)} callback
* @return {void}
*/
exists(filepath, callback) {
filepath = path.join(this._cwd, filepath);
fs.exists(filepath, callback);
}
/**
* Create a file even if sub-directories do not exist
* @param {string} filepath
* @param {any} data
*/
createFile(filepath, data) {
fs.createFileSync(filepath);
fs.writeFileSync(filepath, data);
}
} |
JavaScript | class ModuleMessages extends Module {
/**
* @param {AppBackground} app - The background application.
*/
constructor(app) {
super(app)
this._platformData(false)
this.app.on('bg:messages:send', async({number, text}) => {
this.sendMessage(number, text);
})
// this.app.timer.registerTimer('bg:messages:size', () => {this._platformData(false)})
// this.app.on('bg:messages:selected', ({message}) => {
// if (message) {
// this.app.setState({messages: {selected: {id: message.id, number: message.number}}}, {persist: true})
// }
// else {
// this.app.setState({messages: {selected: {id: null, number: null}}}, {persist: true})
// }
// // this.app.modules.ui.menubarState()
// // this.setMessageSizesTimer()
// })
}
/**
* Initializes the module's store.
* @returns {Object} The module's store properties.
*/
_initialState() {
return {
messages: [],
search: {
disabled: false,
input: '',
},
message: {
number: '',
text: [],
},
create: false,
view: false,
state: null,
status: null,
}
}
/**
* Adjust the message-size timer when the WebExtension
* popup opens or closes.
* @param {String} type - Whether the popup is set to `close` or `open`.`
*/
_onPopupAction(type) {
// this.setMessageSizesTimer()
}
/**
* Load information about message callgroups from the
* VoIPGRID platform.
* @param {Boolean} empty - Whether to empty the messages list and set the state to `loading`.
*/
async _platformData(empty = true) {
// API retrieval possibility check is already performed at
// the application level, but is also required here because
// of the repeated timer function.
if (!this.app.state || !this.app.state.user.authenticated || !this.app.state.app.online) return
if (empty) this.app.setState({messages: {messages: [], status: 'loading'}})
const res = await this.app.api.client.get('api/messages/')
if (this.app.api.NOTOK_STATUS.includes(res.status)) {
this.app.logger.warn(`${this}platform data request failed (${res.status})`)
return
}
let messages = res.data.objects
this.app.setState({messages: {messages: messages, status: null}}, {persist: true})
this.app.modules.ui.menubarState()
// this.setMessageSizesTimer()
}
/**
* Converts a message size to a menubar icon state.
* @param {String|Number} messageSize - The message size as returned from the VoIPGRID API.
* @returns {String} - The menubar state, which is linked to a .png filename.
*/
messageMenubarIcon(messageSize) {
let messageState = 'queue'
if (!isNaN(messageSize)) {
if (messageSize < 10) messageState = `queue-${messageSize}`
else messageState = 'queue-10'
}
return messageState
}
/**
* Send message text.
* @param {String|Number} number - recipient.
* @param {String} text - The message text.
*/
async sendMessage(number, text){
const res = await this.app.api.client.put('api/message/send/', {
number, text
});
this.app.logger.warn(`${this}triggered bg:messages:send`)
if (this.app.api.NOTOK_STATUS.includes(res.status)) {
this.app.logger.warn(`${this}message data request failed (${res.status})`)
return
}
}
/**
* Register the queus update timer function and
* the dynamic interval check.
*/
setMessageSizesTimer() {
// Set a dynamic timer interval.
this.app.timer.setTimeout('bg:messages:size', () => {
let timeout = 0
// Only when authenticated.
if (this.app.state.user.authenticated) {
// Check every 20s when a message is selected, no matter
// if the popup is opened or closed.
if (this.app.state.messages.selected.id) {
timeout = 20000
// Check more regularly when the popup is open and the
// messages widget is open.
if (this.app.state.ui.visible) timeout = 5000
}
}
this.app.logger.debug(`${this}set message timer to ${timeout} ms`)
return timeout
}, true)
this.app.timer.startTimer('bg:messages:size')
}
/**
* Generate a representational name for this module. Used for logging.
* @returns {String} - An identifier for this module.
*/
toString() {
return `${this.app}[messages] `
}
} |
JavaScript | class NumberStore extends Store {
constructor() {
super(AppDispatcher);
// The set of number rows (with a default initial value):
this.numbers = [{id: 'c37fef88-d878-403c-a0c2-3cb9ec475313', hundreds: true, twenties: true, fives: true, value: 0}];
}
// Get the rows
getRows() {
return this.numbers;
}
__onDispatch(action) {
switch (action.actionType) {
case ActionTypes.RECEIVE_ROWS:
this.numbers = action.numbers;
this.__emitChange();
break;
case ActionTypes.ADD_ROW:
// Add a new row:
const uid = uuidv4();
// Get the current array -- add a row to the end of it.
let newRows = this.numbers.concat({id: uid, hundreds: true, twenties: true, fives: true, value: 0})
// Set the new array collection
this.numbers = newRows;
this.__emitChange();
break;
case ActionTypes.REMOVE_ROW:
// Filter out this id
let updatedRows = this.numbers.filter(r => r.id !== action.id);
// Set the new array collection
this.numbers = updatedRows;
this.__emitChange();
break;
case ActionTypes.UPDATE_ROW:
this.numbers = this.numbers.map(n =>
n.id === action.id
? { ...n, hundreds: action.hundreds, twenties: action.twenties, fives: action.fives, value: action.value }
: n
);
this.__emitChange();
break;
default:
// no op
}
}
} |
JavaScript | class VideoProcessor {
/**
* @param {!AsyncWriter} output The output writer.
* @param {!VideoProcessorArgs} processorArgs
*/
constructor(output, processorArgs) {
assertNotReached();
}
/**
* Writes a chunk data into the processor.
* @param {!Blob} blob
* @return {!Promise}
* @abstract
*/
async write(blob) {
assertNotReached();
}
/**
* Closes the processor. No more write operations are allowed.
* @return {!Promise} Resolved when all the data are processed and flushed.
* @abstract
*/
async close() {
assertNotReached();
}
/**
* Cancels the remaining tasks. No more write operations are allowed.
* @return {!Promise}
* @abstract
*/
async cancel() {
assertNotReached();
}
} |
JavaScript | class IO extends SandGrain {
constructor() {
super();
this.defaultConfig = require('./default');
this.io = null;
this.paths = {};
this.version = require('../package').version;
this.name = 'io';
this.configName = this.name;
}
/**
* Initialize IO module
*
* @param config
* @param done
*
* @returns {IO}
*/
init(config, done) {
super.init(config);
this.log('Initializing...');
done();
return this;
}
start(done) {
if (this.config.useExistingHTTP && typeof sand.http === 'undefined') {
this.log('The IO Module requires the HTTP module to be loaded first');
return this;
}
this.io = socketIO(this.config.useExistingHTTP ? sand.http.server : this.config.port);
this.setup();
this.logStart();
done();
return this;
}
shutdown(done) {
this.log('Shutting down...');
try {
this.io.httpServer.close(done);
} catch (e) {
// Must already be shutting down
}
}
/**
* Setup io Routes
*/
setup() {
var ioRoutes = require(require('path').resolve(sand.appPath, this.config.routesFile));
//var path = sand.appPath + this.config.path;
//var files = require('require-all')({
// dirname: path,
// filter: /(\w+)\.js/
//});
for (let route in ioRoutes) {
if (ioRoutes.hasOwnProperty(route)) {
this.registerIO(ioRoutes[route]);
}
}
}
/**
* Registers functions to IO
*
* @param options
*/
registerIO(options) {
var io = this.io;
if (options.path) {
// Register namespace
this.log('Registering ' + options.path);
io = this.io.of(options.path);
this.paths[options.path] = io;
}
for (let key in options) {
var option = options[key];
if (typeof option === 'function') {
var matches = key.match(/on(\w+)/);
if (matches && typeof matches[1] === 'string') {
io.on(matches[1].toLowerCase(), option);
} else if (key === 'before') {
io.use(option);
}
}
}
}
/**
* Logs starting of IO
*/
logStart() {
if (!this.config.useExistingHTTP) {
this.log('Listening on ' + this.config.port);
}
}
} |
JavaScript | class ExtensionDefinition extends DomainResource {
/**
The URL at which this definition is (or will be) published, and which is used to reference this profile in extension urls in operational FHIR systems.
@returns {Array} an array of {@link String} objects
*/
url () { return this.json['url'] }
/**
Formal identifier that is used to identify this profile when it is represented in other formats (e.g. ISO 11179(, or referenced in a specification, model, design or an instance (should be globally unique OID, UUID, or URI), (if it's not possible to use the literal URI).
@returns {Array} an array of {@link Identifier} objects
*/
identifier () {
if (this.json['identifier']) {
return this.json['identifier'].map(item => new Identifier(item))
}
}
/**
A free text natural language name identifying the extension.
@returns {Array} an array of {@link String} objects
*/
name () { return this.json['name'] }
/**
Defined so that applications can use this name when displaying the value of the extension to the user.
@returns {Array} an array of {@link String} objects
*/
display () { return this.json['display'] }
/**
Details of the individual or organization who accepts responsibility for publishing the extension definition.
@returns {Array} an array of {@link String} objects
*/
publisher () { return this.json['publisher'] }
/**
Contact details to assist a user in finding and communicating with the publisher.
@returns {Array} an array of {@link ContactPoint} objects
*/
telecom () {
if (this.json['telecom']) {
return this.json['telecom'].map(item => new ContactPoint(item))
}
}
/**
A free text natural language description of the extension and its use.
@returns {Array} an array of {@link String} objects
*/
description () { return this.json['description'] }
/**
A set of terms from external terminologies that may be used to assist with indexing and searching of extension definitions.
@returns {Array} an array of {@link Coding} objects
*/
code () {
if (this.json['code']) {
return this.json['code'].map(item => new Coding(item))
}
}
/**
The status of the extension.
@returns {Array} an array of {@link String} objects
*/
status () { return this.json['status'] }
/**
This extension definition was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage.
@returns {Array} an array of {@link boolean} objects
*/
experimental () { return this.json['experimental'] }
/**
The date that this version of the extension was published.
@returns {Array} an array of {@link Date} objects
*/
date () { if (this.json['date']) { return DT.DateTime.parse(this.json['date']) } }
/**
The Scope and Usage that this extension was created to meet.
@returns {Array} an array of {@link String} objects
*/
requirements () { return this.json['requirements'] }
/**
An external specification that the content is mapped to.
@returns {Array} an array of {@link ExtensionDefinitionMappingComponent} objects
*/
mapping () {
if (this.json['mapping']) {
return this.json['mapping'].map(item => new ExtensionDefinitionMappingComponent(item))
}
}
/**
Identifies the type of context to which the extension applies.
@returns {Array} an array of {@link String} objects
*/
contextType () { return this.json['contextType'] }
/**
Identifies the types of resource or data type elements to which the extension can be applied.
@returns {Array} an array of {@link String} objects
*/
context () { return this.json['context'] }
/**
Definition of the elements that are defined to be in the extension.
@returns {Array} an array of {@link ElementDefinition} objects
*/
element () {
if (this.json['element']) {
return this.json['element'].map(item => new ElementDefinition(item))
}
}
} |
JavaScript | class Level {
constructor(plan) {
let rows = plan.trim(split('\n').map(l => [...l]));
this.height = rows.length;
this.width = rows[0].length;
this.startActors = [];
this.rows = rows.map((row, y) => {
return row.map((ch, x) => {
let type = levelChars[ch];
if (typeof type === 'string') return true;
this.startActors.push(type.create(new Vec(x, y), ch));
})
})
}
} |
JavaScript | class State {
constructor(level, actors, status) {
this.level = level;
this.actors = actors;
this.status = status;
}
static start(level) {
return State(level, level.startActors, 'playing');
}
get Player() {
return this.actors.find(a => a.type === 'player');
}
} |
JavaScript | class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
}
plus(newCoord) {
return new Vec(this.x + newCoord.x, this.y + newCoord.y);
}
times(newCoord) {
return new Vec(this.x * newCoord.x, this.y * newCoord.y);
}
} |
JavaScript | class AbstractReader {
/**
* The constructor.
*
* @public
*/
constructor() {
if (new.target === AbstractReader) {
throw new TypeError("Class 'AbstractReader' is abstract");
}
}
/**
* Locates resources by matching glob patterns.
*
* @example
* byGlob("**/*.{html,htm}");
* byGlob("**/.library");
* byGlob("/pony/*");
*
* @public
* @param {string|string[]} virPattern glob pattern as string or array of glob patterns for
* virtual directory structure
* @param {Object} [options] glob options
* @param {boolean} [options.nodir=true] Do not match directories
* @returns {Promise<module:@ui5/fs.Resource[]>} Promise resolving to list of resources
*/
byGlob(virPattern, options = {nodir: true}) {
const trace = new Trace(virPattern);
return this._byGlob(virPattern, options, trace).then(function(result) {
trace.printReport();
return result;
}).then((resources) => {
if (resources.length > 1) {
// Pseudo randomize result order to prevent consumers from relying on it:
// Swap the first object with a randomly chosen one
const x = 0;
const y = randomInt(0, resources.length - 1);
// Swap object at index "x" with "y"
resources[x] = [resources[y], resources[y]=resources[x]][0];
}
return resources;
});
}
/**
* Locates resources by matching a given path.
*
* @public
* @param {string} virPath Virtual path
* @param {Object} [options] Options
* @param {boolean} [options.nodir=true] Do not match directories
* @returns {Promise<module:@ui5/fs.Resource>} Promise resolving to a single resource
*/
byPath(virPath, options = {nodir: true}) {
const trace = new Trace(virPath);
return this._byPath(virPath, options, trace).then(function(resource) {
trace.printReport();
return resource;
});
}
/**
* Locates resources by one or more glob patterns.
*
* @abstract
* @protected
* @param {string|string[]} virPattern glob pattern as string or an array of
* glob patterns for virtual directory structure
* @param {Object} options glob options
* @param {module:@ui5/fs.tracing.Trace} trace Trace instance
* @returns {Promise<module:@ui5/fs.Resource[]>} Promise resolving to list of resources
*/
_byGlob(virPattern, options, trace) {
throw new Error("Not implemented");
}
/**
* Locate resources by matching a single glob pattern.
*
* @abstract
* @protected
* @param {string} pattern glob pattern
* @param {Object} options glob options
* @param {module:@ui5/fs.tracing.Trace} trace Trace instance
* @returns {Promise<module:@ui5/fs.Resource[]>} Promise resolving to list of resources
*/
_runGlob(pattern, options, trace) {
throw new Error("Not implemented");
}
/**
* Locates resources by path.
*
* @abstract
* @protected
* @param {string} virPath Virtual path
* @param {module:@ui5/fs.tracing.Trace} trace Trace instance
* @returns {Promise<module:@ui5/fs.Resource>} Promise resolving to a single resource
*/
_byPath(virPath, trace) {
throw new Error("Not implemented");
}
} |
JavaScript | class CWCIconBrandPrefixA extends CustomHTMLElement {
/**
* @public @static @name template
* @description Template function to return web component UI
* @return {TemplateResult} HTML template result
*/
static template() {
return html`
<style>
:host {
display: inline-block;
width: 30px;
height: 30px;
padding: 5px;
box-sizing: border-box;
vertical-align: middle;
}
svg { float: left; }
</style>
${ICONS[this.getAttribute('name')]}
`;
}
/**
* @public @static @get @name observedAttributes
* @description Provide attributes to watch for changes
* @return {Array} Array of attribute names as strings
*/
static get observedAttributes() { return ['name'] }
/**
* @public @name attributeChanged
* @description Callback run when a custom elements attributes change
* @param {String} attribute The attribute name
* @param {Mixed} oldValue The old value
* @param {Mixed} newValue The new value
*/
attributeChanged(attribute, oldValue, newValue) { this.updateTemplate() }
} |
JavaScript | class BrowserDb {
constructor(schema) {
this.schema = schema;
this.open = new Promise((resolve, reject) => {
const req = indexedDB.open(schema.name, schema.version);
req.onerror = () => reject(req.error);
req.onblocked = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
req.onupgradeneeded = () => {
const db = req.result;
for (const name of db.objectStoreNames)
db.deleteObjectStore(name);
for (const col of schema.collections) {
db.createObjectStore(col.name, {
keyPath: col.keyPath,
autoIncrement: col.autoGenerated,
});
}
};
});
this.collections = this.open.then((db) => this.schema.collections.map((col) => new BrowserDbCollection_1.default(db, col)));
}
getName() {
return this.schema.name;
}
getVersion() {
return this.schema.version;
}
getCollections() {
return this.collections;
}
getCollection(name) {
return this.collections.then((cols) => cols.find((col) => col.getName() === name));
}
drop() {
return new Promise((resolve, reject) => {
const req = indexedDB.deleteDatabase(this.schema.name);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
getSchema() {
return this.schema;
}
} |
JavaScript | class ARIATypeInteger extends ARIAAttrAssembler {
/**
* value = .0
* value = .0e-1
* value = '.0'
* value = '.0e-1'
* value = []
* value = [.0]
* value = ['.0e-1']
* value = false
* => '0'
*
* value = 1.1
* value = 11e-1
* value = '1.1'
* value = '11e-1'
* value = [1.1]
* value = ['11e-1']
* value = true
* => '1'
*
* value = 4.2
* value = 42e-1
* value = '4.2'
* value = '42e-1'
* value = [4.2]
* value = ['4.2']
* => '4'
*
* value = NaN
* value = 'NaN'
* value = 'xyz' // non empty string
* value = {}
* value = [.0, 4.2, 1.1]
* value = function() {}
* value = undefined
* => 'NaN'
*
* value = Infinity
* value = 'Infinity'
* => 'Infinity'
*
* value = null
* value = ''
* => no attr
*
* @param {number|null} value {number|null}
*/
set value(value) {
if(this.constructor.removeOnValue(value)) {
this.remove()
}
else this.node.value = String(Math.floor(value))
}
/**
* value === '.0'
* value === '.0e-1'
* => 0
*
* value === '1.1'
* value === '11e-1'
* => 1
*
* value === '4.2'
* value === '42e-1'
* => 4
*
* value === 'NaN'
* value === 'true'
* value === 'false'
* value === 'undefined'
* value === 'xyz' // non empty string
* => NaN
*
* value === 'Infinity'
* => Infinity
*
* value === ''
* no attr
* => null
*
* @returns {number|null}
*/
get value() {
const value = this.node.value
return value?
Math.floor(Number(value)) :
this.constructor.defaultValue
}
} |
JavaScript | class Boid {
constructor() {
this.pos = createVector(10, 10)
this.vel = createVector(0, 0)
this.acc = createVector(0, 0);
this.range = 0;
this.forceLine = new ForceLine()
this.showForce = false
}
show() {
circle(this.pos.x, this.pos.y, 15); // feel free to change this to rectangle or triangle or custom shape
if (this.showForce) {
this.forceLine.show()
}
}
update() {
this.forceLine.setStart(this.pos.x,this.pos.y);
this.forceLine.setEnd(this.acc.x, this.acc.y)
this.vel.add(this.acc)
this.pos.add(this.vel)
this.acc.mult(0)
}
applyForce(force) {
this.acc.add(force)
}
setPos(x, y) {
this.pos = createVector(x, y)
}
setVel(vel_vector) {
this.vel = vel_vector
}
applyVel(vel) {
this.vel.add(vel)
}
// bounce from walls
bounceFromWalls() {
if (this.pos.x >= width - 5 || this.pos.x <= 5) {
this.setVel(this.vel.rotate(PI/2))
}
}
checkCollision(rect2) {
let rect1 = {
x: this.pos.x,
y: this.pos.y,
w: 10,
h: 10
}
if (rect1.x < rect2.x + rect2.w &&
rect1.x + rect1.w > rect2.x &&
rect1.y < rect2.y + rect2.h &&
rect1.y + rect1.h > rect2.y) {
// collision detected!
return true;
}
else {
return false;
}
}
bounceBack() {
this.setVel(this.vel.rotate(PI/2))
}
toggleForceLine() {
this.showForce = !this.showForce;
}
} |
JavaScript | class PluginArtifactUploadWizard extends Component {
constructor(props) {
super(props);
this.state = {
showWizard: this.props.isOpen,
successInfo: {},
};
}
componentWillUnmount() {
PluginArtifactUploadStore.dispatch({
type: PluginArtifactUploadActions.onReset,
});
}
onSubmit() {
this.buildSuccessInfo();
return ArtifactUploadActionCreator.uploadArtifact(this.props.includeParents).mergeMap(() => {
this.props.onSubmit();
return ArtifactUploadActionCreator.uploadConfigurationJson();
});
}
toggleWizard(returnResult) {
if (this.state.showWizard) {
this.props.onClose(returnResult);
}
this.setState({
showWizard: !this.state.showWizard,
});
}
buildSuccessInfo() {
this.setState({
successInfo: this.props.buildInfo(),
});
}
render() {
let input = this.props.input;
let pkg = input.package || {};
let headerLabel = input.headerLabel;
let wizardModalTitle =
(pkg.label ? pkg.label + ' | ' : '') +
(headerLabel ? headerLabel : T.translate('features.Wizard.Informational.headerlabel'));
return (
<WizardModal
title={wizardModalTitle}
isOpen={this.state.showWizard}
toggle={this.toggleWizard.bind(this, false)}
className="artifact-upload-wizard"
>
<Wizard
wizardConfig={this.props.wizardConfig}
wizardType="ArtifactUpload"
store={PluginArtifactUploadStore}
onSubmit={this.onSubmit.bind(this)}
successInfo={this.state.successInfo}
onClose={this.toggleWizard.bind(this)}
/>
</WizardModal>
);
}
} |
JavaScript | class Net {
/**
* Create and send a web request using GET
* @param {string} url - The request URL
* @param {string[]} headers - Http request headers
* @param {string} responseType - specifies type of data for response
* @returns {promise} Promise
*/
static Get(url, headers, responseType) {
var d = Core.Defer();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState != 4) return; // 4 - DONE
if (this.status == 200) d.Resolve(this.response); // 200 - OK
else d.Reject({ status:this.status, response:this.response });
};
xhttp.open("GET", url, true);
if (headers) {
for (var id in headers) xhttp.setRequestHeader(id, headers[id]);
}
if (responseType) xhttp.responseType = responseType;
xhttp.send();
return d.promise;
}
/**
* Create and send a web request using POST
* @param {string} url - The request URL
* @param {string} data - Request body
* @param {string[]} headers - Http request headers
* @param {string} responseType - specifies type of data for response
* @returns {promise} Promise
*/
static Post(url, data, headers, responseType) {
var d = Core.Defer();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState != 4) return; // 4 - DONE
if (this.status == 200) d.Resolve(this.response); // 200 - OK
else d.Reject({ status:this.status, response:this.response });
};
xhttp.open("POST", url, true);
if (responseType) xhttp.responseType = responseType;
if (headers) {
for (var id in headers) xhttp.setRequestHeader(id, headers[id]);
}
(data) ? xhttp.send(data) : xhttp.send();
return d.promise;
}
/**
* Get JSON from URL
* @param {string} url for JSON file
* @returns (promise) Promise with parsed JSON if resolved
*/
static JSON(url) {
var d = Core.Defer();
Net.Get(url).then(r => d.Resolve(JSON.parse(r)), d.Reject);
return d.promise;
}
/**
* Create file object on successful request
* @param {string} url - The request URL
* @param {string} name - The name of the file
* @returns {promise} Promise
*/
static File(url, name) {
var d = Core.Defer();
Net.Get(url, null, 'blob').then(b => {
d.Resolve(new File([b], name));
}, d.Reject);
return d.promise;
}
/**
* Parses the location query and returns a string dictionary
* @returns {object} A dictionary of string key values containing the parameters from the location query
*/
static ParseUrlQuery() {
var params = {};
var query = location.search.slice(1);
if (query.length == 0) return params;
query.split("&").forEach(p => {
var lr = p.split("=");
params[lr[0]] = lr[1];
});
return params;
}
/**
* Get a parameter value from the document URL
* @param {string} name - The name of the parameter to retrieve from the URL
* @returns {string} The value of the parameter from the URL, an empty string if not found
*/
static GetUrlParameter (name) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
var results = regex.exec(window.location.href);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
/**
* Download content as a file
* @param {string} name - The name of the file to download
* @param {string} content - Content from page
* @returns {void}
*/
static Download(name, content) {
var link = document.createElement("a");
link.href = "data:application/octet-stream," + encodeURIComponent(content);
link.download = name;
link.click();
link = null;
}
/**
* Gets the base URL for the app
* @returns {string} - The base path to the web app
*/
static AppPath() {
var path = location.href.split("/");
path.pop();
return path.join("/");
}
/**
* Gets the URL for the app and file
* @param {string} file - The filename to which path will be added
* @returns {string} The URL for the app and the file
*/
static FilePath(file) {
file = file.charAt(0) == "/" ? file.substr(1) : file;
var path = [Net.AppPath(), file];
return path.join("/");
}
} |
JavaScript | class Restaurant {
constructor(srcBaseUrl, contentType) {
this.card = require('./design/restaurant.json');
this.contentType = contentType;
this.srcUrl = `${srcBaseUrl}/restaurant`;
}
async renderCard(bot, logger, cardSelection) {
let message = {};
try {
message = await bot.say('The Restaurant sample demonstrates the following types of controls:\n' +
'* ColumnSets and Columns with the width attribute\n' +
'* Image with the size and attribute\n' +
'* Text Blocks with many attributes including size, weight, isSubtle and spacing\n' +
'* OpenUrl Action\n\n' +
'Cards with images can take a few seconds to render. ' +
'In the meantime you can see the full source here: ' + this.srcUrl);
message = await bot.sendCard(this.card, "If you see this your client cannot render our Restaurant example.");
logger.info(`Sent the ${cardSelection} card to space: ${bot.room.title}`);
} catch (err) {
let msg = 'Failed to render Restaurant card example.';
logger.error(`${msg} Error:${err.message}`);
bot.say(`${msg} Please contact the Webex Developer Support: https://developer.webex.com/support`)
.catch((e) => logger.error(`Failed to post error message to space. Error:${e.message}`));
}
bot.reply(message, 'When a user clicks on a Action.OpenUrl button in Webex Teams, the client opens that link directly, ' +
'and there is no event to the application that posted the card.\n\n' +
'...Don\'t click on more Info unless you want to see more pictures of yummy food!\n\n' +
'Post any message to me if you want to see another card')
.catch((e) => logger.error(`Failed to post follow-up to Restaurant card. Error:${e.message}`));
logger.info(`Sent reply to the ${cardSelection} card to space: ${bot.room.title}`);
};
} |
JavaScript | class Slide {
constructor(el) {
this.DOM = {el: el};
this.DOM.imgWrap = this.DOM.el.querySelector('.slide__img-wrap');
this.DOM.img = this.DOM.imgWrap.querySelector('.slide__img');
this.DOM.revealer = this.DOM.imgWrap.querySelector('.slide__img-reveal');
this.DOM.title = this.DOM.el.querySelector('.slide__title');
this.DOM.titleBox = this.DOM.title.querySelector('.slide__box');
this.DOM.titleInner = this.DOM.title.querySelector('.slide__title-inner');
this.DOM.subtitle = this.DOM.el.querySelector('.slide__subtitle');
this.DOM.subtitleBox = this.DOM.subtitle.querySelector('.slide__box');
this.DOM.subtitleInner = this.DOM.subtitle.querySelector('.slide__subtitle-inner');
this.DOM.quote = this.DOM.el.querySelector('.slide__quote');
this.DOM.explore = this.DOM.el.querySelector('.slide__explore');
// Some config values.
this.config = {
revealer: {
// Speed and ease for the revealer animation.
speed: {hide: 0.5, show: 0.7},
ease: {hide: 'Quint.easeOut', show: 'Quint.easeOut'}
}
};
// init/bind events.
this.initEvents();
}
initEvents() {
this.mouseenterFn = () => {
// hover on the "explore" link: scale up the img element.
if ( this.isPositionedCenter() ) {
this.zoom({scale: 1.2, speed: 2, ease: 'Quad.easeOut'});
/*TweenMax.to(this.DOM.explore.querySelector('.slide__explore-inner'), 0.3, {
y: '-100%'
});*/
}
};
this.mouseleaveFn = () => {
// hover on the "explore" link: reset the scale of the img element.
if ( this.isPositionedCenter() ) {
this.zoom({scale: 1.1, speed: 2, ease: 'Quad.easeOut'});
/*TweenMax.to(this.DOM.explore.querySelector('.slide__explore-inner'), 0.3, {
startAt: {y: '100%'},
y: '0%'
});*/
}
};
this.DOM.explore.addEventListener('mouseenter', this.mouseenterFn);
this.DOM.explore.addEventListener('mouseleave', this.mouseleaveFn);
}
// set the class current.
setCurrent(hideBefore = true) {
this.isCurrent = true;
if ( hideBefore ) {
// Hide the image.
this.showRevealer({animation: false});
// And the texts.
this.DOM.titleInner.style.opacity = 0;
this.DOM.subtitleInner.style.opacity = 0;
this.DOM.titleBox.style.opacity = 0;
this.DOM.subtitleBox.style.opacity = 0;
this.DOM.explore.style.opacity = 0;
}
this.DOM.el.classList.add('slide--current', 'slide--visible');
}
// Set the class left.
setLeft(hideBefore = true) {
this.isRight = this.isCurrent = false;
this.isLeft = true;
// Show the revealer and reset the texts that are visible for the left and right slides.
if ( hideBefore ) {
this.resetLeftRight();
}
this.DOM.el.classList.add('slide--left', 'slide--visible');
}
// Set the class right.
setRight(hideBefore = true) {
this.isLeft = this.isCurrent = false;
this.isRight = true;
// Show the revealer and reset the texts that are visible for the left and right slides.
if ( hideBefore ) {
this.resetLeftRight();
}
this.DOM.el.classList.add('slide--right', 'slide--visible');
}
// Show the revealer and reset the texts that are visible for the left and right slides.
resetLeftRight() {
this.showRevealer({animation: false});
// Reset texts.
this.DOM.titleInner.style.opacity = 0;
this.DOM.titleInner.style.transform = 'none';
}
// Check if the slide is positioned on the right side (if it´s the next slide in the slideshow).
isPositionedRight() {
return this.isRight;
}
// Check if the slide is positioned on the left side (if it´s the previous slide in the slideshow).
isPositionedLeft() {
return this.isLeft;
}
// Check if the slide is the current one.
isPositionedCenter() {
return this.isCurrent;
}
// Shows the white container on top of the image.
showRevealer(opts = {}) {
return this.toggleRevealer('hide', opts);
}
// Hides the white container on top of the image.
hideRevealer(opts = {}) {
return this.toggleRevealer('show', opts);
}
toggleRevealer(action, opts) {
return new Promise((resolve, reject) => {
if ( opts.animation ) {
TweenMax.to(this.DOM.revealer, opts.speed || this.config.revealer.speed[action], {
delay: opts.delay || 0,
ease: opts.ease || this.config.revealer.ease[action],
startAt: action === 'hide' ? {y: opts.direction === 'prev' ? '-100%' : '100%'} : {},
y: action === 'hide' ? '0%' : opts.direction === 'prev' ? '100%' : '-100%',
onComplete: resolve
});
}
else {
this.DOM.revealer.style.transform = action === 'hide' ?
'translate3d(0,0,0)' :
`translate3d(0,${opts.direction === 'prev' ? '100%' : '-100%'},0)`
resolve();
}
});
}
// Hide the slide.
hide(direction, delay) {
return this.toggle('hide', direction, delay);
}
// Show the slide.
show(direction, delay) {
return this.toggle('show', direction, delay);
}
// Show/Hide the slide.
toggle(action, direction, delay) {
// Zoom in/out the image
this.zoom({
scale: action === 'hide' ? 1.2 : 1.1,
speed: action === 'hide' ? this.config.revealer.speed[action] : this.config.revealer.speed[action]*2.5,
ease: this.config.revealer.ease[action],
startAt: action === 'show' ? {scale: 1} : {},
delay: delay
});
// Hide/Show the slide´s texts.
if ( action === 'hide' ) {
this.hideTexts(direction, delay);
}
else {
this.showTexts(direction, delay);
}
// Hide/Show revealer on top of the image
return this[action === 'hide' ? 'showRevealer' : 'hideRevealer']({delay: delay, direction: direction, animation: true});
}
hideTexts(direction, delay) {
this.toggleTexts('hide',direction, delay);
}
showTexts(direction, delay) {
this.toggleTexts('show',direction, delay);
}
toggleTexts(action, direction, delay) {
if ( this.isPositionedCenter() ) {
this.DOM.titleBox.style.transformOrigin = this.DOM.subtitleBox.style.transformOrigin = action === 'hide' ? '100% 50%' : '0% 50%';
const speed = action === 'hide' ? 0.2 : 0.6;
const ease = action === 'hide' ? 'Power3.easeInOut' : 'Expo.easeOut';
TweenMax.to(this.DOM.titleInner, speed, {
ease: ease,
delay: action === 'hide' ? delay : delay + 0.2,
startAt: action === 'show' ? {x: '-100%'} : {},
x: action === 'hide' ? '100%' : '0%',
opacity: action === 'hide' ? 0 : 1
});
TweenMax.to(this.DOM.titleBox, speed, {
ease: ease,
delay: action === 'hide' ? delay + 0.2 : delay,
startAt: action === 'show' ? {scaleX: 0} : {},
scaleX: action === 'hide' ? 0 : 1,
opacity: 1
});
TweenMax.to(this.DOM.subtitleInner, speed, {
ease: ease,
delay: action === 'hide' ? delay + 0.3 : delay + 0.5,
startAt: action === 'show' ? {x: '-100%'} : {},
x: action === 'hide' ? '100%' : '0%',
opacity: action === 'hide' ? 0 : 1
});
TweenMax.to(this.DOM.subtitleBox, speed, {
ease: ease,
delay: action === 'hide' ? delay + 0.5 : delay + 0.3,
startAt: action === 'show' ? {scaleX: 0} : {},
scaleX: action === 'hide' ? 0 : 1,
opacity: 1
});
TweenMax.to(this.DOM.explore, speed, {
ease: ease,
delay: delay + 0.2,
startAt: action === 'show' ? {y: '100%'} : {},
y: action === 'hide' ? '-100%' : '0%',
opacity: action === 'hide' ? 0 : 1
});
}
else {
TweenMax.to(this.DOM.titleInner, this.config.revealer.speed.hide, {
ease: 'Quint.easeOut',
delay: delay,
startAt: action === 'show' ? {x: direction === 'next' ? '-50%' : '50%', opacity: 0} : {},
x: action === 'show' ? '0%' : direction === 'next' ? '50%' : '-50%',
opacity: action === 'hide' ? 0 : 1
});
}
}
load() {
// Scale up the images.
this.zoom({
scale: 1.1,
speed: this.config.revealer.speed['show']*2.5,
ease: this.config.revealer.ease.hide
});
// For the current also animate in the "explore" link.
if ( this.isPositionedCenter() ) {
TweenMax.to(this.DOM.explore, this.config.revealer.speed['show']*2.5, {
ease: this.config.revealer.ease.hide,
startAt: {y: '100%', opacity: 0},
y: '0%',
opacity: 1
});
}
}
// Zooms in/out the image.
zoom(opts = {}) {
TweenMax.to(this.DOM.img, opts.speed || 1, {
startAt: opts.startAt || {},
delay: opts.delay || 0,
scale: opts.scale || 1,
ease: opts.ease || 'Quint.easeOut'
});
}
// Reset classes and state.
reset() {
this.isRight = this.isLeft = this.isCurrent = false;
this.DOM.el.classList = 'slide';
}
} |
JavaScript | class Slideshow {
constructor(el) {
this.DOM = {el: el};
// The slides.
this.slides = [];
Array.from(this.DOM.el.querySelectorAll('.slide')).forEach(slideEl => this.slides.push(new Slide(slideEl)));
// The total number of slides.
this.slidesTotal = this.slides.length;
// At least 3 slides to continue...
if ( this.slidesTotal < 3 ) {
return false;
}
// Current slide position.
this.current = 0;
// Set the current/right/left slides.
// Passing false indicates we dont need to show the revealer (white container that hides the images) on the images.
this.render(false);
// Init/Bind events.
this.initEvents();
}
render(hideSlidesBefore = false) {
// The current, next, and previous slides.
this.currentSlide = this.slides[this.current];
this.nextSlide = this.slides[this.current+1 <= this.slidesTotal-1 ? this.current+1 : 0];
this.prevSlide = this.slides[this.current-1 >= 0 ? this.current-1 : this.slidesTotal-1];
// Set the classes.
this.currentSlide.setCurrent(hideSlidesBefore);
this.nextSlide.setRight(hideSlidesBefore);
this.prevSlide.setLeft(hideSlidesBefore);
}
// Set the animations for the slides when the slideshow gets revealed initially (scale up images and animate some of the texts)
load() {
[this.nextSlide,this.currentSlide,this.prevSlide].forEach(slide => slide.load());
}
initEvents() {
// Clicking the next and previous slide.
this.navigateFn = (slide) => {
if ( slide.isPositionedRight() ) {
this.navigate('next');
}
else if ( slide.isPositionedLeft() ) {
this.navigate('prev');
}
};
for (let slide of this.slides) {
slide.DOM.imgWrap.addEventListener('click', () => this.navigateFn(slide));
}
}
hideSlides(direction) {
return this.toggleSlides('hide', direction);
}
updateSlides() {
// Reset current visible slides, by removing the right/left/current and visible classes.
[this.nextSlide,this.currentSlide,this.prevSlide].forEach(slide => slide.reset());
// Set the new left/right/current slides and make sure the revealer is shown on top of them (hide its images).
this.render(true);
}
showSlides(direction) {
return this.toggleSlides('show', direction);
}
// Show/Hide the slides, each with a delay.
toggleSlides(action, direction) {
const delayFactor = 0.2;
let processing = [];
[this.nextSlide,this.currentSlide,this.prevSlide].forEach(slide => {
let delay = slide.isPositionedCenter() ? delayFactor/2 :
direction === 'next' ? slide.isPositionedRight() ? 0 : delayFactor :
slide.isPositionedRight() ? delayFactor : 0;
processing.push(slide[action](direction, delay));
});
return Promise.all(processing);
}
// Navigate the slideshow.
navigate(direction) {
// If animating return.
if ( this.isAnimating ) return;
this.isAnimating = true;
// Update current.
this.current = direction === 'next' ?
this.current < this.slidesTotal-1? this.current+1 : 0 :
this.current = this.current > 0 ? this.current-1 : this.slidesTotal-1;
// Hide the current visible slides (left, right and current),
// then switch and show the new slides.
this.hideSlides(direction)
.then(() => this.updateSlides())
.then(() => this.showSlides(direction))
.then(() => this.isAnimating = false);
}
} |
JavaScript | class BehaviourAccordion extends LitElement {
static get is() {
return 'behaviour-accordion';
}
static get properties() {
return {
target: { type: String }
};
}
static get styles() {
/** CSS-VARIABLES
--arrow-color: #333;
*/
return css`
:host {
display: inline;
}
.toggle {
cursor: pointer;
content: " ";
position: relative;
left: 10px;
width: 0;
height: 0;
margin-top: 0;
border: 8px solid transparent;
}
.disabled {
cursor: not-allowed;
opacity:0.3;
}
.down {
border-top-color: var(--arrow-color, #333);
top: 15px;
}
.up {
border-bottom-color: var(--arrow-color, #333);
top: -13px;
}
`;
}
_collapseSection() {
const element = this.targetElement;
const sectionHeight = element.scrollHeight;
const elementTransition = element.style.transition;
element.style.transition = '';
requestAnimationFrame(() => {
element.style.height = sectionHeight + 'px';
element.style.transition = elementTransition;
requestAnimationFrame(() => {
element.style.height = 0 + 'px';
});
});
element.setAttribute('data-collapsed', 'true');
}
_expandSection() {
const element = this.targetElement;
const sectionHeight = element.scrollHeight;
element.style.height = sectionHeight + 'px';
element.addEventListener('transitionend', (e) => {
element.removeEventListener('transitionend', arguments.callee);
element.style.height = null;
});
element.setAttribute('data-collapsed', 'false');
}
_toggleCollapse(ev) {
if (this.targetElement) {
const el = ev.target;
if (el.classList.value.includes('up')) {
el.classList.remove('up');
el.classList.add('down');
this._collapseSection();
} else {
el.classList.remove('down');
el.classList.add('up');
this._expandSection();
}
}
}
constructor() {
super();
this.target = '';
this.targetElement = null;
this.collapsedStyle = 'overflow:hidden; transition:height 0.3s ease-out;';
this._toggleCollapse = this._toggleCollapse.bind(this);
}
connectedCallback() {
super.connectedCallback();
}
disconnectedCallback() {
super.disconnectedCallback();
this.shadowRoot.querySelector('a').removeEventListener('click', this._toggleCollapse);
}
firstUpdated() {
this.shadowRoot.querySelector('a').addEventListener('click', this._toggleCollapse);
this.targetElement = document.querySelector(this.target) || null;
if (this.targetElement) {
this.targetElement.style = this.collapsedStyle;
this.shadowRoot.querySelector('a').classList.remove('disabled');
} else {
this.shadowRoot.querySelector('a').classList.add('disabled');
}
}
render() {
return html`
<a class="toggle up"></a>
`;
}
} |
JavaScript | class r extends y{constructor(){super(...arguments);this.alignEnd=!1,this.spaceBetween=!1,this.nowrap=!1,this.label="",this.mdcFoundationClass=E}createAdapter(){return{registerInteractionHandler:(t,e)=>{this.labelEl.addEventListener(t,e)},deregisterInteractionHandler:(t,e)=>{this.labelEl.removeEventListener(t,e)},activateInputRipple:async()=>{const t=this.input;if(t instanceof s){const e=await t.ripple;e&&e.startPress()}},deactivateInputRipple:async()=>{const t=this.input;if(t instanceof s){const e=await t.ripple;e&&e.endPress()}}}}get input(){return u(this.slotEl,"*")}render(){const t={"mdc-form-field--align-end":this.alignEnd,"mdc-form-field--space-between":this.spaceBetween,"mdc-form-field--nowrap":this.nowrap};return p`
<div class="mdc-form-field ${b(t)}">
<slot></slot>
<label class="mdc-label"
@click="${this._labelClick}">${this.label}</label>
</div>`}_labelClick(){const t=this.input;t&&(t.focus(),t.click())}} |
JavaScript | class TreeNode {
constructor(value ) {
this.value = value;
this.parent = undefined;
this.children = [];
}
addChild(child) {
child.parent = this;
this.children.push(child);
}
} |
JavaScript | class FormElement {
constructor(summary, dom_elem) {
Object.assign(this, summary);
this.element = dom_elem;
}
isInput() {
return (INPUT_TAGS.indexOf(this.tag.toLowerCase()) != -1)
&& (this.type.toLowerCase() != 'hidden')
&& (this.visible); // TODO: ok for now, but sometimes we may want to interact with non-visible inputs (in a modal thats not active for instance)
}
isAction() {
return (this.type.toLowerCase() == 'submit')
|| (this.tag.toLowerCase() == 'button');
}
} |
JavaScript | class ApplicationProfile extends BaseProfile {
/**
* The name of the application.
*
* @returns {null|Attribute}
*/
getName() {
return this.getAttribute(constants.ATTR_APPLICATION_NAME);
}
/**
* The URL where the application is available at.
*
* @returns {null|Attribute}
*/
getUrl() {
return this.getAttribute(constants.ATTR_APPLICATION_URL);
}
/**
* The logo of the application that will be displayed to users that perform a share with it.
*
* @returns {null|Attribute}
*/
getLogo() {
return this.getAttribute(constants.ATTR_APPLICATION_LOGO);
}
/**
* The background colour that will be displayed on each receipt the user gets, as a result
* of a share with the application.
*
* @returns {null|Attribute}
*/
getReceiptBgColor() {
return this.getAttribute(constants.ATTR_APPLICATION_RECEIPT_BGCOLOR);
}
} |
JavaScript | class BulkMessage{
/**
* Initializes a new instance of the BasicMessage class
*/
constructor() {
/**
* The list of To recipients.
*/
this.to = [];
/**
* The list of custom headers.
*/
this.customHeaders = [];
/**
* The list of attachments.
*/
this.attachments = [];
/**
* The list of global merge data.
*/
this.globalMergeData = [];
/**
* The type of message.
*/
this.messageType = "bulk";
}
/**
* Sets the message Subject
* @param {string} value
*/
setSubject(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if (typeof value !== 'string') {
throw new Error("Invalid subject, type of 'string' was expected.");
}
/**
* The message Subject
*/
this.subject = value;
}
/**
* Sets the plain text portion of the message body.
* (Optional) Either TextBody or HtmlBody must be used with the AmpBody or use a ApiTemplate
* @param {string} value
*/
setTextBody(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if (typeof value !== 'string') {
throw new Error("Invalid Plain Text Body, type of 'string' was expected.");
}
/**
* The plain text portion of the message body.
*/
this.textBody = value;
}
/**
* Sets the HTML portion of the message body.
* (Optional) Either TextBody or HtmlBody must be used with the AmpBody or use a ApiTemplate
* @param {string} value
*/
setHtmlBody(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if (typeof value !== 'string') {
throw new Error("Invalid HTML Body, type of 'string' was expected.");
}
/**
* The HTML portion of the message body.
*/
this.htmlBody = value;
}
/**
* Sets the Api Template for the message.
* (Optional) Either TextBody or HtmlBody must be used with the AmpBody or use a ApiTemplate
* @param {int} value
*/
setApiTemplate(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if (!Number.isInteger(value)) {
throw new Error("Invalid Api Template, type of 'Integer' was expected.");
}
/**
* The Api Template for the message.
*/
this.apiTemplate = value;
}
/**
* Sets the ampBody for the message.
* (Optional) Either TextBody or HtmlBody must be used with the AmpBody or use a ApiTemplate
* @param {int} value
*/
setAmpBody(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if (typeof value !== 'string') {
throw new Error("Invalid ampBody, type of 'string' was expected.");
}
/**
* The Api Template for the message.
*/
this.ampBody = value;
}
/**
* Sets the custom MailingId for the message.
* @param {string} value
*/
setMailingId(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if (typeof value !== 'string') {
throw new Error("Invalid Mailing Id, type of 'string' was expected.");
}
/**
* The custom MailingId for the message.
* (Optional) See https://www.socketlabs.com/blog/best-practices-for-using-custom-mailingids-and-messageids/ for more information.
*/
this.mailingId = value;
}
/**
* Sets the custom MessageId for the message.
* @param {string} value
*/
setMessageId(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if (typeof value !== 'string') {
throw new Error("Invalid Message Id, type of 'string' was expected.");
}
/**
* The custom MessageId for the message.
*/
this.messageId = value;
}
/**
* Sets the From address.
* @param {EmailAddress} value
*/
setFrom(value) {
if (typeof value === 'undefined' || !value) {
return;
}
else {
this.from = toEmailAddress.convert(value);
}
}
/**
* Sets the From address.
* @param {string} value
* @param {string} name
*/
setFromAddress(value, name) {
/**
* The From emailAddress.
*/
this.from = new emailAddress(value, { friendlyName: name });
}
/**
* Sets the Reply To address.
* @param {EmailAddress} value
*/
setReplyTo(value) {
if (typeof value === 'undefined' || !value) {
return;
}
else {
this.replyTo = toEmailAddress.convert(value);
}
}
/**
* Sets the Reply To address.
* @param {string} value
* @param {string} name
*/
setReplyToAddress(value, name) {
/**
* The Reply emailAddress.
*/
this.replyTo = new emailAddress(value, { friendlyName: name });
}
/**
* Sets the character set for your message.
* (Optional) Default is UTF8
* @param {string} value
*/
setCharSet(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if (typeof value !== 'string') {
throw new Error("Invalid character set, type of 'string' was expected.");
}
/**
* The character set for your message.
*/
this.charSet = value;
}
/**
* Sets the list of To recipients, an array of BulkRecipient items
* @param {Array} value
*/
setTo(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if(value && Array.isArray(value)) {
value.forEach(element => {
this.to.push(toBulkRecipient.convert(element));
});
}
else {
this.to.push(toBulkRecipient.convert(value));
}
}
/**
* Add a new EmailAddress to the array of To recipients
* @param {string} value
* @param {string} name
* @param {string} mergeData
*/
addToRecipient(value, name, mergeData) {
this.to.push(new bulkRecipient(value, { friendlyName: name, mergeData: mergeData }));
}
/**
* Sets the list of attachments, an array of Attachment items
* @param {EmailAddress} value
*/
setAttachments(value) {
this.addAttachments(value);
}
/**
* Add an EmailAddress to the array of BCC recipients
* @param {Attachment} value
*/
addAttachments(value) {
if(value && Array.isArray(value)) {
value.forEach(element => {
if (element.constructor === attachment) {
this.attachments.push(element);
}
});
}
else if (value.constructor === attachment) {
this.attachments.push(value);
}
else {
throw new Error("Invalid attachment, the attachment was not submitted in an expected format!");
}
}
/**
* Sets the list of custom headers, an array of CustomHeader items
* @param {CustomHeader} value
*/
setCustomHeaders(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if(value && Array.isArray(value)) {
value.forEach(element => {
this.customHeaders.push(toCustomHeader.convert(element));
});
}
else {
this.customHeaders.push(toCustomHeader.convert(value));
}
}
/**
* Add a CustomHeader to the message
* @param {string} name
* @param {string} value
*/
addCustomHeaders(name, value) {
this.customHeaders.push(new customHeader(name, value));
}
/**
* Sets the list of MergeData items that will be global across the whole message, an array of MergeData items.
* @param {MergeData} value
*/
setGlobalMergeData(value) {
if (typeof value === 'undefined' || !value) {
return;
}
if(value && Array.isArray(value)) {
value.forEach(element => {
this.globalMergeData.push(toMergeData.convert(element));
});
}
else {
this.globalMergeData.push(toMergeData.convert(value));
}
}
/**
* Add a MergeData to the array of GlobalMergeData
* @param {string} key
* @param {string} value
*/
addGlobalMergeData(key, value) {
this.globalMergeData.push(new mergeData(key, value));
}
/**
* String representation of the CustomHeader class.
* @returns {string}
*/
toString() {
return `Recipients: ${this.to.length}, Subject: '${this.subject}'`;
}
/**
* JSON string representation of the CustomHeader class.
*/
toJSON() {
var json = {};
if (this.subject) {
json.subject = this.subject;
}
if (this.htmlBody) {
json.htmlBody = this.htmlBody;
}
if (this.textBody) {
json.textBody = this.textBody;
}
if (this.apiTemplate) {
json.apiTemplate = this.apiTemplate;
}
if (this.ampBody) {
json.ampBody = this.ampBody;
}
if (this.mailingId) {
json.mailingId = this.mailingId;
}
if (this.messageId) {
json.messageId = this.messageId;
}
json.from = toEmailAddress.convert(this.from).toJSON();
if (this.replyTo) {
json.replyTo = this.replyTo.toJSON();
}
if (this.charSet) {
json.charSet = this.CharSet;
}
if (this.customHeaders.length > 0) {
var _ch = [];
this.customHeaders.forEach(element => {
_ch.push(toCustomHeader.convert(element).toJSON());
});
json.customHeaders = _ch;
}
if (this.attachments.length > 0) {
var _at = [];
this.attachments.forEach(element => {
_at.push(toAttachment.convert(element).toJSON());
});
json.attachments = _at;
}
if (this.to.length > 0) {
if (!json.mergeData)
json.mergeData = {};
json.to = [ { emailAddress: "%%DeliveryAddress%%", friendlyName: "%%RecipientName%%" } ];
var _pm = [];
if (this.to.length > 0) {
this.to.forEach(element => {
_pm.push(toBulkRecipient.convert(element).toJSON());
});
}
json.mergeData.PerMessage = _pm;
}
if (this.globalMergeData.length > 0) {
if (!json.mergeData)
json.mergeData = {};
var _gd = [];
if (this.globalMergeData.length > 0) {
var keys = this.globalMergeData.map((mdata) => mdata.key.toLowerCase());
var duplicateKeys = keys.reduce((acc, curr, i, arr) => {
if(arr.indexOf(curr) !== i && acc.indexOf(curr) < 0){
acc.push(curr);
}
return acc;
}, []);
if(duplicateKeys.length > 0) {
throw new Error(`Invalid global merge data, merge data items contained duplicate keys: ${duplicateKeys}.`);
}
this.globalMergeData.forEach(element => {
_gd.push(toMergeData.convert(element).toJSON());
});
}
json.mergeData.Global = _gd;
}
return json;
}
} |
JavaScript | class Intern extends Employee {
constructor(name, id, email, school){
super (name, id, email)
this.school=school;
}
getSchool(){
return this.school
}
getRole(){
return "Intern"
}
} |
JavaScript | class Register extends React.Component {
//Detail Screen to show from any Open detail button
constructor(props) {
super(props);
}
state = {
modalFlag: false,
user_token: "",
showButtons: true,
refreshing: false,
SharedLoading: true,
loading: true,
initialIndexRadioForm1: -1,
initialIndexRadioForm2: -1,
type_of_meal_1: [
{ label: "Breakfast", value: "Breakfast" },
{ label: "Lunch", value: "Lunch" }
],
type_of_meal_2: [
{ label: "Dinner", value: "Dinner" },
{ label: "Snack", value: "Snack" }
],
stringDay: "",
number_of_servings: "1",
day: moment().format("YYYY-MM-DD"),
day_display: moment().format("MMMM Do YYYY"),
query: "",
choosen_type_of_meal: "",
choosen__meal: "",
meals: []
};
componentWillMount() {
this.keyboardDidShowListener = Keyboard.addListener(
"keyboardDidShow",
this._keyboardDidShow
);
this.keyboardDidHideListener = Keyboard.addListener(
"keyboardDidHide",
this._keyboardDidHide
);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidHide = () => {
this.refs["meal_input"].blur();
this.setState({ showButtons: true });
}
async componentDidMount() {
await this._retrieveData();
let date = this.props.navigation.getParam("date", null);
let food_log_type = this.props.navigation.getParam("food_log_type", null);
if (date != null) {
this.dealWithParams(date, food_log_type);
} else {
this.dealWithTime();
}
if (!this.state.SharedLoading) {
this.getMeals();
}
}
dealWithParams = (date, type) => {
let day = moment(date, "YYYY-MM-DD").format("YYYY-MM-DD");
let day_display = moment(date, "YYYY-MM-DD").format("MMMM Do YYYY");
if (type == "Breakfast") {
this.setState({
day: day,
day_display: day_display,
choosen_type_of_meal: "Breakfast",
initialIndexRadioForm1: 0
});
} else if (type == "Lunch") {
this.setState({
day: day,
day_display: day_display,
choosen_type_of_meal: "Lunch",
initialIndexRadioForm1: 1
});
} else if (type == "Dinner") {
this.setState({
day: day,
day_display: day_display,
choosen_type_of_meal: "Dinner",
initialIndexRadioForm2: 0
});
} else {
this.setState({
day: day,
day_display: day_display,
choosen_type_of_meal: "Snack",
initialIndexRadioForm2: 1
});
}
console.log(day_display);
};
_storeData = async token => {
console.log("Storing Token: " + token);
try {
await AsyncStorage.setItem("token", token);
this.setState({ user_token: token });
} catch (error) {
console.log(error);
}
};
dealWithTime = () => {
//moment.locale("pt");
var currentTime = moment(new Date(), "h:mma");
var beginningBreakfastTime = moment("6:00am", "h:mma");
var endBreakfastTime = moment("11:00am", "h:mma");
var beginningLunchTime = moment("12:00pm", "h:mma");
var endLunchTime = moment("3:00pm", "h:mma");
var beginningDinnerTime = moment("6:30pm", "h:mma");
var endDinnerTime = moment("10:30pm", "h:mma");
if (
beginningBreakfastTime.isSameOrBefore(currentTime) &&
endBreakfastTime.isSameOrAfter(currentTime)
) {
console.log("Breakfast time");
this.setState({
choosen_type_of_meal: "Breakfast",
initialIndexRadioForm1: 0
});
} else if (
beginningLunchTime.isSameOrBefore(currentTime) &&
endLunchTime.isSameOrAfter(currentTime)
) {
console.log("Lunch time");
this.setState({
choosen_type_of_meal: "Lunch",
initialIndexRadioForm1: 1
});
} else if (
beginningDinnerTime.isSameOrBefore(currentTime) &&
endDinnerTime.isSameOrAfter(currentTime)
) {
console.log("Dinner time");
this.setState({
choosen_type_of_meal: "Dinner",
initialIndexRadioForm2: 0
});
} else {
console.log("Snack");
this.setState({
choosen_type_of_meal: "Snack",
initialIndexRadioForm2: 1
});
}
};
_retrieveData = async () => {
console.log("HELLO");
try {
const value = await AsyncStorage.getItem("token");
if (value !== null) {
// We have data!!
this.setState({
SharedLoading: false,
user_token: value
});
} else {
this.setState({
SharedLoading: false // TODO ELIMINATE THIS
});
}
} catch (error) {
console.log(error);
this.setState({
SharedLoading: false // TODO ELIMINATE THIS
});
}
};
addFoodLog() {
//unsecure way to send a post
var login_info = "Token " + this.state.user_token;
console.log(this.state.choosen__meal);
if (
this.state.day == "" ||
this.state.day == "Pick a day" ||
this.state.choosen_type_of_meal == "" ||
this.state.number_of_servings == "" ||
this.state.choosen__meal == ""
) {
alert("Fill in the required information!");
} else {
fetch(`${API_URL}/food-logs`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: login_info
},
body: JSON.stringify({
//change these params later
day: this.state.day,
type_of_meal: this.state.choosen_type_of_meal,
number_of_servings: this.state.number_of_servings,
meal: this.state.choosen__meal //this shouldnt go out as clear text
})
})
.then(this.processResponse)
.then(res => {
const { statusCode, responseJson } = res;
if (statusCode == 401) {
this.processInvalidToken();
} else {
console.log(responseJson);
if (responseJson.state == "Error") {
alert(responseJson.message);
} else {
//this.refs.toast.show("Food Log added 💯", DURATION.LENGTH_LONG);
this.props.navigation.navigate("FoodLogs", { refresh: true,alerts: responseJson["alerts"],day:this.state.day,type:this.state.choosen_type_of_meal,showAlerts:true });
}
}
})
.catch(error => {
alert("Error adding Food Log.");
console.error(error);
});
}
}
openDatepicker = async () => {
if (Platform.OS === "android") {
try {
const { action, year, month, day } = await DatePickerAndroid.open({
// Use `new Date()` for current date.
// May 25 2020. Month 0 is January.
date: new Date()
});
if (action !== DatePickerAndroid.dismissedAction) {
let picked_date = new Date(year, month, day);
this.setState({
day:
year.toString() +
"-" +
(month + 1).toString() +
"-" +
day.toString(),
day_display: moment(picked_date).format("MMMM Do YYYY")
});
}
} catch ({ code, message }) {
console.warn("Cannot open date picker", message);
}
}
};
_removeData = async () => {
// TODO Remove Fitbit flag
};
async processResponse(response) {
const statusCode = response.status;
const data = response.json();
const res = await Promise.all([statusCode, data]);
return {
statusCode: res[0],
responseJson: res[1]
};
}
async processInvalidToken() {
this._removeData();
this.props.navigation.navigate("Auth");
}
async getMeals() {
var login_info = "Token " + this.state.user_token;
console.log("adeus");
fetch(`${API_URL}/meals`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: login_info
}
})
.then(this.processResponse)
.then(res => {
const { statusCode, responseJson } = res;
if (statusCode == 401) {
this.processInvalidToken();
} else {
let mealDropdown = [];
//console.log(responseJson)
this._storeData(responseJson.token);
for (var i = 0; i < responseJson.message.length; i++) {
mealDropdown.push({
label: responseJson.message[i].name,
value: responseJson.message[i].id,
compare: false
});
}
this.setState({
meals: mealDropdown,
refreshing: false,
loading: false
});
console.log("Dishes", mealDropdown);
}
})
.catch(error => {
console.log(error);
});
}
handleIdentifiedMeal = identifiedFood => {
this.setState({ choosen__meal: identifiedFood["id"],query: identifiedFood["name"] });
};
handleRefresh = () => {
// Refresh a zona de filtros tambem?
this.setState(
{
refreshing: true
},
() => {
this.getMeals();
}
);
};
handleNavigation = () => {
this.setState({ modalFlag: false });
this.props.navigation.navigate("MealRegister", {
handleRefreshParent: this.handleRefresh.bind(this)
});
};
handleNavigationML = () => {
this.setState({ modalFlag: false });
this.props.navigation.navigate("FoodLogRegisterML", {
handleIdentifiedMeal: this.handleIdentifiedMeal.bind(this)
});
};
handleNavigationBarcode = () => {
this.setState({ modalFlag: false });
this.props.navigation.navigate("FoodLogRegisterBarcodeScanner", {
handleIdentifiedMeal: this.handleIdentifiedMeal.bind(this)
});
};
renderModalAddnewMeal() {
const { modalFlag } = this.state;
if (!modalFlag) return null;
return (
<Modal
isVisible={modalFlag}
useNativeDriver
animationType="fade"
//backdropColor={'grey'}
onBackButtonPress={() => this.setState({ modalFlag: false })}
onBackdropPress={() => this.setState({ modalFlag: false })}
onSwipeComplete={() => this.setState({ modalFlag: false })}
style={styles.modalContainer}
>
<View style={styles.modal}>
<View
style={{
flex: 0.2,
justifyContent: "center",
alignItems: "center",
backgroundColor: theme.primary_color,
borderTopLeftRadius: 0.0234375 * height,
borderTopRightRadius: 0.0234375 * height
}}
>
<Text
style={{
color: theme.white,
fontSize: moderateScale(15),
fontWeight: "normal",
textAlign: "center",
marginHorizontal: 5
}}
>
Add a new meal
</Text>
</View>
<View
style={{
flex: 1
}}
>
<TouchableOpacity
style={{
flex: 0.5,
flexDirection: "row",
borderBottomWidth: 2,
borderColor: theme.primary_color,
justifyContent: "space-around",
alignItems: "center"
}}
onPress={() => this.handleNavigation()}
>
<Text
style={{
color: theme.primary_color,
fontSize: moderateScale(18),
fontWeight: "bold",
textAlign: "center",
marginHorizontal: 5
}}
>
Manually Insert
</Text>
<Ionicons
name="md-arrow-forward"
size={moderateScale(25)}
style={{
color: theme.primary_color,
width: moderateScale(20),
height: moderateScale(20)
}}
></Ionicons>
</TouchableOpacity>
<TouchableOpacity
style={{
flex: 0.5,
flexDirection: "row",
justifyContent: "space-around",
alignItems: "center"
}}
onPress={() => this.handleNavigationML()}
>
<Text
style={{
color: theme.primary_color,
fontSize: moderateScale(18),
fontWeight: "bold",
textAlign: "center",
marginHorizontal: 5
}}
>
MyLife Food Detector
</Text>
<Ionicons
name="md-arrow-forward"
size={moderateScale(25)}
style={{
color: theme.primary_color,
width: moderateScale(20),
height: moderateScale(20)
}}
></Ionicons>
</TouchableOpacity>
</View>
</View>
</Modal>
);
}
findMeal(query) {
if (query === "") {
return [];
}
const { meals } = this.state;
const regex = new RegExp(`${query.trim()}`, "i");
return meals.filter(meals => meals.label.search(regex) >= 0);
}
renderButtons = () => {
if (this.state.showButtons) {
return (
<View
style={{
alignItems: "center",
flexDirection: "row",
flex: 0.5,
position: "absolute",
paddingVertical: 8,
right: 0
}}
>
<View
style={{
flex: 0.15,
justifyContent: "center",
alignItems: "flex-end",
marginHorizontal: 2
}}
>
<TouchableOpacity
style={styles.addButton}
onPress={() => this.handleNavigationML()}
>
<Entypo
name="camera"
size={moderateScale(20)}
style={{
color: "white",
width: moderateScale(20),
height: moderateScale(20)
}}
>
{" "}
</Entypo>
</TouchableOpacity>
</View>
<View
style={{
flex: 0.15,
justifyContent: "center",
alignItems: "flex-end",
marginHorizontal: 2
}}
>
<TouchableOpacity
style={styles.addButton}
onPress={() => this.handleNavigationBarcode()}
>
<MaterialCommunityIcons
name="barcode-scan"
size={moderateScale(20)}
style={{
color: "white",
width: moderateScale(20),
height: moderateScale(20)
}}
/>
</TouchableOpacity>
</View>
<View
style={{
flex: 0.15,
justifyContent: "center",
alignItems: "flex-end",
marginHorizontal: 2
}}
>
<TouchableOpacity
style={styles.addButton}
onPress={() => this.handleNavigation()}
>
<AntDesign
name="plus"
size={moderateScale(20)}
style={{
color: "white",
width: moderateScale(20),
height: moderateScale(20)
}}
/>
</TouchableOpacity>
</View>
</View>
);
} else {
return (
<View
style={{
alignItems: "center",
flexDirection: "row",
flex: 0.5,
position: "absolute",
paddingVertical: 8,
right: 0
}}
>
<View
style={{
flex: 0.15,
justifyContent: "center",
alignItems: "flex-end",
marginHorizontal: 2
}}
>
<TouchableOpacity
style={styles.deleteButton}
onPress={() => {
this.refs["meal_input"].blur();
this.setState({ showButtons: true });
}}
>
<Text style={styles.loginButtonText}>Cancel</Text>
</TouchableOpacity>
</View>
</View>
);
}
};
handleRadioButton = (value, radioFormIndex) => {
this.setState({ choosen_type_of_meal: value });
if (radioFormIndex == 0) {
console.log(radioFormIndex);
this.refs["radioForm2"].clearSelection();
} else {
this.refs["radioForm1"].clearSelection();
}
};
handleMinusDose() {
if (parseFloat(this.state.number_of_servings) - 1 / 2 >= 0.5) {
this.setState({
number_of_servings: parseFloat(this.state.number_of_servings) - 1 / 2
});
}
}
handlePlusDose() {
this.setState({
number_of_servings: parseFloat(this.state.number_of_servings) + 1 / 2
});
}
render() {
const { query, loading } = this.state;
const meals = this.findMeal(query);
const comp = (a, b) => a.toLowerCase().trim() === b.toLowerCase().trim();
if (loading) {
return (
<View style={{ flex: 1, justifyContent: "center" }}>
<ActivityIndicator size="large" />
</View>
);
} else {
return (
<KeyboardAvoidingView style={styles.container} enabled>
<ScrollView
style={{ flex: 1, width: "100%" }}
vertical
keyboardShouldPersistTaps={"always"}
scrollEnabled
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh}
/>
}
scrollEventThrottle={16}
contentContainerStyle={{
flexGrow: 1
}}
>
{/* Date Component*/}
<View
style={{
flex: 0.2,
alignItems: "center",
justifyContent: "center"
}}
>
<TouchableOpacity
onPress={() => this.openDatepicker()}
style={styles.inputView}
>
<AntDesign
name="calendar"
size={moderateScale(20)}
style={{
color: theme.white,
width: moderateScale(20),
height: moderateScale(20)
}}
/>
<Text style={styles.inputText}>{this.state.day_display}</Text>
</TouchableOpacity>
</View>
<View
style={{
flex: 0.35
}}
>
<View
style={{
flex: 0.3,
alignItems: "flex-end",
flexDirection: "row",
justifyContent: "flex-start"
}}
>
<View style={styles.subHeaderView}>
<MaterialCommunityIcons
name="food"
size={moderateScale(20)}
style={{
color: theme.white,
marginLeft: 10,
width: moderateScale(20),
height: moderateScale(20)
}}
/>
<Text style={styles.inputText}>Meal</Text>
</View>
</View>
<View
style={{
flex: 0.7,
alignItems: "flex-start",
flexDirection: "row",
justifyContent: "flex-start",
marginBottom: 10
//zIndex:2000,
}}
>
<View
style={
this.state.showButtons
? styles.autocompleteContainer
: styles.autocompleteContainerBig
}
>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
onFocus={() => this.setState({ showButtons: false })}
hideResults={this.state.showButtons}
ref="meal_input"
style={{
backgroundColor: "#fff",
padding: 10,
borderRadius: 16,
borderColor: theme.primary_color,
borderWidth: 1
}}
listStyle={{ position: "relative" }}
inputContainerStyle={{
paddingHorizontal: 5,
paddingTop: 5,
borderWidth: 0
}}
containerStyle={{}}
data={
meals.length === 1 && comp(query, meals[0].label)
? []
: meals
}
defaultValue={query}
onChangeText={text => this.setState({ query: text })}
placeholder="Enter meal name"
renderItem={({ item }) => (
<TouchableOpacity
onPress={() =>
this.setState({
query: item.label,
choosen__meal: item.value
})
}
>
<Text style={styles.itemText}>{item.label}</Text>
</TouchableOpacity>
)}
/>
</View>
{this.renderButtons()}
</View>
</View>
<View
style={{
flex: 0.15
}}
>
<View
style={{
flex: 0.1,
alignItems: "flex-end",
flexDirection: "row",
justifyContent: "flex-start"
}}
>
<View style={styles.subHeaderView}>
<MaterialCommunityIcons
name="food"
size={moderateScale(20)}
style={{
color: theme.white,
marginLeft: 10,
width: moderateScale(20),
height: moderateScale(20)
}}
/>
<Text style={styles.inputText}>Type of Food Log</Text>
</View>
</View>
<View
style={{
flex: 0.9,
marginTop: 10,
marginLeft: 10,
flexDirection: "row",
justifyContent: "space-around"
}}
>
<RadioForm
radio_props={this.state.type_of_meal_1}
ref="radioForm1" // !! This is the main prop that needs to be there
initial={this.state.initialIndexRadioForm1}
onPress={value => this.handleRadioButton(value, 0)}
/>
<RadioForm
radio_props={this.state.type_of_meal_2}
ref="radioForm2" // !! This is the main prop that needs to be there
initial={this.state.initialIndexRadioForm2}
onPress={value => this.handleRadioButton(value, 1)}
/>
</View>
</View>
<View
style={{
flex: 0.15
}}
>
<View
style={{
flex: 0.1,
flexDirection: "row"
}}
>
<View style={styles.subHeaderView}>
<Feather
name="hash"
size={moderateScale(20)}
style={{
color: theme.white,
marginLeft: 10,
width: moderateScale(20),
height: moderateScale(20)
}}
/>
<Text style={styles.inputText}>Number of servings</Text>
</View>
<View
style={{
flexDirection: "row",
flex: 0.5,
justifyContent: "space-around"
}}
>
<TouchableOpacity
style={styles.plusButton}
onPress={() => this.handleMinusDose()}
>
<Text style={styles.loginButtonText}>-</Text>
</TouchableOpacity>
<View style={styles.inputView_2}>
<TextInput
style={styles.inputText_2}
value={this.state.number_of_servings.toString()}
placeholderTextColor="#003f5c"
keyboardType="numeric"
onChangeText={text =>
this.setState({ number_of_servings: text })
}
maxLength={9}
/>
</View>
<TouchableOpacity
style={styles.plusButton}
onPress={() => this.handlePlusDose()}
>
<Text style={styles.loginButtonText}>+</Text>
</TouchableOpacity>
</View>
</View>
</View>
{/*<View
style={{
flex: 0.2,
justifyContent: "center",
alignItems: "center",
padding: 20,
width: width,
}}
>
<Text
style={{
fontSize: moderateScale(20),
fontWeight: "600",
width: "100%",
textAlign: "center"
}}
>
Insert a Food Log 📖
<Text style={{ color: "#0096dd", fontWeight: "bold" }}>
{this.state.name}
</Text>
</Text>
</View>
<View style={styles.containerScroll}>
<TouchableOpacity
onPress={() => this.openDatepicker()}
style={styles.inputView}
>
<Text style={styles.inputText}>{this.state.day}</Text>
</TouchableOpacity>
<View style={styles.inputView}>
<RNPickerSelect
placeholder={this.state.placeholder_1}
items={this.state.type_of_meal}
onValueChange={value => {
this.setState({
choosen_type_of_meal: value
});
}}
style={{
...pickerSelectStyles,
iconContainer: {
top: 10,
right: 12
}
}}
value={this.state.choosen_type_of_meal}
useNativeAndroidPickerStyle={false}
textInputProps={{ underlineColor: "yellow" }}
Icon={() => {
return (
<Ionicons
name="md-arrow-down"
size={18}
style={styles.icon}
/>
);
}}
/>
</View>
<View style={styles.inputView}>
<TextInput
style={styles.inputText}
placeholder="Number of servings"
maxLength={3}
keyboardType={"numeric"}
onChangeText={text =>
this.setState({ number_of_servings: text })
}
/>
</View>
<View
style={{
flexDirection: "row",
justifyContent: "center",
alignItems: "center"
}}
>
<View style={styles.inputView_2}>
<RNPickerSelect
placeholder={this.state.placeholder_2}
items={this.state.meals}
onValueChange={value => {
this.setState({
choosen__meal: value
});
}}
style={{
...pickerSelectStyles,
iconContainer: {
top: 10,
right: 2
}
}}
value={this.state.choosen__meal}
useNativeAndroidPickerStyle={false}
textInputProps={{ underlineColor: "yellow" }}
Icon={() => {
return (
<Ionicons
name="md-arrow-down"
size={18}
style={styles.icon}
/>
);
}}
/>
</View>
<View
style={{
flex: 0.15,
justifyContent: "flex-start",
alignItems: "center",
marginLeft: moderateScale(20)
}}
>
<TouchableOpacity
style={styles.addButton}
onPress={() => this.setState({ modalFlag: true })}
>
<Text style={styles.loginButtonText}>+</Text>
</TouchableOpacity>
</View>
</View>
</View>*/}
<View
style={{
flex: 0.1,
justifyContent: "flex-start",
alignItems: "center"
}}
>
<TouchableOpacity
style={styles.loginGoogleButton}
onPress={() => this.addFoodLog()}
>
<Text style={styles.loginButtonText}>Confirm</Text>
</TouchableOpacity>
</View>
</ScrollView>
{this.renderModalAddnewMeal()}
<Toast
ref="toast"
style={{ backgroundColor: theme.gray }}
position="bottom"
positionValue={100}
fadeInDuration={500}
fadeOutDuration={500}
/>
</KeyboardAvoidingView>
);
}
}
} |
JavaScript | class PromQLExtension {
constructor() {
this.complete = newCompleteStrategy();
this.lint = newLintStrategy();
this.enableLinter = true;
this.enableCompletion = true;
}
setComplete(conf) {
this.complete = newCompleteStrategy(conf);
return this;
}
getComplete() {
return this.complete;
}
activateCompletion(activate) {
this.enableCompletion = activate;
return this;
}
setLinter(linter) {
this.lint = linter;
return this;
}
getLinter() {
return this.lint;
}
activateLinter(activate) {
this.enableLinter = activate;
return this;
}
asExtension() {
let extension = [promQLLanguage];
if (this.enableCompletion) {
const completion = promQLLanguage.data.of({
autocomplete: (context) => {
return this.complete.promQL(context);
},
});
extension = extension.concat(completion);
}
if (this.enableLinter) {
extension = extension.concat(promQLLinter(this.lint.promQL, this.lint));
}
return extension;
}
} |
JavaScript | class RouteDrawer {
/**
* @param {google.maps.Map} map - The map
* @param {google.maps.InfoWindow} info - The information window
* to display the steps descriptions and other information
*/
constructor(map, info) {
/**
* The real map, once it is created
* @type {google.maps.Map}
* @private
*/
this._map = map;
/**
* The info window, once the map is available
* @type {google.maps.InfoWindow}
* @private
*/
this._info = info;
/**
* The directions renderer, once it is available
* @type {google.maps.DirectionsRenderer}
* @private
*/
this._directionsRenderer = this._newDirectionsRenderer();
/**
* Route markers, if a route is displayed.
* @type {google.maps.Marker[]}
* @private
*/
this._routeMarkers = [];
/**
* The panel which displays the directions and travel types
* @type {?DirectionsPanel}
* @private
*/
this._directionsPanel = null;
/**
* The polyline which highlights the currently highlited step
* @type {?google.maps.Polyline}
* @private
*/
this._highlightedStep = null;
}
/**
* Draws a result obtained from the API in the map.
* @param {google.maps.DirectionsResult} result - The result obtained from the API
*/
draw(result) {
this.clear();
this._directionsRenderer.setMap(this._map);
this._directionsRenderer.setDirections(result);
if(result.routes.length > 0) {
// We pick the first route
this._directionsRenderer.setRouteIndex(0);
this._drawRouteMarkers(result.routes[0]);
this._directionsPanel.showGuideButton();
}
}
/**
* Displays the content to display when no results have been received
*/
displayZeroResults() {
this._directionsPanel.displayZeroResults();
}
/**
* Clears the displayed route from the map
*/
clear() {
this._directionsRenderer.setMap(null);
if(this._directionsPanel) {
this._directionsPanel.clear();
}
this._clearRouteMarkers();
}
/**
* Hides the directions panel (if associated already)
*/
hidePanel() {
if(this._directionsPanel) {
this._directionsPanel.hide();
}
}
/**
* Sets the directions panel and associates the directions render to its
* instructions container.
* @param {DirectionsPanel} panel
*/
setDirectionsPanel(panel) {
this._directionsPanel = panel;
this._directionsRenderer.setPanel(
this._directionsPanel.getInstructionsContainer());
}
/**
* Displays the given travel mode as the selected one.
* It delegates into the homonim method of DirectionsPanel,
* so it has no effect if there is no panel associated.
* @see {DirectionsPanel#selectedTravelMode}
* @param {TravelMode} travelMode
*/
selectedTravelMode(travelMode) {
if(this._directionsPanel) {
this._directionsPanel.selectedTravelMode(travelMode);
}
}
/**
* The currently displayed route, or null if no route is displayed
* @return {?google.maps.DirectionsRoute}
*/
getRoute() {
if(!this._directionsRenderer.getMap())
return null; // When no map assigned, no route is displayed :)
let dirs = this._directionsRenderer.getDirections();
if(dirs) {
return dirs.routes[this._directionsRenderer.getRouteIndex()];
} else {
return null;
}
}
/**
* Highlights the given step, hiding away
* the previous one.
* @param {Number} idx - The index of the step, used to highlight the indications
* @param {google.maps.DirectionsStep} step - The step
*/
highlightStep(idx, step) {
this.clearHighlightedStep();
this._highlightedStep = new google.maps.Polyline({
path: step.path,
geodesic: true,
strokeColor: '#7C0D82',
strokeOpacity: 0.7,
strokeWeight: 6,
zIndex: 2
});
this._highlightedStep.setMap(this._map);
this._map.panTo(step.start_location);
this._map.setZoom(18);
if(this._directionsPanel) {
this._directionsPanel.highlightStep(idx);
}
}
clearHighlightedStep() {
if(this._highlightedStep) {
this._highlightedStep.setMap(null);
this._directionsPanel.clearHighlightedSteps();
this._highlightedStep = null;
}
}
/**
* Draws the markers for the first leg of the given route
* @param {google.maps.DirectionsRoute} route - The route we want to draw
* @private
*/
_drawRouteMarkers(route) {
let leg = route.legs[0];
if(leg.steps.length < 50) {
for (let i = 0; i < leg.steps.length; i++) {
let step = leg.steps[i];
this._createStepMarker(i, step);
}
}
}
/**
* Creates a new step marker
* @param {int} idx - The index of the step (starting in 0)
* @param {google.maps.DirectionsStep} step - the step itself
* @private
*/
_createStepMarker(idx, step) {
let marker = new google.maps.Marker({
map: this._map,
position: step.start_point,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: 'white',
fillOpacity: 1,
strokeColor: '#212121',
strokeWeight: 1
},
zIndex: 10
});
let self = this;
google.maps.event.addListener(marker, 'click', function() {
self._info.setContent(step.instructions);
self._info.open(self._map, marker);
});
// Don't forget to add it to the route markers!
this._routeMarkers.push(marker);
}
/**
* Clears all the markers for the displayed route
* @private
*/
_clearRouteMarkers() {
for(let marker of this._routeMarkers) {
marker.setMap(null);
}
this._routeMarkers = [];
}
/**
* Creates the directions renderer
* @returns {google.maps.DirectionsRenderer}
* @private
*/
_newDirectionsRenderer() {
return new google.maps.DirectionsRenderer({
suppressMarkers: true,
infoWindow: this._info
});
}
} |
JavaScript | class IsResponseFinished extends AsyncObject {
constructor (response) {
super(response)
}
syncCall () {
return (response) => {
return response.finished
}
}
} |
JavaScript | class Connection {
static get instance() {
return _instance;
}
/**
* Create a new Connection
*/
constructor() {
/* eslint consistent-this: "off" */
if ( !_instance ) {
_instance = this;
}
/**
* If browser is offline
* @type {Boolean}
*/
this.offline = false;
this.index = 0;
this._evHandler = new EventHandler(name, []);
this.onlineFn = () => this.onOnline();
this.offlineFn = () => this.onOffline();
}
/**
* Initializes the instance
* @return {Promise<undefined, Error>}
*/
init() {
if ( typeof navigator.onLine !== 'undefined' ) {
window.addEventListener('offline', this.offlineFn);
window.addEventListener('online', this.onlineFn);
}
return Promise.resolve();
}
/**
* Destroys the instance
*/
destroy() {
window.removeEventListener('offline', this.offlineFn);
window.removeEventListener('online', this.onlineFn);
if ( this._evHandler ) {
this._evHandler = this._evHandler.destroy();
}
_instance = null;
}
/**
* Default method to perform a resolve on a VFS File object.
*
* This should return the URL for given resource.
*
* @param {FileMetadata} item The File Object
* @param {Object} [options] Options. These are added to the URL
*
* @return {String}
*/
getVFSPath(item, options) {
options = options || {};
const base = getConfig('Connection.RootURI', '/').replace(/\/?$/, '/');
const defaultDist = getConfig('VFS.Dist');
if ( window.location.protocol === 'file:' ) {
return item ? base + item.path.substr(defaultDist.length) : base;
}
let url = getConfig('Connection.FSURI', '/');
if ( item ) {
url += '/read';
options.path = item.path;
} else {
url += '/upload';
}
if ( options ) {
const q = Object.keys(options).map((k) => {
return k + '=' + encodeURIComponent(options[k]);
});
if ( q.length ) {
url += '?' + q.join('&');
}
}
return url;
}
/**
* Get if connection is Online
*
* @return {Boolean}
*/
isOnline() {
return !this.offline;
}
/**
* Get if connection is Offline
*
* @return {Boolean}
*/
isOffline() {
return this.offline;
}
/**
* Called upon a VFS request completion
*
* It is what gets called 'after' a VFS request has taken place
*
* @param {Mountpoint} mount VFS Module Name
* @param {String} method VFS Method Name
* @param {Object} args VFS Method Arguments
* @param {*} response VFS Response Result
* @param {Process} [appRef] Application reference
* @return {Promise<Boolean, Error>}
*/
onVFSRequestCompleted(mount, method, args, response, appRef) {
return Promise.resolve(true);
}
/**
* When browser goes online
*/
onOnline() {
console.warn('Connection::onOnline()', 'Going online...');
this.offline = false;
if ( this._evHandler ) {
this._evHandler.emit('online');
}
}
/**
* When browser goes offline
*
* @param {Number} reconnecting Amount retries for connection
*/
onOffline(reconnecting) {
console.warn('Connection::onOffline()', 'Going offline...');
if ( !this.offline && this._evHandler ) {
this._evHandler.emit('offline', [reconnecting]);
}
this.offline = true;
}
/**
* Default method to perform a call to the backend (API)
*
* Please use the static request() method externally.
*
* @param {String} method API method name
* @param {Object} args API method arguments
* @param {Object} [options] Options passed on to the connection request method (ex: XHR.ajax)
*
* @return {Promise<Object, Error>}
*/
createRequest(method, args, options) {
args = args || {};
options = options || {};
if ( this.offline ) {
return Promise.reject(new Error('You are currently off-line and cannot perform this operation!'));
}
const {raw, requestOptions} = this.createRequestOptions(method, args);
return new Promise((resolve, reject) => {
axios(appendRequestOptions(requestOptions, options)).then((result) => {
return resolve(raw ? result.data : {error: false, result: result.data});
}).catch((error) => {
reject(new Error(error.message || error));
});
});
}
/**
* Creates default request options
*
* @param {String} method API method name
* @param {Object} args API method arguments
*
* @return {Object}
*/
createRequestOptions(method, args) {
const realMethod = method.replace(/^FS:/, '');
let raw = true;
let requestOptions = {
responseType: 'json',
url: getConfig('Connection.APIURI') + '/' + realMethod,
method: 'POST',
data: args
};
if ( method.match(/^FS:/) ) {
if ( realMethod === 'get' ) {
requestOptions.responseType = 'arraybuffer';
requestOptions.url = args.url || this.getVFSPath({path: args.path});
requestOptions.method = args.method || 'GET';
raw = false;
} else if ( realMethod === 'upload' ) {
requestOptions.url = this.getVFSPath();
} else {
requestOptions.url = getConfig('Connection.FSURI') + '/' + realMethod;
}
}
return {raw, requestOptions};
}
/**
* Subscribe to a event
*
* NOTE: This is only available on WebSocket connections
*
* @param {String} k Event name
* @param {Function} func Callback function
*
* @return {Number}
*
* @see EventHandler#on
*/
subscribe(k, func) {
return this._evHandler.on(k, func, this);
}
/**
* Removes an event subscription
*
* @param {String} k Event name
* @param {Number} [idx] The hook index returned from subscribe()
*
* @return {Boolean}
*
* @see EventHandler#off
*/
unsubscribe(k, idx) {
return this._evHandler.off(k, idx);
}
/*
* This is a wrapper for making a request
*
* @desc This method performs a request to the server
*
* @param {String} m Method name
* @param {Object} a Method arguments
* @param {Object} options Request options
* @return {Promise<Object, Error>}
*/
static request(m, a, options) {
a = a || {};
options = options || {};
if ( options && typeof options !== 'object' ) {
return Promise.reject(new TypeError('request() expects an object as options'));
}
Loader.create('Connection.request');
if ( typeof options.indicator !== 'undefined' ) {
delete options.indicator;
}
return new Promise((resolve, reject) => {
this.instance.createRequest(m, a, options).then((response) => {
if ( response.error ) {
return reject(new Error(response.error));
}
return resolve(response.result);
}).catch(((err) => {
reject(new Error(err));
})).finally(() => {
Loader.destroy('Connection.request');
});
});
}
} |
JavaScript | class ShanghaiDisneyResortMagicKingdom extends DisneyLegacy {
/**
* Create a new ShanghaiDisneyResortMagicKingdom object
*/
constructor(options = {}) {
options.name = options.name || 'Magic Kingdom - Shanghai Disney Resort';
options.timezone = options.timezone || 'Asia/Shanghai';
// set park's location as it's entrance
options.latitude = options.latitude || 31.1433;
options.longitude = options.longitude || 121.6580;
// Disney API configuration for Shanghai Magic Kingdom
options.resortId = options.resortId || 'shdr';
options.parkId = options.parkId || 'desShanghaiDisneyland';
options.resortRegion = options.resortRegion || 'cn';
options.resortCode = options.resortCode || 'shdr';
// API auth is different for Shanghai for some reason...
// override access token POST body
options.accessTokenBody = options.accessTokenBody
|| 'grant_type=assertion&assertion_type=public&client_id=DPRD-SHDR.MOBILE.ANDROID-PROD';
// override API auth URL
options.apiAuthURL = options.apiAuthURL || 'https://authorization.shanghaidisneyresort.com/curoauth/v1/token';
// override api base URL
options.apiBaseURL = options.apiBaseURL || 'https://apim.shanghaidisneyresort.com/';
// inherit from base class
super(options);
}
async FetchFacilitiesData() {
// TODO - perform rolling updates on this data
return this.ParseFacilitiesUpdate(ShanghaiBaseData);
}
async FetchWaitTimes() {
const resp = await this.GetAPIUrl({
url: `${this.GetAPIBase}explorer-service/public/wait-times/${this.GetResortCode};entityType=destination`,
data: {
region: 'cn',
},
});
const facilityData = await this.GetFacilityData(resp.entries.map(x => x.id));
resp.entries.forEach((ride) => {
const cleanID = DisneyUtil.CleanID(ride.id);
if (facilityData[cleanID]) {
let waitTime = -1;
if (ride.waitTime.status === 'Operating') {
waitTime = ride.waitTime.postedWaitMinutes || 0;
} else if (ride.waitTime.status === 'Down') {
waitTime = -2;
} else if (ride.waitTime.status === 'Renewal') {
waitTime = -3;
}
this.UpdateRide(cleanID, {
name: facilityData[cleanID].name,
waitTime,
fastPass: facilityData[cleanID].fastpass,
});
}
});
}
HTTP(options) {
if (!options.headers) options.headers = [];
// always request English names (if possible)
options.headers['accept-language'] = 'en';
// Allows unauthorized HTTPS certificates as ShanghaiDisneyResort uses a self-signed certificate
options.rejectUnauthorized = false;
return super.HTTP(options);
}
} |
JavaScript | class InstanceFactory {
/**
* \@internal
* @param {?} conf
*/
constructor(conf) {
this[conf$] = conf;
}
/**
* @param {?} cfg
* @return {?}
*/
getInstance(cfg) {
cfg = Object.assign({}, this[conf$].config, cfg || {});
/** @type {?} */
const hash = getHash(cfg);
if (!stores[hash]) {
stores[hash] = lf.createInstance(cfg);
}
return stores[hash];
}
} |
JavaScript | class FileRepository extends Repository {
constructor(dataPath, deserializer) {
super();
this.dataPath = dataPath;
this.deserializer = deserializer;
FileRepository._createDirectory(dataPath);
}
saveCollectionAsync(collectionId, serializedCollection) {
return writeFileAsync(this._getFilename(collectionId), serializedCollection);
}
// collectionId is a filename without the extension
loadCollectionAsync(collectionId, bypassCache) {
let filename = this._getFilename(collectionId);
return readFileAsync(filename, 'utf8')
.then((text) => {
return this.deserializer.convertToObjectsAsync(text, this._getSource(collectionId));
})
.then((objs) => {
this.insert(objs);
});
}
deleteCollection(collectionId) {
let filename = this._getFilename(collectionId);
if (fs.existsSync(filename)) {
console.info("Delete: " + filename);
fs.unlinkSync(filename);
}
}
static _createDirectory(filePath) {
let directoryNames = path.normalize(filePath).split(path.sep);
let dataDirectory = "";
for (let dirname of directoryNames) {
dataDirectory = path.join(dataDirectory, dirname);
if (!fs.existsSync(dataDirectory)) {
fs.mkdirSync(dataDirectory);
}
}
}
_getFilename(id) {
let ext = this.deserializer.fileType();
return path.join(this.dataPath, id) + "." + ext;
}
// This method can be overridden in order to indicate where the
// object originally came from in the case where FileRepository
// is being used as a local cache.
_getSource(id) {
return this._getFilename(collectionId);
}
} |
JavaScript | class NumOfSignedIdentifiers {
constructor() {
}
validate({ request = undefined }) {
const si = request.payload;
if ((si !== null || si !== undefined) && si.length > 5) {
throw new AError(ErrorCodes.InvalidInput);
}
}
} |
JavaScript | class Coin{
// theres going to be a wobble effect that makes it look like the coin is moving to make it a little more interesting so it needs a position, a base position and a wobble
constructor(position, basePosition, wobble) {
this.position = position
this.basePosition = basePosition
this.wobble = wobble
}
// needs a getter that return "coin" for drawing later
get type(){
return "coin"
}
// needs a create method that takes in a position
static create(position){
// need to calculate the basePosition by setting it to the given position which is going to be a vector object and using its plus method and adding a new value to it
let basePosition = position.plus(new VectorPosition(0.2, 0.1))
// then create the coin and passing in its position, basePosition and "Math.random() * Math.PI * 2"
// math code is for making coins move in a circle at different intervals since if you didn't have it they would circle at the same exact time
return new Coin(position, basePosition, Math.random() * Math.PI * 2)
}
} |
JavaScript | class Controller extends ParentCtrl {
/**
* Constructor.
* @param {!angular.Scope} $scope The Angular scope.
* @param {!angular.JQLite} $element The root DOM element.
* @ngInject
*/
constructor($scope, $element) {
super();
/**
* The Angular scope.
* @type {?angular.Scope}
* @private
*/
this.scope_ = $scope;
/**
* The root DOM element.
* @type {?angular.JQLite}
* @private
*/
this.element_ = $element;
/**
* A public property on the class.
* @type {string}
*/
this.prop1 = 'Hello';
/**
* A protected property on the class.
* @type {string}
* @protected
*/
this.prop2 = 'World';
/**
* A private property on the class.
* @type {string}
* @private
*/
this.prop3_ = '!!!';
/**
* Property exposed for Angular.
* @type {string}
*/
this['exposedProp1'] = 'foo';
/**
* Property exposed for Angular.
* @type {string}
*/
this['exposedProp2'] = 'bar';
$scope.$on('someEvent', Controller.staticFn_);
$scope.$on('$destroy', this.destroy_.bind(this));
}
/**
* Clean up.
* @private
*/
destroy_() {
os.alertManager.unlisten(os.alert.EventType.ALERT, this.registerAlert_, false, this);
this.scope_ = null;
}
/**
* A function on the class.
* @param {string} arg1 First arg.
* @param {number=} opt_arg2 Optional second arg.
* @return {boolean}
*/
memberFn(arg1, opt_arg2) {
if (arg1 === Controller.CONSTANT) {
goog.log.fine(Controller.LOGGER_, 'Some message');
return true;
}
return false;
}
/**
* @inheritDoc
*/
overrideFn(arg1, opt_arg2) {
return super.overrideFn(arg1);
}
/**
* @inheritDoc
*/
oldOverrideFn(arg1, opt_arg2) {
return super.oldOverrideFn(arg1);
}
/**
* @inheritDoc
*/
oldOverrideDifferentClass(arg1, opt_arg2) {
// can't convert due to difference in class
return os.ns.AnotherClass.superClass_.oldOverrideDifferentClass.call(this, arg1);
}
/**
* @param {angular.Scope.Event} evt The angular event
* @param {string} type The event type to send
* @private
*/
static staticFn_(evt, type) {
os.dispatcher.dispatchEvent(type);
}
} |
JavaScript | class Prefix {
constructor(prefix, namespace) {
this.prefix = prefix;
this.namespace = namespace;
}
// return the prefix
getPrefix() {
return this.prefix;
}
// return the namespace associated with the prefix
getNamespace() {
return this.namespace;
}
} |
JavaScript | class PrefixManager {
constructor(prefixes) {
this.defaultPrefix = 'endefault';
this.defaultNamespace = 'http://ont.enapso.com/default#';
this.prefixes = [];
for (let item of prefixes) {
let prefix = new Prefix(item.prefix, item.iri);
this.prefixes.push(prefix);
}
}
getPrefixes() {
return this.prefixes;
}
getPrefixesForConnector() {
let prefixes = [];
for (let item of this.prefixes) {
prefixes.push({
prefix: item.getPrefix(),
iri: item.getNamespace()
});
}
return prefixes;
}
getPrefixesInSPARQLFormat() {
let prefixes = '';
for (let item of this.prefixes) {
prefixes = `${prefixes}
PREFIX ${item.getPrefix()}: <${item.getNamespace()}>`;
}
return prefixes;
}
// returns the prefix of a certain namespace, or null if the namespace cannot be found
getPrefixByNamespace(namespace) {
for (let item of this.prefixes) {
if (item.getNamespace() === namespace) {
return item.getPrefix();
}
}
return null;
}
// returns the namespace of a certain prefix, or null if the prefix cannot be found
getNamespaceByPrefix(prefix) {
for (let item of this.prefixes) {
if (item.getPrefix() === prefix) {
return item.getNamespace();
}
}
return null;
}
// sets the default prefix and the default namespace automatically with it
setDefaultPrefix(prefix) {
this.defaultPrefix = prefix;
this.defaultNamespace = this.getNamespaceByPrefix(prefix);
}
// sets the default namespace and the default prefix automatically with it
setDefaultNamespace(namespace) {
this.defaultNamespace = namespace;
this.defaultPrefix = this.getPrefixByNamespace(namespace);
}
// returns the default prefix
getDefaultPrefix() {
return this.defaultPrefix;
}
// returns the default namespace
getDefaultNamespace() {
return this.defaultNamespace;
}
// returns true if the input value is already a full IRI for SPARQL, otherwise false
isSparqlIRI(input) {
// todo: maybe better check with a regExp
return input.startsWith('<') && input.endsWith('>');
}
// returns true if the input value is already a full IRI for SPARQL, otherwise false
isURI(input) {
// todo: maybe better check with a regExp
return input.startsWith('http://') || input.startsWith('https://');
}
// returns true if the input value is already a prefixed IRI for SPARQL, otherwise false
isPrefixedIRI(input) {
// todo: maybe better check with a regExp
return !this.isURI(input) && input.indexOf(':') >= 0;
}
// splits a given prefixed IRI into prefix and namespace
splitPrefixedName(input) {
let parts = input.split(':', 2);
return {
prefix: parts[0],
identifier: parts[1]
};
}
// converts a prefixed resource identifier to a full IRI
// the IRI does not need to be part of the PrefixManager
prefixedNameToIRI(input) {
if (this.isPrefixedIRI(input)) {
} else {
throw 'IRI is not prefixed';
}
}
// converts a full IRI into a prefixed resource identifier
fullToPrefixedIRI(input) {
try {
let namespace = this.getIRI(input);
let prefixFound = false;
for (let item of this.prefixes) {
let ns = item.getNamespace();
if (namespace.startsWith(ns)) {
prefixFound = true;
return item.getPrefix() + ':' + namespace.substr(ns.length);
}
}
// if (!prefixFound) {
// // console.log('Hello');
// let prefix = this.randomPrefixToIRI();
// let iri = namespace.split('#');
// let ontoIRI = `${iri[0]}#`;
// this.prefixes.push(new Prefix(prefix, ontoIRI));
// let className = iri[1];
// return prefix + ':' + className;
// // this.fullToPrefixedIRI(input);
// //console.log(pre);
// }
// else return unchanged
return input;
} catch (e) {
return e;
}
}
// randomPrefixToIRI() {
// return randomstring.generate({
// length: 7,
// charset: 'alphabetic'
// });
// }
// returns the plain (i.e. non-prefixed, non-sparql'd) IRI of an input
getIRI(input) {
input = input.trim();
if (this.isSparqlIRI(input)) {
// cut off trailing < and ending >
return input.substr(1, input.length - 2);
} else if (this.isURI(input)) {
return input;
} else if (this.isPrefixedIRI(input)) {
let parts = this.splitPrefixedName(input);
let namespace = this.getNamespaceByPrefix(parts.prefix);
return namespace + parts.identifier;
}
return this.defaultNamespace + input;
}
// returns the IRI in SPARQL syntax,
// i.e. with starting < and trailing >
getSparqlIRI(input) {
// if the input is already a SPARQL formatted IRI,
// return it "as is"
if (this.isSparqlIRI(input)) {
return input;
}
// otherwise generate or get the IRI and
// make it a SPARQL formatted IRI
return '<' + input + '>';
}
} |
JavaScript | class Notifications {
/**
* @param {Object} utils - general utilities passed from main HERETracking
* @param {function(varArgs: ...string): string} utils.url - Generate the URL for HERE Tracking
* @param {function(options: Object, required: Array): Promise} utils.validate - Check the supplied parameters
* @param {function(url: string, options: Object): Object} utils.fetch - Wrap the standard Fetch API
* (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to provide error handling
*/
constructor(utils) {
/**
* Generate the URL for HERE Tracking
* @type {function(varArgs: ...string): string} generate URL for HERE Tracking
*/
this.url = utils.url;
/**
* Check the supplied parameters
* @type {function(options: Object, required: Array): Promise}
*/
this.validate = utils.validate;
/**
* Wrap the standard Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
* to provide error handling
* @type {function(url: string, options: Object): Object}
*/
this.fetch = utils.fetch;
}
/**
* Register a notifications channel
* /notifications/v2/register
*
* @param {string} type - Type of channel, possible value: 'webhook'
* @param {Object} value - Channel details, URL for 'webhook'
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object} Success message
* @throws {Error} When an HTTP error has occurred
*/
register(type, value, { token }) {
return this.validate({ type, token }, ['type', 'value', 'token'])
.then(() => {
const channel = {
type
};
if (type !== 'webhook') {
return Promise.reject(new Error('Unsupported notification type'));
}
channel.url = value;
const url = this.url('notifications', 'v2', 'register');
return this.fetch(url, {
method: 'post',
credentials: 'include',
headers: new Headers({
'Authorization': `Bearer ${token}`
}),
body: JSON.stringify(channel)
});
});
}
/**
* Retrieve list of registered notification channels
* /notifications/v2/registrations
*
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object} List of notification channels
* @throws {Error} When an HTTP error has occurred
*/
list({ token }) {
return this.validate({ token }, ['token'])
.then(() => this.fetch(this.url('notifications', 'v2', 'registrations'), {
credentials: 'include',
headers: new Headers({
'Authorization': `Bearer ${token}`
})
}));
}
/**
* Remove a notification channel
* /notifications/v2/registration/{channelName}
*
* @param {Object} channelName - ID of the channel
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @throws {Error} When an HTTP error has occurred
*/
delete(channelName, { token }) {
return this.validate({ channelName }, ['channelName'])
.then(() => this.fetch(this.url('notifications', 'v2', 'registration', channelName), {
method: 'delete',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
})
}));
}
} |
JavaScript | class AppNew extends Component {
componentDidMount() {
this.props.getUserInfo();
}
render() {
return (
<div>
<Header />
<Suspense fallback={<h1>...Loading</h1>}>
<Switch>
<PublicRoute exact path={routes.home} component={HomeView} />
<PublicRoute
path={routes.login}
restricted
redirectTo={routes.contacts}
component={LoginView}
/>
<PublicRoute
path={routes.register}
restricted
redirectTo={routes.contacts}
component={RegisterView}
/>
<PrivateRoute
path={routes.contacts}
redirectTo={routes.login}
component={Phonebook}
/>
{/* <Route component={NotFoundView} /> */}
</Switch>
</Suspense>
</div>
);
}
} |
JavaScript | class App extends React.Component {
constructor(props) {
super(props);
this.installApp = this.installApp.bind(this);
this.selectRow = this.selectRow.bind(this);
this.showQRCode = this.showQRCode.bind(this);
const device = new DeviceDetector().parse(navigator.userAgent);
this.state = {
isLoading: true,
url: "config.json",
device: device,
list: [],
current: null,
isInstalling: false,
headerTitle: "很高兴邀请您安装Superbuy App,测试并反馈问题,便于我们及时解决您遇到的问题,十分谢谢!Thanks♪(・ω・)ノ"
};
this.ref = React.createRef()
}
componentDidMount () {
const { url, device, headerTitle } = this.state;
fetch(url)
.then(res => res.json())
.then(json => {
const title = !json["title"] ? headerTitle : json["title"]
const ipaList = json["ipaList"] || []
const apkList = json["apkList"] || []
const appList = json["appList"] || []
let list = []
if (device.os.name === 'iOS') {
list = [...ipaList];
} else if (device.os.name === 'Android') {
list = [...apkList];
} else if (device.device.type === 'desktop') { // pc
list = [...ipaList, ...apkList, ...appList]
}
list = [...list].sort((a, b) => a.time < b.time ? 1 : -1)
this.setState({isLoading: false, headerTitle: title, list: [...list], current: list.length ? list[0] : null})
});
this.showQRCode();
}
showQRCode() {
const canvas = this.ref.current;
if (canvas) {
QRCode.toCanvas({
canvas: canvas,
content: window.location.href,
width: 260,
logo: {
src: 'icon.png',
radius: 8
}
})
}
}
installApp () {
const { current, device } = this.state;
if (current) {
if (device.os.name === 'iOS') {
window.location.href = "itms-services://?action=download-manifest&url=" + current.domain + current.path + "manifest.plist";
setTimeout(() => {
this.setState({isInstalling: true})
}, 1000);
} else {
window.location.href = current.domain + current.path + current.name;
}
}
console.log(this.refs.qrcode)
}
selectRow (value) {
this.setState({current: value})
}
render() {
const { isLoading, list, current, isInstalling, headerTitle, device } = this.state;
const obj = current ? current : {version: "", build: 0, size: 0, time: 0, desc: "", name: "*.ipa"}
const iconClassName = obj.name.indexOf(".apk") !== -1 ? "fa fa-android" : "fa fa-apple";
const appleSvg = <svg t="1594871600015" className="icon"
viewBox="0 0 1024 1024" version="1.1"
xmlns="http://www.w3.org/2000/svg" p-id="3036"
width="20" height="20">
<path
d="M737.007 537.364c-1.092-104.007 84.833-153.888 88.595-156.316-48.181-70.512-123.305-80.221-150.126-81.435-63.958-6.432-124.761 37.622-157.165 37.622-32.404 0-82.405-36.652-135.441-35.681-69.663 1.092-133.863 40.535-169.787 102.915-72.453 125.732-18.569 311.903 52.065 413.727 34.467 49.881 75.609 105.828 129.616 103.887 51.943-2.063 71.604-33.618 134.47-33.618s80.464 33.618 135.563 32.646c55.948-1.092 91.387-50.851 125.611-100.852 39.564-57.89 55.948-113.959 56.798-116.63-1.214-0.729-109.105-41.991-110.197-166.267zM633.605 232.258c28.641-34.71 47.938-83.012 42.72-131.072-41.264 1.699-91.265 27.428-120.878 62.138-26.457 30.826-49.881 79.978-43.569 127.067 45.997 3.641 93.085-23.423 121.727-58.132z"
fill="" p-id="3037">
</path>
</svg>;
const androidSvg = <svg t="1594871933417" className="icon"
viewBox="0 0 1024 1024" version="1.1"
xmlns="http://www.w3.org/2000/svg" p-id="4595"
width="20" height="20">
<path
d="M391.405714 276.004571a22.308571 22.308571 0 0 0 0-44.544c-11.995429 0-21.723429 10.276571-21.723428 22.272s9.728 22.272 21.723428 22.272z m241.152 0c11.995429 0 21.723429-10.276571 21.723429-22.272s-9.728-22.272-21.723429-22.272a22.308571 22.308571 0 0 0 0 44.544zM168.539429 381.147429a58.514286 58.514286 0 0 1 58.294857 58.294857v245.723428c0 32.585143-25.709714 58.843429-58.294857 58.843429S109.696 717.714286 109.696 685.165714v-245.723428c0-32 26.294857-58.294857 58.843429-58.294857z m605.732571 10.861714v380.562286c0 34.852571-28.013714 62.866286-62.281143 62.866285h-42.861714v129.718857c0 32.585143-26.294857 58.843429-58.843429 58.843429s-58.843429-26.294857-58.843428-58.843429v-129.718857H472.594286v129.718857c0 32.585143-26.294857 58.843429-58.843429 58.843429a58.660571 58.660571 0 0 1-58.294857-58.843429l-0.585143-129.718857H312.594286a62.683429 62.683429 0 0 1-62.866286-62.866285V392.009143h524.580571z m-132.571429-231.424c80.018286 41.142857 134.290286 119.990857 134.290286 210.870857H247.424c0-90.843429 54.272-169.728 134.838857-210.870857L341.705143 85.723429a8.338286 8.338286 0 0 1 2.852571-11.446858c3.986286-1.718857 9.142857-0.585143 11.446857 3.437715L397.147429 153.161143c34.852571-15.433143 73.728-23.990857 114.870857-23.990857s80.018286 8.557714 114.870857 23.990857l41.142857-75.446857c2.304-3.986286 7.424-5.156571 11.446857-3.437715a8.338286 8.338286 0 0 1 2.852572 11.446858zM914.267429 439.442286v245.723428c0 32.585143-26.294857 58.843429-58.843429 58.843429a58.660571 58.660571 0 0 1-58.294857-58.843429v-245.723428a58.148571 58.148571 0 0 1 58.294857-58.294857c32.585143 0 58.843429 25.709714 58.843429 58.294857z"
fill="#000000" p-id="4596">
</path>
</svg>
return (
<LoadingOverlay active={isLoading} spinner text='Loading...'>
<div className="App">
<p>{headerTitle}</p>
<img src={"icon.png"} className="App-icon" alt={""}/>
<p className="App-detail-text">
版本:{obj.version}
(build {obj.build})
大小:{(obj.size/1024/1024).toFixed(2)} MB
更新时间:{format('yyyy-MM-dd hh:mm:ss', new Date(obj.time * 1000))}
</p>
<div className="App-update-desc">{obj.desc}</div>
{
!current ? <p>Sorry,未找到任何软件包!</p> :
<button id="install-app" className="App-install-button" onClick={this.installApp}>
<i className={iconClassName} aria-hidden="true">
<span className="App-install-button-text"> {isInstalling ? "正在安装..." : "安装App"}</span>
</i>
</button>
}
{
device.os.name === 'iOS' || true ? <a href="https://www.pgyer.com/tools/udid" className="App-help">安装遇到问题?</a> : null
}
<canvas ref={this.ref} />
<div className="App-line"> </div>
<p>历史版本</p>
<div className="App-history-version">
{
list.map((value, index) => {
const className = index % 2 === 0 ? "App-box-0" : "App-box-1";
const svg = value.name.indexOf(".apk") !== -1 ? androidSvg : appleSvg;
return (
<div key={index} className={className} onClick={()=>{this.selectRow(value)}}>
{device.device.type === 'desktop' && <i>{svg}</i>}
{device.device.type === 'desktop' && <i style={{ marginRight: "10%" }}> {value.name}</i>}
<p style={{marginRight: "10%"}}>{value.version} (build {value.build} )</p>
<p>{format('yyyy-MM-dd hh:mm:ss', new Date(value.time * 1000))}</p>
</div>
)
})
}
</div>
</div>
</LoadingOverlay>
);
}
} |
JavaScript | class Documenter {
/**
* Documentation theme paths.
*
* @type {object}
*/
get theme() {
return {
output: `${_paths.default.documentationTheme}/build`,
images: `${_paths.default.documentationTheme}/sources/images`,
scripts: `${_paths.default.documentationTheme}/sources/scripts`,
styles: `${_paths.default.documentationTheme}/sources/styles`
};
}
/**
* Copy documentation common assets to output directory.
*
* @param {string} [destination={@link PackagePaths}.documentation] - Path to the generated documentation.
*/
generateCommonAssets(destination = _paths.default.package.documentation) {
_terminal.terminal.print('Copy documentation common assets').spacer();
const commonPath = `${destination}/assets__`;
_fss.default.remove(destination);
_fss.default.ensureDir(commonPath);
_fss.default.copy(`${_paths.default.documentationTheme}/build`, commonPath);
}
/**
* Build API documentation via JSDoc.
*
* @param {object} [options] - Options.
* @param {string} [options.root={@link PackagePaths}.root] - Root to the package.
* @param {string} [options.source={@link PackagePaths}.sources] - Path to source code.
* @param {string} [options.destination={@link PackagePaths}.documentation] - Path to the generated documentation.
* @param {number} [options.depth=1] - Directory depth relative to the documentation root.
*/
generateAPI({
root = _paths.default.package.root,
source = _paths.default.package.sources,
destination = _paths.default.package.documentation,
depth = 1
} = {}) {
_terminal.terminal.print(`Build API documentation for ${_util.default.relativizePath(source)}`).spacer();
const output = `${destination}/api`;
_fss.default.remove(output);
_fss.default.ensureDir(output);
const options = {
root,
source,
destination: output,
depth
};
const jsdocBin = `${(0, _resolvePkg.default)('jsdoc', {
cwd: __dirname
})}/jsdoc.js`;
_terminal.terminal.process.run(`node ${jsdocBin} --configure ${_paths.default.documentationTheme}/jsdoc/config.js`, {
environment: {
[_environment.default.JSDOC_CLI_KEY]: JSON.stringify(options)
}
});
_terminal.terminal.spacer(2);
}
/**
* Build text documentation.
*
* @param {object} [options] - Options.
* @param {string} [options.source={@link PackagePaths}.sources] - Path to source code.
* @param {string} [options.destination={@link PackagePaths}.documentation] - Path to the generated documentation.
*/
generateText({
source = _paths.default.package.sources,
destination = _paths.default.package.documentation
} = {}) {
_terminal.terminal.print(`Build text documentation for ${_util.default.relativizePath(source)}`).spacer(); // Temporarily redirect main url to API docs
_fss.default.copy(`${_paths.default.documentationTheme}/redirect/index.html`, `${destination}/index.html`);
}
} |
JavaScript | class TxtRotate {
static animateLine1 = true;
static animateLine2 = false;
/**
* Constructor of a TxtRotate object, and begins typewriter animation
* @param {element} el The HTML element that will show typewriter animation
* @param {array} toRotate The strings for the typewriter to rotate through
* @param {number} period The period of a tick when displaying full string (in milliseconds)
* @param {number} id The unique id of a 'txt-rotate' class object
*/
constructor(el, toRotate, period, id) {
this.toRotate = toRotate;
this.el = el;
this.period = period;
this.id = id;
this.txt = "";
this.loopNum = 0;
this.tick();
this.isDeleting = false;
}
/**
* Performs a single insertion or deletion of a character
*/
tick() {
// Gets the current string that will be displayed
var i = this.loopNum % this.toRotate.length;
var fullTxt = this.toRotate[i];
// Updates the current string based on whether characters are being inserted or deleted
if (this.id == 1 && TxtRotate.animateLine1 || this.id == 2 && TxtRotate.animateLine2) {
if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';
}
var self = this;
// Gives randomness in speed of each intermediate tick
var delta = 150 - Math.random() * 100;
// Ensures deleting tick speeds are on average twice the speed of insertion ticks
if (this.isDeleting) { delta /= 2; }
// Uses default tick speeds when the string is complete of when the string is empty
if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
if (this.id == 1) {
TxtRotate.animateLine1 = false;
TxtRotate.animateLine2 = true;
}
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
this.loopNum++;
delta = 500;
if (this.id == 2) {
TxtRotate.animateLine1 = true;
TxtRotate.animateLine2 = false;
}
}
// Sets the timeout for each tick
setTimeout(function() {
self.tick();
}, delta);
}
} |
JavaScript | class GraphComponents {
static getCitiesEdgeList () {
return [
[0, 1, 2230],
[0, 2, 1631],
[0, 3, 1566],
[0, 4, 1346],
[0, 5, 1352],
[0, 6, 1204],
[0, 7, 2895],
[0, 8, 2513],
[0, 9, 2340],
[0, 10, 2344],
[0, 11, 2063],
[0, 12, 3423],
[1, 2, 845],
[1, 3, 707],
[1, 4, 1001],
[1, 5, 947],
[1, 6, 1484],
[1, 7, 886],
[1, 8, 5085],
[1, 9, 2972],
[1, 10, 4151],
[1, 11, 3432],
[1, 12, 495],
[2, 3, 627],
[2, 4, 773],
[2, 5, 424],
[2, 6, 644],
[2, 7, 1220],
[2, 8, 4720],
[2, 9, 2608],
[2, 10, 3787],
[2, 11, 3068],
[2, 12, 1585],
[3, 4, 302],
[3, 5, 341],
[3, 6, 1027],
[3, 7, 393],
[3, 8, 3991],
[3, 9, 1843],
[3, 10, 3023],
[3, 11, 2303],
[3, 12, 899],
[4, 5, 368],
[4, 6, 916],
[4, 7, 865],
[4, 8, 976],
[4, 9, 1348],
[4, 10, 2567],
[4, 11, 1847],
[4, 12, 3540],
[5, 6, 702],
[5, 7, 916],
[5, 8, 4048],
[5, 9, 1954],
[5, 10, 3133],
[5, 11, 2413],
[5, 12, 1444],
[6, 7, 2021],
[6, 8, 4451],
[6, 9, 2620],
[6, 10, 3772],
[6, 11, 3052],
[6, 12, 2549],
[7, 8, 4172],
[7, 9, 2030],
[7, 10, 3238],
[7, 11, 2519],
[7, 12, 542],
[8, 9, 2319],
[8, 10, 973],
[8, 11, 1743],
[8, 12, 4557],
[9, 10, 1327],
[9, 11, 572],
[9, 12, 2269],
[10, 11, 758],
[10, 12, 3527],
[11, 12, 2850],
/**
* NOTE on the below edge:
* RoutingMachine.js > fetchPath() will create markers
* based on sourceNodes so we must provide every node we want
* a marker for as the source node in an edge (i.e. the first
* node in the array).
*
* Each array follows the pattern: [sourceNode, destNode, edgeWeight]
*
* TSPutils.js > isEdgeSelected() will make sure an edge which
* has the same source and destination nodes will not be pushed
* into the selected-edges edge list to solve
*/
[12, 12, 0]
]
}
static getCitiesLatLong () {
return {
Albuquerque: [35.106766, -106.629181],
Boston: [42.361145, -71.057083],
'Charlotte, NC': [35.227085, -80.843124],
Detroit: [42.331429, -83.045753],
'Evanston, IL': [42.045597, -87.688568],
'Frankfort, Kentucky': [37.839333, -84.270020],
'Gulfport, Mississippi': [30.367420, -89.092819],
'Toronto, ON, CA': [43.653225, -79.383186],
'Vancouver, BC, CA': [49.263569, -123.138573],
'Winnipeg, MB, CA': [49.900501, -97.139313],
'Calgary, AB, CA': [51.047310, -114.057968],
'Regina, SK, CA': [50.451191, -104.616623],
'Montréal, QC, CA': [45.508888, -73.561668]
}
}
static getCitiesIdMapping () {
return {
0: 'Albuquerque',
1: 'Boston',
2: 'Charlotte, NC',
3: 'Detroit',
4: 'Evanston, IL',
5: 'Frankfort, Kentucky',
6: 'Gulfport, Mississippi',
7: 'Toronto, ON, CA',
8: 'Vancouver, BC, CA',
9: 'Winnipeg, MB, CA',
10: 'Calgary, AB, CA',
11: 'Regina, SK, CA',
12: 'Montréal, QC, CA'
}
}
static getCitiesNameMapping () {
return {
Albuquerque: 0,
Boston: 1,
'Charlotte, NC': 2,
Detroit: 3,
'Evanston, IL': 4,
'Frankfort, Kentucky': 5,
'Gulfport, Mississippi': 6,
'Toronto, ON, CA': 7,
'Vancouver, BC, CA': 8,
'Winnipeg, MB, CA': 9,
'Calgary, AB, CA': 10,
'Regina, SK, CA': 11,
'Montréal, QC, CA': 12
}
}
static getVanEdgeList () {
return [
[0, 1, 16.5],
[0, 2, 7.3],
[0, 3, 7.3],
[0, 4, 7.9],
[0, 5, 11.3],
[0, 6, 24.7],
[0, 7, 14.9],
[0, 8, 9.8],
[0, 9, 11.1],
[0, 10, 10.5],
[0, 11, 21.3],
[0, 12, 21.5],
[1, 2, 9.2],
[1, 3, 9.1],
[1, 4, 10.6],
[1, 5, 7.3],
[1, 6, 8],
[1, 7, 4.4],
[1, 8, 17.5],
[1, 9, 5.2],
[1, 10, 8.8],
[1, 11, 5.6],
[1, 12, 8.4],
[2, 3, 1],
[2, 4, 1.2],
[2, 5, 9.4],
[2, 6, 17.1],
[2, 7, 10.1],
[2, 8, 6.1],
[2, 9, 3.8],
[2, 10, 6.9],
[2, 11, 14.7],
[2, 12, 17.3],
[3, 4, 1.9],
[3, 5, 7.2],
[3, 6, 19.2],
[3, 7, 8.8],
[3, 8, 4.9],
[3, 9, 3.6],
[3, 10, 6.1],
[3, 11, 14.2],
[3, 12, 15.9],
[4, 5, 8.9],
[4, 6, 20.8],
[4, 7, 11.7],
[4, 8, 7.7],
[4, 9, 5.1],
[4, 10, 7.7],
[4, 11, 19.4],
[4, 12, 21.8],
[5, 6, 13.3],
[5, 7, 5.6],
[5, 8, 8.3],
[5, 9, 5],
[5, 10, 1.8],
[5, 11, 11.2],
[5, 12, 10.8],
[6, 7, 8.9],
[6, 8, 29.9],
[6, 9, 16.2],
[6, 10, 15.7],
[6, 11, 4.3],
[6, 12, 4],
[7, 8, 15.5],
[7, 9, 6],
[7, 10, 7.2],
[7, 11, 6.4],
[7, 12, 7.3],
[8, 9, 5.9],
[8, 10, 4.4],
[8, 11, 16.1],
[8, 12, 16.1],
[9, 10, 4.1],
[9, 11, 12.9],
[9, 12, 13],
[10, 11, 13.4],
[10, 12, 13.4],
[11, 12, 4.4],
/**
* NOTE on the below edge:
* RoutingMachine.js > fetchPath() will create markers
* based on sourceNodes so we must provide every node we want
* a marker for as the source node in an edge (i.e. the first
* node in the array).
*
* Each array follows the pattern: [sourceNode, destNode, edgeWeight]
*
* TSPutils.js > isEdgeSelected() will make sure an edge which
* has the same source and destination nodes will not be pushed
* into the selected-edges edge list to solve
*/
[12, 12, 0]
]
}
static getVanLatLong () {
return {
'UBC campus': [49.2666656, -123.249999],
'SFU campus': [49.2768, -122.9180],
'Canada Place': [49.288644, -123.110708],
'Rogers Arena': [49.2733, -123.1053],
'Stanley park': [49.299999, -123.139999],
'Metropolise at Metrotown': [49.2274, -122.9999],
'Lafarge lake': [49.2863, -122.7890],
'Burnaby lake': [49.2420, -122.9441],
'Queen Elizabeth park': [49.2418, -123.1126],
'Playland at PNE': [49.282743, -123.036773],
'Burnaby Central Park': [49.2277, -123.0180],
'Mundy Park': [49.2568, -122.8255],
'Colony Farm Park': [49.229848, -122.807044]
}
}
static getVanIdMapping () {
return {
0: 'UBC campus',
1: 'SFU campus',
2: 'Canada Place',
3: 'Rogers Arena',
4: 'Stanley park',
5: 'Metropolise at Metrotown',
6: 'Lafarge lake',
7: 'Burnaby lake',
8: 'Queen Elizabeth park',
9: 'Playland at PNE',
10: 'Burnaby Central Park',
11: 'Mundy Park',
12: 'Colony Farm Park'
}
}
static getVanNameMapping () {
return {
'UBC campus': 0,
'SFU campus': 1,
'Canada Place': 2,
'Rogers Arena': 3,
'Stanley park': 4,
'Metropolise at Metrotown': 5,
'Lafarge lake': 6,
'Burnaby lake': 7,
'Queen Elizabeth park': 8,
'Playland at PNE': 9,
'Burnaby Central Park': 10,
'Mundy Park': 11,
'Colony Farm Park': 12
}
}
static getFlowersEdgeList () {
return [
[0, 1, 2.23606797749979],
[0, 2, 6.4031242374328485],
[0, 3, 13.601470508735444],
[0, 4, 9.055385138137417],
[0, 5, 4.123105625617661],
[0, 6, 4.743416490252569],
[0, 7, 10.259142264341596],
[0, 8, 8.558621384311845],
[0, 9, 10.594810050208546],
[0, 10, 10.124228365658293],
[0, 11, 2.0],
[0, 12, 6.576473218982953],
[1, 2, 4.47213595499958],
[1, 3, 11.661903789690601],
[1, 4, 8.06225774829855],
[1, 5, 3.1622776601683795],
[1, 6, 2.5495097567963922],
[1, 7, 8.139410298049853],
[1, 8, 8.077747210701755],
[1, 9, 9.12414379544733],
[1, 10, 7.905694150420948],
[1, 11, 2.23606797749979],
[1, 12, 5.5901699437494745],
[2, 3, 7.211102550927978],
[2, 4, 5.0],
[2, 5, 3.1622776601683795],
[2, 6, 3.5355339059327378],
[2, 7, 4.031128874149275],
[2, 8, 6.103277807866851],
[2, 9, 5.024937810560445],
[2, 10, 4.527692569068709],
[2, 11, 5.0],
[2, 12, 3.3541019662496847],
[3, 4, 7.280109889280518],
[3, 5, 9.899494936611665],
[3, 6, 10.124228365658293],
[3, 7, 4.031128874149275],
[3, 8, 9.340770846134703],
[3, 9, 4.6097722286464435],
[3, 10, 5.522680508593631],
[3, 11, 12.041594578792296],
[3, 12, 8.32165848854662],
[4, 5, 5.0],
[4, 6, 8.276472678623424],
[4, 7, 6.800735254367722],
[4, 8, 2.0615528128088303],
[4, 9, 2.692582403567252],
[4, 10, 8.276472678623424],
[4, 11, 7.0710678118654755],
[4, 12, 2.5],
[5, 6, 4.301162633521313],
[5, 7, 7.158910531638177],
[5, 8, 4.924428900898052],
[5, 9, 6.5],
[5, 10, 7.648529270389178],
[5, 11, 2.23606797749979],
[5, 12, 2.5],
[6, 7, 6.264982043070834],
[6, 8, 8.902246907382429],
[6, 9, 8.558621384311845],
[6, 10, 5.656854249492381],
[6, 11, 4.527692569068709],
[6, 12, 6.103277807866851],
[7, 8, 8.631338250816034],
[7, 9, 5.0],
[7, 10, 1.8027756377319946],
[7, 11, 9.013878188659973],
[7, 12, 6.519202405202649],
[8, 9, 4.743416490252569],
[8, 10, 9.962429422585638],
[8, 11, 6.576473218982953],
[8, 12, 2.8284271247461903],
[9, 10, 6.726812023536855],
[9, 11, 8.73212459828649],
[9, 12, 4.301162633521313],
[10, 11, 9.192388155425117],
[10, 12, 7.566372975210778],
[11, 12, 4.6097722286464435]
]
}
} |
JavaScript | class TD__P extends Model {
static reducer(action, TD__P) {
const { type, payload } = action;
switch(type) {
case ADD_PLANTER_TO_TALLY_DATE:
TD__P.create({id: (new Date).getTime(), planter: payload.listed_element_id, tally_date: payload.related_element_id});
break;
case REMOVE_PLANTER_FROM_TALLY_DATE:
TD__P.all().filter({tally_date: payload.related_element_id}).filter({planter: payload.listed_element_id}).delete();
break;
}
}
} |
JavaScript | class Certificate {
/**
* Create a Certificate.
* @member {string} [id] Gets the id of the resource.
* @member {string} [name] Gets the name of the certificate.
* @member {string} [thumbprint] Gets the thumbprint of the certificate.
* @member {date} [expiryTime] Gets the expiry time of the certificate.
* @member {boolean} [isExportable] Gets the is exportable flag of the
* certificate.
* @member {date} [creationTime] Gets the creation time.
* @member {date} [lastModifiedTime] Gets the last modified time.
* @member {string} [description] Gets or sets the description.
*/
constructor() {
}
/**
* Defines the metadata of Certificate
*
* @returns {object} metadata of Certificate
*
*/
mapper() {
return {
required: false,
serializedName: 'Certificate',
type: {
name: 'Composite',
className: 'Certificate',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
thumbprint: {
required: false,
readOnly: true,
serializedName: 'properties.thumbprint',
type: {
name: 'String'
}
},
expiryTime: {
required: false,
readOnly: true,
serializedName: 'properties.expiryTime',
type: {
name: 'DateTime'
}
},
isExportable: {
required: false,
readOnly: true,
serializedName: 'properties.isExportable',
type: {
name: 'Boolean'
}
},
creationTime: {
required: false,
readOnly: true,
serializedName: 'properties.creationTime',
type: {
name: 'DateTime'
}
},
lastModifiedTime: {
required: false,
readOnly: true,
serializedName: 'properties.lastModifiedTime',
type: {
name: 'DateTime'
}
},
description: {
required: false,
serializedName: 'properties.description',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class USDistanceUnits extends BaseUnit {
/**
* Constructor.
*/
constructor() {
super();
}
/**
* @inheritDoc
*/
getTitle() {
return 'US';
}
/**
* @inheritDoc
*/
getUnitType() {
return 'distance';
}
/**
* @inheritDoc
*/
getSystem() {
return 'us';
}
/**
* @inheritDoc
*/
getDefaultMultiplier() {
return this.getMultiplier('mi');
}
/**
* @inheritDoc
*/
getConversionFactor() {
return (1 / 1609.3472);
}
/**
* @inheritDoc
*/
initMultipliers() {
this.multipliers.push(new Multiplier('in', (1 / 63360.0), false, 'inches'));
this.multipliers.push(new Multiplier('yd', (1 / 1760.0), true, 'yards'));
this.multipliers.push(new Multiplier('ft', (1 / 5280.0), true, 'feet'));
this.multipliers.push(new Multiplier('mi', 1, true, 'miles', .1));
}
} |
JavaScript | class Endpoint extends Resource {
/**
* Creates an instance of Endpoint.
* @param {String} name Endpoint name
* @param {String} type Endpoint Type
* @param {Number} maxTps Endpoint max TPS
* @param {Object} kwargs rest
* @memberof Endpoint
*/
constructor(name, type, maxTps, kwargs) {
super();
let properties = kwargs;
if (name instanceof Object) {
properties = name;
} else {
this.name = name;
this.type = type;
this.maxTps = maxTps;
}
this.endpointSecurity = {};
this.endpointConfig = {};
for (const key in properties) {
if (Object.prototype.hasOwnProperty.call(properties, key)) {
this[key] = properties[key];
}
}
}
/**
* Return the service URL of the Endpoint
* @returns {String} HTTP/HTTPS Service URL
* @memberof Endpoint
*/
getServiceUrl() {
return this.endpointConfig.service_url;
}
/**
* Persist the local endpoint object changes via Endpoint REST API
* @returns {Promise} Promise resolve with newly created Endpoint object
* @memberof Endpoint
*/
save() {
const promisedEndpoint = this.client.then((client) => {
return this._serialize().then((serializedData) => {
const payload = { body: serializedData, 'Content-Type': 'application/json' };
return client.apis['Endpoint (Collection)'].post_endpoints(payload, Resource._requestMetaData());
});
});
return promisedEndpoint.then((response) => {
return new Endpoint(response.body);
});
}
/**
* Serialize the object to send over the wire
* @returns {Object} serialized JSON object
* @memberof Endpoint
*/
_serialize() {
return this.client.then((client) => {
const { properties } = client.spec.definitions.EndPoint;
const data = {};
for (const property in this) {
if (property in properties) {
data[property] = this[property];
}
}
return data;
});
}
/**
* Get a global endpoint by giving its UUID
* @static
* @param {String} id UUID of the endpoint
* @returns {Promise} promise resolving to endpoint object
* @memberof Endpoint
*/
static get(id) {
const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
const promisedGet = apiClient.then((client) => {
return client.apis['Endpoint (individual)'].get_endpoints__endpointId_(
{
endpointId: id,
'Content-Type': 'application/json',
},
this._requestMetaData(),
);
});
return promisedGet.then((response) => {
const endpointJSON = response.body;
return new Endpoint(endpointJSON);
});
}
/**
* Get all Global endpoints
* @static
* @returns {Array} Array of global Endpoint objects
* @memberof Endpoint
*/
static all() {
const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
const promisedEndpoints = apiClient.then((client) => {
return client.apis['Endpoint (Collection)'].get_endpoints({}, this._requestMetaData());
});
return promisedEndpoints.then((response) => {
return response.body.list.map(endpointJSON => new Endpoint(endpointJSON));
});
}
} |
JavaScript | class APIError extends Error {
/**
* Creates an API error.
* @param {number} status - HTTP status code of error.
* @param {string} message - Custom error message.
*/
constructor(status = HttpStatus.INTERNAL_SERVER_ERROR, message) {
super(message)
this.name = this.constructor.name
this.status = status
this.message = message
this.isOperational = true // This is required since bluebird 4 doesn't append it anymore.
Error.captureStackTrace(this, this.constructor.name)
}
} |
JavaScript | class StackGallery extends React.Component {
constructor(props) {
super(props);
this.state = {
highlight_item: 0
}
}
clickImage(image, e) {
console.log("clickImage", image);
let _id = image.image_id;
_id = (_id + 1) % this.props.images.length;
this.setState({highlight_item: _id});
}
render() {
this.props.images.map((image, i) => {
image.image_id = i;
return image;
});
let image_list = this.props.images.map((image, i) => {
let _image_class = "";
if (this.state.highlight_item === i) {
_image_class = "stack-gallery-image-1";
} else {
_image_class = "stack-gallery-image-" + (i + 1)
}
return (<img className={_image_class}
src={image.src}
alt={image.alt}
key={image.image_id}
onClick={this.clickImage.bind(this, image)} />);
});
return (
<div className="stack-gallery">
<div>
<img className="stack-gallery-image" src={this.props.images[0].src} alt={this.props.images[0].alt} />
{image_list}
</div>
</div>
)
}
} |
JavaScript | class BodyController {
constructor($scope, $transitions) {
$scope.listMarksControllerHackyList = []
var tearDownListMarksController = function() {
$scope.listMarksControllerHackyList.forEach(element => {
element.tearDownThis()
})
$scope.listMarksControllerHackyList = []
}
$scope.enableVideoKeyBindings = (aBoolean) => {
$scope.videoKeyBindingsEnabled = aBoolean
}
$transitions.onEnter({entering: "video.listMarks"}, function(){
$scope.enableVideoKeyBindings(true)
})
$transitions.onExit({exiting: "video.listMarks"}, function(){
tearDownListMarksController()
})
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.