language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class PaypalButton extends React.Component {
constructor(props) {
super(props);
this.state = {
showButtons: false,
loading: true,
paid: false
};
window.React = React;
window.ReactDOM = ReactDOM;
}
//...
} |
JavaScript | class IKArm {
constructor(length, angle = 0, x = 0, y = 0) {
this.length = length;
this.angle = angle;
this.x = x;
this.y = y;
this.init();
}
/**
* ==================================================================================
* @Methods
* ==================================================================================
**/
/**
* Initial setup
*/
init() {
this.parent = null;
}
/**
* ==================================================================================
* @Controller
* ==================================================================================
**/
/**
* Move all `Arm` axis to specified coordinates
* @param {int} x
* @param {int} y
*/
drag(x, y) {
/* Rotate to coordinates */
this.pointAt(x, y);
/* Set axis to coordinates */
this.x = x - Math.cos(this.angle) * this.length;
this.y = y - Math.sin(this.angle) * this.length;
/* Update parent if it exists */
if(this.parent) {
this.parent.drag(this.x, this.y);
}
}
/**
* Change angle to specified coordinates
* @param {int} x
* @param {int} y
*/
pointAt(x, y) {
let dx = x - this.x,
dy = y - this.y;
this.angle = Math.atan2(dy, dx);
}
/**
* Update coordinates
*/
update() {
/* Check if has parent, check `axis` for changes */
if(this.parent) {
this.x = this.parent.getEndX();
this.y = this.parent.getEndY();
}
}
/**
* ==================================================================================
* @Renderer
* ==================================================================================
**/
/**
* Draw the `Arm`
* @param {CanvasRenderingContext2D} context
*/
draw(context) {
context.save();
context.beginPath();
context.moveTo(this.x, this.y);
context.lineTo(this.getEndX(), this.getEndY());
context.stroke();
context.restore();
}
/**
* ==================================================================================
* @Getter/Setter
* ==================================================================================
**/
/**
* Get the end values of `x` & `y` coordinates depending on specified length and angle
* @return {Int}
*/
getEndX() { return this.x + Math.cos(this.angle) * this.length; }
getEndY() { return this.y + Math.sin(this.angle) * this.length; }
/**
* Set parent `Arm`
* @param {IKArm} parent
*/
setParent(parent) {
this.parent = parent;
/* Update `x` & `y` to parents end coordinates */
this.x = parent.getEndX();
this.y = parent.getEndY();
}
/**
* ==================================================================================
* @Checker
* ==================================================================================
**/
//
} |
JavaScript | class StatusBarState {
constructor() {
this.disposed = false;
}
updateStatusBarItem(item) {
this.hideItem(item);
}
updateDominantSpeakerStatusBarItem(item) {
this.hideItem(item);
}
updateAudioConnectedStatusBarItem(item) {
this.hideItem(item);
}
hideItem(item) {
item.hide();
item.text = undefined;
item.command = undefined;
item.tooltip = undefined;
}
/**
* Conditionally shows quick pick items based on whether they are enabled or not.
*/
showQuickPick(items, options) {
return vscode.window.showQuickPick(items.filter(item => item.enabled()), options);
}
dispose() {
this.disposed = true;
}
} |
JavaScript | class InitialState extends StatusBarState {
updateStatusBarItem(statusBarItem) {
return __awaiter(this, void 0, void 0, function* () {
this.hideItem(statusBarItem);
});
}
} |
JavaScript | class LiveShareWithoutAudioState extends StatusBarState {
constructor(liveShare) {
super();
this.liveShare = liveShare;
this.disconnectedQuickPickItems = [
{
label: '$(plug) Connect/Start Audio Call',
description: '',
detail: 'Start an audio call or connect to an existing one.',
command: 'liveshare.audio.startOrJoinAudio',
enabled: () => !!(this.liveShare.session && this.liveShare.session.id)
}
];
}
updateStatusBarItem(statusBarItem) {
return __awaiter(this, void 0, void 0, function* () {
const commandId = '_liveShareAudio.disconnectedShowOptions';
yield extensionutil_1.ExtensionUtil.tryRegisterCommand(commandId, () => {
return this.showQuickPick(this.disconnectedQuickPickItems, { placeHolder: 'What would you like to do?' })
.then(pick => pick && vscode.commands.executeCommand(pick.command, pick.commandArg));
});
statusBarItem.text = !(this.liveShare.session && this.liveShare.session.id) ? '$(link-external) Share + Audio' : '$(link-external) Audio';
statusBarItem.command = commandId;
statusBarItem.show();
});
}
} |
JavaScript | class NoLiveShareState extends StatusBarState {
constructor(liveShare) {
super();
this.liveShare = liveShare;
}
updateStatusBarItem(statusBarItem) {
return __awaiter(this, void 0, void 0, function* () {
statusBarItem.hide();
});
}
} |
JavaScript | class Algorithm {
constructor() {}
linearSearch(array, item) {
for (let i = 0; i < array.length; i++) {
if (array[i] == item) {
return "Found " + item + " at position " + (i + 1);
}
}
return item + " not found!";
}
linearRec(array, item, left, right) {
if (left <= right) {
if (array[left] == item) {
return "Found " + item + " at position " + (left + 1);
}
if (array[right] == item) {
return "Found " + item + " at position " + (right + 1);
}
return this.linearRec(array, item, left + 1, right - 1);
}
return item + " not found!";
}
binarySearch(array, item) {
let left = 0,
right = array.length - 1,
found = false;
while (left <= right && !found) {
let mid = Math.floor((right + left) / 2);
console.log(mid);
if (item > array[mid]) {
left = mid + 1;
}
else if (item == array[mid]) {
found = true;
return "Found " + item + " at position " + (mid + 1);
}
else {
right = mid - 1;
}
}
return item + " not found!";
}
binaryRec(array, item, left, right) {
if (left <= right) {
let mid = Math.floor((left + right) / 2);
if (item > array[mid]) {
return this.binaryRec(array, item, mid + 1, right);
}
if (item == array[mid]) {
return "Found " + item + " at position " + (mid + 1);
}
if (item < array[mid]) {
return this.binaryRec(array, item, left, mid - 1);
}
}
return item + " not found";
}
} |
JavaScript | class Memoizable {
/**
* This abstract class should not call this constructor method or an error
* will be thrown.
*
* @throws {Error} Thrown when the class is called directly.
*/
constructor () {
if (this.constructor === Memoizable) {
throw new Error("Can't instantiate abstract class!");
}
}
/**
* Returns the methods of the class, wrapped inside a throttled function
* @param {Number} [wait=null] - Throttle duration in millisecond. The `null` means no limitations.
* @return {Object} All the methods of the class
*/
throttled (wait = null) {
return reduce(this.methods, (map, key) => {
const fn = this[key].bind(this)
map[key] = wait === null ? memoize(fn) : throttle(fn, wait)
return map
}, {})
}
get memoized () {
this[_memoized] = this[_memoized] || this.throttled()
return this[_memoized]
}
get methods() {
const prototype = Object.getPrototypeOf(this);
const methods = Object.getOwnPropertyNames(prototype);
// Remove the non-callable attribute
pull(methods, key => typeof this[key] === 'function')
// Remove the constructor from the method list (as he won't be memoized)
return difference(methods, ['constructor'])
}
} |
JavaScript | class Client extends ws {
constructor({ address = 'localhost', port, logger }) {
super(`ws://${address}:${port}`);
this._logger = logger;
}
// Really only exposed so that a user can import only the client for convenience
get Build() {
return build;
}
static async Create(...args) {
const result = new Client(...args);
await new Promise((resolve, reject) => {
result.on('open', resolve);
result.on('error', reject);
});
return result;
}
async send(msg) {
const data = typeof msg === 'string' ? msg : serialise(msg);
this._logger.log('Send msg as a client through websocket : ', data);
this._logger.log('Websocket client information : ', this.url);
return new Promise((resolve) => super.send.call(this, data, resolve));
}
// Receive a single message
async receive() {
return new Promise((resolve) => this.once('message', (data) => {
const deserialiseMessage = deserialise(data);
resolve(deserialiseMessage);
}));
}
} |
JavaScript | class UserAliasToken extends Requestable {
/**
* Constructor
* @param {JsXnat} jsXnat
*/
constructor(jsXnat) {
super(jsXnat);
}
/**
* User Alias Token Object
* @typedef UserAliasTokenObject
* @property {string} alias
* @property {string} xdatUserId
* @property {string} secret
* @property {boolean} singleUse
* @property {integer} estimatedExpirationTime
* @property {integer} timestamp
* @property {boolean} enabled
* @property {integer} created
* @property {string} id
* @property {integer} disabled
*/
/**
* Issue A New User Alias Token
* @param {function} [cb] Callback function
* @return {UserAliasTokenObject} User Alias Token Object
*/
async issueToken(cb = undefined) {
const res = await this._request(
'GET',
`/data/services/tokens/issue`,
undefined,
cb,
CONTENT_TYPES.json,
AUTH_METHODS.password
);
if (typeof res === 'object') {
return res;
} else {
return JSON.parse(res);
}
}
/**
* Issue A New User Alias Token For Another User
* @param {string} username username
* @param {function} [cb] Callback function
* @return {UserAliasTokenObject} User Alias Token Object
*/
issueTokenForUser(username, cb = undefined) {
if (!username) {
throw new IllegalArgumentsError('username is required');
}
return this._request(
'GET',
`/data/services/tokens/issue/user/${username}`,
undefined,
cb
);
}
/**
* Validate A User Alias Token
* @param {string} token token
* @param {string} secret secret
* @param {function} [cb] Callback function
* @return {object}
*/
validateToken(token, secret, cb = undefined) {
if (!token) {
throw new IllegalArgumentsError('token is required');
}
if (!secret) {
throw new IllegalArgumentsError('secret is required');
}
return this._request(
'GET',
`/data/services/tokens/validate/${token}/${secret}`,
undefined,
cb
);
}
/**
* Invalidate A User Alias Token
* @param {string} token token
* @param {string} secret secret
* @param {function} [cb] Callback function
* @return none
*/
invalidateToken(token, secret, cb = undefined) {
if (!token) {
throw new IllegalArgumentsError('token is required');
}
if (!secret) {
throw new IllegalArgumentsError('secret is required');
}
return this._request(
'GET',
`/data/services/tokens/invalidate/${token}/${secret}`,
undefined,
cb
);
}
} |
JavaScript | class CommentsContainer extends React.Component {
state = {
showCommentForm: false,
comment: "",
comments: [],
currentVideoComments: []
}
componentDidMount() {
fetch(COMMENTS)
.then(resp => resp.json())
.then(comments => this.setState({ comments: comments }, this.filterComments))
this.filterComments()
}
filterComments = () => {
let results = []
this.state.comments.filter(comment => {
if (comment.video_id == this.props.videoId) {
results.push(comment)
}
})
this.setState({ currentVideoComments: results })
}
toggleCommentForm = () => {
this.setState({ showCommentForm: true })
}
handleChange = (event) => {
this.setState({ comment: event.target.value })
}
handleSubmit = (event) => {
event.preventDefault()
let comments = this.state.comments
let newComment = this.state.comment
comments.push(newComment)
this.setState({ comments: comments })
this.postComment(newComment)
}
postComment = (comment) => {
fetch(COMMENTS, {
method: "POST",
headers: {
"Content-Type": "application/json",
accept: 'application/json'
},
body: JSON.stringify({
user_id: this.props.user.id,
video_id: this.props.videoId,
comment: comment
}),
})
.then((res) => res.json())
.then(console.log);
};
render() {
console.log(this.props.user, "ust")
return (
<>
<h3>Comments</h3>
{/* {this.state.showCommentForm && this.props.user.loggedIn ? <button name="submit" onClick={this.handleSubmit}>Submit Comment</button> : <button name="add-comment" onClick={this.toggleCommentForm}>Add Comment</button>} */}
{this.props.user.loggedIn ? <CommentForm handleChange={this.handleChange} handleSubmit={this.handleSubmit} text={this.state.comment} /> : <h4>You must be logged in to post a comment</h4>}
{this.state.currentVideoComments.map(comment => <Comment text={comment.comment} users={this.props.users} user={comment.user_id} />)}
</>
);
}
} |
JavaScript | class ExampleQuestHandler {
/**
* Construct a MyQuest quest handler
*
* @param {Player} player The player object
*/
constructor(player) {
this.player = player
// Set up the player so that this quest answers for requests to /my-quest
this.player.express.post('/my-simple-quest', this.handleRequest.bind(this))
}
/**
* Controller that will handle incoming requests for '/my-quest'
*
* @param {*} request Express.js request object
* @param {*} response Express.js response object
*/
handleRequest(request, response) {
if (request.method === 'POST') {
// We will always get JSON from the server
const data = request.body
// Let's see what the server is asking
log.info(`Server sent POST to /my-simple-quest: ${JSON.stringify(data)}`)
// Ok so we know that the question is "Who invented C++?"
// The request always contains a "msg" field, and the response always contains an "answer" field
const reply = {'answer': 'bjarne stroustrup'}
// The web server always expects a JSON response
response.send(JSON.stringify(reply))
} else {
log.error('This quest is supposed to handle POST requests')
}
}
} |
JavaScript | class Despesa{
constructor(ano, mes, dia, tipo, descricao, valor){
this.ano = ano;
this.mes = mes;
this.dia = dia;
this.tipo = tipo;
this.descricao = descricao;
this.valor = valor;
}
// VALIDA DE TODOS OS CAMPOS ESTÃO CORRETOS
setValidarAbas() {
for(let i in this){
if((this[i] === "") || (this[i] === undefined) || (this[i] === null) ){
return false;
}
}
return true;
}
} |
JavaScript | class HidRequest {
constructor (cmd, payload) {
this.cmd = cmd;
this.data = payload;
}
/** toInit
* @param {Integer} cid Optional CID
* @return {Uint8Array} 64 byte init HID packet.
*/
toInit(cid) {
cid = cid || 0x11223344;
var pkt = new Uint8Array(64);
pkt[0] = (cid & 0xff000000) >> 24;
pkt[1] = (cid & 0x00ff0000) >> 16;
pkt[2] = (cid & 0x0000ff00) >> 8;
pkt[3] = (cid & 0x000000ff) >> 0;
pkt[4] = this.cmd | 0x80;
pkt[5] = (this.data.length & 0xff00) >> 8;
pkt[6] = (this.data.length & 0x00ff) >> 0;
// Send (64-7) bytes of payload.
for (var i = 7; i < 64; i++)
{
if (i - 7 >= this.data.length)
{
break;
}
pkt[i] = this.data[i-7];
}
return pkt;
}
/** toPackets
* @param {Integer} cid Optional CID
* @return {Array[Uint8Array]} Array of 64 byte packets to write to FIDO device.
*/
toPackets(cid) {
var init = this.toInit(cid);
var arr = [init];
// Offset starting at 64-7 for rest of data.
var offset = 64 - 7;
var seq = 0;
while (offset < this.data.length)
{
var pkt = init.slice(0);
pkt[4] = seq++;
for (var i = 5; i < 64; i++){
if ((offset + i -5) >= this.data.length)
{
break;
}
pkt[i] = this.data[offset + i - 5];
}
offset += (64 - 5);
arr.push(pkt);
}
return arr;
}
} |
JavaScript | class EventManager extends Collection {
/**
* Creates an instance of EventManager.
* @author Lilly Rizuri
* @date 26/09/2021
* @param {import("../structures/Client")} client
* @memberof EventManager
*/
constructor(client) {
super();
/**
* The client.
* @type {import("../structures/Client")}
* @author Lilly Rizuri
* @date 26/09/2021
* @memberof EventManager
*/
this.client = client;
}
/**
* Loads an event.
* @author Lilly Rizuri
* @date 26/09/2021
* @param {string} filePath
* @param {import("../structures/Client")} client
* @returns {import("../structures/Event").eventID}
* @memberof EventManager
*/
load(filePath) {
if (filePath === void 0) {
throw new ReferenceError("No file path was provided.");
}
// Generate a random id.
const id = Math.random().toString(36).substring(7);
if (this.has(id)) {
return this.load(filePath);
}
/** @type {import("../structures/Event")} */
const event = new (require(path.resolve(filePath)))(this.client);
event.filePath = `${filePath}`;
console.log(event.filePath);
this.client.on(event.name, (...args) => {
try {
event.run(...args);
} catch (e) {
return this.client.error(e);
}
});
}
/**
* @description
* @author Lilly Rizuri
* @date 26/09/2021
* @param {string} eventResolvable A string that can be resolved as an event.
*
* This can be an `eventID`, `eventName`, or a `filePath`.
*
* @returns {this}
* @memberof EventManager
*/
unload(eventResolvable) {
if (this.has(eventResolvable)) {
this.client.removeListener(this.get(eventResolvable).name, this.get(eventResolvable).run);
this.delete(eventResolvable);
return this;
}
if (Object.values(eventNames).indexOf(eventResolvable) !== -1) {
this.client.removeAllListeners(eventResolvable);
this
.filter(e => e.name === eventResolvable)
.each(e => this.delete(e.id));
return this;
}
if (this.filter(e => e.filePath === eventResolvable).size > 0) {
this
.filter(e => e.filePath === eventResolvable)
.each(event => {
this.client.removeListener(event.name, (...args) => {
this.client.run(...args);
});
this.delete(event.id);
});
return this;
}
throw new Error("Unable to resolve an event from the provided string.");
}
} |
JavaScript | class SakaiProfile extends LitElement {
constructor() {
super();
loadProperties("profile").then(i18n => this.i18n = i18n);
}
static get properties() {
return {
userId: { attribute: "user-id", type: String },
siteId: { attribute: "site-id", type: String },
tool: { type: String },
profile: { attribute: false, type: Object },
i18n: { attribute: false, type: Object },
playing: { attribute: false, type: Boolean },
};
}
set userId(value) {
this._userId = value;
const url = `/api/users/${value}/profile`;
fetch(url, { credentials: "include" })
.then(r => {
if (r.ok) {
return r.json();
}
throw new Error(`Network error while getting user profile from ${url}`);
})
.then(profile => this.profile = profile)
.catch(error => console.error(error));
}
get userId() { return this._userId; }
playPronunciation() {
this.shadowRoot.getElementById("pronunciation-player").play();
}
render() {
return html`
<div class="container">
<div class="header">
<div class="photo" style="background-image:url(/direct/profile/${this.userId}/image/thumb)">
</div>
<div>
<div class="name">${this.profile.name}</div>
${this.profile.role ? html`
<div class="role">${this.profile.role}</div>
` : ""}
<div class="pronouns">${this.profile.pronouns}</div>
</div>
</div>
<div class="body">
${this.profile.pronunciation || this.profile.pronunciationRecordingUrl ? html`
<div class="label">${this.i18n.name_pronunciation}</div>
<div class="field pronunciation">
${this.profile.pronunciation ? html`
<div>${this.profile.pronunciation}</div>`
: ""}
${this.profile.hasPronunciationRecording ? html`
<sakai-pronunciation-player user-id="${this.userId}"></sakai-pronunciation-player>
` : ""}
</div>
` : ""}
${this.profile.email ? html`
<div class="label">${this.i18n.email}</div>
<div class="field">${this.profile.email}</div>
` : ""}
${this.profile.studentNumber ? html`
<div class="label">${this.i18n.student_number}</div>
<div class="field">${this.profile.studentNumber}</div>
` : ""}
${this.profile.url ? html`
<div class="label url"><a href="${this.profile.url}">${this.i18n.view_full_profile}</a></div>
` : ""}
</div>
</div>
`;
}
static get styles() {
return css`
.container {
padding: 14px;
}
.header {
display: flex;
margin-bottom: var(--sakai-profile-header-margin-bottom, 10px);
padding-bottom: var(--sakai-profile-header-padding-bottom, 10px);
border-bottom: var(--sakai-profile-border-bottom, 1px solid #E0E0E0);
}
.header > div:nth-child(2) > div {
margin-top: 5px;
}
.photo {
min-width: var(--sakai-profile-photo-size, 64px);
max-width: var(--sakai-profile-photo-size, 64px);
height: var(--sakai-profile-photo-size, 64px);
background-position: 50%;
background-size: auto 50%;
border-radius: 50%;
margin-right: var(--sakai-profile-photo-margin-right, 10px);
background-size: var(--sakai-profile-photo-size, 64px) var(--sakai-profile-photo-size, 64px);
}
.name {
font-weight: var(--sakai-profile-name-weight, 700);
font-size: var(--sakai-profile-name-size, 16px);
color: var(--sakai-profile-name-color, #262626);
margin-bottom: var(--sakai-profile-name-margin-bottom, 8px);
}
.role, .pronouns {
font-weight: var(--sakai-profile-header-weight, 400);
font-size: var(--sakai-profile-header-size, 12px);
color: var(--sakai-profile-header-color, #262626);
}
.label {
font-weight: var(--sakai-profile-label-weight, 700);
font-size: var(--sakai-profile-label-size, 12px);
color: var(--sakai-profile-label-color, #666666);
margin-bottom: var(--sakai-profile-label-margin-bottom, 4px);
}
.url {
margin-top: var(--sakai-profile-url-margin-top, 12px);
}
.field {
margin-bottom: var(--sakai-profile-field-margin-bottom, 8px);
}
.pronunciation {
display: flex;
align-items: center;
}
.pronunciation > div {
margin-right: 10px;
}
`;
}
} |
JavaScript | class CodeBlockManager {
constructor() {
this._replacers = {};
}
/**
* Set replacer for code block
* @param {string} language - code block language
* @param {function} replacer - replacer function to code block element
*/
setReplacer(language, replacer) {
this._replacers[language] = replacer;
}
/**
* get replacer for code block
* @param {string} language - code block type
* @returns {function} - replacer function
*/
getReplacer(language) {
return this._replacers[language];
}
/**
* Create code block html.
* @param {string} language - code block language
* @param {string} codeText - code text
* @returns {string}
*/
createCodeBlockHtml(language, codeText) {
const replacer = this.getReplacer(language);
if (replacer) {
return replacer(codeText, language);
}
return escape(codeText, false);
}
} |
JavaScript | class SV3DSwym extends Service_1.default {
static signRequests(data) {
this.commonOptions.headers['X-DS-SWYM-CSRFTOKEN'] = data.result.ServerToken;
}
} |
JavaScript | class FileConfigurationService extends TwyrBaseService {
// #region Constructor
constructor(parent) {
super(parent);
this.$cacheMap = {};
}
// #endregion
// #region setup/teardown code
/**
* @async
* @function
* @override
* @instance
* @memberof FileConfigurationService
* @name _setup
*
* @returns {boolean} Boolean true/false.
*
* @summary Sets up the file watcher to watch for changes on the fly.
*/
async _setup() {
try {
await super._setup();
const chokidar = require('chokidar'),
path = require('path');
const rootPath = path.dirname(path.dirname(require.main.filename));
this.$watcher = chokidar.watch(path.join(rootPath, `config${path.sep}${twyrEnv}`), {
'ignored': /[/\\]\./,
'ignoreInitial': true
});
this.$watcher
.on('add', this._onNewConfiguration.bind(this))
.on('change', this._onUpdateConfiguration.bind(this))
.on('unlink', this._onDeleteConfiguration.bind(this));
return null;
}
catch(err) {
throw new TwyrSrvcError(`${this.name}::_setup error`, err);
}
}
/**
* @async
* @function
* @override
* @instance
* @memberof FileConfigurationService
* @name _teardown
*
* @returns {boolean} Boolean true/false.
*
* @summary Shutdown the file watcher that watches for changes on the fly.
*/
async _teardown() {
try {
this.$watcher.close();
await super._teardown();
return null;
}
catch(err) {
throw new TwyrSrvcError(`${this.name}::_teardown error`, err);
}
}
// #endregion
// #region API
/**
* @async
* @function
* @instance
* @memberof FileConfigurationService
* @name loadConfiguration
*
* @param {TwyrBaseModule} twyrModule - Instance of the {@link TwyrBaseModule} that requires configuration.
*
* @returns {Object} - The twyrModule's file-based configuration.
*
* @summary Retrieves the configuration of the twyrModule requesting for it.
*/
async loadConfiguration(twyrModule) {
try {
let config = null;
const twyrModulePath = this.$parent._getPathForModule(twyrModule);
if(this.$cacheMap[twyrModulePath]) return this.$cacheMap[twyrModulePath];
const fs = require('fs-extra'),
path = require('path'),
promises = require('bluebird');
const filesystem = promises.promisifyAll(fs);
const rootPath = path.dirname(path.dirname(require.main.filename));
const configPath = path.join(rootPath, `config${path.sep}${twyrEnv}`, `${twyrModulePath}.js`);
await filesystem.ensureDirAsync(path.dirname(configPath));
const doesExist = await this._exists(configPath, filesystem.R_OK);
if(doesExist) config = require(configPath).config;
this.$cacheMap[twyrModulePath] = config;
return config;
}
catch(err) {
throw new TwyrSrvcError(`${this.name}::loadConfig::${twyrModule.name} error`, err);
}
}
/**
* @async
* @function
* @instance
* @memberof FileConfigurationService
* @name saveConfiguration
*
* @param {TwyrBaseModule} twyrModule - Instance of the {@link TwyrBaseModule} that requires configuration.
* @param {Object} config - The {@link TwyrBaseModule}'s' configuration that should be persisted.
*
* @returns {Object} - The twyrModule configuration.
*
* @summary Saves the configuration of the twyrModule requesting for it.
*/
async saveConfiguration(twyrModule, config) {
try {
const deepEqual = require('deep-equal'),
fs = require('fs-extra'),
path = require('path'),
promises = require('bluebird');
const twyrModulePath = this.$parent._getPathForModule(twyrModule);
if(deepEqual(this.$cacheMap[twyrModulePath], config))
return config;
this.$cacheMap[twyrModulePath] = config;
const rootPath = path.dirname(path.dirname(require.main.filename));
const configPath = path.join(rootPath, `config${path.sep}${twyrEnv}`, `${twyrModulePath}.js`);
const filesystem = promises.promisifyAll(fs);
await filesystem.ensureDirAsync(path.dirname(configPath));
const configString = `exports.config = ${JSON.stringify(config, undefined, '\t')};\n`;
await filesystem.writeFileAsync(configPath, configString);
return config;
}
catch(err) {
throw new TwyrSrvcError(`${this.name}::saveConfig::${twyrModule.name} error`, err);
}
}
/**
* @async
* @function
* @instance
* @memberof FileConfigurationService
* @name getModuleState
*
* @param {TwyrBaseModule} twyrModule - Instance of the {@link TwyrBaseModule} that requires its state.
*
* @returns {boolean} - Boolean true always, pretty much.
*
* @summary Empty method, since the file-based configuration module doesn't manage the state.
*/
async getModuleState(twyrModule) {
return !!twyrModule;
}
/**
* @async
* @function
* @instance
* @memberof FileConfigurationService
* @name setModuleState
*
* @param {TwyrBaseModule} twyrModule - Instance of the {@link TwyrBaseModule} that requires its state.
* @param {boolean} enabled - State of the module.
*
* @returns {Object} - The state of the twyrModule.
*
* @summary Empty method, since the file-based configuration module doesn't manage the state.
*/
async setModuleState(twyrModule, enabled) {
return enabled;
}
/**
* @async
* @function
* @instance
* @memberof FileConfigurationService
* @name getModuleId
*
* @returns {null} - Nothing.
*
* @summary Empty method, since the file-based configuration module doesn't manage module ids.
*/
async getModuleId() {
return null;
}
// #endregion
// #region Private Methods
/**
* @async
* @function
* @instance
* @private
* @memberof FileConfigurationService
* @name _processConfigChange
*
* @param {TwyrBaseModule} configUpdateModule - The twyrModule for which the configuration changed.
* @param {Object} config - The updated configuration.
*
* @returns {null} - Nothing.
*
* @summary Persists the configuration to the filesystem.
*/
async _processConfigChange(configUpdateModule, config) {
try {
const deepEqual = require('deep-equal'),
fs = require('fs-extra'),
path = require('path'),
promises = require('bluebird');
if(deepEqual(this.$cacheMap[configUpdateModule], config))
return;
const rootPath = path.dirname(path.dirname(require.main.filename));
const configPath = path.join(rootPath, `config${path.sep}${twyrEnv}`, configUpdateModule);
this.$cacheMap[configUpdateModule] = config;
const filesystem = promises.promisifyAll(fs);
await filesystem.ensureDirAsync(path.dirname(configPath));
const configString = `exports.config = ${JSON.stringify(config, undefined, '\t')};`;
await filesystem.writeFileAsync(`${configPath}.js`, configString);
}
catch(err) {
console.error(`Process changed configuration to file error: ${err.message}\n${err.stack}`);
}
}
/**
* @async
* @function
* @instance
* @private
* @memberof FileConfigurationService
* @name _processStateChange
*
* @returns {null} - Nothing.
*
* @summary Empty method, since the file-based configuration module doesn't manage module states.
*/
async _processStateChange() {
return null;
}
/**
* @async
* @function
* @instance
* @private
* @memberof FileConfigurationService
* @name _onNewConfiguration
*
* @param {string} filePath - The absolute path of the new configuration file.
*
* @returns {null} - Nothing.
*
* @summary Reads the new configuration, maps it to a loaded twyrModule, and tells the rest of the configuration services to process it.
*/
async _onNewConfiguration(filePath) {
try {
const path = require('path');
const rootPath = path.dirname(path.dirname(require.main.filename));
const twyrModulePath = path.relative(rootPath, filePath).replace(`config${path.sep}${twyrEnv}${path.sep}`, '').replace('.js', '');
this.$cacheMap[twyrModulePath] = require(filePath).config;
this.$parent.emit('new-config', this.name, twyrModulePath, this.$cacheMap[twyrModulePath]);
}
catch(err) {
console.error(`Process new configuration in ${filePath} error: ${err.message}\n${err.stack}`);
}
}
/**
* @async
* @function
* @instance
* @private
* @memberof FileConfigurationService
* @name _onUpdateConfiguration
*
* @param {string} filePath - The absolute path of the updated configuration file.
*
* @returns {null} - Nothing.
*
* @summary Reads the new configuration, maps it to a loaded twyrModule, and tells the rest of the configuration services to process it.
*/
async _onUpdateConfiguration(filePath) {
try {
const deepEqual = require('deep-equal'),
path = require('path');
const rootPath = path.dirname(path.dirname(require.main.filename));
const twyrModulePath = path.relative(rootPath, filePath).replace(`config${path.sep}${twyrEnv}${path.sep}`, '').replace('.js', '');
delete require.cache[filePath];
await snooze(500);
if(deepEqual(this.$cacheMap[twyrModulePath], require(filePath).config))
return;
this.$cacheMap[twyrModulePath] = require(filePath).config;
this.$parent.emit('update-config', this.name, twyrModulePath, require(filePath).config);
}
catch(err) {
console.error(`Process updated configuration in ${filePath} error: ${err.message}\n${err.stack}`);
}
}
/**
* @async
* @function
* @instance
* @private
* @memberof FileConfigurationService
* @name _onDeleteConfiguration
*
* @param {string} filePath - The absolute path of the deleted configuration file.
*
* @returns {null} - Nothing.
*
* @summary Removes configuration from the cache, etc., and tells the rest of the configuration services to process it.
*/
async _onDeleteConfiguration(filePath) {
try {
const path = require('path');
const rootPath = path.dirname(path.dirname(require.main.filename));
const twyrModulePath = path.relative(rootPath, filePath).replace(`config${path.sep}${twyrEnv}${path.sep}`, '').replace('.js', '');
delete require.cache[filePath];
delete this.$cacheMap[twyrModulePath];
this.$parent.emit('delete-config', this.name, twyrModulePath);
}
catch(err) {
console.error(`Process deleted configuration in ${filePath} error: ${err.message}\n${err.stack}`);
}
}
// #endregion
// #region Properties
/**
* @override
*/
get basePath() {
return __dirname;
}
// #endregion
} |
JavaScript | class MyBuild extends Component {
constructor(props) {
super(props);
this.state = {users:[]};
}
baseURL = process.env.REACT_APP_API || "http://localhost:5000";
componentDidMount() {
axios.get(this.baseURL + "/user/users")
.then(res=>{
this.setState({
users: res.data
})
console.log("below this")
console.log(this.state.users)
})
.catch(err=>console.log(err));
}
users() {
return this.state.users.map(curUser =>{
if(curUser.username !== 'admin') {
return <User user={curUser} key={curUser._id}
/>
}
})
}
render() {
return (
<div className='MyBuilds text-center users-div'>
<h1 className="users">USERS</h1>
<TableScrollbar rows={10}>
<table className="table table-bordered table-hover users-table">
<thead className="thead-dark">
<tr>
<th>Username</th>
<th>Date Created</th>
<th className="text-center">Builds</th>
</tr>
</thead>
<tbody >
{this.users()}
</tbody>
</table>
</TableScrollbar>
</div>
);
}
} |
JavaScript | class Bins {
constructor(dwst) {
this._dwst = dwst;
}
commands() {
return ['bins'];
}
usage() {
return [
'/bins [name]',
];
}
examples() {
return [
'/bins',
'/bins default',
];
}
info() {
return 'list loaded binaries';
}
_run(variable = null) {
if (variable !== null) {
const buffer = this._dwst.bins.get(variable);
if (typeof buffer !== 'undefined') {
this._dwst.terminal.blog(buffer, 'system');
return;
}
const listTip = [
'List available binaries by typing ',
{
type: 'command',
text: '/bins',
},
'.',
];
this._dwst.terminal.mlog([`Binary "${variable}" does not exist.`, listTip], 'error');
return;
}
const listing = [...this._dwst.bins.entries()].map(([name, buffer]) => {
return `"${name}": <${buffer.byteLength}B of binary data>`;
});
const strs = ['Loaded binaries:'].concat(listing);
this._dwst.terminal.mlog(strs, 'system');
}
run(paramString) {
if (paramString.length < 1) {
this._run();
return;
}
const params = paramString.split(' ');
this._run(...params);
}
} |
JavaScript | class Banner extends LitElement {
static get properties() {
return {
hasNav: { attribute: false },
hasSubnav: { attribute: false },
};
}
static get styles() {
return [
theme,
css`
:host {
display: flex;
flex-direction: column;
background-color: var(--pzsh-banner-bg);
}
::slotted([slot="tangram"]) {
display: none;
}
.content {
flex: auto;
display: flex;
align-items: center;
justify-content: center;
position: relative; /* Move in front of tangram */
}
::slotted([slot="content"]) {
flex: auto;
overflow: hidden;
margin: var(--pzsh-spacer) calc(2 * var(--pzsh-spacer));
}
@media (min-width: 800px) {
:host {
position: relative;
overflow: hidden;
}
::slotted([slot="tangram"]) {
display: block;
position: absolute;
top: 0;
right: 0;
}
::slotted([slot="content"]) {
margin: calc(6 * var(--pzsh-spacer)) var(--pzsh-spacer);
}
.content.has-nav {
margin-top: var(--pzsh-nav-height);
}
.content.has-subnav {
margin-top: calc(2 * var(--pzsh-nav-height));
}
}
`,
];
}
constructor() {
super();
this.hasNav = false;
this.hasSubnav = false;
this.handleMenuNavChange = this.handleMenuNavChange.bind(this);
}
connectedCallback() {
super.connectedCallback();
document.addEventListener(
"pzsh-menu-nav-change",
this.handleMenuNavChange,
true
);
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener(
"pzsh-menu-nav-change",
this.handleMenuNavChange,
true
);
}
handleMenuNavChange(e) {
e.stopPropagation();
const { hasNav, hasSubnav } = e.detail;
this.hasNav = hasNav;
this.hasSubnav = hasSubnav;
}
render() {
return html`
<slot name="tangram"></slot>
<div
class=${classMap({
content: true,
"has-nav": this.hasNav,
"has-subnav": this.hasSubnav,
})}
>
<slot name="content"></slot>
</div>
`;
}
} |
JavaScript | class VigenereCipheringMachine {
constructor (whatType) {
if (whatType === false) {
this.direction = false;
} else {
this.direction = true;
}
this.alpfabet = ['A', 'B', 'C', 'D', 'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
};
encrypt(message, key) {
if (!key || !message) {
throw new Error('Incorrect arguments!');
};
let cnt = 0;
let newString = message.toUpperCase().split('').map(element => {
if (this.alpfabet.includes(element)) {
return key[cnt++ % key.length].toUpperCase();
} else {
return element;
};
});
let result = [];
message.toUpperCase().split('').forEach((element, n) => {
if (this.alpfabet.includes(element)) {
let temp = (this.alpfabet.indexOf(element) + this.alpfabet.indexOf(newString[n])) % 26;
result.push(this.alpfabet[temp]);
} else {
result.push(element);
};
});
if (this.direction) {
return result.join('');
} else {
return result.reverse().join('');
};
};
decrypt(message, key) {
if (!key || !message) {
throw new Error('Incorrect arguments!');
};
let cnt = 0;
let newString = message.toUpperCase().split('').map(element => {
if (this.alpfabet.includes(element)) {
return key[cnt++ % key.length].toUpperCase();
} else {
return element;
}
})
let result = [];
message.toUpperCase().split('').forEach((element, n) => {
if (this.alpfabet.includes(element)) {
let temp = this.alpfabet.indexOf(element) - (this.alpfabet.indexOf(newString[n]) % 26);
if (temp < 0) {
temp += 26;
}
result.push(this.alpfabet[temp])
} else {
result.push(element)
}
});
if (this.direction) {
return result.join('');
} else {
return result.reverse().join('');
};
};
} |
JavaScript | class TestTransformer extends Transformer {
async compute() {
debug("Running the TestTransformer!");
}
async prepare() {
debug("Preparing transformer!");
}
} |
JavaScript | class Controller extends FileImportWizard {
/**
* Constructor.
* @param {!angular.Scope} $scope
* @param {!angular.JQLite} $element
* @param {!angular.$timeout} $timeout
* @param {!Object.<string, string>} $attrs
* @ngInject
*/
constructor($scope, $element, $timeout, $attrs) {
super($scope, $element, $timeout, $attrs);
}
/**
* @param {!CSVDescriptor} descriptor
* @protected
* @override
*/
addDescriptorToProvider(descriptor) {
CSVProvider.getInstance().addDescriptor(descriptor);
}
/**
* @param {!CSVParserConfig} config
* @return {!CSVDescriptor}
* @protected
* @override
*/
createFromConfig(config) {
const descriptor = new CSVDescriptor(this.config);
FileDescriptor.createFromConfig(descriptor, CSVProvider.getInstance(), this.config);
return descriptor;
}
/**
* @param {!CSVDescriptor} descriptor
* @param {!CSVParserConfig} config
* @protected
* @override
*/
updateFromConfig(descriptor, config) {
descriptor.updateFromConfig(config);
}
} |
JavaScript | class Server {
/**
* Server constructor
* @constructs Server
* @param {number} [port = 8080] - Port number the server should listen
* @example
* const customPort = 3000;
* const app = new Server(customPort);
*/
constructor(port = 8080) {
/**
* Express application instance
* @member Server#app
*/
this.app = express();
this.app.use(express.static('src'));
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: true }));
/**
* Express server instance
* @member Server#server
*/
this.server = require('http').createServer(this.app);
/**
* Configuration holder
* @member {Object} Server#config
*/
this.config = {};
/**
* Port number
* @member {number} Server#config.port
*/
this.config.port = port;
}
/**
* Launches this server instance
* @method launch
* @example
* const app = new Server();
* app.launch();
*/
launch() {
this.server.listen(process.env.PORT || this.config.port);
console.log(`__________________________________________`);
console.log(`Express server launched`);
console.log(`port: ${this.config.port}`);
}
} |
JavaScript | class ArrayUtils {
/**
* search item in array by function
* @param arr
* @param f
* @deprecated use Array.prototype.find
* @return {T}
*/
static search(arr, f) {
let r = undefined;
arr.some((v) => {
if (f(v)) {
r = v;
return true;
}
return false;
});
return r;
}
/**
*
* @deprecated use Array.prototype.findIndex
* @param arr
* @param f
* @return {number}
*/
static indexOf(arr, f) {
let r = -1;
arr.some((v, i) => {
if (f(v)) {
r = i;
return true;
}
return false;
});
return r;
}
/**
* converts the given arguments object into an array
* @param args
* @deprecated use Array.from(arguments) instead
* @internal
* @returns {*|Array}
*/
static argList(args) {
if (arguments.length > 1) {
return Array.prototype.slice.call(arguments);
}
else {
return Array.prototype.slice.call(args);
}
}
/**
* array with indices of 0...n-1
* @param n
* @returns {any[]}
*/
static indexRange(n) {
//http://stackoverflow.com/questions/3746725/create-a-javascript-array-containing-1-n
return Array.apply(null, { length: n }).map(Number.call, Number);
}
/**
* returns the sorted indices of this array, when sorting by the given function
* @param arr
* @param compareFn
* @param thisArg
*/
static argSort(arr, compareFn, thisArg) {
const indices = ArrayUtils.indexRange(arr.length);
return indices.sort((a, b) => {
return compareFn.call(thisArg, arr[a], arr[b]);
});
}
/**
* returns the indices, which remain when filtering the given array
* @param arr
* @param callbackfn
* @param thisArg
*/
static argFilter(arr, callbackfn, thisArg) {
const indices = ArrayUtils.indexRange(arr.length);
return indices.filter((value, index) => {
return callbackfn.call(thisArg, arr[value], index);
});
}
} |
JavaScript | class DeckValidator {
constructor(packs) {
this.packs = packs;
this.bannedList = new BannedList();
this.restrictedList = new RestrictedList();
}
validateDeck(deck) {
let errors = [];
let rules = this.getRules(deck);
let objectiveCount = getDeckCount(deck.objectiveCards);
if(objectiveCount < rules.minimumObjective) {
errors.push('A deck requires a minimum of 10 objectives');
}
_.each(rules.rules, rule => {
if(!rule.condition(deck)) {
errors.push(rule.message);
}
});
let objectiveCards = deck.objectiveCards;
_.each(objectiveCards, objectiveCard => {
if(objectiveCard.card.limit1PerObjectiveDeck && objectiveCard.count > 1) {
errors.push(objectiveCard.card.name + ' is limited to 1 per objective deck');
}
if(objectiveCard.count > 2) {
errors.push('limit 2 objective copies per deck');
}
if(objectiveCard.card.loyalAffiliationOnly && deck.affiliation.value !== objectiveCard.card.affiliation) {
errors.push(objectiveCard.card.name + ' is ' + objectiveCard.card.affiliation + ' affiliation only');
}
if(objectiveCard.card.side !== deck.affiliation.side) {
errors.push(objectiveCard.card.name + ' is in the wrong side of the force... for now.');
}
});
let restrictedResult = this.restrictedList.validate(objectiveCards.map(cardQuantity => cardQuantity.card));
let bannedResult = this.bannedList.validate(objectiveCards.map(cardQuantity => cardQuantity.card));
return {
basicRules: errors.length === 0,
faqRestrictedList: restrictedResult.valid && bannedResult.valid,
faqVersion: restrictedResult.version,
objectiveCount: objectiveCount,
extendedStatus: errors.concat(restrictedResult.errors, bannedResult.errors)
};
}
getRules(deck) {
const standardRules = {
minimumObjective: 10,
};
let affiliationRules = this.getAffiliationRules(deck.affiliation.value.toLowerCase());
return this.combineValidationRules([standardRules, affiliationRules]);
}
getAffiliationRules(affiliation) {
return {
mayInclude: card => card.side === affiliation.side
};
}
combineValidationRules(validators) {
let mayIncludeFuncs = _.compact(_.pluck(validators, 'mayInclude'));
let cannotIncludeFuncs = _.compact(_.pluck(validators, 'cannotInclude'));
let combinedRules = _.reduce(validators, (rules, validator) => rules.concat(validator.rules || []), []);
let combined = {
mayInclude: card => _.any(mayIncludeFuncs, func => func(card)),
cannotInclude: card => _.any(cannotIncludeFuncs, func => func(card)),
rules: combinedRules
};
return _.extend({}, ...validators, combined);
}
} |
JavaScript | class ConsoleLogger extends Transform {
constructor (options) {
super(options)
this.data = {
projects: 0,
occurrences: 0
}
}
_transform (results, encoding, done) {
this.data.projects++
this.data.occurrences += results.count
logger.log(formatter(results))
this.push(results)
done()
}
_flush (done) {
const message = `${this.data.occurrences} occurrences found in ${this.data.projects} projects`
process.stdout.write(newline + message + newline)
this.push(message)
done()
}
} |
JavaScript | class PowerSchoolFinalGrade {
constructor(api, id, grade, percentage, date, comment, reportingTermID, courseID) {
this.api = api;
/**
* The ID of this event.
* @member {number}
*/
this.id = id;
/**
* The grade received in this course, to be displayed.
* @member {string}
*/
this.grade = grade;
/**
* The grade received in this course as a percentage (value from 0-1), if can be calculated.
* @member {number}
*/
this.percentage = percentage;
/**
* The date this mark was stored, if available.
* @member {Date}
*/
this.date = date;
/**
* The teacher's comment for this grade, if available.
* @member {string}
*/
this.comment = comment;
/**
* The identifier of the reporting term this grade is from.
* @member {number}
*/
this.reportingTermID = reportingTermID;
/**
* The identifier of the course this grade is from.
* @member {number}
*/
this.courseID = courseID;
}
static fromData(data, api) {
return new PowerSchoolFinalGrade(api, data.id, data.grade, data.percent / 100, data.dateStored ? new Date(data.dateStored) : null, data.commentValue, data.reportingTermId, data.sectionid);
}
/**
* Get the reporting term this grade is from.
* @return {PowerSchoolReportingTerm}
*/
getReportingTerm() {
return this.api._cachedInfo.reportingTerms[this.reportingTermID];
}
/**
* Get the course this grade is from.
* @return {PowerSchoolCourse}
*/
getCourse() {
return this.api._cachedInfo.courses[this.courseID];
}
} |
JavaScript | class Source {
id; // String
name; // String
avatar; // Avatar?
style; // object
maxPosts; // Number
followers; // TruncatedNormalDistribution
credibility; // TruncatedNormalDistribution
truePostPercentage; // null or a Number between 0 and 1
constructor(id, name, avatar, style, maxPosts, followers, credibility, truePostPercentage) {
doTypeCheck(id, "string", "Source ID");
doNullableTypeCheck(avatar, [StudyImage, StudyImageMetadata], "Source Avatar");
doNullableTypeCheck(style, "object", "Style");
doTypeCheck(name, "string", "Source Name");
doTypeCheck(maxPosts, "number", "Source Maximum Posts");
doTypeCheck(followers, TruncatedNormalDistribution, "Source Initial Followers");
doTypeCheck(credibility, TruncatedNormalDistribution, "Source Initial Credibility");
doNullableTypeCheck(truePostPercentage, "number", "Source True Post Percentage");
this.id = id;
this.name = name;
this.avatar = avatar;
this.style = style || Source.randomStyle();
this.maxPosts = maxPosts;
this.followers = followers;
this.credibility = credibility;
this.truePostPercentage = truePostPercentage;
}
toJSON() {
return {
"id": this.id,
"name": this.name,
"avatar": (!this.avatar ? null : this.avatar.toMetadata().toJSON()),
"style": this.style,
"maxPosts": this.maxPosts,
"followers": this.followers.toJSON(),
"credibility": this.credibility.toJSON(),
"truePostPercentage": this.truePostPercentage
};
}
static fromJSON(json) {
return new Source(
json["id"], json["name"],
(!json["avatar"] ? null : StudyImageMetadata.fromJSON(json["avatar"])),
json["style"],
json["maxPosts"],
TruncatedNormalDistribution.fromJSON(json["followers"]),
TruncatedNormalDistribution.fromJSON(json["credibility"]),
json["truePostPercentage"]
);
}
static randomStyle() {
return randElement(SOURCE_AVAILABLE_SOURCE_STYLES);
}
} |
JavaScript | class ReactionValues {
like; // TruncatedNormalDistribution?
dislike; // TruncatedNormalDistribution?
share; // TruncatedNormalDistribution?
flag; // TruncatedNormalDistribution?
constructor(like, dislike, share, flag) {
doNullableTypeCheck(like, TruncatedNormalDistribution, "Reaction Value for a Like");
doNullableTypeCheck(dislike, TruncatedNormalDistribution, "Reaction Value for a Dislike");
doNullableTypeCheck(share, TruncatedNormalDistribution, "Reaction Value for a Share");
doNullableTypeCheck(flag, TruncatedNormalDistribution, "Reaction Value for a Flag");
this.like = like;
this.dislike = dislike;
this.share = share;
this.flag = flag;
}
sampleAll() {
const numberOfReactions = {};
const reactions = ["like", "dislike", "share", "flag"];
for (let index = 0; index < reactions.length; ++index) {
const reaction = reactions[index];
const distribution = this[reaction];
if (!distribution)
continue;
numberOfReactions[reaction] = Math.round(distribution.sample());
}
return numberOfReactions;
}
static reactionToJSON(dist) {
return (dist !== null ? dist.toJSON() : null);
}
static reactionFromJSON(json) {
return (json !== null ? TruncatedNormalDistribution.fromJSON(json) : null);
}
toJSON() {
return {
"like": ReactionValues.reactionToJSON(this.like),
"dislike": ReactionValues.reactionToJSON(this.dislike),
"share": ReactionValues.reactionToJSON(this.share),
"flag": ReactionValues.reactionToJSON(this.flag)
};
}
static fromJSON(json) {
return new ReactionValues(
ReactionValues.reactionFromJSON(json["like"]),
ReactionValues.reactionFromJSON(json["dislike"]),
ReactionValues.reactionFromJSON(json["share"]),
ReactionValues.reactionFromJSON(json["flag"])
);
}
static zero() {
const zero = TruncatedNormalDistribution.zero();
return new ReactionValues(zero, zero, zero, zero);
}
} |
JavaScript | class PostComment {
index; // Number
sourceName; // String
message; // String
numberOfReactions; // ReactionValues
constructor(index, sourceName, message, numberOfReactions) {
doTypeCheck(index, "number", "Comment's Index")
doTypeCheck(sourceName, "string", "Comment's Source Name");
doTypeCheck(message, "string", "Comment's Message");
doTypeCheck(numberOfReactions, ReactionValues, "Comment Number of Reactions");
this.index = index;
this.sourceName = sourceName;
this.message = message;
this.numberOfReactions = numberOfReactions;
}
toJSON() {
return {
"sourceName": this.sourceName,
"message": this.message,
"numberOfReactions": this.numberOfReactions.toJSON()
};
}
static fromJSON(json, index) {
return new PostComment(
index,
json["sourceName"],
json["message"],
ReactionValues.fromJSON(json["numberOfReactions"])
);
}
} |
JavaScript | class UserComment extends PostComment {
constructor(message) {
super(-1, "You", message, ReactionValues.zero());
}
} |
JavaScript | class Post {
id; // String
headline; // String
content; // StudyImage, StudyImageMetadata, or String
isTrue; // Boolean
changesToFollowers; // ReactionValues
changesToCredibility; // ReactionValues
numberOfReactions; // ReactionValues
comments; // PostComment[]
constructor(id, headline, content, isTrue, changesToFollowers, changesToCredibility, numberOfReactions, comments) {
doTypeCheck(id, "string", "Post ID");
doTypeCheck(headline, "string", "Post Headline");
doTypeCheck(content, [StudyImage, StudyImageMetadata, "string"], "Post Content");
doTypeCheck(isTrue, "boolean", "Whether the post is true");
doTypeCheck(changesToFollowers, ReactionValues, "Post's Change to Followers");
doTypeCheck(changesToCredibility, ReactionValues, "Post's Change to Credibility");
doTypeCheck(numberOfReactions, ReactionValues, "Post's Number of Reactions");
doTypeCheck(comments, Array, "Post's Comments");
this.id = id;
this.headline = headline;
this.content = content;
this.isTrue = isTrue;
this.changesToFollowers = changesToFollowers;
this.changesToCredibility = changesToCredibility;
this.numberOfReactions = numberOfReactions;
this.comments = comments;
}
static commentsToJSON(comments) {
const commentsJSON = [];
for (let index = 0; index < comments.length; ++index) {
commentsJSON.push(comments[index].toJSON())
}
return commentsJSON;
}
static commentsFromJSON(json) {
const comments = [];
for (let index = 0; index < json.length; ++index) {
comments.push(PostComment.fromJSON(json[index], index));
}
return comments;
}
toJSON() {
let contentJSON = this.content;
if (isOfType(contentJSON, [StudyImage, StudyImageMetadata])) {
contentJSON = contentJSON.toMetadata().toJSON();
}
return {
"id": this.id,
"headline": this.headline,
"content": contentJSON,
"isTrue": this.isTrue,
"changesToFollowers": this.changesToFollowers.toJSON(),
"changesToCredibility": this.changesToCredibility.toJSON(),
"numberOfReactions": this.numberOfReactions.toJSON(),
"comments": Post.commentsToJSON(this.comments)
};
}
static fromJSON(json) {
let content = json["content"];
if (!isOfType(content, "string")) {
content = StudyImageMetadata.fromJSON(content);
}
return new Post(
json["id"], json["headline"],
content, json["isTrue"],
ReactionValues.fromJSON(json["changesToFollowers"]),
ReactionValues.fromJSON(json["changesToCredibility"]),
ReactionValues.fromJSON(json["numberOfReactions"]),
Post.commentsFromJSON(json["comments"])
);
}
} |
JavaScript | class BrokenStudy {
id; // String
json; // JSON Object
error; // String
name; // String
description; // String
lastModifiedTime; // Number, UNIX Epoch Time in Seconds
constructor(id, json, error, name, description, lastModifiedTime) {
doTypeCheck(id, "string", "Invalid Study's ID");
doNonNullCheck(json, "Invalid Study's JSON");
doTypeCheck(error, "string", "Invalid Study's Error");
doNullableTypeCheck(name, "string", "Invalid Study's Name");
doNullableTypeCheck(description, "string", "Invalid Study's Description");
doNullableTypeCheck(lastModifiedTime, "number", "The last time the invalid study was modified");
this.id = id;
this.json = json;
this.error = error;
this.name = name || "Unknown Name";
this.description = description || "Missing Description";
this.lastModifiedTime = lastModifiedTime || 0;
}
static fromJSON(id, json, error) {
return new BrokenStudy(
id, json, error, json["name"], json["description"], json["lastModifiedTime"]
);
}
} |
JavaScript | class Study {
id; // String
authorID; // String
authorName; // String
name; // String
description; // String
lastModifiedTime; // Number (UNIX Epoch Time in Seconds)
enabled; // Boolean
prompt; // String
promptDelaySeconds; // Number
length; // Number
requireReactions; // Boolean
reactDelaySeconds; // Number
requireComments; // String
minimumCommentLength; // Number
requireIdentification; // Boolean
displayFollowers; // Boolean
displayCredibility; // Boolean
displayProgress; // Boolean
displayNumberOfReactions; // Boolean
postEnabledReactions; // {String: Boolean}
commentEnabledReactions; // {String: Boolean}
genCompletionCode; // Boolean
completionCodeDigits; // Number
genRandomDefaultAvatars; // Boolean
preIntro; // HTML String
preIntroDelaySeconds; // Number
rules; // HTML String
rulesDelaySeconds; // Number
postIntro; // HTML String
postIntroDelaySeconds; // Number
debrief; // HTML String
sourcePostSelectionMethod; // SourcePostSelectionMethod
sources; // Source[]
posts; // Post[]
/**
* This is a really long constructor, although it is only called
* twice (once from the excel reader, and once from the JSON reader).
* Additionally, all the parameters are required. Therefore, this
* is simpler than a builder would be. Perhaps grouping the parameters
* into functional groups could assist in simplifying this, although
* that seems like a lot of work for little gain.
*/
constructor(
id, authorID, authorName,
name, description, lastModifiedTime, enabled,
prompt, promptDelaySeconds, length,
requireReactions, reactDelaySeconds,
requireComments, minimumCommentLength,
requireIdentification,
displayFollowers, displayCredibility,
displayProgress, displayNumberOfReactions,
postEnabledReactions, commentEnabledReactions,
genCompletionCode, completionCodeDigits,
genRandomDefaultAvatars,
preIntro, preIntroDelaySeconds,
rules, rulesDelaySeconds,
postIntro, postIntroDelaySeconds,
debrief, sourcePostSelectionMethod,
sources, posts) {
if (requireComments) {
requireComments = requireComments.toLowerCase();
}
doTypeCheck(id, "string", "Study ID");
doTypeCheck(authorID, "string", "Study Author's ID");
doTypeCheck(authorName, "string", "Study Author's Name");
doTypeCheck(name, "string", "Study Name");
doTypeCheck(description, "string", "Study Description");
doNullableTypeCheck(lastModifiedTime, "number", "The last time the study was modified");
doNullableTypeCheck(enabled, "boolean", "Whether the study is enabled");
doTypeCheck(prompt, "string", "Study Prompt");
doTypeCheck(promptDelaySeconds, "number", "Study Prompt Continue Delay");
doTypeCheck(length, "number", "Study Length");
doTypeCheck(requireReactions, "boolean", "Whether the study requires reactions to posts");
doTypeCheck(reactDelaySeconds, "number", "Study Reaction Delay");
doEnumCheck(
requireComments, ["required", "optional", "disabled"],
"Whether comments are required, optional, or disabled"
);
doTypeCheck(minimumCommentLength, "number", "Minimum Comment Length");
doTypeCheck(requireIdentification, "boolean", "Whether the study requires identification");
doTypeCheck(displayFollowers, "boolean", "Whether to display followers");
doTypeCheck(displayCredibility, "boolean", "Whether to display credibility");
doTypeCheck(displayProgress, "boolean", "Whether to display progress");
doTypeCheck(displayNumberOfReactions, "boolean", "Whether to display number of reactions");
doTypeCheck(postEnabledReactions, "object", "The reactions enabled for posts");
doTypeCheck(postEnabledReactions["like"], "boolean", "Whether likes are enabled for posts");
doTypeCheck(postEnabledReactions["dislike"], "boolean", "Whether likes are enabled for posts");
doTypeCheck(postEnabledReactions["share"], "boolean", "Whether likes are enabled for posts");
doTypeCheck(postEnabledReactions["flag"], "boolean", "Whether likes are enabled for posts");
doTypeCheck(commentEnabledReactions, "object", "The reactions enabled for comments");
doTypeCheck(commentEnabledReactions["like"], "boolean", "Whether likes are enabled for comments");
doTypeCheck(commentEnabledReactions["dislike"], "boolean", "Whether likes are enabled for comments");
doTypeCheck(genCompletionCode, "boolean", "Whether the study generates a completion code");
doTypeCheck(completionCodeDigits, "number", "Study Completion Code Digits");
doTypeCheck(genRandomDefaultAvatars, "boolean", "Whether the study generates random default avatars for sources");
doTypeCheck(preIntro, "string", "Study Introduction before Game Rules");
doTypeCheck(preIntroDelaySeconds, "number", "Study Introduction before Game Rules Continue Delay");
doTypeCheck(rules, "string", "Game Rules");
doTypeCheck(rulesDelaySeconds, "number", "Game Rules Continue Delay");
doTypeCheck(postIntro, "string", "Study Introduction after Game Rules");
doTypeCheck(postIntroDelaySeconds, "number", "Study Introduction after Game Rules Continue Delay");
doTypeCheck(debrief, "string", "Study Debrief");
doTypeCheck(sourcePostSelectionMethod, SourcePostSelectionMethod, "Study Source/Post Selection Method");
doTypeCheck(sources, Array, "Study Sources");
doTypeCheck(posts, Array, "Study Posts");
this.id = id;
this.authorID = authorID;
this.authorName = authorName;
this.name = name;
this.description = description;
this.lastModifiedTime = lastModifiedTime || 0;
this.enabled = enabled || false;
this.prompt = prompt;
this.promptDelaySeconds = promptDelaySeconds;
this.length = length;
this.requireReactions = requireReactions;
this.reactDelaySeconds = reactDelaySeconds;
this.requireComments = requireComments;
this.minimumCommentLength = minimumCommentLength;
this.requireIdentification = requireIdentification;
this.displayFollowers = displayFollowers;
this.displayCredibility = displayCredibility;
this.displayProgress = displayProgress;
this.displayNumberOfReactions = displayNumberOfReactions;
this.postEnabledReactions = postEnabledReactions;
this.commentEnabledReactions = commentEnabledReactions;
this.genCompletionCode = genCompletionCode;
this.completionCodeDigits = completionCodeDigits;
this.genRandomDefaultAvatars = genRandomDefaultAvatars;
this.preIntro = preIntro;
this.preIntroDelaySeconds = preIntroDelaySeconds;
this.rules = rules;
this.rulesDelaySeconds = rulesDelaySeconds;
this.postIntro = postIntro;
this.postIntroDelaySeconds = postIntroDelaySeconds;
this.debrief = debrief;
this.sourcePostSelectionMethod = sourcePostSelectionMethod;
this.sources = sources;
this.posts = posts;
}
static convertEnabledReactionsToList(enabledReactions) {
const enabled = [];
for (let key in enabledReactions) {
if (enabledReactions.hasOwnProperty(key) && enabledReactions[key]) {
enabled.push(key);
}
}
return enabled;
}
getPostEnabledReactions() {
return Study.convertEnabledReactionsToList(this.postEnabledReactions);
}
getCommentEnabledReactions() {
return Study.convertEnabledReactionsToList(this.commentEnabledReactions);
}
areUserCommentsRequired() {
return this.requireComments === "required";
}
areUserCommentsOptional() {
return this.requireComments === "optional";
}
areUserCommentsEnabled() {
return this.areUserCommentsRequired() || this.areUserCommentsOptional();
}
areUserCommentsDisabled() {
return !this.areUserCommentsEnabled();
}
/**
* Updates the last modified time to now.
* This does not update the database.
*/
updateLastModifiedTime() {
this.lastModifiedTime = getUnixEpochTimeSeconds();
}
/**
* Finds the source with ID {@param sourceID}.
*/
getSource(sourceID) {
for (let index = 0; index < this.sources.length; ++index) {
const source = this.sources[index];
if (source.id === sourceID)
return source;
}
throw new Error("Unknown source ID " + sourceID);
}
/**
* Finds the post with ID {@param postID}.
*/
getPost(postID) {
for (let index = 0; index < this.posts.length; ++index) {
const post = this.posts[index];
if (post.id === postID)
return post;
}
throw new Error("Unknown post ID " + postID);
}
/**
* Generates a random completion code string for this study.
*/
generateRandomCompletionCode() {
if (!this.genCompletionCode)
throw new Error("Completion codes are disabled for this study");
return randDigits(this.completionCodeDigits);
}
/**
* Returns a list of all the paths to assets related
* to this study that are stored in Firebase Storage.
*/
getAllStoragePaths() {
const paths = [];
for (let index = 0; index < this.posts.length; ++index) {
const post = this.posts[index];
if (isOfType(post.content, "string"))
continue;
paths.push(StudyImage.getPath(
this, post.id, post.content.toMetadata()
));
}
for (let index = 0; index < this.sources.length; ++index) {
const source = this.sources[index];
if (!source.avatar)
continue;
paths.push(StudyImage.getPath(
this, source.id, source.avatar.toMetadata()
));
}
return paths;
}
static sourcesToJSON(sources) {
const sourcesJSON = [];
for (let index = 0; index < sources.length; ++index) {
doTypeCheck(sources[index], Source, "Source at index " + index);
sourcesJSON.push(sources[index].toJSON());
}
return sourcesJSON;
}
static sourcesFromJSON(json) {
const sources = [];
for (let index = 0; index < json.length; ++index) {
sources.push(Source.fromJSON(json[index]));
}
return sources;
}
static postsToJSON(posts) {
const postsJSON = [];
for (let index = 0; index < posts.length; ++index) {
doTypeCheck(posts[index], Post, "Post at index " + index);
postsJSON.push(posts[index].toJSON());
}
return postsJSON;
}
static postsFromJSON(json) {
const posts = [];
for (let index = 0; index < json.length; ++index) {
posts.push(Post.fromJSON(json[index]));
}
return posts;
}
/**
* This does _not_ include the full source and post
* information, just the base information.
*/
toJSON() {
return {
"authorID": this.authorID,
"authorName": this.authorName,
"name": this.name,
"description": this.description,
"lastModifiedTime": this.lastModifiedTime,
"enabled": this.enabled,
"prompt": this.prompt,
"promptDelaySeconds": this.promptDelaySeconds,
"length": this.length,
"requireReactions": this.requireReactions,
"reactDelaySeconds": this.reactDelaySeconds,
"requireComments": this.requireComments,
"minimumCommentLength": this.minimumCommentLength,
"requireIdentification": this.requireIdentification,
"displayFollowers": this.displayFollowers,
"displayCredibility": this.displayCredibility,
"displayProgress": this.displayProgress,
"displayNumberOfReactions": this.displayNumberOfReactions,
"postEnabledReactions": this.postEnabledReactions,
"commentEnabledReactions": this.commentEnabledReactions,
"genCompletionCode": this.genCompletionCode,
"completionCodeDigits": this.completionCodeDigits,
"genRandomDefaultAvatars": this.genRandomDefaultAvatars,
"preIntro": this.preIntro,
"preIntroDelaySeconds": this.preIntroDelaySeconds,
"rules": this.rules,
"rulesDelaySeconds": this.rulesDelaySeconds,
"postIntro": this.postIntro,
"postIntroDelaySeconds": this.postIntroDelaySeconds,
"debrief": this.debrief,
"sourcePostSelectionMethod": this.sourcePostSelectionMethod.toJSON(),
"sources": Study.sourcesToJSON(this.sources),
"posts": Study.postsToJSON(this.posts)
}
}
static fromJSON(id, json) {
const randDefaultAvatars = json["genRandomDefaultAvatars"];
return new Study(
id, json["authorID"], json["authorName"],
json["name"], json["description"],
json["lastModifiedTime"], json["enabled"],
json["prompt"], json["promptDelaySeconds"],
json["length"],
json["requireReactions"], json["reactDelaySeconds"],
json["requireComments"], json["minimumCommentLength"],
json["requireIdentification"],
json["displayFollowers"], json["displayCredibility"],
json["displayProgress"], json["displayNumberOfReactions"],
json["postEnabledReactions"], json["commentEnabledReactions"],
json["genCompletionCode"], json["completionCodeDigits"],
(randDefaultAvatars === undefined ? true : randDefaultAvatars),
json["preIntro"], json["preIntroDelaySeconds"],
json["rules"] || "", json["rulesDelaySeconds"] || 0,
json["postIntro"], json["postIntroDelaySeconds"],
json["debrief"],
SourcePostSelectionMethod.fromJSON(json["sourcePostSelectionMethod"]),
Study.sourcesFromJSON(json["sources"]),
Study.postsFromJSON(json["posts"])
);
}
} |
JavaScript | class UserOperations {
constructor(user, settings) {
this.user = user;
this.settings = settings;
}
/**
* Determine if we can change the scene and warp, pan, etc. for the current
* user.
*
* @param {string} sceneId
* The target scene ID.
*
* @return {boolean}
* If we should change the scene or not.
*/
canChangeGameForUser(sceneId) {
if (
this.user.isGM
|| this.user.viewedScene === sceneId
) {
return true;
}
const warpPlayers = this.settings.get(
Constants.MODULE_NAME,
'warp-players',
);
return !!warpPlayers;
}
} |
JavaScript | class ProductCtrl {
constructor(
$scope,
$timeout,
DomService,
ApiService
) {
this.$scope = $scope;
this.$timeout = $timeout;
this.domService = DomService;
this.apiService = ApiService;
this.product = window.product || { bristles: [], colors: [] };
if (this.product.bristles.length) {
this.bristle = this.product.bristles[0];
}
if (this.product.colors.length) {
this.color = this.product.colors[0];
}
$scope.$on('destroy', () => {});
}
get bristle() {
return this.bristle_;
}
set bristle(bristle) {
if (this.bristle_ !== bristle) {
this.bristle_ = bristle;
this.$scope.$broadcast('onBristle', bristle);
}
}
get color() {
return this.color_;
}
set color(color) {
if (this.color_ !== color) {
this.color_ = color;
this.$scope.$broadcast('onColor', color);
}
}
} |
JavaScript | class EventDetailDataItemAllOf {
/**
* Constructs a new <code>EventDetailDataItemAllOf</code>.
* @alias module:model/EventDetailDataItemAllOf
* @param created {Date} Date/Time in UTC the event was first recorded in our data store.
* @param updated {Date} Date/Time in UTC the event was last updated.
* @param details {Object.<String, Object>} Signal specific event properties.
*/
constructor(created, updated, details) {
EventDetailDataItemAllOf.initialize(this, created, updated, details);
}
/**
* 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, created, updated, details) {
obj['created'] = created;
obj['updated'] = updated;
obj['details'] = details;
}
/**
* Constructs a <code>EventDetailDataItemAllOf</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/EventDetailDataItemAllOf} obj Optional instance to populate.
* @return {module:model/EventDetailDataItemAllOf} The populated <code>EventDetailDataItemAllOf</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new EventDetailDataItemAllOf();
if (data.hasOwnProperty('created')) {
obj['created'] = ApiClient.convertToType(data['created'], 'Date');
}
if (data.hasOwnProperty('updated')) {
obj['updated'] = ApiClient.convertToType(data['updated'], 'Date');
}
if (data.hasOwnProperty('details')) {
obj['details'] = ApiClient.convertToType(data['details'], {'String': Object});
}
}
return obj;
}
} |
JavaScript | class CardAction extends PlayTypeAbility {
constructor(game, card, properties, isJob = false) {
super(game, card, properties);
this.title = properties.title;
if(this.isCardAbility()) {
this.usage = new AbilityUsage(properties, this.playType);
}
this.anyPlayer = properties.anyPlayer || false;
this.condition = properties.condition;
this.ifCondition = properties.ifCondition;
this.ifFailMessage = properties.ifFailMessage;
this.clickToActivate = !!properties.clickToActivate;
if(properties.location) {
if(Array.isArray(properties.location)) {
this.location = properties.location;
} else {
this.location = [properties.location];
}
} else if(card.getType() === 'action') {
this.location = ['hand'];
} else {
this.location = ['play area'];
}
this.events = new EventRegistrar(game, this);
this.activationContexts = [];
if(card.getType() === 'action') {
this.cost = this.cost.concat(Costs.playAction());
}
if(!this.gameAction) {
if(card.getType() !== 'spell' && !isJob) {
throw new Error('Actions must have a `gameAction` or `handler` property.');
} else {
this.gameAction = new HandlerGameActionWrapper({ handler: () => true });
}
}
}
defaultCondition() {
if(this.playType.includes('cheatin resolution')) {
return this.card.controller.canPlayCheatinResolution();
}
if(this.game.isShootoutPlayWindow() && !this.playType.includes('shootout:join') && CardTypesForShootout.includes(this.card.getType())) {
return this.game.shootout.isInShootout(this.card);
}
return true;
}
isLocationValid(location) {
return this.location.includes(location);
}
allowMenu() {
return this.isLocationValid(this.card.location);
}
allowPlayer(player) {
return this.card.controller === player || this.anyPlayer;
}
meetsRequirements(context) {
if(!super.meetsRequirements(context)) {
return false;
}
if(this.card.hasKeyword('headline') && this.game.shootout.headlineUsed) {
return false;
}
if(this.isCardAbility() && !context.player.canTrigger(this)) {
return false;
}
if(!this.options.allowUsed && this.usage.isUsed()) {
return false;
}
if(!this.allowPlayer(context.player)) {
return false;
}
if(this.card.getType() === 'action' && !context.player.isCardInPlayableLocation(this.card, 'play')) {
return false;
}
if(this.card.getType() !== 'action' && !this.isLocationValid(this.card.location)) {
return false;
}
if(this.card.isAnyBlank()) {
return false ;
}
if(!this.defaultCondition()) {
return false;
}
if(this.condition && !this.condition(context)) {
return false;
}
return this.canResolvePlayer(context) && this.canPayCosts(context) && this.canResolveTargets(context) && this.gameAction.allow(context);
}
// Main execute function that excutes the ability. Once the targets are selected, the executeHandler is called.
execute(player) {
var context = this.createContext(player);
if(!this.meetsRequirements(context)) {
return false;
}
this.activationContexts.push(context);
this.game.resolveAbility(this, context);
return true;
}
executeHandler(context) {
if(!this.ifCondition || this.ifCondition(context)) {
super.executeHandler(context);
} else {
let formattedCancelMessage = AbilityMessage.create(this.ifFailMessage || '{player} uses {source} but fails to meet requirements');
formattedCancelMessage.output(context.game, context);
}
this.usage.increment();
}
getMenuItem(arg, player) {
let context = this.createContext(player);
return {
text: this.title,
method: 'doAction',
arg: arg,
anyPlayer: !!this.anyPlayer,
disabled: !this.meetsRequirements(context)
};
}
isAction() {
return true;
}
isTriggeredAbility() {
return true;
}
isClickToActivate() {
return this.clickToActivate;
}
isPlayableActionAbility() {
return this.card.getType() === 'action' && this.isLocationValid('hand');
}
incrementLimit() {
if(!this.isLocationValid(this.card.location)) {
return;
}
super.incrementLimit();
}
deactivate(player) {
if(this.activationContexts.length === 0) {
return false;
}
var context = this.activationContexts[this.activationContexts.length - 1];
if(!context || player !== context.player) {
return false;
}
if(this.canUnpayCosts(context)) {
this.unpayCosts(context);
context.abilityDeactivated = true;
return true;
}
return false;
}
onBeginRound() {
this.activationContexts = [];
}
isEventListeningLocation(location) {
return this.isLocationValid(location);
}
registerEvents() {
this.events.register(['onBeginRound']);
if(this.usage) {
this.usage.registerEvents(this.game);
}
}
unregisterEvents() {
this.events.unregisterAll();
if(this.usage) {
this.usage.unregisterEvents(this.game);
}
}
} |
JavaScript | class SPA extends App {
/**
* Create a single-page app.
* @param {Object} [settings={}] Settings for the application.
* @param {String} [settings.name="@fabric/maki"] Name of the app.
* @param {Boolean} [settings.offline=true] Hint offline mode to browsers.
* @param {Object} [components] Map of Web Components for the application to utilize.
* @return {App} Instance of the application.
*/
constructor (settings = {}) {
super(settings);
// Assist in debugging
if (settings.verbosity >= 4) console.log('[WEB:SPA]', 'Creating instance with constructor settings:', settings);
// Assign defaults
this.settings = Object.assign({
name: "@fabric/maki",
authority: 'localhost.localdomain:9999',
persistent: true,
// TODO: enable by default?
websockets: false,
secure: false, // TODO: default to secure (i.e., TLS on all connections)
components: {}
}, config, settings);
// TODO: enable Web Worker integration
/* this.worker = new Worker('./worker', {
type: 'module'
}); */
this.bridge = new Bridge(this.settings);
this.router = new Router(this.settings);
this.store = new Store(this.settings);
this.routes = [];
this.bindings = {
'click': this._handleClick.bind(this)
};
return this;
}
// TODO: reconcile with super(), document use of constructor vs. CustomElements
init (settings = {}) {
if (settings && settings.verbosity >= 5) console.trace('[WEB:SPA]', 'Calling init() with settings:', settings);
this.bridge = new Bridge(this.settings);
this.browser = new Browser(this.settings);
this.store = new Store(Object.assign({}, this.settings, { path: './stores/spa' }));
this.settings = Object.assign({}, this.settings, settings);
this._state = (window.app && window.app.state) ? window.app.state : {};
}
get handler () {
return page;
}
set state (state) {
if (!state) throw new Error('State must be provided.');
this._state = state;
this._redraw(this._state);
}
get state () {
return Object.assign({}, this._state);
}
define (name, definition) {
if (this.settings.verbosity >= 5) console.trace('[WEB:SPA]', 'Defining for SPA:', name, definition);
// TODO: check for async compatibility in HTTP.App
super.define(name, definition);
let resource = new Resource(definition);
let snapshot = Object.assign({
name: name,
names: { plural: pluralize(name) }
}, resource);
let address = snapshot.routes.list.split('/')[1];
// TODO: reconcile with server.define
// if (this.settings.verbosity >= 5) console.log('[WEB:SPA]', 'Defining for SPA:', name, definition);
let route = this.router.define(name, definition);
// if (this.settings.verbosity >= 5) console.log('[WEB:SPA]', 'Defined:', name, route);
this.types.state[name] = definition;
this.resources[name] = definition;
this.state[address] = {};
return this.resources[name];
}
// TODO: document this vs. @fabric/core/types/app
_defineElement (handle, definition) {
this.components[handle] = definition;
// TODO: custom elements polyfill
if (typeof customElements !== 'undefined') {
try {
customElements.define(handle, definition);
} catch (E) {
console.error('[MAKI:APP]', 'Could not define Custom Element:', E, handle, definition);
}
}
}
register () {
return this;
}
route (path) {
for (let i = 0; i < this.routes.length; i++) {
console.log('[MAKI:SPA]', 'testing route:', this.routes[i]);
}
}
disconnectedCallback () {
for (let name in this._boundFunctions) {
this.removeEventListener('message', this._boundFunctions[name]);
}
}
_handleClick (e) {
console.log('SPA CLICK EVENT:', e);
}
async _handleNavigation (ctx) {
let address = await this.browser.route(ctx.path);
let element = document.createElement(address.route.component);
this.target = element;
this.browser._setAddress(ctx.path);
this.browser._setElement(element);
element.state = (typeof window !== 'undefined' && window.app) ? window.app.state : this.state;
}
/* async _loadIndex (ctx) {
console.log('[WEB:SPA]','loading index, app:', this);
console.log('[WEB:SPA]','loading index, app.settings:', this.settings);
console.log('[WEB:SPA]','loading index, ctx:', ctx);
console.log('[WEB:SPA]','all components:', Object.keys(this.components));
console.log('[WEB:SPA]','Seeking for index:', this.settings.components.index);
let address = await this.browser.route(ctx.path);
let Index = this.components[this.settings.components.index];
if (!Index) throw new Error(`Could not find component: ${this.settings.components.index}`);
let resource = new Index(this.state);
let content = resource.render();
// this._setTitle(resource.name);
// this._renderContent(content);
let element = document.createElement(address.route.component);
console.log('created element:', element);
this.target = element;
this.browser._setAddress(ctx.path);
this.browser._setElement(element);
for (let name in this.state) {
element.state[name] = this.state[name];
}
} */
_setTitle (title) {
this.title = `${title} · ${this.settings.name}`;
document.querySelector('title').innerHTML = this.title;
}
_redraw (state = {}) {
if (!state) state = this.state;
// if (this.settings && this.settings.verbosity >= 5) console.log('[HTTP:SPA]', 'redrawing with state:', state);
this.innerHTML = this._getInnerHTML(state);
// this.init(state);
return this;
}
_renderContent (html) {
// TODO: enable multi-view composition?
// NOTE: this means to iterate over all bound targets, instead of the first one...
if (!this.target) this.target = document.querySelector(BROWSER_TARGET);
if (!this.target) return console.log('COULD NOT ACQUIRE TARGET:', document);
this.target.innerHTML = html;
return this.target;
}
_renderWith (html) {
let hash = crypto.createHash('sha256').update(html).digest('hex');
// TODO: move CSS to inline from webpack
return `<!DOCTYPE html>
<html lang="${this.settings.language}"${(this.settings.offline) ? 'manifest="cache.manifest"' : ''}>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>${this.title}</title>
<!-- <link rel="manifest" href="/manifest.json"> -->
<link rel="stylesheet" type="text/css" href="/styles/screen.css" />
<link rel="stylesheet" type="text/css" href="/styles/semantic.css" />
</head>
<body data-bind="${hash}">${html}</body>
<script type="text/javascript" src="/scripts/jquery-3.4.1.js"></script>
<script type="text/javascript" src="/scripts/semantic.js"></script>
</html>`;
}
/**
* Return a string of HTML for the application.
* @return {String} Fully-rendered HTML document.
*/
render () {
let body = super.render();
// TODO: define Custom Element
// let app = SPA.toString('base64');
// definition = customElements.define(name, SPA);
return this._renderWith(body);
}
async stop () {
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Stopping...');
try {
if (this.settings.verbosity >= 5) console.log('[HTTP:SPA]', 'Stopping bridge...');
await this.bridge.stop();
} catch (E) {
console.error('Could not stop SPA bridge:', E);
}
try {
if (this.settings.verbosity >= 5) console.log('[HTTP:SPA]', 'Stopping router...');
await this.router.stop();
} catch (E) {
console.error('Could not stop SPA router:', E);
}
try {
if (this.settings.verbosity >= 5) console.log('[HTTP:SPA]', 'Stopping store...');
await this.store.stop();
} catch (E) {
console.error('Could not stop SPA store:', E);
}
// await super.stop();
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Stopped!');
return this;
}
async _handleBridgeMessage (msg) {
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Handling message from Bridge:', msg);
if (!msg.type && msg['@type']) msg.type = msg['@type'];
if (!msg.data && msg['@data']) msg.data = msg['@data'];
switch (msg.type) {
default:
console.warn('[HTTP:SPA]', 'Unhandled message type (origin: bridge)', msg.type);
break;
case 'Receipt':
console.log('Receipt for your message:', msg);
break;
case 'Pong':
console.log('Received pong:', msg.data);
let time = new Date(msg.data / 1000);
console.log('time:', time, time.toISOString());
case 'Ping':
const now = Date.now();
const message = Message.fromVector(['Pong', now.toString()]);
const pong = JSON.stringify(message.toObject());
this.bridge.send(pong);
break;
case 'State':
console.log('RAD STATE:', msg);
this.state = msg.data;
break;
case 'Transaction':
this._applyChanges(msg['@data']['changes']);
await this.commit();
break;
case 'GenericMessage':
console.warn('[AUDIT]', 'GENERIC MESSAGE:', msg);
break;
}
}
async start () {
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Starting...');
// await super.start();
this.on('error', (error) => {
console.error('got error:', error);
});
this.bridge.on('message', this._handleBridgeMessage.bind(this));
if (this.settings.persistent) {
try {
if (this.settings.verbosity >= 5) console.log('[HTTP:SPA]', 'Starting bridge...');
await this.store.start();
} catch (E) {
console.error('Could not start SPA store:', E);
}
}
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Defining resources from settings...');
/* Resources */
for (let name in this.settings.resources) {
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Defining Resource:', name);
let definition = this.settings.resources[name];
let plural = pluralize(name);
let resource = await this.define(name, definition);
// console.log('[AUDIT]', 'Created resource:', resource);
// this.router._addFlat(`/${plural.toLowerCase()}`, definition);
this.router._addRoute(`/${plural.toLowerCase()}/:id`, definition.components.view);
this.router._addRoute(`/${plural.toLowerCase()}`, definition.components.list);
// add menu items & handler
if (!definition.hidden) {
this.menu._addItem({ name: plural, path: `/${plural.toLowerCase()}`, icon: definition.icon });
}
// page.js router...
this.handler(`/${plural.toLowerCase()}`, this._handleNavigation.bind(this));
this.handler(`/${plural.toLowerCase()}/:id`, this._handleNavigation.bind(this));
}
/* Components */
for (let name in this.settings.components) {
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Defining Component:', name);
let definition = this.settings.components[name];
// TODO: consider async _defineElement (define at `function _defineElement`)
let component = this._defineElement(name, definition);
}
/* Services */
try {
if (this.settings.verbosity >= 5) console.log('[HTTP:SPA]', 'Starting router...');
await this.router.start();
} catch (E) {
console.error('Could not start SPA router:', E);
}
if (this.settings.websockets) {
try {
if (this.settings.verbosity >= 5) console.log('[HTTP:SPA]', 'Starting bridge...');
this.bridge.start();
} catch (exception) {
console.error('Could not connect to bridge:', exception);
}
}
/* HTML-specific traits */
// Set page title
this.title = `${this.settings.synopsis} · ${this.settings.name}`;
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Started!');
return this;
}
} |
JavaScript | class Biddings extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
catalogue: [],
currentIndex: 0,
itemShow: 3,
random: 0,
loading: true,
error: null,
token: "",
file:""
};
}
upload(e) {
console.log(e.target.files[0]);
}
uploadImageS3 = (e) => {
const ReactS3Client = new S3(config);
/* Notice that if you don't provide a dirName, the file will be automatically uploaded to the root of your bucket */
/* This is optional */
const newFileName = 'test-file';
console.log(e.target.files[0]);
ReactS3Client
.uploadFile(e.target.files[0],newFileName)
.then(data => console.log(data))
.catch(err => console.error(err))
/**
* {
* Response: {
* bucket: "myBucket",
* key: "image/test-image.jpg",
* location: "https://myBucket.s3.amazonaws.com/media/test-file.jpg"
* }
* }
*/
}
fetchToken = async () => {
const res = await axios.post('http://desmond.business:8080/fyp/authenticate', {
"username": "des123",
"password": "password"
})
return res;
}
fetchBiddings = async () => {
/*
const authUrl = 'http://desmond.business:8080/fyp/authenticate';
const getBiddingsUrl = 'http://desmond.business:8080/fyp/getBiddings';
let userAuth = {
"username": "des123",
"password": "password"
};
axios.post(authUrl, userAuth).then(response => {
console.log(response.data.token);
let config = {
headers: {
"Authorization": `Bearer${response.data.token}`
}
}
console.log(config);
axios.get(getBiddingsUrl, config).then(result => {
console.log(result);
}
).catch(err => {
console.log(err);
})
})
*/
axios.get("http://desmond.business:8080/fyp/getBiddings")
.then(res => {
// Transform the raw data by extracting the nested posts
const updateCatalogue = this.state.catalogue
const posts = res.data.results;
for (var i = 0; i < this.state.itemShow; i++) {
//console.log(this.state.itemSHow)
//console.log("i=" + i)
const min = 0;
const max = posts.length;
const rand = parseInt(min + Math.random() * (max - min))
//console.log("rand" + rand)
updateCatalogue.push(
<Col key={posts[rand].id} className="col-md-4">
<Card style={{ width: '20rem' }}>
<CardImg top src={require("assets/img/mac_apple.jpg")} alt="..." />
<CardBody>
<CardTitle>{posts[rand].title}</CardTitle>
<CardText>{posts[rand].create_timestamp}</CardText>
<Link to={`/CarsforSale/${posts[rand].id}`}>
<Button color="primary">
${posts[rand].selling_price}
</Button>
</Link>
</CardBody>
</Card>
</Col>
)
}
//console.log(this.state.catalogue);
//console.log(posts);
// Update state to trigger a re-render.
// Clear any errors, and turn off the loading indiciator.
this.setState({
posts,
catalogue: updateCatalogue,
loading: false,
error: null
});
})
.catch(err => {
// Something went wrong. Save the error in state and re-render.
this.setState({
loading: false,
error: err
});
});
}
componentDidMount() {
// Remove the 'www.' to cause a CORS error (and see the error state)
this.fetchBiddings()
}
showMore = () => {
this.fetchBiddings()
//console.log(this.state.catalogue);
//console.log(this.state.currentIndex);
}
renderLoading() {
return <div>Loading...</div>;
}
renderError() {
return (
<div>
Uh oh: {this.state.error.message}
</div>
);
}
renderPosts() {
if (this.state.error) {
return this.renderError();
}
//console.log(this.state.posts[0]);
return (
<h6>
Success getting Bidding Records
</h6>
);
}
render() {
const catalogue = this.state.catalogue
if (this.state.loading) {
return (
<div className="section">
<Container className="text-center">
<Card className="text-center">
<Row>
<Col>
<div className="title">
<h1 className="bd-title">{this.props.title}</h1>
<input
type="file"
onChange={this.uploadImageS3}
/>
</div>
</Col>
</Row>
<div>
<Spinner animation="border" variant="primary" />
</div>
</Card>
</Container>
</div>
)
} else {
return (
<div className="section">
<Container className="text-center">
<Card className="text-center">
<Row>
<Col>
<div className="title">
<h1 className="bd-title">{this.props.title}</h1>
</div>
</Col>
</Row>
<CardBody>
<Row>
{catalogue}
</Row>
</CardBody>
</Card>
</Container>
</div>
);
}
}
} |
JavaScript | class ContainerExecRequest {
/**
* Create a ContainerExecRequest.
* @member {string} [command] The command to be executed.
* @member {object} [terminalSize] The size of the terminal.
* @member {number} [terminalSize.rows] The row size of the terminal
* @member {number} [terminalSize.cols] The column size of the terminal
*/
constructor() {
}
/**
* Defines the metadata of ContainerExecRequest
*
* @returns {object} metadata of ContainerExecRequest
*
*/
mapper() {
return {
required: false,
serializedName: 'ContainerExecRequest',
type: {
name: 'Composite',
className: 'ContainerExecRequest',
modelProperties: {
command: {
required: false,
serializedName: 'command',
type: {
name: 'String'
}
},
terminalSize: {
required: false,
serializedName: 'terminalSize',
type: {
name: 'Composite',
className: 'ContainerExecRequestTerminalSize'
}
}
}
}
};
}
} |
JavaScript | class ApiStoreEndpointListOperationsEvent extends ApiStoreContextEvent {
/**
* @returns {string} Endpoint's domain id or its path used to initialize this event.
*/
get pathOrId() {
return this[idValue];
}
/**
* @param {string} pathOrId The domain id of the endpoint to list operations from or its path.
*/
constructor(pathOrId) {
super(EventTypes.Endpoint.listOperations);
this[idValue] = pathOrId;
}
} |
JavaScript | class ApiStoreEndpointAddEvent extends ApiStoreContextEvent {
/**
* @returns {EndPointInit} Endpoint init definition used to initialize this event.
*/
get init() {
return this[initValue];
}
/**
* @param {EndPointInit} endpointInit The endpoint init definition
*/
constructor(endpointInit) {
super(EventTypes.Endpoint.add);
this[initValue] = Object.freeze({ ...endpointInit });
}
} |
JavaScript | class ApiStoreEndpointDeleteEvent extends ApiStoreContextEvent {
/**
* @returns {string} Endpoint id used to initialize this event.
*/
get id() {
return this[idValue];
}
/**
* @param {string} endpointId The id of the endpoint to remove.
*/
constructor(endpointId) {
super(EventTypes.Endpoint.delete);
this[idValue] = endpointId;
}
} |
JavaScript | class ApiStoreEndpointReadEvent extends ApiStoreContextEvent {
/**
* @returns {string} The domain id of the endpoint or its path used to initialize this event.
*/
get pathOrId() {
return this[idValue];
}
/**
* @param {string} pathOrId The domain id of the endpoint or its path.
*/
constructor(pathOrId) {
super(EventTypes.Endpoint.get);
this[idValue] = pathOrId;
}
} |
JavaScript | class ApiStoreEndpointUpdateEvent extends ApiStoreContextEvent {
/**
* @returns {string} The domain id of the endpoint used to initialize this event.
*/
get id() {
return this[idValue];
}
/**
* @returns {string} The property name to update used to initialize this event.
*/
get property() {
return this[propertyValue];
}
/**
* @returns {any} The new value to set used to initialize this event.
*/
get value() {
return this[valueValue];
}
/**
* @param {string} endpointId The domain id of the endpoint.
* @param {string} property The property name to update
* @param {any} value The new value to set.
*/
constructor(endpointId, property, value) {
super(EventTypes.Endpoint.update);
this[idValue] = endpointId;
this[propertyValue] = property;
this[valueValue] = value;
}
} |
JavaScript | class ApiStoreOperationCreateEvent extends ApiStoreContextEvent {
/**
* @param {string} pathOrId The path or domain id of the endpoint that is the parent of the operation.
* @param {OperationInit} init The object initialization properties.
*/
constructor(pathOrId, init) {
super(EventTypes.Endpoint.addOperation, { pathOrId, init });
}
} |
JavaScript | class Trends {
/**
* Constructs a new <code>Trends</code>.
* @alias module:model/Trends
*/
constructor() {
Trends.initialize(this);
}
/**
* 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) {
}
/**
* Constructs a <code>Trends</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/Trends} obj Optional instance to populate.
* @return {module:model/Trends} The populated <code>Trends</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new Trends();
if (data.hasOwnProperty('field')) {
obj['field'] = ApiClient.convertToType(data['field'], 'String');
if ('field' !== 'field') {
Object.defineProperty(obj, 'field', {
get() {
return obj['field'];
}
});
}
}
if (data.hasOwnProperty('published_at.end')) {
obj['published_at.end'] = ApiClient.convertToType(data['published_at.end'], 'Date');
if ('published_at.end' !== 'publishedAtEnd') {
Object.defineProperty(obj, 'publishedAtEnd', {
get() {
return obj['published_at.end'];
}
});
}
}
if (data.hasOwnProperty('published_at.start')) {
obj['published_at.start'] = ApiClient.convertToType(data['published_at.start'], 'Date');
if ('published_at.start' !== 'publishedAtStart') {
Object.defineProperty(obj, 'publishedAtStart', {
get() {
return obj['published_at.start'];
}
});
}
}
if (data.hasOwnProperty('trends')) {
obj['trends'] = ApiClient.convertToType(data['trends'], [Trend]);
if ('trends' !== 'trends') {
Object.defineProperty(obj, 'trends', {
get() {
return obj['trends'];
}
});
}
}
}
return obj;
}
} |
JavaScript | class Rectangle {
constructor(rect) {
this.x = rect.x;
this.y = rect.y;
this.width = rect.width;
this.height = rect.height;
this.color = rect.color;
}
} |
JavaScript | class RDFTransformResourceDialog {
#strText;
#elemPosition;
#strDefault;
#strLookForType;
#projectID;
/** @type RDFTransformDialog */
#dialog;
#onDone;
constructor(strText, elemPosition, strDefault, strLookForType, projectID, dialog, onDone) {
this.#strText = strText;
this.#elemPosition = elemPosition;
this.#strDefault = strDefault;
this.#strLookForType = strLookForType;
this.#projectID = projectID;
this.#dialog = dialog;
this.#onDone = onDone;
}
show() {
// Can we finish? If not, there is no point in continuing...
if ( ! this.#onDone ) {
alert(
$.i18n('rdft-dialog/error') + "\n" +
$.i18n("rdft-dialog/missing-proc") );
return;
}
var menu = MenuSystem.createMenu().width('331px'); // ...331px fits Suggest Term
menu.html(
'<div id="rdf-transform-menu-search" class="rdf-transform-menu-search">' +
'<span>' +
$.i18n('rdft-dialog/search-for') + ' ' + this.#strLookForType + ":" +
'</span>' +
'<input type="text" bind="rdftNewResourceIRI" >' +
'</div>'
);
MenuSystem.showMenu(menu, () => {} );
MenuSystem.positionMenuLeftRight(menu, $(this.#elemPosition));
var elements = DOM.bind(menu);
elements.rdftNewResourceIRI
.val(this.#strDefault)
.suggestTerm(
{ "project" : this.#projectID.toString(),
"type" : this.#strLookForType,
"parent" : '.rdf-transform-menu-search'
}
)
.bind('fb-select', // ...select existing item...
async (evt, data) => {
// Variable "data" is a JSON object from the RDFTransform SearchResultItem class
// containing key:value entries:
// iri, label, desc, prefix, namespace, localPart, description
MenuSystem.dismissAll();
var strIRI = null;
var strLabel = null;
var strDesc = null;
var strPrefix = null;
var strNamespace = null;
var strLocalPart = null;
var strLongDescription = null;
if ( data !== null && typeof data === 'object' && !Array.isArray(data) ) {
if (RDFTransform.gstrIRI in data) {
strIRI = data.iri;
}
if ("label" in data) {
strLabel = data.label;
}
if ("desc" in data) {
strDesc = data.desc;
}
if (RDFTransform.gstrPrefix in data) {
strPrefix = data.prefix;
}
if ("namespace" in data) {
strNamespace = data.namespace;
}
if (RDFTransform.gstrLocalPart in data) {
strLocalPart = data.localPart;
}
if ("description" in data) {
strLongDescription = data.description;
}
}
/* DEBUG
alert("DEBUG: Select: Existing Item:\n" +
" IRI: " + strIRI + "\n" +
" Label: " + strLabel + "\n" +
" Desc: " + strDesc + "\n" +
"Prefix: " + strPrefix + "\n" +
" NS: " + strNamespace + "\n" +
" lPart: " + strLocalPart + "\n" +
" LDesc: " + strLongDescription
);
*/
/** @type {{prefix?: string, localPart?: string}} */
var obj = null;
if (strLocalPart) { // ...not null or ""
if (strPrefix != null) {
// Prefixed...
obj = {};
obj.prefix = strPrefix;
obj.localPart = strLocalPart;
}
else if (strNamespace != null) {
// Not Prefixed: Full IRI...
obj = {};
obj.prefix = null;
obj.localPart = strNamespace + strLocalPart;
}
}
else if (strIRI) {
// Full IRI...
//await this.#extractPrefixLocalPart(strIRI," IRI: ");
obj = {};
obj.prefix = null; // No Prefix
obj.localPart = strIRI; // Full IRI
}
if (obj !== null) {
// Process existing or not-added IRI object...
this.#onDone(obj);
}
else {
alert(
$.i18n('rdft-dialog/alert-iri') + "\n" +
$.i18n('rdft-dialog/alert-iri-invalid') + "\n" +
"The selection does not have a valid Resource object!\n" + // TODO: $.i18n()
"IRI: " + strIRI
);
}
}
)
.bind('fb-select-new', // ...add new item...
async (evt, data) => {
// Variable "data" is the raw IRI input value from the dialog
var strIRI = null;
var strLabel = null;
var strDesc = null;
var strPrefix = null;
var strNamespace = null;
var strLocalPart = null;
var strLongDescription = null;
// If there is a possible IRI...
if ( data !== null && typeof data === 'string' ) {
strIRI = data;
// A leading ':' for Base IRI encoding is an invalid IRI, so remove for test...
var strTestIRI = strIRI;
const bBaseIRI = (strIRI[0] === ':');
if (bBaseIRI) {
strTestIRI = strIRI.substring(1);
}
// Does the IRI look like a prefixed IRI?
// 1 : Yes | 0 : No, but IRI | -1 : Not an IRI
var iPrefixedIRI = await RDFTransformCommon.isPrefixedQName(strTestIRI);
// Is it an IRI?
if ( iPrefixedIRI >= 0 ) {
MenuSystem.dismissAll();
// If it's a good BaseIRI prefixed IRI...
if (bBaseIRI) {
iPrefixedIRI = 2; // ...then it's a BaseIRI prefixed IRI
}
// Is it a prefixed IRI?
if ( iPrefixedIRI === 1 ) {
// Divide the IRI into Prefix and LocalPart portions...
strPrefix = RDFTransformCommon.getPrefixFromQName(strIRI);
strLocalPart = RDFTransformCommon.getSuffixFromQName(strIRI);
// Get the Namespace of the Prefix...
strNamespace = this.#dialog.getNamespacesManager().getNamespaceOfPrefix(strPrefix);
// Get the Full IRI from the Prefixed IRI...
strIRI =
RDFTransformCommon.getFullIRIFromQName(
strIRI,
this.#dialog.getBaseIRI(),
this.#dialog.getNamespacesManager().getNamespaces()
);
strLabel = strIRI;
}
// or Is it an BaseIRI prefixed IRI?
else if ( iPrefixedIRI === 2 ) {
strPrefix = ""; // ...use Base IRI Prefix
strNamespace = this.#dialog.getBaseIRI();
strLocalPart = strIRI.substring(1);
strLabel = strIRI;
strIRI = strNamespace + strLocalPart;
}
// or Is it an non-prefixed IRI?
else if ( iPrefixedIRI === 0 ) {
strLabel = strIRI; // ...take it as is...
}
}
// Otherwise, it's a BAD IRI!
}
/* DEBUG
alert("DEBUG: Select New: Add Item:\n" +
" IRI: " + strIRI + "\n" +
" Label: " + strLabel + "\n" +
" Desc: " + strDesc + "\n" +
"Prefix: " + strPrefix + "\n" +
" NS: " + strNamespace + "\n" +
" lPart: " + strLocalPart + "\n" +
" LDesc: " + strLongDescription
);
*/
/** @type {{prefix?: string, localPart?: string}} */
var obj = null;
// If there are valid parts decribed from the given IRI...
if (strLocalPart) { // ...not null or ""
// Is there an existing prefix matching the given prefix?
if ( strPrefix === "" || this.#dialog.getNamespacesManager().hasPrefix(strPrefix) ) {
// ...yes (BaseIRI or already managed namespace), add resource...
obj = {};
obj.prefix = strPrefix;
obj.localPart = strLocalPart;
}
// No, then this prefix is not using the BaseIRI prefix and is not managed...
else if (strPrefix) {
// ...create prefix (which may change in here) and add (re-prefixed) resource...
//
// NOTE: We are passing a function to RDFTransformNamespacesManager.addNamespace() which,
// in turn, passes it in an event function to RDFTransformNamespaceAdder.show().
this.#dialog.getNamespacesManager().addNamespace(
$.i18n('rdft-dialog/unknown-pref') + ': <em>' + strPrefix + '</em> ',
strPrefix,
(strResPrefix) => {
// NOTE: Only the prefix (without the related IRI) is returned. We don't need
// the IRI...addNamespace() added it. We will get the IRI from the prefix
// manager later to ensure the IRI is present.
// Do the original and resulting prefix match?
// NOTE: It can change via edits in RDFTransformNamespaceAdder.show()
if ( strPrefix.normalize() === strResPrefix.normalize() ) {
// ...yes, set as before...
obj = {};
obj.prefix = strPrefix; // Given Prefix
obj.localPart = strLocalPart; // Path portion of IRI
}
// No, then adjust...
else {
// ...get new Namespace of the Prefix to validate...
var strResNamespace =
this.#dialog.getNamespacesManager().getNamespaceOfPrefix(strResPrefix);
// Ensure the prefix's IRI was added...
if ( strResNamespace != null ) {
obj = {};
obj.prefix = strResPrefix; // New Prefix
obj.localPart = strLocalPart; // Path portion of IRI
}
// If not, abort the resource addition with a null obj...
}
}
);
}
// Otherwise, check for a namespace without a prefix...
else if (strNamespace != null) {
// Not Prefixed: Full IRI...
obj = {};
obj.prefix = null;
obj.localPart = strNamespace + strLocalPart;
}
}
// Otherwise, if there is a good IRI...
else if (strIRI && strIRI !== ":") {
// If it has a Base IRI prefix...
if (strIRI[0] === ':' && strIRI.length > 1) {
obj = {};
obj.prefix = ""; // ...use Base IRI Prefix
obj.localPart = strIRI.substring(1);
}
// Otherwise, it's a Full IRI...
else {
obj = {};
obj.prefix = null; // No Prefix
obj.localPart = strIRI; // Full IRI
}
}
// Do we have a good resource (obj) to add?
if (obj !== null) {
// Add new IRI object to suggestions...
var term = {};
term.iri = strIRI;
term.label = strIRI;
//term.desc
if (obj.prefix != null) {
term.prefix = obj.prefix;
}
if (strNamespace != null) {
term.namespace = strNamespace;
}
term.localPart = obj.localPart;
//term.description
this.#handlerAddSuggestTerm(evt, this.#strLookForType, term);
// Process new IRI object...
this.#onDone(obj);
}
else {
alert(
$.i18n('rdft-dialog/alert-iri') + "\n" +
$.i18n('rdft-dialog/alert-iri-invalid') + "\n" +
"The selection does not have a valid Resource object!\n" + // TODO: $.i18n()
"IRI: " + strIRI
);
}
}
);
elements.rdftNewResourceIRI.focus();
}
#handlerAddSuggestTerm(evt, strType, params) {
evt.preventDefault();
params.project = theProject.id;
params.type = strType;
var dismissBusy = DialogSystem.showBusy($.i18n('rdft-vocab/adding-term') + ' ' + params.iri);
Refine.postCSRF(
"command/rdf-transform/add-suggest-term",
params,
(data) => {
if (data.code === "error") {
alert($.i18n('rdft-vocab/error-adding-term') + ': [' + params.iri + "]");
}
dismissBusy();
},
"json"
);
}
/*
async #extractPrefixLocalPart(strIRI, strResp) {
/** @type {{prefix?: string, localPart?: string}} * /
var obj = null;
var iPrefixedIRI = await RDFTransformCommon.isPrefixedQName(strIRI);
if ( iPrefixedIRI === 1 ) { // ...Prefixed IRI
var strPrefix = RDFTransformCommon.getPrefixFromQName(strIRI);
var strLocalPart = RDFTransformCommon.getSuffixFromQName(strIRI);
// IRI = Namespace of Prefix + strLocalPart
// CIRIE = strResPrefix + ":" + strLocalPart
obj = {};
obj.prefix = strPrefix; // Given Prefix
obj.localPart = strLocalPart; // Path portion of IRI
this.#onDone(obj);
}
else if ( iPrefixedIRI === 0 ) { // ...Full IRI
// IRI = Namespace of Prefix + strLocalPart
// CIRIE = strResPrefix + ":" + strLocalPart
obj = {};
obj.prefix = null; // No Prefix
obj.localPart = strIRI; // Full IRI
this.#onDone(obj);
}
else { // iPrefixedIRI === -1 // ...Bad IRI
alert(
$.i18n('rdft-dialog/alert-iri') + "\n" +
$.i18n('rdft-dialog/alert-iri-invalid') + "\n" +
strResp + strIRI
);
}
}
*/
/*
async #addPrefixLocalPart(strIRI, strResp) {
/** @type {{prefix?: string, localPart?: string}} * /
var obj = null;
// Does the IRI look like a prefixed IRI?
var iPrefixedIRI = await RDFTransformCommon.isPrefixedQName(strIRI);
// Is it a prefixed IRI?
if ( iPrefixedIRI === 1 ) {
MenuSystem.dismissAll();
// Divide the IRI into Prefix and LocalPart portions...
var strPrefix = RDFTransformCommon.getPrefixFromQName(strIRI);
var strLocalPart = RDFTransformCommon.getSuffixFromQName(strIRI);
// Is there an existing prefix matching the given prefix?
if ( strPrefix === "" || this.#dialog.getNamespacesManager().hasPrefix(strPrefix) ) {
// ...yes (BaseIRI or already managed), add resource...
// IRI = Namespace of Prefix + strLocalPart
// CIRIE = strResPrefix + ":" + strLocalPart
obj = {};
obj.prefix = strPrefix; // Given Prefix
obj.localPart = strLocalPart; // Path portion of IRI
this.#onDone(obj);
}
// No, then this prefix is not using the BaseIRI prefix and is not managed...
else {
// ...create prefix (which may change in here) and add (re-prefixed) resource...
//
// NOTE: We are passing a function to RDFTransformNamespacesManager.addNamespace() which,
// in turn, passes it in an event function to RDFTransformNamespaceAdder.show().
this.#dialog.getNamespacesManager().addNamespace(
$.i18n('rdft-dialog/unknown-pref') + ': <em>' + strPrefix + '</em> ',
strPrefix,
(strResPrefix) => {
// NOTE: Only the prefix (without the related IRI) is returned. We don't need
// the IRI...addNamespace() added it. We will get the IRI from the prefix
// manager later to ensure the IRI is present.
// Do the original and resulting prefix match?
// NOTE: It can change via edits in RDFTransformNamespaceAdder.show()
if ( strPrefix.normalize() === strResPrefix.normalize() ) {
// ...yes, set as before...
// IRI = Namespace of Prefix + strLocalPart
// CIRIE = strResPrefix + ":" + strLocalPart
obj = {};
obj.prefix = strPrefix; // Given Prefix
obj.localPart = strLocalPart; // Path portion of IRI
}
// No, then adjust...
else {
// ...get new Namespace of the Prefix to validate...
var strResNamespace =
this.#dialog.getNamespacesManager().getNamespaceOfPrefix(strResPrefix);
// Ensure the prefix's IRI was added...
if ( strResNamespace != null ) {
// IRI = Namespace of Prefix + strLocalPart
// CIRIE = strResPrefix + ":" + strLocalPart
obj = {};
obj.prefix = strResPrefix; // New Prefix
obj.localPart = strLocalPart; // Path portion of IRI
}
// If not, abort the resource addition with a null obj...
}
// Do we have a good resource (obj) to add?
if (obj !== null) {
// ...yes, add resource...
this.#onDone(obj);
}
}
);
}
}
// Is it a full IRI?
else if ( iPrefixedIRI === 0 ) {
MenuSystem.dismissAll();
// ...take it as is...
//new RDFTransformResourceResolveDialog(this.#element, data, this.#onDone);
/** @type {{prefix?: string, localPart?: string}} * /
obj = {};
obj.prefix = null; // No Prefix
obj.localPart = strIRI; // Full IRI
this.#onDone(obj);
}
// Is it a BAD IRI?
else { // iPrefixedIRI === -1
alert(
$.i18n('rdft-dialog/alert-iri') + "\n" +
$.i18n('rdft-dialog/alert-iri-invalid') + "\n" +
strResp + strIRI
);
}
}
*/
} |
JavaScript | class PatientDataPage extends React.Component {
constructor(/** @type {PatientDataProps} */ props) {
super(props);
const { api, patient } = this.props;
this.log = bows("PatientData");
this.trackMetric = api.metrics.send;
this.chartRef = React.createRef();
/** @type {DataUtil | null} */
this.dataUtil = null;
this.apiUtils = new ApiUtils(api, patient);
const currentUser = api.whoami;
const browserTimezone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
this.showProfileDialog = currentUser.userid !== patient.userid;
this.state = {
loadingState: LOADING_STATE_NONE,
errorMessage: null,
/** Current display date (date at center) */
epochLocation: 0,
/** Current display data range in ms around epochLocation */
msRange: 0,
timePrefs: {
timezoneAware: true,
timezoneName: browserTimezone,
},
bgPrefs: {
bgUnits: currentUser.settings?.units?.bg ?? MGDL_UNITS,
bgClasses: {},
},
permsOfLoggedInUser: {
view: {},
notes: {},
},
canPrint: false,
pdf: null,
// Messages
messageThread: null,
createMessageDatetime: null,
// Original states info
chartPrefs: {
basics: {},
daily: {},
trends: {
activeDays: {
monday: true,
tuesday: true,
wednesday: true,
thursday: true,
friday: true,
saturday: true,
sunday: true,
},
/** To keep the wanted extentSize (num days between endpoints) between charts switch. */
extentSize: 14,
// we track both showingCbg & showingSmbg as separate Booleans for now
// in case we decide to layer BGM & CGM data, as has been discussed/prototyped
showingCbg: true,
showingSmbg: false,
smbgGrouped: false,
smbgLines: false,
smbgRangeOverlay: true,
},
bgLog: {
bgSource: "smbg",
},
},
chartStates: {
trends: {
},
},
printOpts: {
numDays: {
daily: 6,
bgLog: 30,
},
},
/** @type {TidelineData | null} */
tidelineData: null,
};
this.handleSwitchToBasics = this.handleSwitchToBasics.bind(this);
this.handleSwitchToDaily = this.handleSwitchToDaily.bind(this);
this.handleSwitchToTrends = this.handleSwitchToTrends.bind(this);
this.handleSwitchToSettings = this.handleSwitchToSettings.bind(this);
this.handleShowMessageCreation = this.handleShowMessageCreation.bind(this);
this.handleClickRefresh = this.handleClickRefresh.bind(this);
this.handleClickNoDataRefresh = this.handleClickNoDataRefresh.bind(this);
this.handleDatetimeLocationChange = this.handleDatetimeLocationChange.bind(this);
this.updateChartPrefs = this.updateChartPrefs.bind(this);
this.unsubscribeStore = null;
}
reduxListener() {
const { store } = this.props;
const { chartStates } = this.state;
const reduxState = store.getState();
if (!_.isEqual(reduxState.viz.trends, this.state.chartStates.trends)) {
this.setState({ chartStates: { ...chartStates, trends: _.cloneDeep(reduxState.viz.trends) } });
}
}
componentDidMount() {
const { store } = this.props;
this.log.debug("Mounting...");
this.unsubscribeStore = store.subscribe(this.reduxListener.bind(this));
this.handleRefresh().then(() => {
const locationChart = this.getChartType();
this.log.debug("Mouting", { locationChart });
switch (locationChart) {
case "overview":
this.handleSwitchToBasics();
break;
case "daily":
this.handleSwitchToDaily();
break;
case "settings":
this.handleSwitchToSettings();
break;
case "trends":
this.handleSwitchToTrends();
break;
default:
this.handleSwitchToDaily();
break;
}
});
}
componentWillUnmount() {
this.log.debug("Unmounting...");
if (typeof this.unsubscribeStore === "function") {
this.log("componentWillUnmount => unsubscribeStore()");
this.unsubscribeStore();
this.unsubscribeStore = null;
}
this.chartRef = null;
this.apiUtils = null;
}
render() {
const { loadingState, errorMessage } = this.state;
const chartType = this.getChartType();
let loader = null;
let messages = null;
let patientData = null;
let errorDisplay = null;
switch (loadingState) {
case LOADING_STATE_EARLIER_FETCH:
case LOADING_STATE_EARLIER_PROCESS:
case LOADING_STATE_DONE:
if (chartType === "daily") {
messages = this.renderMessagesContainer();
}
patientData = this.renderPatientData();
break;
case LOADING_STATE_NONE:
messages = <p>Please select a patient</p>;
break;
case LOADING_STATE_INITIAL_FETCH:
case LOADING_STATE_INITIAL_PROCESS:
loader = <Loader />;
break;
default:
if (errorMessage === "no-data") {
errorDisplay = this.renderNoData();
} else {
errorDisplay = <p id="loading-error-message">{errorMessage ?? t("An unknown error occurred")}</p>;
}
break;
}
return (
<div className="patient-data patient-data-yourloops">
{messages}
{patientData}
{loader}
{errorDisplay}
</div>
);
}
renderPatientData() {
if (this.isInsufficientPatientData()) {
return this.renderNoData();
}
return this.renderChart();
}
renderEmptyHeader() {
return <Header
chartType="no-data"
title={t("Data")}
canPrint={false}
trackMetric={this.trackMetric} />;
}
renderInitialLoading() {
const header = this.renderEmptyHeader();
return (
<div>
{header}
<div className="container-box-outer patient-data-content-outer">
<div className="container-box-inner patient-data-content-inner">
<div className="patient-data-content"></div>
</div>
</div>
</div>
);
}
renderNoData() {
const header = this.renderEmptyHeader();
const patientName = personUtils.fullName(this.props.patient);
const noDataText = t("{{patientName}} does not have any data yet.", { patientName });
const reloadBtnText = t("Click to reload.");
return (
<div>
{header}
<div className="container-box-outer patient-data-content-outer">
<div className="container-box-inner patient-data-content-inner">
<div className="patient-data-content">
<div className="patient-data-message-no-data">
<p>{noDataText}</p>
<button type="button" className="btn btn-primary" onClick={this.handleClickNoDataRefresh}>
{reloadBtnText}
</button>
</div>
</div>
</div>
</div>
</div>
);
}
isInsufficientPatientData() {
/** @type {PatientData} */
const diabetesData = _.get(this.state, "tidelineData.diabetesData", []);
if (_.isEmpty(diabetesData)) {
this.log.warn("Sorry, no data to display");
return true;
}
return false;
}
renderChart() {
const { patient, profileDialog, prefixURL } = this.props;
const {
canPrint,
permsOfLoggedInUser,
loadingState,
chartPrefs,
chartStates,
epochLocation,
msRange,
tidelineData,
} = this.state;
return (
<Switch>
<Route path={`${prefixURL}/overview`}>
<Basics
profileDialog={this.showProfileDialog ? profileDialog : null}
bgPrefs={this.state.bgPrefs}
chartPrefs={chartPrefs}
dataUtil={this.dataUtil}
timePrefs={this.state.timePrefs}
patient={patient}
tidelineData={tidelineData}
loading={loadingState !== LOADING_STATE_DONE}
canPrint={canPrint}
prefixURL={prefixURL}
permsOfLoggedInUser={permsOfLoggedInUser}
onClickRefresh={this.handleClickRefresh}
onClickNoDataRefresh={this.handleClickNoDataRefresh}
onSwitchToBasics={this.handleSwitchToBasics}
onSwitchToDaily={this.handleSwitchToDaily}
onClickPrint={this.handleClickPrint}
onSwitchToTrends={this.handleSwitchToTrends}
onSwitchToSettings={this.handleSwitchToSettings}
trackMetric={this.trackMetric}
updateChartPrefs={this.updateChartPrefs}
ref={this.chartRef}
/>
</Route>
<Route path={`${prefixURL}/daily`}>
<Daily
profileDialog={this.showProfileDialog ? profileDialog : null}
bgPrefs={this.state.bgPrefs}
chartPrefs={chartPrefs}
dataUtil={this.dataUtil}
timePrefs={this.state.timePrefs}
patient={patient}
tidelineData={tidelineData}
epochLocation={epochLocation}
msRange={msRange}
loading={loadingState !== LOADING_STATE_DONE}
canPrint={canPrint}
prefixURL={prefixURL}
permsOfLoggedInUser={permsOfLoggedInUser}
onClickRefresh={this.handleClickRefresh}
onCreateMessage={this.handleShowMessageCreation}
onShowMessageThread={this.handleShowMessageThread.bind(this)}
onSwitchToBasics={this.handleSwitchToBasics}
onSwitchToDaily={this.handleSwitchToDaily}
onClickPrint={this.handleClickPrint}
onSwitchToTrends={this.handleSwitchToTrends}
onSwitchToSettings={this.handleSwitchToSettings}
onDatetimeLocationChange={this.handleDatetimeLocationChange}
trackMetric={this.trackMetric}
updateChartPrefs={this.updateChartPrefs}
ref={this.chartRef}
/>
</Route>
<Route path={`${prefixURL}/trends`}>
<Trends
profileDialog={this.showProfileDialog ? profileDialog : null}
bgPrefs={this.state.bgPrefs}
chartPrefs={chartPrefs}
currentPatientInViewId={patient.userid}
dataUtil={this.dataUtil}
timePrefs={this.state.timePrefs}
epochLocation={epochLocation}
msRange={msRange}
patient={patient}
tidelineData={tidelineData}
loading={loadingState !== LOADING_STATE_DONE}
canPrint={canPrint}
prefixURL={prefixURL}
permsOfLoggedInUser={permsOfLoggedInUser}
onClickRefresh={this.handleClickRefresh}
onSwitchToBasics={this.handleSwitchToBasics}
onSwitchToDaily={this.handleSwitchToDaily}
onSwitchToTrends={this.handleSwitchToTrends}
onSwitchToSettings={this.handleSwitchToSettings}
onDatetimeLocationChange={this.handleDatetimeLocationChange}
trackMetric={this.trackMetric}
updateChartPrefs={this.updateChartPrefs}
trendsState={chartStates.trends}
/>
</Route>
<Route path={`${prefixURL}/settings`}>
<div className="app-no-print">
<Settings
bgPrefs={this.state.bgPrefs}
chartPrefs={this.state.chartPrefs}
currentPatientInViewId={patient.userid}
timePrefs={this.state.timePrefs}
patient={patient}
patientData={tidelineData}
canPrint={canPrint}
prefixURL={prefixURL}
permsOfLoggedInUser={this.state.permsOfLoggedInUser}
onClickRefresh={this.handleClickRefresh}
onClickNoDataRefresh={this.handleClickNoDataRefresh}
onSwitchToBasics={this.handleSwitchToBasics}
onSwitchToDaily={this.handleSwitchToDaily}
onSwitchToTrends={this.handleSwitchToTrends}
onSwitchToSettings={this.handleSwitchToSettings}
onClickPrint={this.handleClickPrint}
trackMetric={this.trackMetric}
/>
</div>
</Route>
</Switch>
);
}
renderMessagesContainer() {
const { patient, api } = this.props;
const { createMessageDatetime, messageThread, timePrefs } = this.state;
if (createMessageDatetime) {
const user = api.whoami;
return (
<Messages
createDatetime={createMessageDatetime}
user={user}
patient={patient}
onClose={this.closeMessageCreation.bind(this)}
onSave={this.handleCreateNote.bind(this)}
onNewMessage={this.handleMessageCreation.bind(this)}
onEdit={this.handleEditMessage.bind(this)}
timePrefs={timePrefs}
trackMetric={this.trackMetric} />
);
} else if (Array.isArray(messageThread)) {
const user = api.whoami;
return (
<Messages
messages={messageThread}
user={user}
patient={patient}
onClose={this.closeMessageThread.bind(this)}
onSave={this.handleReplyToMessage.bind(this)}
onEdit={this.handleEditMessage.bind(this)}
timePrefs={timePrefs}
trackMetric={this.trackMetric} />
);
}
return null;
}
getChartType() {
const { history, prefixURL } = this.props;
switch (history.location.pathname) {
case `${prefixURL}/overview`:
return "overview";
case `${prefixURL}/daily`:
return "daily";
case `${prefixURL}/trends`:
return "trends";
case `${prefixURL}/settings`:
return "settings";
}
return null;
}
generatePDFStats(data) {
const { timePrefs } = this.state;
const {
bgBounds,
bgUnits,
latestPump: { manufacturer, deviceModel },
} = this.dataUtil;
const isAutomatedBasalDevice = isAutomatedBasalDeviceCheck(manufacturer, deviceModel);
const getStat = (statType) => {
const { bgSource, days } = this.dataUtil;
return getStatDefinition(this.dataUtil[statFetchMethods[statType]](), statType, {
bgSource,
days,
bgPrefs: {
bgBounds,
bgUnits,
},
manufacturer,
});
};
const basicsDateRange = _.get(data, "basics.dateRange");
if (basicsDateRange) {
data.basics.endpoints = [basicsDateRange[0], getLocalizedCeiling(basicsDateRange[1], timePrefs).toISOString()];
this.dataUtil.endpoints = data.basics.endpoints;
data.basics.stats = {
[commonStats.timeInRange]: getStat(commonStats.timeInRange),
[commonStats.readingsInRange]: getStat(commonStats.readingsInRange),
[commonStats.totalInsulin]: getStat(commonStats.totalInsulin),
[commonStats.timeInAuto]: isAutomatedBasalDevice ? getStat(commonStats.timeInAuto) : undefined,
[commonStats.carbs]: getStat(commonStats.carbs),
[commonStats.averageDailyDose]: getStat(commonStats.averageDailyDose),
};
}
const dailyDateRanges = _.get(data, "daily.dataByDate");
if (dailyDateRanges) {
_.forIn(
dailyDateRanges,
_.bind(function (value, key) {
data.daily.dataByDate[key].endpoints = [
getLocalizedCeiling(dailyDateRanges[key].bounds[0], timePrefs).toISOString(),
getLocalizedCeiling(dailyDateRanges[key].bounds[1], timePrefs).toISOString(),
];
this.dataUtil.endpoints = data.daily.dataByDate[key].endpoints;
data.daily.dataByDate[key].stats = {
[commonStats.timeInRange]: getStat(commonStats.timeInRange),
[commonStats.averageGlucose]: getStat(commonStats.averageGlucose),
[commonStats.totalInsulin]: getStat(commonStats.totalInsulin),
[commonStats.timeInAuto]: isAutomatedBasalDevice ? getStat(commonStats.timeInAuto) : undefined,
[commonStats.carbs]: getStat(commonStats.carbs),
};
}, this)
);
}
const bgLogDateRange = _.get(data, "bgLog.dateRange");
if (bgLogDateRange) {
data.bgLog.endpoints = [
getLocalizedCeiling(bgLogDateRange[0], timePrefs).toISOString(),
addDuration(getLocalizedCeiling(bgLogDateRange[1], timePrefs).toISOString(), 864e5),
];
this.dataUtil.endpoints = data.bgLog.endpoints;
data.bgLog.stats = {
[commonStats.averageGlucose]: getStat(commonStats.averageGlucose),
};
}
return data;
}
generatePDF() {
const { patient } = this.props;
const { tidelineData, bgPrefs, printOpts, timePrefs } = this.state;
const diabetesData = tidelineData.diabetesData;
const mostRecent = diabetesData[diabetesData.length - 1].normalTime;
const opts = {
bgPrefs,
numDays: printOpts.numDays,
patient,
timePrefs,
mostRecent,
};
const dailyData = vizUtils.data.selectDailyViewData(
mostRecent,
_.pick(tidelineData.grouped, ["basal", "bolus", "cbg", "food", "message", "smbg", "upload", "physicalActivity"]),
printOpts.numDays.daily,
timePrefs
);
const bgLogData = vizUtils.data.selectBgLogViewData(
mostRecent,
_.pick(tidelineData.grouped, ["smbg"]),
printOpts.numDays.bgLog,
timePrefs
);
const pdfData = {
basics: tidelineData.basicsData,
daily: dailyData,
settings: _.last(tidelineData.grouped.pumpSettings),
bgLog: bgLogData,
};
this.generatePDFStats(pdfData);
this.log("Generating PDF with", pdfData, opts);
return createPrintPDFPackage(pdfData, opts);
}
async handleMessageCreation(message) {
this.log.debug("handleMessageCreation", message);
const shapedMessage = nurseShark.reshapeMessage(message);
this.log.debug({ message, shapedMessage });
await this.chartRef.current.createMessage(nurseShark.reshapeMessage(message));
this.trackMetric("note", "create_note");
}
async handleReplyToMessage(comment) {
const { api } = this.props;
const id = await api.replyMessageThread(comment);
this.trackMetric("note", "reply_note");
return id;
}
/**
* Create a new note
* @param {MessageNote} message the message
* @returns {Promise<string>}
*/
handleCreateNote(message) {
const { api } = this.props;
return api.startMessageThread(message);
}
/**
* Callback after a message is edited.
* @param {MessageNote} message the edited message
* @returns {Promise<void>}
*/
async handleEditMessage(message) {
this.log.debug("handleEditMessage", { message });
const { api } = this.props;
await api.editMessage(message);
this.trackMetric("note", "edit_note");
if (_.isEmpty(message.parentmessage)) {
// Daily timeline view only cares for top-level note
const reshapedMessage = nurseShark.reshapeMessage(message);
this.chartRef.current.editMessage(reshapedMessage);
}
}
async handleShowMessageThread(messageThread) {
this.log.debug("handleShowMessageThread", messageThread);
const { api } = this.props;
const messages = await api.getMessageThread(messageThread);
this.setState({ messageThread: messages });
}
handleShowMessageCreation(/** @type {moment.Moment | Date} */ datetime) {
const { epochLocation, tidelineData } = this.state;
this.log.debug("handleShowMessageCreation", { datetime, epochLocation });
let mDate = datetime;
if (datetime === null) {
const timezone = tidelineData.getTimezoneAt(epochLocation);
mDate = moment.utc(epochLocation).tz(timezone);
}
this.setState({ createMessageDatetime : mDate.toISOString() });
}
closeMessageThread() {
this.setState({ createMessageDatetime: null, messageThread: null });
}
closeMessageCreation() {
this.setState({ createMessageDatetime: null, messageThread: null });
}
handleSwitchToBasics(e) {
const { prefixURL, history } = this.props;
const fromChart = this.getChartType();
const toChart = "overview";
if (e) {
e.preventDefault();
}
this.dataUtil.chartPrefs = this.state.chartPrefs[toChart];
if (fromChart !== toChart) {
history.push(`${prefixURL}/${toChart}`);
this.trackMetric("data_visualization", "click_view", toChart);
}
}
/**
*
* @param {moment.Moment | Date | number | null} datetime The day to display
*/
handleSwitchToDaily(datetime = null) {
const { prefixURL, history } = this.props;
const fromChart = this.getChartType();
const toChart = "daily";
let { epochLocation } = this.state;
if (typeof datetime === "number") {
epochLocation = datetime;
} else if (moment.isMoment(datetime) || datetime instanceof Date) {
epochLocation = datetime.valueOf();
}
this.log.info("Switch to daily", { date: moment.utc(epochLocation).toISOString(), epochLocation });
this.dataUtil.chartPrefs = this.state.chartPrefs[toChart];
this.setState({
epochLocation,
msRange: MS_IN_DAY,
}, () => {
if (fromChart !== toChart) {
history.push(`${prefixURL}/${toChart}`);
this.trackMetric("data_visualization", "click_view", toChart);
}
});
}
handleSwitchToTrends(e) {
const { prefixURL, history } = this.props;
const fromChart = this.getChartType();
const toChart = "trends";
if (e) {
e.preventDefault();
}
this.dataUtil.chartPrefs = this.state.chartPrefs[toChart];
if (fromChart !== toChart) {
history.push(`${prefixURL}/${toChart}`);
this.trackMetric("data_visualization", "click_view", toChart);
}
}
handleSwitchToSettings(e) {
const { prefixURL, history } = this.props;
const fromChart = this.getChartType();
const toChart = "settings";
if (e) {
e.preventDefault();
}
if (fromChart !== toChart) {
history.push(`${prefixURL}/${toChart}`);
this.trackMetric("data_visualization", "click_view", toChart);
}
}
/** @returns {Promise<void>} */
handleClickPrint = () => {
function openPDFWindow(pdf) {
const printWindow = window.open(pdf.url);
if (printWindow !== null) {
printWindow.focus();
if (!utils.isFirefox()) {
printWindow.print();
}
}
}
this.trackMetric("export_data", "save_report", this.getChartType() ?? "");
// Return a promise for the tests
return new Promise((resolve, reject) => {
if (this.state.pdf !== null) {
openPDFWindow(this.state.pdf);
resolve();
} else {
const { tidelineData, loadingState } = this.state;
let hasDiabetesData = false;
if (tidelineData !== null) {
hasDiabetesData = _.get(tidelineData, "diabetesData.length", 0) > 0;
}
if (loadingState === LOADING_STATE_DONE && hasDiabetesData) {
this.generatePDF()
.then((pdf) => {
openPDFWindow(pdf);
this.setState({ pdf });
resolve();
})
.catch((err) => {
this.log("generatePDF:", err);
if (_.isFunction(window.onerror)) {
window.onerror("print", "patient-data", 0, 0, err);
}
reject(err);
});
} else {
resolve();
}
}
});
}
handleClickRefresh(/* e */) {
this.handleRefresh().catch(reason => this.log.error(reason));
}
handleClickNoDataRefresh(/* e */) {
this.handleRefresh().catch(reason => this.log.error(reason));
}
onLoadingFailure(err) {
// TODO A cleaner message
const errorMessage = _.isError(err) ? err.message : (new String(err)).toString();
this.log.error(errorMessage, err);
this.setState({ loadingState: LOADING_STATE_ERROR, errorMessage });
}
updateChartPrefs(updates, cb = _.noop) {
this.log.debug("updateChartPrefs", { updates, cb});
const newPrefs = {
...this.state.chartPrefs,
...updates,
};
const fromChart = this.getChartType();
if (fromChart) {
this.dataUtil.chartPrefs = newPrefs[fromChart];
this.setState({ chartPrefs: newPrefs, }, cb);
}
}
/**
* Chart display date / range change
* @param {number} epochLocation datetime epoch value in ms
* @param {number} msRange ms around epochLocation
* @returns {Promise<boolean>} true if new data are loaded
*/
async handleDatetimeLocationChange(epochLocation, msRange) {
const { loadingState } = this.state;
const chartType = this.getChartType();
let dataLoaded = false;
// this.log.debug('handleDatetimeLocationChange()', {
// epochLocation,
// msRange,
// date: moment.utc(epochLocation).toISOString(),
// rangeDays: msRange/MS_IN_DAY,
// loadingState,
// });
if (!Number.isFinite(epochLocation) || !Number.isFinite(msRange)) {
throw new Error("handleDatetimeLocationChange: invalid parameters");
}
// Don't do anything if we are currently loading
if (loadingState === LOADING_STATE_DONE) {
// For daily check for +/- 1 day (and not 0.5 day), for others only the displayed range
let msRangeDataNeeded = chartType === "daily" ? MS_IN_DAY : msRange / 2;
/** @type {DateRange} */
let rangeDisplay = {
start: epochLocation - msRangeDataNeeded,
end: epochLocation + msRangeDataNeeded,
};
const rangeToLoad = this.apiUtils.partialDataLoad.getRangeToLoad(rangeDisplay);
if (rangeToLoad) {
// We need more data!
if (chartType === "daily") {
// For daily we will load 1 week to avoid too many loading
msRangeDataNeeded = MS_IN_DAY * 3;
rangeDisplay = {
start: epochLocation - msRangeDataNeeded,
end: epochLocation + msRangeDataNeeded,
};
}
this.setState({ epochLocation, msRange, loadingState: LOADING_STATE_EARLIER_FETCH });
const data = await this.apiUtils.fetchDataRange(rangeDisplay);
this.setState({ loadingState: LOADING_STATE_EARLIER_PROCESS });
await this.processData(data);
dataLoaded = true;
} else {
this.setState({ epochLocation, msRange });
}
}
return dataLoaded;
}
async handleRefresh() {
this.setState({
loadingState: LOADING_STATE_INITIAL_FETCH,
dataRange: null,
epochLocation: 0,
msRange: 0,
tidelineData: null,
pdf: null,
canPrint: false,
});
try {
const data = await this.apiUtils.refresh();
this.setState({ loadingState: LOADING_STATE_INITIAL_PROCESS });
await waitTimeout(1);
// Process the data to be usable by us
await this.processData(data);
} catch (reason) {
this.onLoadingFailure(reason);
}
}
/**
*
* @param {PatientData} data
*/
async processData(data) {
const { store, patient } = this.props;
const { timePrefs, bgPrefs, epochLocation, msRange } = this.state;
let { tidelineData } = this.state;
const firstLoadOrRefresh = tidelineData === null;
this.props.api.metrics.startTimer("process_data");
const res = nurseShark.processData(data, bgPrefs.bgUnits);
await waitTimeout(1);
if (firstLoadOrRefresh) {
const opts = {
timePrefs,
...bgPrefs,
// Used by tideline oneDay to set-up the scroll range
// Send this information by tidelineData options
dataRange: this.apiUtils.dataRange,
YLP820_BASAL_TIME: config.YLP820_BASAL_TIME,
};
tidelineData = new TidelineData(opts);
}
await tidelineData.addData(res.processedData);
if (_.isEmpty(tidelineData.data)) {
this.props.api.metrics.endTimer("process_data");
throw new Error("no-data");
}
const bgPrefsUpdated = {
bgUnits: tidelineData.opts.bgUnits,
bgClasses: tidelineData.opts.bgClasses,
};
this.dataUtil = new DataUtil(tidelineData.data, { bgPrefs: bgPrefsUpdated, timePrefs, endpoints: tidelineData.endpoints });
let newLocation = epochLocation;
if (epochLocation === 0) {
// First loading, display the last day in the daily chart
newLocation = moment.utc(tidelineData.endpoints[1]).valueOf() - MS_IN_DAY/2;
}
let newRange = msRange;
if (msRange === 0) {
newRange = MS_IN_DAY;
}
this.setState({
bgPrefs: bgPrefsUpdated,
timePrefs: tidelineData.opts.timePrefs,
tidelineData,
epochLocation: newLocation,
msRange: newRange,
loadingState: LOADING_STATE_DONE,
canPrint: true,
}, () => this.log.info("Loading finished"));
if (firstLoadOrRefresh) {
store.dispatch({
type: FETCH_PATIENT_DATA_SUCCESS,
payload: {
patientId: patient.userid,
},
});
}
this.props.api.metrics.endTimer("process_data");
}
} |
JavaScript | class HomeCarousel extends Component {
state = { activeIndex: 0 };
onExiting = () => {
this.animating = true;
};
onExited = () => {
this.animating = false;
};
next = () => {
if (this.animating) return;
const nextIndex =
this.state.activeIndex === this.props.trending.length - 1
? 0
: this.state.activeIndex + 1;
this.setState({ activeIndex: nextIndex });
};
previous = () => {
if (this.animating) return;
const nextIndex =
this.state.activeIndex === 0
? this.props.trending.length - 1
: this.state.activeIndex - 1;
this.setState({ activeIndex: nextIndex });
};
goToIndex = newIndex => {
if (this.animating) return;
this.setState({ activeIndex: newIndex });
};
render() {
const { activeIndex } = this.state;
const slides = this.props.trending.map(item => {
return (
<CarouselItem
onExiting={this.onExiting}
onExited={this.onExited}
key={item.id}
>
<Link to={`/details/${this.props.topic}/${item.id}`}>
<div
className="carousel-img"
style={{
backgroundImage: `url(https://image.tmdb.org/t/p/original${
item.backdrop_path
})`
}}
/>
</Link>
<div className="carousel-text">
<h3 className="carousel-genre">TRENDING</h3>
<h2 className="carousel-title">{item.title}</h2>
<h2 className="carousel-title">{item.name}</h2>
<p>{`Rating | ${item.vote_average} out of 10`}</p>
</div>
</CarouselItem>
);
});
if (this.props.trending.length === 0) {
return (
<div className="carousel-img">
<div className="loader">
<Loader type="Oval" color="#fff" height="100" width="100" />
</div>
</div>
)
} else {
return (
<Carousel
activeIndex={activeIndex}
next={this.next}
previous={this.previous}
>
{slides}
</Carousel>
);
}
}
} |
JavaScript | class Controller {
/**
* Constructor.
* @param {!angular.Scope} $scope
* @param {!angular.JQLite} $element
* @ngInject
*/
constructor($scope, $element) {
/**
* @type {?angular.Scope}
* @protected
*/
this.scope = $scope;
/**
* @type {?angular.JQLite}
* @protected
*/
this.element = $element;
/**
* @type {Logger}
* @protected
*/
this.log = logger;
/**
* @type {Feature|undefined}
* @protected
*/
this.preview = undefined;
/**
* @type {Error}
* @private
*/
this.error_ = null;
/**
* Interaction for freeform modification.
* @type {Modify}
*/
this.interaction = null;
/**
* @type {Feature|undefined}
* @protected
*/
this.areaPreview = null;
/**
* @type {Feature|undefined}
* @protected
*/
this.targetPreview = null;
/**
* @type {!Object<string, string>}
*/
this['help'] = {
'area1': 'The base area to be modified. A preview of the result will be shown on the map in blue, and this ' +
'area can either be replaced or you can create a new area.',
'area2': 'The area that will be used to modify the base area.',
'mapArea': 'The area to add to/remove from the base area. This area was drawn/selected using the map. If you ' +
'would like to choose a saved area, click Clear and select one from the dropdown.',
'operation': 'How the area should be modified.',
'addOp': 'The selected area will be combined with the Area to Modify.',
'removeOp': 'The selected area will be cut out of the Area to Modify.',
'intersectOp': 'The new area will only include intersecting portions of the selected areas.',
'replace': 'If checked, the Area to Modify will be replaced with the area indicated by the preview. Otherwise ' +
'a new area will be created with the provided title.',
'title': 'The title to give to the new area'
};
/**
* @type {boolean}
*/
this['loading'] = false;
/**
* @type {boolean}
*/
this['replace'] = true;
/**
* @type {?string}
*/
this['title'] = 'New Area';
/**
* The currently selected tab.
* @type {?string}
*/
this['tab'] = null;
/**
* Flag for whether we are operating on an area.
* @type {boolean}
*/
this['showTabs'] = true;
/**
* Controls for freeform modification.
* @type {Array<Object<string, *>>}
*/
this['controls'] = [
{
'text': 'Remove Vertex',
'keys': [KeyCodes.ALT, '+'],
'other': [Controls.MOUSE.LEFT_MOUSE]
},
{
'text': 'Save Changes',
'keys': [KeyCodes.ENTER]
},
{
'text': 'Cancel',
'keys': [KeyCodes.ESC]
}
];
// default the op and the tab to freeform
$scope['op'] = $scope['op'] || ModifyOp.ADD;
const am = getAreaManager();
let showTabs = true;
let feature;
let initialTab = ModifyType.FREEFORM;
// configure the form
if ($scope['feature']) {
feature = /** @type {!Feature} */ ($scope['feature']);
showTabs = am.contains(feature) && am.getAll().length >= 2;
this.interaction = new Modify(feature);
initialTab = ModifyType.FREEFORM;
} else if ($scope['targetArea']) {
feature = /** @type {!Feature} */ ($scope['targetArea']);
showTabs = false;
this.interaction = null;
initialTab = ModifyType.ADD_REMOVE;
}
this['showTabs'] = showTabs;
this.setTab(initialTab);
$scope.$watch('feature', this.onAreaChange.bind(this));
$scope.$watch('op', this.updatePreview.bind(this));
$scope.$watch('targetArea', this.onTargetAreaChange.bind(this));
$scope.$emit(WindowEventType.READY);
}
/**
* Angular destroy hook.
*/
$onDestroy() {
this.setPreviewFeature(undefined);
dispose(this.interaction);
if (this.areaPreview) {
getMapContainer().removeFeature(this.areaPreview);
this.areaPreview = null;
}
if (this.targetPreview) {
getMapContainer().removeFeature(this.targetPreview);
this.targetPreview = null;
}
this.scope = null;
this.element = null;
}
/**
* Sets the tab.
* @param {string} tab The tab to set.
* @export
*/
setTab(tab) {
if (tab != this['tab']) {
this['tab'] = tab;
const mc = getMapContainer();
if (tab == ModifyType.FREEFORM) {
this.interaction.setOverlay(/** @type {Vector} */ (mc.getDrawingLayer()));
mc.getMap().addInteraction(this.interaction);
this.interaction.setActive(true);
listen(this.interaction, ModifyEventType.COMPLETE, this.onInteractionComplete, this);
listen(this.interaction, ModifyEventType.CANCEL, this.onInteractionCancel, this);
} else if (tab == ModifyType.ADD_REMOVE && this.interaction) {
mc.getMap().removeInteraction(this.interaction);
this.interaction.setActive(false);
}
}
this.validate();
}
/**
* Callback handler for successfully completing a modify of a geometry.
* @param {PayloadEvent} event
*/
onInteractionComplete(event) {
const feature = /** @type {!Feature} */ (this.scope['feature']);
const clone = /** @type {!Feature} */ (event.getPayload());
const source = getSource(feature);
let modifyFunction;
if (osImplements(source, IModifiableSource.ID)) {
modifyFunction = /** @type {IModifiableSource} */ (source).getModifyFunction();
}
if (modifyFunction) {
// call the modify function to finalize the update
modifyFunction(feature, clone);
} else {
const geometry = clone.getGeometry();
if (feature && geometry) {
// default behavior is to assume that we're modifying an area, so update it in AreaManager
const modifyCmd = new AreaModify(feature, geometry);
CommandProcessor.getInstance().addCommand(modifyCmd);
}
}
// remove the clone and the interaction from the map
getMapContainer().getMap().removeInteraction(this.interaction);
this.close_();
}
/**
* Callback handler for canceling a modify.
*/
onInteractionCancel() {
this.close_();
}
/**
* Make sure everything is kosher.
*
* @protected
*/
validate() {
this['error'] = null;
if (this.scope && this['tab'] == ModifyType.ADD_REMOVE) {
if (!this.scope['feature']) {
// source isn't selected
this['error'] = 'Please choose an area to modify.';
} else if (!this.scope['targetArea']) {
// source is selected, target is not
this['error'] = 'Please choose an area to ' + this.scope['op'] + '.';
} else if (this.scope['feature'] == this.scope['targetArea']) {
// areas cannot be the same
this['error'] = 'Please select two different areas.';
} else if (this.error_) {
switch (this.error_.message) {
case osJsts.ErrorMessage.EMPTY:
if (this.scope['op'] == ModifyOp.REMOVE) {
this['error'] = 'Area to Remove cannot fully contain the Area to Modify, or the result will be empty.';
} else if (this.scope['op'] == ModifyOp.INTERSECT) {
this['error'] = 'Areas do not have an intersection.';
} else {
// really hope we don't get here... add shouldn't result in an empty geometry
this['error'] = this.scope['op'] + ' failed. Please check the log for details.';
}
break;
case osJsts.ErrorMessage.NO_OP:
if (this.scope['op'] == ModifyOp.REMOVE) {
this['error'] = 'Area to Remove will not remove anything from the Area to Modify.';
} else {
this['error'] = 'Area to Add will not add anything to the Area to Modify.';
}
break;
default:
this['error'] = this.scope['op'] + ' failed. Please check the log for details.';
break;
}
} else if (!this.preview) {
this['error'] = this.scope['op'] + ' failed. Please check the log for details.';
}
}
}
/**
* Handle change to the source area.
*
* @param {Feature=} opt_new
* @param {Feature=} opt_old
* @protected
*/
onAreaChange(opt_new, opt_old) {
if (this.areaPreview) {
getMapContainer().removeFeature(this.areaPreview);
}
this.areaPreview = null;
if (opt_new instanceof Feature && opt_new.getGeometry()) {
// clone the feature because we don't want the style, nor do we want to remove the original from the map
this.areaPreview = osOlFeature.clone(opt_new);
this.areaPreview.set(RecordField.DRAWING_LAYER_NODE, false);
getMapContainer().addFeature(this.areaPreview);
}
// area was provided, but it isn't in the area manager. assume it's a user-drawn area, or from a source.
this.scope['fixArea'] = this.scope['feature'] && !getAreaManager().contains(this.scope['feature']);
this.updatePreview();
}
/**
* Handle change to the target area.
*
* @param {Feature=} opt_new
* @param {Feature=} opt_old
* @protected
*/
onTargetAreaChange(opt_new, opt_old) {
if (this.targetPreview) {
getMapContainer().removeFeature(this.targetPreview);
}
this.targetPreview = null;
if (opt_new instanceof Feature && opt_new.getGeometry()) {
// clone the feature because we don't want the style, nor do we want to remove the original from the map
this.targetPreview = osOlFeature.clone(opt_new);
this.targetPreview.set(RecordField.DRAWING_LAYER_NODE, false);
getMapContainer().addFeature(this.targetPreview);
}
// target area was provided, but it isn't in the area manager. assume it's a user-drawn area, or from a source.
this.scope['fixTargetArea'] = this.scope['targetArea'] && !getAreaManager().contains(this.scope['targetArea']);
this.updatePreview();
}
/**
* Update the preview feature.
*/
updatePreview() {
this.setPreviewFeature(this.getMergedArea_());
this.validate();
}
/**
* @param {Feature|undefined} feature
* @protected
*/
setPreviewFeature(feature) {
if (this.preview) {
getMapContainer().removeFeature(this.preview);
}
this.preview = feature;
if (this.preview && this.preview.getGeometry()) {
getMapContainer().addFeature(this.preview, PREVIEW_CONFIG);
}
}
/**
* Merge the two selected areas, returning the result.
*
* @return {Feature|undefined}
* @private
*/
getMergedArea_() {
this.error_ = null;
var feature;
if (this.scope['feature'] && this.scope['targetArea']) {
try {
switch (this.scope['op']) {
case ModifyOp.ADD:
feature = osJsts.addTo(this.scope['feature'], this.scope['targetArea']);
break;
case ModifyOp.REMOVE:
feature = osJsts.removeFrom(this.scope['feature'], this.scope['targetArea']);
break;
case ModifyOp.INTERSECT:
feature = osJsts.intersect(this.scope['feature'], this.scope['targetArea']);
break;
default:
log.error(this.log, 'Unsupported operation: ' + this.scope['op']);
break;
}
} catch (e) {
this.error_ = e;
}
}
if (feature) {
feature.set(RecordField.DRAWING_LAYER_NODE, false);
}
return feature;
}
/**
* Fire the cancel callback and close the window.
*
* @export
*/
cancel() {
this.close_();
}
/**
* Performs the area modification.
*
* @export
*/
confirm() {
if (this['tab'] == ModifyType.FREEFORM) {
this.interaction.complete();
} else if (this['tab'] == ModifyType.ADD_REMOVE) {
var feature = this.getMergedArea_();
var geometry = feature ? feature.getGeometry() : null;
if (feature && geometry) {
var cmd;
if (this['replace']) {
// modify the geometry in the existing area
cmd = new AreaModify(this.scope['feature'], geometry);
} else {
// add a new area
feature.set('title', this['title']);
cmd = new AreaAdd(feature);
}
if (cmd) {
CommandProcessor.getInstance().addCommand(cmd);
}
} else {
AlertManager.getInstance().sendAlert('Failed modifying area! Please see the log for more details.',
AlertEventSeverity.ERROR, this.log);
}
}
this.close_();
}
/**
* Get the help popover title for an operation.
*
* @param {string} op The operation
* @return {string}
* @export
*/
getPopoverTitle(op) {
switch (op) {
case ModifyOp.ADD:
return 'Add Area';
case ModifyOp.REMOVE:
return 'Remove Area';
case ModifyOp.INTERSECT:
return 'Area Intersection';
default:
break;
}
return 'Area Help';
}
/**
* Get the help popover content for an operation.
*
* @param {string} op The operation
* @return {string}
* @export
*/
getPopoverContent(op) {
switch (op) {
case ModifyOp.ADD:
return this['help']['addOp'];
case ModifyOp.REMOVE:
return this['help']['removeOp'];
case ModifyOp.INTERSECT:
return this['help']['intersectOp'];
default:
break;
}
return 'Area Help';
}
/**
* Close the window.
*
* @private
*/
close_() {
close(this.element);
}
} |
JavaScript | class jfDragAndDropTxtController{
/**
* Constructor
* */
constructor($scope,$element,$attrs,JFrogNotifications){
this.$scope = $scope;
this.$element = $element;
this.JFrogNotifications = JFrogNotifications;
// Binding dragenter,dragleave,drop to <jf_drang_and_drop_text> element
// since these events are not natively supported by Angular
this.$element.bind('dragover', this.handleDragEnter.bind(this));
this.$element.bind('dragleave', this.handleDragLeave.bind(this));
this.$element.bind('drop', this.handleDropEvent.bind(this));
this.draggedFileSizeLimit = 400; // limit file size (in KB)
this.entered = false;
}
$onInit() {
this.dndAutoFocus = this.dndAutoFocus=== undefined ? true : this.dndAutoFocus;
this.dndCallToAction = this.dndCallToAction || "Copy your text or <b>drop a file</b>";
}
shouldDisplayUploadIcon(){
return ($(this.$element).find('textarea').val() === "" && !$(this.$element).is('.over'));
}
/**
* File Reader event handlers
* */
onFileLoadSuccess(event){
this.dndContent = event.target.result;
$(this.$element).find('textarea').focus();
if(this.dndChange && this.dndChange !== null) this.dndChange();
}
onFileLoadFailure(event){
let errorMessage = "Unable to access license file.";
if(event.target.error.name === "SecurityError") {
errorMessage += "<br> The file is either unsafe or being used by another application.";
}
if(this.dndOnError !== null){
this.dndOnError({msg: errorMessage});
}
else{
this.JFrogNotifications.create({
error: errorMessage
});
}
}
/**
* Drag event handlers
* */
handleDropEvent(event) {
this.entered = false;
this.toggleDragEffect();
event.preventDefault();
event.stopPropagation();
// Initialize a file reader and get file path
let reader = new FileReader();
let file = event.originalEvent.dataTransfer.files[0];
// Bind to reader events
reader.onload = (event)=>{this.onFileLoadSuccess(event)};
reader.onerror = (event)=>{this.onFileLoadFailure(event)};
// Limit the read file size
let fileSize = Math.round(file.size/1000);
if(fileSize > this.draggedFileSizeLimit){
let errorMessage = 'File exceeds the maximum size of ' + this.draggedFileSizeLimit + ' KB';
if(this.dndOnError !== null){
this.dndOnError({msg: errorMessage});
}
else{
this.JFrogNotifications.create({
error: errorMessage
});
}
return false;
}
// Read the file if not exceeds size limit
reader.readAsText(file);
}
callingCodeShouldEnd(event){
// This is an ugly fix for the issue of FireFox browser
// firing the dragover/dragenter and dragleve events again and again
// when dragging a file over the textarea
let theCallingCodeShouldEnd = false;
try {
if(event.relatedTarget.nodeType == 3) {
theCallingCodeShouldEnd = true;
}
}
catch(err) {}
if(event.target === event.relatedTarget) {
theCallingCodeShouldEnd = true;
}
return theCallingCodeShouldEnd;
}
handleDragEnter(event) {
event.preventDefault();
event.stopPropagation(); // cancel the event on FF
if(this.callingCodeShouldEnd(event)){
return;
}
if(!this.entered){
this.entered = true;
this.toggleDragEffect();
event.originalEvent.dataTransfer.effectAllowed = 'copy';
return false;
}
}
handleDragLeave(event) {
event.preventDefault();
event.stopPropagation(); // cancel the event on FF
if(this.callingCodeShouldEnd(event)){
return;
}
if(this.entered){
this.entered = false;
this.toggleDragEffect();
return false;
}
}
/**
* Toggle the drag effect
* */
toggleDragEffect(){
let dndWrapper = $(this.$element).find('.drag-and-drop-txt-wrapper');
// dndWrapper.removeClass('icon-upload');
dndWrapper.toggleClass('over');
}
} |
JavaScript | class Body extends Component {
/**
* Adds a click action to each row, called with the clicked row's data as an argument.
* Can be used with both the blockless and block invocations.
*
* @argument onRowClick
* @type Function
*/
@action
handleRowClick(rowData) {
this.args.onRowClick?.(rowData);
}
} |
JavaScript | class Base {
constructor (name, robot, ...args) {
this.name = name
this.robot = robot
if (!_.isString(this.name)) this.error('Module requires a name')
if (!_.isObject(this.robot)) this.error('Module requires a robot object')
this.config = {}
if (_.isObject(args[0])) this.configure(args.shift())
if (_.isString(args[0])) this.key = args.shift()
this.id = _.uniqueId(this.name)
}
/**
* Getter allows robot to be replaced at runtime without losing route to log.
*
* @return {Object} The robot's log instance
*/
get log () {
if (!this.robot) return null
return {
info: (text) => this.robot.logger.info(this.appendLogDetails(text)),
debug: (text) => this.robot.logger.debug(this.appendLogDetails(text)),
warning: (text) => this.robot.logger.warning(this.appendLogDetails(text)),
error: (text) => this.robot.logger.error(this.appendLogDetails(text))
}
}
/**
* Append the base instance details to any log it generates
*
* @param {string} text The original log message
* @return {string} Log message with details appended
*/
appendLogDetails (text) {
let details = `id: ${this.id}`
if (!_.isNil(this.key)) details += `, key: ${this.key}`
return `${text} (${details})`
}
/**
* Generic error handling, logs and emits event before throwing.
*
* @param {Error/string} err Error object or description of error
*/
error (err) {
if (_.isString(err)) {
let text = `${this.id || 'constructor'}: ${err}`
if (!_.isNil(this.key)) text += ` (key: ${this.key})`
err = new Error(text)
}
if (this.robot !== null) this.robot.emit('error', err)
throw err
}
/**
* Merge-in passed options, override any that exist in config.
*
* @param {Object} options Key/vals to merge with existing config
* @return {Base} Self for chaining
*
* @example
* radOne.configure({ radness: 'overload' }) // overwrites initial config
*/
configure (options) {
if (!_.isObject(options)) this.error('Non-object received for config')
this.config = _.defaults({}, options, this.config)
return this
}
/**
* Fill any missing settings without overriding any existing in config.
*
* @param {Object} settings Key/vals to use as config fallbacks
* @return {Base} Self for chaining
*
* @example
* radOne.defaults({ radness: 'meh' }) // applies unless configured otherwise
*/
defaults (settings) {
if (!_.isObject(settings)) this.error('Non-object received for defaults')
this.config = _.defaults({}, this.config, settings)
return this
}
/**
* Emit events using robot's event emmitter, allows listening from any module.
*
* Prepends the instance to event args, so listens can be implicitly targeted.
*
* @param {string} event Name of event
* @param {...*} [args] Arguments passed to event
*/
emit (event, ...args) {
this.robot.emit(event, this, ...args)
}
/**
* Fire callback on robot events if event ID arguement matches this instance.
*
* @param {string} event Name of event
* @param {Function} callback Function to call
*/
on (event, callback) {
let cb = (instance, ...args) => {
if (this === instance) callback(...args) // eslint-disable-line
}
this.robot.on(event, cb)
return cb
}
} |
JavaScript | class Category {
/**
* Contains all commands with corresponding categories to the category's name.
* @param {string} id The name of the category
* @param {Collection<any, any>} commands The discord.js command collection
*/
constructor(id, commands) {
/**
* The name of the category
* @type {string}
*/
this.id = id;
/**
* The discord.js command collection
* @type {Collection<any, any>}
*/
this.commands = commands;
};
} |
JavaScript | class APIError extends Error {
constructor (res, body) {
super()
/**
* This error's name.
* @type {string}
*/
this.name = 'BrawlStarsAPIError'
/**
* This error's response from Brawl Stars API.
* @type {Object}
*/
this.res = res
/**
* This error's url. (where it happened)
* @type {string}
*/
this.url = res.url
/**
* This error's code.
* @type {number}
*/
this.code = res.status
/**
* This error's headers. (Bearer access token, application/json)
* @type {Object}
*/
this.headers = res.headers
/**
* This error's reason. (what/why happened)
* @type {string}
*/
this.reason = JSON.parse(body).message
/**
* This error's message. (which is logged)
* @type {string}
*/
this.message = `${this.reason}\n🔗 ${this.url}\n`
}
} |
JavaScript | class CompanyPeople {
/**
* Constructs a new <code>CompanyPeople</code>.
* List of executives for the specified company identifier.
* @alias module:model/CompanyPeople
*/
constructor() {
CompanyPeople.initialize(this);
}
/**
* 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) {
}
/**
* Constructs a <code>CompanyPeople</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/CompanyPeople} obj Optional instance to populate.
* @return {module:model/CompanyPeople} The populated <code>CompanyPeople</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new CompanyPeople();
if (data.hasOwnProperty('fsymId')) {
obj['fsymId'] = ApiClient.convertToType(data['fsymId'], 'String');
}
if (data.hasOwnProperty('email')) {
obj['email'] = ApiClient.convertToType(data['email'], 'String');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('jobFunction1')) {
obj['jobFunction1'] = ApiClient.convertToType(data['jobFunction1'], 'String');
}
if (data.hasOwnProperty('jobFunction2')) {
obj['jobFunction2'] = ApiClient.convertToType(data['jobFunction2'], 'String');
}
if (data.hasOwnProperty('jobFunction3')) {
obj['jobFunction3'] = ApiClient.convertToType(data['jobFunction3'], 'String');
}
if (data.hasOwnProperty('jobFunction4')) {
obj['jobFunction4'] = ApiClient.convertToType(data['jobFunction4'], 'String');
}
if (data.hasOwnProperty('mainPhone')) {
obj['mainPhone'] = ApiClient.convertToType(data['mainPhone'], 'String');
}
if (data.hasOwnProperty('personId')) {
obj['personId'] = ApiClient.convertToType(data['personId'], 'String');
}
if (data.hasOwnProperty('phone')) {
obj['phone'] = ApiClient.convertToType(data['phone'], 'String');
}
if (data.hasOwnProperty('requestId')) {
obj['requestId'] = ApiClient.convertToType(data['requestId'], 'String');
}
if (data.hasOwnProperty('title')) {
obj['title'] = ApiClient.convertToType(data['title'], 'String');
}
}
return obj;
}
} |
JavaScript | class FloatingButton extends PureComponent {
static propTypes = {
/**
* The className to use for rendering the `FontIcon`.
*/
iconClassName: PropTypes.string,
/**
* Any children to use to render the `FontIcon`.
*/
children: PropTypes.node,
/**
* An optional className to apply to the button.
*/
className: PropTypes.string,
/**
* The button type.
*/
type: PropTypes.string,
/**
* Boolean if the button is disabled.
*/
disabled: PropTypes.bool,
/**
* An optional href to convert the button into a link button.
*/
href: PropTypes.string,
/**
* An optional function to call when the button is clicked.
*/
onClick: PropTypes.func,
/**
* An optional label to use if you would like a tooltip to display
* on hover or touch hold.
*/
tooltipLabel: PropTypes.node,
/**
* The position that the tooltip should be displayed relative to
* the button.
*/
tooltipPosition: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* An optional amount of delay before the tooltip appears.
*/
tooltipDelay: PropTypes.number,
/**
* Boolean if the floating button is fixed.
*/
fixed: PropTypes.bool,
/**
* Boolean if the floating button should be displayed as the mini
* version.
*/
mini: PropTypes.bool,
/**
* Boolean if the floating button should be styled with the primary color.
*/
primary: PropTypes.bool,
/**
* Boolean if the floating button should be styled with the secondary color.
*/
secondary: PropTypes.bool,
deprecated: deprecated(
'The behavior of the `FloatingButton` can be achieved with the `Button` component ' +
'without the additional bundle size. Switch to the `Button` component and add a ' +
'prop `floating`.'
),
};
render() {
const {
className,
fixed,
mini,
children,
iconClassName,
...props
} = this.props;
return (
<IconButton
{...props}
className={cn({
'md-btn--floating-fixed': fixed,
'md-btn--floating-mini': mini,
}, className)}
iconClassName={iconClassName}
floating
>
{children}
</IconButton>
);
}
} |
JavaScript | class FileImport {
/**
* Constructs a new file import.
*
* @param {Number} start - The start position of this import statement.
* @param {Number} end - The end position of this import statement.
* @param {String} name - The name of the imported data.
* @param {String} path - The path of the imported file.
* @param {String} encoding - The file encoding.
* @param {String} [data=null] - The contents of the imported file.
*/
constructor(start, end, name, path, encoding, data = null) {
/**
* The start position of this import statement.
*
* @type {Number}
*/
this.start = start;
/**
* The end position of this import statement.
*
* @type {Number}
*/
this.end = end;
/**
* The name of the imported data.
*
* @type {String}
*/
this.name = name;
/**
* The path of the imported file.
*
* @type {String}
*/
this.path = path;
/**
* The file encoding.
*
* @type {String}
*/
this.encoding = encoding;
/**
* The contents of the imported file.
*
* @type {String}
*/
this.data = data;
}
} |
JavaScript | class BeatList extends React.Component {
static propTypes = {
beats: PropTypes.array,
beatInfo: PropTypes.object,
scoreBeat: PropTypes.func,
addNewPopulation: PropTypes.func,
resetBeats: PropTypes.func,
timelineIndex: PropTypes.number,
storeDomNodes: PropTypes.func,
domNodes: PropTypes.array,
evolutionPairs: PropTypes.array,
};
static defaultProps = {
beats: [],
beatInfo: {},
scoreBeat: () => {},
addNewPopulation: () => {},
resetBeats: () => {},
timelineIndex: 0,
storeDomNodes: () => {},
}
/* Populate the array at init */
componentWillMount() {
this.setState({
clickedPlay: [],
sequences: [],
higherGenerationExists: false,
scoreZeroExists: false,
allInfoActive: false,
showArrow: false,
});
}
/* Require the Tone.js lib and set it to the state. Can only be loaded once
* the component did mount, so we set the state here. */
componentDidMount() {
const Tone = require('tone');
this.populateBeatArray(this.props);
this.setState({ Tone }, () => this.populateSequenceArray(this.props.beats));
}
/* Populate the beat array and the sequence array on new props from redux
* Don't update the sequence array when the score is changed. */
componentWillReceiveProps(nextProps) {
const nextBeats = nextProps.beats;
const beats = this.props.beats;
// Reset the clickedPlay array
this.setState({ clickedPlay: [] });
let scoreIsSame = true;
let allScoreZero = true;
/* Since setState is asynchronus. When resetting beats, we need to know if
higher generations exists to pass to the box component and score component */
let higherGenerationExists = false;
// Check if the score has changed
for (let i = 0; i < nextBeats.length; i++) {
if (!Object.is(nextBeats[i].score, beats[i].score)) scoreIsSame = false;
if (nextBeats[i].score !== 0) allScoreZero = false;
}
/* Only update the sequence array if the score has changed, or when we
* have a new population with zero score */
if (!scoreIsSame || allScoreZero) {
this.populateSequenceArray(nextProps.beats);
}
// If we have a beatlist with a higher index than this, update state.
// Used to disable the run-button and scorer
if (nextProps.timelineIndex !== nextProps.noOfGenerations - 1) {
this.setState({ higherGenerationExists: true });
higherGenerationExists = true;
} else {
this.setState({ higherGenerationExists: false });
higherGenerationExists = false;
};
this.populateBeatArray(nextProps, higherGenerationExists);
}
/* When clicking the beat to play */
onPlayClick(index) {
const { Tone, sequences } = this.state;
// Update the state with the clicked state of the beat
const clickedPlay = this.state.clickedPlay.slice();
clickedPlay[index] = !clickedPlay[index];
this.setState({ clickedPlay });
// Stop all beats first, then play.
sequences.forEach((seq, i) => stopBeat(sequences[i]));
if (clickedPlay[index]) startBeat(sequences[index]);
}
/* When clicking the button that runs the genetic algorithm. Check for score
* of the beat first. */
onGenesisClick() {
const scoreZeroExists = this.props.beats.map(beat => beat.score).includes(0);
this.setState({ scoreZeroExists });
// Remove the tooltip after 3 seconds
setTimeout(() => {this.setState({scoreZeroExists: false})}, 3000);
// Reset the scorer check after new population has been made.
if (!scoreZeroExists) ga.newPopulation(this.props, () => {
this.setState({scoreZeroExists: false});
// Set a timer for the arrow tooltip
if(this.props.timelineIndex === 0) {
this.setState({showArrow: true});
setTimeout(() => this.setState({showArrow: false}), 6000);
}
});
}
/* Click on all box refs and display their info
*/
onBeatInfoClick = () => {
let allInfoActiveState = this.state.allInfoActive;
this.setState({ allInfoActive: !allInfoActiveState });
allInfoActiveState = this.state.allInfoActive;
if (allInfoActiveState) {
for (let i = 0; i < this.props.beatInfo.noOfBeats; i++) {
this[`box${i}`].hideInfo();
}
} else {
for (let i = 0; i < this.props.beatInfo.noOfBeats; i++) {
this[`box${i}`].showInfo();
}
}
}
/* Initialize sequences and put in the state to be able to play them. */
populateSequenceArray(newBeats) {
const sequences = this.state.sequences;
for (let i = 0; i < this.props.beatInfo.noOfBeats; i++) {
sequences[i] = (initializeBeat(this.state.Tone, newBeats, this.props.beatInfo, i, this.props.timelineIndex));
}
this.setState({ sequences });
}
/* Populate the beatlist with Box components. Used when updating from redux. */
populateBeatArray(props, higherGenerationExists) {
const { beats, scoreBeat, timelineIndex, storeDomNodes, evolutionPairs, beatInfo, noOfGenerations } = props;
this.beatList = [];
beats.forEach((beat, index) => {
this.beatList.push(
<Box
id={'beat' + timelineIndex + '' + index}
beat={beat}
index={index}
timelineIndex={timelineIndex}
scoreBeat={scoreBeat}
key={beat.id}
onPlayClick={this.onPlayClick.bind(this)}
storeDomNodes={storeDomNodes}
evolutionPairs={evolutionPairs}
onRef={ref => (this[`box${index}`] = ref)}
noOfGenerations={noOfGenerations}
higherGenerationExists={higherGenerationExists}
/>);
});
}
render() {
const runButtonClass = cx('runButton', { hidden: this.state.higherGenerationExists });
const overlayClass = cx('overlay', { active: this.state.scoreZeroExists });
const arrowDownTooltipClass = cx('arrowDownTooltip', { active: this.state.showArrow && this.props.timelineIndex === 0 });
return (
<div className={s.root} id="beatList">
{ this.beatList }
<section className={s.buttons}>
<div className={s.flexGrow}>
<div
className={s.beatInfoButton}
onClick={this.onBeatInfoClick.bind(this)}
tabIndex={-10}
role="button"
>i</div>
</div>
<div
className={runButtonClass}
onClick={() => this.onGenesisClick()}
role="button"
tabIndex="-1"
>BEAT GENESIS</div>
<div className={arrowDownTooltipClass} />
<div className={overlayClass}>
Please score all beats
<div className={s.triangle} />
</div>
</section>
<Lines
domNodes={this.props.domNodes}
beatInfo={this.props.beatInfo}
evolutionPairs={this.props.evolutionPairs}
timeLineIndex={this.props.timelineIndex}
beatList={this.beatList}
/>
</div>
);
}
} |
JavaScript | class ScenarioEditingComponent extends React.Component {
constructor(props) {
super(props);
this.handleScenarioEditEvent = this.handleScenarioEditEvent.bind(this);
}
/** Pass changes back up to the index page component to update all parts of the page*/
handleScenarioEditEvent(e) {
const key = e.target.name;
const value = e.target.value;
this.props.onModelInputChange(key, value);
}
// Implement this function please!
render() {
return <> </>
}
} |
JavaScript | class Vectors {
/**
* Checks if two vectors are approximately equal.
* @param {(vec2|vec3|vec4)} u
* @param {(vec2|vec3|vec4)} v
* @param {number} [tolerance=KraGL.EPSILON]
* @return {boolean}
*/
static approx(u, v, tolerance=KraGL.EPSILON) {
if(u.length !== v.length)
throw new Error('Vectors must be the same length.');
return _.chain(_.range(u.length))
.find(i => {
return !KraGL.math.approx(u[i], v[i], tolerance);
})
.isUndefined()
.value();
}
/**
* Checks if two vectors are exactly equal.
* @param {(vec2|vec3|vec4)} u
* @param {(vec2|vec3|vec4)} v
* @return {boolean}
*/
static equal(u, v) {
if(u.length !== v.length)
throw new Error('Vectors must be the same length.');
return _.chain(_.range(u.length))
.find(i => {
return u[i] !== v[i];
})
.isUndefined()
.value();
}
/**
* Getes the glmatrix type for a vector.
* @param {(vec2|vec3|vec4)} u
* @return {type}
*/
static getType(u) {
if(u.length === 2)
return vec2;
if(u.length === 3)
return vec3;
if(u.length === 4)
return vec4;
throw new Error('Not a valid glmatrix vector type.');
}
/**
* Checks if two vectors are parallel.
* @param {(vec2|vec3|vec4)} u
* @param {(vec2|vec3|vec4)} v
* @param {number} [tolerance=KraGL.EPSILON]
* @return {boolean}
*/
static parallel(u, v, tolerance=KraGL.EPSILON) {
u = KraGL.math.toVec3(u);
v = KraGL.math.toVec3(v);
let cross = vec3.cross([], u, v);
let sin = vec3.length(cross);
return KraGL.math.approx(sin, 0, tolerance);
}
/**
* Calculates the reflection vector of some incident vector.
* See: https://www.opengl.org/sdk/docs/man/html/reflect.xhtml
* @param {vec3} i The normalized incident vector.
* @param {vec3} n The normalized surface normal vector.
* @return {vec3}
*/
static reflect(i, n) {
let scalar = 2 * vec3.dot(n, i);
let nScaled = vec3.scale([], n, scalar);
return vec3.sub([], i, nScaled);
}
/**
* Calculates the refraction vector of some incident vector.
* See: https://www.opengl.org/sdk/docs/man/html/refract.xhtml
* @param {vec3} i The normalized incident vector.
* @param {vec3} n The normalized surface normal vector.
* @param {number} eta The ratio of indices of refraction.
* @return {vec3}
*/
static refract(i, n, eta) {
let dotNI = vec3.dot(n, i);
let k = 1.0 - eta*eta * (1.0 - dotNI*dotNI);
if(k < 0)
return [0,0,0];
else {
// eta * i - (eta * dot(n, i) + sqrt(k)) * n
return vec3.sub([],
vec3.scale([], i, eta),
vec3.scale([], n, eta*dotNI + Math.sqrt(k))
);
}
}
/**
* Computes the scalar projection of v onto u. This is also the length
* of the projection of v onto u.
* You can get the projection of v onto u by scaling uHat by this value.
* @param {(vec2|vec3|vec4)} u
* @param {(vec2|vec3|vec4)} v
* @return {number}
*/
static scalarProjection(u, v) {
let clazz = this.getType(u);
let uHat = clazz.normalize([], u);
return clazz.dot(uHat, v);
}
/**
* Spherically interpolates between two vectors.
* @param {vec3} u
* @param {vec3} v
* @param {number} alpha
* @return {vec3}
*/
static slerp(u, v, alpha) {
let uHat = vec3.normalize([], u);
let vHat = vec3.normalize([], v);
let n = vec3.cross([], u, v);
let nHat = vec3.normalize([], n);
if(nHat.length === 0)
return vec3.lerp([], u, v, alpha);
let dotUVHat = vec3.dot(uHat, vHat);
let theta = Math.acos(dotUVHat) * alpha;
let lenU = vec3.len(u);
let lenV = vec3.len(v);
let length = KraGL.math.mix(alpha, [lenU, lenV]);
let q = quat.setAxisAngle([], nHat, theta);
let slerpedHat = vec3.transformQuat([], uHat, q);
return vec3.scale([], slerpedHat, length);
}
} |
JavaScript | class WT_MapViewOrientationDisplayLayer extends WT_MapViewLayer {
constructor(displayTexts, className = WT_MapViewOrientationDisplayLayer.CLASS_DEFAULT, configName = WT_MapViewOrientationDisplayLayer.CONFIG_NAME_DEFAULT) {
super(className, configName);
this._displayTexts = displayTexts;
}
_createHTMLElement() {
this._displayBox = new WT_MapViewOrientationDisplay();
return this._displayBox;
}
/**
* @param {WT_MapViewState} state
*/
onUpdate(state) {
this._displayBox.update(state, this._displayTexts);
}
} |
JavaScript | class PostAccountsTypeAccountIdRequest {
/**
* Constructs a new <code>PostAccountsTypeAccountIdRequest</code>.
* PostAccountsTypeAccountIdRequest
* @alias module:model/PostAccountsTypeAccountIdRequest
*/
constructor() {
PostAccountsTypeAccountIdRequest.initialize(this);
}
/**
* 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) {
}
/**
* Constructs a <code>PostAccountsTypeAccountIdRequest</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/PostAccountsTypeAccountIdRequest} obj Optional instance to populate.
* @return {module:model/PostAccountsTypeAccountIdRequest} The populated <code>PostAccountsTypeAccountIdRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PostAccountsTypeAccountIdRequest();
if (data.hasOwnProperty('requestedShares')) {
obj['requestedShares'] = ApiClient.convertToType(data['requestedShares'], [PostAccountsRequestedShares]);
}
}
return obj;
}
} |
JavaScript | class Page {
/**
* Constructor.
*/
constructor() {
this.currentPageUrl = null
this.requests = new Map()
this.openRequests = new Set()
}
/**
* Sets current page.
* @param {string} url Current page URL.
*/
setCurrentPage(url) {
this.currentPageUrl = url
}
/**
* Clears the page info.
*/
async clear() {
this.openRequests.clear()
this.requests.clear()
this.currentPageUrl = null
}
/**
* Indicates a request has been started.
* @param {string} requestId Request ID.
* @param {string} url Request URL.
*/
async requestStarted(requestId, url) {
try {
const parsedUrl = new URL(url)
const domain = parsedUrl.hostname
if (!this.requests.has(domain)) {
this.requests.set(domain, [])
}
this.requests.get(domain).push(true)
} catch (exception) {
console.log(
`Failed to record a started request[${requestId}=${url}]: ` +
`${exception.message}`)
}
this.openRequests.add(requestId)
}
/**
* Indicates a request has been completed
*
* @param {string} requestId Request ID.
* @param {string} url Request URL.
*/
async requestEnded(requestId, url) {
if (this.openRequests.has(requestId)) {
this.openRequests.delete(requestId)
}
//if (this.openRequests.size <= 0) {
// console.log('==============================================')
// this.requests.forEach((value, key) => {
// console.log(`${key}: ${value.length}`)
// })
//}
}
/**
* Retrieves a list of domains communicated from the current page.
* @return {!Map<string, Object>} A Map object with following keys:
* - currentPage: URL of the current page.
* - domains: Array of object with the following keys:
* - domain: Domain of a request sent from the current page.
* - requestCount: A number of requests the page requested to the
* domain.
*/
async domains() {
const result = {
currentPage: this.currentPageUrl,
}
const domains = []
this.requests.forEach((value, domain) => {
const entry = {
domain: domain,
requestCount: value.length,
}
domains.push(entry)
})
result.domains = domains
return result
}
} |
JavaScript | class Handler {
/**
* Create the tooltip handler and initialize the element and style.
*
* @param options Tooltip Options
*/
constructor(options) {
this.options = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
const elementId = this.options.id;
// bind this to call
this.call = this.tooltipHandler.bind(this);
// prepend a default stylesheet for tooltips to the head
if (!this.options.disableDefaultStyle && !document.getElementById(this.options.styleId)) {
const style = document.createElement('style');
style.setAttribute('id', this.options.styleId);
style.innerHTML = createDefaultStyle(elementId);
const head = document.head;
if (head.childNodes.length > 0) {
head.insertBefore(style, head.childNodes[0]);
}
else {
head.appendChild(style);
}
}
// append a div element that we use as a tooltip unless it already exists
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.el = document.getElementById(elementId);
if (!this.el) {
this.el = document.createElement('div');
this.el.setAttribute('id', elementId);
this.el.classList.add('vg-tooltip');
document.body.appendChild(this.el);
}
}
/**
* The tooltip handler function.
*/
tooltipHandler(handler, event, item, value) {
// console.log(handler, event, item, value);
// hide tooltip for null, undefined, or empty string values
if (value == null || value === '') {
this.el.classList.remove('visible', `${this.options.theme}-theme`);
return;
}
// set the tooltip content
this.el.innerHTML = formatValue(value, this.options.sanitize, this.options.maxDepth);
// make the tooltip visible
this.el.classList.add('visible', `${this.options.theme}-theme`);
const { x, y } = calculatePosition(event, this.el.getBoundingClientRect(), this.options.offsetX, this.options.offsetY);
this.el.setAttribute('style', `top: ${y}px; left: ${x}px`);
}
} |
JavaScript | class Server {
constructor (port, address) {
this.port = port || 5000;
this.address = address || '127.0.0.1';
// Holds our currently connected clients
this.clients = [];
}
/*
* Starting the server
* The callback argument is executed when the server finally inits
*/
start (callback) {
let server = this; // we'll use 'this' inside the callback below
server.connection = net.createServer((socket) => { // old onClientConnected
let client = new Client(socket);
console.log(`${client.name} connected.`);
// TODO: Broadcast to everyone connected the new connection
// Storing client for later usage
server.clients.push(client);
// Triggered on message received by this client
socket.on('data', (data) => {
let m = data.toString().replace(/[\n\r]*$/, '');
console.log(`${clientName} said: ${m}`);
socket.write(`We got your message (${m}). Thanks!\n`);
// TODO: Broadcasting the message to the other clients
});
// Triggered when this client disconnects
socket.on('end', () => {
// Removing the client from the list
server.clients.splice(server.clients.indexOf(client), 1);
console.log(`${client.name} disconnected.`);
// TODO: Broadcasting that this client left
});
});
// starting the server
this.connection.listen(this.port, this.address);
// setuping the callback of the start function
this.connection.on('listening', callback);
}
// TODO
broadcast(message, client) {}
} |
JavaScript | class TimeLine {
constructor(canvas){
this.canvas = canvas;
this.timeViewRange = this.canvas.vptCoords.tr.x - this.canvas.vptCoords.tl.x; // amount of time in the view window, measured in seconds
console.log("creating TimeLine", this.timeViewRange);
this.maxGridLines = 50; //the maximum number of lines on the view before rescaling
this.gridSpacing = 10; //default grid spacing before rescaling;
this.lineHeight = 50; //default height of the grid
this.viewRangeUnit = 'hour';
this.lineGroup = {};
this.tickFormats = {minor:"ha", major: "ddd d"};
this.viewRanges = {
hour: {min:"0", minorFormat:"h:mm", majorFormat: "ddd D"},
day: {min:"200000", minorFormat:"dd D", majorFormat: "MMM D"},
month: {min:"7500000", minorFormat:"MMM", majorFormat: "MMM YYYY"},
year: {min:"75000000", minorFormat:"YYYY", majorFormat: "YYYY"},
}
}
setGrid(){
// console.log("setGrid")
// determine scale display-range based on date start-end
const viewWidth = rangeEnd - rangeStart;
const lastRangeUnit = this.viewRangeUnit;
// Object.keys(this.viewRanges).forEach(key=>{console.log(key)})
Object.keys(this.viewRanges).forEach(key => {
if(viewWidth > this.viewRanges[key].min) this.viewRangeUnit = key;
});
$("#rangeMid").text(viewWidth + " - " + this.viewRangeUnit);
//if we've just switched to a new unit, then wipe the lines from the array and canvas, and set the tickLabel formats
if(this.viewRangeUnit != lastRangeUnit){
// console.log("CLEARING LINES", this.lineGroup);
// wipe group and canvas
for(const key in this.lineGroup) {
this.canvas.remove(this.lineGroup[key].tick);
this.canvas.remove(this.lineGroup[key].label);
delete this.lineGroup[key];
}
//update the tick label formats
this.tickFormats.minor = this.viewRanges[this.viewRangeUnit].minorFormat;
this.tickFormats.major = this.viewRanges[this.viewRangeUnit].majorFormat;
}
//determine start point in the middle of current screen, rounding to nearest unit
const viewMiddle = rangeEnd - (viewWidth/2);
const middleUnitMoment = moment.unix(viewMiddle).startOf(this.viewRangeUnit);
// console.log('viewMiddle', viewMiddle, middleUnitMoment.format())
//starting from midpoint, go both ways checking if there is a line at that next unit-x-point, until off-screen either way.
// GO RIGHT
let xTime = middleUnitMoment;
let x = dateToCanvas(xTime.unix());
while (x < dateToCanvas(rangeEnd)) {
// if there's not already a line at that position
//add a line
if( this.lineGroup.hasOwnProperty(x) == false){
// console.log("adding line RIGHT at", x, dateToCanvas(rangeEnd));
const line = this.createLine(x, this.canvas.height);
this.lineGroup[x] = (line);
this.canvas.add(line.tick);
this.canvas.add(line.label);
}
// add a text label
xTime.add(1,this.viewRangeUnit);
x = dateToCanvas(xTime.unix());
// console.log("new xTime", xTime.unix());
}
// NOW GO LEFT
xTime = middleUnitMoment;
x = dateToCanvas(xTime.unix());
while (x > dateToCanvas(rangeStart)) {
// if there's not already a line at that position
//add a line
if( this.lineGroup.hasOwnProperty(x) == false){
// console.log("adding line LEFT at", x, dateToCanvas(rangeEnd));
const line = this.createLine(x, this.canvas.height);
this.lineGroup[x] = (line);
this.canvas.add(line.tick);
this.canvas.add(line.label);
}
xTime.add(-1, this.viewRangeUnit);
x = dateToCanvas(xTime.unix());
// console.log("new xTime", xTime.unix());
}
// strip out any OUTSIDE the range lext or right
for(const key in this.lineGroup) {
if (this.lineGroup.hasOwnProperty.call(this.lineGroup, key)) {
const line = this.lineGroup[key].tick;
const label = this.lineGroup[key].label;
// console.log(line.left, this.canvas.vptCoords.tl.x, this.canvas.vptCoords.tr.x);
// if it's outside the range delete it
if(line.left > this.canvas.vptCoords.tr.x || line.left < this.canvas.vptCoords.tl.x){
this.canvas.remove(line);
this.canvas.remove(label);
delete this.lineGroup[key];
}
}
}
// console.log("this.lineGroup", this.lineGroup)
}
createLine(x, y){
let tickHeight = this.lineHeight;
let tickWidth = 2;
let tickColor = 'black';
let weight = 'normal';
let labelMoment = moment.unix(canvasToDate(x));
let label = "";
if(
(this.viewRangeUnit=='hour' && labelMoment.hour() == 0) ||
(this.viewRangeUnit=='day' && labelMoment.date() == 1) ||
(this.viewRangeUnit=='month' && labelMoment.month() == 0) ||
(this.viewRangeUnit=='year' && labelMoment.year() % 10 == 0)
){
label = labelMoment.format(this.tickFormats.major);
weight = 'bold';
}else{
label = labelMoment.format(this.tickFormats.minor);
tickHeight = tickHeight * 0.8;
tickWidth = tickWidth * 0.5;
tickColor = 'grey';
}
let textSize = 10;
let text = new fabric.Text(
label.toString()
,{
left: Math.round(x),
top: Math.round(y - this.lineHeight - (textSize*1.5)),
originalTop: Math.round(y - this.lineHeight - (textSize*1.5)),
fontSize: textSize,
fontFamily: 'sans-serif',
fontWeight: weight,
textAlign: 'center',
// stroke: 'black',
strokeWidth:1,
selectable: false,
evented: false,
}
);
let line = new fabric.Line([
Math.round(x),
Math.round(y),
Math.round(x),
Math.round(y + tickHeight)
],
{
originalTop: Math.round(y - tickHeight),
stroke: tickColor,
strokeWidth: tickWidth,
selectable: false,
evented: false,
}
);
return {"tick": line, "label":text};
}
} |
JavaScript | class Square {
draw() {
return 0;
}
size() {
return 0;
}
} |
JavaScript | class BadSquare {
size() {
return 0;
}
} |
JavaScript | class StaticContainer extends React.Component {
shouldComponentUpdate(nextProps) {
return !!nextProps.shouldUpdate;
}
render() {
var child = this.props.children;
return (child === null || child === false) ? null : onlyChild(child);
}
} |
JavaScript | class Book {
/**
* Creates a Book
*
* @param {Object} params The Default Values overrides.
*
* @public
*/
constructor(params) {
const defaultValues = {
name: 'Default Book Name',
author: {},
genre: genres.indeterminate,
publishDate: moment.utc([1, 1, 1]).toDate(), // year, month (zero based), day
index: 0,
};
const bookData = {
...defaultValues,
...params,
};
this.name = bookData.name;
this.author = bookData.author;
this.genre = bookData.genre;
this.publishDate = bookData.publishDate;
this.index = bookData.index;
this.horrorFlag = false;
this.financeFlag = false;
this.flagSpecialCases();
}
/**
* Checks if the release date of the book is halloween
*
* @returns {boolean}
* @public
*/
publishedInHalloween() {
// halloween case (XXXX-10-31) but month is Zero based (XXXX-09-31)
return (this.publishDate.getMonth() === 9) && (this.publishDate.getDate() === 31);
}
/**
* Checks if the publishDate occurred in the last friday of the month.
*
* @returns {boolean}
* @public
*/
publishedLastFridayOfMonth() {
const lastFriday = moment([this.publishDate.getFullYear(), this.publishDate.getMonth()]).endOf('month');
while (lastFriday.day() !== 5) {
lastFriday.subtract(1, 'days');
}
const lastFridayDate = lastFriday.toDate();
return (lastFridayDate.getDate() === this.publishDate.getDate()) &&
(lastFridayDate.getMonth() === this.publishDate.getMonth()) &&
(lastFridayDate.getFullYear() === this.publishDate.getFullYear());
}
/**
* Flags two especial cases:
* - books in the "horror" genre, published on Halloween
* - books in the "finance" genre, published on the last Friday of any month
*
* @returns {void}
* @public
*/
flagSpecialCases() {
if (this.publishedInHalloween() && (this.genre.id === genres.horror.id)) {
this.horrorFlag = true;
}
if (this.publishedLastFridayOfMonth() && (this.genre.id === genres.finance.id)) {
this.financeFlag = true;
}
}
/**
* Returns a JSON version of the instance data.
*
* @returns {{name: String, author: (Author), genre: String, publishDate: Date}}
*
* @public
*/
toJSON() {
return {
name: this.name,
author: this.author,
genre: this.genre,
publishDate: this.publishDate,
index: this.index,
};
}
} |
JavaScript | class MuteButton extends Component {
/**
* {@code MuteButton} component's property types.
*
* @static
*/
static propTypes = {
/**
* Whether or not the participant is currently audio muted.
*/
isAudioMuted: React.PropTypes.bool,
/**
* The callback to invoke when the component is clicked.
*/
onClick: React.PropTypes.func,
/**
* The ID of the participant linked to the onClick callback.
*/
participantID: React.PropTypes.string,
/**
* Invoked to obtain translated strings.
*/
t: React.PropTypes.func
};
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { isAudioMuted, onClick, participantID, t } = this.props;
const muteConfig = isAudioMuted ? {
translationKey: 'videothumbnail.muted',
muteClassName: 'mutelink disabled'
} : {
translationKey: 'videothumbnail.domute',
muteClassName: 'mutelink'
};
return (
<RemoteVideoMenuButton
buttonText = { t(muteConfig.translationKey) }
displayClass = { muteConfig.muteClassName }
iconClass = 'icon-mic-disabled'
id = { `mutelink_${participantID}` }
onClick = { onClick } />
);
}
} |
JavaScript | class CylinderFactory extends MeshFactory {
/**
* Create a new cylinder Factory object that will use the given subdivision
* parameter to generate unit cylinders centered at (0, 0, 0) aligned with Y.
* @param {number} slices The number of subdivisions around the central axis.
**/
constructor (slices) {
super()
this._count++
this._name = `Cylinder ${this._count}`
this._slices = slices || 18
}
/**
* Set the subdivisions around the outside of the cylinder.
* @param {number} newVal The number of subdivisions around the central axis.
**/
set slices (newVal) {
if (typeof newVal === 'number') {
this._slices = newVal
}
}
/**
* Build and return a THREE.Geometry() object representing a cylinder.
* @override
* @return {THREE.Geometry} The raw geometry structure (not wrapped with Mesh)
**/
makeObjectGeometry () {
// A fresh, empty Geometry object that will hold the mesh geometry
let cylGeom = new THREE.Geometry()
// TODO: Copy in your code from project 3
// Note: if you do not use cylinders in your humanoid you can skip this step
// Return finished geometry
return cylGeom
}
} |
JavaScript | class MaybeWorker {
constructor(maybeEffect) {
this.maybeEffect = maybeEffect;
this.someWorker = noop;
this.noneWorker = noop;
}
/**
* Perform action if Maybe returned Some result
* You can pass a function, generator or saga effect
*/
some(worker) {
this.someWorker = makeEffect(worker);
return this;
}
/**
* Perform action if Maybe returned None result
* You can pass a function, generator or saga effect
*/
none(worker) {
this.noneWorker = makeEffect(worker);
return this;
}
/**
* Bind redux saga routine.
* Will call routine.success if Maybe has some value
* of routine.failure if Maybe has None value.
*/
bind(routine) {
if (process.env.NODE_ENV !== 'production') {
assert(
['request', 'success', 'failure', 'fulfill'].every(t => is.func(routine[t])),
'Expected a valid redux saga routine'
);
}
this.routine = routine;
this.successMapper = this.successMapper || identity;
this.failureMapper = this.failureMapper || identity;
return this;
}
/**
* Provide some value mapper which will be passed to routine.success
* @param {any} map mapping function which acceps Some argument or any value
*/
mapSuccess(map) {
this.successMapper = makeMapper(map);
return this;
}
/**
* Provide none value mapper which will be passed to routine.failure
* @param {any} map mapping function which acceps None argument or any value
*/
mapFailure(map) {
this.failureMapper = makeMapper(map);
return this;
}
/**
* Returns create redux saga call effect
*/
run() {
const dispatchRoutines = !!this.routine;
const runner = function* () {
if (dispatchRoutines) {
yield put(this.routine.request());
}
try {
const some = yield this.maybeEffect;
if (dispatchRoutines) {
yield pipe(
this.successMapper,
this.routine.success,
put
)(some);
}
yield this.someWorker(some);
return { some };
} catch (error) {
if (process.env.NODE_ENV === 'production') {
console.error(error, error.message); // eslint-disable-line
}
if (dispatchRoutines) {
yield pipe(
this.failureMapper,
this.routine.failure,
put
)(error);
}
yield this.noneWorker(error);
return { none: error };
} finally {
if (dispatchRoutines) {
yield put(this.routine.fulfill());
}
}
};
return call([this, runner]);
}
} |
JavaScript | class ParentDispatcher extends EventEmitter {
constructor({ log, handleReduceSelf, handleDispatch } = {}) {
super()
should.exist(this.log)
should.exist(handleReduceSelf)
should.exist(handleDispatch)
this.log = log
this.handleReduceSelf = handleReduceSelf
this.handleDispatch = handleDispatch
}
init = () => new Promise((resolve, reject) => {
process.on('message', action => {
if(!action || !action.type) return
const { type, meta, payload, error } = action
if(error) return this.log.error({ action }, 'RECEIVE_ERROR')
/** CAN BE ORDERED TO REDUCE OR DISPATCH BY ITS PARENT, MUST SIGNAL FINALIZERS BACK */
switch(meta) {
case __.REDUCE:
this._reduceSelf(action)
break
case __.DISPATCH:
this.dispatch(action)
break
case __.DISPATCH_PARENT_END:
this._dispatchParentEnd(action)
break
}
})
});
/** Starts the dispatch */
dispatch = action => {
console.warn('dispatch called (parent-dispatcher)')
this.dispatch(action)
process.send({ type: 'INTERNAL', meta: __.DISPATCH_END, otherOtherMeta: 'BLAAAAAH' })
};
dispatchParent = action => {
if(process.send)
process.send({ ...action, meta: __.DISPATCH, otherMeta: 'BLAHBLAH' })
};
_dispatchParentEnd = action => {
this.handleDispatchParent({ type: 'DISPATCH_PARENT_END', meta: 'BLAH'})
};
/** Starts the reduce */
_reduceSelf = action => {
console.warn('reduce called')
this.handleReduceSelf(action)
process.send({ msg: 'REDUCE SELF'})
};
} |
JavaScript | class Sheet extends React.Component {
constructor(props) {
super(props);
this.state = {loading: true}; /// Note: Equivalent to <getInitialState()>.
}
/**
* Listen for keystrokes and events then get initial state data.
*/
componentDidMount() {
this._setKeystrokeListeners();
ReactCsvStore.addChangeListener(this._onChange.bind(this));
ReactCsvActions.initializeDataStore({
numRows: this.props.numRows,
numCols: this.props.numCols,
loading: false
});
}
/**
* Remove the change listener to save memory once the component disappears.
*/
componentWillUnmount() {
document.onkeydown = null;
ReactCsvStore.removeChangeListener(this._onChange.bind(this));
}
/**
* Update state with the new change and enable undo.
* @param {object} e A DOM event object.
*/
_saveChange(e) {
ReactCsvActions.save(e);
}
/**
* Update form input value on change without impacting undo or redo.
* @param {object} e A DOM event object.
*/
_updateValue(e) {
var wasNotEnterKey = !(e.keyCode === 13 || e.which === 13);
if (wasNotEnterKey) {
ReactCsvActions.updateValue(e);
}
}
/**
* Listen for keystrokes to activate the <undo()> and <redo()> functions.
*/
_setKeystrokeListeners() {
document.onkeydown = function(e) { /// Undo: CTRL-Z | Redo: CTRL-Y
if (e.ctrlKey &&
(e.key === 'z' || e.keyCode === 90 || e.which === 90) &&
this.state.tableUndo.length > 0) {
ReactCsvActions.undo();
} else if (e.ctrlKey &&
(e.key === 'y' || e.keyCode === 89 || e.which === 89) &&
this.state.tableRedo.length > 0) {
ReactCsvActions.redo();
}
}.bind(this);
}
/**
* Render the CSV table but only after the data has loaded into state.
* @return {object} A reference to the DOM component.
*/
render() {
// Display loading message.
if (this.state.loading === true) {
return (
<div>
<p className="italic">Loading...</p>
</div>
);
}
// Display table with data.
const cols = this.props.numCols;
const rows = this.props.numRows;
const table = this.state.tablePending;
const update = this._updateValue.bind(this);
const save = this._saveChange.bind(this);
return (
<div>
<table className="table-light overflow-hidden bg-white border">
<HeaderRow numCols={cols}
csv={table}
update={update}
saveChange={save} />
<BodyRows numCols={cols}
numRows={this.props.hasFooter ? rows-2 : rows-1}
csv={table}
update={update}
saveChange={save} />
{this.props.hasFooter ? <FooterRow numCols={cols}
numRows={rows-1}
csv={table}
update={update}
saveChange={save} />
: null}
</table>
<Toolbar csv={table}
showExport={this.props.showExportButton} />
</div>
);
}
/**
* Event handler f or "change" events coming from the ReactCsvStore.
*/
_onChange() {
this.setState(ReactCsvStore.getAll());
}
} |
JavaScript | class TrapThemePF extends D20TrapTheme {
/**
* @inheritdoc
*/
get name() {
return 'Pathfinder';
}
/**
* @inheritdoc
*/
getAC(character) {
return TrapTheme.getSheetAttr(character, 'AC');
}
/**
* @inheritdoc
*/
getPassivePerception(character) {
return TrapTheme.getSheetAttr(character, 'Perception')
.then(perception => {
return perception + 10;
});
}
/**
* @inheritdoc
*/
getSaveBonus(character, saveName) {
return TrapTheme.getSheetAttr(character, SAVE_NAMES[saveName]);
}
/**
* @inheritdoc
*/
getThemeProperties(trapToken) {
let result = super.getThemeProperties(trapToken);
let save = _.find(result, item => {
return item.id === 'save';
});
save.options = [ 'none', 'fort', 'ref', 'will' ];
return result;
}
/**
* @inheritdoc
* Also supports the Trap Spotter ability.
*/
passiveSearch(trap, charToken) {
super.passiveSearch(trap, charToken);
let character = getObj('character', charToken.get('represents'));
let effect = (new TrapEffect(trap, charToken)).json;
// Perform automated behavior for Trap Spotter.
if((effect.type === 'trap' || _.isUndefined(effect.type)) && effect.spotDC && character) {
TrapTheme.getSheetRepeatingRow(character, 'class-ability', rowAttrs => {
if(!rowAttrs.name)
return false;
let abilityName = rowAttrs.name.get('current');
return abilityName.toLowerCase().includes('trap spotter');
})
.then(trapSpotter => {
let dist = ItsATrap.getSearchDistance(trap, charToken);
if(trapSpotter && dist <= 10)
this._trapSpotter(character, trap, effect);
})
.catch(err => {
sendChat('Trap theme: ' + this.name, '/w gm ' + err.message);
log(err.stack);
});
}
}
/**
* Trap Spotter behavior.
* @private
*/
_trapSpotter(character, trap, effect) {
// Quit early if this character has already attempted to trap-spot
// this trap.
let trapId = trap.get('_id');
let charId = trap.get('_id');
if(!state.TrapThemePathfinder.trapSpotterAttempts[trapId])
state.TrapThemePathfinder.trapSpotterAttempts[trapId] = {};
if(state.TrapThemePathfinder.trapSpotterAttempts[trapId][charId])
return;
else
state.TrapThemePathfinder.trapSpotterAttempts[trapId][charId] = true;
// Make a hidden Perception check to try to notice the trap.
TrapTheme.getSheetAttr(character, 'Perception')
.then(perception => {
if(_.isNumber(perception)) {
return TrapTheme.rollAsync('1d20 + perception');
}
else
throw new Error('Trap Spotter: Could not get Perception value for Character ' + charToken.get('_id') + '.');
})
.then(searchResult => {
// Inform the GM about the Trap Spotter attempt.
sendChat('Trap theme: ' + this.name, `/w gm ${character.get('name')} attempted to notice trap "${trap.get('name')}" with Trap Spotter ability. Perception ${searchResult.total} vs DC ${effect.spotDC}`);
// Resolve whether the trap was spotted or not.
if(searchResult.total >= effect.spotDC) {
let html = TrapTheme.htmlNoticeTrap(character, trap);
ItsATrap.noticeTrap(trap, html.toString(TrapTheme.css));
}
})
.catch(err => {
sendChat('Trap theme: ' + this.name, '/w gm ' + err.message);
log(err.stack);
});
}
} |
JavaScript | class Network {
constructor({
learningRate = 0.03,
layers,
weights,
epoch = 0,
activation = Utils.ActivationFunctions.tanh,
error = Utils.ErrorFunctions.linear,
globalError = 0
} = {}) {
// Two-dimensional array of layers and neurons in each layer
this.layers = layers
// Array of weight matrices between layers
this.weights = weights
// Learning Rate for back-propagation
this.learningRate = learningRate
// Activation function to pass to neurons
this.activation = activation
// Error function for back-propagation
this.error = error
// Current epoch (iteration) of the neural network
this.epoch = epoch
// Global network error
this.globalError = globalError
}
/**
* Initialize and return a new Network object
*
* @static
* @param {*} layers
* @returns
* @memberof Network
*/
static initialize(layers) {
return new Network({
layers: this.createLayers(layers),
weights: this.createWeights(layers)
})
}
/**
* Given an array of layers each containing a number representing the number
* of nodes in that layer,return an array layers containing that number of
* neurons in each layer.
*
* e.g., [2, 3, 4, 2]
* Input layer - 2 neurons
* Hidden layer 1 - 3 neurons
* Hidden layer 2- 4 neurons
* Output layer - 2 neurons
*
* @static
* @param {*} layers
* @memberof Network
*/
static createLayers(layers = []) {
return layers
.map(layer => Array(layer).fill({}))
.map(layer =>
layer.map(
(node, i) => new Neuron(i, { activation: this.activation, ...node })
)
)
}
/**
* Return an array of weight matrices from the provided array of layers.
* A matrix is generated for every pair of layers.
*
* e.g., If there are 6 layers including input and output layers, an array
* of 5 matrices is returned corresponding to the following pairs of layers:
* [0-1, 1-2, 2-3, 3-4, 4-5]
*
* If layer 1 has 2 neurons and layer 2 has 3 neurons, the resulting matrix is:
* | w11 w21 |
* | w12 w22 |
* | w13 w23 |
*
* @static
* @param {*} [layers=[]]
* @memberof Network
*/
static createWeights(layers = []) {
const weights = []
// For every layer
for (let i = 0; i < layers.length - 1; i++) {
const current = layers[i],
next = layers[i + 1]
const matrix = []
// For every node in the next layer
for (let j = 0; j < next; j++) {
const row = []
// For every node in this layer
for (let k = 0; k < current; k++) {
row[k] = Math.random() * 2 - 1
}
matrix.push(row)
}
weights.push(matrix)
}
return weights
}
/**
* Get an array of neurons in the input layer
*
* @readonly
* @memberof Network
*/
get inputLayer() {
return this.layers[0] || []
}
/**
* Get an array of the hidden layers (each of which is an array of neurons)
*
* @readonly
* @memberof Network
*/
get hiddenLayers() {
return this.layers.slice(1, this.layers.length - 1) || []
}
/**
* Get an array of neurons in the output layer
*
* @readonly
* @memberof Network
*/
get outputLayer() {
return this.layers[this.layers.length - 1] || []
}
/**
* Feed-forward algorithm to update weights
*
* @param {*} [inputs=[]] Array of inputs for every node in the input layer
* @memberof Network
*/
feedForward(inputs = []) {
// Set the outputs of the input layer to these inputs
this.inputLayer.forEach((node, i) => (node.output = inputs[i]))
// Update the outputs of every node in every layer after the input layer
this.layers.forEach((layer, i) => {
if (i === 0) return
// For every node on this layer...
layer.forEach((node, j) => {
// Calculate the product of this node with every node in the prev. layer
let input = node.bias
// For every node on the previous layer...
this.layers[i - 1].forEach((prevNode, k) => {
// Calculate w1 * x1 + w2 * x2 + ... + wn * xn
// weights[][][]
// First array - weight matrices. Index 0 -> array btwn layers 0 and 1
// Second array - node on the *current* layer
// Third array - node on the *previous* layer
input += this.weights[i - 1][j][k] * prevNode.output
})
// Calculate the new output based on the activation function
node.output = this.activation.func(input)
})
})
}
/**
* Back-propagation of errors to update weights
*
* @param {number} [target=0] Target value for the output
* @memberof Network
*/
backPropagate(target = 0) {
// Reset global network error
this.globalError = 0
// Compute output layer error (error = 1/2(output - target)^2)
// For the output node, use the network's error function for the derivative
this.outputLayer.forEach(node => {
// Calculate error and bias
node.error =
this.error.func(node.output, target) *
this.error.der(node.output, target)
node.bias -= this.learningRate * node.error
// Update global network error
this.globalError += Math.abs(node.error)
})
// Propagate error backwards through the layers in the network
for (let i = this.layers.length - 1; i >= 1; i--) {
const layer = this.layers[i]
const prevLayer = this.layers[i - 1]
const weights = this.weights[i - 1]
// Calculate error for every neuron in each layer based on the next layer
prevLayer.forEach((prevNode, j) => {
// Compute error (e = (w1 * e1 + w2 * e2 + ... + wn * en) * output)
let sum = layer.reduce(
(sum, node, k) => sum + weights[k][j] * node.error,
0
)
// Calculate error and bias
prevNode.error = sum * this.error.der(prevNode.output, target)
prevNode.bias -= this.learningRate * prevNode.error
// Update global network error
this.globalError += Math.abs(prevNode.error)
// Update weights (w = w + lr * en * output)
layer.forEach((node, k) => {
weights[k][j] -= this.learningRate * node.error * prevNode.output
})
})
}
}
/**
* Execute a single epoch for this neural network
*
* @param {*} inputs Array of points each with an associated value
* @memberof Network
*/
runOnce(inputs) {
// Scale inputs to values from range [-5, 5] to [-1, 1]
const scaledInputs = inputs.map(input => ({
x: (2 * (input.x + 5)) / 10 - 1,
y: (2 * (input.y + 5)) / 10 - 1,
value: input.value
}))
const logs = []
// For each input, feedforward and back-propagate
scaledInputs.forEach((input, i) => {
// Feed input features into network
this.feedForward([input.x, input.y])
// Pass expected output to network to calc error
this.backPropagate(input.value)
// Log inputs and output
logs.push({
x: inputs[i].x,
y: inputs[i].y,
expectedOutput: input.value,
actualOutput: this.outputLayer[0].output,
error: this.outputLayer[0].output - input.value
})
})
// Print the log to the console
console.clear()
console.table({ epoch: this.epoch })
console.table(logs)
this.epoch++
}
} |
JavaScript | class AboutView {
// #
// #
// ### ## ###
// # # # ## #
// ## ## #
// # ## ##
// ###
/**
* Gets the rendered about page template.
* @returns {string} An HTML string of the about page.
*/
static get() {
return /* html */`
<div id="about">
<div class="section">About the Overload Teams League</div>
<div class="text">
The Overload Teams League is a community of players who compete in the game <a href="https://playoverload.com" target="_blank">Overload</a>, a Six Degrees of Freedom First Person Shooter by Revival Productions.<br /><br />
To play, join the Discord server (link is at the bottom of the page), where you may join an existing team or create your own. For rules specific to the league, please see the Rules section on the Discord server.
</div>
<div class="section">Available Maps</div>
<div class="text">
For a complete list of maps available to play in the OTL, visit the <a href="/maplist">map list</a>.
</div>
<div class="section">Discord Bot Commands</div>
<div class="text">
The following commands are available on the Discord server. You may issue most commands in any channel, or in private messages to The Fourth Sovereign. Don't worry, she won't try to absorb your consciousness into her own.
</div>
<div id="commands">
<div class="header">Command</div>
<div class="header">Description</div>
<div class="header">Examples</div>
<div class="section">Basic Commands</div>
<div class="command">!help</div>
<div>Get a link to this page.</div>
<div class="example">!help</div>
<div class="command">!version</div>
<div>Get the version of the bot.</div>
<div class="example">!version</div>
<div class="command">!website</div>
<div>Get a link to the website.</div>
<div class="example">!website</div>
<div class="command">!maplist</div>
<div>Get a link to the map list.</div>
<div class="example">!maplist</div>
<div class="command">!testing</div>
<div>Adds you to the publicly mentionable Testing Discord role.</div>
<div class="example">!testing</div>
<div class="command">!stoptesting</div>
<div>Removes you from the publicly mentionable Testing Discord role.</div>
<div class="example">!stoptesting</div>
<div class="command">!timezone [<timezone>]</div>
<div>Changes your personal time zone. See #timezone-faq on the Discord server for details. Pass no parameters to clear your timezone.</div>
<div class="example">!timezone America/Los_Angeles<br />!timezone Europe/Berlin<br />!timezone</div>
<div class="command">!twitch <channel></div>
<div>Sets your Twitch channel. Useful if you will be streaming your team's matches, or if you will be casting matches.</div>
<div class="example">!twitch kantor</div>
<div class="command">!removetwitch</div>
<div>Unsets your Twitch channel.</div>
<div class="example">!removetwitch</div>
<div class="command">!homes [team]</div>
<div>Gets the current list of home levels for either your team or the specified team.</div>
<div class="example">!homes<br />!homes CF<br />!homes Cronus Frontier</div>
<div class="command">!neutrals [team]</div>
<div>Gets the current list of preferred neutral levels for either your team or the specified team.</div>
<div class="example">!neutrals<br />!neutrals CF<br />!neutrals Cronus Frontier</div>
<div class="command">!next [time]</div>
<div>List the upcoming scheduled matches and events. Displays a countdown by default, use the "time" parameter to display times in your local time zone instead.</div>
<div class="example">!next<br />!next time</div>
<div class="command">!mynext [time]</div>
<div>List the upcoming scheduled matches for your team. Displays a countdown by default, use the "time" parameter to display times in your local time zone instead.</div>
<div class="example">!next<br />!mynext time</div>
<div class="command">!matchtime <challengeId></div>
<div>Gets the match time in your local time zone.</div>
<div class="example">!matchtime 12</div>
<div class="command">!countdown <challengeId></div>
<div>Gets the amount of time until the match begins.</div>
<div class="example">!countdown 12</div>
<div class="command">!cast (<challengeId>|<wbr />next)</div>
<div>Indicates that you wish to cast a scheduled match that you are not playing in. You can get the challenge ID from the #scheduled-matches channel on Discord. You will join the challenge channel and be able to coordinate your efforts with both teams. You can see what match is next by using the word "next" instead of a challenge ID.</div>
<div class="example">!cast 1<br />!cast next</div>
<div class="command">!uncast</div>
<div>You must use this command in a challenge room you are casting a match for. Indicates that you no longer wish to cast a scheduled match.</div>
<div class="example">!uncast</div>
<div class="command">!vod <challengeId> <url></div>
<div>Post a video on demand for a match that you cast. Only works if you !cast the match. The challengeId will be messaged to you by the bot upon the closure of the match.</div>
<div class="example">!vod 1 https://twitch.tv/videos/12345678</div>
<div class="command">!stats [<pilot>]</div>
<div>Gets the current season stats for the player, or yourself if used without mentioning a pilot.</div>
<div class="example">!stats @Kantor<br />!stats</div>
<div class="command">!request <team></div>
<div>Request to join a team.</div>
<div class="example">!request CF<br />!request Cronus Frontier</div>
<div class="command">!accept <team></div>
<div>Accepts an invitation to join a team.</div>
<div class="example">!accept CF<br />!accept Cronus Frontier</div>
<div class="command">!leave</div>
<div>Leaves your current team.</div>
<div class="example">!leave</div>
<div class="section">Team Creation</div>
<div class="command">!createteam</div>
<div>Begins the process of creating a new team. This will create a new channel where you can complete creation of your team.</div>
<div class="example">!createteam</div>
<div class="command">!name <name></div>
<div>Names your team. Must be between 6 and 25 characters. Use only alpha-numeric characters and spaces.</div>
<div class="example">!name Cronus Frontier</div>
<div class="command">!tag <tag></div>
<div>Creates a tag for that represents your team in short form. Must be 5 characters or less. Use only alpha-numeric characters.</div>
<div class="example">!tag CF</div>
<div class="command">!cancel</div>
<div>Cancels the process of creating a new team, removing the new team channel.</div>
<div class="example">!cancel</div>
<div class="command">!complete</div>
<div>Completes the process of creating a new team. This will create four new channels for use by your new team. There are two text channels and two voice channels, one of each for the team and one of each for the team's leadership. Your team will also be officially added to the website.</div>
<div class="example">!complete</div>
<div class="section">Team Management</div>
<div class="command">!color<br />[(light|<wbr />dark)]<br />(red|<wbr />orange|<wbr />yellow|<wbr />green|<wbr />blue|<wbr />purple)</div>
<div>Founder only. Gives your team role a color on the Discord server.</div>
<div class="example">!color red<br />!color dark green</div>
<div class="command">!teamtimezone <timezone></div>
<div>Changes your team's time zone. See #timezone-faq on the Discord server for details.</div>
<div class="example">!teamtimezone America/Los_Angeles<br />!teamtimezone Europe/Berlin</div>
<div class="command">!addhome (CTF|<wbr />2v2|<wbr />3v3|<wbr />4v4+) <map></div>
<div>Founder or Captain only. Adds a home map for your team. You must have 5 home maps set for each game type before you can issue a challenge. You can have no more than 5 maps.</div>
<div class="example">!addhome 2v2 Vault<br />!addhome 4v4+ Syrinx<br />!addhome CTF Halcyon</div>
<div class="command">!removehome (CTF|<wbr />2v2|<wbr />3v3|<wbr />4v4+) <map></div>
<div>Founder or Captain only. Removes a home map for your team. You must have 5 home maps set for each game type before you can issue a challenge.</div>
<div class="example">!removehome 2v2 Vault<br />!removehome 4v4+ Syrinx<br />!removehome CTF Halcyon</div>
<div class="command">!addneutral (CTF|<wbr />2v2|<wbr />3v3|<wbr />4v4+) <map></div>
<div>Founder or Captain only. Adds a neutral map for your team. Having a neutral map list is optional.</div>
<div class="example">!addneutral 2v2 Vault<br />!addneutral 4v4+ Syrinx<br />!addneutral CTF Halcyon</div>
<div class="command">!removeneutral (CTF|<wbr />2v2|<wbr />3v3|<wbr />4v4+) <map></div>
<div>Founder or Captain only. Removes a neutral map for your team.</div>
<div class="example">!removeneutral 2v2 Vault<br />!removeneutral 4v4+ Syrinx<br />!removeneutral CTF Halcyon</div>
<div class="command">!invite <pilot></div>
<div>Founder or Captain only. Invites a pilot to your team. You must have 2 pilots on your team before you can issue a challenge.</div>
<div class="example">!invite @Kantor</div>
<div class="command">!remove <pilot></div>
<div>Founder or Captain only. Removes a pilot from the team, or cancels a request or invitation from the pilot.</div>
<div class="example">!remove @Kantor</div>
<div class="command">!addcaptain <pilot></div>
<div>Founder only. Adds a captain from your roster to your team, up to two captains.</div>
<div class="example">!addcaptain @Kantor</div>
<div class="command">!removecaptain <pilot></div>
<div>Founder only. Removes a captain from your team. The player will remain on your roster.</div>
<div class="example">!removecaptain @Kantor</div>
<div class="command">!disband</div>
<div>Founder only. Disbands your team. Clears your roster (including you), removes your team channels, and sets your team as disbanded on the website.</div>
<div class="example">!disband</div>
<div class="command">!makefounder <pilot></div>
<div>Founder only. Transfers ownership of your team to another pilot. You remain on the roster as a captain. Note that if this puts your team above the team limit of 2 captains, you cannot issue this command until you remove another captain.</div>
<div class="example">!makefounder @Kantor</div>
<div class="command">!reinstate <team></div>
<div>Reinstates a disbanded team. You must have previously been a founder or captain of the team you are trying to reinstate.</div>
<div class="example">!reinstate CF<br />!reinstate Cronus Frontier</div>
<div class="command">!challenge <team> (TA|<wbr />CTF)</div>
<div>Founder or Captain only. Challenges another team to a match. Creates a challenge channel where you can negotiate the match parameters with the other team. You can optionally include the game type.</div>
<div class="example">!challenge CF<br />!challenge Cronus Frontier TA</div>
<div class="section">Challenges (Only allowed in challenge channels)</div>
<div class="command">!convert (<date and time>|<wbr />now)</div>
<div>Converts a date and time to everyone's time zone in the challenge room. If you omit the date or year, it will use what the date or year will be the next time it is the entered time. Uses your personal time zone.</div>
<div class="example">!convert 3/14 3:00 PM<br />!convert Mar 14 15:00<br />!convert 3:00 PM<br />!convert now</div>
<div class="command">!matchtime</div>
<div>Gets the match time in your local time zone.</div>
<div class="example">!matchtime</div>
<div class="command">!countdown</div>
<div>Gets the amount of time until the match begins.</div>
<div class="example">!countdown</div>
<div class="command">!deadline</div>
<div>Gets the clock deadilne in your local time zone.</div>
<div class="example">!deadline</div>
<div class="command">!deadlinecountdown</div>
<div>Gets the amount of time until the clock deadline expires.</div>
<div class="example">!deadlinecountdown</div>
<div class="command">!stream<br />!streaming</div>
<div>Indicates that you will be streaming this match as you play it.</div>
<div class="example">!stream<br />!streaming</div>
<div class="command">!notstreaming</div>
<div>Indicates that you will not be streaming this match as you play it. This is the default, you only need to issue this command if you previously used the !streaming command but no longer will be streaming the match as you play.</div>
<div class="example">!notstreaming</div>
<div class="command">!pickmap (a|<wbr />b|<wbr />c|<wbr />d|<wbr />e)</div>
<div>Founder or Captain only. Picks a map from the home map team's home maps and locks in that map for the match. Cannot be used once the map is locked in.</div>
<div class="example">!pickmap b</div>
<div class="command">!suggestmap <map></div>
<div>Founder or Captain only. Suggests a neutral map. The suggested map cannot be one of the home map team's home maps. Cannot be used once the map is locked in.</div>
<div class="example">!suggestmap Vault</div>
<div class="command">!suggestrandommap [(top|<wbr />bottom) <count>]</div>
<div>Founder or Captain only. Suggests a random map. This will choose a map for the game type that's been played on the OTL before, but is not one of the home map team's home maps. You can limit the random selection to the most popular (top) or least popular (bottom) maps in the league.</div>
<div class="example">!suggestrandommap<br />!suggestrandommap top 10<br />!suggestrandommap bottom 20</div>
<div class="command">!confirmmap</div>
<div>Founder or Captain only. Confirms a neutral map suggestion from the other team and locks in that map for the match. Cannot be used once the map is locked in.</div>
<div class="example">!confirmmap</div>
<div class="command">!suggestteamsize (2|<wbr />3|<wbr />4|<wbr />5|<wbr />6|<wbr />7|<wbr />8)</div>
<div>Founder or Captain only. Suggests the team size for the match.</div>
<div class="example">!suggestteamsize 3</div>
<div class="command">!confirmteamsize</div>
<div>Founder or Captain only. Confirms a team size suggestion from the other team.</div>
<div class="example">!confirmteamsize</div>
<div class="command">!suggesttype (TA|<wbr />CTF)</div>
<div>Founder or Captain only. Suggests the game type for the match.</div>
<div class="example">!suggesttype CTF</div>
<div class="command">!confirmtype</div>
<div>Founder or Captain only. Confirms a game type suggestion from the other team.</div>
<div class="example">!confirmtype</div>
<div class="command">!suggesttime (<date and time>|<wbr />now)</div>
<div>Founder or Captain only. Suggests a date and time for the challenge. If you omit the date or year, it will use what the date or year will be the next time it is the entered time. Uses your personal time zone.</div>
<div class="example">!suggesttime 3/14 3:00 PM<br />!suggesttime Mar 14 15:00<br />!suggesttime 3:00 PM<br />!suggesttime now</div>
<div class="command">!confirmtime</div>
<div>Founder or Captain only. Confirms a match time suggestion from the other team.</div>
<div class="example">!confirmtime</div>
<div class="command">!clock</div>
<div>Founder or Captain only. Puts a challenge on the clock, giving both teams 28 days to schedule and play the match. Limits apply, see #challenges on the Discord server for details.</div>
<div class="example">!clock</div>
<div class="command">!report (<score1> <score2>|<tracker url>)</div>
<div>Founder or Captain only. Reports the score, indicating that your team has not won the match.</div>
<div class="example">!report 62 39<br />!report 45 78<br />!report 63 63<br />!report https://tracker.otl.gg/archive/12345</div>
<div class="command">!confirm</div>
<div>Founder or Captain only. Confirms the score reported by the other team.</div>
<div class="example">!confirm</div>
<div class="command">!rematch</div>
<div>Founder or Captain only. Requests a rematch. Both teams must enter this command. Once that happens, this will create a new challenge room with normal parameters, except the team size will remain the same as the previous match and the match time will be set to start immediately.</div>
<div class="example">!rematch</div>
</div>
</div>
`;
}
} |
JavaScript | class Authentication extends Middleware {
/**
* Flags all clients as not authenticated first.
* @param client
*/
install(client) {
client._authenticated = false;
}
/**
* Executes 'authenticateConnection' for every new 'connect'. Sends
* 'connack' with 'returnCode: 4' and dismisses packet if authentication
* fails
*
* @param client
* @param packet
* @param next
* @param done
*/
handle(client, packet, next, done) {
if (packet.cmd == 'connect') {
if (!client._authenticated) {
let store = {};
this.stack.execute('authenticateConnection', {
client: client,
packet: packet,
username: packet.username,
password: packet.password
}, store, function (err) {
if (err) return next(err);
if (store.valid) {
client._authenticated = true;
return next();
} else {
return client.write({
cmd: 'connack',
returnCode: 4
}, done);
}
});
}
} else {
return next();
}
}
} |
JavaScript | class EnemyPool {
constructor() {
this.items = [];
this.keys = [];
}
addItem(item) {
this.items.push(item);
this.keys.push(this.items.length-1);
}
getItem(k) {
return this.items[k];
}
getRandomKey() {
if(!this.keys.length) {
return false;
}
let i = Math.floor(Math.random() * this.keys.length);
let k = this.keys.splice(i, 1)[0];
return k;
}
returnKey(k) {
this.keys.push(k);
}
reset() {
this.items = [];
this.keys = [];
}
} |
JavaScript | class NatureManager {
constructor() {
this.config = {
"remove_z": {
"ground": 50,
"earth": 250
},
"levels": {
"playground": {
"max_amount": 20,
"z_distance": 5,
"z_distance_rand": [1, 3],
"x_random_range": [-2.5, 2.5],
"remove_z": 20,
"spawn": null
},
"first": {
"max_amount": 20, // 25 for z_distance = 4 is optimal
"z_distance": 5,
"z_distance_rand": [1, 4],
"remove_z": 20,
"spawn": null
},
"second": {
"max_amount": 20,
"z_distance": 10,
"z_distance_rand": [1, 4],
"remove_z": 20,
"spawn": null
},
"third": {
"max_amount": 10,
"z_distance": 30,
"z_distance_rand": [1, 7],
"remove_z": 20,
"spawn": null
},
"water": {
"max_amount": 10,
"z_distance": 20,
"z_distance_rand": [1, 4],
"remove_z": 20,
"spawn": null // will be set at game start
},
"water2": {
"max_amount": 20,
"z_distance": 10,
"z_distance_rand": [1, 2],
"remove_z": 20,
"spawn": null // will be set at game start
},
"empty": {
"max_amount": 20,
"z_distance": 10,
"z_distance_rand": [1, 4],
"remove_z": 20,
"spawn": null // will be set at game start
},
},
"misc_items": {
"PalmTree": {
"rescale_rand": [2, 3],
"x_random_range": [-3, 3]
},
"tumbleweed": {
"rescale_rand": [.6, .8],
"x_random_range": [-3, 3],
"random_rotate_vel": [0.01, 0.1],
"y_rotate": -(Math.PI / 2),
"rotate_direction": 'z',
"behavior": 'roll'
},
"cactus": {
"rescale_rand": [.6, 1.2],
"x_random_range": [-3, 3],
"y_random_rotate": [-80, 80]
},
"desert_skull": {
"rescale_rand": [.15, .3],
"x_random_range": [-3, 3],
"z_random_rotate": [-60, 60],
"y_random_rotate": [-30, 30]
},
"scorpion": {
"rescale_rand": [.3, .7], // [.3, .7]
"x_random_range": [-3, 3],
"y_random_rotate": [-40, 40]
},
"rocks": {
"rescale_rand": [.5, 3],
"x_random_range": [-3, 3],
},
"flowers": {
"rescale_rand": [.7, 1.3],
"x_random_range": [-3, 3],
},
"trees": {
"rescale_rand": [.8, 3],
"x_random_range": [-3, 3],
"y_random_rotate": [-80, 80]
},
"fish": {
"rescale_rand": [.1, .4],
"x_random_range": [-2.5, 2.5],
"y_random_rotate": [-60, 60]
},
"seaweed": {
"rescale_rand": [.3, 1],
"x_random_range": [-2.5, 2.5],
"y_random_rotate": [-60, 60]
}
}
}
this.earth_chunks = [];
this.ground_chunks = [];
this.ground_chunks_decoration = [];
this.ground_chunks_decoration_levels = [];
this.water = null;
this.rocks = [];
this.flowers = [];
this.misc = {};
this.cache = {
"earth": {
"box": null,
"geometry": null,
"material": null,
"texture": null
},
"ground": {
"box": null,
"geometry": null,
"material": null
},
"ground_decoration": {
"box": null,
"geometry": null,
"material": null
},
"water": {
"geometry": null,
"material": null
},
"rocks": {
"geometry": null,
"material": null
},
"flowers": {
"geometry": null,
"material": null
},
"misc": {
"geometry": null,
"material": null
}
};
}
initEarth(chunks = 3) {
// earth
if(!this.cache.earth.geometry) {
this.cache.earth.texture = load_manager.get_texture('t_ground').top;
this.cache.earth.texture.wrapS = this.cache.earth.texture.wrapT = THREE.RepeatWrapping;
this.cache.earth.texture.offset.set( 0, 0 );
this.cache.earth.texture.repeat.set( 100 / 8, 250 / 16 );
this.cache.earth.geometry = new THREE.BoxGeometry( 100, 0, 250 );
this.cache.earth.material = new THREE.MeshLambertMaterial( {map: this.cache.earth.texture} ); // 0xD6B161
}
for(let i = 0; i < chunks; i++) {
let chunk = new THREE.Mesh(this.cache.earth.geometry, this.cache.earth.material);
chunk.receiveShadow = true;
chunk.position.x = 0;
chunk.position.y = nature.cache.ground.box.min.y - .5;
if(i > 0) {
// reposition
let lChunk = this.earth_chunks[this.earth_chunks.length-1];
chunk.position.z = this.earth_chunks[this.earth_chunks.length-1].position.z - (250 * lChunk.scale.z);
} else {
// first
chunk.position.z = -20;
}
if(!this.cache.earth.box) {
this.cache.earth.box = new THREE.Box3().setFromObject(chunk);
}
this.earth_chunks.push(chunk)
scene.add( chunk );
}
// set leader
this.earth_chunks.leader = this.earth_chunks.length - 1;
}
moveEarth(timeDelta) {
for(let i = 0; i < this.earth_chunks.length; i++) {
if(this.earth_chunks[i].position.z > this.config.remove_z.earth) {
// re move
let lChunk = this.earth_chunks[this.earth_chunks.leader];
this.earth_chunks[i].position.z = lChunk.position.z - (250 * lChunk.scale.z);
this.earth_chunks.leader = i;
}
// move
this.earth_chunks[i].position.z += enemy.config.vel * timeDelta;
}
}
initWater() {
if(this.cache.water.geometry === null) {
// set cache
this.cache.water.geometry = new THREE.BoxGeometry( 8, 1, 250 );
this.cache.water.material = new THREE.MeshLambertMaterial( {color: 0x6EDFFF, transparent: true, opacity: .85} );
}
this.water = new THREE.Mesh( this.cache.water.geometry, this.cache.water.material );
scene.add( this.water );
this.water.position.z = -75;
this.water.position.x = -7;
this.water.position.y = nature.cache.earth.box.max.y + .5;
}
initGround(chunks = 15) {
// get vox
let vox = load_manager.get_vox('ground');
// set cache
this.cache.ground = {
"geometry": vox.geometry,
"material": vox.material
};
// spawn runner ground chunks
for(let i = 0; i < chunks; i++) {
let chunk = new THREE.Mesh( this.cache.ground.geometry, this.cache.ground.material );
chunk.receiveShadow = true;
// chunk.castShadow = true;
chunk.position.y = -2.5;
chunk.scale.set(1.5, 1.5, 1.5);
if(i > 0) {
// reposition
let lChunk = this.ground_chunks[this.ground_chunks.length-1];
chunk.position.z = this.ground_chunks[this.ground_chunks.length-1].position.z - (10 * lChunk.scale.z);
} else {
// first
chunk.position.z = 15;
if(!this.cache.ground.box) {
this.cache.ground.box = new THREE.Box3().setFromObject(chunk);
}
}
// push chunk to pool
this.ground_chunks.push(chunk);
// spawn chunk
scene.add(chunk);
}
// set leader
this.ground_chunks.leader = this.ground_chunks.length - 1;
}
moveGround(timeDelta) {
for(let i = 0; i < this.ground_chunks.length; i++) {
if(this.ground_chunks[i].position.z > this.config.remove_z.ground) {
// re move
let lChunk = this.ground_chunks[this.ground_chunks.leader];
this.ground_chunks[i].position.z = lChunk.position.z - (10 * lChunk.scale.z);
this.ground_chunks.leader = i;
}
// move
this.ground_chunks[i].position.z += enemy.config.vel * timeDelta;
}
}
initGroundDecoration(level_name, x, y, receiveShadow = true, spawn = 'all', chunks = 11) {
// get vox
let vox = load_manager.get_vox('ground_bg');
// set cache
this.cache.ground_decoration = {
"geometry": vox.geometry,
"material": vox.material
};
// create pool
let pool = [];
// spawn runner ground chunks
for(let i = 0; i < chunks; i++) {
let chunk = new THREE.Mesh( this.cache.ground_decoration.geometry, this.cache.ground_decoration.material );
chunk.scale.set(3, 2, 3);
chunk.position.x = x;
chunk.position.y = y;
chunk.receiveShadow = receiveShadow;
// chunk.castShadow = true;
if(i > 0) {
// reposition
let lChunk = pool[pool.length-1];
chunk.position.z = lChunk.position.z - (10 * lChunk.scale.z);
} else {
// first
chunk.position.z = 15;
this.cache.ground_decoration.box = new THREE.Box3().setFromObject(chunk);
}
// save level position
this.ground_chunks_decoration_levels[level_name] = {
"x": x,
"y": y,
"spawn": spawn,
"box": new THREE.Box3().setFromObject(chunk)
};
// push chunk to pool
pool.push(chunk);
// spawn chunk
scene.add(chunk);
}
// set pool leader
pool.leader = pool.length - 1;
// pull pool to chunks pool
this.ground_chunks_decoration.push(pool);
// add custom locations
// this.ground_chunks_decoration_levels.push({
// "x": -9,
// "y": nature.cache.earth.box.max.y,
// "box": new THREE.Box3().setFromObject(this.earth)
// });
// this.ground_chunks_decoration_levels.push({
// "x": 8,
// "y": nature.cache.earth.box.max.y,
// "box": new THREE.Box3().setFromObject(this.earth)
// });
}
moveGroundDecoration(timeDelta) {
for(let i = 0; i < this.ground_chunks_decoration.length; i++) {
// pools
for(let j = 0; j < this.ground_chunks_decoration[i].length; j++) {
// chunks
if(this.ground_chunks_decoration[i][j].position.z > this.config.remove_z.ground) {
// re move
let lChunk = this.ground_chunks_decoration[i][this.ground_chunks_decoration[i].leader];
this.ground_chunks_decoration[i][j].position.z = lChunk.position.z - (10 * lChunk.scale.z);
this.ground_chunks_decoration[i].leader = j;
}
// move
this.ground_chunks_decoration[i][j].position.z += enemy.config.vel * timeDelta;
}
}
}
async initMisc() {
// get vox
let vox = load_manager.get_vox('misc');
// set cache
this.cache.misc = {
"geometry": await load_manager.get_mesh_geometry('misc'),
"material": await load_manager.get_mesh_material('misc')
};
for(let l in this.config.levels) {
let level = this.config.levels[l];
let randLevel = this.ground_chunks_decoration_levels[l];
if(!level.spawn) {
delete this.config.levels[l];
continue;
}
// spawn misc according to level
for(let i = 0; i < level.max_amount; i++) {
// get misc
let rand
let misc = null;
if(level.spawn == '*') {
// any from all
rand = Math.floor(Math.random() * load_manager.assets['misc'].mesh.length);
misc = new THREE.Mesh(
this.cache.misc.geometry[rand],
this.cache.misc.material[rand]
);
} else {
// any from given list
rand = level.spawn[Math.floor(Math.random() * level.spawn.length)];
misc = new THREE.Mesh(
this.cache.misc.geometry[rand],
this.cache.misc.material[rand]
);
}
// basic misc setup
misc.misc_type = vox[rand].misc_type;
let misc_type = misc.misc_type.split('/')[0]; // local
misc.castShadow = true;
misc.receiveShadow = true;
misc.randLevel = randLevel;
// set X position according to level
if( "x_random_range" in level ) {
// level override
if( Array.isArray(level.x_random_range) ) {
// all
misc.position.x = this.random(
randLevel.x + level.x_random_range[1],
randLevel.x + level.x_random_range[0]
);
} else {
// declared
misc.position.x = this.random(
randLevel.x + level.x_random_range[misc_type][1],
randLevel.x + level.x_random_range[misc_type][0]
);
}
} else {
// misc config
misc.position.x = this.random(
randLevel.x + this.config.misc_items[misc_type].x_random_range[1],
randLevel.x + this.config.misc_items[misc_type].x_random_range[0]
);
}
misc.init_x = misc.position.x;
// Other positioning (init)
if("behavior" in this.config.misc_items[misc_type]) {
// Special behavior
if(this.config.misc_items[misc_type].behavior == 'roll') {
// roll behavior
misc.geometry.center();
misc.position.y = randLevel.box.max.y + 0.6;
misc.position.z = randLevel.box.max.y;
misc.rotation.y = this.config.misc_items[misc_type].y_rotate;
misc.rotate_vel = this.random(this.config.misc_items[misc_type].random_rotate_vel[0], this.config.misc_items[misc_type].random_rotate_vel[1]);
} else if(this.config.misc_items[misc_type].behavior == 'move') {
// walk behavior
misc.position.y = randLevel.box.max.y;
// Z random rotate
if(typeof(this.config.misc_items[misc_type].z_random_rotate) !== 'undefined') {
let zRandomRotate = this.random(this.config.misc_items[misc_type].z_random_rotate[0], this.config.misc_items[misc_type].z_random_rotate[1]);
misc.rotateZ(THREE.Math.degToRad(zRandomRotate));
}
// Y random rotate
if(typeof(this.config.misc_items[misc_type].y_random_rotate) !== 'undefined') {
let yRandomRotate = this.random(this.config.misc_items[misc_type].y_random_rotate[0], this.config.misc_items[misc_type].y_random_rotate[1]);
misc.rotateY(THREE.Math.degToRad(yRandomRotate));
}
}
} else {
// all other mesh types
misc.position.y = randLevel.box.max.y;
// Z random rotate
if(typeof(this.config.misc_items[misc_type].z_random_rotate) !== 'undefined') {
let zRandomRotate = this.random(this.config.misc_items[misc_type].z_random_rotate[0], this.config.misc_items[misc_type].z_random_rotate[1]);
misc.rotateZ(THREE.Math.degToRad(zRandomRotate));
}
// Y random rotate
if(typeof(this.config.misc_items[misc_type].y_random_rotate) !== 'undefined') {
let yRandomRotate = this.random(this.config.misc_items[misc_type].y_random_rotate[0], this.config.misc_items[misc_type].y_random_rotate[1]);
misc.rotateY(THREE.Math.degToRad(yRandomRotate));
}
// Y add
if(typeof(this.config.misc_items[misc_type].y_add) !== 'undefined') {
misc.position.y += this.config.misc_items[misc_type].y_add;
}
}
// Rescale mesh
let rescaleRand = this.random(this.config.misc_items[misc_type].rescale_rand[0], this.config.misc_items[misc_type].rescale_rand[1]);
misc.scale.set(rescaleRand, rescaleRand, rescaleRand);
// Set Z initial position
let zRand = this.get_z('misc', l);
if((l in this.misc) && this.misc[l].length) {
// tail z
misc.position.z = -(-this.misc[l][this.misc[l].length-1].position.z + zRand);
} else {
// first z
misc.position.z = zRand;
}
// add to level pool
if(!(l in this.misc)) {
this.misc[l] = [];
}
this.misc[l].push(misc);
// add to scene
scene.add(misc);
}
// set last mesh index
this.misc[l].leader = level.max_amount - 1;
}
}
moveMisc(timeDelta) {
for(let l in this.config.levels) {
let level = this.config.levels[l];
let randLevel = this.ground_chunks_decoration_levels[l];
if(!(l in this.misc)) {
continue;
}
for(let i = 0; i < this.misc[l].length; i++) {
let misc_type = this.misc[l][i].misc_type.split('/')[0];
// reposition, if required
if(this.misc[l][i].position.z > level.remove_z) {
// random rescale
let rescaleRand = this.random(
this.config.misc_items[misc_type].rescale_rand[0],
this.config.misc_items[misc_type].rescale_rand[1]
);
this.misc[l][i].scale.set(rescaleRand, rescaleRand, rescaleRand);
// new Z position
let zRand = this.get_z('misc', l);
this.misc[l][i].position.z = -(-this.misc[l][ this.misc[l].leader ].position.z + zRand);
this.misc[l].leader = i;
// other stuff
if("behavior" in this.config.misc_items[misc_type]) {
if(this.config.misc_items[misc_type].behavior == "roll") {
// roll behavior
// misc.position.y = randLevel.box.max.y + 0.6;
this.misc[l][i].rotation.y = this.config.misc_items[misc_type].y_rotate;
// misc.rotate_vel = this.random(
// this.config.misc_items[misc_type].random_rotate_vel[0],
// this.config.misc_items[misc_type].random_rotate_vel[1]
// );
} else if(this.config.misc_items[misc_type].behavior == "move") {
this.misc[l][i].position.x = misc.init_x;
}
} else {
// any other mesh
// misc.position.y = randLevel.box.max.y;
// if(typeof(this.config.misc_items[misc_type].y_add) !== 'undefined') {
// // Y add
// misc.position.y += this.config.misc_items[misc_type].y_add;
// }
// Z random rotate
if(typeof(this.config.misc_items[misc_type].z_random_rotate) !== 'undefined') {
let zRandomRotate = this.random(this.config.misc_items[misc_type].z_random_rotate[0], this.config.misc_items[misc_type].z_random_rotate[1]);
this.misc[l][i].rotateZ(THREE.Math.degToRad(zRandomRotate));
}
// Y random rotate
if(typeof(this.config.misc_items[misc_type].y_random_rotate) !== 'undefined') {
let yRandomRotate = this.random(this.config.misc_items[misc_type].y_random_rotate[0], this.config.misc_items[misc_type].y_random_rotate[1]);
this.misc[l][i].rotateY(THREE.Math.degToRad(yRandomRotate));
}
}
continue;
}
// move
if("behavior" in this.config.misc_items[misc_type]) {
if( this.config.misc_items[misc_type].behavior == 'roll' ) {
// roll behavior
this.misc[l][i].rotation[this.config.misc_items[misc_type].rotate_direction] -= this.misc[l][i].rotate_vel;
this.misc[l][i].position.z += (enemy.config.vel * 1 + (this.misc[l][i].rotate_vel * 20)) * timeDelta;
} else if(this.config.misc_items[misc_type].behavior == "move") {
this.misc[l][i].position.x -= (this.config.misc_items[misc_type].move_speed / 2) * -this.misc[l][i].rotation.y;
this.misc[l][i].position.z += enemy.config.vel * timeDelta;
}
} else {
// any other mesh movement
this.misc[l][i].position.z += enemy.config.vel * timeDelta;
}
}
}
}
random(from, to, float = true) {
if(float) {
return (Math.random() * (to - from) + from).toFixed(4)
} else {
return Math.floor(Math.random() * to) + from;
}
}
get_z(type, level) {
// according to level
let zrr = this.random(
this.config.levels[level].z_distance_rand[0],
this.config.levels[level].z_distance_rand[1],
);
return this.config.levels[level].z_distance * zrr;
}
reset() {
// remove misc
for(let l in this.config.levels) {
for(let i = 0; i < this.misc[l].length; i++) {
scene.remove(this.misc[l][i]);
}
}
// remove earth chunks
for(let i = 0; i < this.earth_chunks.length; i++) {
scene.remove(this.earth_chunks[i]);
}
// remove ground chunks
for(let i = 0; i < this.ground_chunks.length; i++) {
scene.remove(this.ground_chunks[i]);
}
// remove all ground chunks decoration
for(let i = 0; i < this.ground_chunks_decoration.length; i++) {
for(let j = 0; j < this.ground_chunks_decoration[i].length; j++) {
scene.remove(this.ground_chunks_decoration[i][j]);
}
}
// remove water
scene.remove(this.water);
// clear arrays
this.misc = [];
this.earth_chunks = [];
this.ground_chunks = [];
this.ground_chunks_decoration = [];
this.ground_chunks_decoration_levels = [];
this.water = null;
}
update(timeDelta) {
this.moveEarth(timeDelta);
this.moveGround(timeDelta);
this.moveGroundDecoration(timeDelta);
this.moveMisc(timeDelta);
}
} |
JavaScript | class EffectsManager {
constructor() {
// day/night circle
this.daytime = {
"is_day": true,
"duration": {
"day": 60, // sec
"night": 20, // sec
},
"transition": {
"active": false,
"duration": 5, // sec
"step": 1 / 30, // times/sec
"clock": new THREE.Clock()
},
"intensity": {
"day": {
"ambient": ALight.intensity,
"direct": DLight.intensity,
"shadow_radius": 1
},
"night": {
"ambient": 0,
"direct": .1,
"shadow_radius": 10
}
},
"fog": {
"day": {
"color": [.91, .70, .32]
},
"night": {
"color": [.24, .40, .55]
},
"diff_cache": null
},
"background": {
"day": {
"color": [.91, .70, .32]
},
"night": {
"color": [.24, .40, .55]
},
"diff_cache": null
},
"clock": new THREE.Clock()
}
if(!config.renderer.effects) {
this.update = function() {};
}
}
changeDaytime(daytime = 'day') {
this.daytime.is_day = daytime == 'day';
// drop clock
this.daytime.clock.stop();
this.daytime.clock.elapsedTime = 0;
this.daytime.clock.start();
// reset values
this.stepTransition(!this.daytime.is_day, 1, 1);
}
stepTransition(darken = true, step, total) {
let inc = step / total;
if(darken) {
// to night
if(inc === 1) {
// set
ALight.intensity = this.daytime.intensity.night.ambient;
DLight.intensity = this.daytime.intensity.night.direct;
scene.fog.color.setRGB(this.daytime.fog.night.color[0], this.daytime.fog.night.color[1], this.daytime.fog.night.color[2]);
scene.background.setRGB(this.daytime.background.night.color[0], this.daytime.background.night.color[1], this.daytime.background.night.color[2]);
DLight.shadow.radius = this.daytime.intensity.night.shadow_radius;
} else {
// step
ALight.intensity = parseFloat((ALight.intensity - (this.daytime.intensity.day.ambient - this.daytime.intensity.night.ambient) * inc).toFixed(5));
DLight.intensity = parseFloat((DLight.intensity - (this.daytime.intensity.day.direct - this.daytime.intensity.night.direct) * inc).toFixed(5));
scene.fog.color.sub(this.daytime.fog.diff_cache);
scene.background.sub(this.daytime.background.diff_cache);
DLight.shadow.radius = parseFloat((DLight.shadow.radius - (this.daytime.intensity.night.shadow_radius - this.daytime.intensity.day.shadow_radius) * inc).toFixed(5));
}
} else {
// to day
if(inc === 1) {
// set
ALight.intensity = this.daytime.intensity.day.ambient;
DLight.intensity = this.daytime.intensity.day.direct;
scene.fog.color.setRGB(this.daytime.fog.day.color[0], this.daytime.fog.day.color[1], this.daytime.fog.day.color[2]);
scene.background.setRGB(this.daytime.background.day.color[0], this.daytime.background.day.color[1], this.daytime.background.day.color[2]);
DLight.shadow.radius = this.daytime.intensity.day.shadow_radius;
} else {
// inc
ALight.intensity = parseFloat((ALight.intensity + (this.daytime.intensity.day.ambient - this.daytime.intensity.night.ambient) * inc).toFixed(5));
DLight.intensity = parseFloat((DLight.intensity + (this.daytime.intensity.day.direct - this.daytime.intensity.night.direct) * inc).toFixed(5));
scene.fog.color.add(this.daytime.fog.diff_cache);
scene.background.add(this.daytime.background.diff_cache);
DLight.shadow.radius = parseFloat((DLight.shadow.radius + (this.daytime.intensity.night.shadow_radius - this.daytime.intensity.day.shadow_radius) * inc).toFixed(5));
}
}
this.daytime.transition.steps_done = parseFloat((this.daytime.transition.steps_done + step).toFixed(5));
}
startTransition(step, total) {
let inc = step / total;
this.daytime.transition.active = true; // begin transition
this.daytime.transition.clock.elapsedTime = 0;
this.daytime.transition.clock.start();
this.daytime.transition.steps_done = 0;
// cache sub & add colors
this.daytime.fog.diff_cache = new THREE.Color();
this.daytime.fog.diff_cache.setRGB(
parseFloat((this.daytime.fog.day.color[0] - this.daytime.fog.night.color[0]) * inc),
parseFloat((this.daytime.fog.day.color[1] - this.daytime.fog.night.color[1]) * inc),
parseFloat((this.daytime.fog.day.color[2] - this.daytime.fog.night.color[2]) * inc)
);
this.daytime.background.diff_cache = new THREE.Color();
this.daytime.background.diff_cache.setRGB(
parseFloat((this.daytime.background.day.color[0] - this.daytime.background.night.color[0]) * inc),
parseFloat((this.daytime.background.day.color[1] - this.daytime.background.night.color[1]) * inc),
parseFloat((this.daytime.background.day.color[2] - this.daytime.background.night.color[2]) * inc)
);
}
stopTransition() {
this.daytime.transition.active = false; // end transition
this.daytime.transition.clock.stop();
this.daytime.transition.clock.elapsedTime = 0;
this.daytime.transition.steps_done = 0;
}
reset() {
this.stopTransition();
this.changeDaytime('day');
}
pause() {
this.pause_time = this.daytime.clock.getElapsedTime();
this.daytime.clock.stop();
if( this.daytime.transition.active ) {
this.pause_transition_time = this.daytime.transition.clock.getElapsedTime();
this.daytime.transition.clock.stop();
}
}
resume() {
this.daytime.clock.start();
this.daytime.clock.elapsedTime = this.pause_time;
if( this.daytime.transition.active ) {
this.daytime.transition.clock.start();
this.daytime.transition.clock.elapsedTime = this.pause_transition_time;
}
}
update(timeDelta) {
if(this.daytime.is_day) {
// day
if(!this.daytime.transition.active) {
// wait until night
if(this.daytime.clock.getElapsedTime() > this.daytime.duration.day) {
this.startTransition(this.daytime.transition.step, this.daytime.transition.duration);
}
} else {
// transition to night
if(this.daytime.transition.steps_done < this.daytime.transition.duration) {
// step
if(this.daytime.transition.clock.getElapsedTime() > (this.daytime.transition.step + this.daytime.transition.steps_done)) {
this.stepTransition(true, this.daytime.transition.step, this.daytime.transition.duration);
}
} else {
// end
this.stopTransition();
this.changeDaytime('night');
}
}
} else {
// night
if(!this.daytime.transition.active) {
// wait until day
if(this.daytime.clock.getElapsedTime() > this.daytime.duration.night) {
this.startTransition(this.daytime.transition.step, this.daytime.transition.duration);
}
} else {
// transition to day
if(this.daytime.transition.steps_done < this.daytime.transition.duration) {
// step
if(this.daytime.transition.clock.getElapsedTime() > (this.daytime.transition.step + this.daytime.transition.steps_done)) {
this.stepTransition(false, this.daytime.transition.step, this.daytime.transition.duration);
}
} else {
// end
this.stopTransition();
this.changeDaytime('day');
}
}
}
}
} |
JavaScript | class commands {
// Simple function for using the command line for taking down an interface.
static takeDown(iface, callback) {
exec('iw dev '+iface+' del', callback);
}
static bringUp(iface, callback){
exec('ifconfig ' + iface + ' up', callback)
}
static configureApIp(ip,callback){
exec('ifconfig uap0 ' + ip, callback)
}
static addApInterface(callback) {
exec('iw phy phy0 interface add uap0 type __ap', callback)
}
static startWpaSupplicant(callback) {
console.log('should be starting the wpa thing')
exec('wpa_supplicant -B -Dnl80211 -iwlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf', callback)
}
static listNetworks(callback){
exec('wpa_cli -i wlan0 list_networks', callback)
}
static stopAP(callback) {
exec('pkill hostapd dnsmasq', callback)
}
// Simplified function for making use of ifconfig command line tool.
//ifconfig -v wlan0 inet 172.24.1.1
//ifconfig -v wlan0 broadcast 172.24.1.255
static ifconfig(iface, addressType, address, callback) {
exec('ifconfig ' + iface + " "+ addressType + " " + address, callback);
}
// Simplified interface to iptables.
static iptables(iface, flagString, callback) {
var command = 'iptables -o ' + iface + " " + flagString;
exec(command, callback);
}
// Function for making hostapd available to nodejs. Has basic options
// for the AP, but also allows for pass-in configuration parameters.
static hostapd(options, callback) {
var commands = [];
// Known good options for the Raspberry PI 3. If you are using the
// Raspberry PI Zero the driver value might need to be different.
var defaultOptions = {
driver:'nl80211',
channel:6,
hw_mode:'g',
interface:'uap0',
ssid:'fabmo'
}
var finalOptions = Object.assign(defaultOptions, options);
if (options.password) {
finalOptions.wpa_passphrase = finalOptions.password;
delete finalOptions.password;
}
Object.getOwnPropertyNames(finalOptions).forEach(function(key) {
commands.push(key + '=' + finalOptions[key]);
});
// The tmp package does nice things for you, like creating a tmp file in the proper
// location and making sure its deleted after the fact. Hostapd really wants to
// take its configurations as a file. So we shove all the options into one and
// pass it along.
tmp.file((err, path, fd) => {
if (err) throw err;
// In case you want to look at the config file:
console.log('File: ', path);
// We then write in the configurations...
console.log(fd);
console.log(commands)
fs.write(fd, commands.join('\n'), function(err, result) {
if(err){
console.log(err);
} else {
console.log(result)
}
});
console.log("Commands being executed: ", commands);
// Then execute the hostapd with the file and boom - AP should be started.
exec('hostapd ' + path);
// Now that we are done - go ahead and let others know.
if (callback) {
callback();
}
});
}
// Simplified access to dnsmasq - the fellow responsible for handing out IP
// addresses to your wifi clients. This can take commands as parameters
// but this function again takes advantage of the file configuration method.
static dnsmasq(options, callback) {
var commands = [];
var defaultOptions = {
'interface':'uap0',
'listen-address':'192.168.42.1',
'bind-interfaces':'',
'server': '8.8.8.8', // <--- Google's DNS servers. Very handy.
'domain-needed':'',
'bogus-priv':'',
'dhcp-range':'192.168.42.10,192.168.42.120,24h'
}
const finalOptions = Object.assign(options, defaultOptions);
Object.getOwnPropertyNames(finalOptions).forEach(function(key) {
if (options[key] != '') {
commands.push(key + '=' + options[key]);
} else {
commands.push(key);
}
});
exec('systemctl stop dnsmasq', () => {
tmp.file((err, path, fd) => {
if (err) console.log(err)
console.log('writing dnsmasq file')
fs.write(fd, commands.join('\n'), function(err, result){
if(err){
console.log(err);
} else {
console.log(result);
}
});
console.log("Commands being executed: ", commands);
exec('dnsmasq -C ' + path);
if (callback) {
callback();
}
});
});
}
static dnsmasqETH(options, callback) {
var commands = [];
var defaultOptions = {
'interface':'eth0',
'listen-address':'192.168.44.1',
'bind-interfaces':'',
'server': '8.8.8.8', // <--- Google's DNS servers. Very handy.
'domain-needed':'',
'bogus-priv':'',
'dhcp-range':'192.168.42.10,192.168.42.120,24h'
}
const finalOptions = Object.assign(options, defaultOptions);
Object.getOwnPropertyNames(finalOptions).forEach(function(key) {
if (options[key] != '') {
commands.push(key + '=' + options[key]);
} else {
commands.push(key);
}
});
exec('systemctl stop dnsmasq', () => {
tmp.file((err, path, fd) => {
if (err) console.log(err)
console.log('writing dnsmasq file')
fs.write(fd, commands.join('\n'), function(err, result){
if(err){
console.log(err);
} else {
console.log(result);
}
});
console.log("Commands being executed: ", commands);
exec('dnsmasq -C ' + path);
if (callback) {
callback();
}
});
});
}
} |
JavaScript | class Signup extends Component{
handleFormSubmit(formProps) {
// Sign user up
this.props.signupUser(formProps)
}
renderAlert(){
if (this.props.errorMessage){
return(
<div className="alert alert-danger">
<strong>Oops!</strong> {this.props.errorMessage}
</div>
);
}
}
render(){
const {handleSubmit, fields: {email, password, passwordConfirm}} = this.props;
return(
<form onSubmit = {handleSubmit(this.handleFormSubmit.bind(this))}>
<Field
name="email"
component={renderField}
type="text"
label="Email" />
<Field
name="password"
component={renderField}
type="password"
label="Password" />
<Field
name="passwordConfirm"
component={renderField}
type="password"
label="Password Confirmation" />
{this.renderAlert()}
<button action="submit" className="btn btn-primary">Sign up!</button>
</form>
);
}
} |
JavaScript | class TimeoutSubscriber extends Subscriber_1.Subscriber {
/**
* @param {?} destination
* @param {?} absoluteTimeout
* @param {?} waitFor
* @param {?} errorToSend
* @param {?} scheduler
*/
constructor(destination, absoluteTimeout, waitFor, errorToSend, scheduler) {
super(destination);
this.absoluteTimeout = absoluteTimeout;
this.waitFor = waitFor;
this.errorToSend = errorToSend;
this.scheduler = scheduler;
this.index = 0;
this._previousIndex = 0;
this._hasCompleted = false;
this.scheduleTimeout();
}
get previousIndex() {
return this._previousIndex;
}
get hasCompleted() {
return this._hasCompleted;
}
/**
* @param {?} state
* @return {?}
*/
static dispatchTimeout(state) {
const /** @type {?} */ source = state.subscriber;
const /** @type {?} */ currentIndex = state.index;
if (!source.hasCompleted && source.previousIndex === currentIndex) {
source.notifyTimeout();
}
}
/**
* @return {?}
*/
scheduleTimeout() {
let /** @type {?} */ currentIndex = this.index;
this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, { subscriber: this, index: currentIndex });
this.index++;
this._previousIndex = currentIndex;
}
/**
* @param {?} value
* @return {?}
*/
_next(value) {
this.destination.next(value);
if (!this.absoluteTimeout) {
this.scheduleTimeout();
}
}
/**
* @param {?} err
* @return {?}
*/
_error(err) {
this.destination.error(err);
this._hasCompleted = true;
}
/**
* @return {?}
*/
_complete() {
this.destination.complete();
this._hasCompleted = true;
}
/**
* @return {?}
*/
notifyTimeout() {
this.error(this.errorToSend || new Error('timeout'));
}
static _tsickle_typeAnnotationsHelper() {
/** @type {?} */
TimeoutSubscriber.prototype.index;
/** @type {?} */
TimeoutSubscriber.prototype._previousIndex;
/** @type {?} */
TimeoutSubscriber.prototype._hasCompleted;
/** @type {?} */
TimeoutSubscriber.prototype.absoluteTimeout;
/** @type {?} */
TimeoutSubscriber.prototype.waitFor;
/** @type {?} */
TimeoutSubscriber.prototype.errorToSend;
/** @type {?} */
TimeoutSubscriber.prototype.scheduler;
}
} |
JavaScript | class HomepageBottomHeader extends React.Component{
constructor(props){
super(props);
}
render(){
const style={
"height":"18%",
"display":"block",
};
return(
<div style={style}>
<LoginBtn />
<HelpBtn />
</div>
);
}
} |
JavaScript | class Canvas {
/**
* @param {CanvasConfig} config A canvas configuration object
* @return {Canvas} A instance of the canvas class
*/
constructor(config) {
/**
* Width of the canvas in pixel
* @type {number} width
* @public
*/
this.width = config.width
/**
* Height of the canvas in pixel
* @type {number} height
* @public
*/
this.height = config.height
/**
* the HTML element used as the canvas element
* @type {HTMLElement} element
* @public
*/
this.element = this._createCanvas()
this.setBackgroundColor(config.background)
document.body.appendChild(this.element)
}
/**
* Sets the color of the canvas
* @param {string} hsla a hsla() string (see https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hsla())
* @return {void}
*/
setBackgroundColor(hsla) {
this.element.style.backgroundColor = hsla
}
/**
* @ignore
*/
_createCanvas() {
const gameArea = document.createElement("DIV")
this._setInitialStyle(gameArea, this.width, this.height)
return gameArea
}
/**
* @ignore
*/
_setInitialStyle(gameArea, width, height) {
gameArea.id = "game-canvas"
gameArea.style.width = this.width
gameArea.style.height = this.height
gameArea.style.position = "fixed"
gameArea.style.padding = "0"
gameArea.style.margin = "0"
gameArea.style.zIndex = "-1"
gameArea.style.userSelect = "none"
}
} |
JavaScript | class SearchBarInit {
/**
*
* @param {?String} settingsScript Path to current settings script.
* This property is optional and default location is used if not provided.
*/
constructor(settingsScript) {
this.created = false;
this.settingsScript = settingsScript;
this.themeLoader = new ThemeLoader();
this._searchCoundHandler = this._searchCoundHandler.bind(this);
this._focusHandler = this._focusHandler.bind(this);
}
/**
* Listens for the main script events.
*/
_listen() {
ipcRenderer.on('search-count', this._searchCoundHandler);
ipcRenderer.on('focus-input', this._focusHandler);
}
/**
* Removes listeners for the main script events.
*/
_unlisten() {
ipcRenderer.removeListener('search-count', this._searchCoundHandler);
ipcRenderer.removeListener('focus-input', this._focusHandler);
}
/**
* Initializes search bar window.
*
* @return {Promise} Resolved promise when settings are ready.
*/
initBar() {
log.info('Initializing search bar window...');
return this.initPreferences()
.then((settings) => this.themeBar(settings));
}
/**
* Reads user proferences.
*
* @return {Promise} A promise resolved to settings object.
*/
initPreferences() {
log.info('Initializing search bar preferences...');
const prefs = new ArcPreferencesRenderer(this.settingsScript);
return prefs.loadSettings();
}
/**
* Loads theme for the search bar window.
* @param {Object} settings Current app settings.
* @return {Promise} Resolved promise when the theme is loaded.
*/
themeBar(settings) {
log.info('Initializing search bar theme.');
let id;
if (settings.theme) {
id = settings.theme;
} else {
id = this.themeLoader.defaultTheme;
}
this.themeLoader.importFileName = 'import-search-bar.html';
this.themeLoader.componentsBasePath = path.join('../', 'components');
return this.themeLoader.activateTheme(id)
.catch((cause) => {
if (id === this.themeLoader.default) {
log.error('Unable to load theme file.', cause);
return;
}
return this.themeLoader.activateTheme(this.themeLoader.defaultTheme);
})
.then(() => {
if (this.themeLoader.activeTheme === this.themeLoader.anypointTheme) {
this._setupAnypoint();
}
})
.catch((cause) => {
log.error('Unable to load default theme file.', cause);
});
}
/**
* Closes the search bar.
*/
close() {
ipcRenderer.send('search-bar-close');
}
/**
* Sends the `search-bar-query` event to the main script
* so the window search handler can perform search operation.
* @param {String} value Search query
*/
query(value) {
ipcRenderer.send('search-bar-query', value);
}
/**
* Sends the `search-bar-query-next` event to the main script
* so the window search handler can mark next search result.
*/
highlightNext() {
ipcRenderer.send('search-bar-query-next');
}
/**
* Sends the `search-bar-query-previous` event to the main script
* so the window search handler can mark previous search result.
*/
highlightPrevious() {
ipcRenderer.send('search-bar-query-previous');
}
/**
* Returns the `<dom-bind>` template element.
*
* @return {HTMLElement} Instance of the `dom-bind` template.
*/
get bar() {
return document.getElementById('bar');
}
/**
* Handler for the `search-count` event from the main page.
* Sets `searchCount` and `selected` properties on the search bar
* template instance.
*
* @param {Event} event Event instance.
* @param {Number} count Search results count
* @param {Number} selected Currently selected instance.
*/
_searchCoundHandler(event, count, selected) {
let bar = this.bar;
bar.searchCount = count;
bar.selected = selected;
}
/**
* Setups anypoint styling.
*/
_setupAnypoint() {
this.bar.isAnypoint = true;
}
/**
* Focuses on the text input.
*/
_focusHandler() {
document.querySelector('paper-input').inputElement.focus();
}
} |
JavaScript | class Story extends Component {
render() {
return (
<React.Fragment>
<CssBaseline />
<Container maxWidth="sm">
<Typography component="div" style={{ backgroundColor: '#cfe8fc', height: '100vh' }} />
</Container>
</React.Fragment>
)
}
} |
JavaScript | class Auth {
async getJwt() {
if( config.jwt ) {
// check that jwt is not expired
let payload = Buffer.from(config.jwt.split('.')[1], 'base64');
payload = JSON.parse(payload);
if( payload.exp*1000 > Date.now() ) {
return config.jwt;
}
}
// now we either don't have a jwt or we have an exired jwt
// check if we have a refresh token
if( config.refreshToken && config.username ) {
let success = await this.loginRefreshToken();
if( success ) return config.jwt;
}
// check if we have a username / password
if( config.password && config.username ) {
let success = await this.loginPassword();
if( success ) return config.jwt;
}
config.jwt = '';
return '';
}
async loginRefreshToken() {
var req = {
method : 'POST',
uri : `${config.host}/auth/token/verify`,
form : {
username: config.username,
token: config.refreshToken
}
}
var {response, body} = await this.request(req);
if( response.statusCode >= 200 && response.statusCode < 300 ) {
var body = JSON.parse(body);
if( !body.error ) {
config.jwt = body.jwt;
return true;
}
}
return false;
}
async loginPassword() {
var req = {
method : 'POST',
uri : `${config.host}/auth/local`,
form : {
username: config.username,
password: config.password
}
}
var {response, body} = await this.request(req);
if( response.statusCode >= 200 && response.statusCode < 300 ) {
var body = JSON.parse(body);
if( !body.error ) {
config.jwt = body.jwt;
return true;
}
}
return false;
}
// promise based request
request(options) {
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if( error ) {
response = {
request : {
method : options.method || 'GET',
path : options.uri,
headers : options.headers,
body : options.body
}
}
return reject({response, error});
}
resolve({response, body});
});
});
}
} |
JavaScript | class CsdlSchema {
/**
* Creates an instance of CsdlSchema.
* @param {Object} rawMetadata raw metadata object for schema
* @param {Object} [settings] (normalized) settings for the metadata, e.g. { strict: false } to ignore non critical errors
* @memberof CsdlSchema
*/
constructor(rawMetadata, settings) {
Object.defineProperty(this, "raw", {
get: () => rawMetadata,
});
Object.defineProperty(this, "namespace", {
get: () => rawMetadata.$.Namespace,
});
Object.defineProperty(this, "alias", {
get: () => rawMetadata.$.Alias,
});
let extensions = [];
Object.defineProperty(this, "extensions", {
get: () => extensions,
});
Object.defineProperty(this, "settings", {
get: () => settings,
});
initChildProperties(this);
initSchemaDependentProperties(this);
this.applyAnnotations(rawMetadata.Annotations);
}
/**
* Gets an EntityType defined in schema
*
* @param {string} [name] type name
* @returns {EntityType} type with given name
* @memberof CsdlSchema
*/
getEntityType(name) {
let type = this.entityTypes.find((t) => t.name === name);
if (!type) {
throw new Error(
`EntityType '${name}' not found in namespace '${this.namespace}'`
);
}
return type;
}
/**
* Gets entity container with given name (or default container).
*
* @param {string} [name] (optional) name of the container.
* @returns {Object} entity container
*/
getEntityContainer(name) {
return this.entityContainers.find((c) =>
name ? c.name === name : c.isDefault
);
}
/**
* Gets a Type available in schema
*
* Enumeration types, collection types and Untyped are not implemented.
*
* @param {string} [name] namespace qualified type name
* @returns {EntityType|ComplexType|SimpleType} type with given name
* @memberof CsdlSchema
*/
getType(name) {
let target = parseTypePath(name);
let type = this._getTypeCollections(target.namespace)
.map((types) => types.find((t) => t.name === target.name))
.find((t) => !!t);
if (!type) {
throw new Error(`Unknown type '${name}'.`);
}
return target.isCollection ? new CollectionType(type) : type;
}
/**
* Resolves model path expression.
*
* A model path is used within Annotation Path, Model Element Path, Navigation Property Path,
* and Property Path expressions to traverse the model of a service and resolves to the model
* element identified by the path
*
* Implemented only needed scope (OASIS-CSDL) and associations (MC-CSDL) (https://docs.microsoft.com/en-us/openspecs/windows_protocols/mc-csdl/77d7ccbb-bda8-444a-a160-f4581172322f).
*
* http://docs.oasis-open.org/odata/odata-csdl-xml/v4.01/cs01/odata-csdl-xml-v4.01-cs01.html#sec_Target
* http://docs.oasis-open.org/odata/odata-csdl-xml/v4.01/cs01/odata-csdl-xml-v4.01-cs01.html#sec_PathExpressions
*
* @param {string} path model path expression
* @returns {Object} schema element
* @memberof CsdlSchema
*/
resolveModelPath(path) {
let target = this._parseModelPath(path);
var child = childCollections
.map((collection) =>
this[collection.name].find((item) => item.name === target.element)
)
.filter(Boolean);
if (child.length === 0) {
throw new Error(`Can't find schema element for path "${path}".`);
} else if (child.length > 1) {
throw new Error(
`Schema error: "${path}" matched ${child.length} schema elememts.`
);
}
let element = child[0].resolveModelPath(target.subElement, this);
if (!element) {
throw new Error(
`Can't resolve '${path}' model path. '${target.element}' found, but '${target.subElement}' did not resolve.`
);
}
return element;
}
/**
* Applies annotations to target elements structures.
*
* @param {Object[]} annotationsData raw annotaions data
* @memberof CsdlSchema
*/
applyAnnotations(annotationsData) {
if (annotationsData && this.raw.EntityContainer) {
let validItems = annotationsData.filter((annotation) =>
_.get(annotation, "$.Target")
);
let annotationGroups = _.groupBy(
validItems,
(annotation) => annotation.$.Target
);
_.each(annotationGroups, this._applyAnnotationsToPath.bind(this));
}
}
/**
* Applies annotation based vendor extensions.
*
* @param {Object} [settings] parsing settings
* @memberof CsdlSchema
*/
applyExtensions(settings) {
Extender.apply(this, settings);
}
/**
* Creates path structure from model path.
*
* @param {string} [path] annotation target model path
* @returns {Object} structure describing annotation target
* @memberof CsdlSchema
* @private
*/
_parseModelPath(path) {
let target = parseModelPath(path);
if (
target.namespace !== this.namespace &&
target.namespace !== this.alias
) {
throw new Error(
`Annotation namespace/alias mismatch. (schema: '${this.namespace}'/'${this.alias}' vs annotation: '${target.namespace}'`
);
}
return target;
}
/**
* Gets type collections for a namespace.
*
* @param {string} [namespace] type namespace
* @returns {Object[]} array of type collections
* @memberof CsdlSchema
* @private
*/
_getTypeCollections(namespace) {
let typeCollections = [];
if (namespace === this.namespace) {
typeCollections = [this.entityTypes, this.complexTypes];
} else if (namespace === "Edm") {
typeCollections = [EdmSimpleType.instances];
}
return typeCollections;
}
/**
* Applies annotations to specific path. Error handling is done according to schema settings.
*
* @param {Object[]} [annotations] annotations to apply
* @param {string} [path] target path
* @memberof CsdlSchema
* @private
*/
_applyAnnotationsToPath(annotations, path) {
let target;
if (this.settings.strict) {
target = this.resolveModelPath(path);
} else {
try {
target = this.resolveModelPath(path);
} catch (error) {
this.settings.logger.warn(
`Can't find annotation target for path '${path}'.`,
error
);
}
}
if (target) {
try {
target.applyAnnotations(annotations);
} catch (e) {
throw new Error(
`Error occured while applying annotations for '${path}': ${e.message}\n${e.stack}`
);
}
}
}
} |
JavaScript | class Grammar {
/**
* @param {String} name
* @param {Rule} startingRule
* @param {...Rule} additionalRules
*/
constructor(name, startingRule, ...additionalRules) {
this.name = name;
this.rules = [].concat(startingRule, additionalRules);
}
/**
* Given an input string and a parser, return whether or not the input is
* accepted by this grammar.
*
* @param {InputBuffer} input
* @param {Parser} parser
* @return {Object} If the input is accepted, this will be the non-null result
* of matching against the rules of this grammar.
*/
accept(input, parser) {
return this.startingRule.accept(input, parser);
}
/**
* Return the rule that has the given name.
*
* @param {String} name
* @return {Rule}
*/
findRuleByName(name) {
let rule = this.rules.find(rule => rule.name === name);
if (!rule) {
throw new Error(`Failed to find a rule named "${name}" in the grammar`);
}
return rule;
}
/**
* Returns the grammar's starting rule.
*
* @return {Rule}
*/
get startingRule() {
return this.rules[0];
}
} |
JavaScript | class MeshBuffer extends Buffer {
/**
* @param {Object} data - attribute object
* @param {Float32Array} data.position - positions
* @param {Float32Array} data.color - colors
* @param {Float32Array} [data.index] - triangle indices
* @param {Float32Array} [data.normal] - radii
* @param {BufferParameters} params - parameter object
*/
constructor(data, params = {}) {
super(data, params);
this.vertexShader = 'Mesh.vert';
this.fragmentShader = 'Mesh.frag';
this.addAttributes({
'normal': { type: 'v3', value: data.normal }
});
if (data.normal === undefined) {
this.geometry.computeVertexNormals();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.