language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class SpellProject extends JSON5File {
/** Registry of known instances. */
static registry = new Map()
constructor(path) {
// Return immediately from registry if already present.
const existing = SpellProject.registry.get(path)
if (existing) return existing
super({ path })
if (!this.location.isProjectPath) {
throw new TypeError(`new SpellProject('${path}'): Must be initialized with project path.`)
}
SpellProject.registry.set(path, this)
}
/** We've been removed from the server -- clean up memory, etc.. */
onRemove() {
super.onRemove()
// eslint-disable-next-line no-unused-expressions
this.files.forEach((file) => file.onRemove())
SpellProject.registry.clear(this.path)
}
@writeOnce path
/**
* Immutable `location` object which we use to get various bits of the path.
*
* Note that we `forward` lots of methods on the location object to this object,
* so you can say `project.projectName` rather than `project.location.projectName`.
*/
@forward(
//
"projectId",
"owner",
"projectName",
"isSystemProject",
"isUserProject"
)
@memoize
get location() {
return new SpellLocation(this.path)
}
@forward("type", "Type")
@memoize
get projectRoot() {
return new SpellProjectRoot(this.location.projectRoot)
}
//-----------------
// Compilation
//-----------------
/** Parser use for our last parse/compile. */
@state scope = undefined
/** Last compiled result as a javascript string. */
@state compiled = undefined
@memoize
get outputFile() {
const location = this.getFileLocation(".output.js")
return new SpellJSFile(location.path)
}
/** Reset our compiled state. */
resetCompiled() {
this.resetState("scope", "compiled")
}
parse(parser) {
this.parser.cancel()
return this.parser.start(parser)
}
compile(parser) {
this.parser.cancel()
this.compiler.cancel()
return this.compiler.start(parser)
}
/**
* Return base project scope, given a `parentScope`.
* TODOC...
*/
getScope(parentScope = SpellParser.rootScope) {
// Make a parser that depends on the parentScope's parser
// This way rules added to the project won't leak out.
const parser = parentScope.parser.clone({ module: this.path })
return new ProjectScope({
name: this.projectName,
path: this.path,
parser,
scope: parentScope
})
}
/**
* Return a TaskList we can use to parse our imports.
* Call as `project.parser.start(parentScope?)`
*/
@memoize
get parser() {
return new TaskList({
name: `Parsing ${this.type}: ${this.projectName}`,
tasks: [
new Task({
name: `Loading ${this.type}`,
run: (parentScope) => {
this.resetCompiled()
const scope = this.getScope(parentScope)
this.setState("scope", scope)
return this.load()
}
}),
TaskList.forEach({
name: `Parsing imports`,
list: () => this.activeImports,
getTask: (file) =>
new Task({
name: `Parsing import: ${file.file}`,
run: () => file.parse(this.scope)
})
})
]
})
}
/**
* Return a TaskList we can use to `compile()` our imports.
* Call as `project.compiler.start(parentScope?)`
*/
@memoize
get compiler() {
return new TaskList({
debug: true,
name: `Compiling ${this.type}: ${this.projectName}`,
tasks: [
this.parser,
TaskList.forEach({
name: `Compiling imports`,
list: () => this.activeImports,
getTask: (file) =>
new Task({
name: `Compiling import: ${file.file}`,
run: () => file.compile()
})
}),
new Task({
name: "Combining output",
run: (allCompiled) => {
const compiled = allCompiled.join("\n// -----------\n")
this.setState("compiled", compiled)
return compiled
}
}),
new Task({
name: "Saving compiled output",
run: async (compiled) => {
this.outputFile.setContents(compiled)
return await this.outputFile.save()
}
})
]
})
}
/**
* Execute our `compiled` code. No-op if not compiled.
* Returns compiled module `exports` or `error` on JS error.
*/
static runAsImport = true // `false` to run by script injection
async executeCompiled() {
if (!this.compiled) return
// reset runtime environment
spellCore.resetRuntime()
delete this.exports
delete this.executionError
// METHOD 2 (working except we can't get line number of failure)
// Run by importing our `outputFile` as a module.
// This lets us catch errors and get access to module `exports`.
// Unfortunately, we don't get the line number of the error
// (although Chrome does get the line number if we re-throw the error.)
try {
// Use `?<timestamp>` to create a unique URL each time
this.exports = await import(this.outputFile.url + `?${Date.now()}`)
return this.exports
} catch (e) {
if (Error.captureStackTrace) Error.captureStackTrace(e, this.executeCompiled)
this.executionError = e
return e
}
// METHOD 1
// Alternate method of running: create a <script> tag
// Problem with this is that we don't get access to errors
// or `exports` in the compiled code.
//
// const scriptEl = document.createElement("script")
// scriptEl.setAttribute("id", "compileOutput")
// scriptEl.setAttribute("type", "module")
// scriptEl.innerHTML = this.compiled
// const existingEl = document.getElementById("compileOutput")
// if (existingEl) {
// existingEl.replaceWith(scriptEl)
// } else {
// document.body.append(scriptEl)
// }
}
/**
* One of our `file`s has updated its contents.
* Have all of our files `resetCompiled()` so they'll compile again.
*/
updatedContentsFor(file) {
this.activeImports.forEach((item) => item.resetCompiled())
}
//-----------------
// Loading / contents
//-----------------
/** Derive `url` from our path if not explicitly set. */
get url() {
return `/api/projects/index/${this.projectId}`
}
/**
* HACK HACK HACK
* When our `contents` are updated,
* immediately re-calculate derived properties below
* to try to avoid react-easy-state rendering errors :-(
*/
onContentsUpdated() {
// eslint-disable-next-line no-unused-vars
const { manifest, files, imports, activeImports } = this
}
/**
* Load our index if necesssary, calling `die()` if something goes wrong.
*/
async loadOrDie(die) {
if (this.isLoaded) return
try {
this.load()
} catch (e) {
die(`Error loading ${this.type} index`, e)
}
}
/**
* Return the `manifest` map from our `contents`.
* Returns `{}` if not loaded or index is malformed.
*
* Returned objects will have:
* - `path` string
* - `location` as SpellLocation for its `path`
* - `file` as pointer to `SpellFile` (etc) for its `path`
* - `created` as created timestamp
* - `modified` as last modified timestamp
* - `size` as file size in bytes
*/
@memoizeForProp("contents")
get manifest() {
if (!this.contents?.manifest) return {}
// add useful stuff to manifest entries
Object.entries(this.contents.manifest).forEach(([path, entry]) => {
entry.path = path
entry.location = new SpellLocation(path)
entry.file = SpellProject.getFileForPath(path)
})
return this.contents.manifest
}
/**
* Return pointers to all `SpellFiles` in our mainfest.
* Returns `[]` if we're not loaded.
*/
@memoizeForProp("contents")
get files() {
return Object.values(this.manifest).map((item) => item.file)
}
/**
* Return the full ordered `imports` list from our `contents`, including inactive items.
* Returns `[]` if not loaded or index is malformed.
*
* Returned objects will have:
* - `path` full path string
* - `active` boolean, `true` if the file should be included in compilation
* - `location` as SpellLocation for its `path`
* - `file` as pointer to `SpellFile` (etc) for its `path`
* - `contents` as file contents (NOTE: only for text files with certain extensions!)
*/
@memoizeForProp("contents")
get imports() {
if (!this.contents?.imports) return []
return this.contents.imports.map(({ path, active, contents }) => {
const location = SpellLocation.getFileLocation(this.projectId, path)
const file = SpellProject.getFileForPath(location.path)
if (contents !== undefined) file.setContents(contents)
return {
path: location.path,
active,
location,
file
}
})
}
/**
* Return array of `SpellFile` (etc) objects from our `active` imports.
* Returns `[]` if we're not loaded or index is malformed.
*/
@memoizeForProp("contents")
get activeImports() {
const { manifest } = this
return this.imports //
.filter((item) => item.active)
.map((item) => manifest[item.path]?.file)
}
//-----------------
// Project file access
//-----------------
/** Given the `fullPath` to a file, return a `SpellFile` or `SpellCSSFile` etc. */
static getFileForPath(fullPath) {
if (!SpellProject.extensionMap) {
SpellProject.extensionMap = {
".css": SpellCSSFile,
".js": SpellJSFile,
".jsx": SpellJSFile,
default: SpellFile
}
}
const location = new SpellLocation(fullPath)
if (!location.isFilePath) {
throw new TypeError(`SpellProject.getFileForPath('${fullPath}'): path is not a file path.`)
}
const Constructor = SpellProject.extensionMap[location.extension] || SpellProject.extensionMap.default
return new Constructor(fullPath)
}
/**
* Given a `path`as:
* - `fullPath`, e.g. `@user:projects:project/file.spell`
* - `filePath`, e.g. `file.spell` or `/file.spell`
* - `SpellLocation` for a file
* return the `SpellLocation` for the file.
*
* Returns `undefined` if not found, path is not valid or is not a file path.
*/
getFileLocation(path) {
let location
if (path instanceof SpellLocation) {
location = path
} else if (typeof path === "string") {
if (path.startsWith("@")) location = SpellLocation.getFileLocation(path)
else location = SpellLocation.getFileLocation(this.projectId, path)
}
if (location?.isFilePath) return location
}
/**
* Assuming we're loaded, return manifest `info` for a file specified by `filePath`.
* `filePath` can be any of:
* - `fullPath`, e.g. `@user:projects:project/file.spell`
* - `filePath`, e.g. `file.spell` or `/file.spell`
* - `SpellLocation` for a file
*
* Returns `undefined` if file not found, couldn't load index, etc.
*/
getFileInfo(filePath) {
const location = this.getFileLocation(filePath)
if (location) return this.manifest[location.path]
}
/**
* Assuming we're loaded, then return one of our `files` as a `SpellFile` or `SpellCSSFile` etc.
* `filePath` can be any of:
* - `fullPath`, e.g. `@user:projects:project/file.spell`
* - `filePath`, e.g. `file.spell` or `/file.spell`
* - `SpellLocation` for a file
*
* Returns `undefined` if file not found, couldn't load index, etc.
*/
getFile(filePath) {
return this.getFileInfo(filePath)?.file
}
//-----------------
// Project file manipulation
//-----------------
/**
* Create a new file within this project.
* `filePath` is a relative to this project, and may or may not start with `/`.
* NOTE: in theory this handles nested files.
*/
async createFile(filePath, contents, newFileName = "Untitled.spell", die) {
if (!die) die = getDier(this, "creating file", { projectId: this.projectId, filePath })
if (!filePath) filePath = prompt("Name for the new file?", newFileName)
if (!filePath) return undefined
die.params.filePath = filePath
await this.loadOrDie(die)
if (this.getFile(filePath)) die("File already exists.")
// Tell the server to create the file, which returns updated index
try {
const newIndex = await $fetch({
url: `/api/projects/create/file`,
contents: {
projectId: this.projectId,
filePath,
contents: contents ?? `## This space intentionally left blank`
},
requestFormat: "json",
format: "json"
})
this.setContents(newIndex)
} catch (e) {
die("Server error creating file", e)
}
// Return the file
return this.getFile(filePath) || die("Server didn't create file.")
}
/**
* Duplicate an existing file.
* Returns pointer to new file.
*/
async duplicateFile(filePath, newFilePath) {
const die = getDier(this, "duplicating file", {
projectId: this.projectId,
originalFilePath: filePath,
filePath: newFilePath
})
await this.loadOrDie(die)
const file = this.getFile(filePath) || die("File not found.")
let contents
try {
contents = await file.load()
} catch (e) {
die("Server error loading file", e)
}
return this.createFile(newFilePath, contents, file.file, die)
}
/**
* Rename an existing file.
* Returns new file.
*/
async renameFile(filePath, newFilePath) {
const die = getDier(this, "renaming file", { projectId: this.projectId, filePath, newFilePath })
await this.loadOrDie(die)
const file = this.getFile(filePath) || die("File not found.")
if (!newFilePath) {
const filename = prompt("New name for the file?", file.file)
if (!filename) return undefined
newFilePath = SpellLocation.getFileLocation(this.projectId, filename).filePath
if (newFilePath === filePath) return undefined
die.params.newFilePath = newFilePath
}
if (this.getFile(newFilePath)) die("New file already exists.")
// Tell the server to rename the file, which returns the updated index.
try {
const newIndex = await $fetch({
url: `/api/projects/rename/file`,
contents: {
projectId: this.projectId,
filePath,
newFilePath
},
requestFormat: "json",
format: "json"
})
this.setContents(newIndex)
} catch (e) {
die("Server error renaming file", e)
}
// Have the file clean itself up in a tick
// (doing it immediately causes react to barf)
setTimeout(() => file.onRemove(), 10)
// return the new file
return this.getFile(newFilePath) || die("Server didn't rename file.")
}
/**
* Remove an existing file from the project.
* Returns `true` on success, `undefined` if cancelled, or throws on error.
*/
async deleteFile(filePath, shouldConfirm) {
const die = getDier(this, "deleting file", { projectId: this.projectId, filePath })
await this.loadOrDie(die)
if (this.files.length === 1) die(`You can't delete the last file in this ${this.type}.`)
const file = this.getFile(filePath) || die("File not found.")
if (shouldConfirm === CONFIRM) {
if (!confirm(`Really remove file '${file.file}'?`)) return undefined
}
// console.warn("before:", { activeImports: this.activeImports })
// Tell the server to delete the file, which returns the updated index.
try {
const newIndex = await $fetch({
url: `/api/projects/remove/file`,
method: "DELETE",
contents: {
projectId: this.projectId,
filePath
},
requestFormat: "json",
format: "json"
})
this.setContents(newIndex)
} catch (e) {
die("Server error deleting file", e)
}
// throw if file is still found
if (this.getFile(filePath)) die("Server didn't delete the file.")
// Have the file clean itself up in a tick
// (doing it immediately causes react to barf)
setTimeout(() => file.onRemove(), 10)
return true
}
//-----------------
// Debug
//-----------------
toString() {
return `${this.constructor.name}: ${this.path}`
}
} |
JavaScript | class APIErrorDialog extends AlertDialog {
/**
* Construct a new APIErrorDialog object,
*
* @param {APIError} error The error object to display.
* @param {BaseDialog_Callback} callback A callback function.
*/
constructor(error, callback) {
let msg = null;
if (!(error instanceof APIError)) { throw error; }
super(
`API HTTP Error ${error.get_status()}`,
error.get_message() ? error.get_message() : "Unknown error.",
callback
);
console.error(error.toString());
}
} |
JavaScript | class ImageSVGDrawable extends ImageStatefulDrawable( SVGSelfDrawable ) {
/**
* @public
* @override
*
* @param {number} renderer
* @param {Instance} instance
*/
initialize( renderer, instance ) {
super.initialize( renderer, instance, false, keepSVGImageElements ); // usesPaint: false
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} initialized for ${instance.toString()}` );
// @protected {SVGImageElement} - Sole SVG element for this drawable, implementing API for SVGSelfDrawable
this.svgElement = this.svgElement || document.createElementNS( svgns, 'image' );
this.svgElement.setAttribute( 'x', '0' );
this.svgElement.setAttribute( 'y', '0' );
// @private {boolean} - Whether we have an opacity attribute specified on the DOM element.
this.hasOpacity = false;
// @private {boolean}
this.usingMipmap = false;
// @private {number} - will always be invalidated
this.mipmapLevel = -1;
// @private {function} - if mipmaps are enabled, this listener will be added to when our relative transform changes
this._mipmapTransformListener = this._mipmapTransformListener || this.onMipmapTransform.bind( this );
this._mipmapListener = this._mipmapListener || this.onMipmap.bind( this );
this.node.mipmapEmitter.addListener( this._mipmapListener );
this.updateMipmapStatus( instance.node._mipmap );
}
/**
* Updates the SVG elements so that they will appear like the current node's representation.
* @protected
*
* Implements the interface for SVGSelfDrawable (and is called from the SVGSelfDrawable's update).
*/
updateSVGSelf() {
const image = this.svgElement;
if ( this.dirtyImage ) {
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} Updating dirty image` );
if ( this.node._image ) {
// like <image xlink:href='https://phet.colorado.edu/images/phet-logo-yellow.png' x='0' y='0' height='127px' width='242px'/>
this.updateURL( image, true );
}
else {
image.setAttribute( 'width', '0' );
image.setAttribute( 'height', '0' );
image.setAttributeNS( xlinkns, 'xlink:href', '//:0' ); // see http://stackoverflow.com/questions/5775469/whats-the-valid-way-to-include-an-image-with-no-src
}
}
else if ( this.dirtyMipmap && this.node._image ) {
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} Updating dirty mipmap` );
this.updateURL( image, false );
}
if ( this.dirtyImageOpacity ) {
if ( this.node._imageOpacity === 1 ) {
if ( this.hasOpacity ) {
this.hasOpacity = false;
image.removeAttribute( 'opacity' );
}
}
else {
this.hasOpacity = true;
image.setAttribute( 'opacity', this.node._imageOpacity );
}
}
}
/**
* @private
*
* @param {SVGImageElement} image
* @param {boolean} forced
*/
updateURL( image, forced ) {
// determine our mipmap level, if any is used
let level = -1; // signals a default of "we are not using mipmapping"
if ( this.node._mipmap ) {
level = this.node.getMipmapLevel( this.instance.relativeTransform.matrix );
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} Mipmap level: ${level}` );
}
// bail out if we would use the currently-used mipmap level (or none) and there was no image change
if ( !forced && level === this.mipmapLevel ) {
return;
}
// if we are switching to having no mipmap
if ( this.mipmapLevel >= 0 && level === -1 ) {
image.removeAttribute( 'transform' );
}
this.mipmapLevel = level;
if ( this.node._mipmap && this.node.hasMipmaps() ) {
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} Setting image URL to mipmap level ${level}` );
const url = this.node.getMipmapURL( level );
const canvas = this.node.getMipmapCanvas( level );
image.setAttribute( 'width', `${canvas.width}px` );
image.setAttribute( 'height', `${canvas.height}px` );
// Since SVG doesn't support parsing scientific notation (e.g. 7e5), we need to output fixed decimal-point strings.
// Since this needs to be done quickly, and we don't particularly care about slight rounding differences (it's
// being used for display purposes only, and is never shown to the user), we use the built-in JS toFixed instead of
// Dot's version of toFixed. See https://github.com/phetsims/kite/issues/50
image.setAttribute( 'transform', `scale(${Math.pow( 2, level ).toFixed( 20 )})` ); // eslint-disable-line bad-sim-text
image.setAttributeNS( xlinkns, 'xlink:href', url );
}
else {
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} Setting image URL` );
image.setAttribute( 'width', `${this.node.getImageWidth()}px` );
image.setAttribute( 'height', `${this.node.getImageHeight()}px` );
image.setAttributeNS( xlinkns, 'xlink:href', this.node.getImageURL() );
}
}
/**
* @private
*
* @param {boolean} usingMipmap
*/
updateMipmapStatus( usingMipmap ) {
if ( this.usingMipmap !== usingMipmap ) {
this.usingMipmap = usingMipmap;
if ( usingMipmap ) {
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} Adding mipmap compute/listener needs` );
this.instance.relativeTransform.addListener( this._mipmapTransformListener ); // when our relative tranform changes, notify us in the pre-repaint phase
this.instance.relativeTransform.addPrecompute(); // trigger precomputation of the relative transform, since we will always need it when it is updated
}
else {
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} Removing mipmap compute/listener needs` );
this.instance.relativeTransform.removeListener( this._mipmapTransformListener );
this.instance.relativeTransform.removePrecompute();
}
// sanity check
this.markDirtyMipmap();
}
}
/**
* @private
*/
onMipmap() {
// sanity check
this.markDirtyMipmap();
// update our mipmap usage status
this.updateMipmapStatus( this.node._mipmap );
}
/**
* @private
*/
onMipmapTransform() {
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} Transform dirties mipmap` );
this.markDirtyMipmap();
}
/**
* Disposes the drawable.
* @public
* @override
*/
dispose() {
sceneryLog && sceneryLog.ImageSVGDrawable && sceneryLog.ImageSVGDrawable( `${this.id} disposing` );
// clean up mipmap listeners and compute needs
this.updateMipmapStatus( false );
this.node.mipmapEmitter.removeListener( this._mipmapListener );
super.dispose();
}
} |
JavaScript | class Webuntis extends utils.Adapter {
constructor(options = {}) {
super({
...options,
name: 'webuntis',
});
this.on('ready', this.onReady.bind(this));
this.on('unload', this.onUnload.bind(this));
this.timetableDate = new Date();
this.class_id = 0;
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
if (this.config.baseUrl == '') {
this.log.error('No baseUrl set');
}
else if (this.config.school == '') {
this.log.error('No school set');
}
else {
if (this.config.anonymous) {
if (this.config.class == '') {
this.log.error('No class set');
}
else {
//Anonymous login startet
const untis = new webuntis_1.default.WebUntisAnonymousAuth(this.config.school, this.config.baseUrl);
untis.login().then(async () => {
this.log.debug('Anonymous Login sucessfully');
//search class id
await untis.getClasses().then((classes) => {
for (const objClass of classes) {
if (objClass.name == this.config.class) {
this.log.debug('Class found with id:' + objClass.id);
this.class_id = objClass.id;
}
}
}).catch(async (error) => {
this.log.error(error);
this.log.error('Login WebUntis failed');
await this.setStateAsync('info.connection', false, true);
});
if (this.class_id > 0) {
// Now we can start
this.readDataFromWebUntis();
}
else {
this.log.error('Class not found');
}
}).catch(err => {
this.log.error(err);
});
}
}
else {
// Testen ob der Login funktioniert
if (this.config.username == '') {
this.log.error('No username set');
}
else if (this.config.client_secret == '') {
this.log.error('No password set');
}
else {
this.log.debug('Api login started');
// Test to login to WebUntis
const untis = new webuntis_1.default(this.config.school, this.config.username, this.config.client_secret, this.config.baseUrl);
untis.login().then(async () => {
this.log.debug('WebUntis Login erfolgreich');
// Now we can start
this.readDataFromWebUntis();
}).catch(async (error) => {
this.log.error(error);
this.log.error('Login WebUntis failed');
await this.setStateAsync('info.connection', false, true);
});
}
}
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
*/
onUnload(callback) {
try {
callback();
this.clearTimeout(this.startHourScheduleTimeout);
}
catch (e) {
callback();
}
}
startHourSchedule() {
if (this.startHourScheduleTimeout) {
this.log.debug('clearing old refresh timeout');
this.clearTimeout(this.startHourScheduleTimeout);
}
this.startHourScheduleTimeout = this.setTimeout(() => {
this.log.debug('Read new data from WebUntis');
this.startHourScheduleTimeout = null;
this.readDataFromWebUntis();
}, this.getMillisecondsToNextFullHour());
}
readDataFromWebUntis() {
if (this.config.anonymous) {
const untis = new webuntis_1.default.WebUntisAnonymousAuth(this.config.school, this.config.baseUrl);
untis.login().then(async () => {
this.log.debug('WebUntis Anonymous Login erfolgreich');
await this.setStateAsync('info.connection', true, true);
//Start the loop, we have an session
this.log.debug('Lese Timetable 0');
untis.getTimetableFor(new Date(), this.class_id, webuntis_1.default.TYPES.CLASS).then(async (timetable) => {
// Now we can start
//this.readDataFromWebUntis()
if (timetable.length > 0) {
this.log.debug('Timetable gefunden');
this.timetableDate = new Date(); //info timetbale is fro today
await this.setTimeTable(timetable, 0);
}
else {
//Not timetable found, search next workingday
this.log.info('No timetable Today, search next working day');
this.timetableDate = this.getNextWorkDay(new Date());
await untis.getTimetableFor(this.timetableDate, this.class_id, webuntis_1.default.TYPES.CLASS).then(async (timetable) => {
this.log.info('Timetable found on next workind day');
await this.setTimeTable(timetable, 0);
}).catch(async (error) => {
this.log.error('Cannot read Timetable data from 0 - possible block by scool');
this.log.debug(error);
});
}
//Next day
this.log.debug('Lese Timetable +1');
this.timetableDate.setDate(this.timetableDate.getDate() + 1);
untis.getTimetableFor(this.timetableDate, this.class_id, webuntis_1.default.TYPES.CLASS).then(async (timetable) => {
await this.setTimeTable(timetable, 1);
}).catch(async (error) => {
this.log.error('Cannot read Timetable data from +1 - possible block by scool');
this.log.debug(error);
});
});
}).catch(async (error) => {
this.log.error(error);
this.log.error('Login Anonymous WebUntis failed');
await this.setStateAsync('info.connection', false, true);
});
}
else {
const untis = new webuntis_1.default(this.config.school, this.config.username, this.config.client_secret, this.config.baseUrl);
untis.login().then(async () => {
this.log.debug('WebUntis Login erfolgreich');
await this.setStateAsync('info.connection', true, true);
this.timetableDate = new Date(); //info timetbale is for today
//Start the loop, we have an session
this.log.debug('Lese Timetable 0');
untis.getOwnTimetableFor(this.timetableDate).then(async (timetable) => {
if (timetable.length > 0) {
this.log.debug('Timetable gefunden');
await this.setTimeTable(timetable, 0);
}
else {
//Not timetable found, search next workingday
this.log.info('No timetable Today, search next working day');
this.timetableDate = this.getNextWorkDay(new Date());
await untis.getOwnTimetableFor(this.timetableDate).then(async (timetable) => {
this.log.info('Timetable found on next workind day');
await this.setTimeTable(timetable, 0);
}).catch(async (error) => {
this.log.error('Cannot read Timetable data from 0 - possible block by scool');
this.log.debug(error);
});
}
//Next day
this.log.debug('Lese Timetable +1');
this.timetableDate.setDate(this.timetableDate.getDate() + 1);
untis.getOwnTimetableFor(this.timetableDate).then(async (timetable) => {
await this.setTimeTable(timetable, 1);
}).catch(async (error) => {
this.log.error('Cannot read Timetable data from +1 - possible block by scool');
this.log.debug(error);
});
}).catch(async (error) => {
this.log.error('Cannot read Timetable for today - possible block by scool');
this.log.debug(error);
});
this.log.debug('Load Message center');
//get Messages from Center
untis.getNewsWidget(new Date()).then((newsFeed) => {
this.log.debug('Get news feed from API');
this.log.debug(JSON.stringify(newsFeed));
this.setNewsFeed(newsFeed);
}).catch(async (error) => {
this.log.info('Cannot read Message Center - possible block by scool');
this.log.debug(error);
});
untis.getInbox().then((messages) => {
this.log.debug('Get inbox from API');
this.log.debug(JSON.stringify(messages));
this.setInbox(messages);
}).catch(async (error) => {
this.log.info('Cannot read Inbox - possible block by scool');
this.log.debug(error);
});
}).catch(async (error) => {
this.log.error(error);
this.log.error('Login WebUntis failed');
await this.setStateAsync('info.connection', false, true);
});
}
// Next round in one Hour
this.startHourSchedule();
}
//FUnktion for Inbox Data
async setInbox(messages) {
await this.setObjectNotExistsAsync('inbox.inbox-date', {
type: 'state',
common: {
name: 'inbox-date',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync('inbox.inbox-date', new Date().toString(), true);
let index = 0;
for (const message of messages.incomingMessages) {
await this.setObjectNotExistsAsync('inbox.' + index + '.subject', {
type: 'state',
common: {
name: 'subject',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync('inbox.' + index + '.subject', message.subject, true);
await this.setObjectNotExistsAsync('inbox.' + index + '.contentPreview', {
type: 'state',
common: {
name: 'contentPreview',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync('inbox.' + index + '.contentPreview', message.contentPreview, true);
//Count Element
index = index + 1;
}
this.deleteOldInboxObject(index);
}
//Function for Newsfeed
async setNewsFeed(newsFeed) {
await this.setObjectNotExistsAsync('newsfeed.newsfeed-date', {
type: 'state',
common: {
name: 'newsfeed-date',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync('newsfeed.newsfeed-date', new Date().toString(), true);
let index = 0;
for (const feed of newsFeed.messagesOfDay) {
await this.setObjectNotExistsAsync('newsfeed.' + index + '.subject', {
type: 'state',
common: {
name: 'subject',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync('newsfeed.' + index + '.subject', feed.subject, true);
await this.setObjectNotExistsAsync('newsfeed.' + index + '.text', {
type: 'state',
common: {
name: 'text',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync('newsfeed.' + index + '.text', feed.text, true);
//Count Element
index = index + 1;
}
this.deleteOldNewsFeedObject(index);
}
//Function for Timetable
async setTimeTable(timetable, dayindex) {
//Info from this date is the timetable
await this.setObjectNotExistsAsync(dayindex + '.timetable-date', {
type: 'state',
common: {
name: 'timetable-date',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync(dayindex + '.timetable-date', this.timetableDate.toString(), true);
let index = 0;
let minTime = 2399;
let maxTime = 0;
let exceptions = false;
//sorting for time
timetable = timetable.sort((a, b) => a.startTime - b.startTime);
this.log.debug(JSON.stringify(timetable));
for (const element of timetable) {
this.log.debug('Element found: ' + index.toString());
this.log.debug(JSON.stringify(element));
//create an Object for each elemnt on the day
await this.setObjectNotExistsAsync(dayindex + '.' + index.toString() + '.startTime', {
type: 'state',
common: {
name: 'startTime',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync(dayindex + '.' + index.toString() + '.startTime', webuntis_1.default.convertUntisTime(element.startTime, this.timetableDate).toString(), true);
//save mintime
if (minTime > element.startTime)
minTime = element.startTime;
await this.setObjectNotExistsAsync(dayindex + '.' + index.toString() + '.endTime', {
type: 'state',
common: {
name: 'endTime',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync(dayindex + '.' + index.toString() + '.endTime', webuntis_1.default.convertUntisTime(element.endTime, this.timetableDate).toString(), true);
//save maxtime
if (maxTime < element.endTime)
maxTime = element.endTime;
await this.setObjectNotExistsAsync(dayindex + '.' + index.toString() + '.name', {
type: 'state',
common: {
name: 'name',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
if (element.su && element.su.length > 0) {
await this.setStateAsync(dayindex + '.' + index.toString() + '.name', element.su[0].name, true);
}
else {
await this.setStateAsync(dayindex + '.' + index.toString() + '.name', null, true);
}
await this.setObjectNotExistsAsync(dayindex + '.' + index.toString() + '.teacher', {
type: 'state',
common: {
name: 'teacher',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
if (element.te && element.te.length > 0) {
await this.setStateAsync(dayindex + '.' + index.toString() + '.teacher', element.te[0].longname, true);
}
else {
await this.setStateAsync(dayindex + '.' + index.toString() + '.teacher', null, true);
}
await this.setObjectNotExistsAsync(dayindex + '.' + index.toString() + '.room', {
type: 'state',
common: {
name: 'room',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
if (element.ro && element.ro.length > 0) {
await this.setStateAsync(dayindex + '.' + index.toString() + '.room', element.ro[0].name, true);
}
else {
await this.setStateAsync(dayindex + '.' + index.toString() + '.room', null, true);
}
await this.setObjectNotExistsAsync(dayindex + '.' + index.toString() + '.code', {
type: 'state',
common: {
name: 'code',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
if (element.code == 'cancelled' || element.code == 'irregular') {
this.log.debug('Exception in lesson found');
exceptions = true;
await this.setStateAsync(dayindex + '.' + index.toString() + '.code', element.code, true);
}
else {
await this.setStateAsync(dayindex + '.' + index.toString() + '.code', 'regular', true);
}
//Next Elemet
index = index + 1;
}
if (index > 0) {
//we have min one element
await this.setObjectNotExistsAsync(dayindex + '.minTime', {
type: 'state',
common: {
name: 'minTime',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync(dayindex + '.minTime', webuntis_1.default.convertUntisTime(minTime, this.timetableDate).toString(), true);
await this.setObjectNotExistsAsync(dayindex + '.maxTime', {
type: 'state',
common: {
name: 'maxTime',
role: 'value',
type: 'string',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync(dayindex + '.maxTime', webuntis_1.default.convertUntisTime(maxTime, this.timetableDate).toString(), true);
await this.setObjectNotExistsAsync(dayindex + '.exceptions', {
type: 'state',
common: {
name: 'exceptions',
role: 'value',
type: 'boolean',
write: false,
read: true,
},
native: {},
}).catch((error) => {
this.log.error(error);
});
await this.setStateAsync(dayindex + '.exceptions', exceptions, true);
}
//check if an Object is over the max index
await this.deleteOldTimetableObject(dayindex, index);
}
//Helpfunction
async deleteOldInboxObject(index) {
const delObject = await this.getObjectAsync('inbox.' + index + '.subject');
if (delObject) {
this.log.debug('Object zum löschen gefunden - ' + index.toString());
await this.delObjectAsync(index.toString(), { recursive: true });
// Have one delted, next round
await this.deleteOldInboxObject(index + 1);
}
}
async deleteOldNewsFeedObject(index) {
const delObject = await this.getObjectAsync('newsfeed.' + index + '.text');
if (delObject) {
this.log.debug('Object zum löschen gefunden - ' + index.toString());
await this.delObjectAsync(index.toString(), { recursive: true });
// Have one delted, next round
await this.deleteOldNewsFeedObject(index + 1);
}
}
async deleteOldTimetableObject(dayindex, index) {
this.log.debug('Object search in deleteOldTimetableObject for: ' + index.toString());
const delObject = await this.getObjectAsync(dayindex + '.' + index.toString() + '.name');
if (delObject) {
this.log.debug('Object for deleting found: ' + index.toString());
await this.delObjectAsync(dayindex + '.' + index.toString(), { recursive: true });
// Have one delted, next round
await this.deleteOldTimetableObject(dayindex, index + 1);
}
}
getNextWorkDay(date) {
const d = new Date(+date);
const day = d.getDay() || 7;
d.setDate(d.getDate() + (day > 4 ? 8 - day : 1));
return d;
}
//thanks to klein0r
getMillisecondsToNextFullHour() {
const now = new Date();
const nextHour = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0, 5, 0); // add 5 seconds to ensure we are in the next hour
return nextHour.getTime() - now.getTime();
}
} |
JavaScript | class GithubObject {
/**
* Either a username and password or an oauth token for Github.
* @typedef {Object} GithubObject.auth
* @prop {string} [username]
* The Github username.
* @prop {string} [password]
* The user's password.
* @prop {token} [token]
* An OAuth token.
*/
/**
* Initialize our Github API.
*
* @param {Github.auth} [auth]
* The credentials used to authenticate with Github. If not provided
* requests will be made unauthenticated.
* @param {string} [base]
* The base of the API url.
*/
constructor(auth, base) {
this._base = base;
this._auth = auth;
if (auth.token) {
this._auth.header = 'token ' + auth.token;
} else if (auth.username && auth.password) {
this._auth.header= 'Basic ' + Base64.encode(auth.username + ':' + auth.password);
}
}
/**
* Make a request to Github to fetch the ratelimit(s).
*
* @return {Promise)
* The Promise for the rate limit request.
*/
getRateLimit() {
const url = this._base + 'rate_limit';
return this._request(url);
}
/**
* Get the headers required for an API request.
*
* @return {Object}
* The headers to pass to the request.
*/
_getRequestHeaders() {
const headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/vnd.github.v3+json',
};
if (this._auth.header) {
headers.Authorization = this._auth.header;
}
return headers;
}
/**
* Sets the default options for API requests
*
* @return {Object}
* Additional options to pass to the request.
*/
_getRequestOptions(options) {
options = Object.assign({
sort: 'updated',
per_page: '5000',
}, options);
return options;
}
/**
* Returns the relevant Github schema objects for a given type.
*
* @return {Promise}
* Promise of schema object.
*/
getSchema() {
throw new Error('You have to implement this abstract method!');
}
/**
* Parse query into useful API request urls.
*
* @param {string} [url]
* Request URI relative to the API base.
* @param {string} [tableId]
* The table identifier.
* @return {Array}
* Array of urls.
*/
parseUrl(url, tableId) {
const base = 'https://api.github.com/',
re = /\[(.*)\]/g,
match = re.exec(url),
urls = [];
// Look for any arrays in our query string.
if (match !== null) {
const delimited = match[1].split(',');
for(const value of delimited) {
urls.push(base + url.replace(re, value));
}
} else {
urls.push(base + url);
}
return urls;
}
/**
* Concurrently runs API requests for a number of given urls.
*
* @param {array}(urls)
* A list of urls to call using the API.
* @param {*} [options]
* Additional options will be sent as query parameters.
* @param {number}(concurrency)
* The number of concurrent API calls we can make.
*
* @returns {Promise}
* @private
*/
getData(urls, options = {}, concurrency = 5) {
return new Promise((resolve, reject) => {
let count = 0,
producer,
pool,
raw = [];
// A Promise Pool producer generates promises as long as there is work left
// to be done. We return null to notify the pool is empty.
producer = () => {
if (count < urls.length) {
let url = urls[count];
count++;
// The actual API request for a given url.
return new Promise((resolve, reject) => {
this._request(url, options).then((result) => {
// Append all our raw data.
raw = raw.concat(...result);
resolve(raw);
}).catch((err) => {
reject('Invalid Github API request: ' + url);
});
});
}
else {
return null;
}
};
// Run our promises concurrently, but never exceeds the maximum number of
// concurrent promises.
pool = new PromisePool(producer, concurrency);
pool.start().then(() => {
resolve(raw);
}, (err) => {
reject(err);
});
});
}
/**
* Make a request and fetch all available data (support pagination).
*
* @param {string} [url]
* The url for the API request.
* @param {*} [options]
* Additional options will be sent as query parameters.
* @param {Object[]} [results]
* For internal use only - recursive requests.
*
* @return {Promise}
* The Promise for the http request
*/
_request(url, options = {}, results = []) {
const config = {
url: url,
method: 'GET',
headers: this._getRequestHeaders(),
qs: this._getRequestOptions(options),
responseType: 'json',
resolveWithFullResponse: true,
json: true,
};
return req(config).then((response) => {
if (response.body instanceof Array) {
// Default GET Github API requests.
results.push(...response.body);
}
else if (response.body instanceof Object) {
// Default single GET Github API requests.
results.push(response.body);
}
else if (response.body.items instanceof Array) {
// Support SEARCH Github API requests.
// @link https://developer.github.com/v3/search/
results.push(...response.body.items);
}
else {
log('reject');
}
// Support Github pagination.
if (response.headers.link) {
const nextPage = getNextPage(response.headers.link);
if (nextPage) {
return this._request(nextPage, options, results);
}
}
// Include request url to all result objects.
results.forEach((element) => {
element._request_url = url;
});
return results;
}).catch(function (err) {
log(err);
throw err;
});
}
/**
* Process our objects into a format that is more Tableau friendly.
* Isolate nested objects and arrays and store them in separate 'tables'.
*
* @param {Object} [result]
* An object where you wish to save the processed data onto.
* @param {Object} [table]
* Table object which contains information about the columns and values.
* @param {Array} [rawData]
* An array of objects to process.
* @returns {Promise}
*/
processData(result, table, rawData) {
const tableId = table.tableInfo.id;
result[tableId] = rawData;
return result;
}
} |
JavaScript | class App3 extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
increaseCounter() {
this.setState({ counter: this.state.counter + 1 });
}
decreaseCounter() {
this.setState({ counter: this.state.counter - 1 });
}
render() {
return (
<div className="App">
<h1>Classfull with State</h1>
<div>
<button onClick={this.decreaseCounter.bind(this)}>
<b>Decrease</b>
</button>
<button onClick={this.increaseCounter.bind(this)}>
<b>Increase</b>
</button>
</div>
<h2>{this.state.counter}</h2>
</div>
);
}
} |
JavaScript | class AlignerLHDefault extends LogicHandler {
constructor(camera, getActive, refreshFunc, undoStack) {
super();
this.camera = camera;
this.getActive = getActive;
this.refresh = refreshFunc;
this.undoStack = undoStack;
this.recordKeyStates();
}
processKeydownEvent() {
this.refreshCursor();
}
processKeyupEvent(e) {
if (this.keystates.ctrl) {
this.refreshCursor();
} else if (e === Codes.keyEvent.undo) {
if(this.undoStack.lastTab() == "state_alignment") {
var action = this.undoStack.pop();
const { layer, matrix } = action.state;
layer.setTransform(matrix);
this.refresh();
}
}
}
processMouseEvent(e, data) {
switch (e) {
case Codes.mouseEvent.down: {
const layer = this.getActive();
const action = new UndoAction(
'state_alignment',
'layerTransform',
{ layer, matrix: layer.getTransform() },
);
this.undoStack.setTemp(action);
} break;
case Codes.mouseEvent.up:
if(this.undoStack.temp) {
const layer = this.getActive();
const matrix = layer.getTransform();
const { layer: prevLayer, matrix: prevMatrix } =
this.undoStack.temp.state;
if (layer === prevLayer && !math.deepEqual(matrix, prevMatrix)) {
this.undoStack.pushTemp();
} else {
this.undoStack.clearTemp();
}
}
this.refresh();
break;
case Codes.mouseEvent.drag:
this.camera.pan(Vec2.Vec2(
data.difference.x,
data.difference.y,
));
this.refresh();
break;
case Codes.mouseEvent.wheel:
this.camera.navigate(data.direction, data.position);
this.refresh();
break;
default:
break;
}
this.refreshCursor();
}
refreshCursor() {
if (this.keystates.mouseLeft) {
setCursor('grabbing');
} else {
setCursor('grab');
}
}
} |
JavaScript | class AlignerLHMove extends AlignerLHDefault {
processKeydownEvent(e) {
if (e === Codes.keyEvent.ctrl) {
super.processKeydownEvent(e);
}
}
processMouseEvent(e, data) {
if (e === Codes.mouseEvent.wheel || data.ctrl) {
super.processMouseEvent(e, data);
return;
}
if (e === Codes.mouseEvent.drag) {
this.getActive().translate(
math.matrix([
[data.difference.x / this.camera.scale],
[data.difference.y / this.camera.scale],
]),
);
} else if (e === Codes.mouseEvent.up) {
super.processMouseEvent(e, data);
} else if (e === Codes.mouseEvent.down) {
super.processMouseEvent(e, data);
}
this.refreshCursor();
}
refreshCursor() {
if (this.keystates.ctrl) {
super.refreshCursor();
return;
}
if (this.keystates.mouseLeft || this.keystates.mouseRight) {
setCursor('crosshair');
} else {
setCursor('move');
}
}
} |
JavaScript | class AlignerLHRotate extends AlignerLHDefault {
constructor(camera, layerManager, refreshFunc, undoStack, rotationPoint) {
super(camera, layerManager, refreshFunc, undoStack);
this.rp = rotationPoint;
this.rpHoverState = false;
this[curs] = 'def';
this.recordMousePosition();
this.recordKeyStates();
}
processKeydownEvent(e) {
if (this.keystates.ctrl) {
super.processKeydownEvent(e);
return;
}
this.refreshState();
}
processKeyupEvent(e) {
if (this.keystates.ctrl) {
super.processKeyupEvent(e);
return;
} else if (e == Codes.keyEvent.undo) {
super.processKeyupEvent(e);
return;
}
this.refreshState();
}
processMouseEvent(e, data) {
if (this.keystates.ctrl || e === Codes.mouseEvent.wheel) {
super.processMouseEvent(e, data);
return;
}
switch (e) {
case Codes.mouseEvent.drag:
if (this[curs] === 'rotate') {
const position = this.camera.mouseToCameraPosition(data.position);
const difference = this.camera.mouseToCameraScale(data.difference);
const to = Vec2.subtract(position, this.rp);
const from = Vec2.subtract(to, difference);
this.getActive().rotate(
Vec2.angleBetween(from, to),
math.matrix([
[this.rp.x],
[this.rp.y],
[1],
]),
);
} else if (this[curs] === 'dragRP') {
const rpNew = Vec2.subtract(
this.rp,
this.camera.mouseToCameraScale(data.difference),
);
this.rp.x = rpNew.x;
this.rp.y = rpNew.y;
this.refresh();
}
break;
case Codes.mouseEvent.down:
if (data.button === Codes.mouseButton.right) {
const rpNew = this.camera.mouseToCameraPosition(data.position);
this.rp.x = rpNew.x;
this.rp.y = rpNew.y;
this.refresh();
}
else {
super.processMouseEvent(e, data);
}
break;
case Codes.mouseEvent.up:
super.processMouseEvent(e, data);
break;
default:
break;
}
this.refreshState();
}
refreshState() {
const { x, y } = this.camera.mouseToCameraPosition(this.mousePosition);
if (this.rp.isHovering(x, y)) {
if (this.keystates.mouseLeft !== true) {
this[curs] = 'hoverRP';
} else if (this[curs] !== 'rotate') {
this[curs] = 'dragRP';
}
if (!this.rpHoverState) {
this.rpHoverState = true;
this.refresh();
}
} else {
if (this.keystates.mouseLeft === true) {
this[curs] = 'rotate';
} else {
this[curs] = 'def';
}
if (this.rpHoverState) {
this.rpHoverState = false;
this.refresh();
}
}
this.refreshCursor();
}
refreshCursor() {
if (this.keystates.ctrl) {
super.refreshCursor();
return;
}
switch (this[curs]) {
case 'dragRP':
setCursor('grabbing');
break;
case 'hoverRP':
setCursor('grab');
break;
case 'rotate':
setCursor('crosshair');
break;
case 'def':
default:
setCursor('move');
break;
}
}
} |
JavaScript | class MessageList extends Component {
constructor(props) {
super(props);
this.state = {
stickBottom: true
};
}
componentDidMount() {
this.removeScrollListener = throttledEventListener(findDOMNode(this), 'scroll', this.handleScroll, this);
this.removeResizeListener = throttledEventListener(window, 'resize', this.handleScroll, this);
this.scrollBottom();
}
componentDidUpdate() {
if (this.state.stickBottom) {
this.scrollBottom();
}
}
scrollBottom() {
if (!this.state.isScrolling) {
var el = findDOMNode(this);
el.scrollTop = el.scrollHeight;
}
}
handleScroll() {
var el = findDOMNode(this);
if (el.scrollTop === 0) {
this.props.onLoadMoreMessages();
}
const stickBottom = el.scrollHeight - 1 <= el.clientHeight + el.scrollTop;
if (stickBottom !== this.state.stickBottom) {
this.setState({ stickBottom });
}
}
renderMessageItem = (message) => {
const { onMarkMessageRead } = this.props;
return (
<MessageListItem
key={message.id}
message={message}
onMarkMessageRead={onMarkMessageRead}/>
);
}
render() {
const reversedMessages = this.props.messages.concat().reverse();
return (
<div className='message-list'>
{reversedMessages.map(this.renderMessageItem)}
</div>
);
}
componentWillUnmount() {
this.removeResizeListener();
this.removeScrollListener();
}
} |
JavaScript | class TopicEdit extends Component {
constructor (props) {
super(props);
this.state = {
topicsEdited: this.props.topicsEdited, // an array of objects (for each topic)
dyad: this.props.topicsEdited[(this.props.location.pathname.split('/')[2])-1].graphOptions.dyad,
groupComp: this.props.topicsEdited[(this.props.location.pathname.split('/')[2])-1].graphOptions.groupComp,
graphText: this.props.topicsEdited[(this.props.location.pathname.split('/')[2])-1].textOptions.graphText,
};
}
componentDidMount() {
window.scrollTo(0, 0)
}
componentWillMount() {
// define the graphText (text that describes the graph)
let graphText;
const topicConfig = this.props.topicsConfig[(this.props.location.pathname.split('/')[2])-1];
if (topicConfig.time !== '') { // case for a line plot
graphText = 'Diese Graphik ist ein Liniendiagramm. Es zeigt die Verteilung der Werte über die Zeit. Die Werte aller Teilnehmer sind der Druchschnitt aller Werte an einem Zeitpunkt.'
}
else { // case for a box plot
if (topicConfig.variable2 === '' && topicConfig.variable3 === '') { // case with 1 variable -> no Z transformation
graphText = 'Diese Graphik ist ein Boxplot. Es zeigt die Verteilung der Werte aller Teilnehmer. 50% der Teilnehmer hatten einen Wert innerhalb der Box. 25% der Teilnehmer waren oberhalb und 25% waren unterhalb der Box. Die Linie innerhalb der Box zeigt den Median. Eine Hälfte der Teilnehmer war oberhalb und die andere Hälfte unterhalb. Die Linie oberhalb und unterhalb der Box (Whiskers) zeigen das Minimum und das Maximum.'}
else { // case with Z transformation (multiple variables)
graphText = 'Diese Graphik ist ein Boxplot. Es zeigt die Verteilung der Werte aller Teilnehmer. 50% der Teilnehmer hatten einen Wert innerhalb der Box. 25% der Teilnehmer waren oberhalb und 25% waren unterhalb der Box. Die Linie innerhalb der Box zeigt den Median. Eine Hälfte der Teilnehmer war oberhalb und die andere Hälfte unterhalb. Die Linie oberhalb und unterhalb der Box (Whiskers) zeigen das Minimum und das Maximum. Da die Variablen auf verschiedenen Skalen gemessen wurden, wurden sie transformiert um vergleichbar zu sein (sogennante Z-Transformation).'}
}
const newTopicsEdited = [...this.state.topicsEdited]
newTopicsEdited[(this.props.location.pathname.split('/')[2])-1].textOptions.graphText = graphText
this.setState({graphText: graphText});
this.setState({topicsEdited: newTopicsEdited});
}
handleTextClick = (text) => {
if (text === 'topicText') {window.scrollTo(0, 250);}
if (text === 'catText') {window.scrollTo(0, 1200);}
}
updateTextHandler = (newVal, text, topicId, allowedCompVals, compVals) => {
let newValue = newVal;
if (typeof(newValue) !== 'string') {
newValue = newVal.target.value;
}
const re_patt = RegExp('#\\w*','gi');
let res;
const all_matches = [];
while ((res = re_patt.exec(newValue)) !== null){
const match = res[0] // the compVals inputed by the user
all_matches.push(match);
}
all_matches.map(match => {
allowedCompVals.map((allowedCompVal, index) => {
if (match === allowedCompVal) {
const replac = compVals[index];
newValue = newValue.replace(match, replac)
}
return newValue
})
return newValue
})
const newtopicsEdited = this.state.topicsEdited;
const newTopicEdited = {...newtopicsEdited[topicId-1]};
const newTextOptions = newTopicEdited.textOptions;
newTextOptions[[text]] = newValue;
newTopicEdited.textOptions = newTextOptions;
newtopicsEdited[topicId-1] = newTopicEdited;
this.setState( {topicsEdited: newtopicsEdited});
this.props.onTopicsEdited(newtopicsEdited);
}
updateGraphQuestions = (dyad, groupComp, topicId) => {
this.setState({
dyad: dyad,groupComp: groupComp})
const newtopicsEdited = [...this.state.topicsEdited];
const newTopicEdited = newtopicsEdited[topicId-1];
const newGraphOptions = newTopicEdited.graphOptions;
newGraphOptions.dyad = dyad;
newGraphOptions.groupComp = groupComp;
newTopicEdited.graphOptions = newGraphOptions;
newtopicsEdited[topicId-1] = newTopicEdited;
this.props.onTopicsEdited(newtopicsEdited);
}
updateURL = (graphDiv) => {
const newtopicsEdited = this.state.topicsEdited;
const newTopicEdited = {...newtopicsEdited[(this.props.location.pathname.split('/')[2])-1]};
const newGraphOptions = newTopicEdited.graphOptions;
newGraphOptions.graphDiv = graphDiv;
newTopicEdited.graphOptions = newGraphOptions;
newtopicsEdited[(this.props.location.pathname.split('/')[2])-1] = newTopicEdited;
this.props.onTopicsEdited(newtopicsEdited);
}
render() {
const topicId = this.props.location.pathname.split('/')[2];
//CAVE does not work if values are undefinded (direct access)
const topicConfig = this.props.topicsConfig[topicId-1];
const topicEdited = this.props.topicsEdited[topicId-1];
const topicsVariables = {...topicConfig};
const topicName = topicsVariables.topicName;
delete topicsVariables.topicName;
Object.keys(topicsVariables).forEach((key) =>
(topicsVariables[key] === "") && delete topicsVariables[key]);
const variableArray = [];
const categoriesArray = [];
Object.values(topicsVariables).map((item, i) => {
if (typeof(item) === "string") {
variableArray.push(item);
categoriesArray.push(Object.keys(topicsVariables)[i]);}
return variableArray;
})
const data_withH = [...this.props.data];
// create a list of all partIds, remove deplicates and choose a random partId to be displayed
const data_noH = [...data_withH]
const partIds = [];
const headers = data_withH[0];
data_noH.shift();
const partIdIndex = headers.indexOf(topicConfig.id);// find the index of the partId
data_noH.map(line => {
partIds.push(line[partIdIndex]);
return partIds;
});
const uniquePartIds = [...new Set(partIds)] // eliminate duplicates (have each partId only once)
const partId = uniquePartIds[Math.floor(0.5*uniquePartIds.length)];
//
// Define the computed values
const pureVars = []; // get only the variables (without ID, time, group)
pureVars.push(topicConfig.variable);
if (topicConfig.variable2 !== '') {pureVars.push(topicConfig.variable2);}
if (topicConfig.variable3 !== '') {pureVars.push(topicConfig.variable3);}
const allowedCompVals = []; // the allowed compVals according to the varialbes chosen for the topic
const compVals = []; // the actual, computed values
pureVars.map(variable => {
if (this.state.dyad) { // for dyads, the computed values of interest are Partner 1 and Partner 2
const partner1 = "#partner1_mean_" + variable
const partner2 = "#partner2_mean_" + variable
allowedCompVals.push(partner1, partner2)
}
else {
const group = "#sample_mean_" + variable
const person = "#person_mean_" + variable
allowedCompVals.push(group, person)}
const all_var = [] // temporary array
const pers_var = []
const varIndex = headers.indexOf(variable); // find the index of the variable
const idIndex = headers.indexOf(topicConfig.id);
data_noH.map(line => {
all_var.push(line[varIndex])
if(line[idIndex] === partId){
pers_var.push(line[varIndex])}
return all_var})
const group_mean = math.mean(all_var).toFixed(2);
const pers_mean = math.mean(pers_var).toFixed(2);
compVals.push(group_mean, pers_mean)
return compVals
})
//
// defining the personalized text to be displayed
const textOptions = topicEdited.textOptions;
const partCategory = findPartCategory(data_noH, headers, topicConfig, partId);
let personalizedText;
if (typeof(textOptions) !== 'object') {
personalizedText = 'No text entered yet';
} else if(textOptions[partCategory] === '') {
if (partCategory === 'textHigh') {
textOptions[partCategory] = 'In der Graphik sehen Sie, wo Ihr Wert im Vergleich der anderen Studienteilnehmer liegt. Ihr Wert befindet sich im oberen Viertel der gesammelten Antworten. Das bedeutet... ';
}
else if (partCategory === 'textMiddle') {
textOptions[partCategory] = 'In der Graphik sehen Sie, wo Ihr Wert im Vergleich der anderen Studienteilnehmer liegt. Ihr Wert befindet sich in der mittleren Hälfte der gesammelten Antworten. Das bedeutet... ';
} else {
textOptions[partCategory] = 'In der Graphik sehen Sie, wo Ihr Wert im Vergleich der anderen Studienteilnehmer liegt. Ihr Wert befindet sich im unteren Viertel der gesammelten Antworten. Das bedeutet... ';
}
personalizedText = textOptions[[partCategory]];
} else {
personalizedText = textOptions[[partCategory]];}
let topicText = topicEdited.textOptions.topicText;
if (topicText === '') {
topicText = 'Während der Studie haben wir Werte zum Thema '+topicName+' gesammelt. Wir möchten diese hiermit in Form eines personalisierten Feedbacks zurückgeben.';}
let graphText = topicEdited.textOptions.graphText;
// further questions
let graphQuestions;
const dyad = this.state.dyad;
let styleDyadYes = "primary";
let styleDyadNo = "default";
if (!dyad) {styleDyadYes = "default"; styleDyadNo = "primary"}
const groupComp=this.state.groupComp;
let styleGCYes = "primary";
let styleGCNo = "default";
if (!groupComp) {styleGCYes = "default"; styleGCNo = "primary";}
let graph;
// Type 8 Time + group/dyad + multiple variables
if (categoriesArray.includes('id') &&
categoriesArray.includes('variable') &&
categoriesArray.includes('time') &&
categoriesArray.includes('group') &&
(categoriesArray.includes('variable2') ||
categoriesArray.includes('variable3')))
{ graphQuestions = <Well><h3>Is the group a dyad?</h3>
<ButtonToolbar><Button bsStyle={styleDyadYes} onClick={() =>
this.updateGraphQuestions(partId, groupComp, topicId)}>Yes</Button>
<Button bsStyle={styleDyadNo} onClick={() =>
this.updateGraphQuestions(false, groupComp, topicId)}>No</Button></ButtonToolbar></Well>
graph = <LinePlot data_noH={data_noH} headers={headers}
topicConfig={topicConfig} partId={partId} dyad={dyad}
urlUpdate={this.updateURL}/>;
}
// Type 7 Time + multiple variables
else if(
categoriesArray.includes('id') &&
categoriesArray.includes('variable') &&
categoriesArray.includes('time') &&
!categoriesArray.includes('group') &&
(categoriesArray.includes('variable2') ||
categoriesArray.includes('variable3')))
{ graph = <LinePlot data_noH={data_noH} headers={headers}
topicConfig={topicConfig} partId={partId}
urlUpdate={this.updateURL}/>; }
// Type 6 Time + Group/Dyad
else if(
categoriesArray.includes('id') &&
categoriesArray.includes('variable') &&
categoriesArray.includes('time') &&
categoriesArray.includes('group') &&
!categoriesArray.includes('variable2') &&
!categoriesArray.includes('variable3'))
{ graphQuestions = <Well><h3>Is the group a dyad?</h3>
<ButtonToolbar><Button bsStyle={styleDyadYes} onClick={() =>
this.updateGraphQuestions(partId, groupComp, topicId)}>Yes</Button>
<Button bsStyle={styleDyadNo} onClick={() =>
this.updateGraphQuestions(false, groupComp, topicId)}>No</Button></ButtonToolbar></Well>
graph = <LinePlot data_noH={data_noH} headers={headers}
topicConfig={topicConfig} partId={partId} dyad={dyad}
urlUpdate={this.updateURL}/>;
}
// Type 5 Only Time
else if(
categoriesArray.includes('id') &&
categoriesArray.includes('variable') &&
categoriesArray.includes('time') &&
!categoriesArray.includes('group') &&
!categoriesArray.includes('variable2') &&
!categoriesArray.includes('variable3'))
{ graphQuestions = <Well><Row><h3>Which kind of comparison would you like to show?</h3>
<ButtonToolbar><Button bsStyle={styleGCYes} onClick={() =>
this.updateGraphQuestions(dyad, true, topicId)}>To all participants (between person)</Button>
<Button bsStyle={styleGCNo} onClick={() =>
this.updateGraphQuestions(dyad, false, topicId)}>To one-self (within-person)</Button></ButtonToolbar></Row></Well>
graph = <LinePlot data_noH={data_noH} headers={headers}
topicConfig={topicConfig} partId={partId} groupComp={groupComp}
urlUpdate={this.updateURL}/>;
}
// Type 4 Multiple variables + Dyad / Group
else if(
categoriesArray.includes('id') &&
categoriesArray.includes('variable') &&
!categoriesArray.includes('time') &&
categoriesArray.includes('group') &&
(categoriesArray.includes('variable2') ||
categoriesArray.includes('variable3')))
{ graphQuestions = <Well><h3>Is the group a dyad?</h3>
<ButtonToolbar><Button bsStyle={styleDyadYes} onClick={() =>
this.updateGraphQuestions(partId, groupComp, topicId)}>Yes</Button>
<Button bsStyle={styleDyadNo} onClick={() =>
this.updateGraphQuestions(false, groupComp, topicId)}>No</Button></ButtonToolbar></Well>
graph = <BoxPlot data_noH={data_noH} headers={headers}
topicConfig={topicConfig} partId={partId} dyad={dyad}
urlUpdate={this.updateURL}/>;
}
// Type 3 - Multiple variables
else if(
categoriesArray.includes('id') &&
categoriesArray.includes('variable') &&
!categoriesArray.includes('time') &&
!categoriesArray.includes('group') &&
(categoriesArray.includes('variable2') ||
categoriesArray.includes('variable3')))
{ graph = <BoxPlot data_noH={data_noH} headers={headers}
topicConfig={topicConfig} partId={partId}
urlUpdate={this.updateURL}/>;}
// Type 2 - Dyad / Group
else if(
categoriesArray.includes('id') &&
categoriesArray.includes('variable') &&
!categoriesArray.includes('time') &&
categoriesArray.includes('group') &&
!categoriesArray.includes('variable2') &&
!categoriesArray.includes('variable3'))
{ const dyadQuestion = <div><h3>Is the group a dyad?</h3>
<ButtonToolbar><Button bsStyle={styleDyadYes} onClick={() =>
this.updateGraphQuestions(partId, groupComp, topicId)}>Yes</Button>
<Button bsStyle={styleDyadNo} onClick={() =>
this.updateGraphQuestions(false, groupComp, topicId)}>No</Button></ButtonToolbar></div>
let groupQuestion;
if (dyad === false) {groupQuestion = <div><h3>Show the comparison to all groups?</h3>
<ButtonToolbar><Button bsStyle={styleGCYes} onClick={() =>
this.updateGraphQuestions(dyad, true, topicId)}>Yes</Button>
<Button bsStyle={styleGCNo} onClick={() =>
this.updateGraphQuestions(dyad, false, topicId)}>No</Button></ButtonToolbar></div>}
graphQuestions = <Well><Row><Col md={6}>{dyadQuestion}</Col>
<Col md={6}>{groupQuestion}</Col></Row></Well>
graph = <BoxPlot data_noH={data_noH} headers={headers}
topicConfig={topicConfig} partId={partId} dyad={dyad} groupComp={groupComp}
urlUpdate={this.updateURL}/>
}
// Type 1 - only variable
else if (
categoriesArray.includes('id') &&
categoriesArray.includes('variable') &&
!categoriesArray.includes('time') &&
!categoriesArray.includes('group') &&
!categoriesArray.includes('variable2') &&
!categoriesArray.includes('variable3'))
{ graph = <BoxPlot data_noH={data_noH} headers={headers}
topicConfig={topicConfig} partId={partId}
urlUpdate={this.updateURL}/>}
//// End of topics
///// Pagination
let previousButton;
let nextButton;
if (topicId > 1) {
const prevConfig = this.props.topicsConfig[topicId-2];
previousButton = <LinkContainer to={'/topic-edit/'+ String(Number(topicId)-1)}><Pager.Item>
← Configure previous research question: {prevConfig.topicName}
</Pager.Item></LinkContainer>};
if (topicId < this.props.topicsConfig.length) {
const nextConfig = this.props.topicsConfig[topicId];
nextButton = <LinkContainer to={'/topic-edit/'+ String(Number(topicId)+1)}><Pager.Item>
Configure next research question: {nextConfig.topicName} →
</Pager.Item></LinkContainer>};
if (topicId >= this.props.topicsConfig.length) {
nextButton = <LinkContainer to={'/'}><Pager.Item>
Add new research question →
</Pager.Item></LinkContainer>};
/////// End of pagination
return (
<div>
<Grid>
<Row>
<h2>You are editing research question {topicId}: {topicName}</h2>
</Row>
<Row>
<Col md={6}><Well>
<p><font size="4">You can set up the research question here. For each topic, the
participants will see a graph (displaying their individual values)
and a text (written by you) explaining the graph.</font></p>
</Well></Col>
<Col md={6}>
<p>Here is the list of the columns you have chosen in the previous page: </p>
<ul>
{variableArray.map(variable => (<li key={variable}>{variable}</li>))}
</ul>
</Col>
</Row>
{/* Topic text */}
<Row >
<Panel bsStyle="warning" defaultExpanded={true}>
<Panel.Heading>
<Panel.Title componentClass="h3" toggle>Description of the research question (click to close)</Panel.Title>
</Panel.Heading>
<Panel.Collapse>
<Panel.Body>
<p>You can add values refering to your data in this text. To do so, please write the
name of the computed value after a # (e.g. #sample_mean_Affect). This will automatically replace the tag by the correct value.</p>
<p>The following computed values are available:</p>
<ul>
{allowedCompVals.map(variable => (<li key={variable}>{variable}</li>))}
</ul>
<FormGroup controlId="topicText">
<FormControl
type="text"
componentClass="textarea"
style={{ height: 200 }}
value={topicText}
placeholder="Enter your text"
onChange={(event) => (this.updateTextHandler(event, 'topicText', topicId, allowedCompVals, compVals))}/>
</FormGroup>
</Panel.Body>
</Panel.Collapse>
</Panel>
</Row>
{/* Graph questions */}
<Row>
{graphQuestions}
</Row>
{/* Preview */}
<Row>
<Panel defaultExpanded>
<Panel.Heading>
<Panel.Title toggle>This is what a random participant would see (click to close)</Panel.Title>
</Panel.Heading>
<Panel.Collapse><Panel.Body>
<ControlLabel>This is your general text on the topic</ControlLabel>
<p onClick={() => this.handleTextClick('topicText')}>{topicText}</p>
<Col md={6}>
{graph}
<form><FormGroup controlId="formControlsTextarea">
<ControlLabel>Here you can update the graph explanation</ControlLabel>
<FormControl componentClass="textarea" value={graphText}
style={{ height: 150 }}
onChange={(event) => (this.updateTextHandler(event, 'graphText', topicId, allowedCompVals, compVals))}/>
</FormGroup></form>
</Col>
<Col md={6}>
<ControlLabel>This is your personalized text:</ControlLabel>
<p onClick={() => this.handleTextClick('catText')}>{personalizedText}</p>
</Col>
</Panel.Body></Panel.Collapse>
</Panel></Row>
{/* Personalized text (yes/no) */}
<Row>
<CatText textOptions={topicEdited.textOptions} allowedCompVals={allowedCompVals}
updateCatText={(newValue, text) => (this.updateTextHandler(newValue, text, topicId, allowedCompVals, compVals))}/>
</Row>
{/* Pager */}
<Row>
<Pager>
{previousButton}
{nextButton}
</Pager>
<Pager>
<LinkContainer to='/'><Pager.Item >
← Overview of the research questions
</Pager.Item></LinkContainer>
<LinkContainer to='/feedback-info'><Pager.Item>
Go to study information →
</Pager.Item></LinkContainer>
</Pager>
</Row>
</Grid>
</div>
);
}
} |
JavaScript | class Authenticator extends cr.EventTarget {
/**
* @param {webview|string} webview The webview element or its ID to host
* IdP web pages.
*/
constructor(webview) {
super();
this.initialFrameUrl_ = null;
this.webviewEventManager_ = WebviewEventManager.create();
this.bindToWebview_(webview);
window.addEventListener('focus', this.onFocus_.bind(this), false);
}
/**
* Reinitializes saml handler.
*/
resetStates() {
this.samlHandler_.reset();
}
/**
* Resets the webview to the blank page.
*/
resetWebview() {
if (this.webview_.src && this.webview_.src != BLANK_PAGE_URL) {
this.webview_.src = BLANK_PAGE_URL;
}
}
/**
* Binds this authenticator to the passed webview.
* @param {!Object} webview the new webview to be used by this
* Authenticator.
* @private
*/
bindToWebview_(webview) {
assert(!this.webview_);
assert(!this.samlHandler_);
this.webview_ = typeof webview == 'string' ? $(webview) : webview;
this.samlHandler_ =
new cr.login.SamlHandler(this.webview_, true /* startsOnSamlPage */);
this.webviewEventManager_.addEventListener(
this.samlHandler_, 'authPageLoaded',
this.onAuthPageLoaded_.bind(this));
// Listen for main-frame redirects to check for success - we can mostly
// detect success by detecting we POSTed something to the password-change
// URL, and the response redirected us to a particular success URL.
this.webviewEventManager_.addWebRequestEventListener(
this.webview_.request.onBeforeRedirect,
this.onBeforeRedirect_.bind(this),
{urls: ['*://*/*'], types: ['main_frame']},
);
// Inject a custom script for detecting password change success in Okta.
this.webview_.addContentScripts([{
name: oktaInjectedScriptName,
matches: ['*://*.okta.com/*'],
js: {code: oktaInjectedJs},
all_frames: true,
run_at: 'document_start'
}]);
// Connect to the script running in Okta web pages once it loads.
this.webviewEventManager_.addWebRequestEventListener(
this.webview_.request.onCompleted,
this.onOktaCompleted_.bind(this),
{urls: ['*://*.okta.com/*'], types: ['main_frame']},
);
// Okta-detect-success-inject script signals success by posting a message
// that says "passwordChangeSuccess", which we listen for:
this.webviewEventManager_.addEventListener(
window, 'message', this.onMessageReceived_.bind(this));
}
/**
* Unbinds this Authenticator from the currently bound webview.
* @private
*/
unbindFromWebview_() {
assert(this.webview_);
assert(this.samlHandler_);
this.webviewEventManager_.removeAllListeners();
this.webview_ = undefined;
this.samlHandler_.unbindFromWebview();
this.samlHandler_ = undefined;
}
/**
* Re-binds to another webview.
* @param {Object} webview the new webview to be used by this Authenticator.
*/
rebindWebview(webview) {
this.unbindFromWebview_();
this.bindToWebview_(webview);
}
/**
* Loads the authenticator component with the given parameters.
* @param {AuthMode} authMode Authorization mode.
* @param {Object} data Parameters for the authorization flow.
*/
load(data) {
this.resetStates();
this.initialFrameUrl_ = this.constructInitialFrameUrl_(data);
this.samlHandler_.blockInsecureContent = true;
this.webview_.src = this.initialFrameUrl_;
}
constructInitialFrameUrl_(data) {
let url;
url = data.passwordChangeUrl;
if (data.userName) {
url = appendParam(url, 'username', data.userName);
}
return url;
}
/**
* Invoked when the sign-in page takes focus.
* @param {object} e The focus event being triggered.
* @private
*/
onFocus_(e) {
this.webview_.focus();
}
/**
* Sends scraped password and resets the state.
* @param {bool} isOkta whether the page is Okta page.
* @private
*/
onPasswordChangeSuccess_(isOkta) {
let passwordsOnce;
let passwordsTwice;
if (isOkta) {
passwordsOnce = this.samlHandler_.getPasswordsWithPropertyScrapedTimes(
1, 'oldPassword');
const newPasswords =
this.samlHandler_.getPasswordsWithPropertyScrapedTimes(
1, 'newPassword');
const verifyPasswords =
this.samlHandler_.getPasswordsWithPropertyScrapedTimes(
1, 'verifyPassword');
if (newPasswords.length == 1 && verifyPasswords.length == 1 &&
newPasswords[0] === verifyPasswords[0]) {
passwordsTwice = Array.from(newPasswords);
} else {
passwordsTwice = [];
}
} else {
passwordsOnce =
this.samlHandler_.getPasswordsWithPropertyScrapedTimes(1);
passwordsTwice =
this.samlHandler_.getPasswordsWithPropertyScrapedTimes(2);
}
this.dispatchEvent(new CustomEvent('authCompleted', {
detail: {
old_passwords: passwordsOnce,
new_passwords: passwordsTwice,
}
}));
this.resetStates();
}
/**
* Invoked when |samlHandler_| fires 'authPageLoaded' event.
* @private
*/
onAuthPageLoaded_(e) {
this.webview_.focus();
}
/**
* Invoked when a new document loading completes.
* @param {Object} details The web-request details.
* @private
*/
onBeforeRedirect_(details) {
if (details.method == 'POST' &&
detectPasswordChangeSuccess(
safeParseUrl_(details.url), safeParseUrl_(details.redirectUrl))) {
this.onPasswordChangeSuccess_(false /* isOkta != OKTA */);
}
}
/**
* Invoked when loading completes on an Okta page.
* @param {Object} details The web-request details.
* @private
*/
onOktaCompleted_(details) {
// Okta_detect_success_injected.js needs to be contacted by the parent,
// so that it can send messages back to the parent.
// Using setTimeout gives the page time to finish initializing.
// TODO: timeout value is chosen empirically, we need a better way
// to pass this to the injected code.
setTimeout(() => {
this.webview_.contentWindow.postMessage('connect', details.url);
}, 2000);
}
/**
* Invoked when the webview posts a message.
* @param {Object} event The message event.
* @private
*/
onMessageReceived_(event) {
if (event.data == 'passwordChangeSuccess') {
const pageProvider = detectProvider_(safeParseUrl_(event.origin));
if (pageProvider == PasswordChangePageProvider.OKTA) {
this.onPasswordChangeSuccess_(true /* isOkta == OKTA */);
}
}
}
} |
JavaScript | class PlanningView extends Component {
render() {
const userid = 1
// Run a query for highest amount transactions, recurring ones, and statistics then display
return (
<Query query={PlanningViewQuery} variables={{userid}}>
{({ loading, error, data }) => {
if (loading) return <Spinner style={{ width: '10rem', height: '10rem', position:'absolute', top: '40vh', left:'40vw'}} />
if (error) {
console.log(error);
return <div>Error</div>
}
const { top, recurring, transaction_aggregate } = data
return (
<div>
<Jumbotron className="mt-5 text-center pb-6">
<h2 className="display-4 pb-2">View all of your important financial data in one place!</h2>
<hr/>
<h3 className="font-weight-light">This is your go to page for custom statistics to track your spending.</h3>
</Jumbotron>
<Row>
<Col sm={4}>
<TransactionStatistics data={transaction_aggregate}/>
</Col>
<Col sm={4}>
<TransactionList transactions={top} text={"Here are your largest transactions to date!"}/>
</Col>
<Col sm={4}>
<TransactionList transactions={recurring} text={"Below are your recurring transactions!"}/>
</Col>
</Row>
</div>
)
}}
</Query>);
}
} |
JavaScript | class Bot extends CommandGroupBase {
/**
* Constructs a new bot
* @param {*} client - A tmi.js client to wrap
* @param {Object} options - keyword arguments to configure the bot
* @param {string} options.prefix - The prefix to use for the bot
*/
constructor(client, { prefix='' }) {
super();
this.client = client;
this.prefix = prefix;
client.on("message", (channel, userstate, message, self) => {
if (self) return;
this.process(channel, userstate, message);
});
}
process(channel, userstate, message) {
let parser = new StringView(message);
parser.skipWhitespace();
if (!parser.skipValue(this.prefix)) {
return;
}
let ctx = new Context(this.client, channel, userstate);
this.invoke(ctx, parser);
}
} |
JavaScript | class SessionError extends Error {
constructor(message, code) {
super();
this.name = this.constructor.name;
this.message = message;
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
else {
this.stack = (new Error()).stack;
}
}
} |
JavaScript | class RuleContext {
constructor(ruleName, pluginName, dirname, filename, options, severity, verboseMode, shared) {
this.ruleName = ruleName;
this.pluginName = pluginName;
this.filesystem = {
dirname,
filename
};
this.options = { ...options };
this.severity = severity;
this.verboseMode = verboseMode;
this.shared = shared;
Object.freeze(this);
Object.freeze(this.filesystem);
Object.freeze(this.options);
}
} |
JavaScript | class Task {
/**
* Create a task instance.
* @param {Object} input Object to initialize the instance.
* @param {String} input.name Task display name.
* @param {String} input.desc Task help display text.
* @param {String} input.help Task help full text.
* @param {String[]} input.preq Task prerequisites to check before it is ran.
* @param {String[]} input.perm Task Discord permissions to check before it is ran.
* @param {Object[]} input.args Task help arguments display.
* @param {String} input.args[].name Argument property name.
* @param {String} input.args[].desc Argument property description.
* @param {Boolean} input.args[].optional Argument property requirement.
* @param {Number} input.time Task cooldown in seconds.
* @param {Function} input.task Task method to invoke when called.
*/
constructor(input) {
this.name = input.name || "";
this.desc = input.desc || "";
this.help = input.help || "";
this.preq = input.preq || [];
this.perm = input.perm || [];
this.args = input.args || [];
this.task = input.task;
}
/**
* Get instance name.
* @return {String} The instance name.
*/
getName() {
return this.name;
}
/**
* Get instance description.
* @return {String} The instance description.
*/
getDescription() {
return this.desc;
}
/**
* Get instance help text.
* @return {String} The instance help text.
*/
getHelp() {
return this.help;
}
/**
* Get instance prerequisites.
* @return {String[]} The instance prerequsites.
*/
getPrerequisites() {
return this.preq;
}
/**
* Get instance permissions.
* @return {String[]} The instance permissions.
*/
getPermissions() {
return this.perm;
}
/**
* Invoke instance method.
*/
runTask() {
this.task();
}
} |
JavaScript | class ResourceTable extends React.Component {
render() {
function ResourceTableRow(data) {
const location = data.location;
const website = (location.organization && location.organization.website) || location.website;
return <tr>
<td>{website ? <a target='_blank' href={website}>{location.name || ''}</a> : location.name || ''}</td>
<td>{location.phones && location.phones.length ? location.phones[0].number : ''}</td>
<td>{location.address && location.address.address_1 ? location.address.address_1 : ''}</td>
</tr>;
}
return (
<div>
<table className="table table-striped">
<thead>
<tr>
<th>Resource</th>
<th>Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{ (this.props.locations || []).map((location, idx) => <ResourceTableRow key={idx} location={location} />) }
</tbody>
</table>
</div>
);
}
} |
JavaScript | class Panel {
/**
* @param {HTMLElement} menuElement - menu dom element
* @param {Object} options - menu options
* @param {string} options.name - name of panel menu
*/
constructor(menuElement, { name }) {
this.name = name;
this.items = [];
this.panelElement = this._makePanelElement();
this.listElement = this._makeListElement();
this.panelElement.appendChild(this.listElement);
menuElement.appendChild(this.panelElement);
}
/**
* Make Panel element
* @returns {HTMLElement}
*/
_makePanelElement() {
const panel = document.createElement('div');
panel.className = `tie-panel-${this.name}`;
return panel;
}
/**
* Make list element
* @returns {HTMLElement} list element
* @private
*/
_makeListElement() {
const list = document.createElement('ol');
list.className = `${this.name}-list`;
return list;
}
/**
* Make list item element
* @param {string} html - history list item html
* @returns {HTMLElement} list item element
*/
makeListItemElement(html) {
const listItem = document.createElement('li');
listItem.innerHTML = html;
listItem.className = `${this.name}-item`;
listItem.setAttribute('data-index', this.items.length);
return listItem;
}
/**
* Push list item element
* @param {HTMLElement} item - list item element to add to the list
*/
pushListItemElement(item) {
this.listElement.appendChild(item);
this.listElement.scrollTop += item.offsetHeight;
this.items.push(item);
}
/**
* Delete list item element
* @param {number} start - start index to delete
* @param {number} end - end index to delete
*/
deleteListItemElement(start, end) {
const { items } = this;
for (let i = start; i < end; i += 1) {
this.listElement.removeChild(items[i]);
}
items.splice(start, end - start + 1);
}
/**
* Get list's length
* @returns {number}
*/
getListLength() {
return this.items.length;
}
/**
* Add class name of item
* @param {number} index - index of item
* @param {string} className - class name to add
*/
addClass(index, className) {
if (this.items[index]) {
this.items[index].classList.add(className);
}
}
/**
* Remove class name of item
* @param {number} index - index of item
* @param {string} className - class name to remove
*/
removeClass(index, className) {
if (this.items[index]) {
this.items[index].classList.remove(className);
}
}
/**
* Toggle class name of item
* @param {number} index - index of item
* @param {string} className - class name to remove
*/
toggleClass(index, className) {
if (this.items[index]) {
this.items[index].classList.toggle(className);
}
}
} |
JavaScript | class LabsSearchFacets extends PolymerElement {
static get properties() {
return {
/**
* Reference to bound listener functions to be removed in disconnectedCallback
*/
_boundListeners: {
type: Object,
value: function() {
return {
_onFacetGroupingChange: null
};
}
},
};
}
static get is() { return 'd2l-labs-search-facets'; }
static get template() {
return html`
<style>
:host {
display: block;
}
</style>
<slot></slot>
`;
}
connectedCallback() {
super.connectedCallback();
afterNextRender(this, () => {
this._boundListeners._onFacetGroupingChange = this._onFacetGroupingChange.bind(this);
this.addEventListener('d2l-labs-search-facets-grouping-change',
this._boundListeners._onFacetGroupingChange);
});
}
disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener('d2l-labs-search-facets-grouping-change',
this._boundListeners._onFacetGroupingChange);
}
_onFacetGroupingChange(e) {
this.dispatchEvent(new CustomEvent('d2l-labs-search-facets-change', {
bubbles: true, composed: true, detail: e.detail
}));
}
} |
JavaScript | class BitGoJsError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
videos: [],
};
this.videoSearch('miley cyrus');
}
videoSearch(term) {
}
render() {
return (
<div>
<SearchBar onSearchTermChange={term => this.videoSearch(term)}/>
<div className="row">
<VideoDetail/>
<VideoList/>
</div>
</div>
);
}
} |
JavaScript | class LinearEdge extends React.Component {
handleClick(e) {
if (this.props.onSelectionChange) {
this.props.onSelectionChange("edge", this.props.name);
}
e.stopPropagation();
}
render() {
let classed = "edge-linear";
let labelClassed = "edge-label";
let styleModifier = "normal";
if (this.props.selected) {
classed += " selected";
labelClassed += "selected";
styleModifier = "selected";
}
if (this.props.muted) {
classed += " muted";
labelClassed += "muted";
styleModifier = "muted";
}
if (this.props.invisible) {
classed += " edge-event-region";
labelClassed += " edge-event-region";
}
if (!_.isUndefined(this.props.classed)) {
classed += " " + this.props.classed;
}
const source = new Vector(this.props.x1, this.props.y1);
const target = new Vector(this.props.x2, this.props.y2);
const diff = target.clone().subtract(source);
const norm = diff.clone().norm();
const perp = new Vector(-norm.y, norm.x);
const offset = new Vector(this.props.offset, this.props.offset);
offset.multiply(perp);
//
// If the edge has multiple paths, with this edge being at
// 'position' (this.props.position) then calculate those
//
const position = this.props.position;
const arrowWidth = this.props.arrowWidth || this.props.width * 1.5;
const arrowLength = this.props.arrowHeight || this.props.width * 2;
// Positioned lines bend from source, to sourceBendControl, to
// targetBendControl, and end at target.
const bendOffset = this.props.position !== 0 ? 15 : 8;
const bendScalar = new Vector(bendOffset, bendOffset);
const sourceToTarget = target.clone().subtract(source);
const sourceToTargetNormalize = sourceToTarget.clone().norm();
const targetToSource = source.clone().subtract(target);
const targetToSourceNormalize = targetToSource.clone().norm();
const sourceBend = sourceToTargetNormalize
.clone()
.multiply(bendScalar)
.add(source);
const targetBend = targetToSourceNormalize
.clone()
.multiply(bendScalar)
.add(target);
const sourceBendPerp = new Vector(-sourceToTargetNormalize.y, sourceToTargetNormalize.x);
const sourceBendPerpScalar = new Vector(position, position);
const sourceBendControl = sourceBendPerp
.clone()
.multiply(sourceBendPerpScalar)
.add(sourceBend);
const targetBendPerp = new Vector(-targetToSourceNormalize.y, targetToSourceNormalize.x);
const targetBendPerpScalar = new Vector(-position, -position);
const targetBendControl = targetBendPerp
.clone()
.multiply(targetBendPerpScalar)
.add(targetBend);
// Arrow at the target end
const arrowLengthScalar = new Vector(-arrowLength, -arrowLength);
const arrowLeftScalar = new Vector(arrowWidth / 2, arrowWidth / 2);
const arrowRightScalar = new Vector(-arrowWidth / 2, -arrowWidth / 2);
const arrowHead = targetToSourceNormalize
.clone()
.multiply(arrowLengthScalar)
.add(targetBendControl);
const arrowBaseLeft = targetBendPerp
.clone()
.multiply(arrowLeftScalar)
.add(targetBendControl);
const arrowBaseRight = targetBendPerp
.clone()
.multiply(arrowRightScalar)
.add(targetBendControl);
// Line and Arc SVG path
let path = "";
path += "M" + source.x + "," + source.y;
path += " L " + sourceBendControl.x + " " + sourceBendControl.y;
path += " L " + targetBendControl.x + " " + targetBendControl.y;
// Arrow SVG path
if (!this.props.arrow) {
path += " L " + target.x + " " + target.y;
}
// Arrow SVG path
let arrow = "M" + arrowHead.x + "," + arrowHead.y + " ";
arrow += "L" + arrowBaseLeft.x + "," + arrowBaseLeft.y;
arrow += "L" + arrowBaseRight.x + "," + arrowBaseRight.y;
let opacity = 1.0;
if (this.props.invisible) {
opacity = 0.0;
} else if (this.props.muted) {
opacity = 0.3;
}
// Label Positioning
const ry = Math.abs(targetBendControl.y - sourceBendControl.y);
const rx = Math.abs(targetBendControl.x - sourceBendControl.x);
let angle = Math.atan2(ry, rx) * 180 / Math.PI;
const cx = (sourceBendControl.x + targetBendControl.x) / 2;
const cy = (sourceBendControl.y + targetBendControl.y) / 2;
if (
(target.y < source.y && source.x < target.x) ||
(source.x > target.x && target.y > source.y)
) {
angle = -angle;
}
let labelElement = null;
if (this.props.label) {
labelElement = (
<Label
x={cx}
y={cy}
r={angle}
textAnchor={this.props.textAnchor}
classed={labelClassed}
style={this.props.labelStyle[styleModifier]}
label={this.props.label}
xOffset={this.props.labelOffsetX}
yOffset={this.props.labelOffsetY}
labelPosition={this.props.labelPosition}
/>
);
}
if (this.props.arrow) {
return (
<g>
<g strokeWidth={this.props.width} stroke={this.props.color} opacity={opacity}>
<path
className={classed}
d={path}
fill="none"
onClick={e => this.handleClick(e)}
/>
<path
className={classed}
d={arrow}
fill={this.props.color}
strokeWidth="1"
/>
</g>
{labelElement}
</g>
);
} else {
return (
<g>
<g strokeWidth={this.props.width} stroke={this.props.color} opacity={opacity}>
<path
className={classed}
d={path}
fill="none"
onClick={e => this.handleClick(e)}
/>
</g>
{labelElement}
</g>
);
}
}
} |
JavaScript | class TemporalCheck {
static toIsoArray ( myFields) { return [myFields.isoYear, myFields.isoMonth, myFields.isoDay] }
static checkOverflowOption (options) {
switch (options.overflow) {
case undefined : options.overflow = "constrain"; break;
case "constrain" : case "reject" : break;
default : throw new RangeError ("Unknown option for 'overflow': " + options.overflow);
}
return options.overflow;
}
/** Check that year components are complete and do not contradict each other, return the year's scalar value or throws if incomplete
* @param (Object) components: the date components.
* @param (Array) eras: the list of eras for this calendar. It is assumed that eras[0] is backward, i.e. 1-y mode, and that year = eraYear all other eras.
* @return (Number) : the scalar year value.
*/
static getYearFromFields (components, eras) {
if ( components.era != undefined) if (! eras.includes(components.era))
throw new RangeError ("Unknown era value in this calendar: " + components.era);
if ((components.era != undefined) != (components.eraYear != undefined))
throw new TypeError ("Properties 'era' and 'eraYear' should be specified together.");
if ( (components.year == undefined)
&& (components.eraYear == undefined || components.era == undefined) )
throw new TypeError ("Incomplete or missing year specification.");
if ( components.year != undefined && components.eraYear != undefined &&
components.year != components.eraYear && (components.era != eras[0] || components.year != 1 - components.eraYear) )
throw new RangeError ("Relative year " + components.year + " does not match era and eraYear: " + components.era + " " + components.eraYear);
if (components.year == undefined)
{ return components.era == eras[0] ? 1 - components.eraYear : components.eraYear }
else return components.year;
}
/** Check that month and monthCode components are complete and do not contradict each other, return the month's numeric value or throws if incomplete
* @param (Object) components: the date components.
* @param (RegExp) reg: the Rgular Expression (regexp) for a month code in this calendar
* @return (Number): the month number.
*/
static getMonthFromFields (components, reg) {
let m = components.month;
if (components.monthCode != undefined) if (! reg.test (components.monthCode) )
throw new RangeError ("Unknown month code for the target calendar: " + components.monthCode);
if (components.month == undefined) m = Number(components.monthCode.match(/\d+/)[0]);
if (components.monthCode != undefined) if (m != Number(components.monthCode.match(/\d+/)[0]))
throw new RangeError ("Computed month number " + m + " differs from month code " + components.monthCode);
if (isNaN(m)) throw new TypeError("Wrong type or missing value for month: " + components.month);
return m
}
} |
JavaScript | class CharAt extends FunctionBrick {
/**
* Executed every time an input gets updated.
* Note that this method will _not_ be executed if an input value is undefined.
*
* @protected
* @param {!Context} context
* @param {string} s
* @param {number} index
* @param {function(string)} setResult
*/
onUpdate(context, [s, index], [setResult]) {
setResult(String(s).charAt(index));
}
} |
JavaScript | class BasicGrammar extends Grammar {
constructor() {
super("BASIC",
// Grammar rules are applied in the order they are specified.
[
["newlines", /(?:\r\n|\r|\n)/],
// BASIC programs used to require the programmer type in her own line numbers. The start at the beginning of the line.
["lineNumbers", /^\d+\s+/],
["whitespace", /(?:\s+)/],
// Comments were lines that started with the keyword "REM" (for REMARK) and ran to the end of the line. They did not have to be numbered, because they were not executable and were stripped out by the interpreter.
["startLineComments", /^REM\s/],
// Both double-quoted and single-quoted strings were not always supported, but in this case, I'm just demonstrating how it would be done for both.
["stringDelim", /("|')/],
// Numbers are an optional dash, followed by a optional digits, followed by optional period, followed by 1 or more required digits. This allows us to match both integers and decimal numbers, both positive and negative, with or without leading zeroes for decimal numbers between (-1, 1).
["numbers", /-?(?:(?:\b\d*)?\.)?\b\d+\b/],
// Keywords are really just a list of different words we want to match, surrounded by the "word boundary" selector "\b".
["keywords",
/\b(?:RESTORE|REPEAT|RETURN|LOAD|LABEL|DATA|READ|THEN|ELSE|FOR|DIM|LET|IF|TO|STEP|NEXT|WHILE|WEND|UNTIL|GOTO|GOSUB|ON|TAB|AT|END|STOP|PRINT|INPUT|RND|INT|CLS|CLK|LEN)\b/
],
// Sometimes things we want to treat as keywords have different meanings in different locations. We can specify rules for tokens more than once.
["keywords", /^DEF FN/],
// These are all treated as mathematical operations.
["operators",
/(?:\+|;|,|-|\*\*|\*|\/|>=|<=|=|<>|<|>|OR|AND|NOT|MOD|\(|\)|\[|\])/
],
// Once everything else has been matched, the left over blocks of words are treated as variable and function names.
["members", /\w+\$?/]
]);
}
tokenize(code) {
return super.tokenize(code.toUpperCase());
}
interpret(sourceCode, input, output, errorOut, next, clearScreen, loadFile, done) {
var tokens = this.tokenize(sourceCode),
EQUAL_SIGN = new Token("=", "operators"),
counter = 0,
isDone = false,
program = new Map(),
lineNumbers = [],
currentLine = [],
lines = [currentLine],
data = [],
returnStack = [],
forLoopCounters = new Map(),
dataCounter = 0;
Object.assign(window, {
INT: function (v) {
return v | 0;
},
RND: function () {
return Math.random();
},
CLK: function () {
return Date.now() / 3600000;
},
LEN: function (id) {
return id.length;
},
LINE: function () {
return lineNumbers[counter];
},
TAB: function (v) {
var str = "";
for (var i = 0; i < v; ++i) {
str += " ";
}
return str;
},
POW: function (a, b) {
return Math.pow(a, b);
}
});
function toNum(ln) {
return new Token(ln.toString(), "numbers");
}
function toStr(str) {
return new Token("\"" + str.replace("\n", "\\n")
.replace("\"", "\\\"") + "\"", "strings");
}
var tokenMap = {
"OR": "||",
"AND": "&&",
"NOT": "!",
"MOD": "%",
"<>": "!="
};
while (tokens.length > 0) {
var token = tokens.shift();
if (token.type === "newlines") {
currentLine = [];
lines.push(currentLine);
}
else if (token.type !== "regular" && token.type !== "comments") {
token.value = tokenMap[token.value] || token.value;
currentLine.push(token);
}
}
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
if (line.length > 0) {
var lastLine = lineNumbers[lineNumbers.length - 1];
var lineNumber = line.shift();
if (lineNumber.type !== "lineNumbers") {
line.unshift(lineNumber);
if (lastLine === undefined) {
lastLine = -1;
}
lineNumber = toNum(lastLine + 1);
}
lineNumber = parseFloat(lineNumber.value);
if (lastLine && lineNumber <= lastLine) {
throw new Error("expected line number greater than " + lastLine +
", but received " + lineNumber + ".");
}
else if (line.length > 0) {
lineNumbers.push(lineNumber);
program.set(lineNumber, line);
}
}
}
function process(line) {
if (line && line.length > 0) {
var op = line.shift();
if (op) {
if (commands.hasOwnProperty(op.value)) {
return commands[op.value](line);
}
else if (!isNaN(op.value)) {
return setProgramCounter([op]);
}
else if (window[op.value] ||
(line.length > 0 && line[0].type === "operators" &&
line[0].value === "=")) {
line.unshift(op);
return translate(line);
}
else {
error("Unknown command. >>> " + op.value);
}
}
}
return pauseBeforeComplete();
}
function error(msg) {
errorOut("At line " + lineNumbers[counter] + ": " + msg);
}
function getLine(i) {
var lineNumber = lineNumbers[i];
var line = program.get(lineNumber);
return line && line.slice();
}
function evaluate(line) {
var script = "";
for (var i = 0; i < line.length; ++i) {
var t = line[i];
var nest = 0;
if (t.type === "identifiers" &&
typeof window[t.value] !== "function" &&
i < line.length - 1 &&
line[i + 1].value === "(") {
for (var j = i + 1; j < line.length; ++j) {
var t2 = line[j];
if (t2.value === "(") {
if (nest === 0) {
t2.value = "[";
}
++nest;
}
else if (t2.value === ")") {
--nest;
if (nest === 0) {
t2.value = "]";
}
}
else if (t2.value === "," && nest === 1) {
t2.value = "][";
}
if (nest === 0) {
break;
}
}
}
script += t.value;
}
try {
return eval(script); // jshint ignore:line
}
catch (exp) {
console.error(exp);
console.debug(line.join(", "));
console.error(script);
error(exp.message + ": " + script);
}
}
function declareVariable(line) {
var decl = [],
decls = [decl],
nest = 0,
i;
for (i = 0; i < line.length; ++i) {
var t = line[i];
if (t.value === "(") {
++nest;
}
else if (t.value === ")") {
--nest;
}
if (nest === 0 && t.value === ",") {
decl = [];
decls.push(decl);
}
else {
decl.push(t);
}
}
for (i = 0; i < decls.length; ++i) {
decl = decls[i];
var id = decl.shift();
if (id.type !== "identifiers") {
error("Identifier expected: " + id.value);
}
else {
var val = null,
j;
id = id.value;
if (decl[0].value === "(" && decl[decl.length - 1].value === ")") {
var sizes = [];
for (j = 1; j < decl.length - 1; ++j) {
if (decl[j].type === "numbers") {
sizes.push(decl[j].value | 0);
}
}
if (sizes.length === 0) {
val = [];
}
else {
val = new Array(sizes[0]);
var queue = [val];
for (j = 1; j < sizes.length; ++j) {
var size = sizes[j];
for (var k = 0,
l = queue.length; k < l; ++k) {
var arr = queue.shift();
for (var m = 0; m < arr.length; ++m) {
arr[m] = new Array(size);
if (j < sizes.length - 1) {
queue.push(arr[m]);
}
}
}
}
}
}
window[id] = val;
return true;
}
}
}
function print(line) {
var endLine = "\n";
var nest = 0;
line = line.map(function (t, i) {
t = t.clone();
if (t.type === "operators") {
if (t.value === ",") {
if (nest === 0) {
t.value = "+ \", \" + ";
}
}
else if (t.value === ";") {
t.value = "+ \" \"";
if (i < line.length - 1) {
t.value += " + ";
}
else {
endLine = "";
}
}
else if (t.value === "(") {
++nest;
}
else if (t.value === ")") {
--nest;
}
}
return t;
});
var txt = evaluate(line);
if (txt === undefined) {
txt = "";
}
output(txt + endLine);
return true;
}
function setProgramCounter(line) {
var lineNumber = parseFloat(evaluate(line));
counter = -1;
while (counter < lineNumbers.length - 1 &&
lineNumbers[counter + 1] < lineNumber) {
++counter;
}
return true;
}
function checkConditional(line) {
var thenIndex = -1,
elseIndex = -1,
i;
for (i = 0; i < line.length; ++i) {
if (line[i].type === "keywords" && line[i].value === "THEN") {
thenIndex = i;
}
else if (line[i].type === "keywords" && line[i].value === "ELSE") {
elseIndex = i;
}
}
if (thenIndex === -1) {
error("Expected THEN clause.");
}
else {
var condition = line.slice(0, thenIndex);
for (i = 0; i < condition.length; ++i) {
var t = condition[i];
if (t.type === "operators" && t.value === "=") {
t.value = "==";
}
}
var thenClause,
elseClause;
if (elseIndex === -1) {
thenClause = line.slice(thenIndex + 1);
}
else {
thenClause = line.slice(thenIndex + 1, elseIndex);
elseClause = line.slice(elseIndex + 1);
}
if (evaluate(condition)) {
return process(thenClause);
}
else if (elseClause) {
return process(elseClause);
}
}
return true;
}
function pauseBeforeComplete() {
output("PROGRAM COMPLETE - PRESS RETURN TO FINISH.");
input(function () {
isDone = true;
if (done) {
done();
}
});
return false;
}
function labelLine(line) {
line.push(EQUAL_SIGN);
line.push(toNum(lineNumbers[counter]));
return translate(line);
}
function waitForInput(line) {
var toVar = line.pop();
if (line.length > 0) {
print(line);
}
input(function (str) {
str = str.toUpperCase();
var valueToken = null;
if (!isNaN(str)) {
valueToken = toNum(str);
}
else {
valueToken = toStr(str);
}
evaluate([toVar, EQUAL_SIGN, valueToken]);
if (next) {
next();
}
});
return false;
}
function onStatement(line) {
var idxExpr = [],
idx = null,
targets = [];
try {
while (line.length > 0 &&
(line[0].type !== "keywords" ||
line[0].value !== "GOTO")) {
idxExpr.push(line.shift());
}
if (line.length > 0) {
line.shift(); // burn the goto;
for (var i = 0; i < line.length; ++i) {
var t = line[i];
if (t.type !== "operators" ||
t.value !== ",") {
targets.push(t);
}
}
idx = evaluate(idxExpr) - 1;
if (0 <= idx && idx < targets.length) {
return setProgramCounter([targets[idx]]);
}
}
}
catch (exp) {
console.error(exp);
}
return true;
}
function gotoSubroutine(line) {
returnStack.push(toNum(lineNumbers[counter + 1]));
return setProgramCounter(line);
}
function setRepeat() {
returnStack.push(toNum(lineNumbers[counter]));
return true;
}
function conditionalReturn(cond) {
var ret = true;
var val = returnStack.pop();
if (val && cond) {
ret = setProgramCounter([val]);
}
return ret;
}
function untilLoop(line) {
var cond = !evaluate(line);
return conditionalReturn(cond);
}
function findNext(str) {
for (i = counter + 1; i < lineNumbers.length; ++i) {
var l = getLine(i);
if (l[0].value === str) {
return i;
}
}
return lineNumbers.length;
}
function whileLoop(line) {
var cond = evaluate(line);
if (!cond) {
counter = findNext("WEND");
}
else {
returnStack.push(toNum(lineNumbers[counter]));
}
return true;
}
var FOR_LOOP_DELIMS = ["=", "TO", "STEP"];
function forLoop(line) {
var n = lineNumbers[counter];
var varExpr = [];
var fromExpr = [];
var toExpr = [];
var skipExpr = [];
var arrs = [varExpr, fromExpr, toExpr, skipExpr];
var a = 0;
var i = 0;
for (i = 0; i < line.length; ++i) {
var t = line[i];
if (t.value === FOR_LOOP_DELIMS[a]) {
if (a === 0) {
varExpr.push(t);
}
++a;
}
else {
arrs[a].push(t);
}
}
var skip = 1;
if (skipExpr.length > 0) {
skip = evaluate(skipExpr);
}
if (!forLoopCounters.has(n) === undefined) {
forLoopCounters.set(n, evaluate(fromExpr));
}
var end = evaluate(toExpr);
var cond = forLoopCounters.get(n) <= end;
if (!cond) {
forLoopCounters.delete(n);
counter = findNext("NEXT");
}
else {
var v = forLoopCounters.get(n);
varExpr.push(toNum(v));
process(varExpr);
v += skip;
forLoopCounters.set(n, v);
returnStack.push(toNum(lineNumbers[counter]));
}
return true;
}
function stackReturn() {
return conditionalReturn(true);
}
function loadCodeFile(line) {
loadFile(evaluate(line))
.then(next);
return false;
}
function noop() {
return true;
}
function loadData(line) {
while (line.length > 0) {
var t = line.shift();
if (t.type !== "operators") {
data.push(t.value);
}
}
return true;
}
function readData(line) {
if (data.length === 0) {
var dataLine = findNext("DATA");
process(getLine(dataLine));
}
var value = data[dataCounter];
++dataCounter;
line.push(EQUAL_SIGN);
line.push(toNum(value));
return translate(line);
}
function restoreData() {
dataCounter = 0;
return true;
}
function defineFunction(line) {
var name = line.shift()
.value;
var signature = "";
var body = "";
var fillSig = true;
for (var i = 0; i < line.length; ++i) {
var t = line[i];
if (t.type === "operators" && t.value === "=") {
fillSig = false;
}
else if (fillSig) {
signature += t.value;
}
else {
body += t.value;
}
}
name = "FN" + name;
var script = "(function " + name + signature + "{ return " + body +
"; })";
window[name] = eval(script); // jshint ignore:line
return true;
}
function translate(line) {
evaluate(line);
return true;
}
var commands = {
DIM: declareVariable,
LET: translate,
PRINT: print,
GOTO: setProgramCounter,
IF: checkConditional,
INPUT: waitForInput,
END: pauseBeforeComplete,
STOP: pauseBeforeComplete,
REM: noop,
"'": noop,
CLS: clearScreen,
ON: onStatement,
GOSUB: gotoSubroutine,
RETURN: stackReturn,
LOAD: loadCodeFile,
DATA: loadData,
READ: readData,
RESTORE: restoreData,
REPEAT: setRepeat,
UNTIL: untilLoop,
"DEF FN": defineFunction,
WHILE: whileLoop,
WEND: stackReturn,
FOR: forLoop,
NEXT: stackReturn,
LABEL: labelLine
};
return function () {
if (!isDone) {
var goNext = true;
while (goNext) {
var line = getLine(counter);
goNext = process(line);
++counter;
}
}
};
};
} |
JavaScript | class Graph {
#nodes;
#n; // number of nodes
constructor() {
this.#nodes = {};
this.#n = 0;
}
addNode(node, state_) {
this.#nodes[node] = {
state: state_,
edges:[],
};
this.#n += 1;
}
addEdge(source, destination, directedGraph = true) {
// if either node does not exist
if ( !this.#nodes[source] || !this.#nodes[destination] ) {
return false;
}
let didAdd1 = false;
let didAdd2 = false;
// Add an edge from the source to the destination
if ( !this.#nodes[source].edges.includes(destination) ) {
this.#nodes[source].edges.push(destination);
didAdd1 = true;
}
// Add an edge from destination to source if the graph is undirected
if ( !directedGraph ) {
if ( !this.#nodes[destination].edges.includes(source) ) {
this.#nodes[destination].edges.push(source);
didAdd2 = true;
}
}
return didAdd1 || didAdd2; // if a change was made to the graph, return true
}
displayGraph() {
console.log(this.#nodes);
}
deleteNode(nodeID) {
/*
First deletes the edges in other nodes that are connected to the node to be deleted
then deletes the node to be deleted
*/
for( let i = 0; i < this.#n; i++ ) {
for ( let j = 0; j < this.#nodes[i].edges.length; j++ ) {
if ( this.#nodes[i].edges[j] == nodeID ) {
this.#nodes[i].edges.splice(j,1);
}
}
}
delete this.#nodes[nodeID];
this.#n -= 1;
}
getEdges(node) {
return this.#nodes[node].edges;
}
/**
*
* Returns the node ID of the state.
* Returns -1 if the state is not found.
*
* @param {Array} state
* @returns {Number} nodeID of state
*/
isStatePresent(state) {
for ( let i = 0; i < this.#n; i++ ) {
// If the state is present in the graph (specific to the Missionaries and Cannibals problem)
if ( this.#nodes[i].state[0] == state[0] && this.#nodes[i].state[1] == state[1] && this.#nodes[i].state[2] === state[2] ) {
return i;
}
}
return -1;
}
getStateFromNodeID(nodeID) {
return this.#nodes[nodeID].state;
}
/**
* Searches for the destination node from the source node via BFS.
* Updates the graph dynamically as the search is performed.
*
* @param {Number} source
* @param {Number} destination
* @returns {Array} Path and number of steps taken
*
*/
bfs(source, destination) {
let queue = [];
let visited = new Array(this.#n);
let distances = new Array(this.#n);
let parents = new Array(this.#n);
// steps is the number of nodes BFS visited in order to reach the destination node (excluding the source node)
// it is a measure of how effective the particular searching algorithm is for that problem
let steps = 0;
visited.fill(false);
queue.push(source);
visited[source] = true;
graphDraw.addNode( JSON.stringify([3,3,'Left Bank']) );
let flag = 0;
parents[source] = -1;
whileLoop: while( queue.length != 0 ) {
let v = queue.shift();
let numNeighbors = this.#nodes[v].edges.length;
for ( let i = 0; i < numNeighbors; i++ ) {
let u = this.#nodes[v].edges[i];
if ( visited[u] == false ) {
visited[u] = true;
graphDraw.addNode( JSON.stringify(this.#nodes[u].state) );
graphDraw.addEdge( JSON.stringify(this.#nodes[u].state),
JSON.stringify(this.#nodes[v].state),
{
style: {
stroke: '#bfa',
fill: '#56f',
}
} );
steps++;
queue.push(u);
distances[u] = distances[v] + 1;
parents[u] = v;
}
//changed to finalState instead of hard coding [0,0,"RB"]
if(JSON.stringify(graph.getStateFromNodeID(destination)) == JSON.stringify(graph.getStateFromNodeID(u))) {
// console.log("WE REACHED AGAIN");
break whileLoop;
}
}
}
if ( visited[destination] == false ) {
console.log("No path!\n");
return {};
}
else {
let path = [];
for ( let v = destination; v != -1; v = parents[v] ) {
path.push(v);
}
path.reverse();
return {"path" : path, "steps" : steps};
}
}
dfs(source, destination, visited = {} ) {
if ( visited[source] ) {
return false;
}
if ( source === destination ) {
return true;
}
visited[source] = true;
const neighbors = this.#nodes[source].edges;
for ( let i = 0; i < neighbors.length; i++ ) {
if ( this.dfs(neighbors[i], destination, visited) ) {
return true;
}
}
return false;
}
/**
* Solves the Water Jug problem using Breadth First Search
* Returns the path taken to reach the final state along with
* the number of steps it took BFS to reach the final state
*
* @param {Array} finalState
* @return {Number} Solution
*/
solveBFS(finalState) {
let source = 0;
let destination = this.isStatePresent(finalState);
if ( destination == -1 ) {
console.log("It is not possible to reach this state!");
return -1;
}
return this.bfs(source, destination);
}
/**
* Solves the Water Jug problem using Depth First Search
* Returns the path taken to reach the final state along with
* the number of steps it took DFS to reach the final state
*
* @param {Array} finalState
* @return {Number} Solution
*/
solveDFS(finalState) {
}
} |
JavaScript | class Bus {
constructor(){
this.broadcast = new Broadcast();
this.manager = new Manager(this.broadcast);
}
async triggerEvent(model, event, args){
return this.broadcast.trigger(`${model}.${event}`, ...args);
}
async debounceEvent(model, event, key, args){
return this.manager.trigger(`${model}.${event}`, key, args);
}
async addListener(model, event, cb){
return this.broadcast.on(`${model}.${event}`, cb);
}
} |
JavaScript | class AdminTeamListView extends React.Component {
constructor(props) {
super(props);
// This is a stateful component so we need to define a default representation of our state
this.state = {
text: '',
teams: null
};
}
render() {
if (this.state.teams == null) {
return (<div> loading teams</div>);
}
return (
<div>
<div>
<textarea value={this.state.text} onChange={this.onTextChange.bind(this)}></textarea>
<button onClick={this.onButtonClick.bind(this)} disabled={this.state.text.length === ''}> Submit </button>
</div>
<div className="team-container">
{this.state.teams.length === 0 && (<p> There are no teams yet </p>)}
{this.state.teams.map((team) =>
<div key={team.teamId} className="team-div">
<div className="team-body">
<li>
<Link to={`/admin-team/${team.teamId}`}> {team.teamName} </Link>
</li>
</div>
</div>
)}
</div>
</div>
);
}
// componentDidMount is a very special function in React. It's part of a group of functions that form part of
// the React lifecycle. React calls each one of these functions to notify you the programmer that certain things
// have happened or are about to occur.
//
// Internally React will call componentDidMount after a component's output has been rendered to the DOM.
// Its common React practice to make any API calls in componentDidMount().
//
// Additional documentation about React's lifecycle can be found here:
// https://reactjs.org/docs/react-component.html#commonly-used-lifecycle-methods
componentDidMount() {
this.getTeams();
}
onTextChange(event) {
event.preventDefault();
this.setState({text: event.target.value});
}
onButtonClick(event) {
event.preventDefault();
fetch(`/admin-team-list?cohortId=${this.props.match.params.cohortId}&teamName=${this.state.text}`, {method: 'POST'})
.then((response) => this.getTeams())
.catch(() => alert('Unable to upload the team. An error occured.'));
}
getTeams() {
// Make a call to our API
return fetch(`/admin-team-list?cohortId=${this.props.match.params.cohortId}`)
// Coax the response to json
.then((response) => response.json())
// Set our state using the returned teams. React will now rerender the component.
.then((teams) => this.setState({teams}));
}
} |
JavaScript | class LinkedStatsSync extends AsyncObject {
constructor (path) {
super(path)
}
syncCall () {
return fs.lstatSync
}
} |
JavaScript | class RocketPartGraphic {
/**
* constructor - Construct a RocketPartGraphic
*
* @param {string} id ID of part
* @param {number} x x to spawn
* @param {number} y y to spawn
*/
constructor(id, x, y) {
this.id = id;
this.data = allParts.index_data[id];
this.sprite = PIXI.Sprite.from(this.data.image_path);
this.sprite.width = this.data.width;
this.sprite.height = this.data.height;
this.x = x;
this.y = y;
// this.sprite.anchor.set(0.5, 0.5);
this.sprite.x = x;
this.sprite.y = y;
}
/**
* select - Display the part as selected
*/
select() {
this.sprite.tint = 0x00FF00;
}
/**
* unselect - Display part as unselected
*/
unselect() {
this.sprite.tint = 0xFFFFFF;
}
} |
JavaScript | class Base_layers_class {
constructor() {
//singleton
if (instance) {
return instance;
}
instance = this;
this.Base_gui = new Base_gui_class();
this.Helper = new Helper_class();
this.View_ruler = new View_ruler_class();
this.last_zoom = 1;
this.auto_increment = 1;
this.stable_dimensions = [];
this.debug_rendering = false;
this.render_success = null;
this.disabled_filter_id = null;
}
/**
* do preparation on start
*/
init() {
this.init_zoom_lib();
new app.Actions.Insert_layer_action({}).do();
var sel_config = {
enable_background: false,
enable_borders: true,
enable_controls: false,
enable_rotation: false,
enable_move: false,
data_function: function () {
return config.layer;
},
};
this.Base_selection = new Base_selection_class(sel_config, 'main');
this.render(true);
}
init_zoom_lib() {
zoomView.setBounds(0, 0, config.WIDTH, config.HEIGHT);
zoomView.setContext(document.getElementById('canvas_wrapper'));
this.stable_dimensions = [
config.WIDTH,
config.HEIGHT
];
}
pre_render() {
zoomView.canvasDefault();
}
after_render() {
config.need_render = false;
config.need_render_changed_params = false;
zoomView.canvasDefault();
}
/**
* renders all layers objects on main canvas
*
* @param {bool} force
*/
render(force) {
var _this = this;
if (force !== true) {
//request render and exit
config.need_render = true;
return;
}
if (this.stable_dimensions[0] != config.WIDTH || this.stable_dimensions[1] != config.HEIGHT) {
//dimensions changed - re-init zoom lib
this.init_zoom_lib();
}
if (config.need_render == true) {
this.render_success = null;
if(this.debug_rendering === true){
console.log('Rendering...');
}
if (this.last_zoom != config.ZOOM) {
//change zoom
zoomView.scaleAt(
this.Base_gui.GUI_preview.zoom_data.x,
this.Base_gui.GUI_preview.zoom_data.y,
config.ZOOM / this.last_zoom
);
}
else if (this.Base_gui.GUI_preview.zoom_data.move_pos != null) {
//move visible window
var pos = this.Base_gui.GUI_preview.zoom_data.move_pos;
var pos_global = zoomView.toScreen(pos);
zoomView.move(-pos_global.x, -pos_global.y);
this.Base_gui.GUI_preview.zoom_data.move_pos = null;
}
//prepare
this.pre_render();
//take data
var layers_sorted = this.get_sorted_layers();
zoomView.apply();
//render main canvas
for (var i = layers_sorted.length - 1; i >= 0; i--) {
var value = layers_sorted[i];
this.render_object(value);
}
//grid
// this.Base_gui.draw_grid();
//guides
// this.Base_gui.draw_guides();
//active tool overlay
this.render_overlay();
//reset
this.after_render();
this.last_zoom = config.ZOOM;
this.Base_gui.GUI_details.render_details();
this.View_ruler.render_ruler();
if(this.render_success === false){
alertify.error('Rendered with errors.');
}
}
requestAnimationFrame(function () {
_this.render(force);
});
}
render_overlay(){
var render_class = config.TOOL.name;
var render_function = 'render_overlay';
if(typeof this.Base_gui.GUI_tools.tools_modules[render_class].object[render_function] != "undefined") {
this.Base_gui.GUI_tools.tools_modules[render_class].object[render_function]();
}
}
/**
* export current layers to given canvas
*
* @param {object} object
* @param {boolean} is_preview
*/
render_object(object, is_preview) {
if (object.visible == false || object.type == null)
return;
//example with canvas object - other types should overwrite this method
if (object.type == 'image') {
document.getElementById('canvas_minipaint_background').style.background = "url(" + object.link.src + ")";
} else {
//call render function from other module
var render_class = object.render_function[0];
var render_function = object.render_function[1];
if(typeof this.Base_gui.GUI_tools.tools_modules[render_class] != "undefined") {
this.Base_gui.GUI_tools.tools_modules[render_class].object[render_function](null, object, is_preview);
}
else{
this.render_success = false;
console.log('Error: unknown layer type: ' + object.type);
}
}
}
/**
* creates new layer
*
* @param {array} settings
* @param {boolean} can_automate
*/
async insert(settings, can_automate = true) {
return app.State.do_action(
new app.Actions.Insert_layer_action(settings, can_automate)
);
}
/**
* autoresize layer, based on dimensions, up - always, if 1 layer - down.
*
* @param {int} width
* @param {int} height
* @param {int} layer_id
* @param {boolean} can_automate
*/
async autoresize(width, height, layer_id, can_automate = true) {
return app.State.do_action(
new app.Actions.Autoresize_canvas_action(width, height, layer_id, can_automate)
);
}
/**
* returns layer
*
* @param {int} id
* @returns {object}
*/
get_layer(id) {
if(id == undefined){
id = config.layer.id;
}
for (var i in config.layers) {
if (config.layers[i].id == id) {
return config.layers[i];
}
}
alertify.error('Error: can not find layer with id:' + id);
return null;
}
/**
* removes layer
*
* @param {int} id
* @param {boolean} force - Force to delete first layer?
*/
async delete(id, force) {
return app.State.do_action(
new app.Actions.Delete_layer_action(id, force)
);
}
/*
* removes all layers
*/
async reset_layers(auto_insert) {
return app.State.do_action(
new app.Actions.Reset_layers_action(auto_insert)
);
}
/**
* toggle layer visibility
*
* @param {int} id
*/
async toggle_visibility(id) {
return app.State.do_action(
new app.Actions.Toggle_layer_visibility_action(id)
);
}
/*
* renew layers HTML
*/
refresh_gui() {
this.Base_gui.GUI_layers.render_layers();
}
/**
* marks layer as selected, active
*
* @param {int} id
*/
async select(id) {
return app.State.do_action(
new app.Actions.Select_layer_action(id)
);
}
/**
* change layer opacity
*
* @param {int} id
* @param {int} value 0-100
*/
async set_opacity(id, value) {
value = parseInt(value);
if (value < 0 || value > 100) {
//reset
value = 100;
}
return app.State.do_action(
new app.Actions.Update_layer_action(id, { opacity: value })
);
}
/**
* clear layer data
*
* @param {int} id
*/
async layer_clear(id) {
return app.State.do_action(
new app.Actions.Clear_layer_action(id)
);
}
/**
* move layer up or down
*
* @param {int} id
* @param {int} direction
*/
async move(id, direction) {
return app.State.do_action(
new app.Actions.Reorder_layer_action(id, direction)
);
}
/**
* clone and sort.
*/
get_sorted_layers() {
return config.layers.concat().sort(
//sort function
(a, b) => b.order - a.order
);
}
/**
* checks if layer empty
*
* @param {int} id
* @returns {Boolean}
*/
is_layer_empty(id) {
var link = this.get_layer(id);
if ((link.width == 0 || link.width === null) && (link.height == 0 || link.height === null) && link.data == null) {
return true;
}
return false;
}
/**
* find next layer
*
* @param {int} id layer id
* @returns {layer|null}
*/
find_next(id) {
id = parseInt(id);
var link = this.get_layer(id);
var layers_sorted = this.get_sorted_layers();
var last = null;
for (var i = layers_sorted.length - 1; i >= 0; i--) {
var value = layers_sorted[i];
if (last != null && last.id == link.id) {
return value;
}
last = value;
}
return null;
}
/**
* find previous layer
*
* @param {int} id layer id
* @returns {layer|null}
*/
find_previous(id) {
id = parseInt(id);
var link = this.get_layer(id);
var layers_sorted = this.get_sorted_layers();
var last = null;
for (var i in layers_sorted) {
var value = layers_sorted[i];
if (last != null && last.id == link.id) {
return value;
}
last = value;
}
return null;
}
/**
* returns global position, for example if canvas is zoomed, it will convert relative mouse position to absolute at 100% zoom.
*
* @param {int} x
* @param {int} y
* @returns {object} keys: x, y
*/
get_world_coords(x, y) {
return zoomView.toWorld(x, y);
}
/**
* updates layer image data
*
* @param {canvas} canvas
* @param {int} layer_id (optional)
*/
update_layer_image(canvas, layer_id) {
return app.State.do_action(
new app.Actions.Update_layer_image_action(canvas, layer_id)
);
}
/**
* returns canvas dimensions.
*
* @returns {object}
*/
get_dimensions() {
return {
width: config.WIDTH,
height: config.HEIGHT,
};
}
/**
* returns all layers
*
* @returns {array}
*/
get_layers() {
return config.layers;
}
} |
JavaScript | class WorkspaceDiagnosticManager {
fileSystemWatcher;
fileFormatFilter;
createDiagnosticMethod;
diagnosticsCollection;
/**
* @param {vscode.WorkspaceFolder} workspaceFolder
* @param {function(vscode.Uri): Thenable<vscode.Diagnostic[]>} createDiagnosticMethod
* @param {string} fileFormatFilter A file glob pattern like *.{ts,js} that will be matched on file paths relative to the base path of workspaceFolder.
*/
constructor(workspaceFolder, createDiagnosticMethod, fileFormatFilter) {
this.createDiagnosticMethod = createDiagnosticMethod;
this.fileFormatFilter = new vscode.RelativePattern(workspaceFolder, fileFormatFilter);
this.diagnosticsCollection = vscode.languages.createDiagnosticCollection(`AL-Toolbox Comment Translation Diagnostics Workspace:${workspaceFolder.name}`);
this.fileSystemWatcher = vscode.workspace.createFileSystemWatcher(this.fileFormatFilter);
this.fileSystemWatcher.onDidCreate(uri => {
this.updateDiagnostics(uri);
});
this.fileSystemWatcher.onDidDelete(uri => {
this.diagnosticsCollection.delete(uri);
});
this.fileSystemWatcher.onDidChange(uri => {
this.updateDiagnostics(uri);
});
vscode.workspace.findFiles(this.fileFormatFilter)
.then(uris => uris.forEach(uri => this.updateDiagnostics(uri)));
}
/**
* @param {vscode.Uri} uri
*/
async updateDiagnostics(uri) {
this.diagnosticsCollection.delete(uri);
this.diagnosticsCollection.set(
uri,
await this.createDiagnosticMethod(uri)
);
}
dispose() {
if (this.fileSystemWatcher) this.fileSystemWatcher.dispose();
this.diagnosticsCollection.dispose();
}
} |
JavaScript | class NewBlock {
/**
* @param hash
* @param generationHash
* @param signature
* @param signer
* @param networkType
* @param version
* @param type
* @param height
* @param timestamp
* @param difficulty
* @param proofGamma
* @param proofScalar
* @param proofVerificationHash
* @param feeMultiplier
* @param previousBlockHash
* @param blockTransactionsHash
* @param blockReceiptsHash
* @param blockStateHash
* @param beneficiaryAddress
*/
constructor(
/**
* The block hash.
*/
hash,
/**
* The generation hash
*/
generationHash,
/**
* The block signature.
* The signature was generated by the signer and can be used to validate that the blockchain
* data was not modified by a node.
*/
signature,
/**
* The public account of block harvester.
*/
signer,
/**
* The network type.
*/
networkType,
/**
* The transaction version.
*/
version,
/**
* The block type.
*/
type,
/**
* The height of which the block was confirmed.
* Each block has a unique height. Subsequent blocks differ in height by 1.
*/
height,
/**
* The number of milliseconds elapsed since the creation of the nemesis blockchain.
*/
timestamp,
/**
* The POI difficulty to harvest a block.
*/
difficulty,
/**
* The feeMultiplier defined by the harvester.
*/
feeMultiplier,
/**
* The last block hash.
*/
previousBlockHash,
/**
* The block transaction hash.
*/
blockTransactionsHash,
/**
* The block receipt hash.
*/
blockReceiptsHash,
/**
* The state hash.
*/
stateHash,
/**
* The proof gamma.
*/
proofGamma,
/**
* The proof scalar.
*/
proofScalar,
/**
* The proof verification hash.
*/
proofVerificationHash,
/**
* The beneficiary address.
*/
beneficiaryAddress) {
this.hash = hash;
this.generationHash = generationHash;
this.signature = signature;
this.signer = signer;
this.networkType = networkType;
this.version = version;
this.type = type;
this.height = height;
this.timestamp = timestamp;
this.difficulty = difficulty;
this.feeMultiplier = feeMultiplier;
this.previousBlockHash = previousBlockHash;
this.blockTransactionsHash = blockTransactionsHash;
this.blockReceiptsHash = blockReceiptsHash;
this.stateHash = stateHash;
this.proofGamma = proofGamma;
this.proofScalar = proofScalar;
this.proofVerificationHash = proofVerificationHash;
this.beneficiaryAddress = beneficiaryAddress;
}
} |
JavaScript | class CmsClient extends AbstractClient {
constructor(credential, region, profile) {
super("cms.tencentcloudapi.com", "2019-03-21", credential, region, profile);
}
/**
* 根据日期,渠道和服务类型查询识别结果概览数据
* @param {DescribeModerationOverviewRequest} req
* @param {function(string, DescribeModerationOverviewResponse):void} cb
* @public
*/
DescribeModerationOverview(req, cb) {
let resp = new DescribeModerationOverviewResponse();
this.request("DescribeModerationOverview", req, resp, cb);
}
/**
* 音频内容检测(Audio Moderation, AM)服务使用了波形分析、声纹分析等技术,能识别涉黄、涉政、涉恐等违规音频,同时支持用户配置音频黑库,打击自定义的违规内容。
通过API直接上传音频即可进行检测,对于高危部分直接屏蔽,可疑部分人工复审,从而节省审核人力,释放业务风险。
* @param {AudioModerationRequest} req
* @param {function(string, AudioModerationResponse):void} cb
* @public
*/
AudioModeration(req, cb) {
let resp = new AudioModerationResponse();
this.request("AudioModeration", req, resp, cb);
}
/**
* 文本内容检测(Text Moderation)服务使用了深度学习技术,识别涉黄、涉政、涉恐等有害内容,同时支持用户配置词库,打击自定义的违规文本。
通过API接口,能检测内容的危险等级,对于高危部分直接过滤,可疑部分人工复审,从而节省审核人力,释放业务风险。
* @param {TextModerationRequest} req
* @param {function(string, TextModerationResponse):void} cb
* @public
*/
TextModeration(req, cb) {
let resp = new TextModerationResponse();
this.request("TextModeration", req, resp, cb);
}
/**
* 图片内容检测服务(Image Moderation, IM)能自动扫描图片,识别涉黄、涉恐、涉政、涉毒等有害内容,同时支持用户配置图片黑名单,打击自定义的违规图片。
通过API获取检测的标签及置信度,可直接采信高置信度的结果,人工复审低置信度的结果,从而降低人工成本,提高审核效率。
* @param {ImageModerationRequest} req
* @param {function(string, ImageModerationResponse):void} cb
* @public
*/
ImageModeration(req, cb) {
let resp = new ImageModerationResponse();
this.request("ImageModeration", req, resp, cb);
}
/**
* 视频内容检测(Video Moderation, VM)服务能识别涉黄、涉政、涉恐等违规视频,同时支持用户配置视频黑库,打击自定义的违规内容。
通过API直接上传视频即可进行检测,对于高危部分直接过滤,可疑部分人工复审,从而节省审核人力,释放业务风险。
* @param {VideoModerationRequest} req
* @param {function(string, VideoModerationResponse):void} cb
* @public
*/
VideoModeration(req, cb) {
let resp = new VideoModerationResponse();
this.request("VideoModeration", req, resp, cb);
}
} |
JavaScript | class Player {
constructor() {
this.sprite = 'images/char-boy.png';
this.x = 200;
this.y = 420;
this.constant = 1000;
this.isOver = false;
this.lifeRemaining = parseInt(document.querySelector(".player-life").textContent);
}
handleInput(allowedKeys) {
if (!this.isOver) {
this.inputKey = allowedKeys;
}
}
// Updates the this
update(dt) {
switch (this.inputKey) {
case 'up':
this.y -= dt * this.constant;
this.inputKey = null;
console.log(this.x, this.y);
break;
case 'down':
this.y += dt * this.constant;
this.inputKey = null;
console.log(this.x, this.y);
break;
case 'left':
this.x -= dt * this.constant;
this.inputKey = null;
console.log(this.x, this.y);
break;
case 'right':
this.x += dt * this.constant;
this.inputKey = null;
console.log(this.x, this.y);
break;
default:
break;
}
if (this.y < -15) {
this.y = -15;
}
if (this.y > 440) {
this.y = 440
}
if (this.x < -10) {
this.x = -10
}
if (this.x > 415) {
this.x = 415
}
console.log("Final:", this.x, this.y);
}
loseLife() {
this.lifeRemaining -= 1;
document.querySelector(".player-life").textContent = this.lifeRemaining;
this.x = 200, this.y = 420;
}
reset() {
this.x = 200, this.y = 420;
this.lifeRemaining = 5;
this.isOver = false;
document.querySelector(".player-life").textContent = this.lifeRemaining;
}
default () {
this.x = 200, this.y = 420;
}
render(ctx) {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}
} |
JavaScript | class RunRestDAO {
getSplineUrlTemplate() {
return RestClient.getSync(`api/runs/splineUrlTemplate`)
}
getAllRunSummaries() {
return RestClient.get("api/runs/summaries")
}
getRunsGroupedByDatasetName() {
return RestClient.get("api/runs/grouped")
}
getRunsGroupedByDatasetVersion(datasetName) {
return RestClient.get(`api/runs/grouped/${encodeURI(datasetName)}`)
}
getRunSummariesByDatasetNameAndVersion(datasetName, datasetVersion) {
return RestClient.get(`api/runs/${encodeURI(datasetName)}/${encodeURI(datasetVersion)}`)
}
getRun(datasetName, datasetVersion, runId) {
return RestClient.get(`api/runs/${encodeURI(datasetName)}/${encodeURI(datasetVersion)}/${encodeURI(runId)}`)
}
getLatestRun(datasetName, datasetVersion){
return RestClient.get(`api/runs/${encodeURI(datasetName)}/${encodeURI(datasetVersion)}/latestrun`)
}
getLatestRunOfLatestVersion(datasetName){
return RestClient.get(`api/runs/${encodeURI(datasetName)}/latestrun`)
}
} |
JavaScript | class CheckersPiece {
constructor(i, j, team) {
this.pos = {
"i": i,
"j": j
};
this.team = team;
this.DOMElement = null;
}
addTo(parentElement, parentSize) {
let pieceElement = document.createElementNS(xmlns, "circle");
pieceElement.setAttributeNS(null, "class", "piece team" + this.team);
pieceElement.setAttributeNS(null, "cx", parentSize / 2);
pieceElement.setAttributeNS(null, "cy", parentSize / 2);
pieceElement.setAttributeNS(null, "r", parentSize / 3);
this.DOMElement = pieceElement;
const ref = this;
pieceElement.addEventListener("mouseover", function (e) {
// console.log(ref);
});
pieceElement.addEventListener("click", function (e) {
if (ref.team != teamPlaying) {
return;
}
unselectPiece();
$(this).addClass("active");
selectedPiece = ref;
ref.getPossibleMoves();
});
parentElement.appendChild(pieceElement);
}
moveTo(i, j) {
this.DOMElement.remove();
document.querySelector(".tile-" + i + "-" + j).appendChild(this.DOMElement);
this.pos.i = i;
this.pos.j = j;
}
getPossibleMoves() {
resetPossibleMoves();
if (this.isKing === true) {
this.isMovementPossible(this.pos.i, this.pos.j);
} else {
let direction = (this.team === 0) ? 1 : -1;
this.isMovementPossible(this.pos.i, this.pos.j, direction);
}
}
isMovementPossible(posI, posJ, direction) {
if (direction == null) {
this.isMovementPossible(posI, posJ, -1);
this.isMovementPossible(posI, posJ, +1);
}
posJ = posJ + direction;
for (let iplus = 0; iplus <= 1; iplus++) {
let i = posI - 1 + 2 * iplus;
let j = posJ;
if (i >= 0 && i < 8) {
let adjacentPiece = pieceAt(i, j);
if (adjacentPiece == null) {
let width = document.querySelector(".tile-" + i + "-" + j + " .tile-rect").getAttributeNS(null, "width");
let height = document.querySelector(".tile-" + i + "-" + j + " .tile-rect").getAttributeNS(null, "height");
let text = document.createElementNS(xmlns, "text");
text.innerHTML = "-";
text.setAttributeNS(null, "class", "possible_move-text");
text.setAttributeNS(null, "x", width / 2);
text.setAttributeNS(null, "y", height / 2);
text.addEventListener("click", function (e) {
selectedPiece.moveTo(i, j);
nextTurn();
});
document.querySelector(".tile-" + i + "-" + j).appendChild(text);
$(".tile-" + i + "-" + j + " .tile-rect").addClass("possible_move");
} else {
i = i - 1 + 2 * iplus;
j = j + direction;
if (adjacentPiece.team != this.team && pieceAt(i, j) == null) {
let width = document.querySelector(".tile-" + i + "-" + j + " .tile-rect").getAttributeNS(null, "width");
let height = document.querySelector(".tile-" + i + "-" + j + " .tile-rect").getAttributeNS(null, "height");
let text = document.createElementNS(xmlns, "text");
text.innerHTML = "x";
text.setAttributeNS(null, "class", "possible_move-text");
text.setAttributeNS(null, "x", width / 2);
text.setAttributeNS(null, "y", height / 2);
text.addEventListener("click", function (e) {
selectedPiece.moveTo(i, j);
adjacentPiece.DOMElement.remove();
board[j].splice(i);
nextTurn();
});
document.querySelector(".tile-" + i + "-" + j).appendChild(text);
$(".tile-" + i + "-" + j + " .tile-rect").addClass("possible_move");
}
}
}
}
}
} |
JavaScript | class MediaSegmentFetcher extends Fetcher {
constructor (config) {
super(config)
this.encoding = 'binary'
}
} |
JavaScript | class BotBuilderGoogleMaps {
/**
* Creates a new instance of the Google Maps handler for Bot Framework.
* @param {string} googleMapsApiKey - The Google Maps API key obtained from
* Google Developer Console.
* @param {object} [options] - The optional settings for the Google Maps
* handler.
*/
constructor(googleMapsApiKey, options) {
this.key = googleMapsApiKey;
this.options = Object.assign(DEFAULT_OPTIONS, options);
}
/**
* Sends a message to the user asking them natively to select a location on
* a map. The message will be shown as a normal plaintext message on other
* channels.
*
* Example:
* const Maps = require('botbuilder-google-maps');
* Maps.sendFacebookLocationPrompt(session, 'Send me your location!');
* @param {object} session - The botbuilder session object.
* @param {string} prompt - The text of the prompt before the location
* request.
*/
static sendFacebookLocationPrompt(session, prompt) {
const message = new builder.Message(session).text(prompt).sourceEvent({
facebook: {
quick_replies: [
{
content_type: "location"
},
],
},
});
session.send(message);
}
} |
JavaScript | class Packet {
data = null;
sourceIP = null;
targetIP = null;
isIpv4 = null;
content = null;
sourcePort = null;
targetPort = null;
sourceMAC = null;
targetMAC = null;
L3Protocol = null;
L4Protocol = null;
L7Protocol = null;
etherType = null;
descriptionText = null;
constructor(data) {
this.data = data;
this.content = data.toString('hex');
}
getLength() {
return this.data.length;
}
getProtocol() {
if (this.L7Protocol !== null)
return this.L7Protocol;
else if (this.L4Protocol !== null)
return this.L4Protocol;
else
return this.L3Protocol;
}
} |
JavaScript | @ComponentComposer
@withStyles(styles)
class IconButton extends ComponentBase {
static propTypes = {
/**
* Base properties from ComponentBase.
*/
...ComponentBase.propTypes,
/**
* The color of the component.
* It supports the theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary', 'disabled']),
/**
* If `true`, the ripple is disabled.
*/
disableRipple: PropTypes.bool,
/**
* Icon name from BOA icon library.
*/
dynamicIcon: PropTypes.string,
/**
* If `true`, the base button has a keyboard focus ripple.
* `disableRipple` must also be `false`.
*/
focusRipple: PropTypes.bool,
/**
* Font icon name from font icon's library.
*/
fontIcon: PropTypes.string,
/**
* Icon props that are passed to the `<Icon />` element.
*/
iconProperties: PropTypes.object,
/**
* @ignore
*/
onClick: PropTypes.func,
/**
* SVG Icon name from material svg icon library.
*/
svgIcon: PropTypes.string,
/**
* If the type is 'icon', tooltip is generated on the icon button.
*/
tooltip: PropTypes.string,
/**
* Position of the tooltip in button.
*/
tooltipPosition: PropTypes.string,
/**
* Button type must be `contained`, `text`, `fab` or `icon`.
*/
};
static defaultProps = {
...ComponentBase.defaultProps,
color: 'default',
disabled: false,
disableRipple: false,
focusRipple: true,
};
render() {
const { classes } = this.props;
const tooltipTitle = this.props.tooltip;
const tooltipPosition = this.props.tooltipPosition;
const iconProperties = { ...this.props.iconProperties };
/* istanbul ignore else */
if (iconProperties && this.props.disabled) {
iconProperties.color = 'disabled';
} else if (this.props.iconProperties) {
iconProperties.color = this.props.iconProperties.color;
}
const iconButton = (
<ButtonBase
id={this.props.id}
classes={{
root: classes.root,
}}
onClick={this.props.onClick}
style={this.props.style}
disabled={this.props.disabled}
focusRipple={this.props.focusRipple}
disableRipple={this.props.disableRipple}
tabIndex={this.props.tabIndex}
>
{Icon.getIcon({ ...this.props, iconProperties })}
</ButtonBase>
);
return tooltipTitle ? (
<ToolTip
context={this.props.context}
tooltip={tooltipTitle}
tooltipPosition={tooltipPosition}
>
{iconButton}
</ToolTip>
) : (
iconButton
);
}
} |
JavaScript | class PeerStream {
constructor(routerSend, config) {
this.connection = new RTCPeerConnection(config);
// Ready the send of ICE Candidate details.
this.connection.onicecandidate = ({candidate}) =>
routerSend({type: 'ice-candidate', payload: candidate});
// Ready the send of the Local Description details.
this.connection.onnegotiationneeded = async () => {
await this.connection.setLocalDescription(
await this.connection.createOffer());
routerSend({type: 'offer', payload: this.connection.localDescription});
}
}
// Respond to client messages.
handleMessage(msg) {
// Store any sent remote ice candidates.
if (msg.type == 'ice-candidate')
this.connection.addIceCandidate(msg.payload || {});
// Store any sent remote descriptions.
if (msg.type == 'answer')
this.connection.setRemoteDescription(msg.payload);
}
} |
JavaScript | class ReportParameters {
/**
* Constructs a new <code>ReportParameters</code>.
* @alias module:model/ReportParameters
*/
constructor() {
ReportParameters.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>ReportParameters</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/ReportParameters} obj Optional instance to populate.
* @return {module:model/ReportParameters} The populated <code>ReportParameters</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ReportParameters();
if (data.hasOwnProperty('type')) {
obj['type'] = ApiClient.convertToType(data['type'], 'String');
}
if (data.hasOwnProperty('filter')) {
obj['filter'] = ApiClient.convertToType(data['filter'], 'String');
}
if (data.hasOwnProperty('source')) {
obj['source'] = ApiClient.convertToType(data['source'], 'String');
}
}
return obj;
}
} |
JavaScript | class StorageProviderFactory {
/**
* The various types of storage provider that the factory can produce.
* @private
* @type {StorageProvider}
*/
providerTypes = [LocalStorageProvider,SessionStorageProvider,NullStorageProvider];
/**
* The default type of storage provider to use if one is not available.
* @private
* @type {Type}
*/
DefaultProvider = NullStorageProvider;
/**
* Create a new storage provider, given its unique name.
* @public
* @param {String} providerName The unique string that identifies a provider to retrieve.
* @returns {StorageProvider} The new storage provider.
*/
createProvider(providerName) {
// Get the first one with the specified name.
const ProviderType = this.providerTypes.find((type) => type.getName() === providerName);
if(ProviderType){
// Create the provider.
const provider = new ProviderType();
if(provider.isAvailable()) {
return provider;
} else {
// Provider can't be used in this context.
return new this.DefaultProvider();
}
} else {
// No match.
throw Error(`Cannot find storage provider with name: ${providerName}`);
}
}
} |
JavaScript | class Register extends Component {
constructor() {
super();
this.state = {
username: '',
country: '',
dialCode: '',
mno: '',
email: '',
password: '',
cpassword: '',
message: '',
variant: '',
countryFlag: ''
}
}
close = () => {
this.setState({ message: '' });
}
handleChange = (e) => {
console.log(e.target.name, e.target.value)
this.setState({
[e.target.name]: e.target.value
})
}
handleCountry = (e) => {
const data = JSON.parse(e.target.value);
this.setState({ country: data.name, dialCode: data.dial_code });
}
handleCode = (code, flag) => {
this.setState({
dailCode: code,
countryFlag: flag
})
}
handleSubmit = (e) => {
e.preventDefault();
const { setNotif } = this.props;
const { username, country, mno, email, password, cpassword } = this.state
if (!/^[a-zA-Z][a-zA-Z0-9][a-zA-Z0-9]+$/.test(username)) {
setNotif({ message: 'Username not valid', variant: 'error' });
} else if (country === "-1") {
setNotif({ message: 'country not valid', variant: 'error' });
} else if ((!/^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/i.test(mno)) && mno.length >= 13) {
setNotif({ message: 'Phone not valid', variant: 'error' });
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email)) {
setNotif({ message: 'Email not valid', variant: 'error' });
} else if (password.length <= 7 || password.length >= 15) {
setNotif({ message: 'Password length is not valid', variant: 'error' });
} else if (password !== cpassword) {
setNotif({ message: 'Confirm Password do not match', variant: 'error' });
} else {
const data = {
username,
country,
mno,
email,
password,
cpassword
};
console.log(data, "data")
}
}
render() {
const { username, country, mno, email, password, cpassword, message, variant, countryFlag, dialCode } = this.state
const countryname = countrydetails.map((item, index) => {
return (
<option key={index} value={JSON.stringify(item)}>{item.name}</option>
)
});
const countrylist = countrydetails.map((item, index) => {
return (
<li
key={index}
className="iti__country iti__preferred"
tabIndex={-1}
id="iti-0__item-us-preferred"
role="option"
data-dial-code={1}
data-country-code="{item.code.toLowerCase()}"
aria-selected="false"
onClick={() => this.handleCode(item.code, item.flag)}
>
<div className="iti__flag-box">
<div className={`iti__flag iti__${item.code.toLowerCase()}`} />
</div>
<span className="iti__country-name">{item.name}</span>
<span className="iti__dial-code">{item.dial_code}</span>
</li>
)
})
return (
<Fragment>
<div className="page-layout">
<div className="container ">
<nav aria-label="breadcrumb">
<ol className="bg-transparent breadcrumb mb-2 p-0 small text-muted">
<li className="breadcrumb-item">
<a href="#">الرئيسية</a>
</li>
<li className="breadcrumb-item active" aria-current="page">
تسجيل حساب وكالة سفر
</li>
</ol>
</nav>
<div className="page-title">
<h1 className="h1 text-primary"> تسجيل حساب وكالة سفر </h1>
</div>
<div className="bg-white p-4 border">
<div className="row">
<div className="col-md-6 col-lg-4">
<div className="form-group ">
{/* User Name */}
<label className="d-block col-form-label">اسم المستخدم </label>
<input type="text" className="form-control" name="username" onChange={this.handleChange} />
</div>
</div>
<div className="col-md-6 col-lg-4">
<div className="form-group ">
<label className="d-block col-form-label"> الدولة</label>
<select id="country" name="country" className="form-control" onChange={this.handleCountry}>
<option value="-1"> Choose the Country </option>
{countryname}
</select>
</div>
</div>
</div>
<div className="row">
<div className="col-md-6 col-lg-4">
<div className="form-group ">
<label className="d-block col-form-label"> رقم الجوال </label>
{/* <input type="number" class="form-control form-mobile"> */}
<div className="input-group custom-dropdown dropdown">
<input
type="text"
className="form-control"
aria-label="Text input with dropdown button"
name="mno"
onChange={this.handleChange}
/>
<div className="input-group-prepend ">
<button
className="dropdown-select"
type="button"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
id="dLabel"
>
<span className="iti_num">{this.state.dialCode}</span>
<span className={`iti_flg iti__flag iti__${countryFlag}`} />
<i className="fas fa-angle-down fa-1x fa-fw" />
</button>
<div className="dropdown-menu" aria-labelledby="dLabel">
<ul>
{countrylist}
</ul>
</div>
</div>
</div>
</div>
</div>
<div className="col-md-6 col-lg-4">
<div className="form-group ">
<label className="d-block col-form-label">
البريد الاليكتروني
</label>
<input type="email" className="form-control" name="email" onChange={this.handleChange} />
</div>
</div>
</div>
<div className="row">
<div className="col-md-6 col-lg-4">
<div className="form-group ">
<label htmlFor={2} className="d-block col-form-label">
كلمة المرور
</label>
<input type="password" className="form-control" name="password" onChange={this.handleChange} />
</div>
</div>
<div className="col-md-6 col-lg-4">
<div className="form-group ">
<label htmlFor={2} className="d-block col-form-label">
تأكيد كلمة المرور
</label>
<input type="password" className="form-control is-invalid" name="cpassword" onChange={this.handleChange} />
<span className="text-danger small">
please inter same password again
</span>
</div>
</div>
</div>
<div className="btn-group mt-5">
<a href="login.html" className="btn btn-default px-0">
الغاء التسجيل
</a>
<div>
{/* Sign Up */}
<a className="btn btn-primary ml-3" onClick={this.handleSubmit}>
تسجيل
</a>
</div>
</div>
</div>
</div>
</div>
</Fragment>
)
}
} |
JavaScript | class SqrGrid extends AbstractGrid{
constructor(config) {
super(config);
/* ______________________________________________
GRID INTERFACE:
*/
this.type = vg.SQR;
this.autogenerated = false;
// create base shape used for building geometry
var verts = [];
verts.push(new THREE.Vector3());
verts.push(new THREE.Vector3(-this.cellSize, this.cellSize));
verts.push(new THREE.Vector3(this.cellSize, this.cellSize));
verts.push(new THREE.Vector3(this.cellSize, -this.cellSize));
// copy the verts into a shape for the geometry to use
this.cellShape = new THREE.Shape();
this.cellShape.moveTo(-this.cellSize, -this.cellSize);
this.cellShape.lineTo(-this.cellSize, this.cellSize);
this.cellShape.lineTo(this.cellSize, this.cellSize);
this.cellShape.lineTo(this.cellSize, -this.cellSize);
this.cellShape.lineTo(-this.cellSize, -this.cellSize);
this.cellGeo = new THREE.Geometry();
this.cellGeo.vertices = verts;
this.cellGeo.verticesNeedUpdate = true;
this.cellShapeGeo = new THREE.ShapeGeometry(this.cellShape);
/* ______________________________________________
PRIVATE
*/
this._fullCellSize = this.cellSize * 2;
this._directions = Coord.sqrDirections;
this._diagonals = [new Cell(-1, -1, 0), new Cell(-1, +1, 0),
new Cell(+1, +1, 0), new Cell(+1, -1, 0)];
// cached objects
this._list = [];
this._conversionVec = new THREE.Vector3();
this._geoCache = [];
this._matCache = [];
}
/*
________________________________________________________________________
High-level functions that the Board interfaces with (all grids implement)
*/
coordToPixel(coord) {
this._vec3.x = coord.col * this._fullCellSize;
this._vec3.y = coord.depth*this.cellHeight;
this._vec3.z = coord.row * this._fullCellSize;
return this._vec3;
}
pixelToCoord(pos) {
const col = Math.round(pos.x / this._fullCellSize);
const row = Math.round(pos.z / this._fullCellSize);
const depth =0;//ToDo
return this._coord.setRCD(row, col, depth);
}
getCellAt(pos) {
var q = Math.round(pos.x / this._fullCellSize);
var r = Math.round(pos.z / this._fullCellSize);
this._coord.set(q, r);
return this.cells[this.coordToHash(this._coord)];
}
getNeighbors(cell, diagonal, filter) {
// always returns an array
var i, n, l = this._directions.length;
this._list.length = 0;
for (i = 0; i < l; i++) {
this._coord.copy(cell.coord);
this._coord.add(this._directions[i]);
n = this.cells.get(this.coordToHash(this._coord));
if (!n || (filter && !filter(cell, n))) {
continue;
}
this._list.push(n);
}
if (diagonal) {
for (i = 0; i < l; i++) {
this._coord.copy(cell);
this._coord.add(this._diagonals[i]);
n = this.cells.get(this.coordToHash(this._coord));
if (!n || (filter && !filter(cell, n))) {
continue;
}
this._list.push(n);
}
}
return this._list;
}
coordToHash(cell) {
return cell.row+this._hashDelimeter+cell.col+this._hashDelimeter+cell.depth; // s is not used in a square grid
}
distance(cellA, cellB) {
var d = Math.max(Math.abs(cellA.row - cellB.row), Math.abs(cellA.col - cellB.col));
//d += cellB.h - cellA.h; // include vertical size
return d;
}
generateTilePoly(material) {
if (!material) {
material = new THREE.MeshBasicMaterial({color: 0x24b4ff});
}
var mesh = new THREE.Mesh(this.cellShapeGeo, material);
this._vec3.set(1, 0, 0);
mesh.rotateOnAxis(this._vec3, vg.PI/2);
return mesh;
}
dispose() {
super.dispose();
this.cellShape = null;
this.cellGeo.dispose();
this.cellGeo = null;
this.cellShapeGeo.dispose();
this.cellShapeGeo = null;
this._list = null;
this._vec3 = null;
this._conversionVec = null;
this._geoCache = null;
this._matCache = null;
}
/*
Load a grid from a parsed json object.
json = {
extrudeSettings,
size,
cellSize,
autogenerated,
cells: [],
materials: [
{
cache_id: 0,
type: 'MeshLambertMaterial',
color, ambient, emissive, reflectivity, refractionRatio, wrapAround,
imgURL: url
},
{
cacheId: 1, ...
}
...
]
}
*/
load(url, callback, scope) {
vg.Tools.getJSON({
url: url,
callback: function(json) {
this.fromJSON(json);
callback.call(scope || null, json);
},
cache: false,
scope: this
});
}
fromJSON(json) {
var i, c;
var cells = json.cells;
this.cells = {};
this.numCells = 0;
this.size = json.size;
this.cellSize = json.cellSize;
this._fullCellSize = this.cellSize * 2;
this.extrudeSettings = json.extrudeSettings;
this.autogenerated = json.autogenerated;
for (i = 0; i < cells.length; i++) {
c = new vg.Cell();
c.copy(cells[i]);
this.add(c);
}
}
toJSON() {
var json = {
size: this.size,
cellSize: this.cellSize,
extrudeSettings: this.extrudeSettings,
autogenerated: this.autogenerated
};
var cells = [];
var c, k;
for (k in this.cells) {
c = this.cells[k];
cells.push({
q: c.q,
r: c.r,
s: c.s,
h: c.h,
walkable: c.walkable,
userData: c.userData
});
}
json.cells = cells;
return json;
}
} |
JavaScript | class ServiceImpactingEventIncidentProperties {
/**
* Create a ServiceImpactingEventIncidentProperties.
* @member {string} [title] Title of the incident.
* @member {string} [service] Service impacted by the event.
* @member {string} [region] Region impacted by the event.
* @member {string} [incidentType] Type of Event.
*/
constructor() {
}
/**
* Defines the metadata of ServiceImpactingEventIncidentProperties
*
* @returns {object} metadata of ServiceImpactingEventIncidentProperties
*
*/
mapper() {
return {
required: false,
serializedName: 'serviceImpactingEvent_incidentProperties',
type: {
name: 'Composite',
className: 'ServiceImpactingEventIncidentProperties',
modelProperties: {
title: {
required: false,
serializedName: 'title',
type: {
name: 'String'
}
},
service: {
required: false,
serializedName: 'service',
type: {
name: 'String'
}
},
region: {
required: false,
serializedName: 'region',
type: {
name: 'String'
}
},
incidentType: {
required: false,
serializedName: 'incidentType',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class BoldUI extends Plugin {
/**
* @inheritDoc
*/
init() {
const editor = this.editor
// Add bold button to feature components.
editor.ui.componentFactory.add(BOLD, locale => {
const command = editor.commands.get(BOLD)
const view = new ButtonView(locale)
view.set({
label: '加粗',
icon: boldIcon,
keystroke: 'CTRL+B',
tooltip: true,
isToggleable: true
})
view.bind('isOn', 'isEnabled').to(command, 'value', 'isEnabled')
// Execute command.
this.listenTo(view, 'execute', () => editor.execute(BOLD))
return view
})
}
} |
JavaScript | class Queue {
constructor() {
// the processes to be added
this.items = [];
}
// Adds any process to the Queue
enqueue(process) {
return this.items.push(process);
}
// Removes the first process from items to follow FIFO
dequeue() {
if(this.items.length > 0) {
return this.items.shift();
}
}
// View the last process added to the queue
peek() {
return this.items[this.items.length - 1];
}
// Check if queue is empty
isEmpty() {
return this.items.length == 0;
}
// Get the size of the current queue
getSize() {
return this.items.length;
}
// Empty the queue at once
clear() {
this.items = [];
}
} |
JavaScript | class DoughnutChart {
/**
Param: DOM element -> where to draw the Chart. It must be of type "canvas"
*/
constructor(docElement){
this.docElement = docElement;
this.arrDataSets = [];
}
/**
Param: string array -> It sets the array of the labels to use on the x axis
*/
setLabels(arrLabels){
this.arrLabels = arrLabels;
}
/**
Param: CovidChartDataset -> It adds the dataset to the list of data to draw
*/
addCovidChartDataset(covidChartDataset){
this.arrDataSets.push(covidChartDataset.getDataSet());
}
clearDataSets(){
if(this.chart != undefined){
this.arrDataSets = [];
//this.chart.destroy();
}
}
/**
Sets the title of the chart
*/
setTitle(stringTitle){
this.title = stringTitle;
}
/**
It draws the chart
*/
drawChart(darkModeOn){
var arrData = [];
var labels = [];
var colors = [];
for(let dataSet of this.arrDataSets){
arrData.push(dataSet.data);
labels.push(dataSet.label);
colors.push(dataSet.backgroundColor);
}
let fontColor = darkModeOn ? "#FFFFFF" : "#666666";
var config = {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: arrData,
backgroundColor: colors
}]
},
options:{
title: {
display: this.title != undefined ? true : false,
text: this.title || '',
fontColor: fontColor
},
legend:{
labels:{
fontColor: fontColor
}
},
responsive: true,
tooltips: {
callbacks: {
label: this.formatToolTip
}
},
}
};
if(this.chart != undefined){
this.chart.options.title.fontColor = fontColor;
this.chart.options.legend.labels.fontColor = fontColor;
this.chart.data.labels.map((v, i) => config.data.labels[i]);
this.chart.data.datasets.forEach((dataSet, i) => {
dataSet.backgroundColor = dataSet.backgroundColor.map((v, j) => config.data.datasets[i].backgroundColor[j]);
dataSet.data = dataSet.data.map((v, j) => config.data.datasets[i].data[j]);
});
this.chart.update();
}else{
this.chart = new Chart(this.docElement, config);
}
}
formatToolTip(toolTip, data){
return data.labels[toolTip.index] + ": " + data.datasets[0].data[toolTip.index].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
} |
JavaScript | class SqljsEntityManager extends EntityManager_1.EntityManager {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(connection, queryRunner) {
super(connection, queryRunner);
this["@instanceof"] = Symbol.for("SqljsEntityManager");
this.driver = connection.driver;
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Loads either the definition from a file (Node.js) or localstorage (browser)
* or uses the given definition to open a new database.
*/
async loadDatabase(fileNameOrLocalStorageOrData) {
await this.driver.load(fileNameOrLocalStorageOrData);
}
/**
* Saves the current database to a file (Node.js) or localstorage (browser)
* if fileNameOrLocalStorage is not set options.location is used.
*/
async saveDatabase(fileNameOrLocalStorage) {
await this.driver.save(fileNameOrLocalStorage);
}
/**
* Returns the current database definition.
*/
exportDatabase() {
return this.driver.export();
}
} |
JavaScript | class WSExecutorFirst extends WSExecutor {
static STATES = {
START: 'START',
SETUP: 'SETUP',
READY: 'READY',
SOLVE: 'SOLVE',
FINISH: 'FINISH',
};
/**
* Binary matrices of size 5x3 (5 rows, 3 columns),
* representing digits from `0` to `9`.
*/
static IDEAL_NUMBERS = {
0: [
[1, 1, 1],
[1, 0, 1],
[1, 0, 1],
[1, 0, 1],
[1, 1, 1],
],
1: [
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
],
2: [
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
],
3: [
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
],
4: [
[1, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[0, 0, 1],
],
5: [
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
],
6: [
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
],
7: [
[1, 1, 1],
[0, 0, 1],
[0, 1, 0],
[1, 0, 0],
[1, 0, 0],
],
8: [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
],
9: [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[0, 0, 1],
],
};
static BASIC_WIDTH = Object.values(WSExecutorFirst.IDEAL_NUMBERS)[0][0].length
static BASIC_HEIGHT = Object.values(WSExecutorFirst.IDEAL_NUMBERS)[0].length
static PATH = '/first/';
static DEFAULT_TTL_SECONDS = 300;
static DEFAULT_TTL = WSExecutorFirst.DEFAULT_TTL_SECONDS * 1E3;
static MAX_TOTAL_STEPS = Math.round(1E6);
static MAX_VERTICAL_SCALE = 100;
static MAX_HORIZONTAL_SCALE = 100;
static VALIDATION_SCHEMAS = {
[WSExecutorFirst.STATES.START]: ajv.compile({
type: 'object',
additionalProperties: false,
required: ['message'],
properties: {
message: {
type: 'string',
const: 'Let\'s start',
},
},
}),
[WSExecutorFirst.STATES.SETUP]: ajv.compile({
type: 'object',
additionalProperties: false,
required: ['width', 'height', 'totalSteps', 'noise', 'shuffle'],
properties: {
width: {
type: 'integer',
minimum: 1,
maximum: WSExecutorFirst.MAX_HORIZONTAL_SCALE,
},
height: {
type: 'integer',
minimum: 1,
maximum: WSExecutorFirst.MAX_VERTICAL_SCALE,
},
totalSteps: {
type: 'integer',
minimum: 1,
maximum: WSExecutorFirst.MAX_TOTAL_STEPS,
},
noise: {
type: 'number',
minimum: 0,
maximum: 1,
},
shuffle: {
type: 'boolean',
},
},
}),
[WSExecutorFirst.STATES.READY]: ajv.compile({
type: 'object',
additionalProperties: false,
required: ['message'],
properties: {
message: {
type: 'string',
const: 'Ready',
},
},
}),
[WSExecutorFirst.STATES.SOLVE]: ajv.compile({
type: 'object',
additionalProperties: false,
required: ['step', 'answer'],
properties: {
step: {
type: 'integer',
minimum: 1,
},
answer: {
enum: Object.keys(WSExecutorFirst.IDEAL_NUMBERS),
},
},
}),
[WSExecutorFirst.STATES.FINISH]: ajv.compile({
type: 'object',
additionalProperties: false,
required: ['message'],
properties: {
message: {
type: 'string',
const: 'Bye',
},
},
}),
};
/**
* Fisher–Yates shuffle.
*/
static shuffle(array) {
const result = [...array];
for (let i = array.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
/**
* Apply Bernoulli noise to the value and return the new one.
*/
static applyElementNoise(value, noiseLevel) {
/* eslint-disable-next-line no-bitwise */
return value ^ (Math.random() < noiseLevel);
}
constructor(data) {
super({
...data,
logger: Logger('Task 1'),
});
this.currentSolution = null;
this.currentStep = 0;
this.horizontalScale = null;
this.noiseLevel = null;
this.state = WSExecutorFirst.STATES.START;
this.successes = 0;
this.totalSteps = null;
this.verticalScale = null;
this.remapping = {};
this.logger.info('Executor First created');
}
onMessage(message) {
switch (this.state) {
case WSExecutorFirst.STATES.START:
this.onStart();
break;
case WSExecutorFirst.STATES.SETUP:
this.onSetup(message);
break;
case WSExecutorFirst.STATES.READY:
this.onReady();
break;
case WSExecutorFirst.STATES.SOLVE:
this.onSolve(message);
break;
case WSExecutorFirst.STATES.FINISH:
this.onFinish();
break;
default:
this.logger.alert(`Unknown state ${this.state}`);
this.socket.close();
break;
}
}
onStart() {
this.state = WSExecutorFirst.STATES.SETUP;
this.sendMessage({
width: WSExecutorFirst.BASIC_WIDTH,
height: WSExecutorFirst.BASIC_HEIGHT,
number: Object.keys(WSExecutorFirst.IDEAL_NUMBERS).length,
});
}
onSetup({
height,
width,
noise,
totalSteps,
shuffle,
}) {
if (shuffle) {
const names = WSExecutorFirst.shuffle(Object.keys(WSExecutorFirst.IDEAL_NUMBERS));
Object.keys(WSExecutorFirst.IDEAL_NUMBERS).forEach((key) => {
this.remapping[key] = names.pop();
});
} else {
Object.keys(WSExecutorFirst.IDEAL_NUMBERS).forEach((key) => {
this.remapping[key] = key;
});
}
[
this.horizontalScale,
this.verticalScale,
this.noiseLevel,
this.totalSteps,
] = [height, width, noise, totalSteps];
this.state = WSExecutorFirst.STATES.READY;
const idealNumbers = {};
Object.keys(WSExecutorFirst.IDEAL_NUMBERS).forEach((key) => {
idealNumbers[key] = this.generateMatrix(
WSExecutorFirst.IDEAL_NUMBERS[this.remapping[key]],
0,
);
});
this.sendMessage(idealNumbers);
}
onReady() {
this.state = WSExecutorFirst.STATES.SOLVE;
this.currentStep += 1;
this.currentSolution = Object.keys(WSExecutorFirst.IDEAL_NUMBERS)[
Math.floor(
Math.random() * Object.keys(WSExecutorFirst.IDEAL_NUMBERS).length,
)
];
const matrix = this.generateMatrix(
WSExecutorFirst.IDEAL_NUMBERS[this.remapping[this.currentSolution]],
this.noiseLevel,
);
this.sendMessage({
currentStep: this.currentStep,
matrix,
});
}
onSolve({ step, answer }) {
if (step !== this.currentStep) {
this.sendErrors({
title: 'Wrong step number',
detail: `The current step is ${this.currentStep}`,
});
this.socket.close();
return;
}
if (this.currentStep < this.totalSteps) {
this.state = WSExecutorFirst.STATES.READY;
} else if (this.currentStep === this.totalSteps) {
this.state = WSExecutorFirst.STATES.FINISH;
} else {
this.logger.alert(`We have step ${this.currentStep} of ${this.totalSteps}!`);
this.socket.close();
return;
}
if (this.currentSolution === answer) {
this.successes += 1;
}
this.sendMessage({
step: this.currentStep,
solution: this.currentSolution,
});
}
onFinish() {
this.sendMessage({
successes: this.successes,
totalSteps: this.totalSteps,
});
}
/**
* Generate new matrix.
* First, one of the First.IDEAL_NUMBERS elements is chosen
* as the initial value.
* First.state.width is used to duplicate columns of the reference.
* First.state.height is used to duplicate rows of the reference.
* Then, we add a noise to the matrix
* by xoring each element with random values generated by Bernoulli law.
*/
generateMatrix(idealDigit, noiseLevel) {
const matrix = [];
idealDigit.forEach((row, i) => {
for (let h = 0; h < this.verticalScale; h += 1) {
matrix.push([]);
for (let j = 0; j < row.length; j += 1) {
for (let w = 0; w < this.horizontalScale; w += 1) {
matrix[i * this.verticalScale + h].push(
WSExecutorFirst.applyElementNoise(idealDigit[i][j], noiseLevel),
);
}
}
}
});
return matrix;
}
get schema() {
return WSExecutorFirst.VALIDATION_SCHEMAS[this.state];
}
} |
JavaScript | class Post {
// the order of the items in the constructor is the order
// in which data will be assigned
constructor(
title,
link,
link2,
author,
img,
body){
this.title = title;
this.link = link;
this.link2 = link2;
this.author = author;
this.img = img;
this.body = body;
}
} |
JavaScript | class ServiceController {
/**
* @param {!ui.router.$state} $state
* @param {!./../common/namespace/namespace_service.NamespaceService} kdNamespaceService
* @ngInject
*/
constructor($resource, $state, kdNamespaceService, kdService) {
/** @export {Object} */
this.service
/** @export {string} */
this.index
/** @export */
this.kdService = kdService;
/** @export {string} */
this.initvalue = '';
}
/** oninit */
$onInit() {
console.log(this.index);
this.initvalue = JSON.stringify(this.service);
}
/** @export */
addService() {
this.kdService.value["content"]["services"][this.kdService.value["content"]["services"].length] = JSON.parse(this.initvalue);
this.kdService.value["content"]["ingress"]["servicename"] = this.kdService.value["content"]["services"][0].name;
console.log(this.kdService)
}
/** @export */
deleteService() {
this.kdService.value["content"]["services"].splice(this.index, 1);
}
/** @export */
addport() {
this.service["ports"][this.service["ports"].length] = JSON.parse(this.initvalue)["ports"][0];
console.log(this.kdService)
// this.kdService.value["content"]["services"][this.kdService.value["content"]["services"].length] = this.service;
}
/** @export */
deleteport(index) {
console.log(this.service)
this.service["ports"].splice(index, 1);
}
} |
JavaScript | class IndexResultProcessor extends ResultProcessor {
constructor(configuration) {
super(configuration);
}
_process(results) {
let returnRef = null;
const configuration = this._getConfiguration();
const keyPropertyName = configuration.keyPropertyName;
if (is.array(results) && is.string(keyPropertyName)) {
returnRef = results.reduce((object, item) => {
const key = attributes.read(item, keyPropertyName);
if (is.string(key)) {
attributes.write(object, key, item);
}
return object;
}, { });
} else {
returnRef = null;
}
return returnRef;
}
toString() {
return '[IndexResultProcessor]';
}
} |
JavaScript | class PodInstanceStatusFilter extends DSLFilter {
/**
* Handle all `is:XXXX` attribute filters that we can handle.
*
* @override
*/
filterCanHandle(filterType, filterArguments) {
return (
filterType === DSLFilterTypes.ATTRIB &&
filterArguments.label === LABEL &&
LABEL_TO_STATUS[filterArguments.text.toLowerCase()] != null
);
}
/**
* Keep only instances whose state matches the value of
* the `is` label
*
* @override
*/
filterApply(resultSet, filterType, filterArguments) {
const testStatus = LABEL_TO_STATUS[filterArguments.text.toLowerCase()];
return resultSet.filterItems(instance => {
let instanceStatus = "completed";
if (instance.isStaging()) {
instanceStatus = "staging";
}
if (instance.isRunning()) {
instanceStatus = "active";
}
return instanceStatus === testStatus;
});
}
} |
JavaScript | class Server {
constructor() {
this._port = undefined;
}
//////////////////////////////////////////////////////////////////////
initialize(onMessageCallback) {
this._onMessageCallback = onMessageCallback;
this._onRuntimeConnect = this._onRuntimeConnect.bind(this);
browser.runtime.onConnect.addListener(this._onRuntimeConnect);
}
//////////////////////////////////////////////////////////////////////
postMessage(message) {
this._port.postMessage(message);
}
//////////////////////////////////////////////////////////////////////
_onRuntimeConnect(port) {
this._port = port;
this._port.onMessage.addListener(this._onMessageCallback)
}
} |
JavaScript | class Client {
constructor() {
this._port = undefined;
}
//////////////////////////////////////////////////////////////////////
connect(portName, onMessageCallback) {
this._port = browser.runtime.connect({ name: portName });
this._port.onMessage.addListener(onMessageCallback);
}
//////////////////////////////////////////////////////////////////////
postMessage(message) {
this._port.postMessage(message);
}
} |
JavaScript | class InheritableMap {
/**
* Public constructor
*/
constructor() {
// Create an instance of an Immutable map and copy the instance attributes
// to this InheritableMap instance.
const map = new Immutable.Map();
Object.keys(map).forEach(key => {
this[key] = map[key];
});
}
/**
* Cast to instance type
* @param {any} x object to cast
* @return {any} object cast to this.__proto__
*/
__cast(x) {
Object.setPrototypeOf(x, Object.getPrototypeOf(this));
return x;
}
} |
JavaScript | class TrapThemePFSimple extends D20TrapTheme {
/**
* @inheritdoc
*/
get name() {
return 'PF-Simple';
}
/**
* @inheritdoc
*/
getAC(character) {
return TrapTheme.getSheetAttr(character, 'ac');
}
/**
* @inheritdoc
*/
getPassivePerception(character) {
return TrapTheme.getSheetAttr(character, 'perception')
.then(perception => {
return perception + 10;
});
}
/**
* @inheritdoc
*/
getSaveBonus(character, saveName) {
return TrapTheme.getSheetAttr(character, SAVE_NAMES[saveName]);
}
/**
* @inheritdoc
*/
getThemeProperties(trapToken) {
let result = super.getThemeProperties(trapToken);
let save = _.find(result, item => {
return item.id === 'save';
});
save.options = [ 'none', 'fort', 'ref', 'will' ];
return result;
}
/**
* @inheritdoc
* Also supports the Trap Spotter ability.
*/
passiveSearch(trap, charToken) {
super.passiveSearch(trap, charToken);
let character = getObj('character', charToken.get('represents'));
let effect = (new TrapEffect(trap, charToken)).json;
// Perform automated behavior for Trap Spotter.
if((effect.type === 'trap' || _.isUndefined(effect.type)) && effect.spotDC && character) {
TrapTheme.getSheetRepeatingRow(character, 'classabilities', rowAttrs => {
if(!rowAttrs.name)
return false;
let abilityName = rowAttrs.name.get('current');
return abilityName.toLowerCase().includes('trap spotter');
})
.then(trapSpotter => {
let dist = ItsATrap.getSearchDistance(trap, charToken);
if(trapSpotter && dist <= 10)
this._trapSpotter(character, trap, effect);
})
.catch(err => {
sendChat('Trap theme: ' + this.name, '/w gm ' + err.message);
log(err.stack);
});
}
}
/**
* Trap Spotter behavior.
* @private
*/
_trapSpotter(character, trap, effect) {
// Quit early if this character has already attempted to trap-spot
// this trap.
let trapId = trap.get('_id');
let charId = trap.get('_id');
if(!state.TrapThemePFSimple.trapSpotterAttempts[trapId])
state.TrapThemePFSimple.trapSpotterAttempts[trapId] = {};
if(state.TrapThemePFSimple.trapSpotterAttempts[trapId][charId])
return;
else
state.TrapThemePFSimple.trapSpotterAttempts[trapId][charId] = true;
// Make a hidden Perception check to try to notice the trap.
TrapTheme.getSheetAttr(character, 'perception')
.then(perception => {
if(_.isNumber(perception)) {
return TrapTheme.rollAsync(`1d20 + ${perception}`);
}
else
throw new Error('Trap Spotter: Could not get Perception value for Character ' + charToken.get('_id') + '.');
})
.then(searchResult => {
// Inform the GM about the Trap Spotter attempt.
sendChat('Trap theme: ' + this.name, `/w gm ${character.get('name')} attempted to notice trap "${trap.get('name')}" with Trap Spotter ability. Perception ${searchResult.total} vs DC ${effect.spotDC}`);
// Resolve whether the trap was spotted or not.
if(searchResult.total >= effect.spotDC) {
let html = TrapTheme.htmlNoticeTrap(character, trap);
ItsATrap.noticeTrap(trap, html.toString(TrapTheme.css));
}
})
.catch(err => {
sendChat('Trap theme: ' + this.name, '/w gm ' + err.message);
log(err.stack);
});
}
} |
JavaScript | class TodoForm extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
};
}
handleInputChange = (e) => {
this.setState({ inputValue: e.target.value });
}
handleSubmit = (e) => {
e.preventDefault();
// TODO: Invoke `createTask` with the `inputValue` state
// and dispatch a 'CREATE_TASK' action
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Add a todo"
value={this.state.inputValue}
onChange={this.handleInputChange}
/>
</form>
);
}
} |
JavaScript | class TaleError extends Error {
constructor (key, values, cause = null) {
const message = `Error: ${key} ${values}`
super(message)
this._key = key
this._values = values
this._cause = cause
this.render = $t => {
return $t(this._key, this._values || [])
}
this.cause = () => this._cause
}
} |
JavaScript | class FormState extends Component {
static propTypes = {
/**
* Elements of the form rendered
*/
children: PropTypes.node.isRequired,
/**
* CSS classes
*/
className: PropTypes.string,
/**
* Tag name used as container
*/
tagName: PropTypes.oneOfType([
PropTypes.instanceOf(Component),
PropTypes.instanceOf(PureComponent),
PropTypes.func,
PropTypes.string,
]),
/**
* Initial data provided
*/
data: PropTypes.shape({}),
/**
* Function to propagate change of the data e.g. Function(path, value)
*/
onChange: PropTypes.func,
/**
* Schema of validation e.g. { [string]: [result of combineValidations function, see recipe] }
*/
schemaData: PropTypes.shape({}),
/**
* Function to propagate settting the data e.g. Function(data)
*/
setData: PropTypes.func,
};
static defaultProps = {
className: '',
data: {},
tagName: 'form',
onChange: null,
schemaData: {},
setData: noop,
};
state = {
data: this.props.data,
createOnChange: path => this.createOnChange(path),
createOnChangeValue: path => this.createOnChangeValue(path),
schemaData: this.props.schemaData,
setData: data => this.setData(data),
addValidations: addValidations.bind(this),
clearValidations: clearValidations.bind(this),
isAllValid: isAllValid.bind(this),
};
// eslint-disable-next-line
UNSAFE_componentWillReceiveProps(nextProps) {
const state = {};
const { data: oldData, schemaData: oldSchemaData } = this.props;
const { data, schemaData } = nextProps;
if (oldSchemaData !== schemaData) {
state.schemaData = schemaData;
}
if (oldData !== data) {
state.data = data;
}
if (Object.keys(state).length) {
this.setState(state);
}
}
onChange = (path, value) => {
const { props: { onChange }, state: { data } } = this;
if (onChange) {
onChange(path, value);
return;
}
if (get(data, path) !== value) {
this.state.setData(set(path, value, data));
}
};
setData = (data) => {
const { setData } = this.props;
this.setState({ data }, () => setData(data));
};
createOnChange = (path) => {
this.memoization = this.memoization || {};
if (!this.memoization[path]) {
const onChangeValue = this.createOnChangeValue(path);
this.memoization[path] = (e) => {
onChangeValue(e.target.value);
};
}
return this.memoization[path];
};
createOnChangeValue = (path) => {
this.memoization = this.memoization || {};
const hash = getOnChangeValueHash(path);
if (!this.memoization[hash]) {
this.memoization[hash] = (value) => {
this.onChange(path, value);
};
}
return this.memoization[hash];
};
render() {
const { className, children, tagName } = this.props;
const Container = tagName;
this.state.clearValidations();
return (
<Container className={className}>
<FormContext.Provider value={this.state}>{children}</FormContext.Provider>
</Container>
);
}
} |
JavaScript | class ListPipelinesCtrl {
/**
* @param {!angular.$http} $http
* @ngInject
*/
constructor($http, $location) {
/** @const @private {!angular.$http} */
this.http_ = $http;
this.location_ = $location;
/** @export {!Array<!Object>} */
this.pipelines = [];
this.getPipelineList_();
}
/**
* Get a list of jobs
* @private
*/
getPipelineList_() {
this.http_.get('/api/pipelines').then((response) => {
// TODO(pasindu): Handle errors.
this.pipelines = response.data.operations;
});
}
getDetail(id) {
this.location_.url(`/pipeline/${id}`);
}
} |
JavaScript | class TopicManager {
constructor(config = defaultConfig) {
this.topics = {};
this.tenants = [];
this.config = config;
}
getKey(subject, tenant) {
return tenant + ":" + subject;
}
/**
* Retrieve a topic from Data Broker.
*
* This function will request Data Broker for a Kafka topic, given a subject
* and a tenant. It will retry a few times (configured in config object) and
* will reject the promise if it is unable to reach Data Broker for any
* reason. This promise will also be rejected if the response is not a valid
* JSON or contains invalid data.
*
* All topics are cached in order to speed up future requests.
*
* If true, the global parameter will indicate to Data Broker that the
* requested topic should be the same for all tenants. This is useful when
* dealing with topics that are intended to contain messages not related to
* tenants, such as messages related to services.
*
* @param {string} subject The subject related to the requested topic
* @param {string} tenant The tenant related to the requested topic
* @param {string} broker URL where data broker can be accessed
* @param {boolean} global true if this topic should be sensitive to tenants
*/
async getTopic(subject, tenant, broker, global) {
const key = this.getKey(subject, tenant);
if (this.topics.hasOwnProperty(key)) {
return Promise.resolve(this.topics[key]);
}
const querystring = global ? "?global=true" : "";
const url = `${broker}/topic/${subject + querystring}`;
return new Promise((resolve, reject) => {
let doIt = (counter) => {
axios({
url,
method: "get",
headers: {
authorization: `Bearer ${auth.getManagementToken(tenant, this.config)}`
}
}).then((response) => {
if ((typeof(response.data) === "object") && ("topic" in response.data)) {
this.topics[key] = response.data.topic;
return resolve(response.data.topic);
} else {
return reject(`Invalid response from Data Broker: ${response.data}`);
}
}).catch((error) => {
logger.error(`Could not get topic for ${subject}@${tenant} (global ${global})`, TAG);
logger.error(`Error is: ${error}`);
logger.debug(`Trying again in a few moments.`, TAG);
counter--;
logger.debug(`Remaining ${counter} time(s).`, TAG);
if (counter > 0) {
setTimeout(() => {
doIt(counter);
}, this.config.databroker.timeoutSleep * 1000);
} else {
return reject(`Could not reach DataBroker.`);
}
});
};
doIt(this.config.databroker.connectionRetries);
});
}
} |
JavaScript | class SvgRenderer extends ElementRenderer {
/**
* Constructor.
* @param {Object=} opt_options Options to configure the renderer
*/
constructor(opt_options) {
super(opt_options);
}
/**
* @inheritDoc
*/
getCanvas() {
return new Promise((resolve, reject) => {
var svgElement = this.getRenderElement();
if (svgElement) {
svgAsDataUri(svgElement, {
'scale': getPixelRatio()
}, this.onSvgUriReady_.bind(this, resolve, reject));
} else {
resolve(null);
}
});
}
/**
* @param {function(HTMLCanvasElement)} resolve The canvas resolve function
* @param {function(*)} reject The canvas rejection function
* @param {string=} opt_uri The SVG element data URI
* @private
*/
onSvgUriReady_(resolve, reject, opt_uri) {
if (opt_uri) {
var image = new Image();
image.onload = this.onSvgImageReady_.bind(this, resolve, reject, image);
/**
* @param {Event} event
*/
image.onerror = function(event) {
resolve(null);
};
image.src = opt_uri;
} else {
resolve(null);
}
}
/**
* @param {function(HTMLCanvasElement)} resolve The canvas resolve function
* @param {function(*)} reject The canvas rejection function
* @param {(Image|Error)=} opt_image The loaded SVG image
* @private
*/
onSvgImageReady_(resolve, reject, opt_image) {
var svgCanvas;
if (opt_image instanceof Image) {
svgCanvas = /** @type {!HTMLCanvasElement} */ (document.createElement('canvas'));
svgCanvas.width = opt_image.width;
svgCanvas.height = opt_image.height;
var context = svgCanvas.getContext('2d');
context.drawImage(opt_image, 0, 0);
}
resolve(svgCanvas || null);
}
} |
JavaScript | class Cmd_Abbandona extends Command {
constructor(client) {
super(client, {
name: "abbandona",
description: "Rimuove il proprio nome dalla lista del gioco specificato.",
category: "Liste Giocatori",
usage: "+abbandona <nome-gioco>",
aliases: ["leave"],
guildOnly: true
});
}
async run(message, args)
{
if (args.length == 0)
{
message.reply("È necessario indicare il nome di un gioco come secondo parametro del comando.");
return;
}
const game = args.shift().toLowerCase();
const userId = message.author.id;
const db = this.client.database.open();
db.getAsync("SELECT * FROM Registrazioni R, Giochi G WHERE R.game = G.nome AND game = ? AND userId = ?", [game, userId])
.then( async (registration) =>
{
if (registration)
{
const gameName = registration.nomeCompleto;
const role = await message.guild.roles.fetch(registration.ruolo);
// Toglie all'utente il ruolo del gioco da cui si è cancellato
if (role) message.member.roles.remove(role);
// Eliminazione del record relativo alla registrazione dell'utente
await db.runAsync("DELETE FROM Registrazioni WHERE game = ? AND userId = ?", [game, userId]);
message.reply(`Sei stato eliminato con successo dalla lista di **${gameName}**.`);
}
else
{
// Il gioco non esiste oppure l'utente non è registrato ?
const result = await db.getAsync("SELECT * FROM Giochi WHERE nome = ?", [game]);
if (result)
message.reply(`Non sei registrato alla lista di **${result.nomeCompleto}**.`);
else message.reply(`Il gioco \`${game}\` non esiste o non ha ancora una lista.`);
}
})
.catch( (error) =>
{
message.reply(`Si è verificato un errore durante l'esecuzione del comando. 🤬`);
tools.logCommandError(this.client.logger, this, error);
})
.finally( () => db.close() );
}
} |
JavaScript | class ASTVisitor {
visit(node) {
return this['visit' + node.type].apply(this, arguments);
}
} |
JavaScript | class ChartExample extends Component {
constructor(props) {
super(props);
/**
* Description of config
* -chartTitle: Defines the title of the chart(optional),
* -labels: Defines the label for xAxis and yAxis(optional),
* -yAxisVisible: If set to false, it will hide y axis data points.
* -dataPoints: Define the coordinates, color, name for the chart data
* -yCoordinates: Point to be plotted along y axis(mandatory). It takes value in array format
* The length of the array defines the multiple datapoint we want to plot
* -xCoordinates: Point to be plotted along x axis(mandatory)
* -dataLabel: Name for the chart(optional)
* -color: Color to be represented for data points(optional)
* -shadowEnabled: Name of the series for which shadow need to be enabled(optional)
* -tooltipVal: Extra tooltip value to be shown along with the main yCoordinate data points.(optional)
* Each object in the array represnt value for the particular yCoordinate datapoint.
*
* Apart from this user defined config, User can provide other highcharts config. This extra will merge while plotting the charts.
*
*/
this.state = {
lineConfig: {
chartTitle: null,
bgColor: '#F1F5FD',
labels: {
xAxis: null,
yAxis: null,
yAxisVisible: true
},
dataPoints: {
yCoordinates: [
[3.7, 3.3, 3.9, 5.1, 5.5, 3.8, 5.0, 9.0, 7.1, 3.7, 3.3, 6.2],
[0.2, 0.1, 0.5, 0.6, 0.3, 0.2, 0.3, 0.5, 0.7, 0.3, 0.2, 0.2],
[0.4, 0.5, 0.1, 0.6, 1.2, 0.9, 2.3, 3.5, 2.7, 4.3, 6.2, 1.2]
],
tooltipVal: [
[{ Goa: 234, Punjab: 98, Orissa: 76 }, { Goa: 112, Punjab: 35, Orissa: 98 }, { Goa: 239, Orissa: 76 }],
[
{ Goa: 244, Punjab: 68, Orissa: 71 },
{ Goa: 214, Punjab: 48, Orissa: 26 },
{ Goa: 294, Punjab: 38, Orissa: 56 },
{ Goa: 204, Punjab: 18, Orissa: 66 }
],
[]
],
shadowEnabled: 'Industry',
xCoordinates: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
seriesName: ['Industry', 'Manufacturing', 'Production'],
showSeriesName: false,
colors: ['#AFCAFD', '#E2E9F8', '#A3AFC7']
},
/**
* User defined tooltip formatting.
*/
tooltip: {
formatter: function() {
let str = `<b>${this.point.name}: </b>${this.y}`;
let tooltipObj = this.point.tootipVal;
if (tooltipObj && typeof tooltipObj !== 'object') {
throw new Error('Tooltip value should be in object format');
}
for (let key in tooltipObj) {
if (tooltipObj.hasOwnProperty(key)) {
str += `<br/>${key}: ${tooltipObj[key] || ''}`;
}
}
return str;
}
}
},
clickedPoint: {}
};
}
/**
* Immutably update the chart
*/
updateChartData = (originalConfig, newData) => {
const dataPoints = { dataPoints: { ...originalConfig.dataPoints, ...newData } };
return { ...originalConfig, ...dataPoints };
};
updateLineConfig = () => {
const coordinates = {
yCoordinates: [[10, 14, 25], [9, 10, 21]],
xCoordinates: ['2000', '2002', '2007']
};
const lineConfig = this.updateChartData(this.state.lineConfig, coordinates);
this.setState({ lineConfig });
};
/**
* Function to select a particular series data
*/
selectSeries = series => {
const enabledShadow = { shadowEnabled: series };
const lineConfig = this.updateChartData(this.state.lineConfig, enabledShadow);
this.setState({ lineConfig });
};
/**
* callback Function to called a once chart is renderd. It exposes a parameter for the type of chart rendered.
*/
postChartRender = chartType => {
console.log('Chart Rendered: ', chartType);
};
/**
* Function to be called upon clicking a particular point in the series
*/
seriesClickHandler = clickedPoint => {
this.setState({ clickedPoint });
};
render() {
const { lineConfig, clickedPoint } = this.state;
return (
<div style={{ width: '600px', margin: '0px auto' }}>
<h2>Linecharts</h2>
<Chart
type="spline"
config={lineConfig}
className="line-chart"
seriesClicked={this.seriesClickHandler}
callback={this.postChartRender}
/>
<button onClick={this.updateLineConfig}>Update Series</button>
<div style={btnGrp}>
<div style={btns} onClick={this.selectSeries.bind(null, 'Industry')}>
Select Industry Series
</div>
<div style={btns} onClick={this.selectSeries.bind(null, 'Manufacturing')}>
Select Manufacturing Series
</div>
<div style={btns} onClick={this.selectSeries.bind(null, 'Production')}>
Select Production Series
</div>
</div>
{clickedPoint.name ? (
<p>
Series Name: {clickedPoint.name}
<br /> Point Clicked: {clickedPoint.point}
</p>
) : null}
</div>
);
}
} |
JavaScript | class GVDataProcessorPlugin extends Plugin {
constructor( editor ) {
super( editor );
editor.data.processor = new GVDataProcessor(editor);
}
} |
JavaScript | class Prompt extends Component {
/**
* @method renderCancelButton
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
renderCancelButton = () => {
const { buttons } = this.props;
return (
<span
className="btn btn-meta-outline-secondary btn-distance-3 btn-sm"
onClick={this.props.onCancelClick}
>
{buttons.cancel}
</span>
);
};
/**
* @method renderSubmitButton
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
renderSubmitButton = () => {
const { buttons } = this.props;
return (
<span
className="btn btn-meta-primary btn-sm btn-submit"
onClick={this.submitClick}
>
{buttons.submit}
</span>
);
};
submitClick = () => {
this.props.onSubmitClick(this.props.selected);
};
/**
* @method render
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
render() {
const { onCancelClick, title, buttons } = this.props;
const { cancel, submit } = buttons;
return (
<div className="screen-freeze screen-prompt-freeze">
<div className="panel panel-modal-primary panel-prompt prompt-shadow">
<div className="panel-groups-header panel-modal-header panel-prompt-header">
<span className="panel-prompt-header-title panel-modal-header-title">
{title}
</span>
<i className="meta-icon-close-1" onClick={onCancelClick} />
</div>
<div className="panel-modal-content panel-prompt-content">
<p>{this.props.text}</p>
</div>
<div className="panel-groups-header panel-modal-header panel-prompt-header panel-prompt-footer">
<div className="prompt-button-wrapper">
{cancel ? this.renderCancelButton() : ''}
{submit ? this.renderSubmitButton() : ''}
</div>
</div>
</div>
<ModalContextShortcuts
done={this.submitClick}
cancel={this.props.onCancelClick}
/>
</div>
);
}
} |
JavaScript | class JavaScriptSettingsModel {
static getAttributeTypeMap() {
return JavaScriptSettingsModel.attributeTypeMap;
}
} |
JavaScript | class LevelScene extends Phaser.Scene {
/**
* Creates an instance of LevelScene.
* @memberof LevelScene
*/
constructor() {
super('LevelScene');
}
/**
* Creates the content of the LevelScene.
*
* @param {*} data
* @memberof LevelScene
*/
create(data) {
const levels = this.cache.json.get('levels');
this.target = levels[data.level].target;
const bg = this.add.image(512, 288, 'bg');
bg.setDepth(-3);
this.scene.get('MusicScene').play(1);
this.scene.run('PauseScene', data);
this.scene.pause();
const offscreen = new Phaser.Geom.Rectangle(1024, 0, 1, 576);
const onscreen = new Phaser.Geom.Rectangle(0, 0, 1025, 576);
const dustGraphics = this.make.graphics();
dustGraphics.fillStyle(0xffffff);
dustGraphics.fillPoint(0, 0, 2);
dustGraphics.generateTexture('dust', 2, 2);
this.add.particles('dust', [{
emitZone: {
source: offscreen,
},
deathZone: {
source: onscreen,
type: 'onLeave',
},
frequency: 25,
speedX: {
min: -200,
max: -1000,
},
lifespan: 5000,
}]);
this.newhorizons =
this.physics.add.image(490, 262, 'sprites', 'newhorizons');
this.newhorizons.body.setCircle(16, 8, 10);
this.newhorizons.setOrigin(0);
this.newhorizons.setCollideWorldBounds(true);
this.newhorizons.speed = 200;
this.focus = this.add.graphics({
x: 512,
y: 288,
});
this.focus.lineStyle(3, 0xffff00, 0.5);
this.focus.beginPath();
this.focus.moveTo(-120 - Profile.range * 24, -104 - Profile.range * 24);
this.focus.lineTo(-120 - Profile.range * 24, -120 - Profile.range * 24);
this.focus.lineTo(-104 - Profile.range * 24, -120 - Profile.range * 24);
this.focus.moveTo(-120 - Profile.range * 24, 104 + Profile.range * 24);
this.focus.lineTo(-120 - Profile.range * 24, 120 + Profile.range * 24);
this.focus.lineTo(-104 - Profile.range * 24, 120 + Profile.range * 24);
this.focus.moveTo(120 + Profile.range * 24, -104 - Profile.range * 24);
this.focus.lineTo(120 + Profile.range * 24, -120 - Profile.range * 24);
this.focus.lineTo(104 + Profile.range * 24, -120 - Profile.range * 24);
this.focus.moveTo(120 + Profile.range * 24, 104 + Profile.range * 24);
this.focus.lineTo(120 + Profile.range * 24, 120 + Profile.range * 24);
this.focus.lineTo(104 + Profile.range * 24, 120 + Profile.range * 24);
this.focus.strokePath();
this.physics.world.enable(this.focus);
this.focus.body.setSize(240 + Profile.range * 48, 240 + Profile.range * 48);
this.focus.body.setOffset(-120 - Profile.range * 24);
this.asteroids = this.physics.add.group();
this.physics.add.overlap(this.newhorizons, this.asteroids, () => {
if (!Profile.invincible) {
if (Profile.timeleft < 100) {
const levels = this.cache.json.get('levels');
Profile.timeleft = Profile.time * 60000;
this.scene.stop('PauseScene');
this.scene.start('LevelScene', {
level: data.level,
map: new AsteroidMap(levels[data.level]),
});
} else {
this.scene.stop('PauseScene');
this.scene.restart();
}
}
});
this.physics.add.overlap(this.focus, this.asteroids, (focus, asteroid) => {
if (!asteroid.shot) {
asteroid.infocus.visible = true;
}
asteroid.outoffocus.visible = false;
});
this.keys =
this.input.keyboard.addKeys('W,A,S,D,UP,LEFT,DOWN,RIGHT,SPACE,ENTER');
this.input.keyboard.on('keydown', (event) => {
event.preventDefault();
});
for (const asteroid of data.map.right) {
this.addasteroid(0, asteroid.x, asteroid.y);
}
for (const asteroid of data.map.down) {
this.addasteroid(1, asteroid.x, asteroid.y);
}
for (const asteroid of data.map.left) {
this.addasteroid(2, asteroid.x, asteroid.y);
}
for (const asteroid of data.map.up) {
this.addasteroid(3, asteroid.x, asteroid.y);
}
this.time.addEvent({
delay: 17000,
callback: () => {
this.cameras.main.fadeOut(300);
},
});
this.time.addEvent({
delay: 100,
loop: -1,
callback: () => {
if (Profile.timeleft < 100) {
return;
}
Profile.timeleft -= 100,
this.timebar.x =
~~(--Profile.timeleft / (60000 * Profile.time) * 206 - 206);
const minutes = ~~(Profile.timeleft / 60000);
const seconds = ~~((Profile.timeleft % 60000) / 1000);
this.timecounter.text =
minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
},
});
this.input.keyboard.on('keydown-ENTER', (event) => {
event.preventDefault();
if (this.photos < Profile.photo * 3) {
this.takePicture();
}
});
this.input.keyboard.on('keydown-SPACE', (event) => {
event.preventDefault();
if (this.photos < Profile.photo * 3) {
this.takePicture();
}
});
this.cameras.main.on('camerafadeoutcomplete', () => {
if (data.level === levels.length - 1) {
this.scene.stop('PauseScene');
this.scene.start('WinScene', {
level: data.level,
science: this.science,
});
this.scene.stop('LevelScene');
} else {
this.scene.stop('PauseScene');
this.scene.start('MenuScene', {
level: data.level,
science: this.science,
});
this.scene.stop('LevelScene');
}
});
this.photos = 0;
this.add.image(76, 512, 'sprites', 'frame').setDepth(-1);
this.add.image(40, 536, 'sprites', 'photocounter');
this.photocounter =
this.add.text(40, 536, Profile.photo * 3 - this.photos, {
fontSize: '24px',
fontFamily: 'font',
});
this.photocounter.setOrigin(0.5);
this.textures.on('addtexture', (photo) => {
this.cameras.main.flash(50, 64, 64, 64);
this.add.image(76 + (this.photos - 1) * 16, 512, photo)
.setDisplaySize(72, 72).setDepth(-1);
this.add.image(76 + (this.photos - 1) * 16, 512, 'sprites', 'frame')
.setDepth(-1);
});
this.science = 0;
const progressborder = this.add.image(0, 0, 'sprites', 'progressborder');
this.progressbar = this.add.image(0, 160, 'sprites', 'progressbar');
const progressoverlay = this.add.image(0, 0, 'sprites', 'progressoverlay');
this.progresscounter = this.add.text(56, -60, this.science + '⚛', {
fontSize: '24px',
fontFamily: 'font',
});
this.add.container(96, 164, [
progressborder,
this.progressbar,
this.progresscounter,
progressoverlay,
]);
this.progressmask = this.add.image(96, 164, 'sprites', 'progressbar');
this.progressmask.visible = false;
this.progressbar.mask =
new Phaser.Display.Masks.BitmapMask(this, this.progressmask);
this.progresscounter.setOrigin(1, 0.5);
const timeborder = this.add.image(0, 0, 'sprites', 'timeborder');
this.timebar = this.add.image(
Profile.timeleft / (Profile.time * 60000) * 206 - 206,
0,
'sprites',
'timebar',
);
this.timecounter = this.add.text(0, 12, '', {
fontSize: '24px',
fontFamily: 'font',
});
const minutes = ~~(Profile.timeleft / 60000);
const seconds = ~~((Profile.timeleft % 60000) / 1000);
this.timecounter.text = minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
this.timecounter.setOrigin(0.5);
this.add.container(512, 48, [
timeborder,
this.timebar,
this.timecounter,
]);
this.timemask = this.add.image(512, 48, 'sprites', 'timebar');
this.timemask.visible = false;
this.timebar.mask =
new Phaser.Display.Masks.BitmapMask(this, this.timemask);
}
/**
*
*
* @memberof LevelScene
*/
takePicture() {
const focus = this.focus.body.getBounds({});
this.game.renderer.snapshotArea(
focus.x,
focus.y,
240 + Profile.range * 48,
240 + Profile.range * 48,
(image) => {
this.photos += 1;
this.textures.addImage('photo' + Phaser.Math.RND.uuid(), image);
this.photocounter.text = Profile.photo * 3 - this.photos;
this.physics.overlapRect(
focus.x,
focus.y,
240 + Profile.range * 48,
240 + Profile.range * 48,
).forEach((body) => {
if (this.asteroids.contains(body.gameObject) &&
!body.gameObject.shot) {
body.gameObject.shot = true;
body.gameObject.infocus.visible = false;
this.science += 1;
this.progresscounter.text = this.science + '⚛';
let y = 160 - ~~((this.science / this.target) * 92);
// eslint-disable-next-line new-cap
y = Phaser.Math.Clamp(y, 0, 160);
this.tweens.add({
targets: this.progressbar,
y: y,
ease: 'Quad',
duration: 300,
});
}
});
},
);
}
/**
*
*
* @memberof LevelScene
*/
update() {
if (!this.newhorizons.body) {
return;
}
this.newhorizons.setVelocity(0);
if (this.keys.W.isDown || this.keys.UP.isDown) {
this.newhorizons.setVelocityY(-this.newhorizons.speed);
}
if (this.keys.A.isDown || this.keys.LEFT.isDown) {
this.newhorizons.setVelocityX(-this.newhorizons.speed);
}
if (this.keys.S.isDown || this.keys.DOWN.isDown) {
this.newhorizons.setVelocityY(this.newhorizons.speed);
}
if (this.keys.D.isDown || this.keys.RIGHT.isDown) {
this.newhorizons.setVelocityX(this.newhorizons.speed);
}
// eslint-disable-next-line new-cap
const focusx = Phaser.Math.Clamp(
this.newhorizons.x + 22,
120 + Profile.range * 24,
904 - Profile.range * 24,
);
// eslint-disable-next-line new-cap
const focusy = Phaser.Math.Clamp(
this.newhorizons.y + 26,
120 + Profile.range * 24,
456 - Profile.range * 24,
);
this.focus.setPosition(focusx, focusy);
this.asteroids.getChildren().forEach((asteroid) => {
if (asteroid.body.touching.none) {
asteroid.infocus.visible = false;
}
asteroid.outoffocus.visible = false;
});
this.physics.overlapRect(0, 0, 1024, 576).forEach((body) => {
if (this.asteroids.contains(body.gameObject) &&
!body.gameObject.infocus.visible &&
!body.gameObject.shot) {
body.gameObject.outoffocus.visible = true;
}
});
}
/**
*
*
* @param {*} d
* @param {*} x
* @param {*} y
* @memberof LevelScene
*/
addasteroid(d, x, y) {
const frame =
['asteroidright', 'asteroiddown', 'asteroidleft', 'asteroidup'][d];
const asteroid = this.add.image(0, 0, 'sprites', frame);
const infocus = this.add.image(0, 0, 'sprites', 'infocus');
const outoffocus = this.add.image(0, 0, 'sprites', 'outoffocus');
// infocus.lineStyle(3, 0xffff00, 0.5);
// infocus.beginPath();
// infocus.moveTo(0, -16);
// infocus.lineTo(0, -24);
// infocus.moveTo(0, 16);
// infocus.lineTo(0, 24);
// infocus.moveTo(-16, 0);
// infocus.lineTo(-24, 0);
// infocus.moveTo(16, 0);
// infocus.lineTo(24, 0);
// infocus.closePath();
// infocus.strokePath();
// infocus.strokeCircle(0, 0, 20);
// const outoffocus = this.add.graphics();
// outoffocus.lineStyle(3, 0xffffff, 0.5);
// outoffocus.beginPath();
// outoffocus.arc(
// // eslint-disable-next-line new-cap
// 0, 0, 40, Phaser.Math.DegToRad(30), Phaser.Math.DegToRad(60),
// );
// outoffocus.strokePath();
// outoffocus.beginPath();
// // eslint-disable-next-line new-cap
// outoffocus.arc(
// // eslint-disable-next-line new-cap
// 0, 0, 40, Phaser.Math.DegToRad(120), Phaser.Math.DegToRad(150),
// );
// outoffocus.strokePath();
// outoffocus.beginPath();
// // eslint-disable-next-line new-cap
// outoffocus.arc(
// // eslint-disable-next-line new-cap
// 0, 0, 40, Phaser.Math.DegToRad(210), Phaser.Math.DegToRad(240),
// );
// outoffocus.strokePath();
// outoffocus.beginPath();
// // eslint-disable-next-line new-cap
// outoffocus.arc(
// // eslint-disable-next-line new-cap
// 0, 0, 40, Phaser.Math.DegToRad(300), Phaser.Math.DegToRad(330),
// );
// outoffocus.strokePath();
this.tweens.add({
targets: [outoffocus, infocus],
angle: 90,
loop: -1,
});
infocus.visible = false;
outoffocus.visible = false;
const asteroidcontainer =
this.add.container(x, y, [asteroid, infocus, outoffocus]);
this.physics.world.enable(asteroidcontainer);
asteroidcontainer.body.setCircle(32, -32, -32);
this.asteroids.add(asteroidcontainer);
asteroidcontainer.body.setVelocity(
[200, 0, -200, 0][d],
[0, 200, 0, -200][d],
);
asteroidcontainer.setDepth(-2);
asteroidcontainer.infocus = infocus;
asteroidcontainer.outoffocus = outoffocus;
}
} |
JavaScript | class Helper {
/**
* update Attribute on input element actively, so we dont have things like pattern="undefined" on the native element.
* @param attribute
* @param value
* @private
*/
static UpdateInputAttribute(caller, attribute, value) {
caller.updateComplete.then((d) => {
if (!caller._theInputElement) {
caller._theInputElement = caller.shadowRoot.getElementById("input");
}
if (value !== null) {
caller._theInputElement.setAttribute(attribute, value);
} else {
// remove the attribute on null value
caller._theInputElement.removeAttribute(attribute);
}
})
}
/**
* Bind a entity field to the input. You can use the entity even when no data was received.
* When you use `@-object-ready` from a `furo-data-object` which emits a EntityNode, just bind the field with `--entity(*.fields.fieldname)`
* @param {Object|caller} furo input element
* @param {Object|FieldNode} fieldNode a Field object
*/
static BindData(caller, fieldNode) {
if (fieldNode === undefined) {
console.warn("Invalid binding ");
console.log(caller);
return
}
caller.field = fieldNode;
CheckMetaAndOverrides.UpdateMetaAndConstraints(caller);
caller._updateField();
caller.field.addEventListener('field-value-changed', (e) => {
caller._updateField();
if (caller.field._meta && caller.field._meta.hint) {
caller._hint = caller.field._meta.hint;
}
if (caller.hint) {
caller._hint = caller.hint;
}
});
// update meta and constraints when they change
caller.field.addEventListener('this-metas-changed', (e) => {
CheckMetaAndOverrides.UpdateMetaAndConstraints(caller);
});
caller.field.addEventListener('field-became-invalid', (e) => {
// updates wieder einspielen
caller.error = true;
caller.errortext = caller.field._validity.description;
caller.requestUpdate();
});
caller.field.addEventListener('field-became-valid', (e) => {
// updates wieder einspielen
caller.error = false;
caller.requestUpdate();
});
}
} |
JavaScript | class NgTooltipDirective {
/**
* @param {?} _el
*/
constructor(_el) {
this._el = _el;
this.tooltipContainer = "body";
this.GetTooltipOptions = () => {
let /** @type {?} */ options = {
title: this.tooltipContent,
html: this.tooltipHtml,
container: this.tooltipContainer
};
if (!!this.tooltipTemplate) {
options.template = this.tooltipTemplate;
}
return options;
};
}
/**
* @return {?}
*/
ngAfterViewInit() {
const /** @type {?} */ tooltipOptions = this.GetTooltipOptions();
this._tooltip = new Tooltip(this._el.nativeElement, tooltipOptions);
}
/**
* @return {?}
*/
ngOnDestroy() {
this._tooltip.dispose();
this._tooltip = null;
}
} |
JavaScript | class ChatUsersPrivateMessages extends Component {
constructor(props){
super(props);
}
// componentWillReceiveProps(nextProps){
// if(nextProps.privateMessages){
// // console.log('---', nextProps.privateMessages);
// }
// }
componentWillUpdate(){
// console.log('me die');
}
componentDidMount(){
console.log('private mounted');
// let last;
// let secondLast;
// if(this.container && this.container.lastChild && this.container.lastChild.previousElementSibling){
// last = this.container.lastChild.clientHeight;
// secondLast = this.container.lastChild.previousElementSibling.clientHeight;
// }
// console.log('handleScroll', this.container.scrollTop, this.container.scrollHeight, this.container.clientHeight);
// if(this.container.scrollHeight > this.container.clientHeight){
//+ another 20 perhaps? >= then it should always be greater, right?
//|| this.container.scrollTop < this.container.scrollHeight - this.container.clientHeight
// if(this.container.scrollTop+ this.container.clientHeight+last+secondLast >= this.container.scrollHeight){
// console.log('qq', this.container.scrollTop, this.container.scrollHeight- this.container.clientHeight);
//- this.container.clientHeight i dont need to substract it..
this.container.scrollTop = this.container.scrollHeight;
// }
}
componentDidUpdate(){
//scroll to the bottom
// console.log('very pls scroll');
let last;
let secondLast;
if(this.container && this.container.lastChild && this.container.lastChild.previousElementSibling){
last = this.container.lastChild.clientHeight;
secondLast = this.container.lastChild.previousElementSibling.clientHeight;
}
// console.log('handleScroll', this.container.scrollTop, this.container.scrollHeight, this.container.clientHeight);
// if(this.container.scrollHeight > this.container.clientHeight){
//+ another 20 perhaps? >= then it should always be greater, right?
//|| this.container.scrollTop < this.container.scrollHeight - this.container.clientHeight
if(this.container.scrollTop+ this.container.clientHeight+last+secondLast >= this.container.scrollHeight){
// console.log('qq', this.container.scrollTop, this.container.scrollHeight- this.container.clientHeight);
//- this.container.clientHeight i dont need to substract it..
this.container.scrollTop = this.container.scrollHeight;
}
}
renderMessages(){
const u = localStorage.getItem('username');
let final = [];
// console.log('PMs', this.props.privateMessages);
// console.log('PM - should rerender!', this.props.privateMessages);
if(this.props.privateMessages[0]){
// console.log('0');
if(this.props.privateMessages[0].messages){
// console.log('1', this.props.fullChat.channel);
//not this.props.channel because it doesnt exist if i leave and join with and open chat
//the state is global now, set right after making the channel
const messages = this.props.privateMessages.filter(message => message.channel === this.props.fullChat.channel);
// console.log('2', messages);
if(messages.length !== 0){
final = messages[0].messages;
}
// console.log('qweqwewq', final);
// console.log('f', final);
// console.log(';', messages);
return final.map((message, index) => {
return (
<div className="chat-full-users-private-messages-single"
key={index}>
<span
className={"chat-full-users-private-messages-single-person " + (message.person !== u ? "other-person" : "")}>
{message.person}:</span> {message.message}
</div>
);
});
}
}
}
render(){
// console.log('PM2', this.props.messages);
// console.log('props', this.props.messages);
// console.log('channel in messages', this.props.channel);
// console.log('messages', this.props.messages);
return (
<div ref={div => this.container = div} className="chat-full-users-private-messages">
{this.renderMessages()}
</div>
);
}
} |
JavaScript | class Html extends Component {
static propTypes = {
assets: PropTypes.object,
component: PropTypes.node,
store: PropTypes.object,
};
render() {
const { assets, component, store } = this.props;
const content = component ? ReactDOM.renderToString(component) : '';
const head = Helmet.rewind();
return (
<html lang="zh-TW">
<head>
{head.base.toComponent()}
{head.title.toComponent()}
{head.meta.toComponent()}
{head.link.toComponent()}
{head.script.toComponent()}
<link
rel="shortcut icon"
href="https://image.goodjob.life/favicon.ico"
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charSet="UTF-8" />
{assets.client.css && (
<link rel="stylesheet" href={assets.client.css} />
)}
{/* include Sentry library for reporting website error --> */}
<script
src="https://cdn.ravenjs.com/3.26.4/raven.min.js"
crossOrigin="anonymous"
/>
{/* install google tag manager */}
<script
dangerouslySetInnerHTML={{
__html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${GTM_ID}');`,
}}
/>
</head>
<body>
{/* install google tag manager */}
<noscript>
{/* eslint-disable-next-line jsx-a11y/iframe-has-title */}
<iframe
src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
height="0"
width="0"
style={{ display: 'none', visibility: 'hidden' }}
/>
</noscript>
<div
id="root"
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: content }}
/>
<script
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `window.__data=${serialize(store.getState())};`,
}}
charSet="UTF-8"
/>
<script src={assets.client.js} charSet="UTF-8" />
</body>
</html>
);
}
} |
JavaScript | class RestClient {
/**
* us-plove-Elderly123!---22
*
* Sends POST request to admin api, which is then forwarded to the correct customer api endpoint.
* The request is validated in the admin api before forwarding.
* @param {function} getState
* @param {string} endPoint
* @param {string} sessionId
*/
static async GetRequest(getState, endPoint, sessionId = null) {
if (typeof getState !== 'function') {
throw new Error('getState parameter must be a function.');
}
const url = `${baseUrl}/${endPoint}`;
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
if (sessionId) {
headers.SessionId = sessionId;
}
try {
const response = await fetch(url, { headers });
const jsonResponse = await response.json();
return Promise.resolve(jsonResponse);
} catch (error) {
return Promise.reject(error);
}
}
/**
* Sends POST request to admin api, which is then forwarded to the correct customer api endpoint.
* The request is validated in the admin api before forwarding.
* @param {function} getState
* @param {string} endPoint
* @param {object} params
*/
static async PostRequest(getState, endPoint, params, keyName, sessionId) {
if (typeof getState !== 'function') {
throw new Error('getState parameter must be a function.');
}
let url = `${baseUrl}/${endPoint}`;
//AgencyId
if (keyName != null && keyName.length > 0) {
const key = '29xdVi33L5W32SL2';
const myObjStr = JSON.stringify(params);
debugger;
NativeModules.AES128.AESEncryptWithPassphrase(
key,
myObjStr,
async (error, encryptedbase64) => {
//this.setState({ isOn: isOn});
//console.log(error)
debugger;
//alert(error + "=>Encryption:-> " + encryptedbase64);
if (encryptedbase64 != null && encryptedbase64.length > 0) {
params = { keyName: encryptedbase64 };
let rawResponse = await axios.post(url, params, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
//debugger;
try {
return Promise.resolve(rawResponse.data);
} catch (error) {
return Promise.reject(error);
}
} else {
return Promise.reject(error);
}
},
);
// RNCryptor.encrypt(params, key).then(async (encryptedbase64)=>{
// console.log(encryptedbase64)
//
// }).catch((error)=>{
// console.log(error)
// debugger;
// return Promise.reject(error);
// })
} else {
var header = {};
if (sessionId == null) {
header = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
} else {
header = {
Accept: 'application/json',
'Content-Type': 'application/json',
SessionId: sessionId,
};
}
//debugger;
let rawResponse = await axios.post(url, params, { headers: header });
console.log('URL:-' + url);
console.log('Input:-' + JSON.stringify(params));
console.log('RES:-' + rawResponse);
//debugger;
try {
return Promise.resolve(rawResponse.data);
} catch (error) {
return Promise.reject(error);
}
}
}
static async PostMultipart(getState, endPoint, file, params) {
if (typeof getState !== 'function') {
throw new Error('getState parameter must be a function.');
}
const url = `${baseUrl}/${endPoint}`;
const { SID } = getState().auth.user;
const { UID } = getState().auth.user;
// const updatedFile = {
// ...file,
// uri: Platform.OS === 'ios' ? file.uri.replace('file://', '') : file.uri,
// };
const formData = new FormData();
if (file)
formData.append('file', {
name: file.fileName,
type: file.type,
uri:
Platform.OS === 'android'
? file.uri
: file.uri.replace('file://', ''),
});
formData.append('ParamData', JSON.stringify(params));
console.log('URL:-' + url);
console.log('Input:-' + JSON.stringify(formData));
debugger;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
SessionId: SID,
},
body: formData,
});
const jsonResponse = await response.json();
debugger;
console.log('OUTPUT:-' + JSON.stringify(jsonResponse));
debugger;
return Promise.resolve(jsonResponse);
} catch (error) {
return Promise.reject(error);
}
}
} |
JavaScript | class Tags {
/**
* @constructor
* @param tags
*/
constructor(tags) {
this.tags = tags;
this.tagsObj = convertTagArrayToObject(tags);
this.tagValues = this.tags.map((t) => t.name);
}
/**
* @description return all tags
* @return {Array<Tag>}
*/
getTags() {
return this.tags;
}
/**
* @desc returns all tags as an Object where Tags' names are the keys
* @return {Object}
*/
getTagsAsObject() {
return this.tagsObj;
}
/**
* @desc looks up if tag is known
* @param {String} tag
* @return {*}
*/
isKnownTag(tag) {
return this.tagValues.includes(tag);
}
/**
* @desc checks if all tags in an array are known
* @param {Array<String>}tagArr
* @return {Promise<boolean>}
*/
async filterInput(tagArr) {
tagArr.forEach((t) => {
if (this.isKnownTag(t) === false) {
throw Error(`tag ${t} is not known`);
}
});
return true;
}
} |
JavaScript | class Row {
constructor() {
this.items = [];
this.letters = 0;
}
} |
JavaScript | class Admin {
/**
* API for login with email
* @param {string} email
* @param {string} password
* @returns success response(status code 200) with auth_token
* @date 2021-12-19
*/
async login(req, res) {
try {
await adminValidator.validateLoginRequest(req.body);
let data = await adminHelper.adminExists(req.body);
if (data.length > 0) {
if(data[0].is_verified==0){
throw {message:'USER_NOT_VERIFIED'}
}else{
let validatePassword = await adminValidator.validatePassword(data[0].hash, req.body.password);
if (!validatePassword) {
responseHandler.sendErrorresponse(res, req.headers.language, 'INCORRECT_PASSWORD');
} else {
delete data[0].password;
let token = await adminHelper.getJwtToken(data[0].email,data[0]._id)
responseHandler.sendSuccessresponse(res, req.headers.language, 'LOGIN_SUCCESS', { admin_data: data, auth_token: token });
}
}
} else {
responseHandler.sendErrorresponse(res, req.headers.language, 'USER_NOT_EXIST');
}
}
catch (error) {
responseHandler.sendErrorresponse(res, req.headers.language, error.message);
}
}
} |
JavaScript | class NoTransform {
constructor(type = 'text/html; charset=utf-8') {
this.type = type;
}
apply(body) {
return (0, either_1.right)(body);
}
} |
JavaScript | class UndefinedContextError extends ErrorBase {
/**
* Create a new instance of {UndefinedContextError}
*
* @param args
* @constructor
* @public
*/
constructor (...args) {
super('Undefined context', ...args)
}
} |
JavaScript | class HoverScale extends Behavior
{
get type(){ return 'HoverScale'; }
constructor(config)
{
super();
this.config = Object.assign(
{scale: 1.15, duration: 75, revertOnDispose: true},
config
);
this.object3d = null;
this.originalScale = null;
this.elapsedTime = this.config.duration;
this.progress = 1;
this.srcScale = null;
this.destScale = null;
this.onHoverStateChange = (() => {
[this.srcScale, this.destScale] = [this.destScale, this.srcScale];
this.progress = 1 - this.progress;
this.elapsedTime = this.config.duration - this.elapsedTime;
}).bind(this);
}
awake(o, s)
{
this.object3d = o;
this.originalScale = this.object3d.scale.clone();
this.srcScale = this.object3d.scale.clone();
this.srcScale.multiplyScalar(this.config.scale);
this.destScale = new THREE.Vector3();
this.destScale.copy(this.originalScale);
this.progress = 1;
this.elapsedTime = this.config.duration;
this.object3d.addEventListener('cursorenter', this.onHoverStateChange);
this.object3d.addEventListener('cursorleave', this.onHoverStateChange);
}
update(deltaTime)
{
if(this.progress < 1) {
this.elapsedTime = THREE.Math.clamp(
this.elapsedTime + deltaTime, 0, this.config.duration
);
this.progress = THREE.Math.clamp(this.elapsedTime / this.config.duration, 0, 1);
this.object3d.scale.lerpVectors(this.srcScale, this.destScale, this.progress);
}
}
dispose()
{
this.object3d.removeEventListener('cursorenter', this.onHoverStateChange);
this.object3d.removeEventListener('cursorleave', this.onHoverStateChange);
// Restore Original Object Scale Before Behavior Was Applied
if(this.config.revertOnDispose)
this.object3d.scale.copy(this.originalScale);
this.originalScale = null;
this.srcScale = null;
this.destScale = null;
this.object3d = null;
}
} |
JavaScript | class LocalStorage {
/**
* Initialize local storage with undefined enabled flag.
*/
constructor() {
/**
* Map to store Key/Value data
*/
this.storage = {};
/**
* Boolean to determine is native LocalStorage is enabled or not.
*/
this.storageEnabled = undefined;
}
/**
* Check if LocalStorage is available.
* @return {Boolean} True if LocalStorage is available, false otherwise
*/
isEnabled() {
if (typeof this.storageEnabled === 'undefined') {
try {
localStorage.setItem(localStorageKeyCheck, true);
localStorage.removeItem(localStorageKeyCheck);
this.storageEnabled = true;
} catch (e) {
this.storageEnabled = false;
}
}
return this.storageEnabled;
}
/**
* Return item from LocalStorage
* @param {String} key Searched key
* @return {Object} Value found or undefined
*/
getItem(key) {
return this.isEnabled() ? localStorage.getItem(key) : this.storage[key];
}
/**
* Store a value with a key from LocalStorage.
* @param {String} key Key stored
* @param {Object} value Value stored
*/
setItem(key, value) {
if (this.isEnabled()) {
localStorage.setItem(key, value);
} else {
this.storage[key] = value;
}
}
/**
* Remove entry from LocalStorage for given key.
* @param {String} key Searched key
*/
removeItem(key) {
if (this.isEnabled()) {
localStorage.removeItem(key);
} else {
delete this.storage[key];
}
}
} |
JavaScript | class Home extends React.Component {
//no need to maintain states as we now have a global store.
//access it from the props.
render() {
//destructuring means mapping the value directly
//to the mentioned keys inside {}
//keys inside { } and of this.state Object should match.
const { posts } = this.props;
// same as posts = this.props.posts.slice();
console.log(posts);
const postList = posts.length ? (
posts.map(post => {
return (
<div className="post card" key={post.id}>
<img src={pokeball} alt="Pokeball" />
<div className="card-content">
<Link to={"/" + post.id} >
<span className="card-title green-text"> {post.title} </span>
</Link>
<p>{post.body}</p>
</div>
</div>
);
})
) : (
<p>You are all caught up!</p>
);
return (
<div className="container">
<h1>Home</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam in animi magnam fugiat expedita exercitationem illum, earum non beatae molestiae placeat nisi dolor quae nobis dolorem doloremque deserunt illo autem.</p>
<h3 className="center">Posts</h3>
{postList}
</div>
);
}
} |
JavaScript | class Build extends Emitter {
static runTask (task) {
const pr = mr.find({ number: task.number })
let build
if (!pr) {
build = null
} else {
build = new Build(task.number, pr.head)
build.promise = build[task.name](task)
}
return build
}
constructor (id, head) {
super()
this.id = id
this.repoUrl = head.repo.clone_url
.replace(/\/\//, `//${config.ghToken}@`)
this.branch = head.ref
this.mainBranch = head.repo.default_branch
this.workspace = join(workDir, '' + this.id)
shelljs.mkdir('-p', this.workspace)
this.emit('status', 'init')
}
exec (cmd, opts = {
async: true,
timeout: config.get('execTimeout')
}) {
if (this.worker) {
this.kill()
}
return new Promise(resolve => {
shelljs.cd(this.workspace)
console.log(`>>>> Run task for #${this.id}@${this.branch}:`, cmd)
this.worker = shelljs.exec(cmd, opts, (code, stdout, stderr) => {
resolve([code, stdout, stderr])
})
})
.then(([code, stdout, stderr]) => {
this.worker = null
if (code !== 0) throw new Error(stderr)
return stdout
})
}
kill () {
if (this.worker) {
this.worker.kill()
this.worker = null
}
this.emit('status', 'kill')
}
download () {
const repoExist = shelljs.test('-d', join(this.workspace, '.git'))
let cmd = !repoExist ?
// first download
`git clone ${this.repoUrl} . && git checkout ${this.branch}`
// update
: `git fetch && git reset --hard FETCH_HEAD && git clean -df `
cmd += ` && git merge origin/${this.mainBranch} --no-edit`
this.emit('status', 'download')
return this.exec(cmd)
}
prepare (params = {}) {
const hasYarn = shelljs.which('yarn')
const cmd = hasYarn ? 'yarn' : 'npm install'
this.setEnv(params)
this.emit('status', 'install')
return this.exec(cmd)
}
setEnv ({ env = {} }) {
Object.assign(shelljs.env, env)
return Promise.resolve()
}
build () {
this.emit('status', 'build')
return this.exec('npm run build')
}
deploy ({ target }) {
this.emit('status', 'deploy')
return this.exec(`TARGET=${target} npm run deploy`)
.then((...args) => {
this.emit('status', 'success')
return args
})
}
clean () {
this.emit('status', 'clean')
return this.exec(`cd .. && rm -rf ${this.workspace}`)
}
} |
JavaScript | class ResizeAwareMap extends PureComponent {
render() {
return (
<ResizeAware style={{ width: '100%', height: '100%' }}>
{({ width, height }) => (
<Map
// mapStyle={appSettings.map.style}
width={width}
height={height}
/>
)}
</ResizeAware>
);
}
} |
JavaScript | class AsyncCreatable {
/**
* Constructs a new `AsyncCreatable` instance. For internal and subclass use only.
* New subclass instances must be created with the static {@link create} method.
*
* @param options An options object providing initialization params.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(options) {
/* leave up to implementer */
}
/**
* Asynchronously constructs and initializes a new instance of a concrete subclass with the provided `options`.
*
* @param options An options object providing initialization params to the async constructor.
*/
static async create(options) {
const instance = new this(options);
await instance.init();
return instance;
}
} |
JavaScript | class AsyncOptionalCreatable {
/**
* Constructs a new `AsyncCreatable` instance. For internal and subclass use only.
* New subclass instances must be created with the static {@link create} method.
*
* @param options An options object providing initialization params.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(options) {
/* leave up to implementer */
}
/**
* Asynchronously constructs and initializes a new instance of a concrete subclass with the optional `options`.
*
* @param options An options object providing initialization params to the async constructor.
*/
static async create(options) {
const instance = new this(options);
await instance.init();
return instance;
}
} |
JavaScript | class MediaOptimizer {
constructor(watch) {
this.watch = watch;
this.handler_list = {};
/**
* Holds runtime config for each handler
* @type {{}}
*/
this.option = {};
}
/**
* Searches the `src` for all files that match registered handlers, executing building and attaching of wanted file/folder watcher
*
* @param src
* @param build
* @return {Promise<{}>}
*/
run(src, build) {
return new Promise((resolve) => {
let exec = [];
let res;
for(let type in this.option) {
// go through all activated handler types, those with option
res = this.handlerDispatch(type, src, build);
if(res) {
exec.push(...res);
}
}
this.analyzeStats(exec).then((result_list) => {
resolve(result_list)
});
});
}
/**
* Executes an array of media handlers and will process their async returns, prints stats
*
* @param exec
* @return {Promise<any[]>}
*/
analyzeStats(exec) {
return Promise.all(exec).then((result_list) => {
// create stats for all created files
let qty = 0;
let saved = 0;
result_list.forEach((elem) => {
if(elem.saved) {
if(0 > elem.saved) {
log.raw(colors.red('MediaOptimizer: negative saved size (' + elem.saved + 'KB) found for `' + elem.file + '`'));
}
saved += elem.saved;
qty++;
}
});
log.raw(
colors.white(
'MediaOptimizer: optimized ' +
qty + ' file' + (1 < qty ? 's' : '') +
' and saved ' +
colors.underline(Math.round(saved * 100) / 100 + 'KB') + ' of size!'
)
);
// ends media optimizer
return result_list;
})
}
/**
* Executes the handler for each file that is found in one dir to one types all file globs, fetch options and add watchers
*
* @param type
* @param src one dir
* @param build one dir
* @return {*}
*/
handlerDispatch(type, src, build) {
src = path.resolve(src);
if(this.handler_list.hasOwnProperty(type) && 'function' === typeof this.handler_list[type]) {
// when handler exists
let option = this.getOption(type);
/**
* Scan for files foreach `files` selector provided through `option`
* @return {Array}
*/
const scanFile = () => {
let files = [];
// suffix the src path with the files glob
// todo: make async multithread glob
option.files.forEach((src_glob) => {
let found = glob(path.resolve(src + '/' + src_glob), {sync: true});
files.push(...found);
});
return files;
};
/**
* the current active files, overwritten when newer detected
*
* @type {Array}
*/
let files = scanFile();
/**
* Gets added files or false for scanned folder files
* @param new_files
* @return {boolean|Array}
*/
const addedFiles = (new_files) => {
let added = new_files.filter(x => !files.includes(x));
if([] === added) {
added = false;
}
return added;
};
let exec = [];
files.forEach((file) => {
/**
* @type {HandlerDynamic|HandlerPNG|HandlerJPG}
*/
let handler = this.initHandler(type, src, file, build, option);
exec.push(handler.run());
});
if(this.watch) {
// add watcher to rescan for new files in folder
// todo: !warning! maybe this spawns too much file listeners, as is initiated for the src of each handler, so one src and 5 handler = 5 media-folder watcher active, they are watching everything and not only for change for their needed files, !warning! it is filtered through rescanning every src again with recursive glob for each handler active
let watcher = new FileWatcher('media-folder ' + src);
watcher.add(src);
watcher.onError();
watcher.onReady();
// Change and Unlink are watched from within each file on itself
// checks for new files in the directory of this mediaoptimizer instance and starts those files on their own, not retriggering everything
watcher.onChangeAdd(() => {
let added = addedFiles(scanFile());
if(added) {
// only for new files
added.forEach((file) => {
/**
* @type {HandlerDynamic|HandlerPNG|HandlerJPG}
*/
let handler = this.initHandler(type, src, file, build, option);
this.analyzeStats([handler.run()]).then((result_list) => {
});
});
}
});
}
return exec;
}
console.log(colors.red('no handler registered for type ' + type));
return [];
}
/**
* @param type
* @param src
* @param file
* @param build
* @param option
* @return {HandlerDynamic|HandlerPNG|HandlerJPG}
*/
initHandler(type, src, file, build, option) {
// creating new handler for file
/**
* @type {HandlerDynamic|HandlerPNG|HandlerJPG}
*/
let tmp_handler = new this.handler_list[type](src, path.resolve(file), path.resolve(build), option);
// initial cleaning
tmp_handler.clean();
if(this.watch) {
// add watcher to each file for cleaning and changing [changing could not be tested atm as every action used from programs is delete then add]
let watcher = new FileWatcher('media-file ' + tmp_handler.name);
watcher.add(tmp_handler.src);
watcher.onError();
watcher.onReady();
watcher.onChangeChange(() => {
tmp_handler.run();
});
watcher.onChangeUnlink(() => {
tmp_handler.clean();
});
}
return tmp_handler;
}
/**
* Returns the set options for a type or an empty object
*
* @param type
*
* @return {*}
*/
getOption(type) {
if(this.option.hasOwnProperty(type)) {
return this.option[type];
}
return {};
}
/**
* Activate a handler through setting his option
*
* @param type
*
* @param option
*/
addHandler(type, option) {
this.option[type] = option;
if('function' === typeof option.handler) {
this.handler_list[type] = option.handler;
return;
}
if('function' === typeof MediaOptimizer.constructor.handler_default[type]) {
// if default handler is registered, execute closure for loading handler
this.handler_list[type] = MediaOptimizer.constructor.handler_default[type]();
return;
}
throw Error('MediaOptimizer: no handler found for type ' + colors.underline(type));
}
} |
JavaScript | class ServiceRegistration extends Base {
constructor(registry, publisher, version, serviceId, service) {
super();
const providerName = Manifest.getPackageName(serviceId);
const specProvider = publisher
.getPluginByNameAndVersion(providerName, version);
this.define('_descriptor', specProvider.getManifest()
.getContributableServiceDescriptor(serviceId));
this.define('_registry', registry);
this.define('_context', publisher);
this.define('_service', service);
this.define('_users', []);
this.define('id', ++serviceUid);
this.define('state', null, {
writable: true
});
this.define('options', {}, {
writable: true
});
}
register(options) {
const registry = this._registry;
const State = ServiceRegistration.State;
//TODO context.checkValid();
this.options = this._createOptions(options);
registry.addServiceRegistration(this);
this.state = State.REGISTERED;
registry.emit('registered', this);
}
unregister() {
const registry = this._registry;
const State = ServiceRegistration.State;
if (this.state !== State.REGISTERED) {
throw new ServiceError(ServiceError.ALREADY_UNREG);
}
this.state = State.UNREGISTERING;
registry.emit('unregistering', this);
registry.removeServiceRegistration(this);
this._releaseUsers();
this.state = State.UNREGISTERED;
registry.emit('unregistered', this);
}
/**
* Adds a new user for this Service.
* @param {PluginContext} user
*/
addUser(user) {
this._users.push(user);
}
/**
* Removes a user from this service's users.
* @param {PluginContext} user
*/
removeUser(user) {
const users = this._users;
const index = users.indexOf(user);
if (index > -1) {
users.splice(index, 1);
}
this.emit('userRemoved', user, this);
}
/**
* Returns the PluginContexts that are using the service
* referenced by this ServiceRegistration.
* @return {Array.<PluginContext>}
*/
getUsers() {
return this._users;
}
/**
* Returns the PluginContext that registered the service
* referenced by this ServiceRegistration.
* @return {PluginContext}
*/
getPublisher() {
return this._context;
}
/**
* Returns the ServiceClosure which wraps the service implementaion.
* @return {ServiceClosure}
*/
getService() {
return this._service;
}
/**
* Returns contributable {@link ServiceDescriptor}
* for this contribution.
* @returns {Object}
*/
getServiceDescriptor() {
return this._descriptor;
}
/**
* Returns contributable spec provider packages's name.
* @returns {string}
*/
getSpecProviderName() {
return this.getServiceDescriptor().provider;
}
/**
* Returns contributable spec provider packages's version.
* @returns {string}
*/
getSpecProviderVersion() {
return this.getServiceDescriptor().version;
}
/**
* Returns contributable service point id.
* @returns {string}
*/
getServiceId() {
return this.getServiceDescriptor().id;
}
/**
* Returns contributable spec based on the package.json.
* @returns {string}
*/
getServiceSpec() {
return this.getServiceDescriptor().spec;
}
toString() {
return '<ServiceRegistration>('
+ this.getPublisher().getPlugin().getId() + "'s "
+ this.getServiceDescriptor().getServicePoint() + ')';
}
_releaseUsers() {
const users = this._users.concat();
while (users.length) {
const user = users.pop();
this.removeUser(user);
}
}
_createOptions(options) {
const props = {};
if (!options) {
options = {};
}
Reflect.ownKeys(options).forEach((key) => {
props[key] = options[key];
});
if (typeof options.priority === 'number') {
if (options.type !== 'super' && options.priority < 0) {
throw new ServiceError(ServiceError.OUTOFBOUND_PRIORITY);
}
this.define('priority', options.priority);
} else {
this.define('priority', 0);
}
return props;
}
} |
JavaScript | class DunningInterval extends Resource {
static getSchema () {
return {
days: Number,
emailTemplate: String
}
}
} |
JavaScript | class Formatter {
/**
* # Heading 1
*
* ## Heading 2
*
* ### Heading 3
*
* #### Heading 4
*
* ##### Heading 5
*
* ###### Heading 6
*
* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam vitae
* elementum urna, id placerat risus. Suspendisse potenti. Sed vel ante ac mi
* efficitur bibendum ut eget mauris.
*
* <small>The fine print</small>
*
* The following text is a [link](#).
*
* The following text should have **strong emphasis**.
*
* The following text should be rendered _with emphasis_.
*
* ---
*
* Here are some lists:
*
* 1. Lorem ipsum dolor sit amet
* 2. Aliquam vitaie elementum urna
* 3. Suspendisse potenti
*
*
* * Lorem ipsum dolor sit amet
* * Aliquam vitaie elementum urna
* * Suspendisse potenti
*
*
* 1. Item 1
* * Lorem ipsum dolor sit amet
* * Aliquam vitaie elementum urna
* * Suspendisse potenti
* 2. Item 2
* * Sed vel ante ac mi efficitur
*
*
* ---
*
* > Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
* > doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
* > veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim
* > ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia
* > consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque
* > porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur,
* > adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et
* > dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis
* > nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid
* > ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
* > voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem
* > eum fugiat quo voluptas nulla pariatur?
* >
* > <small>Cicero, Section 1.10.32, <cite>de Finibus Bonorum et Malorum</cite>,
* > 45 BC.</small>
*
* ---
*
* | Fruit | Color | Quantity |
* | :----- | :----: | -------: |
* | Apple | Red | 1 |
* | Apple | Green | 2 |
* | Banana | Yellow | 3 |
* | Orange || 4 |
* [Table caption]
*
* ---
*
* Lorem ipsum `dolor sit amet`, consectetur adipiscing elit. Aliquam vitae
* elementum urna, id placerat risus. Suspendisse potenti. Sed `vel` `ante` ac mi
* efficitur bibendum ut eget mauris.
*
* // This is an indented code block.
* function sayHello() {
* console.log('Hello, world!');
* }
*
* ```
* // This a fenced code block.
* function sayHello() {
* console.log('Hello, world!');
* }
* ```
*
* ---
*
* <dl>
* <dt>Term 1</dt>
* <dd>Definition 1.a</dd>
* <dd>Definition 1.b</dd>
* <dt>Term 2</dt>
* <dd>Definition 2.a</dd>
* <dd>Definition 2.b</dd>
* </dl>
*
* @param {string} a the string to format.
* @param {string} b another string to format.
* @param {string} c this parameter includes a table in its description. Why?
* Because users could do crazy things like that.
*
* | Fruit | Color | Quantity |
* | :----- | :----: | -------: |
* | Apple | Red | 1 |
* | Apple | Green | 2 |
* | Banana | Yellow | 3 |
* | Orange || 4 |
* [Table caption]
*
*
* @param {...string} d all the other strings to format.
* @return {string} the formatted string.
* @throws {TypeError} if input is invalid.
* @see Formatter
*/
format(a, b, c, d) {
}
/**
* @param {string} s the string to format.
* @return {string} the formatted string.
* @throws {TypeError} if input is invalid.
* @deprecated use {@link #format(s)} instead.
* @see Formatter
*/
oldFormat(s) {
}
} |
JavaScript | class ResourceServer extends ResourceServerBase {
/**
* Removes access and refresh tokens.
* @param {Object} context Module context.
* @returns {Promise} Promise for nothing.
*/
removeAuthorization(context) {
const token = this.getToken(context);
const redirectUri = context.location.clone();
const returnUri = context.location.clone();
returnUri.scheme = null;
returnUri.authority = null;
redirectUri.path = uriHelper.getRemovePath(this._config.endpoint.name);
redirectUri.scheme = null;
redirectUri.authority = null;
redirectUri.fragment = null;
redirectUri.query = redirectUri.createQuery('');
redirectUri.query.values.token = token;
redirectUri.query.values[FIELD_RETURN_URI] = returnUri.toString();
return context.redirect(redirectUri.toString());
}
} |
JavaScript | class DataBrowserDialog extends React.Component {
state = {
sessionFiles: [],
sessions: [],
apiUrl: this.props.apiUrl
}
componentDidMount() {
this.fetchSessions()
}
/**
* Data API Access:
* Fetch all media sessions
*
* Request:
* -> GET <API_URL>/data/media/all
* Expected response:
* -> application/json - PagedSessionList
*/
fetchSessions = () => {
fetch(this.state.apiUrl + '/data/media/all')
.then(result => {
return result.json();
}).then(this.renderSessions)
}
/**
* Render received PagedSessionList
*/
renderSessions = (data) => {
let sessions = data.sessions.map((sessionId) => {
const filesIdAttribute = { ["id"]: 'files-' + sessionId }
const sessionIdAttribute = { ["id"]: 'session-' + sessionId }
return (
<div className="data-session" key={sessionId} {... sessionIdAttribute}>
<h4>Session ID: {sessionId}</h4>
<button type="button" onClick={() => this.fetchFilesFromSession(sessionId)}>Load files</button>
<button type="button" onClick={() => this.uploadFilesToSession(sessionId)}>Upload files</button>
<button type="button" onClick={() => this.deleteSession(sessionId)}>Delete session</button>
<div {... filesIdAttribute}></div>
</div>
)
})
this.setState({sessions: sessions})
console.log("state", this.state.sessions)
}
/**
* Navigate to UploadDialog with sessionId as parameter
*/
uploadFilesToSession = (sessionId) => {
console.log("upload files", sessionId)
this.props.history.push( '/upload?sessionId=' + sessionId )
}
/**
* Data API Access:
* Delete a whole session
*
* Request:
* -> DELETE <API_URL>/data/media/<sessionId>
* Expected response:
* -> statusCode
*/
deleteSession = (sessionId) => {
console.log("delete session", sessionId)
fetch(this.state.apiUrl + '/data/media/' + sessionId, {
method: 'DELETE'
})
.then(result => {
console.log("delete response", result)
if(result.status == 200) {
var sessionNode = document.getElementById('session-' + sessionId)
sessionNode.parentElement.removeChild(sessionNode);
alert('Session with ID ' + sessionId + ' successfully deleted.')
} else {
alert('Session with ID ' + sessionId + ' cannot be deleted.')
}
})
}
/**
* Data API Access:
* Fetch files for a specific session
*
* Request:
* -> GET <API_URL>/data/<sessionId>/files
* Expected response:
* -> application/json - PagedDataFileList
*/
fetchFilesFromSession = (sessionId) => {
console.log("fetch files for sessionId", sessionId)
fetch(this.state.apiUrl + '/data/'+ sessionId + '/files')
.then(result => {
return result.json();
}).then(data => this.renderFilesFromSession(sessionId, data))
}
/**
* Render received PagedDataFileList
*/
renderFilesFromSession = (sessionId, data) => {
console.log("render files for sessionId", sessionId, data)
let files = data.entities.map((entity) => {
const fileIdAttribute = { ["id"]: 'file-' + sessionId + '-' + entity.fileName}
return (
<tr key={entity.fileName} {... fileIdAttribute}>
<td><a href={ this.state.apiUrl + '/data/' + sessionId + '/files/' + entity.fileName } target="_blank">{entity.fileName}</a></td>
<td>{entity.contentType}</td>
<td>{new Date(entity.uploadedAt).toISOString()}</td>
<td>{entity.size}</td>
<td><button type="button" onClick={() => this.deleteFile(sessionId, entity.fileName)}>Delete</button></td>
</tr>
)
})
console.log("files for session " + sessionId, files)
const table = <table id="data-session-files-{sessionId}">
<tbody>
<tr>
<th>File name</th>
<th>Content type</th>
<th>Uploaded at</th>
<th>Size in bytes</th>
<th>Actions</th>
</tr>
{files}
</tbody>
</table>;
ReactDOM.render(table, document.getElementById('files-' + sessionId));
}
/**
* Raw Data Store API Access:
* Delete a file from sessionId
*
* Request:
* -> DELETE <API_URL>/data/<sessionId>/files/<fileName>
* Expected response:
* -> statusCode
*/
deleteFile = (sessionId, fileName) => {
console.log("delete session", sessionId)
fetch(this.state.apiUrl + '/data/' + sessionId + '/files/' + fileName, {
method: 'DELETE'
})
.then(result => {
console.log("delete response", result)
if(result.status == 200) {
var fileNode = document.getElementById('file-' + sessionId + '-' + fileName)
fileNode.parentElement.removeChild(fileNode);
alert('File ' + fileName + ' successfully deleted from session with ID ' + sessionId + '.')
} else {
alert('File ' + fileName + ' from session with ID ' + sessionId + ' could not be deleted.')
}
})
}
/**
* Render MediaDataBrowserDialog
*/
render() {
return(
<div>
<h1>Media Data Browser</h1>
<button type="button" onClick={ this.fetchSessions }> <span>Reload files</span> </button><br/><br/>
<h2>Available sessions</h2>
<div id="session-table">
{this.state.sessions}
</div>
</div>
)
}
} |
JavaScript | class GroupPage extends Component {
state = {
width: window.innerWidth,
}
/**
* This function will run when the window is loaded. It will set an
* eventlistener to check whenever the user resizes the window.
* If so, it will call the handleWindowResize function
*/
componentDidMount() {
window.addEventListener('resize', this.handleWindowResize);
}
/**
* This function will run when the window is exited.
* It will remove the eventlistener added in componentDidMount
*/
componentWillUnmount() {
window.removeEventListener('resize', this.handleWindowResize);
}
/**
* This function edits the state width of the window based on the window
* width of the user.
*/
handleWindowResize = () => {
this.setState({width: window.innerWidth});
}
/**
* This function takes the user to the previous page visited.
*/
goBack = () => {
this.props.history.goBack();
}
/**
* This method changes tha path to view the selected group
* member detail page
*/
viewMembers = () => {
this.props.history.push(`/overview/
${this.props.selectedGroup.groupname}/members`);
}
/**
* This function will delete the current selected group by clicking
* the delete group button. It will the redirect the user.
*/
deleteGroup = () => {
this.props.history.replace('/overview');
axios.delete(`http://${BASEURL}:${PORT}/groups/
${this.props.selectedGroup.groupid}`).catch();
}
/**
* This render function will render differently depending on if a user is
* logged in or not AND whether the width of the window is less than 500
* pixels. If the window width is less than 500, the groupmemberview will
* not be visible on the page, and will then have to be opened as any other
* page by clicking the button that appears in its place.
* @return {HTMLElement} - either the grouppage or NotFound depending
* on login status
*/
render() {
const isMobile = this.state.width <= 500;
return this.props.isLoggedIn ?
<>
<Header name={this.props.currentUser.username}
history={this.props.history}
logout={this.props.unloadStateAfterLogout} />
<div className="main">
<div className="inlineFlex">
<div className="inlineFlex">
<button
className="blueButton"
style={{marginRight: '5px'}}
onClick={this.goBack}
>
<Icon name="back" />
</button>
<h3>{this.props.selectedGroup.groupname}</h3>
<button
className="redButton"
onClick={() => {
this.deleteGroup();
}}
>
Slett gruppe
<Icon name="delete" />
</button>
</div>
{isMobile &&
<button className="blueButton"
onClick={this.viewMembers}>
<Icon name="group" />
</button>
}
</div>
<div className="inlineDiv">
<div style={{flexGrow: '3'}}>
<p>Våre handlelister:</p>
<ShoppingListView
selectedGroup={this.props.selectedGroup}
listClickHandler={this.props.listClickHandler}
history={this.props.history} />
</div>
{!isMobile &&
<div style={{flexGrow: 1}} className="sidebar">
<GroupMemberView
members={this.props.members}
addMemberByEmail={this.props.addMemberByEmail}
currentUser={this.props.currentUser}
removeUserById={this.props.removeUserById}
checkIfGroupAdmin={this.props.checkIfGroupAdmin}
getGroupMembers={this.props.getGroupMembers}
/>
</div>
}
</div>
</div>
</> :
<NotFound />;
}
} |
JavaScript | class MultiPoint extends Point {
constructor(pointArray) {
super()
this.points = []
if (pointArray) {
forEach(pointArray, (point) => {
this.addPoint(point)
})
}
this.renderData = []
this.id = 'multi'
this.toPoint = this.fromPoint = null
this.patternStylerKey = 'multipoints_pattern'
}
/**
* Get id
*/
getId() {
return this.id
}
/**
* Get type
*/
getType() {
return 'MULTI'
}
getName() {
if (this.fromPoint) return this.fromPoint.getName()
if (this.toPoint) return this.toPoint.getName()
let shortest = null
forEach(this.points, (point) => {
if (point.getType() === 'TURN') return
if (!shortest || point.getName().length < shortest.length) {
shortest = point.getName()
}
})
return shortest
}
containsSegmentEndPoint() {
for (let i = 0; i < this.points.length; i++) {
if (this.points[i].containsSegmentEndPoint()) return true
}
return false
}
containsBoardPoint() {
for (let i = 0; i < this.points.length; i++) {
if (this.points[i].containsBoardPoint()) return true
}
return false
}
containsAlightPoint() {
for (let i = 0; i < this.points.length; i++) {
if (this.points[i].containsAlightPoint()) return true
}
return false
}
containsTransferPoint() {
for (let i = 0; i < this.points.length; i++) {
if (this.points[i].containsTransferPoint()) return true
}
return false
}
containsFromPoint() {
return this.fromPoint !== null
}
containsToPoint() {
return this.toPoint !== null
}
getPatterns() {
const patterns = []
forEach(this.points, (point) => {
if (!point.patterns) return
forEach(point.patterns, (pattern) => {
if (patterns.indexOf(pattern) === -1) patterns.push(pattern)
})
})
return patterns
}
addPoint(point) {
if (this.points.indexOf(point) !== -1) return
this.points.push(point)
this.id += '-' + point.getId()
if (point.containsFromPoint()) {
// getType() === 'PLACE' && point.getId() === 'from') {
this.fromPoint = point
}
if (point.containsToPoint()) {
// getType() === 'PLACE' && point.getId() === 'to') {
this.toPoint = point
}
this.calcWorldCoords()
}
calcWorldCoords() {
let tx = 0
let ty = 0
forEach(this.points, (point) => {
tx += point.worldX
ty += point.worldY
})
this.worldX = tx / this.points.length
this.worldY = ty / this.points.length
}
/**
* Add render data
*
* @param {Object} stopInfo
*/
addRenderData(pointInfo) {
if (pointInfo.offsetX !== 0 || pointInfo.offsetY !== 0) {
this.hasOffsetPoints = true
}
this.renderData.push(pointInfo)
}
clearRenderData() {
this.hasOffsetPoints = false
this.renderData = []
}
/**
* Draw a multipoint
*
* @param {Display} display
*/
render(display) {
super.render(display)
if (!this.renderData) return
// Compute the bounds of the merged marker
const xArr = this.renderData.map((d) => d.x)
const yArr = this.renderData.map((d) => d.y)
const xMin = Math.min(...xArr)
const xMax = Math.max(...xArr)
const yMin = Math.min(...yArr)
const yMax = Math.max(...yArr)
const r = 6
const x = xMin - r
const y = yMin - r
const width = xMax - xMin + r * 2
const height = yMax - yMin + r * 2
// Draw the merged marker
display.drawRect(
{ x, y },
{
fill: '#fff',
height,
rx: r,
ry: r,
stroke: '#000',
'stroke-width': 2,
width
}
)
// Store marker bounding box
this.markerBBox = { height, width, x, y }
// TODO: support pattern-specific markers
}
initMergedMarker(display) {
// set up the merged marker
if (this.fromPoint || this.toPoint) {
this.mergedMarker = this.markerSvg
.append('g')
.append('circle')
.datum({
owner: this
})
.attr('class', 'transitive-multipoint-marker-merged')
} else if (this.hasOffsetPoints || this.renderData.length > 1) {
this.mergedMarker = this.markerSvg
.append('g')
.append('rect')
.datum({
owner: this
})
.attr('class', 'transitive-multipoint-marker-merged')
}
}
getRenderDataArray() {
return this.renderData
}
setFocused(focused) {
this.focused = focused
forEach(this.points, (point) => {
point.setFocused(focused)
})
}
runFocusTransition(display, callback) {
if (this.mergedMarker) {
const newStrokeColor = display.styler.compute(
display.styler.multipoints_merged.stroke,
display,
{
owner: this
}
)
this.mergedMarker
.transition()
.style('stroke', newStrokeColor)
.call(callback)
}
if (this.label) this.label.runFocusTransition(display, callback)
}
} |
JavaScript | class Star {
constructor(ctx, x, y, layer, width) {
this.ctx = ctx;
this.x = x;
this.originalX = x;
this.y = y;
this.originalY = y;
this.layer = layer;
this.speed = 3 - layer;
this.width = width;
}
draw() {
this.ctx.beginPath();
this.ctx.arc(
this.x,
this.y,
0.8 - (this.layer / 8) * 2,
0,
2 * Math.PI
);
this.ctx.fillStyle = 'white';
this.ctx.fill();
this.ctx.closePath();
this.ctx.fillStyle = 'black';
}
update() {
this.x += this.speed;
if (this.x > this.width) {
this.x = 0;
// Little position change after respawn
this.x = 0 + getRandom(-8, 8);
this.y = this.originalY + getRandom(-8, 8);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.