language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class QueueAction extends FutureAction_1.FutureAction {
/**
* @param {?=} state
* @param {?=} delay
* @return {?}
*/
_schedule(state, delay = 0) {
if (delay > 0) {
return super._schedule(state, delay);
}
this.delay = delay;
this.state = state;
const /** @type {?} */ scheduler = this.scheduler;
scheduler.actions.push(this);
scheduler.flush();
return this;
}
} |
JavaScript | class Swirl {
constructor(scale, increment, speed) {
this._ = {
canvas: document.getElementById("swirl").getContext("2d"),
scale: scale !== undefined ? scale : 3,
increment: increment !== undefined ? increment : .01,
noise: [],
flowfield: [],
particles: [],
z_offset: 0
}
this._.width = this._.canvas.canvas.width
this._.height = this._.canvas.canvas.height
this._.cols = Math.floor(this._.width / this._.scale)
this._.rows = Math.floor(this._.height / this._.scale)
this._.speed = speed !== undefined ? this.increment / speed : this.increment
}
get canvas() { return this._.canvas }
get scale() { return this._.scale }
get particles() { return this._.particles }
get width() { return this._.width }
get height() { return this._.height }
get columns() { return this._.cols }
get rows() { return this._.rows }
get flowfield() { return this._.flowfield }
get noise() { return this._.noise }
get increment() { return this._.increment }
get z_offset() { return this._.z_offset }
get speed() { return this._.speed }
set flowfield(value) { this._.flowfield = value }
set noise(value) { this._.noise = value }
set z_offset(value) { this._.z_offset = value }
setup() {
noise.seed(Math.random())
let y_offset = 0
this.amount = this.density * 500
for (let y = 0; y < this.rows; y++) {
let x_offset = 0
this.noise[y] = []
for (let x = 0; x < this.columns; x++) {
this.noise[y][x] = this.calculateNoiseAt(x_offset, y_offset)
x_offset += this.increment
}
y_offset += this.increment
}
}
calculateFlowFieldAt(i, x, y) {
this.flowfield[i] = new Vector(x, y)
this.flowfield[i].x = x * this.scale
this.flowfield[i].y = y * this.scale
this.flowfield[i].rotateToDegree(this.noise[y][x])
this.flowfield[i].magnitude = this.scale
}
calculateNoise() {
let y_offset = 0
for (let y = 0; y < this.rows; y++) {
let x_offset = 0
this.noise[y] = []
for (let x = 0; x < this.columns; x++) {
this.noise[y][x] = this.calculateNoiseAt(x_offset, y_offset)
x_offset += this.increment
}
y_offset += this.increment
}
this.z_offset += this.speed
}
drawFlowField() {
this.canvas.clearRect(0, 0, this.width, this.height)
for (let y = 0; y < this.rows; y++) {
for (let x = 0; x < this.columns; x++) {
let i = (y * this.columns) + x + 1
this.calculateFlowFieldAt(i, x, y)
this.canvas.beginPath()
this.canvas.moveTo(this.flowfield[i].x, this.flowfield[i].y)
this.canvas.lineTo(this.flowfield[i].x2, this.flowfield[i].y2)
this.canvas.stroke()
}
}
this.calculateNoise()
window.requestAnimationFrame(this.drawFlowField.bind(this))
}
calculateNoiseAt(x, y) {
return noise.simplex3(x, y, this.z_offset).map(-1, 1, 0, 360)
}
draw() {
for (let y = 0; y < this.rows; y++) {
for (let x = 0; x < this.columns; x++) {
let shade = Math.round(this.noise[y][x])
this.canvas.fillStyle = rgbToHex([shade, shade, shade])
this.canvas.fillRect(x * this.scale, y * this.scale, this.scale, this.scale)
}
}
}
} |
JavaScript | class CLIBase extends PObject {
/**
* Constructor of the CLI Command.
*
* @param {string} name The name of the command.
*/
constructor(name) {
super();
/**
* A reference to the CLI object.
*
* @member {cli}
*/
this.cli = puzzle.cli;
/**
* The name of the command, like: db:migrate, db:seed and so on.
*
* @member {string}
*/
this.name = name;
/**
* Options passed to the command line
*
* @member {Object<string, Array>}
*/
this.options = {};
}
/**
* Puts a message in both log and screen for CLI commands.
*
* @type {Object}
*/
get put() {
const { cli } = this;
return {
/**
* Prints a debug message.
*
* @param {string} msg The message to be printed.
*/
debug: (...msg) => {
cli.debug(puzzle.i18n.__(...msg));
},
/**
* Prints an information message.
*
* @param {string} msg The message to be printed.
*/
info: (...msg) => {
cli.info(puzzle.i18n.__(...msg));
},
/**
* Prints an error message.
*
* @param {string} msg The message to be printed.
*/
error: (...msg) => {
cli.error(puzzle.i18n.__(...msg));
},
/**
* Prints a fatal error message.
*
* @param {string} msg The message to be printed.
*/
fatal: (...msg) => {
cli.fatal(puzzle.i18n.__(...msg));
},
/**
* Prints an ok message.
*
* @param {string} msg The message to be printed.
*/
ok: (...msg) => {
cli.ok(puzzle.i18n.__(...msg));
}
};
}
/**
* Puts an untranslated message in both log and screen for CLI commands.
*
* @type {Object}
*/
get putU() {
const { cli } = this;
return {
/**
* Prints a debug message.
*
* @param {string} msg The message to be printed.
*/
debug: (msg) => {
cli.debug(msg);
},
/**
* Prints an information message.
*
* @param {string} msg The message to be printed.
*/
info: (msg) => {
cli.info(msg);
},
/**
* Prints an error message.
*
* @param {string} msg The message to be printed.
*/
error: (msg) => {
cli.error(msg);
},
/**
* Prints a fatal error message.
*
* @param {string} msg The message to be printed.
*/
fatal: (msg) => {
cli.fatal(msg);
},
/**
* Prints an ok message.
*
* @param {string} msg The message to be printed.
*/
ok: (msg) => {
cli.ok(msg);
}
};
}
/**
* Runs the command.
*
* @abstract
* @param {string[]} args The command line arguments
* @param {Object} options The options given to the command.
*/
run(args = [], options = {}) {
this.put.info("We've got:");
this.put.info(args);
this.put.info(options);
}
/**
* Command usage information.
*
* @param {string[]} args The command line arguments
* @param {Object} options The options given to the command.
*/
usage(args = [], options = {}) {
this.put.info("We currently have no usage for this command!");
}
/**
* Exit the command with the given code.
*
* @param {number} errCode The error code to be returned to cli system.
*/
done(errCode) {
if (puzzle.env === "test") {
puzzle.cli.shouldExit = true;
puzzle.cli.exitCode = errCode || 0;
return;
}
process.exit(errCode || 0);
}
} |
JavaScript | class HomeHeroMobile extends React.Component {
constructor(props) {
// Make our props accessible through this.props
super(props);
}
// Render element.
render() {
let LocationData = this.props.LocationData;
// Render Menu
return (
<Device Query="Mobile">
<MobileHomeHeroStyle>
<MobileHomeHeroStyle.Inner className="hero-inner">
<HeroContent Flex="row">
<MobileHomeHeroStyle.LocationSwitch>
<div className="location-switch-inner">
<span className="label">{TimeString()}</span>
<LocationList />
</div>
</MobileHomeHeroStyle.LocationSwitch>
</HeroContent>
<HeroContent Flex="row">
<SlideSection
Widgets={MenuWidgets({
HeadlineString: 'MenuHeadline',
})}
SectionSize={5}
Theme={{
TextColor: Theme.Color.Black,
BgColor: 'none',
}}
SliderSettings={{
slidesToShow: 1,
slidesToScroll: 1,
// autoplay: true,
autoplay: true,
arrows: false,
infinite: true,
useTransform: false,
}}
/>
</HeroContent>
<HeroContent Flex="row">
<SuggestionList
BaseUrl={
'/menu' +
'/' +
slugify(LocationData.geography.state.toLowerCase()) +
'/' +
LocationData.slug +
'/'
}
List={LocationData.nearby}
Label="Nearby"
TextColor={Theme.Color.Nightsky}
GradientColor={Theme.Color.White}
Padding={[1, 0, 0, 0]}
/>
</HeroContent>
</MobileHomeHeroStyle.Inner>
</MobileHomeHeroStyle>
</Device>
);
}
} |
JavaScript | class Analyzer {
/**
* Constructor
* @param {Object} [options] JSON object which have key-value pairs settings
* @param {string} [options.dictPath] Path of the dictionary files
*/
constructor({ dictPath } = {}) {
this._analyzer = null;
if (!dictPath) {
this._dictPath = path.join( __dirname, "dict" );
}
else {
this._dictPath = dictPath;
}
}
/**
* Initialize the analyzer
* @returns {Promise} Promise object represents the result of initialization
*/
init() {
return new Promise((resolve, reject) => {
const self = this;
if (this._analyzer == null) {
kuromoji.builder({ dicPath: this._dictPath }).build((err, newAnalyzer) => {
if (err) {
return reject(err);
}
self._analyzer = newAnalyzer;
resolve();
});
}
else {
reject(new Error("This analyzer has already been initialized."));
}
});
}
/**
* Parse the given string
* @param {string} str input string
* @returns {Promise} Promise object represents the result of parsing
* @example The result of parsing
* [{
* "surface_form": "黒白", // 表層形
* "pos": "名詞", // 品詞 (part of speech)
* "pos_detail_1": "一般", // 品詞細分類1
* "pos_detail_2": "*", // 品詞細分類2
* "pos_detail_3": "*", // 品詞細分類3
* "conjugated_type": "*", // 活用型
* "conjugated_form": "*", // 活用形
* "basic_form": "黒白", // 基本形
* "reading": "クロシロ", // 読み
* "pronunciation": "クロシロ", // 発音
* "verbose": { // Other properties
* "word_id": 413560,
* "word_type": "KNOWN",
* "word_position": 1
* }
* }]
*/
parse(str = "") {
return new Promise((resolve, reject) => {
if (str.trim() === "") return resolve([]);
const result = this._analyzer.tokenize(str);
for (let i = 0; i < result.length; i++) {
result[i].verbose = {};
result[i].verbose.word_id = result[i].word_id;
result[i].verbose.word_type = result[i].word_type;
result[i].verbose.word_position = result[i].word_position;
delete result[i].word_id;
delete result[i].word_type;
delete result[i].word_position;
}
resolve(result);
});
}
} |
JavaScript | class ModuleResolver {
constructor(options) {this.
_getPackageMainPath = packageJsonPath => {
const package_ = this._options.moduleCache.getPackage(packageJsonPath);
return package_.getMain();
};this._options = options;}_redirectRequire(fromModule, modulePath) {const pck = fromModule.getPackage();if (pck) {return pck.redirectRequire(modulePath);}return modulePath;}_resolveModulePath(fromModule, toModuleName, platform) {const modulePath = isAbsolutePath(toModuleName) ? resolveWindowsPath(toModuleName) : path.join(path.dirname(fromModule.path), toModuleName);const redirectedPath = this._redirectRequire(fromModule, modulePath);if (redirectedPath === false) {return resolvedAs({ type: 'empty' });}const context = _extends({}, this._options, { getPackageMainPath: this._getPackageMainPath });const result = resolveFileOrDir(context, redirectedPath, platform);if (result.type === 'resolved') {return result;}return failedFor({ type: 'modulePath', which: result.candidates });}resolveDependency(fromModule, toModuleName, allowHaste, platform) {const result = this._resolveDependency(fromModule, toModuleName, allowHaste, platform);if (result.type === 'resolved') {return this._getFileResolvedModule(result.resolution);}if (result.candidates.type === 'modulePath') {const which = result.candidates.which;throw new UnableToResolveError(fromModule.path, toModuleName, `The module \`${toModuleName}\` could not be found ` + `from \`${fromModule.path}\`. ` + `Indeed, none of these files exist:\n\n` + ` * \`${formatFileCandidates(which.file)}\`\n` + ` * \`${formatFileCandidates(which.dir)}\``);}var _result$candidates = result.candidates;const dirPaths = _result$candidates.dirPaths,extraPaths = _result$candidates.extraPaths;const displayDirPaths = dirPaths.filter(dirPath => this._options.dirExists(dirPath)).concat(extraPaths);const hint = displayDirPaths.length ? ' or in these directories:' : '';throw new UnableToResolveError(fromModule.path, toModuleName, `Module does not exist in the module map${hint}\n` + displayDirPaths.map(dirPath => ` ${path.dirname(dirPath)}\n`).join(', ') + '\n' + `This might be related to https://github.com/facebook/react-native/issues/4968\n` + `To resolve try the following:\n` + ` 1. Clear watchman watches: \`watchman watch-del-all\`.\n` + ` 2. Delete the \`node_modules\` folder: \`rm -rf node_modules && npm install\`.\n` + ' 3. Reset Metro Bundler cache: `rm -rf $TMPDIR/react-*` or `npm start -- --reset-cache`.' + ' 4. Remove haste cache: `rm -rf $TMPDIR/haste-map-react-native-packager-*`.');}_resolveDependency(fromModule, toModuleName, allowHaste, platform) {if (isRelativeImport(toModuleName) || isAbsolutePath(toModuleName)) {return this._resolveModulePath(fromModule, toModuleName, platform);}const realModuleName = this._redirectRequire(fromModule, toModuleName); // exclude
if (realModuleName === false) {return resolvedAs({ type: 'empty' });}if (isRelativeImport(realModuleName) || isAbsolutePath(realModuleName)) {// derive absolute path /.../node_modules/fromModuleDir/realModuleName
const fromModuleParentIdx = fromModule.path.lastIndexOf('node_modules' + path.sep) + 13;const fromModuleDir = fromModule.path.slice(0, fromModule.path.indexOf(path.sep, fromModuleParentIdx));const absPath = path.join(fromModuleDir, realModuleName);return this._resolveModulePath(fromModule, absPath, platform);} // At that point we only have module names that
// aren't relative paths nor absolute paths.
if (allowHaste) {const result = resolveHasteName(_extends({}, this._options, { resolveHasteModule: name => this._options.moduleMap.getModule(name, platform, /* supportsNativePlatform */true), resolveHastePackage: name => this._options.moduleMap.getPackage(name, platform, /* supportsNativePlatform */true), getPackageMainPath: this._getPackageMainPath }), normalizePath(realModuleName), platform);if (result.type === 'resolved') {return result;}}const dirPaths = [];for (let currDir = path.dirname(fromModule.path); currDir !== '.' && currDir !== path.parse(fromModule.path).root; currDir = path.dirname(currDir)) {const searchPath = path.join(currDir, 'node_modules');dirPaths.push(path.join(searchPath, realModuleName));}const extraPaths = [];if (this._options.extraNodeModules) {const extraNodeModules = this._options.extraNodeModules;const bits = path.normalize(toModuleName).split(path.sep);const packageName = bits[0];if (extraNodeModules[packageName]) {bits[0] = extraNodeModules[packageName];extraPaths.push(path.join.apply(path, bits));}}const allDirPaths = dirPaths.concat(extraPaths);for (let i = 0; i < allDirPaths.length; ++i) {const context = _extends({}, this._options, { getPackageMainPath: this._getPackageMainPath });const result = resolveFileOrDir(context, allDirPaths[i], platform);if (result.type === 'resolved') {return result;}}return failedFor({ type: 'moduleName', dirPaths, extraPaths });} /**
* FIXME: get rid of this function and of the reliance on `TModule`
* altogether, return strongly typed resolutions at the top-level instead.
*/_getFileResolvedModule(resolution) {switch (resolution.type) {
case 'sourceFile':
return this._options.moduleCache.getModule(resolution.filePath);
case 'assetFiles':
// FIXME: we should forward ALL the paths/metadata,
// not just an arbitrary item!
const arbitrary = getArrayLowestItem(resolution.filePaths);
invariant(arbitrary != null, 'invalid asset resolution');
return this._options.moduleCache.getAssetModule(arbitrary);
case 'empty':const
moduleCache = this._options.moduleCache;
const module = moduleCache.getModule(ModuleResolver.EMPTY_MODULE);
invariant(module != null, 'empty module is not available');
return module;
default:
resolution.type;
throw new Error('invalid type');}
}} |
JavaScript | class ServiceBlueprintUserOptions extends BlueprintUserOptions {
constructor() {
super();
}
} |
JavaScript | class Node {
constructor(val) {
this.val = val;
this.next = null;
}
} |
JavaScript | class OTypeahead extends Typeahead {
componentWillReceiveProps(nextProps) {
this.fuzzySearchKeyAttribute = nextProps.fuzzySearchKeyAttribute || this.props.fuzzySearchKeyAttribute;
if (nextProps.options instanceof Promise) {
this.setState(
{
loadingOptions: true
},
() => {
nextProps.options.then(response => {
//this.props.onElementFocused({ focused: true });
this.setState(
{
loadingOptions: false,
header: nextProps.header,
datatype: nextProps.datatype,
options: response.data,
visible: this.getOptionsForValue(null, response.data)
},
() => {
let inputRef = this.getInputRef();
if (inputRef) {
inputRef.focus();
}
}
);
});
}
);
} else {
let inputRef = this.getInputRef(),
isValueEmpty = inputRef == undefined || inputRef.value == "";
this.setState({
options: nextProps.options,
header: nextProps.header,
datatype: nextProps.datatype,
visible: this.getOptionsForValue(isValueEmpty ? null : inputRef.value, nextProps.options)
});
}
}
isOptionsLoading() {
return this.state.loadingOptions;
}
_onOptionSelected(option) {
if (option !== this.props.fuzzySearchEmptyMessage) {
var nEntry = this.entryRef;
nEntry.focus();
if (typeof option == "object") {
nEntry.value = option[this.props.fuzzySearchKeyAttribute];
} else {
nEntry.value = option;
}
this.setState({
visible: this.getOptionsForValue(option, this.state.options),
selection: option,
entryValue: option
});
this.props.onOptionSelected(option);
}
}
_getTypeaheadInput({ classList, inputClassList }) {
return (
<div className={classList}>
{this.state.loadingOptions ? (
this.props.renderLoading ? (
this.props.renderLoading()
) : (
<div>Loading...</div>
)
) : (
<span ref={ref => (this.inputRef = ref)} onFocus={this._onFocus}>
<input
ref={ref => (this.entryRef = ref)}
type={this.state.datatype == "number" ? "number" : "text"}
placeholder={this.props.placeholder}
className={inputClassList}
defaultValue={this.state.entryValue}
onChange={this._onTextEntryUpdated}
onKeyDown={this._onKeyDown}
disabled={this.props.disabled}
/>
{this._renderIncrementalSearchResults()}
</span>
)}
</div>
);
}
} |
JavaScript | class ComputationLock {
constructor($b) {
if (!$b) $b = {};
/**@type {string}*/
this.Token = $b.token;
/**@type {Date}*/
this.ExpireTimestamp = $b.timestamp || new Date();
}
/**
* Is the lock currently in use
* @readonly
* @memberof ComputationLock
*/
get IsLocked() {
return (
!(this.Token === "" || this.Token == null) &&
new Date() > this.ExpireTimestamp
);
}
/**
* Try to Lock
* @param {Date} duration
* @returns {Boolean}
* @memberof ComputationLock
*/
TryLock(duration) {
if (this.IsLocked) return false;
this.Token = new uuidv4();
this.ExpireTimestamp = new Date() + duration;
return true;
}
/**
*
*
* @param {*} token
* @param {*} duration
* @returns {Boolean}
* @memberof ComputationLock
*/
TryExtend(token, duration) {
if (token !== this.Token) return false;
this.ExpireTimestamp = new Date() + duration;
return true;
}
/**
*
*
* @param {*} token
* @returns {Boolean}
* @memberof ComputationLock
*/
TryRelease(token) {
if (this.Token !== token) return false;
this.Token = null;
this.ExpireTimestamp = new Date();
return true;
}
} |
JavaScript | class ConfigurationBindingsElectron extends ConfigurationBindings {
async initialize() {
await super.initialize();
ArcEnvironment.ipc.on('preferences-value-updated', this.ioChangeHandler.bind(this));
}
/**
* @returns {Promise<ARCConfig>}
*/
// @ts-ignore
async readAll() {
return ArcEnvironment.ipc.invoke('preferences-read');
}
/**
* Updates a single property in the app settings.
* @param {string} key
* @param {unknown} value
* @returns {Promise<void>}
*/
async update(key, value) {
return ArcEnvironment.ipc.invoke('preferences-update', key, value);
}
/**
* Handler for the IO event for settings update.
*
* @param {Electron.IpcRendererEvent} e
* @param {String} name Name of changed property
* @param {any} value
*/
ioChangeHandler(e, name, value) {
Events.Config.State.update(document.body, name, value);
}
} |
JavaScript | class mat23 {
/**
* Creates a matrix, with elements specified separately.
*
* @param {Number} m00 - Value assigned to element a.
* @param {Number} m01 - Value assigned to element b.
* @param {Number} m02 - Value assigned to element c.
* @param {Number} m03 - Value assigned to element d.
* @param {Number} m04 - Value assigned to element tx.
* @param {Number} m05 - Value assigned to element ty.
*/
constructor(m00 = 1, m01 = 0, m02 = 0, m03 = 1, m04 = 0, m05 = 0) {
/**
* The element a.
* @type {number}
* */
this.m00 = m00;
/**
* The element b.
* @type {number}
* */
this.m01 = m01;
/**
* The element c.
* @type {number}
* */
this.m02 = m02;
/**
* The element d.
* @type {number}
* */
this.m03 = m03;
/**
* The element tx.
* @type {number}
* */
this.m04 = m04;
/**
* The element ty.
* @type {number}
* */
this.m05 = m05;
}
/**
* Creates a matrix, with elements specified separately.
*
* @param {Number} m00 - Value assigned to element a.
* @param {Number} m01 - Value assigned to element b.
* @param {Number} m02 - Value assigned to element c.
* @param {Number} m03 - Value assigned to element d.
* @param {Number} m04 - Value assigned to element tx.
* @param {Number} m05 - Value assigned to element ty.
* @returns {mat23} The newly created matrix.
*/
static create(m00 = 1, m01 = 0, m02 = 0, m03 = 1, m04 = 0, m05 = 0) {
return new mat23(m00, m01, m02, m03, m04, m05);
}
/**
* Clone a matrix.
*
* @param {mat23} a - Matrix to clone.
* @returns {mat23} The newly created matrix.
*/
static clone(a) {
return new mat23(
a.m00, a.m01,
a.m02, a.m03,
a.m04, a.m05
);
}
/**
* Copy content of a matrix into another.
*
* @param {mat23} out - Matrix to modified.
* @param {mat23} a - The specified matrix.
* @returns {mat23} out.
*/
static copy(out, a) {
out.m00 = a.m00;
out.m01 = a.m01;
out.m02 = a.m02;
out.m03 = a.m03;
out.m04 = a.m04;
out.m05 = a.m05;
return out;
}
/**
* Sets a matrix as identity matrix.
*
* @param {mat23} out - Matrix to modified.
* @returns {mat23} out.
*/
static identity(out) {
out.m00 = 1;
out.m01 = 0;
out.m02 = 0;
out.m03 = 1;
out.m04 = 0;
out.m05 = 0;
return out;
}
/**
* Sets the elements of a matrix to the given values.
*
* @param {mat23} out - The matrix to modified.
* @param {Number} a - Value assigned to element a.
* @param {Number} b - Value assigned to element b.
* @param {Number} c - Value assigned to element c.
* @param {Number} d - Value assigned to element d.
* @param {Number} tx - Value assigned to element tx.
* @param {Number} ty - Value assigned to element ty.
* @returns {mat23} out.
*/
static set(out, a, b, c, d, tx, ty) {
out.m00 = a;
out.m01 = b;
out.m02 = c;
out.m03 = d;
out.m04 = tx;
out.m05 = ty;
return out;
}
/**
* Inverts a matrix.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - Matrix to invert.
* @returns {mat23} out.
*/
static invert(out, a) {
let aa = a.m00, ab = a.m01, ac = a.m02, ad = a.m03,
atx = a.m04, aty = a.m05;
let det = aa * ad - ab * ac;
if (!det) {
return null;
}
det = 1.0 / det;
out.m00 = ad * det;
out.m01 = -ab * det;
out.m02 = -ac * det;
out.m03 = aa * det;
out.m04 = (ac * aty - ad * atx) * det;
out.m05 = (ab * atx - aa * aty) * det;
return out;
}
/**
* Calculates the determinant of a matrix.
*
* @param {mat23} a - Matrix to calculate.
* @returns {Number} Determinant of a.
*/
static determinant(a) {
return a.m00 * a.m03 - a.m01 * a.m02;
}
/**
* Multiply two matrices explicitly.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - The first operand.
* @param {mat23} b - The second operand.
* @returns {mat23} out.
*/
static multiply(out, a, b) {
let a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05,
b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05;
out.m00 = a0 * b0 + a2 * b1;
out.m01 = a1 * b0 + a3 * b1;
out.m02 = a0 * b2 + a2 * b3;
out.m03 = a1 * b2 + a3 * b3;
out.m04 = a0 * b4 + a2 * b5 + a4;
out.m05 = a1 * b4 + a3 * b5 + a5;
return out;
}
/**
* Alias of {@link mat23.multiply}.
*/
static mul(out, a, b) {
return mat23.multiply(out, a, b);
}
/**
* Rotates a matrix by the given angle.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - Matrix to rotate.
* @param {Number} rad - The rotation angle.
* @returns {mat23} out
*/
static rotate(out, a, rad) {
let a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05,
s = Math.sin(rad),
c = Math.cos(rad);
out.m00 = a0 * c + a2 * s;
out.m01 = a1 * c + a3 * s;
out.m02 = a0 * -s + a2 * c;
out.m03 = a1 * -s + a3 * c;
out.m04 = a4;
out.m05 = a5;
return out;
}
/**
* Multiply a matrix with a scale matrix given by a scale vector.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - Matrix to multiply.
* @param {vec2} v - The scale vector.
* @returns {mat23} out
**/
static scale(out, a, v) {
let a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05,
v0 = v.x, v1 = v.y;
out.m00 = a0 * v0;
out.m01 = a1 * v0;
out.m02 = a2 * v1;
out.m03 = a3 * v1;
out.m04 = a4;
out.m05 = a5;
return out;
}
/**
* Multiply a matrix with a translation matrix given by a translation offset.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - Matrix to multiply.
* @param {vec2} v - The translation offset.
* @returns {mat23} out.
*/
static translate(out, a, v) {
let a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05,
v0 = v.x, v1 = v.y;
out.m00 = a0;
out.m01 = a1;
out.m02 = a2;
out.m03 = a3;
out.m04 = a0 * v0 + a2 * v1 + a4;
out.m05 = a1 * v0 + a3 * v1 + a5;
return out;
}
/**
* Creates a matrix from a given angle.
* This is equivalent to (but much faster than):
*
* mat23.identity(dest);
* mat23.rotate(dest, dest, rad);
*
* @param {mat23} out - Matrix to store result.
* @param {Number} rad - The rotation angle.
* @returns {mat23} out.
*/
static fromRotation(out, rad) {
let s = Math.sin(rad), c = Math.cos(rad);
out.m00 = c;
out.m01 = s;
out.m02 = -s;
out.m03 = c;
out.m04 = 0;
out.m05 = 0;
return out;
}
/**
* Creates a matrix from a scale vector.
* This is equivalent to (but much faster than):
*
* mat23.identity(dest);
* mat23.scale(dest, dest, vec);
*
* @param {mat23} out - Matrix to store result.
* @param {vec2} v - Scale vector.
* @returns {mat23} out.
*/
static fromScaling(out, v) {
out.m00 = v.m00;
out.m01 = 0;
out.m02 = 0;
out.m03 = v.m01;
out.m04 = 0;
out.m05 = 0;
return out;
}
/**
* Creates a matrix from a translation offset.
* This is equivalent to (but much faster than):
*
* mat23.identity(dest);
* mat23.translate(dest, dest, vec);
*
* @param {mat23} out - Matrix to store result.
* @param {vec2} v - The translation offset.
* @returns {mat23} out.
*/
static fromTranslation(out, v) {
out.m00 = 1;
out.m01 = 0;
out.m02 = 0;
out.m03 = 1;
out.m04 = v.x;
out.m05 = v.y;
return out;
}
/**
* Creates a matrix from a rotation, translation offset and scale vector.
* This is equivalent to (but faster than):
*
* mat23.identity(dest);
* mat23.translate(dest, vec);
* let tmp = mat23.create();
* mat23.fromRotation(tmp, rot);
* mat23.multiply(dest, dest, tmp);
* mat23.fromScaling(tmp, scale);
* mat23.multiply(dest, dest, tmp);
*
* @param {mat23} out - Matrix to store result.
* @param {number} r - Rotation radian.
* @param {vec2} t - Translation offset.
* @param {vec2} s - Scale vector.
* @returns {mat23} out.
*/
static fromRTS(out, r, t, s) {
let sr = Math.sin(r), cr = Math.cos(r);
out.m00 = cr * s.x;
out.m01 = sr * s.x;
out.m02 = -sr * s.y;
out.m03 = cr * s.y;
out.m04 = t.x;
out.m05 = t.y;
return out;
}
/**
* Returns a string representation of a matrix.
*
* @param {mat23} a - The matrix.
* @returns {String} String representation of this matrix.
*/
static str(a) {
return `mat23(${a.m00}, ${a.m01}, ${a.m02}, ${a.m03}, ${a.m04}, ${a.m05})`;
}
/**
* Store elements of a matrix into array.
*
* @param {array} out - Array to store result.
* @param {mat23} m - The matrix.
* @returns {Array} out.
*/
static array(out, m) {
out[0] = m.m00;
out[1] = m.m01;
out[2] = m.m02;
out[3] = m.m03;
out[4] = m.m04;
out[5] = m.m05;
return out;
}
/**
* Store elements of a matrix into 16 floats array.
*
* @param {array} out
* @param {mat23} m
* @returns {array}
*/
static array4x4(out, m) {
out[0] = m.m00;
out[1] = m.m01;
out[2] = 0;
out[3] = 0;
out[4] = m.m02;
out[5] = m.m03;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = m.m04;
out[13] = m.m05;
out[14] = 0;
out[15] = 1;
return out;
}
/**
* Returns Frobenius norm of a matrix.
*
* @param {mat23} a - Matrix to calculate Frobenius norm of.
* @returns {Number} - The frobenius norm.
*/
static frob(a) {
return (Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + 1));
}
/**
* Adds two matrices.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - The first operand.
* @param {mat23} b - The second operand.
* @returns {mat23} out.
*/
static add(out, a, b) {
out.m00 = a.m00 + b.m00;
out.m01 = a.m01 + b.m01;
out.m02 = a.m02 + b.m02;
out.m03 = a.m03 + b.m03;
out.m04 = a.m04 + b.m04;
out.m05 = a.m05 + b.m05;
return out;
}
/**
* Subtracts matrix b from matrix a.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - The first operand.
* @param {mat23} b - The second operand.
* @returns {mat23} out.
*/
static subtract(out, a, b) {
out.m00 = a.m00 - b.m00;
out.m01 = a.m01 - b.m01;
out.m02 = a.m02 - b.m02;
out.m03 = a.m03 - b.m03;
out.m04 = a.m04 - b.m04;
out.m05 = a.m05 - b.m05;
return out;
}
/**
* Alias of {@link mat23.subtract}.
*/
static sub(out, a, b) {
return mat23.subtract(out, a, b);
}
/**
* Multiply each element of a matrix by a scalar number.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - Matrix to scale
* @param {Number} b - The scale number.
* @returns {mat23} out.
*/
static multiplyScalar(out, a, b) {
out.m00 = a.m00 * b;
out.m01 = a.m01 * b;
out.m02 = a.m02 * b;
out.m03 = a.m03 * b;
out.m04 = a.m04 * b;
out.m05 = a.m05 * b;
return out;
}
/**
* Adds two matrices after multiplying each element of the second operand by a scalar number.
*
* @param {mat23} out - Matrix to store result.
* @param {mat23} a - The first operand.
* @param {mat23} b - The second operand.
* @param {Number} scale - The scale number.
* @returns {mat23} out.
*/
static multiplyScalarAndAdd(out, a, b, scale) {
out.m00 = a.m00 + (b.m00 * scale);
out.m01 = a.m01 + (b.m01 * scale);
out.m02 = a.m02 + (b.m02 * scale);
out.m03 = a.m03 + (b.m03 * scale);
out.m04 = a.m04 + (b.m04 * scale);
out.m05 = a.m05 + (b.m05 * scale);
return out;
}
/**
* Returns whether the specified matrices are equal. (Compared using ===)
*
* @param {mat23} a - The first matrix.
* @param {mat23} b - The second matrix.
* @returns {Boolean} True if the matrices are equal, false otherwise.
*/
static exactEquals(a, b) {
return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05;
}
/**
* Returns whether the specified matrices are approximately equal.
*
* @param {mat23} a - The first matrix.
* @param {mat23} b - The second matrix.
* @returns {Boolean} True if the matrices are equal, false otherwise.
*/
static equals(a, b) {
let a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05;
let b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05;
return (
Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) &&
Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) &&
Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) &&
Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5))
);
}
} |
JavaScript | class MsgFilter {
// Attempts to parse and classify JSON data coming in as pubsub messags.
// If the data can not be processed, it returns false, so the message can be
// ignored.
parse (message) {
const data = false
try {
const retObj = {}
retObj.ipfsId = message.from
retObj.msgData = JSON.parse(message.data)
return retObj
} catch (err) {
return data
}
}
} |
JavaScript | class Nav extends React.Component {
render() {
return (
<ul className="nav nav-pills nav-justified">
<Router>
<li className="active">
<Link to="/home">Home</Link>
</li>
<li>
<Link to="/about-us">About Us</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
<li>
<Link to="/testimonies">Testimonies</Link>
</li>
<li>
<Link to="/awards">Awards</Link>
</li>
</Router>
</ul>
);
}
} |
JavaScript | class SampleNode {
constructor() {
// define inputs
this.addInput("A")
this.addInput("B")
// define outputs
this.addOutput("A ^ B")
this.button = this.addWidget('button', '+', null, () => this.addOutput("next"))
this.serialize_widgets = true
}
onStart() {
console.log("Node Started")
this.triggerSlot(0, 1)
}
onConfigure() {
console.log("Node Configured")
}
// callback on input slot triggered
onAction(type, data) {
console.log("Node Input Triggered", { type, data })
}
getMenuOptions() {
return [
{
content: "log graph",
has_submenu: false,
disabled: false,
callback: () => {
console.log(
JSON.stringify(
this.graph.serialize()
)
)
}
}
]
}
} |
JavaScript | class CallerTest extends Core.cls( "Core.abstract.Component" ) {
methodEntryPoint() {
return this.getCaller();
}
get getterEntryPoint() {
return this.getCaller();
}
set setterEntryPoint( ignoredValue ) {
this._setterCaller = this.getCaller();
}
getCaller() {
return Core.debugInspector.getCaller();
}
// ----
static staticMethodEntryPoint() {
return this.getStaticCaller();
}
static get staticGetterEntryPoint() {
return this.getStaticCaller();
}
static set staticSetterEntryPoint( ignoredValue ) {
this._staticSetterCaller = this.getStaticCaller();
}
static getStaticCaller() {
return Core.debugInspector.getCaller();
}
} |
JavaScript | class SharedGeometryEmitter extends SharedEmitter {
/**
* @param {ParticleEmitter2|RibbonEmitter|EventObjectSplEmitter|EventObjectUbrEmitter} modelObject
*/
constructor(modelObject) {
super(modelObject);
this.data = new Float32Array(0);
this.buffer = modelObject.model.viewer.gl.createBuffer();
this.bufferSize = 0;
}
/**
* @param {ParticleEmitter2View|RibbonEmitterView|EventObjectEmitterView} emitterView
* @param {boolean} flag
* @return {Particle2|Ribbon|EventObjectSpl|EventObjectUbr}
*/
emitObject(emitterView, flag) {
return super.emitObject(emitterView, flag);
}
/**
*
*/
updateData() {
let objects = this.objects;
let alive = this.alive;
let sizeNeeded = alive * this.elementsPerEmit;
if (this.data.length < sizeNeeded) {
this.data = new Float32Array(powerOfTwo(sizeNeeded));
let gl = this.modelObject.model.viewer.gl;
gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
gl.bufferData(gl.ARRAY_BUFFER, this.data.byteLength, gl.DYNAMIC_DRAW);
}
let data = this.data;
for (let i = 0, offset = 0; i < alive; i += 1, offset += 30) {
let object = objects[i];
let vertices = object.vertices;
let lta = object.lta;
let lba = object.lba;
let rta = object.rta;
let rba = object.rba;
let rgb = object.rgb;
data[offset + 0] = vertices[0];
data[offset + 1] = vertices[1];
data[offset + 2] = vertices[2];
data[offset + 3] = lta;
data[offset + 4] = rgb;
data[offset + 5] = vertices[3];
data[offset + 6] = vertices[4];
data[offset + 7] = vertices[5];
data[offset + 8] = lba;
data[offset + 9] = rgb;
data[offset + 10] = vertices[6];
data[offset + 11] = vertices[7];
data[offset + 12] = vertices[8];
data[offset + 13] = rba;
data[offset + 14] = rgb;
data[offset + 15] = vertices[0];
data[offset + 16] = vertices[1];
data[offset + 17] = vertices[2];
data[offset + 18] = lta;
data[offset + 19] = rgb;
data[offset + 20] = vertices[6];
data[offset + 21] = vertices[7];
data[offset + 22] = vertices[8];
data[offset + 23] = rba;
data[offset + 24] = rgb;
data[offset + 25] = vertices[9];
data[offset + 26] = vertices[10];
data[offset + 27] = vertices[11];
data[offset + 28] = rta;
data[offset + 29] = rgb;
}
}
/**
* @param {ModelView} modelView
* @param {ShaderProgram} shader
*/
render(modelView, shader) {
let modelObject = this.modelObject;
let alive = this.alive;
if (modelObject.internalResource && alive > 0) {
let model = modelObject.model;
let gl = model.viewer.gl;
gl.blendFunc(modelObject.blendSrc, modelObject.blendDst);
gl.uniform2fv(shader.uniforms.u_dimensions, modelObject.dimensions);
model.bindTexture(modelObject.internalResource, 0, modelView);
gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.data.subarray(0, alive * 30));
gl.vertexAttribPointer(shader.attribs.a_position, 3, gl.FLOAT, false, 20, 0);
gl.vertexAttribPointer(shader.attribs.a_uva_rgb, 2, gl.FLOAT, false, 20, 12);
gl.drawArrays(gl.TRIANGLES, 0, alive * 6);
}
}
} |
JavaScript | class RepList extends Component {
// definerer et tomt array 'reps'
reps = [];
render() {
return (
<Row style={{ marginLeft: '2%', marginTop: '2%', marginRight: '2%', marginBottom: '2%' }}>
<Col>
<Card title="Reparasjoner">
{/* lager en tabell med all informasjon */}
<Table responsive hover>
<thead>
<tr>
<th>Reparasjon id</th>
<th>Sykkel id</th>
<th>Innlevering</th>
<th>Utlevering</th>
<th>Beskrivelse</th>
<th>
<NavLink to={'/reps/add'}>
<Button>Legg til ny</Button>
</NavLink>
</th>
</tr>
</thead>
{/* går gjennom alle reparasjonene */}
{/* .map() funksjonen går gjennom alle elementene i en array i en rekkefølge */}
{this.reps.map(rep => (
<tbody>
<tr key={rep.reparasjons_id}>
<td>{rep.reparasjons_id}</td>
<td>{rep.sykkel_id}</td>
<td>
{/* formaterer riktig dato-oppsett */}
{('0' + rep.repinnlev_dato.getDate()).slice(-2) +
'.' +
('0' + (rep.repinnlev_dato.getMonth() + 1)).slice(-2) +
'.' +
rep.repinnlev_dato.getFullYear()}
</td>
<td>
{('0' + rep.reputlev_dato.getDate()).slice(-2) +
'.' +
('0' + (rep.reputlev_dato.getMonth() + 1)).slice(-2) +
'.' +
rep.reputlev_dato.getFullYear()}
</td>
<td>{rep.rep_beskrivelse}</td>
<td>
{/* link med en knapp med sti til endre reparasjon */}
<NavLink to={'/reps/' + rep.reparasjons_id + '/edit'}>
<Button variant="outline-primary">Endre</Button>
</NavLink>
</td>
</tr>
</tbody>
))}
</Table>
</Card>
</Col>
</Row>
);
}
// mounted()- funksjonen blir kalt når komponenten blir lagt til for visning
// kjører spørringen som ligger i classen repService med navn getReps
mounted() {
repService.getReps(reps => {
this.reps = reps;
});
}
} |
JavaScript | class PreferencesEditorInputFactory extends editor_contribution_1.AbstractSideBySideEditorInputFactory {
createEditorInput(name, description, secondaryInput, primaryInput) {
return new preferencesEditorInput_1.PreferencesEditorInput(name, description, secondaryInput, primaryInput);
}
} |
JavaScript | class DefaultPreferencesEditorInputFactory {
canSerialize(editorInput) {
return true;
}
serialize(editorInput) {
const input = editorInput;
const serialized = { resource: input.resource.toString() };
return JSON.stringify(serialized);
}
deserialize(instantiationService, serializedEditorInput) {
const deserialized = JSON.parse(serializedEditorInput);
return instantiationService.createInstance(preferencesEditorInput_1.DefaultPreferencesEditorInput, uri_1.URI.parse(deserialized.resource));
}
} |
JavaScript | class CountDown {
/**
* Contruct count down and asign start max value to start discount
* @param startValue Asign value to start discount time
* @param clockFormat output format. Return with clock format or no
*/
constructor(startValue, clockFormat = true) {
/**
* @ignore
*/
this.value = -1;
this.value = startValue;
this.clockFormat = clockFormat;
}
/**
* Time seconds counter until asign limit. Increment time values by second
* @example
* 1 EXAMPLE
* this.value = 3.
* this.clockFormat = false
* Return:
* 0d 0h 0m 3s
* 0d 0h 0m 2s
* 0d 0h 0m 1s
* FINISH
* 2 EXAMPLE
* this.value = 3.
* this.clockFormat = true
* Return:
* 00:00:03
* 00:00:02
* FINISH
*/
start(interval_ = constants_1.Timer.ONE_SECOND_IN_MS) {
return interval_1.interval(interval_).pipe(map_1.map((x) => {
return converter_1.secondsInTimeFormat(this.value - x, 2, 1, this.clockFormat);
}));
}
} |
JavaScript | class PackageCommand extends AbstractCommand {
constructor(logger) {
super(logger);
this._target = null;
this._files = null;
this._onlyModified = false;
this._enableMinify = false;
}
// eslint-disable-next-line class-methods-use-this
get requireConfigFile() {
return false;
}
withTarget(value) {
this._target = value;
return this;
}
withFiles(value) {
this._files = value;
return this;
}
withOnlyModified(value) {
this._onlyModified = value;
return this;
}
withMinify(value) {
this._enableMinify = value;
return this;
}
async init() {
await super.init();
this._target = path.resolve(this.directory, this._target);
}
/**
* Creates a .zip package that contains the contents to be deployed to openwhisk.
* As a side effect, this method updates the {@code info.archiveSize} after completion.
*
* @param {ActionInfo} info - The action info object.
* @param {ProgressBar} bar - The progress bar.
* @returns {Promise<any>} Promise that resolves to the package file {@code path}.
*/
async createPackage(info, bar) {
const { log } = this;
const tick = (message, name) => {
const shortname = name.replace(/\/package.json.*/, '').replace(/node_modules\//, '');
bar.tick({
action: name ? `packaging ${shortname}` : '',
});
if (message) {
this.log.maybe({
progress: true,
level: 'info',
message,
});
}
};
return new Promise((resolve, reject) => {
const archiveName = path.basename(info.zipFile);
let hadErrors = false;
// create zip file for package
const output = fs.createWriteStream(info.zipFile);
const archive = archiver('zip');
log.debug(`preparing package ${archiveName}`);
output.on('close', () => {
if (!hadErrors) {
log.debug(`${archiveName}: Created package. ${archive.pointer()} total bytes`);
// eslint-disable-next-line no-param-reassign
info.archiveSize = archive.pointer();
this.emit('create-package', info);
resolve(info);
}
});
archive.on('entry', (data) => {
log.debug(`${archiveName}: A ${data.name}`);
tick('', data.name);
});
archive.on('warning', (err) => {
log.error(`${chalk.redBright('[error] ')}Unable to create archive: ${err.message}`);
hadErrors = true;
reject(err);
});
archive.on('error', (err) => {
log.error(`${chalk.redBright('[error] ')}Unable to create archive: ${err.message}`);
hadErrors = true;
reject(err);
});
archive.pipe(output);
const packageJson = {
name: info.name,
version: '1.0',
description: `Lambda function of ${info.name}`,
main: path.basename(info.main),
license: 'Apache-2.0',
};
archive.append(JSON.stringify(packageJson, null, ' '), { name: 'package.json' });
archive.file(info.bundlePath, { name: path.basename(info.main) });
archive.finalize();
});
}
/**
* Creates the action bundles from the given scripts. It uses the {@code ActionBundler} which
* in turn uses webpack to create individual bundles of each {@code script}. The final bundles
* are wirtten to the {@code this._target} directory.
*
* @param {ActionInfo[]} scripts - the scripts information.
* @param {ProgressBar} bar - The progress bar.
*/
async createBundles(scripts, bar) {
const progressHandler = (percent, msg, ...args) => {
/* eslint-disable no-param-reassign */
const action = args.length > 0 ? `${msg} ${args[0]}` : msg;
const rt = bar.renderThrottle;
if (msg !== 'building') {
// this is kind of a hack to force redraw for non-bundling steps.
bar.renderThrottle = 0;
}
bar.update(percent * 0.8, { action });
bar.renderThrottle = rt;
/* eslint-enable no-param-reassign */
};
// create the bundles
const bundler = new ActionBundler()
.withDirectory(this._target)
.withModulePaths(['node_modules', path.resolve(__dirname, '..', 'node_modules')])
.withLogger(this.log)
.withProgressHandler(progressHandler)
.withMinify(this._enableMinify);
const files = {};
scripts.forEach((script) => {
files[script.name] = path.resolve(this._target, script.main);
});
const stats = await bundler.run(files);
if (stats.errors) {
stats.errors.forEach(this.log.error);
}
if (stats.warnings) {
stats.warnings.forEach(this.log.warn);
}
}
/**
* Run this command.
*/
async run() {
await this.init();
// always run build first to make sure scripts are up to date
await new BuildCommand(this.log)
.withFiles(this._files)
.withTargetDir(this._target)
.run();
// get the list of scripts from the info files
const infos = [...glob.sync(`${this._target}/**/*.info.json`)];
const scriptInfos = await Promise.all(infos.map((info) => fs.readJSON(info)));
// resolve dependencies
let scripts = flattenDependencies(scriptInfos);
// filter out the ones that already have the info and a valid zip file
if (this._onlyModified) {
await Promise.all(scripts.map(async (script) => {
// check if zip exists, and if not, clear the path entry
if (!script.zipFile || !(await fs.pathExists(script.zipFile))) {
// eslint-disable-next-line no-param-reassign
delete script.zipFile;
}
}));
scripts.filter((script) => script.zipFile).forEach((script) => {
this.emit('ignore-package', script);
});
scripts = scripts.filter((script) => !script.zipFile);
}
if (scripts.length > 0) {
// generate additional infos
scripts.forEach((script) => {
/* eslint-disable no-param-reassign */
script.name = path.basename(script.main, '.js');
script.bundleName = `${script.name}.bundle.js`;
script.bundlePath = path.resolve(this._target, script.bundleName);
script.dirname = script.isStatic ? '' : path.dirname(script.main);
script.archiveName = `${script.name}.zip`;
script.zipFile = path.resolve(this._target, script.dirname, script.archiveName);
script.infoFile = path.resolve(this._target, script.dirname, `${script.name}.info.json`);
/* eslint-enable no-param-reassign */
});
// we reserve 80% for bundling the scripts and 20% for creating the zip files.
const bar = new ProgressBar('[:bar] :action :elapseds', {
total: scripts.length * 2 * 5,
width: 50,
renderThrottle: 50,
stream: process.stdout,
});
// create bundles
await this.createBundles(scripts, bar);
// package actions
await Promise.all(scripts.map((script) => this.createPackage(script, bar)));
// write back the updated infos
// eslint-disable-next-line max-len
await Promise.all(scripts.map((script) => fs.writeJson(script.infoFile, script, { spaces: 2 })));
}
this.log.info('✅ packaging completed');
return this;
}
} |
JavaScript | class ReverseGeoWrapper {
constructor(googleResponse) {
if (googleResponse && googleResponse.results)
this.googleResponse = [...googleResponse.results];
else this.googleResponse = [];
}
/**
* Returns the very first result on the `results` array from Google Geocoding API.
* @param {boolean} formatted - Return address as a formatted string if `true`. `false` by default.
* @returns {(string|object|null)} - returns string representing formatted address, { lat, lng } if formatted is false, or null on error.
*/
getTopAddress(formatted = false) {
const results = this.googleResponse;
if (Array.isArray(results) && results.length > 0 && !formatted) {
if (results[0].geometry && results[0].geometry.location) {
return results[0].geometry.location;
}
return null;
} else if (Array.isArray(results) && results.length > 0 && formatted) {
return results[0].formatted_address || null;
} else {
return null;
}
}
/**
* Returns the very first result on the `results` array from Google Geocoding API.
* @returns {array} - returns a shallow copy of an array of address objects
*/
getAllAddresses() {
if (Array.isArray(this.googleResponse)) {
return [...this.googleResponse];
}
return null;
}
} |
JavaScript | class LayerPanelListItem extends Component {
render () {
const { title, item, children, handleDoubleClick } = this.props
return (
<ListItem key={title} onDoubleClick={() => { handleDoubleClick(item) }}>
{children}
</ListItem>
)
}
} |
JavaScript | class ComplexBarcodeGenerator extends assist.BaseJavaClass {
static javaClassName = "com.aspose.mw.barcode.complexbarcode.MwComplexBarcodeGenerator";
parameters;
init() {
this.parameters = new generation.BaseGenerationParameters(this.getJavaClass().getParametersSync());
}
/**
* Generation parameters.
*/
getParameters() {
return this.parameters;
}
/**
* Creates an instance of ComplexBarcodeGenerator.
* @param arg Complex codetext
*/
constructor(arg) {
super(ComplexBarcodeGenerator.initComplexBarcodeGenerator(arg));
this.init();
}
static initComplexBarcodeGenerator(arg) {
if (arg instanceof SwissQRCodetext) {
let javaComplexBarcodeGenerator = java.import(ComplexBarcodeGenerator.javaClassName);
return new javaComplexBarcodeGenerator(arg.getJavaClass())
} else {
let java_link = java.import(arg);
return new java_link();
}
}
/**
* Generates complex barcode image under current settings.
* @return Barcode image. See {@code Bitmap}.
*/
generateBarcodeImage(format_name) {
let base64Image = this.getJavaClass().generateBarCodeImageSync(format_name);
return base64Image;
}
/**
* <p>
* Generates and saves complex barcode image under current settings.
* </p>
* @param filename Path to save to.
* @param format Specifies the file format of the output image.
*/
save(filePath, format_name) {
let image64 = this.generateBarcodeImage(format_name);
let buff = Buffer.from(image64, 'base64');
fs.writeFileSync(filePath, buff);
}
} |
JavaScript | class Address extends assist.BaseJavaClass {
static javaClassName = "com.aspose.mw.barcode.complexbarcode.MwAddress";
constructor(arg) {
super(Address.initAddress(arg));
this.init();
}
static initAddress(arg) {
if (arg == null) {
let javaAddress = java.import(Address.javaClassName);
return new javaAddress();
}
return arg;
}
/**
* Gets the address type.
*
* The address type is automatically set by either setting street / house number
* or address line 1 and 2. Before setting the fields, the address type is Undetermined.
* If fields of both types are set, the address type becomes Conflicting.
*
* Value: The address type.
*/
getType() {
return this.getJavaClass().getTypeSync();
}
/**
* Gets the name, either the first and last name of a natural person or the
* company name of a legal person.
* Value: The name.
*/
getName() {
return this.getJavaClass().getNameSync();
}
/**
* Sets the name, either the first and last name of a natural person or the
* company name of a legal person.
* Value: The name.
*/
setName(value) {
this.getJavaClass().setNameSync(value);
}
/**
* Gets the address line 1.
*
* Address line 1 contains street name, house number or P.O. box.
*
* Setting this field sets the address type to AddressType.COMBINED_ELEMENTS unless it's already
* AddressType.STRUCTURED, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for combined elements addresses and is optional.
*
* Value: The address line 1.
*/
getAddressLine1() {
return this.getJavaClass().getAddressLine1Sync();
}
/**
* Sets the address line 1.
*
* Address line 1 contains street name, house number or P.O. box.
*
* Setting this field sets the address type to AddressType.COMBINED_ELEMENTS unless it's already
* AddressType.STRUCTURED, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for combined elements addresses and is optional.
*
* Value: The address line 1.
*/
setAddressLine1(value) {
this.getJavaClass().setAddressLine1Sync(value);
}
/**
* Gets the address line 2.
* Address line 2 contains postal code and town.
* Setting this field sets the address type to AddressType.COMBINED_ELEMENTS unless it's already
* AddressType.STRUCTURED, in which case it becomes AddressType.CONFLICTING.
* This field is only used for combined elements addresses. For this type, it's mandatory.
* Value: The address line 2.
*/
getAddressLine2() {
return this.getJavaClass().getAddressLine2Sync();
}
/**
* Sets the address line 2.
* Address line 2 contains postal code and town.
* Setting this field sets the address type to AddressType.COMBINED_ELEMENTS unless it's already
* AddressType.STRUCTURED, in which case it becomes AddressType.CONFLICTING.
* This field is only used for combined elements addresses. For this type, it's mandatory.
* Value: The address line 2.
*/
setAddressLine2(value) {
this.getJavaClass().setAddressLine2Sync(value);
}
/**
* Gets the street.
* The street must be speicfied without house number.
* Setting this field sets the address type to AddressType.STRUCTURED unless it's already
* AddressType.COMBINED_ELEMENTS, in which case it becomes AddressType.CONFLICTING.
* This field is only used for structured addresses and is optional.
* Value: The street.
*/
getStreet() {
return this.getJavaClass().getStreetSync();
}
/**
* Sets the street.
*
* The street must be speicfied without house number.
*
* Setting this field sets the address type to AddressType.STRUCTURED unless it's already
* AddressType.COMBINED_ELEMENTS, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for structured addresses and is optional.
*
* Value: The street.
*/
setStreet(value) {
this.getJavaClass().setStreetSync(value);
}
/**
* Gets the house number.
*
* Setting this field sets the address type to AddressType.STRUCTURED unless it's already
* AddressType.COMBINED_ELEMENTS, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for structured addresses and is optional.
*
* Value: The house number.
*/
getHouseNo() {
return this.getJavaClass().getHouseNoSync();
}
/**
* Sets the house number.
*
* Setting this field sets the address type to AddressType.STRUCTURED unless it's already
* AddressType.COMBINED_ELEMENTS, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for structured addresses and is optional.
*
* Value: The house number.
*/
setHouseNo(value) {
this.getJavaClass().setHouseNoSync(value);
}
/**
* Gets the postal code.
*
* Setting this field sets the address type to AddressType.STRUCTURED unless it's already
* AddressType.COMBINED_ELEMENTS, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for structured addresses. For this type, it's mandatory.
*
* Value: The postal code.
*/
getPostalCode() {
return this.getJavaClass().getPostalCodeSync();
}
/**
* Sets the postal code.
*
* Setting this field sets the address type to AddressType.STRUCTURED unless it's already
* AddressType.COMBINED_ELEMENTS, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for structured addresses. For this type, it's mandatory.
*
* Value: The postal code.
*/
setPostalCode(value) {
this.getJavaClass().setPostalCodeSync(value);
}
/**
* Gets the town or city.
*
* Setting this field sets the address type to AddressType.STRUCTURED unless it's already
* AddressType.COMBINED_ELEMENTS, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for structured addresses. For this type, it's mandatory.
*
* Value: The town or city.
*/
getTown() {
return this.getJavaClass().getTownSync();
}
/**
* Sets the town or city.
*
* Setting this field sets the address type to AddressType.STRUCTURED unless it's already
* AddressType.COMBINED_ELEMENTS, in which case it becomes AddressType.CONFLICTING.
*
* This field is only used for structured addresses. For this type, it's mandatory.
*
* Value: The town or city.
*/
setTown(value) {
this.getJavaClass().setTownSync(value);
}
/**
* Gets the two-letter ISO country code.
*
* The country code is mandatory unless the entire address contains null or emtpy values.
*
* Value: The ISO country code.
*/
getCountryCode() {
return this.getJavaClass().getCountryCodeSync();
}
/**
* Sets the two-letter ISO country code.
*
* The country code is mandatory unless the entire address contains null or emtpy values.
*
* Value: The ISO country code.
*/
setCountryCode(value) {
this.getJavaClass().setCountryCodeSync(value);
}
/**
* Clears all fields and sets the type to AddressType.UNDETERMINED.
*/
clear() {
this.setName(null);
this.setAddressLine1(null);
this.setaddressLine2(null);
this.setStreet(null);
this.setHouseNo(null);
this.setPostalCode(null);
this.setTown(null);
this.setCountryCode(null);
}
/**
* Determines whether the specified object is equal to the current object.
* @return true if the specified object is equal to the current object; otherwise, false.
* @param obj The object to compare with the current object.
*/
equals(obj) {
return this.getJavaClass().equalsSync(obj);
}
/**
* Gets the hash code for this instance.
* @return A hash code for the current object.
*/
hashCode() {
return this.getJavaClass().hashCodeSync();
}
init() {
// TODO: Implement init() method.
}
} |
JavaScript | class AlternativeScheme extends assist.BaseJavaClass {
static get javaClassName() {
return "com.aspose.mw.barcode.complexbarcode.MwAlternativeScheme";
}
constructor(instruction)
{
let javaAlternativeScheme = java.import(AlternativeScheme.javaClassName);
super(new javaAlternativeScheme(instruction));
}
/**
* Gets the payment instruction for a given bill.
*
* The instruction consists of a two letter abbreviation for the scheme, a separator characters
* and a sequence of parameters(separated by the character at index 2).
*
* Value: The payment instruction.
*/
getInstruction() {
return this.getJavaClass().getInstructionSync();
}
/**
* Gets the payment instruction for a given bill.
* The instruction consists of a two letter abbreviation for the scheme, a separator characters
* and a sequence of parameters(separated by the character at index 2).
* Value: The payment instruction.
*/
setInstruction(value) {
this.getJavaClass().setInstructionSync(value);
}
/**
* Determines whether the specified object is equal to the current object.
* @return true if the specified object is equal to the current object; otherwise, false.
* @param obj The object to compare with the current object.
*/
equals(obj) {
return this.getJavaClass().equalsSync(obj);
}
/**
* Gets the hash code for this instance.
* @return hash code for the current object.
*/
hashCode() {
return this.getJavaClass().hashCodeSync();
}
init() {
// TODO: Implement init() method.
}
} |
JavaScript | class ComplexCodetextReader {
static javaClassName = "com.aspose.mw.barcode.complexbarcode.MwComplexCodetextReader";
/**
* Decodes SwissQR codetext.
*
* @return decoded SwissQRCodetext or null.
* @param encodedCodetext encoded codetext
*/
static tryDecodeSwissQR(encodedCodetext) {
let javaPhpComplexCodetextReader = java.import(ComplexCodetextReader.javaClassName);
return new SwissQRCodetext(javaPhpComplexCodetextReader.tryDecodeSwissQRSync(encodedCodetext));
}
} |
JavaScript | class SwissQRCodetext extends assist.BaseJavaClass {
static javaClassName = "com.aspose.mw.barcode.complexbarcode.MwSwissQRCodetext";
bill;
init() {
this.bill = new SwissQRBill(this.getJavaClass().getBillSync());
}
/**
* SwissQR bill data
*/
getBill() {
return this.bill;
}
/**
* Creates an instance of SwissQRCodetext.
*
* @param bill SwissQR bill data
* @throws BarcodeException
*/
constructor(arg) {
super(SwissQRCodetext.initSwissQRCodetext(arg));
this.init();
}
static initSwissQRCodetext(arg) {
if (arg instanceof SwissQRBill) {
let javaSwissQRCodetext = java.import(SwissQRCodetext.javaClassName);
return new javaSwissQRCodetext(arg.getJavaClass());
} else if (arg == null) {
let javaSwissQRCodetext = java.import(SwissQRCodetext.javaClassName);
return new javaSwissQRCodetext();
} else {
return arg;
}
}
/**
* Construct codetext from SwissQR bill data
*
* @return Constructed codetext
*/
getConstructedCodetext() {
return this.getJavaClass().getConstructedCodetextSync();
}
/**
* Initializes Bill with constructed codetext.
*
* @param constructedCodetext Constructed codetext.
*/
initFromString(constructedCodetext) {
this.getJavaClass().initFromStringSync(constructedCodetext);
}
/**
* Gets barcode type.
*
* @return Barcode type.
*/
getBarcodeType() {
return this.getJavaClass().getBarcodeTypeSync();
}
} |
JavaScript | class StorageProvider {
/**
* Gets the name of this type of storage provider.
* @public
* @abstract
* @method
* @returns {String}
*/
static getName() {}
/**
* Store a name-value pair of information.
* @public
* @abstract
* @param {String} name The name of the value to store.
* @param {any} value The string value to store. Note that any type
* of object is accepted, not only strings.
*/
async storeValue(name, value) {}
/**
* Retrieve a value based on its name from the storage repository.
* @public
* @abstract
* @param {String} name The name of the value to retrieve.
* @param {any} defaultValue The value to return if one cannot be found.
* @param {...any} args Any arguments to return along with the value.
* @returns {StorageRetrievalResult} The result of the retrieval attempt.
*/
async getValue(name, defaultValue, ...args) {}
/**
* Determine whether or not this storage provider is available in the
* current context.
* @public
* @abstract
* @returns {Boolean}
*/
isAvailable() {}
} |
JavaScript | class AsyncImage extends Component {
/**
* @param {*} props
*/
constructor(props) {
super(props);
this.state = {
has_error: false,
image_loaded: false,
loading_finished: false,
source: null
};
this._fetchImageFromSrc = this._fetchImageFromSrc.bind(this);
this.renderImageOrPlaceholder = this.renderImageOrPlaceholder.bind(this);
}
// Methods
// --------------------------------------------------------------------
/**
* @private
*/
async _fetchImageFromSrc() {
const { props, state } = this;
if (state.image_loaded === false) {
try {
const load = await axios.get(
props.src,
{
responseType: "arraybuffer"
}
);
if (load.data instanceof ArrayBuffer) {
let buffer = new Buffer(load.data, "binary").toString("base64");
let mime = load.headers["content-type"];
let data = `data:${mime};base64,${buffer}`;
this.setState({
image_loaded: true,
source: data
});
} else {
this.setState({
has_error: true,
image_loaded: true
});
console.error("Received data is not a valid array buffer.");
}
} catch (err) {
this.setState({
has_error: true,
image_loaded: true
});
console.error(err);
}
}
}
/**
* Conditional renderer.
*/
renderImageOrPlaceholder() {
const { props, state } = this;
let _cls_error = (props.errorClass !== "")
? props.errorClass
: "async-image-error";
let _cls_loader = (props.loaderClass !== "")
? props.loaderClass
: "async-image-loader";
let _cls_image_placeholder = (props.loaderClass !== "")
? props.loaderClass
: "async-image-placeholder";
let _cls_image = (props.imageClass !== "")
? props.imageClass
: "async-image-item";
if (state.has_error === true) {
return (
<span className={"async-image-error"}>Could not load image.</span>
);
}
if (state.image_loaded === false) {
if (
props.placeholderImage !== ""
&& props.placeholderImage !== null
&& props.placeholderImage !== undefined
) {
return (
<img
src={props.placeholderImage}
alt={props.alt}
className={"async-image-placeholder"}/>
);
}
return (
<span className={"async-image-loading"}></span>
);
}
return (
<img src={state.source} alt={props.alt} className={"async-image-item"}/>
);
}
// React Lifecycle
// --------------------------------------------------------------------
componentDidMount() {
this._fetchImageFromSrc();
}
componentDidUpdate() {
const { state } = this;
}
render() {
const { props } = this;
let _cls = (props.className) ? classnames(props.className) : "async-image";
return (
<div className={_cls}>
{this.renderImageOrPlaceholder()}
</div>
);
};
} |
JavaScript | class MultiVerseBar extends Bar {
getContentRender() {
return this.html `
${super.getContentRender()}
${this.selectType === 'brush'
? this.html `<multi-brush
id="selector"
x-continuous=""
.log="${this.log}"
.xScale="${this.bottomScale}"
.preventClear="${this.preventClear}"
@selected-values-changed="${e => this.selectedValues = e.detail.value}"
></multi-brush>`
: this.html `<multi-select
id="selector"
.multi="${this.multi}"
.trackHover="${this.trackHover}"
.selectedItems="${this.selectedItems}"
.selectedValues="${this.selectedValues}"
.selectedItem="${this.selectedItem}"
.selected="${this.selected}"
@selected-values-changed="${e => this.selectedValues = e.detail.value}"
@selected-changed="${e => this.selected = e.detail.value}"
></multi-select>`
}
`;
}
get selector() {
return this.renderRoot.querySelector('#selector');
}
clearSelection() {
this.selector && this.selector.clearSelection()
}
static get properties() {
return {
...super.properties,
...Select.properties,
...ChartProperties,
keys: {
type: Array,
value: ['count']
},
valuePath: {
type: String,
attribute: 'value-path',
value: 'value.count'
},
bottomPadding: {
type: Number,
attribute: 'bottom-padding',
value: 0.3
},
/*
* `preventClear` set true to prevent selection to cleat on brush end
*/
preventClear: {
type: Boolean,
attribute: 'prevent-clear'
},
};
}
} |
JavaScript | class GlideDuration {
/**
* Instantiates a GlideDuration object.
*/
constructor() {}
/**
* Add the specified duration to the object.
* @param {GlideDuration} duration The value to add to the object.
* @returns The sum of the current and the added duration.
* @example var duration = new GlideDuration('3 12:00:00');
* var duration2 = new GlideDuration('3:00:00');
* var answer = duration.add(duration2);
* gs.info(answer.getDisplayValue());
*/
add(duration) {}
/**
* Gets the duration in the specified format.
* @param {String} format The duration format.
* @returns The current duration in the specified format.
* @example var dur = new GlideDuration('3 22:00:00');
* gs.info(dur.getByFormat('HH:mm'));
*/
getByFormat(format) {}
/**
* Gets the number of days.
* @returns The number of days.
* @example var dur = new GlideDuration('3 12:00:00');
* gs.info(dur.getDayPart());
*/
getDayPart() {}
/**
* Gets the display value of the duration in number of days, hours, and
* minutes.
* @returns The number of days, hours, and minutes.
* @example var dur = new GlideDuration('3 12:00:00');
* gs.info(dur.getDisplayValue());
*/
getDisplayValue() {}
/**
* Gets the duration value in "d HH:mm:ss" format.
* @returns The duration value.
* @example var dur = new GlideDuration('3 12:00:00');
* gs.info(dur.getDurationValue());
*/
getDurationValue() {}
/**
* Gets the rounded number of days. If the time part is more than 12 hours, the return
* value is rounded up. Otherwise, it is rounded down.
* @returns The day part, rounded.
* @example var dur = new GlideDuration('3 11:00:00');
* gs.info(dur.getRoundedDayPart());
*/
getRoundedDayPart() {}
/**
* Gets the internal value of the GlideDuration object.
* @returns The duration in the object's internal format, which is the date and time from
* January 1, 1970, 00:00:00.
* @example var dur = new GlideDuration('3 12:00:00');
* gs.info(dur.getValue());
*/
getValue() {}
/**
* Sets the display value.
* @param {String} asDisplayed The duration in "d HH:mm:ss" format.
* @returns Method does not return a value
* @example var dur = new GlideDuration();
* dur.setDisplayValue('3 08:00:00');
* gs.info(dur.getDisplayValue());
*/
setDisplayValue(asDisplayed) {}
/**
* Sets the internal value of the GlideDuration object.
* @param {Object} o The duration in the object's internal format, which is the date and time from
* January 1, 1970, 00:00:00.
* @returns Method does not return a value
* @example var dur = new GlideDuration();
* dur.setValue('1970-01-05 08:00:00'); // sets internal DateTime value. The String will be parsed into a GlideDateTime object.
* gs.info(dur.getDisplayValue());
*/
setValue(o) {}
/**
* Subtracts the specified duration from the current duration.
* @param {GlideDuration} duration The duration to subtract.
* @returns Method does not return a value
* @example var duration = new GlideDuration('3 12:00:00');
* var duration2 = new GlideDuration('3:00:00');
* var answer = duration.subtract(duration2);
* gs.info(answer.getDisplayValue());
*/
subtract(duration) {}
} |
JavaScript | class DashboardModel extends Model {
constructor(server) {
const schema = Joi.object().keys({
title: Joi.string(),
hits: Joi.number().integer(),
description: Joi.string(),
panelsJSON: Joi.string(),
optionsJSON: Joi.string(),
uiStateJSON: Joi.string(),
version: Joi.number().integer(),
timeRestore: Joi.boolean(),
timeMode: Joi.string(),
timeTo: Joi.string(),
timeFrom: Joi.string(),
savedSearchId: Joi.string(),
refreshInterval: Joi.object().keys({
display: Joi.string(),
pause: Joi.boolean(),
value: Joi.number(),
section: Joi.number()
}),
priority: Joi.number(),
kibanaSavedObjectMeta: Joi.object().keys({
searchSourceJSON: Joi.string()
})
});
super(server, 'dashboard', schema, 'Dashboard');
}
} |
JavaScript | class PromiseQueue {
constructor (options) {
Object.assign(this, options)
this.onFinish = this.onFinish ? this.onFinish.bind(this) : () => {}
this.concurrency = this.concurrency ? this.concurrency : 1
this.promises = []
this.queue = []
}
add (fn, options) {
if (typeof fn !== 'function') {
throw new Error('Expected a function as an argument.')
}
return new Promise((resolve, reject) => {
const attempts = (options && options.attempts && options.attempts > 0) ? options.attempts : 1
const onFinish = (options && options.onFinish) ? options.onFinish.bind(this) : () => {}
if (this.promises.length < this.concurrency) {
const id = this.promises.length ? this.promises[this.promises.length - 1].id + 1 : 1
this.promises.push({id: id, promise: this._wrap(fn, id, resolve, reject, attempts, onFinish)})
} else {
this.queue.push({fn, attempts, resolve, reject, onFinish})
}
})
}
_promised (fn) {
try {
return Promise.resolve(fn())
} catch (error) {
return Promise.reject(error)
}
}
_next (id) {
if (this.signal.aborted) {
return true
}
if (this.queue.length > 0) {
const nextFn = this.queue.shift()
return this._wrap(nextFn.fn, id, nextFn.resolve, nextFn.reject, nextFn.attempts)
}
const promiseId = this.promises.findIndex(promise => promise.id === id)
const finishedPromise = this.promises.splice(promiseId, 1)[0]
if (finishedPromise && finishedPromise.onFinish) {
finishedPromise.onFinish()
}
if (this.promises.length === 0) {
this.onFinish()
}
return true
}
_wrap (fn, id, resolve, reject, attempts) {
let retryCount = 0
const retry = error => {
if (retryCount >= attempts) {
throw error || new Error('Retry attempts exceeded')
}
retryCount++
return this._promised(fn).catch(retry)
}
return retry()
.then(promise => resolve(promise), error => reject(error))
.then(() => this._next(id))
}
} |
JavaScript | class MapReducer extends MapReducerCore {
static getLayerModel() {
return layerModel;
}
static setMapDate(state, action) {
state = MapReducerCore.setMapDate(state, action);
let size = state.get("dateIntervalSize");
let scale = state.get("dateIntervalScale");
let date = moment.utc(state.get("date"));
return state.set("intervalDate", date.subtract(size, scale).toDate());
}
static setDateInterval(state, action) {
let alerts = state.get("alerts");
if (state.getIn(["animation", "initiated"])) {
if (state.getIn(["animation", "isPlaying"])) {
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.ANIMATION_NO_CHANGE_STEP.title,
body: appStrings.ALERTS.ANIMATION_NO_CHANGE_STEP.formatString,
severity: appStrings.ALERTS.ANIMATION_NO_CHANGE_STEP.severity,
time: new Date()
})
);
}
state = this.stopAnimation(state, {});
}
let size = parseInt(action.size);
let scale = action.scale;
try {
let intervalDate = moment.utc(state.get("date")).subtract(size, scale);
if (intervalDate.isValid()) {
// let intervalMs = moment.duration(size, scale).asMilliseconds();
// update each map
state.get("maps").forEach(map => {
if (map.setMapDateInterval({ size, scale })) {
// update each layer on the map
state.get("layers").forEach(layerSection => {
layerSection.forEach(layer => {
if (
layer.get("isActive") &&
layer.get("updateParameters").get("time")
) {
map.updateLayer(layer);
}
});
});
}
});
return state
.set("dateIntervalSize", size)
.set("dateIntervalScale", scale)
.set("intervalDate", intervalDate.toDate())
.set("alerts", alerts);
}
} catch (err) {
console.warn("Error in MapReducer.setDateInterval: ", err);
return state;
}
}
static setLayerLoading(state, action) {
let actionLayer = action.layer;
if (typeof actionLayer === "string") {
actionLayer = this.findLayerById(state, actionLayer);
}
if (typeof actionLayer !== "undefined") {
state = state.setIn(
["layers", actionLayer.get("type"), actionLayer.get("id"), "isLoading"],
action.isLoading
);
}
return state;
}
static setInsituLayerTitles(state, action) {
if (typeof action.titleField !== "undefined") {
let dataLayers = state
.getIn(["layers", appStrings.LAYER_GROUP_TYPE_INSITU_DATA])
.map(layer => {
if (typeof layer.getIn(["insituMeta", action.titleField]) !== "undefined") {
return layer.set("title", layer.getIn(["insituMeta", action.titleField]));
}
return layer;
});
return state
.setIn(["layers", appStrings.LAYER_GROUP_TYPE_INSITU_DATA], dataLayers)
.set("insituLayerTitleField", action.titleField);
}
return state;
}
static setLayerActive(state, action) {
// turn off the other data layers first
if (action.active) {
// resolve layer from id if necessary
let actionLayer = action.layer;
if (typeof actionLayer === "string") {
actionLayer = this.findLayerById(state, actionLayer);
}
if (typeof actionLayer !== "undefined") {
if (actionLayer.get("type") === appStringsCore.LAYER_GROUP_TYPE_DATA) {
let dataLayers = state.getIn(["layers", appStringsCore.LAYER_GROUP_TYPE_DATA]);
dataLayers.map((layer, id) => {
if (layer.get("isActive")) {
state = MapReducerCore.setLayerActive(state, {
layer: id,
active: false
});
}
});
} else if (actionLayer.get("type") === appStrings.LAYER_GROUP_TYPE_INSITU_DATA) {
// set the color of this vector layer
let dataLayers = state.getIn([
"layers",
appStrings.LAYER_GROUP_TYPE_INSITU_DATA
]);
let colorIndex = MiscUtil.getRandomInt(
0,
appConfig.INSITU_VECTOR_COLORS.length
);
let color = appConfig.INSITU_VECTOR_COLORS[colorIndex];
state = state
.setIn(
[
"layers",
appStrings.LAYER_GROUP_TYPE_INSITU_DATA,
actionLayer.get("id"),
"vectorColor"
],
color
)
.setIn(
[
"layers",
appStrings.LAYER_GROUP_TYPE_INSITU_DATA,
actionLayer.get("id"),
"isLoading"
],
true
);
}
}
}
state = MapReducerCore.setLayerActive(state, action);
// check if we need to stop and clear the animation
let alerts = state.get("alerts");
if (state.getIn(["animation", "initiated"])) {
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.ANIMATION_NO_LAYER_TOGGLE.title,
body: appStrings.ALERTS.ANIMATION_NO_LAYER_TOGGLE.formatString,
severity: appStrings.ALERTS.ANIMATION_NO_LAYER_TOGGLE.severity,
time: new Date()
})
);
state = this.stopAnimation(state, {}).set("alerts", alerts);
}
return state;
}
static setTrackErrorActive(state, action) {
// resolve layer from id if necessary
let actionLayer = action.layer;
if (typeof actionLayer === "string") {
actionLayer = this.findLayerById(state, actionLayer);
}
if (typeof actionLayer !== "undefined") {
state = state.setIn(
["layers", actionLayer.get("type"), actionLayer.get("id"), "isErrorActive"],
action.isActive
);
}
return state;
}
static pixelHover(state, action) {
let pixelCoordinate = state.getIn(["view", "pixelHoverCoordinate"]).set("isValid", false);
state.get("maps").forEach(map => {
if (map.isActive) {
let data = [];
let coords = map.getLatLonFromPixelCoordinate(action.pixel);
if (coords.isValid) {
// find data if any
data = map.getDataAtPoint(coords, action.pixel, state.get("palettes"));
data = data !== false ? data : [];
data = Immutable.fromJS(
data.map(entry => {
entry.layer = this.findLayerById(state, entry.layerId);
return entry;
})
);
// extract reference layer data
let refData = data.filter(entry => {
return (
entry.getIn(["layer", "type"]) ===
appStrings.LAYER_GROUP_TYPE_DATA_REFERENCE
);
});
data = data
.filterNot(entry => {
return (
entry.getIn(["layer", "type"]) ===
appStrings.LAYER_GROUP_TYPE_DATA_REFERENCE
);
})
.slice(0, 1);
state = state.setIn(["view", "refHoverData"], refData);
// set the coordinate as valid
pixelCoordinate = pixelCoordinate
.set("lat", coords.lat)
.set("lon", coords.lon)
.set("x", action.pixel[0])
.set("y", action.pixel[1])
.set("data", data)
.set("showData", data.size > 0)
.set("isValid", true);
} else {
pixelCoordinate = pixelCoordinate.set("isValid", false);
}
}
return true;
});
return state.setIn(["view", "pixelHoverCoordinate"], pixelCoordinate);
}
static pixelClick(state, action) {
let pixelCoordinate = state.getIn(["view", "pixelClickCoordinate"]).set("isValid", false);
state.get("maps").forEach(map => {
if (map.isActive) {
let data = [];
let pixel = map.getPixelFromClickEvent(action.clickEvt);
if (pixel) {
let coords = map.getLatLonFromPixelCoordinate(pixel);
if (coords.isValid) {
// find data if any
data = map.getDataAtPoint(coords, pixel, state.get("palettes"));
data = data !== false ? data : [];
data = Immutable.fromJS(
data.map(entry => {
entry.layer = this.findLayerById(state, entry.layerId);
return entry;
})
);
data = data
.filterNot(entry => {
return (
entry.getIn(["layer", "type"]) ===
appStrings.LAYER_GROUP_TYPE_DATA_REFERENCE
);
})
.slice(0, 1);
// set the coordinate as valid
pixelCoordinate = pixelCoordinate
.set("lat", coords.lat)
.set("lon", coords.lon)
.set("x", pixel[0])
.set("y", pixel[1])
.set("data", data)
.set("showData", data.size > 0)
.set("isValid", true);
let dateStr = data.getIn([0, "properties", "position_date_time", 0]);
if (typeof dateStr !== "undefined") {
// let date = moment.utc(dateStr, data.getIn([0, "layer", "timeFormat"]));
let date = moment.utc(dateStr);
state = MapReducer.setMapDate(state, { date: date.toDate() });
}
} else {
pixelCoordinate = pixelCoordinate.set("isValid", false);
}
}
}
return true;
});
return state.setIn(["view", "pixelClickCoordinate"], pixelCoordinate);
}
static addLayer(state, action) {
if (typeof action.layer !== "undefined") {
let mergedLayer = this.getLayerModel().mergeDeep(action.layer);
if (
typeof mergedLayer.get("id") !== "undefined" &&
typeof state.getIn(["layers", mergedLayer.get("type")]) !== "undefined"
) {
state = state.setIn(
["layers", mergedLayer.get("type"), mergedLayer.get("id")],
mergedLayer
);
}
return this.setLayerActive(state, {
layer: mergedLayer.get("id"),
active: action.setActive
});
}
return state;
}
static removeLayer(state, action) {
if (state.hasIn(["layers", action.layer.get("type"), action.layer.get("id")])) {
state = this.setLayerActive(state, {
layer: action.layer.get("id"),
active: false
});
return state.deleteIn(["layers", action.layer.get("type"), action.layer.get("id")]);
}
return state;
}
static setInsituVectorLayerColor(state, action) {
// resolve layer from id if necessary
let actionLayer = action.layer;
if (typeof actionLayer === "string") {
actionLayer = this.findLayerById(state, actionLayer);
}
if (typeof actionLayer !== "undefined") {
let anySucceed = state.get("maps").reduce((acc, map) => {
if (map.setVectorLayerColor(actionLayer, action.color)) {
return true;
}
return acc;
}, false);
if (anySucceed) {
state = state.setIn(
["layers", actionLayer.get("type"), actionLayer.get("id"), "vectorColor"],
action.color
);
}
}
return state;
}
static zoomToLayer(state, action) {
// resolve layer from id if necessary
let actionLayer = action.layer;
if (typeof actionLayer === "string") {
actionLayer = this.findLayerById(state, actionLayer);
}
if (typeof actionLayer !== "undefined") {
let anySucceed = state.get("maps").reduce((acc, map) => {
if (map.zoomToLayer(actionLayer, action.pad)) {
return true;
}
return acc;
}, false);
}
return state;
}
static enableAreaSelection(state, action) {
action.delayClickEnable = false;
state = this.disableMeasuring(state, action);
state = this.disableDrawing(state, action);
state = this.disableAreaSelection(state, action);
// For each map, enable drawing
let anySucceed = state.get("maps").reduce((acc, map) => {
if (map.isActive) {
if (map.enableAreaSelection(action.geometryType)) {
return true;
}
}
return acc;
}, false);
if (anySucceed) {
return state
.setIn(["areaSelection", "isAreaSelectionEnabled"], true)
.setIn(["areaSelection", "geometryType"], action.geometryType);
}
return state;
}
static enableMeasuring(state, action) {
state = this.disableAreaSelection(state, { delayClickEnable: false });
return MapReducerCore.enableMeasuring(state, action);
}
static disableAreaSelection(state, action) {
// For each map, disable drawing
let anySucceed = state.get("maps").reduce((acc, map) => {
if (map.disableAreaSelection(action.delayClickEnable)) {
return true;
}
return acc;
}, false);
if (anySucceed) {
return state
.setIn(["areaSelection", "isAreaSelectionEnabled"], false)
.setIn(["areaSelection", "geometryType"], "");
}
return state;
}
static removeAllAreaSelections(state, action) {
state = this.disableAreaSelection(state, action);
state = this.disableDrawing(state, action);
state = this.disableMeasuring(state, action);
let alerts = state.get("alerts");
state.get("maps").forEach(map => {
if (!map.removeAllAreaSelections()) {
let contextStr = map.is3D ? "3D" : "2D";
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.GEOMETRY_REMOVAL_FAILED.title,
body: appStrings.ALERTS.GEOMETRY_REMOVAL_FAILED.formatString.replace(
"{MAP}",
contextStr
),
severity: appStrings.ALERTS.GEOMETRY_REMOVAL_FAILED.severity,
time: new Date()
})
);
}
});
return state.set("alerts", alerts);
}
static addGeometryToMap(state, action) {
if (
action.interactionType === appStrings.INTERACTION_AREA_SELECTION ||
action.interactionType === appStrings.INTERACTION_AREA_DISPLAY
) {
let alerts = state.get("alerts");
// Add geometry to each inactive map
state.get("maps").forEach(map => {
// Only add geometry to inactive maps unless it's an area selection
if (!map.addGeometry(action.geometry, action.interactionType, action.geodesic)) {
let contextStr = map.is3D ? "3D" : "2D";
alerts = alerts.push(
alertCore.merge({
title: appStringsCore.ALERTS.GEOMETRY_SYNC_FAILED.title,
body: appStringsCore.ALERTS.GEOMETRY_SYNC_FAILED.formatString.replace(
"{MAP}",
contextStr
),
severity: appStringsCore.ALERTS.GEOMETRY_SYNC_FAILED.severity,
time: new Date()
})
);
}
});
return state.set("alerts", alerts);
} else {
return MapReducerCore.addGeometryToMap(state, action);
}
}
static removeGeometry(state, action) {
if (
action.interactionType === appStrings.INTERACTION_AREA_SELECTION ||
action.interactionType === appStrings.INTERACTION_AREA_DISPLAY
) {
let alerts = state.get("alerts");
// Add geometry to each inactive map
state.get("maps").forEach(map => {
// Only add geometry to inactive maps unless it's an area selection
if (!map.removeGeometry(action.geometry, action.interactionType)) {
let contextStr = map.is3D ? "3D" : "2D";
alerts = alerts.push(
alertCore.merge({
title: appStringsCore.ALERTS.GEOMETRY_SYNC_FAILED.title,
body: appStringsCore.ALERTS.GEOMETRY_SYNC_FAILED.formatString.replace(
"{MAP}",
contextStr
),
severity: appStringsCore.ALERTS.GEOMETRY_SYNC_FAILED.severity,
time: new Date()
})
);
}
});
return state.set("alerts", alerts);
} else {
return state;
}
}
static setAnimationOpen(state, action) {
// state = this.setAnimationStartDate(state, { date: moment.utc(state.get("date")).subtract(1, 'week').toDate() });
// state = this.setAnimationEndDate(state, { date: moment.utc(state.get("date")).add(1, 'week').toDate() });
if (action.isOpen && action.updateRange) {
state = this.setAnimationStartDate(state, {
date: moment
.utc(state.get("date"))
.subtract(2, "week")
.toDate()
});
state = this.setAnimationEndDate(state, {
date: moment.utc(state.get("date"))
});
}
return state.setIn(["animation", "isOpen"], action.isOpen);
}
static setAnimationCollapsed(state, action) {
return state.setIn(["animation", "isCollapsed"], action.isCollapsed);
}
static setAnimationPlaying(state, action) {
return state.setIn(["animation", "isPlaying"], action.isPlaying);
}
static fillAnimationBuffer(state, action) {
let alerts = state.get("alerts");
// get an array of layers that will animate (active and time dependant)
let animateTypes = [
appStringsCore.LAYER_GIBS_RASTER,
appStringsCore.LAYER_WMTS_RASTER,
appStringsCore.LAYER_XYZ_RASTER,
appStrings.LAYER_MULTI_FILE_VECTOR_KML
];
let timeLayers = state
.getIn(["layers", appStringsCore.LAYER_GROUP_TYPE_DATA])
.filter(layer => {
return layer.get("isActive") && layer.getIn(["updateParameters", "time"]);
});
// filter layers we can/cannot animate
let layersToBuffer = timeLayers.filter(layer => {
return animateTypes.indexOf(layer.get("handleAs")) !== -1;
});
let layersToRemove = timeLayers.filter(layer => {
return animateTypes.indexOf(layer.get("handleAs")) === -1;
});
// validate step size
let stepSize = action.stepResolution.split("/");
let stepDate = moment.utc(action.startDate).add(stepSize[0], stepSize[1]);
let framesAvailable = !stepDate.isAfter(moment.utc(action.endDate));
if (framesAvailable) {
// if (layersToBuffer.size > 0) {
// remove layers we cannot animate
layersToRemove.forEach(layer => {
MapReducerCore.setLayerActive(state, { layer, active: false });
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.NON_ANIMATION_LAYER.title,
body: appStrings.ALERTS.NON_ANIMATION_LAYER.formatString.replace(
"{LAYER}",
layer.get("title")
),
severity: appStrings.ALERTS.NON_ANIMATION_LAYER.severity,
time: new Date()
})
);
});
// send the layers off to buffer
let anySucceed = state.get("maps").reduce((acc, map) => {
// only animate on the active map
if (map.isActive) {
if (
map.fillAnimationBuffer(
layersToBuffer,
action.startDate,
action.endDate,
action.stepResolution,
action.callback
)
) {
return true;
} else {
// catch errors
let contextStr = map.is3D ? "3D" : "2D";
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.FILL_BUFFER_FAILED.title,
body: appStrings.ALERTS.FILL_BUFFER_FAILED.formatString.replace(
"{MAP}",
contextStr
),
severity: appStrings.ALERTS.FILL_BUFFER_FAILED.severity,
time: new Date()
})
);
}
}
return acc;
}, false);
if (anySucceed) {
// signal that buffering has begun
state = state.setIn(["animation", "initiated"], true);
// begin checking the initial buffer
state = this.checkInitialAnimationBuffer(state, {});
}
// }
// else {
// state = this.stopAnimation(state, {});
// alerts = alerts.push(
// alertCore.merge({
// title: appStrings.ALERTS.NO_ANIMATION_LAYERS.title,
// body: appStrings.ALERTS.NO_ANIMATION_LAYERS.formatString,
// severity: appStrings.ALERTS.NO_ANIMATION_LAYERS.severity,
// time: new Date()
// })
// );
// }
} else {
state = this.stopAnimation(state, {});
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.NO_STEP_FRAMES.title,
body: appStrings.ALERTS.NO_STEP_FRAMES.formatString,
severity: appStrings.ALERTS.NO_STEP_FRAMES.severity,
time: new Date()
})
);
}
return state.set("alerts", alerts);
}
static emptyAnimationBuffer(state, action) {
let alerts = state.get("alerts");
let anySucceed = state.get("maps").reduce((acc, map) => {
// clear all maps' buffers (just in case)
if (map.clearAnimationBuffer()) {
return true;
} else {
// catch errors
let contextStr = map.is3D ? "3D" : "2D";
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.CLEAR_BUFFER_FAILED.title,
body: appStrings.ALERTS.CLEAR_BUFFER_FAILED.formatString.replace(
"{MAP}",
contextStr
),
severity: appStrings.ALERTS.CLEAR_BUFFER_FAILED.severity,
time: new Date()
})
);
}
return acc;
}, false);
return state.set("alerts", alerts);
}
static stopAnimation(state, action) {
// empty the animation buffer
state = this.emptyAnimationBuffer(state, {});
// upate state variables
state = state
.setIn(["animation", "isPlaying"], false)
.setIn(["animation", "initiated"], false)
.setIn(["animation", "bufferLoaded"], false)
.setIn(["animation", "initialBufferLoaded"], false)
.setIn(["animation", "nextFrameLoaded"], false)
.setIn(["animation", "previousFrameLoaded"], false)
.setIn(["animation", "bufferFramesTotal"], 0)
.setIn(["animation", "bufferFramesLoaded"], 0)
.setIn(["animation", "bufferTilesTotal"], 0)
.setIn(["animation", "bufferTilesLoaded"], 0);
// don't need to reactivate layers if we are opening the panel for the first time
if (state.getIn(["animation", "isOpen"])) {
// get an array of layers that must be reactivated (were active, time dependant, and non-raster)
let animateTypes = [
appStringsCore.LAYER_GIBS_RASTER,
appStringsCore.LAYER_WMTS_RASTER,
appStringsCore.LAYER_XYZ_RASTER
];
let layersToReactivate = state
.getIn(["layers", appStringsCore.LAYER_GROUP_TYPE_DATA])
.filter(layer => {
return (
layer.get("isActive") &&
layer.getIn(["updateParameters", "time"]) &&
animateTypes.indexOf(layer.get("handleAs")) === -1
);
});
// reactivate the layers and adjust opacity
layersToReactivate.forEach(layer => {
state = MapReducerCore.setLayerActive(state, {
layer: layer.set("isActive", false),
active: true
});
state = MapReducerCore.setLayerOpacity(state, {
layer,
opacity: layer.get("opacity")
});
});
}
return state;
}
static stepAnimation(state, action) {
let nextFrame = false;
// check frames
state = this.checkNextAnimationFrame(state, {});
state = this.checkPreviousAnimationFrame(state, {});
if (action.forward) {
// verify frame is loaded
if (state.getIn(["animation", "nextFrameLoaded"])) {
nextFrame = state.get("maps").reduce((acc, map) => {
let frame = map.nextAnimationFrame();
if (frame) {
return frame;
}
return acc;
}, false);
} else {
state = this.checkAnimationBuffer(state, {});
}
} else {
// verify frame is loaded
if (state.getIn(["animation", "previousFrameLoaded"])) {
nextFrame = state.get("maps").reduce((acc, map) => {
let frame = map.previousAnimationFrame();
if (frame) {
return frame;
}
return acc;
}, false);
} else {
state = this.checkAnimationBuffer(state, {});
}
}
// update the current frame reference
if (nextFrame) {
let nextDate = nextFrame.get("date");
state = this.setMapDate(state, { date: nextDate });
}
return state;
}
static checkAnimationBuffer(state, action) {
state = this.checkNextAnimationFrame(state, {});
state = this.checkPreviousAnimationFrame(state, {});
let bufferStatus = state.get("maps").reduce((acc, map) => {
// check only active map
if (map.isActive) {
return map.getBufferStatus();
}
return acc;
}, false);
if (bufferStatus) {
return state
.setIn(["animation", "bufferLoaded"], bufferStatus.isLoaded)
.setIn(["animation", "bufferFramesTotal"], bufferStatus.framesTotal)
.setIn(["animation", "bufferFramesLoaded"], bufferStatus.framesLoaded)
.setIn(["animation", "bufferTilesTotal"], bufferStatus.tilesTotal)
.setIn(["animation", "bufferTilesLoaded"], bufferStatus.tilesLoaded);
}
return state;
}
static checkInitialAnimationBuffer(state, action) {
// verify the buffer has been filled at least once
if (!state.getIn(["animation", "initialBufferLoaded"])) {
state = this.checkAnimationBuffer(state, {});
state = state.setIn(
["animation", "initialBufferLoaded"],
state.getIn(["animation", "bufferLoaded"])
);
state = this.setAnimationPlaying(state, {
isPlaying: state.getIn(["animation", "bufferLoaded"])
});
}
return state;
}
static checkNextAnimationFrame(state, action) {
let nextFrameLoaded = state.get("maps").reduce((acc, map) => {
// check only active map
if (map.isActive) {
let status = map.getNextFrameStatus();
if (status.isLoaded) {
return acc;
}
return false;
}
return acc;
}, true);
return state.setIn(["animation", "nextFrameLoaded"], nextFrameLoaded);
}
static checkPreviousAnimationFrame(state, action) {
let previousFrameLoaded = state.get("maps").reduce((acc, map) => {
// check only active map
if (map.isActive) {
let status = map.getPreviousFrameStatus();
if (status.isLoaded) {
return acc;
}
return false;
}
return acc;
}, true);
return state.setIn(["animation", "previousFrameLoaded"], previousFrameLoaded);
}
static setAnimationStartDate(state, action) {
state = this.stopAnimation(state, {});
let alerts = state.get("alerts");
let date = action.date;
if (typeof date === "string") {
if (date.toLowerCase() === "today") {
date = moment.utc().startOf("day");
} else {
date = moment.utc(date, "YYYY-MM-DD", true);
}
} else {
date = moment.utc(date);
}
if (date.isValid()) {
let minDate = moment.utc(appConfig.MIN_DATE);
let maxDate = moment.utc(state.getIn(["animation", "endDate"]));
if (date.isBefore(minDate)) {
date = minDate;
} else if (date.isAfter(maxDate)) {
date = maxDate;
}
state = state.setIn(["animation", "startDate"], date.toDate());
} else {
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.ANIMATION_BAD_DATE.title,
body: appStrings.ALERTS.ANIMATION_BAD_DATE.formatString.replace(
"{STARTEND}",
"start"
),
severity: appStrings.ALERTS.ANIMATION_BAD_DATE.severity,
time: new Date()
})
);
}
return state.set("alerts", alerts);
}
static setAnimationEndDate(state, action) {
state = this.stopAnimation(state, {});
let alerts = state.get("alerts");
let date = action.date;
if (typeof date === "string") {
if (date.toLowerCase() === "today") {
date = moment.utc().startOf("day");
} else {
date = moment.utc(date, "YYYY-MM-DD", true);
}
} else {
date = moment.utc(date);
}
if (date.isValid()) {
let minDate = moment.utc(state.getIn(["animation", "startDate"]));
let maxDate = moment.utc(appConfig.MAX_DATE);
if (date.isBefore(minDate)) {
date = minDate;
} else if (date.isAfter(maxDate)) {
date = maxDate;
}
state = state.setIn(["animation", "endDate"], date.toDate());
} else {
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.ANIMATION_BAD_DATE.title,
body: appStrings.ALERTS.ANIMATION_BAD_DATE.formatString.replace(
"{STARTEND}",
"end"
),
severity: appStrings.ALERTS.ANIMATION_BAD_DATE.severity,
time: new Date()
})
);
}
return state.set("alerts", alerts);
}
static setAnimationDateRange(state, action) {
let alerts = state.get("alerts");
if (state.getIn(["animation", "initiated"]) && state.getIn(["animation", "isPlaying"])) {
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.ANIMATION_NO_LAYER_TOGGLE.title,
body: appStrings.ALERTS.ANIMATION_NO_LAYER_TOGGLE.formatString,
severity: appStrings.ALERTS.ANIMATION_NO_LAYER_TOGGLE.severity,
time: new Date()
})
);
}
state = this.stopAnimation(state, {});
let startDate = action.startDate;
if (typeof startDate === "string") {
if (startDate.toLowerCase() === "today") {
startDate = moment.utc().startOf("day");
} else {
startDate = moment.utc(startDate, "YYYY-MM-DD", true);
}
} else {
startDate = moment.utc(startDate);
}
let endDate = action.endDate;
if (typeof endDate === "string") {
if (endDate.toLowerCase() === "today") {
endDate = moment.utc().startOf("day");
} else {
endDate = moment.utc(endDate, "YYYY-MM-DD", true);
}
} else {
endDate = moment.utc(endDate);
}
if (startDate.isValid() && endDate.isValid() && startDate.isSameOrBefore(endDate)) {
let minDate = moment.utc(appConfig.MIN_DATE);
let maxDate = moment.utc(appConfig.MAX_DATE);
if (startDate.isBefore(minDate)) {
startDate = minDate;
} else if (startDate.isAfter(maxDate)) {
startDate = maxDate;
}
if (endDate.isBefore(minDate)) {
endDate = minDate;
} else if (endDate.isAfter(maxDate)) {
endDate = maxDate;
}
state = state
.setIn(["animation", "startDate"], startDate.toDate())
.setIn(["animation", "endDate"], endDate.toDate());
} else {
alerts = alerts.push(
alertCore.merge({
title: appStrings.ALERTS.ANIMATION_BAD_DATE.title,
body: appStrings.ALERTS.ANIMATION_BAD_DATE.formatString.replace(
"{STARTEND}",
"start or end"
),
severity: appStrings.ALERTS.ANIMATION_BAD_DATE.severity,
time: new Date()
})
);
}
return state.set("alerts", alerts);
}
static setAnimationSpeed(state, action) {
return state.setIn(["animation", "speed"], action.speed);
}
} |
JavaScript | class CustomValueAccessor {
/**
* @param {?} _host
*/
constructor(_host) {
this._host = _host;
this.onChange = () => { };
this.onTouched = () => { };
}
/**
* @param {?} value
* @return {?}
*/
writeValue(value) {
this._host.writeValue(value);
}
/**
* @param {?} fn
* @return {?}
*/
registerOnChange(fn) {
this.onChange = fn;
}
/**
* @param {?} fn
* @return {?}
*/
registerOnTouched(fn) {
this.onTouched = fn;
}
} |
JavaScript | class Board {
/**
* Board constructor.
* @param {Board} board - Optional paremeter used to clone and set the properties of this
* board to that of given board; defaults to null.
* @param {number} y - Y position value.
*/
constructor(board=null) {
// If default constructor, initialize board properties
if (board == null)
this.reset();
else {
// Copy pieces into new list
this.pieces = [];
for (var i = 0; i < board.pieces.length; i++)
this.pieces.push(board.pieces[i].clone());
// Copy
this.goatsMove = board.goatsMove;
this.goatsInHand = board.goatsInHand;
this.tigersTrapped = board.tigersTrapped;
this.goatsCaptured = board.goatsCaptured;
this.historyMoves = Array.from(board.historyMoves);
}
}
/** Method to reset the board to it's default start state. */
reset() {
// Place tigers at default positions
this.pieces = [];
this.pieces.push(new Tiger(0, 0));
this.pieces.push(new Tiger(0, 4));
this.pieces.push(new Tiger(4, 0));
this.pieces.push(new Tiger(4, 4));
// Reset
this.goatsMove = true;
this.goatsInHand = PLACEABLE_GOATS;
this.tigersTrapped = this.goatsCaptured = 0;
this.historyMoves = [];
}
/** Method to switch to the next player. If was goats turn changes to tiger, else goat if tiger. */
switchToNextPlayer() {
this.goatsMove = !this.goatsMove;
}
/**
* Method to check if a given x and y position is within game bounds.
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns true if given x and y posiiton is within game bounds, or false otherwise.
*/
withinBounds(x, y) {
// If to x and y are outside bounds, return false
return !(x < 0 || x > 4 || y < 0 || y > 4);
}
/**
* Method to a piece at a given x and y position.
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns the piece at the given x and y position if it exists, or null otherwise.
*/
getPieceAt(x, y) {
for (var piece of this.pieces)
if (piece.isPositionAt(x, y))
return piece;
return null;
}
/**
* Method to check if a piece exists at a given x and y position
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns true if a piece exists at given x and y position, or false otherwise.
*/
isPieceAt(x, y) {
return this.getPieceAt(x, y) != null ? true : false;
}
/**
* Method to check if a goat exists at a given x and y position
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns true if a goat exists at given x and y position, or false otherwise.
*/
isGoatAt(x, y) {
var piece = this.getPieceAt(x, y);
return (piece != null && piece.isGoat) ? true : false;
}
/**
* Method to check if a tiger exists at a given x and y position
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns true if a tiger exists at given x and y position, or false otherwise.
*/
isTigerAt(x, y) {
var piece = this.getPieceAt(x, y);
return (piece != null && piece.isTiger) ? true : false;
}
/**
* Method to remove piece at gieven x and y position.
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns piece removed, or null if piece at given x and y doesnt exist.
*/
removePieceAt(x, y) {
for (var i = 0; i < this.pieces.length; i++)
if (this.pieces[i].isPositionAt(x, y))
// Remove and return piece at i from array
return this.pieces.splice(i, 1)[0];
return null;
}
/**
* Method to place goat at given x and y position.
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns true if goats to place is greater than 0, position was empty and goat
* was placed, or false otherwise.
*/
placeGoatAt(x, y) {
// If has goats to place, within bounds and piece doesnt exist at given x and y, place new goat
if (this.goatsInHand > 0 && this.withinBounds(x, y) && !this.isPieceAt(x, y)) {
this.pieces.push(new Goat(x, y));
this.goatsInHand--;
return true;
}
return false;
}
/**
* Method to capture a goat at given x and y positon.
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns false if given x and y doesn't have a goat, or true if goat was removed.
*/
captureGoatAt(x, y) {
if (this.isGoatAt(x, y)) {
this.removePieceAt(x, y);
this.goatsCaptured++;
return true;
}
return false;
}
/**
* Method to move a piece to a given x and y position.
* @param {Vector} from - Vector x and y from position value.
* @param {number} x - X to position value.
* @param {number} y - Y to position value.
* @param {boolean} simulated - Optional parameter simulated can be assigned to state if move
* has already been simulated or not; defaults to false.
* @return {boolean} Returns true if piece was moved, or false otherwise.
*/
move(from, x, y, simulated=false) {
var piece = this.getPieceAt(from.x, from.y);
// If piece is null, return false
if (piece == null)
return false;
if (piece.move(this, x, y, simulated)) {
// If all goats have been placed, push move properties to queue (from, to)
if (this.goatsInHand == 0)
this.historyMoves.push([from, piece.position]);
return true;
}
return false;
}
/**
* Method to get and return the number of tigers trapped.
* @return {number} Number of tigers trapped on the board.
*/
numOfTigersTrapped() {
var count = 0;
// Loop all tigers on board and count number of trapped tigers
for (var piece of this.pieces)
if (piece.isTiger)
if (piece.isTrapped(this))
count++;
return count;
}
/**
* Method to get the number of possible captures that can be made by all the tigers on the board.
* @return {number} Number of possible captures that can be made.
*/
numOfPossibleCaptures() {
var count = 0;
for (var piece of this.pieces)
if (piece.isTiger)
count += piece.numOfPossibleCaptures(this);
return count;
}
/**
* Method to get the number of tigers occupying a corner on the board.
* @return {number} Number of tigers occupying a corner on the board.
*/
numOfTigersInCorners() {
var count = 0;
for (var piece of this.pieces)
if (piece.isTiger)
// If in a corner, increase count
if ((piece.position.x == 0 && piece.position.y == 0) ||
(piece.position.x == 0 && piece.position.y == 4) ||
(piece.position.x == 4 && piece.position.y == 4) ||
(piece.position.x == 4 && piece.position.y == 0))
count++;
return count;
}
/**
* Method to get the number of outside goats on the board. Goat is outside if along outside edge of board.
* @return {number} Number of outside goats on the board.
*/
numOfOutsideGoats() {
var count = 0;
for (var x = 0; x < 5; x++)
for (var y = 0; y < 5; y++)
// If on outside of board, and piece doesnt exist, increase count
if (x < 1 || x > 3 || y < 1 || y > 3)
if (this.isGoatAt(x, y))
count++;
return count;
}
/**
* Method to get and return selected piece.
* @return {Piece} Returns selected piece, or null if piece is not currently selected.
*/
getSelectedPiece() {
var piece = this.pieces[this.pieces.length - 1];
return piece.isMoving ? piece : null;
}
/**
* Method to return state of if piece is currently selected.
* @return {boolean} Returns true if selected, or false otherwise.
*/
isPieceSelected() {
return this.getSelectedPiece() != null;
}
/**
* Method to select a piece at a given x and y to be moved.
* @param {number} x - X position value.
* @param {number} y - Y position value.
* @return {boolean} Returns true if piece was selected, or false otherwise.
*/
selectPieceAt(x, y) {
if (this.withinBounds(x, y))
// If piece exists at given x and y
for (var i = 0; i < this.pieces.length; i++)
if (this.pieces[i].isPositionAt(x, y)) {
// If goat move and player is moving goat, or if tiger move and moving tiger, select piece and return true
if ((this.goatsMove && this.pieces[i].isGoat) ||
(!this.goatsMove && this.pieces[i].isTiger)) {
this.pieces[i].isMoving = true;
this.pieces.splice(this.pieces.length - 1, 0, this.pieces.splice(i, 1)[0]);
return true;
}
}
return false;
}
/** Method used to unselect the currently selected piece. */
unselectPiece() {
this.pieces[this.pieces.length - 1].isMoving = false;
}
/**
* Method to simulate and return boards array of all possible goat placements. Each board contains all the
* possible placements a goat can make.
* @return {Board[]} Boards array of all possible goat placements.
*/
simulatePlacements() {
var boards = [];
// Push all empty tiles on board to list
for (var x = 0; x < 5; x++)
for (var y = 0; y < 5; y++)
if (!this.isPieceAt(x, y)) {
var tempBoard = this.clone();
tempBoard.placeGoatAt(x, y);
boards.push(tempBoard);
}
return boards;
}
/**
* Method to simulate and return boards array of all possible goat moves. Each board either contains a
* potential placement if goats to place in hand or a potential move a goat can make.
* @return {Board[]} Boards array of all possible goat placements/moves.
*/
simulateGoatBoards() {
var boards = [];
// If board has goats to place, simulate goat placements
if (this.goatsInHand > 0)
boards = boards.concat(this.simulatePlacements())
// Else, simulate goat moves
else
for (var piece of this.pieces)
if (piece.isGoat)
boards = boards.concat(piece.simulateBoards(this));
return boards;
}
/**
* Method to simulate and return boards array of all possible tiger moves. Each board contains a
* potential move a tiger can take.
* @return {Board[]} Boards array of all possible tiger moves.
*/
simulateTigerBoards() {
var boards = [];
for (var piece of this.pieces)
if (piece.isTiger)
boards = boards.concat(piece.simulateBoards(this));
return boards;
}
/**
* Method to return game goat win state. Goat wins if all tigers are trapped.
* @return {boolean} Returns true if goat win, or false otherwise.
*/
isGoatWin() {
return (this.tigersTrapped = this.numOfTigersTrapped()) >= 4;
}
/**
* Method to return game tiger win state. Tiger wins if atleast 5 goats have been captured.
* @return {boolean} Returns true if tiger win, or false otherwise.
*/
isTigerWin() {
return this.goatsCaptured >= 5;
}
/**
* Method to return position string of a given history move.
* @param {Vector[,]} move - Vector array of from and to move positions.
* @param {boolean} invert - Optional parameter invert can be used to return inverted result,
* eg in previous '1211' (default=false).
* @return {string} Returns history string of given move. For example, '1112' if piece was
* previously at position '11' (xy) and moved to position '12'.
*/
getHistoryStringOf(move, invert=false) {
var from = move[0].x.toString() + move[0].y.toString();
var to = move[1].x.toString() + move[1].y.toString();
return invert ? to + from : from + to;
}
/**
* Method to return game draw state.
* @return {boolean} Returns true if game is a draw, or false otherwise.
*/
isDraw() {
// Prevent array getting longer than required
if (this.historyMoves.length > 5)
this.historyMoves.shift();
// If all goats have been placed and enough moves have been played, check for draw
if (this.goatsInHand == 0 && this.historyMoves.length > 4) {
var length = this.historyMoves.length;
// If pieces are moving back and forth, return draw (true)
var move1 = this.getHistoryStringOf(this.historyMoves[length - 1]);
var move2 = this.getHistoryStringOf(this.historyMoves[length - 2]);
var move3Invert = this.getHistoryStringOf(this.historyMoves[length - 3], true);
var move4Invert = this.getHistoryStringOf(this.historyMoves[length - 4], true);
if ((move1 == move3Invert) && (move2 == move4Invert))
return true;
// If pieces are circling, return draw
var move4 = this.getHistoryStringOf(this.historyMoves[length - 4]);
var move5 = this.getHistoryStringOf(this.historyMoves[length - 5]);
if ((move1 == move4) && (move2 == move5))
return true;
}
return false;
}
/**
* Method to get and return current game state.
* @return {GameState} Returns game state, of in-game (-1), tiger win (0), goat win (1) or draw (2).
*/
getGameState() {
if (this.isTigerWin())
return GameState.TIGER_WIN;
else if (this.isGoatWin())
return GameState.GOAT_WIN;
else if (this.isDraw())
return GameState.DRAW;
else
return GameState.IN_GAME;
}
/** Draw. */
draw() {
// Draw board
image(textures[0], canvasSize / 2, canvasSize / 2, canvasSize, canvasSize);
// Draw pieces
for (var piece of this.pieces)
piece.draw();
}
/**
* Method to clone this board object.
* @return {Goat} Returns new cloned board object.
*/
clone() {
return new Board(this);
}
} |
JavaScript | class EventListeners {
constructor() {
debug('[event-listeners] initializing');
this.tmpInitializedPromiseResolvers = [];
this.tmpInitialized = this.tmpInitialized.bind(this);
this.defaultTimeout = 30; // seconds
this._listeners = [];
[
{
api: ['webRequest', 'onBeforeRequest'],
options: [
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']
],
target: ['request', 'webRequestOnBeforeRequest'],
timeout: 5,
},
{
api: ['webRequest', 'onCompleted'],
options: [{urls: ['<all_urls>'], types: ['main_frame']}],
target: ['request', 'cleanupCanceled']
},
{
api: ['webRequest', 'onErrorOccurred'],
options: [{urls: ['<all_urls>'], types: ['main_frame']}],
target: ['request', 'cleanupCanceled']
},
{
api: ['webRequest', 'onCompleted'],
options: [
{urls: ['<all_urls>'],
types: ['script', 'font', 'image', 'imageset', 'stylesheet']
},
['responseHeaders']
],
target: ['statistics', 'collect']
},
{
api: ['browserAction', 'onClicked'],
target: ['browseraction', 'onClicked']
},
{
api: ['contextMenus', 'onClicked'],
target: ['contextmenu', 'onClicked']
},
{
api: ['contextMenus', 'onShown'],
target: ['contextmenu', 'onShown']
},
{
api: ['windows', 'onFocusChanged'],
target: ['contextmenu', 'windowsOnFocusChanged']
},
{
api: ['webRequest', 'onBeforeSendHeaders'],
options: [
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking', 'requestHeaders']
],
target: ['cookies', 'maybeSetAndAddToHeader'],
},
{
api: ['management', 'onDisabled'],
target: ['management', 'disable']
},
{
api: ['management', 'onUninstalled'],
target: ['management', 'disable']
},
{
api: ['management', 'onEnabled'],
target: ['management', 'enable']
},
{
api: ['management', 'onInstalled'],
target: ['management', 'enable']
},
['commands', 'onCommand'],
['runtime', 'onMessage'],
['runtime', 'onMessageExternal'],
['runtime', 'onStartup'],
['runtime', 'onUpdateAvailable']
]
.map(conf => {
const confIsObj = typeof conf === 'object';
const api = confIsObj && conf.api || conf;
const target = confIsObj && conf.target || api;
const timeout = confIsObj && conf.timeout || this.defaultTimeout;
const listener = this.wrap(api.join('.'), function() {
return window.tmp[target[0]][target[1]].call(
window.tmp[target[0]], ...arguments
);
}, {timeout});
browser[api[0]][api[1]].addListener(listener,
...confIsObj && conf.options || []
);
this._listeners.push({listener, api});
});
}
wrap(apiName, listener, options) {
const tmpInitializedPromise = this.createTmpInitializedPromise(options);
return async function() {
if (!window.tmp || !window.tmp.initialized) {
try {
await tmpInitializedPromise;
} catch (error) {
debug(`[event-listeners] call to ${apiName} timed out after ${options.timeout}s`);
throw error;
}
}
return listener(...arguments);
};
}
createTmpInitializedPromise(options) {
const abortController = new AbortController;
const timeout = window.setTimeout(() => {
abortController.abort();
}, options.timeout * 1000);
return new Promise((resolve, reject) => {
this.tmpInitializedPromiseResolvers.push({resolve, timeout});
abortController.signal.addEventListener('abort', () => {
reject('Timed out while waiting for Add-on to initialize');
});
});
}
tmpInitialized() {
this.tmpInitializedPromiseResolvers.map(resolver => {
clearTimeout(resolver.timeout);
resolver.resolve();
});
}
remove() {
this._listeners.map(listener => {
browser[listener.api[0]][listener.api[1]].removeListener(listener.listener);
});
}
} |
JavaScript | class Gallery {
/**
* Initialize a gallery block
*
* @param {JQuery} $root The block's root
*/
constructor($root) {
$root.magnificPopup({
delegate: SELECTORS.THUMB_LINK,
mainClass: CLASSES.LIGHTBOX,
type: 'image',
gallery: {
enabled: true,
tCounter: '',
},
closeMarkup: `
<button aria-label="Close" type="button" class="mfp-close">
×
</button>
`,
arrowMarkup: `
<button
aria-label="%title%"
type="button"
class="mfp-arrow mfp-arrow-%dir%"
>
</button>
`,
callbacks: {
beforeOpen() {
// Add role and label attributes for accessibility purposes
this.wrap.attr({
'role': 'dialog',
'aria-label': 'Gallery',
});
},
},
});
}
} |
JavaScript | class ChunkHandler {
/**
* Constructor
*/
constructor () {
this.body = {};
}
/**
* Determine value is string
* @param {*} value
* @return {bool}
*/
isString (value) {
return typeof value === 'string' || value instanceof String;
}
/**
* Determine value is array
* @param {*} value
* @return {bool}
*/
isArray (value) {
if (value === undefined || value === '') {
return false;
}
return value && typeof value === 'object' && value.constructor === Array;
}
/**
* Determine value is object
* @param {*} value
* @return {bool}
*/
isObject (value) {
if (value === undefined || value === '') {
return false;
}
return value && typeof value === 'object' && value.constructor === Object;
}
/**
* Determine value is empty
* @param {const} value
* @return {bool}
*/
isEmpty (value) {
return (value === undefined || value === null || value === '');
}
/**
* Determine value is empty and array
* @param {*} value
* @return {bool}
*/
isEmptyArray (value) {
return (value === undefined || value === null || value.length === 0);
}
/**
* Determine object value is empty
* @param {*} value
* @return {bool}
*/
isEmptyObject (value) {
return ((value === undefined || value === null) || (Object.keys(value).length === 0 && value.constructor === Object));
}
/**
* Blocking test for asynchronous
* @param {integer} ms this is miliseconds value for event block
* @return {int}
*/
blockingTest (ms = 1000) {
const start = Date.now();
const time = start + ms;
while (Date.now() < time) {
// empty progress
}
return start;
}
/**
* Get best size to chunk
* @param {int|string} length this is the maximum array/string length number
* @param {int|string} split [optional] split value will create maximum (value*10) means if split is 5 then will make array length not more than 50
* @return {int}
*/
getBestSize (length, split = 5) {
length = parseInt(length);
split = parseInt(split);
if (split < 1 || split > 10) {
throw new Error('Split value must be between 1-10');
}
if (length <= 100000 && split > 1) {
split = 1;
}
if (length > 100000 && length <= 1000000 && split === 1) {
split = 5;
}
const max = (split * 10);
const start = (max - (Math.ceil(max / 10)));
const slice = (max - start);
switch (true) {
case (length <= 5000000 && length > 4000000):
return Math.ceil(length / (max - (slice * 1)));
case (length <= 4000000 && length > 3500000):
return Math.ceil(length / (max - (slice * 2)));
case (length <= 3500000 && length > 3000000):
return Math.ceil(length / (max - (slice * 3)));
case (length <= 3000000 && length > 2500000):
return Math.ceil(length / (max - (slice * 4)));
case (length <= 2500000 && length > 2000000):
return Math.ceil(length / (max - (slice * 5)));
case (length <= 2000000 && length > 1500000):
return Math.ceil(length / (max - (slice * 6)));
case (length <= 1500000 && length > 1000000):
return Math.ceil(length / (max - (slice * 7)));
case (length <= 1000000 && length > 500000):
return Math.ceil(length / (max - (slice * 8)));
case (length <= 500000 && length > 100000):
return Math.ceil(length / (max - (slice * 9)));
case (length <= 100000 && length > 50000):
return Math.ceil(length / 3);
case (length <= 50000 && length > 10000):
return Math.ceil(length / 2);
case (length <= 10000 && length > 1):
return Math.ceil(length / 1);
default:
return Math.ceil(length / max);
}
}
/**
* Get random number between min and max values
* @param {int} min min random value (included)
* @param {int} max max random value (included)
*/
getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Make value to be chunked
* @param {string|array} value this is value to be chunked
* @param {string|int} size [optional] if value is type string then size will make split from letters per size number
* @return {array}
*/
make (value, size = 100) {
size = parseInt(size);
if (!this.isString(value) && !this.isArray(value)) throw new Error('Value must be string or array');
if (this.isString(value)) {
let i = 0; let o = 0; const numChunks = Math.ceil(value.length / size); const chunks = new Array(numChunks);
for (i, o; i < numChunks; ++i, o += size) {
chunks[i] = value.substr(o, size);
}
return chunks;
} else {
const result = [];
// add each chunk to the result
let x = 0; const len = Math.ceil(value.length / size);
for (x; x < len; x++) {
const start = x * size;
const end = start + size;
result.push(value.slice(start, end));
}
return result;
}
}
/**
* Make aleatory chunks from value
* @param {array} value this is the array to be aleatory chunked
* @param {int} numberOfChunks the number of chunks that will be created
*/
makeAleatory (value, numberOfChunks) {
const array = value;
const result = new Array([]);
const chunkSize = parseInt(value.length / numberOfChunks, 10);
let chunkIndex = 0;
for (chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++) {
result[parseInt(chunkIndex, 10)] = [];
for (let itemIndex = 0; itemIndex < chunkSize; itemIndex++) {
// Gets a random index to be included in the chunk
const randomIndex = this.getRandomInt(0, array.length - 1);
// Inserts the item and remove it from array
result[parseInt(chunkIndex, 10)].push(array.splice(randomIndex, 1)[0]);
}
}
// Add the remaining items
if (array.length > 0) {
result[parseInt(chunkIndex - 1, 10)].push(...array);
}
return result;
}
/**
* Merge data chunked
* @param {object} data data is an array from this.get(name)
* @return {mixed} could be string or array
*/
merge (data) {
if (!this.isArray(data) && this.isEmptyArray(data)) return '';
let file = '';
let i = 0; const len = data.length;
if (!this.isEmpty(data[0].data)) {
if (!this.isEmpty(data[0].part)) {
data.sort(function (a, b) {
return parseFloat(a.part) - parseFloat(b.part);
});
}
if (this.isArray(data[0].data)) {
file = [];
}
for (i; i < len; i++) {
if (this.isArray(data[i].data)) {
file = file.concat(data[i].data);
} else {
file += data[i].data;
}
}
} else {
if (this.isArray(data[0])) {
file = [];
}
for (i; i < len; i++) {
if (this.isArray(data[i])) {
file = file.concat(data[i]);
} else {
file += data[i];
}
}
}
return file;
}
/**
* Add new or replace data chunk by it's name
* @param {string} name
* @param {object} data
* @param {int} part
* @return {this}
*/
add (name, data, part = '') {
if (this.isString(name)) {
name = name.replace(/[^A-Z0-9]/ig, '_');
if (data) {
if (!this.isEmpty(part)) {
part = parseInt(part);
if (this.isEmpty(this.body[name])) {
this.body[name] = [];
this.body[name].push({ part: part, data: data });
} else {
this.body[name].push({ part: part, data: data });
}
} else {
if (this.isEmpty(this.body[name])) {
this.body[name] = [];
this.body[name].push({ data: data });
} else {
this.body[name].push({ data: data });
}
}
}
}
return this;
}
/**
* Remove data chunk by name
* @param {string} name
* @return {this}
*/
remove (name) {
if (this.isString(name)) {
name = name.replace(/[^A-Z0-9]/ig, '_');
delete this.body[name];
}
return this;
}
/**
* Cleanup all data chunk
*/
clean () {
this.body = {};
return this;
}
/**
* Get data chunk by name
* @param {string} name
* @return {string}
*/
get (name) {
name = name.replace(/[^A-Z0-9]/ig, '_');
return this.body[name];
}
/**
* Get all data chunk
* @return {object}
*/
getBody () {
return this.body;
}
/**
* Make asynchronous process with Promise
* @param {*} fn
* @return {this}
*/
promisify (fn) {
const self = this;
return new Promise(function (resolve, reject) {
try {
resolve(fn.call(self, self));
} catch (err) {
reject(err);
}
});
}
} |
JavaScript | class AppForDev extends Component {
/**
* @param {object} props - The props used to construct. */
constructor(props) {
super(props);
this.state = {
mode: 0,
};
this.changeMode = this.changeMode.bind(this);
this.renderPages = this.renderPages.bind(this);
}
/**
* It changes the value of this.state.mode and used it to switch the page between PageA and PageB.
* this.state.mode === 0 -> PageA
* this.state.mode === 1 -> PageB
* this.state.mode === 2 -> PageC
* this.state.mode === 3 -> PageIO
* @param {number} mode - the page's mode we want to switch into */
changeMode(mode) {
this.setState({ mode });
}
/**
* render the current page of this.state.mode
* @return {JSX} - A syntax extension to JavaScript, which will be eventually compiled
* into html code. */
renderPages() {
if (this.state.mode === 0) {
return <PageA />;
} else if (this.state.mode === 1) {
return <PageB />;
} else if (this.state.mode === 2) {
return <PageC />;
} else {
return <PageIO />;
}
}
/**
* @return {JSX} - A syntax extension to JavaScript, which will be eventually compiled
* into html code. */
render() {
return (
<div>
<button onClick={() => { this.changeMode(0); }}>PageA</button>
<button onClick={() => { this.changeMode(1); }}>PageB</button>
<button onClick={() => { this.changeMode(2); }}>PageC</button>
<button onClick={() => { this.changeMode(3); }}>PageIO</button>
{this.renderPages()}
</div>
);
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
videos: [],
playlist: [],
currentVideo: {},
roomDetails: {},
socket: io.connect(RootApiUrl),
userList: [],
userDetails: {
username: AuthService.getUserDetails()
},
windowSize: {
width: 0,
height: 0
},
isMobile: false,
isSideMenuOpen: false,
isSearchOpen: false,
isUserListOpen: false
};
}
//Video searching function
videoSearch(term) {
var params = {
part: 'snippet',
key: API_KEY,
q: term,
type: 'video',
maxResults: MAX_RESULTS
};
//Searches for the videos with the Youtube API
axios.get(ROOT_URL, {params: params})
.then((response) => {
var videosArray = [];
//Search result
response.data.items.map((video) => {
var videoDetails = {};
videoDetails.title = video.snippet.title;
videoDetails.thumbnail = video.snippet.thumbnails.default.url;
videoDetails.id = video.id.videoId;
videosArray.push(videoDetails);
});
//Getting Video durations
var IDs = '';
videosArray.map((video) => {
IDs += video.id + ',';
});
var videoParams = {
part: 'contentDetails',
key: API_KEY,
id: IDs
};
axios.get(ROOT_URL_VIDEOS, {params: videoParams})
.then((response) => {
for (var i = 0; i < videosArray.length; i++) {
videosArray[i].duration = YTFormat(response.data.items[i].contentDetails.duration);
}
//console.log(videosArray);
this.setState({
videos: videosArray
});
});
})
.catch((error) => {
console.error(error);
});
}
getPlayListItems() {
axios.get(`${RootApiUrl}/songs/${this.props.params.roomId}`)
.then((response) => {
let songsArray = [];
response.data.songs.map((song) => {
songsArray.push(song);
});
this.setState({playlist: songsArray});
//Set the current video to the first one
this.setState({currentVideo: this.state.playlist[0]});
//console.log(this.state.playlist);
})
.catch((e) => {
return console.log(e);
});
};
getRoomDetails() {
axios.get(`${RootApiUrl}/room/${this.props.params.roomId}`)
.then((res) => {
this.setState({roomDetails: res.data[0]});
})
.catch((e) => {
console.log(e);
});
};
setUserDetails() {
this.setState({userDetails: {username: AuthService.getUserDetails()}});
}
setInitialSpeakerValue = () => {
if (this.state.roomDetails.speakers.includes(this.state.userDetails.username)) {
this.setState({isSpeaker: true}, () => {
//console.log("Setting initial isSpeaker", this.state.isSpeaker);
});
} else {
this.setState({isSpeaker: false}, () => {
//console.log("Setting initial isSpeaker", this.state.isSpeaker);
});
}
};
setSpeakers = (speakersArray) => {
let currentRoomDetails = this.state.roomDetails;
//console.log(currentRoomDetails.speakers);
currentRoomDetails.speakers = speakersArray;
//console.log('Before state set:', this.state.roomDetails);
this.setState({roomDetails: currentRoomDetails}, () => {
if (this.state.roomDetails.speakers.includes(this.state.userDetails.username)) {
this.setState({isSpeaker: true}, () => {
//console.log("Setting isSpeaker", this.state.isSpeaker);
this.onSpeakerChange(this.state.isSpeaker);
});
} else {
this.setState({isSpeaker: false}, () => {
//console.log("Setting isSpeaker", this.state.isSpeaker);
this.onSpeakerChange(this.state.isSpeaker);
});
}
});
};
//Use an arrow function if you need to use another function in the same scope
onVideoSelect = (video) => {
video.roomId = this.props.params.roomId;
axios.post(`${RootApiUrl}/song`, video)
.then((response) => {
if (response.status !== 200) {
return console.error(response.status);
}
//console.log('Success');
//Refresh playlist - Need for an arrow function
this.getPlayListItems();
this.refreshPlaylistForOthers();
})
.catch((e) => {
console.error(e);
});
};
refreshPlaylistForOthers = () => {
this.state.socket.emit('refresh', {
type: 'playlist',
roomId: this.state.roomDetails.id
});
};
//Deleting
onPlayListItemDelete = (playlistItem) => {
console.log();
axios.delete(`${RootApiUrl}/song/${this.props.params.roomId}/${playlistItem._id}`)
.then((response) => {
if (response.status !== 200) {
return console.error(response);
}
this.getPlayListItems();
this.refreshPlaylistForOthers();
//console.log(response);
})
.catch((e) => {
console.error(e);
});
//console.log('Should delete ' + playlistItem.id, playlistItem.title);
};
playNextInList = () => {
this.onPlayListItemDelete(this.state.currentVideo);
//console.log('Play next');
};
setUserList = (userArray) => {
this.setState({userList: userArray});
};
onNavBackClick = () => {
this.state.socket.emit('unsubscribe', {
roomId: this.state.roomDetails.id,
username: AuthService.getUserDetails()
}, () => {
console.log('Disconnect');
});
browserHistory.push('/');
};
onSpeakerClick = (user) => {
//console.log('Speaker clicked', this.state.roomDetails.speakers, this.state.userDetails.username);
//Checking if the client is speaker
if (this.state.roomDetails.speakers.includes(this.state.userDetails.username) && user === this.state.userDetails.username) {
//If the client is a speaker
//console.log(`Toggle speaker off for ${user}`, this.state.roomDetails.speakers);
this.state.socket.emit('removeSpeaker', {
roomId: this.state.roomDetails.id,
username: this.state.userDetails.username
});
} else if (user === this.state.userDetails.username) {
//If the client is not a speaker
//console.log(`Toggle speaker on for ${user}`, this.state.roomDetails.speakers);
this.state.socket.emit('addSpeaker', {
roomId: this.state.roomDetails.id,
username: this.state.userDetails.username
});
}
};
onSpeakerChange = (isSpeaker) => {
return isSpeaker;
};
onMenuClick = () => {
this.toggleSideMenu();
};
toggleSideMenu = () => {
this.setState({isSideMenuOpen: !this.state.isSideMenuOpen});
};
onSearchClick = (value) => { //Value must be true or false
this.toggleSearch(value);
};
toggleSearch = (value) => { //Value must be true or false
this.setState({isSearchOpen: value});
};
toggleUserList = () => { //Value must be true or false
this.setState({isUserListOpen: !this.state.isUserListOpen});
};
updateWindowDimensions = () => {
this.setState({
windowSize: {
width: window.innerWidth,
height: window.innerHeight
}
}, () => {
if (this.state.windowSize.width <= 600) {
this.setState({isMobile: true});
} else {
this.setState({isMobile: false});
}
});
};
changeTitle(title) {
document.title = `${title} - Youtube Playlist`;
};
//Getting playlist items on startup
componentWillMount() {
this.getPlayListItems();
this.getRoomDetails();
this.setUserDetails();
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
};
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions);
};
componentDidMount() {
//Socket.io stuff
const checkVariable = () => {
if (this.state.roomDetails !== undefined) {
this.changeTitle(this.state.roomDetails.name);
/*console.log(this.state.roomDetails.id);*/
//console.log("Room details", this.state.roomDetails);
this.state.socket.emit('subscribe', {
roomId: this.state.roomDetails.id,
username: this.state.userDetails.username
});
this.state.socket.on(`refresh-${this.state.roomDetails.id}`, (data) => {
//console.log(`refresh-${this.state.roomDetails.id}`);
if (data.type === 'userlist') {
//Refreshing the userlist
//console.log("Refresh userlist", data.userlist);
this.setUserList(data.userlist);
} else if (data.type === 'playlist') {
//Refresing playlist
//console.log('playlist refresh');
this.getPlayListItems();
} else if (data.type === 'speakers') {
//Refreshing speakers list
//console.log("Speakers list", data.speakers);
this.setSpeakers(data.speakers)
}
});
/*this.state.socket.emit(this.state.roomDetails.id, {
message: `Hello from the Client`
});*/
//console.log("RoomID:", this.state.roomDetails.id);
this.state.socket.on(this.state.roomDetails.id, (data) => {
//const userlist = data.room.userlist;
//console.log("From server:", data);
this.setUserList(data.userlist);
});
}
//Setting the initial isSpeaker state
this.setInitialSpeakerValue();
};
setTimeout(checkVariable, 500);
};
render() {
const videoSearch = _.debounce((term) => {
this.videoSearch(term);
}, 200);
let searchList;
let sideMenu;
if (this.state.isMobile /*&& this.state.isSideMenuOpen*/) {
sideMenu = (
<SideMenu
roomName={this.state.roomDetails.name}
onNavBackClick={this.onNavBackClick}
isSideMenuOpen={this.state.isSideMenuOpen}
toggleSideMenu={this.toggleSideMenu}
toggleUserList={this.toggleUserList}
/>
);
searchList = (
<VideoList
onVideoSelect={this.onVideoSelect}
videos={this.state.videos}
isVisible={this.state.isSearchOpen}
isMobile={this.state.isMobile}
/>
);
} else {
searchList = (
<VideoList
onVideoSelect={this.onVideoSelect}
videos={this.state.videos}
isMobile={this.state.isMobile}
/>
);
}
return (
<div className="app-wrapper">
<Header
roomDetails={this.state.roomDetails}
location={'app'}
onNavBackClick={this.onNavBackClick}
onMenuClick={this.onMenuClick}
isMobile={this.state.isMobile}
>
<SearchBar
onSearchTermChange={videoSearch}
isMobile={this.state.isMobile}
onSearchClick={this.onSearchClick}
isSearchOpen={this.state.isSearchOpen}
/>
</Header>
<div className="content-wrapper">
{sideMenu}
<UserList
userList={this.state.userList}
speakers={this.state.roomDetails.speakers}
onSpeakerClick={this.onSpeakerClick}
clientUsername={this.state.userDetails.username}
isUserListOpen={this.state.isUserListOpen}
isMobile={this.state.isMobile}
toggleUserList={this.toggleUserList}
/>
<div className="playlist-container">
<YoutubePlayer
currentVideo={this.state.currentVideo}
playNextInList={this.playNextInList}
isSpeaker={this.state.isSpeaker}
onNextClick={this.onPlayListItemDelete}
currentSong={this.state.currentVideo}
onSpeakerClick={this.onSpeakerClick}
/>
<PlayList
playlist={this.state.playlist}
onPlayListItemDelete={this.onPlayListItemDelete}
/>
</div>
{/*VideoList*/}
{searchList}
</div>
</div>
);
}
} |
JavaScript | class Range {
// constructor defaults
constructor(start = 0, end = Infinity, step = 1) {
this.start = start;
this.end = end;
this.step = step;
}
// for (const i of new Range(1, 4)) ...
*[Symbol.iterator]() {
for (let i = this.start; i < this.end; i += this.step)
yield i;
}
// for (const value of new Range(1, 4).for('abcde')) ...
*for(iterable) {
for (let i = this.start; i < this.end; i += this.step)
yield* iterable[i];
}
} |
JavaScript | class Data {
/**
* Create a new `Data` with `attrs`.
*
* @param {Object|Data|Map} attrs
* @return {Data} data
*/
static create(attrs = {}) {
if (Map.isMap(attrs)) {
return attrs
}
if (isPlainObject(attrs)) {
return Data.fromJSON(attrs)
}
throw new Error(
`\`Data.create\` only accepts objects or maps, but you passed it: ${attrs}`
)
}
/**
* Create a `Data` from a JSON `object`.
*
* @param {Object} object
* @return {Data}
*/
static fromJSON(object) {
return new Map(object)
}
/**
* Create a `Data` from a JSON `object`.
*
* @param {Object} object
* @return {Data}
*/
static fromJS(object) {
return typeof object !== 'object' || object === null ? object :
Seq(object).map(Data.propertyFromJS).toMap()
}
/**
* Create `Data`'s property from a JSON `object`.
*
* @param {Object} object
* @return {Data}
*/
static propertyFromJS(object) {
return typeof object !== 'object' || object === null ? object :
Array.isArray(object) ?
Seq(object).map(Data.propertyFromJS).toList() :
Operation.fromJSON(object);
}
} |
JavaScript | class RKIFetcher {
static api = "https://opendata.arcgis.com/datasets/917fc37a709542548cc3be077a786c17_0.geojson";
city;
data = null;
landkreisPictureQuery;
queryResultRenderer;
static incidency;
static totalCases;
static totalDeaths;
static survivalRate;
static storedData = [];
cards = document.querySelectorAll(".card");
constructor(city) {
if(city) {
this.city = city;
}
document.querySelector("#landkreis").addEventListener("click", function(e) {
e.target.value = "";
e.target.click();
})
this.landkreisPictureQuery = new LandkreisPictureQuery(city);
this.cards.forEach(card => card.style.display = "none");
this.queryResultRenderer = new QueryResultRenderer(document.querySelector("#RKITarget"));
this.queryResultRenderer.hideRenderTarget();
}
async getAllLandkreise() {
const landkreise = [];
await fetch(RKIFetcher.api).then(res => res.json()).then(json => json.features.forEach(feature => landkreise.push(feature.properties.GEN)));
return landkreise;
}
static calculateIncidency() {
RKIFetcher.incidency = Number.parseInt((RKIFetcher.storedData.map(landkreis => landkreis.properties.cases7_per_100k).reduce((a,b) => a+b) / RKIFetcher.storedData.length) * 10) / 10
}
async findNeighbourDistricts(data_) {
console.log(this.data);
if(!this.data) {
await this.getInformation();
}
if(data_.properties.GEN == "Düsseldorf") {
RKIFetcher.storedData.forEach(feature => {
if(feature.properties.GEN == "Mettmann") {
data_ = feature;
}
})
}
return RKIFetcher
.storedData
.sort(function(a,b) { return Math.abs(a.properties.OBJECTID - data_.properties.OBJECTID) - Math.abs(b.properties.OBJECTID - data_.properties.OBJECTID)})
.slice(1, 6);
}
static async getAllLandkreiseAsObjects() {
if(RKIFetcher.storedData.length < 1) {
await fetch(RKIFetcher.api)
.then(res => res.json())
.then(json => json.features.forEach(feature => this.storedData.push(feature)));
}
RKIFetcher.calculateIncidency();
RKIFetcher.totalCases = RKIFetcher.calculateTotalCases();
RKIFetcher.totalDeaths = RKIFetcher.calculateTotalDeaths();
RKIFetcher.survivalRate = RKIFetcher.calculateAverageSurvivalRate();
}
async getInformation() {
await fetch(RKIFetcher.api).then(res => res.json()).then(json => json.features.forEach(feature => {
if(feature.properties.GEN == this.city) {
this.data = feature;
console.log(this.data);
window.location.href = window.location.href.split("?")[0] + "?share=" + RKIFetcher.landkreisToURL(feature.properties.GEN);
}
}))
}
static landkreisToURL(landkreis) {
let result = "";
for(let i = 0; i < landkreis.length; i++) {
result += "#" + landkreis.charCodeAt(i);
}
return result;
}
static findHotspots() {
return RKIFetcher.storedData.sort(function(a,b) { return b.properties.cases7_per_100k - a.properties.cases7_per_100k }).slice(0,5);
}
static calculateTotalCases() {
return RKIFetcher.storedData.map(landkreis => landkreis.properties.cases).reduce((a,b) => a+b)
}
static calculateTotalDeaths() {
return RKIFetcher.storedData.map(landkreis => landkreis.properties.deaths).reduce((a,b) => a+b)
}
static calculateAverageSurvivalRate() {
return Number.parseInt((RKIFetcher.storedData.map(landkreis => (Number.parseInt((landkreis.properties.death_rate) * 100) / 100)).reduce((a,b) => a+b) / RKIFetcher.storedData.length) * 10) / 10
}
static findSafestAreas() {
return RKIFetcher.storedData.sort(function(a,b) { return a.properties.cases7_per_100k - b.properties.cases7_per_100k }).slice(0,5);
}
static URLToLandkreis(landkreis) {
let result = "";
for(let i = 1; i < landkreis.split("#").length; i++) {
result += String.fromCharCode(landkreis.split("#")[i]);
}
return result;
}
async displayResult() {
if(!this.data) await this.getInformation();
const imageData = await LandkreisPictureQuery.requestPictureFromAPI(this.landkreisPictureQuery);
this.queryResultRenderer.render(imageData, this.city, this.data.properties);
this.queryResultRenderer.showRenderTarget();
this.queryResultRenderer.updateNeighbours(await this.findNeighbourDistricts(this.data));
dialog.modal('hide');
//this.queryResultRenderer.updateHotSpots(RKIFetcher.findHotspots());
//this.queryResultRenderer.updateSafest(RKIFetcher.findSafestAreas());
}
static transformParameterToLandkreis() {
return window.location.href
.split("?")[1]
.replace("share=", "")
.split("&")[0]
.replace("#1", "ä")
.replace("#2", "Ä")
.replace("#3", "ö")
.replace("#4", "Ö")
.replace("#5", "ü")
.replace("#6", "Ü")
.replace("#7", " ")
.replace("#8", "-");
}
static createRKIFetcherForLandkreis(landkreis) {
return new RKIFetcher(landkreis);
}
getAPIUrl() {
return RKIFetcher.api;
}
} |
JavaScript | class Zone {
/**
* Creates an instance of Zone.
* @param {deps} deps
* @memberof Zone
*/
constructor(deps) {
this.__deps = deps;
// Default zone settings
this.__defaultSettings = Object.freeze({
"name": undefined,
"verbose": true,
"spawnObject": true
});
// Entered zone id
this.__id = undefined;
// Instance of loaded guide
this.__guide = undefined;
// Settings of entered zone
this.__settings = undefined;
// Guide loaded status
this.__loaded = false;
// Migrate settings (compat)
this.__migrateSettings();
}
/**
* Initialize dungeon zones configuration.
* @memberof Zone
*/
async init() {
// Create a list of available guide ids
const availableGuides = new Set();
// Read directory of the available guides
(await readdir(this.getGuidePath()))
.forEach(file => {
if (!file.endsWith(".js")) return;
const zoneId = file.split(".")[0];
// Checking the dungeon id for a number, if it is a number add to the settings
if (!this.__deps.mod.settings.dungeons[zoneId] && !isNaN(parseInt(zoneId)))
this.__deps.mod.settings.dungeons[zoneId] = { "name": undefined, ...this.__defaultSettings };
// Add id to list of available guide ids
availableGuides.add(zoneId);
});
// Remove old configuration
Object.keys(this.__deps.mod.settings.dungeons).forEach(zoneId => {
if (!availableGuides.has(zoneId))
delete this.__deps.mod.settings.dungeons[zoneId];
});
let queredFromClient = false;
// Try to query a list of dungeon names and apply them to settings
try {
await this.queryDungeonNamesFromClient((zoneId, name) => {
queredFromClient = true;
if (!this.__deps.mod.settings.dungeons[zoneId])
return;
this.__deps.mod.settings.dungeons[zoneId].name = name;
});
} catch (e) {
this.__deps.mod.warn(e);
}
// If the client functions is not available, try to read dungeon list
// from guides directory, as dungeon name uses first line of the guide file
if (!queredFromClient)
await this.queryDungeonNamesFromFiles((zoneId, name) => {
if (!this.__deps.mod.settings.dungeons[zoneId])
return;
this.__deps.mod.settings.dungeons[zoneId].name = name;
});
}
/**
* Load zone.
* @param {string} [id=undefined] Zone identifier.
* @param {boolean} [debugMode=false] Force enable debug messages.
* @return {void}
* @memberof Zone
*/
load(id = undefined, debugMode = false) {
// Return if guide is loaded and zone id not changed
if (this.__loaded && id.toString() === this.__guide.id && !debugMode)
return;
// Unload current loaded guide
this.unload(debugMode);
// Set zone id of the entered zone
if (id !== undefined)
this.__id = id.toString();
// Return if module disabled
if (!this.__deps.mod.settings.enabled)
return;
// Send debug message
if (!debugMode)
this.__deps.handlers.send.debug(false, `Entered zone: ${this.__id}`);
// Check the entered zone id and set settings for them
if (this.__id === "test")
this.__settings = { ...this.__defaultSettings, "name": "Test Guide" };
else if (this.__deps.mod.settings.dungeons[this.__id])
this.__settings = this.__deps.mod.settings.dungeons[this.__id];
else {
if (debugMode)
this.__deps.handlers.send.debug(true, `Guide "${this.__id}" is not found.`);
return;
}
// Create an instance of Guide
const guide = new Guide(this.__deps, this.__id);
try {
// Try to load a guide for the entered zone
guide.load(debugMode);
} catch (e) {
if (e.code === "ENOENT")
return this.__deps.mod.warn(`Script file for the guide "${this.__id}" is not a loadable.`);
return this.__deps.mod.error(`Unable to load a script for the guide "${this.__id}":\n`, e);
}
// Set an instance of Guide
this.__guide = guide;
// Send debug message
this.__deps.handlers.send.debug(debugMode, `Guide "${guide.id}" loaded.`);
// Send welcome text
this.__deps.handlers.send.welcomeMessage(debugMode);
// Set guide as a loaded
this.__loaded = true;
}
/**
* Unload loaded zone.
* @param {boolean} [debugMode=false] Force enable debug messages.
* @memberof Zone
*/
unload(debugMode = false) {
if (!this.__loaded)
return;
// Unload loaded guide
this.__guide.unload(debugMode);
// Clear out properties
this.__guide = undefined;
this.__settings = undefined;
// Set guide as not a loaded
this.__loaded = false;
}
/**
* Query dungeon names from client.
* @param {Function} handler
* @memberof Zone
*/
async queryDungeonNamesFromClient(handler) {
const dungeons = new Map();
// Read list of available dungeons
(await this.__deps.mod.queryData("/EventMatching/EventGroup/Event@type=?", ["Dungeon"], true, true, ["id"]))
.map(res => {
const zoneId = res.children
.find(x => x.name == "TargetList").children
.find(x => x.name == "Target").attributes.id;
let dungeon = dungeons.get(zoneId);
if (!dungeon) {
dungeon = { "id": zoneId, "name": "" };
dungeons.set(zoneId, dungeon);
}
return dungeon;
});
// Read list of dungeon name strings
(await this.__deps.mod.queryData("/StrSheet_Dungeon/String@id=?", [[...dungeons.keys()]], true))
.forEach(res => handler(
res.attributes.id.toString(),
res.attributes.string.toString()
));
}
/**
* Query dungeon names from the guides files, as name uses first line of the file.
* @param {Function} handler
* @memberof Zone
*/
async queryDungeonNamesFromFiles(handler) {
// Read directory of the available guides
(await readdir(this.getGuidePath()))
.forEach(file => {
if (!file.endsWith(".js")) return;
const zoneId = file.split(".")[0];
const lineReader = readline.createInterface({
"input": fs.createReadStream(path.resolve(this.__deps.mod.info.path, "guides", file))
});
// Get first line of file and set as dungeon name
lineReader.on("line", line => {
handler(zoneId, line.trim().replace(new RegExp("^[/ ]+", "g"), "") || zoneId);
lineReader.close();
lineReader.removeAllListeners();
});
});
}
/**
* Get path of the guide.
* @param {boolean} [useLanguages=false] Allow to use translations folders.
* @param {string[]} pathArgs Array of path arguments.
* @return {string} Path string.
* @memberof Zone
*/
getGuidePath(useLanguages = false, ...pathArgs) {
let resolvedPath = undefined;
// Try to use path with translation
if (useLanguages) {
resolvedPath = path.resolve(this.__deps.mod.info.path, `guides_${this.__deps.lang.languageUC}`, ...pathArgs);
if (!fs.existsSync(resolvedPath))
resolvedPath = undefined;
}
// Use default path in it's not exists
if (!resolvedPath)
resolvedPath = path.resolve(this.__deps.mod.info.path, "guides", ...pathArgs);
return resolvedPath;
}
/**
* Get zone id.
* @readonly
* @memberof Zone
*/
get id() {
return this.__id;
}
/**
* Get zone settings.
* @readonly
* @memberof Zone
*/
get settings() {
return this.__settings;
}
/**
* Get zone loaded status.
* @readonly
* @memberof Zone
*/
get loaded() {
return this.__loaded;
}
/**
* Get instance of Guide (if loaded).
* @readonly
* @memberof Zone
*/
get guide() {
return this.__guide;
}
__migrateSettings() {
if (this.__deps.mod.settings.dungeons === null || typeof this.__deps.mod.settings.dungeons !== "object" || Array.isArray(this.__deps.mod.settings.dungeons))
this.__deps.mod.settings.dungeons = {};
}
destructor() {
this.unload();
}
} |
JavaScript | class Manager extends Employee
{
constructor (name, id, email, officeNumber)
{
super (name, id, email);
this.officeNumber = officeNumber;
}
getRole()
{
return "Manager";
}
getOfficeNumber()
{
return this.officeNumber;
}
} |
JavaScript | class Persona{
constructor(nombre, apellido,){
//'atributo de nuestra clase' = 'parametro';
this._nombre = nombre;
this._apellido = apellido;
}
get get_nombre(){
return this._nombre;
}
set set_nombre(nombre){
this._nombre = nombre;
}
} |
JavaScript | class IORegister {
constructor(gpu) {
this._memory = new Uint8Array(2 ** 7);
this.keyColumns = [new Array(4).fill(1), new Array(4).fill(1)];
this.currentColumn = 0;
this._gpu = gpu;
}
readByte(address) {
if (address === 0x00) return this.getKeys();
else if (address === 0x02) return this._memory[address] | 0b01111110; // TODO: SC
else if (address === 0x10) return this._memory[address] | 0b10000000; // TODO: NR 10
else if (address === 0x1A) return this._memory[address] | 0b01111111; // TODO: NR 30
else if (address === 0x1C) return this._memory[address] | 0b10011111; // TODO: NR 32
else if (address === 0x20) return this._memory[address] | 0b11000000; // TODO: NR 41
else if (address === 0x23) return this._memory[address] | 0b00111111; // TODO: NR 44
else if (address === 0x26) return this._memory[address] | 0b01110000; // TODO: NR 52
else if (address === 0x41) return this._gpu.renderTiming.getStat();
else if (address === 0x42) return this._gpu.registers.y;
else if (address === 0x43) return this._gpu.registers.x;
else if (address === 0x44) return this._gpu.renderTiming.getLine();
else if (isUnmapped(address)) return 0xFF;
return this._memory[address];
}
writeByte(address, value) {
this._memory[address] = value;
if (address === 0x00) this.currentColumn = value & 0x30;
else if (address === 0x40) this._handleLCDC(value);
else if (address === 0x41) this._gpu.renderTiming.EnableOrDisableStatInterrupts(value);
else if (address === 0x42) this._gpu.registers.y = value;
else if (address === 0x43) this._gpu.registers.x = value;
else if (address === 0x44) this._gpu.renderTiming.resetLine();
else if (address === 0x45) this._gpu.renderTiming.lyc = value & 0xFF;
else if (address === 0x47) this._gpu.setPalette(value, 'bg');
else if (address === 0x48) this._gpu.setPalette(value, 'obj0');
else if (address === 0x49) this._gpu.setPalette(value, 'obj1');
else if (address === 0x4A) this._gpu.registers.wy = value;
else if (address === 0x4B) this._gpu.registers.wx = value;
}
getKeys() {
switch (this.currentColumn) {
case 0x10: return toByte(this.keyColumns[0]);
case 0x20: return toByte(this.keyColumns[1]);
default: return 0xFF;
}
}
// TODO: custom mapping scheme
handleKeyDown(event) {
switch (event.key) {
case 'Enter': this.keyColumns[0][0] = 0; break;
case 'Space': this.keyColumns[0][1] = 0; break;
case 'z': this.keyColumns[0][2] = 0; break;
case 'x': this.keyColumns[0][3] = 0; break;
case 'Down':
case 'ArrowDown': this.keyColumns[1][0] = 0; break;
case 'Up':
case 'ArrowUp': this.keyColumns[1][1] = 0; break;
case 'Left':
case 'ArrowLeft': this.keyColumns[1][2] = 0; break;
case 'Right':
case 'ArrowRight': this.keyColumns[1][3] = 0; break;
default: break;
}
}
handleKeyUp(event) {
switch (event.key) {
case 'Enter': this.keyColumns[0][0] = 1; break;
case 'Space': this.keyColumns[0][1] = 1; break;
case 'z': this.keyColumns[0][2] = 1; break;
case 'x': this.keyColumns[0][3] = 1; break;
case 'Down':
case 'ArrowDown': this.keyColumns[1][0] = 1; break;
case 'Up':
case 'ArrowUp': this.keyColumns[1][1] = 1; break;
case 'Left':
case 'ArrowLeft': this.keyColumns[1][2] = 1; break;
case 'Right':
case 'ArrowRight': this.keyColumns[1][3] = 1; break;
default: break;
}
}
_handleLCDC(value) {
const bgOn = Util.getBit(value, 0);
const spriteOn = Util.getBit(value, 1);
this._gpu.registers.bg = bgOn;
this._gpu.registers.sprite = spriteOn;
this._gpu.registers.spriteHeight = Util.getBit(value, 2) ? 16 : 8;
this._gpu.registers.tilemap = Util.getBit(value, 3);
this._gpu.registers.tileset = Util.getBit(value, 4);
this._gpu.registers.window = Util.getBit(value, 5);
this._gpu.registers.tilemapWindow = Util.getBit(value, 6);
this._gpu.registers.lcd = Util.getBit(value, 7);
}
} |
JavaScript | class Manager extends Employee{
constructor(name,id,email,role,officeNumber){
super(name,id,email,role);
this._officNumber=officeNumber
this._role=role;
}
getRole(){
return this._role
};
getOfficeNumber(){
return this._officNumber
};
} |
JavaScript | class SkillsConfiguration {
constructor() {
this.skillsData = {};
// Note: we only have two skills in this sample but we could load more if needed.
const botFrameworkSimpleSkill = {
id: process.env.SkillSimpleId,
appId: process.env.SkillSimpleAppId,
skillEndpoint: process.env.SkillSimpleEndpoint
};
const botFrameworkBookingSkill = {
id: process.env.SkillBookingId,
appId: process.env.SkillBookingAppId,
skillEndpoint: process.env.SkillBookingEndpoint
};
this.skillsData[botFrameworkSimpleSkill.id] = botFrameworkSimpleSkill;
this.skillsData[botFrameworkBookingSkill.id] = botFrameworkBookingSkill;
this.skillHostEndpointValue = process.env.SkillHostEndpoint;
if (!this.skillHostEndpointValue) {
throw new Error('[SkillsConfiguration]: Missing configuration parameter. SkillHostEndpoint is required');
}
}
get skills() {
return this.skillsData;
}
get skillHostEndpoint() {
return this.skillHostEndpointValue;
}
} |
JavaScript | class MozuAppDevContractsDevAccountMember {
/**
* Constructs a new <code>MozuAppDevContractsDevAccountMember</code>.
* @alias module:model/MozuAppDevContractsDevAccountMember
*/
constructor() {
MozuAppDevContractsDevAccountMember.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>MozuAppDevContractsDevAccountMember</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/MozuAppDevContractsDevAccountMember} obj Optional instance to populate.
* @return {module:model/MozuAppDevContractsDevAccountMember} The populated <code>MozuAppDevContractsDevAccountMember</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new MozuAppDevContractsDevAccountMember();
if (data.hasOwnProperty('emailAddress')) {
obj['emailAddress'] = ApiClient.convertToType(data['emailAddress'], 'String');
}
if (data.hasOwnProperty('firstName')) {
obj['firstName'] = ApiClient.convertToType(data['firstName'], 'String');
}
if (data.hasOwnProperty('lastName')) {
obj['lastName'] = ApiClient.convertToType(data['lastName'], 'String');
}
if (data.hasOwnProperty('userId')) {
obj['userId'] = ApiClient.convertToType(data['userId'], 'String');
}
if (data.hasOwnProperty('dateLastSent')) {
obj['dateLastSent'] = ApiClient.convertToType(data['dateLastSent'], 'Date');
}
if (data.hasOwnProperty('invitationState')) {
obj['invitationState'] = ApiClient.convertToType(data['invitationState'], 'String');
}
if (data.hasOwnProperty('invitationId')) {
obj['invitationId'] = ApiClient.convertToType(data['invitationId'], 'String');
}
if (data.hasOwnProperty('roleId')) {
obj['roleId'] = ApiClient.convertToType(data['roleId'], 'Number');
}
}
return obj;
}
} |
JavaScript | class SalesDB {
/**
* Initialises the connector.
*/
constructor() {
// Parse numeric column to float in javascript instead of string.
pg.types.setTypeParser(1700, 'text', parseFloat);
// Pool a connection to the postgres database server.
this.pool = new pg.Pool({
connectionString: process.env.DATABASE_URL, ssl: {
rejectUnauthorized: false
}
});
}
/**
* Get the current instance of the connector.
*
* @returns {SalesDB}
*/
static getInstance() {
// Setup the singleton if not initialised yet.
if(!singleton) {
singleton = new SalesDB();
}
// Return the singleton instance.
return singleton;
}
// ----------------
// LIBRARY WRAPPERS
// ----------------
/**
* Connects to the database.
*
* @async
* @returns {pg.Client} An instance of the database connection against which queries can be run.
*/
async connect() {
return this.pool.connect();
}
/**
* Connects to the database, runs a query and then disconnects.
*
* @param {string} queryString - The SQL query to run.
* @param {any[]} [params] - The list of parameters to pass into the query.
*
* @returns {pg.Query} The database query results.
*/
async query(queryString, params=null) {
// Connect to the database.
const client = await this.connect();
// Run the specified query.
let result = await client.query(queryString, params);
// Release the database connection.
client.release();
// Return the query results.
return result;
}
// ----------------
// DATABASE CONTENT
// ----------------
/**
* Create the default tables in the Sales DB.
*
* Note: this function can be removed if you created the DB structure yourself using an postgres DB client.
*
* @returns {void}
*/
async createTables() {
console.log('DB - creating tables');
try {
// Connect to the database.
const client = await this.connect();
// Create the orders table.
await client.query(`
CREATE TABLE IF NOT EXISTS items(
name VARCHAR (50) NOT NULL,
brand VARCHAR (50) NOT NULL,
shopname VARCHAR (50) NOT NULL,
amount NUMERIC (1000) NOT NULL
)
`);
// Create the orders table.
await client.query(`
CREATE TABLE IF NOT EXISTS orders(
shopname VARCHAR (50) NOT NULL,
items TEXT[]
)
`);
// Release the database connection.
client.release();
} catch(error) {
console.error(error);
}
}
async createTablesOrders() {
console.log('SalesDB - creating tables');
try {
// Connect to the database.
const client = await this.connect();
// Create the orders table.
await client.query(`
CREATE TABLE IF NOT EXISTS orders(
orderno SERIAL PRIMARY KEY,
date TIMESTAMP NOT NULL,
amount NUMERIC (10, 2) NOT NULL,
status VARCHAR (50) NOT NULL
)
`);
// Release the database connection.
client.release();
} catch(error) {
console.error(error);
}
}
/**
* Insert the default data records into the Sales DB
*
* Note: this function can be removed and is here of demo purposes only.
*
* @returns {void}
*/
async insertDefaultData() {
//this.ClearDefaultData()
console.log('SalesDB - inserting default data');
const items = [
]
try {
// Connect to the database.
const client = await this.connect();
// Insert each of the demo order records.
for(const item of items) {
await client.query(`
INSERT INTO items (name, brand, shopname, tags, amount)
SELECT $1, $2, $3, $4, $5
`, [
item.name,
item.brand,
item.shopname,
item.tages,
item.amount,
]);
}
// Release the database connection.
client.release();
} catch(error) {
console.error(error);
}
}
async ClearDefaultData() {
console.log('SalesDB - deleting default data');
try {
// Connect to the database.
const client = await this.connect();
await client.query('DELETE FROM items');
// Release the database connection.
client.release();
} catch(error) {
console.error(error);
}
}
} |
JavaScript | class ValidateCreateUser {
/**
* Create A User
* @param {object} req
* @param {object} res
* @param {object} next
* @returns {object} response object
*/
static validateCreate(req, res, next) {
if (!req.body.fullname || !req.body.email || !req.body.password || !req.body.confirmPassword) {
return res.status(400).send({ status: 400, error: 'Please check your input--some input missing' });
}
if (!userAuthHelper.isWhiteSpace(req.body.email, req.body.password, req.body.confirmPassword)) {
return res.status(400).send({ status: 400, error: 'White Space are not allowed in input fields' });
}
if (typeof req.body.fullname.lenght < 3) {
return res.status(400).send({ status: 400, error: 'Full name lenght is too short' });
}
if (typeof req.body.fullname !== 'string') {
return res.status(400).send({ status: 400, error: 'Full Name Is Invalid' });
}
if (!userAuthHelper.isValidEmail(req.body.email)) {
return res.status(400).send({ status: 400, error: 'Please enter a valid email address' });
}
if (!userAuthHelper.ispasswordValid(req.body.password)) {
return res.status(400).send({ status: 400, error: 'Password Must Be at least Five Characters And Must Be A string' });
}
if (!userAuthHelper.doesPasswordMatch(req.body.password, req.body.confirmPassword)) {
return res.status(400).send({ status: 400, error: 'Passwords Do not match' });
}
next();
}
/**
* Create A User
* @param {object} req
* @param {object} res
* @param {object} next
* @returns {object} response object
*/
static validateLogin(req, res, next) {
if (!req.body.email || !req.body.password) {
return res.status(401).send({ status: 401, message: 'Some values are missing' });
}
if (!userAuthHelper.isValidEmail(req.body.email)) {
return res.status(401).send({ status: 401, message: 'Please enter a valid email address' });
}
if (!userAuthHelper.ispasswordValid(req.body.password)) {
return res.status(401).send({ status: 401, error: 'Password Must Be at least Five Characters' });
}
next();
}
} |
JavaScript | class LightSystem extends System {
/** @hidden */
execute() {
this.queries.light.added.forEach((entity) => {
let light = entity.getComponent(Light);
let direction = xyzToVector3(light.direction);
let scene = getScene(this, light.scene);
switch (light.type) {
case LightTypes.Point:
light.object = new BABYLON.PointLight(light.type, BABYLON.Vector3.Zero(), scene);
break;
case LightTypes.Directional:
light.object = new BABYLON.DirectionalLight(light.type, direction, scene);
break;
case LightTypes.Spot:
light.object = new BABYLON.SpotLight(light.type, BABYLON.Vector3.Zero(), direction, degreeToRadians(light.angle), light.exponent, scene);
break;
default:
light.object = new BABYLON.HemisphericLight(LightTypes.Hemispheric, direction, scene);
break;
}
this._updateLight(light);
updateObjectsTransform(entity);
});
this.queries.light.changed.forEach((entity) => {
this._updateLight(entity.getComponent(Light));
});
this.queries.light.removed.forEach((entity) => {
disposeObject(entity.getComponent(Light));
});
}
_updateLight(light) {
for (let prop in light) {
switch (prop) {
case "direction":
updateObjectVector3(light, prop);
break;
case "color":
this._updateColor(light, light.color);
break;
default:
updateObjectValue(light, prop);
break;
}
}
}
_updateColor(light, color) {
for (let prop in color) {
light.object[prop] = hexToColor3(color[prop]);
}
}
} |
JavaScript | class SpreadsheetSelection extends SystemObject {
static reportInvalidCharacter(c, pos) {
throw new Error("Invalid character " + CharSequences.quoteAndEscape(Character.fromJson(c)) + " at " + pos);
}
columnOrRange() {
SystemObject.throwUnsupportedOperation();
}
rowOrRange() {
SystemObject.throwUnsupportedOperation();
}
/**
* Returns true if the selection is a cell or cell-range
*/
isCellScalarOrRange() {
return false;
}
/**
* Returns true if the selection is a column/row or column-range/row-range.
*/
isColumnOrRowScalarOrRange() {
return false;
}
deleteHistoryHashToken() {
SystemObject.throwUnsupportedOperation();
}
testCell(cellReference) {
SystemObject.throwUnsupportedOperation();
}
testColumn(columnReference) {
SystemObject.throwUnsupportedOperation();
}
testRow(rowReference) {
SystemObject.throwUnsupportedOperation();
}
toHistoryHashToken() {
SystemObject.throwUnsupportedOperation();
}
apiLoadCellsQueryStringParameterSelectionType() {
SystemObject.throwUnsupportedOperation();
}
apiDeleteUrl() {
SystemObject.throwUnsupportedOperation();
}
apiInsertAfterUrl(count) {
SystemObject.throwUnsupportedOperation();
}
// 0 = ""
// 1 == api
// 2 == spreadsheet
// 3 == $spreadsheet-id
// 4 == column == Selection
// 5 == $selection
// 6 == before == insert-action.toUrl
apiInsertBeforePostUrl(urlPaths) {
SystemObject.throwUnsupportedOperation();
}
/**
* This is the text that will appear in the {@link SpreadsheetSelectAutocompleteWidget}.
*/
selectOptionText() {
SystemObject.throwUnsupportedOperation();
}
// key events.......................................................................................................
/**
*
*/
onViewportKeyDown(key, selectRange, selection, anchor, viewportHome, saveSelection, giveFormulaFocus) {
console.log("onViewportKeyDown: " + key + " " + (selectRange ? "selecting range ": "") + this + " " + (selection ? selection + " ": "") + (anchor ? anchor + " ": "") + (viewportHome ? " home=" + viewportHome : ""));
const selectionOrThis = selection ? selection : this;
switch(key) {
case Keys.ARROW_LEFT:
saveSelection(
selectRange ?
selectionOrThis.viewportLeftExtend(anchor, this, viewportHome):
this.viewportLeft(viewportHome).setAnchor()
);
break;
case Keys.ARROW_RIGHT:
saveSelection(
selectRange ?
selectionOrThis.viewportRightExtend(anchor, this, viewportHome):
this.viewportRight(viewportHome).setAnchor()
);
break;
case Keys.ARROW_UP:
saveSelection(
selectRange ?
selectionOrThis.viewportUpExtend(anchor, this, viewportHome):
this.viewportUp(viewportHome).setAnchor()
);
break;
case Keys.ARROW_DOWN:
saveSelection(
selectRange ?
selectionOrThis.viewportDownExtend(anchor, this, viewportHome):
this.viewportDown(viewportHome).setAnchor()
);
break;
case Keys.ENTER:
selectionOrThis.viewportEnter(giveFormulaFocus);
break;
case Keys.ESCAPE:
saveSelection(null);
break;
default:
// ignore other keys
break;
}
}
viewportContextMenuClick(clicked) {
SystemObject.throwUnsupportedOperation();
}
/**
* This method is called whenever the element for this selection is clicked, providing an opportunity to
* build the context menu items that will be displayed ready for clicking.
*/
viewportContextMenuItems(historyTokens){
SystemObject.throwUnsupportedOperation();
}
static VIEWPORT_CONTEXT_MENU_ID = "viewport-context-menu";
static VIEWPORT_CONTEXT_MENU_CLEAR_ID = SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_ID + "-clear";
static VIEWPORT_CONTEXT_MENU_DELETE_ID = SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_ID + "-delete";
// the id for the "delete column" menu item
static VIEWPORT_CONTEXT_MENU_DELETE_COLUMN_ID = SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_ID + "-delete-column";
// the id for the "delete row" menu item
static VIEWPORT_CONTEXT_MENU_DELETE_ROW_ID = SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_ID + "-delete-row";
static VIEWPORT_CONTEXT_MENU_INSERT_AFTER_2_ID = SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_ID + "-insert-after-2";
static VIEWPORT_CONTEXT_MENU_INSERT_AFTER_1_ID = SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_ID + "-insert-after-1"
static VIEWPORT_CONTEXT_MENU_INSERT_BEFORE_2_ID = SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_ID + "-insert-before-2";
static VIEWPORT_CONTEXT_MENU_INSERT_BEFORE_1_ID = SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_ID + "-insert-before-1";
/**
* Builds the context menu items for a cell or cell-range.
*/
viewportContextMenuItemsCell(historyTokens, history) {
historyTokens[SpreadsheetHistoryHashTokens.SELECTION] = this;
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = null;
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ANCHOR] = null;
const menuItems = [];
// delete cells
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = SpreadsheetCellDeleteSelectionActionHistoryHashToken.INSTANCE;
menuItems.push(
history.menuItem(
this.viewportDeleteCellText(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_DELETE_ID,
historyTokens
)
);
// delete column
const columnOrRange = this.columnOrRange();
historyTokens[SpreadsheetHistoryHashTokens.SELECTION] = columnOrRange;
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = SpreadsheetColumnOrRowDeleteHistoryHashToken.INSTANCE;
menuItems.push(
history.menuItem(
columnOrRange.viewportDeleteCellColumnText(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_DELETE_COLUMN_ID,
historyTokens
)
);
// delete row
const rowOrRange = this.rowOrRange();
historyTokens[SpreadsheetHistoryHashTokens.SELECTION] = rowOrRange;
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = SpreadsheetColumnOrRowDeleteHistoryHashToken.INSTANCE;
menuItems.push(
history.menuItem(
rowOrRange.viewportDeleteCellRowText(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_DELETE_ROW_ID,
historyTokens
)
);
return menuItems;
}
// delete
// insert 1 before
// insert 2 before
// insert 1 after
// insert 2 after
viewportContextMenuItemsColumnOrRow(historyTokens, history) {
historyTokens[SpreadsheetHistoryHashTokens.SELECTION] = this;
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = null;
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ANCHOR] = null;
const menuItems = [];
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = SpreadsheetColumnOrRowClearHistoryHashToken.INSTANCE;
menuItems.push(
history.menuItem(
this.viewportClearText(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_CLEAR_ID,
historyTokens
)
);
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = SpreadsheetColumnOrRowDeleteHistoryHashToken.INSTANCE;
menuItems.push(
history.menuItem(
this.viewportDeleteText(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_DELETE_ID,
historyTokens
)
);
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = new SpreadsheetColumnOrRowInsertBeforeHistoryHashToken(2);
menuItems.push(
history.menuItem(
this.viewportInsertBefore2Text(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_INSERT_BEFORE_2_ID,
historyTokens
)
);
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = new SpreadsheetColumnOrRowInsertBeforeHistoryHashToken(1);
menuItems.push(
history.menuItem(
this.viewportInsertBefore1Text(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_INSERT_BEFORE_1_ID,
historyTokens
)
);
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = new SpreadsheetColumnOrRowInsertAfterHistoryHashToken(1);
menuItems.push(
history.menuItem(
this.viewportInsertAfter1Text(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_INSERT_AFTER_1_ID,
historyTokens
)
);
historyTokens[SpreadsheetHistoryHashTokens.SELECTION_ACTION] = new SpreadsheetColumnOrRowInsertAfterHistoryHashToken(2);
menuItems.push(
history.menuItem(
this.viewportInsertAfter2Text(),
SpreadsheetSelection.VIEWPORT_CONTEXT_MENU_INSERT_AFTER_2_ID,
historyTokens
)
);
return menuItems;
}
viewportEnter(giveFormulaFocus) {
SystemObject.throwUnsupportedOperation();
}
viewportFocus(giveFormulaFocus) {
SystemObject.throwUnsupportedOperation();
}
viewportLeft(start) {
SystemObject.throwUnsupportedOperation()
}
viewportRight(start) {
SystemObject.throwUnsupportedOperation()
}
viewportUp(start) {
SystemObject.throwUnsupportedOperation()
}
viewportDown(start) {
SystemObject.throwUnsupportedOperation()
}
viewportLeftExtend(start) {
SystemObject.throwUnsupportedOperation()
}
viewportRightExtend(start) {
SystemObject.throwUnsupportedOperation()
}
viewportUpExtend(start) {
SystemObject.throwUnsupportedOperation()
}
viewportDownExtend(start) {
SystemObject.throwUnsupportedOperation()
}
viewportClearText() {
return "Clear";
}
viewportDeleteText() {
return "Delete";
}
viewportDeleteCellText() {
SystemObject.throwUnsupportedOperation();
}
viewportDeleteColumnText() {
SystemObject.throwUnsupportedOperation();
}
viewportDeleteRowText() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertAfter1Id() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertAfter1Text() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertAfter2Id() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertAfter2Text() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertBefore1Id() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertBefore1Text() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertBefore2Id() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertBefore2Text() {
SystemObject.throwUnsupportedOperation();
}
viewportId() {
SystemObject.throwUnsupportedOperation();
}
static reportInvalidAnchor(anchor) {
throw new Error("Invalid anchor=" + anchor);
}
setAnchor(anchor) {
return new SpreadsheetViewportSelection(this, anchor);
}
/**
* If the sub class is a range, call setAnchor with the given anchor otherwise call with null.
*/
setAnchorConditional(anchor) {
SystemObject.throwUnsupportedOperation();
}
checkAnchor(anchor) {
const anchors = this.anchors();
switch(anchors.length) {
case 0:
if(null != anchor){
throw new Error("Expected no anchor got " + anchor);
}
break;
default:
if(null == anchor){
throw new Error("Missing anchor");
}
if(anchors.findIndex(a => a.equals(anchor)) === -1){
throw new Error("Unknown anchor " + anchor + ", expected any of " + anchors.join(", "));
}
break;
}
}
defaultAnchor() {
SystemObject.throwUnsupportedOperation();
}
/**
* Returns an array of allowed anchors for this selection.
*/
anchors() {
SystemObject.throwUnsupportedOperation();
}
viewportInsertBeforePostSuccessSelection(count) {
SystemObject.throwUnsupportedOperation();
}
toString() {
return this.toJson();
}
} |
JavaScript | class FieldParser {
/**
* Parses a single value of a field and return the sanitized form.
*
* @public
* @abstract
*/
parse () {
throw new Error('Not yet implemented');
}
} |
JavaScript | class Switch extends Sprite {
constructor(options = {}) {
super('switch', {
imageId: 'objects',
x: options.x,
y: options.y,
pool: options.pool,
objectId: options.objectId || '',
animations: {
unactivated: {
frameDuration: 1,
frames: [{
offsetX: 204,
offsetY: 37,
width: 31,
height: 31,
hitBox: {
x: 0,
y: 0,
x2: 31,
y2: 31
},
plane: 0
}],
loop: 0
},
activated: {
frameDuration: 1,
frames: [{
offsetX: 238,
offsetY: 37,
width: 31,
height: 31,
hitBox: {
x: 0,
y: 0,
x2: 31,
y2: 31
},
plane: 0
}],
loop: 0
}
}
});
var that = this;
// options = options || {};
options.x = typeof options.x !== 'undefined' ? options.x : 600;
options.y = typeof options.y !== 'undefined' ? options.y : 300;
// switch-specific options
this.isActivated = options.isActivated || false;
// /switch-specific options
this.running = true;
}
toggleSwitch() {
this.isActivated = !this.isActivated;
this.setAnimationFromSwitch();
AM.play('leverActivated', this.soundRef);
}
reset() {
super.reset();
this.currentMovement = '';
this.setAnimationFromSwitch();
}
setAnimationFromSwitch() {
this.setAnimation(this.isActivated ? 'activated' : 'unactivated');
}
} |
JavaScript | class CaesarCipherEncoder extends Encoder {
/**
* Returns brick meta.
* @return {object}
*/
static getMeta () {
return meta
}
/**
* Constructor
*/
constructor () {
super()
this.addSettings([
{
name: 'shift',
type: 'number',
label: 'Shift',
priority: 10,
value: defaultShift,
integer: true,
useBigInt: true,
describeValue: this.describeShiftValue.bind(this),
randomizeValue: this.randomizeShiftValue.bind(this)
},
{
name: 'alphabet',
type: 'text',
value: defaultAlphabet,
uniqueChars: true,
minLength: 2,
caseSensitivity: false,
randomizable: false
},
{
name: 'caseStrategy',
type: 'enum',
value: 'maintain',
elements: ['maintain', 'ignore', 'strict'],
labels: ['Maintain case', 'Ignore case', 'Strict (A ≠ a)'],
width: 6,
randomizable: false
},
{
name: 'includeForeignChars',
type: 'boolean',
label: 'Foreign Chars',
width: 6,
value: true,
trueLabel: 'Include',
falseLabel: 'Ignore',
randomizable: false
}
])
}
/**
* Performs encode or decode on given content.
* @param {Chain} content
* @param {boolean} isEncode True for encoding, false for decoding
* @return {number[]|string|Uint8Array|Chain} Resulting content
*/
performTranslate (content, isEncode) {
const { shift, caseStrategy, includeForeignChars } =
this.getSettingValues()
// Prepare alphabet(s) depending on chosen case strategy
let alphabet = this.getSettingValue('alphabet')
let uppercaseAlphabet
if (caseStrategy !== 'strict') {
alphabet = alphabet.toLowerCase()
uppercaseAlphabet = alphabet.toUpperCase()
}
const m = alphabet.getLength()
const n = content.getLength()
const result = new Array(n)
let codePoint, x, y, uppercase
let j = 0
// Go through each character in content
for (let i = 0; i < n; i++) {
codePoint = content.getCodePointAt(i)
// Match alphabet character
x = alphabet.indexOfCodePoint(codePoint)
uppercase = false
// Match uppercase alphabet character (depending on case strategy)
if (x === -1 && caseStrategy !== 'strict') {
x = uppercaseAlphabet.indexOfCodePoint(codePoint)
uppercase = true
}
if (x === -1) {
// Character is not in the alphabet
if (includeForeignChars) {
result[j++] = codePoint
}
} else {
// Shift character
if (typeof shift !== 'bigint') {
y = MathUtil.mod(x + shift * (isEncode ? 1 : -1), m)
} else {
y = Number(MathUtil.mod(
BigInt(x) + shift * BigInt(isEncode ? 1 : -1),
BigInt(m)
))
}
// Translate index to character following the case strategy
if (caseStrategy === 'maintain' && uppercase) {
result[j++] = uppercaseAlphabet.getCodePointAt(y)
} else {
result[j++] = alphabet.getCodePointAt(y)
}
}
}
return result.slice(0, j)
}
/**
* Triggered when a setting field has changed.
* @param {Field} setting Sender setting field
* @param {mixed} value New field value
*/
settingValueDidChange (setting, value) {
switch (setting.getName()) {
case 'caseStrategy':
// Apply case sensitivity on the alphabet setting
this.getSetting('alphabet').setCaseSensitivity(value === 'strict')
break
case 'alphabet':
// The shift value description depends on the alphabet and thus needs
// to be updated when the alphabet changes
this.getSetting('shift').setNeedsValueDescriptionUpdate()
break
}
}
/**
* Generates a random shift setting value.
* @param {Random} random Random instance
* @param {Field} setting Shift setting
* @return {string} Randomized plugboard setting value
*/
randomizeShiftValue (random, setting) {
const alphabetSetting = this.getSetting('alphabet')
if (alphabetSetting.isValid()) {
return random.nextInteger(1, alphabetSetting.getValue().getLength() - 1)
}
return null
}
/**
* Function describing the given shift value in a human-readable way.
* @param {number} value Field value
* @param {Field} setting Sender
* @return {?string} Shift label
*/
describeShiftValue (value, setting) {
// The shift value description depends on the alphabet setting
if (!this.getSetting('alphabet').isValid()) {
return null
}
// Shift the first character of the alphabet to describe the translation
const { alphabet, shift } = this.getSettingValues()
const plain = alphabet.getCharAt(0)
const index = MathUtil.mod(
shift,
typeof shift !== 'bigint'
? alphabet.getLength()
: BigInt(alphabet.getLength())
)
const encoded = alphabet.getCharAt(index)
return `${plain}→${encoded}`
}
} |
JavaScript | class IP {
constructor(contents) {
this.type = IP.Types.NORMAL;
this.contents = contents;
}
toString() {
return `IP: {
type:${this.type.name},
contents: ${(this.contents === null) ? "<null>" : "<data>"}
}`;
}
} |
JavaScript | class MainWindow {
/**
* Constructor for the main window
*/
constructor() {
this.mainWindow = null;
this.messageService = null;
this.menuHandler;
this.appManager;
this.isMac = process.platform === 'darwin';
//register async initialization of the application window.
app.on('ready', () => {
this.initializeApp();
});
app.on('window-all-closed', () => {
app.quit();
});
}
/**
* Initializes the application. This initializes the following:
* - blogly file system service
* - main application window
*/
initializeApp() {
// get all cofigurations loaded
try {
// initialize app services
this.initializeAppServices();
// creates the main window
this.createMainWindow();
// subscribe to the system preferences
if (this.isMac) {
systemPreferences.subscribeNotification(
'AppleInterfaceThemeChangedNotification',
function theThemeHasChanged() {
console.log(
'The theme has been changed to ' +
systemPreferences.isDarkMode()
? 'dark'
: 'light'
);
}
);
}
} catch (error) {
console.error(error);
throw error;
}
}
/**
* Initializes all the application services
*/
initializeAppServices() {
// initializes menu handler
this.menuHandler = new MenuManagerService(Menu, app);
// initialize app manager service
this.appManager = new AppManagerService({
app: app,
debugMode: true,
menuManager: this.menuHandler,
});
}
/**
* Creates the main window and displays it
*/
createMainWindow() {
// initialize a new window
var windowConfigs = this.appManager.getStartupConfigurations();
this.mainWindow = new BrowserWindow(windowConfigs);
// initializes the message manager service
this.messageService = this.appManager.initializeApp(
ipcMain,
this.mainWindow
);
this.menuHandler.setMessenger(this.messageService);
// initializes the listeners for UI events
this.appManager.initializeListeners();
// sets the application menu
this.appManager.updateBlogsMenus(this.menuHandler);
this.menuHandler.setMenu(Menu);
this.enableSpellCheck();
// load the compiled index.html file
this.mainWindow.loadFile('./out/client/blogly/index.html');
// display the window once ready
this.mainWindow.once('ready-to-show', () => {
this.mainWindow.show();
});
}
/**
* Enables spell check context menus
*/
enableSpellCheck() {
this.mainWindow.webContents.on('context-menu', (event, params) => {
const menu = new Menu();
if (
params.dictionarySuggestions != null &&
params.dictionarySuggestions.length > 0
) {
// Add each spelling suggestion
for (const suggestion of params.dictionarySuggestions) {
menu.append(
new MenuItem({
label: suggestion,
click: () =>
this.mainWindow.webContents.replaceMisspelling(
suggestion
),
})
);
}
} else {
menu.append(
new MenuItem({
label: 'No guesses found',
enabled: false,
})
);
}
menu.append(
new MenuItem({
type: 'separator',
})
);
// Allow users to add the misspelled word to the dictionary
if (params.misspelledWord) {
menu.append(
new MenuItem({
label: 'Add to dictionary',
click: () =>
this.mainWindow.webContents.session.addWordToSpellCheckerDictionary(
params.misspelledWord
),
})
);
}
menu.popup();
});
}
} |
JavaScript | class SafeConsent extends Consent {
constructor(obj) {
super(SafeConsent.getClass(), [obj.userId, obj.appId, obj.caseId, obj.docId]);
obj['host'] = '';
obj['when'] = '';
Object.assign(this, obj);
}
/**
* Basic getters and setters
*/
getUserId() {
return this.userId;
}
setUserId(userId) {
this.userId = userId;
}
getAppId() {
return this.appId;
}
setAppId(appId) {
this.appId = appId;
}
getCaseId() {
return this.caseId;
}
setCaseId(caseId) {
this.caseId = caseId;
}
getDocId() {
return this.docId;
}
setDocId(docId) {
this.docId = docId;
}
getForApp() {
return this.forApp;
}
setForApp(forApp) {
this.forApp = forApp;
}
getForWhom() {
return this.forWhom;
}
setForWhom(forWhom) {
this.forWhom = forWhom;
}
getAcl() {
return this.acl;
}
setAcl(acl) {
this.acl = acl;
}
getFrom() {
return this.from;
}
setFrom(from) {
this.from = from;
}
getTo() {
return this.to;
}
setTo(to) {
this.to = to;
}
getHost() {
return this.host;
}
setHost(host) {
this.host = host;
}
getWhen() {
return this.when;
}
setWhen(when) {
this.when = when;
}
/**
* Useful methods to encapsulate safeconsent states
*/
setRequested() {
this.action = cpaction.REQUESTED;
}
setAccepted() {
this.action = cpState.APPROVE;
}
setRejected() {
this.action = cpState.DISAPPROVE;
}
isConsentGiven() {
return this.action === cpState.APPROVE;
}
static fromBuffer(buffer) {
return SafeConsent.deserialize(Buffer.from(JSON.parse(buffer)));
}
toBuffer() {
return Buffer.from(JSON.stringify(this));
}
/**
* Deserialize a consent data to safeconsent
* @param {Buffer} data to form back into the object
*/
static deserialize(data) {
return Consent.deserializeClass(data, SafeConsent);
}
/**
* Factory method to create a safeconsent object
*/
static createInstance(userId, appId, caseId, docId, forApp,forWhom,acl,from, to) {
return new SafeConsent({ userId, appId, caseId, docId, forApp,forWhom, acl,from, to });
}
static getClass() {
return 'org.safeconnet.safeconsent';
}
} |
JavaScript | class CardDeck {
/**
* @constructor
*
* @param {object} options - Configure by sending options.
*/
constructor(options = {}) {
this.numberOfDecks = options.numberOfDecks || 2;
this.numberOfCards = options.numberOfCards || 52;
this.decks = [];
for (let i = 0; i < this.numberOfDecks * 52; i++) {
this.decks.push(i % this.numberOfCards);
}
}
/**
* Get number of cards in deck.
*
* @returns {integer} The amount of cards in the deck.
*/
getNumberOfCards() {
return (this.decks.length);
}
/**
* Show all cards by their id.
*
* @returns {array} With all cards.
*/
showAllCardsById() {
return (this.decks.slice());
}
/**
* Shuffle the deck.
*
* @returns {void}
*/
shuffle() {
for (let i = this.decks.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this.decks[i], this.decks[j]] = [this.decks[j], this.decks[i]];
}
}
/**
* Get a card from the deck, remove it from the deck.
*
* @returns {integer} As card id.
*/
getCard() {
return (this.decks.pop());
}
} |
JavaScript | class Client extends abstract_client_1.AbstractClient {
constructor(clientConfig) {
super("iotcloud.tencentcloudapi.com", "2021-04-08", clientConfig);
}
/**
* 设置设备上报的日志级别
*/
async UpdateDeviceLogLevel(req, cb) {
return this.request("UpdateDeviceLogLevel", req, cb);
}
/**
* 查询私有CA绑定的产品列表
*/
async DescribePrivateCABindedProducts(req, cb) {
return this.request("DescribePrivateCABindedProducts", req, cb);
}
/**
* 本接口(DescribeDevices)用于查询物联网通信设备的设备列表。
*/
async DescribeDevices(req, cb) {
return this.request("DescribeDevices", req, cb);
}
/**
* 本接口(CreateDevice)用于新建一个物联网通信设备。
*/
async CreateDevice(req, cb) {
return this.request("CreateDevice", req, cb);
}
/**
* 查询产品绑定的CA证书
*/
async DescribeProductCA(req, cb) {
return this.request("DescribeProductCA", req, cb);
}
/**
* 查询私有化CA信息
*/
async DescribePrivateCA(req, cb) {
return this.request("DescribePrivateCA", req, cb);
}
/**
* 创建私有CA证书
*/
async CreatePrivateCA(req, cb) {
return this.request("CreatePrivateCA", req, cb);
}
/**
* 本接口(DeleteProduct)用于删除一个物联网通信产品
*/
async DeleteProduct(req, cb) {
return this.request("DeleteProduct", req, cb);
}
/**
* 更新私有CA证书
*/
async UpdatePrivateCA(req, cb) {
return this.request("UpdatePrivateCA", req, cb);
}
/**
* 查询私有CA证书列表
*/
async DescribePrivateCAs(req, cb) {
return this.request("DescribePrivateCAs", req, cb);
}
/**
* 删除私有CA证书
*/
async DeletePrivateCA(req, cb) {
return this.request("DeletePrivateCA", req, cb);
}
/**
* 本接口(DescribeDevice)用于查看设备信息
*/
async DescribeDevice(req, cb) {
return this.request("DescribeDevice", req, cb);
}
/**
* 批量启用或者禁用设备
*/
async UpdateDevicesEnableState(req, cb) {
return this.request("UpdateDevicesEnableState", req, cb);
}
/**
* 本接口(DeleteDevice)用于删除物联网通信设备。
*/
async DeleteDevice(req, cb) {
return this.request("DeleteDevice", req, cb);
}
/**
* 本接口(DescribeProduct)用于查看产品详情
*/
async DescribeProduct(req, cb) {
return this.request("DescribeProduct", req, cb);
}
} |
JavaScript | class RTCPInbox extends RTCPEvents {
logPrefix = "[RTCP Inbox]"; // string to append to log
log = RTCP.log; // use logger of main module
_inbox = []; // initialize empty inbox
_inboxReady = false; // to be able to wait for inbox to be loaded on app start
_lastInboxSync = new Date(0); // timestamp of last inbox sync with server
_readReceiptQueue = []; // array of push_ids to send read receipt to server for
_readReceiptTimer = null; // reference to timer object
_events = ["onInboxUpdate"]; // list of subscribable events
async init(options) {
this.log("Initializing rtcp-react-native Inbox module");
// --- Module configuration ---
// enableBadge
this.enableBadge = typeof options.enableBadge !== "undefined" ? options.enableBadge : true;
if (Platform.OS === "ios") await DefaultPreference.set("rtcp_enable_badge", this.enableBadge.toString()); // store in userdefaults for NSE
// update badge and write inbox to storage on changes
if (this.enableBadge) this.registerEventHandler("onInboxUpdate", () => {
PushNotification.setApplicationIconBadgeNumber(this.getUnreadCount());
this._writeInboxToStorage();
});
// inboxSize
this.inboxSize = typeof options.inboxSize !== "undefined" ? options.inboxSize : DEFAULTINBOXSIZE;
if (Platform.OS === "ios") await DefaultPreference.set("rtcp_inbox_size", this.inboxSize.toString()); // store in userdefaults for NSE
// syncOnAppstart
this.syncOnAppstart = typeof options.syncOnAppstart !== "undefined" ? options.syncOnAppstart : false;
if (this.syncOnAppstart) {
this.syncInbox().catch(() => {});
AppState.addEventListener("change", (nextAppState) => {
if (nextAppState === "active") this.syncInbox().catch(() => {});
});
} else {
this._loadInboxFromStorage();
// on iOS load inbox from storage on every appstart to sync possible changes made by NSE
if (Platform.OS === "ios") {
AppState.addEventListener("change", (nextAppState) => {
if (nextAppState === "active") this._loadInboxFromStorage();
});
}
}
// --- Initializations ---
RTCP.registerEventHandler("onRemoteNotification", (notification) => this._onRemoteNotification(notification));
}
async syncInbox(force = false) {
if (force || new Date() - this._lastInboxSync > SYNCTIMEOUT * 1000) {
// send outstanding read receipts to server before syncing inbox
if (this._readReceiptQueue.length != 0) {
this._startReadReceiptTimer(0);
let tenthsOfSecond = 0;
while (this._readReceiptQueue.length != 0 || tenthsOfSecond <= 10) { // wait max of 1 second for read receipt queue to clear
await new Promise(resolve => setTimeout(resolve, 100));
tenthsOfSecond++;
}
}
this._inbox = (await RTCP.getRecentNotifications(this.inboxSize)) || this._inbox; // get inbox from server, throws on error
this._lastInboxSync = new Date(); // note sync time
this._inboxReady = true;
this._emitEvent("onInboxUpdate", this._inbox); // emit update event
} else {
this.log("Time since last sync too short. Not syncing Inbox with server");
}
}
getInbox() {
return this._inbox;
}
getUnreadCount() {
return this._inbox.filter((notification) => notification["read"] === false).length; // return number of unread notifications
}
setRead(index) {
if (this._inbox[index] && this._inbox[index]["read"] === false) {
this._inbox[index]["read"] = true;
// queue up read receipts to reduce server requests and load
this._readReceiptQueue.indexOf(this._inbox[index]["push_id"]) === -1 && this._readReceiptQueue.push(this._inbox[index]["push_id"]);
this._startReadReceiptTimer(READRECEIPTWAITTIME);
this._emitEvent("onInboxUpdate", this._inbox);
}
}
delete(index) {
if (this._inbox[index]) {
RTCP.deleteNotification(this._inbox[index]["push_id"]);
this._inbox.splice(index, 1);
this._emitEvent("onInboxUpdate", this._inbox);
}
}
// --- private methods ---
async _onRemoteNotification(notification) {
// on Android manage inbox on incoming message
if (Platform.OS === "android") {
if (!this._inboxReady) {
await new Promise(resolve => setTimeout(resolve, 100));
}
let data = notification.data;
if (data.revoke || (data.message && !data.not_in_inbox)) {
// received a new notification. add it to inbox
data.time = data.time || new Date().toISOString();
data.read = false;
if (data.revoke) {
let index = this._inbox.findIndex((notification) => notification.push_id === data.revoke);
if (index >= 0) {
this.log("Removing inbox item:", this._inbox[index]);
this._inbox.splice(index, 1);
this._emitEvent("onInboxUpdate", this._inbox);
} else {
this.log("Notification to be revoked not found in inbox:", data.revoke);
return;
}
} else if (data.replace) {
let index = this._inbox.findIndex((notification) => notification.push_id === data.replace);
if (index >= 0) {
this.log("Replacing inbox item:", this._inbox[index], "with:", data);
this._inbox[index] = data;
this._emitEvent("onInboxUpdate", this._inbox);
} else {
this.log("Notification to be replaced not found in inbox:", data.replace);
return;
}
} else {
this.log("Adding new notification to inbox:", data);
this._inbox.unshift(data);
if (this._inbox.length > this.inboxSize) this._inbox.length = this.inboxSize; // limit inbox to max size
this._emitEvent("onInboxUpdate", this._inbox);
}
}
}
// on iOS inbox is managed by NSE on incoming message, load changes.
if (Platform.OS === "ios" && notification.foreground) {
this._loadInboxFromStorage();
}
}
async _loadInboxFromStorage() {
RTCP.debugLog && this.log("Loading Inbox from storage");
// get inbox and last sync time from storage
inboxString = await DefaultPreference.get("rtcp_inbox");
if (inboxString) {
this._inbox = JSON.parse(inboxString);
this._lastInboxSync = new Date(await DefaultPreference.get("rtcp_last_inbox_sync"));
this._inboxReady = true;
this._emitEvent("onInboxUpdate", this._inbox);
} else {
// inbox storage has not been initialized yet. Get messages from server in case this is a re-install
this.syncInbox().catch(() => {});
}
}
async _writeInboxToStorage() {
RTCP.debugLog && this.log("Writing Inbox to storage");
await DefaultPreference.set("rtcp_last_inbox_sync", this._lastInboxSync.toISOString());
await DefaultPreference.set("rtcp_inbox", JSON.stringify(this._inbox));
}
_startReadReceiptTimer(delay) {
// stop existing timer
if (this._readReceiptTimer != null) {
clearTimeout(this._readReceiptTimer);
this._readReceiptTimer = null;
AppState.removeEventListener("change", this._sendReceiptsOnAppClose);
}
// start new timer
this._readReceiptTimer = setTimeout(async () => {
await RTCP.sendReadReceipt(this._readReceiptQueue);
this._readReceiptQueue = [];
this._readReceiptTimer = null;
AppState.removeEventListener("change", this._sendReceiptsOnAppClose);
}, delay);
if (delay > 0) {
AppState.addEventListener("change", this._sendReceiptsOnAppClose);
}
}
_sendReceiptsOnAppClose = (nextAppState) => {
if (nextAppState !== "active") {
// send out immediately when app goes inactive
this._startReadReceiptTimer(0);
}
};
} |
JavaScript | class Tooltip extends React.Component {
static propTypes = {
style: PropTypes.object,
show: PropTypes.bool,
/**
* Desired horizontal position of the tooltip.
*/
horizontalPosition: PropTypes.oneOf([ 'left', 'center', 'right' ])
};
state = {
/**
* Overflow-prevented horizontal position of the tooltip.
*/
horizontalPosition: this.props.horizontalPosition,
/**
* Whether the tooltip element is currently in the DOM.
*/
insert: this.props.show,
/**
* Whether the tooltip element is currently visible.
*/
show: this.props.show
};
componentWillReceiveProps(nextProps) {
if (!this.props.show && nextProps.show) {
this.show();
}
if (this.props.show && !nextProps.show) {
this.hide();
}
}
/**
* Clear the fade-out animation timeout.
*/
clearTimeout() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
/**
* Show the tooltip.
*/
show() {
this.clearTimeout();
this.setState({ insert: true }, () => {
this.position();
this.setState({ show: true });
});
}
/**
* Hide the tooltip.
*/
hide() {
if (this.timeout) {
return;
}
// First hide it,
this.setState({ show: false }, () => {
// Then wait for the fade-out animation,
this.timeout = setTimeout(() => {
// And finally remove the element.
this.setState({
insert: false,
// The horizontal position is reset here, so that the next time the
// tooltip is shown, the positioning checks run on the original
// position. Otherwise, it might getBoundingClientRect() from an
// already-repositioned element, discover that it is fits, and go back
// to the initial state even if it did not fit.
horizontalPosition: this.props.horizontalPosition
});
}, 450);
});
}
/**
* Reposition the tooltip if it is close to the window border.
*/
position() {
if (!this.tooltip) {
return;
}
// eslint-disable-next-line react/no-find-dom-node
const rect = findDOMNode(this.tooltip).getBoundingClientRect();
this.setState({
horizontalPosition: rect.right > window.innerWidth ? 'left' :
this.props.horizontalPosition
});
}
refTooltip = (tooltip) => {
this.tooltip = tooltip;
};
render() {
const { insert, show } = this.state;
return (
<div className="u-TooltipFix">
{insert && (
<MuiTooltip
ref={this.refTooltip}
{...this.props}
show={show}
horizontalPosition={this.state.horizontalPosition}
style={{
// "pointer-events: none" avoids interference with tooltips that
// are very close to or overlay other elements that have tooltips.
pointerEvents: 'none',
...this.props.style
}}
/>
)}
</div>
);
}
} |
JavaScript | class Content {
constructor(input = {}) {
const { card = null, collection = null, collectionBrowse = null, image = null, list = null, media = null, table = null, } = input;
if (card) {
this.card = card;
}
if (collection) {
this.collection = collection;
}
if (collectionBrowse) {
this.collectionBrowse = collectionBrowse;
}
if (image) {
this.image = image;
}
if (list) {
this.list = list;
}
if (media) {
this.media = media;
}
if (table) {
this.table = table;
}
}
} |
JavaScript | class Option {
constructor(name, click, visible = visibleFunc) {
this.name = name;
this.click = click;
this.visible = visible;
}
} |
JavaScript | class Matches extends Flow.Component {
constructor(id =null) {
super(id);
this.name = 'Matches';
let text = new Flow.Property('Text', 'text');
text.required = true;
this.addProperty(text);
// a regular expression object
text = new Flow.Property('Match', 'object');
text.required = true;
this.addProperty(text);
const done = new Flow.Port('Done');
done.addProperty(new Flow.Property('Result', 'list'));
this.addPort(done);
this.attachTask(function() {
let match = this.getProperty('Match').data;
let text = this.getProperty('Text').data;
let port = this.getPort('Done');
port.getProperty('Result').data = text.match(match);
port.emit();
this.taskComplete();
});
}
} |
JavaScript | class SourceSelector extends React.Component {
constructor(props) {
super(props);
this._sourceToOption = source => {
const label = this._getLabelFromSource(source);
return {
value: source,
label,
selectedLabel: label
};
};
this._disposables = new (_UniversalDisposable().default)();
this.state = {
selectableSources: [],
selectedSource: null
};
}
_getNewlySelectedSource(selectedSource, projectPaths, deserializedProjectPath) {
let newSelectedSource = null;
if (selectedSource != null) {
newSelectedSource = projectPaths.includes(selectedSource) ? selectedSource : null;
}
if (newSelectedSource == null && projectPaths.length > 0) {
const matches = projectPaths.filter(projectPath => projectPath.projectPath === deserializedProjectPath);
newSelectedSource = matches.length > 0 ? matches[0] : projectPaths[0];
}
return newSelectedSource;
}
componentDidMount() {
this._disposables.add((0, _utils().observeProjectPathsAllFromSourcePathsService)(projectPaths => {
const newSelectedSource = this._getNewlySelectedSource( // TODO: (wbinnssmith) T30771435 this setState depends on current state
// and should use an updater function rather than an object
// eslint-disable-next-line react/no-access-state-in-setstate
this.state.selectedSource, projectPaths, this.props.deserialize());
this.setState({
selectableSources: projectPaths,
selectedSource: newSelectedSource
});
}));
}
componentWillUnmount() {
this._disposables.dispose();
}
_getLabelFromSource(source) {
const {
projectPath,
hostLabel
} = source;
const basename = _nuclideUri().default.basename(projectPath);
return hostLabel + ' - ' + basename;
}
setState(partialState, callback) {
const fullState = Object.assign({}, this.state, partialState);
super.setState(fullState, () => {
var _ref;
this.props.onSelect((_ref = fullState) != null ? (_ref = _ref.selectedSource) != null ? _ref.projectPath : _ref : _ref);
callback && callback();
});
}
render() {
const {
selectableSources,
selectedSource
} = this.state;
const options = selectableSources.map(this._sourceToOption);
if (options.length === 0) {
return React.createElement("div", null, "No Projects Found. Please add a project to your file tree so the debugger can find sources.");
}
const potentiallyWrongSourceLabel = selectedSource != null && !selectedSource.suggested ? React.createElement("label", null, "Nuclide is not sure that you have selected a project which contains sources the debugger can use. Please double check that your selected source is correct.") : null;
return React.createElement("div", null, React.createElement(_Dropdown().Dropdown, {
options: options,
onChange: option => this.setState({
selectedSource: option
}),
placeholder: 'Select a source',
value: selectedSource
}), potentiallyWrongSourceLabel);
}
} |
JavaScript | class PaymentPending extends Component {
static propTypes = {
/** @ignore */
t: PropTypes.func.isRequired,
/** @ignore */
theme: PropTypes.object.isRequired,
/** @ignore */
themeName: PropTypes.string.isRequired,
/** @ignore */
isFetchingTransactionDetails: PropTypes.bool.isRequired,
/** @ignore */
hasErrorFetchingTransactionDetails: PropTypes.bool.isRequired,
/** @ignore */
activeTransaction: PropTypes.object,
/** @ignore */
transactionId: PropTypes.string,
/** @ignore */
fetchTransactionDetails: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
const { t } = props;
this.state = {
appState: AppState.currentState,
subtitle: t('moonpay:paymentPendingExplanation'),
buttonText: t('moonpay:viewReceipt'),
hasErrorFetchingTransactionDetails: false,
};
this.handleAppStateChange = this.handleAppStateChange.bind(this);
this.onButtonPress = this.onButtonPress.bind(this);
}
componentDidMount() {
AppState.addEventListener('change', this.handleAppStateChange);
const { activeTransaction, t } = this.props;
const status = get(activeTransaction, 'status');
if (status === MOONPAY_TRANSACTION_STATUSES.completed) {
this.redirectToScreen('paymentSuccess');
} else if (status === MOONPAY_TRANSACTION_STATUSES.failed) {
this.redirectToScreen('paymentFailure');
} else if (status === MOONPAY_TRANSACTION_STATUSES.waitingAuthorization) {
this.setState({
subtitle: t('moonpay:pleaseComplete3DSecure'),
buttonText: t('global:continue'),
});
}
}
componentWillReceiveProps(nextProps) {
const { activeTransaction, t } = nextProps;
if (this.props.isFetchingTransactionDetails && !nextProps.isFetchingTransactionDetails) {
if (nextProps.hasErrorFetchingTransactionDetails) {
this.setState({
subtitle: t('moonpay:errorGettingTransactionDetails'),
buttonText: t('moonpay:tryAgain'),
hasErrorFetchingTransactionDetails: true,
});
} else {
const status = get(activeTransaction, 'status');
if (status === MOONPAY_TRANSACTION_STATUSES.completed) {
this.redirectToScreen('paymentSuccess');
} else if (status === MOONPAY_TRANSACTION_STATUSES.failed) {
this.redirectToScreen('paymentFailure');
} else if (status === MOONPAY_TRANSACTION_STATUSES.waitingAuthorization) {
this.setState({
subtitle: t('moonpay:pleaseComplete3DSecure'),
buttonText: t('global:complete'),
});
} else if (status === MOONPAY_TRANSACTION_STATUSES.pending) {
this.setState({
subtitle: t('moonpay:paymentPendingExplanation'),
buttonText: t('moonpay:viewReceipt'),
});
}
}
}
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
}
/**
* Handles app state changes
*
* @method handleAppStateChange
*
* @param {string} nextAppState
*
* @returns {void}
*/
handleAppStateChange(nextAppState) {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
const { activeTransaction, isFetchingTransactionDetails, transactionId } = this.props;
if (
!isFetchingTransactionDetails &&
get(activeTransaction, 'status') === MOONPAY_TRANSACTION_STATUSES.waitingAuthorization
) {
this.props.fetchTransactionDetails(transactionId || get(activeTransaction, 'id'));
this.setState({ hasErrorFetchingTransactionDetails: false });
}
}
this.setState({ appState: nextAppState });
}
/**
* Navigates to chosen screen
*
* @method redirectToScreen
*/
redirectToScreen(screen) {
navigator.push(screen);
}
/**
* On (Single) button press callback handler
*
* @method onButtonPress
*
* @returns {void}
*/
onButtonPress() {
const { activeTransaction } = this.props;
if (get(activeTransaction, 'status') === MOONPAY_TRANSACTION_STATUSES.waitingAuthorization) {
Linking.openURL(get(activeTransaction, 'redirectUrl'));
} else {
this.redirectToScreen('purchaseReceipt');
}
}
render() {
const {
activeTransaction,
transactionId,
t,
theme: { body },
themeName,
isFetchingTransactionDetails,
} = this.props;
const { hasErrorFetchingTransactionDetails, subtitle, buttonText } = this.state;
const textColor = { color: body.color };
return (
<View style={[styles.container, { backgroundColor: body.bg }]}>
<View style={styles.topContainer}>
<AnimatedComponent
animationInType={['slideInRight', 'fadeIn']}
animationOutType={['slideOutLeft', 'fadeOut']}
delay={400}
>
<Header iconSize={width / 3} iconName="moonpay" textColor={body.color} />
</AnimatedComponent>
</View>
<View style={styles.midContainer}>
<View style={{ flex: 0.2 }} />
<AnimatedComponent
animationInType={['slideInRight', 'fadeIn']}
animationOutType={['slideOutLeft', 'fadeOut']}
delay={266}
>
<InfoBox>
<Text style={[styles.infoText, textColor]}>{t('moonpay:paymentPending')}</Text>
<Text style={[styles.infoTextRegular, textColor, { paddingTop: height / 60 }]}>
{subtitle}
</Text>
</InfoBox>
</AnimatedComponent>
<View style={{ flex: 0.4 }} />
<AnimatedComponent
animationInType={['fadeIn', 'slideInRight']}
animationOutType={['fadeOut', 'slideOutLeft']}
delay={200}
style={styles.animation}
>
<LottieView
source={getAnimation('onboardingComplete', themeName)}
loop={false}
autoPlay
style={styles.animation}
/>
</AnimatedComponent>
</View>
<View style={styles.bottomContainer}>
<AnimatedComponent animationInType={['fadeIn']} animationOutType={['fadeOut']}>
{hasErrorFetchingTransactionDetails ? (
<DualFooterButtons
onLeftButtonPress={() => navigator.setStackRoot('home')}
onRightButtonPress={() => {
this.props.fetchTransactionDetails(transactionId || get(activeTransaction, 'id'));
this.setState({
hasErrorFetchingTransactionDetails: false,
});
}}
leftButtonText={t('global:close')}
rightButtonText={t('global:tryAgain')}
leftButtonTestID="moonpay-back-to-home"
rightButtonTestID="moonpay-purchase-receipt"
/>
) : (
<SingleFooterButton
isLoading={isFetchingTransactionDetails}
onButtonPress={this.onButtonPress}
buttonText={buttonText}
/>
)}
</AnimatedComponent>
</View>
</View>
);
}
} |
JavaScript | class Node {
constructor(value) {
this.value = value;
this.prev = this;
this.next = this;
}
} |
JavaScript | class Texture{
constructor( w, h, iformat, format, type, options={} ){
this.gl = cgl.gl ;
this.texture = gl.createTexture() ;
this.width = w ;
this.height = h ;
this.internalFormat = readGlOption( iformat, 'rgba32f' ,
'No internal format provided, assuming RBGA32F' ) ;
this.format = readGlOption( format , 'rgba' ) ;
this.type = readGlOption( type, 'float' ) ;
this.data = readOption( options.data ,
null ) ;
this.wrapS = readGlOption( options.wrapS ,
gl.CLAMP_TO_EDGE ) ;
this.wrapT = readGlOption( options.wrapT ,
gl.CLAMP_TO_EDGE ) ;
this.minFilter = readGlOption( options.minFilter,
gl.NEAREST ) ;
this.magFilter = readGlOption( options.magFilter,
gl.NEAREST ) ;
/*------------------------------------------------------------------------
* bind and set texture
*------------------------------------------------------------------------
*/
gl.bindTexture( gl.TEXTURE_2D, this.texture ) ;
gl.texParameteri( gl.TEXTURE_2D,
gl.TEXTURE_WRAP_S,
this.wrapS ) ;
gl.texParameteri( gl.TEXTURE_2D,
gl.TEXTURE_WRAP_T,
this.wrapT ) ;
gl.texParameteri( gl.TEXTURE_2D,
gl.TEXTURE_MIN_FILTER,
this.minFilter ) ;
gl.texParameteri( gl.TEXTURE_2D,
gl.TEXTURE_MAG_FILTER,
this.magFilter ) ;
gl.texImage2D( gl.TEXTURE_2D, 0 ,
this.internalFormat,
this.width, this.height, 0,
this.format,
this.type,
this.data ) ;
gl.bindTexture( gl.TEXTURE_2D, null ) ;
}
/*------------------------------------------------------------------------
* setWrapS
*------------------------------------------------------------------------
*/
setWrapS(wrapS){
this.wrapS = readGlOption(wrapS, this.wrapS ) ;
gl.bindTexture( gl.TEXTURE_2D, this.texture ) ;
gl.texParameteri( gl.TEXTURE_2D,
gl.TEXTURE_WRAP_S,
this.wrapS ) ;
gl.bindTexture( gl.TEXTURE_2D, null ) ;
}
/*------------------------------------------------------------------------
* setWrapT
*------------------------------------------------------------------------
*/
setWrapT(wrapT){
this.wrapT = readGlOption(wrapT, this.wrapT ) ;
gl.bindTexture( gl.TEXTURE_2D, this.texture ) ;
gl.texParameteri( gl.TEXTURE_2D,
gl.TEXTURE_WRAP_T,
this.wrapT ) ;
gl.bindTexture( gl.TEXTURE_2D, null ) ;
return ;
}
/*------------------------------------------------------------------------
* setMinFilter
*------------------------------------------------------------------------
*/
setMinFilter(minFilter){
this.minFilter = readOption(minFilter, this.minFilter ) ;
gl.bindTexture( gl.TEXTURE_2D, this.texture ) ;
gl.texParameteri( gl.TEXTURE_2D,
gl.TEXTURE_MIN_FILTER,
this.minFilter ) ;
gl.bindTexture( gl.TEXTURE_2D, null ) ;
}
/*------------------------------------------------------------------------
* setMagFilter
*------------------------------------------------------------------------
*/
setMagFilter(magFilter){
this.magFilter = readOption(magFilter, this.magFilter ) ;
gl.bindTexture( gl.TEXTURE_2D, this.texture ) ;
gl.texParameteri( gl.TEXTURE_2D,
gl.TEXTURE_MAG_FILTER,
this.magFilter ) ;
gl.bindTexture( gl.TEXTURE_2D, null ) ;
}
/*------------------------------------------------------------------------
* updateData
*------------------------------------------------------------------------
*/
updateData( newData ){
gl.bindTexture(gl.TEXTURE_2D, this.texture) ;
this.data = readOption( newData, this.data ) ;
gl.texImage2D( gl.TEXTURE_2D, 0 , this.internalFormat,
this.width, this.height, 0, this.format, this.type ,
this.data ) ;
gl.bindTexture(gl.TEXTURE_2D, null) ;
}
/*------------------------------------------------------------------------
* resize
*------------------------------------------------------------------------
*/
resize(width,height){
this.width = width ;
this.height = height ;
gl.bindTexture(gl.TEXTURE_2D, this.texture) ;
gl.texImage2D( gl.TEXTURE_2D, 0 , this.internalFormat,
this.width,
this.height, 0, this.format, this.type, null ) ;
}
} |
JavaScript | class Uint32Texture extends Texture{
constructor(w,h,options={}){
super( w,h, 'rgba32ui','rgba_integer', 'unsigned_int' , options) ;
}
} |
JavaScript | class Int32Texture extends Texture{
constructor(w,h, options={}){
super(w,h,'rgba32i','rgba_integer','int',options) ;
}
} |
JavaScript | class Float32Texture extends Texture{
constructor(w,h,options={}){
super(w,h,'rgba32f','rgba','float',options) ;
}
resize( width, height ){
var target = {} ;
target.texture = this.texture ;
target.width = this.width ;
target.height = this.height ;
this.temp = new Float32Texture( this.width, this.height) ;
copyTexture(target, this.temp ) ;
this.width = width ;
this.height = height ;
gl.bindTexture(gl.TEXTURE_2D, this.texture) ;
gl.texImage2D( gl.TEXTURE_2D, 0 , gl.RGBA32F,
this.width,
this.height, 0, gl.RGBA, gl.FLOAT, null ) ;
copyTexture(this.temp, target ) ;
}
} |
JavaScript | class Storage{
constructor(options={}){
this.storage = localStorage ;
this.prefix = readOption( options.prefix, "") ;
}
/*------------------------------------------------------------------------
* store
*------------------------------------------------------------------------
*/
store(name, value){
this.storage.setItem(this.prefix+name, value) ;
}
/*------------------------------------------------------------------------
* get
*------------------------------------------------------------------------
*/
get(name){
return this.storage.getItem(this.prefix+name) ;
}
/*------------------------------------------------------------------------
* getFloat
*------------------------------------------------------------------------
*/
getFloat(name){
return parseFloat(this.get(name)) ;
}
/*------------------------------------------------------------------------
* storeList
*------------------------------------------------------------------------
*/
storeList( names, values ){
for(var i=0; i<names.length; i++){
this.store(names[i], values[i]) ;
}
}
/*------------------------------------------------------------------------
* restoreFloatList
*------------------------------------------------------------------------
*/
restoreFloatList( vars, names ){
for(var i=0; i< vars.length ; i++){
vars[i] = this.getFloat( names[i]) ;
}
}
/*------------------------------------------------------------------------
* restoreValue
*------------------------------------------------------------------------
*/
restoreValue( variable, name ){
variable = this.get(name) ;
}
/*------------------------------------------------------------------------
* storeAsXML
*------------------------------------------------------------------------
*/
storeAsXML(options={}){
var xml = readOption(options.xml, undefined ) ;
var obj = readOption(options.object,undefined) ;
obj = readOption(options.obj, obj ) ;
if( obj == undefined ){
warn('You need to define "object"') ;
}
var names = readOption(options.names, [] ) ;
function xmlAdd( name, value ){
var type = typeof(value) ;
return '\t<data id="'+
name+
'" type="'
+type+'">'
+value+
'</data>\n' ;
}
var fileName = readOption(options.fileName, 'download.xml') ;
var stream = '<?xml version="1.0" encoding="utf-8"?>\n' ;
stream += '<xml>\n' ;
for( var i=0 ; i< names.length ; i++){
var name = names[i] ;
stream += xmlAdd( name , obj[name] ) ;
}
stream += '</xml>' ;
this.store(xml, stream) ;
}
/*------------------------------------------------------------------------
* restoreFromXML
*------------------------------------------------------------------------
*/
restoreFromXML(options={}){
var xml = readOption(options.xml, undefined ) ;
var obj = readOption(options.object,undefined) ;
obj = readOption(options.obj, obj ) ;
if( obj == undefined ){
warn('You need to define "object"') ;
}
var names = readOption(options.names, undefined , 'You need to define "names"' ) ;
if ( obj == undefined || names == undefined ){
warn( 'Insuficient information was provided' ) ;
warn( 'Exit without loading from XML file') ;
return ;
}
var callback = readOption(options.callback, function(){} ) ;
var stream = this.get(xml) ;
if (stream){
var parser = new DOMParser() ;
var doc = parser.parseFromString(stream, "text/xml") ;
for (var i=0; i<names.length ; i++){
var name = names[i] ;
var v = doc.getElementById(name) ;
var type ;
if (v){
type = v.getAttribute('type') ;
switch (type){
case 'number':
obj[name] = eval( v.innerHTML ) ;
break ;
case 'boolean':
obj[name] = eval( v.innerHTML ) ;
break ;
case 'object':
var strArray = v.innerHTML.split(',') ;
for(var i=0 ; i<strArray.length; i++){
obj[name][i] = eval(strArray[i]) ;
}
break ;
default:
obj[name] = v.innerHTML ;
break ;
}
}
}
callback() ;
}
}
} /* end of Storage Class */ |
JavaScript | class Gui{
constructor(){
this.panels = [] ;
}
/*------------------------------------------------------------------------
* create a new panel and add it to the gui
*------------------------------------------------------------------------
*/
addPanel(options={}){
var panel = new GUI.GUI(options) ;
this.panels.push(panel) ;
return panel ;
}
/*------------------------------------------------------------------------
* updateControllersDisplay : update display for all conrolers
*------------------------------------------------------------------------
*/
updateControllersDisplay( controllers, verbose ){
for(var c in controllers ){
if(verbose) log('Controller : ', c) ;
controllers[c].updateDisplay() ;
if( typeof(controllers[c].__onChange) == 'function'){
if (verbose) log('running onChange') ;
controllers[c].__onChange() ;
}
}
}
/*------------------------------------------------------------------------
* updateFolderDisplay : update display for all subfolder of a folder
*------------------------------------------------------------------------
*/
updateFolderDisplay( folder ,verbose ){
for(var fldr in folder.__folders ){
if (verbose) log( 'Entering folder :', fldr ) ;
this.updateFolderDisplay(folder.__folders[fldr], verbose) ;
}
this.updateControllersDisplay( folder.__controllers , verbose ) ;
}
/*------------------------------------------------------------------------
* updateDisplay : updates all gui displays and runs onChange
* callback functions
*------------------------------------------------------------------------
*/
updateDisplay(options={}){
var verbose = readOption(options.verbose, false ) ;
for(var panel in this.panels){
this.updateFolderDisplay(this.panels[panel], verbose) ;
}
}
/*------------------------------------------------------------------------
* update : forks updateDisplay
*------------------------------------------------------------------------
*/
update(options={}){
this.updateDisplay(options) ;
}
} |
JavaScript | class SQLDBDriver {
/**
* Constructor
* @param {Object} configuration - configuration
*/
constructor(config) {
this.db = new Sequelize(
config.database,
config.username,
config.password,
{
host: config.host,
dialect: config.dialect,
storage: config.storage,
},
);
this.definitions = {};
this.models = {};
}
/**
* Add a models to the DB
* @param {Object} model - the model definition
*/
addModel(modelDefinition) {
this.definitions[modelDefinition.name] = modelDefinition;
this.models[modelDefinition.name] = this.db.define(
modelDefinition.name,
mapFields(modelDefinition.fields),
);
}
/**
* Get access to the model.
* @param {string} name - name of the model to retrieve.
*/
getModel(name) {
const wrappedModel = dataTransformProxy(
wrapper(this.models[name]),
this.definitions[name],
);
return validateProxy(
wrappedModel,
this.definitions[name],
);
}
/**
* Synchronizes the data base.
* @returns {Promise}
*/
sync() {
relateModels(this.definitions, this.models);
const promises = Object.keys(this.models)
.map(n => this.models[n].sync({ force: false }));
return new Promise((resolve) => {
Promise.all(promises).then(() => {
resolve(this);
});
});
}
} |
JavaScript | class BitcoinOutPoint {
/**
* Instantiate a new `BitcoinOutPoint`.
*
* See the class properties for expanded information on these parameters.
*
* @property {Uint8Array|Buffer} hash
* @property {number} n
* @constructs BitcoinOutPoint
*/
constructor (hash, n) {
this.hash = hash
this.n = n
}
/**
* Convert to a serializable form that has nice stringified hashes and other simplified forms. May be
* useful for simplified inspection.
*/
toJSON () {
return Object.assign({}, this, {
hash: toHashHex(this.hash)
})
}
} |
JavaScript | class BotUtil {
/**
* @param {Client} client - The client to use
* @param {SettingStorage} settings - The setting storage to use
* @param {BotConfig} config - The bot config to use
*/
constructor(client, settings, config) {
if(!client || !settings || !config) throw new Error('A client, settings, and config must be specified.');
/** @type {Client} */
this.client = client;
/** @type {SettingStorage} */
this.settings = settings;
/** @type {BotConfig} */
this.config = config;
/**
* @type {PatternConstants}
* @see {@link BotUtil.patterns}
*/
this.patterns = patterns;
}
/**
* Build a command usage string
* @param {string} command - The short command string (ex. "roll d20")
* @param {Guild|string} [guild] - The guild or guild ID to use the prefix of
* @param {boolean} [onlyMention=false] - Whether or not the usage string should only show the mention form
* @return {string} The command usage string
* @see {@link BotUtil.usage}
*/
usage(command, guild = null, onlyMention = false) {
return this.constructor.usage(this.client, this.settings, this.config, command, guild, onlyMention);
}
/**
* Build a command usage string
* @param {Client} client - The client to use
* @param {SettingStorage} settings - The setting storage to use
* @param {BotConfig} config - The bot config to use
* @param {string} command - The short command string (ex. "roll d20")
* @param {Guild|string} [guild] - The guild or guild ID to use the prefix of
* @param {boolean} [onlyMention=false] - Whether or not the usage string should only show the mention form
* @return {string} The command usage string
* @see {@link BotUtil#usage}
*/
static usage(client, settings, config, command, guild = null, onlyMention = false) {
const nbcmd = this.nbsp(command);
if(!guild && !onlyMention) return `\`${nbcmd}\``;
let prefixAddon;
if(!onlyMention) {
let prefix = this.nbsp(settings.getValue(guild, 'command-prefix', config.values.commandPrefix));
if(prefix.length > 1 && !prefix.endsWith('\xa0')) prefix += '\xa0';
prefixAddon = prefix ? `\`${prefix}${nbcmd}\` or ` : '';
}
return `${prefixAddon || ''}\`@${this.nbsp(client.user.username)}#${client.user.discriminator}\xa0${nbcmd}\``;
}
/**
* Build a disambiguation list - useful for telling a user to be more specific when finding partial matches from a command
* @param {Object[]} items - An array of items to make the disambiguation list for
* @param {string} label - The text to refer to the items as (ex. "characters")
* @param {string} [property=name] - The property on items to display in the list
* @return {string} The disambiguation list
* @see {@link BotUtil.disambiguation}
*/
disambiguation(items, label, property = 'name') {
return this.constructor.disambiguation(items, label, property);
}
/**
* Build a disambiguation list - useful for telling a user to be more specific when finding partial matches from a command
* @param {Object[]} items - An array of items to make the disambiguation list for
* @param {string} label - The text to refer to the items as (ex. "characters")
* @param {string} [property=name] - The property on items to display in the list
* @return {string} The disambiguation list
* @see {@link BotUtil#disambiguation}
*/
static disambiguation(items, label, property = 'name') {
const itemList = items.map(item => `"${this.nbsp(property ? item[property] : item)}"`).join(', ');
return `Multiple ${label} found, please be more specific: ${itemList}`;
}
/**
* Paginate an array of items
* @param {Object[]} items - An array of items to paginate
* @param {number} [page=1] - The page to select
* @param {number} [pageLength=10] - The number of items per page
* @return {Object} The resulting paginated object
* @property {Object[]} items - The chunk of items for the current page
* @property {number} page - The current page
* @property {number} maxPage - The maximum page
* @property {number} pageLength - The numer of items per page
* @property {string} pageText - The current page string ("page x of y")
* @see {@link BotUtil.paginate}
*/
paginate(items, page = 1, pageLength = 10) {
return this.constructor.paginate(items, page, pageLength);
}
/**
* Paginate an array of items
* @param {Object[]} items - An array of items to paginate
* @param {number} [page=1] - The page to select
* @param {number} [pageLength=10] - The number of items per page
* @return {Object} The resulting paginated object
* @property {Object[]} items - The chunk of items for the current page
* @property {number} page - The current page
* @property {number} maxPage - The maximum page
* @property {number} pageLength - The numer of items per page
* @property {string} pageText - The current page string ("page x of y")
* @see {@link BotUtil#paginate}
*/
static paginate(items, page = 1, pageLength = 10) {
const maxPage = Math.ceil(items.length / pageLength);
if(page < 1) page = 1;
if(page > maxPage) page = maxPage;
let startIndex = (page - 1) * pageLength;
return {
items: items.length > pageLength ? items.slice(startIndex, startIndex + pageLength) : items,
page: page,
maxPage: maxPage,
pageLength: pageLength,
pageText: `page ${page} of ${maxPage}`
};
}
/**
* Search for matches in a list of items
* @param {Object[]} items - An array of items to search in
* @param {string} searchString - The string to search for
* @param {SearchOptions} options - An options object
* @return {Object[]} The matched items
* @see {@link BotUtil.search}
*/
search(items, searchString, { property = 'name', searchInexact = true, searchExact = true, useStartsWith = false } = {}) {
return this.constructor.search(items, searchString, { property: property, searchInexact: searchInexact, searchExact: searchExact, useStartsWith: useStartsWith });
}
/**
* Search for matches in a list of items
* @param {Object[]} items - An array of items to search in
* @param {string} searchString - The string to search for
* @param {SearchOptions} options - An options object
* @return {Object[]} The matched items
* @see {@link BotUtil#search}
*/
static search(items, searchString, { property = 'name', searchInexact = true, searchExact = true, useStartsWith = false } = {}) {
if(!items || items.length === 0) return [];
if(!searchString) return items;
const lowercaseSearch = searchString.toLowerCase();
let matchedItems;
// Find all items that start with or include the search string
if(searchInexact) {
if(useStartsWith && searchString.length === 1) {
matchedItems = items.filter(element => String(property ? element[property] : element)
.normalize('NFKD')
.toLowerCase()
.startsWith(lowercaseSearch)
);
} else {
matchedItems = items.filter(element => String(property ? element[property] : element)
.normalize('NFKD')
.toLowerCase()
.includes(lowercaseSearch)
);
}
} else {
matchedItems = items;
}
// See if any are an exact match
if(searchExact && matchedItems.length > 1) {
const exactItems = matchedItems.filter(element => String(property ? element[property] : element).normalize('NFKD').toLowerCase() === lowercaseSearch);
if(exactItems.length > 0) return exactItems;
}
return matchedItems;
}
/**
* Splits a string using specified characters into multiple strings of a maximum length
* @param {string} text - The string to split
* @param {number} [maxLength=1925] - The maximum length of each split string
* @param {string} [splitOn=\n] - The characters to split the string with
* @param {string} [prepend] - String to prepend to every split message
* @param {string} [append] - String to append to every split message
* @return {string[]} The split strings
* @see {@link BotUtil.split}
*/
split(text, maxLength = 1925, splitOn = '\n', prepend = '', append = '') {
return this.constructor.split(text, maxLength, splitOn, prepend, append);
}
/**
* Splits a string using specified characters into multiple strings of a maximum length
* @param {string} text - The string to split
* @param {number} [maxLength=1925] - The maximum length of each split string
* @param {string} [splitOn=\n] - The characters to split the string with
* @param {string} [prepend] - String to prepend to every split message
* @param {string} [append] - String to append to every split message
* @return {string[]} The split strings
* @see {@link BotUtil#split}
*/
static split(text, maxLength = 1900, splitOn = '\n', prepend = '', append = '') {
const splitText = text.split(splitOn);
if(splitText.length === 1 && text.length > maxLength) throw new Error('Message exceeds the max length and contains no split characters.');
const messages = [''];
let msg = 0;
for(let i = 0; i < splitText.length; i++) {
if(messages[msg].length + splitText[i].length + 1 > maxLength) {
messages[msg] += append;
messages.push(prepend);
msg++;
}
messages[msg] += (messages[msg].length > 0 && messages[msg] !== prepend ? splitOn : '') + splitText[i];
}
return messages;
}
/**
* Escapes Markdown in the string
* @param {string} text - The text to escape
* @returns {string} The escaped text
* @see {@link BotUtil.escapeMarkdown}
*/
escapeMarkdown(text) {
return this.constructor.escapeMarkdown(text);
}
/**
* Escapes Markdown in the string
* @param {string} text - The text to escape
* @returns {string} The escaped text
* @see {@link BotUtil#escapeMarkdown}
*/
static escapeMarkdown(text) {
return text.replace(/\\(\*|_|`|~|\\)/g, '$1').replace(/(\*|_|`|~|\\)/g, '\\$1');
}
/**
* Convert spaces to non-breaking spaces
* @param {string} text - The text to convert
* @return {string} The converted text
* @see {@link BotUtil.nbsp}
*/
nbsp(text) {
return this.constructor.nbsp(text);
}
/**
* Convert spaces to non-breaking spaces
* @param {string} text - The text to convert
* @return {string} The converted text
* @see {@link BotUtil#nbsp}
*/
static nbsp(text) {
return String(text).replace(spacePattern, nbsp);
}
/**
* @type {PatternConstants}
* @see {@link BotUtil#patterns}
*/
static get patterns() {
return patterns;
}
} |
JavaScript | class Card extends Component {
constructor(properties) {
super(properties);
const { style, ...childProps } = properties; // eslint-disable-line no-unused-vars
this.childProps = childProps;
}
static displayName = 'Card';
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]),
style: PropTypes.object,
};
/**
* Update the childProps based on the updated properties passed to the card.
*/
componentWillReceiveProps(properties) {
const { style, ...childProps } = properties; // eslint-disable-line no-unused-vars
this.childProps = childProps;
}
render() {
const divStyle = { ...cardStyle.style, ...this.props.style };
return (
<div {...this.childProps} style={ divStyle }>
{ this.props.children }
</div>
);
}
} |
JavaScript | class DownloadedBinary extends binary_1.Binary {
constructor(binary) {
super();
this.versions = [];
this.binary = binary;
this.name = binary.name;
this.versionCustom = binary.versionCustom;
}
id() {
return this.binary.id();
}
} |
JavaScript | class BaseStoreModule {
constructor() {
this.namespaced = true;
this.state = {
all: [],
};
this.getters = {
getAll: state => state.all,
};
this.actions = {
async fetchAll({ dispatch }, { service, Transform }) {
const resp = await service.fetchAll();
if (resp && resp.status === 200) {
let results = resp.data;
/* Possibly tranform each row */
if (Transform) {
results = results.map(res => new Transform(res));
}
dispatch('setAll', { results });
}
},
setAll({ commit }, { results }) {
commit(types.SET_ALL, results);
},
clearAll({ commit }) {
commit(types.SET_ALL, []);
},
clearStore({ dispatch }) {
dispatch('setAll', { results: [] });
},
};
this.mutations = {
[types.SET_ALL](state, items) {
state.all = items;
},
};
}
} |
JavaScript | class ComponentOptionsList {
constructor() {
/**
* List of ComponentOptions for the actions registered by each hot keys component.
* @type {ComponentOptions[]}
*/
this._list = [];
/**
* Dictionary mapping the ids of the components defining actions, and their
* position in the list.
* @type {Object.<ComponentId, Number>}
*/
this._idToIndex = {};
/**
* Counter for the length of the longest sequence currently enabled.
* @type {number}
*/
this.longestSequence = 1;
/**
* The id of the component with the longest key sequence
* @type {ComponentId}
*/
this._longestSequenceComponentId = null;
/**
* Record of whether at least one keymap is bound to each event type (keydown,
* keypress or keyup)
* @type {KeyEvent}
*/
this._keyMapEventRecord = KeyEventStateArrayManager.newRecord();
}
/**
* Return a new iterator that can be used to enumerate the list
* @returns {ComponentOptionsListIterator}
*/
get iterator() {
return new ComponentOptionsListIterator(this);
}
/**
* Adds a new hot key component's options, to be parsed and standardised before being
* added to the list
* @param {ComponentId} componentId - Id of the component the options belong to
* @param {KeyMap} actionNameToKeyMap - Map of actions to key maps
* @param {HandlersMap} actionNameToHandlersMap - Map of actions to handlers
* @param {Object} options - Hash of options that configure how the key map is built.
* @param {string} options.defaultKeyEvent - The default key event to use for any
* action that does not explicitly define one.
* @returns {number} The position the component options have in the list
*/
add(componentId, actionNameToKeyMap, actionNameToHandlersMap, options) {
if (this.containsId(componentId)) {
return this.update(
componentId, actionNameToKeyMap, actionNameToHandlersMap, options
);
}
const componentOptions = this._build(
componentId, actionNameToKeyMap, actionNameToHandlersMap, options
);
this._list.push(componentOptions);
const newIndex = this.length - 1;
return this._idToIndex[componentId] = newIndex;
}
/**
* Whether the list contains options for a component with the specified id
* @param {ComponentId} id Id of the component
* @returns {boolean} True if the list contains options for the component with the
* specified id
*/
containsId(id) {
return !!this.getById(id);
}
/**
* Retrieves options for a component from the list
* @param {ComponentId} id Id of the component to retrieve the options for
* @returns {ComponentOptions} Options for the component with the specified id
*/
getById(id) {
return this.getAtPosition(this.getPositionById(id));
}
/**
* Returns the position of the options belonging to the component with the specified
* id.
* @param {ComponentId} id Id of the component to retrieve the options for
* @returns {number} The position of the component options in the list.
*/
getPositionById(id) {
return this._idToIndex[id];
}
/**
* Replaces the options of a component already in the list with new values
* @param {ComponentId} componentId - Id of the component to replace the options of
* @param {KeyMap} actionNameToKeyMap - Map of actions to key maps
* @param {HandlersMap} actionNameToHandlersMap - Map of actions to handlers
* @param {Object} options - Hash of options that configure how the key map is built.
* @param {string} options.defaultKeyEvent - The default key event to use for any
* action that does not explicitly define one.
* @returns {number} The position the component options have in the list
*/
update(componentId, actionNameToKeyMap, actionNameToHandlersMap, options) {
/**
* We record whether we're building new options for the component that currently
* has the longest sequence, to decide whether we need to recalculate the longest
* sequence.
*/
const isUpdatingLongestSequenceComponent =
this._isUpdatingComponentWithLongestSequence(componentId);
const longestSequenceBefore = this.longestSequence;
const componentOptions = this._build(
componentId, actionNameToKeyMap, actionNameToHandlersMap, options
);
if (isUpdatingLongestSequenceComponent &&
componentOptions.sequenceLength !== longestSequenceBefore) {
/**
* Component with the longest sequence has just had new options registered
* so we need to reset the longest sequence
*/
if (componentOptions.sequenceLength > longestSequenceBefore) {
/**
* The same component has registered a longer sequence, so we just
* need to update the sequence length to the new, larger number
*/
this.longestSequence = componentOptions.sequenceLength;
} else {
/**
* The component may no longer have the longest sequence, so we need to
* recalculate
*/
this._recalculateLongestSequence();
}
}
this._list[this.getPositionById(componentId)] = componentOptions;
}
/**
* Removes the options of a component from the list
* @param {ComponentId} id The id of the component whose options are removed
* @returns {void}
*/
remove(id) {
const isUpdatingLongestSequenceComponent =
this._isUpdatingComponentWithLongestSequence(id);
this.removeAtPosition(this.getPositionById(id));
if (isUpdatingLongestSequenceComponent) {
this._recalculateLongestSequence();
}
}
/**
* Whether a component is the root component (the last one in the list)
* @param {ComponentId} id Id of the component to query if it is the root
* @returns {boolean} true if the component is the last in the list
*/
isRoot(id) {
return this.getPositionById(id) >= this.length - 1;
}
/**
* Whether the list contains at least one component with an action bound to a
* particular keyboard event type.
* @param {KeyEventType} keyEventType Index of the keyboard event type
* @returns {boolean} true when the list contains a component with an action bound
* to the event type
*/
anyActionsForEventType(keyEventType) {
return !!this._keyMapEventRecord[keyEventType];
}
/**
* The number of components in the list
* @type {number} Number of components in the list
*/
get length() {
return this._list.length;
}
/**
* The component options at particular position in the list
* @param {number} position The position in the list
* @returns {ComponentOptions} The component options at the position in the list
*/
getAtPosition(position) {
return this._list[position];
}
/**
* Remove the component options at a position in the list
* @param {number} position The position in the list to remove the options
* return {void}
*/
removeAtPosition(position) {
this._list = removeAtIndex(this._list, position);
let counter = position;
while(counter < this.length) {
this._idToIndex[this.getAtPosition(counter).componentId] = counter;
counter++;
}
}
/**
* A plain JavaScript object representation of the component options list that can
* be used for serialization or debugging
* @returns {ComponentOptions[]} plain JavaScript object representation of the list
*/
toJSON() {
return this._list;
}
/**
* Builds the internal representation that described the options passed to a hot keys
* component
* @param {ComponentId} componentId - Id of the component the options belong to
* @param {KeyMap} actionNameToKeyMap - Map of actions to key maps
* @param {HandlersMap} actionNameToHandlersMap - Map of actions to handlers
* @param {Object} options - Hash of options that configure how the key map is built.
* @returns {ComponentOptions} Options for the specified component
* @private
*/
_build(componentId, actionNameToKeyMap, actionNameToHandlersMap, options){
const actions =
this._buildActionDictionary(actionNameToKeyMap, options, componentId);
return {
actions, handlers: actionNameToHandlersMap, componentId, options
};
}
_isUpdatingComponentWithLongestSequence(componentId) {
return componentId === this._getLongestSequenceComponentId();
}
_getLongestSequenceComponentId() {
return this._longestSequenceComponentId;
}
_recalculateLongestSequence() {
const iterator = this.iterator;
while(iterator.next()) {
const {longestSequence, componentId } = iterator.getComponent();
if (longestSequence > this.longestSequence) {
this._longestSequenceComponentId = componentId;
this.longestSequence = longestSequence;
}
}
}
/**
* Returns a mapping between ActionNames and ActionConfiguration
* @param {KeyMap} actionNameToKeyMap - Mapping of ActionNames to key sequences.
* @param {Object} options - Hash of options that configure how the key map is built.
* @param {string} options.defaultKeyEvent - The default key event to use for any
* action that does not explicitly define one.
* @param {ComponentId} componentId Index of the component the matcher belongs to
* @returns {ActionDictionary} Map from ActionNames to ActionConfiguration
* @private
*/
_buildActionDictionary(actionNameToKeyMap, options, componentId) {
return Object.keys(actionNameToKeyMap).reduce((memo, actionName) => {
const keyMapConfig = actionNameToKeyMap[actionName];
const keyMapOptions = function(){
if (isObject(keyMapConfig) && hasKey(keyMapConfig, 'sequences')) {
return arrayFrom(keyMapConfig.sequences)
} else {
return arrayFrom(keyMapConfig);
}
}();
keyMapOptions.forEach((keyMapOption) => {
const { keySequence, keyEventType } =
normalizeActionOptions(keyMapOption, options);
this._addActionOptions(
memo, componentId, actionName, keySequence, keyEventType
);
});
return memo;
}, {});
}
_addActionOptions(memo, componentId, actionName, keySequence, keyEventType) {
const {sequence, combination} = KeySequenceParser.parse(keySequence, {keyEventType});
if (sequence.size > this.longestSequence) {
this.longestSequence = sequence.size;
this._longestSequenceComponentId = componentId;
}
/**
* Record that there is at least one key sequence in the focus tree bound to
* the keyboard event
*/
this._keyMapEventRecord[keyEventType] = KeyEventState.seen;
if (!memo[actionName]) {
memo[actionName] = [];
}
memo[actionName].push({
prefix: sequence.prefix,
actionName,
sequenceLength: sequence.size,
...combination,
});
}
} |
JavaScript | class AttachedPolicies {
constructor() {
this.policies = new Array();
}
/**
* Adds a policy to the list of attached policies.
*
* If this policy is already, attached, returns false.
* If there is another policy attached with the same name, throws an exception.
*/
attach(policy) {
if (this.policies.find(p => p === policy)) {
return; // already attached
}
if (this.policies.find(p => p.policyName === policy.policyName)) {
throw new Error(`A policy named "${policy.policyName}" is already attached`);
}
this.policies.push(policy);
}
} |
JavaScript | class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
"config": null
};
}
// Get the general info, like the captcha sitekey
componentDidMount() {
let self = this;
//Import configuration data
return request({"url": "/api/", "json": true}, function (error, response, body) {
if (error) {
return notification.error(error.message);
}
if (response.statusCode >= 300) {
return notification.error(body.message);
}
//New configuration object
return self.setState({"config": body});
});
}
//Render the links used in the footer
renderFooterLinks() {
let self = this;
let children = [];
let counter = 0;
this.state.config.footer.links.forEach(function (key) {
let item = self.state.config.links[key];
if (typeof item !== "undefined" && item !== null) {
//Check if the children list is not empty to add the separator
if (children.length > 0) {
children.push(React.createElement("div", {"key": counter, "className": "pf-footer-links-separator"}));
counter = counter + 1;
}
//Add the link
let linkProps = {
"key": counter,
"className": "pf-footer-links-link",
"href": item.url,
"target": "_blank"
};
children.push(React.createElement(Link, linkProps, item.text));
//Increment the links counter
counter = counter + 1;
}
});
//Check the number of links added
if (children.length > 0) {
return React.createElement("div", {"className": "pf-footer-links"}, children);
}
}
render() {
//Check if the configuration has been imported
if (this.state.config === null) {
return <Spinner color="primary" style={{"marginTop": "75px"}}/>;
}
else {
//Save the configuration object
let config = this.state.config;
return (
<div>
<Router.HashbangRouter>
<Router.Switch>
<Router.Route exact path="/login" component={Login} props={config}/>
<Router.Route exact path="/authorize" component={Authorize} props={config}/>
<Router.Route exact path="/register" component={Register} props={config}/>
<Router.Route path="/resetpwd" component={ResetPwd} props={config}/>
<Router.Route path="/dashboard" component={Dashboard} props={config}/>
<Router.Route path="/" component={Login} props={config}/>
</Router.Switch>
</Router.HashbangRouter>
<Footer size="medium" className="pf-footer" align="center">
{this.renderFooterLinks()}
<div className="pf-footer-logo pf-logo"></div>
<div className="pf-footer-legal">
Powered by <strong>PassFort</strong>
</div>
</Footer>
</div>
);
}
}
} |
JavaScript | class Animal {
//constructor(baw) {
// this.baw = baw;
//}
say() {
console.log(this.baw);
}
} |
JavaScript | class UsageTransaction {
/**
* Create a UsageTransaction.
* @member {date} [timestamp]
* @member {number} [email]
* @member {number} [sms]
*/
constructor(data = {}) {
this.timestamp = new Date(data.timestamp);
this.email = data.email || 0;
this.sms = data.sms || 0;
}
} |
JavaScript | class Timeout {
/**
* @function constructor
* @param {Function} fn - Method to run on timeout
* @param {number} wait - Number of milliseconds to wait for execution
*/
constructor(fn, wait) {
this.wait = wait;
if (wait === -1)
return;
this.executed = false;
this.id = setTimeout(() => {
fn(() => {
this.executed = true;
});
}, wait);
}
/**
* Ends execution
*
* @function stop
*/
stop() {
clearTimeout(this.id);
}
} |
JavaScript | class View extends Backbone.View {
/**
* Load the template file.
* @param {String} templatePath - The path.
*/
initializeTemplate(templatePath) {
this.template = Handlebars.compile(fs.readFileSync(templatePath, 'utf8'));
}
} |
JavaScript | class Server {
static _reqs = {};
static addRequest(hash, canceller) {
if (hash)
Server._reqs['e' + hash] = {
hash,
canceller
}
}
static removeRequest(hash) {
delete Server._reqs['e' + hash];
}
static hookLoginRequire = () => {};
static hook403 = () => {};
static hookAll = () => {};
static start() {}
static end() {}
static requestCount = 0;
static beforSend() {
Server.requestCount++;
Server.start(Server.requestCount);
}
static afterRecieve() {
Server.requestCount--;
if (Server.requestCount < 0)
Server.requestCount = 0;
Server.end(Server.requestCount);
}
static checkuser(h) {
Server.hookLoginRequire(h);
}
static errorHooks(e) {
Server.hookAll();
switch (e) {
case 403:
Server.hook403();
break;
default:
}
}
static errorHandler(options, status) {
if (500 <= status && status < 600) {
if (options.e500 && typeof options.e500 === "function")
options.e500(status);
}
else if (400 <= status && status < 500) {
if (options.e500 && typeof options.e500 === "function")
options.e400(status);
}
else if (300 <= status && status < 400) {
if (options.e500 && typeof options.e500 === "function")
options.e300(status);
}
else if (100 <= status && status < 200) {
if (options.e500 && typeof options.e500 === "function")
options.e400(status);
}
if (options.error && typeof options.error === "function") {
options.error(status);
}
}
static timeOut = 12000;
static axiosInstance = null;
static getAxios() {
if (!Server.axiosInstance)
Server.axiosInstance = axios.create({
onDownloadProgress: (/*e*/) => {}
});
return Server.axiosInstance;
}
static controller(cont, meth, params, options) {
options = options || {
cache: false,
timeout: Server.timeOut,
method: 'GET'
};
options.cancel = options.cancel || Server.generalCancel;
options.method = options.method || "get";
options.method = options
.method
.toLowerCase()
let timeout = options.timeOut || Server.timeOut;
let cache = options.cache || false;
let hash = "";
if (process.env.NODE_ENV === "development")
hash = `${cont}/${meth}.ctrl/${params
? JSON.stringify(params)
: ""}`;
else
hash = hashcode({cont, meth, params});
// if(options.cache) hash=hashcode({cont,meth,params});
// hash=`${cont}/${meth}.ctrl/${params?hashcode(params):""}`;
let prom = new Promise((res, rej) => {
tmpLocalForage
.getItem(hash)
.then(a => {
if (cache && a) {
return res(a);
}
Server.beforSend();
const pars = options.method === "get"
? params
: null;
const dats = options.method === "post"
? objectToFormData(params)
: null;
var ct = undefined;
axios({
// ax({
method: options.method,
url: `${cont}/${meth}.ctrl`,
params: pars,
data: dats,
timeout: timeout,
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
}).then(d => {
Server.removeRequest(hash);
Server.afterRecieve();
if (d.data && d.data.header) {
Server.checkuser(d.data.header.userState);
tmpLocalForage.setItem(hash, d.data);
if (d.data.header.result !== 0)
rej(d.data);
else
res(d.data);
}
else {
tmpLocalForage.setItem(hash, d.data);
res(d.data);
}
}).catch(d => {
Server.removeRequest(hash);
if (d && d.data && d.data.header)
Server.checkuser(d.data.header.userState);
Server.afterRecieve();
if (d.request) {
Server.errorHooks(d.request.status);
rej(d.request.status);
} else {
Server.errorHooks(d);
rej(d);
}
// Server.errorHandler(options, d.request.status);
});
Server.addRequest(hash, ct);
});
});
return prom;
}
static dvm(name, params, options) {
options = options || {
cache: false,
timeout: Server.timeOut,
cancel: Server.generalCancel
};
let timeout = options.timeOut || Server.timeOut;
let cache = options.cache || false;
let hash = "";
if (process.env.NODE_ENV === "development")
hash = `${name}${params
? JSON.stringify(params)
: ""}`;
else
hash = hashcode({name, params});
// hash = `${name}.dvm/${params ? hashcode(params) : ""}`;
return new Promise((res, rej) => {
tmpLocalForage
.getItem(hash)
.then(a => {
if (cache && a) {
return res(a);
}
Server.beforSend();
axios({method: "get", url: `${name}.dvm`, params: params, timeout: timeout}).then(d => {
Server.afterRecieve();
tmpLocalForage.setItem(hash, d.data);
Server.checkuser(d.data.header.userState);
if (d.header) {
if (d.header.result !== 0)
res(d.data);
}
else
res(d.data);
}
).catch(d => {
if (d && d.data && d.data.header)
Server.checkuser(d.data.header.userState);
Server.afterRecieve();
Server.errorHooks(d.request.status);
rej(d.request.status);
// Server.errorHandler(options, d.request.status);
});
});
});
}
static get(url, params, options) {
options = options || { catch: false,
timeout: Server.timeOut
};
let timeout = options.timeOut || Server.timeOut;
return axios({
method: "get",
url,
params,
timeout,
config: {
headers: {
'Content-Type': 'multipart/form-data',
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "GET,POST,PUT"
//Access-Control-Allow-Origin: https://www.bobank.com
}
}
}).then(a => a.data);
}
} |
JavaScript | class apiNetwork {
constructor() {
this.layers = {}
}
/**
* Adds a new layer to the layer json with given amount of nodes
*
* @param numLayersToAdd
* @param numNodesInLayer
*/
addLayers(numLayersToAdd = 1, numNodesInLayer = 1) {
for (let i = 0; i < numLayersToAdd; i++) {
const numOfLayers = Object.keys(this.layers).length;
this.layers[`layer ${numOfLayers + 1}`] = {
'activation': 'sigmoid',
'neurons': numNodesInLayer,
}
}
}
/**
* Increases the 'neurons' attribute by one in a given layer
*
* @param layerIndex
* @param numNodesAdded
*/
addNodes(layerIndex, numNodesAdded = 1) {
const jsonLayerIndex = Object.keys(this.layers)[layerIndex];
this.layers[jsonLayerIndex].neurons += numNodesAdded;
console.log(this.layers);
}
/**
* Removes a layer from the layers json
*
* @param layerIndex
*/
removeLayer(layerIndex) {
let jsonLayerIndex = Object.keys(this.layers)[layerIndex];
delete this.layers[jsonLayerIndex];
this.renameLayers();
console.log(this.layers);
}
/**
* Decreases the 'neurons' attribute by one in a given layer
*
* @param layerIndex
*/
removeNode(layerIndex) {
const jsonLayerIndex = Object.keys(this.layers)[layerIndex];
this.layers[jsonLayerIndex].neurons -= 1;
}
/**
* Renames all the layers in the network so they are in order
* EG:
* layer 1
* layer 2
* layer 4
*
* Becomes
*
* layer 1
* layer 3
* layer 2
*/
renameLayers() {
const layerKeys = Object.keys(this.layers);
for (let i = 0; i < layerKeys.length; i++) {
let jsonLayerIndex = layerKeys[i];
if (jsonLayerIndex !== `layer ${i + 1}`) {
this.layers[`layer ${i + 1}`] = this.layers[jsonLayerIndex];
delete this.layers[jsonLayerIndex];
}
}
}
wipeLayers() {
this.layers = {}
}
} |
JavaScript | class PluginMetricsProject
{
/**
* Loads any default settings that are not already provided by any user options.
*
* @param {object} ev - escomplex plugin event data.
*
* The following options are:
* ```
* (boolean) noCoreSize - Boolean indicating whether the visibility list is not calculated; default (false).
* ```
*/
onConfigure(ev)
{
ev.data.settings.noCoreSize = typeof ev.data.options.noCoreSize === 'boolean' ?
ev.data.options.noCoreSize : false;
}
/**
* Performs average calculations based on collected report data.
*
* @param {object} ev - escomplex plugin event data.
*/
onProjectAverage(ev)
{
ProjectMetricAverage.calculate(ev.data.projectReport);
}
/**
* Performs initial calculations based on collected report data.
*
* @param {object} ev - escomplex plugin event data.
*/
onProjectCalculate(ev)
{
ProjectMetricCalculate.calculate(ev.data.projectReport, ev.data.pathModule, ev.data.settings);
}
} |
JavaScript | class Invoke {
/**
* Creates an new invoke action
*
* @param {string} command - the command to invoke in the contract
* @param {Array<Argument>} argumentsList - the arguments for the contract
*/
constructor(command, argumentsList) {
this._command = command;
this._arguments = argumentsList;
}
/**
* Creates a new Invoke command from one Argument
*
* @param {string} command - the command to invoke in the contract
* @param {string} argument - name of the argument
* @param {Uint8Array} value - the value of the argument
* @return {Invoke}
*/
static fromArgumentInfo(command, argument, value) {
return new Invoke(command, [new Argument(argument, value)]);
}
/**
* Getter for the command
*
* @return {string}
*/
get command() {
return this._command;
}
/**
* Getter for the arguments
*
* @return {Array<Argument>}
*/
get argumentsList() {
return this._arguments;
}
/**
* Create an object with all the necessary field needed to be a valid message
* in the sense of protobufjs. This object can then be used with the "create"
* method of protobuf
*
* @return {Object}
*/
toProtobufValidMessage() {
return {
command: this._command,
args: this.argumentsList.map(arg => arg.toProtobufValidMessage())
};
}
} |
JavaScript | class Register extends React.Component {
constructor(props) {
super(props);
this.state = {
"done": false,
"loading": false,
"checked": 0
};
this.ref = {
"nameInput": React.createRef(),
"emailInput": React.createRef(),
"pwd1Input": React.createRef(),
"pwd2Input": React.createRef(),
"captcha": React.createRef()
};
//Register the checkboxes elements
let self = this;
this.props.signup.must_agree.forEach(function (key) {
console.log(key);
self.ref[key + "Checkbox"] = React.createRef();
});
//Bind functions
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
this.handleCaptchaError = this.handleCaptchaError.bind(this);
this.redirectToLogin = this.redirectToLogin.bind(this);
}
//Callback for the captcha in case of error
handleCaptchaError() {
return notification.error("Captcha validation error");
}
//Handle checkbox change
handleCheckboxChange(event) {
let checkedNum = this.state.checked;
if (event.nativeEvent.target.checked === true) {
checkedNum = checkedNum + 1;
}
else {
checkedNum = checkedNum - 1;
}
//Update the state
this.setState({"checked": checkedNum});
}
// Register the user with the provided info
handleSubmit() {
let self = this;
let data = {
"name": this.ref.nameInput.current.value,
"email": this.ref.emailInput.current.value,
"pwd": this.ref.pwd1Input.current.value
};
console.log(this.ref);
//Check if the uer has checked all the checkboxes
for (let i = 0; i < this.props.signup.must_agree.length; i++) {
let key = this.props.signup.must_agree[i];
if (this.ref[key + "Checkbox"].current.checked === false) {
//Display error and exit
let name = this.props.links[key].text;
return notification.error("You must agree our " + name + " before creating an account");
}
}
//If the captcha is enabled check it
if (this.props.captcha.enabled === true) {
//data = Object.assign({recaptcha: this.ref.captcha.current.getResponse()}, data);
data.recaptcha = this.ref.captcha.current.getResponse();
if (typeof data.recaptcha !== "string" || data.recaptcha.length === 0) {
return notification.error("Show that you are not a robot");
}
}
//Check if the email is valid
if (data.email.indexOf("@") === -1) {
return notification.error("Invalid email provided");
}
//Check if the password is valid
if (data.pwd.length < 6) {
return notification.error("Password must contain at least 6 characters");
}
//Check if passwords match
if (data.pwd !== this.ref.pwd2Input.current.value) {
return notification.error("Passwords don't match");
}
//Change the state
return this.setState({"loading": true}, function () {
//Do the request
let requestOptions = {
"url": "/api/users",
"method": "post",
"json": true,
"body": data
};
return request(requestOptions, function (error, response, body) {
if (error) {
notification.error(error.message);
return self.setState({"loading": false});
}
if (response.statusCode >= 300) {
notification.error(body.message);
return self.setState({"loading": false});
}
//Show the successful register view
return self.setState({"done": true, "loading": false});
});
});
}
//Perform a redirection
redirectTo(redirectUrl) {
//Check if is not loading
if (this.state.loading === false) {
let query = this.props.request.query;
//Check the continue url
if (typeof query.continueTo === "string") {
redirectUrl = redirectUrl + "?continueTo=" + window.encodeURIComponent(query.continueTo);
}
return redirect(redirectUrl);
}
}
//Redirect to the login screen
redirectToLogin() {
return this.redirectTo("/login");
}
//Render the captcha
renderCaptcha() {
if (this.props.captcha.enabled === true) {
return <Captcha sitekey={this.props.captcha.key} onError={this.handleCaptchaError} ref={this.ref.captcha}/>;
}
}
//Render the checkboxes
renderCheckboxes() {
let self = this;
//Check the number of checkboxes
if (this.props.signup.must_agree.length > 0) {
let children = this.props.signup.must_agree.map(function (key, index) {
let item = self.props.links[key];
let ref = self.ref[key + "Checkbox"];
let itemCheckbox = React.createElement(Checkbox, {"ref": ref, "defaultChecked": false, "onChange": self.handleCheckboxChange})
let itemLink = React.createElement(Link, {"href": item.url, "target": "_blank"}, item.text);
let itemLabel = React.createElement(Label, {}, "I agree with the ", itemLink);
return React.createElement("div", {"key": index}, itemCheckbox, itemLabel);
});
//Return the card with the checkboxes
return React.createElement("div", {}, children);
}
}
//Render the submit button
renderSubmit() {
if (this.state.loading === true) {
return <Spinner color="blue" className="pf-register-loading"/>;
}
else {
let isDisabled = this.state.checked !== this.props.signup.must_agree.length;
return <Btn color="blue" onClick={this.handleSubmit} fluid disabled={isDisabled}>Create account</Btn>;
}
}
render() {
if (this.state.done === true) {
return (
<div className="pf-register-content pf-register-success">
<Heading type="h2" align="center">Register completed</Heading>
<Small className="pf-register-subtitle" align="center">
Thanks for creating an account in <strong>{this.props.name}</strong>. You can now continue with your signup:
</Small>
<Btn color="green" onClick={this.redirectToLogin} fluid>Continue</Btn>
</div>
);
}
else {
return (
<div className="pf-register-content">
<Heading type="h2" align="center">Register</Heading>
<Small className="pf-register-subtitle" align="center">
Fill the following fields to create a new <b>{this.props.name}</b> account. All of them are required.
</Small>
<div>
{/*Name input*/}
<Field>
<FieldLabel>Name</FieldLabel>
<Input ref={this.ref.nameInput} maxLength="16" type="text" fluid/>
<FieldHelper>
What should we call you?
</FieldHelper>
</Field>
{/*Email input*/}
<Field>
<FieldLabel>Email</FieldLabel>
<Input ref={this.ref.emailInput} type="text" fluid/>
<FieldHelper>
We will never share your email address with anyone without your permission.
</FieldHelper>
</Field>
{/*Password input*/}
<Field>
<FieldLabel>Password</FieldLabel>
<Input ref={this.ref.pwd1Input} type="password" fluid/>
<FieldHelper>Your password should contain at least 6 characters.</FieldHelper>
</Field>
{/*Password input*/}
<Field>
<FieldLabel>Repeat password</FieldLabel>
<Input ref={this.ref.pwd2Input} type="password" fluid/>
<FieldHelper>
For security reasons please type again your password.
</FieldHelper>
</Field>
{/*Checkboxes*/}
{this.renderCheckboxes()}
{/*Captcha*/}
{this.renderCaptcha()}
{/*Notice*/}
<Small className="pf-register-privacy" align="center">
Check that all the information is correct and click on <b>"Create account"</b>
</Small>
{/*Register*/}
{this.renderSubmit()}
{/*Login*/}
<Field className="pf-register-login">
<FieldLabel align="center">Are you already registered?</FieldLabel>
<Btn color="green" onClick={this.redirectToLogin} fluid>Log in</Btn>
</Field>
</div>
</div>
);
}
}
} |
JavaScript | class Logger {
/**
* Creates an instance of Logger
*
* @param {Object} options - Initialization options
*/
constructor (options) {
try {
this.options = Object.assign({}, defaultOptions, options)
this.cache = new Map()
} catch (err) {
console.log('Unable to create Logger', err)
}
}
getLogger (loggerId = '', opts = {}) {
let logger = PandaLogger.cache.get(loggerId)
if (logger) return logger
const Config = require('./cfg')
const level = process.env.LOG_LEVEL || opts.level || Config.cfg.LOG_LEVEL || 'debug'
// console.log(`Log level for ${loggerId}: ${level}`)
logger = Winston.createLogger({
level: level,
format: combine(
label({ label: loggerId, message: false }),
Winston.format.colorize(),
splat(),
timestamp(),
myFormat
),
transports: [
// new Winston.transports.Console({ level: 'info' }),
new Winston.transports.Console({ level: level })
// new transports.File({ filename: config.get("app.logging.outputfile"), level: 'debug' }),
]
})
PandaLogger.cache.set(loggerId, logger)
return logger
}
style (style) {
return this.Colors[style] || ''
}
reset () {
return this.Colors.Reset
}
} |
JavaScript | class Entity extends Phaser.GameObjects.Sprite {
constructor(scene, x, y, key, type) {
super(scene, x, y, key);
this.scene = scene;
this.scene.add.existing(this);
this.scene.physics.world.enableBody(this, 0);
this.setData('type', type);
this.setData('isDead', false);
}
explode(canDestroy) {
if (!this.getData('isDead')) {
this.setTexture('sprExplosion');
this.play('sprExplosion');
this.scene.sfx.explosions[Phaser.Math.Between(0, this.scene.sfx.explosions.length - 1)].play();
if (this.shootTimer !== undefined) {
if (this.shootTimer) {
this.shootTimer.remove(false);
}
}
this.setAngle(0);
this.body.setVelocity(0, 0);
this.on('animationcomplete', function() {
if (canDestroy) {
this.destroy();
}
else {
this.setVisible(false);
}
}, this);
this.setData('isDead', true);
}
}
} |
JavaScript | class Sidebar extends React.Component {
static contextType = ThemeContext
render() {
console.log(this.context);
return(
<aside style={{flex: 1, border: 'solid 1px', margin: '1em',
padding: '1em', ...this.context
}}>
<h4>My Sidebar</h4>
<ul>
<li>
<NavLink exact to="/"> Home </NavLink>
</li>
<li>
<NavLink exact to="/post/1"> Post 1 </NavLink>
</li>
<li>
<NavLink exact to="/post/2"> Post 2 </NavLink>
</li>
<li>
<NavLink exact to="/post/3"> Post 3 </NavLink>
</li>
<li>
<NavLink to="/about"> About </NavLink>
</li>
<li>
<NavLink to="/contact"> Contact </NavLink>
</li>
<UserContext.Consumer>
{({authenticated}) =>
authenticated &&
<li>
<NavLink to="/profile"> My profile </NavLink>
</li>
}
</UserContext.Consumer>
</ul>
</aside>
)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.