language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Uint32 extends BufferMethodIntType { constructor(){ super('writeUInt32LE', 'readUInt32LE', 4); } }
JavaScript
class ObjectHelper { // csvFormat options get csvFormats() { return ([ 'Default', 'Excel', 'MySQL', 'RFC4180', 'TDF', ]); } constructor(opts = {}) { const { axios, api } = opts; this.axios = axios; this.api = api; } // index index() { return this.axios.get(`${this.api}/`); } // Create object create(opts = {}) { const { db, collection, id, payload } = opts; // Create object with id if (id) { return this.axios.post(`${this.api}/${db}/${collection}/${id}`, payload); } return this.axios.post(`${this.api}/${db}/${collection}`, payload); } // Get object get(opts = {}) { const { db, collection, id } = opts; return this.axios.get(`${this.api}/${db}/${collection}/${id}`); } // Update object update(opts = {}) { const { db, collection, id, payload } = opts; return this.axios.put(`${this.api}/${db}/${collection}/${id}`, payload); } // Delete object delete(opts = {}) { const { db, collection, id } = opts; return this.axios.delete(`${this.api}/${db}/${collection}/${id}`); } // Delete collection deleteCollection(opts = {}) { const { db, collection } = opts; return this.axios.delete(`${this.api}/${db}/${collection}`); } // Aggregate aggregate(opts = {}) { const { db, collection, payload = {} } = opts; return this.axios.post(`${this.api}/${db}/${collection}/aggregate`, payload); } // Count object(s) count(opts = {}) { const { db, collection, payload = {} } = opts; return this.axios.post(`${this.api}/${db}/${collection}/count`, payload); } // Get distinct values distinct(opts = {}) { const { db, collection, field, payload = {} } = opts; return this.axios.post(`${this.api}/${db}/${collection}/distinct/${field}`, payload); } // Find object(s) find(opts = {}) { const { db, collection, payload = {}, from = 0, size = -1, sort = '', order = 1, } = opts; const qs = querystring.stringify({ from, size, sort, order, }); return this.axios.post(`${this.api}/${db}/${collection}/find?${qs}`, payload); } // Bulk import of objects from a CSV file importCSV(opts = {}) { const { db, collection, csv, csvFormat = 'Default' } = opts; const qs = querystring.stringify({ csvFormat }); return this.axios.post(`${this.api}/bulk/${db}/${collection}?${qs}`, csv, { headers: { 'Content-Type': 'multipart/form-data' }, }); } // Create a list of objects importList(opts = {}) { const { db, collection, payload = [] } = opts; return this.axios.post(`${this.api}/multi/${db}/${collection}`, payload); } }
JavaScript
class RosterSocket { constructor(roster, service) { this.addresses = roster.identities.map(conode => tlsToWebsocket(conode.tcpAddr, "")); this.service = service; this.lastGoodServer = null; } /** * send tries to send the request to a random server in the list as long as there is no successful response. It tries a permutation of all server's addresses. * * @param {string} request name of the protobuf packet * @param {string} response name of the protobuf packet response * @param {Object} data javascript object representing the request * @returns {Promise} holds the returned data in case of success. */ send(request, response, data) { const that = this; const fn = co.wrap(function* () { const service = that.service; // Create a copy of the array else it gets longer after every call to send. let addresses = []; that.addresses.forEach(addr => { addresses.push(addr); }) shuffle(addresses); // try first the last good server we know if (that.lastGoodServer) { delete addresses[addresses.findIndex(addr => { return addr == that.lastGoodServer; })]; addresses.unshift(that.lastGoodServer); } for (let i = 0; i < addresses.length; i++) { const addr = addresses[i]; if (addr == undefined) { continue; } try { const socket = new Socket(addr, service); Log.lvl2("RosterSocket: trying out index " + i + " at address " + addr + "/" + service); const socketResponse = yield socket.send(request, response, data); that.lastGoodServer = addr; return socketResponse; } catch (err) { Log.rcatch(err, "rostersocket"); } } throw new Error("no conodes are available or all conodes returned an error"); }); return fn(); } }
JavaScript
class LeaderSocket { constructor(roster, service) { this.service = service; this.roster = roster; if (this.roster.identities.length === 0) { throw new Error("Roster should have atleast one node"); } } /** * Send transmits data to a given url and parses the response. * @param {string} request name of registered protobuf message * @param {string} response name of registered protobuf message * @param {object} data to be sent * * @returns {Promise} with response message on success and error on failure. */ send(request, response, data) { // fn is a generator that tries the sending the request to the leader // maximum 3 times and returns on the first successful attempt const that = this; const fn = co.wrap(function* () { var lastErr for (let i = 0; i < 3; i++) { try { const socket = new Socket( that.roster.identities[0].websocketAddr, that.service ); const reply = yield socket.send(request, response, data); return Promise.resolve(reply); } catch (err) { Log.catch(err, "error sending request: "); lastErr = err } } throw new Error("couldn't send request after 3 attempts: " + lastErr.message); }); return fn(); } }
JavaScript
class TableUtils { static dataType = { BOOLEAN: 'boolean', CHAR: 'char', DATETIME: 'datetime', DECIMAL: 'decimal', INT: 'int', STRING: 'string', }; static sortDirection = { ascending: 'ASC', descending: 'DESC', reverse: 'REVERSE', none: null, }; static REVERSE_TYPE = Object.freeze({ NONE: 'none', PRE_SORT: 'pre-sort', POST_SORT: 'post-sort', }); // Regex looking for a negative or positive integer or decimal number static NUMBER_REGEX = /^-?\d+(\.\d+)?$/; static getSortIndex(sort, columnIndex) { for (let i = 0; i < sort.length; i += 1) { const s = sort[i]; if (s.column?.index === columnIndex) { return i; } } return null; } /** * Retrieves a column from the provided table at the index, or `null` and logs an error if it's invalid * * @param {dh.Table} table The table to get the column for * @param {Number} columnIndex The column index to get */ static getColumn(table, columnIndex) { if (columnIndex < table.columns.length) { return table.columns[columnIndex]; } log.error( 'Unable to retrieve column', columnIndex, '>=', table.columns.length ); return null; } /** * Retrieves a column from the provided table matching the name, or `null` and log an error if not found * @param {dh.Table} table The table to get the column for * @param {String} columnName The column name to retrieve */ static getColumnByName(table, columnName) { const column = table.columns.find( tableColumn => tableColumn.name === columnName ); if (column == null) { log.error( 'Unable to retrieve column by name', columnName, table.columns.map(tableColumn => tableColumn.name) ); } return column; } /** * @param {dh.Sort[]} tableSort The sorts from the table to get the sort from * @param {number} columnIndex The index of the column to get the sort for * @return {dh.Sort} The sort for the column, or null if it's not sorted */ static getSortForColumn(tableSort, columnIndex) { const sortIndex = TableUtils.getSortIndex(tableSort, columnIndex); if (sortIndex != null) { return tableSort[sortIndex]; } return null; } static getFilterText(filter) { if (filter) { return filter.toString(); } return null; } /** Return the valid filter types for the column */ static getFilterTypes(columnType) { if (TableUtils.isBooleanType(columnType)) { return [FilterType.isTrue, FilterType.isFalse, FilterType.isNull]; } if ( TableUtils.isNumberType(columnType) || TableUtils.isDateType(columnType) ) { return [ FilterType.eq, FilterType.notEq, FilterType.greaterThan, FilterType.greaterThanOrEqualTo, FilterType.lessThan, FilterType.lessThanOrEqualTo, ]; } if (TableUtils.isTextType(columnType)) { return [ FilterType.eq, FilterType.eqIgnoreCase, FilterType.notEq, FilterType.notEqIgnoreCase, FilterType.contains, FilterType.notContains, FilterType.startsWith, FilterType.endsWith, ]; } return []; } static getNextSort(table, columnIndex) { if ( !table || !table.columns || columnIndex < 0 || columnIndex >= table.columns.length ) { return null; } const sort = TableUtils.getSortForColumn(table.sort, columnIndex); if (sort === null) { return table.columns[columnIndex].sort().asc(); } if (sort.direction === TableUtils.sortDirection.ascending) { return sort.desc(); } return null; } static makeColumnSort(table, columnIndex, direction, isAbs) { if ( !table || !table.columns || columnIndex < 0 || columnIndex >= table.columns.length ) { return null; } if (direction === TableUtils.sortDirection.none) { return null; } let sort = table.columns[columnIndex].sort(); switch (direction) { case TableUtils.sortDirection.ascending: sort = sort.asc(); break; case TableUtils.sortDirection.descending: sort = sort.desc(); break; default: break; } if (isAbs) { sort = sort.abs(); } return sort; } /** * Toggles the sort for the specified column * @param {array} sorts The current sorts from IrisGrid.state * @param {dh.Table} table The table to apply the sort to * @param {number} columnIndex The column index to apply the sort to * @param {boolean} addToExisting Add this sort to the existing sort */ static toggleSortForColumn(sorts, table, columnIndex, addToExisting = false) { if (!table || columnIndex < 0 || columnIndex >= table.columns.length) { return []; } const newSort = TableUtils.getNextSort(table, columnIndex); return TableUtils.setSortForColumn( sorts, columnIndex, newSort, addToExisting ); } static sortColumn(table, modelColumn, direction, isAbs, addToExisting) { if (!table || modelColumn < 0 || modelColumn >= table.columns.length) { return []; } const newSort = TableUtils.makeColumnSort( table, modelColumn, direction, isAbs ); return TableUtils.setSortForColumn( table.sort, modelColumn, newSort, addToExisting ); } /** * Sets the sort for the given column *and* removes any reverses * @param {dh.Sort[]} tableSort The current sorts from IrisGrid.state * @param {number} columnIndex The column index to apply the sort to * @param {dh.Sort} sort The sort object to add * @param {boolean} addToExisting Add this sort to the existing sort * @returns {array} Returns the modified array of sorts - removing reverses */ static setSortForColumn(tableSort, columnIndex, sort, addToExisting = false) { const sortIndex = TableUtils.getSortIndex(tableSort, columnIndex); let sorts = []; if (addToExisting) { sorts = sorts.concat( tableSort.filter( ({ direction }) => direction !== TableUtils.sortDirection.reverse ) ); if (sortIndex !== null) { sorts.splice(sortIndex, 1); } } if (sort !== null) { sorts.push(sort); } return sorts; } static getNormalizedType(columnType) { switch (columnType) { case 'boolean': case 'java.lang.Boolean': case TableUtils.dataType.BOOLEAN: return TableUtils.dataType.BOOLEAN; case 'char': case 'java.lang.Character': case TableUtils.dataType.CHAR: return TableUtils.dataType.CHAR; case 'java.lang.String': case TableUtils.dataType.STRING: return TableUtils.dataType.STRING; case 'io.deephaven.db.tables.utils.DBDateTime': case 'com.illumon.iris.db.tables.utils.DBDateTime': case TableUtils.dataType.DATETIME: return TableUtils.dataType.DATETIME; case 'double': case 'java.lang.Double': case 'float': case 'java.lang.Float': case TableUtils.dataType.DECIMAL: return TableUtils.dataType.DECIMAL; case 'int': case 'java.lang.Integer': case 'long': case 'java.lang.Long': case 'short': case 'java.lang.Short': case 'byte': case 'java.lang.Byte': case TableUtils.dataType.INT: return TableUtils.dataType.INT; default: return null; } } static isLongType(columnType) { switch (columnType) { case 'long': case 'java.lang.Long': return true; default: return false; } } static isDateType(columnType) { switch (columnType) { case 'io.deephaven.db.tables.utils.DBDateTime': case 'com.illumon.iris.db.tables.utils.DBDateTime': return true; default: return false; } } static isNumberType(columnType) { return ( TableUtils.isIntegerType(columnType) || TableUtils.isDecimalType(columnType) ); } static isIntegerType(columnType) { switch (columnType) { case 'int': case 'java.lang.Integer': case 'java.math.BigInteger': case 'long': case 'java.lang.Long': case 'short': case 'java.lang.Short': case 'byte': case 'java.lang.Byte': return true; default: return false; } } static isDecimalType(columnType) { switch (columnType) { case 'double': case 'java.lang.Double': case 'java.math.BigDecimal': case 'float': case 'java.lang.Float': return true; default: return false; } } static isBooleanType(columnType) { switch (columnType) { case 'boolean': case 'java.lang.Boolean': return true; default: return false; } } static isTextType(columnType) { switch (columnType) { case 'char': case 'java.lang.Character': case 'java.lang.String': return true; default: return false; } } /** * Get base column type * @param {string} columnType Column type * @returns {string} Element type for array columns, original type for non-array columns */ static getBaseType(columnType) { return columnType.split('[]')[0]; } /** * Check if the column types are compatible * @param {string} type1 Column type to check * @param {string} type2 Column type to check * @returns {boolean} True, if types are compatible */ static isCompatibleType(type1, type2) { return ( TableUtils.getNormalizedType(type1) === TableUtils.getNormalizedType(type2) ); } /** * Create filter with the provided column and text. Handles multiple filters joined with && or || * @param {dh.Column} column The column to set the filter on * @param {String} text The text string to create the filter from * @returns {dh.FilterCondition} Returns the created filter, null if text could not be parsed */ static makeQuickFilter(column, text) { const orComponents = text.split('||'); let orFilter = null; for (let i = 0; i < orComponents.length; i += 1) { const orComponent = orComponents[i]; const andComponents = orComponent.split('&&'); let andFilter = null; for (let j = 0; j < andComponents.length; j += 1) { const andComponent = andComponents[j].trim(); if (andComponent.length > 0) { const filter = TableUtils.makeQuickFilterFromComponent( column, andComponent ); if (filter) { if (andFilter) { andFilter = andFilter.and(filter); } else { andFilter = filter; } } else { throw new Error(`Unable to parse quick filter from text ${text}`); } } } if (orFilter) { orFilter = orFilter.or(andFilter); } else { orFilter = andFilter; } } return orFilter; } /** * Create filter with the provided column and text of one component (no multiple conditions) * @param {dh.Column} column The column to set the filter on * @param {String} text The text string to create the filter from * @returns {dh.FilterCondition} Returns the created filter, null if text could not be parsed */ static makeQuickFilterFromComponent(column, text) { const { type } = column; if (TableUtils.isNumberType(type)) { return this.makeQuickNumberFilter(column, text); } if (TableUtils.isBooleanType(type)) { return this.makeQuickBooleanFilter(column, text); } if (TableUtils.isDateType(type)) { return this.makeQuickDateFilter(column, text); } return this.makeQuickTextFilter(column, text); } static makeQuickNumberFilter(column, text) { if (text == null) { return null; } const columnFilter = column.filter(); let filter = null; const regex = /\s*(>=|<=|=>|=<|>|<|!=|=|!)?(\s*-\s*)?(\s*\d*(?:,\d{3})*(?:\.\d*)?\s*)?(null|nan|infinity|inf|\u221E)?(.*)/i; const result = regex.exec(text); let operation = null; let negativeSign = null; let value = null; let abnormalValue = null; // includes nan, null and infinity(positive & negative) let overflow = null; if (result.length > 3) { [, operation, negativeSign, value, abnormalValue, overflow] = result; } if (overflow != null && overflow.trim().length > 0) { // Some bad characters after the number, bail out! return null; } if (operation == null) { operation = '='; } if (value == null && abnormalValue == null) { return null; } if (abnormalValue != null) { if (!(operation === '=' || operation === '!' || operation === '!=')) { // only equal and not equal operations are supported for abnormal value filter return null; } abnormalValue = abnormalValue.trim().toLowerCase(); switch (abnormalValue) { case 'null': filter = columnFilter.isNull(); break; case 'nan': filter = dh.FilterCondition.invoke('isNaN', columnFilter); break; case 'infinity': case 'inf': case '\u221E': if (negativeSign != null) { filter = dh.FilterCondition.invoke('isInf', columnFilter).and( columnFilter.lessThan(dh.FilterValue.ofNumber(0)) ); } else { filter = dh.FilterCondition.invoke('isInf', columnFilter).and( columnFilter.greaterThan(dh.FilterValue.ofNumber(0)) ); } break; default: break; } if (operation === '!' || operation === '!=') { filter = filter.not(); } return filter; } value = TableUtils.removeCommas(value); if (TableUtils.isLongType(column.type)) { try { value = dh.FilterValue.ofNumber( dh.LongWrapper.ofString(`${negativeSign != null ? '-' : ''}${value}`) ); } catch (error) { log.warn('Unable to create long filter', error); return null; } } else { value = parseFloat(value); if (value == null || Number.isNaN(value)) { return null; } value = dh.FilterValue.ofNumber(negativeSign != null ? 0 - value : value); } filter = column.filter(); switch (operation) { case '=': return filter.eq(value); case '<': return filter.lessThan(value); case '<=': case '=<': return filter.lessThanOrEqualTo(value); case '>': return filter.greaterThan(value); case '>=': case '=>': return filter.greaterThanOrEqualTo(value); case '!=': case '!': return filter.notEq(value); default: return null; } } static makeQuickTextFilter(column, text) { if (text == null) { return null; } const cleanText = `${text}`.trim(); const regex = /^(!~|!=|~|=|!)?(.*)/; const result = regex.exec(cleanText); let operation = null; let value = null; if (result.length > 2) { [, operation, value] = result; if (value != null) { value = value.trim(); } } if (value == null || value.length === 0) { return null; } if (operation == null) { operation = '='; } const filter = column.filter(); if (value.toLowerCase() === 'null') { // Null is a special case! switch (operation) { case '=': return filter.isNull(); case '!=': case '!': return filter.isNull().not(); default: return null; } } let prefix = null; let suffix = null; if (value.startsWith('*')) { prefix = '*'; value = value.substring(1); } else if (value.endsWith('*') && !value.endsWith('\\*')) { suffix = '*'; value = value.substring(0, value.length - 1); } value = value.replace('\\', ''); switch (operation) { case '~': { return filter .isNull() .not() .and( filter.invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i).*\\Q${value}\\E.*`) ) ); } case '!~': return filter .isNull() .or( filter .invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i).*\\Q${value}\\E.*`) ) .not() ); case '!=': if (prefix === '*') { // Does not end with return filter .isNull() .or( filter .invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i).*\\Q${value}\\E$`) ) .not() ); } if (suffix === '*') { // Does not start with return filter .isNull() .or( filter .invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i)^\\Q${value}\\E.*`) ) .not() ); } return filter.notEqIgnoreCase( dh.FilterValue.ofString(value.toLowerCase()) ); case '=': if (prefix === '*') { // Ends with return filter .isNull() .not() .and( filter.invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i).*\\Q${value}\\E$`) ) ); } if (suffix === '*') { // Starts with return filter .isNull() .not() .and( filter.invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i)^\\Q${value}\\E.*`) ) ); } return filter.eqIgnoreCase( dh.FilterValue.ofString(value.toLowerCase()) ); default: break; } return null; } static makeQuickBooleanFilter(column, text) { if (text == null) { return null; } const regex = /^(!=|=|!)?(.*)/; const result = regex.exec(`${text}`.trim()); const [, operation, value] = result; const notEqual = operation === '!' || operation === '!='; const cleanValue = value.trim().toLowerCase(); let filter = column.filter(); try { const boolValue = TableUtils.makeBooleanValue(cleanValue); if (boolValue) { filter = filter.isTrue(); } else if (boolValue === null) { filter = filter.isNull(); } else { filter = filter.isFalse(); } return notEqual ? filter.not() : filter; } catch (e) { return null; } } /** * Builds a date filter parsed from the text string which may or may not include an operator. * @param {Column} column The column to build the filter from, with or without a leading operator. * @param {string} text The date string text to parse. */ static makeQuickDateFilter(column, text) { const cleanText = text.trim(); const regex = /\s*(>=|<=|=>|=<|>|<|!=|!|=)?(.*)/; const result = regex.exec(cleanText); if (result == null || result.length <= 2) { throw new Error(`Unable to parse date filter: ${text}`); } let operation = null; let dateText = null; [, operation, dateText] = result; let filterOperation = FilterType.eq; switch (operation) { case '<': filterOperation = FilterType.lessThan; break; case '<=': case '=<': filterOperation = FilterType.lessThanOrEqualTo; break; case '>': filterOperation = FilterType.greaterThan; break; case '>=': case '=>': filterOperation = FilterType.greaterThanOrEqualTo; break; case '!=': case '!': filterOperation = FilterType.notEq; break; case '=': case '==': default: filterOperation = FilterType.eq; break; } return TableUtils.makeQuickDateFilterWithOperation( column, dateText, filterOperation ); } /** * Builds a date filter parsed from the text string with the provided filter. * @param {Column} column The column to build the filter from. * @param {string} text The date string text to parse, without an operator. * @param {FilterType} operation The filter operation to use. */ static makeQuickDateFilterWithOperation( column, text, operation = FilterType.eq ) { if (column == null) { throw new Error('Column is null'); } const [startDate, endDate] = DateUtils.parseDateRange(text); const startValue = startDate != null ? dh.FilterValue.ofNumber(startDate) : null; const endValue = endDate != null ? dh.FilterValue.ofNumber(endDate) : null; const filter = column.filter(); if (startValue == null && endValue == null) { return operation === FilterType.notEq ? filter.isNull().not() : filter.isNull(); } switch (operation) { case FilterType.eq: { if (endValue != null) { const startFilter = filter.greaterThanOrEqualTo(startValue); const endFilter = filter.lessThan(endValue); return startFilter.and(endFilter); } return filter.eq(startValue); } case FilterType.lessThan: { return filter.lessThan(startValue); } case FilterType.lessThanOrEqualTo: { if (endValue != null) { return filter.lessThan(endValue); } return filter.lessThanOrEqualTo(startValue); } case FilterType.greaterThan: { if (endValue != null) { return filter.greaterThanOrEqualTo(endValue); } return filter.greaterThan(startValue); } case FilterType.greaterThanOrEqualTo: return filter.greaterThanOrEqualTo(startValue); case FilterType.notEq: { if (endValue != null) { const startFilter = filter.lessThan(startValue); const endFilter = filter.greaterThanOrEqualTo(endValue); return startFilter.or(endFilter); } return filter.notEq(startValue); } default: throw new Error(`Invalid operator: ${operation}`); } } /** * Wraps a table promise in a cancelable promise that will close the table if the promise is cancelled. * Use in a component that loads a table, and call cancel when unmounting. * @param {Promise<dh.Table> | dh.Table} table The table promise to wrap */ static makeCancelableTablePromise(table) { return PromiseUtils.makeCancelable(table, resolved => { resolved.close(); }); } /** * Make a cancelable promise for a one-shot table event with a timeout. * @param {dh.Table|dh.TreeTable} table Table to listen for events on * @param {string} eventName Event to listen for * @param {number} timeout Event timeout in milliseconds, defaults to 0 * @param {function} matcher Optional function to determine if the promise can be resolved or stays pending * @returns {Promise} Resolves with the event data */ static makeCancelableTableEventPromise( table, eventName, timeout = 0, matcher = null ) { let eventCleanup = null; let timeoutId = null; let isPending = true; const wrappedPromise = new Promise((resolve, reject) => { timeoutId = setTimeout(() => { eventCleanup(); isPending = false; reject(new TimeoutError(`Event "${eventName}" timed out.`)); }, timeout); eventCleanup = table.addEventListener(eventName, event => { if (matcher != null && !matcher(event)) { log.debug2('Event triggered, but matcher returned false.'); return; } log.debug2('Event triggered, resolving.'); eventCleanup(); clearTimeout(timeoutId); isPending = false; resolve(event); }); }); wrappedPromise.cancel = () => { if (isPending) { log.debug2('Pending promise cleanup.'); eventCleanup(); clearTimeout(timeoutId); isPending = false; return; } log.debug2('Ignoring non-pending promise cancel.'); }; return wrappedPromise; } static makeAdvancedFilter(column, options) { const { filterItems, filterOperators, invertSelection, selectedValues, } = options; let filter = null; for (let i = 0; i < filterItems.length; i += 1) { const filterItem = filterItems[i]; const { selectedType, value } = filterItem; if ( selectedType != null && selectedType.length > 0 && value != null && value.length > 0 ) { try { const newFilter = TableUtils.makeAdvancedValueFilter( column, selectedType, value ); if (newFilter != null) { if (i === 0) { filter = newFilter; } else if (filter !== null && i - 1 < filterOperators.length) { const filterOperator = filterOperators[i - 1]; if (filterOperator === FilterOperator.and) { filter = filter.and(newFilter); } else if (filterOperator === FilterOperator.or) { filter = filter.or(newFilter); } else { log.error( 'Unexpected filter operator', filterOperator, newFilter ); filter = null; break; } } } else { log.debug2('Empty filter ignored for', selectedType, value); } } catch (err) { log.error('Unable to create filter', err); filter = null; break; } } } const selectValueFilter = TableUtils.makeSelectValueFilter( column, selectedValues, invertSelection ); if (selectValueFilter != null) { if (filter != null) { filter = filter.and(selectValueFilter); } else { filter = selectValueFilter; } } return filter; } static removeCommas(value) { return value.replace(/[\s|,]/g, ''); } /** * @param {String} columnType The column type to make the filter value from. * @param {String} value The value to make the filter value from. * @returns {dh.FilterValue} The FilterValue item for this column/value combination */ static makeFilterValue(columnType, value) { const type = TableUtils.getBaseType(columnType); if (TableUtils.isTextType(type)) { return dh.FilterValue.ofString(value); } if (TableUtils.isLongType(type)) { return dh.FilterValue.ofNumber( dh.LongWrapper.ofString(TableUtils.removeCommas(value)) ); } return dh.FilterValue.ofNumber(TableUtils.removeCommas(value)); } /** * Takes a value and converts it to an `dh.FilterValue` * * @param {String} columnType The column type to make the filter value from. * @param {unknown} value The value to actually set * @returns {dh.FilterValue} The FilterValue item for this column/value combination */ static makeFilterRawValue(columnType, rawValue) { if (TableUtils.isTextType(columnType)) { return dh.FilterValue.ofString(rawValue); } if (TableUtils.isBooleanType(columnType)) { return dh.FilterValue.ofBoolean(rawValue); } return dh.FilterValue.ofNumber(rawValue); } /** * Converts a string value to a value appropriate for the column * @param {string} columnType The column type to make the value for * @param {string} text The string value to make a type for */ static makeValue(columnType, text) { if (text == null || text === 'null') { return null; } if (TableUtils.isTextType(columnType)) { return text; } if (TableUtils.isLongType(columnType)) { return dh.LongWrapper.ofString(TableUtils.removeCommas(text)); } if (TableUtils.isBooleanType(columnType)) { return TableUtils.makeBooleanValue(text, true); } if (TableUtils.isDateType(columnType)) { const [date] = DateUtils.parseDateRange(text); return date; } if (TableUtils.isNumberType(columnType)) { return TableUtils.makeNumberValue(text); } log.error('Unexpected column type', columnType); return null; } static makeBooleanValue(text, allowEmpty = false) { if (text === '' && allowEmpty) { return null; } switch (text?.toLowerCase()) { case 'null': return null; case '0': case 'f': case 'fa': case 'fal': case 'fals': case 'false': case 'n': case 'no': return false; case '1': case 't': case 'tr': case 'tru': case 'true': case 'y': case 'ye': case 'yes': return true; default: throw new Error(`Invalid boolean '${text}'`); } } static makeNumberValue(text) { if (text == null || text === 'null' || text === '') { return null; } const cleanText = text.toLowerCase().trim(); if (cleanText === '∞' || cleanText === 'infinity' || cleanText === 'inf') { return Number.POSITIVE_INFINITY; } if ( cleanText === '-∞' || cleanText === '-infinity' || cleanText === '-inf' ) { return Number.NEGATIVE_INFINITY; } const numberText = TableUtils.removeCommas(cleanText); if (TableUtils.NUMBER_REGEX.test(numberText)) { return parseFloat(numberText); } throw new Error(`Invalid number '${text}'`); } static makeAdvancedValueFilter(column, operation, value) { if (TableUtils.isDateType(column.type)) { return TableUtils.makeQuickDateFilterWithOperation( column, value, operation ); } const filterValue = TableUtils.makeFilterValue(column.type, value); const filter = column.filter(); switch (operation) { case FilterType.eq: return filter.eq(filterValue); case FilterType.eqIgnoreCase: return filter.eqIgnoreCase(filterValue); case FilterType.notEq: return filter.notEq(filterValue); case FilterType.notEqIgnoreCase: return filter.notEqIgnoreCase(filterValue); case FilterType.greaterThan: return filter.greaterThan(filterValue); case FilterType.greaterThanOrEqualTo: return filter.greaterThanOrEqualTo(filterValue); case FilterType.lessThan: return filter.lessThan(filterValue); case FilterType.lessThanOrEqualTo: return filter.lessThanOrEqualTo(filterValue); case FilterType.isTrue: return filter.isTrue(); case FilterType.isFalse: return filter.isFalse(); case FilterType.isNull: return filter.isNull(); case FilterType.contains: return filter .isNull() .not() .and( filter.invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i).*\\Q${value}\\E.*`) ) ); case FilterType.notContains: return filter .isNull() .or( filter .invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i).*\\Q${value}\\E.*`) ) .not() ); case FilterType.startsWith: return filter .isNull() .not() .and( filter.invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i)^\\Q${value}\\E.*`) ) ); case FilterType.endsWith: return filter .isNull() .not() .and( filter.invoke( 'matches', dh.FilterValue.ofString(`(?s)(?i).*\\Q${value}\\E$`) ) ); case FilterType.in: case FilterType.inIgnoreCase: case FilterType.notIn: case FilterType.notInIgnoreCase: case FilterType.invoke: default: throw new Error(`Unexpected filter operation: ${operation}`); } } /** * Create a filter using the selected items * Has a flag for invertSelection as we start from a "Select All" state and a user just deselects items. * Since there may be millions of distinct items, it's easier to build an inverse filter. * @param {String[]} selectedValues The values that are selected * @param {boolean} invertSelection Invert the selection (eg. All items are selected, then you deselect items) * @returns dh.FilterCondition Returns a `in` or `notIn` FilterCondition as necessary, or null if no filtering should be applied (everything selected) */ static makeSelectValueFilter(column, selectedValues, invertSelection) { if (selectedValues.length === 0) { if (invertSelection) { // No filter means select everything return null; } // KLUDGE: Return a conflicting filter to show no results. // Could recognize this situation at a higher or lower level and pause updates on the // table, but this situation should be rare and that wouldn't be much gains for some added complexity let value = null; if (TableUtils.isTextType(column.type)) { value = dh.FilterValue.ofString(''); } else if (TableUtils.isBooleanType(column.type)) { value = dh.FilterValue.ofBoolean(true); } else if (TableUtils.isDateType(column.type)) { value = dh.FilterValue.ofNumber(dh.DateWrapper.ofJsDate(new Date())); } else { value = dh.FilterValue.ofNumber(0); } const eqFilter = column.filter().eq(value); const notEqFilter = column.filter().notEq(value); return eqFilter.and(notEqFilter); } const values = []; let isNullSelected = false; for (let i = 0; i < selectedValues.length; i += 1) { const value = selectedValues[i]; if (value == null) { isNullSelected = true; } else if (TableUtils.isTextType(column.type)) { values.push(dh.FilterValue.ofString(value)); } else if (TableUtils.isBooleanType(column.type)) { values.push(dh.FilterValue.ofBoolean(!!value)); } else { values.push(dh.FilterValue.ofNumber(value)); } } if (isNullSelected) { if (values.length > 0) { if (invertSelection) { return column .filter() .isNull() .not() .and(column.filter().notIn(values)); } return column.filter().isNull().or(column.filter().in(values)); } if (invertSelection) { return column.filter().isNull().not(); } return column.filter().isNull(); } if (invertSelection) { return column.filter().notIn(values); } return column.filter().in(values); } static isTreeTable(table) { return table && table.expand && table.collapse; } /** * Copies the provided array, sorts by column name case insensitive, and returns the sorted array. * @param {Array<dh.Column>}} columns The columns to sort * @param {boolean} isAscending Whether to sort ascending */ static sortColumns(columns, isAscending = true) { return [...columns].sort((a, b) => { const aName = a.name.toUpperCase(); const bName = b.name.toUpperCase(); return TextUtils.sort(aName, bName, isAscending); }); } }
JavaScript
class GMap { /** * Constructor method. * @param {HTMLElement} node The Google Map to install. * @param {string} apiKey Our Google Maps JavaScript key. * @returns {Promise} Promise which resolves and calls the the createMap() function as son as THe Google API beocmes availalble. */ constructor(node, apiKey) { if(!apiKey) { logKeyMissing(); return; } /** {HTMLElement} Reference to the map container. */ this.map = node; /** {Object} The Google Maps map instance. */ this.googleMap = {}; /** {Object[]} An array of optional markers. */ this.markers = []; /** {Object[]} An array of optional info windows.. */ this.infoWindows = []; /** {string} Parsed string containing the complete URL to the Google Maps API (including API key). */ this.googleMapsSrc = GOOGLE_MAPS_API + '?key=' + apiKey; return this.setUpGoogleMaps(); } /** * Installs Google Maps API. * Creates the map when ready. */ setUpGoogleMaps() { return this.installGoogleMapsApi() .then(this.createMap.bind(this)); } /** * Installs the Google Maps API if not already installed. * Polls for Google Maps api and resolves promise when available. * @returns {Promise} resolve when API is ready to use. */ installGoogleMapsApi() { // Installs the Google Maps API if not already installed. if (!this.isGoogleMapsApiInstalled()) { let script = document.createElement('script'); script.src = this.googleMapsSrc; document.head.appendChild(script); } // Polls for Google Maps api and resolves promise when available. return new Promise((resolve) => { function pollGoogleObject() { if (window.google && window.google.maps) { resolve(); return; } setTimeout(pollGoogleObject, 100); } setTimeout(pollGoogleObject, 100); }); } /** * Returns whether the Google Maps API is installed. * @returns {boolean} */ isGoogleMapsApiInstalled() { return !![...document.scripts].find(script => script.src === this.googleMapsSrc); } /** * Creates the Google Maps instance. * @returns {Promise} */ createMap() { return new Promise((resolve, reject) => { if (!(this.map.dataset.coordinates && this.map.dataset.zoom)) { logKeyMissing(); reject(); } let lat = parseFloat(this.map.dataset.coordinates.split(',')[0]); let lng = parseFloat(this.map.dataset.coordinates.split(',')[1]); let zoom = parseInt(this.map.dataset.zoom); let markers = (this.map.dataset.markers) ? JSON.parse(this.map.dataset.markers) : []; let disableDefaultUI = this.map.dataset.disableDefaultUi || false; let disableInfoWindows = this.map.dataset.disableInfoWindows || false; let infoWindowConfig = (this.map.dataset.infowindow) ? JSON.parse(this.map.dataset.infowindow) : {}; if (!lat || !lng || !zoom) { console.warn('Parsing failed, please provide data-coordinates as commas separated lat/lng pair and data-zoom as number.'); reject(); } this.googleMap = new google.maps.Map(this.map, { center: {lat, lng}, zoom, disableDefaultUI }); this.markers = markers.map(marker => { let lat = parseFloat(marker.latitude); let lng = parseFloat(marker.longitude); let mapMarker = new google.maps.Marker({ map: this.googleMap, position: {lat, lng}, title: marker.title, optimized: false, // IE }); if (!disableInfoWindows) { let infoWindow = new google.maps.InfoWindow(infoWindowConfig); infoWindow.setContent(marker.html || `<h1>${marker.title}</h1><p>${marker.description}</p>`); mapMarker.addListener('click', () => { // jshint ignore:line infoWindow.open(this.googleMap, mapMarker); }); this.infoWindows.push(infoWindow) } // if (this.map.dataset.markerIcon) { // tempMarker.icon = { // url: this.map.dataset.markerIcon, // scaledSize: new google.maps.Size(16, 27), // FIXME // }; // } return mapMarker; }); resolve(this); }); } }
JavaScript
class OriginNavWrapper extends Component { componentDidMount() { PushNotificationIOS.checkPermissions(permissions => { this.props.storeNotificationsPermissions(permissions) }) originWallet.initNotifications() // skip the prompt // originWallet.events.on(Events.PROMPT_LINK, (data, matcher) => { // this.props.newEvent(matcher, data) // this.props.setActiveEvent(data) // NavigationService.navigate('Home') // }) originWallet.events.on(Events.PROMPT_TRANSACTION, (data, matcher) => { this.props.newEvent(matcher, data) // this.props.setActiveEvent(data) NavigationService.navigate('Home') }) originWallet.events.on(Events.PROMPT_SIGN, (data, matcher) => { this.props.newEvent(matcher, data) // this.props.setActiveEvent(data) NavigationService.navigate('Home') }) originWallet.events.on(Events.NEW_ACCOUNT, ({ address }, matcher) => { this.props.initWallet(address) this.props.fetchUser(address) this.props.getBalance() }) originWallet.events.on(Events.LINKED, (data, matcher) => { this.props.processedEvent(matcher, {}, data) NavigationService.navigate('Home') }) originWallet.events.on(Events.TRANSACTED, (data, matcher) => { this.props.processedEvent(matcher, { status: 'completed' }, data) this.props.getBalance() NavigationService.navigate('Home') }) originWallet.events.on(Events.UNLINKED, (data, matcher) => { originWallet.getDevices() this.props.updateEvent(matcher, { linked: false }) }) originWallet.events.on(Events.REJECT, (data, matcher) => { this.props.processedEvent(matcher, { status: 'rejected' }, data) NavigationService.navigate('Home') }) originWallet.events.on(Events.LINKS, (devices) => { this.props.setDevices(devices) }) originWallet.events.on(Events.UPDATE, () => { this.props.getBalance() }) originWallet.events.on(Events.NEW_MESSAGE, () => { // TODO: show indicator of new message here }) originWallet.events.on(Events.SHOW_MESSAGES, () => { NavigationService.navigate('Messaging') }) originWallet.events.on(Events.NOTIFICATION, notification => { this.props.addNotification({ id: notification.data.notificationId, message: notification.message.body, url: notification.data.url, }) }) originWallet.openWallet() // get the balance every five seconds setInterval(() => this.props.getBalance(), 5000) } componentWillUnmount() { originWallet.closeWallet() } render() { return <OriginNavigator ref={navigatorRef => NavigationService.setTopLevelNavigator(navigatorRef) } /> } }
JavaScript
class PlaceholderBoxPainter { paint(ctx, size) { ctx.lineWidth = 2; ctx.strokeColor = '#FC5D5F'; // Dibuja una linea desde arriba a la izquierda // hasta abajo a la derecha. ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(size.width, size.height); ctx.stroke(); // Dibuja una línea desde arriba a la derecha // hasta abajo a la izquierda ctx.beginPath(); ctx.moveTo(size.width, 0); ctx.lineTo(0, size.height); ctx.stroke(); } }
JavaScript
class Layout extends Plugin { /** * @function * @async * @param {Defiant.Plugin} plugin * The Plugin to which the `action` pertains. * @param {String} action * The action being performed. Example actions include "pre-enable", * "enable", "disable", "update". * @param {Mixed} [data=NULL] * Any supplementary information. */ async notify(plugin, action, data=null) { super.notify(plugin, action, data); switch (action) { case 'pre:enable': // Create the Layouts Registry. /** * @member {Defiant.util.InitRegistry} Defiant.Plugin.Layout#layoutRegistry * A collection of Layouts which can be customized. */ this.layoutRegistry = new InitRegistry({}, [this.engine]); this.layoutRegistry.set(new LayoutRenderable(this.engine, { id: 'defaultLayout', templateContents: `<nav> <div class="nav-wrapper"> <%= navigation %> </div> </nav> <div class="row"> <div class="col s12"> <%= content %> </div> </div> <div class="divider"></div> <div class="row"> <footer class="col s12"> <%= footer %> </footer> </div>`, variables: ['navigation', 'content', 'footer'], paths: [''], regions: { navigation: [ 'Layout.SiteNameWidget', 'Menu.default', ], content: [ 'Layout.TitleWidget', 'Message.MessageWidget', 'Layout.ContentWidget', ], footer: [ 'Menu.admin', ], }, })); // Create the Widgets Registry. /** * @member {Defiant.util.InitRegistry} Defiant.Plugin.Layout#widgetRegistry * Registry that holds Widgets that may be included in Layouts. */ this.widgetRegistry = new InitRegistry({}, [this.engine]); this.widgetRegistry.set(require('./widget/contentWidget')) .set(require('./widget/siteNameWidget')) .set(require('./widget/titleWidget')); for (let existingPlugin of ['FormApi', 'Router', 'ThemeBase', 'Settings', 'Library'].map(name => this.engine.pluginRegistry.get(name))) { if (existingPlugin instanceof Plugin) { await this.notify(existingPlugin, 'enable'); } } break; // pre:enable case 'enable': switch ((plugin || {}).id) { case 'FormApi': // Register Form and Elements plugin .setElement(require('./renderable/widgetPlacementRenderable.js')) .setForm(new Form(this.engine, { id: 'LayoutEditForm', Instance: require('./form/layoutEditFormInstance'), })); break; // FormApi case 'ThemeBase': plugin .setRenderable(require('./renderable/widgetPlacementRenderable.js')) .setRenderable(require('./widget')) .setRenderable(require('./widget/contentWidget')) .setRenderable(require('./widget/siteNameWidget')) .setRenderable(require('./widget/titleWidget')); break; // ThemeBase case 'Router': // Add the layout Handler. plugin .addHandler(new (require('./handler/layoutEditHandler'))()) .addHandler(new (require('./handler/layoutHandler'))()) .addHandler(new (require('./handler/layoutListHandler'))()) .addHandler(new ServeDirectoryHandler({ id: 'Layout.DirectoryHandler', path: 'file/layout', target: path.join(__dirname, 'file'), menu: undefined, fileOptions: {}, directoryOptions: undefined, })); break; // Router case 'Settings': // Add layout settings files. for (let layout of this.layoutRegistry.getIterator()) { if (!plugin.cacheRegistry.get(`layout/${layout.id}.json`)) { plugin.cacheRegistry.set(new Data({ id: `layout/${layout.id}.json`, filename: path.join('layout', `${layout.id}.json`), storage: 'settings', storageCanChange: true, // TODO: Translate. // TODO: Escape. description: 'Stores the overrides of the layout class, which are set through the administrative interface.', default: { templateContents: layout.templateContents, paths: layout.paths, regions: layout.regions, variables: layout.variables, }, })); } } break; // Settings case 'Library': // Add Library Entries. plugin.register({ id: 'LayoutWidgetPlacement', require: ['jQueryUI'], css: [{ id: 'layoutEdit', url: '/file/layout/css/layoutEdit.css', path: path.join(__dirname, 'file/css/layoutEdit.css'), }], jsFooter: [{ id: 'layoutEdit', url: '/file/layout/js/layoutEdit.js', path: path.join(__dirname, 'file/js/layoutEdit.js'), }], }); break; // Library case this.id: for (let existingPlugin of ['Settings'].map(name => this.engine.pluginRegistry.get(name))) { if (existingPlugin instanceof Plugin) { await this.notify(existingPlugin, 'enable'); } } break; // this.id } break; // enable case 'pre:disable': // @todo Cleanup. for (let existingPlugin of ['FormApi', 'Router', 'ThemeBase', 'Settings', 'Library'].map(name => this.engine.pluginRegistry.get(name))) { if (existingPlugin instanceof Plugin) { await this.notify(existingPlugin, 'disable'); } } break; // pre:disable case 'disable': switch ((plugin || {}).id) { case this.id: break; // this.id } break; // disable } } }
JavaScript
class Tape { /** * * @param {number} [ptr] * @param {Array<0 | 1 | -1>} [bits] */ constructor(ptr = 0, bits = [0]) { this.ptr = ptr; this.bits = bits; } /** * `INC` * もしヘッドが一番右にあればヘッドを進めて0を追加しZを返す。 * そうでなければヘッドを進めてNZを返す */ inc() { if (this.ptr === this.bits.length - 1) { this.bits.push(0); this.ptr += 1; return 0; } else { this.ptr += 1; return 1; } } /** * `DEC` * もしヘッドが一番左にあればZを返す。 * そうでなければヘッドを戻してNZを返す。 */ dec() { if (this.ptr === 0) { return 0; } else { this.ptr -= 1; return 1; } } /** * `READ` * 現在のヘッドの位置の値が0のときその値を消去してZを返す。 * 1のときの値を消去してNZを返す。 * そうでなければエラー */ read() { const bit = this.bits[this.ptr]; if (bit === 0) { this.bits[this.ptr] = -1; return 0; } else if (bit === 1) { this.bits[this.ptr] = -1; return 1; } else if (bit === -1) { throw Error("Runtime error: Tape.read"); } else { throw Error("Runtime error: Tape.read"); } } // internal /** * * @param {0 | 1} v * @returns {null} */ setValue(v) { if (this.bits[this.ptr] !== -1) { throw Error("Runtime error: Tape.set"); } this.bits[this.ptr] = v; return null; } /** * `SET` * @returns {null} */ set() { if (this.bits[this.ptr] === -1) { this.bits[this.ptr] = 1; return null; } else { throw Error("Runtime error: Tape.set"); } } /** * `RESET` * @returns {null} */ reset() { if (this.bits[this.ptr] === -1) { this.bits[this.ptr] = 0; return null; } else { throw Error("Runtime error: Tape.set"); } } toString() { const { prefix, head, suffix } = this.toObject(); let start = prefix.join(" "); return start + (start.length === 0 ? "" : " ") + "{" + head + "} " + suffix.join(" "); } toObject() { return { prefix: this.bits.slice(0, this.ptr), head: this.bits[this.ptr], suffix: this.bits.slice(this.ptr + 1), } } toArray() { return this.bits.slice(); } toArrayMinusOneIsZero() { return this.bits.map(v => v === -1 ? 0 : v); } getDecimal() { return parseInt(this.toArrayMinusOneIsZero().reverse().join(""), 2); } /** * @returns {bigint | number} */ getBigInt() { if (typeof BigInt === "undefined") { return this.getDecimal(); } return BigInt("0b" + this.toArrayMinusOneIsZero().reverse().join("")); } }
JavaScript
class Encryption { /** * Create a instance of the Encryption service * * @param {string} clientPrivateKeySetLocation - String that can be a URL or path to file with client JWK set * @param {string} hyperwalletKeySetLocation - String that can be a URL or path to file with hyperwallet JWK set * @param {string} encryptionAlgorithm - JWE encryption algorithm, by default value = RSA-OAEP-256 * @param {string} signAlgorithm - JWS signature algorithm, by default value = RS256 * @param {string} encryptionMethod - JWE encryption method, by default value = A256CBC-HS512 * @param {string} jwsExpirationMinutes - Minutes when JWS signature is valid */ constructor(clientPrivateKeySetLocation, hyperwalletKeySetLocation, encryptionAlgorithm = "RSA-OAEP-256", signAlgorithm = "RS256", encryptionMethod = "A256CBC-HS512", jwsExpirationMinutes = 5) { /** * String that can be a URL or path to file with client JWK set * * @type {string} * @protected */ this.clientPrivateKeySetLocation = clientPrivateKeySetLocation; /** * String that can be a URL or path to file with hyperwallet JWK set * * @type {string} * @protected */ this.hyperwalletKeySetLocation = hyperwalletKeySetLocation; /** * Client KeyStore object * * @type {string} * @protected */ this.clientKeyStore = null; /** * Hyperwallet KeyStore object * * @type {string} * @protected */ this.hwKeyStore = null; /** * JWE encryption algorithm, by default value = RSA-OAEP-256 * * @type {string} * @protected */ this.encryptionAlgorithm = encryptionAlgorithm; /** * JWS signature algorithm, by default value = RS256 * * @type {string} * @protected */ this.signAlgorithm = signAlgorithm; /** * JWE encryption method, by default value = A256CBC-HS512 * * @type {string} * @protected */ this.encryptionMethod = encryptionMethod; /** * Minutes when JWS signature is valid, by default value = 5 * * @type {number} * @protected */ this.jwsExpirationMinutes = jwsExpirationMinutes; } /** * Makes an encrypted request : 1) signs the request body; 2) encrypts payload after signature * * @param {string} body - The request body to be encrypted */ encrypt(body) { return new Promise((resolve, reject) => { const keyStorePromise = (this.clientKeyStore && this.hwKeyStore) ? Promise.resolve(this.keyStore) : this.createKeyStore(); keyStorePromise .then(() => this.signBody(body)) .then((signedBody) => this.encryptBody(signedBody)) .then((result) => resolve(result)) .catch((error) => reject(error)); }); } /** * Decrypts encrypted response : 1) decrypts the request body; 2) verifies the payload signature * * @param {string} body - The response body to be decrypted */ decrypt(body) { return new Promise((resolve, reject) => { const keyStorePromise = this.keyStore ? Promise.resolve(this.keyStore) : this.createKeyStore(); keyStorePromise .then(() => this.decryptBody(body)) .then((decryptedBody) => this.checkSignature(decryptedBody.plaintext)) .then((result) => resolve(result)) .catch((error) => reject(error)); }); } /** * Verify if response body has a valid signature * * @param {string} body - The response body to be verified */ checkSignature(body) { return new Promise((resolve, reject) => { const key = this.hwKeyStore.all({ alg: this.signAlgorithm })[0]; if (!key) { reject(new Error(`JWK set doesn't contain key with algorithm = ${this.signAlgorithm}`)); } const options = { handlers: { exp: (jws) => { if (this.getCurrentTime() > jws.header.exp) { reject(new Error("JWS signature has expired")); } }, }, }; jose.JWS.createVerify(key, options) .verify(body.toString()) .then((result) => resolve(result)) .catch(() => reject(new Error(`Failed to verify signature with key id = ${key.kid}`))); }); } /** * Decrypts the response body * * @param {string} body - The response body to be decrypted */ decryptBody(body) { return new Promise((resolve, reject) => { const key = this.clientKeyStore.all({ alg: this.encryptionAlgorithm })[0]; if (!key) { reject(new Error(`JWK set doesn't contain key with algorithm = ${this.encryptionAlgorithm}`)); } jose.JWE.createDecrypt(key) .decrypt(body) .then((result) => resolve(result)) .catch(() => reject(new Error(`Failed to decrypt payload with key id = ${key.kid}`))); }); } /** * Encrypts the request body * * @param {string} body - The request body to be encrypted */ encryptBody(body) { return new Promise((resolve, reject) => { const key = this.hwKeyStore.all({ alg: this.encryptionAlgorithm })[0]; if (!key) { reject(new Error(`JWK set doesn't contain key with algorithm = ${this.encryptionAlgorithm}`)); } const encryptionHeader = { format: "compact", alg: key.alg, enc: this.encryptionMethod, kid: key.kid, }; jose.JWE.createEncrypt(encryptionHeader, key) .update(body) .final() .then((result) => resolve(result)) .catch(() => reject(new Error(`Failed to encrypt payload with key id = ${key.kid}`))); }); } /** * Makes signature for request body * * @param {string} body - The request body to be signed */ signBody(body) { return new Promise((resolve, reject) => { const key = this.clientKeyStore.all({ alg: this.signAlgorithm })[0]; if (!key) { reject(new Error(`JWK set doesn't contain key with algorithm = ${this.signAlgorithm}`)); } const signHeader = { format: "compact", alg: key.alg, fields: { crit: ["exp"], exp: this.getSignatureExpirationTime(), kid: key.kid, }, }; jose.JWS.createSign(signHeader, key) .update(JSON.stringify(body), "utf8") .final() .then((result) => resolve(result)) .catch(() => reject(new Error(`Failed to sign with key id = ${key.kid}`))); }); } /** * Calculates signature expiration time in seconds ( by default expiration time = 5 minutes ) */ getSignatureExpirationTime() { const millisecondsInMinute = 60000; const millisecondsInSecond = 1000; const currentTime = new Date(new Date().getTime() + this.jwsExpirationMinutes * millisecondsInMinute).getTime(); return Math.round(currentTime / millisecondsInSecond); } /** * Get current time in seconds */ getCurrentTime() { const millisecondsInSecond = 1000; return Math.round(new Date().getTime() / millisecondsInSecond); } /** * Creates 2 JWK key stores : 1) for client keys 2) for hyperwallet keys */ createKeyStore() { return new Promise((resolve, reject) => { this.readKeySet(this.hyperwalletKeySetLocation) .then((jwkSet) => this.createKeyStoreFromJwkSet(this.hyperwalletKeySetLocation, jwkSet)) .then(() => this.readKeySet(this.clientPrivateKeySetLocation)) .then((jwkSet) => this.createKeyStoreFromJwkSet(this.clientPrivateKeySetLocation, jwkSet)) .then((result) => resolve(result)) .catch((error) => reject(error)); }); } /** * Converts JWK set in JSON format to JOSE key store format * * @param {string} jwkSetPath - The location of JWK set (can be URL string or path to file) * @param {string} jwkSet - The JSON representation of JWK set, to be converted to keystore */ createKeyStoreFromJwkSet(jwkSetPath, jwkSet) { return new Promise((resolve, reject) => { jose.JWK.asKeyStore(jwkSet). then((result) => { if (jwkSetPath === this.clientPrivateKeySetLocation) { this.clientKeyStore = result; } else { this.hwKeyStore = result; } resolve(result); }) .catch(() => reject(new Error("Failed to create keyStore from given jwkSet"))); }); } /** * Reads JWK set in JSON format either from given URL or path to local file * * @param {string} keySetPath - The location of JWK set (can be URL string or path to file) */ readKeySet(keySetPath) { return new Promise((resolve, reject) => { if (fs.existsSync(keySetPath)) { fs.readFile(keySetPath, { encoding: "utf-8" }, (err, keySetData) => { if (!err) { resolve(keySetData); } else { reject(new Error(err)); } }); } else { this.checkUrlIsValid(keySetPath, (isValid) => { if (isValid) { request(keySetPath, (error, response) => { if (!error) { const responseBody = response.body && Object.keys(response.body).length !== 0 ? response.body : response.text; resolve(responseBody); } }); } else { reject(new Error(`Wrong JWK set location path = ${keySetPath}`)); } }); } }); } /** * Checks if an input string is a valid URL * * @param {string} url - The URL string to be verified * @param {string} callback - The callback method to process the verification result of input url */ checkUrlIsValid(url, callback) { request(url, (error, response) => { callback(!error && response.statusCode === 200); }); } /** * Convert encrypted string to array of Buffer * * @param {string} encryptedBody - Encrypted body to be decoded */ base64Decode(encryptedBody) { const parts = encryptedBody.split("."); const decodedParts = []; parts.forEach(elem => { decodedParts.push(jose.util.base64url.decode(elem)); }); const decodedBody = {}; decodedBody.parts = decodedParts; return decodedBody; } /** * Convert array of Buffer to encrypted string * * @param {string} decodedBody - Array of Buffer to be decoded to encrypted string */ base64Encode(decodedBody) { const encodedParts = []; decodedBody.parts.forEach(part => { encodedParts.push(jose.util.base64url.encode(Buffer.from(JSON.parse(JSON.stringify(part)).data))); }); return encodedParts.join("."); } }
JavaScript
class DOMElement { /** * Constructor. * @param node Original node */ constructor(node) { this._origNode = node; this._tagName = node.tagName.toLowerCase(); this._parent = null; } /** * Get original node. * * @returns Original node */ origNode() { return this._origNode; } /** * Get id. * * @param {string=} id Optional id * @return {string|DOMElement} Element id or DOMElement for chaining when used as setter */ id(id) { if (id) { this._origNode.id = id; return this; } else { return this._origNode.id; } } /** * Get tag name. * * @returns {string|*} */ tag() { return this._tagName; } /** * Get / set height. * @param {number=} value Value to set (optional) * @returns {number|DOMElement} Height in px or DOMElement for chaining when used as setter */ height(value) { if (value === undefined) { return this._origNode.getBoundingClientRect().height; } else { this._origNode.style.height = `${value}${PX}`; return this; } } /** * Get / set width. * * @param {number=} value Value to set (optional) * @returns {number|DOMElement} Width in px or DOMElement for chaining when used as setter */ width(value) { if (value === undefined) { return this._origNode.getBoundingClientRect().width; } else { this._origNode.style.width = `${value}${PX}`; return this; } } /** * Get fixed position relative to scroll container. * * @returns {{top: number, left: number, bottom: number, right: number}} */ position() { return { top: this._origNode.offsetTop, left: this._origNode.offsetLeft, bottom: this._origNode.offsetTop + this._origNode.offsetHeight, right: this._origNode.offsetLeft + this._origNode.offsetWidth } } /** * Get scroll position relative to visible viewport. * * @returns {{top: number, left: number, bottom: number, right: number}} */ offset() { return { top: this._origNode.getBoundingClientRect().top, left: this._origNode.getBoundingClientRect().left, bottom: this._origNode.getBoundingClientRect().bottom, right: this._origNode.getBoundingClientRect().right } } /** * Check if class is set. * * @param className Class name * @returns {boolean} true if set, false if not */ hasClass(className) { if (this._origNode.classList) { return this._origNode.classList.contains(className); } else { console.error("classList not available"); return false; } } /** * Add class. * * @param {...string} classNames Class names * @returns {DOMElement} DOMElement for chaining */ addClass(...classNames) { if (this._origNode.classList) { this._origNode.classList.add(...classNames); if (classNames.length > 1) { // Workaround for browser that do not support multiple class names if (!this.hasClass(classNames[1])) { classNames .filter((className) => !this.hasClass(className)) .forEach((className) => this.addClass(className)) ; } } } else { console.error("classList not available"); } return this; } /** * Replace class. * * @param className Class name to be replaced * @param otherClassName Class name to be set * * @returns {DOMElement} DOMElement for chaining */ replaceClass(className, otherClassName) { if (this._origNode.classList) { if (this._origNode.classList.replace) { if (this.hasClass(className)) { this._origNode.classList.replace(className, otherClassName); } else { this.addClass(otherClassName); } } else { this.removeClass(className).addClass(otherClassName); } } else { console.error("classList not available"); } return this; } /** * Remove class. * * @param {...string} classNames Class names * @returns {DOMElement} DOMElement for chaining */ removeClass(...classNames) { if (this._origNode.classList) { this._origNode.classList.remove(...classNames); if (classNames.length > 1) { // Workaround for browser that do not support multiple class names if (this.hasClass(classNames[1])) { classNames .filter((className) => this.hasClass(className)) .forEach((className) => this.removeClass(className)) ; } } } else { console.error("classList not available"); } // Remove class attribute if we have no more class set if (this.attr("class") === "") { this.removeAttr("class"); } return this; } /** * Toggle class. * * @param {string} className Class name * @param {boolean=} force Force add or remove (optional) * @returns {DOMElement} */ toggleClass(className, force) { if (this._origNode.classList) { this._origNode.classList.toggle(className, force) } else { console.error("classList not available"); } // Remove class attribute if we have no more class set if (this.attr("class") === "") { this.removeAttr("class"); } return this; } /** * Check if element is hidden. * * @returns {boolean} true if hidden, false if visible */ hidden() { let computedStyles = window.getComputedStyle(this._origNode); return computedStyles.display.toLowerCase() === NONE || computedStyles.visibility.toLowerCase() === HIDDEN; } /** * Check if element is visible. * * @returns {boolean} true if visible, false if hidden */ visible() { return !this.hidden(); } /** * Get / set attribute value. * * @param name Attribute name * @param {string=} value Attribute value (optional) * @returns {*} Attribute value or DOMElement for chaining when used as setter */ attr(name, value) { if (value === undefined) { return this._origNode.getAttribute(name); } else { this._origNode.setAttribute(name, value); return this; } } /** * Remove attribute. * * @param attrName Attribute name * @returns {DOMElement} DOMElement for chaining */ removeAttr(attrName) { this._origNode.removeAttribute(attrName); return this; } /** * Check if element has a specific attribute. * * @param attrName Attribute name * @returns {boolean} true if available false if not */ hasAttr(attrName) { return this.attr(attrName) != null; } /** * Get / set css style. * * If the last style is removed the attribute style is removed as well. * Style can be removed if value is null. * * @param style Style name * @param {?*=} value Style value (optional) * @returns {*} Style value or DOMElement for chaining when used as setter */ css(style, value) { if (value === undefined) { return window.getComputedStyle(this._origNode)[style]; } else { this._origNode.style[style] = value ? value : ""; if (this.attr(STYLE) === "") { this.removeAttr(STYLE); } return this; } } /** * Get parent. * * @returns {DOMElement} Parent element */ parent() { if (!this._parent) { this._parent = new DOMElement(this._origNode.parentNode); } return this._parent; } /** * Return nearest parent which is not static. * * @returns {DOMElement} Offset parent element or null */ offsetParent() { let parent = this._origNode.offsetParent; return parent != null ? new DOMElement(this._origNode.offsetParent) : null; } /** * Show element. * * Is able to save/restore the initial display value even if its an inline style. * * TODO Add easing */ show() { // TODO Add easing return _showOrHide(this, this.hidden(), BLOCK); } /** * Hide element. * * Is able to save/restore the initial display value even if its an inline style. */ hide() { // TODO Add easing return _showOrHide(this, this.visible(), NONE); } /** * Add event listener. * * @param {string|Event|CustomEvent} event Event name or event * @param handler Event handler * @param capture true for capture phase, false for bubbling phase * return {DOMElement} DOMElement for chaining */ addEvent(event, handler, capture = false) { DOM.addEvent(this._origNode, event, handler, capture); return this; } /** * Remove event listener. * * @param {string|Event|CustomEvent} event Event name or event * @param handler Event handler * @param capture true for capture phase, false for bubbling phase * return {DOMElement} DOMElement for chaining */ removeEvent(event, handler, capture = false) { DOM.removeEvent(this._origNode, event, handler, capture); return this; } /** * Trigger event. * * @param {string|Event|CustomEvent} event Event name or event * @returns {boolean} true if cancelled, false if event has not been cancelled */ dispatchEvent(event) { return DOM.dispatchEvent(this._origNode, event); } /** * Animate element. * * @param {string} type Animation type "transition" or "animation" (default). * @returns {Animation} Animation */ animate(type = "animation") { return new Animation(this, type); } /** * Append child element. * * @param {DOMElement} element Child element * @returns {DOMElement} DOMElement for chaining */ appendChild(element) { this._origNode.appendChild(element.origNode()); return this; } /** * Remove child element. * * @param {DOMElement} element Child element * return {DOMElement} DOMElement for chaining */ removeChild(element) { this._origNode.removeChild(element.origNode()); return this; } /** * Get a specific child item. * * @param index Index of the child item */ child(index) { return new DOMElement(this._origNode.children[index]); } /** * Insert element before other element. * * @param element Inserted (moved) element * @param reference Reference element * @returns {DOMElement} Inserted element */ insertBefore(element, reference) { return new DOMElement(this._origNode.insertBefore(element._origNode, reference._origNode)); } /** * Get/set inner HTML. * * @param {?string=} data HTML data (optional) * @returns {*} Inner HTML or DOMElement for chaining when used as setter */ html(data) { if (!data) { return this._origNode.innerHTML; } else { this._origNode.innerHTML = data; return this; } } /** * Get/set inner text. * * @param {?*=} text Text * @returns {*} Inner text or DOMElement for chaining when used as setter */ text(text) { if (!text) { return this._origNode.innerText; } else { this._origNode.innerText = text; return this; } } /** * Load external HTML into element * * @param url Location of HTML file * @param {Function=} handler Optional handler that is executed after loading is finished * @returns {DOMElement} DOMElement for chaining */ load(url, handler) { let request = new XMLHttpRequest(); request.onload = () => { this.html(request.responseXML.body ? request.responseXML.body.innerHTML : request.responseText /* Fix: IE9 */); if (handler) { handler(request); } }; request.open("GET", url); request.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); request.responseType = "document"; // FIX: must be set AFTER open otherwise InvalidStateError in IE request.send(); return this; } /** * Query elements in the context of the current element. * * Syntax: DOM.query(<selectors>[,<context>]); * * @param {string} selectors String with selectors * @returns {!Array} Array of DOMElement items */ query(selectors) { return DOM.query(selectors, this); } /** * Query a unique element in the context of the current element. * * @param selector Selector * @returns {DOMElement} DOMElement or null if not found */ queryUnique(selector) { return DOM.queryUnique(selector, this); } /** * Get last child. * * @param {boolean} elementsOnly Consider all nodes (false) or only elements true). Default is false. * @returns {?DOMElement} DOMElement or null if not an element */ lastChild(elementsOnly = false) { let child = elementsOnly ? this.origNode().lastElementChild : this.origNode().lastChild; if (child instanceof Element) { return new DOMElement(child); } // TODO Support DOMText as well return null; } /** * Get first child. * * @param {boolean} elementsOnly Consider all nodes (false) or only elements true). Default is false. * @returns {DOMElement} DOMElement or null if not an element */ firstChild(elementsOnly = false) { let child = elementsOnly ? this.origNode().firstElementChild : this.origNode().firstChild; if (child instanceof Element) { return new DOMElement(child); } // TODO Support DOMText as well return null; } /** * Get next sibling element. * * @param {boolean} elementsOnly Consider all nodes (false) or only elements true). Default is false. * @returns {DOMElement} DOMElement or null if not an element */ nextSibling(elementsOnly = false) { let sibling = elementsOnly ? this.origNode().nextElementSibling : this.origNode().nextSibling; if (sibling instanceof Element) { return new DOMElement(sibling); } // TODO Support DOMText as well return null; } /** * Get previous sibling element. * * @param {boolean} elementsOnly Consider all nodes (false) or only elements true). Default is false. * @returns {DOMElement} DOMElement or null if not an element */ previousSibling(elementsOnly = false) { let sibling = elementsOnly ? this.origNode().previousElementSibling : this.origNode().previousSibling; if (sibling instanceof Element) { return new DOMElement(sibling); } // TODO Support DOMText as well return null; } /** * Get or set a data attribute value. * @param property Name of the property in camel case (e.g. alternateLabel instead of data-alternate-label) * @param {?string=} value New value (optional) * @returns {string | undefined | DOMElement} */ data(property, value) { if (this.origNode().dataset) { if (!value) { return this.origNode().dataset[property]; } else { this.origNode().dataset[property] = value; return this; } } else { if (!value) { return this.origNode().getAttribute("data-" + StringUtils.fromCamelCase(property)); } else { let label = StringUtils.fromCamelCase((property).replace("data", "")); this.origNode().setAttribute(`data-${label.substr(0, 1).toLowerCase()+ label.substring(1)}`, value); } } } }
JavaScript
class Pokamnieto { /** * Class for revealing elements when they appear in the view while scrolling the page based on the IntersectionObserver API. * * @param {string} selector * @param {Object} config */ constructor(selector = '.js-pokamnieto', config = {}) { this.elements = [...document.querySelectorAll(selector)]; this.config = Object.assign({}, defaultConfig, config); this.state = { observedElements: 0, }; this.prepareElements = this.prepareElements.bind(this); window.addEventListener('scroll', this.prepareElements); } /** * Function that prepare elements to reveal animation. * It fired only once after the first page rewind. * * @return {void} */ prepareElements() { const { elementPreparedClassName } = this.config; window.removeEventListener('scroll', this.prepareElements); /** * Filter items in the current viewport */ this.elements = this.elements.filter(element => { const [isInViewport, viewportPosition] = elementPositionInfo(element); /** * Adds a "prepared class" only to elements outside of the viewport. * An additional class adds a class with information about whether the item is above or below the viewport. */ if (!isInViewport) { element.classList.add(viewportPosition); element.classList.add(elementPreparedClassName); } return !isInViewport; }); this.state.observedElements = this.elements.length; this.initObserver(); } /** * Function that initializes the IntersectionObserver instance * * @return {void} */ initObserver() { this.observer = new IntersectionObserver(this.callback.bind(this), { root: this.config.root, rootMargin: this.config.rootMargin, threshold: this.config.threshold, }); for (let i = 0; i < this.elements.length; i += 1) { this.observer.observe(this.elements[i]); } } /** * Callback for the IntersectionObserver instance * * @param {Array} entries * @return {void} */ callback(entries) { const { elementVisibleClassName } = this.config; entries.forEach(entry => { const { target } = entry; if (entry.isIntersecting) { target.classList.add(elementVisibleClassName); this.observer.unobserve(target); this.state.observedElements -= 1; this.unmountIf(); } }); } /** * A method that stops the observer if there are no observed elements * * @return {void} */ unmountIf() { const { observedElements } = this.state; const { unmountOnRevealAll } = this.config; if (observedElements === 0 && unmountOnRevealAll) { this.unmount(); } } /** * Public method that stops the observer * * @return {void} */ unmount() { this.observer.disconnect(); } /** * Public method that adds another element to the IntersectionObserver instance * * @param {Element} element * @return {void} */ observe(element) { this.observer.observe(element); this.state.observedElements += 1; } }
JavaScript
class Input { /** * @param {function[]} inputPipeline array of functions that generate input values every frame */ constructor(inputPipeline) { for (const f of inputPipeline) if (f.name == "") throw new Error("All input functions must have names") this.inputPipeline = inputPipeline this.last = null this.now = null } /** * Collect inputs and update `now` and `last`. * * Sets `last` to `now` and computes a new value for `now` by calling every * function in the input pipeline in turn. The values returned are * associated with the functions' names in `now`. * * Input functions are called by passing in the new value for `now` as the * first argument and the last frame's input as the second argument. These * arguments can be ignored if they are not useful. * * Expected to be called once a frame before any application logic. * * @example * // previous value can be used to compute deltas * let input = new Input([ * function time(_now, previous) { * let now = performance.now() * let delta = !previous ? 0 : now - previous.time.now; * return { now, delta } * } * ]) * * // now value can be used to process values from earlier in the pipeline * let input = new Input([ * function rawData() { ... } * function smoothData(now) { * return smoothFunction(now.rawData) * } * ]) */ collect() { let _now = {} for (const f of this.inputPipeline) { _now[f.name] = f(_now, this.now) } this.last = this.now this.now = deepFreeze(_now) } }
JavaScript
class App { /** * @type {Router} */ #router; /** * @type (string) */ #webRoot; /** * Construct app * * @param 0.router {Router} * @param 0.webRoot (string) */ constructor( { router=new Router(), webRoot=defaultWebRoot(), }={}, ) { this.#router= router; this.#webRoot= webRoot; } /** * Listen a host with HTTP * * @param host (string) * * @return ~<void> */ async listenHTTP( host, ) { for await( const denoRequest of HttpServer.serve( host, ) ) new Request( denoRequest, ) .then( this['::'].handle, ) .then( denoRequest['::'].respond, ) ; } /** * Handle a single deno request * * @param request {Request} * * @return ~{Response} */ async handle( request, ) { const route= this.#router.dispatch( request, ); if( route ) return route.run( { request, app:this, }, ); else if( await this.hasFile( request.path, ) ) return makeFileResponse( this.localPath( request.path, ), ); else return notFound( { request, app:this, }, ); } /** * Check whether a file exists in web root. * * @param path (string) * * @return ~(boolean) */ async hasFile( path, ) { const localPath= this.localPath( path, ); return (await file_exists( localPath, )) && (await is_file( localPath, )); } /** * Transform url path into local path */ localPath( path, ) { return `${this.#webRoot}${path}`; } }
JavaScript
class SuspendedFilmstripOnlyOverlay extends AbstractSuspendedOverlay { /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const { t } = this.props; return ( <FilmstripOnlyOverlayFrame isLightOverlay = { true }> <div className = 'inlay-filmstrip-only__container'> <div className = 'inlay-filmstrip-only__title'> { t('suspendedoverlay.title') } </div> <div className = 'inlay-filmstrip-only__text'> { translateToHTML(t, 'suspendedoverlay.text') } </div> </div> <ReloadButton textKey = 'suspendedoverlay.rejoinKeyTitle' /> </FilmstripOnlyOverlayFrame> ); } }
JavaScript
class Dino { constructor(species, weight, height, diet, where, when, fact, img) { this.species = species, this.weight = weight, this.height = height, this.diet = diet, this.where = where, this.when = when, this.fact = fact, this.img = img } compareWeight (humanWeight) { const dinoToKgs = this.weight * 0.45359237; const diffValue = Math.trunc(dinoToKgs - humanWeight); const result = diffValue > 0 ? `${this.species} is heavier than you` : `${this.species} is lighter than you`; return result; } compareHeight (humanHeight) { const diffValue = Math.trunc(this.height - humanHeight); const result = diffValue > 0 ? `${this.species} is taller than you` : `${this.species} is smaller than you`; return result; } compareDiet (humanDiet) { let result = ''; switch (this.diet) { case 'carnivor': result = `${this.species} is a carnivor. You can hunt meat together.`; break; case 'herbavor': result = `${this.species} is a herbavor. Keep healthy and breath fresh air.`; break; case this.diet == humanDiet: result = `${this.species} is the same as you. You are born in ancient time.`; break; default: result = `${this.species} is a ${this.diet}. You are different from others.`; break; } return result; } }
JavaScript
class Human { constructor(name, feet, inches, diet) { this.name = name, this.feet = feet, this.inches = inches, this.diet = diet, this.species = 'human', this.img = 'human' } }
JavaScript
class HAXWiring { constructor() { /** * haxProperties */ this.haxProperties = { canScale: false, canPosition: false, canEditSource: false, settings: { quick: [], configure: [], advanced: [] }, wipeSlot: {} }; this.pathFromUrl = url => { return url.substring(0, url.lastIndexOf("/") + 1); }; /** * Setter to bridge private haxProperties setter. * This is to then be implemented by the ready state of whatever is supplying the * properties in order to be able to bubble up the properties for a tag. */ this.setup = (props, tag = "", context = this) => { if (typeof this.tagName !== typeof undefined) { tag = this.tagName.toLowerCase(); } window.addEventListener( "hax-store-ready", this._haxStoreReady.bind(this) ); if ( typeof window.HaxStore !== typeof undefined && window.HaxStore.instance != null && window.HaxStore.ready ) { return this.setHaxProperties(props, tag, context, true); } else { return this.setHaxProperties(props, tag, context, false); } }; /** * HAX store is ready so now we can fire events */ this._haxStoreReady = e => { if ( e.detail && typeof this.tagName !== typeof undefined && typeof this.haxProperties !== typeof undefined ) { let tag = this.tagName; let props = this.haxProperties; let context = this; if (tag != "" && typeof window.HaxStore === typeof undefined) { const evt = new CustomEvent("hax-register-properties", { bubbles: true, composed: true, cancelable: true, detail: { tag: tag.toLowerCase(), properties: props, polymer: false } }); context.dispatchEvent(evt); } else if ( tag != "" && typeof window.HaxStore.instance.elementList[tag.toLowerCase()] === typeof undefined ) { const evt = new CustomEvent("hax-register-properties", { bubbles: true, composed: true, cancelable: true, detail: { tag: tag.toLowerCase(), properties: props } }); context.dispatchEvent(evt); } else if ( typeof this.tagName !== typeof undefined && typeof window.HaxStore.instance.elementList[ this.tagName.toLowerCase() ] === typeof undefined ) { const evt = new CustomEvent("hax-register-properties", { bubbles: true, composed: true, cancelable: true, detail: { tag: this.tagName.toLowerCase(), properties: props } }); context.dispatchEvent(evt); } } }; /** * Setter to bridge private haxProperties setter. * This is to then be implemented by the ready state of whatever is supplying the * properties in order to be able to bubble up the properties for a tag. */ this.setHaxProperties = ( props = {}, tag = "", context = document, isReady = false ) => { // these are a core piece of hax capabilities // set them in the event this got called without anything // so we at least won't bomb if (typeof props.api === typeof undefined) { props.api = "1"; } // sets us up for future API versioning of property validation // and clean up. if (props.api == "1") { if (typeof props.canPosition === typeof undefined) { props.canPosition = true; } if (typeof props.canScale === typeof undefined) { props.canScale = true; } if (typeof props.canEditSource === typeof undefined) { props.canEditSource = false; } if (typeof props.gizmo === typeof undefined) { props.gizmo = false; } else { // support possible dynamic import of iconset // this would be if the user defined their own icons if (typeof props.gizmo.iconLib !== typeof undefined) { const basePath = this.pathFromUrl( decodeURIComponent(import.meta.url) ); import(`${basePath}../../../${props.gizmo.iconLib}`); } } // while not required, this is where all the raw power of this // approach really lies since this wires properties/slots to HAX's // ability to manipulate things via contextual menus if (typeof props.settings !== typeof undefined) { // loop through any potential settings in each of the three // groupings of possible settings and validate that each setting is accurate if (typeof props.settings.quick === typeof undefined) { props.settings.quick = []; } for (let i = 0; i < props.settings.quick.length; i++) { props.settings.quick[i] = this.validateSetting( props.settings.quick[i] ); // account for a bad property and remove it if (!props.settings.quick[i]) { props.settings.quick.splice(i, 1); } } if (typeof props.settings.configure === typeof undefined) { props.settings.configure = []; } for (let i = 0; i < props.settings.configure.length; i++) { props.settings.configure[i] = this.validateSetting( props.settings.configure[i] ); if (!props.settings.configure[i]) { props.settings.configure.splice(i, 1); } } if (typeof props.settings.advanced === typeof undefined) { props.settings.advanced = []; } for (let i = 0; i < props.settings.advanced.length; i++) { props.settings.advanced[i] = this.validateSetting( props.settings.advanced[i] ); if (!props.settings.advanced[i]) { props.settings.advanced.splice(i, 1); } } props = this.standardAdvancedProps(props); } // support for advanced save options if (typeof props.saveOptions === typeof undefined) { props.saveOptions = { wipeSlot: false }; } // support for demoSchema if (typeof props.demoSchema === typeof undefined) { props.demoSchema = []; } // fire event so we know they have been set for the store to collect // only fire if we haven't already so multiple elements don't keep bubbling // if there's no global HaxStore then this means it is a custom // implementation of the schema if (isReady) { this.readyToFireHAXSchema(tag, props, context); } // only set these when tag hasn't been force fed if (tag === "") { if (typeof this._setHaxProperties === "function") { this._setHaxProperties(props); } else { this.haxProperties = props; } } } else { // especially useful during development if we implement our own API // incorrectly. Don't hard brick cause it'll still more or less work // but would probably default to an iframe which is less then ideal // but at least wouldn't brick the AX. console.warn( "This is't a valid usage of hax API. See hax-body-behaviors/lib/HAXWiring.js for more details on how to implement the API. https://haxtheweb.org/hax-schema for details but we will try and guess the wiring" ); } }; this.readyToFireHAXSchema = (tag, props, context) => { if (tag != "" && typeof window.HaxStore === typeof undefined) { const evt = new CustomEvent("hax-register-properties", { bubbles: true, composed: true, cancelable: true, detail: { tag: tag.toLowerCase(), properties: props, polymer: false } }); context.dispatchEvent(evt); } else if (tag != "") { const evt = new CustomEvent("hax-register-properties", { bubbles: true, composed: true, cancelable: true, detail: { tag: tag.toLowerCase(), properties: props } }); context.dispatchEvent(evt); } else if (typeof this.tagName !== typeof undefined) { const evt = new CustomEvent("hax-register-properties", { bubbles: true, composed: true, cancelable: true, detail: { tag: this.tagName.toLowerCase(), properties: props } }); context.dispatchEvent(evt); } else if (typeof context.tagName !== typeof undefined) { const evt = new CustomEvent("hax-register-properties", { bubbles: true, composed: true, cancelable: true, detail: { tag: context.tagName.toLowerCase(), properties: props } }); context.dispatchEvent(evt); } else { console.warn(context); console.warn( `${tag} missed our checks and has an issue in implementation with HAX` ); } }; /** * Standard advanced properties we support for all forms */ this.standardAdvancedProps = props => { // allow classes to be modified this way props.settings.advanced.push({ attribute: "class", title: "Classes", description: "CSS classes applied manually to the element", inputMethod: "textfield" }); // allow styles to be modified this way props.settings.advanced.push({ attribute: "style", title: "Styles", description: "Custom CSS styles as applied to the element", inputMethod: "textfield" }); // allow schema definitions props.settings.advanced.push({ attribute: "prefix", title: "Schema: prefix", description: "Schema prefixes", inputMethod: "textfield" }); props.settings.advanced.push({ attribute: "typeof", title: "Schema: TypeOf", description: "typeof definition for Schema usage", inputMethod: "textfield" }); props.settings.advanced.push({ attribute: "property", title: "Schema: Property", description: "typeof definition for Schema usage", inputMethod: "textfield" }); props.settings.advanced.push({ attribute: "resource", title: "Schema: Resource ID", description: "Schema resource identifier", inputMethod: "textfield" }); // allow the id to be modified props.settings.advanced.push({ attribute: "id", title: "ID", description: "element ID, only set this if you know why", inputMethod: "textfield" }); // we need to support slot in the UI but actually shift it around under the hood // this is so that shadow roots don't get mad when previewing props.settings.advanced.push({ attribute: "slot", title: "slot", description: "DOM slot area", inputMethod: "textfield" }); return props; }; /** * Validate settings object. */ this.validateSetting = setting => { // we don't have a property or slot so it's not valid. if ( typeof setting.property === typeof undefined && typeof setting.slot === typeof undefined && typeof setting.attribute === typeof undefined ) { return false; } // ensure there's a title if (typeof setting.title === typeof undefined) { if (typeof setting.attribute === typeof undefined) { setting.title = setting.property; } else { setting.title = setting.attribute; } } // ensure there's at least an empty description if (typeof setting.description === typeof undefined) { setting.description = ""; } // ensure there's at least an input method if (typeof setting.inputMethod === typeof undefined) { setting.inputMethod = "textfield"; } // ensure there's at least a type if (typeof setting.type === typeof undefined) { setting.type = "settings"; } // ensure there's at least an icon if (typeof setting.icon === typeof undefined) { setting.icon = "android"; } // ensure there's at least an empty options area if (typeof setting.options === typeof undefined) { setting.options = {}; } // ensure there's required set if (typeof setting.required === typeof undefined) { setting.required = false; } // ensure there's required set if (typeof setting.disabled === typeof undefined) { setting.disabled = false; } // ensure there's validation or make it anything if none set if (typeof setting.validation === typeof undefined) { setting.validation = ".*"; } // ensure there's validation or make it anything if none set if (typeof setting.validationType === typeof undefined) { setting.validationType = ""; } // slot can have a slot wrapper property if (typeof setting.slot !== typeof undefined) { if (typeof setting.slotWrapper === typeof undefined) { setting.slotWrapper = "span"; } if (typeof setting.slotAttributes === typeof undefined) { setting.slotAttributes = {}; } } return setting; }; /** * Match convention for set. */ this.getHaxProperties = () => { return this.haxProperties; }; /** * Convert haxProperties structure to a simple json-schema. * This allows for complex form building systems based on this data. * type is configure or advanced */ this.getHaxJSONSchema = (type, haxProperties, target = this) => { if (typeof type === typeof undefined) { type = "configure"; } if (typeof haxProperties === typeof undefined) { haxProperties = target.haxProperties; } let settings = haxProperties.settings[type]; var schema = { $schema: "http://json-schema.org/schema#", title: "HAX " + type + " form schema", type: "object", properties: {} }; schema.properties = new SimpleFields().fieldsToSchema(settings); // support post processing of schema in order to allow for really // custom implementations that are highly dynamic in nature // post process hook needs to see if there's a class overriding this // if we have a definition for this component then we should run its postProcess // just to be safe if ( haxProperties.gizmo && haxProperties.gizmo.tag && window.customElements.get(haxProperties.gizmo.tag) ) { let tmp = document.createElement(haxProperties.gizmo.tag); if (typeof tmp.postProcessgetHaxJSONSchema === "function") { schema = tmp.postProcessgetHaxJSONSchema(schema); } else { schema = target.postProcessgetHaxJSONSchema(schema); } } else { schema = target.postProcessgetHaxJSONSchema(schema); } return schema; }; /** * Default postProcessgetHaxJSONSchema to be overridden. */ this.postProcessgetHaxJSONSchema = schema => { return schema; }; /** * Internal helper for getHaxJSONSchema to buiild the properties object * correctly with support for recursive nesting thx to objects / arrays. */ this._getHaxJSONSchemaProperty = settings => { return new SimpleFields().fieldsToSchema(settings); }; /** * Convert input method to schema type */ this.getHaxJSONSchemaType = inputMethod => { var method = new SimpleFields().fieldsConversion.inputMethod[inputMethod] || new SimpleFields().fieldsConversion; return method && method.defaultSettings && method.defaultSettings.type ? method.defaultSettings.type : "string"; }; /** * List valid input methods. */ this.validHAXPropertyInputMethod = () => { var methods = Object.keys( new SimpleFields().fieldsConversion.inputMethod ); return methods; }; /** * Return a haxProperties prototype / example structure */ this.prototypeHaxProperties = () => { // example properties valid for HAX context menu. let props = { api: "1", canScale: true, canPosition: true, canEditSource: false, gizmo: { title: "Tag name", description: "", icon: "icons:android", color: "purple", groups: ["Content"], handles: [ { type: "data", type_exclusive: false, url: "src" } ], meta: { author: "auto" } }, settings: { quick: [ { property: "title", title: "Title", inputMethod: "textfield", icon: "android" }, { property: "primaryColor", title: "Primary color", inputMethod: "colorpicker", icon: "color" } ], configure: [ { slot: "", title: "Inner content", description: "The slotted content that lives inside the tag", inputMethod: "textfield", icon: "android", required: true, validationType: "text" }, { slot: "button", title: "Button content", description: "The content that can override the button", inputMethod: "textfield", icon: "android", required: true, validationType: "text" }, { property: "title", title: "Title", description: "", inputMethod: "textfield", icon: "android", required: true, validationType: "text" }, { property: "primaryColor", title: "Title", description: "", inputMethod: "textfield", icon: "android", required: false, validation: ".*", validationType: "text" } ], advanced: [ { property: "secondaryColor", title: "Secondary color", description: "An optional secondary color used in certain edge cases.", inputMethod: "colorpicker", icon: "color" }, { property: "endPoint", title: "API endpoint", description: "An optional endpoint to hit and load in more data dymaically.", inputMethod: "textfield", icon: "android", validation: "[a-z0-9]", validationType: "url" } ] }, saveOptions: { wipeSlot: false, unsetAttributes: ["end-point", "secondary-color"] }, demoSchema: [ { tag: "my-tag", content: "<p>inner html</p>", properties: { endPoint: "https://cdn2.thecatapi.com/images/9j5.jpg", primaryColor: "yellow", title: "A cat" } } ] }; return props; }; } }
JavaScript
class ProcedureCaller { constructor () { this._procedures = new Map() } /** * Defines a procedure by the given `name`. * @param {string} name The name of the procedure * @param {Function} fn The procedure function * @param {Boolean} [override=false] Override if a procedure with this name already exists */ define (name, fn, override = false) { if (!name || typeof name !== 'string') { throw new TypeError('name must be a string') } if (!fn || typeof fn !== 'function') { throw new TypeError('fn must be a function') } if (!override && this._procedures.has(name)) { throw new Error(`${name} already defined`) } this._procedures.set(name, fn) } /** * Calls the procedure with the given `name` and returns the result. * @param {string} name The name of the procedure * @param {any} ...args Zero, one or more arguments * @return {any} The result of the procedure */ call (name, ...args) { if (!name || typeof name !== 'string') { throw new TypeError('name must be a string') } if (!this._procedures.has(name)) { throw new Error(`${name} not defined`) } const procedure = this._procedures.get(name) return procedure.apply(null, args) } /** * Delete the procedure with the given `name`. * @param {string} name The name of the procedure * @param {Boolean} [failSilently=true] Don't throw an error if `name` is not defined */ delete (name, failSilently = true) { if (!name || typeof name !== 'string') { throw new TypeError('name must be a string') } if (!failSilently && !this._procedures.has(name)) { throw new Error(`${name} not defined`) } this._procedures.delete(name) } }
JavaScript
class WarriorAttribute { constructor(name){ verifyType(name, TYPES.string); this.name = name; } }
JavaScript
class NgbToastConfig { constructor() { this.autohide = true; this.delay = 500; this.ariaLive = 'polite'; } }
JavaScript
class UpdatePlayerAction extends Action { constructor(playerIndex, propertyName, propertyValue) { super(); this.playerIndex = playerIndex; this.propertyName = propertyName; this.propertyValue = propertyValue; } dump() { const state = super.dump(); state.playerIndex = this.playerIndex; state.propertyName = this.propertyName; state.propertyValue = this.propertyValue; return state; } restore(state) { this.playerIndex = state.playerIndex; this.propertyName = state.propertyName; this.propertyValue = state.propertyValue; } }
JavaScript
class Page { constructor(dom) { this.dom = dom; } /** * Performs a querySelector in the page content or document * * @param {string} selector * @param {DocumentElement} context * * @return {Node} */ querySelector(selector, context = this.dom) { const result = context.querySelector(selector); if (!result) { throw new Error(`Not found the target "${selector}"`); } return result; } /** * Performs a querySelector * * @param {string} selector * @param {DocumentElement} context * * @return {Nodelist} */ querySelectorAll(selector, context = this.dom) { const result = context.querySelectorAll(selector); if (!result.length) { throw new Error(`Not found the target "${selector}"`); } return result; } /** * Removes elements in the document * * @param {String} selector * * @return {this} */ removeContent(selector) { this.querySelectorAll(selector, document).forEach(element => element.remove() ); return this; } /** * Replace an element in the document by an element in the page * Optionally, it can execute a callback to the new inserted element * * @param {String} selector * @param {Function|undefined} callback * * @return {this} */ replaceContent(selector = 'body', callback = undefined) { const content = this.querySelector(selector); this.querySelector(selector, document).replaceWith(content); if (typeof callback === 'function') { callback(content); } return this; } /** * Appends the content of an element in the page in other element in the document * Optionally, it can execute a callback for each new inserted elements * * @param {String} selector * @param {Function|undefined} callback * * @return {this} */ appendContent(target = 'body', callback = undefined) { const content = Array.from(this.querySelector(target).childNodes); const fragment = document.createDocumentFragment(); content.forEach(item => fragment.appendChild(item)); this.querySelector(target, document).append(fragment); if (typeof callback === 'function') { content .filter(item => item.nodeType === Node.ELEMENT_NODE) .forEach(callback); } return this; } replaceNavReferences(context = 'head') { const documentContext = this.querySelector(context, document); const pageContext = this.querySelector(context); documentContext.querySelectorAll('link[rel="prev"]').forEach(link => link.remove()); documentContext.querySelectorAll('link[rel="next"]').forEach(link => link.remove()); documentContext.querySelectorAll('link[rel="parent"]').forEach(link => link.remove()); var link; link = pageContext.querySelector('link[rel="prev"]'); if (link) documentContext.append(link); link = pageContext.querySelector('link[rel="next"]'); if (link) documentContext.append(link); link = pageContext.querySelector('link[rel="parent"]'); if (link) documentContext.append(link); return this; } /** * Change the css of the current page * * @param {string} context * * @return Promise */ replaceStyles(context = 'head') { const documentContext = this.querySelector(context, document); const pageContext = this.querySelector(context); const oldLinks = Array.from( documentContext.querySelectorAll('link[rel="stylesheet"]') ); const newLinks = Array.from( pageContext.querySelectorAll('link[rel="stylesheet"]') ); oldLinks.forEach(link => { const index = newLinks.findIndex( newLink => newLink.href === link.href ); if (index === -1) { link.remove(); } else { newLinks.splice(index, 1); } }); documentContext .querySelectorAll('style') .forEach(style => style.remove()); pageContext .querySelectorAll('style') .forEach(style => documentContext.append(style)); return Promise.all( newLinks.map( link => new Promise((resolve, reject) => { link.addEventListener('load', resolve); link.addEventListener('error', reject); documentContext.append(link); }) ) ).then(() => Promise.resolve(this)); } /** * Change the scripts of the current page * * @param {string} context * * @return Promise */ replaceScripts(context = 'head') { const documentContext = this.querySelector(context, document); const pageContext = this.querySelector(context); const oldScripts = Array.from( documentContext.querySelectorAll('script') ); const newScripts = Array.from(pageContext.querySelectorAll('script')); oldScripts.forEach(script => { if (!script.src) { script.remove(); return; } const index = newScripts.findIndex( newScript => newScript.src === script.src ); if (index === -1) { script.remove(); } else { newScripts.splice(index, 1); } }); return Promise.all( newScripts.map( script => new Promise((resolve, reject) => { const scriptElement = document.createElement('script'); scriptElement.type = script.type || 'text/javascript'; scriptElement.defer = script.defer; scriptElement.async = script.async; if (script.src) { scriptElement.src = script.src; scriptElement.addEventListener('load', resolve); scriptElement.addEventListener('error', reject); documentContext.append(scriptElement); return; } scriptElement.innerText = script.innerText; documentContext.append(script); resolve(); }) ) ).then(() => Promise.resolve(this)); } }
JavaScript
class Indecision extends React.Component { constructor (props) { // Call parent class constructor super(props); // Set state variables this.state = { options: [] }; // Method Bindings this.handleAddOption = this.handleAddOption.bind(this); this.handleRemoveAll = this.handleRemoveAll.bind(this); this.handleRemoveOne = this.handleRemoveOne.bind(this); this.handlePickOne = this.handlePickOne.bind(this); } handleAddOption(option) { if(!option) { return <span><b>InvalidOption:</b> Enter a valid value to add option</span>; } else if(this.state.options.indexOf(option) > -1) { return <span><b>DuplicateOption:</b> Option already exists</span>; } else { this.setState( (prevState, props) => { return {options: prevState.options.concat([option])}; } ); } } handleRemoveAll() { this.setState( (prevState, props) => { return {options: []}; } ); } handleRemoveOne() { } handlePickOne() { const rand_idx = Math.floor(Math.random() * this.state.options.length); alert("I have selected: " + this.state.options[rand_idx]); } render() { const appTitle = "Indecision?"; const appSubTitle = "Let the machine decide for you"; return ( <div className="container w-50 shadow-lg p-2 text-center mt-4"> <Header title={appTitle} subtitle={appSubTitle} /> <hr /> <Action hasOptions={this.state.options.length > 0} handlePickOne={this.handlePickOne} /> <Options options={this.state.options} handleRemoveAll={this.handleRemoveAll} handleRemoveOne={this.handleRemoveOne} /> <AddOption handleAddOption={this.handleAddOption} /> </div> ); } }
JavaScript
class Header extends React.Component { constructor (props) { super(props); } render() { return ( <div> <h1>{this.props.title}</h1> <p className="lead">{this.props.subtitle}</p> </div> ); } }
JavaScript
class Action extends React.Component { constructor (props) { super(props); } render() { return ( <div className="d-flex justify-content-center"> <button className="btn btn-primary mb-4 w-50 shadow btn-block font-weight-bold" onClick={this.props.handlePickOne} disabled={!this.props.hasOptions}>What should I do?</button> </div> ); } }
JavaScript
class Option extends React.Component { constructor (props) { super(props); } render() { return ( <p className="font-weight-bold">{this.props.option}</p> ); } }
JavaScript
class Options extends React.Component { constructor (props) { super(props); } render() { return ( <div> <div className="d-flex flex-column justify-content-center align-items-center"> <div className="mb-2 w-25 text-center text-wrap"> { this.props.options.map((option) => <Option option={option} key={option} />) } </div> <button className="btn btn-sm btn-danger btn-block w-25 shadow mb-2" onClick={this.props.handleRemoveAll} disabled={!this.props.options.length}>Remove All</button> </div> </div> ); } }
JavaScript
class AddOption extends React.Component { constructor (props) { super(props); this.state = { inputValue: "", error: undefined }; this.formSubmitHandler = this.formSubmitHandler.bind(this); } formSubmitHandler(event) { event.preventDefault(); const entered_option = event.target.elements.option.value.trim(); const error = this.props.handleAddOption(entered_option); if(error) { this.setState( () => { return { error }; } ); } this.setState({ inputValue: "" }); } render() { return ( <div> {this.state.error && <div className="alert alert-danger p-1 mt-2">{this.state.error}</div>} <form className="form-inline justify-content-center" id="addOptionForm" onSubmit={this.formSubmitHandler}> <div className="form-row"> <div className="col"> <input className="form-control shadow" type="text" name="option" value={this.state.inputValue} onChange={e => this.setState({ inputValue: e.target.value, error: undefined })} /> </div> <div className="col"> <button className="form-control btn btn-success mb-2 shadow">Add Option</button> </div> </div> </form> </div> ); } }
JavaScript
class ConfirmResetPasswordTokenHandler extends BaseHandler { static get accessTag () { return 'web#users:confirm-reset-password' } static get validationRules () { return { body: { resetPasswordToken: new RequestRule(UserModel.schema.resetPasswordToken, { required: true }) } } } static async run (ctx) { const tokenData = await jwtHelper.verify(ctx.body.resetPasswordToken, config.token.resetPassword.secret) const tokenUserId = tokenData.sub const user = await UserDAO.baseGetById(tokenUserId) if (user.resetPasswordToken !== ctx.body.resetPasswordToken) { throw new ErrorWrapper({ ...errorCodes.WRONG_RESET_PASSWORD_TOKEN }) } return this.result({ message: 'Reset password valid' }) } }
JavaScript
class SignIn extends Component { state = { email: '', password: '', errors: {} } componentWillReceiveProps(nextProps){ if(nextProps.UI.errors){ this.setState({ errors: nextProps.UI.errors }) } } handleChange = (e) => { this.setState({ [e.target.name]: e.target.value }) } handleSubmit = (e) => { e.preventDefault() console.log(this.state) const userData = { email: this.state.email, password: this.state.password } const { history } = this.props this.props.loginUser(userData,history) } render () { if(localStorage.getItem('Token')) return <Redirect to='/'/> // const { UI: { loading, errors: { password,email } }} = this.props const { UI: { loading }} = this.props const { errors: { password,email }} = this.state const password_error = password ? ("is-invalid form-control") : ('form-control') const email_error = email ? ("is-invalid form-control") : ('form-control') const spinner = loading ? (<span className="spinner-border spinner-border-sm text-light" role="status" aria-hidden="true"></span>) : '' return ( <FormArea> <div className="container"> <form onSubmit={this.handleSubmit}> <h1 className="text-center text-warning"> - Hurry Up!</h1> <div className="form-group"> <label htmlFor="exampleInputEmail1">Email address</label> <input type="email" name="email" value={this.state.email} onChange={this.handleChange} className={email_error} id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"/> <div className="invalid-feedback">{email}</div> <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div className="form-group"> <label htmlFor="exampleInputPassword1">Password</label> <input type="password" name="password" value={this.state.password} onChange={this.handleChange} className={password_error} id="exampleInputPassword1" placeholder="Password"/> <div className="invalid-feedback">{password}</div> </div> <button type="submit" disabled={loading} className="btn btn-block btn-warning"> {spinner} Submit</button> </form> </div> </FormArea> ) } }
JavaScript
class NavigatorSeriesLabelsComponent extends SeriesLabelsComponent { constructor(configurationService) { super(configurationService); this.configurationService = configurationService; this.markAsVisible(); } }
JavaScript
class TermBase { constructor(sendRequest, query, legalMethods) { this._sendRequest = sendRequest this._query = query this._legalMethods = legalMethods } toString() { let string = `Collection('${this._query.collection}')` if (this._query.find) { string += `.find(${JSON.stringify(this._query.find)})` } if (this._query.find_all) { string += `.findAll(${JSON.stringify(this._query.find_all)})` } if (this._query.order) { string += `.order(${JSON.stringify(this._query.order[0])}, ` + `${JSON.stringify(this._query.order[1])})` } if (this._query.above) { string += `.above(${JSON.stringify(this.query.above[0])}, ` + `${JSON.stringify(this.query.above[1])})` } if (this._query.below) { string += `.below(${JSON.stringify(this.query.below[0])}, ` + `${JSON.stringify(this.query.below[1])})` } if (this._query.limit) { string += `.limit(${JSON.stringify(this._query.limit)})` } return string } // Returns a sequence of the result set. Every time it changes the // updated sequence will be emitted. If raw change objects are // needed, pass the option 'rawChanges: true'. An observable is // returned which will lazily emit the query when it is subscribed // to watch({ rawChanges = false } = {}) { const query = watchRewrites(this, this._query) const raw = this._sendRequest('subscribe', query) if (rawChanges) { return raw } else { return makePresentable(raw, this._query) } } // Grab a snapshot of the current query (non-changefeed). Emits an // array with all results. An observable is returned which will // lazily emit the query when subscribed to fetch() { const raw = this._sendRequest('query', this._query).map(val => { delete val.$hz_v$ return val }) if (this._query.find) { return raw.defaultIfEmpty(null) } else { return raw.toArray() } } findAll(...fieldValues) { checkIfLegalToChain.call(this, 'findAll') checkArgs('findAll', arguments, { maxArgs: 100 }) return new FindAll(this._sendRequest, this._query, fieldValues) } find(idOrObject) { checkIfLegalToChain.call(this, 'find') checkArgs('find', arguments) return new Find(this._sendRequest, this._query, idOrObject) } order(fields, direction = 'ascending') { checkIfLegalToChain.call(this, 'order') checkArgs('order', arguments, { minArgs: 1, maxArgs: 2 }) return new Order(this._sendRequest, this._query, fields, direction) } above(aboveSpec, bound = 'closed') { checkIfLegalToChain.call(this, 'above') checkArgs('above', arguments, { minArgs: 1, maxArgs: 2 }) return new Above(this._sendRequest, this._query, aboveSpec, bound) } below(belowSpec, bound = 'open') { checkIfLegalToChain.call(this, 'below') checkArgs('below', arguments, { minArgs: 1, maxArgs: 2 }) return new Below(this._sendRequest, this._query, belowSpec, bound) } limit(size) { checkIfLegalToChain.call(this, 'limit') checkArgs('limit', arguments) return new Limit(this._sendRequest, this._query, size) } }
JavaScript
class Footer extends Component { render() { return ( <footer className={`pt-4 ${!this.props.noMargin && 'mt-5'} pt-md-5 border-top`}> <div className="row"> <div className="col-12 col-md"> <img className="mb-2" src={Logo} alt="" width="24" height="24" /> <small className="d-block mb-3 text-muted">&copy; 2017-2018</small> </div> <div className="col-6 col-md"> <h5>Sitemap</h5> <ul className="list-unstyled text-small"> <li><Link className="text-muted" to="/pricing">Pricing</Link></li> <li><Link className="text-muted" to="/videos">Videos</Link></li> <li><Link className="text-muted" to="/login">Login</Link></li> <li><Link className="text-muted" to="/signup">Sign Up</Link></li> <li><Link className="text-muted" to="/cookie">Cookie Policy</Link></li> </ul> </div> <div className="col-6 col-md"> <h5>Resources</h5> <ul className="list-unstyled text-small"> <li><Link className="text-muted" to="/support">Support</Link></li> <li><Link className="text-muted" to="/legal">Legal</Link></li> <li><Link className="text-muted" to="/legal">Privacy</Link></li> <li><Link className="text-muted" to="/terms">Terms of Service</Link></li> <li><Link className="text-muted" target="_blank" to="/sitemap.xml">Sitemap</Link></li> </ul> </div> </div> </footer> ); } }
JavaScript
class UserInteractionMetricsResponse { /** * Create a UserInteractionMetricsResponse. * @member {boolean} [lessThan100Apps] check if the user has less than 100 * apps. * @member {boolean} [hasMoreThan1Release] check if the user's whole apps has * more than 1 releases. */ constructor() { } /** * Defines the metadata of UserInteractionMetricsResponse * * @returns {object} metadata of UserInteractionMetricsResponse * */ mapper() { return { required: false, serializedName: 'UserInteractionMetricsResponse', type: { name: 'Composite', className: 'UserInteractionMetricsResponse', modelProperties: { lessThan100Apps: { required: false, serializedName: 'less_than_100_apps', type: { name: 'Boolean' } }, hasMoreThan1Release: { required: false, serializedName: 'has_more_than_1_release', type: { name: 'Boolean' } } } } }; } }
JavaScript
class FileTreeSidebarFilterComponent extends _react.default.Component { render() { const { filter, found } = this.props; const classes = (0, (_classnames || _load_classnames()).default)({ 'nuclide-file-tree-filter': true, show: Boolean(filter && filter.length), 'not-found': !found }); const text = `search for: ${filter}`; return _react.default.createElement( 'div', { className: classes }, text ); } }
JavaScript
class SignUp extends React.Component { constructor(props) { super(props); this.state = { waiver: "Loading...", membership: "Loading...", waiverOpen: false, membershipOpen: false, dateOfBirth: new Date(), agreedLiabilityWaiver: false, agreedMembershipContract: false, registered: false, signupBtnIsHovered: false } this.handleSignupBtnHover = this.handleSignupBtnHover.bind(this); } async componentDidMount() { const waiver = await axios.get(process.env.GATSBY_CMS_HOST + "/liability-waiver"); this.setState({waiver: marked(waiver['data']['content'])}); const membership = await axios.get(process.env.GATSBY_CMS_HOST + "/membership-agreement"); this.setState({membership: marked(membership['data']['content'])}); } handleSignupBtnHover(){ this.setState(prevState => ({ signupBtnIsHovered: !prevState.signupBtnIsHovered })); } validationSchema = Yup.object().shape({ nameFirst: Yup.string() .required("Required"), nameLast: Yup.string() .required("Required"), sex: Yup.string() .ensure() .required("Required"), username: Yup.string() .required("Required"), email: Yup.string() .email("Invalid Email") .required("Required"), password: Yup.string() .required("Required"), phoneNumber: phoneValidation, dateOfBirth: Yup.date() .required("Required"), address: addressValidation, studentStatus: Yup.string() .ensure() .required("Required"), studentNumber: Yup.number() .positive("Student Number must be positive") .integer("Student Number must be an integer") .required("Required"), emergencyContact: Yup.object().shape({ name: Yup.string() .required("Required"), phoneNumber: phoneValidation, address: addressValidation }), medicalDetails: Yup.string(), agreedLiabilityWaiver: Yup.boolean() .oneOf([true], "You must agree to the Liability Waiver"), agreedMembershipContract: Yup.boolean() .oneOf([true], "You must agree to the Membership Agreement") }); //Function to handle login form submission handleSubmit = async (data, actions) => { //Attempt to register a new user const response = await authenticationService.register(data); //Check register request was successful if (response === true) { this.setState({ registered: true }); } else { actions.setFieldError('general', response); } actions.setSubmitting(false); } //Simple Sign Up form render() { if (this.state.registered) { return ( <Redirect noThrow to="/login" /> ) } else { return ( <div className="content-full-width form-container"> <MuiPickersUtilsProvider utils={DateFnsUtils}> <Formik initialValues={{ dateOfBirth: new Date(), agreedLiabilityWaiver: false, agreedMembershipContract: false }} validationSchema={this.validationSchema} onSubmit={this.handleSubmit} > {(formProps) => ( <Form> <h2>Your Details</h2> <label htmlFor="nameFirst">First Name</label> <Field name="nameFirst" className="text-field-short" /> <ErrorMessage name="nameFirst" /> <br /> <label htmlFor="nameLast">Last Name</label> <Field name="nameLast" className="text-field-short" /> <ErrorMessage name="nameLast" /> <br /> <label htmlFor="sex">Sex</label> <Select name="sex" options={userService.sexes} /> <ErrorMessage name="sex" /> <br /> <label htmlFor="username">Username</label> <Field name="username" className="text-field-short" /> <ErrorMessage name="username" /> <br /> <label htmlFor="email">Email</label> <Field name="email" type="email" className="text-field-short" /> <ErrorMessage name="email" /> <br /> <label htmlFor="password">Password</label> <Field name="password" type="password" className="text-field-short" /> <ErrorMessage name="password" /> <br /> <Phone name="phoneNumber" /> <label htmlFor="dateOfBirth">Date of Birth</label> <Field name="dateOfBirth" component={DatePicker} className="date-picker" /> <ErrorMessage name="dateOfBirth" /> <br /> <Address name="address" /> <label htmlFor="studentStatus">Student Status</label> <Select name="studentStatus" options={userService.studentStatuses} /> <ErrorMessage name="studentStatus" /> <br /> {/*TODO: number?*/} <label htmlFor="studentNumber">Student Number</label> <Field name="studentNumber" className="text-field-short" /> <ErrorMessage name="studentNumber" /> <br /> <label htmlFor="medicalDetails">Medical Details</label> <ErrorMessage name="medicalDetails" /> <br /> <Field name="medicalDetails" as="textarea" className="text-field-short" /> <br /> <h2>Emergency Contact</h2> <label htmlFor="emergencyContact.name">Contact Name</label> <Field name="emergencyContact.name" className="text-field-short" /> <ErrorMessage name="emergencyContact.name" /> <br /> <Phone name="emergencyContact.phoneNumber" /> <Address name="emergencyContact.address" /> <h2>Membership</h2> <label htmlFor="agreedLiabilityWaiver">Liability Waiver</label> <button type="button" onClick={() => this.setState({ waiverOpen: true })}>View Waiver</button> <Modal open={this.state.waiverOpen} > <div className="modal"> <div className="modal-header"> <button type="button" onClick={() => this.setState({ waiverOpen: false })}>Close Waiver</button> </div> <div className="modal-text" dangerouslySetInnerHTML={{ __html: this.state.waiver }} /> <div className="accept-terms-field-container"> <Field name="agreedLiabilityWaiver" type="checkbox" /> <label htmlFor="agreedLiabilityWaiver" className="label-inline"><span className="highlight">Accept Waiver</span></label> </div> <div className="modal-header"> <button className="btn" type="button" onClick={() => this.setState({ waiverOpen: false })}>Close Waiver</button> </div> </div> </Modal> <ErrorMessage name="agreedLiabilityWaiver" /> <br /> <label htmlFor="agreedMembershipContract">Membership agreement</label> <button type="button" onClick={() => this.setState({ membershipOpen: true })}>View Membership Agreement</button> <Modal open={this.state.membershipOpen} > <div className="modal"> <div className="modal-header"> <button type="button" onClick={() => this.setState({ membershipOpen: false })}>Close Membership Agreement</button> </div> <div className="modal-text" dangerouslySetInnerHTML={{ __html: this.state.membership }} /> <div className="accept-terms-field-container"> <Field name="agreedMembershipContract" type="checkbox" /> <label htmlFor="agreedMembershipContract" className="label-inline"><span className="highlight">Accept Membership Agreement</span></label> </div> <div className="modal-header"> <button className="btn" type="button" onClick={() => this.setState({ membershipOpen: false })}>Close Membership Agreement</button> </div> </div> </Modal> <ErrorMessage name="agreedMembershipContract" /> <br /> { formProps.isSubmitting ? <LinearProgress /> : <div style={{color: "red"}}>{formProps.errors.general}</div> } <button className="btn" disabled={formProps.isSubmitting} onClick={formProps.handleSubmit} > Sign Up </button> </Form> )} </Formik> </MuiPickersUtilsProvider> </div> ) } } }
JavaScript
class ShowProfile extends React.Component { constructor(props) { super(props); this.state = { name: null } this.styles = { width: 140, height: 140 } this.handleUpdateProfile = this.handleUpdateProfile.bind(this); this.getName = this.getName.bind(this); } componentDidMount() { this.getName(); } getName() { this.setState({ name: jwt.decode(this.props.getToken()).name }); } handleUpdateProfile(data) { axios.put('/api/profile', data, { headers: {'Authorization': this.props.getToken()} }) .then((res) => { this.props.onLogin(res.data.token); this.getName(); }).catch((err) => console.log(err)); } render() { return ( <div className='profileBox'> <div className="profileName"> <h1>{this.state.name}</h1> </div> <Avatar style={this.styles} backgroundColor='none' alt="User Picture" src="https://i.imgur.com/katTIZJ.png" /> <div> { (this.props.editProfile) ? <ProfileForm getToken={this.props.getToken} handleUpdateProfile={this.handleUpdateProfile} /> : null } </div> </div> ); }; }
JavaScript
class Address { /** * Constructor. * * @param {number} id - The row ID of the Address. * @param {string} name - Name of the street. * @param {number} number - House number. * @param {string} letter - Apartment number. * @param {string} zip - Postal code. * @param {string} area - Postal area. * */ constructor(id, name, number, letter, zip, area){ this._id = id; this._name = name; this._number = number; this._letter = letter; this._zip = zip; this._area = area.toUpperCase(); } /** * Get ID. * @return {number} - The address ID. * */ get id() { return this._id; } /** * Set ID. * @param {number} value - The address ID. * */ set id(value) { this._id = value; } /** * Get name. * @return {string} - The street name. * */ get name() { return this._name; } /** * Set name. * @param {string} value - The street name. * */ set name(value) { this._name = value; } /** * Get number. * @return {number} - The house number. * */ get number() { return this._number; } /** * Set number. * @param {number} value - The house number. * */ set number(value) { this._number = value; } /** * Get letter. * @return {string} - The apartment letter. * */ get letter() { return this._letter; } /** * Set letter. * @param {string} value - The apartment letter. * */ set letter(value) { this._letter = value; } /** * Get ZIP. * @return {string} - The ZIP code. * */ get zip() { return this._zip; } /** * Set ZIP. * @param {string} value - The ZIP code. * */ set zip(value) { this._zip = value; } /** * Get area. * @return {string} - The area name. * */ get area() { return this._area; } /** * Set area. * @param {string} value - The area name. * */ set area(value) { this._area = value; } /** * Get short. * @return {string} - The short address, containing the name, number, and letter. * */ get short() { return this._name + ' ' + this._number + this._letter; } }
JavaScript
class AuthorizedImage extends AuthorizedFetchMixin(PolymerElement) { static get template() { return html` <style> /* Fit this component into the the parent */ :host { display: inline-block; overflow: hidden; position: relative; } /* Fit the image into this space */ iron-image { width: 100%; height: 100%; vertical-align: top; } </style> <iron-image id="image" alt="{{alt}}" crossorigin="{{crossorigin}}" error="{{_ironImageError}}" fade="{{fade}}" height="{{height}}" loaded="{{loaded}}" loading="{{loading}}" placeholder="[[_computePlaceholder(src, placeholder)]]" position="{{position}}" preload="{{preload}}" prevent-load="[[_computePreventLoad(preventLoad, _displayed)]]" sizing="{{sizing}}" src="[[_computeSrc(src, _wasVisible, _displayed, token)]]" width="{{width}}" ></iron-image>`; } static get is() { return 'authorized-image'; } static get properties() { return { _displayed: Object, _ironImageError: Boolean, _supportsIntersectionObserver: { readOnly: true, type: Boolean, value: typeof IntersectionObserver === 'function', }, /** * Whether this image was visible according to the intersection observer. * * This value is only valid when the component is "ready" and _supportsIntersectionObserver is true. */ _visible: Boolean, /** * Whether this image was ever visible. * This property is used to delay the internal "fetch" request for invisible images, but avoid * extra _computeSrc calls when this image is hidden after it was visible once. */ _wasVisible: { computed: '_computeWasVisible(_wasVisible, _supportsIntersectionObserver, _visible)' }, alt: String, crossorigin: String, error: { computed: '_computeError(_ironImageError, _displayed)', notify: true, readOnly: true, reflectToAttribute: true, type: Boolean, }, fade: Boolean, height: Number, loaded: { notify: true, readOnly: true, type: Boolean, }, loading: { notify: true, readOnly: true, type: Boolean, }, placeholder: String, position: String, preload: Boolean, preventLoad: Boolean, sizing: String, src: String, width: Number, token: String, // eslint-disable-line sort-keys mode: { // eslint-disable-line sort-keys type: String, value: 'cors', }, }; } ready() { super.ready(); // Register an "intersection observer" to learn when this element is actually becoming // visible. // If the browser doesn't support this functionality we rely on the default value. // Observe mutations to the parent element that affect us if (this._supportsIntersectionObserver) { this._observer = new IntersectionObserver(entries => { // eslint-disable-line no-unused-vars // See https://stackoverflow.com/a/38873788/196315 // XXX: Can we instead look at the entries, specifically 'isIntersecting'? this._visible = Boolean(this.offsetHeight || this.offsetWidth || this.getClientRects().length > 0); }); this._observer.observe(this); } } _computeWasVisible(wasVisible, supportsIntersectionObserver, visible) { // If the element was visible before do no longer change. if (wasVisible) { return wasVisible; } // If the browser does not support intersection observers assume the element is // visible. if (!supportsIntersectionObserver) { return true; } // Otherwise: Check the property that will be set by the intersection observer. return visible; } _computeError(ironImageError, displayed) { return Boolean(ironImageError) || Boolean(displayed && displayed.dataUrl === ''); } _computeSrc(src, wasVisible, displayed, token) { // Use the dataUrl if the src was fetched already earlier // In case the image wasn't loaded and the token changed, we try to fetch again to see if the image loads now. if (displayed && displayed.src === src && (displayed.dataUrl || displayed.token === token)) { return displayed.dataUrl; } // Start with a return value of '', which iron-image treats as "nothing to do" let result = ''; if (src && wasVisible) { // Set base to support relative URLs const srcUrl = new URL(src, window.location); if (srcUrl.protocol === 'data:') { // Data URL, we can use that directly. this._displayed = this._fetched(src, src, token); result = src; } else if (!token) { // No token, so no need to go through fetch. // This means however that `img-src` in the CSP must be set for these. // XXX: It is possible that this observer is called before the `token` property is initialized though, // in which case setting the result here will lead to problems if the image hasn't been fetched before. // These problems will get cured as soon as the token property gets set though. // If we're "lucky" and the browser has the image cached already we save one async cycle. this._displayed = this._fetched(src, src, token); result = src; } else { // Starting fetching content this.fetchDataUrl(src, token).then(fetched => { // Update the _displayed property with the result of fetching, as long as the value is still "current" // and the change would not be a noop (dataUrl, src, or token must have actually changed) if (!this._displayed || this._isChanged(this._displayed, fetched)) { this._displayed = fetched; } }); } } return result; } _computePreventLoad(preventLoad, displayed) { // Prevent loading when either the user requested that, or when we cannot actually display things. if (preventLoad) { return true; } return Boolean(displayed && displayed.dataUrl === ''); } _computePlaceholder(src, placeholder) { // Only use the placeholder when we do not have a src at all if (!src) { return placeholder; } return undefined; } _isChanged(displayed, fetched) { return displayed.src !== fetched.src || displayed.token !== fetched.token || displayed.dataUrl !== fetched.dataUrl; } }
JavaScript
class ValidationError extends ExtendableError { /** * Create a new ValidationError. */ constructor (message = 'Provided object was invalid for the recieving component.') { super(message) } }
JavaScript
class BinaryHeap { /** * @param {Array} list - an array from which binary heap will be built */ constructor(list) { this.length = 0; if (Array.isArray(list)) { this.buildFromArray(list); } else { this._initList(); } } _initList() { this.list = [0]; } /** * Percolate the element with given index upon binary tree * @param {Number} index - index of current element */ _percolateUp(index) { while (Math.floor(index / 2) > 0) { var parentIndex = Math.floor(index / 2); // if parent node is less then current node if (this.list[index] < this.list[parentIndex]) { var tmp = this.list[parentIndex]; // then swap current node this its parent this.list[parentIndex] = this.list[index]; this.list[index] = tmp; } index = parentIndex; } } /** * Percolate the element with given index down binary tree * @param {Number} index - index of current element */ _percolateDown(index) { while (index * 2 <= this.length) { var minChildIndex = this._minChildIndex(index); // If parent node greater then min of children // then swap parent with that child if (this.list[index] > this.list[minChildIndex]) { var tmp = this.list[index]; this.list[index] = this.list[minChildIndex]; this.list[minChildIndex] = tmp; } index = minChildIndex; } } /** * Get index of the smallest children for given parent index * @param {Number} parentIndex * @return {Number} */ _minChildIndex(parentIndex) { if (parentIndex * 2 + 1 > this.length) { // there is no right child // so return index if left child return parentIndex * 2; } else { if (this.list[parentIndex * 2] < this.list[parentIndex * 2 + 1]) { // left child is less then right one // return index of left child return parentIndex * 2 } else { // right child is less then left one // return index of right child return parentIndex * 2 + 1; } } } /** * Add new item to the heap * @param {Number} item */ push(item) { this.list.push(item); this.length++; this._percolateUp(this.length); } /** * Return last (the smallest of the largest) item of the heap * @return {Number} */ pop() { var result = this.list[1]; this.list[1] = this.list[this.length] this.length--; this.list.pop(); this._percolateDown(1) return result; } /** * Build binary heap from given array of numbers * @param {Array} list */ buildFromArray(list) { var length = list.length, middleIndex = Math.floor(length / 2); this._initList(); this.length = length; this.list = this.list.concat(list); while (middleIndex > 0) { this._percolateDown(middleIndex); middleIndex--; } } }
JavaScript
class BinaryHeapStore extends BinaryHeap { _initList() { this.list = [[0, 0]]; } /** * Percolate the element with given index upon binary tree * @param {Number} index - index of current element */ _percolateUp(index) { while (Math.floor(index / 2) > 0) { var parentIndex = Math.floor(index / 2); // if parent node is less then current node if (this.list[index][0] < this.list[parentIndex][0]) { var tmp = this.list[parentIndex]; // then swap current node this its parent this.list[parentIndex] = this.list[index]; this.list[index] = tmp; } index = parentIndex; } } /** * Percolate the element with given index down binary tree * @param {Number} index - index of current element */ _percolateDown(index) { while (index * 2 <= this.length) { var minChildIndex = this._minChildIndex(index); // If parent node greater then min of children // then swap parent with that child if (this.list[index][0] > this.list[minChildIndex][0]) { var tmp = this.list[index]; this.list[index] = this.list[minChildIndex]; this.list[minChildIndex] = tmp; } index = minChildIndex; } } /** * Get index of the smallest children for given parent index * @param {Number} parentIndex * @return {Number} */ _minChildIndex(parentIndex) { if (parentIndex * 2 + 1 > this.length) { // there is no right child // so return index if left child return parentIndex * 2; } else { if (this.list[parentIndex * 2][0] < this.list[parentIndex * 2 + 1][0]) { // left child is less then right one // return index of left child return parentIndex * 2 } else { // right child is less then left one // return index of right child return parentIndex * 2 + 1; } } } /** * */ decreaseItemValue(item, value) { var found = false, index = 1, indexOfItem = 0; // search the index of given item while (!found && index <= this.length) { if (this.list[index][1] == item) { indexOfItem = index; found = true; } else { index++; } } // in case it has been found if (indexOfItem > 0) { this.list[indexOfItem] = [value, this.list[index][1]]; this._percolateUp(indexOfItem); } } }
JavaScript
class App extends Component { constructor(props) { super(props); } componentDidMount() { SplashScreen.hide(); /**codePush.sync({ updateDialog: false, installMode: codePush.InstallMode.IMMEDIATE }).then( () => { SplashScreen.hide(); }); */ } render() { return ( <View style={{flex:1}}> <Router /> <MessageBar /> </View> ); } }
JavaScript
class Queue { constructor() { this.queue = []; this.pending = false; } /** * Add a transfer to the queue. * * @param {Function} start - start the transfer. */ push(start) { return new Promise((resolve, reject) => { this.queue.push({ start, resolve, reject }); this.pop(); }); } /** Run the next transfer in queue. */ pop() { if(this.pending) return; const transfer = this.queue.shift(); if(!transfer) return; this.pending = true; transfer.start().then((value) => { this.pending = false; transfer.resolve(value); this.pop(); }) .catch((error) => { this.pending = false; transfer.reject(error); this.pop(); }); } }
JavaScript
class DataService extends EventEmitter { /** * Instantiate a new DataService object. * * @constructor * @param {Object} model - The Connection model or object. */ constructor(model) { super(); // Stores the most recent topology description from // the server's SDAM events: // https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring-monitoring.rst#events this.lastSeenTopology = null; this.client = null; const NativeClient = require('./native-client'); this.client = new NativeClient(model) .on('status', (evt) => this.emit('status', evt)) .on('serverDescriptionChanged', (evt) => this.emit('serverDescriptionChanged', evt)) .on('serverOpening', (evt) => this.emit('serverOpening', evt)) .on('serverClosed', (evt) => this.emit('serverClosed', evt)) .on('topologyOpening', (evt) => this.emit('topologyOpening', evt)) .on('topologyClosed', (evt) => this.emit('topologyClosed', evt)) .on('topologyDescriptionChanged', (evt) => { this.lastSeenTopology = evt.newDescription; this.emit('topologyDescriptionChanged', evt); }); } getConnectionOptions() { return this.client.connectionOptions; } /** * Get the kitchen sink information about a collection. * * @param {String} ns - The namespace. * @param {object} options - The options. * @param {Function} callback - The callback. */ collection(ns, options, callback) { this.client.collectionDetail(ns, callback); } /** * Get the stats for a collection. * * @param {String} databaseName - The database name. * @param {String} collectionName - The collection name. * @param {Function} callback - The callback. */ collectionStats(databaseName, collectionName, callback) { this.client.collectionStats(databaseName, collectionName, callback); } /** * Execute a command. * * @param {String} databaseName - The db name. * @param {Object} comm - The command. * @param {Function} callback - The callback. */ command(databaseName, comm, callback) { this.client.command(databaseName, comm, callback); } /** * Is the data service allowed to perform write operations. * * @returns {Boolean} If the data service is writable. */ isWritable() { return this.client.isWritable; } /** * Is the data service connected to a mongos. * * @returns {Boolean} If the data service is connected to a mongos. */ isMongos() { return this.client.isMongos; } /** * Executes a buildInfo command on the currently connected instance. * * @param {Function} callback - The callback. */ buildInfo(callback) { this.client.buildInfo(callback); } /** * Executes a hostInfo command on the currently connected instance. * * @param {Function} callback - The callback. */ hostInfo(callback) { this.client.hostInfo(callback); } /** * Executes a connectionStatus command on the currently connected instance. * * @param {Function} callback - The callback. */ connectionStatus(callback) { this.client.connectionStatus(callback); } /** * Executes a usersInfo command on the provided authenticationDatabase. * * @param {String} authenticationDatabase - The database name. * @param {object} options - Options passed to NativeClient.usersInfo method. * @param {Function} callback - The callback. */ usersInfo(authenticationDatabase, options, callback) { this.client.usersInfo(authenticationDatabase, options, callback); } /** * List all collections for a database. * * @param {String} databaseName - The database name. * @param {Object} filter - The filter. * @param {Function} callback - The callback. */ listCollections(databaseName, filter, callback) { this.client.listCollections(databaseName, filter, callback); } /** * List all databases on the currently connected instance. * * @param {Function} callback - The callback. */ listDatabases(callback) { this.client.listDatabases(callback); } /** * Connect to the server. * * @param {function} done - The callback function. */ connect(done) { this.client.connect((err) => { if (err) { return done(err); } done(null, this); this.emit('readable'); }); } /** * Count the number of documents in the collection. * * @param {string} ns - The namespace to search on. * @param {object} options - The query options. * @param {function} callback - The callback function. */ estimatedCount(ns, options, callback) { this.client.estimatedCount(ns, options, callback); } /** * Count the number of documents in the collection for the provided filter * and options. * * @param {string} ns - The namespace to search on. * @param {object} options - The query options. * @param {function} callback - The callback function. */ count(ns, filter, options, callback) { this.client.count(ns, filter, options, callback); } /** * Creates a collection * * @param {String} ns - The namespace. * @param {Object} options - The options. * @param {Function} callback - The callback. */ createCollection(ns, options, callback) { this.client.createCollection(ns, options, callback); } /** * Creates an index * * @param {String} ns - The namespace. * @param {Object} spec - The index specification. * @param {Object} options - The options. * @param {Function} callback - The callback. */ createIndex(ns, spec, options, callback) { this.client.createIndex(ns, spec, options, callback); } /** * Get the kitchen sink information about a database and all its collections. * * @param {String} name - The database name. * @param {object} options - The query options. * @param {Function} callback - The callback. */ database(name, options, callback) { this.client.databaseDetail(name, callback); } /** * Delete a single document from the collection. * * @param {String} ns - The namespace. * @param {Object} filter - The filter. * @param {Object} options - The options. * @param {Function} callback - The callback. */ deleteOne(ns, filter, options, callback) { this.client.deleteOne(ns, filter, options, callback); } /** * Deletes multiple documents from a collection. * * @param {String} ns - The namespace. * @param {Object} filter - The filter. * @param {Object} options - The options. * @param {Function} callback - The callback. */ deleteMany(ns, filter, options, callback) { this.client.deleteMany(ns, filter, options, callback); } /** * Disconnect the service. * @param {Function} callback - The callback. */ disconnect(callback) { this.client.disconnect(callback); } /** * Drops a collection from a database * * @param {String} ns - The namespace. * @param {Function} callback - The callback. */ dropCollection(ns, callback) { this.client.dropCollection(ns, callback); } /** * Drops a database * * @param {String} name - The database name. * @param {Function} callback - The callback. */ dropDatabase(name, callback) { this.client.dropDatabase(name, callback); } /** * Drops an index from a collection * * @param {String} ns - The namespace. * @param {String} name - The index name. * @param {Function} callback - The callback. */ dropIndex(ns, name, callback) { this.client.dropIndex(ns, name, callback); } /** * Execute an aggregation framework pipeline with the provided options on the * collection. * * * @param {String} ns - The namespace to search on. * @param {Object} pipeline - The aggregation pipeline. * @param {Object} options - The aggregation options. * @param {Function} callback - The callback function. * @return {(null|AggregationCursor)} */ aggregate(ns, pipeline, options, callback) { return this.client.aggregate(ns, pipeline, options, callback); } /** * Find documents for the provided filter and options on the collection. * * @param {String} ns - The namespace to search on. * @param {Object} filter - The query filter. * @param {Object} options - The query options. * @param {Function} callback - The callback function. */ find(ns, filter, options, callback) { this.client.find(ns, filter, options, callback); } /** * Fetch documents for the provided filter and options on the collection. * * @param {String} ns - The namespace to search on. * @param {Object} filter - The query filter. * @param {Object} options - The query options. * * @returns {Cursor} The cursor. */ fetch(ns, filter, options) { return this.client.fetch(ns, filter, options); } /** * Find one document and replace it with the replacement. * * @param {String} ns - The namespace to search on. * @param {Object} filter - The filter. * @param {Object} replacement - The replacement doc. * @param {Object} options - The query options. * @param {Function} callback - The callback. */ findOneAndReplace(ns, filter, replacement, options, callback) { this.client.findOneAndReplace(ns, filter, replacement, options, callback); } /** * Find one document and update it with the update operations. * * @param {String} ns - The namespace to search on. * @param {Object} filter - The filter. * @param {Object} update - The update operations doc. * @param {Object} options - The query options. * @param {Function} callback - The callback. */ findOneAndUpdate(ns, filter, update, options, callback) { this.client.findOneAndUpdate(ns, filter, update, options, callback); } /** * Returns explain plan for the provided filter and options on the collection. * * @param {String} ns - The namespace to search on. * @param {Object} filter - The query filter. * @param {Object} options - The query options. * @param {Function} callback - The callback function. */ explain(ns, filter, options, callback) { this.client.explain(ns, filter, options, callback); } /** * Get the indexes for the collection. * * @param {String} ns - The collection namespace. * @param {Object} options - The options (unused). * @param {Function} callback - The callback. */ indexes(ns, options, callback) { this.client.indexes(ns, callback); } /** * Get the current instance details. * * @param {Object} options - The options. * @param {Function} callback - The callback function. */ instance(options, callback) { this.client.instance(callback); } /** * Insert a single document into the database. * * @param {String} ns - The namespace. * @param {Object} doc - The document to insert. * @param {Object} options - The options. * @param {Function} callback - The callback. */ insertOne(ns, doc, options, callback) { this.client.insertOne(ns, doc, options, callback); } /** * Inserts multiple documents into the collection. * * @param {String} ns - The namespace. * @param {Array} docs - The documents to insert. * @param {Object} options - The options. * @param {Function} callback - The callback. */ insertMany(ns, docs, options, callback) { this.client.insertMany(ns, docs, options, callback); } /** * Inserts multiple documents into the collection. * * @param {String} ns - The namespace. * @param {Array} docs - The documents to insert. * @param {Object} options - The options. * * @returns {Promise} The promise. */ putMany(ns, docs, options) { return this.client.putMany(ns, docs, options); } /** * Update a collection. * * @param {String} ns - The namespace. * @param {Object} flags - The flags. * @param {Function} callback - The callback. */ updateCollection(ns, flags, callback) { this.client.updateCollection(ns, flags, callback); } /** * Update a single document in the collection. * * @param {String} ns - The namespace. * @param {Object} filter - The filter. * @param {Object} update - The update. * @param {Object} options - The options. * @param {Function} callback - The callback. */ updateOne(ns, filter, update, options, callback) { this.client.updateOne(ns, filter, update, options, callback); } /** * Updates multiple documents in the collection. * * @param {String} ns - The namespace. * @param {Object} filter - The filter. * @param {Object} update - The update. * @param {Object} options - The options. * @param {Function} callback - The callback. */ updateMany(ns, filter, update, options, callback) { this.client.updateMany(ns, filter, update, options, callback); } /** * Returns the results of currentOp. * * @param {Boolean} includeAll - if true also list currently idle operations in the result. * @param {Function} callback - The callback. */ currentOp(includeAll, callback) { this.client.currentOp(includeAll, callback); } /** * Returns the most recent topology description from the server's SDAM events. * https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring-monitoring.rst#events * * @returns {null | TopologyDescription} If the data service is connected to a mongos. */ getLastSeenTopology() { return this.lastSeenTopology; } /** * Returns the result of serverStats. * * @param {function} callback - the callback. */ serverstats(callback) { this.client.serverStats(callback); } /** * Get the collection stats plus sharding distribution information. This merges * the shard distribution statistics under the "shards" array that was a result * of the collStats command. * * @param {String} ns - The namespace. * @param {Function} callback - The callback. */ shardedCollectionDetail(ns, callback) { this.client.shardedCollectionDetail(ns, callback); } /** * Returns the result of top. * * @param {function} callback - the callback. */ top(callback) { this.client.top(callback); } /** * Create a new view. * * @param {String} name - The collectionName for the view. * @param {String} sourceNs - The source `<db>.<collectionOrViewName>` for the view. * @param {Array} pipeline - The agggregation pipeline for the view. * @param {Object} options - Options e.g. collation. * @param {Function} callback - The callback. * @option {Object} collation */ createView(name, sourceNs, pipeline, options, callback) { this.client.createView(name, sourceNs, pipeline, options, callback); } /** * Update an existing view. * * @param {String} name - The collectionName for the view. * @param {String} sourceNs - The source `<db>.<collectionOrViewName>` for the view. * @param {Array} pipeline - The agggregation pipeline for the view. * @param {Object} options - Options e.g. collation. * @param {Function} callback - The callback. * @option {Object} collation */ updateView(name, sourceNs, pipeline, options, callback) { this.client.updateView(name, sourceNs, pipeline, options, callback); } /** * Convenience for dropping a view as a passthrough to `dropCollection()`. * * @param {String} ns - The namespace. * @param {Function} callback - The callback. */ dropView(ns, callback) { this.client.dropView(ns, callback); } /** * Sample documents from the collection. * * @param {String} ns * - The namespace to sample. * @param {Object} aggregationOptions * - The sampling options. * @param {Object} aggregationOptions.query * - The aggregation match stage. Won't be used if empty. * @param {Object} aggregationOptions.size * - The size option for the match stage. Default to 1000 * @param {Object} aggregationOptions.fields * - The fields for the project stage. Won't be used if empty. * @param {Object} [options={}] * - Driver options (ie. maxTimeMs, session, batchSize ...) * @return {Cursor} An AggregationCursor. */ sample(...args) { return this.client.sample(...args); } /** * Create a ClientSession that can be passed to commands. */ startSession(...args) { return this.client.startSession(...args); } /** * Kill a session and terminate all in progress operations. * @param {ClientSession} clientSession * - a ClientSession (can be created with startSession()) */ killSession(...args) { return this.client.killSession(...args); } isConnected() { return this.client.isConnected(); } /** * When Node supports ES6 default values for arguments, this can go away. * * @param {Array} args - The route arguments. * @param {Object} options - The options passed to the method. * @param {Function} callback - The callback. * * @return {Array} The generate arguments. */ _generateArguments(args, options, callback) { options = options || {}; if (typeof options === 'function') { callback = options; options = {}; } args.push.apply(args, [options, callback]); return args; } }
JavaScript
class User extends Component { constructor(props){ super(props); this.state = { usuario: null } } getUser = () => { API.get("usuarios/" + this.props.match.params.id).then(response => { this.setState({usuario: response.data}); console.log(response.data); }).catch(error => { console.log(error); }) } componentDidMount() { this.getUser(); } render() { //const user = this.state.usuarios.find( user => user.id.toString() === this.props.match.params.id ); //const user = usersData.find( user => user.id.toString() === this.props.match.params.id) const userDetails = this.state.usuario ? Object.entries(this.state.usuario) : [['id', (<span><i className="text-muted icon-ban"></i> Not found</span>)]] return ( <div className="animated fadeIn"> <Row> <Col lg={6}> <Card> <CardHeader> <strong><i className="icon-info pr-1"></i>User id: {this.props.match.params.id}</strong> </CardHeader> <CardBody> <Table responsive striped hover> <tbody> { userDetails.map(([key, value]) => { return ( <tr key={key}> <td style={{textTransform: 'capitalize'}}><strong>{`${key}:`}</strong></td> <td>{value}</td> </tr> ) }) } </tbody> </Table> </CardBody> </Card> </Col> </Row> </div> ) } }
JavaScript
class MixerModel extends Observable { constructor() { super(); // Base path (relative URL) to the module dir this.basePath = ""; // Array of Frame objects, one per animal, containing images, call, text, credits this.frames = []; // Array of Noise objects, one per noise, containing recording, text, credits, icon this.noises = []; // Array of noise Objects, one per animal call, containing filtered recording of animal calls this.animalCalls = []; this.maxNoises = 6; // how many noises shall be displayed in each frame // Dict of dicts, UI texts (all texts except texts on animals, which are in frames array) // Each text has a name, as in config.json, and is itself a dict where the key is // the language code (e.g. "de") this.uiTexts = []; } /** * Resets the model's state, notifies observers. */ reset() { this.progress = new Progress(); this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } /** * Sets the model state to started, notifies observers. */ start() { this.progress.started = true; this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } /** * Selects a frame (an animal) and the corresponding filtered noises * * @param i int index of the frame */ setSelectedFrame(i) { // update the progress object this.progress.currentFrame = this.frames[i]; //*** noises ***// // remember which noises were active var activeNoises = []; for (var n in this.progress.currentNoises) { activeNoises.push(this.progress.currentNoises[n].active); } // set current noises according to filter this.progress.currentNoises = this._selectNoises(this.frames[i].id); // reactivate previuosly active noises for (var n in this.progress.currentNoises) { this.progress.currentNoises[n].active = activeNoises[n]; } //*** animal calls ***// // remember which animal calls were active var activeAnimalCalls = []; for (var n in this.progress.currentAnimalCalls) { activeAnimalCalls.push(this.progress.currentAnimalCalls[n].active); } // set current animal calls according to filter this.progress.currentAnimalCalls = this._selectAnimalCalls(this.frames[i].id); // reactivate previuosly active animal calls for (var n in this.progress.currentAnimalCalls) { this.progress.currentAnimalCalls[n].active = activeAnimalCalls[n]; } // notify observers this.progress.continue = false; this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } /* Activates or mutes a noise recording */ toggleNoise(n) { this.progress.currentNoises[n].active = !this.progress.currentNoises[n].active; this.progress.continue = true; this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } /* Activates or mutes an animal recording */ toggleAnimal(n) { this.progress.currentAnimalCalls[n].active = !this.progress.currentAnimalCalls[n].active; this.progress.continue = true; this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } /* Deactivate and mute all noises */ mute() { for (var n in this.progress.currentNoises) { this.progress.currentNoises[n].active = false; } for (var n in this.progress.currentAnimalCalls) { this.progress.currentAnimalCalls[n].active = false; } this.progress.continue = true; this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } /* Shows/hides the credits screen */ toggleCredits() { this.progress.showCredits = !this.progress.showCredits; this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } /** * Sets the relative path to the module's root folder * * @param String path part of the folder's URL */ setBasePath(path) { this.basePath = path; } /** * Add a frame configuration * Frames are defined in config.json and * loaded and parsed by the controller on start up. */ addFrame(frame) { this.frames.push(frame); } /** * Add a noise configuration * Noises are defined in config.json and * loaded and parsed by the controller on start up. */ addNoise(noise) { this.noises.push(noise); } /** * Add an animal call configuration * Animals/frames are defined in config.json and * loaded and parsed by the controller on start up. */ addAnimalCall(call) { this.animalCalls.push(call); } /** * Add a UI text * UI texts are defined in config.json and * loaded and parsed by the controller on start up. * Texts can be accessewd through this.text["text_name"] * Text in the frames, i.e. text on animals and noises, * are handled by addFrame(frame) and stored in this.frame array. */ addUIText(name, text) { this.uiTexts[name] = text; } /** * Randomize the order of the frames every time the mixer starts, * make sure the "soundscape" frame is at the beginning * put the frames in group "antarctic" at the beginning */ shuffleFrames() { this.frames = this._shuffle(this.frames); this.frames = this._reorder(this.frames); } /** Select a group of animals to display */ setAnimalGroup(name) { this.progress.animalGroup = name; this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } setSpeed(speed) { this.progress.speed = speed; this.setChanged(); this.notifyObservers(this.progress); this.clearChanged(); } /* private methods */ // https://www.geeksforgeeks.org/how-to-shuffle-an-array-using-javascript/ _shuffle(array) { for (var i = array.length - 1; i > 0; i--) { // Generate random number var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } /** Add the "soundscape" frame at the beginning */ _reorder(frames) { // remove soundscape frame var resp = frames.filter(function(frame) { return frame.id !== "Rubbing_ice"; }); // add soundscape at the beginning var first = null; for (var i in frames) { if (frames[i].id == "Rubbing_ice") { first = frames[i]; break; } } resp.unshift(first); return resp; } _groupBy(frames, groupName) { var resp = frames.filter(function(frame) { return frame.group.includes(groupName); }); return(resp); } /** Return the noises filtered for the current animal/frame */ _selectNoises(id) { var resp = []; for (var n in this.noises) { if (this.noises[n].filter == id) { resp.push(this.noises[n]); } } return resp; } /** Return the animal calls filtered for the current frame */ _selectAnimalCalls(id) { var resp = []; for (var n in this.animalCalls) { if (this.animalCalls[n].filter == id) { resp.push(this.animalCalls[n]); } } return resp; } _shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } }
JavaScript
class Progress { constructor() { /* boolean true if the mixer has started */ this.started = false; /* Frame object: the frame currently loaded, with the animal call, text and image */ this.currentFrame = null; /* Array of Noise objects: recordings of noises filtered for this animal */ this.currentNoises = null; this.currentAnimalCalls = null; /* Do not clear the screen */ this.continue = false; /* Show the credits screen */ this.showCredits = false; /* Selected visualization (spectro|wave)*/ this.visualization = "wave"; /* Which group of animals shall be loaded. * Animals are assigned a group in config.ini (antarctic|pinnipeds|wales|...) */ this.animalGroup = 'antarctic'; /* Playback speed */ this.speed = 1; } }
JavaScript
class If extends _node.Node { // Provide a node instance /** * Construct a new If node */ constructor() { super("If"); this.inputs = [new _socket.InputSocket("Condition", this, _type.Types.BOOLEAN, false)]; this.outputs = []; this.nexts = [new _socket.NextSocket("Then", this), new _socket.NextSocket("Else", this)]; this.prev = new _socket.PrevSocket("In", this); } /** * Clone this node * @param {Function} factory The factory class function */ clone(factory = If.instance) { return super.clone(factory); } /** * The process function */ async process() { await this.evaluateInputs(); let flow = null; if (this.input("Condition").value) { flow = this.next("Then"); } else { flow = this.next("Else"); } return this.getFlowResult(flow); } }
JavaScript
class Penguin extends SceneItem { /** * */ constructor(configuration) { super(configuration); this.centered = configuration.centered; this.jumpSprite = null; this.walkSprite = null; this.intervalId = null; this.changePenguinState(STATIC_PENGUIN); this.initImages(); } /** * uploads images */ initImages() { //image of penguin stays on the place this.initImage(STATIC_PENGUIN, staticPenguin); this.initImage(PENGUIN_HALF, panguinHalf); //image of penguin jumps this.initImage(PENGUIN_JUMP, penguinJump, { chunkCount: 3, loop: false }).then((sprite)=> { this.jumpSprite = sprite; this.jumpSprite.on('stopped', this.onJumpEnded.bind(this)); }); //image of penguin walk this.initImage(PENGUIN_WALK, penguinWalk, { chunkCount: 4, loop: true }).then((sprite) => { this.walkSprite = sprite }); this.initImage(PENGUIN_SLIDE, penguinSlide, { chunkCount: 2, loop: false }).then((sprite) => { this.slideSprite = sprite; }); this.initImage(PENGUIN_FALL, penguinFall, { chunkCount: 4, loop: false }).then((sprite) => { this.fallSprite = sprite; }); } /** * */ changePenguinState(state) { this.currentState = state; clearInterval(this.intervalId); this.intervalId = null; this.emit('stateChanged', state); } /** * */ slide() { this.changePenguinState(PENGUIN_SLIDE); this.intervalId = setInterval(()=> { this.slideSprite.next(); this.changed(); }, 200); setTimeout(()=> { this.stop(); }, 3000); } /** * */ fall() { this.changePenguinState(PENGUIN_FALL); this.intervalId = setInterval(()=> { this.fallSprite.next(); this.changed(); }, 200); } /** * */ onJumpEnded() { this.stop(); } /** * */ walk() { this.changePenguinState(PENGUIN_WALK); this.intervalId = setInterval(()=> { this.walkSprite.next(); this.changed(); }, 200); } /** * */ jump() { this.changePenguinState(PENGUIN_JUMP); this.jumpSprite.toStart(); this.intervalId = setInterval(()=> { this.jumpSprite.next(); this.changed(); }, 200); this.changed(); } /** * */ stop() { this.changePenguinState(STATIC_PENGUIN); this.changed(); } /** * @override */ draw(context, width, height) { super.draw(context, width, height); this.y = height - this.height; if (this.centered) { this.x = 0.5 * width - 0.5 * this.width; } switch(this.currentState) { case STATIC_PENGUIN: this.drawImage(STATIC_PENGUIN); break; case PENGUIN_WALK: this.drawImage(PENGUIN_WALK); break; case PENGUIN_JUMP: this.drawImage(PENGUIN_JUMP); break; case PENGUIN_SLIDE: this.drawImage(PENGUIN_SLIDE); break; case PENGUIN_FALL: this.drawImage(PENGUIN_FALL); break; case PENGUIN_HALF: this.drawImage(PENGUIN_HALF); break; } } }
JavaScript
class ButtonsBar extends React.Component { render() { return ( <div> <BoldButton ref="Bold"/> <ItalicButton ref="Italic"/> <MonospaceButton ref="Monospace"/> <UnderlineButton ref="Underline"/> </div> ); } }
JavaScript
class ButtonsBar extends React.Component { render() { return ( <div> <BarStyleButton ref="BarButton"/> </div> ); } }
JavaScript
class CustomButtonsBar extends React.Component { render() { return ( <div> <BoldButton> <div ref="BoldChild"/> </BoldButton> <ItalicButton> <div ref="ItalicChild"/> </ItalicButton> <MonospaceButton> <div ref="MonospaceChild"/> </MonospaceButton> <UnderlineButton> <div ref="UnderlineChild"/> </UnderlineButton> </div> ); } }
JavaScript
class ButtonsBar extends React.Component { render() { return ( <div> <ParagraphButton ref="Paragraph"/> <BlockquoteButton ref="Blockquote"/> <CodeButton ref="Code"/> <OLButton ref="OL"/> <ULButton ref="UL"/> <H1Button ref="H1"/> <H2Button ref="H2"/> <H3Button ref="H3"/> <H4Button ref="H4"/> <H5Button ref="H5"/> <H6Button ref="H6"/> </div> ); } }
JavaScript
class ButtonsBar extends React.Component { render() { return ( <div> <FooBlockButton ref="FooButton"/> </div> ); } }
JavaScript
class CustomButtonsBar extends React.Component { render() { return ( <div> <ParagraphButton> <div ref="ParagraphChild"/> </ParagraphButton> <BlockquoteButton> <div ref="BlockquoteChild"/> </BlockquoteButton> <CodeButton> <div ref="CodeChild"/> </CodeButton> <OLButton> <div ref="OLChild"/> </OLButton> <ULButton> <div ref="ULChild"/> </ULButton> <H1Button> <div ref="H1Child"/> </H1Button> <H2Button> <div ref="H2Child"/> </H2Button> <H3Button> <div ref="H3Child"/> </H3Button> <H4Button> <div ref="H4Child"/> </H4Button> <H5Button> <div ref="H5Child"/> </H5Button> <H6Button> <div ref="H6Child"/> </H6Button> </div> ); } }
JavaScript
class LayeredScene extends Scene { // eslint-disable-line no-unused-vars /** * Add layer * @param {Layer} layer Added layer */ addLayer(layer) { layer.init(); } /** * Remove layer * @abstract * @param {Layer} layer Removed layer */ removeLayer(layer) {} /** * Clear all layer */ clearLayer() { for (const it of this.getLayers().reverse()) { this.removeLayer(it); } } /** * Get list pf layers * @abstract * @protected * @return {Array<Layer>} List of layers */ getLayers() {} /** * Update scene * @override * @param {number} dt Delta time */ update(dt) { for (const layer of this.getLayers()) { layer.update(dt); } } /** * Render scene * @override * @param {Context} ctx Canvas context */ render(ctx) { for (const layer of this.getLayers()) { layer.render(ctx); } } }
JavaScript
class IgnoreType { /** * @param len number of bytes to ignore */ constructor(len) { this.len = len; } // ToDo: don't read, but skip data get(buf, off) { } }
JavaScript
class StringType { constructor(len, encoding) { this.len = len; this.encoding = encoding; } get(buf, off) { return buf.toString(this.encoding, off, off + this.len); } }
JavaScript
class AnsiStringType { constructor(len) { this.len = len; } static decode(buffer, off, until) { let str = ''; for (let i = off; i < until; ++i) { str += AnsiStringType.codePointToString(AnsiStringType.singleByteDecoder(buffer[i])); } return str; } static inRange(a, min, max) { return min <= a && a <= max; } static codePointToString(cp) { if (cp <= 0xFFFF) { return String.fromCharCode(cp); } else { cp -= 0x10000; return String.fromCharCode((cp >> 10) + 0xD800, (cp & 0x3FF) + 0xDC00); } } static singleByteDecoder(bite) { if (AnsiStringType.inRange(bite, 0x00, 0x7F)) { return bite; } const codePoint = AnsiStringType.windows1252[bite - 0x80]; if (codePoint === null) { throw Error('invaliding encoding'); } return codePoint; } get(buf, off = 0) { return AnsiStringType.decode(buf, off, off + this.len); } }
JavaScript
class StreamReader { constructor(s) { this.s = s; this.endOfStream = false; /** * Store peeked data * @type {Array} */ this.peekQueue = []; if (!s.read || !s.once) { throw new Error('Expected an instance of stream.Readable'); } this.s.once('end', () => this.reject(new EndOfFileStream_1.EndOfStreamError())); this.s.once('error', err => this.reject(err)); this.s.once('close', () => this.reject(new Error('Stream closed'))); } /** * Read ahead (peek) from stream. Subsequent read or peeks will return the same data * @param buffer - Buffer to store data read from stream in * @param offset - Offset buffer * @param length - Number of bytes to read * @returns Number of bytes peeked */ async peek(buffer, offset, length) { const bytesRead = await this.read(buffer, offset, length); this.peekQueue.push(buffer.slice(offset, offset + bytesRead)); // Put read data back to peek buffer return bytesRead; } /** * Read chunk from stream * @param buffer - Target buffer to store data read from stream in * @param offset - Offset of target buffer * @param length - Number of bytes to read * @returns Number of bytes read */ async read(buffer, offset, length) { if (length === 0) { return 0; } if (this.peekQueue.length === 0 && this.endOfStream) { throw new EndOfFileStream_1.EndOfStreamError(); } let remaining = length; let bytesRead = 0; // consume peeked data first while (this.peekQueue.length > 0 && remaining > 0) { const peekData = this.peekQueue.pop(); // Front of queue const lenCopy = Math.min(peekData.length, remaining); peekData.copy(buffer, offset + bytesRead, 0, lenCopy); bytesRead += lenCopy; remaining -= lenCopy; if (lenCopy < peekData.length) { // remainder back to queue this.peekQueue.push(peekData.slice(lenCopy)); } } // continue reading from stream if required while (remaining > 0 && !this.endOfStream) { const reqLen = Math.min(remaining, maxStreamReadSize); const chunkLen = await this._read(buffer, offset + bytesRead, reqLen); bytesRead += chunkLen; if (chunkLen < reqLen) break; remaining -= chunkLen; } return bytesRead; } /** * Read chunk from stream * @param buffer Buffer to store data read from stream in * @param offset Offset buffer * @param length Number of bytes to read * @returns {any} */ async _read(buffer, offset, length) { assert.ok(!this.request, 'Concurrent read operation?'); const readBuffer = this.s.read(length); if (readBuffer) { readBuffer.copy(buffer, offset); return readBuffer.length; } else { this.request = { buffer, offset, length, deferred: new Deferred() }; this.s.once('readable', () => { this.tryRead(); }); return this.request.deferred.promise.then(n => { this.request = null; return n; }, err => { this.request = null; throw err; }); } } tryRead() { const readBuffer = this.s.read(this.request.length); if (readBuffer) { readBuffer.copy(this.request.buffer, this.request.offset); this.request.deferred.resolve(readBuffer.length); } else { this.s.once('readable', () => { this.tryRead(); }); } } reject(err) { this.endOfStream = true; if (this.request) { this.request.deferred.reject(err); this.request = null; } } }
JavaScript
class EndOfStreamError extends Error { constructor() { super(exports.defaultMessages); } }
JavaScript
class Map extends React.Component { constructor(props) { super(props); this.map = null; if (!props.hasOwnProperty('google')) { throw new Error('You must include a `google` prop.'); } } componentDidUpdate(prevProps, prevState) { if (prevProps.google !== this.props.google) { this.loadMap(); } } componentDidMount() { this.loadMap(); } loadMap() { if (this.props && this.props.google) { const { google } = this.props; const { centerMap } = this.props; const maps = google.maps; const mapRef = this.refs.map; const node = ReactDOM.findDOMNode(mapRef); let zoom = 14; let { lat } = centerMap; let { lng } = centerMap; const center = new maps.LatLng(lat, lng); const mapConfig = Object.assign({}, { center: center, zoom: zoom, styles: customMapStyle, mapTypeControl: false, streetViewControl: false, fullscreenControl: false, zoomControl: true, zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_BOTTOM }, }) this.map = new maps.Map(node, mapConfig); this.setState({ shouldLoadMarkers: true }); } } renderChildren() { const {children} = this.props; if (!children) return; return React.Children.map(children, c => { return React.cloneElement(c, { map: this.map, google: this.props.google, }) }); } render() { const style = { width: '100vw', height: '100vh' } return ( <div> <div style={style} ref='map'></div> {this.renderChildren()} </div> ) } }
JavaScript
class Tw2ShaderAnnotation { @meta.string name = ""; @meta.string description = ""; @meta.array components = null; @meta.boolean display = true; @meta.string group = "None"; @meta.string widget = ""; /** * Creates an annotation from json * TODO: Replace with util functions * @param {Object} json * @param {Tw2EffectRes} context * @param {String} [key] * @return {Tw2ShaderAnnotation} */ static fromJSON(json, context, key) { const annotation = new Tw2ShaderAnnotation(); assignIfExists(annotation, json, [ "name", "description", "display", "group", "widget" ]); const components = []; if (json.components) { for (let i = 0; i < json.components.length; i++) { components[i] = json.components[i]; } } if (components.length) annotation.components = components; annotation.name = annotation.name || key; return annotation; } /** * Reads ccp shader annotations * @param {Tw2BinaryReader} reader * @param {Tw2EffectRes} context * @return {Tw2ShaderAnnotation} */ static fromCCPBinary(reader, context) { const annotation = new Tw2ShaderAnnotation(); annotation.name = context.ReadString(); const annotationCount = reader.ReadUInt8(), components = []; for (let annotationIx = 0; annotationIx < annotationCount; ++annotationIx) { let key = context.ReadString(), type = reader.ReadUInt8(), value; switch (type) { case 0: value = reader.ReadUInt32() !== 0; break; case 1: value = reader.ReadInt32(); break; case 2: value = reader.ReadFloat32(); break; default: value = context.ReadString(); } // Normalize the annotations switch (key.toUpperCase()) { case "UIWIDGET": annotation.widget = value.toUpperCase(); if (annotation.widget === "LINEARCOLOR") { components[0] = "Linear red"; components[1] = "Linear green"; components[2] = "Linear blue"; components[3] = "Linear alhpa"; } break; case "SASUIVISIBLE": annotation.display = value; break; case "SASUIDESCRIPTION": annotation.description = value; break; case "GROUP": annotation.group = value; break; case "COMPONENT1": components[0] = value; break; case "COMPONENT2": components[1] = value; break; case "COMPONENT3": components[2] = value; break; case "COMPONENT4": components[3] = value; break; default: key = key.charAt(0).toLowerCase() + key.substring(1); annotation[key] = value; } } if (!annotation.widget && annotation.name.toUpperCase().includes("MAP")) { annotation.widget = "TEXTURE"; annotation.group = "Textures"; } if (components.length) { annotation.components = components; } return annotation; } }
JavaScript
class Node { constructor(p, level) { this.p = p; this.level = level; this.value = ''; this.leaf = true; this.width = 0; this.offset = 0; this.child_width = 0; this.subscript = ''; } }
JavaScript
class ApiClient { constructor(module, { headers, toJson, } = {}) { this.token = localStorage.getItem("auth_token"); this.module = module; this.headers = headers; this.toJson = toJson || true; } get(endpoint, params) { return this.request('GET', endpoint, params); } post(endpoint, params) { return this.request('POST', endpoint, params); } put(endpoint, params) { return this.request('PUT', endpoint, params); } patch(endpoint, params) { return this.request('PATCH', endpoint, params); } delete(endpoint, params) { return this.request('DELETE', endpoint, params); } file(endpoint, params) { const formData = objectToFormData(params); this.headers = []; let url = this.serverUrl(endpoint); let fetchData = { method: 'POST', headers: this.authHeader(), mode: 'cors', body: formData } let fetchRequest = fetch(url, fetchData); if (this.toJson) { fetchRequest = fetchRequest.then((response) => response.json()) } return fetchRequest; } request(method, endpoint, params) { let url = ''; let fetchData = {}; if (params) { url = this.serverUrl(endpoint) + '?' + toQueryString(params); } else { url = this.serverUrl(endpoint); } if(method.toUpperCase() == 'GET') { fetchData = { method: method, headers: this.authHeader(), mode: 'cors' } } else { params = (params ? params : {}); params = JSON.stringify(params); url = this.serverUrl(endpoint); fetchData = { method: method, headers: this.authHeader(), mode: 'cors', body: params } } let fetchRequest = fetch(url, fetchData); if (this.toJson) { fetchRequest = fetchRequest.then((response) => response.json()) } return fetchRequest; } serverUrl(endpoint) { return `http://dev-${this.module}api.us-east-1.elasticbeanstalk.com/${endpoint}` //return `http://localhost:8002/${endpoint}` } authHeader() { if(this.headers == undefined) { this.headers = {}; this.headers['Content-Type'] = 'application/json'; } return Object.assign({ 'Authorization': `Bearer ${this.token}`, 'Accept': 'application/json' }, this.headers); } }
JavaScript
class NIcon extends HTMLElement { constructor() { super(); this.icon = this.innerText; this.size = this.getAttribute('size'); } connectedCallback() { if (icons[this.icon]) this.innerHTML = `${icons[this.icon]}`; } }
JavaScript
class Force { constructor(xDir, yDir, magnitude) { this.xDir = xDir; this.yDir = yDir; this.magnitude = magnitude; // Determine the direction of the force this.dirVec = new Vec2(xDir, yDir).normalize(); // Determine the force vector based on inputs this.forceVec = this.dirVec.clone().multiplyScalar(magnitude); // A unique id for this force this.id = xxh.h32(`${JSON.stringify(this.forceVec)}${new Date().getTime()}`, 0xCAFEBABE).toString(16); } }
JavaScript
class HorizontalLineTool { /** * Tools contructor. Is provided with canvas-wrapper and eventAggregator by contract. * @constructor * @param {Canvas} canvasWrapper - Canvas. * @param {EventAggregator} eventAggregator - Event mediator. */ constructor(canvasWrapper, eventAggregator, toolOptions) { const canvas = canvasWrapper.canvas; let horizontalLine; eventAggregator.subscribeTo(CONST.TOOL.HORIZONTAL_LINE, 'HorizontalLineTool', activateHorizontalLineTool); function notify(message) { eventAggregator.notify('TOOL_USAGE', CONST.TOOL.HORIZONTAL_LINE, message); } function createHorizontalLine() { return new fabric.Line([0, 0, canvas.width, 0], { left: 0, top: 1, hasControls: false, lockMovementX: true, opacity: 0.7, padding: 4, stroke: toolOptions.color, strokeWidth: 2 }); } function activateHorizontalLineTool(addr, sender, action) { if (action !== 'toolbar-click') { abort(); return; } notify('active'); horizontalLine = createHorizontalLine(); canvas.add(horizontalLine); eventAggregator.subscribeTo('keydown', 'HorizontalLine', (abortTopic, abortSender, abortKeyCode) => { if (abortKeyCode === 27) { abort(); } }); function abort() { canvas.remove(horizontalLine); horizontalLine = undefined; // TODO unsubscribe detachHorizontalLineListener(); notify('inactive'); } const onMouseMove = (options) => { if (horizontalLine) { horizontalLine.set({ top: canvas.getPointer(options.e).y }); horizontalLine.setCoords(); canvas.renderAll(); } }; canvas.on('mouse:move', onMouseMove); const onMouseUp = () => { horizontalLine = createHorizontalLine(); canvas.add(horizontalLine); }; canvas.on('mouse:up', onMouseUp); function detachHorizontalLineListener() { canvas.off('mouse:move', onMouseMove); canvas.off('mouse:up', onMouseUp); } } } }
JavaScript
class ColorSet { constructor( background, idle, active, stem ) { this.background = new THREE.Color( background ); this.idle = new THREE.Color( idle ); this.active = new THREE.Color( active ); this.stem = new THREE.Color( stem ); } setUniforms( material ) { material.uniforms.bgColor.value = this.background; material.uniforms.idleColor.value = this.idle; material.uniforms.activeColor.value = this.active; } }
JavaScript
class SwalForm { constructor(swalOptions, template = '#js-panel-form-template', selector = '.js-entity-from') { this.swalOptions = swalOptions; this.template = template; this.selector = selector; } create(url) { let swalOptions = { options: this.swalOptions.editView, onBeforeOpen: this.onBeforeOpenEditView.bind(this), confirmButtonText: this.swalOptions.text.create.confirmButtonText, titleText: this.swalOptions.text.create.titleText, confirmTitleText: this.swalOptions.text.create.confirmTitleText, }; return this.display(swalOptions, url, 'create'); } /** * Display a form to create or edit entity. * * @param {Object} swalOptions * @param {Object} swalOptions.options * @param {function} swalOptions.onBeforeOpen * @param {string} swalOptions.confirmButtonText * @param {string} swalOptions.titleText * @param {string} swalOptions.confirmTitleText * @param {string} url * @param {string} method * @param {Object} data Use to pre populate the from. * * @return {*|Promise|Promise<T | never>} */ display(swalOptions, url, method, data = null) { // Keeping backward compatibility if (method === 'create' || method === 'update') { method = method === 'create' ? 'POST' : 'PUT'; } // Build form html base on the template. const html = this.html(); // Swal form modal const swalForm = Swal.mixin(swalOptions.options);// The options use to show the form inside the modal and how to parser the inputs. return swalForm.fire({ html: html, confirmButtonText: swalOptions.confirmButtonText, titleText: swalOptions.titleText, onBeforeOpen: () => { const $modal = $(swalForm.getContainer()).find('.swal2-modal'); swalOptions.onBeforeOpen(data, $modal); }, preConfirm: () => { const $modal = $(swalForm.getContainer()).find('.swal2-modal'); if (swalOptions.preConfirm) { return swalOptions.preConfirm($modal, url, method); } return this.preConfirm($modal, url, method); }, onClose: () => { const $modal = $(swalForm.getContainer()).find('.swal2-modal'); if (swalOptions.onClose) { return swalOptions.onClose($modal); } }, }).then((result) => { // Show popup with success message if (result.value) { this.showStatusMessage(swalOptions.confirmTitleText); } return result }).catch((arg) => { // canceling is cool! console.log(arg) }); } /** * Form html code. * * @return {*} */ html() { return Template.compile(this.template); } /** * Show action success message. * * @param titleText */ showStatusMessage(titleText) { const toast = Swal.mixin(this.swalOptions.confirm); toast.fire({ type: 'success', titleText }); } /** * Defines instructions to execute before the form totaly display. * * This method should overwritten by the child class in case the form requires to be preload. * * @param {Object} data * @param $wrapper */ onBeforeOpenEditView(data, $wrapper) { console.log('onBeforeOpenEditView'); } preConfirm($wrapper, url, method, excludes) { // Getting form data. const $form = $wrapper.find(this.selector); const formData = {}; $.each($form.serializeArray(), (key, fieldData) => { if ($.isArray(excludes) && !$.inArray(fieldData.name, excludes)) { return; } formData[fieldData.name] = fieldData.value }); // Sending the data to the server. return InvestmentManagerClient.sendRPC(url, method, formData) // Catches response error .catch((errorsData) => { let $swalValidationMessage = $('#swal2-validation-message'); $swalValidationMessage.empty(); if (errorsData.errors) { this.mapErrors($form, errorsData.errors); return false; } if (errorsData.message) { $swalValidationMessage.append( $('<span></span>').html(errorsData.message) ).show() } return false; }); } mapErrors($form, errorData) { // Remove form errors $form.find('.js-field-error').remove(); $form.find('.form-group').removeClass('has-error'); // Add errors $form.find(':input').each((index, input) => { const fieldName = $(input).attr('name'); const $groupWrapper = $(input).closest('.form-group'); const $wrapper = $(input).closest('div'); if (!errorData[fieldName]) { // no error! return; } const $error = $('<span class="js-field-error help-block" style="text-align: left;"></span>'); $error.html(errorData[fieldName]); $wrapper.append($error); $groupWrapper.addClass('has-error'); }); } update(url, data) { let swalOptions = { options: this.swalOptions.editView, onBeforeOpen: this.onBeforeOpenEditView.bind(this), confirmButtonText: this.swalOptions.text.update.confirmButtonText, titleText: this.swalOptions.text.update.titleText, confirmTitleText: this.swalOptions.text.update.confirmTitleText, }; return this.display(swalOptions, url, 'update', data); } delete(url, id, title) { // Create delete text confirmation. const text = this.swalOptions.deleteView.text.replace(/\{0\}/g, '"' + title + '"'); // Swal confirmation modal const swalConfirm = Swal.mixin(this.swalOptions.deleteView); return swalConfirm.fire({ text, preConfirm: () => { return InvestmentManagerClient.sendRPC(url, 'DELETE'); } }).then((result) => { // Show popup with success message if (result.value) { this.showStatusMessage(this.swalOptions.text.delete.confirmTitleText); } return result }).catch((arg) => { // canceling is cool! console.log(arg); }); } }
JavaScript
class PersonClass { constructor(name, hairColor){ this.name = name; this.hairColor = hairColor; } sayHello(){ console.log(`hello from ${this.name}`); } }
JavaScript
class Investment extends React.Component { // Constructor setting default state constructor ( props ) { super ( props ) // Set the state objects this.state = { interest: { pessimistic: this.props.pessimistic || 2, historical: this.props.historical || 4, optimistic: this.props.optimistic || 8 }, income: 1150, capital: 0, timeline: 40, showOptions: false, compound: { capital: 1000, monthly: 500, timeline: 40, roi: 4 } } // Bind the functions for use in the render this.setPersona = this.setPersona.bind( this ) this.optionsToggle = this.optionsToggle.bind( this ) } // Set the parameters setPersona( e ) { let newState = { interest: this.state.interest, compound: this.state.compound } // Change the state interest key based on changed input switch( e.target.name ) { case 'pessimistic': newState.interest.pessimistic = e.target.value break case 'historical': newState.interest.historical = e.target.value break case 'optimistic': newState.interest.optimistic = e.target.value break case 'income': newState.income = e.target.value e.target.styles = 'width: ' + ( ( e.target.value.length * 8 ) + 15 ) + 'px;' break case 'timeline': newState.timeline = e.target.value e.target.styles = 'width: ' + ( ( e.target.value.length * 8 ) + 15 ) + 'px;' break case 'capital': newState.capital = Number( e.target.value ) e.target.styles = 'width: ' + ( ( e.target.value.length * 8 ) + 15 ) + 'px;' break case 'capitalCompound': newState.compound.capital = Number( e.target.value ) break case 'monthlyCompound': newState.compound.monthly = e.target.value break case 'timelineCompound': newState.compound.timeline = e.target.value break case 'roiCompound': newState.compound.roi = e.target.value break } this.setState( newState ) } // Show the options bar optionsToggle( ) { this.setState( { showOptions: this.state.showOptions ? false : true } ) } // Rendering of message render( ) { // Show the app result return( <div> <p className="note">If you are just getting started with budgeting & investing <a href="https://www.skillcollector.com/manage-finances-investments/">read this</a>.</p> <ParametersView handleChange = { this.setPersona } interest = { this.state.interest } income = { this.state.income } timeline = { this.state.timeline } capital = { this.state.capital } /> <PlanningView handleChange = { this.setPersona } interest = { this.state.interest } desiredYearlyIncome = { this.state.income * 12 } capital = { this.state.capital } timeline = { this.state.timeline } showOptions = { this.state.showOptions } toggleOptions = { this.optionsToggle } /> <DesiresView interest = { this.state.interest } income = { this.state.income } timeline = { this.state.timeline } /> <CompoundView handleChange = { this.setPersona } capital = { this.state.compound.capital } monthly = { this.state.compound.monthly } timeline = { this.state.compound.timeline } roi = { this.state.compound.roi } /> <ExplainReasoningView /> </div> ) } }
JavaScript
class NoiseFilter extends core.Filter { /** * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. */ constructor(noise = 0.5, seed = Math.random()) { super( // vertex shader readFileSync(join(__dirname, '../fragments/default.vert'), 'utf8'), // fragment shader readFileSync(join(__dirname, './noise.frag'), 'utf8') ); this.noise = noise; this.seed = seed; } /** * The amount of noise to apply, this value should be in the range (0, 1]. * * @member {number} * @default 0.5 */ get noise() { return this.uniforms.uNoise; } set noise(value) // eslint-disable-line require-jsdoc { this.uniforms.uNoise = value; } /** * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. * * @member {number} */ get seed() { return this.uniforms.uSeed; } set seed(value) // eslint-disable-line require-jsdoc { this.uniforms.uSeed = value; } }
JavaScript
class Task { /** * Create a task * @param {Modem} modem Modem to connect to the remote service * @param {string} id Id of the task (optional) */ constructor(modem, id) { this.data = {}; this.modem = modem; this.id = id; } /** * Get low-level information on a task * https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/inspect-a-task * The reason why this module isn't called inspect is because that interferes with the inspect utility of task. * @param {Object} opts Query params in the request (optional) * @param {String} id ID of the task to inspect, if it's not set, use the id of the Object (optional) * @return {Promise} Promise return the task */ status(opts) { const call = { path: `/tasks/${this.id}?`, method: 'GET', options: opts, statusCodes: { 200: true, 404: 'no such task', 500: 'server error' } }; return new Promise((resolve, reject) => { this.modem.dial(call, (err, conf) => { if (err) return reject(err); const task = new Task(this.modem, this.id); task.data = conf; resolve(task); }); }); } }
JavaScript
class MenuRenderer { constructor() { var scene = new THREE.Scene(); var aspect = window.innerWidth / window.innerHeight; var camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 100); scene.add(camera); var renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); var effect = new THREE.VREffect(renderer); var controls = new THREE.VRControls(camera); controls.standing = true; var manager = new WebVRManager(renderer, effect); document.body.appendChild(renderer.domElement); // Input manager. var rayInput = new RayInput(camera) rayInput.setSize(renderer.getSize()); rayInput.on('raydown', (opt_mesh) => { this.handleRayDown_(opt_mesh) }); rayInput.on('rayup', (opt_mesh) => { this.handleRayUp_(opt_mesh) }); rayInput.on('raycancel', (opt_mesh) => { this.handleRayCancel_(opt_mesh) }); rayInput.on('rayover', (mesh) => { this.setSelected_(mesh, true) }); rayInput.on('rayout', (mesh) => { this.setSelected_(mesh, false) }); // Add the ray input mesh to the scene. scene.add(rayInput.getMesh()); this.manager = manager; this.camera = camera; this.scene = scene; this.controls = controls; this.rayInput = rayInput; this.effect = effect; this.renderer = renderer; // Add a small fake menu to interact with. var menu = this.createMenu_(); scene.add(menu); // Add a floor. var floor = this.createFloor_(); scene.add(floor); menu.children.forEach(function(menuItem) { //console.log('menuItem', menuItem); rayInput.add(menuItem); }); } render() { this.controls.update(); this.rayInput.update(); this.effect.render(this.scene, this.camera); } resize() { this.camera.aspect = window.innerWidth / window.innerHeight; this.camera.updateProjectionMatrix(); this.renderer.setSize(window.innerWidth, window.innerHeight); this.rayInput.setSize(this.renderer.getSize()); } handleRayDown_(opt_mesh) { this.setAction_(opt_mesh, true); } handleRayUp_(opt_mesh) { this.setAction_(opt_mesh, false); } handleRayCancel_(opt_mesh) { this.setAction_(opt_mesh, false); } setSelected_(mesh, isSelected) { //console.log('setSelected_', isSelected); var newColor = isSelected ? HIGHLIGHT_COLOR : DEFAULT_COLOR; mesh.material.color = newColor; } setAction_(opt_mesh, isActive) { //console.log('setAction_', !!opt_mesh, isActive); if (opt_mesh) { var newColor = isActive ? ACTIVE_COLOR : HIGHLIGHT_COLOR; opt_mesh.material.color = newColor; if (!isActive) { opt_mesh.material.wireframe = !opt_mesh.material.wireframe; } } } createMenu_() { var menu = new THREE.Object3D(); // Create a 2x2 grid of menu items (green rectangles). for (var i = 0; i < WIDTH; i++) { for (var j = 0; j < HEIGHT; j++) { var item = this.createMenuItem_(); item.position.set(i, j, 0); item.scale.set(0.9, 0.9, 0.1); menu.add(item); } } menu.position.set(-WIDTH/4, HEIGHT/2, -3); return menu; } createMenuItem_() { var geometry = new THREE.BoxGeometry(1, 1, 1); var material = new THREE.MeshBasicMaterial({color: DEFAULT_COLOR}); var cube = new THREE.Mesh(geometry, material); return cube; } createFloor_() { var boxSize = 10; var loader = new THREE.TextureLoader(); loader.load('img/box.png', onTextureLoaded); var out = new THREE.Object3D(); function onTextureLoaded(texture) { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.repeat.set(boxSize, boxSize); var geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize); var material = new THREE.MeshBasicMaterial({ map: texture, color: 0x015500, side: THREE.BackSide }); // Align the skybox to the floor (which is at y=0). let skybox = new THREE.Mesh(geometry, material); skybox.position.y = boxSize/2; out.add(skybox); } return out; } }
JavaScript
class Orders extends Component { state = { sales: [], searchWord: '', month: '%', activeOrder: null }; /**handle change * change the searchword whenever there * is an input in the search box, then call to searchSales() * to print out the new list. * @event - event/value of the clicked element */ onChangeHandle(event) { this.setState({ state: (this.state.searchWord = event.target.value) }, this.searchSales()); } handleChangeSelect(event) { this.setState({ month: (this.state.month = event.target.value) }, this.searchSales()); } /** Search Sales * Uses a query to search through the database * to return a new list of sales * that only show relevant sales towards search word */ searchSales() { let searchWord = '%' + this.state.searchWord + '%'; let month = '%' + this.state.month + '%'; rentalService.searchSales(searchWord, month, results => { this.setState({ state: (this.state.sales = []) }); this.setState(state => { const sales = state.sales.concat(results); return { sales, results }; }); }); } /** * Will change the activeOrder state, and send it to * the child component, aswell as updated the value in * each order in orderlist to reflect * which order is currently clicked * @order - clicked order from table row */ chooseActive(order) { let index = this.state.sales .map(function(e) { return e.id; }) .indexOf(order.id); for (let i = 0; i < this.state.sales.length; i++) { this.state.sales[i].selectedSale = false; } this.state.sales[index].selectedSale = true; orderService.getOrder(order.id, result => { this.setState({ state: (this.state.activeOrder = result) }); }); } render() { return ( <div> <NavBar brand="CycleOn Rentals"> <h1>Ordrer</h1> </NavBar> <Card role="main"> <Row> <Column width={5}> <Select name="locationSelect" value={this.state.month} onChange={this.handleChangeSelect}> <Select.Option value="%">Alle måneder</Select.Option> <Select.Option value="-01-">Januar</Select.Option> <Select.Option value="-02-">Februar</Select.Option> <Select.Option value="-03-">Mars</Select.Option> <Select.Option value="-04-">April</Select.Option> <Select.Option value="-05-">Mai</Select.Option> <Select.Option value="-06-">Juni</Select.Option> <Select.Option value="-07-">Juli</Select.Option> <Select.Option value="-08-">August</Select.Option> <Select.Option value="-09-">September</Select.Option> <Select.Option value="-10-">Oktober</Select.Option> <Select.Option value="-11-">November</Select.Option> <Select.Option value="-12-">Desember</Select.Option> </Select> <br /> <br /> <Form.Input type="search" placeholder="Søk på kunde, selger, datoer og pris." onChange={this.onChangeHandle} > {this.state.searchWord} </Form.Input> <br /> <ClickTable> <ClickTable.Thead> <ClickTable.Th>Ordredato</ClickTable.Th> <ClickTable.Th>Ordre ID</ClickTable.Th> <ClickTable.Th>Kunde ID</ClickTable.Th> </ClickTable.Thead> <ClickTable.Tbody> {this.state.sales.map(sale => ( <ClickTable.Tr style={sale.selectedSale ? { backgroundColor: '#c5e0e4' } : { backgroundColor: '' }} key={sale.id} onClick={() => { this.chooseActive(sale); }} > <ClickTable.Td>{sale.dateOrdered.toString().substring(4, 16)}</ClickTable.Td> <ClickTable.Td>{sale.id}</ClickTable.Td> <ClickTable.Td>{sale.customer_id}</ClickTable.Td> </ClickTable.Tr> ))} </ClickTable.Tbody> </ClickTable> </Column> <Column> <SelectedOrder activeOrder={this.state.activeOrder} /> </Column> </Row> <br /> </Card> <br /> </div> ); } mounted() { rentalService.getAllSales(results => { for (let i = 0; i < results.length; i++) { if (i == 0) { results[i].selectedSale = true; } else { results[i].selectedSale = false; } } this.setState({ sales: results, activeOrder: results[0] }); }); } }
JavaScript
class Worker { /** * @param {Object} options - Default values to use when creating AMQP channels and queues. * See RabbitMQ docs (http://www.rabbitmq.com/amqp-0-9-1-reference.html) for more details. * @param {Object} options.assertQueue * @param {boolean} options.assertQueue.exclusive * @param {boolean} options.assertQueue.durable * @param {boolean} options.assertQueue.autoDelete * @param {boolean} options.assertQueue.arguments * @param {boolean} options.prefetch */ constructor(options) { this._queues = {}; this._middlewares = []; this._options = Object.assign(defaultOptions, options); debug(`.constructor() options=${JSON.stringify(options)}`); debug(` _options=${JSON.stringify(this._options)}`); } /** * Manually set the amqplib connection that the worker will use. * @param {Object} conn - An amqplib connection. */ set connection(conn) { this._conn = conn; } /** * Open a connection to the RabbitMQ server. * @param {string} url - Address of the RabbitMQ server to connect to. * @return {Promise} Promise that resolves when the connection is made, channel is open, and outstanding queues are asserted. */ connect(url) { debug(`.connect() url=${url}`); return amqp.connect(url).then(conn => { this._conn = conn; this._conn.on('close', () => debug('event: connection closed') ); this._conn.on('error', error => debug('event: connection error:', error) ); return this._createChannel(this._conn); }); } /** * Disconnect from the RabbitMQ server. * @throws {error} Throw error when not connected. */ disconnect() { debug('.disconnect()'); if (!this._conn) { debug(' error: Not connected'); throw 'Disconnecting: Not connected'; } this._closeChannel().then(() => { return this._conn.close(); }).then(() => { delete this._conn; debug(' success: disconnected'); }); } /** * Bind a callback handler to a route. * @param {string} route - Route to bind callback handler to. * @param {function} callback - handler to execute when a request is received on the given route. */ accept(route, callback) { debug(`.accept() route='${route}', callback='${callback}'`); assert(!this._queues[route], `'${route}'' already exists`); this._queues[route] = {}; this._queues[route].callback = callback; if (this._ch) { return this._openQueue(route); } } /** * Set a middleware function that will execute for each request on a bound route before the callback handler is called. * @param {function} middleware - Middleware function to use. * @return {number} Count totalling number of middleware functions loaded. */ use(middleware) { debug(`.use() middleware=${middleware}`); return this._middlewares.push(middleware); } _createChannel(connection) { debug('_createChannel()'); // Yuck, but amqplib-mock doesn't return a promise from createChannel() return new Promise((resolve, reject) => { return resolve(connection.createChannel()); }).then(ch => { this._ch = ch; this._ch.on('close', () => debug('event: channel closed') ); this._ch.on('error', error => debug('event: channel error:', error) ); const promises = []; for (let q in this._queues) { promises.push(this._openQueue(q)); } return Promise.all(promises); }); } _closeChannel() { debug('_closeChannel()'); const promises = []; for (let q in this._queues) { promises.push(this._closeQueue(q)); } return Promise.all(promises).then(() => { return this._ch.close; }); } _openQueue(q) { debug(`._openQueue() q=${q}`); const queue = this._queues[q]; this._ch.assertQueue(q, this._options.assertQueue); this._ch.prefetch(this._options.prefetch); const cb = (msg) => { if (!msg) { return; } debug(`.callback() q=${q}`); debug(` fields=${JSON.stringify(msg.fields)}`); debug(` properties=${JSON.stringify(msg.properties)}`); debug(` content=${msg.content.toString()}`); const request = new Request(msg); const response = new Response(this._ch, msg); this._execCallback(0, request, response, queue.callback); }; return this._ch.consume(q, cb); } _closeQueue(q) { debug(`._closeQueue() q=${q}`); const promise = this._ch.deleteQueue(q); delete this._queues[q]; return promise; } _execCallback(i, request, response, last) { debug(`_execCallback() i=${i}`); if (i === this._middlewares.length) { debug(' executing callback'); return last(request, response); } debug(' executing middleware'); return this._middlewares[i]( request, response, () => { return new Promise((resolve, reject) => { try { resolve(this._execCallback(i+1, request, response, last)); } catch (error) { reject(error); } }); } ); } }
JavaScript
class CalculatorStore { acknowledgedDisclaimer = InitialValues.acknowledgedDisclaimer; averageAnnual401kFees = InitialValues.averageAnnual401kFees; averageAnnual401kGrowth = InitialValues.averageAnnual401kGrowth; averageEmployerESOPContribution = InitialValues.averageEmployerESOPContribution; averageRaise = InitialValues.averageRaise; averageShareGrowth = InitialValues.averageShareGrowth; currentEmployeeAge = InitialValues.currentEmployeeAge; initYear = InitialValues.initYear; employee401kContribution = InitialValues.employee401kContribution; selectedTab = InitialValues.selectedTab; startDate = InitialValues.startDate; starting401kBalance = InitialValues.starting401kBalance; startingSalary = InitialValues.startingSalary; startingESOPAccountValue = InitialValues.startingESOPAccountValue; yearsToCalculate = InitialValues.yearsToCalculate; /** * @param {string} setting - the setting name to update * @param {any} value - The appropriate value to set */ handleInputsUpdate = (setting, value) => { this[setting] = value; }; /** * @param {event} event - Not used * @param {any} value - The index of the tab to select */ handleTabChange = (event, value) => { this.selectedTab = value; }; get dataPoints401k() { return generate401kGrowthData( this.startDate, this.starting401kBalance, this.startingSalary, this.employee401kContribution / 100, this.averageRaise / 100, this.averageAnnual401kGrowth / 100, this.averageAnnual401kFees / 100, this.initYear, this.yearsToCalculate, this.currentEmployeeAge ); } get dataPointsESOP() { return generateESOPGrowthData( this.startDate, this.startingESOPAccountValue, this.averageShareGrowth / 100, this.startingSalary, this.averageRaise / 100, this.averageEmployerESOPContribution / 100, this.initYear, this.yearsToCalculate ); } tabs = [ Constants.USAGE_GUIDE, Constants.ESOP_GROWTH, Constants.ONLY_401K, Constants.COMBINED_INVESTMENTS, ]; get selectedTabName() { return this.tabs[this.selectedTab]; } }
JavaScript
class DirectoryCompanyService { constructor (url) { this.url = url; } async getCompanies () { this.log(`Getting all directory companies from UnivJobs API...\n`) const response = await axios.get( `${this.url}/api/v1/public/companies/directory` ) // Get all companies from the backend. let companies = response.data.directory; // Add the dummy company so that it can build. companies = companies.concat([dummy]) // Log it out this.log(`Retrieved ${companies.length} companies.\n`) return companies; } log (message) { console.log(`[DirectoryCompanyService]: ${message}`) } }
JavaScript
class TriggerList { constructor() { this._list = {}; } get list() { return this._list; } set list(triggers) { this._list = triggers; } }
JavaScript
class BannedDomainList { constructor() { this._list = []; } get list() { return this._list; } set list(domains) { this._list = domains; } }
JavaScript
class EmojiRolePosts { constructor() { this._posts = []; } get posts() { return this._data; } set posts(ids) { this._posts = ids; } }
JavaScript
class ImageRenderer extends Component { constructor(props) { super(props); } renderProgress(progress) { return progress >= 0 ? <div className={this.props.plugin.theme.imageLoader} style={{width: `${100 - progress}%`}}/> : null; } render() { const {alignmentClassName, focusClassName, blockProps, style} = this.props; const {theme} = this.props.plugin; const {progress, src, url, alt} = blockProps.entityData; let {width, height} = blockProps.entityData; if (!width) width = '100%'; if (!height) height = '100%'; return ( <span className={[theme.imageWrapper, alignmentClassName].join(' ')} contentEditable={false} style={style}> <img src={src || url} alt={alt} width={width} height={height} className={[theme.image, focusClassName].join(' ')}/> {this.renderProgress(progress, theme)} </span> ); } }
JavaScript
class AntiReplayWindow { constructor() { // window bitmap looks as follows: // v- upper end lower end --v // [111011 ... window_n]...[11111101 ... window_0] this.window = []; this.reset(); } /** * Initializes the anti replay window to its default state */ reset() { this.window = []; for (let i = 0; i < width / INT_SIZE; i++) { this.window[i] = 0; } this.ceiling = width - 1; } /** * Checks if the packet with the given sequence number may be received or has to be discarded * @param seq_num - The sequence number of the packet to be checked */ mayReceive(seq_num) { if (seq_num > this.ceiling + width) { // we skipped a lot of packets... I don't think we should accept return false; } else if (seq_num > this.ceiling) { // always accept new packets return true; } else if (seq_num >= this.ceiling - width + 1 && seq_num <= this.ceiling) { // packet falls within the window, check if it was received already. // if so, don't accept return !this.hasReceived(seq_num); } else /* seq_num <= this.ceiling - width */ { // too old, don't accept return false; } } /** * Checks if the packet with the given sequence number is marked as received * @param seq_num - The sequence number of the packet to be checked */ hasReceived(seq_num) { // check if the packet was received already const lowerBound = this.ceiling - width + 1; // find out where the bit is located const bitIndex = seq_num - lowerBound; const windowIndex = Math.floor(bitIndex / INT_SIZE); const windowBit = bitIndex % INT_SIZE; const flag = 1 << windowBit; // check if it is set; return (this.window[windowIndex] & flag) === flag; } /** * Marks the packet with the given sequence number as received * @param seq_num - The sequence number of the packet */ markAsReceived(seq_num) { if (seq_num > this.ceiling) { // shift the window let amount = seq_num - this.ceiling; // first shift whole blocks while (amount > INT_SIZE) { for (let i = 1; i < this.window.length; i++) { this.window[i - 1] = this.window[i]; } this.window[this.window.length - 1] = 0; amount -= INT_SIZE; } // now shift bitwise (to the right) let overflow = 0; for (let i = 0; i < this.window.length; i++) { overflow = this.window[i] << (INT_SIZE - amount); // BBBBBBAA => AA000000 this.window[i] = this.window[i] >>> amount; // BBBBBBAA ==> 00BBBBBB if (i > 0) this.window[i - 1] |= overflow; } // and remember the new ceiling this.ceiling = seq_num; } const lowerBound = this.ceiling - width + 1; // find out where the bit is located const bitIndex = seq_num - lowerBound; const windowIndex = Math.floor(bitIndex / INT_SIZE); const windowBit = bitIndex % INT_SIZE; const flag = 1 << windowBit; // and set it this.window[windowIndex] |= flag; } }
JavaScript
class DebugNode__PRE_R3__ { /** * @param {?} nativeNode * @param {?} parent * @param {?} _debugContext */ constructor(nativeNode, parent, _debugContext) { this.listeners = []; this.parent = null; this._debugContext = _debugContext; this.nativeNode = nativeNode; if (parent && parent instanceof DebugElement__PRE_R3__) { parent.addChild(this); } } /** * @return {?} */ get injector() { return this._debugContext.injector; } /** * @return {?} */ get componentInstance() { return this._debugContext.component; } /** * @return {?} */ get context() { return this._debugContext.context; } /** * @return {?} */ get references() { return this._debugContext.references; } /** * @return {?} */ get providerTokens() { return this._debugContext.providerTokens; } }
JavaScript
class DebugElement__PRE_R3__ extends DebugNode__PRE_R3__ { /** * @param {?} nativeNode * @param {?} parent * @param {?} _debugContext */ constructor(nativeNode, parent, _debugContext) { super(nativeNode, parent, _debugContext); this.properties = {}; this.attributes = {}; this.classes = {}; this.styles = {}; this.childNodes = []; this.nativeElement = nativeNode; } /** * @param {?} child * @return {?} */ addChild(child) { if (child) { this.childNodes.push(child); ((/** @type {?} */ (child))).parent = this; } } /** * @param {?} child * @return {?} */ removeChild(child) { /** @type {?} */ const childIndex = this.childNodes.indexOf(child); if (childIndex !== -1) { ((/** @type {?} */ (child))).parent = null; this.childNodes.splice(childIndex, 1); } } /** * @param {?} child * @param {?} newChildren * @return {?} */ insertChildrenAfter(child, newChildren) { /** @type {?} */ const siblingIndex = this.childNodes.indexOf(child); if (siblingIndex !== -1) { this.childNodes.splice(siblingIndex + 1, 0, ...newChildren); newChildren.forEach((/** * @param {?} c * @return {?} */ c => { if (c.parent) { ((/** @type {?} */ (c.parent))).removeChild(c); } ((/** @type {?} */ (child))).parent = this; })); } } /** * @param {?} refChild * @param {?} newChild * @return {?} */ insertBefore(refChild, newChild) { /** @type {?} */ const refIndex = this.childNodes.indexOf(refChild); if (refIndex === -1) { this.addChild(newChild); } else { if (newChild.parent) { ((/** @type {?} */ (newChild.parent))).removeChild(newChild); } ((/** @type {?} */ (newChild))).parent = this; this.childNodes.splice(refIndex, 0, newChild); } } /** * @param {?} predicate * @return {?} */ query(predicate) { /** @type {?} */ const results = this.queryAll(predicate); return results[0] || null; } /** * @param {?} predicate * @return {?} */ queryAll(predicate) { /** @type {?} */ const matches = []; _queryElementChildren(this, predicate, matches); return matches; } /** * @param {?} predicate * @return {?} */ queryAllNodes(predicate) { /** @type {?} */ const matches = []; _queryNodeChildren(this, predicate, matches); return matches; } /** * @return {?} */ get children() { return (/** @type {?} */ (this .childNodes // .filter((/** * @param {?} node * @return {?} */ (node) => node instanceof DebugElement__PRE_R3__)))); } /** * @param {?} eventName * @param {?} eventObj * @return {?} */ triggerEventHandler(eventName, eventObj) { this.listeners.forEach((/** * @param {?} listener * @return {?} */ (listener) => { if (listener.name == eventName) { listener.callback(eventObj); } })); } }
JavaScript
class SlotManager { /** * Constructor of the class. */ constructor() { this.intents = {}; } /** * Returns an slot given the intent and entity. * @param {String} intent Name of the intent. * @param {String} entity Name of the entity. * @returns {Object} Slot or undefined if not found. */ getSlot(intent, entity) { if (!this.intents[intent]) { return undefined; } return this.intents[intent][entity]; } /** * Indicates if a given slot exists, given the intent and entity. * @param {String} intent Name of the intent. * @param {String} entity Name of the entity. * @returns {boolean} True if the slot exists, false otherwise. */ existsSlot(intent, entity) { return this.getSlot(intent, entity) !== undefined; } /** * Adds a new slot for a given intent and entity. * @param {String} intent Name of the intent. * @param {String} entity Name of the entity. * @param {boolean} mandatory Flag indicating if is mandatory or optional. * @param {Object} questions Question to ask when is mandatory, by locale. * @returns {Object} New slot instance. */ addSlot(intent, entity, mandatory = false, questions) { if (!this.intents[intent]) { this.intents[intent] = {}; } this.intents[intent][entity] = { intent, entity, mandatory, locales: questions || {}, }; return this.intents[intent][entity]; } /** * Remove an slot given the intent and the entity. * @param {String} intent Name of the intent. * @param {String} entity Name of the entity. */ removeSlot(intent, entity) { if (this.intents[intent]) { delete this.intents[intent][entity]; } } /** * Add several entities if they don't exists. * @param {String} intent Name of the intent. * @param {String[]} entities List of entities. * @returns {Object[]} Array of resulting entities. */ addBatch(intent, entities) { const result = []; if (entities && entities.length > 0) { entities.forEach(entity => { let slot = this.getSlot(intent, entity); if (!slot) { slot = this.addSlot(intent, entity); } result.push(slot); }); } return result; } /** * Given an intent, return the array of entity names of this intent. * @param {String} intent Name of the intent. * @returns {String[]} Array of entity names of the intent. */ getIntentEntityNames(intent) { if (!this.intents[intent]) { return undefined; } return Object.keys(this.intents[intent]); } /** * Clear the slot manager. */ clear() { this.intents = {}; } /** * Loads the slot manager content. * @param {Object} src Source content. */ load(src) { this.intents = src || {}; } /** * Returns the slot manager content. * @returns {Object} Slot manager content. */ save() { return this.intents; } /** * Given an intent return the mandatory slots. * @param {String} intent Name of the intent * @returns {Object} Object with the mandatory slots. */ getMandatorySlots(intent) { const result = {}; const intentSlots = this.intents[intent]; if (intentSlots) { const keys = Object.keys(intentSlots); for (let i = 0, l = keys.length; i < l; i += 1) { const slot = intentSlots[keys[i]]; if (slot.mandatory) { result[slot.entity] = slot; } } } return result; } cleanContextEntities(intent, srcContext) { const context = srcContext; if (context.slotFill) { return; } const mandatorySlots = this.getMandatorySlots(intent); const keys = Object.keys(mandatorySlots); if (keys.length === 0) { return; } keys.forEach(key => { delete context[key]; }); } process(srcResult, srcContext) { const result = srcResult; const context = srcContext; this.cleanContextEntities(result.intent, context); if (context.slotFill) { result.intent = context.slotFill.intent; result.answer = context.slotFill.answer; result.srcAnswer = context.slotFill.srcAnswer; } if (!result.intent || result.intent === 'None') { return false; } if (context.slotFill && context.slotFill.intent === result.intent) { result.entities = [...context.slotFill.entities, ...result.entities]; } const mandatorySlots = this.getMandatorySlots(result.intent); let keys = Object.keys(mandatorySlots); if (keys.length === 0) { return false; } if (context.slotFill) { result.entities.push({ entity: context.slotFill.currentSlot, utteranceText: result.utterance, sourceText: result.utterance, accuracy: 0.95, start: 0, end: result.utterance.length - 1, len: result.utterance.length, }); } for (let i = 0, l = result.entities.length; i < l; i += 1) { delete mandatorySlots[result.entities[i].entity]; } keys = Object.keys(mandatorySlots); if (!keys || keys.length === 0) { return true; } if (context.slotFill && context.slotFill.intent === result.intent) { result.localeIso2 = context.slotFill.localeIso2; } result.slotFill = { localeIso2: result.localeIso2, intent: result.intent, entities: result.entities, answer: result.answer, srcAnswer: result.srcAnswer, }; const currentSlot = mandatorySlots[keys[0]]; result.slotFill.currentSlot = currentSlot.entity; result.srcAnswer = currentSlot.locales[result.localeIso2]; context.slotFill = result.slotFill; return true; } }
JavaScript
class AbstractService { /** * The service key to be registered with the session. It must be unique. * * @returns {string} The unique service key. */ static get SERVICE_KEY() { return 'abstractService'; } /** Services must have a no-args constructor. */ constructor() { this._provider = null; } setProvider(provider) { this._provider = provider; return this; } // These callbacks will only be called if Class.CONTEXT is defined. reducer(state, action) {} /** * Called by ModuleManager (if CONTEXT is defined) to handle to set up the state of the service provider. * Usually, you would want to expose the interface by setting properties in the * passed-in state. This state is the object that will be referenced when someone * uses the CONTEXT.StateProvider React element. * * Any initialization that depends on other services should be handled in * onSessionLoad() or onSessionMount() instead. * * @param {object} state The state of the service provider. */ onServiceLoad(state) {} /** * Called by ModuleManager (if CONTEXT is defined) to handle any set up with the service provider itself. * This is called AFTER onServiceLoad(). * * @param {ServiceProvider} provider The service provider containing the state and dispatch. */ onServiceMount(provider) {} /** * Called by ModuleManager (if CONTEXT is defined) to handle any tear down with the service provider itself. * This is called BEFORE onServiceUnload(). * * @param {ServiceProvider} provider The service provider container the state and dispatch. */ onServiceUnmount(provider) {} /** * Called by ModuleManager (if CONTEXT is defined) to handle any tear down with the state of the service provider. * Do remove ALL properties, listeners, handlers, etc. from the state to prevent memory leaks! * * @param {object} state The state of the service provider. */ onServiceUnload(state) {} // These callbacks will be called every time, regardless if Class.CONTEXT is null. /** * Called by ModuleManager to handle any set up with the session state. * * @param {object} session The session state. */ onSessionLoad(session) {} /** * Called by ModuleManager to handle any set up with the session provider. * This is called AFTER onSessionLoad(). * * @param {SessionProvider} provider The session provider containing state and dispatch. */ onSessionMount(provider) {} /** * Called by ModuleManager to handle any tear down with the session provider. * This is called BEFORE onSessionUnload(). * * @param {SessionProvider} provider The session provider containing state and dispatch. */ onSessionUnmount(provider) {} /** * Called by ModuleManager to handle any tear down with the session state. * * @param {object} session The session state. */ onSessionUnload(session) {} getProvider() { return this._provider; } }
JavaScript
class EnvironmentsStore { constructor() { this.state = {}; this.state.environments = []; this.state.stoppedCounter = 0; this.state.availableCounter = 0; this.state.paginationInformation = {}; return this; } /** * * Stores the received environments. * * In the main environments endpoint, each environment has the following schema * { name: String, size: Number, latest: Object } * In the endpoint to retrieve environments from each folder, the environment does * not have the `latest` key and the data is all in the root level. * To avoid doing this check in the view, we store both cases the same by extracting * what is inside the `latest` key. * * If the `size` is bigger than 1, it means it should be rendered as a folder. * In those cases we add `isFolder` key in order to render it properly. * * @param {Array} environments * @returns {Array} */ storeEnvironments(environments = []) { const filteredEnvironments = environments.map((env) => { let filtered = {}; if (env.size > 1) { filtered = Object.assign({}, env, { isFolder: true, folderName: env.name }); } if (env.latest) { filtered = Object.assign(filtered, env, env.latest); delete filtered.latest; } else { filtered = Object.assign(filtered, env); } return filtered; }); this.state.environments = filteredEnvironments; return filteredEnvironments; } setPagination(pagination = {}) { const normalizedHeaders = gl.utils.normalizeHeaders(pagination); const paginationInformation = gl.utils.parseIntPagination(normalizedHeaders); this.state.paginationInformation = paginationInformation; return paginationInformation; } /** * Stores the number of available environments. * * @param {Number} count = 0 * @return {Number} */ storeAvailableCount(count = 0) { this.state.availableCounter = count; return count; } /** * Stores the number of closed environments. * * @param {Number} count = 0 * @return {Number} */ storeStoppedCount(count = 0) { this.state.stoppedCounter = count; return count; } }
JavaScript
class TableConstraint { /** * @param {object} o */ constructor(o) { this.table_id = +o.table_id; if (o.table) { this.table_id = o.table.id; } this.type = o.type; this.id = !o.id ? null : +o.id; this.configuration = stringToJSON(o.configuration) || {}; contract.class(this); } /** * @type {object} */ get toJson() { return { type: this.type, configuration: this.configuration, }; } /** * @param {*} where * @param {*} selectopts * @returns {Promise<TableConstraint[]>} */ static async find(where, selectopts) { const db_flds = await db.select("_sc_table_constraints", where, selectopts); return db_flds.map((dbf) => new TableConstraint(dbf)); } /** * @param {*} where * @returns {Promise<TableConstraint>} */ static async findOne(where) { const p = await db.selectMaybeOne("_sc_table_constraints", where); return p ? new TableConstraint(p) : null; } /** * @param {*} f * @returns {Promise<TableConstraint>} */ static async create(f) { const con = new TableConstraint(f); const { id, ...rest } = con; const fid = await db.insert("_sc_table_constraints", rest); con.id = fid; if (con.type === "Unique" && con.configuration.fields) { const Table = require("./table"); const table = await Table.findOne({ id: con.table_id }); await db.add_unique_constraint(table.name, con.configuration.fields); } return con; } /** * @returns {Promise<void>} */ async delete() { await db.deleteWhere("_sc_table_constraints", { id: this.id }); if (this.type === "Unique" && this.configuration.fields) { const Table = require("./table"); const table = await Table.findOne({ id: this.table_id }); await db.drop_unique_constraint(table.name, this.configuration.fields); } } /** * @param {*} table * @param {*} field * @returns {Promise<void>} */ static async delete_field_constraints(table, field) { const tblcs = await TableConstraint.find({ table_id: table.id }); for (const c of tblcs) { if (c.configuration.fields && c.configuration.fields.includes(field.name)) await c.delete(); } } /** * @type {string[]} */ static get type_options() { return ["Unique"]; } }
JavaScript
class SearchBar extends Component { constructor(props){ super(props); //calls the constructor of the extended function(Component) this.state = {term: ''};//initialize state propeerty. //State can contain multiple properties. //Here we care about the term the user endered } render(){ //method so it can renders itself. it is still a function despite the syntax return ( <div> <input value={this.state.term} onChange={event => this.setState({ term: event.target.value })}/> </div> ); //onChange is an out of the box event. It is a default react property. //setState changes the state of the instance of a class //Whenever we reference a javascript variable, we wrap it around {} }; }
JavaScript
class Carousel3D { constructor(o) { // Helpers const $=function(s){return document.querySelector(s)}; const $$=function(s){let nl=document.querySelectorAll(s),a=[];for(let i=0,l=nl.length;i<l;i++){a[i]=nl[i]}return a}; // General let carouselStr = o.carousel; let carousel = $(carouselStr); let itemsStr = o.items; let items = $$(itemsStr); let itemsPercentOf = o.itemsPercentOf || 0.25; let perspective = o.perspective || o.perspective === 0 ? o.perspective : 0.25; let depth = o.depth || o.depth === 0 ? 1 / o.depth : 2; let float = o.float || 'left'; // Filters let filterOpacity = o.opacity ? o.opacity : 1; let filterGrayscale = o.grayscale ? o.grayscale : 0; let filterSepia = o.sepia ? o.sepia : 0; let filterBlur = o.blur ? o.blur : 0; // Math Dependencies let itemWidthAndHeight = ''; let itemMargin = ''; let widthRadius = 0; let heightRadius = 0; let degrees = []; let degree = 0; let len = items.length; let half = Math.ceil(len / 2); let incBy = 360 / len; // Animation let animate = o.animate || o.animate === 0 ? o.animate : 0; let fps = o.fps || o.fps === 0 ? o.fps : 62.5; let speed = animate ? animate / fps : 0; let divisions = animate ? animate / speed : 1; let fromDegree = 0; let toDegreeHigher = null; let degreesToAnimateBy = 0; let turning = function() { fromDegree += degreesToAnimateBy; let goToDegree = fromDegree < 0 ? 360 - ((-1 * fromDegree) % 360) : fromDegree; turn(goToDegree); }; let animating = function() { setTimeout(function() { toDegreeHigher ? fromDegree >= degree ? clearTimeout(this) : (turning(), animating()) : fromDegree <= degree ? clearTimeout(this) : (turning(), animating()); }, speed); }; // Run let run = function(extDegree) { if (animate) { let turnTo = extDegree; toDegreeHigher = turnTo > degree; fromDegree = degree; degree = turnTo; degreesToAnimateBy = (degree - fromDegree) / divisions; animating(); } else { turn(extDegree); } }; // Turn let turn = function(deg) { let i = 0; var d = []; // new degrees array for (;i<len;i++) { d[i] = degrees[i] + deg + 90; } i = 0; for (;i<len;i++) { let r = d[i] * Math.PI / 180; let rr = ((degrees[i] + deg) % 360) * Math.PI / 180; let percentAsDecimal = rr < Math.PI ? rr / Math.PI : ((Math.PI * 2) - rr) / Math.PI; let s = rr > Math.PI ? 1 - ((Math.PI - (rr - Math.PI)) / (Math.PI * depth)) : 1 - (rr / (Math.PI * depth)); let x = widthRadius * Math.cos(r) + widthRadius; let y = heightRadius * Math.sin(r) + heightRadius; let z = (function() { var degreeMod360 = (degrees[i] + deg + 180) % 360; return Math.round(degreeMod360 > 180 ? (180 - (degreeMod360 - 180)) / incBy : degreeMod360 / incBy); }()); let p = 'position:absolute;z-index:' + z + ';left:' + x + 'px;top:' + y + 'px;' + itemMargin + itemWidthAndHeight + '-webkit-transform:scale(' + s + ',' + s + ');' + '-moz-transform:scale(' + s + ',' + s + ');' + '-ms-transform:scale(' + s + ',' + s + ');' + '-o-transform:scale(' + s + ',' + s + ');' + 'transform:scale(' + s + ',' + s + ');'; let fOpacity = 'opacity:' + (filterOpacity < 1 ? 1 - ((1 - (1 * filterOpacity)) * percentAsDecimal) : 1) + ';'; let fGrayscale = 'grayscale(' + (filterGrayscale ? (1 * filterGrayscale) * percentAsDecimal : 0) + ')'; let fSepia = 'sepia('+ (filterSepia ? (1 * filterSepia) * percentAsDecimal : 0) + ')'; let fBlur = 'blur('+ (filterBlur ? (filterBlur * percentAsDecimal) : 0) + 'px)'; let f = fOpacity + '-webkit-filter:' + fGrayscale + ' ' + fSepia + ' ' + fBlur + ';' + '-moz-filter:' + fGrayscale + ' ' + fSepia + ' ' + fBlur + ';' + '-ms-filter:' + fGrayscale + ' ' + fSepia + ' ' + fBlur + ';' + '-o-filter:' + fGrayscale + ' ' + fSepia + ' ' + fBlur + ';' + 'filter:' + fGrayscale + ' ' + fSepia + ' ' + fBlur + ';'; items[i].style.cssText = p + f; } }; // turn // Reset let reset = function() { // Carousel size let carouselWidth = carousel.offsetWidth; let carouselHeight = carouselWidth * perspective; carousel.style.height = carouselHeight + 'px'; // Items size let aspectPointWidth = items[0].offsetWidth; let aspectPointHeight = items[0].offsetHeight; let itemAspectRatio = aspectPointHeight / aspectPointWidth; let itemWidthNum = carouselWidth * itemsPercentOf; itemWidthAndHeight = 'width:' + itemWidthNum + 'px;height:auto;'; itemMargin = 'margin:-' + ((itemWidthNum * itemAspectRatio) / 2) + 'px auto auto -' + (itemWidthNum / 2) + 'px;'; // Math widthRadius = carouselWidth / 2; heightRadius = carouselHeight / 2; degrees = [float === 'left' ? 360 : 0]; // Reset degrees and first elem for (let i=1;i<len;i++) { degrees.push(float === 'left' ? 360 - Math.floor(i * incBy) : Math.floor(i * incBy)); } // Position the items turn(0); }; // Hard reset let hardReset = function() { carousel = $(carouselStr); items = $$(itemsStr); len = items.length; half = Math.ceil(len / 2); incBy = 360 / len; reset(); }; // Init (function() { carousel.style.position = 'relative'; reset.bind(this)(); window.addEventListener('load', reset.bind(this)); window.addEventListener('resize',reset.bind(this)); }.bind(this))() // Dev API return { turn: run, reset: hardReset } } // constructor } // Carousel3D
JavaScript
class Entity1 extends BaseModel { /** * @constructor * @param {Object} obj The object passed to constructor */ constructor(obj) { super(obj); if (obj === undefined || obj === null) return; this.accessFee = this.constructor.getValue(obj.accessFee || obj.access_fee); this.commitmentDuration = this.constructor.getValue(obj.commitmentDuration || obj.commitment_duration); this.debit = this.constructor.getValue(obj.debit); this.entityId = this.constructor.getValue(obj.entityId || obj.entity_id); this.interventionTimeGuaranteedApplicability = this.constructor.getValue(obj.interventionTimeGuaranteedApplicability || obj.intervention_time_guaranteed_applicability); this.interventionTimeGuaranteedDelay = this.constructor.getValue(obj.interventionTimeGuaranteedDelay || obj.intervention_time_guaranteed_delay); this.name = this.constructor.getValue(obj.name); this.preferredOffer = this.constructor.getValue(obj.preferredOffer || obj.preferred_offer); this.recoveryTimeGuaranteedApplicability = this.constructor.getValue(obj.recoveryTimeGuaranteedApplicability || obj.recovery_time_guaranteed_applicability); this.recoveryTimeGuaranteedDelay = this.constructor.getValue(obj.recoveryTimeGuaranteedDelay || obj.recovery_time_guaranteed_delay); this.recurringPrice = this.constructor.getValue(obj.recurringPrice || obj.recurring_price); } /** * Function containing information about the fields of this model * @return {array} Array of objects containing information about the fields */ static mappingInfo() { return super.mappingInfo().concat([ { name: 'accessFee', realName: 'access_fee' }, { name: 'commitmentDuration', realName: 'commitment_duration' }, { name: 'debit', realName: 'debit' }, { name: 'entityId', realName: 'entity_id' }, { name: 'interventionTimeGuaranteedApplicability', realName: 'intervention_time_guaranteed_applicability', }, { name: 'interventionTimeGuaranteedDelay', realName: 'intervention_time_guaranteed_delay', }, { name: 'name', realName: 'name' }, { name: 'preferredOffer', realName: 'preferred_offer' }, { name: 'recoveryTimeGuaranteedApplicability', realName: 'recovery_time_guaranteed_applicability', }, { name: 'recoveryTimeGuaranteedDelay', realName: 'recovery_time_guaranteed_delay' }, { name: 'recurringPrice', realName: 'recurring_price' }, ]); } /** * Function containing information about discriminator values * mapped with their corresponding model class names * * @return {object} Object containing Key-Value pairs mapping discriminator * values with their corresponding model classes */ static discriminatorMap() { return {}; } }
JavaScript
class BaseScript { constructor() { this.constants = [[], []]; this.name = '<main>'; this.info = []; this.code = []; } }
JavaScript
class VMActorScript extends BaseScript { constructor() { super(...arguments); this.info = exports.commonFunctions; } }
JavaScript
class BitcoinException extends exception.Exception { /** * @constructor * @summary Creates a new error from the bitcoin network * @param {*} bitcoinErr The RAW error from the ethereum server */ constructor(bitcoinErr) { super("Error interacting with Bitcoin network", exception.ErrorCodes.COM_FAILURE, bitcoinErr); } }
JavaScript
class CombatFFG extends Combat { /** @override */ _getInitiativeRoll(combatant, formula) { const cData = duplicate(combatant.actor.data.data); if (combatant.actor.data.type === "vehicle") { return new RollFFG("0"); } if (formula === "Vigilance") { formula = _getInitiativeFormula( cData.skills.Vigilance, parseInt(cData.characteristics.Willpower.value) ); } else if (formula === "Cool") { formula = _getInitiativeFormula( cData.skills.Cool, parseInt(cData.characteristics.Presence.value) ); } const rollData = combatant.actor ? combatant.actor.getRollData() : {}; let roll = new RollFFG(formula, rollData).roll(); const total = roll.ffg.success + roll.ffg.advantage * 0.01; roll._result = total; roll._total = total; return roll; } /** @override */ _getInitiativeFormula(combatant) { return CONFIG.Combat.initiative.formula || game.system.data.initiative; } getCombatant(id) { return this.turns.find(({ data }) => data._id === id); } /** @override */ async rollInitiative( ids, { formula = null, updateTurn = true, messageOptions = {} } = {} ) { let initiative = this; let promise = new Promise(async function (resolve, reject) { const id = randomID(); let whosInitiative = initiative.combatant.name; let dicePools = []; let vigilanceDicePool = new DicePoolFFG({}); let coolDicePool = new DicePoolFFG({}); let addDicePool = new DicePoolFFG({}); const defaultInitiativeFormula = formula || initiative._getInitiativeFormula(); if (Array.isArray(ids) && ids.length > 1) { whosInitiative = "Multiple Combatants"; } else { // Make sure we are dealing with an array of ids ids = typeof ids === "string" ? [ids] : ids; const c = initiative.getCombatant(ids[0]); const data = c.actor.data.data; whosInitiative = c.actor.name; vigilanceDicePool = _buildInitiativePool(data, "Vigilance"); coolDicePool = _buildInitiativePool(data, "Cool"); const initSkills = Object.keys(data.skills).filter( (skill) => data.skills[skill].useForInitiative ); initSkills.forEach((skill) => { if (dicePools.find((p) => p.name === skill)) return; const skillPool = _buildInitiativePool(data, skill); skillPool.label = data.skills[skill].label; skillPool.name = skill; dicePools.push(skillPool); }); } if (dicePools.findIndex((p) => p.name === "Vigilance") < 0) { vigilanceDicePool.label = "SWFFG.SkillsNameVigilance"; vigilanceDicePool.name = "Vigilance"; dicePools.push(vigilanceDicePool); } if (dicePools.findIndex((p) => p.name === "Cool") < 0) { coolDicePool.label = "SWFFG.SkillsNameCool"; coolDicePool.name = "Cool"; dicePools.push(coolDicePool); } const title = game.i18n.localize("SWFFG.InitiativeRoll") + ` ${whosInitiative}...`; const content = await renderTemplate( "systems/starwarsffg/templates/dialogs/ffg-initiative.html", { id, dicePools, addDicePool, defaultInitiativeFormula, } ); new Dialog({ title, content, buttons: { one: { icon: '<i class="fas fa-check"></i>', label: game.i18n.localize("InitiativeRoll"), callback: async () => { const container = document.getElementById(id); const currentId = initiative.combatant.id; const baseFormulaType = container.querySelector( 'input[name="skill"]:checked' ).value; // Iterate over Combatants, performing an initiative roll for each const [updates, messages] = ids.reduce( (results, id, i) => { let [updates, messages] = results; // Get Combatant data const c = initiative.getEmbeddedDocument("Combatant", id); if (!c || !c.isOwner) return resolve(results); // Detemine Formula let pool = _buildInitiativePool( c.actor.data.data, baseFormulaType ); const addPool = DicePoolFFG.fromContainer( container.querySelector(`.addDicePool`) ); pool.success += +addPool.success; pool.advantage += +addPool.advantage; pool.failure += +addPool.failure; pool.threat += +addPool.threat; pool.boost += +addPool.boost; pool.setback += +addPool.setback; const rollData = c.actor ? c.actor.getRollData() : {}; let roll = new RollFFG( pool.renderDiceExpression(), rollData, { success: pool.success, advantage: pool.advantage, failure: pool.failure, threat: pool.threat, } ).roll(); const total = roll.ffg.success + roll.ffg.advantage * 0.01; roll._result = total; roll._total = total; // Roll initiative updates.push({ _id: id, initiative: roll.total }); // Determine the roll mode let rollMode = messageOptions.rollMode || game.settings.get("core", "rollMode"); if ((c.token.hidden || c.hidden) && rollMode === "roll") rollMode = "gmroll"; // Construct chat message data let messageData = mergeObject( { speaker: { scene: canvas.scene.id, actor: c.actor ? c.actor.id : null, token: c.token.id, alias: c.token.name, }, flavor: `${c.token.name} ${game.i18n.localize( "SWFFG.InitiativeRoll" )} (${game.i18n.localize( `SWFFG.SkillsName${baseFormulaType.replace( /[: ]/g, "" )}` )})`, flags: { "core.initiativeRoll": true }, }, messageOptions ); const chatData = roll.toMessage(messageData, { create: false, rollMode, }); // Play 1 sound for the whole rolled set if (i > 0) chatData.sound = null; messages.push(chatData); // Return the Roll and the chat data return results; }, [[], []] ); if (!updates.length) return initiative; // Update multiple combatants await initiative.updateEmbeddedDocuments("Combatant", updates); // Ensure the turn order remains with the same combatant if (updateTurn) { await initiative.update({ turn: initiative.turns.findIndex((t) => t.id === currentId), }); } // Create multiple chat messages await CONFIG.ChatMessage.documentClass.create(messages); resolve(initiative); }, }, two: { icon: '<i class="fas fa-times"></i>', label: game.i18n.localize("SWFFG.Cancel"), }, }, }).render(true); }); return await promise; } }