language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class ExampleModule extends BaseModule {
async configure(options) {
await super.configure(options);
// load and register a sub-schema
const schema = await options.container.create(INJECT_SCHEMA);
schema.addSchema('example', require('./schema.json'));
// bind a service by name
this.bind('example-service').toConstructor(ExampleService);
options.logger.debug(options, 'example module configured');
}
} |
JavaScript | class ErrorHandler
{
///////////////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
///////////////////////////////////////////////////////////////////////////////////////
/**
* Constructor.
*/
constructor()
{
window.onerror = (errorText, url, lineNumber, columnNumber, error) => this._handleJavaScriptError(errorText, url, lineNumber, columnNumber, error);
Radio.channel('rodan').reply(RODAN_EVENTS.REQUEST__SYSTEM_HANDLE_ERROR, (options) => this._handleError(options));
}
///////////////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
///////////////////////////////////////////////////////////////////////////////////////
/**
* Handles Javscript error.
*/
_handleJavaScriptError(errorText, url, lineNumber, columnNumber, error)
{
var text = 'Rodan Client has encountered an unexpected error.<br><br>';
text += 'text: ' + errorText + '<br>';
text += 'url: ' + url + '<br>';
text += 'line: ' + lineNumber + '<br>';
text += 'column: ' + columnNumber;
this._showError(text, error);
}
/**
* Handle error.
*/
_handleError(options)
{
var response = options.response;
var responseTextObject = response.responseText !== '' ? JSON.parse(response.responseText) : null;
if (responseTextObject !== null)
{
if (responseTextObject.hasOwnProperty('error_code'))
{
var error = options.response.responseJSON
var text = error.error_code + '<br>';
text += error.details[0];
Radio.channel('rodan').trigger(RODAN_EVENTS.EVENT__SERVER_ERROR, {json: error});
}
else
{
var response = options.response;
var responseTextObject = JSON.parse(response.responseText);
var message = 'An unknown error occured.';
// Look for message in options first.
if (options.hasOwnProperty('message'))
{
message = options.message;
}
// Go through the response text.
var first = true;
for(var property in responseTextObject)
{
if (responseTextObject.hasOwnProperty(property))
{
message += '\n';
if (first)
{
message += '\n';
first = false;
}
message += responseTextObject[property];
}
}
this._showError(message, null);
}
}
else
{
this._showError(response.statusText, null);
}
}
/**
* Show error.
*/
_showError(text, error)
{
console.error(error);
Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__MODAL_ERROR, {content: text, title: 'Error'});
}
} |
JavaScript | class InvalidParameterError extends Error {
constructor (message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
} |
JavaScript | class BatchAccountCreateParameters {
/**
* Create a BatchAccountCreateParameters.
* @property {string} location The region in which to create the account.
* @property {object} [tags] The user-specified tags associated with the
* account.
* @property {object} [autoStorage] The properties related to the
* auto-storage account.
* @property {string} [autoStorage.storageAccountId] The resource ID of the
* storage account to be used for auto-storage account.
* @property {string} [poolAllocationMode] The allocation mode to use for
* creating pools in the Batch account. The pool allocation mode also affects
* how clients may authenticate to the Batch Service API. If the mode is
* BatchService, clients may authenticate using access keys or Azure Active
* Directory. If the mode is UserSubscription, clients must use Azure Active
* Directory. The default is BatchService. Possible values include:
* 'BatchService', 'UserSubscription'
* @property {object} [keyVaultReference] A reference to the Azure key vault
* associated with the Batch account.
* @property {string} [keyVaultReference.id] The resource ID of the Azure key
* vault associated with the Batch account.
* @property {string} [keyVaultReference.url] The URL of the Azure key vault
* associated with the Batch account.
* @property {string} [publicNetworkAccess] The network access type for
* accessing Azure Batch account. If not specified, the default value is
* 'enabled'. Possible values include: 'Enabled', 'Disabled'. Default value:
* 'Enabled' .
* @property {object} [encryption] The encryption configuration for the Batch
* account. Configures how customer data is encrypted inside the Batch
* account. By default, accounts are encrypted using a Microsoft managed key.
* For additional control, a customer-managed key can be used instead.
* @property {string} [encryption.keySource] Type of the key source. Possible
* values include: 'Microsoft.Batch', 'Microsoft.KeyVault'
* @property {object} [encryption.keyVaultProperties] Additional details when
* using Microsoft.KeyVault
* @property {string} [encryption.keyVaultProperties.keyIdentifier] Full path
* to the versioned secret. Example
* https://mykeyvault.vault.azure.net/keys/testkey/6e34a81fef704045975661e297a4c053.
* To be usable the following prerequisites must be met:
*
* The Batch Account has a System Assigned identity
* The account identity has been granted Key/Get, Key/Unwrap and Key/Wrap
* permissions
* The KeyVault has soft-delete and purge protection enabled
* @property {object} [identity] The identity of the Batch account.
* @property {string} [identity.principalId] The principal id of the Batch
* account. This property will only be provided for a system assigned
* identity.
* @property {string} [identity.tenantId] The tenant id associated with the
* Batch account. This property will only be provided for a system assigned
* identity.
* @property {string} [identity.type] The type of identity used for the Batch
* account. Possible values include: 'SystemAssigned', 'None'
*/
constructor() {
}
/**
* Defines the metadata of BatchAccountCreateParameters
*
* @returns {object} metadata of BatchAccountCreateParameters
*
*/
mapper() {
return {
required: false,
serializedName: 'BatchAccountCreateParameters',
type: {
name: 'Composite',
className: 'BatchAccountCreateParameters',
modelProperties: {
location: {
required: true,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
autoStorage: {
required: false,
serializedName: 'properties.autoStorage',
type: {
name: 'Composite',
className: 'AutoStorageBaseProperties'
}
},
poolAllocationMode: {
required: false,
serializedName: 'properties.poolAllocationMode',
type: {
name: 'Enum',
allowedValues: [ 'BatchService', 'UserSubscription' ]
}
},
keyVaultReference: {
required: false,
serializedName: 'properties.keyVaultReference',
type: {
name: 'Composite',
className: 'KeyVaultReference'
}
},
publicNetworkAccess: {
required: false,
serializedName: 'properties.publicNetworkAccess',
defaultValue: 'Enabled',
type: {
name: 'Enum',
allowedValues: [ 'Enabled', 'Disabled' ]
}
},
encryption: {
required: false,
serializedName: 'properties.encryption',
type: {
name: 'Composite',
className: 'EncryptionProperties'
}
},
identity: {
required: false,
serializedName: 'identity',
type: {
name: 'Composite',
className: 'BatchAccountIdentity'
}
}
}
}
};
}
} |
JavaScript | class EthereumChainService extends EventEmitter {
constructor(config) {
super();
this.config = config;
}
start() {
if (this._child && this._child.connected) {
this.emit("message", "start");
} else {
const child = this._child = fork(CHAIN_PATH, [], CHAIN_OPTIONS);
child.on("message", (msg) => {
if (!msg || !msg.type){
return;
}
const {type, data} = msg || {};
switch (type) {
case "process-started":
this.emit("message", "start");
return;
case "server-started":
this._serverStarted = true;
this.emit(type, data);
this.emit("message", type, data);
return;
case "server-stopped":
this._serverStarted = false;
this.emit(type, data);
return;
case "db-location":
this.emit(type, data);
return;
}
this.emit("message", type, data);
});
child.on("error", error => {
this.emit("error", error);
this.emit("message", "error", error);
});
child.on("exit", this._exitHandler);
child.stdout.on("data", this._stdHandler.bind(this, "stdout"));
child.stderr.on("data", this._stdHandler.bind(this, "stderr"));
}
}
async startServer(settings) {
if (this._child) {
const options = this._ganacheCoreOptionsFromGanacheSettingsObject(settings);
return new Promise((resolve, reject) => {
const handleServerStarted = () => {
this.removeListener("error", handleServerError);
resolve();
};
const handleServerError = (e) => {
this.removeListener("server-started", handleServerStarted);
reject(e);
};
this.once("server-started", handleServerStarted);
this.once("error", handleServerError);
this._child.send({
type: "start-server",
data: options,
});
});
} else {
throw new Error("Can't start server. Process not started.");
}
}
stopServer() {
if (this._child && this._child.connected) {
return new Promise(resolve => {
this.once("server-stopped", resolve);
this._child.send({
type: "stop-server"
});
});
}
}
getDbLocation() {
if (this._child) {
if (this.isServerStarted()) {
return new Promise(resolve => {
this.once("db-location", resolve);
this._child.send({
type: "get-db-location",
});
});
} else {
throw new Error("Can't get db-location. Server not started.");
}
} else {
throw new Error("Can't get db-location. Process not started.");
}
}
async stop() {
if (this._child) {
await this.stopServer();
this._child.removeListener("exit", this._exitHandler);
this._child.kill("SIGINT");
}
}
isServerStarted() {
return this._serverStarted;
}
/**
* Returns an options object to be used by ganache-core from Ganache settings
* model. Should be broken out to call multiple functions if it becomes even
* moderately complex.
*/
_ganacheCoreOptionsFromGanacheSettingsObject(settings) {
// clone to avoid mutating the settings object in case it's sent elsewhere
let options = cloneDeep(settings.server);
if (settings.randomizeMnemonicOnStart) {
delete options.mnemonic;
}
options.logDirectory = settings.logDirectory;
return options;
}
_exitHandler(code, signal) {
this._child = null;
if (code != null) {
this.emit("message",
"error",
`Blockchain process exited prematurely with code '${code}', due to signal '${signal}'.`,
);
} else {
this.emit("message",
"error",
`Blockchain process exited prematurely due to signal '${signal}'.`,
);
}
}
_stdHandler (stdio, data) {
// Remove all \r's and the final line ending
this.emit("message",
stdio,
data
.toString()
// we don't care enough to handling carriage returns :-|
.replace(/\r/g, "")
);
}
} |
JavaScript | class FilterButton extends Component {
// initialize component
constructor() {
super();
this.state = {};
this.state.filters = [];
this.state.tempActive = null;
}
// when component mounts
componentDidMount() {
window.addEventListener('mouseup', this.onMouseUp);
}
// when component unmounts
componentWillUnmount() {
window.removeEventListener('mouseup', this.onMouseUp);
}
// when user presses mouse down on button
onMouseDown = () => {
this.props.beginDrag(!this.props.active);
this.props.addToDragList(this.props.name);
this.setState({ tempActive: !this.props.active });
};
// when user moves mouse across button
onMouseMove = () => {
if (typeof this.props.drag === 'boolean') {
this.props.addToDragList(this.props.name);
this.setState({ tempActive: this.props.drag });
}
};
// when user releases mouse anywhere
onMouseUp = () => {
this.setState({ tempActive: null });
};
// when user presses key on button
onKeyDown = () => {
this.props.toggle(this.props.name);
}
// display component
render() {
let active;
if (typeof this.state.tempActive === 'boolean')
active = this.state.tempActive;
else
active = this.props.active;
return (
<Button
className='node_search_filter_button'
disabled={!active}
tooltipText={this.props.tooltipText + ' Ctrl+click to solo.'}
onCtrlClick={() => this.props.solo(this.props.name)}
onMouseDown={this.onMouseDown}
onMouseMove={this.onMouseMove}
onKeyDown={this.onKeyDown}
>
<MetanodeChip type={this.props.name} />
{this.props.name}
</Button>
);
}
} |
JavaScript | class CompositeId {
static decode(compositeId) {
if (compositeId.length > CompositeId.MAX_LENGTH) {
throw new InvalidCompositeIdError('maximum length exceeded');
}
const typeSeparatorIndex = compositeId.indexOf(':');
if (typeSeparatorIndex === -1) {
throw new InvalidCompositeIdError(`invalid structure: ${compositeId}`);
}
const type = compositeId.slice(0, typeSeparatorIndex);
if (type !== 's1') {
throw new InvalidCompositeIdError(`invalid type: ${compositeId}`);
}
const str = compositeId.slice(typeSeparatorIndex + 1);
try {
const bitStream = BitStream.fromString(str);
const n = bitStream.bitLength / CompositeId.BITS_PER_FEATURE;
if (!Number.isInteger(n)) {
throw new InvalidCompositeIdError(`invalid bit length: ${bitStream.bitLength}`);
}
const features = new Array(n);
for (let i = 0; i < n; i++) {
const featureType = bitStream.read(1);
const centrelineType = featureType === 0
? CentrelineType.INTERSECTION
: CentrelineType.SEGMENT;
const centrelineId = bitStream.read(CompositeId.BITS_PER_FEATURE - 1);
if (centrelineId === 0) {
throw new InvalidCompositeIdError('invalid zero value for centrelineId');
}
features[i] = { centrelineId, centrelineType };
}
return features;
} catch (err) {
if (err instanceof BitStreamOverflowError) {
throw new InvalidCompositeIdError(err);
} else if (err instanceof BitStreamSerializationError) {
throw new InvalidCompositeIdError(err);
} else {
throw err;
}
}
}
static encode(features) {
const n = features.length;
if (n > CompositeId.MAX_FEATURES) {
throw new InvalidCompositeIdError('maximum number of features exceeded');
}
const numBytes = Math.ceil(n * CompositeId.BITS_PER_FEATURE / 8);
const bytes = new Uint8Array(numBytes);
const bitStream = new BitStream(bytes);
for (let i = 0; i < n; i++) {
const { centrelineId, centrelineType } = features[i];
const featureType = centrelineType === CentrelineType.INTERSECTION ? 0 : 1;
bitStream.write(1, featureType);
bitStream.write(CompositeId.BITS_PER_FEATURE - 1, centrelineId);
}
const str = bitStream.toString();
return `s1:${str}`;
}
} |
JavaScript | class Emoji {
/**
* Specifies Tool as Inline Toolbar Tool
*
* @return {boolean}
*/
static get isInline() {
return true
}
/**
* @param {{api: object}} - Editor.js API
*/
constructor({ api }) {
this.api = api
/**
* Tag represented the term
*
* @type {string}
*/
this.CSS = {
emoji: CSS.emoji,
emojiToolbarBlock: 'cdx-emoji-toolbar-block',
emojiContainer: 'cdx-emoji__container',
emojiInput: 'cdx-emoji__input',
emojiIntro: 'cdx-emoji-suggestion__intro',
emojiAvatar: 'cdx-emoji-suggestion__avatar',
emojiTitle: 'cdx-emoji-suggestion__title',
suggestionsWrapper: 'cdx-emoji-suggestions-wrapper',
simpleSuggestionsWrapper: 'cdx-emoji-simple-suggestions-wrapper',
simpleSuggestion: 'cdx-emoji-simple-suggestion',
suggestion: 'cdx-emoji-suggestion',
inlineToolBar: 'ce-inline-toolbar',
inlineToolBarOpen: 'ce-inline-toolbar--showed',
inlineToolbarButtons: 'ce-inline-toolbar__buttons',
}
/**
* CSS classes
*/
this.iconClasses = {
base: this.api.styles.inlineToolButton,
active: this.api.styles.inlineToolButtonActive,
}
this.nodes = {
emojiWrapper: make('div', this.CSS.emojiContainer),
suggestionsWrapper: make('div', this.CSS.suggestionsWrapper),
// include latest-used && common-suggestions
simpleSuggestionsWrapper: make('div', this.CSS.simpleSuggestionsWrapper),
emojiInput: make('input', this.CSS.emojiInput),
}
this.nodes.emojiInput.addEventListener('focus', () => {
const emojiEl = document.querySelector('#' + this.CSS.emoji)
if (emojiEl) {
const emojiCursorHolder = make('span', CSS.focusHolder)
emojiEl.parentNode.insertBefore(emojiCursorHolder, emojiEl.nextSibling)
}
})
// TODO: cache it
COMMON_EMOJIS.forEach((emoji) => {
const EmojiEl = make('div', this.CSS.simpleSuggestion, {
innerHTML: emoji.imgEl,
})
this.api.tooltip.onHover(EmojiEl, emoji.title, {
delay: 400,
placement: 'top',
})
this._bindSuggestionClick(EmojiEl, emoji)
this.nodes.simpleSuggestionsWrapper.appendChild(EmojiEl)
})
this.nodes.emojiWrapper.appendChild(this.nodes.emojiInput)
this.nodes.emojiWrapper.appendChild(this.nodes.simpleSuggestionsWrapper)
this.nodes.emojiWrapper.appendChild(this.nodes.suggestionsWrapper)
this.nodes.emojiInput.addEventListener(
'keyup',
debounce(this._handleInput.bind(this), 100),
)
}
/**
* handle emoji input
*
* @return {void}
*/
_handleInput(e) {
if (e.code === 'Escape') return this._hideMentionPanel()
if (e.code === 'Enter') {
return console.log('select first item')
}
const inputVal = e.target.value
if (inputVal.trim() !== '') {
this.nodes.simpleSuggestionsWrapper.style.display = 'none'
this.nodes.suggestionsWrapper.style.display = 'block'
} else {
setTimeout(() => {
this.nodes.simpleSuggestionsWrapper.style.display = 'flex'
this.nodes.suggestionsWrapper.style.display = 'none'
})
}
// empty the existed suggestion if need
const emptyContainer = make('div', this.CSS.suggestionsWrapper)
this.nodes.suggestionsWrapper.replaceWith(emptyContainer)
this.nodes.suggestionsWrapper = emptyContainer
const emojiSearchResults = emojiSearch(inputVal).map((item) => {
return {
title: item.name,
imgEl: twemoji.parse(item.char),
}
})
for (let index = 0; index < emojiSearchResults.length; index++) {
const { title, imgEl } = emojiSearchResults[index]
const suggestion = this._drawSuggestion({ title, imgEl })
this.nodes.suggestionsWrapper.appendChild(suggestion)
}
}
/**
* generate suggestion block
* @param {EmojiItem} emoji
* @return {HTMLElement}
*/
_drawSuggestion(emoji) {
const WrapperEl = make('div', this.CSS.suggestion)
const AvatarEl = make('div', this.CSS.emojiAvatar, {
innerHTML: emoji.imgEl,
})
const IntroEl = make('div', this.CSS.emojiIntro)
const TitleEl = make('div', [this.CSS.emojiTitle], {
innerText: emoji.title,
})
WrapperEl.appendChild(AvatarEl)
IntroEl.appendChild(TitleEl)
WrapperEl.appendChild(IntroEl)
this._bindSuggestionClick(WrapperEl, emoji)
return WrapperEl
}
/**
* handle suggestion click
*
* @param {HTMLElement} el
* @param {EmojiItem} emoji
* @memberof Emoji
*/
_bindSuggestionClick(el, emoji) {
el.addEventListener('click', () => {
this.nodes.emojiInput.value = emoji.title
const EmojiEl = document.querySelector('#' + this.CSS.emoji)
if (!EmojiEl) return false
EmojiEl.innerHTML = emoji.imgEl
EmojiEl.classList.add('no-pseudo')
const EmojiParentEl = EmojiEl.parentNode
// 防止重复插入 holder, 否则会导致多次聚焦后光标错位
if (!EmojiParentEl.querySelector(`.${CSS.focusHolder}`)) {
const EmojiCursorHolder = make('span', CSS.focusHolder)
EmojiParentEl.insertBefore(EmojiCursorHolder, EmojiEl.nextSibling)
}
EmojiEl.contenteditable = true
this.closeEmojiPopover()
moveCaretToEnd(EmojiEl.nextElementSibling)
// it worked !
document.querySelector(`.${CSS.focusHolder}`).remove()
insertHtmlAtCaret(' ')
})
}
/**
* close the emoji popover, then focus to emoji holder
*
* @return {void}
*/
closeEmojiPopover() {
this._clearSuggestions()
const emoji = document.querySelector('#' + this.CSS.emoji)
const inlineToolBar = document.querySelector('.' + this.CSS.inlineToolBar)
this._clearInput()
// this.api.toolbar.close is not work
// so close the toolbar by remove the optn class mannully
inlineToolBar.classList.remove(this.CSS.inlineToolBarOpen)
// emoji holder id should be uniq
// 在 moveCaret 定位以后才可以删除,否则定位会失败
setTimeout(() => {
this.removeAllHolderIds()
}, 50)
}
/**
* close the emoji popover, then focus to emoji holder
*
* @return {void}
*/
_hideMentionPanel() {
const emojiEl = document.querySelector('#' + this.CSS.emoji)
if (!emojiEl) return
// empty the mention input
this._clearInput()
this._clearSuggestions()
// closePopover
const inlineToolBar = document.querySelector('.' + this.CSS.inlineToolBar)
// this.api.toolbar.close is not work
// so close the toolbar by remove the open class manually
// this.api.toolbar.close()
inlineToolBar.classList.remove(this.CSS.inlineToolBarOpen)
// move caret to end of the current emoji
if (emojiEl.nextElementSibling) {
moveCaretToEnd(emojiEl.nextElementSibling)
}
// emoji holder id should be uniq
// 在 moveCaret 定位以后才可以删除,否则定位会失败
setTimeout(() => {
this.removeAllHolderIds()
removeElementByClass(CSS.focusHolder)
if (emojiEl.innerHTML === ' ') {
convertElementToText(emojiEl, true, ':')
}
})
}
/**
* Create button element for Toolbar
* @ should not visible in toolbar, so return an empty div
* @return {HTMLElement}
*/
render() {
const emptyDiv = make('div', this.CSS.emojiToolbarBlock)
return emptyDiv
}
/**
* NOTE: inline tool must have this method
*
* @param {Range} range - selected fragment
*/
surround(range) {}
/**
* Check and change Term's state for current selection
*/
checkState(termTag) {
// NOTE: if emoji is init after mention, then the restoreDefaultInlineTools should be called
// otherwise restoreDefaultInlineTools should not be called, because the mention plugin
// called first
//
// restoreDefaultInlineTools 是否调用和 mention / emoji 的初始化循序有关系,
// 如果 mention 在 emoji 之前初始化了,那么 emoji 这里就不需要调用 restoreDefaultInlineTools,
// 否则会导致 mention 无法正常显示。反之亦然。
if (!termTag || termTag.anchorNode.id !== CSS.emoji)
return restoreDefaultInlineTools()
if (termTag.anchorNode.id === CSS.emoji) {
return this._handleEmojiActions()
}
// normal inline tools
return restoreDefaultInlineTools()
}
/**
* show emoji suggestions, hide normal actions like bold, italic etc...inline-toolbar buttons
* 隐藏正常的 粗体,斜体等等 inline-toolbar 按钮,这里是借用了自带 popover 的一个 hack
*/
_handleEmojiActions() {
// NOTE: the custom tool only visible on next tick
setTimeout(() => keepCustomInlineToolOnly('emoji'))
setTimeout(() => {
this.nodes.emojiInput.focus()
}, 100)
}
/**
* clear suggestions list
* @memberof Emoji
*/
_clearSuggestions() {
const node = document.querySelector('.' + this.CSS.suggestionsWrapper)
if (node) {
while (node.firstChild) {
node.removeChild(node.firstChild)
}
}
}
/**
* clear current input
* @memberof Emoji
*/
_clearInput() {
this.nodes.emojiInput.value = ''
}
// 删除所有 emoji-holder 的 id, 因为 closeEmojiPopover 无法处理失焦后
// 自动隐藏的情况
removeAllHolderIds() {
const holders = document.querySelectorAll('.' + this.CSS.emoji)
holders.forEach((item) => item.removeAttribute('id'))
return false
}
renderActions() {
this.nodes.emojiInput.placeholder = '搜索表情'
return this.nodes.emojiWrapper
}
/**
* Sanitizer rule
* @return {{mark: {class: string}}}
*/
static get sanitize() {
return {
[INLINE_BLOCK_TAG.emoji]: {
class: CSS.emoji,
},
img: {
class: 'emoji',
},
}
}
/**
* hide mention panel after popover closed
* @see @link https://editorjs.io/inline-tools-api-1#clear
* @memberof Mention
*/
clear() {
/**
* should clear anchors after user manually click outside the popover,
* otherwise will confuse the next insert
*
* 用户手动点击其他位置造成失焦以后,如果没有输入的话需要清理 anchors,
* 否则会造成下次插入 emoji 的时候定位异常
*
*/
setTimeout(() => this._hideMentionPanel())
}
} |
JavaScript | class UpdateTransaction extends Component {
//Navigationsoptionen
static navigationOptions = ({navigation}) => {
const {params} = navigation.state
return {
title: 'Edit a Transaction',
headerRight: (
<View style={{flex: 1, flexDirection: 'row', marginTop: 15}}>
<TouchableOpacity onPress={params.handleSave} style={{paddingRight: 15, flex: 1}}>
<Image source={require('../images/save.png')} style={{height: 25, width: 25}}/>
</TouchableOpacity>
<TouchableOpacity onPress={params.handleDelete} style={{paddingRight: 15, flex: 1}}>
<Image source={require('../images/garbage.png')} style={{height: 25, width: 25}}/>
</TouchableOpacity>
</View>
)
}
}
constructor(props) {
super(props)
this._validateForm = this._validateForm.bind(this)
this._handleSave = this._handleSave.bind(this)
this._updateTransaction = this._updateTransaction.bind(this)
this._onDataChanged = this._onDataChanged.bind(this)
this._handleDelete = this._handleDelete.bind(this)
}
componentWillMount() {
const {transaction} = this.props.navigation.state.params
const budgets = realm.objects('Budget')
this.setState({
budgets,
formData: {},
transaction
})
this.props.navigation.setParams({
handleSave: this._handleSave,
handleDelete: this._handleDelete
})
}
_validateForm() {
const {name, budget, account, value} = this.state.formData
return (name && budget && account && value)
}
_handleSave() {
Keyboard.dismiss()
if (!this._validateForm()) {
ToastAndroid.show('Bitte alle Werte eingeben', ToastAndroid.SHORT)
return
}
this._updateTransaction()
}
_handleDelete() {
Alert.alert('Transaktion löschen',
'Möchten Sie die Transaktion löschen?',
[
{text: 'Nein', style: 'cancel'},
{text: 'Ja', style: 'OK'}
])
}
_updateTransaction() {
const {name, budget, account, value, note, date} = this.state.formData
const transactionData = {name, budget, account, value, note, date, receipt: null}
if (!updateTransaction(this.state.transaction, transactionData)) {
ToastAndroid.show('Fehler beim Speichern', ToastAndroid.SHORT)
} else {
this.props.navigation.navigate('TransactionIndex', {budget: null})
}
}
_onDataChanged(data) {
this.setState({
formData: data
})
}
render() {
return (
<TransactionForm budgets={this.state.budgets}
onDataChanged={(data) => this._onDataChanged(data)}
budget={this.state.budget} transaction={this.state.transaction}/>
)
}
} |
JavaScript | class QuestionnaireItemMediaAudio extends QuestionnaireItemMedia {
/**
@param {string} [className] CSS class
@param {string} [question]
@param {boolean} [required=false]
@param {string|array<string>} url The URL of the media element to be loaded; if supported by the browser also data URI.
@param {boolean} required Element must report ready before continue.
@param {boolean} [readyOnError=true] Sets ready=true if an error occures.
*/
constructor(className, question, required, url, readyOnError) {
super(className, question, required, url, readyOnError);
this.audioNode = null;
this.progressbar = null;
this.audioPlayDurations = []; // Stores how long the audio got listend to each time
this.audioCreationTime = null; // Point in time when the audio gets created
this.audioStartTimes = []; // Stores when the audio started relative to audioCreationTime
this.replayCount = 0; // Counts how often the audio got replayed explicitly with replay()
}
_createAnswerNode() {
const answerNode = document.createElement("div");
this._createMediaNode();
this.audioCreationTime = new Date().getTime(); // Before play event listener gets set
this.progressbar = document.createElement("progress");
answerNode.appendChild(this.progressbar);
answerNode.appendChild(this.audioNode);
this.audioNode.addEventListener("timeupdate", (event) => this._onProgress(event));
this.audioNode.addEventListener("error", (event) => this._onError(event));
this.audioNode.addEventListener("ended", () => this._onEnded());
this.audioNode.addEventListener("stalled", () => this._onStalled());
this.audioNode.addEventListener("play", () => this._onPlay());
return answerNode;
}
releaseUI() {
this.audioPlayDurations.push(this.audioNode.currentTime);
super.releaseUI();
this.audioNode = null;
this.progressbar = null;
}
_loadMedia() {
this._createMediaNode();
}
_createMediaNode() {
if (this.audioNode !== null) {
TheFragebogen.logger.debug(this.constructor.name + "()", "audioNode was already created.");
return;
}
this.audioNode = new Audio();
this.audioNode.addEventListener("canplaythrough", () => this._onLoaded());
for (let i = 0; i < this.url.length; i++) {
const audioSource = document.createElement("source");
audioSource.src = this.url[i];
this.audioNode.appendChild(audioSource);
}
let pTag = document.createElement("p");
pTag.innerHTML = "This is a fallback content. Your browser does not support the provided audio formats.";
this.audioNode.appendChild(pTag);
}
replay() {
this.audioPlayDurations.push(this.audioNode.currentTime);
this.replayCount += 1;
this._updateAnswer();
this.audioNode.pause();
this.audioNode.currentTime = 0.0;
this.audioNode.play();
}
_play() {
if (this.audioNode === null) {
TheFragebogen.logger.warn(this.constructor.name + "()", "Cannot start playback without this.audioNode.");
return;
}
try {
this.audioNode.play();
} catch (e) {
TheFragebogen.logger.warn(this.constructor.name + "()", "No supported format available.");
this._onError();
}
}
_pause() {
if (this.audioNode === null) {
TheFragebogen.logger.warn(this.constructor.name + "()", "Cannot start playback without this.audioNode.");
return;
}
this.audioNode.pause();
}
_onProgress() {
if (this.progressbar && !isNaN(this.audioNode.duration)) {
this.progressbar.value = (this.audioNode.currentTime / this.audioNode.duration);
}
}
_onPlay() {
this.audioStartTimes.push((new Date().getTime() - this.audioCreationTime) / 1000);
this._updateAnswer();
}
_updateAnswer() {
this.setAnswer([this.url, this.audioNode.duration, this.stallingCount, this.replayCount, this.audioStartTimes, this.audioPlayDurations]);
}
} |
JavaScript | class TopNode extends Node {
constructor(functions) {
super();
let i = 0;
this.topLevelExprs = functions.map(func => this.assignNode(func, this, i++));
}
notifyUpdate(pos, node, returning) {
}
print() {
return this.topLevelExprs.map(func => func.print() + '\n').join("");
}
accept(visitor) {
visitor.onTopNode(this);
}
update(node, returning) {
throw new Error("Method not implemented.");
}
setColour(colour) {
}
} |
JavaScript | class InnerNode extends Node {
constructor() {
super();
this._position = 0;
}
get colour() {
return this._colour;
}
set colour(value) {
this._colour = value;
}
set position(value) {
this._position = value;
}
get position() {
return this._position;
}
set parent(value) {
this._parent = value;
}
get parent() {
return typeof (this._parent) != "undefined" ? this._parent : new NullNode();
}
print() {
throw new Error("Method not implemented.");
}
hasParent() {
if (this._parent)
return true;
return false;
}
update(node, returning) {
if (!(this.parent instanceof NullNode))
this.parent.notifyUpdate(this._position, node, returning); //Update pointer to a subtree of the parent
}
loadVariable(variable, node) {
return false;
}
setColour(colour) {
this._colour = colour;
}
clone() {
return this;
}
removeReduction() {
this._nodes.forEach(node => {
if (node instanceof ReduceNode) {
//If reduce node, remove the reduce node for its original subtree
this._nodes[node.position] = node.original();
node.original().position = node.position;
node.original().parent = this;
}
});
this._nodes.forEach(node => {
node.removeReduction();
});
}
} |
JavaScript | class PriorityQueue {
constructor () {
this.values = [];
}
/**
* Enqueue
*
* @param {any} val - the queue value
* @param {number} priority - priority of the queue
* @return {void}
*/
enqueue (val, priority) {
if (typeof priority !== 'number') throw new Error('priority must be a number');
this.values.push({ val, priority });
this.bubbleUp();
}
/**
* Bubble up
*
* @private
* @description move the last queue (last index) up to the right place
* @return {void}
*/
bubbleUp () {
let index = this.values.length - 1;
const value = this.values[index];
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
const parent = this.values[parentIndex];
if (value.priority >= parent.priority) break;
this.values[parentIndex] = value;
this.values[index] = parent;
index = parentIndex;
}
}
dequeue () {
const min = this.values[0];
const last = this.values.pop();
if (this.values.length) {
this.values[0] = last;
this.sinkDown();
}
return min;
}
/**
* Sink down
*
* @private
* @description move the first index down to the right place
* @return {void}
*/
sinkDown () {
let index = 0;
const { length } = this.values;
const value = this.values[0];
// eslint-disable-next-line no-constant-condition
while (true) {
const leftChildIndex = (2 * index) + 1;
const rightChildIndex = (2 * index) + 2;
let leftChild;
let rightChild;
let swap = null;
if (leftChildIndex < length) {
leftChild = this.values[leftChildIndex];
if (leftChild.priority < value.priority) {
swap = leftChildIndex;
}
}
if (rightChildIndex < length) {
rightChild = this.values[rightChildIndex];
if (
(swap === null && rightChild.priority < value.priority) ||
(swap !== null && rightChild.priority < leftChild.priority)
) {
swap = rightChildIndex;
}
}
if (swap === null) break;
this.values[index] = this.values[swap];
this.values[swap] = value;
index = swap;
}
}
} |
JavaScript | class BigIntegerHelper {
/**
* Convert trits to a bigInteger.
* @param trits The trits to convert.
* @param offset Offset within the array to start.
* @param length The length of the trits array to convert.
* @returns Big integer version of trits.
*/
static tritsToBigInteger(trits, offset, length) {
if (!objectHelper_1.ObjectHelper.isType(trits, Int8Array) || trits.length === 0) {
throw new cryptoError_1.CryptoError("The trits must be a non empty Int8Array");
}
if (!numberHelper_1.NumberHelper.isInteger(offset) || offset < 0) {
throw new cryptoError_1.CryptoError("The offset must be a number >= 0");
}
if (!numberHelper_1.NumberHelper.isInteger(length) || length <= 0) {
throw new cryptoError_1.CryptoError("The length must be a number > 0");
}
if (offset + length > trits.length) {
throw new cryptoError_1.CryptoError("The offset + length is beyond the length of the array");
}
let value = big_integer_1.default.zero;
for (let i = length - 1; i >= 0; i--) {
value = value.multiply(BigIntegerHelper.RADIX).add(big_integer_1.default(trits[offset + i]));
}
return value;
}
/**
* Convert bigInteger to trits.
* @param value The bigInteger to convert to trits.
* @param trits The array to receive the trits.
* @param offset The offset to place the trits in the array.
* @param length The length of the array.
*/
static bigIntegerToTrits(value, trits, offset, length) {
if (!objectHelper_1.ObjectHelper.isType(value, big_integer_1.default)) {
throw new cryptoError_1.CryptoError("The value must be a bigInteger type");
}
if (!objectHelper_1.ObjectHelper.isType(trits, Int8Array)) {
throw new cryptoError_1.CryptoError("The trits must be an Int8Array");
}
if (!numberHelper_1.NumberHelper.isInteger(offset) || offset < 0) {
throw new cryptoError_1.CryptoError("The offset must be a number >= 0");
}
if (!numberHelper_1.NumberHelper.isInteger(length) || length <= 0) {
throw new cryptoError_1.CryptoError("The length must be a number > 0");
}
if (offset + length > trits.length) {
throw new cryptoError_1.CryptoError("The offset + length is beyond the length of the array");
}
let absoluteValue = value.compareTo(big_integer_1.default.zero) < 0 ? value.negate() : value;
for (let i = 0; i < length; i++) {
const divRemainder = absoluteValue.divmod(BigIntegerHelper.RADIX);
absoluteValue = divRemainder.quotient;
let remainder = divRemainder.remainder;
if (remainder > BigIntegerHelper.MAX_TRIT_VALUE) {
remainder = BigIntegerHelper.MIN_TRIT_VALUE;
absoluteValue = absoluteValue.add(big_integer_1.default["1"]);
}
trits[offset + i] = remainder.toJSNumber();
}
if (value.compareTo(big_integer_1.default.zero) < 0) {
for (let i = 0; i < length; i++) {
// Avoid negative zero
trits[offset + i] = trits[offset + i] === 0 ? 0 : -trits[offset + i];
}
}
}
/**
* Convert the bigInteger into bytes.
* @param value The value to convert.
* @param destination The destination array to store the bytes.
* @param offset The offset within the array to store the bytes.
*/
static bigIntegerToBytes(value, destination, offset) {
if (!objectHelper_1.ObjectHelper.isType(value, big_integer_1.default)) {
throw new cryptoError_1.CryptoError("The value must be a bigInteger type");
}
if (!objectHelper_1.ObjectHelper.isType(destination, ArrayBuffer) || destination.byteLength === 0) {
throw new cryptoError_1.CryptoError("The destination must be an array");
}
if (!numberHelper_1.NumberHelper.isInteger(offset) || offset < 0) {
throw new cryptoError_1.CryptoError("The offset must be a number >= 0");
}
if (destination.byteLength - offset < BigIntegerHelper.BYTE_HASH_LENGTH) {
throw new cryptoError_1.CryptoError(`Destination array has invalid size, it must be at least ${BigIntegerHelper.BYTE_HASH_LENGTH}`);
}
// Remember if it is negative for later
const isNeg = value.isNegative() ? -1 : 0;
let hexString = value.toString(16);
if (isNeg === -1) {
// But remove it for now
hexString = hexString.slice(1);
}
// Now make sure the hex string is an even length so the regex works
if (hexString.length % 2 === 1) {
hexString = `0${hexString}`;
}
const matches = hexString.match(/[0-9a-f]{2}/g);
// Convert the hex to numbers
const signedBytes = new Int8Array(matches
.map(hex => parseInt(`0x${hex}`, 16)));
if (isNeg === -1) {
BigIntegerHelper.twosComplement(signedBytes);
}
const dataView = new DataView(destination);
// Pad the start of the buffer with the neg value
let i = offset;
while (i + signedBytes.length < BigIntegerHelper.BYTE_HASH_LENGTH) {
dataView.setInt8(i++, isNeg);
}
// And copy in the actual bytes
for (let j = signedBytes.length; j-- > 0;) {
dataView.setInt8(i++, signedBytes[signedBytes.length - 1 - j]);
}
}
/**
* Convert bytes to a bigInteger.
* @param source The source bytes.
* @param offset The offset within the bytes to start conversion.
* @param length The length of the bytes to use for conversion.
* @returns Big integer version of bytes.
*/
static bytesToBigInteger(source, offset, length) {
if (!objectHelper_1.ObjectHelper.isType(source, ArrayBuffer) || source.byteLength === 0) {
throw new cryptoError_1.CryptoError("The source must be a non empty number array");
}
if (!numberHelper_1.NumberHelper.isInteger(offset) || offset < 0) {
throw new cryptoError_1.CryptoError("The offset must be a number >= 0");
}
if (!numberHelper_1.NumberHelper.isInteger(length) || length <= 0) {
throw new cryptoError_1.CryptoError("The length must be a number > 0");
}
if (source.byteLength - offset < BigIntegerHelper.BYTE_HASH_LENGTH) {
throw new cryptoError_1.CryptoError(`Source array has invalid size, it must be at least ${BigIntegerHelper.BYTE_HASH_LENGTH}`);
}
const dataView = new DataView(source);
let signedBytes = new Int8Array(dataView.byteLength);
for (let b = 0; b < dataView.byteLength; b++) {
signedBytes[b] = dataView.getInt8(b + offset);
}
// Remove the initial padding leaving at least one byte
let paddingOffset = 0;
const firstByte = signedBytes[0];
const isNeg = firstByte < 0;
// If the first padding character is negative then reverse the 2s complement
// but first strip of the leading padding
if (firstByte === 0 || firstByte === -1) {
while (signedBytes[paddingOffset] === firstByte && paddingOffset < signedBytes.length - 1) {
paddingOffset++;
}
// Strip any padding
signedBytes = signedBytes.slice(paddingOffset);
}
if (isNeg) {
BigIntegerHelper.twosComplement(signedBytes);
}
let hexString = isNeg ? "-" : "";
const dv = new DataView(signedBytes.buffer);
for (let h = 0; h < dv.byteLength; h++) {
hexString += `00${dv.getUint8(h).toString(16)}`.slice(-2);
}
return big_integer_1.default(hexString, 16);
}
/* @internal */
static twosComplement(signedBytes) {
// if the whole number is negative then
// change to 2's complements by noting all the numbers
// and adding 1 to the last i.e. ~bignum+1
for (let b = 0; b < signedBytes.length; b++) {
signedBytes[b] = ~signedBytes[b];
}
// Add 1 to last number, if the number is 0xFF continue to carry
let c = signedBytes.length - 1;
do {
signedBytes[c]++;
} while (signedBytes[c--] === 0 && c > 0);
}
} |
JavaScript | class UnionNode {
constructor(nodes) {
this._nodes = void 0;
this._nodes = [];
this.add(nodes);
}
add(nodes) {
if (Array.isArray(nodes)) {
nodes.forEach(node => {
this._nodes.push(node);
});
} else {
this._nodes.push(nodes);
}
}
get() {
return this._nodes;
}
} |
JavaScript | class PointLightShader extends LightShader {
constructor(gl) {
super(gl, null, fragment, {
// height of the light above the viewport
uLightRadius: {
type: '1f',
value: 1
}
});
}
} |
JavaScript | class QuizList extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="quiz-list information-text">
{this.props.quizzes && this.props.quizzes.map((curr) => {
return <QuizListItem key={curr.name} name={curr.name} date={curr.created} onQuizStart={this.props.onQuizStart} onQuizEdit={this.props.onQuizEdit} />;
})}
</div>
);
}
} |
JavaScript | class BbCredentialsManager {
@observable stateId = null;
@observable pendingValidation = false;
configure(scmId, apiUrl) {
this._credentialsApi = new BbCredentialsApi(scmId);
this.apiUrl = apiUrl;
}
constructor(credentialsApi) {
this._credentialsApi = credentialsApi;
}
@action
findExistingCredential() {
this.stateId = BbCredentialsState.PENDING_LOADING_CREDS;
return this._credentialsApi
.findExistingCredential(this.apiUrl)
.then(...delayBoth(MIN_DELAY))
.catch(error => this._findExistingCredentialFailure(error));
}
@action
_findExistingCredentialFailure(error) {
if (error.type === LoadError.TOKEN_NOT_FOUND) {
this.stateId = BbCredentialsState.NEW_REQUIRED;
} else if (error.type === LoadError.TOKEN_INVALID) {
this.stateId = BbCredentialsState.INVALID_CREDENTIAL;
} else if (error.type === LoadError.TOKEN_REVOKED) {
this.stateId = BbCredentialsState.REVOKED_CREDENTIAL;
} else {
this.stateId = BbCredentialsState.UNEXPECTED_ERROR_CREDENTIAL;
}
}
@action
createCredential(userName, password) {
this.pendingValidation = true;
return this._credentialsApi
.createBbCredential(this.apiUrl, userName, password)
.then(...delayBoth(MIN_DELAY))
.then(response => this._createCredentialSuccess(response))
.catch(error => this._onCreateTokenFailure(error));
}
@action
_createCredentialSuccess(credential) {
this.pendingValidation = false;
this.stateId = BbCredentialsState.SAVE_SUCCESS;
return credential;
}
@action
_onCreateTokenFailure(error) {
this.pendingValidation = false;
if (error.type === SaveError.INVALID_CREDENTIAL) {
this.stateId = BbCredentialsState.INVALID_CREDENTIAL;
} else {
throw error;
}
}
} |
JavaScript | class Hierarchy {
constructor() {
this.users = [];
this.roles = [];
this.idMapping = {};
}
/**
* This method takes an array of usersArr and checks if the array is empty
* then assigns the value to the users array
* @param {Array} usersArr
*/
setUsers(usersArr) {
if (!Array.isArray(usersArr) || usersArr.length === 0) {
throw new Error('Users is expected as a non-empty array of users object');
}
this.users = usersArr;
}
/**
* This method takes an array of rolesArr and checks if the array is empty
* then assigns the value to the roles array
* Then call the setRoleIdMapping to mapp each role to their parent
* @param {Array} rolesArr
*/
setRoles(rolesArr) {
if (!Array.isArray(rolesArr) || rolesArr.length === 0) {
throw new Error('Roles is expected as a non-empty array of roles object');
}
this.roles = rolesArr;
this.setRoleIdMapping();
}
/**
* This method finds the parent role and map each child into the parent
*/
setRoleIdMapping() {
const mappedRoles = {};
const root = this.roles.find((role) => role.Parent === 0);
mappedRoles[root.Id] = [];
this.roles.forEach((role) => {
if (mappedRoles[role.Parent] instanceof Array) {
mappedRoles[role.Parent].push(role.Id);
} else {
mappedRoles[role.Parent] = [role.Id];
}
if (!mappedRoles[root.Id].includes(role.Id)) {
mappedRoles[root.Id].push(role.Id);
}
});
this.idMapping = mappedRoles;
}
/**
*
* This method takes the user id , checks if the user exists in the user arr
* and then return the subordinate for the user
* @param {Number} id
* @returns {Array} of user's subordinate
*/
getSubOrdinates(id) {
const { Role, Id } = this.users.find((user) => user.Id === id) || {};
if (!Role) {
throw new Error(`A user with role'${id}' is not found.`);
}
return this.users
.filter((user) => this.idMapping[Role] && this.idMapping[Role].includes(user.Role)
&& user.Id !== Id);
}
} |
JavaScript | class FireEpic {
//Epic middleware for login
static signinEpic = (action$) =>
action$.ofType(FIRE_LOGIN)
.switchMap(({payload}) => {
return Observable.fromPromise(firebase.auth().signInWithEmailAndPassword(payload.email, payload.password))
.catch(err => {
console.log('err ', err)
return Observable.of(err);
})
.switchMap((d) => {
console.log('d login ecpis', d)
if (d.message) {
// error
return Observable.of({
type: FIRE_LOGIN_FAILURE,
payload: d.message
});
} else {
return Observable.fromPromise(firebase.database().ref('/').child(`users/${d.uid}`).once('value'))
.map(u => {
//set local storage
localStorage.setItem('user', JSON.stringify(u.val()));
return {
type: FIRE_LOGIN_SUCCESS,
payload: u.val()
}
})
}
})
})
//Epic middleware for signup
static signupEpic = (action$) =>
action$.ofType(FIRE_SIGNUP)
.switchMap(({ payload }) => {
return Observable.fromPromise(
firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
)
.catch((err) => {
return {
type:FIRE_SIGNUP_FAILURE,
payload:err.message
}
})
.map((d) =>{
console.log("signup epic",d)
if(d.type === FIRE_SIGNUP_FAILURE){
return d;
}
delete payload.password;
let user = {
uid: d.uid,
email: payload.email,
username: payload.username,
};
firebase.database().ref('/').child(`users/${d.uid}`).set(user);
console.log('user created suucessfully!')
return {
type: FIRE_SIGNUP_SUCCESS,
payload: user
}
})
})
} |
JavaScript | class ModelResource extends Resource {
constructor(client) {
super(client);
}
repository(repository) {
this.variables.repository = repository;
return this;
}
sortBy(sortBy) {
this.variables.sortBy = sortBy;
return this;
}
sortUp() {
this.variables.sortDirection = 'ASC';
return this;
}
sortDown() {
this.variables.sortDirection = 'DESC';
return this;
}
pageSize(pageSize) {
this.variables.pageSize = pageSize;
return this;
}
page(page) {
this.variables.page = page;
return this;
}
status(status) {
this.variables.status = status;
return this;
}
async fetch(fields) {
if (this.variables.id) {
const variables = {
id: this.variables.id,
};
const response = await this.client.query(`query model($id: ID!) {
model(id: $id) {
${fields}
}
}`, variables);
return {
data: response.data.model,
};
}
const variables = {
repositoryId: this.variables.repository,
};
const response = await this.client.query(`query models($repositoryId: ID) {
models(repositoryId: $repositoryId) {
${fields}
}
}`, variables);
return {
data: response.data.models,
};
}
async delete() {
if (!this.variables.id) {
throw new Error('Model ID needs to be supplied before you can delete.');
}
const variables = {
modelId: this.variables.id,
};
const response = await this.client.query(`mutation deleteModel($modelId: ID!) {
deleteModel(modelId: $modelId) {
id
name
}
}`, variables);
return {
data: response.data.deleteModel,
};
}
} |
JavaScript | class App extends Component {
resume;
constructor() {
super();
// this.iconsToConvert = [
// {
// icon: faGithub,
// alt: 'github icon'
// },
// {
// icon: faMedium,
// alt: 'medium icon'
// }
// ]
// this.canvLoaded = false;
}
exportPDF = () => {
this.resume.save();
}
/* convertSvgToImage = (arr) => {
let canv = this.refs.canvas;
if (!this.canvLoaded) {
this.canvLoaded = true;
canv.getContext("2d");
arr.forEach((d, i) => {
let htmlString = ReactDOMServer.renderToStaticMarkup(
<FontAwesomeIcon icon={d.icon} size={"3x"} style={{ color: '#005696', height: '500px', width: '500px' }} />
);
canvg(canv, htmlString);
d.icon = canv.toDataURL("image/png");
});
this.setState({});
}
}*/
componentDidMount() {
// this.convertSvgToImage(this.iconsToConvert);
}
render() {
return (
<div style={{ height: '100vh', width: '100vw', paddingTop: 30, backgroundColor: 'gray' }}>
{!this.canvLoaded && <canvas ref="canvas" style={{ display: 'none' }}>
</canvas>}
<div style={{ textAlign: 'center', marginBottom: 10 }}><button onClick={this.exportPDF} style={{ margin: 'auto' }}>print</button></div>
<PDFExport paperSize={'Letter'}
fileName="___bill.pdf"
title=""
subject=""
keywords=""
ref={(r) => this.resume = r}>
<div style={{
height: 792, width: 612, padding: 'none',
backgroundColor: 'white',boxShadow: '5px 5px 5px black',
margin: 'auto', overflowX: 'hidden',
overflowY: 'hidden'
}}>Hi , This is a Wonderful day!!!
<br></br>
<br></br>
<div>
<Row>
<title>AutoSplash Car Wash</title>
<Table style={{ border: "3", padding: "5",textAlign: "left",width:"100%"}}>
<thead>
<tr>
<th scope="col">Greeter:jhon</th>
<th scope="col"> Empid:8736 </th>
</tr>
<tr>
<th scope="col"> shif:2 </th>
<th scope="col"> 03/01/2019 </th>
<th scope="col"> 10.30AM </th>
</tr>
<tr style={{borderBottom:"100"}}>
<th scope="col">work order #092888 </th>
<th scope="col"> Empid:8736 </th>
<th scope="col"> Invoice #23309765</th>
</tr>
</thead>
<hr/>
<tr>
<th scope="col"> Service</th>
<th scope="col">Amount</th>
</tr> <tbody>
<tr>
<td>Quick Full Service</td>
<td>$20.00</td>
</tr>
<tr>
<td>Super Wash</td>
<td>$10.00</td>
</tr>
<tr>
<td>Quick Full Service Discount</td>
<td>-$10.00</td>
</tr>
</tbody>
<br/>
<br/>
<br/>
<hr></hr>
<tr><th>Total</th>
<td>$20.0</td></tr>
<hr></hr>
<tr> <th>Paid</th>
<td>$20.0</td></tr>
<hr></hr>
</Table>
</Row>
</div>
</div>
</PDFExport>
</div>
);
}
} |
JavaScript | class TokenFilter {
constructor(lexer) {
this.lexer = lexer;
}
next() {
const token = this.lexer.next();
if (token && token.type === 'ws') {
return this.next();
}
return token;
}
save() { return this.lexer.save(); }
reset(chunk, info) { this.lexer.reset(chunk, info); }
formatError(token) { return this.lexer.formatError(token); }
has(name) { return this.lexer.has(name); }
} |
JavaScript | class TBinaryReader {
/**
* @constructor
* @param parameters
* @param parameters.buffer
* @param parameters.offset
* @param parameters.length
* @param parameters.endianness
* @constructor
*/
constructor ( parameters = {} ) {
const _parameters = {
...{
buffer: new ArrayBuffer( 0 ),
offset: 0,
length: 0,
endianness: Endianness.Little
}, ...parameters
}
this.buffer = _parameters.buffer
this.offset = _parameters.offset
this.length = _parameters.length
this.endianness = _parameters.endianness
this._updateDataView()
}
/**
*
* @returns {*}
*/
get buffer () {
return this._buffer
}
set buffer ( value ) {
const memberName = 'Buffer'
const expect = 'Expect an instance of ArrayBuffer.'
if ( isNull( value ) ) { throw new TypeError( `${memberName} cannot be null ! ${expect}` ) }
if ( isUndefined( value ) ) { throw new TypeError( `${memberName} cannot be undefined ! ${expect}` ) }
if ( isNotArrayBuffer( value ) ) { throw new TypeError( `${memberName} cannot be an instance of ${value.constructor.name} ! ${expect}` ) }
this._buffer = value
this._offset = 0
this._length = value.byteLength
this._updateDataView()
}
/**
*
* @returns {*}
*/
get offset () {
return this._offset
}
set offset ( value ) {
const memberName = 'Offset'
const expect = 'Expect a number.'
if ( isNull( value ) ) { throw new TypeError( `${memberName} cannot be null ! ${expect}` ) }
if ( isUndefined( value ) ) { throw new TypeError( `${memberName} cannot be undefined ! ${expect}` ) }
if ( isNotNumber( value ) ) { throw new TypeError( `${memberName} cannot be an instance of ${value.constructor.name} ! ${expect}` ) }
this._offset = value
this._updateDataView()
}
get length () {
return this._length
}
/**
*
* @param value
*/
set length ( value ) {
const memberName = 'Length'
const expect = 'Expect a number.'
if ( isNull( value ) ) { throw new TypeError( `${memberName} cannot be null ! ${expect}` ) }
if ( isUndefined( value ) ) { throw new TypeError( `${memberName} cannot be undefined ! ${expect}` ) }
if ( isNotNumber( value ) ) { throw new TypeError( `${memberName} cannot be an instance of ${value.constructor.name} ! ${expect}` ) }
this._length = value
this._updateDataView()
}
/**
*
* @returns {*}
*/
get endianness () {
return this._endianness
}
set endianness ( value ) {
const memberName = 'Endianness'
const expect = 'Expect a boolean.'
if ( isNull( value ) ) { throw new TypeError( `${memberName} cannot be null ! ${expect}` ) }
if ( isUndefined( value ) ) { throw new TypeError( `${memberName} cannot be undefined ! ${expect}` ) }
if ( isNotBoolean( value ) ) { throw new TypeError( `${memberName} cannot be an instance of ${value.constructor.name} ! ${expect}` ) }
this._endianness = value
}
/**
*
* @param buffer
* @param offset
* @param length
* @returns {TBinaryReader}
*/
setBuffer ( buffer, offset, length ) {
this.buffer = buffer
this.offset = offset || 0
this.length = length || buffer.byteLength
return this
}
/**
*
* @param value
* @returns {TBinaryReader}
*/
setOffset ( value ) {
this.offset = value
return this
}
/**
*
* @param value
* @returns {TBinaryReader}
*/
setLength ( value ) {
this.length = value
return this
}
/**
*
* @param endianess
* @returns {TBinaryReader}
*/
setEndianess ( endianess ) {
this.endianness = endianess
return this
}
/**
*
* @param increment
* @returns {*}
* @private
*/
_getAndUpdateOffsetBy ( increment ) {
const currentOffset = this._offset
this._offset += increment
return currentOffset
}
/**
*
* @private
*/
_updateDataView () {
this._dataView = new DataView( this._buffer, this._offset, this._length )
}
/**
*
* @returns {boolean}
*/
isEndOfFile () {
return ( this._offset === this._length )
}
/**
*
* @param offset
* @returns {TBinaryReader}
*/
skipOffsetTo ( offset ) {
this._offset = offset
return this
}
/**
*
* @param nBytes
* @returns {TBinaryReader}
*/
skipOffsetOf ( nBytes ) {
this._offset += nBytes
return this
}
/**
*
* @returns {boolean}
*/
getBoolean () {
return ( ( this.getUint8() & 1 ) === 1 )
}
/**
*
* @param length
* @returns {Array}
*/
getBooleanArray ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getBoolean() )
}
return array
}
/**
*
* @returns {number}
*/
getInt8 () {
return this._dataView.getInt8( this._getAndUpdateOffsetBy( Byte.One ) )
}
/**
*
* @param length
* @returns {Array}
*/
getInt8Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getInt8() )
}
return array
}
/**
*
* @returns {number}
*/
getUint8 () {
return this._dataView.getUint8( this._getAndUpdateOffsetBy( Byte.One ) )
}
/**
*
* @param length
* @returns {Array}
*/
getUint8Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getUint8() )
}
return array
}
/**
*
* @returns {number}
*/
getInt16 () {
return this._dataView.getInt16( this._getAndUpdateOffsetBy( Byte.Two ), this._endianness )
}
/**
*
* @param length
* @returns {Array}
*/
getInt16Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getInt16() )
}
return array
}
/**
*
* @returns {number}
*/
getUint16 () {
return this._dataView.getUint16( this._getAndUpdateOffsetBy( Byte.Two ), this._endianness )
}
/**
*
* @param length
* @returns {Array}
*/
getUint16Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getUint16() )
}
return array
}
/**
*
* @returns {number}
*/
getInt32 () {
return this._dataView.getInt32( this._getAndUpdateOffsetBy( Byte.Four ), this._endianness )
}
/**
*
* @param length
* @returns {Array}
*/
getInt32Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getInt32() )
}
return array
}
/**
*
* @returns {number}
*/
getUint32 () {
return this._dataView.getUint32( this._getAndUpdateOffsetBy( Byte.Four ), this._endianness )
}
/**
*
* @param length
* @returns {Array}
*/
getUint32Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getUint32() )
}
return array
}
/**
*
* @returns {number}
*/
getInt64 () {
// From THREE.FBXLoader
// JavaScript doesn't support 64-bit integer so attempting to calculate by ourselves.
// 1 << 32 will return 1 so using multiply operation instead here.
// There'd be a possibility that this method returns wrong value if the value
// is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
// TODO: safely handle 64-bit integer
let low = null
let high = null
if ( this._endianness === Endianness.Little ) {
low = this.getUint32()
high = this.getUint32()
} else {
high = this.getUint32()
low = this.getUint32()
}
// calculate negative value
if ( high & 0x80000000 ) {
high = ~high & 0xFFFFFFFF
low = ~low & 0xFFFFFFFF
if ( low === 0xFFFFFFFF ) {
high = ( high + 1 ) & 0xFFFFFFFF
}
low = ( low + 1 ) & 0xFFFFFFFF
return -( high * 0x100000000 + low )
}
return high * 0x100000000 + low
}
/**
*
* @param length
* @returns {Array}
*/
getInt64Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getInt64() )
}
return array
}
/**
*
* @returns {number}
*/
getUint64 () {
// Note: see getInt64() comment
let low = null
let high = null
if ( this._endianness === Endianness.Little ) {
low = this.getUint32()
high = this.getUint32()
} else {
high = this.getUint32()
low = this.getUint32()
}
return high * 0x100000000 + low
}
/**
*
* @param length
* @returns {Array}
*/
getUint64Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getUint64() )
}
return array
}
/**
*
* @returns {number}
*/
getFloat32 () {
return this._dataView.getFloat32( this._getAndUpdateOffsetBy( Byte.Four ), this._endianness )
}
/**
*
* @param length
* @returns {Array}
*/
getFloat32Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getFloat32() )
}
return array
}
/**
*
* @return {number}
*/
getFloat64 () {
return this._dataView.getFloat64( this._getAndUpdateOffsetBy( Byte.Height ), this._endianness )
}
/**
*
* @param length
* @returns {Array}
*/
getFloat64Array ( length ) {
const array = []
for ( let i = 0 ; i < length ; i++ ) {
array.push( this.getFloat64() )
}
return array
}
/**
*
* @returns {string}
*/
getChar () {
return String.fromCharCode( this.getUint8() )
}
/**
*
* @param length
* @param trim
* @return {string}
*/
getString ( length, trim = true ) {
let string = ''
let charCode = null
for ( let i = 0 ; i < length ; i++ ) {
charCode = this.getUint8()
if ( charCode === 0 ) {
continue
}
string += String.fromCharCode( charCode )
}
if ( trim ) {
string = string.trim()
}
return string
}
/**
*
* @param size
* @returns {ArrayBuffer}
*/
getArrayBuffer ( size ) {
const offset = this._getAndUpdateOffsetBy( size )
return this._dataView.buffer.slice( offset, offset + size )
}
} |
JavaScript | class QueueService {
/**
* Queue management service
* @param {OkanjoApp} app
* @param {*} [config] service config
* @constructor
*/
constructor(app, config) {
this.app = app;
this.config = config;
if (!this.config || !this.config.rascal) {
throw new Error('okanjo-app-queue: No rascal configuration set for QueueService!');
}
this.broker = null; // set on connect
// Register the connection with the app
app._serviceConnectors.push(async () => {
await this.connect();
});
}
/**
* Connects to RabbitMQ and binds the necessary exchanges and queues
*/
async connect() {
try {
this.broker = await Rascal.BrokerAsPromised.create(Rascal.withDefaultConfig(this.config.rascal));
this.broker.on('error', this._handleBrokerError.bind(this));
} catch(err) {
this.app.report('okanjo-app-queue: Failed to create Rascal broker:', err);
throw err;
}
}
/**
* Publishes a message to the given queue
* @param {string} queue - The queue name to publish to
* @param {*} data - The message data to queue
* @param [options] - The message data to queue
* @param [callback] - Fired when done
* @returns {Promise}
*/
publishMessage(queue, data, options, callback) {
// Overload - e.g. publishMessage(queue, data, callback);
if (arguments.length === 3 && typeof options === "function") {
callback = options;
options = {};
}
let replied = false;
let reply = (err, res) => {
/* istanbul ignore else: in some circumstances, it may be possible for a double callback if rabbit does some wacky connection stuff */
if (!replied) {
replied = true;
if (callback) {
callback(err, res);
return true;
}
}
};
return new Promise((resolve, reject) => {
this.broker
.publish(queue, data, options)
.catch(err => {
this.app.report('okanjo-app-queue: Failed to publish queue message', err, { queue, data, options })
.then(() => {
if (reply(err)) return;
return reject(err);
})
;
})
.then(pub => {
pub.on('error', /* istanbul ignore next: out of scope */ async err => {
await this.app.report('okanjo-app-queue: Failed to publish queue message', err, { queue, data, options })
});
if (reply(null, pub)) return;
return resolve(pub);
})
;
});
}
_handleBrokerError(err) {
this.app.report('okanjo-app-queue: Rascal Broker error', err);
}
} |
JavaScript | class Validator {
validateBlockchain(blockchain) {
//loop through the blocks of the chain (bypass the genesis one)
for (var i = 1; i < blockchain.chain.length - 1; i++) {
//validate the current hash
if (!(compareWordArrays(blockchain.chain[i].getCurrentHash().words, blockchain.chain[i].hash.words))) {
console.log("Blockchain is NOT valid.");
return;
};
//validate the current/previous hash relation
if (!(compareWordArrays(blockchain.chain[i].getCurrentHash().words, blockchain.chain[i + 1].previousHash.words))) {
console.log("Blockchain is NOT valid.");
return;
};
}
console.log("Blockchain is valid.");
}
} |
JavaScript | class ImageUtils {
static decodeBase64EncodedImage(base64EncodedImage, callback) {
this._createImage('data:image/png;base64,' + base64EncodedImage, callback);
}
static rotateFromLandscapeOrientation(imageInLanscapeOrientation, callback) {
var canvas = document.createElement('canvas');
canvas.width = imageInLanscapeOrientation.height;
canvas.height = imageInLanscapeOrientation.width;
var context = canvas.getContext('2d');
context.rotate(-90 * (Math.PI / 180));
context.translate(-imageInLanscapeOrientation.width, 0);
context.drawImage(imageInLanscapeOrientation, 0, 0);
this._createImage(canvas.toDataURL(), callback);
}
static rotateFromLandscapeRightOrientation(imageInLanscapeRightOrientation, callback) {
var canvas = document.createElement('canvas');
canvas.width = imageInLanscapeRightOrientation.height;
canvas.height = imageInLanscapeRightOrientation.width;
var context = canvas.getContext('2d');
context.rotate(90 * (Math.PI / 180));
context.translate(0, -imageInLanscapeRightOrientation.height);
context.drawImage(imageInLanscapeRightOrientation, 0, 0);
this._createImage(canvas.toDataURL(), callback);
}
static _createImage(source, callback) {
var image = new Image();
image.src = source;
image.onload = function() {
callback(image);
};
}
// Source : https://gist.github.com/jonleighton/958841
static base64ArrayBuffer(arrayBuffer) {
var base64 = ''
var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
var bytes = new Uint8Array(arrayBuffer)
var byteLength = bytes.byteLength
var byteRemainder = byteLength % 3
var mainLength = byteLength - byteRemainder
var a, b, c, d
var chunk
// Main loop deals with bytes in chunks of 3
for (var i = 0; i < mainLength; i = i + 3) {
// Combine the three bytes into a single integer
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12 // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6 // 4032 = (2^6 - 1) << 6
d = chunk & 63 // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
}
// Deal with the remaining bytes and padding
if (byteRemainder == 1) {
chunk = bytes[mainLength]
a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4 // 3 = 2^2 - 1
base64 += encodings[a] + encodings[b] + '=='
} else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4 // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2 // 15 = 2^4 - 1
base64 += encodings[a] + encodings[b] + encodings[c] + '='
}
return base64
}
} |
JavaScript | class Wienerlinien extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'wienerlinien',
});
this.killTimeout = null;
this.on('ready', this.onReady.bind(this));
this.on('unload', this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Initialize your adapter here
const self = this;
const senderKey = this.config.senderKey;
const stationID = this.config.stationID.split(";");
var stationIDs = "";
for(const id in stationID){
stationIDs = stationIDs + 'rbl=' + stationID[id] + '&';
}
this.log.debug(stationIDs);
// The adapters config (in the instance object everything under the attribute "native") is accessible via
// this.config:
this.log.info('config senderKey: ' + this.config.senderKey);
this.log.info('config stationID: ' + this.config.stationID);
this.log.debug('request started');
request(
{
url: 'http://www.wienerlinien.at/ogd_realtime/monitor?' + stationIDs + 'sender=' + senderKey,
json: true,
time: true,
timeout: 4500
},
(error, response, content) => {
self.log.debug('remote request done');
if (response) {
self.log.debug('received data (' + response.statusCode + '): ' + JSON.stringify(content));
self.setObjectNotExists('lastResponseCode', {
type: 'state',
common: {
name: 'lastResponseCode',
type: 'number',
role: 'value',
read: true,
write: false
},
native: {}
});
self.setState('lastResponseCode', {val: response.statusCode, ack: true});
self.setObjectNotExists('lastResponseTime', {
type: 'state',
common: {
name: 'lastResponseTime',
type: 'number',
role: 'value',
unit: 'ms',
read: true,
write: false
},
native: {}
});
self.setState('lastResponseTime', {val: parseInt(response.timingPhases.total), ack: true});
if (!error && response.statusCode == 200) {
if (content) {
for(const key in content.data.monitors){
const monitor = content.data.monitors[key];
const station = monitor.locationStop.properties.title + ' - ' + monitor.lines[0].towards + '.';
self.setObjectNotExists(station + 'Station', {
type: 'state',
common: {
name: 'Station',
type: 'string',
role: 'name',
},
native: {}
});
self.setState(station + 'Station', {val: monitor.locationStop.properties.title, ack: true});
self.setObjectNotExists(station + 'Line', {
type: 'state',
common: {
name: 'Line',
type: 'string',
role: 'name',
},
native: {}
});
self.setState(station + 'Line', {val: monitor.lines[0].name, ack: true});
self.setObjectNotExists(station + 'Towards', {
type: 'state',
common: {
name: 'Towards',
type: 'string',
role: 'name',
},
native: {}
});
self.setState(station + 'Towards', {val: monitor.lines[0].towards, ack: true});
self.setObjectNotExists(station + 'StationBarrierFree', {
type: 'state',
common: {
name: 'StationBarrierFree',
type: 'bool',
role: 'value',
},
native: {}
});
self.setState(station + 'StationBarrierFree', {val: monitor.lines[0].barrierFree, ack: true});
for(const key in monitor.lines[0].departures.departure){
const departure = monitor.lines[0].departures.departure[key];
const d = 'Departure' + key.toString();
self.setObjectNotExists(station + d, {
type: 'state',
common: {
name: d,
type: 'number',
role: 'value',
unit: 'min',
},
native: {}
});
self.setState(station + d, {val: departure.departureTime.countdown, ack: true});
var vehicleBarrierFree = false;
if(departure.hasOwnProperty('vehicle')){
vehicleBarrierFree = departure.vehicle.barrierFree;
}
else{
vehicleBarrierFree = monitor.lines[0].barrierFree;
}
self.setObjectNotExists(station + d + '_vehicleBarrierFree', {
type: 'state',
common: {
name: d + '_vehicleBarrierFree',
type: 'bool',
role: 'value',
},
native: {}
});
self.setState(station + d + '_vehicleBarrierFree', {val: vehicleBarrierFree, ack: true});
}
}
}
}
} else if (error) {
self.log.warn(error);
}
}
);
this.killTimeout = setTimeout(this.stop.bind(this), 10000);
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
if (this.killTimeout) {
this.log.debug('clearing kill timeout');
clearTimeout(this.killTimeout);
}
this.log.debug('cleaned everything up...');
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
onStateChange(id, state) {
if (state) {
// The state was changed
this.log.info(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
} else {
// The state was deleted
this.log.info(`state ${id} deleted`);
}
}
} |
JavaScript | class NetworkSimulator {
/**
* Initializes a new instance of the {@link NetworkSimulator} class to operate on the given {@link NetworkModel}.
* @param {NetworkModel} model The network model to simulate.
*/
constructor(model) {
this.initNetworkSimulator()
this.$model = model
this.$somethingFailedEvent = null
this.$failuresEnabled = false
this.$time = 0
}
/**
* The number of new packets that should be created per tick.
* @return {number}
*/
static get NEW_PACKETS_PER_TICK() {
return 5
}
/**
* The probability that a node or edge fails.
* @return {number}
*/
static get FAILURE_PROBABILITY() {
return 0.001
}
/**
* The number of past ticks to consider when calculating the load of nodes and edges.
* @return {number}
*/
static get HISTORY_SIZE() {
return 23
}
/** @type {function(Object, PropertyChangedEventArgs)} */
set somethingFailedEvent(value) {
this.$somethingFailedEvent = value
}
/** @type {function(Object, PropertyChangedEventArgs)} */
get somethingFailedEvent() {
return this.$somethingFailedEvent
}
/** @type {number} */
set time(value) {
this.$time = value
}
/** @type {number} */
get time() {
return this.$time
}
/**
* Event handler for network failures.
* @param {function(Object, PropertyChangedEventArgs)} value
*/
addSomethingFailedListener(value) {
this.somethingFailedEvent = delegate.combine(this.somethingFailedEvent, value)
}
/**
* Event handler for network failures.
* @param {function(Object, PropertyChangedEventArgs)} value
*/
removeSomethingFailedListener(value) {
this.somethingFailedEvent = delegate.remove(this.somethingFailedEvent, value)
}
/**
* Gets the network model to simulate.
* @type {NetworkModel}
*/
get model() {
return this.$model
}
/**
* Sets the network model to simulate.
* @type {NetworkModel}
*/
set model(value) {
this.$model = value
}
/**
* Sets a value indicating whether random failures of nodes and edges should happen.
* @type {boolean}
*/
set failuresEnabled(value) {
this.$failuresEnabled = value
}
/**
* Gets a value indicating whether random failures of nodes and edges should happen.
* @type {boolean}
*/
get failuresEnabled() {
return this.$failuresEnabled
}
/**
* Performs one step in the simulation.
* Packets move one node per tick. Every tick a number of new packets are created.
*/
tick() {
if (this.failuresEnabled) {
this.breakThings()
}
// Reset packet-related properties on the edges
this.activePackets.forEach(packet => {
packet.edge.hasForwardPacket = false
packet.edge.hasBackwardPacket = false
})
this.pruneOldPackets()
this.movePackets()
this.updateLoads()
this.createPackets()
this.activePackets.forEach(packet => {
const edge = packet.edge
edge.hasForwardPacket |= packet.start === edge.source
edge.hasBackwardPacket |= packet.start === edge.target
})
this.time++
}
/**
* Determines for every edge and node whether it should fail and does so, if necessary.
*/
breakThings() {
const thingsThatCanBreak = []
this.model.nodes.forEach(node => {
if (!node.failed) {
thingsThatCanBreak.push(node)
}
})
this.model.edges.forEach(edge => {
if (!edge.failed) {
thingsThatCanBreak.push(edge)
}
})
let c = 0
for (let i = 0; i < thingsThatCanBreak.length && c < 2; i++) {
const thing = thingsThatCanBreak[i]
if (Math.random() < NetworkSimulator.FAILURE_PROBABILITY * (thing.load + 0.1)) {
thing.failed = true
this.onSomethingFailed(thing)
c++
}
}
}
/**
* Creates new packets.
* Packets are only sent from laptops, workstations, smartphones and tablets.
* @see {@link ModelNode#canSendPackets}
*/
createPackets() {
// Find all edges that are still enabled and unbroken. Edges are automatically disabled if either endpoint is
// disabled or broken. Restrict them to those edges that are adjacent to a node that can send packets.
const eligibleEdges = new List()
this.$model.edges.forEach(e => {
if (e.enabled && !e.failed && (e.source.canSendPackets() || e.target.canSendPackets())) {
eligibleEdges.add(e)
}
})
// Pick a number of those edges at random
const selectedEdges = new List()
for (let i = 0; i < eligibleEdges.size && i < NetworkSimulator.NEW_PACKETS_PER_TICK; i++) {
const k = (Math.random() * eligibleEdges.size) | 0
selectedEdges.add(eligibleEdges.get(k))
eligibleEdges.removeAt(k)
}
const packets = new List()
selectedEdges.forEach(edge => {
const startNode = edge.source.canSendPackets() ? edge.source : edge.target
const endNode = edge.source.canSendPackets() ? edge.target : edge.source
packets.add(this.createPacket(startNode, endNode, edge))
})
this.activePackets.addRange(packets)
}
/**
* Moves the active packets around the network according to certain rules.
* Packets move freely and randomly within the network until they arrive at a non-switch, non-WiFi node.
* Servers and databases always bounce back a new packet when they receive one, while �client� nodes
* simply receive packets and maybe spawn new ones in {@link NetworkSimulator#createPackets}.
* @see {@link NetworkSimulator#createPackets}
* @see {@link ModelNode#canConnectTo}
*/
movePackets() {
// Find packets that need to be considered for moving.
// This excludes packets that end in a disabled or broken node or that travel along a now-broken edge.
// We don't care whether the source is alive or not by now.
const packetsToMove = new List()
this.activePackets.forEach(p => {
if (p.edge.enabled && !p.edge.failed && p.end.enabled && !p.end.failed) {
packetsToMove.add(p)
}
})
// Packets that arrive at servers or databases. They result in a reply packet.
const replyPackets = new List()
packetsToMove.forEach(p => {
if (
(p.end.type === ModelNode.SERVER || p.end.type === ModelNode.DATABASE) &&
p.start.enabled &&
!p.start.failed
) {
replyPackets.add(p)
}
})
// All other packets that just move on to their next destination.
const movingPackets = new List()
packetsToMove.forEach(p => {
if (!p.end.canReceivePackets()) {
movingPackets.add(p)
}
})
// All packets have to be moved to the history list. We create new ones appropriately.
this.historicalPackets.addRange(this.activePackets)
this.activePackets.clear()
movingPackets.forEach(packet => {
const origin = packet.start
const currentEdge = packet.edge
// We start from the old target of the packet
const startNode = packet.end
// Try finding a random edge to follow ...
const adjacentEdges = this.model.getAdjacentEdges(startNode)
const possiblePathEdges = new List()
adjacentEdges.forEach(e => {
const edgeTarget = e.source === startNode ? e.target : e.source
if (e !== currentEdge && origin.canConnectTo(edgeTarget) && e.enabled && !e.failed) {
possiblePathEdges.add(e)
}
})
let /** @type {ModelEdge} */ edge
if (possiblePathEdges.size > 0) {
const i = (Math.random() * possiblePathEdges.size) | 0
edge = possiblePathEdges.get(i)
const endNode = edge.source === startNode ? edge.target : edge.source
const newPacket = this.createPacket(startNode, endNode, edge)
this.activePackets.add(newPacket)
}
})
replyPackets.forEach(packet => {
this.activePackets.add(this.createPacket(packet.end, packet.start, packet.edge))
})
}
/**
* Removes packets from the history that are no longer considered for edge or node load.
* @see {@link NetworkSimulator#HISTORY_SIZE}
*/
pruneOldPackets() {
for (let i = this.historicalPackets.size - 1; i >= 0; i--) {
const p = this.historicalPackets.get(i)
if (p.time < this.time - NetworkSimulator.HISTORY_SIZE) {
this.historicalPackets.removeAt(i)
}
}
}
/**
* Updates load of nodes and edges based on traffic in the network.
* The criteria are perhaps a bit arbitrary here. Edge load is defined as the number of timestamps in the
* history that this edge transmitted a packet. Node load is the number of packets involving this node
* adjusted by the number of adjacent edges.
*/
updateLoads() {
const history = new List()
history.addRange(this.activePackets)
history.addRange(this.historicalPackets)
this.model.edges.forEach(edge => {
const set = new Set()
history.forEach(
/** Packet */ packet => {
if (packet.edge === edge) {
if (!set.has(packet.time)) {
set.add(packet.time)
}
}
}
)
const numberOfHistoryPackets = set.size
edge.load = Math.min(1, numberOfHistoryPackets / NetworkSimulator.HISTORY_SIZE)
})
this.model.nodes.forEach(node => {
const set = new Set()
history.forEach(packet => {
if (packet.start === node || packet.end === node) {
if (!set.has(packet)) {
set.add(packet)
}
}
})
const numberOfHistoryPackets = set.size
node.load = Math.min(
1,
numberOfHistoryPackets /
NetworkSimulator.HISTORY_SIZE /
this.model.getAdjacentEdges(node).size
)
})
}
/**
* Convenience method to create a single packet with the appropriate timestamp.
* @param {ModelNode} startNode The start node of the packet.
* @param {ModelNode} endNode The end node of the packet.
* @param {ModelEdge} edge The edge on which the packet travels.
* @return {Packet} The newly-created packet.
*/
createPacket(startNode, endNode, edge) {
const newPacket = new Packet()
newPacket.start = startNode
newPacket.end = endNode
newPacket.edge = edge
newPacket.time = this.time
return newPacket
}
/**
* Called when something fails.
* @param {Object} sender
*/
onSomethingFailed(sender) {
const handler = this.somethingFailedEvent
if (handler !== null) {
handler(sender, new EventArgs())
}
}
initNetworkSimulator() {
this.historicalPackets = new List()
this.activePackets = new List()
}
} |
JavaScript | class Packet {
constructor() {
this.$time = 0
this.$start = null
this.$end = null
this.$edge = null
}
/** @type {number} */
get time() {
return this.$time
}
/** @type {number} */
set time(value) {
this.$time = value
}
/** @type {ModelNode} */
get start() {
return this.$start
}
/** @type {ModelNode} */
set start(value) {
this.$start = value
}
/** @type {ModelNode} */
get end() {
return this.$end
}
/** @type {ModelNode} */
set end(value) {
this.$end = value
}
/** @type {ModelEdge} */
get edge() {
return this.$edge
}
/** @type {ModelEdge} */
set edge(value) {
this.$edge = value
}
} |
JavaScript | class BufferTimeSubscriber extends Subscriber_1.Subscriber {
/**
* @param {?} destination
* @param {?} bufferTimeSpan
* @param {?} bufferCreationInterval
* @param {?} scheduler
*/
constructor(destination, bufferTimeSpan, bufferCreationInterval, scheduler) {
super(destination);
this.bufferTimeSpan = bufferTimeSpan;
this.bufferCreationInterval = bufferCreationInterval;
this.scheduler = scheduler;
this.buffers = [];
const buffer = this.openBuffer();
if (bufferCreationInterval !== null && bufferCreationInterval >= 0) {
const closeState = { subscriber: this, buffer };
const creationState = { bufferTimeSpan, bufferCreationInterval, subscriber: this, scheduler };
this.add(scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
}
else {
const timeSpanOnlyState = { subscriber: this, buffer, bufferTimeSpan };
this.add(scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
}
}
/**
* @param {?} value
* @return {?}
*/
_next(value) {
const /** @type {?} */ buffers = this.buffers;
const /** @type {?} */ len = buffers.length;
for (let /** @type {?} */ i = 0; i < len; i++) {
buffers[i].push(value);
}
}
/**
* @param {?} err
* @return {?}
*/
_error(err) {
this.buffers.length = 0;
super._error(err);
}
/**
* @return {?}
*/
_complete() {
const { buffers, destination } = this;
while (buffers.length > 0) {
destination.next(buffers.shift());
}
super._complete();
}
/**
* @return {?}
*/
_unsubscribe() {
this.buffers = null;
}
/**
* @return {?}
*/
openBuffer() {
let /** @type {?} */ buffer = [];
this.buffers.push(buffer);
return buffer;
}
/**
* @param {?} buffer
* @return {?}
*/
closeBuffer(buffer) {
this.destination.next(buffer);
const /** @type {?} */ buffers = this.buffers;
buffers.splice(buffers.indexOf(buffer), 1);
}
static _tsickle_typeAnnotationsHelper() {
/** @type {?} */
BufferTimeSubscriber.prototype.buffers;
/** @type {?} */
BufferTimeSubscriber.prototype.bufferTimeSpan;
/** @type {?} */
BufferTimeSubscriber.prototype.bufferCreationInterval;
/** @type {?} */
BufferTimeSubscriber.prototype.scheduler;
}
} |
JavaScript | class EditProfileScreen extends React.Component {
static navigationOptions = {
title: "",
headerTintColor: "white",
headerStyle: {
backgroundColor: "#0B345A"
}
};
state = {
// Data For TextInput Fields //
forename: "",
surname: "",
email: "",
link: "",
// Flag For If TextInput Has Chnaged Since componentDidMount() //
link_changed: false,
forename_changed: false,
surname_changed: false,
email_changed: false,
// Biometrics Flags //
compatible: false, // Compatible With The Device
biometrics: false, // Enabled And Scans Available
// Settinsg Flags //
processing: false,
is_mounted: false
};
componentDidMount () {
this.checkDeviceForHardware();
this.checkForBiometrics();
this.setState( { is_mounted: true } );
SecureStore.getItemAsync( "biometrics" ).then( value => {
if ( value == "true" ) {
this.setState( { is_mounted: true, biometrics: true, compatible: true } )
}
});
this.setTextInput();
};
componentWillUnmount () {
this.setState( { is_mounted: false } );
};
checkDeviceForHardware = async () => { // Check Device Has The Hardware For Biometrics
let compatible = await LocalAuthentication.hasHardwareAsync();
this.setState( { compatible: compatible } );
};
checkForBiometrics = async () => { // Check Device Has A Biometric Scan To Use
let biometrics = await LocalAuthentication.isEnrolledAsync();
this.setState( { biometrics: biometrics } );
};
setBiometrics = async ( value ) => {
if ( value ) {
if ( this.state.biometrics && this.state.compatible ) {
SecureStore.setItemAsync( "biometrics", String( value ) );
} else {
Alert.alert( "Biometrics Is Not Available On This Device", "", [ { text: "Dismiss" } ] );
}
} else {
this.setState( { biometrics: false } );
SecureStore.setItemAsync( "biometrics", String( value ) );
}
};
setTextInput = async () => {
let account = JSON.parse( await SecureStore.getItemAsync( "account" ) );
this.setState(
{
is_mounted: true,
forename: account[ "forename" ],
link: account[ "profile_pic_link" ],
surname: account[ "surname" ],
email: account[ "email" ]
}
);
};
updateProfile = async () => {
const { navigate } = this.props.navigation;
var id = await SecureStore.getItemAsync( "session_id" );
var account = JSON.parse( await SecureStore.getItemAsync( "account" ) );
const form_data = new FormData();
form_data.append( "session_id", id );
if ( this.state.forename_changed ) {
form_data.append( "forename", this.state.forename );
}
if ( this.state.surname_changed ) {
form_data.append( "surname", this.state.surname );
}
if (this.state.link == null) {
this.setState( { link: "" } );
}
form_data.append( "profile_pic_link", this.state.link );
// Check A Valid Email Has Been Given If Provided //
if ( this.state.email_changed ) {
const expression = /(?!.*\.{2})^([a-z\d!#$%&"*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&"*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([\t]*\r\n)?[\t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([\t]*\r\n)?[\t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
if ( expression.test( this.state.email.toLowerCase() ) ) { // Test E-Mail Is Valid On Lower Case For Realism
if ( this.state.email.endsWith( ".ac.uk" ) ) { // Must Be Education Email
form_data.append( "email", this.state.email );
account[ "email" ] = this.state.email;
} else {
Alert.alert( "Your Registered Email Must Be An Educational Address", "", [ { text: "Dismiss" } ] );
this.setState( { email_changed: false, forename_changed: false, surname_changed: false } );
return;
}
} else {
Alert.alert( "Please Enter A Valid Email", "", [ { text: "Dismiss" } ] );
this.setState( { email_changed: false, forename_changed: false, surname_changed: false } );
return;
}
}
this.setState( { processing: true } );
Keyboard.dismiss();
const url = "./updateProfile.php";
var that = this;
require("../../assets/fetch.js").getFetch( url, form_data, function ( err, response, timeout ) {
if ( timeout ) {
Alert.alert( "Request Timed Out", "A Stable Internet Connection Is Required", [ { text: "Dismiss" }, { text: "Logout", onPress: () => ( clearInterval( that.session ), clearInterval( that.validity ), navigate( 'Home' ) ) } ] );
return;
} else {
if ( ! err ) {
if ( response != undefined ) {
response = JSON.parse( response );
if ( response[ "error" ] ) {
Alert.alert( "An Error Occured", response[ "message" ], [ { text: "Dismiss" }, { text: "Logout", onPress: () => ( clearInterval( that.session ), clearInterval( that.validity ), navigate( 'Home' ) ) } ] );
} else {
account[ "forename" ] = that.state.forename;
account[ "surname" ] = that.state.surname;
account[ "profile_pic_link" ] = that.state.link;
if (that.state.link == null) {
this.setState( { link: "" } );
}
SecureStore.setItemAsync( "account", JSON.stringify ( account ) );
that.setState( { email_changed: false, forename_changed: false, surname_changed: false } );
Alert.alert( "Profile Updated", "", [ { text: "Dismiss" } ] );
}
}
} else {
err = JSON.parse( err );
Alert.alert( "Request Failed", err[ "message" ], [ { text: "Dismiss" }, { text: "Logout", onPress: () => ( clearInterval( that.session ), clearInterval( that.validity ), navigate( 'Home' ) ) } ] );
}
}
that.setState( { processing: false } );
} );
};
render() {
return (
<KeyboardAvoidingView style={ Styles.container } behavior="padding" keyboardVerticalOffset="145">
<StatusBar backgroundColor="#FFFFFF" barStyle="light-content"/>
<Offline />
<View style={ Styles.form }>
<TextInput placeholderTextColor="#C7C7CD" value={ this.state.forename } placeholder="Forename" style={ Styles.textInput } onChangeText={ text => this.setState( { forename: text, forename_changed: true } ) } />
<TextInput placeholderTextColor="#C7C7CD" value={ this.state.surname } placeholder="Surname" style={ Styles.textInput } onChangeText={ text => this.setState( { surname: text, surname_changed: true } ) } />
<TextInput placeholderTextColor="#C7C7CD" value={ this.state.email } autoCorrect={ false } autoCapitalize = "none" keyboardType="email-address" placeholder="E-Mail" style={ Styles.textInput } onChangeText={ text => this.setState( { email: text, email_changed: true } ) } />
<TextInput placeholderTextColor="#C7C7CD" value={ this.state.link } autoCorrect={ false } autoCapitalize = "none" placeholder="Profile Picture Link" style={ Styles.textInput } onChangeText={ text => this.setState( { link: text, link_changed: true } ) } />
{ this.state.compatible && this.state.biometrics ?
<View style={ Styles.switch }>
<Text style={ Styles.text }>Turn On Biometrics:{"\n"}</Text>
<Switch value={ this.state.compatible && this.state.biometrics } onValueChange={ v => { this.setBiometrics( v ); } } />
</View>
: undefined
}
<Button disabled={ this.processing } main={ true } label={ "Update" } onPress={ () => this.updateProfile() } />
<ActivityIndicator style={ { paddingTop: 10 } } size="small" color="#0000ff" animating={ this.state.processing } />
</View>
</KeyboardAvoidingView>
);
};
} |
JavaScript | class MelcloudDevice {
constructor(that) {
gthat = that;
this.platform = null;
this.airInfo = null;
this.deviceInfoRequestQueue = [];
this.currentDeviceInfoRequests = 0;
this.deviceSetRequestQueue = [];
this.currentDeviceSetRequests = 0;
this.hasBeenCreated = false;
// Info
this.id = -1;
this.name = "";
this.serialNumber = "";
this.macAddress = "";
this.buildingId = -1;
this.floorId = -1;
this.canCool = false;
this.canHeat = false;
this.canDry = false;
this.minTempCoolDry = 0;
this.maxTempCoolDry = 0;
this.minTempHeat = 0;
this.maxTempHeat = 0;
this.minTempAuto = 0;
this.maxTempAuto = 0;
this.roomTemp = 0;
this.actualFanSpeed = 0;
this.numberOfFanSpeeds = 0;
this.lastCommunication = null;
this.nextCommunication = null;
this.deviceOnline = false;
// Control
this.power = false;
this.operationMode = commonDefines.DeviceOperationModes.UNDEF.value;
this.targetTemp = 0;
this.fanSpeed = 0;
this.vaneVerticalDirection = 0;
this.vaneHorizontalDirection = 0;
// Reports
this.powerConsumptionReportStartDate = "";
this.powerConsumptionReportEndDate = "";
this.powerConsumptionReportMonths = [];
this.monthlyPowerConsumptionCooling = [];
this.monthlyPowerConsumptionHeating = [];
this.monthlyPowerConsumptionAuto = [];
this.monthlyPowerConsumptionDry = [];
this.monthlyPowerConsumptionVent = [];
this.totalPowerConsumptionCooling = 0;
this.totalPowerConsumptionHeating = 0;
this.totalPowerConsumptionAuto = 0;
this.totalPowerConsumptionDry = 0;
this.totalPowerConsumptionVent = 0;
this.totalPowerConsumptionMinutes = 0;
}
// Creates all necessery states and channels and writes the values into the DB
async CreateAndSave() {
// check if object has already been created
if (this.hasBeenCreated) return;
const devicePrefix = commonDefines.AdapterDatapointIDs.Devices + "." + this.id;
await gthat.extendObjectAsync(devicePrefix, {
type: "channel",
common: {
name: "Device " + this.id + " (" + this.name + ")"
},
native: {}
});
//#region INFO
let infoPrefix = devicePrefix + "." + commonDefines.AdapterDatapointIDs.Info;
await gthat.extendObjectAsync(infoPrefix, {
type: "channel",
common: {
name: "Device information"
},
native: {}
});
infoPrefix += ".";
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.DeviceName, {
type: "state",
common: {
name: "Device name",
type: "string",
role: "info.name",
read: true,
write: false,
def: this.name,
desc: "MELCloud device name"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.SerialNumber, {
type: "state",
common: {
name: "Serial number",
type: "string",
role: "value",
read: true,
write: false,
def: this.serialNumber,
desc: "Serial number of the device"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.MacAddress, {
type: "state",
common: {
name: "MAC address",
type: "string",
role: "info.mac",
read: true,
write: false,
def: this.macAddress,
desc: "MAC address of the device"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.BuildingId, {
type: "state",
common: {
name: "Building ID",
type: "number",
role: "value",
read: true,
write: false,
def: this.buildingId,
desc: "MELCloud building ID"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.FloorId, {
type: "state",
common: {
name: "Floor ID",
type: "number",
role: "value",
read: true,
write: false,
def: this.floorId,
desc: "MELCloud floor ID"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.CanCool, {
type: "state",
common: {
name: "Ability to cool",
type: "boolean",
role: "value",
read: true,
write: false,
def: this.canCool,
desc: "Ability to cool"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.CanHeat, {
type: "state",
common: {
name: "Ability to heat",
type: "boolean",
role: "value",
read: true,
write: false,
def: this.canHeat,
desc: "Ability to heat"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.CanDry, {
type: "state",
common: {
name: "Ability to dry",
type: "boolean",
role: "value",
read: true,
write: false,
def: this.canDry,
desc: "Ability to dry"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.MinTempCoolDry, {
type: "state",
common: {
name: "Minimal temperature (Cool/Dry)",
type: "number",
role: "value.temperature",
unit: this.platform.UseFahrenheit ? "°F" : "°C",
read: true,
write: false,
def: this.minTempCoolDry,
desc: "Minimal temperature in cool/dry-mode"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.MaxTempCoolDry, {
type: "state",
common: {
name: "Maximal temperature (Cool/Dry)",
type: "number",
role: "value.temperature",
unit: this.platform.UseFahrenheit ? "°F" : "°C",
read: true,
write: false,
def: this.maxTempCoolDry,
desc: "Maximal temperature in cool/dry-mode"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.MinTempHeat, {
type: "state",
common: {
name: "Minimal temperature (Heat)",
type: "number",
role: "value.temperature",
unit: this.platform.UseFahrenheit ? "°F" : "°C",
read: true,
write: false,
def: this.minTempHeat,
desc: "Minimal temperature in heat-mode"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.MaxTempHeat, {
type: "state",
common: {
name: "Maximal temperature (Heat)",
type: "number",
role: "value.temperature",
unit: this.platform.UseFahrenheit ? "°F" : "°C",
read: true,
write: false,
def: this.maxTempHeat,
desc: "Maximal temperature in heat-mode"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.MinTempAuto, {
type: "state",
common: {
name: "Minimal Temperature (Auto)",
type: "number",
role: "value.temperature",
unit: this.platform.UseFahrenheit ? "°F" : "°C",
read: true,
write: false,
def: this.minTempAuto,
desc: "Minimal temperature in auto-mode"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.MaxTempAuto, {
type: "state",
common: {
name: "Maximal Temperature (Auto)",
type: "number",
role: "value.temperature",
unit: this.platform.UseFahrenheit ? "°F" : "°C",
read: true,
write: false,
def: this.maxTempAuto,
desc: "Maximal temperature in auto-mode"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.RoomTemp, {
type: "state",
common: {
name: "Room temperature",
type: "number",
role: "value.temperature",
unit: this.platform.UseFahrenheit ? "°F" : "°C",
read: true,
write: false,
def: this.roomTemp,
desc: "Maximal temperature in auto-mode"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.FanSpeedAuto, {
type: "state",
common: {
name: "Fan speed (while in auto mode)",
type: "number",
role: "value",
read: true,
write: false,
def: this.actualFanSpeed,
desc: "Actual fan speed when fan is set to auto mode"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.NumberOfFanSpeeds, {
type: "state",
common: {
name: "Number of fan speeds",
type: "number",
role: "value",
read: true,
write: false,
def: this.numberOfFanSpeeds,
desc: "Number of available fan speeds"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.LastCommunication, {
type: "state",
common: {
name: "Last communication",
type: "string",
role: "date",
read: true,
write: false,
def: this.lastCommunication,
desc: "Last communication date/time (MELCloud to device)"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.NextCommunication, {
type: "state",
common: {
name: "Next communication",
type: "string",
role: "date",
read: true,
write: false,
def: this.nextCommunication,
desc: "Next communication date/time (MELCloud to device)"
},
native: {}
});
await gthat.extendObjectAsync(infoPrefix + commonDefines.AdapterStateIDs.DeviceOnline, {
type: "state",
common: {
name: "Is device online",
type: "boolean",
role: "indicator.reachable",
read: true,
write: false,
def: this.deviceOnline,
desc: "Indicates if device is reachable"
},
native: {}
});
//#endregion
//#region CONTROL
let controlPrefix = devicePrefix + "." + commonDefines.AdapterDatapointIDs.Control;
await gthat.extendObjectAsync(controlPrefix, {
type: "channel",
common: {
name: "Device control"
},
native: {}
});
controlPrefix += ".";
await gthat.extendObjectAsync(controlPrefix + commonDefines.AdapterStateIDs.Power, {
type: "state",
common: {
name: "Power",
type: "boolean",
role: "switch.power",
read: true,
write: true,
def: this.power,
desc: "Power switch"
},
native: {}
});
await gthat.extendObjectAsync(controlPrefix + commonDefines.AdapterStateIDs.Mode, {
type: "state",
common: {
name: "Operation mode",
type: "number",
role: "value",
read: true,
write: true,
def: this.operationMode,
desc: "Operation mode of the device",
states: {
1: "HEAT",
2: "DRY",
3: "COOL",
7: "VENT",
8: "AUTO"
}
},
native: {}
});
const minTemp = Math.min(this.minTempAuto, this.minTempCoolDry, this.minTempHeat);
const maxTemp = Math.max(this.maxTempAuto, this.maxTempCoolDry, this.maxTempHeat);
await gthat.extendObjectAsync(controlPrefix + commonDefines.AdapterStateIDs.TargetTemp, {
type: "state",
common: {
name: "Target temperature",
type: "number",
role: "level.temperature",
unit: this.platform.UseFahrenheit ? "°F" : "°C",
min: minTemp,
max: maxTemp,
step: 0.5,
read: true,
write: true,
def: this.targetTemp,
desc: "Target temperature of the device"
},
native: {}
});
// Extend existing object
await gthat.extendObject(controlPrefix + commonDefines.AdapterStateIDs.TargetTemp, {
common: {
step: 0.5
}
});
await gthat.extendObjectAsync(controlPrefix + commonDefines.AdapterStateIDs.FanSpeedManual, {
type: "state",
common: {
name: "Fan speed (while in manual mode)",
type: "number",
role: "value",
min: 0,
max: 5,
states: {
0: "AUTO",
1: "LOWEST",
2: "LOW",
3: "MEDIUM",
4: "HIGH",
5: "MAX"
},
read: true,
write: true,
def: this.fanSpeed,
desc: "Current fan speed of the device (while in manual mode)"
},
native: {}
});
await gthat.extendObjectAsync(controlPrefix + commonDefines.AdapterStateIDs.VaneVerticalDirection, {
type: "state",
common: {
name: "Vane vertical direction",
type: "number",
role: "value",
min: 0,
max: 7,
states: {
0: "AUTO",
1: "TOPMOST",
2: "UP",
3: "MIDDLE",
4: "DOWN",
5: "BOTTOMMOST",
7: "SWING"
},
read: true,
write: true,
def: this.vaneVerticalDirection,
desc: "Current vertical direction of the device's vane"
},
native: {}
});
await gthat.extendObjectAsync(controlPrefix + commonDefines.AdapterStateIDs.VaneHorizontalDirection, {
type: "state",
common: {
name: "Vane horizontal direction",
type: "number",
role: "value",
min: 0,
max: 12,
states: {
0: "AUTO",
1: "LEFTMOST",
2: "LEFT",
3: "MIDDLE",
4: "RIGHT",
5: "RIGHTMOST",
8: "50/50",
12: "SWING"
},
read: true,
write: true,
def: this.vaneHorizontalDirection,
desc: "Current horizontal direction of the device's vane"
},
native: {}
});
//#endregion
//#region REPORTS
let reportsPrefix = devicePrefix + "." + commonDefines.AdapterDatapointIDs.Reports;
await gthat.extendObjectAsync(reportsPrefix, {
type: "channel",
common: {
name: "Device reports"
},
native: {}
});
reportsPrefix += ".";
await gthat.extendObjectAsync(reportsPrefix + commonDefines.AdapterStateIDs.ReportStartDate, {
type: "state",
common: {
name: "Report start date (format: YYYY-MM-DD)",
type: "string",
role: "date",
read: true,
write: true,
desc: "Report data will be collected starting at this date"
},
native: {}
});
await gthat.extendObjectAsync(reportsPrefix + commonDefines.AdapterStateIDs.ReportEndDate, {
type: "state",
common: {
name: "Report end date (format: YYYY-MM-DD)",
type: "string",
role: "date",
read: true,
write: true,
desc: "Report data will be collected until this date"
},
native: {}
});
await gthat.extendObjectAsync(reportsPrefix + commonDefines.AdapterStateIDs.GetPowerConsumptionReport, {
type: "state",
common: {
name: "Get current power consumption report",
type: "boolean",
role: "button",
min: 0,
read: false,
write: true,
def: false,
desc: "Get current power consumption report"
},
native: {}
});
await gthat.extendObjectAsync(reportsPrefix + commonDefines.AdapterStateIDs.ReportedMonths, {
type: "state",
common: {
name: "Months included in current report",
type: "string",
role: "value",
read: true,
write: false,
def: "",
desc: "Months included in current report"
},
native: {}
});
monthNames.forEach(month => {
operationModes.forEach(mode => {
gthat.extendObjectAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + mode, {
type: "state",
common: {
name: "Total power consumption for mode '" + mode + "'",
type: "number",
role: "value.power.consumption",
min: 0,
read: true,
write: false,
unit: "kWh",
def: 0,
desc: "Total power consumption for mode '" + mode + "'"
},
native: {}
});
gthat.extendObjectAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + mode + month, {
type: "state",
common: {
name: "Total power consumption for month '" + month + "' in mode '" + mode + "'",
type: "number",
role: "value.power.consumption",
min: 0,
read: true,
write: false,
unit: "kWh",
def: 0,
desc: "Total power consumption for month '" + month + "' in mode '" + mode + "'",
},
native: {}
});
});
});
await gthat.extendObjectAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalMinutes, {
type: "state",
common: {
name: "Total power consumption minutes",
type: "number",
role: "value",
min: 0,
read: true,
write: false,
unit: "min",
def: 0,
desc: "Total operation time"
},
native: {}
});
//#endregion
gthat.log.debug("Created and saved device " + this.id + " (" + this.name + ")");
this.hasBeenCreated = true;
}
// Only writes changed device data into the DB
async UpdateDeviceData(deviceOption = null) {
//#region INFO
const infoPrefix = commonDefines.AdapterDatapointIDs.Devices + "." + this.id + "." + commonDefines.AdapterDatapointIDs.Info + ".";
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.DeviceName, this.name, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.SerialNumber, this.serialNumber, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.MacAddress, this.macAddress, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.BuildingId, this.buildingId, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.FloorId, this.floorId, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.CanCool, this.canCool, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.CanHeat, this.canHeat, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.CanDry, this.canDry, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.MinTempCoolDry, this.minTempCoolDry, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.MaxTempCoolDry, this.maxTempCoolDry, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.MinTempHeat, this.minTempHeat, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.MaxTempHeat, this.maxTempHeat, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.MinTempAuto, this.minTempAuto, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.MaxTempAuto, this.maxTempAuto, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.RoomTemp, this.roomTemp, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.FanSpeedAuto, this.actualFanSpeed, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.NumberOfFanSpeeds, this.numberOfFanSpeeds, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.LastCommunication, this.lastCommunication, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.NextCommunication, this.nextCommunication, true);
await gthat.setStateChangedAsync(infoPrefix + commonDefines.AdapterStateIDs.DeviceOnline, this.deviceOnline, true);
//#endregion
//#region CONTROL
const controlPrefix = commonDefines.AdapterDatapointIDs.Devices + "." + this.id + "." + commonDefines.AdapterDatapointIDs.Control + ".";
switch (deviceOption) {
case commonDefines.DeviceOptions.PowerState:
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.Power, this.power, true);
break;
case commonDefines.DeviceOptions.TargetHeatingCoolingState:
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.Mode, this.operationMode, true);
break;
case commonDefines.DeviceOptions.TargetTemperature:
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.TargetTemp, this.targetTemp, true);
break;
case commonDefines.DeviceOptions.FanSpeed:
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.FanSpeedManual, this.fanSpeed, true);
break;
case commonDefines.DeviceOptions.VaneHorizontalDirection:
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.VaneHorizontalDirection, this.vaneHorizontalDirection, true);
break;
case commonDefines.DeviceOptions.VaneVerticalDirection:
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.VaneVerticalDirection, this.vaneVerticalDirection, true);
break;
default:
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.Power, this.power, true);
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.Mode, this.operationMode, true);
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.TargetTemp, this.targetTemp, true);
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.FanSpeedManual, this.fanSpeed, true);
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.VaneHorizontalDirection, this.vaneHorizontalDirection, true);
await gthat.setStateChangedAsync(controlPrefix + commonDefines.AdapterStateIDs.VaneVerticalDirection, this.vaneVerticalDirection, true);
break;
}
//#endregion
gthat.log.debug("Updated device data for device " + this.id + " (" + this.name + ")");
}
// Only writes changed report data into the DB
async UpdateReportData() {
const reportsPrefix = commonDefines.AdapterDatapointIDs.Devices + "." + this.id + "." + commonDefines.AdapterDatapointIDs.Reports + ".";
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.ReportStartDate, this.powerConsumptionReportStartDate, true);
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.ReportEndDate, this.powerConsumptionReportEndDate, true);
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.ReportedMonths, this.powerConsumptionReportMonths, true);
let counter = 0;
this.powerConsumptionReportMonths.forEach(month => {
const monthName = monthNames[month - 1]; // months delivered from cloud range from 1=January to 12=December
gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.COOL.id + monthName, commonDefines.roundValue(this.monthlyPowerConsumptionCooling[counter], 3), true);
gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.HEAT.id + monthName, commonDefines.roundValue(this.monthlyPowerConsumptionHeating[counter], 3), true);
gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.AUTO.id + monthName, commonDefines.roundValue(this.monthlyPowerConsumptionAuto[counter], 3), true);
gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.DRY.id + monthName, commonDefines.roundValue(this.monthlyPowerConsumptionDry[counter], 3), true);
gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.VENT.id + monthName, commonDefines.roundValue(this.monthlyPowerConsumptionVent[counter], 3), true);
counter++;
});
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.COOL.id, commonDefines.roundValue(this.totalPowerConsumptionCooling, 3), true);
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.HEAT.id, commonDefines.roundValue(this.totalPowerConsumptionHeating, 3), true);
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.AUTO.id, commonDefines.roundValue(this.totalPowerConsumptionAuto, 3), true);
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.DRY.id, commonDefines.roundValue(this.totalPowerConsumptionDry, 3), true);
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalPowerConsumptionPrefix + commonDefines.DeviceOperationModes.VENT.id, commonDefines.roundValue(this.totalPowerConsumptionVent, 3), true);
await gthat.setStateChangedAsync(reportsPrefix + commonDefines.AdapterStateIDs.TotalMinutes, this.totalPowerConsumptionMinutes, true);
gthat.log.debug("Updated report data for device " + this.id + " (" + this.name + ")");
}
getDeviceInfo(callback, deviceOption, value) {
const gthis = this;
if (gthis.airInfo != null) {
gthat.log.debug("Data already available for: " + gthis.id + " (" + gthis.name + ")");
callback && callback(deviceOption, value, gthis);
if (gthis.deviceInfoRequestQueue.length) {
const args = gthis.deviceInfoRequestQueue.shift();
gthat.log.debug("Dequeuing getDeviceInfo remote request for device option '" + args[1].id + "' with value '" + (args[2].value != undefined ? args[2].value : args[2]) + "'...");
gthis.getDeviceInfo.apply(gthis, args);
}
return;
}
gthat.log.debug("Getting device data for " + gthis.id + " (" + gthis.name + ")");
if (gthis.currentDeviceInfoRequests < 1) {
gthis.currentDeviceInfoRequests++;
const url = "https://app.melcloud.com/Mitsubishi.Wifi.Client/Device/Get?id=" + gthis.id + "&buildingID=" + gthis.buildingId;
Axios.get(url, {
headers: {
"X-MitsContextKey": gthis.platform.contextKey
}
}).then(function handleDeviceInfoResponse(response) {
if (!response || !response.data || JSON.stringify(response.data).search("<!DOCTYPE html>") != -1) {
gthat.log.error("There was a problem receiving the response from: " + url);
gthis.airInfo = null;
}
else {
const statusCode = response.status;
gthat.log.debug("Received response from: " + url + " (status code: " + statusCode + " - " + response.statusText + ")");
if (statusCode != HttpStatus.StatusCodes.OK) {
gthis.airInfo = null;
gthat.log.error("Invalid HTTP status code (" + statusCode + " - " + response.statusText + "). Getting device data failed!");
return;
}
gthat.log.debug("Response from cloud: " + JSON.stringify(response.data));
gthis.airInfo = response.data;
// Cache airInfo data for 1 minute
setTimeout(function clearAirInfo() {
gthis.airInfo = null;
}, 60 * 1000);
}
gthis.currentDeviceInfoRequests--;
callback && callback(deviceOption, value, gthis);
if (gthis.deviceInfoRequestQueue.length) {
const args = gthis.deviceInfoRequestQueue.shift();
gthat.log.debug("Dequeuing getDeviceInfo remote request for device option '" + args[1].id + "' with value '" + (args[2].value != undefined ? args[2].value : args[2]) + "'");
gthis.getDeviceInfo.apply(gthis, args);
}
}).catch(error => {
gthat.log.error("There was a problem getting device data from: " + url);
gthat.log.error("Error: " + error);
gthis.airInfo = null;
});
}
else {
gthat.log.debug("Queueing getDeviceInfo remote request for '" + deviceOption.id + "' with value '" + (value.value != undefined ? value.value : value) + "'...");
gthis.deviceInfoRequestQueue.push(arguments);
}
}
setDevice(deviceOption, value, gthis) {
if (gthis.currentDeviceSetRequests < 1) {
gthis.currentDeviceSetRequests++;
gthat.log.debug("Changing device option '" + deviceOption.id + "' to '" + (value.value != undefined ? value.value : value) + "'...");
const r = gthis.airInfo;
value = gthis.verifyDeviceOptionValue(deviceOption, value, gthis);
if (deviceOption == commonDefines.DeviceOptions.PowerState) {
switch (value) {
case commonDefines.DevicePowerStates.OFF:
r.Power = commonDefines.DevicePowerStates.OFF.value;
r.EffectiveFlags = commonDefines.DevicePowerStates.OFF.effectiveFlags;
break;
case commonDefines.DevicePowerStates.ON:
r.Power = commonDefines.DevicePowerStates.ON.value;
r.EffectiveFlags = commonDefines.DevicePowerStates.ON.effectiveFlags;
break;
default:
gthat.log.error("Unsupported value for device option - please report this to the developer!");
return;
}
}
else if (deviceOption == commonDefines.DeviceOptions.TargetHeatingCoolingState) {
switch (value) {
case commonDefines.DeviceOperationModes.HEAT:
r.OperationMode = commonDefines.DeviceOperationModes.HEAT.value;
r.EffectiveFlags = commonDefines.DeviceOperationModes.HEAT.effectiveFlags;
break;
case commonDefines.DeviceOperationModes.DRY:
r.OperationMode = commonDefines.DeviceOperationModes.DRY.value;
r.EffectiveFlags = commonDefines.DeviceOperationModes.DRY.effectiveFlags;
break;
case commonDefines.DeviceOperationModes.COOL:
r.OperationMode = commonDefines.DeviceOperationModes.COOL.value;
r.EffectiveFlags = commonDefines.DeviceOperationModes.COOL.effectiveFlags;
break;
case commonDefines.DeviceOperationModes.VENT:
r.OperationMode = commonDefines.DeviceOperationModes.VENT.value;
r.EffectiveFlags = commonDefines.DeviceOperationModes.VENT.effectiveFlags;
break;
case commonDefines.DeviceOperationModes.AUTO:
r.OperationMode = commonDefines.DeviceOperationModes.AUTO.value;
r.EffectiveFlags = commonDefines.DeviceOperationModes.AUTO.effectiveFlags;
break;
default:
gthat.log.error("Unsupported value for device option - please report this to the developer!");
return;
}
}
else if (deviceOption == commonDefines.DeviceOptions.TargetTemperature) {
r.SetTemperature = value;
r.EffectiveFlags = commonDefines.DeviceOptions.TargetTemperature.effectiveFlags;
}
else if (deviceOption == commonDefines.DeviceOptions.FanSpeed) {
r.SetFanSpeed = value;
r.EffectiveFlags = commonDefines.DeviceOptions.FanSpeed.effectiveFlags;
}
else if (deviceOption == commonDefines.DeviceOptions.VaneHorizontalDirection) {
r.VaneHorizontal = value;
r.EffectiveFlags = commonDefines.DeviceOptions.VaneHorizontalDirection.effectiveFlags;
}
else if (deviceOption == commonDefines.DeviceOptions.VaneVerticalDirection) {
r.VaneVertical = value;
r.EffectiveFlags = commonDefines.DeviceOptions.VaneVerticalDirection.effectiveFlags;
}
else {
gthat.log.error("Unsupported device option - please report this to the developer!");
return;
}
r.HasPendingCommand = true;
const url = "https://app.melcloud.com/Mitsubishi.Wifi.Client/Device/SetAta";
const body = JSON.stringify(gthis.airInfo);
gthat.log.silly("Request body: " + body);
Axios.post(url, body, {
headers: {
"X-MitsContextKey": gthis.platform.contextKey,
"content-type": "application/json"
}
}).then(function handleSetDeviceResponse(response) {
if (!response) {
gthat.log.error("There was a problem receiving the response from: " + url);
gthis.airInfo = null;
}
else {
const statusCode = response.status;
const statusText = response.statusText;
gthat.log.debug("Received response from: " + url + " (status code: " + statusCode + " - " + statusText + ")");
if (statusCode != HttpStatus.StatusCodes.OK) {
gthis.airInfo = null;
gthat.log.error("Invalid HTTP status code (" + statusCode + " - " + statusText + "). Changing device option failed!");
return;
}
const responseData = response.data;
gthat.log.debug("Response from cloud: " + JSON.stringify(responseData));
gthis.lastCommunication = responseData.LastCommunication;
gthis.nextCommunication = responseData.NextCommunication;
gthis.roomTemp = responseData.RoomTemperature;
gthis.deviceOnline = !responseData.Offline;
switch (deviceOption) {
case commonDefines.DeviceOptions.PowerState:
gthis.power = responseData.Power;
break;
case commonDefines.DeviceOptions.TargetHeatingCoolingState:
gthis.operationMode = responseData.OperationMode;
break;
case commonDefines.DeviceOptions.TargetTemperature:
gthis.targetTemp = responseData.SetTemperature;
break;
case commonDefines.DeviceOptions.FanSpeed:
gthis.fanSpeed = responseData.SetFanSpeed;
break;
case commonDefines.DeviceOptions.VaneHorizontalDirection:
gthis.vaneHorizontalDirection = responseData.VaneHorizontal;
break;
case commonDefines.DeviceOptions.VaneVerticalDirection:
gthis.vaneVerticalDirection = responseData.VaneVertical;
break;
default:
break;
}
gthis.UpdateDeviceData(deviceOption); // write updated values
gthis.currentDeviceSetRequests--;
if (gthis.deviceSetRequestQueue.length) {
const args = gthis.deviceSetRequestQueue.shift();
gthat.log.debug("Dequeuing setDevice remote request for device option '" + args[0].id + "' with value '" + (args[1].value != undefined ? args[1].value : args[1]) + "'");
gthis.setDevice.apply(gthis, args);
}
}
}).catch(error => {
gthat.log.error("There was a problem setting info to: " + url);
gthat.log.error(error);
});
}
else {
gthat.log.debug("Queueing setDevice remote request for '" + deviceOption.id + "' with value '" + (value.value != undefined ? value.value : value) + "'...");
gthis.deviceSetRequestQueue.push(arguments);
}
}
verifyDeviceOptionValue(deviceOption, value, gthis) {
switch (deviceOption) {
case commonDefines.DeviceOptions.FanSpeed:
if (value > gthis.numberOfFanSpeeds) {
gthat.log.warn("Fan speed limited to " + gthis.numberOfFanSpeeds + " because device can't handle more than that!");
return gthis.numberOfFanSpeeds;
}
return value;
case commonDefines.DeviceOptions.TargetTemperature:
// eslint-disable-next-line no-case-declarations
let min, max;
switch (gthis.operationMode) {
case commonDefines.DeviceOperationModes.COOL.value:
case commonDefines.DeviceOperationModes.DRY.value:
min = gthis.minTempCoolDry;
max = gthis.maxTempCoolDry;
break;
case commonDefines.DeviceOperationModes.HEAT.value:
min = gthis.minTempHeat;
max = gthis.maxTempHeat;
break;
case commonDefines.DeviceOperationModes.AUTO.value:
min = gthis.minTempAuto;
max = gthis.maxTempAuto;
break;
default:
min = gthis.platform.UseFahrenheit ? 60 : 16;
max = gthis.platform.UseFahrenheit ? 104 : 40;
break;
}
if (value < min) {
value = min;
gthat.log.warn("SetTemperature limited to " + min + " because device can't handle lower than that!");
}
else if (value > max) {
value = max;
gthat.log.warn("SetTemperature limited to " + max + " because device can't handle more than that!");
}
return value;
case commonDefines.DeviceOptions.VaneHorizontalDirection:
if (value < 0 || value > 5 && value != 8 && value != 12) {
gthat.log.warn("VaneHorizontalDirection: unsupported value '" + value + "' - falling back to '0'!");
value = 0;
}
return value;
case commonDefines.DeviceOptions.VaneVerticalDirection:
if (value < 0 || value > 5 && value != 7) {
gthat.log.warn("VaneVerticalDirection: unsupported value '" + value + "' - falling back to '0'!");
value = 0;
}
return value;
default: return value;
}
}
async getPowerConsumptionReport() {
const gthis = this;
gthat.log.debug("Getting power consumption report for " + gthis.id + " (" + gthis.name + ")");
const url = "https://app.melcloud.com/Mitsubishi.Wifi.Client/EnergyCost/Report";
const body = JSON.stringify(await this.buildPowerConsumptionReportRequestBody());
gthat.log.silly("Request body: " + body);
if (body == "{}") return; // creating body failed or was provided dates were invalid
Axios.post(url, body, {
headers: {
"X-MitsContextKey": gthis.platform.contextKey,
"content-type": "application/json"
}
}).then(function handleConsumptionReportResponse(response) {
if (!response) {
gthat.log.error("There was a problem receiving the response from: " + url);
}
else {
const statusCode = response.status;
const statusText = response.statusText;
gthat.log.debug("Received response from: " + url + " (status code: " + statusCode + " - " + statusText + ")");
if (statusCode != HttpStatus.StatusCodes.OK) {
gthis.airInfo = null;
gthat.log.error("Invalid HTTP status code (" + statusCode + " - " + statusText + "). Getting power consumption report failed!");
return;
}
const responseData = response.data;
gthat.log.debug("Response from cloud: " + JSON.stringify(responseData));
if (responseData.LinkedDevicesNotIncludedInArregateEnergyReport.includes(gthis.name)) {
gthat.log.warn("Power consumption report is not supported for this device!");
return;
}
// only save date portion of timestamp without the empty time
gthis.powerConsumptionReportStartDate = responseData.FromDate.replace("T00:00:00", "");
gthis.powerConsumptionReportEndDate = responseData.ToDate.replace("T00:00:00", "");
gthis.powerConsumptionReportMonths = responseData.Labels;
gthis.monthlyPowerConsumptionCooling = responseData.Cooling;
gthis.monthlyPowerConsumptionHeating = responseData.Heating;
gthis.monthlyPowerConsumptionAuto = responseData.Auto;
gthis.monthlyPowerConsumptionDry = responseData.Dry;
gthis.monthlyPowerConsumptionVent = responseData.Fan;
// round all consumption values to 3 digits
gthis.totalPowerConsumptionCooling = responseData.TotalCoolingConsumed;
gthis.totalPowerConsumptionHeating = responseData.TotalHeatingConsumed;
gthis.totalPowerConsumptionAuto = responseData.TotalAutoConsumed;
gthis.totalPowerConsumptionDry = responseData.TotalDryConsumed;
gthis.totalPowerConsumptionVent = responseData.TotalFanConsumed;
gthis.totalPowerConsumptionMinutes = responseData.TotalMinutes;
gthis.UpdateReportData();
}
}).catch(error => {
gthat.log.error("There was a problem getting power consumption report from: " + url);
gthat.log.error("Error: " + error);
});
}
async buildPowerConsumptionReportRequestBody() {
const requestBody = {};
const startDateObj = await gthat.getStateAsync(commonDefines.AdapterDatapointIDs.Devices + "." + this.id + "." + commonDefines.AdapterDatapointIDs.Reports + "." + commonDefines.AdapterStateIDs.ReportStartDate);
let startDate = (startDateObj == null || startDateObj.val == null) ? "" : startDateObj.val;
const endDateObj = await gthat.getStateAsync(commonDefines.AdapterDatapointIDs.Devices + "." + this.id + "." + commonDefines.AdapterDatapointIDs.Reports + "." + commonDefines.AdapterStateIDs.ReportEndDate);
let endDate = (endDateObj == null || endDateObj.val == null) ? "" : endDateObj.val;
if (startDate == "") {
gthat.log.warn("No valid start date was provided (format: YYYY-MM-DD). Defaulting to 6 months prior.");
const d = new Date();
d.setMonth(d.getMonth() - 6);
startDate = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}
const parsedStartDate = startDate.split("-");
if (parsedStartDate.length != 3 || parsedStartDate[0].length != 4 || parsedStartDate[1].length > 2 || parsedStartDate[2].length > 2) {
gthat.log.warn("No valid start date was provided (format: YYYY-MM-DD). Defaulting to 6 months prior.");
const d = new Date();
d.setMonth(d.getMonth() - 6);
startDate = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}
if (endDate == "") {
gthat.log.warn("No valid end date was provided (format: YYYY-MM-DD). Defaulting to today.");
const d = new Date();
endDate = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}
const parsedEndDate = endDate.split("-");
if (parsedEndDate.length != 3 || parsedEndDate[0].length != 4 || parsedEndDate[1].length > 2 || parsedEndDate[2].length > 2) {
gthat.log.warn("No valid end date was provided (format: YYYY-MM-DD). Defaulting to today.");
const d = new Date();
endDate = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}
if (startDate == endDate) {
gthat.log.warn("Start and end date must not be the same. Ignoring request.");
return requestBody;
}
requestBody.DeviceId = this.id;
requestBody.FromDate = startDate + "T00:00:00";
requestBody.ToDate = endDate + "T00:00:00";
requestBody.UseCurrency = false;
return requestBody;
}
} |
JavaScript | class BookSearch extends Component {
state = {
query: "",
queriedBooks: []
}
/**
* run the query and fetch the books.
* Set the state accordingly
* @param {*} query
* @memberof BookSearch
*/
queryBooks(query) {
if (query) {
let queryResults = [];
BooksAPI.search(query).then(results => {
if (results && results.length) {
queryResults = results.map(result => {
result.shelf = this.addShelf(result);
return result;
});
this.setState({queriedBooks: queryResults});
} else {
this.setState({ queriedBooks: []});
}
});
} else {
this.setState({queriedBooks: []});
}
this.setState({ query: query.trim()});
}
addShelf(result) {
let hasShelf = this.props.books.filter(book => book.id === result.id);
return hasShelf.length ? hasShelf[0].shelf : "none";
}
render() {
return (
<div className="search-books">
<div className="search-books-bar">
<Link className="close-search" to="/">
>
Close
</Link>
<div className="search-books-input-wrapper">
{/*
NOTES: The search from BooksAPI is limited to a particular set of search terms.
You can find these search terms here:
https://github.com/udacity/reactnd-project-myreads-starter/blob/master/SEARCH_TERMS.md
However, remember that the BooksAPI.search method DOES search by title or author. So, don't worry if
you don't find a specific author or title. Every search is limited by search terms.
*/}
<input
onChange={event => this.queryBooks(event.target.value)}
placeholder="Search by title or author"
type="text"
/>
</div>
</div>
<div className="search-books-results">
{this.state.queriedBooks.length > 0 &&
<div className="bookshelf">
<h2 className="bookshelf-title"> Results </h2>
<div className="bookshelf-books">
<ol className="books-grid">
{
this.state.queriedBooks.map((book) => <Book book={book} key={book.id} changeShelf={this.props.changeShelf} />)
}
</ol>
</div>
</div>
}
</div>
</div>
)
}
} |
JavaScript | class Version extends function_base_1.QualifiedFunctionBase {
constructor(scope, id, props) {
super(scope, id);
this.canCreatePermissions = true;
this.lambda = props.lambda;
const version = new lambda_generated_1.CfnVersion(this, 'Resource', {
codeSha256: props.codeSha256,
description: props.description,
functionName: props.lambda.functionName
});
this.version = version.attrVersion;
this.functionArn = version.ref;
this.functionName = `${this.lambda.functionName}:${this.version}`;
}
static fromVersionAttributes(scope, id, attrs) {
class Import extends function_base_1.QualifiedFunctionBase {
constructor() {
super(...arguments);
this.version = attrs.version;
this.lambda = attrs.lambda;
this.functionName = `${attrs.lambda.functionName}:${attrs.version}`;
this.functionArn = `${attrs.lambda.functionArn}:${attrs.version}`;
this.grantPrincipal = attrs.lambda.grantPrincipal;
this.role = attrs.lambda.role;
this.canCreatePermissions = false;
}
}
return new Import(scope, id);
}
get grantPrincipal() {
return this.lambda.grantPrincipal;
}
get role() {
return this.lambda.role;
}
metric(metricName, props = {}) {
// Metrics on Aliases need the "bare" function name, and the alias' ARN, this differes from the base behavior.
return super.metric(metricName, {
dimensions: {
FunctionName: this.lambda.functionName,
// construct the ARN from the underlying lambda so that alarms on an alias
// don't cause a circular dependency with CodeDeploy
// see: https://github.com/aws/aws-cdk/issues/2231
Resource: `${this.lambda.functionArn}:${this.version}`
},
...props
});
}
} |
JavaScript | class JobController {
/**
*
* @param {Request} req
* @param {Response} res
* @returns {Promise} -
*/
static async getJobs(req, res) {
const jobs = await JobModel.find();
return jsonResponse({ res, data: jobs });
}
/**
*
* @param {Request} req
* @param {Response} res
* @returns {Promise} -
*/
static async getApplications(req, res) {
const applications = await JobApplicationModel.find()
.where({ job: req.params.jobId })
.limit(10)
.populate('applicant', ['firstName', 'lastName', 'email', 'phoneNumber'])
.populate('job')
.exec();
return jsonResponse({ res, data: applications });
}
/**
*
* @param {Request} req
* @param {Response} res
* @returns {Promise} -
*/
static async getRecruiterJobs(req, res) {
const jobs = await JobModel.find().where({ postedBy: String(req.currentUserId) });
return jsonResponse({ res, data: jobs });
}
/**
*
* @param {Request} req
* @param {Response} res
* @returns {Promise} -
*/
static async postJob(req, res) {
const newJob = await JobModel.create({ ...req.body, postedBy: req.currentUserId });
return jsonResponse({ status: statusCodes.HTTP_CREATED, res, data: newJob });
}
/**
*
* @param {Request} req
* @param {Response} res
* @returns {Promise} -
*/
static async getJobDetails(req, res) {
const job = await JobModel.findById(req.params.jobId);
if (job) {
return jsonResponse({ res, data: job });
}
return jsonResponse({
status: statusCodes.HTTP_NOT_FOUND,
res,
message: 'Job not found.',
});
}
/**
*
* @param {Request} req
* @param {Response} res
* @returns {Promise} -
*/
static async getJobApplications(req, res) {
const { jobId } = req.params;
const jobApplications = await JobApplicationModel.find()
.where({ job: jobId })
.populate('job')
.populate('applicant')
.exec();
if (jobApplications) {
return jsonResponse({ res, data: jobApplications });
}
return jsonResponse({ res, status: statusCodes.HTTP_NOT_FOUND, message: 'This job has not applications yet.' });
}
} |
JavaScript | class UserEditPassword extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
}
render() {
return (
<div>
<div className="modal fade popup_add" tabIndex="-1" role="dialog" id={this.props.id}>
<div className="modal-dialog" role="document">
<button type="button" className="close" data-dismiss="modal" aria-label="Close"><i className="icon-arrow-left2"></i></button>
<div className="modal-header">
<h2>Edit password</h2>
</div>
<div className="modal-content">
<form className="form-left">
<div className="form-group">
<label htmlFor="inputCurrentPassword">Current password</label>
<input type="password" className="form-control" id="currentPassword" placeholder="current password..." />
</div>
<div className="form-group">
<label htmlFor="inputNewPassword">New password</label>
<input type="text" className="form-control" id="newPassword" placeholder="new password..." />
</div>
<div className="form-group">
<label htmlFor="inputConfirmPassword">Confirm password</label>
<input type="email" className="form-control" id="confirmPassword" placeholder="confirm password..." />
</div>
</form>
<div className="modal-footer d-flex justify-content-start">
<button type="button" className="btn btn-danger btn-radius">VALIDATE</button>
<button type="button" className="btn btn-secondary btn-secondary2 btn-radius" data-dismiss="modal">CANCEL</button>
</div>
</div>
</div>
</div>
</div>
);
}
} |
JavaScript | class RangeNumbersController extends Controller {
/**
*
* @param {number} defaultMin
* @param {number} defaultMax
* @param {Object} options options of InputController
*/
constructor(defaultMin, defaultMax, options) {
super('rangeNumbers');
this.options = Object.assign({}, defaultOptions)
for (var attrname in options) { this.options[attrname] = options[attrname]; }
this.minInputController = new RangeInputController(defaultMin, this.options, this, true)
this.maxInputController = new RangeInputController(defaultMax, this.options, this, false)
}
get type() {
return this.minInputController.type
}
} |
JavaScript | class RangeInputController extends InputController {
/**
* Create RangeInputController for RangeNumbersController
* @param {*} defaultValue defaultValue of InputController
* @param {Object} inputOptions inputOptions of InputController
* @param {RangeNumbersController} rangeNumbersController
* @param {boolean} min Is this component used for the minimum value of the range number?
*/
constructor(defaultValue, inputOptions, rangeNumbersController, min) {
super(defaultValue, inputOptions)
this.rangeNumbersController = rangeNumbersController
this.min = min
}
// Event called when the user input the field
blur() {
super.blur()
const minCtrlr = this.rangeNumbersController.minInputController
const maxCtrlr = this.rangeNumbersController.maxInputController
// This controller is used for the min value of rangeNumber and the max value is smaller than min
if ( this.min && maxCtrlr.value < minCtrlr.value ) {
maxCtrlr.value = minCtrlr.value // Set max to min value
}
// This controller is used for the max value of rangeNumber and the min value is bigger than max
if ( !this.min && minCtrlr.value > maxCtrlr.value ) {
minCtrlr.value = maxCtrlr.value // Set min to max value
}
}
} |
JavaScript | class Help extends Base {
constructor(client) {
// Initialise base command and pass data - all properties except name are optional
super(client, {
name: "help",
category: "Util",
enabled: true,
aliases: ["ajuda", "help"],
owner: false
});
}
run(message, args, Discord) {
let init = new Discord.MessageEmbed()
.setColor(`BLACK`)
.setTitle(`**<a:rikka_moon:777886530651947048>・${message.client.config.bot.botname} Help**`)
.setDescription("**Me chamo `"+message.client.config.bot.botname+"` um bot para Discord, com funções inovádoras e repletas de alegria para seu servidor**\n \n **<:rikka_link:777887753475194880>・Links**\n <:rikka_server:777874900923711488> | [Servidor de Suporte]("+message.client.config.bot.supportserverinvite+")\n <:rikka_link:777887753475194880> | [Website](https://"+message.client.config.url+") \n <:rikka_add:777896091840413778> | [Adicione-me]("+message.client.config.bot.botinvitelink+")\n \n **<:rikkahelppasta:769605039151906847>・Comandos**\n <:rikkahelpum:769601818061701196> | Moderação\n <:rikkahelpdois:769601901251526737> | Útilidade")
.setAuthor(message.client.config.bot.botname, message.client.user.displayAvatarURL())
.setImage("https://cdn.discordapp.com/attachments/743826730514514030/803063076110204958/Screenshot_20210124-214545.png")
.setFooter(`Comando requisitado por: ${message.author.username}`, message.author.displayAvatarURL({ dynamic: true }))
.setThumbnail(message.client.user.displayAvatarURL())
message.channel.send(init).then(msg => {
msg.react('769601818061701196')
msg.react('769601901251526737')
const ModFilter = (reaction, user) => reaction.emoji.id === '769601818061701196' && user.id === message.author.id;
const UtilyFilter = (reaction, user) => reaction.emoji.id === '769601901251526737' && user.id === message.author.id;
const Mod = msg.createReactionCollector(ModFilter);
const Utily = msg.createReactionCollector(UtilyFilter);
Mod.on('collect', async r5 => {
r5.users.remove(message.author.id)
const comandosmod = await message.client.commands.array().filter(ch => ch.help.category === 'Mod');
let texto = ''
let embed = new Discord.MessageEmbed()
embed.setTitle("Comandos de Moderação")
embed.setThumbnail(message.client.user.displayAvatarURL())
embed.setTimestamp()
embed.setColor("8be9fd")
embed.setImage("https://cdn.discordapp.com/attachments/743826730514514030/803063076110204958/Screenshot_20210124-214545.png")
comandosmod.forEach(async cmd => {
texto += cmd.help.name.charAt(0).toUpperCase() + cmd.help.name.slice(1) + (comandosmod[comandosmod.length - 1].help.name === cmd.help.name ? '.' : ', ');
})
embed.setDescription(texto)
msg.edit(embed)
})
Utily.on('collect', async r5 => {
r5.users.remove(message.author.id)
const comandosutil = await message.client.commands.array().filter(ch => ch.help.category === 'Util');
let texto = ''
let embed = new Discord.MessageEmbed()
.setTitle("Comandos de Útilidade")
.setDescription('`Help`')
.setThumbnail(message.client.user.displayAvatarURL())
.setTimestamp()
.setColor("8be9fd")
.setImage("https://cdn.discordapp.com/attachments/743826730514514030/803063076110204958/Screenshot_20210124-214545.png")
comandosutil.forEach(async cmd => {
texto += cmd.help.name.charAt(0).toUpperCase() + cmd.help.name.slice(1) + (comandosutil[comandosutil.length - 1].help.name === cmd.help.name ? '.' : ', ');
})
embed.setDescription(texto)
msg.edit(embed)
})
})
}
} |
JavaScript | class EntSelectorTemplate {
/**
* Constructs a new <code>EntSelectorTemplate</code>.
* @alias module:model/EntSelectorTemplate
*/
constructor() {
EntSelectorTemplate.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>EntSelectorTemplate</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/EntSelectorTemplate} obj Optional instance to populate.
* @return {module:model/EntSelectorTemplate} The populated <code>EntSelectorTemplate</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new EntSelectorTemplate();
if (data.hasOwnProperty('ActionOutputFilter')) {
obj['ActionOutputFilter'] = JobsActionOutputFilter.constructFromObject(data['ActionOutputFilter']);
}
if (data.hasOwnProperty('AsFilter')) {
obj['AsFilter'] = ApiClient.convertToType(data['AsFilter'], 'Boolean');
}
if (data.hasOwnProperty('ContextMetaFilter')) {
obj['ContextMetaFilter'] = JobsContextMetaFilter.constructFromObject(data['ContextMetaFilter']);
}
if (data.hasOwnProperty('DataSourceSelector')) {
obj['DataSourceSelector'] = JobsDataSourceSelector.constructFromObject(data['DataSourceSelector']);
}
if (data.hasOwnProperty('Description')) {
obj['Description'] = ApiClient.convertToType(data['Description'], 'String');
}
if (data.hasOwnProperty('IdmSelector')) {
obj['IdmSelector'] = JobsIdmSelector.constructFromObject(data['IdmSelector']);
}
if (data.hasOwnProperty('Label')) {
obj['Label'] = ApiClient.convertToType(data['Label'], 'String');
}
if (data.hasOwnProperty('Name')) {
obj['Name'] = ApiClient.convertToType(data['Name'], 'String');
}
if (data.hasOwnProperty('NodesSelector')) {
obj['NodesSelector'] = JobsNodesSelector.constructFromObject(data['NodesSelector']);
}
if (data.hasOwnProperty('TriggerFilter')) {
obj['TriggerFilter'] = JobsTriggerFilter.constructFromObject(data['TriggerFilter']);
}
}
return obj;
}
} |
JavaScript | class RCCircuit {
/**
*
* Take a value of resistance in ohms and value of capacitance in farads and calculates the
* cut off frequency of a low-pass circuit. The return value is in hertz.
*
* @param {number} resistance
* @param {number} capacitance
* @returns {number}
*/
static lowPassFilter(resistance, capacitance) {
return 1 / (2 * Math.PI * resistance * capacitance);
}
} |
JavaScript | class Cellphone {
//Método construtor
constructor(){
this.color = 'Branco';
this.call = function(){
return 'Fazendo uma ligação';
}
}
} |
JavaScript | class IndexMemoryMetric extends ElasticsearchMetric {
constructor(opts) {
super({
...opts,
title: 'Index Memory',
format: SMALL_BYTES,
metricAgg: 'max',
units: 'B'
});
}
} |
JavaScript | class SumerianConciergeUtils {
constructor(errorOutputId) {
this._errorOutput = document.getElementById(errorOutputId);
this._video = null;
this._stream = null;
}
get video() {
return this._video;
}
clearError() {
this._errorOutput.innerHTML = '';
}
/* Video helper functions */
/**
* Gets access and starts the webcam. Uses QVGA dimensions.
* Emits "videoCanPlay" event.
* @param {String} [videoId] DOM element ID for the video
* @param {Number} [faceDetectionRate] Rate per second the face detection algorithm is run. Prints message if webcam FPS is lower than this.
*/
startCamera(videoId, faceDetectionRate) {
this._video = document.getElementById(videoId);
if (!this._video) {
this._video = document.createElement('video');
}
navigator.mediaDevices.getUserMedia({ video: { width: 160, height: 120 }, audio: false })
.then((stream) => {
this._video.srcObject = stream;
this._stream = stream;
this._video.play();
// Set the video dimensions here as they are set to 0 until the video is ready to play.
// See https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement.
this._video.oncanplay = () => {
this._video.width = this._video.videoWidth;
this._video.height = this._video.videoHeight;
const webcamFps = this.precisionRound(stream.getVideoTracks()[0].getSettings().frameRate, 1);
if (faceDetectionRate > webcamFps) {
console.log(`[Sumerian Concierge] Your webcam's frame rate is ${webcamFps} fps. We recommend that the 'face detection rate' value on the Main Script Inspector panel is no higher than the webcam frame rate. Hover over the 'face detection rate' parameter on the IDE to see more details.`);
}
sumerian.SystemBus.emit("concierge.videoCanPlay");
}
})
.catch((err) => {
throw new Error(`Camera Error: ${err.name}. ${err.message}`);
});
}
/**
* Stops the webcam.
*/
stopCamera() {
if (this._video) {
this._video.pause();
this._video.srcObject = null;
}
if (this._stream) {
this._stream.getTracks()[0].stop();
}
}
/**
* Gets the webcam input as ImageData object and draws the input on the canvas with the id 'videoId'.
* Note that the image is flipped for webcam.
* @param {DOMElement} [videoId] Video DOM element
* @param {CanvasRenderingContext2D} [canvasContext] Canvas context for the video
* @param {int} [width] Canvas width
* @param {int} [height] Canvas height
* @returns {ImageData} The ImageData object containing the data for the webcam input
*/
getWebcamInputImageData(videoId, canvasContext, width, height) {
canvasContext.clearRect(0, 0, width, height);
// Flip the image for webcam
canvasContext.translate(width, 0);
canvasContext.scale(-1, 1);
canvasContext.drawImage(videoId, 0, 0, width, height);
// Reset the transform
canvasContext.setTransform(1, 0, 0, 1, 0, 0);
return canvasContext.getImageData(0, 0, width, height);
}
/**
* Draws the ImageData object onto a CanvasRenderingContext2D
* @param {ImageData} [inputImageData] Image data object to draw
* @param {CanvasRenderingContext2D} [canvasContext] Canvas context to draw the image data onto
* @param {int} [width] Canvas width
* @param {int} [height] Canvas height
*/
drawImageData(inputImageData, canvasContext, width, height) {
canvasContext.clearRect(0, 0, width, height);
if (inputImageData) {
canvasContext.putImageData(inputImageData, 0, 0);
}
}
/**
* Creates a data-URL from the canvas content and draws the webcam feed on the canvas.
* Note that the image is flipped for webcam.
* @param {DOMElement} [videoId] Video DOM element
* @param {Canvas} [canvas] Canvas to draw the video
* @param {CanvasRenderingContext2D} [canvasContext] Canvas context for the video
* @param {int} [width] Canvas width
* @param {int} [height] Canvas height
* @returns {DOMString} jpeg image as a string
*/
createWebcamFeedURL(videoId, canvas, canvasContext, width, height) {
canvasContext.clearRect(0, 0, width, height);
// Flip the image for webcam
canvasContext.translate(width, 0);
canvasContext.scale(-1, 1);
canvasContext.drawImage(videoId, 0, 0, width, height);
const imgURL = canvas.toDataURL('image/jpeg');
// Reset the transform
canvasContext.setTransform(1, 0, 0, 1, 0, 0);
return imgURL;
}
/**
* Shows image on canvas for debugging.
* @param {String} [imgStr] Image as a data-URL
* @param {CanvasRenderingContext2D} [canvasCtx] Canvas context to draw the image on
*/
showImageStringToCanvas(imgStr, canvasCtx) {
if (imgStr) {
const image = new Image();
image.onload = () => {
canvasCtx.drawImage(image, 0, 0);
};
image.src = imgStr;
}
}
/**
* Converts string to array buffer
* @param {String} str The string
* @returns {ArrayBuffer} Array buffer
*/
convertStringToArrayBuffer(str, ctx) {
// 2 bytes for each char
const buf = new ArrayBuffer(str.length * 2);
const bufView = new Uint16Array(buf);
for (let i = 0, len = str.length; i < len; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
/**
* Draws rectangle on the canvas. Useful for debugging face detection.
* @param {CanvasRenderingContext2D} [canvasContext] The canvas context to draw the rectangle on
* @param {String} [color] The color of the rectangle. See https://developer.mozilla.org/en-US/docs/Web/CSS/color_value for options
* @param {int} [x] The x-coordinate of the upper-left corner of the rectangle
* @param {int} [y] The y-coordinate of the upper-left corner of the rectangle
* @param {int} [width] The width of the rectangle, in pixels
* @param {int} [height] The height of the rectangle, in pixels
* @param {int} [canvasWidth] The width of the canvas
* @param {int} [canvasHeight] The height of the canvas
*/
drawRectangle(canvasContext, color, x, y, width, height, canvasWidth, canvasHeight) {
canvasContext.clearRect(0, 0, canvasWidth, canvasHeight);
canvasContext.strokeStyle = color;
canvasContext.strokeRect(x, y, width, height);
}
/**
* Get a random integer value less than max.
* @param {int} [max] The integer value one greater than the highest value returned by this function.
* @returns {Integer} A random integer
*/
getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
/**
* Rounds a number up to 0 or 1 decimal point.
* @param {Number} [number] A number input
* @param {Integer} [precision] 1 returns 1 decimal place, -1 removes decimal place
* @returns {Number} Rounded number
*/
precisionRound(number, precision) {
const factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
/**
* Gets the time of the day based on the local time.
* @returns {String} Time of the day based on the local time
*/
getTimeofDay() {
const hour = new Date().getHours();
let tod;
if (hour >= 6 && hour <= 12) {
tod = "morning";
} else if (hour > 12 && hour < 17){
tod = "afternoon";
} else {
tod = "evening";
}
return tod;
}
/**
* Asynchronously waits to execute a function for a period of time in milliseconds.
* @param {Integer} [ms] Time in milliseconds
* @returns {Promise} Resolves with setTimeout()
*/
sleep(ms) {
return new Promise((resolve) => { setTimeout(resolve, ms) });
}
/**
* Find key of the object given the value.
* @param {Object} [object] The object
* @param {Data} [value] The value for the key
* @returns {String} The key of the object
*/
findKeyOfObject(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
/**
* Prints script dependency error message for scripts attached on Main Script entity.
* @param {String} [thisScriptName] The script itself
* @param {String} [dependentScriptName] The script the file depends on
*/
printScriptDependencyError(thisScriptName, dependentScriptName) {
console.error("[Sumerian Concierge] Please make sure that " + dependentScriptName + ".js is loaded before " + thisScriptName + ".js on the Main Script entity. The scripts on the Script Component are loaded from top to bottom in Sumerian - you can change the order of file loading by dragging the files on the Inspector panel.");
}
/* Helper functions for handling HTML element visibility */
/**
* Fades in a DOM element with the defined id property.
* The classes are defined in CSSGlobal.html.
* @param {String} [id] The id property
*/
fadeInElementId(id) {
if (id && id.classList.contains("fade-out")) {
id.classList.remove("fade-out");
id.classList.add("fade-in");
}
}
/**
* Fades out a DOM element with the defined id property.
* The classes are defined in CSSGlobal.html.
* @param {String} [id] The id property
*/
fadeOutElementId(id) {
if (id && id.classList.contains("fade-in")) {
id.classList.add("fade-out");
id.classList.remove("fade-in");
}
}
/**
* Shows DOM element with the defined id property.
* The classes are defined in CSSGlobal.html.
* @param {String} [id] The id property
*/
showElementId(id) {
if (id && id.classList.contains("hide")) {
id.disabled = false;
id.classList.remove("hide");
id.classList.add("show");
this.fadeInElementId(id);
}
}
/**
* Hides DOM element with the defined id property.
* The classes are defined in CSSGlobal.html.
* @param {String} [id] The id property
*/
hideElementId(id) {
if (id && id.classList.contains("show")) {
id.disabled = true;
this.fadeOutElementId(id);
id.classList.remove("show");
id.classList.add("hide");
}
}
/**
* API call
*/
callAPI() { // 1
// const GEO_URL = 'https://sonchau.pythonanywhere.com/summarizer/api/v1.0/summarize';
// fetch(GEO_URL) // 2
// .then(response => response.json())
// .then(({my_response}) => {
// console.log(my_response);
// });
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'https://sonchau.pythonanywhere.com/summarizer/api/v1.0/summarize'
fetch(proxyUrl+targetUrl, {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res=>res.json())
.then(res => console.log(res));
}
} |
JavaScript | class Reducer {
commonDebug(registrations, registered, path) {
const passedRegistered = registered || registrations;
const passedPath = path || this.getDispatchName();
Object.keys(passedRegistered).forEach(actionKey => {
const action = passedRegistered[actionKey];
const actionPath = Reducer.getActionName(passedPath, actionKey);
if (typeof action === 'function') {
console.log(actionPath);
} else {
this.commonDebug(registrations, action, actionPath);
}
});
}
debug(actions, path) {
if (!actions && !path) {
console.log(this.getDispatchName(), 'remob');
}
console.log('actions');
this.commonDebug(this.actions);
console.log('selectors');
this.commonDebug(this.selectors);
}
/**
* simple action register
* reducer will check this implementations to call on some change
*/
registerAction(fn, path) {
this.actions = this.getActions();
set(this.actions, path, fn);
}
/**
* simple dispatch register
* on inherit it will get this dispatches to pass through
*/
registerDispatch(fn, path) {
this.dispatches = this.getDispatches();
set(this.dispatches, path, fn);
}
/**
* simple selector register
* needed for inherit purposes as dispatch
*/
registerSelector(fn, path) {
this.selectors = this.getSelectors();
set(this.selectors, path, fn);
}
/**
* inherit register dispatches
* it partially makes automatic insertion of methods into class from other remob
* it does not push this dispatches in this.disaptches, you have to do it elsewhere
* like registerMixin does
*/
registerDispatches(dispatches, path) {
if (typeof dispatches === 'function') {
set(this, path, partialRight(dispatches, this.getDispatchName(path)));
} else {
each(dispatches, (fn, fnKey) => {
this.registerDispatches(fn, Reducer.getActionName(path, fnKey));
});
}
}
/**
* inherit register action
* it passes implementation of actions to this.action
* pretending to be @action - making function to be actionable.
*/
registerActions(actions, path, prevPath = '') {
if (typeof actions === 'function') {
this.registerAction(actionable(actions, prevPath, false), path);
} else {
each(actions, (fn, fnKey) => {
this.registerActions(fn, Reducer.getActionName(path, fnKey), prevPath || path);
});
}
}
/**
* inherit register mixin
* manually pushes registers for dispatch and selectors, as well as initial state
* automatically passes actionale and dispatchables with registerDispatches and registerActions.
*/
registerMixin(mixin, mixinKey) {
const { actions, dispatches, initialState, selectors } = mixin;
this.initialState[mixinKey] = initialState;
this.dispatches[mixinKey] = dispatches;
this.selectors[mixinKey] = selectors;
this.registerActions(actions, mixinKey);
this.registerDispatches(dispatches, mixinKey);
}
// getters
getInitialState(initialState) {
return initialState || this.initialState || {};
}
getActions() {
return this.actions || {};
}
getDispatches() {
return this.dispatches || {};
}
getSelectors() {
return this.selectors || {};
}
constructor(initialState) {
// binds
this.registerDispatches = this.registerDispatches.bind(this);
this.registerActions = this.registerActions.bind(this);
this.registerMixin = this.registerMixin.bind(this);
this.getDispatchName = this.getDispatchName.bind(this);
this.getClearActionType = this.getClearActionType.bind(this);
this.debug = this.debug.bind(this);
this.commonDebug = this.commonDebug.bind(this);
this.reducer = this.reducer.bind(this);
// default setters
this.actions = this.getActions();
this.dispatches = this.getDispatches();
this.initialState = this.getInitialState(initialState);
this.selectors = this.getSelectors();
// mixin registrator
each(this.initialState, (value, key) => {
if (value instanceof Reducer) {
this.registerMixin(value, key);
}
});
}
// path helpers
getClearActionType(action) {
return action.type.split(`${this.constructor.name}.`).pop();
}
static getActionName(path, fnKey = '') {
return `${path}${path && fnKey ? '.' : ''}${fnKey}`;
}
getDispatchName(path) {
return Reducer.getActionName(this.constructor.name, path);
}
// reducer
reducer(state = this.initialState, action) {
const clearActionType = this.getClearActionType(action);
const callableAction = get(this.actions, clearActionType);
return callableAction ? callableAction(state, action) : state;
}
} |
JavaScript | class AiringsService {
/**
* Search for lineups for a particular zip code and country
* @param {Object} queries
* @returns {Promise<Array>}
*/
static async searchLineups(queries = {}) {
try {
return await Request.fetchLineUps(queries);
} catch (e) {
throw new Error(e);
}
}
/**
* Get airings for a specific lineup
* @param {String} tmsId
* @param {Object} queries
* @returns {Promise<Array>}
*/
static async fetchAirings(lineupId, queries) {
try {
return await Request.fetchAirings(lineupId, queries);
} catch (e) {
throw new Error(e);
}
}
/**
* Create a new list of airing(s)
* @param {Array} data
* @param {Boolean} isBulk
* @returns {Object}
*/
static async create(data, isBulk = false) {
try {
return !isBulk
? await Airings.create(data)
: await Airings.insertMany(data);
} catch (e) {
throw new Error(e);
}
}
/**
* Fetch an airing from DB
* @params {Object} filter
* @returns {Promise<Array>}
*/
static async findOne(filter = {}) {
try {
return await Airings.findOne(filter).lean();
} catch (e) {
throw new Error(e);
}
}
/**
* Fetch airings from DB
* @returns {Promise<Array>}
*/
static async findAll(skip = 0, limit = 0, sort = -1) {
try {
return await Airings.find()
.skip(skip)
.limit(limit)
.sort({ _id: sort })
.lean();
} catch (e) {
throw new Error(e);
}
}
/**
* Return number of airings found
* @returns {Promise<Number>}
*/
static async count() {
try {
return await Airings.countDocuments();
} catch (e) {
throw new Error(e);
}
}
/**
* Updates an airing
* @param {Object} filter - query filter
* @param {Object} new_data - update data
* @returns {Promise<Object>} Fulfillment
*/
static async updateOne(filter, new_data) {
try {
return await Airings.updateOne(filter, new_data);
} catch (e) {
throw new Error(e);
}
}
} |
JavaScript | class OKMWebservice {
// eslint-disable-next-line no-unused-vars
constructor(opts = {}) {
this._restURL = '/rest';
this._jSessionId = '';
this._token = '';
}
/**
* Set the token in webservice modules variables
*
* @param token - The authorization token value
*/
setToken(token) {
this._token = token;
}
/**
* Get the current token
* @returns {*} Return the current token
*/
getToken() {
return this._token;
}
/**
* Set the JSESSIONID in webservice module
*
* @param jSessionId
*/
setJSessionId(jSessionId) {
this._jSessionId = jSessionId;
}
/**
* Get the JSESSIONID
*
* @returns {string} Return the JSESSIONID value
*/
getJSessionId() {
return this._jSessionId;
}
/**
* Set the host url
*
* @param hostUrl - The host url
*/
setHostUrl(hostUrl) {
console.log(hostUrl);
}
} |
JavaScript | class Greeting extends React.Component {
render() {
return React.createElement("p", null,
"Greeting! with number = ",
this.props.val);
}
} |
JavaScript | class UserAPI extends API {
/**
* Creates UserAPI
* @param {UserListQuery} userListQuery
* @returns {Promise} list of users
*/
list(userListQuery = new UserListQuery()) {
return this.send(ApiMap.listUser, userListQuery.toObject());
}
/**
* Returns count of users
* @param {UserCountQuery} userCountQuery
* @returns {Promise} count of users
*/
count(userCountQuery = new UserCountQuery()) {
return this.send(ApiMap.countUser, userCountQuery.toObject());
}
/**
* Returns information about the current user
* @param {number} userId
* @returns {Promise} selected user
*/
get(userId) {
return this.send(ApiMap.getUser, { userId: userId });
}
/**
* Registers a user
* @param {User} user data
* @returns {Promise} count of users
*/
insert(user) {
return this.send(ApiMap.addUser, {}, user.toObject());
}
/**
* Updates a user (only for administrators)
* @param {User} user data
* @returns {Promise} count of users
*/
update(user) {
return this.send(ApiMap.updateUser, { userId: user.id }, user.toObject());
}
/**
* Deletes an existing user
* @param {number} userId
* @returns {Promise}
*/
delete(userId) {
return this.send(ApiMap.deleteUser, { userId: userId });
}
/**
* Returns information about the current user
* @returns {Promise} selected user
*/
getCurrent() {
return this.send(ApiMap.getCurrentUser);
}
/**
* Updates a user (only for administrators)
* @param {User} user data
* @returns {Promise} count of users
*/
updateCurrent(user) {
return this.send(ApiMap.updateCurrentUser, {}, user.toObject());
}
/**
* Returns user's device types
* @param userId
* @returns {Promise}
*/
getDeviceTypes(userId) {
return this.send(ApiMap.getUserDeviceTypes, { userId: userId });
}
/**
* Unassigns all user's device types
* @param userId
* @returns {Promise}
*/
unassignAllDeviceTypes(userId) {
return this.send(ApiMap.unassignAllDeviceTypes, { userId: userId });
}
/**
* Assigns all device types to user
* @param userId
* @returns {Promise}
*/
assignAllDeviceTypes(userId) {
return this.send(ApiMap.assignAllDeviceTypes, { userId: userId });
}
/**
* Unassigns mentioned device type
* @param userId
* @param deviceTypeId
* @returns {Promise}
*/
unassignDeviceType(userId, deviceTypeId) {
return this.send(ApiMap.unassignDeviceType, { userId: userId, deviceTypeId: deviceTypeId });
}
/**
* Returns user's device type by id
* @param userId
* @param deviceTypeId
* @returns {Promise}
*/
getDeviceType(userId, deviceTypeId) {
return this.send(ApiMap.getUserDeviceType, { userId: userId, deviceTypeId: deviceTypeId });
}
/**
* Assigns mentioned device type to user
* @param userId
* @param deviceTypeId
* @returns {Promise}
*/
assignDeviceType(userId, deviceTypeId) {
return this.send(ApiMap.assignDeviceType, { userId: userId, deviceTypeId: deviceTypeId });
}
/**
* Gets information about user/network association
* @param {number} userId - User ID
* @param {number} networkId - Network ID
* @returns {Promise}
*/
getNetwork(userId, networkId) {
return this.send(ApiMap.getUserNetwork, { userId: userId, networkId: networkId });
}
/**
* Associates network with the user
* @param {number} userId - User ID
* @param {number} networkId - Network ID
* @returns {Promise}
*/
assignNetwork(userId, networkId) {
return this.send(ApiMap.assignNetwork, { userId: userId, networkId: networkId });
}
/**
* Removes association between network and user
* @param {number} userId - User ID
* @param {number} networkId - Network ID
* @returns {Promise}
*/
unassignNetwork(userId, networkId) {
return this.send(ApiMap.unassignNetwork, { userId: userId, networkId: networkId });
}
} |
JavaScript | class Cities extends React.Component {
static propTypes = {
pakCities: PropTypes.array
}
render() {
return (
<div>
<ul>
{
this.props.pakCities.map((city, index) => <li key={index}>{city}</li>)
}
</ul>
<button onClick={this.props.changeTheState}>Change the State</button>
</div>
);
}
} |
JavaScript | class Blooket extends EventEmitter {
constructor() {
super();
};
/* Global */
/**
* @function joinGame
* @param {string} gamePin
* @param {string} botName
* @param {string} blook
*/
async joinGame(gamePin, botName, blook) {
checkPinType(gamePin);
checkNameType(botName);
const game = await this.getGameData(gamePin);
const data = {
blook: blook,
name: botName,
gameSet: game.host.set,
gameMode: game.host.s.t
}
const cred = await getCred(gamePin, botName)
const ranges = serverCodes();
ranges.forEach(async range => {
const socketUrl = await findSocketUri(range.code);
const ws = new WebSocket(socketUrl);
ws.on('open', () => {
ws.send(messages.authorize(cred))
ws.send(messages.join(gamePin, botName, blook))
});
});
this.emit('Joined', data)
};
/**
* @function floodGame
* @param {string} gamePin
* @param {string} amount
*/
async floodGame(gamePin, amount) {
checkPinType(gamePin);
if (amount > 100) {
throw new Error(errors.onJoin.amount);
} else {
for (let i = 0; i < amount; i++) {
const botName = crypto.randomBytes(10).toString('hex');
const randomBlook = getRandomBlook();
const cred = await getCred(gamePin, botName);
const ranges = serverCodes();
ranges.forEach(async range => {
const socketUrl = await findSocketUri(range.code);
const ws = new WebSocket(socketUrl);
ws.on('open', () => {
ws.send(messages.authorize(cred))
ws.send(messages.join(gamePin, botName, randomBlook))
});
});
this.emit('flood', { player: botName });
};
};
};
/**
* @function createGame
* @param {string} hostName
* @param {boolean} isPlus
* @param {string} qSetId
* @param {string} t_a
* @param {string} gameMode
* @param {string} authToken
*/
async createGame(hostName, isPlus, qSetId, t_a /* t = True | a = Amount */, gameMode, authToken) {
const dateISOString = new Date().toISOString();
const liveData = await liveCred(hostName, isPlus, qSetId, dateISOString, t_a, gameMode, authToken);
const cred = liveData._idToken
const gamePin = liveData._id
const ranges = serverCodes();
ranges.forEach(async range => {
const socketUrl = await findSocketUri(range.code);
const ws = new WebSocket(socketUrl);
ws.on('open', () => {
ws.send(messages.authorize(cred))
ws.send(messages.live.createGame(gamePin, hostName, isPlus, dateISOString, t_a, gameMode, qSetId))
});
});
this.emit('gameCreated', { gamePin: gamePin });
};
/**
* @function login
* @param {string} email
* @param {string} password
* @returns {Promise}
*/
async login(email, password) {
const response = await axios.post(utils.links.login, {
name: email,
password: password,
}, {
headers: {
Referer: 'https://www.blooket.com/',
},
});
if (response.data.errType == APIResponseMessages.login.errType.MSG_EMAIL) {
throw new Error(APIResponseMessages.login.MSG_E);
} else if (response.data.errType == APIResponseMessages.login.errType.MSG_PASSWORD) {
throw new Error(APIResponseMessages.login.MSG);
};
return response.data
};
/**
* @function getAccountData
* @param {string} authToken
* @returns {Promise}
*/
async getAccountData(authToken) {
const modifiedAuthToken = authToken.split('JWT ')[1];
const response = await axios(utils.links.verifyAcc + modifiedAuthToken);
if (response.data == null) {
throw new Error(errors.data.invalidAuthToken);
};
return response.data
};
/**
* @function getGameData
* @param {string} gamePin
* @returns {Promise}
*/
async getGameData(gamePin) {
checkPinType(gamePin);
const botName = crypto.randomBytes(10).toString('hex');
const checkGamePin = await isGameAlive(gamePin)
if (checkGamePin.success == true) {
const response = await axios.put(utils.links.join, {
id: gamePin,
name: botName,
}, {
headers: {
Referer: 'https://www.blooket.com/',
},
});
return response.data
} else {
throw new Error(errors.onJoin.invalidGame);
};
};
/**
* @function getAnswers
* @param {string} gamePin
* @returns {Promise}
*/
async getAnswers(gamePin) {
checkPinType(gamePin);
const game = await this.getGameData(gamePin);
const response = await axios(utils.links.gameQuery + game.host.set, {}, {
headers: {
Referer: 'https://www.blooket.com/',
},
});
const data = [];
response.data.questions.forEach(quetsion => {
data.push("Question: " + quetsion.question + " | Answer: " + quetsion.correctAnswers)
});
return data
};
/**
* @function spamPlayGame
* @param {string} setId
* @param {string} name
* @param {string} authToken
* @param {amount} amount
*/
async spamPlayGame(setId, name, authToken, amount) {
for (let i = 0; i < amount; i++) {
try {
await axios.post(utils.links.history, {
"standings": [{}],
"settings": {},
"set": "",
"setId": setId,
"name": name,
}, {
headers: {
authorization: authToken
},
});
this.emit('spamPlays', { setId: setId });
} catch (e) {
if (e.response.data == APIResponseMessages.historyAPI.MSG) {
console.log(APIResponseMessages.historyAPI.MSG);
break;
};
};
};
};
/**
* @function favoriteSet
* @param {string} setId
* @param {string} name
* @param {string} authToken
* @returns {Promise}
*/
async favoriteSet(setId, name, authToken) {
const checkIfFavorited = await isFavorited(setId, authToken);
if (checkIfFavorited == false) {
const response = await axios.put(utils.links.favorite, {
id: setId,
isUnfavoriting: false,
name: name,
}, {
headers: {
authorization: authToken,
},
});
return response.data
} else {
throw new Error(errors.favorite.favorited);
};
};
/**
* @function createSet
* @param {string} author
* @param {string} desc
* @param {boolean} isPrivate
* @param {string} title
* @param {string} authToken
* @returns {Promise}
*/
async createSet(author, desc, isPrivate, title, authToken) {
const response = await axios.post(utils.links.games, {
author: author,
coverImage: {},
desc: desc,
private: isPrivate,
title: title,
}, {
headers: {
authorization: authToken,
},
});
return response.data
};
/**
* @function addTokens
* @param {string} tokenAmount
* @param {string} xpAmount
* @param {string} name
* @param {string} authToken
* @returns {Promise}
*/
async addTokens(tokenAmount, xpAmount, name, authToken) {
const response = await axios.put(utils.links.rewards, {
addedTokens: tokenAmount,
addedXp: xpAmount,
name: name,
}, {
headers: {
authorization: authToken,
}
});
return response.data
};
/**
* @function getHistories
* @param {string} authToken
* @returns {Promise}
*/
async getHistories(authToken) {
const response = await axios(utils.links.histories, {
headers: {
authorization: authToken,
},
});
return response.data
};
/**
* @function getHomeworks
* @param {string} authToken
* @returns {Promise}
*/
async getHomeworks(authToken) {
const response = await axios(utils.links.homeworks, {
headers: {
authorization: authToken,
},
});
return response.data
};
/**
* @function deleteHomework
* @param {string} setId
* @param {string} authToken
* @returns {Promise}
*/
async deleteHomework(setId, authToken) {
try {
const response = await axios.delete(utils.links.homeWorkQuery + setId, {
headers: {
authorization: authToken,
},
});
return response.data
} catch (e) {
if (e.response.status == 404) {
throw new Error(e.response.data);
};
};
};
/**
* @function getBlooks
* @param {string} authToken
* @returns {Promise}
*/
async getBlooks(authToken) {
const response = await axios(utils.links.blooks, {
headers: {
authorization: authToken,
},
});
return response.data
};
/**
* @function getTokens
* @param {string} authToken
* @returns {Promise}
*/
async getTokens(authToken) {
const response = await axios(utils.links.tokens, {
headers: {
authorization: authToken,
},
});
return response.data
};
/**
* @function getStats
* @param {string} authToken
* @returns {Promise}
*/
async getStats(authToken) {
const response = await axios(utils.links.users, {
headers: {
authorization: authToken,
},
});
return response.data
};
/**
* @function getUserData
* @param {string} name
* @param {string} authToken
* @returns {Promise}
*/
async getUserData(name, authToken) {
try {
const response = await axios(utils.links.userQuery + name, {
headers: {
authorization: authToken,
},
});
return response.data
} catch (e) {
if (e.response.status == 404) {
throw new Error(e.response.data);
};
};
};
/**
* @function openBox
* @param {string} box
* @param {string} name
* @param {string} authToken
* @returns {Promise}
*/
async openBox(box, name, authToken) {
checkNameType(name);
const response = await axios.put(utils.links.unlock, {
box: box,
name: name,
}, {
headers: {
authorization: authToken,
},
});
return response.data
};
/**
* @function sellBlook
* @param {string} blook
* @param {string} name
* @param {number} numSold
* @param {string} authToken
* @returns {Promise}
*/
async sellBlook(blook, name, numSold, authToken) {
checkAmountType(numSold);
checkNameType(name)
const response = await axios.put(utils.links.sell, {
blook: blook,
name: name,
numSold: numSold,
}, {
headers: {
authorization: authToken,
},
});
return response.data
};
/* Global End */
/* Gold Quest */
/**
* @function stealGold
* @param {string} gamePin
* @param {string} victimName
* @param {number} goldAmount
*/
async stealGold(gamePin, victimName, goldAmount) {
checkAmountType(goldAmount)
const botName = "hecker" + Math.floor(100 + Math.random() * 900).toString();
const randomBlook = getRandomBlook();
const cred = await getCred(gamePin, botName);
const game = await this.getGameData(gamePin);
const names = Object.keys(game.host.c);
if (!names.includes(victimName)) throw new Error(victimName + " " + errors.gold.playerExists);
const ranges = serverCodes();
if (game.host.s.t != "Gold") {
throw new Error(errors.gold.func);
} else {
ranges.forEach(async range => {
const socketUrl = await findSocketUri(range.code);
const ws = new WebSocket(socketUrl);
ws.on('open', () => {
ws.send(messages.authorize(cred))
ws.send(messages.gold.join(gamePin, botName, randomBlook))
ws.send(messages.gold.steal(gamePin, botName, randomBlook, victimName, goldAmount))
});
});
this.emit('goldStolen', { player: victimName });
};
};
/**
* @function giveGold
* @param {string} gamePin
* @param {string} victimName
* @param {number} goldAmount
*/
async giveGold(gamePin, victimName, goldAmount) {
checkAmountType(goldAmount);
const botName = "hecker" + Math.floor(100 + Math.random() * 900).toString();
const randomBlook = getRandomBlook();
const cred = await getCred(gamePin, botName);
const game = await this.getGameData(gamePin);
const names = Object.keys(game.host.c)
if (!names.includes(victimName)) throw new Error(victimName + " " + errors.gold.playerExists);
const ranges = serverCodes();
if (game.host.s.t != "Gold") {
throw new Error(errors.gold.func);
} else {
ranges.forEach(async range => {
const socketUrl = await findSocketUri(range.code);
const ws = new WebSocket(socketUrl);
ws.on('open', () => {
ws.send(messages.authorize(cred))
ws.send(messages.gold.join(gamePin, botName, randomBlook))
ws.send(messages.gold.give(gamePin, botName, randomBlook, victimName, goldAmount))
});
});
this.emit('goldGiven', { player: victimName });
};
};
/* Gold Quest End */
/* Racing */
async endGame(gamePin) {
const botName = "hecker" + Math.floor(100 + Math.random() * 900).toString();
const cred = await getCred(gamePin, botName);
const game = await this.getGameData(gamePin);
const goalAmount = game.host.s.a
const ranges = serverCodes();
if (game.host.s.t != "Racing") {
throw new Error(errors.racing.func);
} else {
ranges.forEach(async range => {
const socketUrl = await findSocketUri(range.code);
const ws = new WebSocket(socketUrl);
ws.on('open', () => {
ws.send(messages.authorize(cred))
ws.send(messages.join(gamePin, botName, "Dog"))
ws.send(messages.racing.endGame(gamePin, botName, goalAmount))
});
});
this.emit('gameEnded', { pin: gamePin });
};
};
/* Racing End */
/* Santas workshop */
async giveToys(gamePin, victimName, toyAmount) {
checkAmountType(toyAmount);
const botName = "hecker" + Math.floor(100 + Math.random() * 900).toString();
const randomBlook = getRandomBlook();
const cred = await getCred(gamePin, botName);
const game = await this.getGameData(gamePin);
const names = Object.keys(game.host.c)
if (!names.includes(victimName)) throw new Error(victimName + " " + errors.toy.playerExists);
const ranges = serverCodes();
if (game.host.s.t != "Toy") {
throw new Error(errors.toy.func);
} else {
ranges.forEach(async range => {
const socketUrl = await findSocketUri(range.code);
const ws = new WebSocket(socketUrl);
ws.on('open', () => {
ws.send(messages.authorize(cred))
ws.send(messages.toy.join(gamePin, botName, randomBlook))
ws.send(messages.toy.give(gamePin, botName, randomBlook, victimName, toyAmount))
});
});
this.emit('toysGiven', { player: victimName });
};
};
async stealToys(gamePin, victimName, toyAmount) {
checkAmountType(toyAmount)
const botName = "hecker" + Math.floor(100 + Math.random() * 900).toString();
const randomBlook = getRandomBlook();
const cred = await getCred(gamePin, botName);
const game = await this.getGameData(gamePin);
const names = Object.keys(game.host.c);
if (!names.includes(victimName)) throw new Error(victimName + " " + errors.toy.playerExists);
const ranges = serverCodes();
if (game.host.s.t != "Toy") {
throw new Error(errors.toy.func);
} else {
ranges.forEach(async range => {
const socketUrl = await findSocketUri(range.code);
const ws = new WebSocket(socketUrl);
ws.on('open', () => {
ws.send(messages.authorize(cred))
ws.send(messages.toy.join(gamePin, botName, randomBlook))
ws.send(messages.toy.steal(gamePin, botName, randomBlook, victimName, toyAmount))
});
});
this.emit('toysStolen', { player: victimName });
};
};
/* Santas Workshop End */
} |
JavaScript | class App extends Component {
constructor() {
super();
this.mediaQuery = {
desktop: 768
};
this.state = {
windowWidth: document.body.clientWidth
};
}
/**
* when the component is being mounted (one of the first things that occur)
* it will create an event listener that listens to the changes in browser
* resizing so we can dynamically make changes depending on how wide the screen is
*/
componentDidMount() {
window.addEventListener("resize", () => {
this.setState({ windowWidth: document.body.clientWidth });
});
}
render() {
let device =
this.state.windowWidth < this.mediaQuery.desktop ? "mobile" : "desktop";
return (
<Router>
<Route exact path="/" render={() => <Home device={device} />} />
<Route
exact
path="/classes"
render={() => <Classes device={device} />}
/>
<Route
exact
path="/contact"
render={() => <Contact device={device} />}
/>
</Router>
);
}
} |
JavaScript | class DatabaseManager {
constructor(id = createID(6)) {
let ref = this
this.timer = setInterval(this.onTick, 15 * 1000, ref);
this.id = id;
this.lastSaved = new Date().toJSON()
this.database = {
"profile": new Profile(),
"items" : [
new Record({
id: "Quick start",
contentType: "Extract",
content: {
"ops": [
{
"attributes": {
"bold": true
},
"insert": "Welcome to Eve!"
},
{
"insert": "\n\n"
},
{
"attributes": {
},
"insert": "This is an alpha release which does mean that the product may consist of bugs here and there. Therefore there are a few things you need to know: when working in Eve please do export the database frequently via the profile page. This means that you will save all your content on your local store which you will be able to import later on if something goes wrong. The platform has only been tested on Safari and Chrome, avoid internet explorer when using Eve. If you find any bugs please report them asap for us to fix them as fast as possible. This can be done via the bugs channel. Any recommendation for a new feature? Then there is a suggestions channel for this. "
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "Quick start:"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Write down the ID, this works as a password. There is no need for a mail"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "2. When you are logged in, go to the shortcut pages via the face in the top right corner and press shortcuts. Here you will see all shortcuts and for changing a shortcut just press the new keyboard combination"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "3. Now go to the main window and you can start processing your content. If you want image occlusion just drag and drop an image to the window and start to draw rectangles and press the shortcut for generating an image occlusion (can be found in the shortcut window)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "4. Start training will go through all your collection (images, extract, and clozes) with SM-2 algorithm. Use the spacebar as default to show the answer and CTRL + 1 - 5 to rate the card from very hard to very easy."
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "Functions currently supported:"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Cloze deletions"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Image occlusions"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Incremental reading"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Similar content (parsing words from Oxford and articles from Wikipedia)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Profile (Cards due, total repetitions)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Customizable keyboard shortcuts"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Export database"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Import database"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Zen Mode"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Dark Mode"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Learning mode"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- SM-2 for image occlusions and clozes"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "- Information structure with folders fully customizable"
},
{
"insert": "\n\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "Q: What is EVE?"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "A: Eve is specifically tailored for evidence-based effective studying with help of evidence-based methods such as spaced repetition (SM2), interleaved practice, and incremental reading."
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "Q: How do I come in contact?"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "A: Send us a message on Discord (MirrorNeuron#1929) or join our channel: https://discord.gg/2xkMPmcGZh."
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "Q: How do I report a bug?"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "A: Please do post it in the bugs channel at Discord."
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "Q: How do I suggest a feature?"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "A: Send a message on the suggestion channel at Discord."
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "Q: How is Eve different from SuperMemo?"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "A: Eve is web-based which means it will run on all systems (even the smartphone). In regards to the algorithm, Eve is using SM2 instead of SM18 which probably will make some difference in lifelong learning and especially when there is a lot of information in the database. There is also a function in Eve which is called \"Similar content\" which means that for each selected word it will send a request to Oxford and Wikipedias API to extract the meaning of the word and similar related concepts. This is great because it will help the user with the coherence of the concept."
},
{
"insert": "\n\n\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "How to make an image occlusion"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Drop an image in the main working window"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "2. Start to drag on the window to create occlusions"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "3. When all occlusions are done, press your shortcut (default: CTRL + Z)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "4. Now you will see the image in the left sidebar"
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "How to make a cloze"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Select the text you want to make a cloze of in the main working window"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "2. Press the shortcut for closure (default: CTRL + C)"
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "How to make a text extract for IR (incremental reading)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Select the text you want to extract from the main working window"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "2. Press the shortcut for text extraction (default: CTRL + X)"
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "How to rename an item (folder, image, or extract)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Right-click on the item in the left sidebar "
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "2. Select the renamed item and enter the name in the input"
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "How to remove an item from the information tree"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Right-click on the item and press remove"
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "How to create a folder"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Right-click on the folder you want to make a folder in"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "2. Select create folder and enter the name of the folder in the input field"
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "How to create an empty text document"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Right-click in the left sidebar on an item and press create text"
},
{
"insert": "\n\n\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "Layout"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "The layout consists of one sidebar to the left, one main working window in the middle, a sidebar to the right, and a header."
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "The header"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. Profile /settings (Due count, Cloze count, Folder count, export and import database)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "2. Zen mode (remove distractions and keep only necessary things visible)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "3. Dark mode"
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "The left sidebar"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "1. The engage button is used for training with help of SM-2. It will start and shuffle through your content (images, clozes, and extracts). You will press space to show the answer then grade how well you remember the item with (default CTRL + 1 - 5) and then it will show you the next item."
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "2. The information tree consists of all your content (images, closures, and extracts)"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "3. The context menu. Right-click on an item and you will see a menu"
},
{
"insert": "\n\n"
},
{
"attributes": {
"bold": true
},
"insert": "The right sidebar:"
},
{
"insert": "\n"
},
{
"attributes": {
},
"insert": "This area is used for a similar context. It will in realtime make an image search and context search to find similar information as the word you have currently highlighted. If you hover the text or images on the right sidebar it will display the image as zoomed in and the text when hovering"
}
]
}
}),
new Record({
id: "Folder1",
contentType: "Folder",
}),
new Record({
id: "Folder2",
contentType: "Folder",
}),
new Record({
id: "Folder2/Folder3",
contentType: "Folder",
}),
new Record({
id: "Folder2/Folder4",
contentType: "Folder",
}),
new Record({
id: "Folder2/Folder4/Folder5",
contentType: "Folder",
}),
],
}
}
onTick(ref) {
if(ref.loggedIn) {
databaseManager.saveLocalDatabase()
graphicsManager.onTick()
}
}
getDatabaseID() {
return this.id
}
async getDatabaseByID(id) {
let r = await fetch(BASE_URL + id + ".json")
if(r.ok) {
let jsonDatabase = await r.json()
return jsonDatabase
} else {
return {}
}
}
setItemFlag(flagged){
const id = graphicsManager.lastRightClickedItemID
if (id != null && id != -1) {
let r = this.getRecordByID(id)
if (r !== undefined){
this.flagItemByID(id, flagged)
}
} else {
graphicsManager.toggleAlert("Can not flag/unflag item.", "warning")
}
}
flagItemByID(id, flagged) {
let r = this.getRecordByID(id)
if (r !== undefined) {
r.isFlagged = flagged
console.log(r.isFlagged)
if (flagged)
r.dueDate = new Date(r.dueDate).addDays(3).toJSON()
graphicsManager.renderFolders()
graphicsManager.expandAllParentsToID(r.id)
if (flagged)
graphicsManager.toggleAlert("Item has been flagged and delayed with 3 days.", "success")
else
graphicsManager.toggleAlert("Item has been unflagged.", "success")
} else {
graphicsManager.toggleAlert("Can not flag/unflag current item.", "warning")
}
}
addImageOcclusions(separateOcclusions, id, occlusions = []) {
// Check if image is visible, then display.
if (document.getElementById("modalbox-occlusion-create").classList.contains("visible")) {
let itemID = -1
if(separateOcclusions) {
let r = databaseManager.getRecordByID(graphicsManager.lastMenuItemClicked)
if (r != null) {
if (r.contentType == "Folder" || r.contentType == "Extract") {
occlusions.forEach(occlusion => {
itemID = r.id + "/" + createID(4) + "-" + id
this.database.items.push(new Record({
id: itemID,
url: id,
contentType: "Occlusion",
occlusions: [occlusion]
}))
})
}
} else {
occlusions.forEach(occlusion => {
itemID = createID(4) + "-" + id
this.database.items.push(new Record({
id: itemID,
url: id,
contentType: "Occlusion",
occlusions: [occlusion]
}))
})
}
} else {
let r = databaseManager.getRecordByID(graphicsManager.lastMenuItemClicked)
if (r != null) {
if (r.contentType == "Folder" || r.contentType == "Extract") {
// Place image occlusions in selected folder.
itemID = r.id + "/" + createID(4) + "-" + id
this.database.items.push(new Record({
id: itemID,
url: id,
contentType: "Occlusion",
occlusions: occlusions
}))
}
} else {
// Place image occlusions in root folder.
itemID = createID(4) + "-" + id
this.database.items.push(new Record({
id: itemID,
url: id,
contentType: "Occlusion",
occlusions: occlusions
}))
}
}
console.log(itemID)
graphicsManager.renderFolders()
graphicsManager.expandAllParentsToID(itemID)
graphicsManager.toggleAlert("Image occlusions generated.", "success")
} else {
graphicsManager.toggleAlert("No image occlusion visible.", "warning")
}
}
toggleImagesInSidebar() {
if(this.database.profile.showImagesInSidebar)
this.database.profile.showImagesInSidebar = false
else
this.database.profile.showImagesInSidebar = true
}
toggleRightSidebar() {
if(this.database.profile.showRightSidebar)
this.database.profile.showRightSidebar = false
else
this.database.profile.showRightSidebar = true
}
// async saveLocalDatabaseOnClose() {
// const r = this.getRecordByID(graphicsManager.activeInformationID)
// const url = BASE_URL + this.id + ".json"
// if (r !== undefined)
// r.content = graphicsManager.quill.getContents()
// //this.pushAgoliaToRemote()
// let database = JSON.stringify(this.database);
// let blob = new Blob([database], {type: "application/json"});
// navigator.sendBeacon(url, blob)
// }
increasePriority(amount) {
}
postponeItemID(id, days = 3) {
let r = this.getRecordByID(id)
if (r != undefined) {
if (r.dueDate != null)
r.dueDate = new Date(r.dueDate).addDays(days).toJSON()
const children = this.getAllChildrenByParentId(id).filter(r => r.id)
for(const child of children) {
if (child.dueDate != null)
child.dueDate = new Date(child.dueDate).addDays(days).toJSON()
console.log("Child postponed: " + child.dueDate)
}
graphicsManager.toggleAlert("Item(s) postponed with " +days+ " days!", "success")
databaseManager.saveLocalDatabase()
} else {
graphicsManager.toggleAlert("Can not postpone item(s). Try another item.", "warning")
}
}
postpone(days = 7) {
const id = graphicsManager.lastRightClickedItemID
if (id!= null && id != -1) {
let r = this.getRecordByID(id)
if (r != undefined) {
if (r.dueDate != null)
r.dueDate = new Date(r.dueDate).addDays(days).toJSON()
const children = this.getAllChildrenByParentId(id).filter(r => r.id)
for(const child of children) {
if (child.dueDate != null)
child.dueDate = new Date(child.dueDate).addDays(days).toJSON()
console.log("Child postponed: " + child.dueDate)
}
graphicsManager.toggleAlert("Item(s) postponed with " +days+ " days!", "success")
databaseManager.saveLocalDatabase()
} else {
graphicsManager.toggleAlert("Can not postpone item(s). Try another item.", "warning")
}
} else {
graphicsManager.toggleAlert("Can not postpone item(s). Try another item.", "warning")
}
}
async getPublicDatabases() {
const username = await localforage.getItem("username")
const password = await localforage.getItem("password")
var myHeaders = new Headers()
myHeaders.append("Authorization", `Basic ${username}:${password}`)
var requestOptions = {
method: 'GET',
headers: myHeaders,
};
let res = await fetch("https://evecloud.io/public/data", requestOptions)
let response = await res.json()
if (response.error && response.error == 403)
return []
else
return response.databases
}
updateDatabase(database) {
if (database.profile.version != undefined) {
if (database.profile.version != DATABASE_VERSION) {
database.profile.version = DATABASE_VERSION
database.profile.changelogViewed = false
console.log("Database has been updated to version: " + DATABASE_VERSION)
} else {
database.profile.changelogViewed = true
console.log("Database is up to date: " + DATABASE_VERSION)
}
} else {
database.profile.version = DATABASE_VERSION
database.profile.changelogViewed = false
console.log("Database (version) set to: " + DATABASE_VERSION + " database has been updated!")
}
if (database.profile.mainWindowPadding == undefined) {
database.profile.mainWindowPadding = 4
console.log("Database (mainWindowPadding) set to: " + database.profile.mainWindowPadding)
}
if (database.profile.leftSidebarPadding == undefined) {
database.profile.leftSidebarPadding = 4
console.log("Database (leftSidebarPadding) set to: " + database.profile.leftSidebarPadding)
}
if (database.profile.rightSidebarPadding == undefined) {
database.profile.rightSidebarPadding = 4
console.log("Database (rightSidebarPadding) set to: " + database.profile.rightSidebarPadding)
}
if (database.profile.showToolbar == undefined) {
database.profile.showToolbar = true
console.log("Database (showToolbar) set to: " + database.profile.showToolbar)
}
if (database.profile.theme == undefined) {
database.profile.theme = "day"
console.log("Database (theme) set to: " + database.profile.theme)
}
if (database.profile.tutorialCompleted == undefined) {
database.profile.tutorialCompleted = false
console.log("Database (statistics) set to: " + database.profile.tutorialCompleted)
}
if (database.profile.statistics == undefined) {
database.profile.statistics = {}
console.log("Database (statistics) set to: {}")
}
if (database.profile.changelogViewed == undefined) {
database.profile.changelogViewed = false
console.log("Database (changelogViewed) set to: " + database.profile.changelogViewed)
}
if (database.profile.windowPadding == undefined) {
database.profile.windowPadding = 12
console.log("Database (windowPadding) set to: " + database.profile.windowPadding)
}
if (database.profile.showRightSidebar == undefined) {
database.profile.showRightSidebar = true
console.log("Database (showRightSidebar) set to: " + database.profile.showRightSidebar)
}
if (database.items[0].isFlagged == undefined) {
database.items.find(r => r.isFlagged = false)
console.log("Database (isFlagged) set to false.")
}
if (database.profile.acceptedPolicy == undefined) {
database.profile.acceptedPolicy = false
console.log("Database (acceptedPolicy) set to false.")
}
let l = database.profile.shortcuts.find(s => s.event == "input-flag-item")
if (l == undefined) {
database.profile.shortcuts.push({event: "input-flag-item", keyCode: 70, altKey: false, metaKey: true, ctrlKey: true, shift: false, combination: "CTRL + F"})
console.log("Database (isFlagged) set to false")
}
return database
}
encrypt(word, key = databaseManager.id) {
let encJson = CryptoJS.AES.encrypt(JSON.stringify(word), key).toString()
let encData = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(encJson))
return encData
}
decrypt(word, key = databaseManager.id) {
let decData = CryptoJS.enc.Base64.parse(word).toString(CryptoJS.enc.Utf8)
let bytes = {}
try {
bytes = CryptoJS.AES.decrypt(decData, key).toString(CryptoJS.enc.Utf8)
} catch (error) {
console.log(error)
}
return bytes
}
isJSON(str) {
try {
return (JSON.parse(str) && !!str);
} catch (e) {
return false;
}
}
async userExistByID(username) {
let response = await fetch(BASE_URL + username + ".json")
if(response.ok) {
let res = await response.text()
if (res.includes("status")) {
return false
} else {
return true
}
} else {
return null
}
}
async register(username, password) {
document.getElementById("modalbox-login").classList.remove("visible");
document.getElementById("modalbox-login").classList.add("hidden");
document.getElementById("overlay").classList.remove("visible");
document.getElementById("overlay").classList.add("hidden");
if(!IS_DEVELOPMENT) {
await graphicsManager.triggerPolicy()
await graphicsManager.triggerTutorial()
}
var myHeaders = new Headers()
myHeaders.append("Authorization", `Basic ${username}:${password}`)
var requestOptions = {
method: 'POST',
headers: myHeaders,
};
let res = await fetch("https://evecloud.io/user/register", requestOptions)
let registerMessage = await res.json()
if (registerMessage.error == 420) {
graphicsManager.toggleAlert("This username is already taken. Try another one.", "warning")
} else if (registerMessage.error == 200) {
graphicsManager.renderFolders()
await localforage.setItem("username", username)
await localforage.setItem("password", password)
graphicsManager.toggleAlert("You have now registered.", "success")
}
}
async login(username, password) {
var myHeaders = new Headers()
myHeaders.append("Authorization", `Basic ${username}:${password}`)
var requestOptions = {
method: 'GET',
headers: myHeaders,
};
let res = await fetch("https://evecloud.io/user/data", requestOptions)
let response = await res.json()
if (response.error && response.error == 403) {
graphicsManager.toggleAlert("You don't have access.", "warning")
this.register(username, password)
} else {
await localforage.setItem("username", username)
await localforage.setItem("password", password)
document.getElementById("modalbox-login").classList.remove("visible");
document.getElementById("modalbox-login").classList.add("hidden");
this.id = username
this.password = password
this.loggedIn = true
this.database = this.updateDatabase(response)
if (!IS_DEVELOPMENT) {
if (this.database.profile.acceptedPolicy == false)
await graphicsManager.triggerPolicy()
if (this.database.profile.tutorialCompleted == false)
await graphicsManager.triggerTutorial()
document.getElementById("overlay").classList.remove("visible");
document.getElementById("overlay").classList.add("hidden");
} else {
this.database.profile.acceptedPolicy = true
this.database.profile.tutorialCompleted = true
document.getElementById("overlay").classList.remove("visible");
document.getElementById("overlay").classList.add("hidden");
}
if (this.database.profile.changelogViewed == false)
graphicsManager.triggerChangelog()
graphicsManager.renderFolders()
let r = this.database.items.find(r => r.contentType == "Extract")
if(r !== undefined) {
graphicsManager.renderInputBox(r)
graphicsManager.expandAllParentsToID(r.id)
}
if(databaseManager.database.profile.showToolbar == false) {
document.getElementById("ql-").add("hidden")
}
setTheme(databaseManager.database.profile.theme)
document.getElementById("mainwindow-padding-slider").value = databaseManager.database.profile.mainWindowPadding
document.documentElement.style.setProperty('--mainWindow-padding', databaseManager.database.profile.mainWindowPadding + "px");
}
}
// async loadSharedDatabase(username, password) {
// let response = await fetch(BASE_URL + id + ".json")
// if(response.ok) {
// let data = await response.text()
// if (data.includes("status")) {
// return {}
// } else if (data.includes("profile")) {
// return JSON.parse(data)
// } else {
// let jsonResponse = JSON.parse(this.decrypt(data, password))
// if("profile" in jsonResponse)
// return jsonResponse
// else
// return {}
// }
// } else {
// return {}
// }
// }
// Import public database to current user.
async importDatabaseByUsername(username) {
var myHeaders = new Headers()
var requestOptions = {
method: 'GET',
headers: myHeaders,
};
let res = await fetch("https://evecloud.io/user/data/rere", requestOptions)
let response = await res.json()
if (response.error && response.error == 403) {
graphicsManager.toggleAlert("You don't have access.", "warning")
} else {
this.database.data = response
graphicsManager.toggleAlert("Database has been imported.", "success")
}
}
async saveLocalDatabase() {
let r = this.getRecordByID(graphicsManager.activeInformationID)
console.log(r)
if (r !== null && r !== undefined) {
r.content = graphicsManager.quill.getContents()
}
this.lastSaved = new Date().toJSON()
//const encryptedData = this.encrypt(this.database, this.password)
const username = await localforage.getItem("username")
const password = await localforage.getItem("password")
var myHeaders = new Headers()
myHeaders.append("Authorization", `Basic ${username}:${password}`)
myHeaders.append("Content-type", `application/json`)
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: JSON.stringify(this.database)
};
let res = await fetch("https://evecloud.io/user/data", requestOptions)
let response = await res.json()
if (response.error && response.error == 403) {
graphicsManager.toggleAlert("You don't have access for pushing a db to this username.", "warning")
}
graphicsManager.saveLocalDatabase()
}
deltaToRawText(delta) {
let parent = document.createElement("div")
let q = new Quill(document.createElement("div"))
if (typeof delta === 'string')
q.setText(delta)
else
q.setContents(delta)
parent.innerHTML = q.root.innerHTML
return q.getText()
}
async convertImageToWEBP(file) {
return new Promise((resolve, reject) => {
let image = new Image()
image.src = URL.createObjectURL(file)
image.onload = () => {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext("2d")
canvas.width = image.width
canvas.height = image.height
ctx.drawImage(image, 0, 0)
canvas.toBlob(function (blob) {
//resolve(blob)
//resolve(URL.createObjectURL(blob))
let file = new File([blob], 'my-new-name.webp', { type: "image/webp" })
resolve(file)
}, "image/webp")
}
})
}
getFileArrayBuffer(file) {
return new Promise((resolve, reject) => {
let read = new FileReader()
read.readAsArrayBuffer(file)
read.onloadend = function(){
resolve(read.result)
}
})
}
uploadFile(file, path = "") {
return new Promise(async (resolve, reject) => {
let id = ""
let extension = ""
let filename = ""
if (path == "") {
id = createID(6)
extension = file.type.split("/")[1]
filename = id + "." + extension
path = BASE_URL + filename
}
const imageDataBuffer = await this.getFileArrayBuffer(file)
console.log(path)
document.title = "Eve — Effective learning (uploading...)"
await fetch(path, {
method: "POST",
body: imageDataBuffer,
headers: new Headers({
"Content-Type": file.type
})
})
document.title = "Eve — Effective learning"
// Return filename
resolve(path.replace(BASE_URL, ""))
})
}
async uploadToFile(content, filename, contentType = "application/json") {
const URL = BASE_URL + filename
await fetch(URL, {
method: "POST",
body: content,
headers: new Headers({
"Content-Type": contentType
})
})
}
downloadToFile (content, filename, contentType = "application/json") {
const a = document.createElement('a');
const file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
}
readFile(file) {
return new Promise(resolve => {
const fr = new FileReader();
fr.onload = e => {
resolve(e.target.result);
};
fr.readAsText(file)
})
}
async deleteDatabase() {
const accept = confirm("Are you sure you want to remove this account, this can not be undone.")
if (accept) {
const username = await localforage.getItem("username")
const password = await localforage.getItem("password")
var myHeaders = new Headers()
myHeaders.append("Authorization", `Basic ${username}:${password}`)
var requestOptions = {
method: 'POST',
headers: myHeaders,
};
let res = await fetch("https://evecloud.io/user/delete", requestOptions)
let response = await res.json()
if (response.error && response.error == 200)
await profileManager.logout()
else
graphicsManager.toggleAlert("Can not remove database.", "warning")
}
}
async exportSelectedDatabase(e) {
const r = databaseManager.getRecordByID(graphicsManager.lastRightClickedItemID)
if (r != null) {
// Get all items which begins with r.id
//await this.saveLocalDatabase()
let children = this.getAllChildrenByParentId(r.id)
children.push(r)
this.downloadToFile(JSON.stringify(children), r.id+".json")
graphicsManager.toggleAlert("Selected path has been exported.", "success")
} else {
this.exportDatabase()
graphicsManager.toggleAlert("The full database has been exported.", "success")
}
}
async importSelectedDatabase(e) {
const r = databaseManager.getRecordByID(graphicsManager.lastRightClickedItemID)
if (r != null) {
this.importDatabase(true, r.id)
graphicsManager.toggleAlert("Database has been imported to selected path!", "success")
} else {
this.importDatabase(true)
graphicsManager.toggleAlert("Database has been imported!", "success")
}
}
async exportDatabase() {
await this.saveLocalDatabase()
this.downloadToFile(JSON.stringify(this.database), "database.json");
}
getDateToday() {
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
let yyyy = today.getFullYear();
let date = yyyy + "-" + mm + "-" + dd
return date
}
async createFreeRecallDocument(clozeList) {
let path = "Recall/"+getDateToday()+"_"+createID(3)
if(databaseManager.itemExistByID("Recall") == false)
databaseManager.createFolder("Recall")
console.log(clozeList)
let content = []
for (const [key, value] of Object.entries(clozeList)) {
console.log(key)
console.log(value)
value.insert += "↵↵↵"
value.insert += "\n\n\n"
content.push({attributes: value.attributes, insert: value.insert})
}
console.log(content)
if (databaseManager.itemExistByID(path) == false)
databaseManager.createText(path, content)
learningManager.recallClozeList = []
}
importQuizletDatabase() {
/*
Sagital plan::Transversalplan
Skär kroppen i två lika delar "framåt"
Coronal plan::Frontal
Skär kroppen i två lika delar "sidled"
Transverse plan::Horisontellt
Skär kroppen i midjan "uppåt"
Os frontale::Pannben
Os maxilla::Överkäken
"Kindben"
*/
let input = document.createElement('input')
input.setAttribute("accept", ".txt")
input.type = 'file'
input.onchange = e => {
const fileList = e.target.files
let fileContent = []
let reader = new FileReader()
reader.onload = () => {
fileContent = reader.result.split("\n\n")
for(const row of fileContent) {
// Check if cloze item
//if(row.contains("{{c")) {
this.createText(createID(5), [{ insert: row }])
//}
console.log("Row: " + row)
}
}
reader.readAsText(fileList[0])
}
input.click()
}
importAnkiDatabase() {
/*
{{c2::Stockholm}} är huvudstaden i {{c1::Sverige}}?
{{c1::Martin}} är mitt namn.
{{c2::Stockholm}} är större än {{c1::Linköping}}
Vad heter Sveriges huvudstad? Stockholm
Vad heter Frankrikes huvudstad? Paris
Vad heter Italiens huvudstad? Rom
Vad heter Greklands huvudstad? Aten
*/
let input = document.createElement('input')
input.setAttribute("accept", ".txt")
input.type = 'file'
input.onchange = e => {
const fileList = e.target.files
let fileContent = []
let reader = new FileReader()
reader.onload = () => {
fileContent = reader.result.split("\n")
for(const row of fileContent) {
// Check if cloze item
//if(row.contains("{{c")) {
this.createText(createID(5), [{ insert: row }])
//}
console.log("Row: " + row)
}
}
reader.readAsText(fileList[0])
}
input.click()
}
async importDatabase(onlyItems = false, startsWithID = ""){
let input = document.createElement('input');
input.setAttribute("accept", ".json,application/json")
input.type = 'file';
input.onchange = e => {
let file = e.target.files[0];
let reader = new FileReader();
reader.onload = (function(f) {
return function(e) {
if(onlyItems) {
const items = JSON.parse(this.result)
for (const item of items) {
if(startsWithID !== "") {
item.id = startsWithID + "/" + item.id
}
databaseManager.database.items.push(item)
}
} else {
const id = createID(6)
databaseManager.database = JSON.parse(this.result)
databaseManager.id = id
}
graphicsManager.renderFolders()
};
})(file);
reader.readAsText(file);
}
input.click();
}
async importItemsDatabase(){
}
async sha256(message) {
// encode as UTF-8
const msgBuffer = new TextEncoder('utf-8').encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
return hashHex;
}
async makeDatabasePrivate() {
const username = await localforage.getItem("username")
const password = await localforage.getItem("password")
var myHeaders = new Headers()
myHeaders.append("Authorization", `Basic ${username}:${password}`)
var requestOptions = {
method: 'POST',
headers: myHeaders,
};
let res = await fetch("https://evecloud.io/user/set/public/false", requestOptions)
let response = await res.json()
if (response.error && response.error == 200) {
databaseManager.database.profile.isDatabasePublic = false
graphicsManager.toggleAlert("Database has been made private.", "success")
} else {
graphicsManager.toggleAlert("Can not make database private.", "warning")
}
}
async makeDatabasePublic() {
const username = await localforage.getItem("username")
const password = await localforage.getItem("password")
var myHeaders = new Headers()
myHeaders.append("Authorization", `Basic ${username}:${password}`)
console.log(username)
var requestOptions = {
method: 'POST',
headers: myHeaders,
};
let res = await fetch("https://evecloud.io/user/set/public/true", requestOptions)
let response = await res.json()
console.log(response)
if (response.error && response.error == 200) {
databaseManager.database.profile.isDatabasePublic = true
graphicsManager.toggleAlert("Database has been made public.", "success")
} else {
graphicsManager.toggleAlert("Error, can not make database public.", "warning")
}
}
async addRecord(record) {
// Append to statistics + 1.
learningManager.updateStatisticsItemCount()
this.database.items.push(record)
graphicsManager.renderFolders()
this.saveLocalDatabase()
}
removeRecordByID(id) {
this.database.items = this.database.items.filter(record => record.id != id)
this.saveLocalDatabase()
}
getRecordByID(id){
return this.database.items.find(record => record.id == id)
}
itemExistByID(id) {
if(this.database.items.filter(r => r.id == id).length > 0)
return true
else
return false
}
moveItemID(fromID, toID) {
if ( databaseManager.getRecordByID(toID + "/" + fromID) == undefined) {
const parent = this.getRecordByID(fromID)
const children = this.getAllChildrenByParentId(fromID)
const selectedNode = parent.id.split("/").pop()
parent.id = toID + "/" + selectedNode
if(children.length > 0) {
for(const child of children) {
child.id = parent.id + child.id.replace(fromID, "")
}
}
} else {
graphicsManager.toggleAlert("Item name already used, try another name.", "warning")
}
}
duplicateItem() {
const r = databaseManager.getRecordByID(graphicsManager.lastRightClickedItemID)
if (r != null) {
let nItem = new Record(r)
let arr = nItem.id.split("/")
let oldPath = arr[arr.length - 1]
let newID = createID(6)
nItem.id = nItem.id.replace(oldPath, newID)
this.addRecord(nItem)
graphicsManager.renderFolders()
graphicsManager.expandAllParentsToID(r.id)
} else {
this.toggleAlert("Can not duplicate this item.")
}
}
createText(id = createID(6), content = [{ insert: 'Enter your content here...' }]) {
this.addRecord(new Record({
"id": id,
"contentType": "Extract",
"content": content
}))
}
createFolder(folderName) {
this.addRecord(new Record({
id: folderName,
contentType: "Folder",
}))
}
removeItem(id) {
// Get all children by parent ID
const children = this.getAllChildrenByParentId(id).map(child => child.id)
for(const child of children)
this.removeRecordByID(child)
this.removeRecordByID(id)
}
renameItem(ID, newID) {
if (this.getRecordByID(newID) == undefined) {
let record = this.getRecordByID(ID)
let children = this.getAllChildrenByParentId(ID)
let parentArr = ID.split("/")
let lastPathID = parentArr[parentArr.length - 1]
let newPathID = ID.replace(lastPathID, newID)
record.id = newPathID
// Check if there is any children for parent.
if (children.length > 0 ) {
for(const child of children) {
const pathIDArr = child.id.split("/")
const lastPathID = pathIDArr[pathIDArr.length - 1]
child.id = newPathID + "/" + lastPathID
}
}
graphicsManager.renderFolders()
} else {
graphicsManager.toggleAlert("Name already used, try another name.", "warning")
}
}
isParentFolder(id) {
if(id.includes("/"))
return false
else
return true
}
// clipboardArticle() {
// let element = document.getElementById(graphicsManager.lastRightClickedSimilarContentID)
// dictionaryManager.getWikipediaSummary(element.innerHTML).then(article => {
// let key = Object.keys(article.query.pages)[0]
// let text = article.query.pages[key].extract
// graphicsManager.updateClipboard(text)
// })
// }
importArticle() {
let element = document.getElementById(graphicsManager.lastRightClickedSimilarContentID)
console.log(element)
dictionaryManager.getWikipediaSummary(element.innerHTML).then(article => {
let key = Object.keys(article.query.pages)[0]
let extract = article.query.pages[key].extract
this.createText(element.innerHTML+"-"+createID(2), [{ insert: extract }])
})
}
getAllChildrenByParentId(id){
// Return all children of parent id.
if (id.charAt(0) == "/")
id = id.substring(1)
let childrenList = this.database.items.filter(item => item.id.startsWith(id))
// Remove parent element from list.
childrenList.splice(childrenList.findIndex(element => element.id == id), 1);
return childrenList;
}
getAllParentsByChildId(id) {
// TODO: fix function, does not work.
var path = id.split("/");
var lastIndex = path.lastIndexOf("/");
var requiredPath = path.slice(0,lastIndex+1);
}
getAllParentPathByChildID(id) {
// TODO: fix function, does not work.
var path = id.split("/");
var lastIndex = path.lastIndexOf("/");
var requiredPath = path.slice(0,lastIndex+1);
}
getTotalReviewsCount() {
let total = 0
this.database.items.forEach(function(record) {
total += record.repetition
})
return total
}
getDueCount() {
let total = 0
if (databaseManager.database.profile.showClozesInLearningMode)
total += databaseManager.getDueClozeCount().length
if (databaseManager.database.profile.showOcclusionsInLearningMode)
total += databaseManager.getDueOcclusionCount().length
if (databaseManager.database.profile.showExtractsInLearningMode)
total += databaseManager.getDueExtractCount().length
return total
}
getDueCountAll() {
const items = this.database.items.filter(r => r.dueDate < new Date().toJSON() && r.contentType != "Folder")
return items.length
}
getPriorityQueue() {
let res = databaseManager.database.items.filter(
(r => r.contentType == "Cloze" ||
r.contentType == "Extract" ||
r.contentType == "Occlusion").sort((a, b) => a.dueDate - b.dueDate)
)
console.log(res)
return res
}
getExtractCount() {
return this.database.items.filter(r => r.contentType == "Extract").length
}
getFolderCount() {
return this.database.items.filter(r => r.contentType == "Folder").length
}
getClozeCount() {
return this.database.items.filter(r => r.contentType == "Cloze").length
}
getOcclusionCount() {
return this.database.items.filter(r => r.contentType == "Occlusion").length
}
getDueClozeCount() {
return this.database.items.filter(r => r.contentType == "Cloze" && r.dueDate < new Date().toJSON());
}
getDueOcclusionCount() {
return this.database.items.filter(r => r.contentType == "Occlusion" && r.dueDate < new Date().toJSON());
}
getDueExtractCount() {
return this.database.items.filter(r => r.contentType == "Extract" && r.dueDate < new Date().toJSON());
}
getDueClozeRecords() {
return this.database.items.filter(r => r.contentType == "Cloze" && r.dueDate < new Date().toJSON());
}
getDueClozeRecord() {
const r = this.getDueClozeRecords();
return r[Math.floor(Math.random() * r.length)];
}
getDueOcclusionRecords() {
return this.database.items.filter(r => r.contentType == "Occlusion" && r.dueDate < new Date().toJSON())
}
getDueOcclusionRecord() {
const r = this.getDueOcclusionRecords()
return r[Math.floor(Math.random() * r.length)];
}
getDueExtractRecords() {
return this.database.items.filter(r => r.contentType == "Extract" && r.dueDate < new Date().toJSON());
}
getDueExtractRecord() {
const r = this.getDueExtractRecords();
return r[Math.floor(Math.random() * r.length)];
}
getOcclusionRecords() {
return this.database.items.filter(r => r.contentType == "Occlusion");
}
getClozeRecords(){
return this.database.items.filter(r => r.contentType == "Cloze");
}
getExtractRecords(){
return this.database.items.filter(r => r.contentType == "Extract");
}
getClozeRecord(){
const r = this.getClozeRecords();
return r[Math.floor(Math.random() * r.length)];
}
getExtractRecord(){
let r = this.getExtractRecords();
return r[Math.floor(Math.random() * r.length)];
}
getOcclusionRecord() {
return getOcclusionRecords()[Math.floor(Math.random() * getOcclusionRecords.length)];
}
} |
JavaScript | class GraphicsManager {
constructor(){
this.isLightModeEnabled = true;
this.isNotZenModeEnabled = true;
this.activeInformationID = -1; // ID of current cloze / text extract or imageOcclusion.
this.lastRightClickedItemID = -1;
this.lastRightClickedSimilarContentID = -1 // ID of last right clicked item in right sidebar.
this.lastMenuItemClicked = 0 // Last id of clicked menu item in the sidebar.
this.lastActiveImageOcclusionURL = ""; // URL of last displayed image occlusion.
this.writtenCharCount = 0; // Autosave database when len > 25
//PERMISSIONS
this.askPermission()
this.toolbarOptions = [
[
'bold',
'italic',
'underline',
'strike',
'image',
'blockquote',
// { 'list': 'ordered'},
// { 'list': 'bullet' },
// { 'indent': '-1'},
// { 'indent': '+1' },
{ 'header': [1, 2, 3, 4, 5, 6, false] },
{ 'color': [] },
{ 'background': [] },
// { 'font': [] },
// { 'align': [] },
'clean'
],
];
this.statisticsOptions1 = {
series: [{
name: "Repetitions",
data: [0, 20]
}],
chart: {
height: 300,
type: 'line',
zoom: {
enabled: false
}
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'straight'
},
title: {
text: 'Repetitions per day',
align: 'left'
},
grid: {
row: {
colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.5
},
},
xaxis: {
categories: ['2021-01-02', '2021-01-02'],
}
};
this.statisticsOptions2 = {
series: [{
name: "New items",
data: [0, 20]
}],
chart: {
height: 300,
type: 'line',
zoom: {
enabled: false
}
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'straight'
},
title: {
text: 'New items per day',
align: 'left'
},
grid: {
row: {
colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.5
},
},
xaxis: {
categories: ['2021-01-02', '2021-01-02'],
}
};
this.chart1 = ""
this.chart2 = ""
//Quill.register("modules/imageUploader", ImageUploader)
//Quill.register("imageDropAndPaste", QuillImageDropAndPaste)
//Quill.register('modules/imageResize', ImageResize)
this.activeOcclusionsList = []
this.quill = new Quill('#content-input', {
theme: 'bubble',
modules: {
toolbar: this.toolbarOptions
}
})
//this.quill.keyboard.addBinding({ key: 'V', ctrlKey: true, shiftKey: true, altKey: true}, this.onQuillPaste);
//this.quill.keyboard.addBinding({ key: 'S', metaKey: true}, this.onQuillPaste);
this.quill.on("selection-change", this.onQuillSelectionChange)
this.quill.on('text-change', this.onQuillTextChange)
// Cursor position.
this.locA
this.locB
this.tutorialStep = 1
}
init() {
// this.renderInputBox(this.database.items[0])
// this.renderFolders()
}
onTick() {
this.sidebarUpdate()
}
duplicateItem() {
databaseManager.duplicateItem()
}
async triggerTutorial() {
this.tutorialStep = 1
document.getElementById("overlay").classList.add("visible")
document.getElementById("overlay").classList.remove("hidden")
document.getElementById("sidebar-left").classList.add("zIndexHighlight")
document.getElementById("learning-button").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step1").classList.remove("hidden")
document.getElementById("modalbox-content-tutorial-step2").classList.add("hidden")
const e = document.getElementById("modalbox-tutorial")
if (e.classList.contains("hidden"))
e.classList.remove("hidden")
else
e.classList.add("hidden")
return new Promise((resolve, reject) => {
document.getElementById("modalbox-tutorial-complete-button").addEventListener("click", function(e) {
document.getElementById("overlay").classList.remove("visible")
document.getElementById("overlay").classList.add("hidden")
document.getElementById("modalbox-tutorial").classList.add("hidden")
databaseManager.database.profile.tutorialCompleted = true
graphicsManager.toggleAlert("Well done, the tutorial will not show next login.", "success")
resolve(true)
})
})
}
stepTutorial(stepForward = true) {
if (stepForward)
this.tutorialStep += 1
else
this.tutorialStep -= 1
if (this.tutorialStep < 1)
this.tutorialStep = 1
else if(this.tutorialStep > 15)
this.tutorialStep = 15
if (this.tutorialStep == 1) {
// Sidebar left
document.getElementById("sidebar-left").classList.add("zIndexHighlight")
document.getElementById("learning-button").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step1").classList.remove("hidden")
document.getElementById("modalbox-content-tutorial-step2").classList.add("hidden")
} else if (this.tutorialStep == 2) {
// Engage button.
document.getElementById("sidebar-left").classList.remove("zIndexHighlight")
document.getElementById("learning-button").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step1").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step2").classList.remove("hidden")
document.getElementById("sidebar-saved").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step3").classList.add("hidden")
} else if (this.tutorialStep == 3) {
// Last saved.
document.getElementById("learning-button").classList.remove("zIndexHighlight")
document.getElementById("sidebar-saved").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step2").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step3").classList.remove("hidden")
document.getElementById("sidebar-due").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step4").classList.add("hidden")
} else if (this.tutorialStep == 4) {
document.getElementById("sidebar-saved").classList.remove("zIndexHighlight")
document.getElementById("sidebar-due").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step3").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step4").classList.remove("hidden")
document.getElementById("content-input").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step5").classList.add("hidden")
} else if (this.tutorialStep == 5) {
document.getElementById("sidebar-due").classList.remove("zIndexHighlight")
document.getElementById("content-input").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step4").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step5").classList.remove("hidden")
document.getElementById("header-settings-button").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step6").classList.add("hidden")
} else if (this.tutorialStep == 6) {
document.getElementById("content-input").classList.remove("zIndexHighlight")
document.getElementById("header-settings-button").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step5").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step6").classList.remove("hidden")
document.getElementById("header-darkmode-button").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step7").classList.add("hidden")
} else if (this.tutorialStep == 7) {
document.getElementById("header-settings-button").classList.remove("zIndexHighlight")
document.getElementById("header-darkmode-button").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step6").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step7").classList.remove("hidden")
document.getElementById("header-database-button").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step8").classList.add("hidden")
} else if (this.tutorialStep == 8) {
document.getElementById("header-darkmode-button").classList.remove("zIndexHighlight")
document.getElementById("header-database-button").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step7").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step8").classList.remove("hidden")
document.getElementById("header-explorer-button").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step9").classList.add("hidden")
} else if (this.tutorialStep == 9) {
document.getElementById("header-database-button").classList.remove("zIndexHighlight")
document.getElementById("header-explorer-button").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step8").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step9").classList.remove("hidden")
document.getElementById("header-flagged-button").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step10").classList.add("hidden")
} else if (this.tutorialStep == 10) {
document.getElementById("header-explorer-button").classList.remove("zIndexHighlight")
document.getElementById("header-flagged-button").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step9").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step10").classList.remove("hidden")
document.getElementById("header-statistics-button").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step11").classList.add("hidden")
} else if (this.tutorialStep == 11) {
document.getElementById("header-flagged-button").classList.remove("zIndexHighlight")
document.getElementById("header-statistics-button").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step10").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step11").classList.remove("hidden")
document.getElementById("sidebar-right").classList.remove("zIndexHighlight")
document.getElementById("sidebar-right").classList.remove("visible")
document.getElementById("modalbox-content-tutorial-step12").classList.add("hidden")
} else if (this.tutorialStep == 12) {
document.getElementById("header-statistics-button").classList.remove("zIndexHighlight")
document.getElementById("sidebar-right").classList.add("visible")
document.getElementById("sidebar-right").classList.add("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step11").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step12").classList.remove("hidden")
document.getElementById("modalbox-content-tutorial-step13").classList.add("hidden")
} else if (this.tutorialStep == 13) {
document.getElementById("sidebar-right").classList.remove("visible")
document.getElementById("sidebar-right").classList.remove("zIndexHighlight")
document.getElementById("modalbox-content-tutorial-step12").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step13").classList.remove("hidden")
document.getElementById("modalbox-content-tutorial-step14").classList.add("hidden")
//Hide the complete button and show the next button.
document.getElementById("modalbox-tutorial-complete-button").classList.add("hidden")
document.getElementById("modalbox-tutorial-next").classList.remove("hidden")
} else if (this.tutorialStep == 14) {
document.getElementById("modalbox-content-tutorial-step13").classList.add("hidden")
document.getElementById("modalbox-content-tutorial-step14").classList.remove("hidden")
//Hide the next button and show complete button.
document.getElementById("modalbox-tutorial-complete-button").classList.remove("hidden")
document.getElementById("modalbox-tutorial-next").classList.add("hidden")
}
}
toggleStatisticsModal() {
const categories = databaseManager.database.profile.statistics
let date = []
let reviewsCount = []
let newItemsCount = []
for (const [key, value] of Object.entries(categories)) {
date.push(key)
reviewsCount.push(value.reviewsCount)
newItemsCount.push(value.newItemsCount)
}
console.log(reviewsCount)
this.statisticsOptions1.xaxis.categories = date
this.statisticsOptions1.series[0].data = reviewsCount
this.statisticsOptions2.xaxis.categories = date
this.statisticsOptions2.series[0].data = newItemsCount
this.chart1 = new ApexCharts(document.querySelector("#chart1"), this.statisticsOptions1)
this.chart2 = new ApexCharts(document.querySelector("#chart2"), this.statisticsOptions2)
this.chart1.render()
this.chart2.render()
// 2. Show the modalbox.
const e = document.getElementById("modalbox-statistics")
if (e.classList.contains("hidden")) {
e.classList.add("visible")
e.classList.remove("hidden")
} else {
e.classList.remove("visible")
e.classList.add("hidden")
}
}
notifyMe(message) {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
console.log("This browser does not support desktop notification");
}
// Let's check whether notification permissions have alredy been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification(message);
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied' || Notification.permission === "default") {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification(message);
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
}
askNotificationPermission() {
if (!('Notification' in window)) {
console.log("This browser does not support notifications.")
} else {
if(Notification.permission == "default") {
Notification.requestPermission().then((permission) => {
handlePermission(permission)
})
}
}
}
askPermission() {
//this.askNotificationPermission()
}
renderPriority() {
document.getElementById("priority-list").innerHTML = "<tr><th>Item</th><th>Repetitions</th><th>E-factor</th><th>Priority</th></tr>"
const items = databaseManager.getPriorityQueue()
for (const record of items) {
let p = document.createElement("tr")
let name = document.createElement("td")
let repetitions = document.createElement("td")
let efactor = document.createElement("td")
let priority = document.createElement("td")
p.setAttribute("onclick", "graphicsManager.onClickExplorerItem(this)")
p.setAttribute("data-id", record.id)
name.innerHTML = record.id
repetitions.innerHTML = record.repetition
efactor.innerHTML = record.efactor
priority.innerHTML = record.priority
p.appendChild(name)
p.appendChild(repetitions)
p.appendChild(efactor)
p.appendChild(priority)
document.getElementById("priority-list").appendChild(p)
}
}
renderFlagged() {
document.getElementById("flagged-list").innerHTML = "<tr><th>Name</th><th>Repetitions</th><th>E-factor</th></tr>"
const items = databaseManager.database.items.filter(r => ["Cloze", "Occlusion", "Extract"].includes(r.contentType) && r.isFlagged)
for (const record of items) {
let p = document.createElement("tr")
let name = document.createElement("td")
let repetitions = document.createElement("td")
let efactor = document.createElement("td")
p.setAttribute("onclick", "graphicsManager.onClickExplorerItem(this)")
p.setAttribute("data-id", record.id)
name.innerHTML = record.id
repetitions.innerHTML = record.repetition
efactor.innerHTML = record.efactor
p.appendChild(name)
p.appendChild(repetitions)
p.appendChild(efactor)
document.getElementById("flagged-list").appendChild(p)
}
}
renderExplorer() {
document.getElementById("explorer-list").innerHTML = "<tr><th>Name</th><th>Repetitions</th><th>E-factor</th></tr>"
const items = databaseManager.database.items.filter(
r => ["Cloze", "Occlusion", "Extract"].includes(r.contentType) &&
r.repetition > -1 &&
r.efactor < 3
)
for (const record of items) {
let p = document.createElement("tr")
let name = document.createElement("td")
let repetitions = document.createElement("td")
let efactor = document.createElement("td")
p.setAttribute("onclick", "graphicsManager.onClickExplorerItem(this)")
p.setAttribute("data-id", record.id)
name.innerHTML = record.id
repetitions.innerHTML = record.repetition
efactor.innerHTML = record.efactor
p.appendChild(name)
p.appendChild(repetitions)
p.appendChild(efactor)
document.getElementById("explorer-list").appendChild(p)
}
}
onClickExplorerItem(item) {
document.querySelectorAll(".active").forEach((node) => {
node.classList.remove("active")
})
const dataID = item.getAttribute("data-id")
const r = databaseManager.getRecordByID(dataID)
if (r.contentType == "Occlusion") {
this.quill.setContents()
this.quill.enable(false)
this.lastMenuItemClicked = r.id
this.toggleOcclusionLearningModal(r.id)
item.classList.add("active")
} else if (r.contentType == "Extract" || r.contentType == "Cloze") {
this.quill.enable(true)
this.renderInputBox(r)
this.lastMenuItemClicked = r.id
item.classList.add("active")
} else if (r.contentType == "Folder") {
this.quill.setContents()
this.quill.enable(false)
this.lastMenuItemClicked = r.id
item.classList.add("active")
}
let e = document.querySelector("[data-id='"+dataID+"']")
e.classList.add("active")
graphicsManager.expandAllParentsToID(r.id)
}
async renderDatabases() {
document.getElementById("database-list").innerHTML = "<tr><th>Shared databases</th></tr>"
const publicIds = await databaseManager.getPublicDatabases()
for (const id of publicIds) {
console.log(id)
let p = document.createElement("tr")
let name = document.createElement("td")
let items = document.createElement("td")
let author = document.createElement("td")
p.setAttribute("data-id", id)
p.setAttribute("onclick", "graphicsManager.onClickDatabaseItem(this)")
name.innerHTML = id
items.innerHTML = "-"
p.appendChild(name)
//p.appendChild(itemCount)
document.getElementById("database-list").appendChild(p)
}
}
async renderLeaderboard() {
document.getElementById("leaderboard-list").innerHTML = "<tr><th>Leaderboard</th></tr>"
const publicProfiles = await databaseManager.getPublicProfiles()
for (const id of publicProfiles) {
// let p = document.createElement("tr")
// let name = document.createElement("td")
// let items = document.createElement("td")
// let author = document.createElement("td")
// p.setAttribute("data-id", id)
// p.setAttribute("onclick", "graphicsManager.onClickDatabaseItem(this)")
// name.innerHTML = id
// items.innerHTML = "-"
// p.appendChild(name)
// // p.appendChild(items)
// // p.appendChild(author)
// document.getElementById("leaderboard-list").appendChild(p)
}
}
async onClickDatabaseItem(e) {
let username = e.getAttribute("data-id")
let password = prompt("All your data in current database will be overwritten with shared database. Write 'accept' to continue.")
if (password == "accept") {
let response = await databaseManager.importDatabaseByUsername(username)
// Database login success, set id of database.
const savedId = databaseManager.database.profile.id
databaseManager.database = response
databaseManager.database.profile.id = savedId
databaseManager.id = savedId
document.getElementById("modalbox-databases").classList.add("hidden")
document.getElementById("modalbox-databases").classList.remove("visible")
this.renderFolders()
this.toggleAlert("Database loaded.", "success")
}
}
toggleOverlayProfile(){
document.getElementById("modalbox-profile").classList.add("visible")
document.getElementById("modalbox-profile").classList.remove("hidden")
document.getElementById("modalbox-shortcuts").classList.remove("visible")
document.getElementById("modalbox-shortcuts").classList.add("hidden")
document.getElementById("modalbox-learning").classList.remove("visible")
document.getElementById("modalbox-learning").classList.add("hidden")
document.getElementById("modalbox-interface").classList.remove("visible")
document.getElementById("modalbox-interface").classList.add("hidden")
document.getElementById("modalbox-database").classList.remove("visible")
document.getElementById("modalbox-database").classList.add("hidden")
}
toggleOverlayShortcuts(){
document.getElementById("modalbox-shortcuts").classList.add("visible")
document.getElementById("modalbox-shortcuts").classList.remove("hidden")
document.getElementById("modalbox-profile").classList.remove("visible")
document.getElementById("modalbox-profile").classList.add("hidden")
document.getElementById("modalbox-learning").classList.remove("visible")
document.getElementById("modalbox-learning").classList.add("hidden")
document.getElementById("modalbox-interface").classList.remove("visible")
document.getElementById("modalbox-interface").classList.add("hidden")
document.getElementById("modalbox-database").classList.remove("visible")
document.getElementById("modalbox-database").classList.add("hidden")
}
toggleOverlayLearning(){
document.getElementById("modalbox-learning").classList.add("visible")
document.getElementById("modalbox-learning").classList.remove("hidden")
document.getElementById("modalbox-shortcuts").classList.remove("visible")
document.getElementById("modalbox-shortcuts").classList.add("hidden")
document.getElementById("modalbox-profile").classList.remove("visible")
document.getElementById("modalbox-profile").classList.add("hidden")
document.getElementById("modalbox-interface").classList.remove("visible")
document.getElementById("modalbox-interface").classList.add("hidden")
document.getElementById("modalbox-database").classList.remove("visible")
document.getElementById("modalbox-database").classList.add("hidden")
}
toggleOverlayInterface(){
document.getElementById("modalbox-interface").classList.add("visible")
document.getElementById("modalbox-interface").classList.remove("hidden")
document.getElementById("modalbox-learning").classList.remove("visible")
document.getElementById("modalbox-learning").classList.add("hidden")
document.getElementById("modalbox-shortcuts").classList.remove("visible")
document.getElementById("modalbox-shortcuts").classList.add("hidden")
document.getElementById("modalbox-profile").classList.remove("visible")
document.getElementById("modalbox-profile").classList.add("hidden")
document.getElementById("modalbox-database").classList.remove("visible")
document.getElementById("modalbox-database").classList.add("hidden")
}
toggleOverlayDatabase(){
document.getElementById("modalbox-database").classList.add("visible")
document.getElementById("modalbox-database").classList.remove("hidden")
document.getElementById("modalbox-interface").classList.remove("visible")
document.getElementById("modalbox-interface").classList.add("hidden")
document.getElementById("modalbox-learning").classList.remove("visible")
document.getElementById("modalbox-learning").classList.add("hidden")
document.getElementById("modalbox-shortcuts").classList.remove("visible")
document.getElementById("modalbox-shortcuts").classList.add("hidden")
document.getElementById("modalbox-profile").classList.remove("visible")
document.getElementById("modalbox-profile").classList.add("hidden")
}
toggleOverlayInformation(){
document.getElementById("modalbox-information").classList.remove("visible")
document.getElementById("modalbox-information").classList.remove("hidden")
document.getElementById("modalbox-database").classList.remove("visible")
document.getElementById("modalbox-database").classList.add("hidden")
document.getElementById("modalbox-interface").classList.remove("visible")
document.getElementById("modalbox-interface").classList.add("hidden")
document.getElementById("modalbox-learning").classList.remove("visible")
document.getElementById("modalbox-learning").classList.add("hidden")
document.getElementById("modalbox-shortcuts").classList.remove("visible")
document.getElementById("modalbox-shortcuts").classList.add("hidden")
document.getElementById("modalbox-profile").classList.remove("visible")
document.getElementById("modalbox-profile").classList.add("hidden")
}
onQuillSelectionChange(range) {
if (range !== null && mobileCheck() == false) {
if(databaseManager.database.profile.showRightSidebar) {
const range = graphicsManager.quill.getSelection()
const selectedText = graphicsManager.quill.getText(range.index, range.length)
const similarContentSidebar = document.getElementById("sidebar-right")
const contentInput = document.getElementById("content-input")
if (selectedText.length == 0) {
if(contentInput.classList.contains("collapsed"))
contentInput.classList.remove("collapsed")
if(similarContentSidebar.classList.contains("visible"))
similarContentSidebar.classList.remove("visible")
}
if (selectedText.length > 0 && selectedText.length < 32) {
similarContentSidebar.innerHTML = ""
// getMeshTermByWord(selectedText).then(async items => {
// let meshTitle = document.createElement("h5")
// meshTitle.innerHTML = "Svensk MeSH"
// similarContentSidebar.appendChild(meshTitle)
// console.log("Mesh: " + items.length)
// if (items.length > 0) {
// if(!contentInput.classList.contains("collapsed"))
// contentInput.classList.add("collapsed")
// if(!similarContentSidebar.classList.contains("visible"))
// similarContentSidebar.classList.add("visible")
// }
// for(const [key, value] of Object.entries(items)) {
// const id = `sidebar-right-item-mesh-${createID(4)}`
// similarContentSidebar.innerHTML += `<a href="${value.link}" data='${value.description}' id="${id}" class="similar-content-item" target="_blank" and rel="noopener noreferrer" onmouseenter='graphicsManager.toggleItemSummary(event)' onmouseleave='graphicsManager.toggleItemSummary(event)' onclick='graphicsManager.toggleItemSummary(event)'>${value.title}</a><br>`
// }
// })
// psykologiguidenLookupWord(selectedText).then(async words => {
// let psykologiguidenTitle = document.createElement("h5")
// psykologiguidenTitle.innerHTML = "Psykologiguiden"
// similarContentSidebar.appendChild(psykologiguidenTitle)
// console.log("Psykologiguiden: " + words.length)
// if (words.length > 0) {
// if(!contentInput.classList.contains("collapsed"))
// contentInput.classList.add("collapsed")
// if(!similarContentSidebar.classList.contains("visible"))
// similarContentSidebar.classList.add("visible")
// }
// let psykologiguidenItems = []
// for(const [key, value] of Object.entries(words)) {
// const id = `sidebar-right-item-psykologiguiden-${createID(4)}`
// value.id = id
// psykologiguidenItems.push(value)
// similarContentSidebar.innerHTML += `<a data='' id="${id}" class="similar-content-item" target="_blank" and rel="noopener noreferrer" onmouseenter='graphicsManager.toggleItemSummary(event)' onmouseleave='graphicsManager.toggleItemSummary(event)' onclick=''>${value.lexWord}</a><br>`
// }
// // Add Psykologiguiden content to sidebar.
// for(const item of psykologiguidenItems) {
// const element = document.getElementById(item.id)
// const Response = await psykologiguidenGetExplanationByID(item.lexId)
// // const summary = response.
// // console.log(summary)
// // element.setAttribute("data", summary)
// }
// })
dictionaryManager.getWikipedia(selectedText).then(async articles => {
let wikipediaTitle = document.createElement("h5")
wikipediaTitle.innerHTML = "Wikipedia"
similarContentSidebar.appendChild(wikipediaTitle)
console.log("Wikipedia: " + articles[1].length)
if (articles[1].length > 0) {
if(!contentInput.classList.contains("collapsed"))
contentInput.classList.add("collapsed")
if(!similarContentSidebar.classList.contains("visible"))
similarContentSidebar.classList.add("visible")
}
let articleList = {
"title": articles[1],
"link": articles[3]
}
let items = []
for(let i = 0; i < articleList.title.length; i++) {
const title = articleList.title[i]
const link = articleList.link[i]
const id = `sidebar-right-item-${title}-${createID(2)}`
items.push({
"id": id,
"title": title,
"link": link
})
similarContentSidebar.innerHTML += `<a data='' id="${id}" class="similar-content-item" target="_blank" and rel="noopener noreferrer" onmouseenter='graphicsManager.toggleItemSummary(event)' onmouseleave='graphicsManager.toggleItemSummary(event)' onclick='graphicsManager.onWikipediaItemClicked(event)'>${title}</a><br>` //href='${link}'>${title}
}
// Add Wikipedia content to sidebar.
for(const item of items) {
const element = document.getElementById(item.id)
const article = await dictionaryManager.getWikipediaSummary(item.title)
const key = Object.keys(article.query.pages)[0]
const summary = article.query.pages[key].extract
element.setAttribute("data", summary)
}
})
// dictionaryManager.getRelatedPicturesByQuery(selectedText, 5).then(pictures => {
// if (pictures !== undefined) {
// for(let i = 0; i < pictures.value.length; i++) {
// let newImage = document.createElement("img")
// newImage.classList.add("sidebar-right-image")
// newImage.src = pictures.value[i].thumbnailUrl
// newImage.setAttribute("onclick", "graphicsManager.onImageSidebarClicked(event, this)")
// newImage.setAttribute("onmouseenter", "graphicsManager.toggleModalFullImage(event)")
// newImage.setAttribute("onmouseleave", "graphicsManager.toggleModalFullImage(event)")
// //newImage.setAttribute("onclick", "graphicsManager.updateOcclusionCreateCanvas(event)")
// similarContentSidebar.appendChild(newImage)
// }
// }
// })
}
} else {
const contentInput = document.getElementById("content-input")
if(contentInput.classList.contains("collapsed"))
contentInput.classList.remove("collapsed")
if(similarContentSidebar.classList.contains("visible"))
similarContentSidebar.classList.remove("visible")
}
}
}
onQuillTextChange(delta, oldDelta, source) {
// if(graphicsManager.writtenCharCount > 10) {
// graphicsManager.writtenCharCount = 0
// const r = databaseManager.getRecordByID(graphicsManager.activeInformationID)
// r.content = oldDelta
// }
// graphicsManager.writtenCharCount += 1
}
// toggleDefault(){}
// toggleSuccess(message = "test", time = 5)
// toggleWarning(){}
// toggleDanger(){}
toggleAlert(message, type = "default") {
let parent = document.getElementById("modalbox-alert")
let child = document.getElementById("modalbox-alert-message")
parent.classList = ""
parent.classList.add("modalbox-alert-active")
parent.classList.add(type)
child.innerHTML = message
let parentClone = parent.cloneNode(true);
let chhildClone = child.cloneNode(true);
parent.parentNode.replaceChild(parentClone, parent);
child.parentNode.replaceChild(chhildClone, child)
}
getMousePos(e) {
// Get the bounds of the clicked element.
var rect = e.target.getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
onCanvasMouseDown(e) {
e.preventDefault();
this.locA = this.getMousePos(e);
}
onCanvasMouseUp(e) {
e.preventDefault();
this.locB = this.getMousePos(e);
const factor = 2000 / 600
e.target.getContext('2d').fillStyle = '#CCCC00';
e.target.getContext('2d').fillRect(this.locA.x * factor, this.locA.y * factor, ((this.locB.x * factor) - (this.locA.x * factor)), ((this.locB.y * factor) - (this.locA.y * factor)));
this.activeOcclusionsList.push(
new Occlusion(this.locA.x * factor, this.locA.y * factor, ((this.locB.x * factor) - (this.locA.x * factor)), ((this.locB.y * factor) - (this.locA.y * factor)) )
)
}
sidebarUpdate(){
// Update graphics in sidebar
document.getElementById("sidebar-due-items").innerHTML = databaseManager.getDueCount() + "(" + databaseManager.getDueCountAll() + ")"
}
// When drag starts.
onFolderDrag(event) {
event.dataTransfer.setData("data-id", event.target.getAttribute("data-id"));
}
findDiff(str1, str2){
let diff= "";
str2.split('').forEach(function(val, i){
if (val != str1.charAt(i))
diff += val ;
});
return diff;
}
// When item has been dropped
onItemDrop(event) {
// When drop starts.
event.preventDefault();
let droppedOnDataID = event.target.getAttribute("data-id");
let dragedDataID = event.dataTransfer.getData("data-id");
let droppedOnRecord = databaseManager.getRecordByID(droppedOnDataID)
let dragedRecord = databaseManager.getRecordByID(dragedDataID)
/*
Folder1
Folder2
Folder2/Folder3
Folder2/Folder4
Folder2/Folder4/Folder5
Folder2/Folder4 ->
Folder2/Folder3 ->
Folder2/Folder3/Folder2
Folder2/Folder3/Folder2/Folder4
*/
// Disable drop functionality on other than folders and extracts.
if(["Folder", "Extract"].includes(droppedOnRecord.contentType)) {
// Check that the folder / item is not dropped on itself.
if (droppedOnDataID != dragedDataID) {
databaseManager.moveItemID(dragedDataID, droppedOnDataID)
graphicsManager.renderFolders()
graphicsManager.expandAllParentsToID(dragedDataID)
graphicsManager.expandAllParentsToID(droppedOnDataID)
graphicsManager.expandItemByID(droppedOnDataID)
} else {
graphicsManager.toggleAlert("Item can not be dropped on itself.", "warning")
}
} else {
this.toggleAlert("Dropped item can only be placed in folders or extracts.", "warning")
}
}
onFolderDragOver(event){
event.preventDefault();
}
renderClozure(record) {
// Check if record exists in database to show.
if (record === undefined) {
// No records in database, show empty
this.activeInformationID = -1
this.quill.setText("No records found in database. Create a new one with help of right clicking in the left sidebar and create folder or start typing in this window and use CTRL + X for extract or CTRL + C for cloze deletion.");
} else {
this.activeInformationID = record.id
if (["Cloze", "Extract"].includes(record.contentType)) {
this.quill.setContents(record.content);
if (record.contentType == "Cloze") {
record.clozes.forEach((cloze) => {
console.log(graphicsManager.isLightModeEnabled)
if (graphicsManager.isLightModeEnabled) {
this.quill.formatText(cloze.startindex, cloze.stopindex, {
'color': 'rgb(0,0,0)',
'background-color': 'rgba(115, 185, 255, 0.7)'
})
} else {
this.quill.formatText(cloze.startindex, cloze.stopindex, {
'color': 'rgb(255,255,255)',
'background-color': 'rgba(255, 255, 255, 0.7)'
})
}
})
}
}
}
}
toggleDatabaseShare() {
const b = document.getElementById("modalbox-settings-database-shared-checkbox")
if (databaseManager.database.profile.isDatabasePublic)
databaseManager.makeDatabasePrivate()
else
databaseManager.makeDatabasePublic()
}
toggleExtractsInLearning() {
const b = document.getElementById("modalbox-profile-extracts-button")
if ( b.classList.contains("enable-button") ) {
b.classList.remove("enable-button")
b.classList.add("disable-button")
b.innerHTML = "Disable extracts in learning mode"
} else {
b.classList.remove("disable-button")
b.classList.add("enable-button")
b.innerHTML = "Enable extracts in learning mode"
}
}
toggleOcclusionsInLearning() {
const b = document.getElementById("modalbox-profile-occlusions-button")
if ( b.classList.contains("enable-button") ) {
b.classList.remove("enable-button")
b.classList.add("disable-button")
b.innerHTML = "Disable occlusions in learning mode"
} else {
b.classList.remove("disable-button")
b.classList.add("enable-button")
b.innerHTML = "Enable occlusions in learning mode"
}
}
toggleClozesInLearning() {
const b = document.getElementById("modalbox-profile-clozes-button")
if ( b.classList.contains("enable-button") ) {
b.classList.remove("enable-button")
b.classList.add("disable-button")
b.innerHTML = "Disable clozes in learning mode"
} else {
b.classList.remove("disable-button")
b.classList.add("enable-button")
b.innerHTML = "Enable clozes in learning mode"
}
}
renderInputBox(record) {
// Check if record exists in database to show.
if (record === undefined) {
// No records in database, show empty
this.activeInformationID = -1
this.quill.setText("No records found in database. Create a new one with help of right clicking in the left sidebar and create folder or start typing in this window and use CTRL + X for extract or CTRL + C for cloze deletion.");
} else {
this.activeInformationID = record.id
if (["Cloze", "Extract"].includes(record.contentType)) {
this.quill.setContents(record.content);
if (record.contentType == "Cloze") {
if(graphicsManager.isLightModeEnabled) {
record.clozes.forEach((cloze) => {
this.quill.formatText(cloze.startindex, cloze.stopindex, {
'color': 'rgb(0, 0, 0)',
'background-color': 'rgba(0, 0, 0)'
})
})
} else {
record.clozes.forEach((cloze) => {
this.quill.formatText(cloze.startindex, cloze.stopindex, {
'color': 'rgb(255, 255, 255)',
'background-color': 'rgba(255, 255, 255)'
})
})
}
}
}
}
}
async triggerPolicy(){
document.getElementById("modalbox-tos").classList.add("visible")
document.getElementById("modalbox-tos").classList.remove("hidden")
document.getElementById("overlay").classList.add("visible")
document.getElementById("overlay").classList.remove("hidden")
graphicsManager.toggleAlert("In order to continue using Eve you have to accept the Terms of Agreement.")
return new Promise((resolve, reject) => {
document.getElementById("modalbox-tos-button").addEventListener("click", async function() {
document.getElementById("overlay").classList.remove("visible")
document.getElementById("overlay").classList.add("hidden")
document.getElementById("modalbox-tos").classList.remove("visible")
document.getElementById("modalbox-tos").classList.add("hidden")
databaseManager.database.profile.acceptedPolicy = true
databaseManager.database.loggedIn = true
graphicsManager.renderFolders()
databaseManager.saveLocalDatabase()
resolve(true)
})
});
}
async triggerChangelog() {
document.getElementById("modalbox-changelog").classList.add("visible")
document.getElementById("modalbox-changelog").classList.remove("hidden")
if(document.getElementById("overlay").classList.contains("hidden"))
document.getElementById("overlay").classList.remove("hidden")
graphicsManager.toggleAlert("Welcome back! A few changes has been made since you last visited.")
}
toggleSpotlight() {
let element = document.getElementById("modalbox-spotlight")
if(!element.classList.contains("visible")) {
element.classList.add("visible")
element.classList.remove("hidden")
} else {
element.classList.remove("visible")
element.classList.add("hidden")
}
}
createTextExtract() {
let currentID = graphicsManager.activeInformationID
let range = this.quill.getSelection()
let selectedText = this.quill.getContents(range.index, range.length)
let record = new Record({
id: currentID+"/"+createID(6),
contentType: "Extract",
content: selectedText
})
// Append selected text to database.
databaseManager.addRecord(record);
// Format the text visually with yellow overlay.
this.quill.formatText(range.index, range.length, {
'background': databaseManager.database.profile.extractHighlightColor
})
this.quill.setSelection(null)
this.expandAllParentsToID(record.id)
}
createClozeItem() {
let currentID = graphicsManager.activeInformationID
let range = this.quill.getSelection();
let contentDelta = this.quill.getContents();
let selectedText = this.quill.getText(range.index, range.length);
let currentRecord = databaseManager.getRecordByID(currentID)
if (currentRecord.contentType == "Cloze") {
currentID = currentID.split("/")
currentID.pop()
currentID = currentID.join("/")
}
// Create new record of selected text.
let record = new Record({
id: currentID+"/"+createID(6),
contentType: "Cloze",
content: contentDelta,
clozes: [new Cloze(selectedText, range.index, range.length)]
})
// Append selected text to database.
databaseManager.addRecord(record)
// Highlight the text visually.
this.quill.formatText(range.index, range.length, {
'background': databaseManager.database.profile.clozeHighlightColor
})
this.quill.setSelection(null)
this.expandAllParentsToID(record.id)
}
disableQuillInput() {
}
HighlightItemInSidebarByID(id) {
document.querySelectorAll(".active").forEach((node) => {
node.classList.remove("active")
})
const clickedRecord = databaseManager.getRecordByID(id)
const clickedDOM = document.querySelector('[data-id="'+id+'"]')
this.lastMenuItemClicked = clickedRecord.id
clickedDOM.classList.add("active")
clickedDOM.parentElement.querySelectorAll(":scope > div").forEach((item) => {
item.classList.toggle("visible")
})
}
onMenuItemClicked(event) {
document.querySelectorAll(".active").forEach((node) => {
node.classList.remove("active")
})
const r = databaseManager.getRecordByID(graphicsManager.activeInformationID)
const clickedRecord = databaseManager.getRecordByID(event.target.getAttribute("data-id"))
// Save current record if any to enable fast switching.
if (r !== null && r !== undefined) {
r.content = graphicsManager.quill.getContents()
}
if (clickedRecord.contentType == "Occlusion") {
//this.quill.setContents()
this.quill.enable(false)
this.lastMenuItemClicked = clickedRecord.id // ID = random + filename
this.toggleOcclusionLearningModal(clickedRecord.id)
event.target.classList.add("active");
} else if (clickedRecord.contentType == "Extract" || clickedRecord.contentType == "Cloze") {
this.quill.enable(true)
this.lastMenuItemClicked = clickedRecord.id
event.target.classList.add("active")
this.renderInputBox(clickedRecord)
} else if (clickedRecord.contentType == "Folder") {
this.lastMenuItemClicked = clickedRecord.id
event.target.classList.add("active")
}
event.target.parentElement.querySelectorAll(":scope > div").forEach((item) => {
item.classList.toggle("visible")
})
}
createFolderTree(tree, values) {
if (values.length == 0)
return tree
const part = values.shift()
tree[part] = this.createFolderTree(tree[part] || {}, values)
return tree
}
renderFolderTree(tree, depth = 0, path = []) {
return Object.keys(tree).map(key => {
let itemID = path.join("/")+"/"+key
if (itemID.charAt(0) == "/")
itemID = itemID.substring(1)
let record = databaseManager.getRecordByID(itemID)
if (record === undefined) {
databaseManager.createFolder(itemID)
if (IS_DEVELOPMENT)
console.log("Document created, not found: " + itemID)
}
let parent = document.createElement("div")
let child = document.createElement("p")
let image = document.createElement("img")
parent.classList.add("menuSubItem")
image.classList.add("threeIcon")
// databaseManager.removeItem(this.lastRightClickedItemID)
// this.renderFolders()
// this.expandAllParentsToID(this.lastRightClickedItemID)
// if (this.lastRightClickedItemID == this.activeInformationID) {
// graphicsManager.lastRightClickedItemID = null
// graphicsManager.activeInformationID = null
// graphicsManager.quill.setContents()
// graphicsManager.quill.enable(false)
if(record.contentType == "Occlusion" && databaseManager.database.profile.showImagesInSidebar == false) {
child.classList.add("hidden")
}
if(record.isFlagged) {
console.log(record.isFlagged)
if(!child.classList.contains("flagged"))
child.classList.add("flagged")
}
if(record.contentType == "Folder")
image.src = "assets/img/folderclose.svg"
else if(record.contentType == "Cloze")
image.src = "assets/img/cloze.svg"
else if(record.contentType == "Extract")
image.src = "assets/img/extract.svg"
else if(record.contentType == "Occlusion") {
image.src = "assets/img/occlusion2.svg"
}
child.setAttribute("onclick", "graphicsManager.onMenuItemClicked(event)")
child.setAttribute("ondragstart", "graphicsManager.onFolderDrag(event)")
child.setAttribute("ondragover", "graphicsManager.onFolderDragOver(event)")
child.setAttribute("ondrop", "graphicsManager.onItemDrop(event)")
child.setAttribute("data-id", itemID)
child.setAttribute("draggable", true)
child.appendChild(image)
child.innerHTML += key
parent.appendChild(child)
let children = this.renderFolderTree(tree[key], depth+1, [...path, key])
children.forEach(element => {
parent.appendChild(element)
})
return parent
})
}
renderFolders(){
let createdTree = databaseManager.database.items.reduce((tree, file) => this.createFolderTree(tree, file.id.split("/")), {})
let renderedTree = this.renderFolderTree(createdTree)
document.getElementById("content-structure").innerHTML = ""
renderedTree.forEach(element => {
document.getElementById("content-structure").appendChild(element)
})
// // Add filter to all images
// const images = document.querySelectorAll("img")
// images.forEach.call(images, function(image) {
// image.classList.remove("filter-day")
// image.classList.remove("filter-night")
// image.classList.remove("filter-homebrew")
// if(databaseManager.database.profile.theme !== "day")
// image.classList.add("filter-"+theme)
// });
this.sidebarUpdate()
}
collapseFolderByID(id) {
// Collapse and hide all childrens.
}
expandAllParentsToID(id) {
let path = id.split("/")
path.pop() // Remove last element
let AllParentsIDList = []
let current = ""
for (let i = 0; i < path.length; i++) {
current += "/" + path[i]
AllParentsIDList.push(current.substring(1))
}
//document.querySelector('[data-id="'+id+'"]').classList.add("active")
for (const r of AllParentsIDList) {
let parent = document.querySelector('[data-id="'+r+'"]').parentElement
parent.querySelectorAll(':scope > .menuSubItem').forEach((menuSubItem)=>{
menuSubItem.classList.add("visible")
})
}
}
expandItemByID(id = "Folder2") {
document.querySelectorAll(".active").forEach((node) => {
node.classList.remove("active")
})
const clickedRecord = databaseManager.getRecordByID(id)
const clickedDOM = document.querySelector('[data-id="'+id+'"]')
this.quill.setContents()
this.quill.enable(false)
this.lastMenuItemClicked = clickedRecord.id
clickedDOM.classList.add("active")
clickedDOM.parentElement.querySelectorAll(":scope > div").forEach((item) => {
item.classList.toggle("visible")
})
}
removeItem(){
if (this.lastRightClickedItemID != null && this.lastRightClickedItemID != -1) {
databaseManager.removeItem(this.lastRightClickedItemID)
this.renderFolders()
this.expandAllParentsToID(this.lastRightClickedItemID)
// Removed item which was selected
if (this.lastRightClickedItemID == this.activeInformationID) {
graphicsManager.lastRightClickedItemID = null
graphicsManager.activeInformationID = null
graphicsManager.quill.setContents()
graphicsManager.quill.enable(false)
}
} else {
this.renderFolders()
}
}
renameItem() {
// If null, create a root directory, else child directory.
const r = databaseManager.getRecordByID(graphicsManager.lastRightClickedItemID)
if (r != null) {
let itemName = r.id
if (r.id.includes("/")) {
let temp = r.id.split("/")
itemName = temp[temp.length-1]
}
console.log(itemName)
const newName = prompt("New name of item", itemName)
if(newName != null && newName != "") {
databaseManager.renameItem(r.id, newName)
this.renderFolders()
this.expandAllParentsToID(r.id)
} else {
graphicsManager.toggleAlert("Name of item can not be empty.", "warning")
}
}
}
createFolder() {
const r = databaseManager.getRecordByID(graphicsManager.lastRightClickedItemID)
if (r != null) {
if(["Folder", "Extract"].includes(r.contentType)) {
const input = prompt("Name of folder", "Name of folder here...")
if(input != null && input != "") {
const foldername = r.id + "/" + input
console.log("Creating folder ID: " + foldername)
if(databaseManager.itemExistByID(foldername) == false) {
databaseManager.createFolder(foldername)
this.renderFolders()
this.expandAllParentsToID(foldername)
} else {
this.toggleAlert("Folder name has already been used in same path. Try another name.", "warning")
}
}
} else {
this.toggleAlert("Can not create a folder, unknown error.", "warning")
}
} else {
// Create folder in root
const folderName = prompt("Name of folder", "Name of folder here...")
if(folderName != null && folderName != "") {
// Check if ID has been used before
if(databaseManager.database.items.filter(r => r.id == folderName).length == 0) {
databaseManager.createFolder(folderName)
this.renderFolders()
} else {
this.toggleAlert("Folder name has already been used in same path. Try another name.", "warning")
}
} else {
this.toggleAlert("Can not create a folder with empty name.", "warning")
}
}
}
createText() {
const r = databaseManager.getRecordByID(graphicsManager.lastRightClickedItemID)
if (r != null) {
if(["Folder", "Extract"].includes(r.contentType)) {
const path = r.id + "/" + createID(6)
databaseManager.createText(path);
this.renderFolders();
this.expandAllParentsToID(path)
} else {
this.toggleAlert("Can not create an text item in this type of object.", "warning")
}
} else {
// Clicked in root, outside of any item. Create text as root.
const path = createID(6)
databaseManager.createText(path);
this.renderFolders();
this.expandAllParentsToID(path)
}
}
// const r = databaseManager.getRecordByID(graphicsManager.lastRightClickedItemID)
// if (r != null) {
// if(["Folder", "Extract"].includes(r.contentType)) {
// const path = r.id + "/" + createID(6)
// databaseManager.createText(path);
// this.renderFolders();
// this.expandAllParentsToID(path)
// } else {
// this.toggleAlert("Can not create an text item in this type of object.")
// }
// } else {
// // Clicked in root, outside of any item. Create text as root.
// const path = createID(6)
// databaseManager.createText(path);
// this.renderFolders();
// this.expandAllParentsToID(path)
// }
spotlightOnKeyDown(e) {
// Search if enter are pressed.
if(e.key == "Enter") {
this.searchDatabaseByKeyword(e.target.value)
}
}
onSpotlightClick(event) {
//Activate item when clicked.
}
// searchDatabaseByKeyword(q) {
// const filter = `username:${databaseManager.id}`
// databaseManager.index.search(q, {filters: filter, facets: ['username'], attributesToHighlight: ["content"]}).then(({ hits }) => {
// document.getElementById("modalbox-spotlight-result").innerHTML = ""
// for (const hit of hits) {
// let child = document.createElement("div")
// let title = document.createElement("div")
// let content = document.createElement("div")
// child.classList.add("modalbox-spotlight-result-item")
// title.classList.add("modalbox-spotlight-result-item-title")
// content.classList.add("modalbox-spotlight-result-item-content")
// title.innerHTML = hit.objectID.split("-")[1]
// content.innerHTML = hit['_highlightResult'].content.value.substring(0, 100)
// child.setAttribute("onclick", "graphicsManager.algoliaResultOnClick(event, this)")
// child.setAttribute("data-id", hit.objectID.split("-")[1])
// child.appendChild(title)
// child.appendChild(content)
// document.getElementById("modalbox-spotlight-result").appendChild(child)
// }
// })
// }
algoliaResultOnClick(event, element) {
const clickedRecord = databaseManager.getRecordByID(element.getAttribute("data-id"))
const e = document.querySelector('[data-id="'+clickedRecord.id+'"]');
document.querySelectorAll(".active").forEach((node) => {
node.classList.remove("active")
})
if (clickedRecord.contentType == "Occlusion") {
this.quill.setContents()
this.quill.enable(false)
this.lastMenuItemClicked = clickedRecord.id // ID = random + filename
this.toggleOcclusionLearningModal(clickedRecord.id)
} else if (clickedRecord.contentType == "Extract" || clickedRecord.contentType == "Cloze") {
this.quill.enable(true)
this.renderInputBox(clickedRecord);
this.lastMenuItemClicked = clickedRecord.id
} else if (clickedRecord.contentType == "Folder") {
this.quill.setContents()
this.quill.enable(false)
this.lastMenuItemClicked = clickedRecord.id
}
e.classList.add("active");
this.expandAllParentsToID(clickedRecord.id)
e.parentElement.querySelectorAll(":scope > div").forEach((item) => {
item.classList.toggle("visible")
})
}
async handleDroppedItem(event) {
handleDocumentImport(event)
}
async quillOnDrop(event) {
event.preventDefault();
this.handleDroppedItem(event)
}
quillOnKeyDown(event, element) {
// event.preventDefault()
// Get all shortcuts for quill editor events.
let clozeShortcut = databaseManager.database.profile.shortcuts.find(r => r.event == "input-create-cloze")
let extractShortcut = databaseManager.database.profile.shortcuts.find(r => r.event == "input-create-extract")
let summarizeShortcut = databaseManager.database.profile.shortcuts.find(r => r.event == "input-text-summarize")
//let flagShortcut = databaseManager.database.profile.shortcuts.find(r => r.event == "input-flag-item")
// Create cloze when pressed.
if (event.keyCode == clozeShortcut.keyCode &&
(event.ctrlKey == clozeShortcut.ctrlKey ||
event.metaKey == clozeShortcut.metaKey) &&
event.altKey == clozeShortcut.altKey) {
graphicsManager.createClozeItem()
} else if (event.keyCode == extractShortcut.keyCode &&
(event.ctrlKey == extractShortcut.ctrlKey ||
event.metaKey == extractShortcut.metaKey) &&
event.altKey == extractShortcut.altKey) {
graphicsManager.createTextExtract()
} else if (event.keyCode == summarizeShortcut.keyCode &&
(event.ctrlKey == summarizeShortcut.ctrlKey ||
event.metaKey == summarizeShortcut.metaKey) &&
event.altKey == summarizeShortcut.altKey) {
let range = graphicsManager.quill.getSelection();
if (range) {
if(range.length > 0) {
const selectedText = graphicsManager.quill.getText(range.index, range.length)
const summarizedText = dictionaryManager.getTextSummarization(selectedText).then((text) => {
let currentID = graphicsManager.activeInformationID
let newID = currentID + "/" + createID(6)
let record = new Record({
id: newID,
contentType: "Extract",
content: {
"ops": [{"insert": text}]
}
})
databaseManager.addRecord(record);
graphicsManager.quill.setSelection(null)
graphicsManager.expandAllParentsToID(newID)
})
}
}
}
}
saveLocalDatabase() {
let d = new Date()
let currentHours = d.getHours();
let currentMinutes = d.getMinutes();
currentHours = ("0" + currentHours).slice(-2);
currentMinutes = ("0" + currentMinutes).slice(-2);
document.getElementById("sidebar-last-saved").innerHTML = `${currentHours}:${currentMinutes}`
}
async getFileFromURL(image) {
const response = await fetch(image)
const blob = await response.blob()
const file = new File([blob], createID()+".jpg", {type: blob.type})
return file
}
async onImageSidebarClicked(e) {
const file = await this.getFileFromURL(e.target.src)
const filename = await databaseManager.uploadFile(file)
this.lastActiveImageOcclusionURL = filename
let image = new Image()
image.crossOrigin = "anonymous"
image.src = BASE_URL + filename
image.onload = () => this.updateOcclusionCreateCanvas(image)
}
toggleOcclusionCreateModal() {
// Check if visisble, then make invisible.
const modalElement = document.getElementById("modalbox-occlusion-create")
if (modalElement.classList.contains("visible")) {
document.getElementById("modalbox-occlusion-create").classList.add("hidden")
document.getElementById("modalbox-occlusion-create").classList.remove("visible")
document.getElementById("overlay").classList.add("hidden")
document.getElementById("overlay").classList.remove("visible")
} else {
document.getElementById("modalbox-occlusion-create").classList.remove("hidden")
document.getElementById("modalbox-occlusion-create").classList.add("visible")
document.getElementById("overlay").classList.remove("hidden")
document.getElementById("overlay").classList.add("visible")
}
}
updateOcclusionCreateCanvas(imageCreate, toggle = true) {
if(toggle)
this.toggleOcclusionCreateModal()
let canvasCreate = document.getElementById("modalbox-occlusion-create-canvas")
let ctxLearning = canvasCreate.getContext("2d")
if(toggle)
ctxLearning.clearRect(0, 0, 2000, 2000);
var scale = Math.min(canvasCreate.width / imageCreate.width, canvasCreate.height / imageCreate.height);
var x = (canvasCreate.width / 2) - (imageCreate.width / 2) * scale;
var y = (canvasCreate.height / 2) - (imageCreate.height / 2) * scale;
if(toggle)
ctxLearning.drawImage(imageCreate, x, y, imageCreate.width * scale, imageCreate.height * scale);
}
updateOcclusionLearnCanvas(id, showClozes = true) {
let record = databaseManager.getRecordByID(id)
let image = new Image()
image.src = BASE_URL + record.url
image.onload = () => {
let canvas = document.getElementById("modalbox-occlusion-learning-canvas")
let ctx = canvas.getContext("2d")
let scale = Math.min(canvas.width / image.width, canvas.height / image.height)
let x = (canvas.width / 2) - (image.width / 2) * scale
let y = (canvas.height / 2) - (image.height / 2) * scale
ctx.fillStyle = '#CCCC00';
ctx.clearRect(0, 0, 2000, 2000)
ctx.drawImage(image, x, y, image.width * scale, image.height * scale);
if(showClozes) {
record.occlusions.forEach(function (occlusion) {
ctx.fillRect(occlusion.x, occlusion.y, occlusion.width, occlusion.height)
})
}
}
}
toggleOcclusionLearningModal(id, showClozes = true) {
this.updateOcclusionLearnCanvas(id, showClozes);
// Check if visisble, then make invisible.
const modalElement = document.getElementById("modalbox-occlusion-learning")
if (modalElement.classList.contains("visible")) {
document.getElementById("modalbox-occlusion-learning").classList.add("hidden")
document.getElementById("modalbox-occlusion-learning").classList.remove("visible")
document.getElementById("overlay").classList.add("hidden")
document.getElementById("overlay").classList.remove("visible")
} else {
document.getElementById("modalbox-occlusion-learning").classList.remove("hidden")
document.getElementById("modalbox-occlusion-learning").classList.add("visible")
document.getElementById("overlay").classList.remove("hidden")
document.getElementById("overlay").classList.add("visible")
}
}
toggleInformationModal() {
// Already visible, hide modalbox and overlay
if (document.getElementById("modalbox-information").classList.contains("visible")) {
document.getElementById("overlay").classList.remove("visible")
document.getElementById("overlay").classList.add("hidden")
document.getElementById("modalbox-information").classList.add("hidden")
document.getElementById("modalbox-information").classList.remove("visible")
} else {
document.getElementById("overlay").classList.add("visible")
document.getElementById("overlay").classList.remove("hidden")
document.getElementById("modalbox-information").classList.remove("hidden")
document.getElementById("modalbox-information").classList.add("visible")
}
}
toggleLearningMode() {
const engageButtonElement = document.getElementById("learning-button")
// Not in learning mode, enable.
if ( engageButtonElement.classList.contains("start-learning-button") ) {
engageButtonElement.classList.remove("start-learning-button")
engageButtonElement.classList.add("stop-learning-button")
engageButtonElement.innerHTML = "Stop learning!"
graphicsManager.toggleAlert("Learning mode started. Eve will show you the next item when the item has been graded.")
if(mobileCheck()) {
document.getElementById("sidebar").classList.remove("visible")
document.getElementById("sidebar").classList.add("hidden")
document.getElementById("modalbox-learning-menu").classList.remove("hidden")
document.getElementById("content-input").classList.add("learning-mode")
}
} else {
engageButtonElement.classList.remove("stop-learning-button")
engageButtonElement.classList.add("start-learning-button")
engageButtonElement.innerHTML = "Engage!"
if(mobileCheck()) {
document.getElementById("sidebar").classList.add("visible")
document.getElementById("sidebar").classList.remove("hidden")
document.getElementById("modalbox-learning-menu").classList.add("hidden")
document.getElementById("content-input").classList.remove("learning-mode")
}
}
}
toggleModalFullImage(e) {
const modalbox = document.getElementById("modalbox-image")
const image = document.getElementById("modalbox-image-content")
if(e.type == "mouseenter") {
image.src = e.target.src
const xPos = e.pageX - 600 + "px";
const yPos = e.pageY - 700 + "px";
modalbox.style.top = yPos;
modalbox.style.left = xPos;
modalbox.classList.add("visible")
modalbox.classList.remove("hidden")
} else if(e.type == "mouseleave") {
modalbox.classList.remove("visible")
modalbox.classList.add("hidden")
}
}
async onWikipediaItemClicked(event) {
await navigator.clipboard.writeText(event.target.getAttribute("data")).then(function() {
graphicsManager.toggleAlert("Article text sent to clipboard!")
}, function(err) {
graphicsManager.toggleAlert(err)
})
}
toggleItemSummary(event) {
const modalbox = document.getElementById("modalbox-summary")
if(event.type == "mouseenter") {
modalbox.innerHTML = event.target.getAttribute("data")
const xPos = event.pageX - 325 + "px";
const yPos = event.pageY + 400 + "px";
modalbox.style.top = yPos;
modalbox.style.left = xPos;
modalbox.classList.add("visible")
modalbox.classList.remove("hidden")
} else if (event.type == "mouseleave") {
modalbox.classList.remove("visible")
modalbox.classList.add("hidden")
}
}
dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
// async embedMaskedImage() {
// // 0. Get canvas from modalbox, check first if in occlusion mode
// var canvas = document.getElementById("modalbox-occlusion-create-canvas")
// var dataURL = canvas.toDataURL();
// var file = this.dataURLtoFile(dataURL, 'test.txt');
// var filename = await databaseManager.uploadFile(file)
// // Embed in the editor
// this.quill.insertEmbed(0, "image", "${BASE_URL}aaPg3ztScyDkfx6A.png");
// // 2. Embed it in the editor with help of API (do not close modalbox).
// }
} |
JavaScript | class LearningManager{
constructor(){
this.isInLearningMode = false
this.stepSize = -1
this.recallClozeList = []
}
toggleExtractsInLearning() {
graphicsManager.toggleExtractsInLearning()
if (databaseManager.database.profile.showExtractsInLearningMode)
databaseManager.database.profile.showExtractsInLearningMode = false
else
databaseManager.database.profile.showExtractsInLearningMode = true
}
toggleOcclusionsInLearning() {
graphicsManager.toggleOcclusionsInLearning()
if (databaseManager.database.profile.showOcclusionsInLearningMode)
databaseManager.database.profile.showOcclusionsInLearningMode = false
else
databaseManager.database.profile.showOcclusionsInLearningMode = true
}
toggleClozesInLearning() {
graphicsManager.toggleClozesInLearning()
if (databaseManager.database.profile.showClozesInLearningMode)
databaseManager.database.profile.showClozesInLearningMode = false
else
databaseManager.database.profile.showClozesInLearningMode = true
}
sm2(grade, repetition, efactor, interval) {
let nextInterval = 0;
let nextRepetition = 0;
let nextEfactor = 0;
if (grade >= 3) {
if (repetition === 0) {
nextInterval = 1;
nextRepetition = 1;
} else if (repetition === 1) {
nextInterval = 6;
nextRepetition = 2;
} else {
nextInterval = Math.round(interval * efactor);
nextRepetition = repetition + 1;
}
} else {
nextInterval = 1;
nextRepetition = 0;
}
nextEfactor = efactor + (0.1 - (5 - grade) * (0.08 + (5 - grade) * 0.02));
if (nextEfactor < 1.3) nextEfactor = 1.3;
return {
interval: nextInterval,
repetition: nextRepetition,
efactor: nextEfactor,
dueDate: new Date().addDays(nextInterval).toJSON()
};
}
// getAverageEfactor() {
// let items = {}
// const l = databaseManager.database.items.filter(r => r.totalRepetitionCount > 0)
// for(const item of l) {
// if (!(item.totalRepetitionCount in items)) {
// items.push({
// repetitions: item.totalRepetitionCount,
// count: 1,
// totalEfactor: item.efactor
// })
// } else {
// }
// items[item.totalRepetitionCount].count += 1
// items[item.totalRepetitionCount].totalEfactor = item.efactor
// }
// }
// gradeRecordMobile(g) {
// const r = databaseManager.getRecordByID(graphicsManager.activeInformationID)
// if(learningManager.isInLearningMode) {
// if(r.contentType == "Occlusion")
// graphicsManager.toggleOcclusionLearningModal(r.id)
// learningManager.gradeRecord(g, r);
// learningManager.engage()
// } else {
// graphicsManager.toggleAlert("Please enter learning mode before grading.")
// }
// }
// Grade the Cloze or image occlusion item.
gradeRecord(grade, record){
// Get the updated factors from the cloze.
let updatedFactors = this.sm2(grade, record.repetition, record.efactor, record.interval)
// Update the record or image occlusion record in the database with updatedFactors.
record.repetition = updatedFactors.repetition;
record.efactor = updatedFactors.efactor;
record.interval = updatedFactors.interval;
record.dueDate = updatedFactors.dueDate;
}
toggleLearning() {
graphicsManager.toggleLearningMode()
if(this.isInLearningMode) {
this.isInLearningMode = false
const c = databaseManager.getRecordByID(graphicsManager.activeInformationID)
graphicsManager.quill.setContents(c.content)
if(mobileCheck()) {
document.getElementById("sidebar").classList.add("visible")
document.getElementById("sidebar").classList.remove("hidden")
document.getElementById("modalbox-learning-menu").classList.add("hidden")
document.getElementById("wrapper").classList.remove("wrapper-learning-mode")
}
} else {
this.isInLearningMode = true
if(mobileCheck()) {
document.getElementById("sidebar").classList.add("hidden")
document.getElementById("sidebar").classList.remove("visible")
document.getElementById("modalbox-learning-menu").classList.remove("hidden")
document.getElementById("wrapper").classList.add("wrapper-learning-mode")
document.getElementById("learning-progressbar-progress").innerHTML = "Due today: " + databaseManager.getDueCount() + "(" + databaseManager.getDueCountAll() + ")"
document.getElementById("learning-progressbar-progress").style.width = "100%"
learningManager.stepSize = 100 / databaseManager.getDueCount()
}
this.engage()
}
}
updateStatisticsItemCount() {
let today = databaseManager.getDateToday()
if( !(today in databaseManager.database.profile.statistics) )
databaseManager.database.profile.statistics[today] = {}
if(databaseManager.database.profile.statistics[today].newItemsCount == undefined)
databaseManager.database.profile.statistics[today].newItemsCount = 1
else
databaseManager.database.profile.statistics[today].newItemsCount += 1
}
updateStatistics() {
let today = databaseManager.getDateToday()
if( !(today in databaseManager.database.profile.statistics) )
databaseManager.database.profile.statistics[today] = {}
if(databaseManager.database.profile.statistics[today].reviewsCount == undefined)
databaseManager.database.profile.statistics[today].reviewsCount = 1
else
databaseManager.database.profile.statistics[today].reviewsCount += 1
console.log(databaseManager.database.profile.statistics)
}
engage() {
let possibleValues = []
let dueCount = 0
graphicsManager.sidebarUpdate()
if (databaseManager.database.profile.showExtractsInLearningMode) {
possibleValues.push("Extract")
dueCount += databaseManager.getDueExtractCount()
}
if (databaseManager.database.profile.showOcclusionsInLearningMode) {
possibleValues.push("Occlusion")
dueCount += databaseManager.getDueOcclusionCount()
}
if (databaseManager.database.profile.showClozesInLearningMode) {
possibleValues.push("Cloze")
dueCount += databaseManager.getDueClozeCount()
}
if (dueCount == 0 && databaseManager.getDueCount() == 0) {
graphicsManager.toggleAlert("Well done. All repetitions done for today!")
learningManager.toggleLearning()
return
} else if(dueCount == 0 && databaseManager.getDueCountAll() > 0) {
graphicsManager.toggleAlert("Enable Clozes, Occlusion and Extract for learning mode to display all due items.")
learningManager.toggleLearning()
return
}
let r = possibleValues[Math.floor(Math.random() * possibleValues.length)]
if(learningManager.recallClozeList.length > 2 && mobileCheck() == false) {
databaseManager.createFreeRecallDocument(learningManager.recallClozeList)
graphicsManager.toggleAlert("Write everything you know about the clozes then grade the knowledge.")
} else {
if(r == "Occlusion") {
let occlusion = databaseManager.getDueOcclusionRecord()
if(occlusion !== undefined) {
occlusion.repetition += 1
occlusion.totalRepetitionCount += 1
this.updateStatistics()
graphicsManager.activeInformationID = occlusion.id
graphicsManager.toggleOcclusionLearningModal(occlusion.id)
graphicsManager.expandAllParentsToID(occlusion.id)
graphicsManager.HighlightItemInSidebarByID(occlusion.id)
} else {
this.engage()
}
} else if (r == "Cloze") {
let cloze = databaseManager.getDueClozeRecord()
if(cloze !== undefined) {
cloze.repetition += 1
cloze.totalRepetitionCount += 1
this.updateStatistics()
graphicsManager.renderInputBox(cloze)
graphicsManager.expandAllParentsToID(cloze.id)
graphicsManager.HighlightItemInSidebarByID(cloze.id)
let tempObj = cloze.content.ops
Object.keys(tempObj).map(function(key, index) {
//console.log(tempObj[key].insert)
if (tempObj[key].insert.trim().includes("!:Q")) {
// console.log("Valid query!")
// console.log(tempObj[key])
learningManager.recallClozeList.push(tempObj[key])
//console.log(learningManager.recallClozeList)
} else {
console.log("Does not contains !:Q")
}
});
// Check if cloze correctly formatted for free recall.
// if (cloze.content.contains("!:Q")) {
// graphicsManager.includes("Item is free recall compatible.")
// learningManager.recallClozeIDList.push(cloze.id)
// }
} else {
this.engage()
}
} else if (r == "Extract") {
let extract = databaseManager.getDueExtractRecord()
if(extract !== undefined) {
extract.repetition += 1
extract.totalRepetitionCount += 1
this.updateStatistics()
graphicsManager.renderInputBox(extract)
graphicsManager.expandAllParentsToID(extract.id)
graphicsManager.HighlightItemInSidebarByID(extract.id)
} else {
this.engage()
}
}
}
}
} |
JavaScript | class Flash extends React.Component {
static propTypes = {
/**
* Custom className
*
* @property className
* @type {String}
*/
className: PropTypes.string,
/**
* A custom close event handler
*
* @property onDismiss
* @type {Function}
*/
onDismiss: PropTypes.func.isRequired,
/**
* Sets the open state of the flash.
*
* @property open
* @type {Boolean}
* @default false
*/
open: PropTypes.bool.isRequired,
/**
* Type of notification.
* (see the 'iconColorSets' for possible values)
*
* @property as
* @type {String}
* @default 'success'
*/
as: PropTypes.string,
/**
* Contents of message.
*
* @property message
* @type {String|Object|Array}
*/
message: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
PropTypes.array
]).isRequired,
/**
* Time for flash to remain on screen
*
* @property timeout
* @type {Number} in milliseconds
*/
timeout: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
}
static defaultProps = {
as: 'success',
className: '',
timeout: 0
}
state = {
/**
* Keeps track on the open state of each dialog
*
* @property dialogs
* @type {Object}
*/
dialogs: {}
}
/**
* Resets the dialog open states if flash is opened/closed.
*
* @method componentWillReceiveProps
* @return(Void)
*/
componentWillReceiveProps(prevProps) {
if (prevProps.open !== this.props.open) {
this.setState({ dialogs: {} });
}
}
/**
* Determines if the component should be updated or not. Required for this component
* as it determines if the timeout should be reset or not.
*
* @method shouldComponentUpdate
* @return {Boolean}
*/
shouldComponentUpdate(nextProps, nextState) {
return shouldComponentUpdate(this, nextProps, nextState);
}
/**
* Conditionally triggers close action after flash displayed.
*
* @method componentDidUpdate
* @return(Void)
*/
componentDidUpdate() {
// reset dialogs to render
this.dialogs = [];
this.startTimeout();
}
/**
* Keeps track of additional dialogs to render for "more info" links
*
* @property dialogs
* @type {Array}
*/
dialogs = []
/**
* A timeout for when a flash should auto-dismiss
*
* @property timeout
* @type {Timer}
*/
timeout = null
/**
* Starts the timer to auto dismiss flash messages.
*
* @method startTimeout
* @return(Void)
*/
startTimeout = () => {
this.stopTimeout();
if (this.shouldStartTimeout()) {
this.timeout = setTimeout(() => {
this.props.onDismiss();
}, this.props.timeout);
}
}
/**
* Determines if the timeout should be started.
*
* @method shouldStartTimeout
* @return {Boolean}
*/
shouldStartTimeout = () => {
if (!this.props.timeout || !this.props.open) { return false; }
let shouldStartTimeout = true;
for (const key in this.state.dialogs) {
if (this.state.dialogs[key]) {
shouldStartTimeout = false;
}
}
return shouldStartTimeout;
}
/**
* Stops the timer to auto dismiss flash messages.
*
* @method stopTimeout
* @return(Void)
*/
stopTimeout = () => {
clearTimeout(this.timeout);
}
/**
* Opens/closes the dialog for the given key.
*
* @method toggleDialog
* @param {String} key
* @param {Object} ev
* @return(Void)
*/
toggleDialog = (key) => {
return (
(ev) => {
if (ev) { ev.preventDefault(); }
const state = this.state.dialogs[key];
// open/close the dialog
this.setState({ dialogs: { [key]: !state } });
// start/stop the timer if the dialog opens or closes
if (state) {
this.startTimeout();
} else {
this.stopTimeout();
}
}
);
}
/**
* Given a description, format it accordingly.
*
* @method toggleDialog
* @param {String} description
* @return {HTML}
*/
formatDescription = (description) => {
const object = isObject(description),
array = isArray(description);
this.dialogs = [];
if (array || object) {
const items = [];
// iterate through the object or array
forEach(description, (value, key) => {
let itemValue;
// pass the value through the find more parser
const text = this.findMore(value);
if (!array && !/(^base|\.base)$/.test(key)) {
// if object, apply key to each item
itemValue = <span>{ key }: { text }</span>;
} else {
// otherwise just set value
itemValue = text;
}
// add item to list
items.push(<li key={ key }>{ itemValue }</li>);
});
return <ul>{ items }</ul>;
}
// if just a string, pass it through the find more parser
return this.findMore(description);
}
/**
* Splits the string and sets additional content inside a dialog.
*
* @method findMore
* @param {String} text
* @return {HTML}
*/
findMore = (text) => {
let value = text;
if (typeof text !== 'string') { return value; }
// detect any instances of "::more::" in the text
const parts = text.split('::more::');
if (parts.length > 1) {
const title = parts[0].trim(),
desc = parts[1].trim(),
info = I18n.t('notifications.more_info', { defaultValue: 'More Information' });
// create dialog for additional content
this.dialogs.push(
<Alert
data-element='info-dialog'
key={ title }
title={ title }
open={ this.state.dialogs[title] || false }
onCancel={ this.toggleDialog(title) }
>
{ desc }
</Alert>
);
// create text for item
value = (
<span>
{ title }
<Link
onClick={ this.toggleDialog(title) }
className='carbon-flash__link'
data-element='more-info'
>
{ info }
</Link>
</span>
);
}
return value;
}
/**
* Returns the icon to display depending on type
*
* @method iconType
* @return {String}
*/
get iconType() {
let icon;
switch (this.props.as) {
case 'success':
icon = 'tick';
break;
default:
icon = this.props.as;
break;
}
return icon;
}
/**
* Parses the message object to get the appropriate description
*
* @method description
* @return {String}
*/
get description() {
const message = this.props.message;
if (isObject(message) && message.description) {
// if defined, return description
return message.description;
}
// otherwise, just return itself
return message;
}
/**
* Returns the computed HTML for the flash.
*
* @method flashHTML
* @return {Object} JSX for flash
*/
get flashHTML() {
const contents = [];
// add icon
contents.push(<Icon className='carbon-flash__icon' type={ this.iconType } key='icon' />);
// add message content
contents.push(
<div className='carbon-flash__message' key='message' data-element='message'>
{ this.formatDescription(this.description) }
</div>
);
// if auto-dismiss is not enabled, add a close icon
if (!this.props.timeout) {
contents.push(
<Icon
className='carbon-flash__close'
data-element='close'
key='close'
onClick={ this.props.onDismiss }
type='close'
/>
);
}
return (
<div className='carbon-flash__content'>
{ contents }
</div>
);
}
/**
* Returns the computed HTML for the slider.
*
* @method flashHTML
* @return {Object} JSX for flash
*/
get sliderHTML() {
return (
<div className='carbon-flash__slider' key='slider' />
);
}
/**
* Returns the classes for the component.
*
* @method classes
* @return {String}
*/
get classes() {
return classNames(
'carbon-flash',
this.props.className,
`carbon-flash--${this.props.as}`
);
}
/**
* @method render
* @return {Object} JSX
*/
render() {
let flashHTML, sliderHTML;
if (this.props.open) {
flashHTML = this.flashHTML;
sliderHTML = this.sliderHTML;
}
return (
<div { ...tagComponent('flash', this.props) }>
<div className={ this.classes }>
<CSSTransitionGroup
transitionName='carbon-flash__slider'
transitionEnterTimeout={ 600 }
transitionLeaveTimeout={ 600 }
>
{ sliderHTML }
<CSSTransitionGroup
transitionName='carbon-flash__content'
transitionEnterTimeout={ 800 }
transitionLeaveTimeout={ 500 }
>
{ flashHTML }
</CSSTransitionGroup>
</CSSTransitionGroup>
</div>
{ this.dialogs }
</div>
);
}
} |
JavaScript | class FsFile extends FsUnit {
constructor(name, content) {
super(name, FS_UNIT_TYPE.FILE);
this._checkContent(content);
this._content = content;
this._setSize(content);
this._parent = undefined;
}
/**
* Set file content. recalculate size
*
* @param {String} content
*/
update(content) {
this._checkContent(content);
this._content = content;
this._setSize(content);
}
/**
* Check is content is string
*
* @param {String} content
*/
_checkContent(content) {
if (typeof content !== 'string') {
throw new Error('Invalid file content');
}
}
/**
* Set content byte size
*
* @param {String} content
*/
_setSize(content) {
if (Blob) {
this._size = new Blob([content]).size;
} else {
this._size = Buffer.byteLength(content, 'utf-8');
}
}
} |
JavaScript | class Crostini {
/**
* Initialize enabled settings.
* Must be done after loadTimeData is available.
*/
initEnabled() {}
/**
* Initialize Volume Manager.
* @param {!VolumeManager} volumeManager
*/
initVolumeManager(volumeManager) {}
/**
* Register for any shared path changes.
*/
listen() {}
/**
* Set whether the specified VM is enabled.
* @param {string} vmName
* @param {boolean} enabled
*/
setEnabled(vmName, enabled) {}
/**
* Returns true if the specified VM is enabled.
* @param {string} vmName
* @return {boolean}
*/
isEnabled(vmName) {}
/**
* Registers an entry as a shared path for the specified VM.
* @param {string} vmName
* @param {!Entry} entry
*/
registerSharedPath(vmName, entry) {}
/**
* Unregisters entry as a shared path from the specified VM.
* @param {string} vmName
* @param {!Entry} entry
*/
unregisterSharedPath(vmName, entry) {}
/**
* Returns true if entry is shared with the specified VM.
* @param {string} vmName
* @param {!Entry} entry
* @return {boolean} True if path is shared either by a direct
* share or from one of its ancestor directories.
*/
isPathShared(vmName, entry) {}
/**
* Returns true if entry can be shared with the specified VM.
* @param {string} vmName
* @param {!Entry} entry
* @param {boolean} persist If path is to be persisted.
*/
canSharePath(vmName, entry, persist) {}
} |
JavaScript | class DefaultEnabledColumnResizeExample {
constructor() {
this.displayedColumns = ['position', 'name', 'weight', 'symbol'];
this.dataSource = ELEMENT_DATA;
}
} |
JavaScript | class WorkerDispatcher extends CommonDispatcher{
constructor(javapoly){
super(javapoly);
this.idCount = 0;
}
initDoppioManager(javapoly) {
const options = javapoly.options;
importScripts(options.browserfsLibUrl + 'browserfs.min.js');
importScripts(options.doppioLibUrl + 'doppio.js');
return Promise.resolve(new DoppioManager(javapoly));
}
// Called by the worker when loading scripts
postMessage(messageType, priority, data, callback) {
const id = this.idCount++;
this.handleIncomingMessage("localMessage" + id, priority, messageType, data, callback);
}
// Handle message data coming from the web-worker message bridge
handleWorkerMessage(data, callback) {
const id = data.messageId;
if (!callback) {
callback = (returnValue) => {
global.self.postMessage({
javapoly:{
messageId: id, messageType:data.messageType, returnValue:returnValue
}});
};
}
this.handleIncomingMessage(id, data.priority, data.messageType, data.data, callback);
}
} |
JavaScript | class AddButton extends React.Component {
handleClick = () => {
this.props.handleClick()
}
render() {
return (
<div classname = "cardStyle" style = {{height: '50%', maxWidth: '5%', margin: '0.8vh 4vw 1vh 0.1vw'}}>
<Button onClick={this.handleClick} size = 'small'>
<img src={AddBtn} width="22vw" height="50%" alt="Add"/>
</Button>
</div>
);
}
} |
JavaScript | class SkylinkState {
/**
* @property {SkylinkApiResponse} skylinkApiResponse
*/
constructor(initOptions) {
/**
* Stores the api response.
* @name apiResponse
* @type {SkylinkApiResponse}
* @since 2.0.0
* @private
*/
this.apiResponse = {};
/**
* Stores the list of Peer DataChannel connections.
* @name dataChannels
* @type {Object}
* @property {String} peerId - The list of DataChannels associated with Peer ID.
* @property {RTCDataChannel} channelLabel - The DataChannel connection.
* The property name <code>"main"</code> is reserved for messaging Datachannel type.
* @since 0.2.0
* @private
*/
this.dataChannels = {};
/**
* Stores the list of buffered ICE candidates that is received before
* remote session description is received and set.
* @name peerCandidatesQueue
* @property {Array} <#peerId> The list of the Peer connection buffered ICE candidates received.
* @property {RTCIceCandidate} <#peerId>.<#index> The Peer connection buffered ICE candidate received.
* @type JSON
* @since 0.5.1
* @private
*/
this.peerCandidatesQueue = {};
/**
* Stores the list of ICE candidates received before signaling end.
* @name peerEndOfCandidatesCounter
* @type JSON
* @since 0.6.16
* @private
*/
this.peerEndOfCandidatesCounter = {};
/**
* Stores the list of Peer connection ICE candidates.
* @name gatheredCandidates
* @property {JSON} <#peerId> The list of the Peer connection ICE candidates.
* @property {JSON} <#peerId>.sending The list of the Peer connection ICE candidates sent.
* @property {JSON} <#peerId>.receiving The list of the Peer connection ICE candidates received.
* @type JSON
* @since 0.6.14
* @private
*/
this.gatheredCandidates = {};
/**
* Stores the window number of Peer connection retries that would increase the wait-for-response timeout
* for the Peer connection health timer.
* @name retryCounters
* @type JSON
* @since 0.5.10
* @private
*/
this.retryCounters = {};
/**
* Stores the list of the Peer connections.
* @name peerConnections
* @property {RTCPeerConnection} <#peerId> The Peer connection.
* @type JSON
* @since 0.1.0
* @private
*/
this.peerConnections = {};
/**
* Stores the list of the Peer connections stats.
* @name peerStats
* @property {JSON} <#peerId> The Peer connection stats.
* @type JSON
* @since 0.6.16
* @private
*/
this.peerStats = {};
/**
* Stores the list of Peers session information.
* @name peerInformations
* @property {JSON} <#peerId> The Peer session information.
* @property {JSON|string} <#peerId>.userData The Peer custom data.
* @property {JSON} <#peerId>.settings The Peer streaming information.
* @property {JSON} <#peerId>.mediaStatus The Peer streaming media status.
* @property {JSON} <#peerId>.agent The Peer agent information.
* @type JSON
* @since 0.3.0
* @private
*/
this.peerInformations = {};
/**
* Stores the Signaling user credentials from the API response required for connecting to the Signaling server.
* @name user
* @property {String} uid The API result "username".
* @property {String} token The API result "userCred".
* @property {String} timeStamp The API result "timeStamp".
* @property {String} sid The Signaling server receive user Peer ID.
* @type SkylinkUser
* @since 0.5.6
* @private
*/
this.user = initOptions.user;
/**
* Stores the User connection priority weight received from signalling server inRoom message.
* In case of crossing offers, the offer that contains the lower weight will be dropped.
* @name peerPriorityWeight
* @type number
* @since 0.5.0
* @private
*/
this.peerPriorityWeight = 0;
/**
* Stores the flag that indicates if "isPrivileged" is enabled.
* If enabled, the User has Privileged features which has the ability to retrieve the list of
* Peers in the same App space with <code>getPeers()</code> method
* and introduce Peers to each other with <code>introducePeer</code> method.
* @name isPrivileged
* @type boolean
* @default false
* @since 0.6.1
* @private
*/
this.isPrivileged = initOptions.isPrivileged;
/**
* Stores the current socket connection information.
* @name socketSession
* @type {socketSession}
* @since 0.6.13
* @private
*/
this.socketSession = {};
/**
* Stores the queued socket messages.
* This is to prevent too many sent over less than a second interval that might cause DROPPED messages
* or jams to the Signaling connection.
* @name socketMessageQueue
* @type Array
* @since 0.5.8
* @private
*/
this.socketMessageQueue = [];
/**
* Stores the flag that indicates if socket connection to the Signaling has opened.
* @name channelOpen
* @type boolean
* @since 0.5.2
* @private
*/
this.channelOpen = false;
/**
* Stores the Signaling server url.
* @name signalingServer
* @type string
* @since 0.5.2
* @private
*/
this.socketServer = initOptions.socketServer;
/**
* Stores the Signaling server protocol.
* @name signalingServerProtocol
* @type string
* @since 0.5.4
* @private
*/
this.signalingServerProtocol = initOptions.forceSSL ? 'https:' : window.location.protocol;
/**
* Stores the value if ICE restart is supported.
* @name enableIceRestart
* @type boolean
* @since 0.6.16
* @private
*/
this.enableIceRestart = false;
/**
* Stores the flag if MCU environment is enabled.
* @name hasMCU
* @type boolean
* @since 0.5.4
* @private
*/
this.hasMCU = initOptions.hasMCU;
/**
* Stores the Room credentials information for <code>joinRoom()</code>.
* @name room
* @property {String} id The "rid" for <code>joinRoom()</code>.
* @property {String} token The "roomCred" for <code>joinRoom()</code>.
* @property {String} startDateTime The "start" for <code>joinRoom()</code>.
* @property {String} duration The "len" for <code>joinRoom()</code>.
* @property {String} connection The RTCPeerConnection constraints and configuration. This is not used in the SDK
* except for the "mediaConstraints" property that sets the default <code>getUserMedia()</code> settings.
* @type SkylinkRoom
* @since 0.5.2
* @private
*/
this.room = initOptions.room;
/**
* Stores the list of Peer messages timestamp.
* @name peerMessagesStamps
* @type JSON
* @since 0.6.15
* @private
*/
this.peerMessagesStamps = {};
/**
* Stores all the Stream required muted settings.
* @name streamsMutedSettings
* @type JSON
* @since 0.6.15
* @private
*/
this.streamsMutedSettings = {};
/**
* Stores all the Stream sending maximum bandwidth settings.
* @name streamsBandwidthSettings
* @type JSON
* @since 0.6.15
* @private
*/
this.streamsBandwidthSettings = {
bAS: {},
};
/**
* Stores the list of recordings.
* @name recordings
* @type JSON
* @since 0.6.16
* @private
*/
this.recordings = {};
/**
* Stores the current active recording session ID.
* There can only be 1 recording session at a time in a Room
* @name currentRecordingId
* @type JSON
* @since 0.6.16
* @private
*/
this.currentRecordingId = false;
/**
* Stores the recording session timeout to ensure 4 seconds has been recorded.
* @name recordingStartInterval
* @type number
* @since 0.6.16
* @private
*/
this.recordingStartInterval = null;
/**
* Stores the currently supported codecs.
* @name currentCodecSupport
* @type JSON
* @since 0.6.18
* @private
*/
this.currentCodecSupport = null;
/**
* Stores the flag if voice activity detection should be enabled.
* @name voiceActivityDetection
* @type boolean
* @default true
* @since 0.6.18
* @private
*/
this.voiceActivityDetection = true;
/**
* Stores the auto bandwidth settings.
* @name bandwidthAdjuster
* @type JSON
* @since 0.6.18
* @private
*/
this.bandwidthAdjuster = null;
/**
* Stores the list of RTMP Sessions.
* @name rtmpSessions
* @type JSON
* @since 0.6.36
* @private
*/
this.rtmpSessions = {};
/**
* Offer buffered in order to apply when received answer
* @name bufferedLocalOffer
* @type Object
* @private
* @since 1.0.0
*/
this.bufferedLocalOffer = {};
/**
* Offers buffered in order to apply when answerAck has been received
* @name bufferedRemoteOffers
* @type Object
* @private
* @since 2.0.0
*/
this.bufferedRemoteOffers = {};
/**
* Map of RTCRTPSenders that are added via addTrack
* @name currentRTCRTPSenders
* @type Object
* @private
* @since 1.0.0
*/
this.currentRTCRTPSenders = {};
/**
* Stores the unique random number used for generating the "client_id".
* @name clientId
* @type string
* @private
* @since 0.6.31
*/
this.clientId = initOptions.clientId;
/**
* Stores all the Stream media status.
* @name streamsMediaStatus
* @type Object
* @private
* @since 1.0.0
*/
this.streamsMediaStatus = {};
/**
* Stores the media info of all peers.
* @name peerMedias
* @type Object
* @private
* @since 2.0.0
*/
this.peerMedias = {};
/**
* Stores the flag if messages should be persisted. Value determined by the hasPersistentMessage value returned from the API.
* This feature is enabled in the Temasys Developer Console by toggling the Persistent Message feature at the key level.
* @name hasPersistentMessage
* @type Object
* @private
* @since 2.0.0
*/
this.hasPersistentMessage = initOptions.hasPersistentMessage;
this.peerStreams = {};
this.streamsSettings = {};
this.enableStatsGathering = initOptions.enableStatsGathering;
}
} |
JavaScript | class DicePoolVTM20 {
// static selectCombination() {
// renderTemplate("systems/foundryvtt-vtm-20th/templates/chat/select.html", {}).then(content => {
// // let chatData = WFRP_Utility.chatDataSetup(html)
// ChatMessage.create({
// user: ChatMessage.getSpeaker(),
// content: content,
// rollMode: "selfroll"
// });
// });
// }
static rollTest(testData = {}, onlyAttribute = false) {
const {
attribute = "strength",
ability = "athletics",
actor = game.user.character,
difficulty = 6,
title
} = testData;
const modifier = 0;
const nan = { value: 0 };
const attributeDice = actor.getAttribute(attribute) || nan;
const abilityDice = actor.getAbility(ability) || nan;
const diceCount = onlyAttribute ?
parseInt(attributeDice.value) + modifier :
parseInt(attributeDice.value) + parseInt(abilityDice.value) + modifier;
const formula = `${diceCount}d10`;
const roll = new Roll(formula).roll();
const dice = roll.dice[0].results;
const fails = dice.filter((d) => d.result === 1).length;
const wins = dice.filter((d) => d.result >= difficulty).length;
const isCritFail = wins === 0 && fails > 0;
const degrees = wins - fails;
let message = `${actor.name} ${game.i18n.localize("DEGREES.GET")} `;
let result;
if (isCritFail) {
message = `${actor.name} ${game.i18n.localize("DEGREES.GETBOTCH")}`;
result = game.i18n.localize("DEGREES.BOTCH");
} else if (degrees <= 0) {
message = `${actor.name} ${game.i18n.localize("DEGREES.GETFAILURE")}`;
result = game.i18n.localize("DEGREES.FAILURE");
} else {
const success = game.i18n.localize("DEGREES.SUCCESS");
const localizeDegree = degrees > 5 ? 5 : degrees;
const degreeLabel = game.i18n.localize(`DEGREES.${localizeDegree}`);
result = `${degreeLabel} ${success}`;
}
// Render the roll for the results button that Foundry provides.
let rollMode = game.settings.get("core", "rollMode") || "roll";
const chatData = {
user: game.user._id,
speaker: ChatMessage.getSpeaker({ actor }),
content: `<p>${message}</p>`,
rollMode: rollMode,
details: message,
roll,
};
let template = 'systems/foundryvtt-vtm-20th/templates/chat/roll.html';
const attributeLabel = game.i18n.localize(attributeDice.label);
const abilityLabel = game.i18n.localize(abilityDice.label);
const difficultyLabel = game.i18n.localize(`DIFFICULTY.${difficulty}`);
const difficultyMessage = `${game.i18n.localize("DIFFICULTY.WAS")} ${difficultyLabel}`;
const poolConfig = onlyAttribute ? attributeLabel : `${attributeLabel} & ${abilityLabel}`
let templateData = {
title: title ? title : poolConfig,
message,
rolls: roll.dice[0].results,
formula,
difficulty,
difficultyMessage,
result,
degrees,
poolConfig: title ? poolConfig : ""
};
// Handle roll visibility. Blind doesn't work, you'll need a render hook to hide it.
if (["gmroll", "blindroll"].includes(rollMode))
chatData["whisper"] = ChatMessage.getWhisperRecipients("GM");
if (rollMode === "selfroll") chatData["whisper"] = [game.user._id];
if (rollMode === "blindroll") chatData["blind"] = true;
roll.render().then((r) => {
templateData.roll = r;
chatData.roll = JSON.stringify(r);
// Render our roll chat card
renderTemplate(template, templateData).then(content => {
chatData.content = content;
// Hook into Dice So Nice!
if (game.dice3d) {
game.dice3d
.showForRoll(roll, game.user, true, chatData.whisper, chatData.blind)
.then((displayed) => {
ChatMessage.create(chatData);
});
}
// Roll normally, add a dice sound.
else {
chatData.sound = CONFIG.sounds.dice;
ChatMessage.create(chatData);
}
});
});
}
static prepareTest(testData = {}, onlyAttribute = false) {
console.log({testData})
DicePoolVTM20.rollTest(testData, onlyAttribute);
}
} |
JavaScript | class MongoOptimizer
{
/**
* Create an optimizer object with the given options.
*
* @param {object} options An object containing all of the options for the optimizer.
*/
constructor(options)
{
const self = this;
self.options = options;
}
/**
* This method connects to the database. It must be called before anything else in the optimizer can be run.
*
* @param {function(err)} done A callback function. This will receive any connection errors from connecting to the
* database.
*/
connect(done)
{
const self = this;
mongodb.MongoClient.connect(self.options.database, function(err, db)
{
if (err)
{
return done(err);
}
else
{
self.db = db;
db.on('close', function(err)
{
// Kill the process
console.error(err);
process.exit(2);
});
return done();
}
});
}
/**
* This method loads all of the data for the optimizer from the database.
*
* That may include both cardinality data and query profiles.
*
* This must be run after MongoOptimizer::connect()
*
* @param {function(err)} done Callback after all of the optimizer data is loaded.
*/
loadOptimizerData(done)
{
const self = this;
const collection = self.db.collection(self.options.collection);
collection.find({}).limit(1).toArray().then(function(results)
{
// If there are no results, then we are operating on a fresh database!
if (results.length == 0)
{
self.sampler = new MongoSampler(self.db, self.options, null);
self.querySet = new QuerySet({}, self.sampler, self.options);
return done();
}
const data = results[0];
if(data.sampler)
{
self.sampler = new MongoSampler(self.db, self.options, data.sampler);
}
else
{
self.sampler = new MongoSampler(self.db, self.options, null);
}
if (data.queryProfiles)
{
self.querySet = new QuerySet({queryProfiles: data.queryProfiles}, self.sampler, self.options);
}
else if (data.querySet)
{
self.querySet = new QuerySet(data.querySet, self.sampler, self.options);
}
else
{
self.querySet = new QuerySet(null, self.sampler, self.options);
}
return done();
}, done).catch(done)
}
/**
* This method saves the data for the optimizer to the database. Basically includes all internal state
* for the optimizer.
*
* That may include both cardinality data and query profiles.
*
* @param {function()} done A callback after the data has been saved.
*/
saveOptimizerData(done)
{
const self = this;
const collection = self.db.collection(self.options.collection);
const objectToSave = {
querySet: self.querySet.toJSON(),
sampler: self.sampler.toJSON()
};
collection.findOneAndUpdate({}, objectToSave,{upsert: true}).then(function(changed)
{
return done();
}, done).catch(done);
}
/**
* This method ensures that Mongo profiling is turned on if it needs to be turned on.
*
* @param {function()} done A callback after profiling has been enabled.
*/
setProfilingLevel(done)
{
const self = this;
if (self.options.profileLevel != -1)
{
// First, set the profiling level
self.db.command( {profile: self.options.profileLevel}, null, function (err, result)
{
if (err)
{
return done(err);
}
if (result.ok !== 1)
{
return done(new Error(`Error while setting the profile level on the database. Got result: ${JSON.stringify(result)}`))
}
else
{
return done();
}
});
}
else
{
return done();
}
}
/**
* This method starts the main loop for the optimizer. It connects to the databases system.profile collection
* and starts tailing it and processing mongos profile object as it goes.
*
* @param {function(err)} done Callback function for after the main loop has been started.
*/
startOptimizer(done)
{
const self = this;
self.setProfilingLevel(function (err)
{
if (err)
{
return done(err);
}
const profile = self.db.collection("system.profile");
var cursor = profile.find({
op: "query",
ns: {$regex: "^[^\\.]+\\.(?!system|\\$cmd)"}
}, {
tailable: true,
awaitdata: true,
timeout: false
});
const queue = async.queue(function(mongoProfile, next)
{
async.nextTick(function()
{
self.processMongoProfile(mongoProfile, function (err)
{
if (err)
{
console.error(err);
return next(err);
}
return next();
});
});
});
cursor.each(function(err, item)
{
if (err)
{
console.error(err);
// process.exit(1);
}
else if(item === null)
{
console.error("Cursor for documents in system.profile collection returned nothing.");
// process.exit(1);
}
else
{
queue.push(item);
}
});
// At the same time, every 30 seconds, we synchronize the indexes with our current optimal layout
function syncIndexes()
{
// This function handles the query finishing
function finish(err)
{
if (err)
{
console.error(err);
}
setTimeout(syncIndexes, self.options.indexSynchronizationInterval * 1000);
}
// First, we remove any old query profiles
self.querySet.removeOldQueryProfiles();
// Save before, because the synchronize step can take a long time,
// and we don't want to lose all the query profiles gathered so far
self.saveOptimizerData(function (err)
{
if (err)
{
return finish(err);
}
try
{
// Perform the synchronization. Internally, this triggers the random sampling of your database.
self.synchronizeIndexes(function (err)
{
if (err)
{
return finish(err);
}
// Also save after, so that we don't lose any of the cached sampling statitics gathered during the first step.
self.saveOptimizerData(function (err)
{
if (err)
{
return finish(err);
}
return finish();
});
});
}
catch(err)
{
return finish(err);
}
});
}
syncIndexes();
return done();
});
}
/**
* This method creates an IndexSet with all of the indexes that currently exist for our collections
*
* @param {function(err, indexSet)} done A callback function which will receive the IndexSet object containing all of the indexes.
*/
getExistingIndexes(done)
{
const self = this;
const collections = underscore.uniq(underscore.map(self.queryProfiles, queryProfile => queryProfile.collectionName));
// For each collection, obtain the list of existing indexes for that collection
async.mapSeries(collections, function(collectionName, next)
{
// Get the collection
const collection = self.db.collection(collectionName);
// Get the existing indexes
collection.listIndexes().toArray().then(function(results)
{
const existingIndexes = underscore.filter(underscore.map(results, result => new MongoIndex(result.key, collectionName, result.name)), index => !index.isIDOnly);
return next(null, existingIndexes)
}, next).catch(next);
}, function(err, allExistingIndexes)
{
if (err)
{
return done(err);
}
return done(null, new IndexSet(underscore.flatten(allExistingIndexes)));
});
}
/**
* This method will go through the reduced set of indexes for our query profiles, and
* compare them to the set of indexes that we have in the database. It will then, for
* each collection, produce its recommended index plan. This includes which indexes to
* drop, which to keep, and which to create new.
*
* @param {function(err, collectionChanges)} done A callback function which will receive the results.
*/
getRecommendedIndexChanges(done)
{
const self = this;
self.getExistingIndexes(function(err, currentIndexSet)
{
if (err)
{
return done(err);
}
self.querySet.computeOptimalIndexSet(function(err, recommendedIndexSet)
{
if (err)
{
return done(err);
}
const collectionChanges = IndexSet.getRecommendedIndexChanges(recommendedIndexSet, currentIndexSet);
return done(null, collectionChanges);
});
});
}
/**
* This method is used to process a single Mongo Profile object - the type that are stored in the system.profile collection,
* or returned when you use the .explain() method on a cursor.
*
* It will extract the query for that profile, determine if its a known query or a new one. If its a new one it stores it.
*
* If its a known query, it will further examine the profile object to see what indexes Mongo actually used for this query.
* It compares this with the indexes that it expects Mongo to use for this query. If Mongo used none of the expected indexes,
* it will print an error.
*
* @param {object} mongoProfile A JSON mongo profile object from the system.profile
* @param {function(err)} done A callback after the mongo profile has been processed.
*
*/
processMongoProfile(mongoProfile, done)
{
const self = this;
const queryProfiles = QueryProfile.createQueryProfilesFromMongoProfile(mongoProfile, self.options);
async.eachSeries(queryProfiles, function (queryProfile, next)
{
// If this query only contains _id or is empty entirely, ignore it
if (queryProfile.isIDOnly || queryProfile.isEmpty)
{
return next();
}
// First add it to the query set
const existingQueryProfile = self.querySet.addQueryProfile(queryProfile);
existingQueryProfile.getCardinalitiesForIndexOptimization(self.sampler, function(err)
{
if (err)
{
return next(err);
}
// Now check to see if it used the indexes we think it should have
const indexesPendingCreation = underscore.any(existingQueryProfile.reducedIndexes, (index) => !index.doesIndexExist());
// If we don't know for sure that the index even exists, then we shouldn't trigger an error message
if (indexesPendingCreation)
{
return next();
}
// Or if there are no indexes for the query, ignore that as well
if (existingQueryProfile.reducedIndexes.length == 0)
{
console.error("Query has no indexes!");
console.error(existingQueryProfile);
console.error(existingQueryProfile.reducedIndexes);
return next();
}
const usedCorrectIndex = existingQueryProfile.didMongoProfileUseIndex(mongoProfile);
if (!usedCorrectIndex)
{
console.log("Missed the correct index in: ", mongoProfile.ns);
console.log("Query:");
console.log(mongoProfile.query);
console.log("Profile");
console.log(existingQueryProfile);
console.log("Used indexes:");
console.log(JSON.stringify(QueryProfile.getUsedIndexesInMongoProfile(mongoProfile), null, 2));
console.log("Expected index:");
console.log(JSON.stringify(existingQueryProfile.reducedIndexes, null, 2));
console.log()
}
return next();
});
}, done);
}
/**
* This method just formats and prints the collectionChanges object created by MongoOptimizer::getRecommendedIndexChanges
*
* @param {object} collectionChanges The results produced from MongoOptimizer::getRecommendedIndexChanges
* @param {String} indent A string containing the number of spaces wanted for indentation at the start of the line.
*/
printChangeSummary(collectionChanges, indent)
{
const self = this;
console.log(`${indent}${collectionChanges.collectionName}`);
if (!self.options.showChangesOnly || collectionChanges.create.length > 0)
{
console.log(`${indent} Create:`);
const sortedCreateIndexes = underscore.sortBy(collectionChanges.create, (index) => JSON.stringify(index));
sortedCreateIndexes.forEach(function(index)
{
index.printIndexData(`${indent} `, true);
console.log("");
});
}
if (!self.options.showChangesOnly)
{
console.log("");
console.log(`${indent} Keep:`);
const sortedKeepIndexes = underscore.sortBy(collectionChanges.keep, (index) => JSON.stringify(index));
sortedKeepIndexes.forEach(function(index, n)
{
index.printIndexData(`${indent} `, true);
console.log("");
});
}
if (!self.options.showChangesOnly || collectionChanges.drop.length > 0)
{
console.log("");
console.log(`${indent} Drop:`);
const sortedDropIndexes = underscore.sortBy(collectionChanges.drop, (index) => JSON.stringify(index));
sortedDropIndexes.forEach(function (index)
{
index.printIndexData(`${indent} `, true);
console.log("");
});
}
}
/**
* This method creates a new index using the Mongo shell. It is done this way to circumvent a bug in the NodeJS Mongo driver
* which doesn't allow creating indexes with periods in them, like {"names.name": 1}
*
* @param {String} collectionName The name of the collection to create the index on
* @param {MongoIndex} index The index object describing the index.
* @param {String} indexName The name of the index
* @param {function(err)} done A callback that will be called once the index has been created.
*/
createIndexSubProcess(collectionName, index, indexName, done)
{
const self = this;
const parsed = mongodbUri.parse(self.options.database);
const resultPrefix = 'index-creation-result:';
const usernameArgument = parsed.username ? [`--username`, `${parsed.username}`] : [];
const passwordArgument = parsed.password ? [`--password`, `${parsed.password}`] : [];
const hostArgument = parsed.hosts[0].host ? [`--host`, `${parsed.hosts[0].host}`] : [];
const portArgument = parsed.hosts[0].port ? [`--port`, `${parsed.hosts[0].port}`] : [];
const databaseArgument = parsed.database ? [`${parsed.database}`] : [];
const commandArgument = [`--eval`, `print("${resultPrefix}" + JSON.stringify(db.${collectionName}.createIndex(${JSON.stringify(index)}, {background: true, name: "${indexName}"})));`];
const allArguments = underscore.flatten([usernameArgument, passwordArgument, hostArgument, portArgument, databaseArgument, commandArgument]);
const command = `mongo ${allArguments.join(" ")}`;
childProcess.execFile("mongo", allArguments, {env: process.env}, function(err, output)
{
if (err)
{
return done(err);
}
const outputPos = output.indexOf(resultPrefix);
if (outputPos === -1)
{
return done(new Error(`Error creating the index through the Mongo Shell. Executed command:\n${command}\nGot output:\n${output}\n`))
}
const jsonOutput = output.substr(outputPos + resultPrefix.length);
let result = null;
try
{
result = JSON.parse(jsonOutput);
}
catch(err)
{
return done(new Error(`Error parsing the JSON output from creating the index on the Mongo Shell. Executed command:\n${command}\n Got output:\n${output}\n`))
}
if (result.ok)
{
return done();
}
else if(result.code === 17280)
{
// This is an error that a particular value in the database is too large to index. This means that we must have not caught that value
// when we did our random sample to determine field cardinalities and maximum value lengths.
const fields = Object.keys(index);
self.sampler.getCollectionStatistics(collectionName, function(err, collectionStatistics)
{
if (err)
{
return done(err);
}
// Get the field that already has the longest maximum length. This field is probably the trouble maker
const fieldToAlter = underscore.max(fields, (field) => collectionStatistics.fieldStatistics[field].longest);
// We change this fields statistics so that its longest known value is longer then whats indexable.
// Other machinery will then react to do the best we can with this field, potentially by creating a
// hash index
collectionStatistics.fieldStatistics[fieldToAlter].mode = 'hash';
return done();
});
}
else
{
return done(new Error(`Error while creating index through the Mongo Shell. Executed command:\n${command}\nGot result:\n${JSON.stringify(result, null, 2)}`));
}
});
}
/**
* This method checks what the current indexes are, compares it to the recommended indexes for the currently known queries,
* and implements the changes if index changing is enabled. If changes are disabled, it will just print its recommended changes
* without implementing them.
*
* @param {function(err)} done A callback after all of the indexes have been synchronized.
*/
synchronizeIndexes(done)
{
const self = this;
function printIndexReportStart()
{
console.log("==========================================================");
console.log("==========================================================");
console.log("Index Report ", new Date().toString());
}
function printIndexReportFinish()
{
console.log("Index Report Finished");
console.log("==========================================================");
console.log("==========================================================");
}
if(self.options.simple)
{
self.querySet.computeOptimalIndexSet(function(err, recommendedIndexSet)
{
if (err)
{
return done(err);
}
printIndexReportStart();
console.log("\n");
recommendedIndexSet.print();
console.log("\n");
printIndexReportFinish();
return done();
});
}
else
{
self.getRecommendedIndexChanges(function (err, collectionsToChange)
{
if (err)
{
return done(err);
}
// sort the collections to change
collectionsToChange = underscore.sortBy(collectionsToChange, (collectionChanges) => (collectionChanges.collectionName));
if (self.options.showChangesOnly)
{
// First see if there are any changes at all
let changes = false;
// Print a summary of the changes that are being made first
collectionsToChange.forEach(function (collectionChanges)
{
if (collectionChanges.create.length > 0 || collectionChanges.drop.length > 0)
{
changes = true;
}
});
// If there are changes, print them
if (changes)
{
printIndexReportStart();
// Print a summary of the changes that are being made first
collectionsToChange.forEach(function (collectionChanges)
{
if (collectionChanges.create.length > 0 || collectionChanges.drop.length > 0)
{
self.printChangeSummary(collectionChanges, " ");
}
});
printIndexReportFinish();
}
}
else
{
printIndexReportStart();
// Print a summary of the changes that are being made first
collectionsToChange.forEach(function (collectionChanges)
{
self.printChangeSummary(collectionChanges, " ");
});
printIndexReportFinish();
}
// If we don't need to do the changes, then don't go any further
if (!self.options.doChanges)
{
return done();
}
async.eachSeries(collectionsToChange, function (collectionChanges, next)
{
// Get the collection
const collection = self.db.collection(collectionChanges.collectionName);
async.eachSeries(collectionChanges.create, function (index, next)
{
collection.createIndex(index, {name: index.mongoIndexName, background: true}, function (err)
{
if (err)
{
self.createIndexSubProcess(collectionChanges.collectionName, index, index.mongoIndexName, function (subProcessError)
{
if (subProcessError)
{
console.error(`Create index error for index ${JSON.stringify(index)}. Index may need to be created manually: ${subProcessError}`);
return next();
}
return next();
});
}
else
{
return next();
}
});
}, function (err)
{
if (err)
{
return next(err);
}
// See the list of indexes we don't need anymore (dangerous!)
async.eachSeries(collectionChanges.drop, function (index, next)
{
collection.dropIndex(index.mongoIndexName, {}, function (err)
{
if (err)
{
console.error(`Drop index error for index ${JSON.stringify(index)}. Index may need to be dropped manually: ${err}`);
return next();
}
else
{
return next();
}
});
}, next);
});
}, function (err)
{
if (err)
{
return done(err);
}
return done();
});
});
}
}
} |
JavaScript | class Engine
{
/**
* Creates a new game engine.
* @param {*} options
*/
constructor(options)
{
this.self = this;
this.options = options;
this.connection = new Connection(this);
this.canvas = document.getElementById('canvas');
this.canvas.addEventListener('mousemove', event=>{
// map the mouse to the client.
const position = this.mapMouse(event);
console.log(position);
});
this.context = canvas.getContext('2d');
this.keyState = {};
this.characters = [];
this.session = {};
this.map = {};
this.userId = null;
window.addEventListener( 'keydown', event=>{
const keyCode = event.keyCode;
// If the key is already down then do nothing.
if (this.keyState[keyCode]) return;
// Update the key state.
this.keyState[keyCode] = true;
// Map the keycode to the action and send it to the server.
this.connection.send({type: 'keydown', action: this.mapKeyCode(keyCode) });
});
window.addEventListener( 'keyup', event=>{
const keyCode = event.keyCode;
// Update the key state.
this.keyState[keyCode] = false;
// Map the keycode to the action and send it to the server.
this.connection.send({type: 'keyup', action: this.mapKeyCode(keyCode) });
});
// Start the render loop
setInterval( ()=>window.requestAnimationFrame(()=>this.render()), this.options.renderInterval );
// The UI of the application
this.ui = new Vue({ el: '#characters', data: this });
}
onConnected()
{
// Request to join the server.
this.connection.send({"type": "join"});
}
setCharacter(name)
{
this.connection.send({"type": "setCharacter", "name": name});
}
mapMouse(event)
{
const target = event.target;
return {x: (target.width * (event.offsetX/target.clientWidth) ), y: (target.height * (event.offsetY/target.clientHeight) )};
//console.log(`x="${event.offsetX}", y="${event.offsetY}"`);
}
/**
*
* @param {*} event
*/
async onMessage(event)
{
// If the actions is an array then loop though them.
if (Array.isArray(event)) { for (let evt of event) this.onMessage(evt); return; }
// Updates the current session user list and session maps and details.
if (event.type === 'session')
{
// Populate the session with the character details.
this.session = await this.loadSession(event);
// Find the user state within the session.
this.session.user = this.session.users.find( user=>(user.id === this.userId) );
}
else if (event.type === 'user')
{
// Get the user ID and set it locally, this is used to fetch the user details from the sesson later.
this.userId = event.id;
}
else if (event.type === 'characters')
{
// Traverse the characters and load their images.
for (let character of event.characters)
await this.loadCharacter(character);
// Set the characters locally.
this.characters = event.characters;
}
else if (event.type === 'update') this.onUpdate(event);
}
onUpdate(event)
{
// Traverse the updates and apply them if it is an array.
if (Array.isArray(event)) { for (let evt of event) this.onUpdate(evt); return; }
// Get the object with id.
const object = this.session.users.find( user=>(user.id === event.id) );
if (object)
{
// Traverse the properties and update them.
for (let key in event.properties)
{
const value = event.properties[key]
Utility.setProperty(object, key, value);
}
}
}
/**
* Loads the character details within the users.
*/
async loadSession(session)
{
// Traverse the users and find their corresponding character definitions.
for (let user of session.users)
user.characterDefinition = this.characters.find( character=>(character.name === user.state.name) );
// Set the map content locally.
this.map = await this.initMap(session.map);
// Return the populated session.
return session;
}
async initMap(map)
{
map.background = await this.loadImage(map.background);
for (let name in map.assets)
{
const asset = map.assets[name];
if (asset.src) asset.src = await this.loadImage(asset.src);
}
return map;
}
/**
* Traverses the given character assets and converts the base64 data url to an image
* so we can speed up rendering.
*/
async loadCharacter(character)
{
for (let name in character.states)
{
// Get the next state.
let state = character.states[name];
// Traverse the base64 and convert to images.
for (let index = 0; index < state.assets.length; index++)
{
// Create the image and set the src using the data url. Replace the base64 with the image.
state.assets[index] = await this.loadImage(state.assets[index]);
}
}
}
loadImage(dataURL)
{
return new Promise( resolve=>{
const image = new Image()
image.src = dataURL;
image.onload = ()=>{
resolve(image);
};
});
}
/**
* Maps the given keyCode to an action based on the user preferences and options.
*/
mapKeyCode(keyCode)
{
//console.log(keyCode);
return this.options.keyboardMap[keyCode];
}
renderMap()
{
// Render the background first.
this.context.drawImage(this.map.background, 0, 0, this.map.size.width, this.map.size.height);
// Render the layout
for (let object of this.map.layout)
{
if (object.type === 'FLOOR')
{
this.context.stroke = "1px";
this.context.strokeStyle = "red";
this.context.strokeRect(object.x1, object.y1, object.x2 - object.x1, object.y2 - object.y1);
continue;
}
// Find the object reference within he assets.
const asset = this.map.assets[object.type];
if (!asset) continue;
this.context.drawImage(asset.src, object.x, object.y - asset.src.height);
}
}
/**
* Refreshes the render of the canvas to the current state.
*/
render()
{
// Clear the canvas.
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
// If there is no session then don't render anything.
if (!this.session || !this.session.users) return;
this.renderMap();
// Render the users in the session.
for (let user of this.session.users)
{
// Get the character definition where the assets are stored.
const character = user.characterDefinition;
// If there is no character definition then skip it.
if (!character) continue;
// Get the current character state image
const state = character.states[user.state.state];
// If we are past the last frame then reset the motion index.
//if (user.state.motionIndex >= (state.assets.length - 1)) user.state.motionIndex = 0;
// Get the next frame and move to the next one.
const image = state.assets[user.state.motionIndex++ % state.assets.length];
// If the user direction is backwards then flip the image.
this.context.drawImage(image, user.state.position.x, user.state.position.y, character.size.width, character.size.height);
// Render the user name on top of the user.
this.context.fillText(user.name, user.state.position.x, user.state.position.y);
}
}
} |
JavaScript | class Pipe {
/**
* Create child pipe
* @param {Pipe} parentPipe
* @param {Function} pipingFunction
* @return {Pipe}
*/
static piping(parentPipe, pipingFunction) {
const pipe = new Pipe();
on(parentPipe, EVENTS.VALUE, value => pipingFunction(value, value => pipe.push(value)));
return pipe;
}
/**
* Merge pipes into one
* @param {Array.<Pipe>} pipes
* @return {Pipe}
*/
static merge(...pipes) {
const pipe = new Pipe();
pipes.forEach(mergePipe => {
on(mergePipe, EVENTS.VALUE, value => pipe.push(value));
});
return pipe;
}
/**
* Creates a pipe from defined interval
* @param {number} milliseconds
* @return {Pipe}
*/
static fromInterval(milliseconds) {
const pipe = new Pipe();
pipe.tick = 0;
pipe.timerId = setInterval(() => pipe.push(++pipe.tick), milliseconds);
pipe.onClose(() => clearInterval(pipe.timerId));
return pipe;
}
/**
* Creates a pipe from YYF Event
* @param {Object} context
* @param {string} eventName
* @param {boolean} onlyFirstArg
* @return {Pipe}
*/
static fromYYFEvent(context, eventName, onlyFirstArg = true) {
const pipe = new Pipe();
const callback = getArgCallback(pipe, onlyFirstArg);
pipe.context = context;
pipe.eventName = eventName;
on(context, eventName, callback);
pipe.onClose(() => un(context, eventName, callback));
return pipe;
}
/**
* Creates a pipe from EventTarget event
* @param {EventTarget} eventTarget
* @param {string} eventName
* @param {boolean} onlyFirstArg
* @return {Pipe}
*/
static fromEventTarget(eventTarget, eventName, onlyFirstArg = true) {
const pipe = new Pipe();
const callback = getArgCallback(pipe, onlyFirstArg);
pipe.eventTarget = eventTarget;
pipe.eventName = eventName;
eventTarget.addEventListener(eventName, callback);
pipe.onClose(() => eventTarget.removeEventListener(eventName, callback));
return pipe;
}
/**
* Creates a pipe from node EventEmitter
* @param {EventEmitter} target
* @param {string} eventName
* @param {boolean} onlyFirstArg
* @return {Pipe}
*/
static fromEventEmitter(target, eventName, onlyFirstArg = true) {
const pipe = new Pipe();
const callback = getArgCallback(pipe, onlyFirstArg);
pipe.target = target;
pipe.eventName = eventName;
target.addListener(eventName, callback);
pipe.onClose(() => target.removeListener(eventName, callback));
return pipe;
}
/**
* Pushes value to the pipe
*
* @param {*} value
* @returns {Pipe}
*/
push = (value) => {
try {
if (this[_closed]) {
throw new Error('Pipe is closed');
}
go(this, EVENTS.VALUE, value);
} catch (error) {
error.value = value;
go(this, EVENTS.ERROR, error);
}
return this;
};
/**
* Listen pipe for value
*
* @param {Function} listener
* @param {boolean} [onetime]
* @returns {Pipe}
*/
listen = (listener, onetime) => {
if (onetime) {
once(this, EVENTS.VALUE, listener);
} else {
on(this, EVENTS.VALUE, listener);
}
return this;
};
/**
* Listen pipe for errors
*
* @param {Function} listener
* @returns {Pipe}
*/
onError = (listener) => {
on(this, EVENTS.ERROR, listener);
return this;
};
/**
* Listen pipe for closing
*
* @param {Function} listener
* @returns {Pipe}
*/
onClose = (listener) => {
on(this, EVENTS.CLOSE, listener);
return this;
};
/**
* Closes pipe
* @returns {Pipe}
*/
close = () => {
go(this, EVENTS.CLOSE);
return this;
};
/**
* Maps values to new pipe
*
* @param {Function|*} mapper
* @returns {Pipe}
*/
map = (mapper) => {
if (mapper instanceof Function) {
return Pipe.piping(this, (value, push) => push(mapper(value)));
}
return Pipe.piping(this, (value, push) => push(mapper));
};
/**
* Reduces values to new pipe
*
* @param {Function} reducer
* @param {*} [init]
* @returns {Pipe}
*/
reduce = (reducer, ...init) => {
let lastValue;
let handler = value => {
lastValue = value;
handler = (value, push) => push(lastValue = reducer(lastValue, value));
};
if (init.length) {
handler(init[0]);
}
return Pipe.piping(this, (value, push) => handler(value, push));
};
/**
* Filters values to new pipe
*
* @param {Function} filter
* @returns {Pipe}
*/
filter = (filter) => {
return Pipe.piping(this, (value, push) => filter(value) && push(value));
};
/**
* Splits value to values for new pipe
*
* @param {Function} splitter
* @returns {Pipe}
*/
split = (splitter) => {
return Pipe.piping(this, (value, push) => Array.from(splitter(value)).forEach(value => push(value)));
};
/**
* Delays pushing values to new pipe
*
* @param {number} milliseconds
* @returns {Pipe}
*/
delay = (milliseconds) => {
const timers = [];
const pipe = Pipe.piping(this, (value, push) => timers.push(setTimeout(push, milliseconds, value)));
pipe.onClose(() => timers.forEach(clearTimeout));
return pipe;
};
/**
* Throttles values for specified period to new pipe
*
* @param {number} milliseconds
* @returns {Pipe}
*/
throttle = (milliseconds) => {
const values = [];
const pipe = Pipe.piping(this, value => values.push(value));
const timerId = setInterval(() => pipe.push(values.splice(0)), milliseconds);
pipe.onClose(() => clearInterval(timerId));
return pipe;
};
/**
* Throttles values for specified period and pass only latest one to new pipe
*
* @param {number} milliseconds
* @returns {Pipe}
*/
throttleLast = (milliseconds) => {
const values = [];
const pipe = Pipe.piping(this, value => values[0] = value);
const timerId = setInterval(() => values.length && pipe.push(values.splice(0)[0]), milliseconds);
pipe.onClose(() => clearInterval(timerId));
return pipe;
};
} |
JavaScript | class DrawerScreen extends PureComponent {
render() {
const {
router,
navigation,
childNavigationProps,
screenProps
} = this.props;
const { routes, index } = navigation.state;
const childNavigation = childNavigationProps[routes[index].key];
const Content = router.getComponentForRouteName(routes[index].routeName);
return <SceneView screenProps={screenProps} component={Content} navigation={childNavigation} />;
}
} |
JavaScript | class StarWarsPluginV1 {
constructor(pluginconfig = {}) {}
apply(compiler) {
console.log('StarWarsPlugin is executed')
}
} |
JavaScript | class StarWarsPluginV2 {
constructor(pluginconfig = {}) {}
apply(compiler) {
// We want the star wars data to be added on top of the rendered Data. So we use the "modulerizrFileRendered"-Hook
compiler.hooks.modulerizrFileRendered.tap('StarWarsPlugin', ($el, srcFile, context) => {
console.log('here we have to add our code');
});
}
} |
JavaScript | class StarWarsPluginV3 {
constructor(pluginconfig = {}) {}
apply(compiler) {
// We want the star wars data to be added on top of the rendered Data. So we use the "modulerizrFileRendered"-Hook
compiler.hooks.modulerizrFileRendered.tap('StarWarsPlugin', ($, srcFile, context) => {
const $body = $('head');
$body.append("<script>console.log(`Let's add some starwars-data`);</script>");
// or in short: $('body').append("<script>console.log('Let's add some starwars-data');</script>");
});
}
} |
JavaScript | class StarWarsPluginV4 {
constructor(pluginconfig = {}) {}
apply(compiler) {
//We want the starwars-data to be fetched just on beginning - so we use the modulerizrInit-Hook
compiler.hooks.modulerizrInit.tapPromise('StarWarsPlugin', async context => {
const starwarsCharacters = await fetch('https://swapi.co/api/people/').then(res => res.json())
context.starwarsCharacters = starwarsCharacters;
});
// We want the star wars data to be rendered in each file. So we use the "modulerizrFileRendered"-Hook
compiler.hooks.modulerizrFileRendered.tap('StarWarsPlugin', ($, srcFile, context) => {
const $body = $('head');
const starwarsDataAsString = JSON.stringify(context.starwarsCharacters.results);
$body.append(`<script>var starwarsdata = ${starwarsDataAsString};</script>`);
});
}
} |
JavaScript | class Group extends React.Component {
static displayName = 'Group'
static defaultProps = {
vertical: false,
noBorders: false,
borderRadius: 0
}
static propTypes = {
/** A group can display it's children **vertical**. */
vertical: PropTypes.bool
}
render () {
const className = cx('group', this.props.className)
const { vertical, children, fluid, ...rest } = this.props
const StyledGroup = vertical ? VGroup : HGroup
const filterChildren = filter(compact(children), e => !isBoolean(e))
const items = React.Children.map(
filterChildren,
(c, index) => {
let itemClassName = cx(
{'child': index !== 0 && index !== filterChildren.length - 1},
{'first': index === 0},
{'last': index === filterChildren.length - 1}
)
let itemProps = {...removeSpaceProps(rest)}
if (filterChildren.length > 1) {
itemProps.className = itemClassName
}
return React.cloneElement(c, itemProps)
}
)
return (
<StyledGroup {...rest} fluid={fluid} className={className}>
{items}
</StyledGroup>
)
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div>
<Router>
<NavBar />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/files/:filename" component={File} />
</Switch>
</Router>
</div>
);
}
} |
JavaScript | class AppProvider extends Component {
state = {
open: false,
savingQuestions: savingQuestions,
selectedQuestion: savingQuestions[0],
possibilitiesList: possibilitiesList,
selectedPossibility: possibilitiesList[0],
resolvingSchedulingList: resolvingSchedulingList,
selectedScheduling: resolvingSchedulingList[0],
showModal: () => this.setState({ open: true }),
hideModal: () => this.setState({ open: false }),
}
handleSelectQuestion = id => {
this.setState(prevState => {
const { selectedItem, newListState } = selectById(
id,
prevState.savingQuestions
)
return {
...this.state,
selectedQuestion: selectedItem,
savingQuestions: newListState,
}
})
}
handleSelectPossibility = id => {
this.setState(prevState => {
const { selectedItem, newListState } = selectById(
id,
prevState.possibilitiesList
)
return {
...this.state,
selectedPossibility: selectedItem,
possibilitiesList: newListState,
}
})
}
handleSelectScheduling = id => {
this.setState(prevState => {
const { selectedItem, newListState } = selectById(
id,
prevState.resolvingSchedulingList
)
return {
...this.state,
selectedScheduling: selectedItem,
resolvingSchedulingList: newListState,
}
})
}
render() {
return (
<Provider
value={{
...this.state,
handleSelectQuestion: this.handleSelectQuestion,
handleSelectPossibility: this.handleSelectPossibility,
handleSelectScheduling: this.handleSelectScheduling,
}}
>
{this.props.children}
</Provider>
)
}
} |
JavaScript | class DateInput extends HTMLElement {
/**
* Create a new DateInput object.
* @constructor
*/
constructor() {
// Must call super first
super();
// Create the CSS parts for the shadow DOM
const style = document.createElement('style');
// Set style
style.textContent =
`
select {
margin: 0.15rem;
padding: 1rem;
color: #555;
background-color: #eee;
border: 1px solid #ccc;
border-radius: 0.5rem;
font-size: 120%;
}
`;
// Attach shadow DOM root
this._shadowRoot = this.attachShadow({mode: 'open'});
// Add styles
this._shadowRoot.appendChild(style);
// Create root HTML
const rootHtml = document.createElement('div');
// Set inner HTML
rootHtml.innerHTML =
`
<select id="year"></select>
<select id="month"></select>
<select id="day"></select>
`;
// Add root HTML to shadow DOM
this._shadowRoot.appendChild(rootHtml);
// Get elements
this._yearElement = this._shadowRoot.getElementById('year');
this._monthElement = this._shadowRoot.getElementById('month');
this._dayElement = this._shadowRoot.getElementById('day');
// Add years, months, days
this._addYears();
this._addMonths();
this._addDays();
// Set default to emply
this._yearElement.value = '';
this._monthElement.value = '';
this._dayElement.value = '';
// Bind click events to this
this._changeEvent = this._changeEvent.bind(this);
}
/**
* Override connectedCallback function to handle when component is attached into the DOM.
* @override
*/
connectedCallback() {
// Get elements
this._yearElement = this._shadowRoot.getElementById('year');
this._monthElement = this._shadowRoot.getElementById('month');
this._dayElement = this._shadowRoot.getElementById('day');
// Add change event listener
this._yearElement.addEventListener('change', this._changeEvent);
this._monthElement.addEventListener('change', this._changeEvent);
this._dayElement.addEventListener('change', this._changeEvent);
}
/**
* Override attributeChangedCallback function to handle attribute changes
* @param {string} name Then name of the attribute that has changed.
* @param {string} oldValue The old value of the attribute before it was changed.
* @param {string} newValue The new value the attribute is being changed to.
* @override
*/
attributeChangedCallback(name, oldValue, newValue) {
// If value attribute changed
if (name === 'value') {
// Check parameter
if (newValue.length !== 10) return;
if (newValue.charAt(4) !== '-') return;
if (newValue.charAt(7) !== '-') return;
// Set date parts
this._yearElement.value = parseInt(newValue.substring(0, 4));
this._monthElement.value = parseInt(newValue.substring(5, 7));
this._dayElement.value = parseInt(newValue.substring(8, 10));
}
}
/**
* Override the observedAttributes function to return the list
* of attributes to monitor.
* @return {Array} List of attribute names.
* @static
* @override
*/
static get observedAttributes() {
// Return the list of attributes
return ['value'];
}
/**
* Gets the value of the whole date currently set.
* @type {string}
*/
get value() {
// Check all parts exist
if (this._yearElement.value.length === 0) return '';
if (this._monthElement.value.length === 0) return '';
if (this._dayElement.value.length === 0) return '';
// Get the year, month and day parts
const year = parseInt(this._yearElement.value);
const month = parseInt(this._monthElement.value);
const day = parseInt(this._dayElement.value);
// Set year text
const yearText = year.toString();
// Set month text
let monthText = month.toString();
if (monthText.length === 1) monthText = '0' + monthText;
// Set day text
let dayText = day.toString();
if (dayText.length === 1) dayText = '0' + dayText;
// Set date text
const dateText = yearText + '-' + monthText + '-' + dayText;
// Return the value of the current date
return dateText;
}
/**
* The value attribute value that is the current date in YYYY-MM-DD format.
* @param {string} value The value of the day.
* @type {string}
*/
set value(value) {
// Set the attribute
this.setAttribute('value', value.toString());
}
/**
* Form translate function. This is used by the Form class to move a date between the web component and a Date object.
* @param {object} data The data that contains the property that will be transferred in and out of the form input elements.
* @param {string} propertyName The name of the property inside the data object (we only use Date object).
* @param {Element} element The form input element to translate the data to/from (this web component).
* @param {number} task The task to perform.
* 1 = Clear all form inputs to be empty/blank
* 2 = Data to form transfer
* 3 = Form to data transfer
* @return {string} The name of the attribute used with the form input element to get/set its value.
*/
static formTranslateFunction(data, propertyName, element, task) {
// Get elements
const yearElement = element._shadowRoot.getElementById('year');
const monthElement = element._shadowRoot.getElementById('month');
const dayElement = element._shadowRoot.getElementById('day');
// If task is clear
if (task === 1) {
// Set date parts
yearElement.value = '';
monthElement.value = '';
dayElement.value = '';
}
// If task is data to form
if (task === 2) {
// If the data property is a Date
if (!(data[propertyName] instanceof Date)) throw new Error('Can only translate from a Date object');
// Get date
const date = data[propertyName];
// Set the year, month and day parts
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
// Set year text
const yearText = year.toString();
// Set month text
let monthText = month.toString();
if (monthText.length === 1) monthText = '0' + monthText;
// Set day text
let dayText = day.toString();
if (dayText.length === 1) dayText = '0' + dayText;
// Set date text
const dateText = yearText + '-' + monthText + '-' + dayText;
// Set element date parts
yearElement.value = year.toString();
monthElement.value = month.toString();
dayElement.value = day.toString();
// Set the attribute
element.setAttribute('value', dateText);
}
// If task is form to data
if (task === 3) {
// If the data property is a Date
if (!(data[propertyName] instanceof Date)) throw new Error('Can only translate to a Date object');
// Check all parts exist
if (yearElement.value.length === 0 || monthElement.value.length === 0 || dayElement.value.length === 0) return 'value';
// Get the year, month and day parts
const year = parseInt(yearElement.value);
const month = parseInt(monthElement.value);
const day = parseInt(dayElement.value);
// Get date
const date = data[propertyName];
// Get current time parts
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
// Create date object
data[propertyName] = new Date(year, month - 1, day, hour, minute, second);
}
// Return the name of the attribute
return 'value';
}
/**
* Add the year <option> parts.
* @private
*/
_addYears() {
// Set year from
const yearFrom = 1970;
// Set year to
const today = new Date();
const yearTo = today.getFullYear() + 20;
// For each year
for (let year = yearFrom; year <= yearTo; year++) {
// Create <option> element
const option = document.createElement('option');
// Set member
option.innerText = year.toString();
option.value = year.toString();
// Add to select year element
this._yearElement.appendChild(option);
}
}
/**
* Add the month <option> parts.
* @private
*/
_addMonths() {
// Set month text
const monthText = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
// For each month
for (let month = 1; month <= 12; month++) {
// Create <option> element
const option = document.createElement('option');
// Set member
option.innerText = month.toString() + ', ' + monthText[month - 1];
option.value = month.toString();
// Add to select month element
this._monthElement.appendChild(option);
}
}
/**
* Add the days <option> parts.
* @private
*/
_addDays() {
// For each day
for (let day = 1; day <= 31; day++) {
// Create <option> element
const option = document.createElement('option');
// Set member
option.innerText = day.toString();
option.value = day.toString();
// Add to select day element
this._dayElement.appendChild(option);
}
}
/**
* change event.
* @param {object} event The change event object.
*/
_changeEvent(event) {
// Set the attribute
this.setAttribute('value', this.value);
}
} |
JavaScript | class PageVisit extends Kowalski.Information {
// Make Kowalski collect this metric on every request
// By default Kowalski.Information sets eachReq to true
static get eachReq () {
return true
}
// The constructor reads the provided object to generate meaningful data.
// Since PageVisit.eachReq is true, Kowalski will always send an Express.Request object
constructor (req) {
super()
// We only want to collect PageVisits of logged in users
// To indicate that we don't want to collect data for this request we return NoInformation
if (!req.user) return Kowalski.Information.NoInformation
this.path = req.path
}
// Define what data should be stored by the storage
// Kowalski will automatically inject the current date!
get data () {
return {
path: this.path
}
}
// Define how an object returned by this.data can be converted back to a PageVisit instance
static fromObject ({ path }) {
return Object.assign(Object.create(PageVisit.prototype), { path })
}
} |
JavaScript | class Book {
constructor (title, author, genre, pageCount, publisherID, ISBN) {
this.title = title
this.author = author
this.genre = genre
this.pageCount = pageCount
this.publisherID = publisherID
this.ISBN = ISBN
}
} |
JavaScript | class BookFactory {
constructor () {
this._existingBooks = {}
}
createBook (title, author, genre, pageCount, publisherID, ISBN) {
// Find out if a particular book meta-data combination has been created before
const existingBook = this._existingBooks[ISBN]
if (existingBook) return existingBook
// If not, create a new instance of the book, store it and return it
const book = new Book(title, author, genre, pageCount, publisherID, ISBN)
this._existingBooks[ISBN] = book
return book
}
static getInstance () {
if (!BookFactory.instance) {
BookFactory.instance = new BookFactory()
}
return BookFactory.instance
}
} |
JavaScript | class BookRecordManager {
constructor () {
this._bookRecordDatabase = {}
}
addBookRecord (id, title, author, genre, pageCount, publisherID, ISBN,
checkoutDate, checkoutMember, dueReturnDate, availability) {
const book = BookFactory.getInstace().createBook(title, author, genre,
pageCount, publisherID, ISBN)
this._bookRecordDatabase[id] = {
checkoutMember: checkoutMember,
checkoutDate: checkoutDate,
dueReturnDate: dueReturnDate,
availability: availability,
book: book
}
}
updateCheckoutStatus (bookID, newStatus, checkoutDate, checkoutMember, newReturnDate) {
const record = this._bookRecordDatabase[bookID]
record.availability = newStatus
record.checkoutDate = checkoutDate
record.checkoutMember = checkoutMember
record.dueReturnDate = newReturnDate
}
extendCheckoutPeriod (bookID, newReturnDate) {
this._bookRecordDatabase[bookID].dueReturnDate = newReturnDate
}
isPastDue (bookID) {
const currentDate = new Date().getTime()
const returnDate = Date.parse(this._bookRecordDatabase[bookID].dueReturnDate)
return currentDate > returnDate
}
static getInstance () {
if (!BookRecordManager.instance) {
BookRecordManager.instance = new BookRecordManager()
}
return BookRecordManager.instance
}
} |
JavaScript | class Modal extends React.Component {
static displayName = 'Modal'
static propTypes = {
children: PropTypes.node,
onClose: PropTypes.func
}
state = {
hover: false
}
hoverOn = () => {
this.setState({ hover: true })
}
hoverOff = () => {
this.setState({ hover: false })
}
render() {
const { hover } = this.state
const { children, onClose } = this.props
return (
<Flex flexDirection="column" width={1} p={3} bg="primaryColor" css={{ height: '100%' }}>
<Flex justifyContent="flex-end" as="header" color="primaryText">
<Box
css={{ cursor: 'pointer', opacity: hover ? 0.6 : 1 }}
ml="auto"
onClick={onClose}
onMouseEnter={this.hoverOn}
onMouseLeave={this.hoverOff}
p={2}
>
<X width="2em" height="2em" />
</Box>
</Flex>
<Box as="section" p={3} pt={1} css={{ flex: 1 }}>
{children}
</Box>
</Flex>
)
}
} |
JavaScript | class LightBoxSlideShow extends React.Component {
constructor( props ) {
super( props )
this.state = {
gif: null,
isOpen: false,
imageReady: false,
isError: false,
currentIndex: false
}
}
componentDidMount(){
document.addEventListener("keydown", this.onKeyDownHandler, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.onKeyDownHandler, false);
}
componentDidUpdate( prevProps ) {
// Open
if( this.props.index !== false && this.state.isOpen === false ) {
this.openSlideShow( this.props.gifs[ this.props.index ] )
this.setState({ currentIndex: this.props.index })
}
// Close
if( this.props.index === false && this.state.isOpen ) {
this.setState({ isOpen: false })
}
}
onKeyDownHandler = event => {
if( this.state.gif && event.key === "Escape" ) {
this.closeSlideShow()
}
if( this.state.gif && event.key === "ArrowRight" ) {
this.nextSlide()
}
if( this.state.gif && event.key === "ArrowLeft" ) {
this.prevSlide()
}
}
preloadImage = ( imageSrc ) => {
var PreloadRequest = new Promise(( resolve, reject ) => {
let img = new Image();
img.onload = ( event ) => resolve('Image loaded')
img.onerror = ( event ) => reject('error')
img.src = imageSrc;
})
return PreloadRequest;
}
closeSlideShow = event => {
this.setState({
imageReady: false
})
this.props.unsetSelectedGif()
}
openSlideShow = ( gif ) => {
this.setState({ gif, isOpen: true });
this.preloadImage( gif.images.original.url )
.then(( result ) => {
this.setState({ imageReady: true })
})
.catch(( result) => {
this.setState({ isError: true })
})
}
nextSlide = event => {
var index = this.state.currentIndex + 1
this.navigateToSlide( index )
}
prevSlide = event => {
var index = this.state.currentIndex - 1
this.navigateToSlide( index )
}
navigateToSlide = ( index ) => {
this.setState({
imageReady: false,
gif: null
})
// console.log('navigateToSlide', index );
if( this.props.gifs[ index ]) {
const gif = this.props.gifs[ index ]
this.setState({ gif, currentIndex: index })
this.preloadImage( gif.images.original.url )
.then(( result ) => {
this.setState({ imageReady: true })
})
.catch(( result) => {
this.setState({ isError: true })
})
}
else {
this.closeSlideShow()
}
}
render() {
if( ! this.props.gifs ) return ''; // do not render until gifs are ready
return (
<LightBoxWindow open={ this.state.isOpen }>
<LightBoxCloseButton onClick={ this.closeSlideShow } />
<LightBoxContent>
{
!this.state.imageReady && !this.state.isError ?
<Loading
color="#000"
loading={ true }
/>
: ''
}
{
this.state.imageReady ?
<LightBoxGifImage
src={ this.state.gif.images.original.url }
href={ this.state.gif.bitly_gif_url }
/>
: ''
}
{
this.state.isError ?
<LightBoxImageError
message="There was an error while loading this gif"
/>
:''
}
</LightBoxContent>
<LightBoxNavButton
direction="left"
onClick={ this.prevSlide }
/>
<LightBoxNavButton
direction="right"
onClick={ this.nextSlide }
/>
</LightBoxWindow>
)
}
} |
JavaScript | class InPortConsumer extends React.Component {
constructor(props) {
super(props);
this.state = {
data: data,
};
this.token = null;
this.recursiveCloneChildren = this.recursiveCloneChildren.bind(this);
this._isMounted = false;
}
render() {
return <div>{this.recursiveCloneChildren(this.props.children)}</div>
}
recursiveCloneChildren(children) {
return React.Children.map(children, child => {
var childProps = {};
if (React.isValidElement(child)) {
if (this.props.propagateDataToChildren) {
if (this.state.data != null) {
childProps = {data: this.state.data};
}
}
} else {
return child;
}
childProps.children = this.recursiveCloneChildren(child.props.children);
return React.cloneElement(child, childProps);
})
}
componentDidMount() {
this.setUpNewDataInConnection(this.props.dataInPort);
this._isMounted = true;
}
componentWillUnmount() {
if (this.token != null) { // close current connection if existing
pubsub.unsubscribe(this.token);
this.token = null;
}
this._isMounted = false;
}
componentWillUpdate(nextProps) { // cannot use componentWillUpdate(), since setUpNewDataInConnection() can change state
let newPort = nextProps.dataInPort;
if (newPort != this.props.dataInPort) {
this.setUpNewDataInConnection(newPort);
}
}
setUpNewDataInConnection(port) {
if (this.token != null) { // close current connection if existing
pubsub.unsubscribe(this.token);
this.token = null;
}
if (port != "") {
this.token = pubsub.subscribe(port, (msg, data) => { // arrow func to preserve 'this'
if (this._isMounted) {
this.setState({data: data});
this.props.receiveCallback(data);
}
});
}
}
} |
JavaScript | class Api {
/**
* Set up token and secret for API access.
*
* @param token API token
* @param secret API secret
*/
constructor(token, secret) {
this.apiURL = "https://api.domeneshop.no/v0";
this.token = token;
this.secret = secret;
}
/**
* Do an API call.
*
* @param method Method for the request
* @param endpoint Request endpoint
* @param data Content of the request
* @param params Params for the request
*/
apiCall(method = "GET", endpoint = "/", data, params) {
const reqOptions = {
auth: {
password: this.secret,
username: this.token,
},
baseURL: this.apiURL,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
method,
responseType: "json",
url: endpoint,
};
if (params) {
reqOptions.params = params;
}
if (data) {
reqOptions.data = data;
}
return axios_1.default(reqOptions);
}
} |
JavaScript | class AppService {
/**
* Executes a console command
*
* @param {String} cmd
* @param {String} cwd
*
* @returns {Promise} Result
*/
static exec(cmd, cwd = '') {
checkParam(cmd, 'cmd', String);
checkParam(cwd, 'cwd', String);
if(!cwd) { cwd = APP_ROOT; }
return new Promise((resolve, reject) => {
let process = ChildProcess.exec(cmd, { cwd: cwd });
let result = '';
let message = '';
process.stdout.on('data', (data) => {
result += data;
});
process.stderr.on('data', (data) => {
message += data;
});
process.on('exit', (code) => {
if(code === 0 || code === '0') {
resolve(result);
} else {
reject(new Error('Process "' + cmd + '" in "' + cwd + '" exited with code ' + code + ': ' + message));
}
});
});
}
/**
* Gets a list of available themes
*
* @return {Array} Themes
*/
static async getThemes() {
let files = await HashBrown.Service.FileService.list(Path.join(APP_ROOT, 'theme'));
let themes = [];
for(let file of files) {
if(Path.extname(file) !== '.css') { continue; }
themes.push(Path.basename(file, '.css'));
}
let pluginThemes = await HashBrown.Service.PluginService.getThemes();
themes = themes.concat(pluginThemes);
themes.sort();
return themes;
}
} |
JavaScript | class Lsm9ds1I2c extends LSM9DS1 {
_read_u8(sensor_type, address) {
const buff = this._read_bytes(sensor_type, address, 1);
return buff[0];
}
_read_bytes(sensor_type, address, count) {
const deviceAddress = (sensor_type === _MAGTYPE) ? _LSM9DS1_ADDRESS_MAG : _LSM9DS1_ADDRESS_ACCELGYRO;
//readSync(address, register, length)
return this.i2c.readSync(
deviceAddress,
address,
count
);
}
_write_u8(sensor_type, address, val) {
const deviceAddress = sensor_type === _MAGTYPE ? _LSM9DS1_ADDRESS_MAG : _LSM9DS1_ADDRESS_ACCELGYRO;
this.i2c.writeSync(
deviceAddress,
address,
Buffer.from([val])
);
}
} |
JavaScript | class SsStreamCipherPreset extends IPreset {
_algorithm = '';
_key = null;
_iv = null;
_ivSize = 0;
_cipher = null;
_decipher = null;
get key() {
return this._key;
}
get iv() {
return this._iv;
}
static onCheckParams({ method = DEFAULT_METHOD }) {
if (typeof method !== 'string' || method === '') {
throw Error('\'method\' must be set');
}
const cipherNames = Object.keys(ciphers);
if (!cipherNames.includes(method)) {
throw Error(`'method' must be one of [${cipherNames}]`);
}
if (method === 'chacha20-ietf' && !process.version.startsWith('v10')) {
throw Error('require Node.js v10.x to run "chacha20-ietf"');
}
}
onInit({ method = DEFAULT_METHOD }) {
const [keySize, ivSize] = ciphers[method];
const iv = crypto.randomBytes(ivSize);
this._algorithm = method;
this._ivSize = ivSize;
this._key = EVP_BytesToKey(this._config.key, keySize, ivSize);
this._iv = iv;
if (this._algorithm.startsWith('rc4')) {
this._algorithm = 'rc4';
if (this._algorithm === 'rc4-md5-6') {
this._iv = this._iv.slice(0, 6);
}
}
if (this._algorithm === 'chacha20-ietf') {
this._algorithm = 'chacha20';
}
}
onDestroy() {
this._key = null;
this._iv = null;
this._cipher = null;
this._decipher = null;
}
createCipher(key, iv) {
const algorithm = this._algorithm;
let _key = key;
let _iv = iv;
if (algorithm === 'rc4') {
_key = hash('md5', Buffer.concat([_key, _iv]));
_iv = NOOP;
}
else if (algorithm === 'none') {
return {
update: (buffer) => buffer,
};
}
else if (algorithm === 'chacha20') {
// 4 bytes counter + 12 bytes nonce
_iv = Buffer.concat([Buffer.alloc(4), _iv]);
}
return crypto.createCipheriv(algorithm, _key, _iv);
}
createDecipher(key, iv) {
const algorithm = this._algorithm;
let _key = key;
let _iv = iv;
if (algorithm === 'rc4') {
_key = hash('md5', Buffer.concat([_key, _iv]));
_iv = NOOP;
}
else if (algorithm === 'none') {
return {
update: (buffer) => buffer,
};
}
else if (algorithm === 'chacha20') {
// 4 bytes counter + 12 bytes nonce
_iv = Buffer.concat([Buffer.alloc(4), _iv]);
}
return crypto.createDecipheriv(algorithm, _key, _iv);
}
// tcp
beforeOut({ buffer }) {
if (!this._cipher) {
this._cipher = this.createCipher(this._key, this._iv);
return Buffer.concat([this._iv, this._cipher.update(buffer)]);
} else {
return this._cipher.update(buffer);
}
}
beforeIn({ buffer, fail }) {
if (!this._decipher) {
const { _ivSize } = this;
if (buffer.length < _ivSize) {
return fail(`buffer is too short to get iv, len=${buffer.length} dump=${dumpHex(buffer)}`);
}
this._iv = buffer.slice(0, _ivSize);
this._decipher = this.createDecipher(this._key, this._iv);
return this._decipher.update(buffer.slice(_ivSize));
} else {
return this._decipher.update(buffer);
}
}
// udp
beforeOutUdp({ buffer }) {
this._iv = crypto.randomBytes(this._ivSize);
this._cipher = this.createCipher(this._key, this._iv);
return Buffer.concat([this._iv, this._cipher.update(buffer)]);
}
beforeInUdp({ buffer, fail }) {
const { _ivSize } = this;
if (buffer.length < _ivSize) {
return fail(`buffer is too short to get iv, len=${buffer.length} dump=${dumpHex(buffer)}`);
}
this._iv = buffer.slice(0, _ivSize);
this._decipher = this.createDecipher(this._key, this._iv);
return this._decipher.update(buffer.slice(_ivSize));
}
} |
JavaScript | class PlatformRef {
/**
* Creates an instance of an `@NgModule` for the given platform
* for offline compilation.
*
* ## Simple Example
*
* ```typescript
* my_module.ts:
*
* @NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* main.ts:
* import {MyModuleNgFactory} from './my_module.ngfactory';
* import {browserPlatform} from '@angular/platform-browser';
*
* let moduleRef = browserPlatform().bootstrapModuleFactory(MyModuleNgFactory);
* ```
*
* @experimental APIs related to application bootstrap are currently under review.
*/
bootstrapModuleFactory(moduleFactory) {
throw unimplemented();
}
/**
* Creates an instance of an `@NgModule` for a given platform using the given runtime compiler.
*
* ## Simple Example
*
* ```typescript
* @NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* let moduleRef = browserPlatform().bootstrapModule(MyModule);
* ```
* @stable
*/
bootstrapModule(moduleType, compilerOptions = []) {
throw unimplemented();
}
/**
* Retrieve the platform {@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton providers.
*/
get injector() { throw unimplemented(); }
;
/**
* @deprecated Use `destroyed` instead
*/
get disposed() { throw unimplemented(); }
get destroyed() { throw unimplemented(); }
} |
JavaScript | class ApplicationRef {
/**
* Retrieve the application {@link Injector}.
*
* @deprecated inject an {@link Injector} directly where needed or use {@link
* NgModuleRef}.injector.
*/
get injector() { return unimplemented(); }
;
/**
* Retrieve the application {@link NgZone}.
*
* @deprecated inject {@link NgZone} instead of calling this getter.
*/
get zone() { return unimplemented(); }
;
/**
* Get a list of component types registered to this application.
* This list is populated even before the component is created.
*/
get componentTypes() { return unimplemented(); }
;
/**
* Get a list of components registered to this application.
*/
get components() { return unimplemented(); }
;
} |
JavaScript | class Piatto {
constructor(id, code, nome, prezzo, calorie, note, imgPath, section, tipo) {
this.id = id;
this.code = code;
this.nome = nome;
this.prezzo = prezzo;
this.calorie = calorie;
this.note = note;
this.imgPath = imgPath;
this.section = section;
this.tipo = tipo;
}
toString() {
return "[" + this.id + ", " +
this.code + ", " +
this.nome + ", " +
this.prezzo + ", " +
this.calorie + ", " +
this.note + ", " +
this.imgPath + ", " +
this.section + ", " +
this.tipo + "]";
}
toJSON() {
return {
id: this.id,
code: this.code,
nome: this.nome,
prezzo: this.prezzo,
calorie: this.calorie,
note: this.note,
imgPath: this.imgPath,
section: this.section,
tipo: this.tipo
}
}
} |
JavaScript | class ControlObject{
constructor(canvas,x,y,w,h){
this.xMouse = 0;
this.yMouse = 0;
this.xMouseStart = 0;
this.yMouseStart = 0;
this.mouseDown = false;
// this.w & this.h is used to calcuate the dragging boxes
this.w = 0;
this.h = 0;
// this.(x,y,w,h)Boundary is used for the Boundary in the rectangle
this.xBoundary = x;
this.yBoundary = y;
this.wBoundary = w;
this.hBoundary = h;
// 'addEventListener' - is there mouse movement
this.element = canvas;
this.element.addEventListener('mousedown', this.mDown.bind(this));
this.element.addEventListener('mousemove', this.mMove.bind(this));
this.element.addEventListener('mouseup', this.mUp.bind(this));
// need a list to hold all of the rectangles that get made
this.object_set = [];
// the default for when the mouse is in the bounds (rectangle)
this.inBounds = false;
this.drag = false;
}
// When the mouse is being pressed 'down'.
mDown(e){
console.log("control object down");
// e.offset X or Y is where ever the mouse is clicking on the canvas
this.xMouseStart = e.offsetX;
this.yMouseStart = e.offsetY;
// the boundary of the background rectangle
this.inBounds = this.inBoundsCheck(this.xMouse, this.yMouse, this.xBoundary, this.yBoundary, this.wBoundary, this.hBoundary);
// if the mouse pushes down inside the bounds, the red line appears - which allows the user to draw the rectangle
if(this.inBounds == true){
this.drag = true;
}
// if the mouse pushes down outside of the bounds, the red line would not appear
else{
this.drag = false;
}
}
// When the mouse is moving within the canvas
mMove(e){
this.xMouse = e.offsetX;
this.yMouse = e.offsetY;
}
// creating the boundary, where the mouse can be clicked or not clicked
inBoundsCheck(xM, yM, x, y, w, h){
// if the mouse clicks in the rectangle - it's either true or false
if(xM > x && xM < x+w && yM > y && yM < y+h){
return true;
}
else{
return false;
}
}
// When the mouse releases from the mouse pad, so your finger is being lifted up
mUp(e){
console.log("mouse up control");
// drawing the different shapes
if(this.drag == true){
// Rectangle
if(Buttons.shape_name == "Rectangle"){
var temp = new Rectangle(this.xMouseStart, this.yMouseStart, this.w, this.h, Colourgrid.colours);
this.object_set.push(temp);
}
// Ellipse
else if(Buttons.shape_name == "Ellipse"){
var temp = new Ellipse(this.xMouseStart, this.yMouseStart, this.w, this.h, Colourgrid.colours);
this.object_set.push(temp);
}
// Star
else if(Buttons.shape_name == "Star"){
var temp = new Star(this.xMouseStart, this.yMouseStart, this.w, this.h, 5, Colourgrid.colours);
this.object_set.push(temp);
}
// Hexagon
else if(Buttons.shape_name == "Hexagon"){
var temp = new Hexagon(this.xMouseStart, this.yMouseStart, this.w, this.h, 6, Colourgrid.colours);
this.object_set.push(temp);
}
// Line
else if(Buttons.shape_name == "Line"){
var temp = new Line(this.xMouseStart, this.yMouseStart, this.xMouse, this.yMouse, 3, Colourgrid.colours);
this.object_set.push(temp);
console.log(this.xMouseStart,this.yMouseStart,this.xMouse,this.yMouse);
}
this.drag = false;
}
else{
this.drag = false;
}
}
// Just a background rectangle (where it can draw) printed on the page
backgroundRect(x, y, w, h){
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fillStyle = "rgb(162, 177, 184)";
ctx.fill();
}
// Shows the outline of the canvas when the mouse is dragging
drawRect(x, y, w, h){
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.lineWidth = 1;
ctx.strokeStyle = "rgb(78, 105, 120)";
ctx.stroke();
}
// the draw function - just moved it so now the code to this.draw in the update function
draw(){
}
// update function
update(){
// Clearing the canvas
if(Buttons.shape_name == "Clear"){
this.object_set = [];
Buttons.shape_name = "";
}
// Undoing what was made on the canvas
else if(Buttons.shape_name == "Undo"){
this.object_set.pop();
Buttons.shape_name = "";
}
ctx.save();
this.backgroundRect(this.xBoundary, this.yBoundary, this.wBoundary, this.hBoundary);
ctx.clip();
// for loop - goes through the object_set list and prints out every rectangle the user wants to draw
for(let i = 0; i < this.object_set.length; i++){
this.object_set[i].update();
}
ctx.restore();
// finds out what the width and height measurements are, using xMouse/yMouse and the 2 startpoints
this.w = this.xMouse - this.xMouseStart;
this.h = this.yMouse - this.yMouseStart;
if(this.drag){
this.draw(this.drawRect(this.xMouseStart, this.yMouseStart, this.w, this.h));
}
}
} |
JavaScript | class PartnerPaginationResult {
/**
* Constructs a new <code>PartnerPaginationResult</code>.
* @alias module:model/PartnerPaginationResult
* @class
*/
constructor() {
}
/**
* Constructs a <code>PartnerPaginationResult</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/PartnerPaginationResult} obj Optional instance to populate.
* @return {module:model/PartnerPaginationResult} The populated <code>PartnerPaginationResult</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PartnerPaginationResult();
if (data.hasOwnProperty('limit'))
obj.limit = ApiClient.convertToType(data['limit'], 'Number');
if (data.hasOwnProperty('offset'))
obj.offset = ApiClient.convertToType(data['offset'], 'Number');
if (data.hasOwnProperty('entryCount'))
obj.entryCount = ApiClient.convertToType(data['entryCount'], 'Number');
if (data.hasOwnProperty('maxEntryCount'))
obj.maxEntryCount = ApiClient.convertToType(data['maxEntryCount'], 'Number');
if (data.hasOwnProperty('entries'))
obj.entries = ApiClient.convertToType(data['entries'], [Partner]);
}
return obj;
}
} |
JavaScript | class User {
constructor(name, email, password){
this.name = name;
this.email = name;
this.password = password;
}
register(){
console.log(this.name + "User registered");
}
static countUsers() {
console.log("There are 100 Users");
}
} |
JavaScript | class Package extends User{
constructor(name, email, password, packageId){
super(name, password, packageId);
this.packageId = packageId;
}
getuser(){
console.log(this.name + " User has package: " + this.packageId);
}
} |
JavaScript | class TestClass {
/**
* Constructor allowing to provide an existing registry
*
* @param {Object} registry
*/
constructor (registry = {}) {
this._registry = registry
this._callbacks = new Map()
}
getRegistry () {
return this._registry
}
hasEntry (category) {
return this._registry[category] !== undefined
}
/**
* A free code block should not harm
*/
/**
* Allows to register a notification callback
*
* @param {function(Object)} callback A callback notifying whenever a new
* entry is available
*/
notifyOnNew (callback) {
this._callbacks.set('new', callback)
}
notifyOnRemoved (callback) {
this._callbacks.set('removed', callback)
}
addEntry (category, entry) {
const entries = this._registry[category]
if (entries) entries.push(entry)
else {
this._registry[category] = [entry]
const callback = this._callbacks.get('new')
if (callback) callback(entry)
}
}
removeEntry (category) {
if (!this.hasEntry(category)) {
throw new Error('Can not remove non-existing entry')
}
const entries = this._registry[category]
const entry = entries.pop()
if (entries.length === 0) {
const callback = this._callbacks.get('removed')
if (callback) callback(entry)
delete this._registry[category]
}
return entry
}
/**
* Waits the configured amount of time and then returns.
*
* @param {number} ms Time to wait
* @returns {number} The time this function waited for
*
*/
async waitForMe (ms = 100) {
await new Promise(resolve => setTimeout(resolve, ms))
return ms
}
async callMeBackLater (callback, ms = 100) {
await new Promise(resolve => setTimeout(resolve, ms))
callback(ms)
}
async willThrowLater () {
await new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Some test error'), 100))
})
}
static crazy (who = undefined) {
if (who === undefined) {
return 'who is crazy?'
}
return `${who} is crazy!`
}
static async promisedEcho (message) {
await new Promise(resolve => setTimeout(resolve, 100))
return message
}
} |
JavaScript | class DeployGnosisSafeMultiSigMaster {
/**
* Constructor for Gnosis-Safe Multi-sig deployment
*
* @param {Object} params
* @param {String} params.tokenId: tokenId
* @param {String} params.auxChainId: auxChainId for which token rules needs be deployed.
* @param {String} params.pendingTransactionExtraData: extraData for pending transaction.
*
* @constructor
*/
constructor(params) {
const oThis = this;
oThis.tokenId = params.tokenId;
oThis.auxChainId = params['auxChainId'];
oThis.pendingTransactionExtraData = params['pendingTransactionExtraData'];
oThis.gasPrice = null;
oThis.chainEndpoint = null;
oThis.auxWeb3Instance = null;
oThis.configStrategyObj = null;
oThis.auxDeployerAddress = null;
}
/**
* Performer
*
* @return {Promise<result>}
*/
perform() {
const oThis = this;
return oThis._asyncPerform().catch(function(error) {
if (responseHelper.isCustomResult(error)) {
return error;
} else {
logger.error(`${__filename}::perform::catch`);
logger.error(error);
return responseHelper.error({
internal_error_identifier: 'l_s_e_dtr_1',
api_error_identifier: 'unhandled_catch_response',
debug_options: { error: error.toString() }
});
}
});
}
/**
* Async performer
*
* @private
*
* @return {Promise<result>}
*/
async _asyncPerform() {
const oThis = this;
await oThis._initializeVars();
await oThis._getAuxDeployerAddr();
await oThis._setWeb3Instance();
const submitTxRsp = await oThis._deployContract();
return Promise.resolve(
responseHelper.successWithData({
taskStatus: workflowStepConstants.taskPending,
transactionHash: submitTxRsp.data['transactionHash'],
debugParams: {
auxDeployerAddress: oThis.auxDeployerAddress
}
})
);
}
/**
* Initialize required variables.
*
* @private
*/
async _initializeVars() {
const oThis = this;
oThis.chainEndpoint = oThis._configStrategyObject.chainRpcProvider(oThis.auxChainId, 'readWrite');
oThis.gasPrice = contractConstants.auxChainGasPrice;
}
/**
* Get Aux Deployer address from chain_addresses table
*
* @private
*
* @return {Promise}
*/
async _getAuxDeployerAddr() {
const oThis = this;
// Fetch all addresses associated with given aux chain id.
const chainAddressCache = new ChainAddressCache({ associatedAuxChainId: oThis.auxChainId }),
chainAddressCacheRsp = await chainAddressCache.fetch();
if (chainAddressCacheRsp.isFailure() || !chainAddressCacheRsp.data) {
return Promise.reject(chainAddressCacheRsp);
}
oThis.auxDeployerAddress = chainAddressCacheRsp.data[chainAddressConstants.auxDeployerKind].address;
}
/**
* set Web3 Instance
*
* @return {Promise<void>}
*/
async _setWeb3Instance() {
const oThis = this;
oThis.auxWeb3Instance = web3Provider.getInstance(oThis.chainEndpoint).web3WsProvider;
}
/**
* Deploy contract
*
* @returns {Promise<*>}
*
* @private
*/
async _deployContract() {
const oThis = this;
let OpenSTJsUserSetup = OpenSTJs.Setup.User,
openSTJsUserSetupHelper = new OpenSTJsUserSetup(oThis.auxWeb3Instance);
let txOptions = {
from: oThis.auxDeployerAddress,
gasPrice: oThis.gasPrice,
gas: contractConstants.deployGnosisSafeMultiSigMasterGas,
value: contractConstants.zeroValue
};
let txObject = await openSTJsUserSetupHelper._deployMultiSigMasterCopyRawTx();
txOptions['data'] = txObject.encodeABI();
const submitTxRsp = await new SubmitTransaction({
chainId: oThis.auxChainId,
tokenId: oThis.tokenId,
pendingTransactionKind: pendingTransactionConstants.deployGnosisSafeMultiSigMasterCopyKind,
provider: oThis.chainEndpoint,
txOptions: txOptions,
options: oThis.pendingTransactionExtraData
}).perform();
if (submitTxRsp && submitTxRsp.isFailure()) {
return Promise.reject(submitTxRsp);
}
return Promise.resolve(submitTxRsp);
}
/***
* Config strategy
*
* @return {Object}
*/
get _configStrategy() {
const oThis = this;
return oThis.ic().configStrategy;
}
/**
* Object of config strategy class
*
* @return {Object}
*/
get _configStrategyObject() {
const oThis = this;
if (oThis.configStrategyObj) return oThis.configStrategyObj;
oThis.configStrategyObj = new ConfigStrategyObject(oThis._configStrategy);
return oThis.configStrategyObj;
}
} |
JavaScript | class DbUtils {
// exemple: insertDaata('test', 'YEVHEN');
static async insert(key, data) {
try {
await AsyncStorage.setItem(key.toString(), data);
console.log(`write data successful \'${key}\'`);
console.log(data);
} catch (error) {
console.log(error);
console.warn(`error while WRITHING data with \'${key}\'`);
}
}
// exemple: const val = await readData('test');
// if not exist return null
static async read(key) {
try {
// await AsyncStorage.clear();
const value = await AsyncStorage.getItem(key.toString());
// console.log(`read successful \'${key}\'`);
// console.log(value);
return value;
} catch (error) {
console.log(error);
console.warn(`error while READ data with \'${key}\'`);
}
}
static remove(key) {
AsyncStorage.removeItem(key.toString(), err => {
if (err) console.warn(`error while REMOVING data with \'${key}\'`, err);
else console.log(`remove successful \'${key}\'`);
});
}
// exemple: DbUtils.insertJson('test', {age: 25}');
static async insertJson(key, data) {
await this.insert(key, JSON.stringify(data));
}
static async readJson(key) {
let res = await this.read(key);
return JSON.parse(res);//if not exist return null
}
} |
JavaScript | class Call {
/**
* Prepares a call which will call the given callback from the handle()
* method.
*
* @template T
* @param {function(?T, string=)=} callback Callback to call. If empty, the
* request will run in synchronous mode.
* @param {number=} retries Overrides the default number of retries.
*/
constructor(callback, retries) {
apiclient.initialize();
this.callback = callback;
this.requestService = new EERequestService(!callback, retries);
}
/**
* Wraps a promise returned by an API call, to call the configured callback.
* Also handles the "fake promise" returned in synchronous mode.
*
* @template T
* @param {!Promise<T>} response
* @return {!T|!Promise<T>} Immediate value in sync mode (constructor called
* without callback), and otherwise a promise which will resolve to the
* value.
*/
handle(response) {
if (response instanceof Promise) {
// Async mode: invoke the callback with the result of the promise.
if (this.callback) {
response.then((result) => this.callback(result)).catch(
// Any errors from the then clause will also be passed to the catch.
(error) => this.callback(undefined, /** @type {string} */(error)));
}
// We should not be running in async mode without a callback, but it is
// still useful to return the promise.
} else {
// Sync mode: convert the fake "instant" promise to actual result.
response.then((result) => { response = result; });
}
return response;
}
/**
* Gets the currently active projects path. This is a method on Call, to
* ensure that initialize() has already been called.
* @return {string}
*/
projectsPath() {
return 'projects/' + apiclient.getProject();
}
// Helper methods to construct the generated api client handlers.
algorithms() {
return new api.ProjectsAlgorithmsApiClientImpl(
VERSION, this.requestService);
}
projects() {
return new api.ProjectsApiClientImpl(
VERSION, this.requestService);
}
assets() {
return new api.ProjectsAssetsApiClientImpl(
VERSION, this.requestService);
}
operations() {
return new api.ProjectsOperationsApiClientImpl(
VERSION, this.requestService);
}
value() {
return new api.ProjectsValueApiClientImpl(VERSION, this.requestService);
}
maps() {
return new api.ProjectsMapsApiClientImpl(VERSION, this.requestService);
}
map() {
return new api.ProjectsMapApiClientImpl(VERSION, this.requestService);
}
image() {
return new api.ProjectsImageApiClientImpl(VERSION, this.requestService);
}
table() {
return new api.ProjectsTableApiClientImpl(VERSION, this.requestService);
}
video() {
return new api.ProjectsVideoApiClientImpl(VERSION, this.requestService);
}
thumbnails() {
return new api.ProjectsThumbnailsApiClientImpl(
VERSION, this.requestService);
}
videoThumbnails() {
return new api.ProjectsVideoThumbnailsApiClientImpl(
VERSION, this.requestService);
}
filmstripThumbnails() {
return new api.ProjectsFilmstripThumbnailsApiClientImpl(
VERSION, this.requestService);
}
} |
JavaScript | class EERequestService extends PromiseRequestService {
/**
* @param {boolean=} sync Run XmlHttpRequests in sync mode. This blocks the
* main browser thread but is needed for legacy compatibility.
* @param {number=} retries Overrides the default max retries value.
*/
constructor(sync = false, retries = undefined) {
super();
this.sync = sync;
if (retries != null) {
this.retries = retries;
} else if (sync) {
this.retries = apiclient.MAX_SYNC_RETRIES_;
} else {
this.retries = apiclient.MAX_ASYNC_RETRIES_;
}
}
/**
* Implements the JSON RPC using the logic in apiclient.send().
* Handles both sync and async cases. In sync mode the returned promise will
* resolve immediately: this is unwrapped by Call.handle() above.
*
* @template T
* @param {!MakeRequestParams} params Provided by the autogenerated client.
* @param {!SerializableCtor<T>=} responseCtor Also provided by the generated
* code. Will be a constructor for one of the ee.api.* response objects,
* which builds a Serializable type from a raw js object.
* @return {!Promise<T>}
* @override
*/
send(params, responseCtor = undefined) {
// Standard TS API Client preprocessing to drop undefined queryParams.
processParams(params);
const path = params.path || '';
const url = apiclient.getSafeApiUrl() + path;
const args = apiclient.makeRequest_(params.queryParams || {});
const body = params.body ? JSON.stringify(params.body) : undefined;
if (this.sync) {
const raw = apiclient.send(
url, args, undefined, params.httpMethod, body, this.retries);
const value = responseCtor ? deserialize(responseCtor, raw) : raw;
// Converts a value into an "instant" promise, with a then method that
// immediately applies a function and builds a new thenable of the result.
// Any errors will be thrown back to the original caller synchronously.
const thenable = (v) => ({'then': (f) => thenable(f(v))});
return /** @type {!Promise<T>} */(thenable(value));
}
const value = new Promise((resolve, reject) => {
const resolveOrReject = (value, error = undefined) => {
if (error) {
reject(error);
} else {
resolve(value);
}
};
apiclient.send(
url, args, resolveOrReject, params.httpMethod, body, this.retries);
});
return value.then(r => responseCtor ? deserialize(responseCtor, r) : r);
}
/** @override abstract method, not used */ makeRequest(params) {}
} |
JavaScript | class BatchCall extends Call {
/**
* Prepares a batch handler which will call the given callback when send()
* completes.
*/
constructor(callback) {
super(callback);
this.requestService = new BatchRequestService();
}
/**
* Constructs a batch request from the part bodies, and calls getResponse
* on the final composite response, providing a dictionary keyed by
* part name. An error will be thrown (or passed to the callback) if any part
* has an error; successful responses will still be passed to the callback
* even if there is an error.
*
* See https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
*
* @param {!Array<!Array<?>>} parts Array of [id, [body, ctor]] tuples. ID is
* a caller-determined ID for each part, and [body, ctor] should be created
* by calling BatchRequestService.send().
* @param {function(!Object):T=} getResponse Optional post-processing step to
* transform the object of ID-keyed responses before calling the callback.
* @return {?T} payload or null if callback is given.
* @template T
*/
send(parts, getResponse) {
const batchUrl = apiclient.getSafeApiUrl() + '/batch';
const boundary = 'batch_EARTHENGINE_batch';
const multipart = `multipart/mixed; boundary=${boundary}`;
const headers = 'Content-Type: application/http\r\n' +
'Content-Transfer-Encoding: binary\r\nMIME-Version: 1.0\r\n';
const build = ([id, [partBody, ctor]]) =>
`--${boundary}\r\n${headers}Content-ID: <${id}>\r\n\r\n${partBody}\r\n`;
const body = parts.map(build).join('') + `--${boundary}--\r\n`;
const deserializeResponses = (response) => {
const result = {};
parts.forEach(([id, [partBody, ctor]]) => {
if (response[id] != null) {
result[id] = deserialize(ctor, response[id]);
}
});
return getResponse ? getResponse(result) : result;
};
if (this.callback) {
const callback = (result, err = undefined) =>
this.callback(err ? result : deserializeResponses(result), err);
apiclient.send(batchUrl, null, callback, multipart, body);
return null;
}
return deserializeResponses(
apiclient.send(batchUrl, null, undefined, multipart, body));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.