hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
3b56329b12523b3325f0c4c0f41bfd9e023cd7c7
196
js
JavaScript
examples/myo-sdk/docs/dir_3359102819577079ef2a091831795c53.js
RevanthK/MyoGestureML
8352e60f3928ce24e6985f30b666e97545c70ec1
[ "MIT" ]
null
null
null
examples/myo-sdk/docs/dir_3359102819577079ef2a091831795c53.js
RevanthK/MyoGestureML
8352e60f3928ce24e6985f30b666e97545c70ec1
[ "MIT" ]
null
null
null
examples/myo-sdk/docs/dir_3359102819577079ef2a091831795c53.js
RevanthK/MyoGestureML
8352e60f3928ce24e6985f30b666e97545c70ec1
[ "MIT" ]
null
null
null
var dir_3359102819577079ef2a091831795c53 = [ [ "cxx", "dir_888ff478648cd2fe655e4e038da097da.html", "dir_888ff478648cd2fe655e4e038da097da" ], [ "myo.hpp", "_myo_8hpp_source.html", null ] ];
39.2
99
0.755102
3b5639a772323d151c8c1bda0d53d31d297b3158
36,663
js
JavaScript
addon/record-data.js
betocantu93/ember-m3
f2575728033a322d0e9718ad2746fd38334a3b9d
[ "MIT" ]
null
null
null
addon/record-data.js
betocantu93/ember-m3
f2575728033a322d0e9718ad2746fd38334a3b9d
[ "MIT" ]
null
null
null
addon/record-data.js
betocantu93/ember-m3
f2575728033a322d0e9718ad2746fd38334a3b9d
[ "MIT" ]
null
null
null
import { isEqual, isNone } from '@ember/utils'; import { dasherize } from '@ember/string'; import { assign } from '@ember/polyfills'; import { copy } from './utils/copy'; import { assert } from '@ember/debug'; import Ember from 'ember'; import { recordDataToRecordMap, recordDataToQueryCache } from './utils/caches'; import { computeNestedModel, computeAttribute } from './utils/resolve'; import { CUSTOM_MODEL_CLASS } from 'ember-m3/-infra/features'; import { schemaTypesInfo, NESTED, REFERENCE, MANAGED_ARRAY } from './utils/schema-types-info'; function pushDataAndNotify(recordData, updates) { recordData.pushData({ attributes: updates }, true, true); } function commitDataAndNotify(recordData, updates) { recordData.didCommit({ attributes: updates }, true); } function notifyProperties(storeWrapper, modelName, id, clientId, changedKeys) { Ember.beginPropertyChanges(); for (let i = 0; i < changedKeys.length; i++) { storeWrapper.notifyPropertyChange(modelName, id, clientId, changedKeys[i]); } Ember.endPropertyChanges(); } /** * A public interface for getting and setting attribute of the underlying * recordData, and track dependent keys resolved by ref key. * * @class M3SchemaInterface */ class M3SchemaInterface { /** * @param {M3RecordData} recordData */ constructor(recordData) { this.recordData = recordData; this._keyBeingResolved = null; this._refKeyDepkeyMap = {}; this._suppressNotifications = false; } /** * Mark the passed in object as a nested m3 model * @param {Object} object */ nested(object) { schemaTypesInfo.set(object, NESTED); return object; } /** * Mark the passed in object as a reference to a m3 or ember data model * @param {Object} object */ reference(object) { schemaTypesInfo.set(object, REFERENCE); return object; } /** * Mark the passed in object as a m3 managed array that contains * either references, nested models or raw values. You need to * mark each individual object in the array as well. * @param {Object} object */ managedArray(object) { schemaTypesInfo.set(object, MANAGED_ARRAY); return object; } /** * @param {string} key * @private */ _beginDependentKeyResolution(key) { assert( 'Do not invoke `SchemaInterface` method `_beginDependentKeyResolution` without ending the resolution of previous key.', this._keyBeingResolved === null ); this._keyBeingResolved = key; } /** * @param {string} key * @private */ _endDependentKeyResolution(key) { assert( 'Do not invoke `SchemaInterface` method `_endDependentKeyResolution` without begining the resolution of the key.', key && this._keyBeingResolved === key ); this._keyBeingResolved = null; } _getDependentResolvedKeys(refKey) { return this._refKeyDepkeyMap[refKey]; } /** * Get the attribute name from the model. * This can be useful if your payload keys are different from your attribute names; * e.g. if your api adds a prefix to attributes that should be interpreted as references. * * @param {string} name name of the attribute * @returns {Object} value of the attribute */ getAttr(name) { let value = this.recordData.getAttr(name); const keyBeingResolved = this._keyBeingResolved; assert( 'Do not manually call methods on `schemaInterface` outside of schema resolution hooks such as `computeAttributeReference`', keyBeingResolved ); if (keyBeingResolved !== name) { // it might be nice to avoid doing this if we know that we don't need to // support depkeys from the server changing between requests this._refKeyDepkeyMap[name] = this._refKeyDepkeyMap[name] || []; let refKeyMap = this._refKeyDepkeyMap[name]; if (refKeyMap.indexOf(keyBeingResolved) < 0) { refKeyMap.push(this._keyBeingResolved); } } return value; } /** * Set attribute for the recordData * * @param {string} key * @param {Object} value */ setAttr(key, value) { this.recordData.setAttr(key, value, this._suppressNotifications); } /** * Delete attribute for the record data * * @param {string} attrName name of the attribute to delete */ deleteAttr(attrName) { this.recordData._deleteAttr(attrName); } } export default class M3RecordData { /** * @param {string} modelName * @param {string} id * @param {number} [clientId] * @param {Store} storeWrapper * @param {SchemaManager} schemaManager * @param {M3RecordData} [parentRecordData] * @param {M3RecordData} [baseRecordData] */ constructor( modelName, id, clientId, storeWrapper, schemaManager, parentRecordData, baseRecordData, globalM3CacheRD ) { this.modelName = modelName; this.clientId = clientId; this.id = id; this.storeWrapper = storeWrapper; if (CUSTOM_MODEL_CLASS) { this.globalM3CacheRD = globalM3CacheRD; if (!baseRecordData && !parentRecordData && id) { this.globalM3CacheRD[this.id] = this; } this._isNew = false; this._isDeleted = false; this._isLoaded = false; this._isDeletionCommited = false; } else { this._embeddedInternalModel = null; } this.isDestroyed = false; this._data = null; this._attributes = null; this.__inFlightAttributes = null; // Properties related to child recordDatas this._parentRecordData = parentRecordData; this.__childRecordDatas = null; this._schema = schemaManager; this.schemaInterface = new M3SchemaInterface(this); // Properties related to projections this._baseRecordData = baseRecordData; this._projections = null; this._initBaseRecordData(); } get _recordArrays() { if (!this.__recordArrays) { this.__recordArrays = new Set(); } return this.__recordArrays; } // PUBLIC API getResourceIdentifier() { return { id: this.id, type: this.modelName, clientId: this.clientId, }; } /** * Notify this `RecordData` that it has new attributes from the server. * * @param {Object} jsonApiResource the payload resource to use for updating * the server attributes * @param {boolean} calculateChange Whether or not changes that result from * this resource being pushed should be calculated. * @param {boolean} [notifyRecord=false] * @params {boolean} [suppressProjectionNotifications=false] * @returns {Array<string>} The list of changed keys if `calculateChange * === true` and `[]` otherwise. */ pushData( jsonApiResource, calculateChange, notifyRecord = false, suppressProjectionNotifications = false ) { if (CUSTOM_MODEL_CLASS) { this._isLoaded = true; } if (this._baseRecordData) { this._baseRecordData.pushData( jsonApiResource, calculateChange, notifyRecord, suppressProjectionNotifications ); // we don't need to return any changed keys, because properties will be invalidated // as part of notifying all projections return []; } let changedKeys; if (jsonApiResource.attributes) { changedKeys = this._mergeUpdates( jsonApiResource.attributes, pushDataAndNotify, // if we need to notify the record, we must calculate the changes calculateChange || notifyRecord || !!this._projections ); changedKeys = this._filterChangedKeys(changedKeys); } if (this.__attributes !== null) { // only do if we have attribute changes this._updateChangedAttributes(); } if (jsonApiResource.id) { // TODO Which cases do we need to initialize the id here? this.id = jsonApiResource.id + ''; } if (CUSTOM_MODEL_CLASS) { if (!this._baseRecordData && !this._parentRecordData && this.id) { this.globalM3CacheRD[this.id] = this; } } // by default, always notify projections when we receive data. We might // not have been asked to calculate changes if the base record data has // no record, but we might still have records instantiated for our // projections. // // Notifications are explicitly suppressed when we're using `pushData` // synthetically while resolving nested record data if (!suppressProjectionNotifications && this._notifyProjectionProperties(changedKeys)) { return []; } if (notifyRecord) { this._notifyRecordProperties(changedKeys); } return changedKeys || []; } willCommit() { if (this._baseRecordData) { return this._baseRecordData.willCommit(); } this._inFlightAttributes = this._attributes; this._attributes = null; if (this.__childRecordDatas) { let nestedKeys = Object.keys(this._childRecordDatas); for (let i = 0; i < nestedKeys.length; ++i) { let childKey = nestedKeys[i]; let childRecordData = this._childRecordDatas[childKey]; if (!Array.isArray(childRecordData)) { childRecordData.willCommit(); } else { childRecordData.forEach((child) => child.willCommit()); } } } } hasChangedAttributes() { if (this._baseRecordData) { return this._baseRecordData.hasChangedAttributes(); } else { let isDirty = this.__attributes !== null && Object.keys(this.__attributes).length > 0; if (isDirty) { return true; } let recordDatas = Object.keys(this._childRecordDatas).map( (key) => this._childRecordDatas[key] ); recordDatas.forEach((child) => { if (!Array.isArray(child)) { if (child.hasChangedAttributes()) { isDirty = true; } } else { isDirty = isDirty || child.some((rd) => rd.hasChangedAttributes()); } }); return isDirty; } } addToHasMany() {} removeFromHasMany() {} _initRecordCreateOptions(options) { return options !== undefined ? options : {}; } didCommit(jsonApiResource, notifyRecord = false) { if (CUSTOM_MODEL_CLASS) { this._isNew = false; if (this._isDeleted) { this._isDeletionCommited = true; this.removeFromRecordArrays(); } } if (jsonApiResource && jsonApiResource.id) { this.id = '' + jsonApiResource.id; } if (CUSTOM_MODEL_CLASS) { if (!this._baseRecordData && !this._parentRecordData && this.id) { this.globalM3CacheRD[this.id] = this; } } if (!this._parentRecordData) { // only set the record ID if it is a top-level recordData this.storeWrapper.setRecordId(this.modelName, this.id, this.clientId); } if (this._baseRecordData) { this._baseRecordData.didCommit(jsonApiResource, notifyRecord); // we don't need to return any changed keys, because properties will be invalidated // as part of notifying all projections return []; } // If the server returns a payload let attributes; if (jsonApiResource) { attributes = jsonApiResource.attributes; } // We need to sync nested models in case of partial updates from server and local. this._syncNestedModelUpdates(attributes); assign(this._data, this._inFlightAttributes); this._inFlightAttributes = null; let changedKeys; changedKeys = this._mergeUpdates(attributes, commitDataAndNotify, true); changedKeys = this._filterChangedKeys(changedKeys); // At this point, all of the nestedModels has been updated, so we can add their updates to the current model's data. this._mergeNestedModelData(); this._updateChangedAttributes(); if (this._notifyProjectionProperties(changedKeys)) { return []; } if (CUSTOM_MODEL_CLASS) { this._notifyRecordProperties(changedKeys); } else { if (notifyRecord) { this._notifyRecordProperties(changedKeys); } } return changedKeys || []; } getHasMany() {} setHasMany() {} commitWasRejected() { if (this._baseRecordData) { return this._baseRecordData.commitWasRejected(); } let keys = Object.keys(this._inFlightAttributes); if (keys.length > 0) { let attrs = this._attributes; for (let i = 0; i < keys.length; i++) { if (attrs[keys[i]] === undefined) { attrs[keys[i]] = this._inFlightAttributes[keys[i]]; } } } this._inFlightAttributes = null; if (this.__childRecordDatas) { let nestedKeys = Object.keys(this._childRecordDatas); for (let i = 0; i < nestedKeys.length; ++i) { let childKey = nestedKeys[i]; let childRecordDatas = this._childRecordDatas[childKey]; if (Array.isArray(childRecordDatas)) { for (let j = 0; j < childRecordDatas.length; ++j) { childRecordDatas[j].commitWasRejected(); } } else { childRecordDatas.commitWasRejected(); } } } } getBelongsTo() {} setBelongsTo() {} /** * @param {string} key * @param {Object} value * @param {boolean} _suppressNotifications * @private */ setAttr(key, value, _suppressNotifications) { if (this._baseRecordData) { return this._baseRecordData.setAttr(key, value, _suppressNotifications); } let originalValue; if (key in this._inFlightAttributes) { originalValue = this._inFlightAttributes[key]; } else { originalValue = this._data[key]; } // If we went back to our original value, we shouldn't keep the attribute around anymore if (value === originalValue) { delete this._attributes[key]; } else { // Add the new value to the changed attributes hash this._attributes[key] = value; } if (!_suppressNotifications && !this._notifyProjectionProperties([key])) { this._notifyRecordProperties([key]); } } isNew() { return this._isNew; } setIsDeleted(value) { this._isDeleted = value; } isDeleted() { return this._isDeleted; } isDeletionCommitted() { return this._isDeletionCommited; } /** * @param {string} key * @private */ getAttr(key) { if (this._baseRecordData) { return this._baseRecordData.getAttr(key); } else if (key in this._attributes) { return this._attributes[key]; } else if (key in this._inFlightAttributes) { return this._inFlightAttributes[key]; } else { return this._data[key]; } } /** * @param {string} key * @private */ _deleteAttr(key) { if (this._baseRecordData) { return this._baseRecordData._deleteAttr(key); } else { delete this._attributes[key]; delete this._data[key]; } } /** * @param {string} key * @returns {boolean} */ hasAttr(key) { if (this._baseRecordData) { return this._baseRecordData.hasAttr(key); } else { return key in this._attributes || key in this._inFlightAttributes || key in this._data; } } /** * @param {string} key * @returns {boolean} */ hasLocalAttr(key) { if (this._baseRecordData) { return this._baseRecordData.hasLocalAttr(key); } else { return key in this._attributes; } } /** * @param {string} key * @returns {boolean} */ getServerAttr(key) { if (this._baseRecordData) { return this._baseRecordData.getServerAttr(key); } else { return this._data[key]; } } unloadRecord() { if (CUSTOM_MODEL_CLASS) { delete this.globalM3CacheRD[this.id]; } if (this.isDestroyed) { return; } if (CUSTOM_MODEL_CLASS) { this.removeFromRecordArrays(); let queryCache = recordDataToQueryCache.get(this); let record = recordDataToRecordMap.get(this); if (record) { queryCache.unloadRecord(record); } } if (this._baseRecordData || this._areAllProjectionsDestroyed()) { this._destroy(); } } removeFromRecordArrays() { if (CUSTOM_MODEL_CLASS) { this._recordArrays.forEach((recordArray) => { recordArray._removeRecordData(this); }); } } /** * @returns {boolean} */ isRecordInUse() { return this.storeWrapper.isRecordInUse(this.modelName, this.id, this.clientId); } removeFromInverseRelationships() {} clientDidCreate() { if (CUSTOM_MODEL_CLASS) { this._isLoaded = true; this._isNew = true; } } // INTERNAL API /** * Iterates through the attributes in-flight attrs and data of the model, * calling the passed function. * * @param {Function} callback * @param {*} binding */ eachAttribute(callback, binding) { if (this._baseRecordData) { return this._baseRecordData.eachAttribute(callback, binding); } let attrs = {}; if (this.__attributes !== null) { Object.keys(this._attributes).forEach((key) => (attrs[key] = true)); } if (this.__inFlightAttributes !== null) { Object.keys(this._inFlightAttributes).forEach((key) => (attrs[key] = true)); } if (this.__data !== null) { this._schema .computeAttributes(Object.keys(this._data), this.modelName) .forEach((key) => (attrs[key] = true)); } Object.keys(attrs).forEach(callback, binding); } // Exposes attribute keys for the schema service to be able to iterate over the props // Expected by the ED and snapshot interfaces. Longer term TODO is to look into decoupling // things more so this is not required attributesDefinition() { let attrs = {}; this.eachAttribute((attr) => { attrs[attr] = { key: attr }; }); return attrs; } /** * Returns an object, whose keys are changed properties, and value is an * [oldProp, newProp] array. * * @method changedAttributes * @returns {Obejct} * @private */ changedAttributes() { if (this._baseRecordData) { return this._baseRecordData.changedAttributes(); } let serverState = this._data; let localChanges = this._attributes; let inFlightData = this._inFlightAttributes; // TODO: test that we copy here let newData = assign(copy(inFlightData), localChanges); let _changedAttributes = Object.create(null); let newDataKeys = Object.keys(newData); for (let i = 0, length = newDataKeys.length; i < length; i++) { let key = newDataKeys[i]; _changedAttributes[key] = [serverState[key], newData[key]]; } if (this.__childRecordDatas) { let nestedKeys = Object.keys(this._childRecordDatas); for (let i = 0; i < nestedKeys.length; ++i) { let childKey = nestedKeys[i]; let childRecordDatas = this._childRecordDatas[childKey]; if (Array.isArray(childRecordDatas)) { let changes = null; for (let j = 0; j < childRecordDatas.length; ++j) { let individualChildRecordData = childRecordDatas[j]; let childChangedAttributes = individualChildRecordData.changedAttributes(); if (Object.keys(childChangedAttributes).length > 0) { if (changes == null) { changes = new Array(childRecordDatas.length); } changes[j] = childChangedAttributes; } } if (changes !== null) { _changedAttributes[childKey] = changes; } } else { let childChangedAttributes = childRecordDatas.changedAttributes(); if (Object.keys(childChangedAttributes).length > 0) { if ( this.getServerAttr(childKey) !== null && this.getServerAttr(childKey) !== undefined && newData[childKey] === undefined // If object is not already staged for change ) { _changedAttributes[childKey] = childChangedAttributes; } else { _changedAttributes[childKey] = [this.getServerAttr(childKey), childChangedAttributes]; } } } } } return _changedAttributes; } rollbackAttributes(notifyRecord = false) { if (this._baseRecordData) { return this._baseRecordData.rollbackAttributes(...arguments); } let dirtyKeys; if (this.hasChangedAttributes()) { dirtyKeys = Object.keys(this._attributes); this._attributes = null; } this._inFlightAttributes = null; if (this.__childRecordDatas) { let nestedKeys = Object.keys(this._childRecordDatas); for (let i = 0; i < nestedKeys.length; ++i) { let childKey = nestedKeys[i]; let childRecordData = this._childRecordDatas[childKey]; if (Array.isArray(childRecordData)) { for (let j = 0; j < childRecordData.length; ++j) { childRecordData[j].rollbackAttributes(true); } } else { childRecordData.rollbackAttributes(true); } } } if (!(dirtyKeys && dirtyKeys.length > 0)) { // nothing dirty on this record and we've already handled nested records return; } if (this._notifyProjectionProperties(dirtyKeys)) { // notifyProjectionProperties already invalidated all relevant records' properties return []; } if (notifyRecord) { this._notifyRecordProperties(dirtyKeys); } return dirtyKeys; } /** * @param {string} key * @returns {boolean} */ isAttrDirty(key) { if (this._baseRecordData) { return this._baseRecordData.isAttrDirty(...arguments); } if (!(key in this._attributes)) { return false; } let originalValue; if (this._inFlightAttributes[key] !== undefined) { originalValue = this._inFlightAttributes[key]; } else { originalValue = this._data[key]; } return originalValue !== this._attributes[key]; } /** * @readonly * @returns {Object} */ get _childRecordDatas() { if (this.__childRecordDatas === null) { this.__childRecordDatas = Object.create(null); } return this.__childRecordDatas; } /** * @readonly * @returns {Object} */ get _attributes() { if (this.__attributes === null) { this.__attributes = Object.create(null); } return this.__attributes; } set _attributes(v) { this.__attributes = v; } /** * @readonly * @returns {Object} */ get _data() { if (this.__data === null) { this.__data = Object.create(null); } return this.__data; } set _data(v) { this.__data = v; } get _inFlightAttributes() { if (this.__inFlightAttributes === null) { this.__inFlightAttributes = Object.create(null); } return this.__inFlightAttributes; } set _inFlightAttributes(v) { this.__inFlightAttributes = v; } _initBaseRecordData() { if (!this._baseRecordData) { let baseModelName = this._schema.computeBaseModelName(this.modelName); if (!baseModelName) { return; } this._baseRecordData = this.storeWrapper.recordDataFor(dasherize(baseModelName), this.id); } if (this._baseRecordData) { this._baseRecordData._registerProjection(this); } } /** * @param {string} key * @param {string} idx * @param {string} modelName * @param {string} id * @param {_embeddedInternalModel} embeddedInternalModel * @returns {M3RecordData} */ _getChildRecordData(key, idx, modelName, id, embeddedInternalModel) { let childRecordData; if (idx !== undefined && idx !== null) { let childRecordDatas = this._childRecordDatas[key]; if (!childRecordDatas) { childRecordDatas = this._childRecordDatas[key] = []; } childRecordData = childRecordDatas[idx]; if (!childRecordData) { childRecordData = childRecordDatas[idx] = this._createChildRecordData( key, idx, modelName, id ); } } else { childRecordData = this._childRecordDatas[key]; if (!childRecordData) { childRecordData = this._childRecordDatas[key] = this._createChildRecordData( key, null, modelName, id ); } } if (!CUSTOM_MODEL_CLASS) { if (!childRecordData._embeddedInternalModel) { childRecordData._embeddedInternalModel = embeddedInternalModel; } } return childRecordData; } /** * @param {string} key * @param {string} idx * @param {string} modelName * @param {string} id * @returns {M3RecordData} */ _createChildRecordData(key, idx, modelName, id) { let baseChildRecordData; if (this._baseRecordData) { // use the base model name if it is available, but otherwise just use the model name - it might be already // the base one let childBaseModelName = this._schema.computeBaseModelName(modelName) || modelName; baseChildRecordData = this._baseRecordData._getChildRecordData( key, idx, childBaseModelName, id, null ); } return new M3RecordData( modelName, id, null, this.storeWrapper, this._schema, this, baseChildRecordData, this.globalM3CacheRD ); } _debugJSON() { // if the model is a projection, delegate to the base record to get the JSON if (this._baseRecordData) { return this._baseRecordData._debugJSON(); } return this._data; } _destroyChildRecordData(key) { if (this._baseRecordData) { return this._baseRecordData._destroyChildRecordData(key); } if (!this.__childRecordDatas) { return; } return this.__destroyChildRecordData(key); } __destroyChildRecordData(key) { if (!this.__childRecordDatas) { return; } let childRecordData = this._childRecordDatas[key]; if (childRecordData) { // destroy delete this._childRecordDatas[key]; } if (this._projections) { // TODO Add a test for this destruction // start from 1 as we know the first projection is the recordData for (let i = 1; i < this._projections.length; i++) { this._projections[i].__destroyChildRecordData(key); } } } /** * Returns an existing child recordData, which can be reused for merging updates or undefined if * there is no such child recordData. * * @param {string} key - The key, which to apply an update to * @param {Mixed} newValue - The updates, which needs to be merged * @return {M3RecordData} The child record data, which can be reused or undefined if there is none. */ _getExistingChildRecordData(key, newValue) { if ( !this.__childRecordDatas || !this.__childRecordDatas[key] || Array.isArray(this.__childRecordDatas[key]) ) { return undefined; } let nested = this._childRecordDatas[key]; // we need to compute the new nested type, hopefully it is not too slow let newNestedDef; if (this._schema.useComputeAttribute()) { newNestedDef = computeAttribute( key, newValue, this.modelName, this.schemaInterface, this._schema ); } else { newNestedDef = computeNestedModel( key, newValue, this.modelName, this.schemaInterface, this._schema ); } let newType = newNestedDef && newNestedDef.type && dasherize(newNestedDef.type); let isSameType = newType === nested.modelName || (isNone(newType) && isNone(nested.modelName)); let newId = newNestedDef && newNestedDef.id; let isSameId = newId === nested.id || (isNone(newId) && isNone(nested.id)); return newNestedDef && isSameType && isSameId ? nested : null; } /** * Updates the childRecordDatas for a key, which is an array, * upon any updates to resolved tracked array. * @param {string} key * @param {string} idx * @param {string} removeLength * @param {string} addLength */ _resizeChildRecordData(key, idx, removeLength, addLength) { if (this._baseRecordData) { this._baseRecordData._resizeChildRecordData(key, idx, removeLength, addLength); } const childRecordDatas = this._childRecordDatas && this._childRecordDatas[key]; if (!childRecordDatas) { return; } assert( `Cannot invoke '_resizeChildRecordData' as childRecordData for ${key} is not an array`, Array.isArray(childRecordDatas) ); const newItemsInChildRecordData = new Array(addLength); Array.prototype.splice.apply( childRecordDatas, [idx, removeLength].concat(newItemsInChildRecordData) ); } _setChildRecordData(key, idx, recordData) { if (recordData._baseRecordData && this._baseRecordData) { this._baseRecordData._setChildRecordData(key, idx, recordData._baseRecordData); } else if (!recordData._baseRecordData && !this._baseRecordData) { // TODO assert against one of these being set but the other one not if (idx !== undefined && idx !== null) { let childRecordDatas = this._childRecordDatas[key]; if (childRecordDatas === undefined) { childRecordDatas = this._childRecordDatas[key] = []; } childRecordDatas[idx] = recordData; } else { this._childRecordDatas[key] = recordData; } } else { assert( 'Projection levels match between the nested recordData being set and the parent recordData', false ); } } _registerProjection(recordData) { if (!this._projections) { // we ensure projections contains the base as well // so we have complete list of all related recordDatas this._projections = [this]; } this._projections.push(recordData); } _unregisterProjection(recordData) { if (!this._projections) { return; } let idx = this._projections.indexOf(recordData); if (idx === -1) { return; } this._projections.splice(idx, 1); // if all projetions have been destroyed and the record is not use, destroy as well if (this._areAllProjectionsDestroyed() && !this.isRecordInUse()) { this._destroy(); } } _destroy() { this.isDestroyed = true; this.storeWrapper.disconnectRecord(this.modelName, this.id, this.clientId); if (this._baseRecordData) { this._baseRecordData._unregisterProjection(this); } } /** * Checks if the attributes which are considered as changed are still * different to the state which is acknowledged by the server. * * This method is needed when data for the internal model is pushed and the * pushed data might acknowledge dirty attributes as confirmed. * * @method _updateChangedAttributes * @private */ _updateChangedAttributes() { let changedAttributes = this.changedAttributes(); let changedAttributeNames = Object.keys(changedAttributes); let attrs = this._attributes; for (let i = 0, length = changedAttributeNames.length; i < length; i++) { let attribute = changedAttributeNames[i]; let data = changedAttributes[attribute]; let oldData = data[0]; let newData = data[1]; if (oldData === newData) { delete attrs[attribute]; } } } /** * Filters keys, which have local changes in _attributes, because even their value on * the server has changed, their local value is not and no property notification should * be sent for them. * * @method _filterChangedKeys * @param {Array<string>} changedKeys * @returns {Array<string>} * @private */ _filterChangedKeys(changedKeys) { if (!changedKeys || changedKeys.length === 0) { return changedKeys; } if (!this.hasChangedAttributes()) { return changedKeys; } let attrs = this._attributes; return changedKeys.filter((key) => attrs[key] === undefined); } _areAllProjectionsDestroyed() { if (!this._projections) { // no projections were ever registered return true; } // if this recordData is the last one in the projections list, then all of the others have been destroyed // note: should not be possible to get into state of no projections (projections.length === 0) return this._projections.length === 1 && this._projections[0] === this; } /** * Merges updates from the server and delegates changes in nested objects to their respective * child recordData. * * @param {Object} updates * @param {Function} nestedCallback a callback for updating the data of a nested RecordData instance * @param {boolean} calculateChanges * @returns {Array<string>} The list of changed keys ignoring any changes in its children. * @private */ _mergeUpdates(updates, nestedCallback, calculateChanges) { let data = this._data; let changedKeys; if (calculateChanges) { changedKeys = []; } if (!updates) { return changedKeys; } let updatedKeys = Object.keys(updates); for (let i = 0; i < updatedKeys.length; i++) { let key = updatedKeys[i]; let newValue = updates[key]; if (isEqual(data[key], newValue)) { // values are equal, nothing to do // note, updates to objects should always result in new object or there will be nothing to update continue; } let reusableChild = this._getExistingChildRecordData(key, newValue); if (reusableChild) { nestedCallback(reusableChild, newValue); continue; } // not an embedded object, destroy the nested recordData this._destroyChildRecordData(key); if (calculateChanges) { changedKeys.push(key); } data[key] = newValue; } return changedKeys; } _notifyRecordProperties(changedKeys) { if (CUSTOM_MODEL_CLASS) { let record = recordDataToRecordMap.get(this); if (record) { record._notifyProperties(changedKeys); } } else { if (this._embeddedInternalModel) { this._embeddedInternalModel.record._notifyProperties(changedKeys); } else if (!this._parentRecordData) { notifyProperties(this.storeWrapper, this.modelName, this.id, this.clientId, changedKeys); } } // else base recordData that was initialized by a projection but never // fetched via `unknownProperty`, which is the only case where we have no // record, and therefore nothing to notify } _notifyProjectionProperties(changedKeys) { if (!changedKeys || !changedKeys.length) { return false; } let projections = this._projections; if (!projections) { return false; } for (let i = 0; i < projections.length; i++) { projections[i]._notifyRecordProperties(changedKeys); } return true; } /** * If there are local changes that are not altered by the server payload, we need to manually call didCOmmit * on them to sync their states. */ _syncNestedModelUpdates(attributes) { // Iterate through the children and call didCommit on it to ensure the childRecordData has the correct state. const childRecordDatas = this._getChildRecordDatas(); childRecordDatas.forEach((childRecordData) => { // Don't do anything if the key is inside the server payload if (attributes && childRecordData.key in attributes) { return; } if (!Array.isArray(childRecordData.data)) { childRecordData.data.didCommit(); } else { childRecordData.data.forEach((child) => child.didCommit()); } }); } /** * Merge data from nested models into parent, so its data is correctly in sync with its children. */ _mergeNestedModelData() { // We need to recursively copy the childRecordDatas into data, to ensure the top level model knows about the change. const childRecordDatas = this._getChildRecordDatas(); childRecordDatas.forEach((childRecordData) => { if (!Array.isArray(childRecordData.data)) { this._data[childRecordData.key] = childRecordData.data._data; } else { this._data[childRecordData.key] = childRecordData.data.map((child) => child._data); } }); } /** * Helper function for returning childRecordDatas in {key, value} format * e.g, [{childKey, childRecordData}, {...}] */ _getChildRecordDatas() { if (this.__childRecordDatas) { let nestedKeys = Object.keys(this._childRecordDatas); return nestedKeys.map((nestedKey) => { return { key: nestedKey, data: this._childRecordDatas[nestedKey], }; }); } return []; } toString() { return `<${this.modelName}:${this.id}>`; } }
28.289352
129
0.641082
3b56666fa30716e5fc630afda2b3af33e3ed362c
870
js
JavaScript
make-index-html-from-page-spec.js
jimkang/static-web-archive
f5e304f07115dd9dc2e189da76afbd9e9d989a57
[ "Unlicense", "MIT" ]
1
2020-09-15T08:41:37.000Z
2020-09-15T08:41:37.000Z
make-index-html-from-page-spec.js
jimkang/static-web-archive
f5e304f07115dd9dc2e189da76afbd9e9d989a57
[ "Unlicense", "MIT" ]
6
2020-05-02T02:30:21.000Z
2022-02-18T15:47:13.000Z
make-index-html-from-page-spec.js
jimkang/static-web-archive
f5e304f07115dd9dc2e189da76afbd9e9d989a57
[ "Unlicense", "MIT" ]
null
null
null
var pluck = require('lodash.pluck'); function makeIndexHTMLFromPageSpec({ mostRecentPageIndex, header, footer, pageSpec, modFragmentFn // ({ cell, fragment }) => string }) { var filename = pageSpec.index + '.html'; if (pageSpec.index === mostRecentPageIndex) { filename = 'index.html'; } var sortedCells = pageSpec.cells.sort(compareCellsByDateDesc); var cellFragments = pluck(sortedCells, 'htmlFragment'); if (modFragmentFn) { cellFragments = sortedCells.map(modifyFragment); } return { filename, content: header + '\n' + cellFragments.join('\n') + '\n' + footer + '\n' }; function modifyFragment(cell) { return modFragmentFn({ cell, fragment: cell.htmlFragment }); } } function compareCellsByDateDesc(a, b) { return new Date(a.date) > new Date(b.date) ? -1 : 1; } module.exports = makeIndexHTMLFromPageSpec;
24.166667
76
0.678161
3b56b20b68b8bf5047e2c440c618090656e38083
1,567
js
JavaScript
source/functions/render.js
lajbel/newgroundsjs
49eb297d7305a4725950e93f9417d058e348647b
[ "MIT" ]
2
2022-02-07T16:38:49.000Z
2022-03-09T21:56:02.000Z
source/functions/render.js
lajbel/newgroundsjs
49eb297d7305a4725950e93f9417d058e348647b
[ "MIT" ]
null
null
null
source/functions/render.js
lajbel/newgroundsjs
49eb297d7305a4725950e93f9417d058e348647b
[ "MIT" ]
null
null
null
function renderMedal(context, id, x, y, h, alpha=.5) { if (!this.medals || !this.medals.find(m => m.id == id)) return; context.save(); context.fillStyle = '#fff'; context.strokeStyle = '#000'; context.shadowColor = '#000'; context.textBaseline = 'middle'; context.textAlign = 'left'; context.font = (h/2)+'px impact'; context.lineWidth = h/35; context.shadowBlur = h/5; context.globalAlpha = alpha; const medal = this.medals.find(m => m.id == id); context.drawImage(medal.image, x, y, h, h); context.strokeRect(x, y, h, h); const points = this.points[medal.difficulty - 1]; const text = this.getMedalText(medal); context.lineWidth = Math.max(1,h/26); context.strokeText(text, x + h*1.2, y+h/2); context.fillText(text, x + h*1.2, y+h/2); context.restore(); }; export function update(delta) { if (this.displayMedalQueue?.length) { const medal = this.displayMedalQueue[0]; medal.time += delta; if(medal.time > this.medalDisplayTime) this.displayMedalQueue.shift(); }; }; export function render(context, size=50) { if (this.displayMedalQueue?.length) { const medal = this.displayMedalQueue[0]; const slideOnPecent = medal.time < 1 ? 1-medal.time : 0; const alpha = medal.time > this.medalDisplayTime - 1 ? this.medalDisplayTime - medal.time : 1; const y = context.canvas.height + slideOnPecent * size * 1.5; renderMedal(context, medal.index, 0, y - size, size, alpha); }; };
34.065217
102
0.615188
3b56e65dcfdc6b73ee20541d68c7150a40cd00c7
245
js
JavaScript
Wikimedia/lookup_web_wikidata_match/ui_settings.js
GLAMpipe/nodes
56dc82cd82be8b7c6ef349f8e6e69e0a400c52a9
[ "MIT" ]
1
2020-07-25T20:11:03.000Z
2020-07-25T20:11:03.000Z
Wikimedia/lookup_web_wikidata_match/ui_settings.js
GLAMpipe/nodes
56dc82cd82be8b7c6ef349f8e6e69e0a400c52a9
[ "MIT" ]
null
null
null
Wikimedia/lookup_web_wikidata_match/ui_settings.js
GLAMpipe/nodes
56dc82cd82be8b7c6ef349f8e6e69e0a400c52a9
[ "MIT" ]
null
null
null
var a = document.getElementById('process_lookup_web_wikidata_match_ui') a.href = `/apps/reconciliation/?node=${node._id}` var div = document.getElementById('process_lookup_wikidata_recon_query_value') div.textContent = node.params.in_field
24.5
78
0.804082
3b57a645d77396e4fef7e26e5aa8a45655bc8a55
576
js
JavaScript
src/api/project.js
nagosang/test_cases_management_front
94aab1c00c95d392304f91259ffd8aea248f6187
[ "MIT" ]
null
null
null
src/api/project.js
nagosang/test_cases_management_front
94aab1c00c95d392304f91259ffd8aea248f6187
[ "MIT" ]
null
null
null
src/api/project.js
nagosang/test_cases_management_front
94aab1c00c95d392304f91259ffd8aea248f6187
[ "MIT" ]
null
null
null
import request from '@/utils/request' export function getProjectListByGroup(groupId) { return request({ url: '/getProjectListByGroup?groupId=' + groupId, method: 'get', }) } export function getProjectListByUser() { return request({ url: '/getProjectListByUser', method: 'get', }) } export function getProjectInfo(projectId) { return request({ url: '/getProjectInfo?projectId=' + projectId, method: 'get' }) } export function updateProjecInfo(data) { return request({ url: '/updateProjectInfo', method: 'post', data }) }
18.580645
53
0.668403
3b57b5fadb94176afca99bfed7f5f7e6f6f1f295
4,039
js
JavaScript
2016-RayTracer/script.js
kovacsv/JS1K
ee1680472ec591a9f702b2a3296e6cec48506c5b
[ "MIT" ]
3
2015-02-14T14:56:00.000Z
2021-11-09T22:47:38.000Z
2016-RayTracer/script.js
kovacsv/JS1K
ee1680472ec591a9f702b2a3296e6cec48506c5b
[ "MIT" ]
2
2015-03-23T16:02:22.000Z
2015-03-23T17:47:43.000Z
2016-RayTracer/script.js
kovacsv/JS1K
ee1680472ec591a9f702b2a3296e6cec48506c5b
[ "MIT" ]
null
null
null
function R (context) { function Vector (x, y, z) { // w component is for rgba usage return {x : x, y : y, z : z, w : 1}; } function Mul (a, b) { return Vector (a.x * b, a.y * b, a.z * b); } function Add (a, b) { return Sub (a, Mul (b, -1)); } function Sub (a, b) { return Vector (a.x - b.x, a.y - b.y, a.z - b.z); } function Dot (a, b) { return a.x * b.x + a.y * b.y + a.z * b.z; } function Normalize (a) { return Mul (a, 1 / mySqrt (a.x * a.x + a.y * a.y + a.z * a.z)); } function RayModelIntersection (rayOrigin, rayDirection) { var sphereIndex = 9, currentIndex, result, sphereRadius, sphereToRay, a, b, minT; // check intersection with every sphere in the scene while (sphereIndex--) { // check ray-sphere intersection currentIndex = 3 * sphereIndex; sphereRadius = geometry[currentIndex + 1]; sphereToRay = Sub (rayOrigin, geometry[currentIndex]); a = Dot (rayDirection, rayDirection) / 2; b = -2 * Dot (sphereToRay, rayDirection); minT = (b - mySqrt (b * b - 8 * a * (Dot (sphereToRay, sphereToRay) - sphereRadius * sphereRadius))) * a; // in case of negative discriminant minT is NaN, and it is not greater than 0.1 :) if (minT > 0.1 && (!result || minT < result.d)) { result = {i : currentIndex, d : minT}; } } return result; } function RenderRowsOneStep () { var sampleCount = 32, imageData = context.createImageData (canvasSize, 1), imageDataIndex = 0, columnIndex = canvasSize, componentIndex, tracedColor, currentSample, rayDirection, intersection, shadedColor, intersectionPoint; while (columnIndex--) { tracedColor = blackColor; currentSample = sampleCount; // shoot random rays through the pixel while (currentSample--) { rayDirection = Normalize ( Sub ( Vector (0, halfCanvasSize - columnIndex + myRandom (), halfCanvasSize - rowIndex + myRandom ()), eyePosition ) ); intersection = RayModelIntersection (eyePosition, rayDirection); shadedColor = backgroundColor; if (intersection) { intersectionPoint = Add (eyePosition, Mul (rayDirection, intersection.d)); // do the shading for intersection point (no shading for the large sphere) shadedColor = RayModelIntersection (intersectionPoint, Normalize (Sub (lightPosition, intersectionPoint))) ? blackColor : // in shadow intersection.i ? // not the first large sphere Mul ( geometry[intersection.i + 2], // sphere color M.max ( Dot ( Normalize (Sub (lightPosition, intersectionPoint)), // direction to the light source Normalize (Sub (intersectionPoint, geometry[intersection.i])) // sphere normal vector ), 0.0 ) // diffuse intensity ) : backgroundColor; // first large sphere } tracedColor = Add (tracedColor, Mul (shadedColor, 1 / sampleCount)); } for (componentIndex in tracedColor) { imageData.data[imageDataIndex++] = tracedColor[componentIndex] * 255; } } context.putImageData (imageData, 1, rowIndex); if (rowIndex++ < canvasSize) { setTimeout (RenderRowsOneStep, 0); } } function Random (from, to) { return myRandom () * (to - from) + from; } var M = Math, mySqrt = M.sqrt, myRandom = M.random, canvasSize = 512, halfCanvasSize = canvasSize / 2, eyePosition = Vector (canvasSize, 0, 0), lightPosition = Vector (canvasSize, Random (-canvasSize, canvasSize), canvasSize), backgroundColor = Vector (0.8, 0.8, 0.8), groundSphereRadius = 1000000, groundOffset = 75, blackColor = Vector (0, 0, 0), geometry = [ Vector (0, 0, -groundSphereRadius - groundOffset), groundSphereRadius, backgroundColor ], rowIndex = 1, randomSphereCount = 8, radius; while (randomSphereCount--) { radius = Random (20, 60); geometry.push (Vector (Random (-canvasSize, halfCanvasSize), Random (-halfCanvasSize, halfCanvasSize), radius - groundOffset), radius, Vector (myRandom (), myRandom (), myRandom ())); } RenderRowsOneStep (); } R (c);
28.85
185
0.646695
3b586eb422f106be97421bfd1e2bf0c0d4cc3d70
3,716
js
JavaScript
bitrix/modules/landing/install/js/landing/ui/form/dynamicblockform/dist/dynamicblockform.bundle.map.js
Poulhouse/dev_don360
9e7b60e38cdd8be47d31a0080c9cdfabe22215ce
[ "Apache-2.0" ]
null
null
null
bitrix/modules/landing/install/js/landing/ui/form/dynamicblockform/dist/dynamicblockform.bundle.map.js
Poulhouse/dev_don360
9e7b60e38cdd8be47d31a0080c9cdfabe22215ce
[ "Apache-2.0" ]
null
null
null
bitrix/modules/landing/install/js/landing/ui/form/dynamicblockform/dist/dynamicblockform.bundle.map.js
Poulhouse/dev_don360
9e7b60e38cdd8be47d31a0080c9cdfabe22215ce
[ "Apache-2.0" ]
null
null
null
{"version":3,"sources":["dynamicblockform.bundle.js"],"names":["this","BX","Landing","UI","exports","main_core","landing_ui_form_baseform","landing_env","landing_loc","DynamicBlockForm","_BaseForm","babelHelpers","inherits","options","_this","classCallCheck","possibleConstructorReturn","getPrototypeOf","call","type","forms","code","onSourceChangeHandler","onSourceChange","dynamicParams","settingFieldsSelectors","addField","createSourceField","createClass","key","value","_this2","Type","isPlainObject","wrapper","settings","isString","source","getSourceById","_DynamicBlockForm$get","getSources","_DynamicBlockForm$get2","slicedToArray","setTimeout","Field","Dropdown","title","Loc","getMessage","selector","content","items","getSourceFieldItems","onValueChange","field","getValue","serialize","fields","reduce","acc","id","references","Dom","hasClass","layout","stubs","src","alt","isReference","Env","getInstance","getOptions","sources","find","String","map","name","isArray","some","reference","BaseForm","Form"],"mappings":"AAAAA,KAAKC,GAAKD,KAAKC,OACfD,KAAKC,GAAGC,QAAUF,KAAKC,GAAGC,YAC1BF,KAAKC,GAAGC,QAAQC,GAAKH,KAAKC,GAAGC,QAAQC,QACpC,SAAUC,EAAQC,EAAUC,EAAyBC,EAAYC,GACjE,aAMA,IAAIC,EAAgC,SAAUC,GAC5CC,aAAaC,SAASH,EAAkBC,GAExC,SAASD,EAAiBI,GACxB,IAAIC,EAEJH,aAAaI,eAAef,KAAMS,GAClCK,EAAQH,aAAaK,0BAA0BhB,KAAMW,aAAaM,eAAeR,GAAkBS,KAAKlB,KAAMa,IAC9GC,EAAMK,KAAON,EAAQM,KACrBL,EAAMM,MAAQP,EAAQO,MACtBN,EAAMO,KAAOR,EAAQQ,KACrBP,EAAMQ,sBAAwBT,EAAQU,eACtCT,EAAMU,cAAgBX,EAAQW,cAC9BV,EAAMW,wBAA0B,UAEhCX,EAAMY,SAASZ,EAAMa,qBAErB,OAAOb,EAGTH,aAAaiB,YAAYnB,IACvBoB,IAAK,oBACLC,MAAO,SAASH,IACd,IAAII,EAAS/B,KAEb,IAAI8B,EAAQ,GAEZ,GAAIzB,EAAU2B,KAAKC,cAAcjC,KAAKwB,gBAAkBnB,EAAU2B,KAAKC,cAAcjC,KAAKwB,cAAcU,UAAY7B,EAAU2B,KAAKC,cAAcjC,KAAKwB,cAAcU,QAAQC,WAAa9B,EAAU2B,KAAKI,SAASpC,KAAKwB,cAAcU,QAAQC,SAASE,QAAS,CAC5PP,EAAQ9B,KAAKwB,cAAcU,QAAQC,SAASE,OAG9C,IAAIA,EAAS5B,EAAiB6B,cAAcR,GAE5C,IAAKO,EAAQ,CACX,IAAIE,EAAwB9B,EAAiB+B,aAE7C,IAAIC,EAAyB9B,aAAa+B,cAAcH,EAAuB,GAE/EF,EAASI,EAAuB,GAGlCE,WAAW,WACTZ,EAAOT,sBAAsBe,IAC5B,GACH,OAAO,IAAIpC,GAAGC,QAAQC,GAAGyC,MAAMC,UAC7BC,MAAOtC,EAAYuC,IAAIC,WAAW,qCAClCC,SAAU,SACVC,QAASpB,EACTqB,MAAO1C,EAAiB2C,sBACxBC,cAAe,SAASA,EAAcC,GACpCvB,EAAOT,sBAAsBb,EAAiB6B,cAAcgB,EAAMC,mBAKxE1B,IAAK,YACLC,MAAO,SAAS0B,IACd,OAAOxD,KAAKyD,OAAOC,OAAO,SAAUC,EAAKL,GACvC,IAAIxB,EAAQwB,EAAMC,WAElB,GAAID,EAAML,WAAa,SAAU,CAC/BU,EAAItB,OAASP,EACb6B,EAAIxB,SAASmB,EAAML,UAAYnB,OAC1B,GAAIA,IAAU,SAAWzB,EAAU2B,KAAKC,cAAcH,IAAUA,EAAM8B,KAAO,QAAS,CAC3FD,EAAIE,WAAWP,EAAML,UAAY,QAEjC,GAAI5C,EAAUyD,IAAIC,SAAST,EAAMU,OAAQ,qCAAsC,CAC7EL,EAAIM,MAAMX,EAAML,UAAY,QACvB,GAAI5C,EAAUyD,IAAIC,SAAST,EAAMU,OAAQ,kCAAmC,CACjFL,EAAIM,MAAMX,EAAML,WACdW,IAAK,EACLM,IAAK,2CACLC,IAAK,UAGJ,GAAI1D,EAAiB2D,YAAYtC,GAAQ,CAC9C6B,EAAIE,WAAWP,EAAML,WACnBW,GAAI9B,QAED,GAAIzB,EAAU2B,KAAKC,cAAcH,IAAUzB,EAAU2B,KAAKI,SAASN,EAAM8B,IAAK,CACnFD,EAAIE,WAAWP,EAAML,UAAYnB,MAC5B,CACL6B,EAAIM,MAAMX,EAAML,UAAYnB,EAG9B,OAAO6B,IAEPxB,YACA0B,cACAI,gBAIJpC,IAAK,aACLC,MAAO,SAASU,IACd,OAAOjC,EAAY8D,IAAIC,cAAcC,aAAaC,WAGpD3C,IAAK,gBACLC,MAAO,SAASQ,EAAcsB,GAC5B,OAAOnD,EAAiB+B,aAAaiC,KAAK,SAAUpC,GAClD,OAAOqC,OAAOrC,EAAOuB,MAAQc,OAAOd,QAIxC/B,IAAK,sBACLC,MAAO,SAASsB,IACd,OAAO3C,EAAiB+B,aAAamC,IAAI,SAAUtC,GACjD,OACEuC,KAAMvC,EAAOuC,KACb9C,MAAOO,EAAOuB,SAKpB/B,IAAK,cACLC,MAAO,SAASsC,EAAYtC,GAC1B,IAAI0C,EAAU/D,EAAiB+B,aAE/B,GAAInC,EAAU2B,KAAK6C,QAAQL,GAAU,CACnC,OAAOA,EAAQM,KAAK,SAAUzC,GAC5B,GAAIhC,EAAU2B,KAAK6C,QAAQxC,EAAOwB,YAAa,CAC7C,OAAOxB,EAAOwB,WAAWiB,KAAK,SAAUC,GACtC,OAAOA,EAAUnB,KAAO9B,IAI5B,OAAO,QAIX,OAAO,UAGX,OAAOrB,EAtI2B,CAuIlCH,EAAyB0E,UAE3B5E,EAAQK,iBAAmBA,GAhJ5B,CAkJGT,KAAKC,GAAGC,QAAQC,GAAG8E,KAAOjF,KAAKC,GAAGC,QAAQC,GAAG8E,SAAYhF,GAAGA,GAAGC,QAAQC,GAAG8E,KAAKhF,GAAGC,QAAQD,GAAGC","file":"dynamicblockform.bundle.map.js"}
3,716
3,716
0.808934
3b58f8fb33517e07e5b62e73b14b9c049cecd404
420
js
JavaScript
Trees/preInTree.js
namit-piriya/dsaInJs
368778d93815f77be1f6c0325017bc4fa929cdeb
[ "MIT" ]
null
null
null
Trees/preInTree.js
namit-piriya/dsaInJs
368778d93815f77be1f6c0325017bc4fa929cdeb
[ "MIT" ]
null
null
null
Trees/preInTree.js
namit-piriya/dsaInJs
368778d93815f77be1f6c0325017bc4fa929cdeb
[ "MIT" ]
null
null
null
function solve(pre, inO) { if (!pre || pre.length === 0 || !inO || inO.length === 0) { return null; } let root = new Tree(pre[0]); let rootIn = pre.indexOf(pre[0]); let nInL = inO.slice(0, rootIn); let nPreL = pre.slice(1, 1 + rootIn); let nPreR = pre.slice(1 + rootIn); let nInR = pre.slice(rootIn + 1); root.left = this.solve(nPreL, nInL); root.left = this.solve(nPreR, nInR); return root; }
28
61
0.597619
3b59192f617420e4ad26f81671a0cbf8e0569f49
2,932
js
JavaScript
ui/src/hooks/use-wallet.js
saleel/stable
8507496d38ecfaffb9033f5fce3129c4241031a3
[ "MIT" ]
null
null
null
ui/src/hooks/use-wallet.js
saleel/stable
8507496d38ecfaffb9033f5fce3129c4241031a3
[ "MIT" ]
null
null
null
ui/src/hooks/use-wallet.js
saleel/stable
8507496d38ecfaffb9033f5fce3129c4241031a3
[ "MIT" ]
null
null
null
import React from 'react'; import { providers } from 'ethers'; const provider = window.ethereum && new providers.Web3Provider(window.ethereum); function useWallet() { const [isLoading, setIsLoading] = React.useState(!!provider); const [isChainValid, setIsChainValid] = React.useState(false); const [signer, setSigner] = React.useState(provider && provider.getSigner()); const [address, setAddress] = React.useState(); React.useEffect(() => { if (!provider) { return; } window.ethereum.on('chainChanged', (newChainId) => { const isValid = parseInt(newChainId, 16) === Number(process.env.REACT_APP_CHAIN_ID); setIsChainValid(isValid); if (!isValid) { setAddress(); } }); (async () => { const chainId = parseInt((await signer.getChainId()).toString(), 10); if (chainId !== Number(process.env.REACT_APP_CHAIN_ID)) { setIsLoading(false); setIsChainValid(false); return; } setIsChainValid(true); if (signer) { signer.getAddress().then((add) => setAddress(add)); } setIsLoading(false); window.ethereum.on('accountsChanged', (([account1]) => { setAddress(account1.toLowerCase()); })); })(); }, [signer]); async function onConnectClick() { await provider.send('eth_requestAccounts', []); setSigner(provider.getSigner()); const account = await provider.getSigner().getAddress(); setAddress(account.toLowerCase()); } function Component() { if (isLoading) return null; if (!provider) { return ( <> <h4 className="subtitle">Cannot find a Wallet provider.</h4> <div className="mt-3 mb-5"> You need to have <a target="_blank" href="https://metamask.io/" rel="noreferrer">Metamask</a> {' '} or other similar browser plugin installed in order to interact with the Stable contract </div> </> ); } if (!isChainValid) { return ( <> <h4 className="subtitle">You are not on Aurora chain.</h4> <div className="mt-3 mb-5"> Please change your Metamask chain to <a target="_blank" href="https://aurora.dev/start" rel="noreferrer">Aurora Mainnet</a>. </div> </> ); } return ( <> <h4 className="subtitle">Connect to your ETH wallet using Metamask (or similar) to interact with the Stable contract.</h4> <div className="mt-3 mb-5"> <img src="https://images.ctfassets.net/9sy2a0egs6zh/4zJfzJbG3kTDSk5Wo4RJI1/1b363263141cf629b28155e2625b56c9/mm-logo.svg" alt="Metamask" /> </div> <button className="button btn-submit-prices is-medium" type="button" onClick={onConnectClick}> Connect </button> </> ); } return { isLoading, signer, provider, address, Component, }; } export default useWallet;
28.466019
148
0.607776
3b59493de373830ddd8103cb4aec286eee9ef44d
160
js
JavaScript
src/styles/movies.components.style.js
Miguel-EpicJS/blockflix
f6e9694af6ffcb46d37786d22b6c9f2a788342b2
[ "MIT" ]
null
null
null
src/styles/movies.components.style.js
Miguel-EpicJS/blockflix
f6e9694af6ffcb46d37786d22b6c9f2a788342b2
[ "MIT" ]
null
null
null
src/styles/movies.components.style.js
Miguel-EpicJS/blockflix
f6e9694af6ffcb46d37786d22b6c9f2a788342b2
[ "MIT" ]
null
null
null
import styled, { css } from "styled-components"; export const TrendingTitle = styled.h1` text-align: center; margin-bottom: 50px; color: #47545F; `
22.857143
48
0.68125
3b598fdea9c91216cb1317a1ad9ccd56efad963d
129
js
JavaScript
tests/baselines/reference/invalidUseOfTypeAsNamespace.js
nilamjadhav/TypeScript
b059135c51ee93f8fb44dd70a2ca67674ff7a877
[ "Apache-2.0" ]
49,134
2015-01-01T02:37:27.000Z
2019-05-06T20:38:53.000Z
tests/baselines/reference/invalidUseOfTypeAsNamespace.js
nilamjadhav/TypeScript
b059135c51ee93f8fb44dd70a2ca67674ff7a877
[ "Apache-2.0" ]
26,488
2015-01-01T13:57:03.000Z
2019-05-06T20:40:00.000Z
tests/baselines/reference/invalidUseOfTypeAsNamespace.js
nilamjadhav/TypeScript
b059135c51ee93f8fb44dd70a2ca67674ff7a877
[ "Apache-2.0" ]
8,518
2015-01-05T03:29:29.000Z
2019-05-06T14:37:49.000Z
//// [invalidUseOfTypeAsNamespace.ts] interface OhNo { } declare let y: OhNo.hello; //// [invalidUseOfTypeAsNamespace.js]
14.333333
38
0.705426
3b5a0a0029c4aa55a48f38577f2dea462bb42eaf
158
js
JavaScript
venue/venue.component.js
mainmeeting/main2021
44f1eac8e44a6a2086006fb05adea717e896f02f
[ "CC0-1.0" ]
null
null
null
venue/venue.component.js
mainmeeting/main2021
44f1eac8e44a6a2086006fb05adea717e896f02f
[ "CC0-1.0" ]
null
null
null
venue/venue.component.js
mainmeeting/main2021
44f1eac8e44a6a2086006fb05adea717e896f02f
[ "CC0-1.0" ]
null
null
null
// Register the `program` component on the `program` module, angular. module('venue'). component('venue', { templateUrl: 'venue/venue.template.html', });
22.571429
60
0.696203
3b5aca3c4fc211f8452f652fa11f2c359f5861f5
4,331
js
JavaScript
app/index.js
izziaraffaele/silex-app-generator
72ef3e7888ff931ad3ea5a44bb7cb1d3c0ec4fa5
[ "MIT" ]
6
2015-04-28T14:26:17.000Z
2017-06-03T20:38:29.000Z
app/index.js
izziaraffaele/generator-silex-app
72ef3e7888ff931ad3ea5a44bb7cb1d3c0ec4fa5
[ "MIT" ]
null
null
null
app/index.js
izziaraffaele/generator-silex-app
72ef3e7888ff931ad3ea5a44bb7cb1d3c0ec4fa5
[ "MIT" ]
null
null
null
'use strict'; var path = require('path'); var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var Generator = yeoman.generators.Base.extend({ init: function () { this.pkg = yeoman.file.readJSON(path.join(__dirname, '../package.json')); this.on('end', function () { if (!this.options['skip-install']) { this.installDependencies(); this.spawnCommand('composer', ['install']); this.spawnCommand('chmod', ['777','app/cache']); this.spawnCommand('chmod', ['777','app/logs']); } }); }, askFor: function () { var done = this.async(); // have Yeoman greet the user console.log(this.yeoman); // replace it with a short and sweet description of your generator console.log(chalk.magenta('You\'re using A Yeoman Generator for a Silex based web app!!')); var prompts = [{ name: 'project', message: 'What is this project\'s name?' }, { type: 'checkbox', name: 'features', message: 'What more would you like?', choices: [{ name: 'Auth system', value: 'includeAuth', checked: true }, { name: 'Jest for unit tests', value: 'includeJest', checked: true }] }]; this.prompt(prompts, function (answers) { var features = answers.features; this.projectName = answers.project || 'myApp'; function hasFeature(feat) { return features.indexOf(feat) !== -1; } // manually deal with the response, get back and store the results. // we change a bit this way of doing to automatically do this in the self.prompt() method. this.includeJest = hasFeature('includeJest'); this.includeAuth = hasFeature('includeAuth'); done(); }.bind(this)); }, app: function () { // main htaccess this.template('_package.json', 'package.json'); this.template('_gulpfile.js', 'gulpfile.js'); this.template('_bower.json', 'bower.json'); this.template('_composer.json', 'composer.json'); this.copy('bowerrc', '.bowerrc'); this.copy('gitignore', '.gitignore'); this.copy('preprocessor.js', 'preprocessor.js'); this.copy('phpunit.xml.dist', 'phpunit.xml.dist'); // webroot this.mkdir('web'); this.copy('web/htaccess','web/.htaccess'); this.copy('web/index.php','web/index.php'); // silex app this.directory('app','app'); this.mkdir('app/cache'); this.mkdir('app/logs'); // src application directory this.directory('src','src'); this.directory('tests','tests'); // Now lets build assets this.mkdir('assets'); this.directory('assets/images','assets/images'); this.directory('assets/scripts','assets/scripts'); this.mkdir('assets/styles'); this.template('assets/styles/_main.scss', 'assets/styles/_main.scss'); this.copy('assets/styles/auth.scss','assets/styles/auth.scss'); this.copy('assets/styles/errors.scss','assets/styles/errors.scss'); this.copy('assets/favicon.ico','assets/favicon.ico'); this.copy('assets/robots.txt','assets/robots.txt'); var routes = []; // lets start adding features if( this.includeAuth ){ routes.push({ routeName: "login", pattern: "/login", method: ["get"], controller: "WebComposer\\AppBundle\\Controllers\\AuthController:login" }); routes.push({ routeName: "signup", pattern: "/signup", method: ["get"], controller: "WebComposer\\AppBundle\\Controllers\\AuthController:signup" }); } if (this.includeJest) { this.directory('assets/scripts/ui/__tests__','assets/scripts/ui/__tests__'); } this.write('app/config/routes.json', JSON.stringify({'config.routes':routes})); } }); module.exports = Generator;
33.061069
102
0.539829
3b5b54c4296c690c124906240a3fa1634ee9bb7b
1,814
js
JavaScript
test/unit/specs/fields/fieldSpectrum.spec.js
uwemaurer/vue-form-generator
721a4eebbde77040a1318e60aa9ef21229bbcf99
[ "MIT" ]
2,270
2017-11-20T01:51:19.000Z
2022-03-30T05:52:23.000Z
test/unit/specs/fields/fieldSpectrum.spec.js
uwemaurer/vue-form-generator
721a4eebbde77040a1318e60aa9ef21229bbcf99
[ "MIT" ]
386
2017-11-20T14:06:04.000Z
2021-07-05T04:54:00.000Z
test/unit/specs/fields/fieldSpectrum.spec.js
uwemaurer/vue-form-generator
721a4eebbde77040a1318e60aa9ef21229bbcf99
[ "MIT" ]
473
2017-11-22T09:23:43.000Z
2022-03-28T02:05:12.000Z
import { mount, createLocalVue } from "@vue/test-utils"; import FieldSpectrum from "src/fields/optional/fieldSpectrum.vue"; const localVue = createLocalVue(); let wrapper; let input; function createField2(data, methods) { const _wrapper = mount(FieldSpectrum, { localVue, propsData: data, methods: methods }); wrapper = _wrapper; input = wrapper.find("input"); return _wrapper; } describe("fieldSpectrum.vue", () => { describe("check template", () => { let schema = { type: "color", label: "Color", model: "color", autocomplete: "off", disabled: false, placeholder: "", readonly: false, inputName: "" }; let model = { color: "#ff8822" }; before(() => { createField2({ schema, model, disabled: false }); }); it("should contain an input color element", () => { expect(wrapper.exists()).to.be.true; expect(input.is("input")).to.be.true; expect(input.attributes().type).to.be.equal("text"); }); it.skip("should contain the value", () => { expect(wrapper.vm.picker.spectrum("get").toHexString()).to.be.equal("#ff8822"); }); describe("check optional attribute", () => { let attributes = ["autocomplete", "disabled", "placeholder", "readonly", "inputName"]; attributes.forEach(name => { it("should set " + name, () => { checkAttribute(name, wrapper, schema); }); }); }); it.skip("input value should be the model value after changed", () => { model.color = "#ffff00"; wrapper.update(); expect(wrapper.vm.picker.spectrum("get").toHexString()).to.be.equal("#ffff00"); }); it.skip("model value should be the input value if changed", () => { wrapper.vm.picker.spectrum("set", "#123456"); wrapper.find(".sp-input").trigger("change"); expect(model.color).to.be.equal("#123456"); }); }); });
24.186667
89
0.627343
3b5ba2f8b09d61c73e0ab4c121d21081face0198
3,337
js
JavaScript
src/store/modules/tagsBar.js
andphp/admin-vue3-antd-js
07f9cdb92b127c436077828654c390296cc91f63
[ "MIT" ]
2
2021-03-18T11:48:28.000Z
2021-08-22T02:06:11.000Z
src/store/modules/tagsBar.js
andphp/admin-vue3-antd-js
07f9cdb92b127c436077828654c390296cc91f63
[ "MIT" ]
null
null
null
src/store/modules/tagsBar.js
andphp/admin-vue3-antd-js
07f9cdb92b127c436077828654c390296cc91f63
[ "MIT" ]
null
null
null
/** * @description tagsBar多标签页逻辑,前期借鉴了很多开源项目发现都有个共同的特点很繁琐并不符合框架设计的初衷,后来在github用户cyea的启发下完成了重构,请勿修改 */ const state = () => ({ visitedRoutes: [], }); const getters = { visitedRoutes: (state) => state.visitedRoutes, }; const mutations = { /** * @description 添加标签页 * @param {*} state * @param {*} route * @returns */ addVisitedRoute(state, route) { let target = state.visitedRoutes.find((item) => item.path === route.path); if (target) { if (route.fullPath !== target.fullPath) Object.assign(target, route); return; } state.visitedRoutes.push(Object.assign({}, route)); }, /** * @description 删除当前标签页 * @param {*} state * @param {*} route * @returns */ delVisitedRoute(state, route) { state.visitedRoutes.forEach((item, index) => { if (item.path === route.path) state.visitedRoutes.splice(index, 1); }); }, /** * @description 删除当前标签页以外其它全部多标签页 * @param {*} state * @param {*} route * @returns */ delOthersVisitedRoutes(state, route) { state.visitedRoutes = state.visitedRoutes.filter((item) => item.meta.affix || item.path === route.path); }, /** * @description 删除当前标签页左边全部多标签页 * @param {*} state * @param {*} route * @returns */ delLeftVisitedRoutes(state, route) { let index = state.visitedRoutes.length; state.visitedRoutes = state.visitedRoutes.filter((item) => { if (item.name === route.name) index = state.visitedRoutes.indexOf(item); return item.meta.affix || index <= state.visitedRoutes.indexOf(item); }); }, /** * @description 删除当前标签页右边全部多标签页 * @param {*} state * @param {*} route * @returns */ delRightVisitedRoutes(state, route) { let index = state.visitedRoutes.length; state.visitedRoutes = state.visitedRoutes.filter((item) => { if (item.name === route.name) index = state.visitedRoutes.indexOf(item); return item.meta.affix || index >= state.visitedRoutes.indexOf(item); }); }, /** * @description 删除全部多标签页 * @param {*} state * @param {*} route * @returns */ delAllVisitedRoutes(state) { state.visitedRoutes = state.visitedRoutes.filter((item) => item.meta.affix); }, }; const actions = { /** * @description 添加标签页 * @param {*} { commit } * @param {*} route */ addVisitedRoute({ commit }, route) { commit("addVisitedRoute", route); }, /** * @description 删除当前标签页 * @param {*} { commit } * @param {*} route */ delVisitedRoute({ commit }, route) { commit("delVisitedRoute", route); }, /** * @description 删除当前标签页以外其它全部多标签页 * @param {*} { commit } * @param {*} route */ delOthersVisitedRoutes({ commit }, route) { commit("delOthersVisitedRoutes", route); }, /** * @description 删除当前标签页左边全部多标签页 * @param {*} { commit } * @param {*} route */ delLeftVisitedRoutes({ commit }, route) { commit("delLeftVisitedRoutes", route); }, /** * @description 删除当前标签页右边全部多标签页 * @param {*} { commit } * @param {*} route */ delRightVisitedRoutes({ commit }, route) { commit("delRightVisitedRoutes", route); }, /** * @description 删除全部多标签页 * @param {*} { commit } */ delAllVisitedRoutes({ commit }) { commit("delAllVisitedRoutes"); }, }; export default { state, getters, mutations, actions };
24.902985
108
0.606832
3b5bd793a752784af35cff6675a59443b4690557
4,459
js
JavaScript
example/friends/friends-supporting.js
vizzuhq/vizzu-beta-release
2621fd14f16342c250966a46f3d5c7f5c8a7bc86
[ "Apache-2.0" ]
7
2021-06-10T14:16:57.000Z
2021-09-17T16:44:11.000Z
example/friends/friends-supporting.js
vizzuhq/vizzu-beta-release
2621fd14f16342c250966a46f3d5c7f5c8a7bc86
[ "Apache-2.0" ]
null
null
null
example/friends/friends-supporting.js
vizzuhq/vizzu-beta-release
2621fd14f16342c250966a46f3d5c7f5c8a7bc86
[ "Apache-2.0" ]
null
null
null
import {data} from './friends-supporting-data.js'; import {Portraits} from './friends-supporting-portraits.js'; import {palette, style} from './friends-supporting-style.js'; import Vizzu from 'https://vizzuhq.github.io/vizzu-beta-release/0.2.0/vizzu.js'; const skip = [ 's01e15', 's01e18', 's01e21', 's01e22', 's01e24', 's02e01', 's02e05', 's02e06', 's02e09', 's02e12', 's02e13', 's02e17', 's02e21', 's03e09', 's03e10', 's03e11', 's03e12', 's03e14', 's03e15', 's03e16', 's03e19', 's03e20', 's03e25', 's04e01', 's04e02', 's04e04', 's04e05', 's04e06', 's04e10', 's04e14', 's04e22', 's05e02', 's05e05', 's05e07', 's05e09', 's05e10', 's05e11', 's05e13', 's05e14', 's05e15', 's05e16', 's05e17', 's05e19', 's05e22', 's05e23', 's05e24', 's06e01', 's06e02', 's06e03', 's06e04', 's06e05', 's06e07', 's06e08', 's06e10', 's06e11', 's06e12', 's06e18', 's06e19', 's06e21', 's07e03', 's07e04', 's07e05', 's07e06', 's07e08', 's07e09', 's07e11', 's07e13', 's07e15', 's07e17', 's07e18', 's07e19', 's07e22', 's08e03', 's08e04', 's08e05', 's08e08', 's08e09', 's08e10', 's08e11', 's08e12', 's08e13', 's08e14', 's08e17', 's08e20', 's08e21', 's08e22', 's09e03', 's09e06', 's09e07', 's09e08', 's09e09', 's09e10', 's09e11', 's09e14', 's09e15', 's09e19', 's09e22', 's10e03', 's10e08', 's10e09', 's10e11', 's10e13', 's10e16' ]; var portraits = new Portraits(); function padZero(num) { return String(num).padStart(2, '0'); } function SEId(id) { return 's' + padZero(id.season) + 'e' + padZero(id.episode); } function next(id) { const seasonLen = [0, 24, 24, 25, 24, 24, 25, 24, 24, 24, 18]; let res = { season: id.season, episode: id.episode }; res.episode++; if (res.episode > seasonLen[res.season]) { res.season++; if (res.season > 10) return undefined; res.episode = 1; } if (res.season == 6 && res.episode == 6) res.episode++; if (res.season == 7 && res.episode == 1) res.episode++; if (res.season == 7 && res.episode == 21) res.episode++; return res; } function drawBg(dc) { dc.drawImage(bgImage, 0, 0); } function text(dc, x, y, sx, sy, txt) { let img = portraits.getByName(txt); if (img !== undefined) { let alpha = String(dc.fillStyle).split(',')[3].slice(0, -1); dc.globalAlpha = alpha; dc.drawImage(img, x + sx + 10, y - 13, 48, 48); dc.globalAlpha = 1; return true; } return false; } function initSlide() { return chart.animate({ data: data, descriptor: { title: '', sort: 'experimental', reverse: true, rotate: -90, }, style: style }); } function waitSlide() { return chart.animate({ style: {legend: {title: {fontSize: Math.random() }}} }); } function slide(seid, actFilter) { return chart.animate({ data: { filter: actFilter }, descriptor: { channels: { x: {attach: ['$exists', 'name'], range: '0,1.02,%'}, y: {attach: ['Lines', 'season'], range: '0,10,1'}, color: {attach: ['season']}, }, title: seid }, style: {plot: {axis: {label: {color: palette[1]}}}} }, { x: { delay: '0s', duration: '.7s', easing: 'linear' }, y: { delay: '0s', duration: '.7s', easing: 'ease-in' }, enable: { delay: '0s', duration: '.7s', easing: 'ease-in' } }); } const bgImage = document.getElementById('bgImage'); let chart = new Vizzu('testVizzuCanvas'); chart.initializing.then(chart => { chart.on('background-draw', event => { drawBg(event.renderingContext); event.preventDefault(); }); chart.on('logo-draw', event => { event.preventDefault(); }); chart.on('plot-axis-label-draw', event => { let rect = event.data.rect; let ok = text(event.renderingContext, rect.pos.x, rect.pos.y, rect.size.x, rect.size.y, event.data.text); if (!ok) event.preventDefault(); }); let res = initSlide(); for (let i = 0; i < 2; i++) res = res.then(() => { return waitSlide(); }); let id = {season: 1, episode: 1}; let filter = []; while (id = next(id), id !== undefined) { let seid = SEId(id); if (data.series[1].values.includes(seid)) { filter.push(seid); if (!skip.includes(seid)) { let actFilter = [...filter]; res = res.then(() => slide(seid, record => actFilter.includes(record.episode))); } } }; for (let i = 0; i < 20; i++) res = res.then(() => waitSlide()); });
30.128378
88
0.568962
3b5be083dd3c90628ce8d8fb62f4cf405bcd4f5d
731
js
JavaScript
x-pack/plugins/maps/public/classes/styles/vector/properties/static_icon_property.js
yojiwatanabe/kibana
1225c32fac1e21d2648f83ee77d01ca2c425cd7a
[ "Apache-2.0" ]
2
2021-04-04T20:57:55.000Z
2022-01-04T22:22:20.000Z
x-pack/plugins/maps/public/classes/styles/vector/properties/static_icon_property.js
yojiwatanabe/kibana
1225c32fac1e21d2648f83ee77d01ca2c425cd7a
[ "Apache-2.0" ]
12
2020-04-20T18:10:48.000Z
2020-07-07T21:24:29.000Z
x-pack/plugins/maps/public/classes/styles/vector/properties/static_icon_property.js
yojiwatanabe/kibana
1225c32fac1e21d2648f83ee77d01ca2c425cd7a
[ "Apache-2.0" ]
1
2020-03-06T01:20:28.000Z
2020-03-06T01:20:28.000Z
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { StaticStyleProperty } from './static_style_property'; import { getMakiSymbolAnchor, getMakiIconId } from '../symbol_utils'; export class StaticIconProperty extends StaticStyleProperty { syncIconWithMb(symbolLayerId, mbMap, iconPixelSize) { const symbolId = this._options.value; mbMap.setLayoutProperty(symbolLayerId, 'icon-anchor', getMakiSymbolAnchor(symbolId)); mbMap.setLayoutProperty(symbolLayerId, 'icon-image', getMakiIconId(symbolId, iconPixelSize)); } }
43
97
0.778386
3b5c4e4a0e09c51f98419b9c9af518024e6becfe
334
js
JavaScript
router.js
Kronapsys/buscadorPelisBackend
75e9472bd44a8e6923343e456ab94ee9ff313c21
[ "MIT" ]
2
2021-03-22T19:12:32.000Z
2021-03-23T08:20:18.000Z
router.js
Kronapsys/buscadorPelisBackend
75e9472bd44a8e6923343e456ab94ee9ff313c21
[ "MIT" ]
null
null
null
router.js
Kronapsys/buscadorPelisBackend
75e9472bd44a8e6923343e456ab94ee9ff313c21
[ "MIT" ]
null
null
null
const router = require("express").Router(); const filmRouter = require("./routers/filmRouter"); const orderRouter = require("./routers/orderRouter"); const userRouter = require("./routers/userRouter"); router.use("/films", filmRouter); router.use("/orders", orderRouter); router.use("/users", userRouter); module.exports = router;
27.833333
53
0.727545
3b5c6966d49fa7865be16a5801a7ce6d17e791fd
13,159
js
JavaScript
static/questions.js
raapperez/mastering-promises
13ef74b14d904e881435ad218c0ee1a902367745
[ "MIT" ]
4
2018-09-12T22:08:54.000Z
2019-02-20T01:51:45.000Z
static/questions.js
raapperez/mastering-promises
13ef74b14d904e881435ad218c0ee1a902367745
[ "MIT" ]
4
2021-03-08T21:51:21.000Z
2021-12-09T00:56:29.000Z
static/questions.js
raapperez/mastering-promises
13ef74b14d904e881435ad218c0ee1a902367745
[ "MIT" ]
1
2018-11-12T20:17:39.000Z
2018-11-12T20:17:39.000Z
function asyncSuccess(param) { return new Promise((resolve) => { setTimeout(() => { resolve(`sucesso(${param})`); }, 100); }); } function asyncFail(param) { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error(`falha(${param})`)); }, 100); }); } window.questions = [ { description: 'Quando a PROMISE é completada com sucesso...', dependencies: [ asyncSuccess, asyncFail, ], problem: function abacaxi() { return asyncSuccess('abacaxi') .then(console.log) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'sucesso(abacaxi)', 'Erro: falha(abacaxi)', 'Erro: sucesso(abacaxi)', ], }, { description: 'Quando a PROMISE é completada com erro...', dependencies: [ asyncFail, ], problem: function beterraba() { return asyncFail('beterraba') .then(console.log) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'sucesso(beterraba)', 'Erro: falha(beterraba)', 'Erro: sucesso(beterraba)', ], }, { description: 'Quando a PROMISE é completada com erro usando await...', dependencies: [ asyncFail, ], problem: async function cebola() { try { const result = await asyncFail('cebola'); console.log(result); } catch (error) { console.log(`Erro: ${error.message}`); } }, answers: [ 'sucesso(cebola)', 'Erro: falha(cebola)', 'Erro: sucesso(cebola)', 'null', ], }, { description: 'Criando uma PROMISE já resolvida...', dependencies: [ ], problem: function mexerica() { return Promise.resolve('mexerica') .then(result => console.log(`Sucesso: ${result}`)) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'Sucesso: mexerica', 'Erro: mexerica', 'null', 'undefined', ], }, { description: 'Criando uma PROMISE já rejeitada...', dependencies: [ ], problem: function goiaba() { return Promise.reject(new Error('goiaba')) .then(result => console.log(`Sucesso: ${result}`)) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'Sucesso: goiaba', 'Erro: goiaba', 'null', 'undefined', ], }, { description: 'PROMISES são executadas "depois", mesmo que já resolvidas...', dependencies: [ ], problem: function caju() { const myPromise = Promise.resolve('caju'); myPromise.then((result) => { console.log(result); }); console.log('cajuzinho'); return myPromise; }, answers: [ 'caju|cajuzinho', 'cajuzinho|caju', ], }, { description: 'Quando acontece um erro no THEN...', dependencies: [ asyncSuccess, ], problem: function milho() { return asyncSuccess('milho') .then((result) => { console.log(result); throw new Error(`falha(${result})`); console.log('milho verde'); }) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'Erro: sucesso(milho)', 'sucesso(milho)|Erro: sucesso(falha(milho))', 'sucesso(milho)|Erro: falha(sucesso(milho))', 'sucesso(milho)|Erro: falha(sucesso(milho))|milho verde', ], }, { description: 'O que acontece: CATCH antes de um THEN num fluxo de sucesso...', dependencies: [ asyncSuccess, ], problem: function laranja() { return asyncSuccess('laranja') .catch(error => console.log(`Erro: ${error.message}`)) .then(console.log); }, answers: [ 'sucesso(laranja)', 'Erro: falha(laranja)', 'undefined', ], }, { description: 'O que acontece: CATCH antes de um THEN num fluxo de erro...', dependencies: [ asyncFail, ], problem: function melancia() { return asyncFail('melancia') .catch(error => console.log(`Erro: ${error.message}`)) .then(console.log); }, answers: [ 'Erro: falha(melancia)', 'Erro: falha(melancia)|sucesso(melancia)', 'Erro: falha(melancia)|undefined', ], }, { description: 'CATCHs podem corrigir um erro...', dependencies: [ asyncFail, ], problem: function banana() { return asyncFail('banana') .then((result) => { console.log('banana prata'); return result; }) .catch((error) => { console.log(`Erro: ${error.message}`); return 'banana nanica'; }) .then(console.log); }, answers: [ 'Erro: falha(banana)|banana nanica', 'banana prata|Erro: falha(banana)|banana nanica', 'Erro: falha(banana)|sucesso(banana naninca)', 'undefined|Erro: falha(banana prata)|banana prata', ], }, { description: 'Os THENs são ignorados no fluxo quando há erro...', dependencies: [ asyncFail, ], problem: function morango() { return asyncFail('morango') .catch((error) => { console.log(`Erro1: ${error.message}`); throw error; }) .then(console.log) .catch((error) => { console.log(`Erro2: ${error.message}`); }); }, answers: [ 'Erro2: falha(morango)', 'Erro1: falha(morango)|Erro2: falha(morango)', 'Erro1: falha(morango)|falha(morango)|Erro2: falha(morango)', ], }, { description: 'É possível retornar PROMISES dentro de THEN / CATCH...', dependencies: [ asyncSuccess, ], problem: function pitanga() { return asyncSuccess('pitanga') .then((result) => { return asyncSuccess(result) .then(console.log); }) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'sucesso(sucesso(pitanga))', 'sucesso(pitanga)|sucesso(pitanga)', 'Erro: sucesso(sucesso(pitanga))', ], }, { description: 'O resultado de um THEN cai no próximo THEN na cadeia...', dependencies: [ asyncSuccess, ], problem: function ameixa() { return asyncSuccess('ameixa') .then((result) => { return asyncSuccess(result); }) .then((result) => { console.log(result); }) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'sucesso(sucesso(ameixa))', 'sucesso(ameixa)|sucesso(ameixa)', 'Erro: sucesso(sucesso(ameixa))', ], }, { description: 'Dificultando um pouco...', dependencies: [ asyncSuccess, ], problem: function cenoura() { return asyncSuccess('cenoura') .then((result) => { return asyncSuccess(result); }) .then((result) => { return asyncSuccess(result) .then(console.log); }) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'sucesso(cenoura)|sucesso(sucesso(cenoura))', 'Erro: sucesso(sucesso(cenoura))', 'sucesso(sucesso(sucesso(cenoura)))', ], }, { description: 'Agora com um erro...', dependencies: [ asyncSuccess, asyncFail, ], problem: function batata() { return asyncSuccess('batata') .then((result) => { return asyncFail(result); }) .then((result) => { return asyncSuccess(result) .then(console.log); }) .catch(error => console.log(`Erro: ${error.message}`)); }, answers: [ 'Erro: sucesso(falha(sucesso(batata)))', 'Erro: falha(sucesso(batata))', 'Erro: sucesso(sucesso(batata(batata)))', ], }, { description: 'Use Promise.all para esperar mais de uma PROMISE...', dependencies: [ ], problem: function amora() { const myPromise = Promise.all([ Promise.resolve('a'), Promise.resolve('m'), Promise.resolve('o'), Promise.resolve('r'), Promise.resolve('a'), ]); return myPromise.then(result => console.log(result.join(''))); }, answers: [ 'amora', '["a", "m", "o", "r", "a"]', ], }, { description: 'A PROMISE só pode ser resolvida ou rejeitada uma vez...', dependencies: [ asyncSuccess, ], problem: function mandioca() { const firstPromise = asyncSuccess('mandioca'); const secondPromise = firstPromise .then((result) => { console.log('aqui'); return `Novo: ${result}`; }); const thirdPromise = secondPromise; return Promise.all([ thirdPromise.then(console.log), thirdPromise.then(console.log), ]); }, answers: [ 'aqui|Novo: sucesso(mandioca)|Novo: sucesso(mandioca)', 'aqui|Novo: sucesso(mandioca)|aqui|Novo: sucesso(mandioca)', 'aqui|aqui|Novo: sucesso(mandioca)', ], }, { description: 'Acontece o mesmo com o CATCH...', dependencies: [ ], problem: function tamarindo() { const myPromise = new Promise((resolve, reject) => { console.log('aqui'); reject(new Error('tamarindo')); }); return Promise.all([ myPromise .then(() => console.log('then')) .catch(error => console.log(`Erro: ${error.message}`)), myPromise.catch(error => console.log(`Erro: ${error.message}`)), myPromise.catch(error => console.log(`Erro: ${error.message}`)), ]); }, answers: [ 'aqui|Erro: tamarindo|Erro: tamarindo|aqui|Erro: tamarindo', 'aqui|Erro: tamarindo|Erro: tamarindo|Erro: tamarindo', 'aqui|then|Erro: tamarindo|Erro: tamarindo|Erro: tamarindo', ], }, { description: 'Comportamento de erro no Promise.all...', dependencies: [ asyncSuccess, asyncFail, ], problem: function coco() { const myPromise = Promise.all([ asyncSuccess('c'), asyncFail('o'), asyncSuccess('c'), asyncFail('o'), ]); return myPromise.then((result) => { console.log(result); }).catch((error) => { console.log(`Erro: ${error.message}`); }); }, answers: [ '["c", undefined, "c", undefined]', 'Erro: ["falha(o)", "falha(o)"]', 'Erro: falha(o)', ], }, { description: 'Tratando erros no Promise.all...', dependencies: [ asyncFail, ], problem: function figo() { const myPromise = Promise.all([ Promise.resolve('f').catch(err => err.message), asyncFail('i').catch(err => err.message), Promise.resolve('g').catch(err => err.message), asyncFail('o').catch(err => err.message), ]); return myPromise.then((result) => { console.log(result.join('-')); }).catch((error) => { console.log(`Error: ${error.message}`); }); }, answers: [ 'f-i-g-o', 'f-falha(i)-g-falha(o)', 'Error: f-falha(i)-g-falha(o)', ], }, { description: 'Executando cada PROMISE do array por vez...', dependencies: [ ], problem: function kiwi() { const promises = [ () => Promise.resolve('k'), () => Promise.resolve('i'), () => Promise.resolve('w'), () => Promise.resolve('i'), ]; return promises.reduce((lastPromise, currentPromise) => { return lastPromise.then(currentPromise); }, Promise.resolve()) .then((result) => { console.log(result); }); }, answers: [ 'i', 'kiwi', '["k", "i", "w", "i"]', ], }, { description: 'Melhorando...', dependencies: [ ], problem: function jaca() { const promises = [ () => Promise.resolve('j'), () => Promise.resolve('a'), () => Promise.resolve('c'), () => Promise.resolve('a'), ]; return promises.reduce((lastPromise, currentPromise) => { return lastPromise.then((lastResult) => { return currentPromise().then(currentResult => [...lastResult, currentResult]); }); }, Promise.resolve([])).then((result) => { console.log(result.join('')); }); }, answers: [ 'a', 'jaca', '["j", "a", "c", "a"]', ], }, { description: 'Melhorando...', dependencies: [ asyncFail, ], problem: function uva() { const promises = [ () => Promise.resolve('u').catch(err => err.message), () => asyncFail('v').catch(err => err.message), () => asyncFail('a').catch(err => err.message), ]; return promises.reduce((lastPromise, currentPromise) => { return lastPromise.then((lastResult) => { return currentPromise().then(currentResult => [...lastResult, currentResult]); }); }, Promise.resolve([])).then((result) => { console.log(result.join('-')); }); }, answers: [ 'a', 'u-v-a', 'u-falha(v)-falha(a)', 'undefined', ], }, ];
25.903543
88
0.531043
3b5cc336d63ab61a8cd3aa48214c96e55b530fb2
571
js
JavaScript
platform/viewer/src/components/BrainnowLogo/BrainnowLogo.js
wuzhuobin/Viewers
02ab9e7d7a164ef32ea05c75571380e2aeb61003
[ "MIT" ]
null
null
null
platform/viewer/src/components/BrainnowLogo/BrainnowLogo.js
wuzhuobin/Viewers
02ab9e7d7a164ef32ea05c75571380e2aeb61003
[ "MIT" ]
5
2019-12-12T09:22:02.000Z
2020-01-15T02:58:46.000Z
platform/viewer/src/components/BrainnowLogo/BrainnowLogo.js
wuzhuobin/Viewers
02ab9e7d7a164ef32ea05c75571380e2aeb61003
[ "MIT" ]
null
null
null
import './BrainnowLogo.css'; import BrainnowIcon from './brainnow-icon.svg' import React from 'react'; function BrainnowLogo() { return ( <a target="_blank" rel="noopener noreferrer" className="header-brand" href="http://brainnow.cn" > <BrainnowIcon className="header-logo-image1"></BrainnowIcon> {/* Logo text would fit smaller displays at two lines: * * Open Health * Imaging Foundation * * Or as `OHIF` on really small displays */} </a> ); } export default BrainnowLogo;
21.148148
66
0.609457
3b5ce886edf7ee8979a51ef05ab36115a66acbb2
2,529
js
JavaScript
scripts/utilities/utils.js
JCGithu/Sinon
4d00a9f276d3f54b3557290a95655b3c4a2e1a42
[ "MIT" ]
null
null
null
scripts/utilities/utils.js
JCGithu/Sinon
4d00a9f276d3f54b3557290a95655b3c4a2e1a42
[ "MIT" ]
2
2020-11-23T15:55:41.000Z
2020-11-24T12:28:50.000Z
scripts/utilities/utils.js
JCGithu/Sinon
4d00a9f276d3f54b3557290a95655b3c4a2e1a42
[ "MIT" ]
3
2020-11-17T10:35:23.000Z
2021-08-06T01:18:50.000Z
function copyString(str) { var el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style = { position: 'absolute', left: '-9999px' }; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); console.log('Clipboard updated'); lineBreak(); } function swalColours() { let darkMode = document.getElementById('darkMode'); if (darkMode.checked) { (swalColour.fail = '#232323'), (swalColour.loading = '#2c3e50'), (swalColour.pass = '#2c3e50'); } else { (swalColour.fail = '#ED6A5A'), (swalColour.loading = 'rgba(0,0,0,0.4)'), (swalColour.pass = '#30bced'); } } function lineBreak() { console.log('~=~=~=~=~=~=~=~=~=~=~=~'); } function progressBar(progress, format, targetFiles) { let progressText = document.getElementById('progressText'); if (progress.percent === undefined) { progressText.textContent = progress.timemark.match('dd:dd:dd)'); } else { if (format.indexOf('concat') >= 0) { progress.percent = progress.percent / targetFiles.length; } if (progress.percent >= 100) { progress.percent = 99.9; } if (progressText) { progressText.textContent = (Math.round(progress.percent * 100) / 100).toFixed(1) + '%'; console.log('Processing: ' + Math.floor(progress.percent) + '% done'); let percentage = parseFloat((Math.round(progress.percent) / 100).toFixed(2)); win.setProgressBar(percentage); } } } function docReady(fn) { if (document.readyState === 'complete' || document.readyState === 'interactive') { setTimeout(fn, 1); } else { document.addEventListener('DOMContentLoaded', fn); } } function URLwipe() { if (document.getElementById('urlWipe').checked) { console.log('URL Wipe applied'); document.getElementById('inputURL').value = ''; } } const axios = require('axios'); async function versionChecker() { return axios.get('http://colloquial.studio/sinondata.json').then(async (response) => { let element = document.getElementById('ver'); if (element.innerHTML !== response.data.version) { element.style = 'color:var(--hover)'; let docs = document.getElementById('documentation'); let docText = `<h4 style="color:var(--hover)">// Current version of Sinon is ${response.data.version}</h4>` + docs.innerHTML; docs.innerHTML = docText; } }); } module.exports = { docReady, lineBreak, progressBar, swalColours, copyString, URLwipe, versionChecker };
32.012658
119
0.652036
3b5d35efc184145a284b2cf2c7e9dd189434126d
1,339
js
JavaScript
plugins/lunchbadger-monitor/src/components/Metric/Subelements/MetricType.js
LunchBadger/lunchbadger-container
48d0103fbb7e32e684d78d44ddd4283c1604cb3a
[ "Apache-2.0" ]
3
2020-07-27T18:44:02.000Z
2022-02-09T21:19:36.000Z
plugins/lunchbadger-monitor/src/components/Metric/Subelements/MetricType.js
LunchBadger/lunchbadger-container
48d0103fbb7e32e684d78d44ddd4283c1604cb3a
[ "Apache-2.0" ]
1
2022-02-10T18:31:45.000Z
2022-02-10T18:31:45.000Z
plugins/lunchbadger-monitor/src/components/Metric/Subelements/MetricType.js
LunchBadger/lunchbadger-container
48d0103fbb7e32e684d78d44ddd4283c1604cb3a
[ "Apache-2.0" ]
2
2020-01-06T13:53:10.000Z
2020-12-29T17:19:52.000Z
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {AND, OR, NOT} from '../../../models/MetricPair'; import classNames from 'classnames'; import './MetricType.scss'; export default class MetricType extends Component { static propTypes = { pair: PropTypes.object.isRequired, circlesClick: PropTypes.func, isCurrentPair: PropTypes.bool }; constructor(props) { super(props); } _handleCirclesClick = () => { if (typeof this.props.circlesClick === 'function') { this.props.circlesClick( (this.props.isCurrentPair) ? null : this.props.pair ); } } render() { const {pair} = this.props; const typeClass = classNames({ 'metric-type': true, 'metric-type--current': this.props.isCurrentPair, 'metric-type--and': pair.type === AND, 'metric-type--not': pair.type === NOT, 'metric-type--or': pair.type === OR }); return ( <div className={typeClass} onClick={this._handleCirclesClick}> <figure className="metric-type__circles"> <span className="metric-type__circle metric-type__circle--left"/> <span className="metric-type__circle metric-type__circle--right"/> </figure> <span className="metric-type__name">{this.props.pair.type}</span> </div> ); } }
28.489362
76
0.634802
3b5e03fefd5168f77c8d6b97d01c30ce6c7e71fe
216
js
JavaScript
lodash/.internal/assocIndexOf.js
littlelake/js-tool
737ab777635681e79d231ae65e7cb9fed8fea1ca
[ "MIT" ]
null
null
null
lodash/.internal/assocIndexOf.js
littlelake/js-tool
737ab777635681e79d231ae65e7cb9fed8fea1ca
[ "MIT" ]
null
null
null
lodash/.internal/assocIndexOf.js
littlelake/js-tool
737ab777635681e79d231ae65e7cb9fed8fea1ca
[ "MIT" ]
null
null
null
import eq from '../eq'; function assocIndexOf(array, key) { let {length} = array; while(length--) { if(eq(array[length][0], key)) { return length; } } return -1; } export default assocIndexOf;
16.615385
35
0.601852
3b5e194e57841af77dc5f97dda0d2026a0887602
12,701
js
JavaScript
out/artifacts/CM_relaease_war_exploded/scripts/h.js
6ylqq/meeting-master
5992443926c3a01dbffa08fa919c239eeb8de03e
[ "Apache-2.0" ]
null
null
null
out/artifacts/CM_relaease_war_exploded/scripts/h.js
6ylqq/meeting-master
5992443926c3a01dbffa08fa919c239eeb8de03e
[ "Apache-2.0" ]
null
null
null
out/artifacts/CM_relaease_war_exploded/scripts/h.js
6ylqq/meeting-master
5992443926c3a01dbffa08fa919c239eeb8de03e
[ "Apache-2.0" ]
2
2020-12-31T03:59:58.000Z
2022-03-15T08:45:43.000Z
(function(){var c={id:"6338835ad35c6d950a554fdedb598e48",dm:["ghostchina.com"],etrk:[],js:"tongji.baidu.com/hm-web/js/",icon:'',br:false,ctrk:false,align:-1,nv:-1,vdur:1800000,age:31536000000,rec:0,rp:[],trust:0,vcard:0,se:[]}; var l=!0,m=null,n=!1;var p=function(){function a(a){/["\\\x00-\x1f]/.test(a)&&(a=a.replace(/["\\\x00-\x1f]/g,function(a){var b=d[a];if(b)return b;b=a.charCodeAt();return"\\u00"+Math.floor(b/16).toString(16)+(b%16).toString(16)}));return'"'+a+'"'}function b(a){return 10>a?"0"+a:a}var d={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return function(d){switch(typeof d){case "undefined":return"undefined";case "number":return isFinite(d)?String(d):"null";case "string":return a(d);case "boolean":return String(d); default:if(d===m)return"null";if(d instanceof Array){var f=["["],k=d.length,h,g,u;for(g=0;g<k;g++)switch(u=d[g],typeof u){case "undefined":case "function":case "unknown":break;default:h&&f.push(","),f.push(p(u)),h=1}f.push("]");return f.join("")}if(d instanceof Date)return'"'+d.getFullYear()+"-"+b(d.getMonth()+1)+"-"+b(d.getDate())+"T"+b(d.getHours())+":"+b(d.getMinutes())+":"+b(d.getSeconds())+'"';h=["{"];for(k in d)if(Object.prototype.hasOwnProperty.call(d,k))switch(g=d[k],typeof g){case "undefined":case "unknown":case "function":break; default:f&&h.push(","),f=1,h.push(p(k)+":"+p(g))}h.push("}");return h.join("")}}}();function q(a,b){var d=a.match(RegExp("(^|&|\\?|#)("+b+")=([^&#]*)(&|$|#)",""));return d?d[3]:m}function v(a){return(a=(a=a.match(/^(https?:\/\/)?([^\/\?#]*)/))?a[2].replace(/.*@/,""):m)?a.replace(/:\d+$/,""):a};function w(a,b){if(window.sessionStorage)try{window.sessionStorage.setItem(a,b)}catch(d){}}function x(a){return window.sessionStorage?window.sessionStorage.getItem(a):m};function y(a,b,d){var e;d.f&&(e=new Date,e.setTime(e.getTime()+d.f));document.cookie=a+"="+b+(d.domain?"; domain="+d.domain:"")+(d.path?"; path="+d.path:"")+(e?"; expires="+e.toGMTString():"")+(d.r?"; secure":"")};function B(a,b){var d=new Image,e="mini_tangram_log_"+Math.floor(2147483648*Math.random()).toString(36);window[e]=d;d.onload=d.onerror=d.onabort=function(){d.onload=d.onerror=d.onabort=m;d=window[e]=m;b&&b(a)};d.src=a};var C;function F(){if(!C)try{C=document.createElement("input"),C.type="hidden",C.style.display="none",C.addBehavior("#default#userData"),document.getElementsByTagName("head")[0].appendChild(C)}catch(a){return n}return l}function G(a,b,d){var e=new Date;e.setTime(e.getTime()+d||31536E6);try{window.localStorage?(b=e.getTime()+"|"+b,window.localStorage.setItem(a,b)):F()&&(C.expires=e.toUTCString(),C.load(document.location.hostname),C.setAttribute(a,b),C.save(document.location.hostname))}catch(f){}} function H(a){if(window.localStorage){if(a=window.localStorage.getItem(a)){var b=a.indexOf("|"),d=a.substring(0,b)-0;if(d&&d>(new Date).getTime())return a.substring(b+1)}}else if(F())try{return C.load(document.location.hostname),C.getAttribute(a)}catch(e){}return m};function I(a,b,d){a.attachEvent?a.attachEvent("on"+b,function(b){d.call(a,b)}):a.addEventListener&&a.addEventListener(b,d,n)};(function(){function a(){if(!a.b){a.b=l;for(var b=0,d=e.length;b<d;b++)e[b]()}}function b(){try{document.documentElement.doScroll("left")}catch(d){setTimeout(b,1);return}a()}var d=n,e=[],f;document.addEventListener?f=function(){document.removeEventListener("DOMContentLoaded",f,n);a()}:document.attachEvent&&(f=function(){"complete"===document.readyState&&(document.detachEvent("onreadystatechange",f),a())});(function(){if(!d)if(d=l,"complete"===document.readyState)a.b=l;else if(document.addEventListener)document.addEventListener("DOMContentLoaded", f,n),window.addEventListener("load",a,n);else if(document.attachEvent){document.attachEvent("onreadystatechange",f);window.attachEvent("onload",a);var e=n;try{e=window.frameElement==m}catch(h){}document.documentElement.doScroll&&e&&b()}})();return function(b){a.b?b():e.push(b)}})().b=n;function N(a,b){return"[object "+b+"]"==={}.toString.call(a)};var aa=navigator.cookieEnabled,ba=navigator.javaEnabled(),ha=navigator.language||navigator.browserLanguage||navigator.systemLanguage||navigator.userLanguage||"",ia=window.screen.width+"x"+window.screen.height,ja=window.screen.colorDepth;var O=0,P=Math.round(+new Date/1E3),Q="https:"==document.location.protocol?"https:":"http:",R="cc cf ci ck cl cm cp cw ds ep et fl ja ln lo lt nv rnd si st su v cv lv api tt u".split(" ");function V(){if("undefined"==typeof window["_bdhm_loaded_"+c.id]){window["_bdhm_loaded_"+c.id]=l;var a=this;a.a={};a.q=[];a.p={push:function(){a.k.apply(a,arguments)}};a.c=0;a.h=n;ka(a)}} V.prototype={getData:function(a){try{var b=RegExp("(^| )"+a+"=([^;]*)(;|$)").exec(document.cookie);return(b?b[2]:m)||x(a)||H(a)}catch(d){}},setData:function(a,b,d){try{y(a,b,{domain:la(),path:ma(),f:d}),d?G(a,b,d):w(a,b)}catch(e){}},k:function(a){if(N(a,"Array")){var b=function(a){return a.replace?a.replace(/'/g,"'0").replace(/\*/g,"'1").replace(/!/g,"'2"):a};switch(a[0]){case "_trackPageview":if(1<a.length&&a[1].charAt&&"/"==a[1].charAt(0)){this.a.api|=4;this.a.et=0;this.a.ep="";this.h?(this.a.nv= 0,this.a.st=4):this.h=l;var b=this.a.u,d=this.a.su;this.a.u=Q+"//"+document.location.host+a[1];this.a.su=document.location.href;W(this);this.a.u=b;this.a.su=d}break;case "_trackEvent":2<a.length&&(this.a.api|=8,this.a.nv=0,this.a.st=4,this.a.et=4,this.a.ep=b(a[1])+"*"+b(a[2])+(a[3]?"*"+b(a[3]):"")+(a[4]?"*"+b(a[4]):""),W(this));break;case "_setCustomVar":if(4>a.length)break;var d=a[1],e=a[4]||3;if(0<d&&6>d&&0<e&&4>e){this.c++;for(var f=(this.a.cv||"*").split("!"),k=f.length;k<d-1;k++)f.push("*"); f[d-1]=e+"*"+b(a[2])+"*"+b(a[3]);this.a.cv=f.join("!");a=this.a.cv.replace(/[^1](\*[^!]*){2}/g,"*").replace(/((^|!)\*)+$/g,"");""!==a?this.setData("Hm_cv_"+c.id,encodeURIComponent(a),c.age):na()}break;case "_trackOrder":a=a[1];if(N(a,"Object")){var h=function(a){for(var b in a)if({}.hasOwnProperty.call(a,b)){var d=a[b];N(d,"Object")||N(d,"Array")?h(d):a[b]=String(d)}};h(a);this.a.api|=16;this.a.nv=0;this.a.st=4;this.a.et=94;this.a.ep=p(a);W(this)}break;case "_trackMobConv":if(a={webim:1,tel:2,map:3, sms:4,callback:5,share:6}[a[1]])this.a.api|=32,this.a.et=93,this.a.ep=a,W(this)}}}};function oa(){var a=x("Hm_unsent_"+c.id);if(a)for(var a=a.split(","),b=0,d=a.length;b<d;b++)B(Q+"//"+decodeURIComponent(a[b]).replace(/^https?:\/\//,""),function(a){X(a)})} function X(a){var b=x("Hm_unsent_"+c.id)||"";b&&((b=b.replace(RegExp(encodeURIComponent(a.replace(/^https?:\/\//,"")).replace(/([\*\(\)])/g,"\\$1")+"(%26u%3D[^,]*)?,?","g"),"").replace(/,$/,""))?w("Hm_unsent_"+c.id,b):window.sessionStorage&&window.sessionStorage.removeItem("Hm_unsent_"+c.id))}function qa(a,b){var d=x("Hm_unsent_"+c.id)||"",e=a.a.u?"":"&u="+encodeURIComponent(document.location.href),d=encodeURIComponent(b.replace(/^https?:\/\//,"")+e)+(d?","+d:"");w("Hm_unsent_"+c.id,d)} function W(a){a.a.rnd=Math.round(2147483647*Math.random());a.a.api=a.a.api||a.c?a.a.api+"_"+a.c:"";var b=Q+"//hm.baidu.com/hm.gif?"+ra(a);a.a.api=0;a.c=0;qa(a,b);B(b,function(a){X(a)})}function sa(a){return function(){a.a.nv=0;a.a.st=4;a.a.et=3;a.a.ep=(new Date).getTime()-a.e.j+","+((new Date).getTime()-a.e.d+a.e.i);W(a)}} function ka(a){try{var b,d,e,f,k,h,g;O=a.getData("Hm_lpvt_"+c.id)||0;13==O.length&&(O=Math.round(O/1E3));if(document.referrer){var u=n;if(Y(document.referrer)&&Y(document.location.href))u=l;else var pa=v(document.referrer),u=Z(pa||"",document.location.hostname);d=u?P-O>c.vdur?1:4:3}else d=P-O>c.vdur?1:4;b=4!=d?1:0;if(h=a.getData("Hm_lvt_"+c.id)){g=h.split(",");for(var D=g.length-1;0<=D;D--)13==g[D].length&&(g[D]=""+Math.round(g[D]/1E3));for(;2592E3<P-g[0];)g.shift();k=4>g.length?2:3;for(1===b&&g.push(P);4< g.length;)g.shift();h=g.join(",");f=g[g.length-1]}else h=P,f="",k=1;a.setData("Hm_lvt_"+c.id,h,c.age);a.setData("Hm_lpvt_"+c.id,P);e=P==a.getData("Hm_lpvt_"+c.id)?"1":"0";if(0==c.nv&&Y(document.location.href)&&(""==document.referrer||Y(document.referrer)))b=0,d=4;a.a.nv=b;a.a.st=d;a.a.cc=e;a.a.lt=f;a.a.lv=k;a.a.si=c.id;a.a.su=document.referrer;a.a.ds=ia;a.a.cl=ja+"-bit";a.a.ln=ha;a.a.ja=ba?1:0;a.a.ck=aa?1:0;a.a.lo="number"==typeof _bdhm_top?1:0;var J=a.a;b="";if(navigator.plugins&&navigator.mimeTypes.length){var z= navigator.plugins["Shockwave Flash"];z&&z.description&&(b=z.description.replace(/^.*\s+(\S+)\s+\S+$/,"$1"))}else if(window.ActiveXObject)try{var ca=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");ca&&(b=ca.GetVariable("$version"))&&(b=b.replace(/^.*\s+(\d+),(\d+).*$/,"$1.$2"))}catch(ya){}J.fl=b;a.a.v="1.0.59";a.a.cv=decodeURIComponent(a.getData("Hm_cv_"+c.id)||"");1==a.a.nv&&(a.a.tt=document.title||"");a.a.api=0;var E=document.location.href;a.a.cm=q(E,"hmmd")||"";a.a.cp=q(E,"hmpl")||"";a.a.cw= q(E,"hmkw")||"";a.a.ci=q(E,"hmci")||"";a.a.cf=q(E,"hmsr")||"";0==a.a.nv?oa():X(".*");if(""!=c.icon){var r,s=c.icon.split("|"),S="http://tongji.baidu.com/hm-web/welcome/ico?s="+c.id,T=("http:"==Q?"http://eiv":"https://bs")+".baidu.com"+s[0]+"."+s[1];switch(s[1]){case "swf":var da=s[2],ea=s[3],J="s="+S,z="HolmesIcon"+P;r='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id="'+z+'" width="'+da+'" height="'+ea+'"><param name="movie" value="'+T+'" /><param name="flashvars" value="'+(J||"")+ '" /><param name="allowscriptaccess" value="always" /><embed type="application/x-shockwave-flash" name="'+z+'" width="'+da+'" height="'+ea+'" src="'+T+'" flashvars="'+(J||"")+'" allowscriptaccess="always" /></object>';break;case "gif":r='<a href="'+S+'" target="_blank"><img border="0" src="'+T+'" width="'+s[2]+'" height="'+s[3]+'"></a>';break;default:r='<a href="'+S+'" target="_blank">'+s[0]+"</a>"}document.write(r)}var K=document.location.hash.substring(1),ua=RegExp(c.id),va=-1<document.referrer.indexOf("baidu.com")? l:n;if(K&&ua.test(K)&&va){var L=document.createElement("script");L.setAttribute("type","text/javascript");L.setAttribute("charset","utf-8");L.setAttribute("src",Q+"//"+c.js+q(K,"jn")+"."+q(K,"sx")+"?"+a.a.rnd);var fa=document.getElementsByTagName("script")[0];fa.parentNode.insertBefore(L,fa)}a.m&&a.m();a.l&&a.l();if(c.rec||c.trust)a.a.nv?(a.g=encodeURIComponent(document.referrer),window.sessionStorage?w("Hm_from_"+c.id,a.g):G("Hm_from_"+c.id,a.g,864E5)):a.g=(window.sessionStorage?x("Hm_from_"+c.id): H("Hm_from_"+c.id))||"";a.n&&a.n();a.o&&a.o();a.e=new ta;I(window,"beforeunload",sa(a));var t=window._hmt;if(t&&t.length)for(r=0;r<t.length;r++){var A=t[r];switch(A[0]){case "_setAccount":1<A.length&&/^[0-9a-z]{32}$/.test(A[1])&&(a.a.api|=1,window._bdhm_account=A[1]);break;case "_setAutoPageview":if(1<A.length){var U=A[1];if(n===U||l===U)a.a.api|=2,window._bdhm_autoPageview=U}}}if("undefined"===typeof window._bdhm_account||window._bdhm_account===c.id){window._bdhm_account=c.id;var M=window._hmt;if(M&& M.length)for(var t=0,xa=M.length;t<xa;t++)a.k(M[t]);window._hmt=a.p}if("undefined"===typeof window._bdhm_autoPageview||window._bdhm_autoPageview===l)a.h=l,a.a.et=0,a.a.ep="",W(a)}catch(ga){a=[],a.push("si="+c.id),a.push("n="+encodeURIComponent(ga.name)),a.push("m="+encodeURIComponent(ga.message)),a.push("r="+encodeURIComponent(document.referrer)),B(Q+"//hm.baidu.com/hm.gif?"+a.join("&"))}} function ra(a){for(var b=[],d=0,e=R.length;d<e;d++){var f=R[d],k=a.a[f];"undefined"!=typeof k&&""!==k&&b.push(f+"="+encodeURIComponent(k))}return b.join("&")}function na(){var a="Hm_cv_"+c.id;try{if(y(a,"",{domain:la(),path:ma(),f:-1}),window.sessionStorage&&window.sessionStorage.removeItem(a),window.localStorage)window.localStorage.removeItem(a);else if(F())try{C.load(document.location.hostname),C.removeAttribute(a),C.save(document.location.hostname)}catch(b){}}catch(d){}} function ma(){for(var a=0,b=c.dm.length;a<b;a++){var d=c.dm[a];if(-1<d.indexOf("/")&&wa(document.location.href,d))return d.replace(/^[^\/]+(\/.*)/,"$1")+"/"}return"/"}function la(){for(var a=document.location.hostname,b=0,d=c.dm.length;b<d;b++)if(Z(a,c.dm[b]))return c.dm[b].replace(/(:\d+)?[\/\?#].*/,"");return a}function Y(a){for(var b=0;b<c.dm.length;b++)if(-1<c.dm[b].indexOf("/")){if(wa(a,c.dm[b]))return l}else{var d=v(a);if(d&&Z(d,c.dm[b]))return l}return n} function wa(a,b){a=a.replace(/^https?:\/\//,"");return 0==a.indexOf(b)}function Z(a,b){a="."+a.replace(/:\d+/,"");b="."+b.replace(/:\d+/,"");var d=a.indexOf(b);return-1<d&&d+b.length==a.length}function ta(){this.d=this.j=(new Date).getTime();this.i=0;"object"==typeof document.onfocusin?(I(document,"focusin",$(this)),I(document,"focusout",$(this))):(I(window,"focus",$(this)),I(window,"blur",$(this)))} function $(a){return function(b){if(!(b.target&&b.target!=window)){if("blur"==b.type||"focusout"==b.type)a.i+=(new Date).getTime()-a.d;a.d=(new Date).getTime()}}}new V;})();
508.04
1,398
0.643571
3b5e2e480797655ff0946a2b6b393c195d3d0504
64
js
JavaScript
tests/await binary left/input.js
jimmydief/babel-plugin-transform-async-to-promises
b409b91db5d3cef756f3028fa3f67ded6b820120
[ "MIT" ]
233
2018-01-07T16:09:06.000Z
2022-02-15T14:08:38.000Z
tests/await binary left/input.js
jimmydief/babel-plugin-transform-async-to-promises
b409b91db5d3cef756f3028fa3f67ded6b820120
[ "MIT" ]
75
2018-02-21T21:32:11.000Z
2022-02-25T12:03:22.000Z
tests/await binary left/input.js
jimmydief/babel-plugin-transform-async-to-promises
b409b91db5d3cef756f3028fa3f67ded6b820120
[ "MIT" ]
22
2018-04-02T12:44:06.000Z
2022-03-07T17:20:57.000Z
async function(left, right) { return await left() + right(); }
16
31
0.65625
3b5e4e97c98a3d1579f6543c2b8b99b135b6e7b3
2,287
js
JavaScript
client/question/services/AutosaveServiceSpec.js
google/tie
156c8410de2e4a85f2ccba5e1bb07e80b7598bf6
[ "Apache-2.0" ]
414
2017-02-10T06:43:34.000Z
2022-01-14T07:16:55.000Z
client/question/services/AutosaveServiceSpec.js
google/tie
156c8410de2e4a85f2ccba5e1bb07e80b7598bf6
[ "Apache-2.0" ]
587
2017-02-15T01:54:25.000Z
2022-02-04T01:43:26.000Z
client/question/services/AutosaveServiceSpec.js
google/tie
156c8410de2e4a85f2ccba5e1bb07e80b7598bf6
[ "Apache-2.0" ]
71
2017-02-16T01:02:47.000Z
2022-03-03T22:36:04.000Z
// Copyright 2017 The TIE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the AutosaveService. */ describe('AutosaveService', function() { var AutosaveService; var CurrentQuestionService; // In the Karma test environment, the deferred promise gets resolved only // when $rootScope.$digest() is called. var $rootScope; beforeEach(module('tie')); beforeEach(inject(function($injector) { AutosaveService = $injector.get('AutosaveService'); CurrentQuestionService = $injector.get('CurrentQuestionService'); $rootScope = $injector.get('$rootScope'); localStorage.clear(); })); describe('basic functionality', function() { it('should only activate after the question is loaded', function(done) { expect(function() { AutosaveService.getLastSavedCode('python'); }).toThrow(); CurrentQuestionService.init(function() { expect(AutosaveService.getLastSavedCode('python')).toEqual(null); done(); }); $rootScope.$digest(); }); it('should save and retrieve code', function(done) { CurrentQuestionService.init(function() { AutosaveService.saveCode('python', 'py_code'); AutosaveService.saveCode('java', 'java_code'); expect(AutosaveService.getLastSavedCode('python')).toEqual('py_code'); expect(AutosaveService.getLastSavedCode('java')).toEqual('java_code'); done(); }); $rootScope.$digest(); }); it('should return null if code is not found', function(done) { CurrentQuestionService.init(function() { expect(AutosaveService.getLastSavedCode('python')).toEqual(null); done(); }); $rootScope.$digest(); }); }); });
34.651515
78
0.678618
3b5e7d0cf54d4120fffd695a2dfa92eeaca83e2a
1,955
js
JavaScript
lib/config/ConfigProviderBuilder.js
bemisguided/rue-config
79473368ea3093b8fbebacfc72d58f8a122b876a
[ "Apache-2.0" ]
1
2017-07-09T14:43:54.000Z
2017-07-09T14:43:54.000Z
lib/config/ConfigProviderBuilder.js
bemisguided/rue-config
79473368ea3093b8fbebacfc72d58f8a122b876a
[ "Apache-2.0" ]
null
null
null
lib/config/ConfigProviderBuilder.js
bemisguided/rue-config
79473368ea3093b8fbebacfc72d58f8a122b876a
[ "Apache-2.0" ]
null
null
null
/** * Rue - nodejs dependency injection container * * Copyright 2017 Martin Crawford (@bemisguided) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @flow */ import { Container, factory } from 'rue'; import ConfigConstants from './ConfigConstants'; import ConfigDependencyNameMapper from './ConfigDependencyNameMapper'; import ConfigPreInjectionFilter from './ConfigPreInjectionFilter'; import type { ConfigProviderFactoryFunction } from './ConfigProviderFactoryFunction'; import ConfigProvider from './ConfigProvider'; export default class ConfigProviderBuilder { container: Container; configProviderFactoryFunction: ConfigProviderFactoryFunction<ConfigProvider>; profileNames: Array<string>; constructor<P: ConfigProvider>(configProviderFactoryFunction: ConfigProviderFactoryFunction<P>, container: Container) { this.container = container; this.configProviderFactoryFunction = configProviderFactoryFunction; this.profileNames = []; } done() { this.container.dependencyNameMappers.push(new ConfigDependencyNameMapper()); factory(ConfigConstants.CONFIG_NAME, this.container) .useFunction(this.configProviderFactoryFunction) .isSingleton(true) .withProfiles(...this.profileNames) .withFilter(new ConfigPreInjectionFilter()) .done(); } withProfiles(...profileNames: Array<string>): ConfigProviderBuilder { this.profileNames = profileNames; return this; } }
33.706897
121
0.761125
3b5eaac7ecb46b0bf189d224f84fda879c21856d
4,356
js
JavaScript
migrations/20211004041324-add_mac_products.js
danielchungara1/mex-back
2b79b3c44bc46fa9b820b915ff487efd092ca905
[ "MIT" ]
null
null
null
migrations/20211004041324-add_mac_products.js
danielchungara1/mex-back
2b79b3c44bc46fa9b820b915ff487efd092ca905
[ "MIT" ]
null
null
null
migrations/20211004041324-add_mac_products.js
danielchungara1/mex-back
2b79b3c44bc46fa9b820b915ff487efd092ca905
[ "MIT" ]
null
null
null
module.exports = { async up(db, client) { // TODO write your migration here. // See https://github.com/seppevs/migrate-mongo/#creating-a-new-migration-script // Example: await db.collection('products').insertMany( [ { "_id": 13, "description": "Cable Repuesto Cargador Macbook Air Pro Magsafe 1 Y 2 ", "price": 1890, "stock": 10, "imageUrlSm": "https://http2.mlstatic.com/D_NQ_NP_990177-MLA46926485597_072021-V.webp", "imageUrlMd": "https://http2.mlstatic.com/D_NQ_NP_990177-MLA46926485597_072021-V.webp", "imageUrlLg": "https://http2.mlstatic.com/D_NQ_NP_990177-MLA46926485597_072021-V.webp", }, { "_id": 14, "description": "Apple MacBook Pro (13 pulgadas, 2020, Chip M1, 512 GB de SSD, 8 GB de RAM) - Gris espacial", "price": 286128, "stock": 2, "imageUrlSm": "https://http2.mlstatic.com/D_NQ_NP_756770-MLA45795181650_052021-V.webp", "imageUrlMd": "https://http2.mlstatic.com/D_NQ_NP_756770-MLA45795181650_052021-V.webp", "imageUrlLg": "https://http2.mlstatic.com/D_NQ_NP_756770-MLA45795181650_052021-V.webp", }, { "_id": 15, "description": "MacBook Air A1466 plata 13.3\", Intel Core i5 5350U 8GB de RAM 128GB SSD, Intel HD Graphics 6000 1440x900px macOS", "price": 154999, "stock": 5, "imageUrlSm": "https://http2.mlstatic.com/D_NQ_NP_722803-MLA42901955282_072020-V.webp", "imageUrlMd": "https://http2.mlstatic.com/D_NQ_NP_722803-MLA42901955282_072020-V.webp", "imageUrlLg": "https://http2.mlstatic.com/D_NQ_NP_722803-MLA42901955282_072020-V.webp", }, { "_id": 16, "description": "Apple Macbook Air (13 pulgadas, 2020, Chip M1, 256 GB de SSD, 8 GB de RAM) - Gris espacial", "price": 172276, "stock": 5, "imageUrlSm": "https://http2.mlstatic.com/D_NQ_NP_801112-MLA46516512347_062021-V.webp", "imageUrlMd": "https://http2.mlstatic.com/D_NQ_NP_801112-MLA46516512347_062021-V.webp", "imageUrlLg": "https://http2.mlstatic.com/D_NQ_NP_801112-MLA46516512347_062021-V.webp", }, { "_id": 17, "description": "Apple Magic Mouse 2 Plata", "price": 12491, "stock": 15, "imageUrlSm": "https://http2.mlstatic.com/D_NQ_NP_856166-MLA46403910103_062021-V.webp", "imageUrlMd": "https://http2.mlstatic.com/D_NQ_NP_856166-MLA46403910103_062021-V.webp", "imageUrlLg": "https://http2.mlstatic.com/D_NQ_NP_856166-MLA46403910103_062021-V.webp", }, { "_id": 18, "description": "Notebook Apple Macbook Pro 13'' 8 Core M1 Chip 512gb Ssd", "price": 272999, "stock": 5, "imageUrlSm": "https://http2.mlstatic.com/D_NQ_NP_966675-MLA46335561609_062021-V.webp", "imageUrlMd": "https://http2.mlstatic.com/D_NQ_NP_966675-MLA46335561609_062021-V.webp", "imageUrlLg": "https://http2.mlstatic.com/D_NQ_NP_966675-MLA46335561609_062021-V.webp", }, { "_id": 19, "description": "New Macbook Pro Retina 2020 Touchbar I5 8gb Garantía Factura", "price": 249999, "stock": 5, "imageUrlSm": "https://http2.mlstatic.com/D_NQ_NP_773077-MLA46292880505_062021-V.webp", "imageUrlMd": "https://http2.mlstatic.com/D_NQ_NP_773077-MLA46292880505_062021-V.webp", "imageUrlLg": "https://http2.mlstatic.com/D_NQ_NP_773077-MLA46292880505_062021-V.webp", }, { "_id": 20, "description": "Apple Macbook Pro 13,31 Mwp52le/a I5 Gen10 16gb Tb Ssd", "price": 390999, "stock": 5, "imageUrlSm": "https://http2.mlstatic.com/D_NQ_NP_713916-MLA43703429895_102020-V.webp", "imageUrlMd": "https://http2.mlstatic.com/D_NQ_NP_713916-MLA43703429895_102020-V.webp", "imageUrlLg": "https://http2.mlstatic.com/D_NQ_NP_713916-MLA43703429895_102020-V.webp", }, ] ); }, async down(db, client) { // TODO write the statements to rollback your migration (if possible) // Example: await db.collection('products').deleteMany( { "_id": { $in: [ 13,14,15,16,17,18,19,20 ] } } ); } };
46.83871
142
0.615932
3b5eaf76ed097da0a4f9dcbe9bd394ed776f3a5a
170
js
JavaScript
iToDo/models/Users.js
cthecheese/Playground
62df679ff230f07acccd73f9eff8271044fdd165
[ "MIT" ]
null
null
null
iToDo/models/Users.js
cthecheese/Playground
62df679ff230f07acccd73f9eff8271044fdd165
[ "MIT" ]
1
2015-09-17T09:54:05.000Z
2015-09-18T04:07:18.000Z
iToDo/models/Users.js
cthecheese/Playground
62df679ff230f07acccd73f9eff8271044fdd165
[ "MIT" ]
null
null
null
var bookshelf = require('./shelf') var User = bookshelf.Model.extend({ tableName: 'users', tasks: function(){ return hasMany(Task) } }) module.exports = User
15.454545
35
0.658824
3b5f04eb7fcc456316eee11a324c8896c3e60c14
300,855
js
JavaScript
src/dashv2.js
ricocai/lab
48677e322fa5a2a306527f8360968095f0eecc4c
[ "MIT" ]
null
null
null
src/dashv2.js
ricocai/lab
48677e322fa5a2a306527f8360968095f0eecc4c
[ "MIT" ]
null
null
null
src/dashv2.js
ricocai/lab
48677e322fa5a2a306527f8360968095f0eecc4c
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------- // You can set the following variables before loading this script: /*global netdataNoDygraphs *//* boolean, disable dygraph charts * (default: false) */ /*global netdataNoSparklines *//* boolean, disable sparkline charts * (default: false) */ /*global netdataNoPeitys *//* boolean, disable peity charts * (default: false) */ /*global netdataNoGoogleCharts *//* boolean, disable google charts * (default: false) */ /*global netdataNoMorris *//* boolean, disable morris charts * (default: false) */ /*global netdataNoEasyPieChart *//* boolean, disable easypiechart charts * (default: false) */ /*global netdataNoGauge *//* boolean, disable gauge.js charts * (default: false) */ /*global netdataNoD3 *//* boolean, disable d3 charts * (default: false) */ /*global netdataNoC3 *//* boolean, disable c3 charts * (default: false) */ /*global netdataNoBootstrap *//* boolean, disable bootstrap - disables help too * (default: false) */ /*global netdataDontStart *//* boolean, do not start the thread to process the charts * (default: false) */ /*global netdataErrorCallback *//* function, callback to be called when the dashboard encounters an error * (default: null) */ /*global netdataRegistry:true *//* boolean, use the netdata registry * (default: false) */ /*global netdataNoRegistry *//* boolean, included only for compatibility with existing custom dashboard * (obsolete - do not use this any more) */ /*global netdataRegistryCallback *//* function, callback that will be invoked with one param: the URLs from the registry * (default: null) */ /*global netdataShowHelp:true *//* boolean, disable charts help * (default: true) */ /*global netdataShowAlarms:true *//* boolean, enable alarms checks and notifications * (default: false) */ /*global netdataRegistryAfterMs:true *//* ms, delay registry use at started * (default: 1500) */ /*global netdataCallback *//* function, callback to be called when netdata is ready to start * (default: null) * netdata will be running while this is called * (call NETDATA.pause to stop it) */ /*global netdataPrepCallback *//* function, callback to be called before netdata does anything else * (default: null) */ /*global netdataServer *//* string, the URL of the netdata server to use * (default: the URL the page is hosted at) */ // ---------------------------------------------------------------------------- // global namespace //import axios from "./node_modules/axios" var NETDATA = window.NETDATA || {}; (function(window, document) { // ------------------------------------------------------------------------ // compatibility fixes // fix IE issue with console if(!window.console) { window.console = { log: function(){} }; } // if string.endsWith is not defined, define it if(typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(s) { if(s.length > this.length) return false; return this.slice(-s.length) === s; }; } // if string.startsWith is not defined, define it if(typeof String.prototype.startsWith !== 'function') { String.prototype.startsWith = function(s) { if(s.length > this.length) return false; return this.slice(s.length) === s; }; } NETDATA.name2id = function(s) { return s .replace(/ /g, '_') .replace(/\(/g, '_') .replace(/\)/g, '_') .replace(/\./g, '_') .replace(/\//g, '_'); }; // ---------------------------------------------------------------------------------------------------------------- // Detect the netdata server // http://stackoverflow.com/questions/984510/what-is-my-script-src-url // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url NETDATA._scriptSource = function() { var script = null; if(typeof document.currentScript !== 'undefined') { script = document.currentScript; } else { var all_scripts = document.getElementsByTagName('script'); script = all_scripts[all_scripts.length - 1]; } if (typeof script.getAttribute.length !== 'undefined') script = script.src; else script = script.getAttribute('src', -1); return script; }; NETDATA.IAMServer = '' NETDATA.OpenAPIServer = '' if(typeof IAMServer !== 'undefined'){ NETDATA.IAMServer = IAMServer; console.log('NETDATA.IAMServer = ', NETDATA.IAMServer) } if(typeof OpenAPIServer !== 'undefined'){ NETDATA.OpenAPIServer = OpenAPIServer; console.log('NETDATA.OpenAPIServer = ', NETDATA.OpenAPIServer) } if(typeof netdataServer !== 'undefined') NETDATA.serverDefault = netdataServer; else { var s = NETDATA._scriptSource(); if(s) NETDATA.serverDefault = s.replace(/\/dash_yunkon.js(\?.*)*$/g, ""); else { console.log('WARNING: Cannot detect the URL of the netdata server.'); NETDATA.serverDefault = null; } } if(NETDATA.serverDefault === null) NETDATA.serverDefault = ''; else if(NETDATA.serverDefault.slice(-1) !== '/') NETDATA.serverDefault += '/'; //NETDATA.serverDefault = 'http://47.93.79.144:8529/_db/api/v1/' console.log('Rico trace in NETDATA.serverDefault = ', NETDATA.serverDefault) NETDATA.instance = axios.create({ baseURL: 'http://47.93.79.144:9110/api/v1/', timeout: 1000, headers: { 'X-Access-Token': 'a311ecb67b4800384533f59e64653761' } }); NETDATA.IAM = axios.create({ baseURL: 'http://47.93.79.144:8529/_db/api/v1/', timeout: 1000, headers: { 'X-Access-Token': 'a311ecb67b4800384533f59e64653761' } }); // default URLs for all the external files we need // make them RELATIVE so that the whole thing can also be // installed under a web server NETDATA.jQuery = NETDATA.serverDefault + 'lib/jquery-2.2.4.min.js'; NETDATA.peity_js = NETDATA.serverDefault + 'lib/jquery.peity-3.2.0.min.js'; NETDATA.sparkline_js = NETDATA.serverDefault + 'lib/jquery.sparkline-2.1.2.min.js'; NETDATA.easypiechart_js = NETDATA.serverDefault + 'lib/jquery.easypiechart-97b5824.min.js'; NETDATA.gauge_js = NETDATA.serverDefault + 'lib/gauge-1.3.2.min.js'; NETDATA.dygraph_js = NETDATA.serverDefault + 'lib/dygraph-combined-dd74404.js'; NETDATA.dygraph_smooth_js = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter-dd74404.js'; NETDATA.raphael_js = NETDATA.serverDefault + 'lib/raphael-2.2.4-min.js'; NETDATA.c3_js = NETDATA.serverDefault + 'lib/c3-0.4.11.min.js'; NETDATA.c3_css = NETDATA.serverDefault + 'css/c3-0.4.11.min.css'; NETDATA.d3_js = NETDATA.serverDefault + 'lib/d3-3.5.17.min.js'; NETDATA.morris_js = NETDATA.serverDefault + 'lib/morris-0.5.1.min.js'; NETDATA.morris_css = NETDATA.serverDefault + 'css/morris-0.5.1.css'; NETDATA.google_js = 'https://www.google.com/jsapi'; //NETDATA.axios = 'https://unpkg.com/axios/dist/axios.min.js' NETDATA.themes = { white: { bootstrap_css: NETDATA.serverDefault + 'css/bootstrap-3.3.7.css', dashboard_css: NETDATA.serverDefault + 'dashboard.css?v20161229-2', background: '#FFFFFF', foreground: '#000000', grid: '#F0F0F0', axis: '#F0F0F0', colors: [ '#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477', '#3B3EAC', '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6', '#994499', '#22AA99', '#6633CC', '#E67300', '#316395', '#8B0707', '#329262', '#3B3EAC' ], easypiechart_track: '#f0f0f0', easypiechart_scale: '#dfe0e0', gauge_pointer: '#C0C0C0', gauge_stroke: '#F0F0F0', gauge_gradient: false }, slate: { bootstrap_css: NETDATA.serverDefault + 'css/bootstrap-slate-flat-3.3.7.css?v20161229-1', dashboard_css: NETDATA.serverDefault + 'dashboard.slate.css?v20161229-2', background: '#272b30', foreground: '#C8C8C8', grid: '#283236', axis: '#283236', /* colors: [ '#55bb33', '#ff2222', '#0099C6', '#faa11b', '#adbce0', '#DDDD00', '#4178ba', '#f58122', '#a5cc39', '#f58667', '#f5ef89', '#cf93c0', '#a5d18a', '#b8539d', '#3954a3', '#c8a9cf', '#c7de8a', '#fad20a', '#a6a479', '#a66da8' ], */ colors: [ '#66AA00', '#FE3912', '#3366CC', '#D66300', '#0099C6', '#DDDD00', '#5054e6', '#EE9911', '#BB44CC', '#e45757', '#ef0aef', '#CC7700', '#22AA99', '#109618', '#905bfd', '#f54882', '#4381bf', '#ff3737', '#329262', '#3B3EFF' ], easypiechart_track: '#373b40', easypiechart_scale: '#373b40', gauge_pointer: '#474b50', gauge_stroke: '#373b40', gauge_gradient: false } }; if(typeof netdataTheme !== 'undefined' && typeof NETDATA.themes[netdataTheme] !== 'undefined') NETDATA.themes.current = NETDATA.themes[netdataTheme]; else NETDATA.themes.current = NETDATA.themes.white; NETDATA.colors = NETDATA.themes.current.colors; // these are the colors Google Charts are using // we have them here to attempt emulate their look and feel on the other chart libraries // http://there4.io/2012/05/02/google-chart-color-list/ //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6', // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11', // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ]; // an alternative set // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/ // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray) //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ]; if(typeof netdataShowHelp === 'undefined') netdataShowHelp = true; if(typeof netdataShowAlarms === 'undefined') netdataShowAlarms = false; if(typeof netdataRegistryAfterMs !== 'number' || netdataRegistryAfterMs < 0) netdataRegistryAfterMs = 1500; if(typeof netdataRegistry === 'undefined') { // backward compatibility netdataRegistry = (typeof netdataNoRegistry !== 'undefined' && netdataNoRegistry === false); } if(netdataRegistry === false && typeof netdataRegistryCallback === 'function') netdataRegistry = true; // ---------------------------------------------------------------------------------------------------------------- // detect if this is probably a slow device var isSlowDeviceResult = undefined; var isSlowDevice = function() { if(isSlowDeviceResult !== undefined) return isSlowDeviceResult; try { var ua = navigator.userAgent.toLowerCase(); var iOS = /ipad|iphone|ipod/.test(ua) && !window.MSStream; var android = /android/.test(ua) && !window.MSStream; isSlowDeviceResult = (iOS === true || android === true); } catch (e) { isSlowDeviceResult = false; } return isSlowDeviceResult; }; // ---------------------------------------------------------------------------------------------------------------- // the defaults for all charts // if the user does not specify any of these, the following will be used NETDATA.chartDefaults = { host: NETDATA.serverDefault, // the server to get data from width: '100%', // the chart width - can be null height: '100%', // the chart height - can be null min_width: null, // the chart minimum width - can be null library: 'dygraph', // the graphing library to use method: 'average', // the grouping method before: 0, // panning after: -600, // panning pixels_per_point: 1, // the detail of the chart fill_luminance: 0.8 // luminance of colors in solid areas }; // ---------------------------------------------------------------------------------------------------------------- // global options NETDATA.options = { pauseCallback: null, // a callback when we are really paused pause: false, // when enabled we don't auto-refresh the charts targets: null, // an array of all the state objects that are // currently active (independently of their // viewport visibility) updated_dom: true, // when true, the DOM has been updated with // new elements we have to check. auto_refresher_fast_weight: 0, // this is the current time in ms, spent // rendering charts continuously. // used with .current.fast_render_timeframe page_is_visible: true, // when true, this page is visible auto_refresher_stop_until: 0, // timestamp in ms - used internally, to stop the // auto-refresher for some time (when a chart is // performing pan or zoom, we need to stop refreshing // all other charts, to have the maximum speed for // rendering the chart that is panned or zoomed). // Used with .current.global_pan_sync_time last_page_resize: Date.now(), // the timestamp of the last resize request last_page_scroll: 0, // the timestamp the last time the page was scrolled // the current profile // we may have many... current: { pixels_per_point: isSlowDevice()?5:1, // the minimum pixels per point for all charts // increase this to speed javascript up // each chart library has its own limit too // the max of this and the chart library is used // the final is calculated every time, so a change // here will have immediate effect on the next chart // update idle_between_charts: 100, // ms - how much time to wait between chart updates fast_render_timeframe: 200, // ms - render continuously until this time of continuous // rendering has been reached // this setting is used to make it render e.g. 10 // charts at once, sleep idle_between_charts time // and continue for another 10 charts. idle_between_loops: 500, // ms - if all charts have been updated, wait this // time before starting again. idle_parallel_loops: 100, // ms - the time between parallel refresher updates idle_lost_focus: 500, // ms - when the window does not have focus, check // if focus has been regained, every this time global_pan_sync_time: 1000, // ms - when you pan or zoom a chart, the background // auto-refreshing of charts is paused for this amount // of time sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount // of time before setting up synchronized selections // on hover. sync_selection: true, // enable or disable selection sync pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart sync_pan_and_zoom: true, // enable or disable pan and zoom sync pan_and_zoom_data_padding: true, // fetch more data for the master chart when panning or zooming update_only_visible: true, // enable or disable visibility management parallel_refresher: (isSlowDevice() === false), // enable parallel refresh of charts concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts destroy_on_hide: (isSlowDevice() === true), // destroy charts when they are not visible show_help: netdataShowHelp, // when enabled the charts will show some help show_help_delay_show_ms: 500, show_help_delay_hide_ms: 0, eliminate_zero_dimensions: true, // do not show dimensions with just zeros stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap smooth_plot: (isSlowDevice() === false), // enable smooth plot, where possible charts_selection_animation_delay: 50, // delay to animate charts when syncing selection color_fill_opacity_line: 1.0, color_fill_opacity_area: 0.2, color_fill_opacity_stacked: 0.8, pan_and_zoom_factor: 0.25, // the increment when panning and zooming with the toolbox pan_and_zoom_factor_multiplier_control: 2.0, pan_and_zoom_factor_multiplier_shift: 3.0, pan_and_zoom_factor_multiplier_alt: 4.0, abort_ajax_on_scroll: false, // kill pending ajax page scroll async_on_scroll: false, // sync/async onscroll handler onscroll_worker_duration_threshold: 30, // time in ms, to consider slow the onscroll handler retries_on_data_failures: 3, // how many retries to make if we can't fetch chart data from the server setOptionCallback: function() { } }, debug: { show_boxes: false, main_loop: true, focus: false, visibility: false, chart_data_url: false, chart_errors: false, // FIXME: remember to set it to false before merging chart_timing: false, chart_calls: false, libraries: false, dygraph: false } }; NETDATA.statistics = { refreshes_total: 0, refreshes_active: 0, refreshes_active_max: 0 }; // ---------------------------------------------------------------------------------------------------------------- // local storage options NETDATA.localStorage = { default: {}, current: {}, callback: {} // only used for resetting back to defaults }; NETDATA.localStorageTested = -1; NETDATA.localStorageTest = function() { if(NETDATA.localStorageTested !== -1) return NETDATA.localStorageTested; if(typeof Storage !== "undefined" && typeof localStorage === 'object') { var test = 'test'; try { localStorage.setItem(test, test); localStorage.removeItem(test); NETDATA.localStorageTested = true; } catch (e) { NETDATA.localStorageTested = false; } } else NETDATA.localStorageTested = false; return NETDATA.localStorageTested; }; NETDATA.localStorageGet = function(key, def, callback) { var ret = def; if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') { NETDATA.localStorage.default[key.toString()] = def; NETDATA.localStorage.callback[key.toString()] = callback; } if(NETDATA.localStorageTest() === true) { try { // console.log('localStorage: loading "' + key.toString() + '"'); ret = localStorage.getItem(key.toString()); // console.log('netdata loaded: ' + key.toString() + ' = ' + ret.toString()); if(ret === null || ret === 'undefined') { // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"'); localStorage.setItem(key.toString(), JSON.stringify(def)); ret = def; } else { // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"'); ret = JSON.parse(ret); // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret)); } } catch(error) { console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"'); ret = def; } } if(typeof ret === 'undefined' || ret === 'undefined') { console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret)); ret = def; } NETDATA.localStorage.current[key.toString()] = ret; return ret; }; NETDATA.localStorageSet = function(key, value, callback) { if(typeof value === 'undefined' || value === 'undefined') { console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value)); } if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') { NETDATA.localStorage.default[key.toString()] = value; NETDATA.localStorage.current[key.toString()] = value; NETDATA.localStorage.callback[key.toString()] = callback; } if(NETDATA.localStorageTest() === true) { // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"'); try { localStorage.setItem(key.toString(), JSON.stringify(value)); } catch(e) { console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"'); } } NETDATA.localStorage.current[key.toString()] = value; return value; }; NETDATA.localStorageGetRecursive = function(obj, prefix, callback) { var keys = Object.keys(obj); var len = keys.length; while(len--) { var i = keys[len]; if(typeof obj[i] === 'object') { //console.log('object ' + prefix + '.' + i.toString()); NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback); continue; } obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback); } }; NETDATA.setOption = function(key, value) { if(key.toString() === 'setOptionCallback') { if(typeof NETDATA.options.current.setOptionCallback === 'function') { NETDATA.options.current[key.toString()] = value; NETDATA.options.current.setOptionCallback(); } } else if(NETDATA.options.current[key.toString()] !== value) { var name = 'options.' + key.toString(); if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined') console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value); //console.log(NETDATA.localStorage); //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()])); //console.log(NETDATA.options); NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null); if(typeof NETDATA.options.current.setOptionCallback === 'function') NETDATA.options.current.setOptionCallback(); } return true; }; NETDATA.getOption = function(key) { return NETDATA.options.current[key.toString()]; }; // read settings from local storage NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null); // always start with this option enabled. NETDATA.setOption('stop_updates_when_focus_is_lost', true); NETDATA.resetOptions = function() { var keys = Object.keys(NETDATA.localStorage.default); var len = keys.length; while(len--) { var i = keys[len]; var a = i.split('.'); if(a[0] === 'options') { if(a[1] === 'setOptionCallback') continue; if(typeof NETDATA.localStorage.default[i] === 'undefined') continue; if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue; NETDATA.setOption(a[1], NETDATA.localStorage.default[i]); } else if(a[0] === 'chart_heights') { if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') { NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]); } } } }; // ---------------------------------------------------------------------------------------------------------------- if(NETDATA.options.debug.main_loop === true) console.log('welcome to NETDATA'); NETDATA.onresizeCallback = null; NETDATA.onresize = function() { NETDATA.options.last_page_resize = Date.now(); NETDATA.onscroll(); if(typeof NETDATA.onresizeCallback === 'function') NETDATA.onresizeCallback(); }; NETDATA.onscroll_updater_count = 0; NETDATA.onscroll_updater_running = false; NETDATA.onscroll_updater_last_run = 0; NETDATA.onscroll_updater_watchdog = null; NETDATA.onscroll_updater_max_duration = 0; NETDATA.onscroll_updater_above_threshold_count = 0; NETDATA.onscroll_updater = function() { NETDATA.onscroll_updater_running = true; NETDATA.onscroll_updater_count++; var start = Date.now(); var targets = NETDATA.options.targets; var len = targets.length; // when the user scrolls he sees that we have // hidden all the not-visible charts // using this little function we try to switch // the charts back to visible quickly if(NETDATA.options.abort_ajax_on_scroll === true) { // we have to cancel pending requests too while (len--) { if (targets[len]._updating === true) { if (typeof targets[len].xhr !== 'undefined') { targets[len].xhr.abort(); targets[len].running = false; targets[len]._updating = false; } targets[len].isVisible(); } } } else { // just find which chart is visible while (len--) targets[len].isVisible(); } var end = Date.now(); // console.log('scroll No ' + NETDATA.onscroll_updater_count + ' calculation took ' + (end - start).toString() + ' ms'); if(NETDATA.options.current.async_on_scroll === false) { var dt = end - start; if(dt > NETDATA.onscroll_updater_max_duration) { // console.log('max onscroll event handler duration increased to ' + dt); NETDATA.onscroll_updater_max_duration = dt; } if(dt > NETDATA.options.current.onscroll_worker_duration_threshold) { // console.log('slow: ' + dt); NETDATA.onscroll_updater_above_threshold_count++; if(NETDATA.onscroll_updater_above_threshold_count > 2 && NETDATA.onscroll_updater_above_threshold_count * 100 / NETDATA.onscroll_updater_count > 2) { NETDATA.setOption('async_on_scroll', true); console.log('NETDATA: your browser is slow - enabling asynchronous onscroll event handler.'); } } } NETDATA.onscroll_updater_last_run = start; NETDATA.onscroll_updater_running = false; }; NETDATA.onscroll = function() { // console.log('onscroll'); NETDATA.options.last_page_scroll = Date.now(); NETDATA.options.auto_refresher_stop_until = 0; if(NETDATA.options.targets === null) return; if(NETDATA.options.current.async_on_scroll === true) { // async if(NETDATA.onscroll_updater_running === false) { NETDATA.onscroll_updater_running = true; setTimeout(NETDATA.onscroll_updater, 0); } else { if(NETDATA.onscroll_updater_watchdog !== null) clearTimeout(NETDATA.onscroll_updater_watchdog); NETDATA.onscroll_updater_watchdog = setTimeout(function() { if(NETDATA.onscroll_updater_running === false && NETDATA.options.last_page_scroll > NETDATA.onscroll_updater_last_run) { // console.log('watchdog'); NETDATA.onscroll_updater(); } NETDATA.onscroll_updater_watchdog = null; }, 200); } } else { // sync NETDATA.onscroll_updater(); } }; window.onresize = NETDATA.onresize; window.onscroll = NETDATA.onscroll; // ---------------------------------------------------------------------------------------------------------------- // Error Handling NETDATA.errorCodes = { 100: { message: "Cannot load chart library", alert: true }, 101: { message: "Cannot load jQuery", alert: true }, 402: { message: "Chart library not found", alert: false }, 403: { message: "Chart library not enabled/is failed", alert: false }, 404: { message: "Chart not found", alert: false }, 405: { message: "Cannot download charts index from server", alert: true }, 406: { message: "Invalid charts index downloaded from server", alert: true }, 407: { message: "Cannot HELLO netdata server", alert: false }, 408: { message: "Netdata servers sent invalid response to HELLO", alert: false }, 409: { message: "Cannot ACCESS netdata registry", alert: false }, 410: { message: "Netdata registry ACCESS failed", alert: false }, 411: { message: "Netdata registry server send invalid response to DELETE ", alert: false }, 412: { message: "Netdata registry DELETE failed", alert: false }, 413: { message: "Netdata registry server send invalid response to SWITCH ", alert: false }, 414: { message: "Netdata registry SWITCH failed", alert: false }, 415: { message: "Netdata alarms download failed", alert: false }, 416: { message: "Netdata alarms log download failed", alert: false }, 417: { message: "Netdata registry server send invalid response to SEARCH ", alert: false }, 418: { message: "Netdata registry SEARCH failed", alert: false } }; NETDATA.errorLast = { code: 0, message: "", datetime: 0 }; NETDATA.error = function(code, msg) { NETDATA.errorLast.code = code; NETDATA.errorLast.message = msg; NETDATA.errorLast.datetime = Date.now(); console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg); var ret = true; if(typeof netdataErrorCallback === 'function') { ret = netdataErrorCallback('system', code, msg); } if(ret && NETDATA.errorCodes[code].alert) alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg); }; NETDATA.errorReset = function() { NETDATA.errorLast.code = 0; NETDATA.errorLast.message = "You are doing fine!"; NETDATA.errorLast.datetime = 0; }; // ---------------------------------------------------------------------------------------------------------------- // fast numbers formatting NETDATA.fastNumberFormat = { formatters_fixed: [], formatters_zero_based: [], // this is the fastest and the preferred getIntlNumberFormat: function(min, max) { var key = max; if(min === max) { if(typeof this.formatters_fixed[key] === 'undefined') this.formatters_fixed[key] = new Intl.NumberFormat(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); return this.formatters_fixed[key]; } else if(min === 0) { if(typeof this.formatters_zero_based[key] === 'undefined') this.formatters_zero_based[key] = new Intl.NumberFormat(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); return this.formatters_zero_based[key]; } else { // this is never used // it is added just for completeness return new Intl.NumberFormat(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); } }, // this respects locale getLocaleString: function(min, max) { var key = max; if(min === max) { if(typeof this.formatters_fixed[key] === 'undefined') this.formatters_fixed[key] = { format: function (value) { return value.toLocaleString(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); } }; return this.formatters_fixed[key]; } else if(min === 0) { if(typeof this.formatters_zero_based[key] === 'undefined') this.formatters_zero_based[key] = { format: function (value) { return value.toLocaleString(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); } }; return this.formatters_zero_based[key]; } else { return { format: function (value) { return value.toLocaleString(undefined, { // style: 'decimal', // minimumIntegerDigits: 1, // minimumSignificantDigits: 1, // maximumSignificantDigits: 1, useGrouping: true, minimumFractionDigits: min, maximumFractionDigits: max }); } }; } }, getFixed: function(min, max) { var key = max; if(min === max) { if(typeof this.formatters_fixed[key] === 'undefined') this.formatters_fixed[key] = { format: function (value) { if(value === 0) return "0"; return value.toFixed(max); } }; return this.formatters_fixed[key]; } else if(min === 0) { if(typeof this.formatters_zero_based[key] === 'undefined') this.formatters_zero_based[key] = { format: function (value) { if(value === 0) return "0"; return value.toFixed(max); } }; return this.formatters_zero_based[key]; } else { return { format: function (value) { if(value === 0) return "0"; return value.toFixed(max); } }; } }, testIntlNumberFormat: function() { var n = 1.12345; var e1 = "1.12", e2 = "1,12"; var s = ""; try { var x = new Intl.NumberFormat(undefined, { useGrouping: true, minimumFractionDigits: 2, maximumFractionDigits: 2 }); s = x.format(n); } catch(e) { s = ""; } // console.log('NumberFormat: ', s); return (s === e1 || s === e2); }, testLocaleString: function() { var n = 1.12345; var e1 = "1.12", e2 = "1,12"; var s = ""; try { s = value.toLocaleString(undefined, { useGrouping: true, minimumFractionDigits: 2, maximumFractionDigits: 2 }); } catch(e) { s = ""; } // console.log('localeString: ', s); return (s === e1 || s === e2); }, // on first run we decide which formatter to use get: function(min, max) { if(this.testIntlNumberFormat()) { // console.log('numberformat'); this.get = this.getIntlNumberFormat; } else if(this.testLocaleString()) { // console.log('localestring'); this.get = this.getLocaleString; } else { // console.log('fixed'); this.get = this.getFixed; } return this.get(min, max); } }; // ---------------------------------------------------------------------------------------------------------------- // commonMin & commonMax NETDATA.commonMin = { keys: {}, latest: {}, get: function(state) { if(typeof state.__commonMin === 'undefined') { // get the commonMin setting var self = $(state.element); state.__commonMin = self.data('common-min') || null; } var min = state.data.min; var name = state.__commonMin; if(name === null) { // we don't need commonMin //state.log('no need for commonMin'); return min; } var t = this.keys[name]; if(typeof t === 'undefined') { // add our commonMin this.keys[name] = {}; t = this.keys[name]; } var uuid = state.uuid; if(typeof t[uuid] !== 'undefined') { if(t[uuid] === min) { //state.log('commonMin ' + state.__commonMin + ' not changed: ' + this.latest[name]); return this.latest[name]; } else if(min < this.latest[name]) { //state.log('commonMin ' + state.__commonMin + ' increased: ' + min); t[uuid] = min; this.latest[name] = min; return min; } } // add our min t[uuid] = min; // find the common min var m = min; for(var i in t) if(t.hasOwnProperty(i) && t[i] < m) m = t[i]; //state.log('commonMin ' + state.__commonMin + ' updated: ' + m); this.latest[name] = m; return m; } }; NETDATA.commonMax = { keys: {}, latest: {}, get: function(state) { if(typeof state.__commonMax === 'undefined') { // get the commonMax setting var self = $(state.element); state.__commonMax = self.data('common-max') || null; } var max = state.data.max; var name = state.__commonMax; if(name === null) { // we don't need commonMax //state.log('no need for commonMax'); return max; } var t = this.keys[name]; if(typeof t === 'undefined') { // add our commonMax this.keys[name] = {}; t = this.keys[name]; } var uuid = state.uuid; if(typeof t[uuid] !== 'undefined') { if(t[uuid] === max) { //state.log('commonMax ' + state.__commonMax + ' not changed: ' + this.latest[name]); return this.latest[name]; } else if(max > this.latest[name]) { //state.log('commonMax ' + state.__commonMax + ' increased: ' + max); t[uuid] = max; this.latest[name] = max; return max; } } // add our max t[uuid] = max; // find the common max var m = max; for(var i in t) if(t.hasOwnProperty(i) && t[i] > m) m = t[i]; //state.log('commonMax ' + state.__commonMax + ' updated: ' + m); this.latest[name] = m; return m; } }; // ---------------------------------------------------------------------------------------------------------------- // Chart Registry // When multiple charts need the same chart, we avoid downloading it // multiple times (and having it in browser memory multiple time) // by using this registry. // Every time we download a chart definition, we save it here with .add() // Then we try to get it back with .get(). If that fails, we download it. NETDATA.fixHost = function(host) { while(host.slice(-1) === '/') host = host.substring(0, host.length - 1); console.info('old host:', host); // http://localhost:8529/_db/api/v1/api/v1/chart?chart=netdata.server_cpu&_=1500781574657 host = 'http://47.93.79.144:8529/_db/api/v1/'; // by rico return host; }; NETDATA.chartRegistry = { charts: {}, fixid: function(id) { return id.replace(/:/g, "_").replace(/\//g, "_"); }, add: function(host, id, data) { host = this.fixid(host); id = this.fixid(id); if(typeof this.charts[host] === 'undefined') this.charts[host] = {}; console.log('added ' + host + '/' + id + ' with data:' + data); this.charts[host][id] = data; }, get: function(host, id) { host = this.fixid(host); id = this.fixid(id); if(typeof this.charts[host] === 'undefined') return null; if(typeof this.charts[host][id] === 'undefined') return null; //console.log('cached ' + host + '/' + id); return this.charts[host][id]; }, downloadAll: function(host, callback) { host = this.host; //NETDATA.fixHost(host); var self = this; console.log('Rico trace in downloadAll:', host + '/api/v1/charts'); $.ajax({ url: host + '/api/v1/charts', async: true, cache: false, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(data !== null) { var h = NETDATA.chartRegistry.fixid(host); self.charts[h] = data.charts; } else NETDATA.error(406, host + '/api/v1/charts'); if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(405, host + '/api/v1/charts'); if(typeof callback === 'function') return callback(null); }); } }; // ---------------------------------------------------------------------------------------------------------------- // Global Pan and Zoom on charts // Using this structure are synchronize all the charts, so that // when you pan or zoom one, all others are automatically refreshed // to the same timespan. NETDATA.globalPanAndZoom = { seq: 0, // timestamp ms // every time a chart is panned or zoomed // we set the timestamp here // then we use it as a sequence number // to find if other charts are synchronized // to this time-range master: null, // the master chart (state), to which all others // are synchronized force_before_ms: null, // the timespan to sync all other charts force_after_ms: null, callback: null, // set a new master setMaster: function(state, after, before) { if(NETDATA.options.current.sync_pan_and_zoom === false) return; if(this.master !== null && this.master !== state) this.master.resetChart(true, true); var now = Date.now(); this.master = state; this.seq = now; this.force_after_ms = after; this.force_before_ms = before; NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time; if(typeof this.callback === 'function') this.callback(true, after, before); }, // clear the master clearMaster: function() { if(this.master !== null) { var st = this.master; this.master = null; st.resetChart(); } this.master = null; this.seq = 0; this.force_after_ms = null; this.force_before_ms = null; NETDATA.options.auto_refresher_stop_until = 0; if(typeof this.callback === 'function') this.callback(false, 0, 0); }, // is the given state the master of the global // pan and zoom sync? isMaster: function(state) { return (this.master === state); }, // are we currently have a global pan and zoom sync? isActive: function() { return (this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0); }, // check if a chart, other than the master // needs to be refreshed, due to the global pan and zoom shouldBeAutoRefreshed: function(state) { if(this.master === null || this.seq === 0) return false; //if(state.needsRecreation()) // return true; return (state.tm.pan_and_zoom_seq !== this.seq); } }; // ---------------------------------------------------------------------------------------------------------------- // dimensions selection // FIXME // move color assignment to dimensions, here var dimensionStatus = function(parent, label, name_div, value_div, color) { this.enabled = false; this.parent = parent; this.label = label; this.name_div = null; this.value_div = null; this.color = NETDATA.themes.current.foreground; this.selected = (parent.unselected_count === 0); this.setOptions(name_div, value_div, color); }; dimensionStatus.prototype.invalidate = function() { this.name_div = null; this.value_div = null; this.enabled = false; }; dimensionStatus.prototype.setOptions = function(name_div, value_div, color) { this.color = color; if(this.name_div !== name_div) { this.name_div = name_div; this.name_div.title = this.label; this.name_div.style.color = this.color; if(this.selected === false) this.name_div.className = 'netdata-legend-name not-selected'; else this.name_div.className = 'netdata-legend-name selected'; } if(this.value_div !== value_div) { this.value_div = value_div; this.value_div.title = this.label; this.value_div.style.color = this.color; if(this.selected === false) this.value_div.className = 'netdata-legend-value not-selected'; else this.value_div.className = 'netdata-legend-value selected'; } this.enabled = true; this.setHandler(); }; dimensionStatus.prototype.setHandler = function() { if(this.enabled === false) return; var ds = this; // this.name_div.onmousedown = this.value_div.onmousedown = function(e) { this.name_div.onclick = this.value_div.onclick = function(e) { e.preventDefault(); if(ds.isSelected()) { // this is selected if(e.shiftKey === true || e.ctrlKey === true) { // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all) ds.unselect(); if(ds.parent.countSelected() === 0) ds.parent.selectAll(); } else { // no key is pressed -> select only this (except if it is the only selected already, in which case select all) if(ds.parent.countSelected() === 1) { ds.parent.selectAll(); } else { ds.parent.selectNone(); ds.select(); } } } else { // this is not selected if(e.shiftKey === true || e.ctrlKey === true) { // control or shift key is pressed -> select this too ds.select(); } else { // no key is pressed -> select only this ds.parent.selectNone(); ds.select(); } } ds.parent.state.redrawChart(); } }; dimensionStatus.prototype.select = function() { if(this.enabled === false) return; this.name_div.className = 'netdata-legend-name selected'; this.value_div.className = 'netdata-legend-value selected'; this.selected = true; }; dimensionStatus.prototype.unselect = function() { if(this.enabled === false) return; this.name_div.className = 'netdata-legend-name not-selected'; this.value_div.className = 'netdata-legend-value hidden'; this.selected = false; }; dimensionStatus.prototype.isSelected = function() { return(this.enabled === true && this.selected === true); }; // ---------------------------------------------------------------------------------------------------------------- var dimensionsVisibility = function(state) { this.state = state; this.len = 0; this.dimensions = {}; this.selected_count = 0; this.unselected_count = 0; }; dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) { if(typeof this.dimensions[label] === 'undefined') { this.len++; this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color); } else this.dimensions[label].setOptions(name_div, value_div, color); return this.dimensions[label]; }; dimensionsVisibility.prototype.dimensionGet = function(label) { return this.dimensions[label]; }; dimensionsVisibility.prototype.invalidateAll = function() { var keys = Object.keys(this.dimensions); var len = keys.length; while(len--) this.dimensions[keys[len]].invalidate(); }; dimensionsVisibility.prototype.selectAll = function() { var keys = Object.keys(this.dimensions); var len = keys.length; while(len--) this.dimensions[keys[len]].select(); }; dimensionsVisibility.prototype.countSelected = function() { var selected = 0; var keys = Object.keys(this.dimensions); var len = keys.length; while(len--) if(this.dimensions[keys[len]].isSelected()) selected++; return selected; }; dimensionsVisibility.prototype.selectNone = function() { var keys = Object.keys(this.dimensions); var len = keys.length; while(len--) this.dimensions[keys[len]].unselect(); }; dimensionsVisibility.prototype.selected2BooleanArray = function(array) { var ret = []; this.selected_count = 0; this.unselected_count = 0; var len = array.length; while(len--) { var ds = this.dimensions[array[len]]; if(typeof ds === 'undefined') { // console.log(array[i] + ' is not found'); ret.unshift(false); } else if(ds.isSelected()) { ret.unshift(true); this.selected_count++; } else { ret.unshift(false); this.unselected_count++; } } if(this.selected_count === 0 && this.unselected_count !== 0) { this.selectAll(); return this.selected2BooleanArray(array); } return ret; }; // ---------------------------------------------------------------------------------------------------------------- // global selection sync NETDATA.globalSelectionSync = { state: null, dont_sync_before: 0, last_t: 0, slaves: [], stop: function() { if(this.state !== null) this.state.globalSelectionSyncStop(); }, delay: function() { if(this.state !== null) { this.state.globalSelectionSyncDelay(); } } }; // ---------------------------------------------------------------------------------------------------------------- // Our state object, where all per-chart values are stored var chartState = function(element) { var self = $(element); this.element = element; // IMPORTANT: // all private functions should use 'that', instead of 'this' var that = this; /* error() - private * show an error instead of the chart */ var error = function(msg) { var ret = true; if(typeof netdataErrorCallback === 'function') { ret = netdataErrorCallback('chart', that.id, msg); } if(ret) { that.element.innerHTML = that.id + ': ' + msg; that.enabled = false; that.current = that.pan; } }; // GUID - a unique identifier for the chart this.uuid = NETDATA.guid(); // string - the name of chart this.id = self.data('netdata'); // string - the key for localStorage settings this.settings_id = self.data('id') || null; // the user given dimensions of the element this.width = self.data('width') || NETDATA.chartDefaults.width; this.height = self.data('height') || NETDATA.chartDefaults.height; this.height_original = this.height; if(this.settings_id !== null) { this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) { // this is the callback that will be called // if and when the user resets all localStorage variables // to their defaults resizeChartToHeight(height); }); } // string - the netdata server URL, without any path console.log('Rico trace in chartState:',self.data('host')) console.log('Rico trace in chartState:',NETDATA.chartDefaults.host) this.host = self.data('host') || NETDATA.chartDefaults.host; // make sure the host does not end with / // all netdata API requests use absolute paths while(this.host.slice(-1) === '/') this.host = this.host.substring(0, this.host.length - 1); console.log('Rico trace in chartState: this.host=', this.host) // string - the grouping method requested by the user this.method = self.data('method') || NETDATA.chartDefaults.method; // the time-range requested by the user this.after = self.data('after') || NETDATA.chartDefaults.after; this.before = self.data('before') || NETDATA.chartDefaults.before; // the pixels per point requested by the user this.pixels_per_point = self.data('pixels-per-point') || 1; this.points = self.data('points') || null; // the dimensions requested by the user this.dimensions = self.data('dimensions') || null; // the chart library requested by the user this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library; // how many retries we have made to load chart data from the server this.retries_on_data_failures = 0; // object - the chart library used this.library = null; // color management this.colors = null; this.colors_assigned = {}; this.colors_available = null; this.colors_custom = null; // the element already created by the user this.element_message = null; // the element with the chart this.element_chart = null; // the element with the legend of the chart (if created by us) this.element_legend = null; this.element_legend_childs = { hidden: null, title_date: null, title_time: null, title_units: null, perfect_scroller: null, // the container to apply perfect scroller to series: null }; this.chart_url = null; // string - the url to download chart info this.chart = null; // object - the chart as downloaded from the server this.title = self.data('title') || null; // the title of the chart this.units = self.data('units') || null; // the units of the chart dimensions this.append_options = self.data('append-options') || null; // additional options to pass to netdata this.override_options = self.data('override-options') || null; // override options to pass to netdata this.running = false; // boolean - true when the chart is being refreshed now this.enabled = true; // boolean - is the chart enabled for refresh? this.paused = false; // boolean - is the chart paused for any reason? this.selected = false; // boolean - is the chart shown a selection? this.debug = self.data('debug') === true; // boolean - console.log() debug info about this chart this.netdata_first = 0; // milliseconds - the first timestamp in netdata this.netdata_last = 0; // milliseconds - the last timestamp in netdata this.requested_after = null; // milliseconds - the timestamp of the request after param this.requested_before = null; // milliseconds - the timestamp of the request before param this.requested_padding = null; this.view_after = 0; this.view_before = 0; this.value_decimal_detail = -1; var d = self.data('decimal-digits'); if(typeof d === 'number') { this.value_decimal_detail = d; } this.auto = { name: 'auto', autorefresh: true, force_update_at: 0, // the timestamp to force the update at force_before_ms: null, force_after_ms: null }; this.pan = { name: 'pan', autorefresh: false, force_update_at: 0, // the timestamp to force the update at force_before_ms: null, force_after_ms: null }; this.zoom = { name: 'zoom', autorefresh: false, force_update_at: 0, // the timestamp to force the update at force_before_ms: null, force_after_ms: null }; // this is a pointer to one of the sub-classes below // auto, pan, zoom this.current = this.auto; // check the requested library is available // we don't initialize it here - it will be initialized when // this chart will be first used if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') { NETDATA.error(402, that.library_name); error('chart library "' + that.library_name + '" is not found'); return; } else if(NETDATA.chartLibraries[that.library_name].enabled === false) { NETDATA.error(403, that.library_name); error('chart library "' + that.library_name + '" is not enabled'); return; } else{ that.library = NETDATA.chartLibraries[that.library_name]; console.log('^^^^^^^^^^^^NETDATA.chartLibraries[] with ', that.library_name) } // milliseconds - the time the last refresh took this.refresh_dt_ms = 0; // if we need to report the rendering speed // find the element that needs to be updated var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms if(refresh_dt_element_name !== null) { this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null; } else this.refresh_dt_element = null; this.dimensions_visibility = new dimensionsVisibility(this); this._updating = false; // ============================================================================================================ // PRIVATE FUNCTIONS var createDOM = function() { if(that.enabled === false) return; if(that.element_message !== null) that.element_message.innerHTML = ''; if(that.element_legend !== null) that.element_legend.innerHTML = ''; if(that.element_chart !== null) that.element_chart.innerHTML = ''; that.element.innerHTML = ''; that.element_message = document.createElement('div'); that.element_message.className = 'netdata-message icon hidden'; that.element.appendChild(that.element_message); that.element_chart = document.createElement('div'); that.element_chart.id = that.library_name + '-' + that.uuid + '-chart'; that.element.appendChild(that.element_chart); if(that.hasLegend() === true) { that.element.className = "netdata-container-with-legend"; that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right'; that.element_legend = document.createElement('div'); that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend'; that.element.appendChild(that.element_legend); } else { that.element.className = "netdata-container"; that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart'; that.element_legend = null; } that.element_legend_childs.series = null; if(typeof(that.width) === 'string') $(that.element).css('width', that.width); else if(typeof(that.width) === 'number') $(that.element).css('width', that.width + 'px'); if(typeof(that.library.aspect_ratio) === 'undefined') { if(typeof(that.height) === 'string') that.element.style.height = that.height; else if(typeof(that.height) === 'number') that.element.style.height = that.height.toString() + 'px'; } else { var w = that.element.offsetWidth; if(w === null || w === 0) { // the div is hidden // this will resize the chart when next viewed that.tm.last_resized = 0; } else that.element.style.height = (w * that.library.aspect_ratio / 100).toString() + 'px'; } if(NETDATA.chartDefaults.min_width !== null) $(that.element).css('min-width', NETDATA.chartDefaults.min_width); that.tm.last_dom_created = Date.now(); showLoading(); }; /* init() private * initialize state variables * destroy all (possibly) created state elements * create the basic DOM for a chart */ var init = function() { if(that.enabled === false) return; that.paused = false; that.selected = false; that.chart_created = false; // boolean - is the library.create() been called? that.updates_counter = 0; // numeric - the number of refreshes made so far that.updates_since_last_unhide = 0; // numeric - the number of refreshes made since the last time the chart was unhidden that.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created that.tm = { last_initialized: 0, // milliseconds - the timestamp it was last initialized last_dom_created: 0, // milliseconds - the timestamp its DOM was last created last_mode_switch: 0, // milliseconds - the timestamp it switched modes last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart last_updated: 0, // the timestamp the chart last updated with data pan_and_zoom_seq: 0, // the sequence number of the global synchronization // between chart. // Used with NETDATA.globalPanAndZoom.seq last_visible_check: 0, // the time we last checked if it is visible last_resized: 0, // the time the chart was resized last_hidden: 0, // the time the chart was hidden last_unhidden: 0, // the time the chart was unhidden last_autorefreshed: 0 // the time the chart was last refreshed }; that.data = null; // the last data as downloaded from the netdata server that.data_url = 'invalid://'; // string - the last url used to update the chart that.data_points = 0; // number - the number of points returned from netdata that.data_after = 0; // milliseconds - the first timestamp of the data that.data_before = 0; // milliseconds - the last timestamp of the data that.data_update_every = 0; // milliseconds - the frequency to update the data that.tm.last_initialized = Date.now(); createDOM(); that.setMode('auto'); }; var maxMessageFontSize = function() { var screenHeight = screen.height; var el = that.element; // normally we want a font size, as tall as the element var h = el.clientHeight; // but give it some air, 20% let's say, or 5 pixels min var lost = Math.max(h * 0.2, 5); h -= lost; // center the text, vertically var paddingTop = (lost - 5) / 2; // but check the width too // it should fit 10 characters in it var w = el.clientWidth / 10; if(h > w) { paddingTop += (h - w) / 2; h = w; } // and don't make it too huge // 5% of the screen size is good if(h > screenHeight / 20) { paddingTop += (h - (screenHeight / 20)) / 2; h = screenHeight / 20; } // set it that.element_message.style.fontSize = h.toString() + 'px'; that.element_message.style.paddingTop = paddingTop.toString() + 'px'; }; var showMessageIcon = function(icon) { that.element_message.innerHTML = icon; maxMessageFontSize(); $(that.element_message).removeClass('hidden'); that.___messageHidden___ = undefined; }; var hideMessage = function() { if(typeof that.___messageHidden___ === 'undefined') { that.___messageHidden___ = true; $(that.element_message).addClass('hidden'); } }; var showRendering = function() { var icon; if(that.chart !== null) { if(that.chart.chart_type === 'line') icon = '<i class="fa fa-line-chart"></i>'; else icon = '<i class="fa fa-area-chart"></i>'; } else icon = '<i class="fa fa-area-chart"></i>'; showMessageIcon(icon + ' netdata'); }; var showLoading = function() { if(that.chart_created === false) { showMessageIcon('<i class="fa fa-refresh"></i> netdata'); return true; } return false; }; var isHidden = function() { return (typeof that.___chartIsHidden___ !== 'undefined'); }; // hide the chart, when it is not visible - called from isVisible() var hideChart = function() { // hide it, if it is not already hidden if(isHidden() === true) return; if(that.chart_created === true) { if(NETDATA.options.current.destroy_on_hide === true) { // we should destroy it init(); } else { showRendering(); that.element_chart.style.display = 'none'; if(that.element_legend !== null) that.element_legend.style.display = 'none'; if(that.element_legend_childs.toolbox !== null) that.element_legend_childs.toolbox.style.display = 'none'; if(that.element_legend_childs.resize_handler !== null) that.element_legend_childs.resize_handler.style.display = 'none'; that.tm.last_hidden = Date.now(); // de-allocate data // This works, but I not sure there are no corner cases somewhere // so it is commented - if the user has memory issues he can // set Destroy on Hide for all charts // that.data = null; } } that.___chartIsHidden___ = true; }; // unhide the chart, when it is visible - called from isVisible() var unhideChart = function() { if(isHidden() === false) return; that.___chartIsHidden___ = undefined; that.updates_since_last_unhide = 0; if(that.chart_created === false) { // we need to re-initialize it, to show our background // logo in bootstrap tabs, until the chart loads init(); } else { that.tm.last_unhidden = Date.now(); that.element_chart.style.display = ''; if(that.element_legend !== null) that.element_legend.style.display = ''; if(that.element_legend_childs.toolbox !== null) that.element_legend_childs.toolbox.style.display = ''; if(that.element_legend_childs.resize_handler !== null) that.element_legend_childs.resize_handler.style.display = ''; resizeChart(); hideMessage(); } }; var canBeRendered = function() { return (isHidden() === false && that.isVisible(true) === true); }; // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers var callChartLibraryUpdateSafely = function(data) { var status; if(canBeRendered() === false) return false; if(NETDATA.options.debug.chart_errors === true) status = that.library.update(that, data); else { try { status = that.library.update(that, data); } catch(err) { status = false; } } if(status === false) { error('chart failed to be updated as ' + that.library_name); return false; } return true; }; // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers var callChartLibraryCreateSafely = function(data) { var status; if(canBeRendered() === false) return false; if(NETDATA.options.debug.chart_errors === true) status = that.library.create(that, data); else { try { status = that.library.create(that, data); } catch(err) { status = false; } } if(status === false) { error('chart failed to be created as ' + that.library_name); return false; } that.chart_created = true; that.updates_since_last_creation = 0; return true; }; // ---------------------------------------------------------------------------------------------------------------- // Chart Resize // resizeChart() - private // to be called just before the chart library to make sure that // a properly sized dom is available var resizeChart = function() { if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_page_resize) { if(that.chart_created === false) return; if(that.needsRecreation()) { init(); } else if(typeof that.library.resize === 'function') { that.library.resize(that); if(that.element_legend_childs.perfect_scroller !== null) Ps.update(that.element_legend_childs.perfect_scroller); maxMessageFontSize(); } that.tm.last_resized = Date.now(); } }; // this is the actual chart resize algorithm // it will: // - resize the entire container // - update the internal states // - resize the chart as the div changes height // - update the scrollbar of the legend var resizeChartToHeight = function(h) { // console.log(h); that.element.style.height = h; if(that.settings_id !== null) NETDATA.localStorageSet('chart_heights.' + that.settings_id, h); var now = Date.now(); NETDATA.options.last_page_scroll = now; NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing; // force a resize that.tm.last_resized = 0; resizeChart(); }; this.resizeHandler = function(e) { e.preventDefault(); if(typeof this.event_resize === 'undefined' || this.event_resize.chart_original_w === 'undefined' || this.event_resize.chart_original_h === 'undefined') this.event_resize = { chart_original_w: this.element.clientWidth, chart_original_h: this.element.clientHeight, last: 0 }; if(e.type === 'touchstart') { this.event_resize.mouse_start_x = e.touches.item(0).pageX; this.event_resize.mouse_start_y = e.touches.item(0).pageY; } else { this.event_resize.mouse_start_x = e.clientX; this.event_resize.mouse_start_y = e.clientY; } this.event_resize.chart_start_w = this.element.clientWidth; this.event_resize.chart_start_h = this.element.clientHeight; this.event_resize.chart_last_w = this.element.clientWidth; this.event_resize.chart_last_h = this.element.clientHeight; var now = Date.now(); if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed && this.element_legend_childs.perfect_scroller !== null) { // double click / double tap event // console.dir(this.element_legend_childs.content); // console.dir(this.element_legend_childs.perfect_scroller); // the optimal height of the chart // showing the entire legend var optimal = this.event_resize.chart_last_h + this.element_legend_childs.perfect_scroller.scrollHeight - this.element_legend_childs.perfect_scroller.clientHeight; // if we are not optimal, be optimal if(this.event_resize.chart_last_h !== optimal) { // this.log('resize to optimal, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString()); resizeChartToHeight(optimal.toString() + 'px'); } // else if the current height is not the original/saved height // reset to the original/saved height else if(this.event_resize.chart_last_h !== this.event_resize.chart_original_h) { // this.log('resize to original, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString()); resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px'); } // else if the current height is not the internal default height // reset to the internal default height else if((this.event_resize.chart_last_h.toString() + 'px') !== this.height_original) { // this.log('resize to internal default, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString()); resizeChartToHeight(this.height_original.toString()); } // else if the current height is not the firstchild's clientheight // resize to it else if(typeof this.element_legend_childs.perfect_scroller.firstChild !== 'undefined') { var parent_rect = this.element.getBoundingClientRect(); var content_rect = this.element_legend_childs.perfect_scroller.firstElementChild.getBoundingClientRect(); var wanted = content_rect.top - parent_rect.top + this.element_legend_childs.perfect_scroller.firstChild.clientHeight + 18; // 15 = toolbox + 3 space // console.log(parent_rect); // console.log(content_rect); // console.log(wanted); // this.log('resize to firstChild, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString() + 'px, firstChild = ' + wanted.toString() + 'px' ); if(this.event_resize.chart_last_h !== wanted) resizeChartToHeight(wanted.toString() + 'px'); } } else { this.event_resize.last = now; // process movement event document.onmousemove = document.ontouchmove = this.element_legend_childs.resize_handler.onmousemove = this.element_legend_childs.resize_handler.ontouchmove = function(e) { var y = null; switch(e.type) { case 'mousemove': y = e.clientY; break; case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break; } if(y !== null) { var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y; if(newH >= 70 && newH !== that.event_resize.chart_last_h) { resizeChartToHeight(newH.toString() + 'px'); that.event_resize.chart_last_h = newH; } } }; // process end event document.onmouseup = document.ontouchend = this.element_legend_childs.resize_handler.onmouseup = this.element_legend_childs.resize_handler.ontouchend = function(e) { void(e); // remove all the hooks document.onmouseup = document.onmousemove = document.ontouchmove = document.ontouchend = that.element_legend_childs.resize_handler.onmousemove = that.element_legend_childs.resize_handler.ontouchmove = that.element_legend_childs.resize_handler.onmouseout = that.element_legend_childs.resize_handler.onmouseup = that.element_legend_childs.resize_handler.ontouchend = null; // allow auto-refreshes NETDATA.options.auto_refresher_stop_until = 0; }; } }; var noDataToShow = function() { showMessageIcon('<i class="fa fa-warning"></i> empty'); that.legendUpdateDOM(); that.tm.last_autorefreshed = Date.now(); // that.data_update_every = 30 * 1000; //that.element_chart.style.display = 'none'; //if(that.element_legend !== null) that.element_legend.style.display = 'none'; //that.___chartIsHidden___ = true; }; // ============================================================================================================ // PUBLIC FUNCTIONS this.error = function(msg) { error(msg); }; this.setMode = function(m) { if(this.current !== null && this.current.name === m) return; if(m === 'auto') this.current = this.auto; else if(m === 'pan') this.current = this.pan; else if(m === 'zoom') this.current = this.zoom; else this.current = this.auto; this.current.force_update_at = 0; this.current.force_before_ms = null; this.current.force_after_ms = null; this.tm.last_mode_switch = Date.now(); }; // ---------------------------------------------------------------------------------------------------------------- // global selection sync // prevent to global selection sync for some time this.globalSelectionSyncDelay = function(ms) { if(NETDATA.options.current.sync_selection === false) return; if(typeof ms === 'number') NETDATA.globalSelectionSync.dont_sync_before = Date.now() + ms; else NETDATA.globalSelectionSync.dont_sync_before = Date.now() + NETDATA.options.current.sync_selection_delay; }; // can we globally apply selection sync? this.globalSelectionSyncAbility = function() { if(NETDATA.options.current.sync_selection === false) return false; return (NETDATA.globalSelectionSync.dont_sync_before <= Date.now()); }; this.globalSelectionSyncIsMaster = function() { return (NETDATA.globalSelectionSync.state === this); }; // this chart is the master of the global selection sync this.globalSelectionSyncBeMaster = function() { // am I the master? if(this.globalSelectionSyncIsMaster()) { if(this.debug === true) this.log('sync: I am the master already.'); return; } if(NETDATA.globalSelectionSync.state) { if(this.debug === true) this.log('sync: I am not the sync master. Resetting global sync.'); this.globalSelectionSyncStop(); } // become the master if(this.debug === true) this.log('sync: becoming sync master.'); this.selected = true; NETDATA.globalSelectionSync.state = this; // find the all slaves var targets = NETDATA.options.targets; var len = targets.length; while(len--) { var st = targets[len]; if(st === this) { if(this.debug === true) st.log('sync: not adding me to sync'); } else if(st.globalSelectionSyncIsEligible()) { if(this.debug === true) st.log('sync: adding to sync as slave'); st.globalSelectionSyncBeSlave(); } } // this.globalSelectionSyncDelay(100); }; // can the chart participate to the global selection sync as a slave? this.globalSelectionSyncIsEligible = function() { return (this.enabled === true && this.library !== null && typeof this.library.setSelection === 'function' && this.isVisible() === true && this.chart_created === true); }; // this chart becomes a slave of the global selection sync this.globalSelectionSyncBeSlave = function() { if(NETDATA.globalSelectionSync.state !== this) NETDATA.globalSelectionSync.slaves.push(this); }; // sync all the visible charts to the given time // this is to be called from the chart libraries this.globalSelectionSync = function(t) { if(this.globalSelectionSyncAbility() === false) return; if(this.globalSelectionSyncIsMaster() === false) { if(this.debug === true) this.log('sync: trying to be sync master.'); this.globalSelectionSyncBeMaster(); if(this.globalSelectionSyncAbility() === false) return; } NETDATA.globalSelectionSync.last_t = t; $.each(NETDATA.globalSelectionSync.slaves, function(i, st) { st.setSelection(t); }); }; // stop syncing all charts to the given time this.globalSelectionSyncStop = function() { if(NETDATA.globalSelectionSync.slaves.length) { if(this.debug === true) this.log('sync: cleaning up...'); $.each(NETDATA.globalSelectionSync.slaves, function(i, st) { if(st === that) { if(that.debug === true) st.log('sync: not adding me to sync stop'); } else { if(that.debug === true) st.log('sync: removed slave from sync'); st.clearSelection(); } }); NETDATA.globalSelectionSync.last_t = 0; NETDATA.globalSelectionSync.slaves = []; NETDATA.globalSelectionSync.state = null; } this.clearSelection(); }; this.setSelection = function(t) { if(typeof this.library.setSelection === 'function') this.selected = (this.library.setSelection(this, t) === true); else this.selected = true; if(this.selected === true && this.debug === true) this.log('selection set to ' + t.toString()); return this.selected; }; this.clearSelection = function() { if(this.selected === true) { if(typeof this.library.clearSelection === 'function') this.selected = (this.library.clearSelection(this) !== true); else this.selected = false; if(this.selected === false && this.debug === true) this.log('selection cleared'); this.legendReset(); } return this.selected; }; // find if a timestamp (ms) is shown in the current chart this.timeIsVisible = function(t) { return (t >= this.data_after && t <= this.data_before); }; this.calculateRowForTime = function(t) { if(this.timeIsVisible(t) === false) return -1; return Math.floor((t - this.data_after) / this.data_update_every); }; // ---------------------------------------------------------------------------------------------------------------- // console logging this.log = function(msg) { console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg); }; this.pauseChart = function() { if(this.paused === false) { if(this.debug === true) this.log('pauseChart()'); this.paused = true; } }; this.unpauseChart = function() { if(this.paused === true) { if(this.debug === true) this.log('unpauseChart()'); this.paused = false; } }; this.resetChart = function(dont_clear_master, dont_update) { if(this.debug === true) this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called'); if(typeof dont_clear_master === 'undefined') dont_clear_master = false; if(typeof dont_update === 'undefined') dont_update = false; if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) { if(this.debug === true) this.log('resetChart() diverting to clearMaster().'); // this will call us back with master === true NETDATA.globalPanAndZoom.clearMaster(); return; } this.clearSelection(); this.tm.pan_and_zoom_seq = 0; this.setMode('auto'); this.current.force_update_at = 0; this.current.force_before_ms = null; this.current.force_after_ms = null; this.tm.last_autorefreshed = 0; this.paused = false; this.selected = false; this.enabled = true; // this.debug = false; // do not update the chart here // or the chart will flip-flop when it is the master // of a selection sync and another chart becomes // the new master if(dont_update !== true && this.isVisible() === true) { this.updateChart(); } }; this.updateChartPanOrZoom = function(after, before) { var logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): '; var ret = true; if(this.debug === true) this.log(logme); if(before < after) { if(this.debug === true) this.log(logme + 'flipped parameters, rejecting it.'); return false; } if(typeof this.fixed_min_duration === 'undefined') this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000); var min_duration = this.fixed_min_duration; var current_duration = Math.round(this.view_before - this.view_after); // round the numbers after = Math.round(after); before = Math.round(before); // align them to update_every // stretching them further away after -= after % this.data_update_every; before += this.data_update_every - (before % this.data_update_every); // the final wanted duration var wanted_duration = before - after; // to allow panning, accept just a point below our minimum if((current_duration - this.data_update_every) < min_duration) min_duration = current_duration - this.data_update_every; // we do it, but we adjust to minimum size and return false // when the wanted size is below the current and the minimum // and we zoom if(wanted_duration < current_duration && wanted_duration < min_duration) { if(this.debug === true) this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString()); min_duration = this.fixed_min_duration; var dt = (min_duration - wanted_duration) / 2; before += dt; after -= dt; wanted_duration = before - after; ret = false; } var tolerance = this.data_update_every * 2; var movement = Math.abs(before - this.view_before); if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance && ret === true) { if(this.debug === true) this.log(logme + 'REJECTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + false); return false; } if(this.current.name === 'auto') { this.log(logme + 'caller called me with mode: ' + this.current.name); this.setMode('pan'); } if(this.debug === true) this.log(logme + 'ACCEPTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + ret); this.current.force_update_at = Date.now() + NETDATA.options.current.pan_and_zoom_delay; this.current.force_after_ms = after; this.current.force_before_ms = before; NETDATA.globalPanAndZoom.setMaster(this, after, before); return ret; }; var __legendFormatValueChartDecimalsLastMin = undefined; var __legendFormatValueChartDecimalsLastMax = undefined; var __legendFormatValueChartDecimals = -1; var __intlNumberFormat = null; this.legendFormatValueDecimalsFromMinMax = function(min, max) { if(min === __legendFormatValueChartDecimalsLastMin && max === __legendFormatValueChartDecimalsLastMax) return; __legendFormatValueChartDecimalsLastMin = min; __legendFormatValueChartDecimalsLastMax = max; var old = __legendFormatValueChartDecimals; if(this.data !== null && this.data.min === this.data.max) // it is a fixed number, let the visualizer decide based on the value __legendFormatValueChartDecimals = -1; else if(this.value_decimal_detail !== -1) // there is an override __legendFormatValueChartDecimals = this.value_decimal_detail; else { // ok, let's calculate the proper number of decimal points var delta; if (min === max) delta = Math.abs(min); else delta = Math.abs(max - min); if (delta > 1000) __legendFormatValueChartDecimals = 0; else if (delta > 10) __legendFormatValueChartDecimals = 1; else if (delta > 1) __legendFormatValueChartDecimals = 2; else if (delta > 0.1) __legendFormatValueChartDecimals = 2; else __legendFormatValueChartDecimals = 4; } if(__legendFormatValueChartDecimals !== old) { if(__legendFormatValueChartDecimals < 0) __intlNumberFormat = null; else __intlNumberFormat = NETDATA.fastNumberFormat.get( __legendFormatValueChartDecimals, __legendFormatValueChartDecimals ); } }; this.legendFormatValue = function(value) { if(typeof value !== 'number') return '-'; if(__intlNumberFormat !== null) return __intlNumberFormat.format(value); var dmin, dmax; if(this.value_decimal_detail !== -1) { dmin = dmax = this.value_decimal_detail; } else { dmin = 0; var abs = (value < 0) ? -value : value; if (abs > 1000) dmax = 0; else if (abs > 10) dmax = 1; else if (abs > 1) dmax = 2; else if (abs > 0.1) dmax = 2; else dmax = 4; } return NETDATA.fastNumberFormat.get(dmin, dmax).format(value); }; this.legendSetLabelValue = function(label, value) { var series = this.element_legend_childs.series[label]; if(typeof series === 'undefined') return; if(series.value === null && series.user === null) return; /* // this slows down firefox and edge significantly // since it requires to use innerHTML(), instead of innerText() // if the value has not changed, skip DOM update //if(series.last === value) return; var s, r; if(typeof value === 'number') { var v = Math.abs(value); s = r = this.legendFormatValue(value); if(typeof series.last === 'number') { if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>'; else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>'; else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>'; } else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>'; series.last = v; } else { if(value === null) s = r = ''; else s = r = value; series.last = value; } */ var s = this.legendFormatValue(value); // caching: do not update the update to show the same value again if(s === series.last_shown_value) return; series.last_shown_value = s; if(series.value !== null) series.value.innerText = s; if(series.user !== null) series.user.innerText = s; }; this.__legendSetDateString = function(date) { if(date !== this.__last_shown_legend_date) { this.element_legend_childs.title_date.innerText = date; this.__last_shown_legend_date = date; } }; this.__legendSetTimeString = function(time) { if(time !== this.__last_shown_legend_time) { this.element_legend_childs.title_time.innerText = time; this.__last_shown_legend_time = time; } }; this.__legendSetUnitsString = function(units) { if(units !== this.__last_shown_legend_units) { this.element_legend_childs.title_units.innerText = units; this.__last_shown_legend_units = units; } }; this.legendSetDateLast = { ms: 0, date: undefined, time: undefined }; this.legendSetDate = function(ms) { if(typeof ms !== 'number') { this.legendShowUndefined(); return; } if(this.legendSetDateLast.ms !== ms) { var d = new Date(ms); this.legendSetDateLast.ms = ms; this.legendSetDateLast.date = d.toLocaleDateString(); this.legendSetDateLast.time = d.toLocaleTimeString(); } if(this.element_legend_childs.title_date !== null) this.__legendSetDateString(this.legendSetDateLast.date); if(this.element_legend_childs.title_time !== null) this.__legendSetTimeString(this.legendSetDateLast.time); if(this.element_legend_childs.title_units !== null) this.__legendSetUnitsString(this.units) }; this.legendShowUndefined = function() { if(this.element_legend_childs.title_date !== null) this.__legendSetDateString(' '); if(this.element_legend_childs.title_time !== null) this.__legendSetTimeString(this.chart.name); if(this.element_legend_childs.title_units !== null) this.__legendSetUnitsString(' '); if(this.data && this.element_legend_childs.series !== null) { var labels = this.data.dimension_names; var i = labels.length; while(i--) { var label = labels[i]; if(typeof label === 'undefined' || typeof this.element_legend_childs.series[label] === 'undefined') continue; this.legendSetLabelValue(label, null); } } }; this.legendShowLatestValues = function() { if(this.chart === null) return; if(this.selected) return; if(this.data === null || this.element_legend_childs.series === null) { this.legendShowUndefined(); return; } var show_undefined = true; if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) show_undefined = false; if(show_undefined) { this.legendShowUndefined(); return; } this.legendSetDate(this.view_before); var labels = this.data.dimension_names; var i = labels.length; while(i--) { var label = labels[i]; if(typeof label === 'undefined') continue; if(typeof this.element_legend_childs.series[label] === 'undefined') continue; if(show_undefined) this.legendSetLabelValue(label, null); else this.legendSetLabelValue(label, this.data.view_latest_values[i]); } }; this.legendReset = function() { this.legendShowLatestValues(); }; // this should be called just ONCE per dimension per chart this._chartDimensionColor = function(label) { this.chartPrepareColorPalette(); if(typeof this.colors_assigned[label] === 'undefined') { if(this.colors_available.length === 0) { var len; // copy the custom colors if(this.colors_custom !== null) { len = this.colors_custom.length; while (len--) this.colors_available.unshift(this.colors_custom[len]); } // copy the standard palette colors len = NETDATA.themes.current.colors.length; while(len--) this.colors_available.unshift(NETDATA.themes.current.colors[len]); } // assign a color to this dimension this.colors_assigned[label] = this.colors_available.shift(); if(this.debug === true) this.log('label "' + label + '" got color "' + this.colors_assigned[label]); } else { if(this.debug === true) this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"'); } this.colors.push(this.colors_assigned[label]); return this.colors_assigned[label]; }; this.chartPrepareColorPalette = function() { var len; if(this.colors_custom !== null) return; if(this.debug === true) this.log("Preparing chart color palette"); this.colors = []; this.colors_available = []; this.colors_custom = []; // add the standard colors len = NETDATA.themes.current.colors.length; while(len--) this.colors_available.unshift(NETDATA.themes.current.colors[len]); // add the user supplied colors var c = $(this.element).data('colors'); // this.log('read colors: ' + c); if(typeof c === 'string' && c.length > 0) { c = c.split(' '); len = c.length; while(len--) { if(this.debug === true) this.log("Adding custom color " + c[len].toString() + " to palette"); this.colors_custom.unshift(c[len]); this.colors_available.unshift(c[len]); } } if(this.debug === true) { this.log("colors_custom:"); this.log(this.colors_custom); this.log("colors_available:"); this.log(this.colors_available); } }; // get the ordered list of chart colors // this includes user defined colors this.chartCustomColors = function() { this.chartPrepareColorPalette(); var colors; if(this.colors_custom.length) colors = this.colors_custom; else colors = this.colors; if(this.debug === true) { this.log("chartCustomColors() returns:"); this.log(colors); } return colors; }; // get the ordered list of chart ASSIGNED colors // (this returns only the colors that have been // assigned to dimensions, prepended with any // custom colors defined) this.chartColors = function() { this.chartPrepareColorPalette(); if(this.debug === true) { this.log("chartColors() returns:"); this.log(this.colors); } return this.colors; }; this.legendUpdateDOM = function() { var needed = false, dim, keys, len, i; // check that the legend DOM is up to date for the downloaded dimensions if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) { // this.log('the legend does not have any series - requesting legend update'); needed = true; } else if(this.data === null) { // this.log('the chart does not have any data - requesting legend update'); needed = true; } else if(typeof this.element_legend_childs.series.labels_key === 'undefined') { needed = true; } else { var labels = this.data.dimension_names.toString(); if(labels !== this.element_legend_childs.series.labels_key) { needed = true; if(this.debug === true) this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"'); } } if(needed === false) { // make sure colors available this.chartPrepareColorPalette(); // do we have to update the current values? // we do this, only when the visible chart is current if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) { if(this.debug === true) this.log('chart is in latest position... updating values on legend...'); //var labels = this.data.dimension_names; //var i = labels.length; //while(i--) // this.legendSetLabelValue(labels[i], this.data.latest_values[i]); } return; } if(this.colors === null) { // this is the first time we update the chart // let's assign colors to all dimensions if(this.library.track_colors() === true) { keys = Object.keys(this.chart.dimensions); len = keys.length; for(i = 0; i < len ;i++) this._chartDimensionColor(this.chart.dimensions[keys[i]].name); } } // we will re-generate the colors for the chart // based on the dimensions this result has data for this.colors = []; if(this.debug === true) this.log('updating Legend DOM'); // mark all dimensions as invalid this.dimensions_visibility.invalidateAll(); var genLabel = function(state, parent, dim, name, count) { var color = state._chartDimensionColor(name); var user_element = null; var user_id = self.data('show-value-of-' + name.toLowerCase() + '-at') || null; if(user_id === null) user_id = self.data('show-value-of-' + dim.toLowerCase() + '-at') || null; if(user_id !== null) { user_element = document.getElementById(user_id) || null; if (user_element === null) state.log('Cannot find element with id: ' + user_id); } state.element_legend_childs.series[name] = { name: document.createElement('span'), value: document.createElement('span'), user: user_element, last: null, last_shown_value: null }; var label = state.element_legend_childs.series[name]; // create the dimension visibility tracking for this label state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color); var rgb = NETDATA.colorHex2Rgb(color); label.name.innerHTML = '<table class="netdata-legend-name-table-' + state.chart.chart_type + '" style="background-color: ' + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')' + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'; var text = document.createTextNode(' ' + name); label.name.appendChild(text); if(count > 0) parent.appendChild(document.createElement('br')); parent.appendChild(label.name); parent.appendChild(label.value); }; var content = document.createElement('div'); if(this.hasLegend()) { this.element_legend_childs = { content: content, resize_handler: document.createElement('div'), toolbox: document.createElement('div'), toolbox_left: document.createElement('div'), toolbox_right: document.createElement('div'), toolbox_reset: document.createElement('div'), toolbox_zoomin: document.createElement('div'), toolbox_zoomout: document.createElement('div'), toolbox_volume: document.createElement('div'), title_date: document.createElement('span'), title_time: document.createElement('span'), title_units: document.createElement('span'), perfect_scroller: document.createElement('div'), series: {} }; this.element_legend.innerHTML = ''; if(this.library.toolboxPanAndZoom !== null) { var get_pan_and_zoom_step = function(event) { if (event.ctrlKey) return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_control; else if (event.shiftKey) return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_shift; else if (event.altKey) return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_alt; else return NETDATA.options.current.pan_and_zoom_factor; }; this.element_legend_childs.toolbox.className += ' netdata-legend-toolbox'; this.element.appendChild(this.element_legend_childs.toolbox); this.element_legend_childs.toolbox_left.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_left.innerHTML = '<i class="fa fa-backward"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_left); this.element_legend_childs.toolbox_left.onclick = function(e) { e.preventDefault(); var step = (that.view_before - that.view_after) * get_pan_and_zoom_step(e); var before = that.view_before - step; var after = that.view_after - step; if(after >= that.netdata_first) that.library.toolboxPanAndZoom(that, after, before); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_left).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Pan Left', content: 'Pan the chart to the left. You can also <b>drag it</b> with your mouse or your finger (on touch devices).<br/><small>Help, can be disabled from the settings.</small>' }); this.element_legend_childs.toolbox_reset.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_reset.innerHTML = '<i class="fa fa-play"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_reset); this.element_legend_childs.toolbox_reset.onclick = function(e) { e.preventDefault(); NETDATA.resetAllCharts(that); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_reset).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Chart Reset', content: 'Reset all the charts to their default auto-refreshing state. You can also <b>double click</b> the chart contents with your mouse or your finger (on touch devices).<br/><small>Help, can be disabled from the settings.</small>' }); this.element_legend_childs.toolbox_right.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_right.innerHTML = '<i class="fa fa-forward"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_right); this.element_legend_childs.toolbox_right.onclick = function(e) { e.preventDefault(); var step = (that.view_before - that.view_after) * get_pan_and_zoom_step(e); var before = that.view_before + step; var after = that.view_after + step; if(before <= that.netdata_last) that.library.toolboxPanAndZoom(that, after, before); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_right).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Pan Right', content: 'Pan the chart to the right. You can also <b>drag it</b> with your mouse or your finger (on touch devices).<br/><small>Help, can be disabled from the settings.</small>' }); this.element_legend_childs.toolbox_zoomin.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_zoomin.innerHTML = '<i class="fa fa-plus"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_zoomin); this.element_legend_childs.toolbox_zoomin.onclick = function(e) { e.preventDefault(); var dt = ((that.view_before - that.view_after) * (get_pan_and_zoom_step(e) * 0.8) / 2); var before = that.view_before - dt; var after = that.view_after + dt; that.library.toolboxPanAndZoom(that, after, before); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_zoomin).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Chart Zoom In', content: 'Zoom in the chart. You can also press SHIFT and select an area of the chart to zoom in. On Chrome and Opera, you can press the SHIFT or the ALT keys and then use the mouse wheel to zoom in or out.<br/><small>Help, can be disabled from the settings.</small>' }); this.element_legend_childs.toolbox_zoomout.className += ' netdata-legend-toolbox-button'; this.element_legend_childs.toolbox_zoomout.innerHTML = '<i class="fa fa-minus"></i>'; this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_zoomout); this.element_legend_childs.toolbox_zoomout.onclick = function(e) { e.preventDefault(); var dt = (((that.view_before - that.view_after) / (1.0 - (get_pan_and_zoom_step(e) * 0.8)) - (that.view_before - that.view_after)) / 2); var before = that.view_before + dt; var after = that.view_after - dt; that.library.toolboxPanAndZoom(that, after, before); }; if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.toolbox_zoomout).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Chart Zoom Out', content: 'Zoom out the chart. On Chrome and Opera, you can also press the SHIFT or the ALT keys and then use the mouse wheel to zoom in or out.<br/><small>Help, can be disabled from the settings.</small>' }); //this.element_legend_childs.toolbox_volume.className += ' netdata-legend-toolbox-button'; //this.element_legend_childs.toolbox_volume.innerHTML = '<i class="fa fa-sort-amount-desc"></i>'; //this.element_legend_childs.toolbox_volume.title = 'Visible Volume'; //this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_volume); //this.element_legend_childs.toolbox_volume.onclick = function(e) { //e.preventDefault(); //alert('clicked toolbox_volume on ' + that.id); //} } else { this.element_legend_childs.toolbox = null; this.element_legend_childs.toolbox_left = null; this.element_legend_childs.toolbox_reset = null; this.element_legend_childs.toolbox_right = null; this.element_legend_childs.toolbox_zoomin = null; this.element_legend_childs.toolbox_zoomout = null; this.element_legend_childs.toolbox_volume = null; } this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler"; this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>'; this.element.appendChild(this.element_legend_childs.resize_handler); if(NETDATA.options.current.show_help === true) $(this.element_legend_childs.resize_handler).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, title: 'Chart Resize', content: 'Drag this point with your mouse or your finger (on touch devices), to resize the chart vertically. You can also <b>double click it</b> or <b>double tap it</b> to reset between 2 states: the default and the one that fits all the values.<br/><small>Help, can be disabled from the settings.</small>' }); // mousedown event this.element_legend_childs.resize_handler.onmousedown = function(e) { that.resizeHandler(e); }; // touchstart event this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) { that.resizeHandler(e); }, false); this.element_legend_childs.title_date.className += " netdata-legend-title-date"; this.element_legend.appendChild(this.element_legend_childs.title_date); this.__last_shown_legend_date = undefined; this.element_legend.appendChild(document.createElement('br')); this.element_legend_childs.title_time.className += " netdata-legend-title-time"; this.element_legend.appendChild(this.element_legend_childs.title_time); this.__last_shown_legend_time = undefined; this.element_legend.appendChild(document.createElement('br')); this.element_legend_childs.title_units.className += " netdata-legend-title-units"; this.element_legend.appendChild(this.element_legend_childs.title_units); this.__last_shown_legend_units = undefined; this.element_legend.appendChild(document.createElement('br')); this.element_legend_childs.perfect_scroller.className = 'netdata-legend-series'; this.element_legend.appendChild(this.element_legend_childs.perfect_scroller); content.className = 'netdata-legend-series-content'; this.element_legend_childs.perfect_scroller.appendChild(content); if(NETDATA.options.current.show_help === true) $(content).popover({ container: "body", animation: false, html: true, trigger: 'hover', placement: 'bottom', title: 'Chart Legend', delay: { show: NETDATA.options.current.show_help_delay_show_ms, hide: NETDATA.options.current.show_help_delay_hide_ms }, content: 'You can click or tap on the values or the labels to select dimensions. By pressing SHIFT or CONTROL, you can enable or disable multiple dimensions.<br/><small>Help, can be disabled from the settings.</small>' }); } else { this.element_legend_childs = { content: content, resize_handler: null, toolbox: null, toolbox_left: null, toolbox_right: null, toolbox_reset: null, toolbox_zoomin: null, toolbox_zoomout: null, toolbox_volume: null, title_date: null, title_time: null, title_units: null, perfect_scroller: null, series: {} }; } if(this.data) { this.element_legend_childs.series.labels_key = this.data.dimension_names.toString(); if(this.debug === true) this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"'); for(i = 0, len = this.data.dimension_names.length; i < len ;i++) { genLabel(this, content, this.data.dimension_ids[i], this.data.dimension_names[i], i); } } else { var tmp = []; keys = Object.keys(this.chart.dimensions); for(i = 0, len = keys.length; i < len ;i++) { dim = keys[i]; tmp.push(this.chart.dimensions[dim].name); genLabel(this, content, dim, this.chart.dimensions[dim].name, i); } this.element_legend_childs.series.labels_key = tmp.toString(); if(this.debug === true) this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"'); } // create a hidden div to be used for hidding // the original legend of the chart library var el = document.createElement('div'); if(this.element_legend !== null) this.element_legend.appendChild(el); el.style.display = 'none'; this.element_legend_childs.hidden = document.createElement('div'); el.appendChild(this.element_legend_childs.hidden); if(this.element_legend_childs.perfect_scroller !== null) { Ps.initialize(this.element_legend_childs.perfect_scroller, { wheelSpeed: 0.2, wheelPropagation: true, swipePropagation: true, minScrollbarLength: null, maxScrollbarLength: null, useBothWheelAxes: false, suppressScrollX: true, suppressScrollY: false, scrollXMarginOffset: 0, scrollYMarginOffset: 0, theme: 'default' }); Ps.update(this.element_legend_childs.perfect_scroller); } this.legendShowLatestValues(); }; this.hasLegend = function() { if(typeof this.___hasLegendCache___ !== 'undefined') return this.___hasLegendCache___; var leg = false; if(this.library && this.library.legend(this) === 'right-side') { var legend = $(this.element).data('legend') || 'yes'; if(legend === 'yes') leg = true; } this.___hasLegendCache___ = leg; return leg; }; this.legendWidth = function() { return (this.hasLegend())?140:0; }; this.legendHeight = function() { return $(this.element).height(); }; this.chartWidth = function() { return $(this.element).width() - this.legendWidth(); }; this.chartHeight = function() { return $(this.element).height(); }; this.chartPixelsPerPoint = function() { // force an options provided detail var px = this.pixels_per_point; if(this.library && px < this.library.pixels_per_point(this)) px = this.library.pixels_per_point(this); if(px < NETDATA.options.current.pixels_per_point) px = NETDATA.options.current.pixels_per_point; return px; }; this.needsRecreation = function() { return ( this.chart_created === true && this.library && this.library.autoresize() === false && this.tm.last_resized < NETDATA.options.last_page_resize ); }; this.chartURL = function() { var after, before, points_multiplier = 1; if(NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(this) === false) { this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq; after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000); before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000); this.view_after = after * 1000; this.view_before = before * 1000; this.requested_padding = null; points_multiplier = 1; } else if(this.current.force_before_ms !== null && this.current.force_after_ms !== null) { this.tm.pan_and_zoom_seq = 0; before = Math.round(this.current.force_before_ms / 1000); after = Math.round(this.current.force_after_ms / 1000); this.view_after = after * 1000; this.view_before = before * 1000; if(NETDATA.options.current.pan_and_zoom_data_padding === true) { this.requested_padding = Math.round((before - after) / 2); after -= this.requested_padding; before += this.requested_padding; this.requested_padding *= 1000; points_multiplier = 2; } this.current.force_before_ms = null; this.current.force_after_ms = null; } else { this.tm.pan_and_zoom_seq = 0; before = this.before; after = this.after; this.view_after = after * 1000; this.view_before = before * 1000; this.requested_padding = null; points_multiplier = 1; } this.requested_after = after * 1000; this.requested_before = before * 1000; this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint()); // build the data URL console.log('this.chart.data_url = ', this.chart.data_url) console.dir(this.chart) this.data_url = NETDATA.IAMServer + this.chart.data_url; this.data_url += "&format=" + this.library.format(); this.data_url += "&points=" + (this.data_points * points_multiplier).toString(); this.data_url += "&group=" + this.method; if(this.override_options !== null) this.data_url += "&options=" + this.override_options.toString(); else this.data_url += "&options=" + this.library.options(this); this.data_url += '|jsonwrap'; if(NETDATA.options.current.eliminate_zero_dimensions === true) this.data_url += '|nonzero'; if(this.append_options !== null) this.data_url += '|' + this.append_options.toString(); if(after) this.data_url += "&after=" + after.toString(); if(before) this.data_url += "&before=" + before.toString(); if(this.dimensions) this.data_url += "&dimensions=" + this.dimensions; if(NETDATA.options.debug.chart_data_url === true || this.debug === true) this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name); }; this.redrawChart = function() { if(this.data !== null) this.updateChartWithData(this.data); }; this.updateChartWithData = function(data) { if(this.debug === true) this.log('updateChartWithData() called.'); // this may force the chart to be re-created resizeChart(); this.data = data; this.updates_counter++; this.updates_since_last_unhide++; this.updates_since_last_creation++; var started = Date.now(); // if the result is JSON, find the latest update-every this.data_update_every = data.view_update_every * 1000; this.data_after = data.after * 1000; this.data_before = data.before * 1000; this.netdata_first = data.first_entry * 1000; this.netdata_last = data.last_entry * 1000; this.data_points = data.points; data.state = this; if(NETDATA.options.current.pan_and_zoom_data_padding === true && this.requested_padding !== null) { if(this.view_after < this.data_after) { // console.log('adjusting view_after from ' + this.view_after + ' to ' + this.data_after); this.view_after = this.data_after; } if(this.view_before > this.data_before) { // console.log('adjusting view_before from ' + this.view_before + ' to ' + this.data_before); this.view_before = this.data_before; } } else { this.view_after = this.data_after; this.view_before = this.data_before; } if(this.debug === true) { this.log('UPDATE No ' + this.updates_counter + ' COMPLETED'); if(this.current.force_after_ms) this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString()); else this.log('STATUS: forced : unset'); this.log('STATUS: requested : ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString()); this.log('STATUS: downloaded: ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString()); this.log('STATUS: rendered : ' + (this.view_after / 1000).toString() + ' - ' + (this.view_before / 1000).toString()); this.log('STATUS: points : ' + (this.data_points).toString()); } if(this.data_points === 0) { noDataToShow(); return; } if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) { if(this.debug === true) this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.'); init(); return; } // check and update the legend this.legendUpdateDOM(); if(this.chart_created === true && typeof this.library.update === 'function') { if(this.debug === true) this.log('updating chart...'); if(callChartLibraryUpdateSafely(data) === false) return; } else { if(this.debug === true) this.log('creating chart...'); if(callChartLibraryCreateSafely(data) === false) return; } hideMessage(); this.legendShowLatestValues(); if(this.selected === true) NETDATA.globalSelectionSync.stop(); // update the performance counters var now = Date.now(); this.tm.last_updated = now; // don't update last_autorefreshed if this chart is // forced to be updated with global PanAndZoom if(NETDATA.globalPanAndZoom.isActive()) this.tm.last_autorefreshed = 0; else { if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes === true) this.tm.last_autorefreshed = now - (now % this.data_update_every); else this.tm.last_autorefreshed = now; } this.refresh_dt_ms = now - started; NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms; if(this.refresh_dt_element !== null) this.refresh_dt_element.innerText = this.refresh_dt_ms.toString(); }; this.updateChart = function(callback) { if(this.debug === true) this.log('updateChart() called.'); if(this._updating === true) { if(this.debug === true) this.log('I am already updating...'); if(typeof callback === 'function') return callback(); return; } // due to late initialization of charts and libraries // we need to check this too if(this.enabled === false) { if(this.debug === true) this.log('I am not enabled'); if(typeof callback === 'function') return callback(); return; } if(canBeRendered() === false) { if(typeof callback === 'function') return callback(); return; } if(this.chart === null) return this.getChart(function() { return that.updateChart(callback); }); if(this.library.initialized === false) { if(this.library.enabled === true) { return this.library.initialize(function () { return that.updateChart(callback); }); } else { error('chart library "' + this.library_name + '" is not available.'); if(typeof callback === 'function') return callback(); return; } } this.clearSelection(); this.chartURL(); //if(this.debug === true) this.log('updating from ' + this.data_url); NETDATA.statistics.refreshes_total++; NETDATA.statistics.refreshes_active++; if(NETDATA.statistics.refreshes_active > NETDATA.statistics.refreshes_active_max) NETDATA.statistics.refreshes_active_max = NETDATA.statistics.refreshes_active; this._updating = true; console.log('>>>>>>>>>>> Rico trace in updateChart with url=', this.data_url) NETDATA.IAM.get(this.data_url) //'/api/v1/data?chart=netdata.server_cpu&format=json&points=60&group=average&options=absolute|jsonwrap|nonzero&after=-60&dimensions=user&_=1500779913718') .then(function (response) { let chart = response.data $("#iam").text(JSON.stringify(chart)); console.log(chart); that.xhr = undefined; that.retries_on_data_failures = 0; that.updateChartWithData(chart); NETDATA.statistics.refreshes_active--; that._updating = false; if(typeof callback === 'function') return callback(); }) .catch(function (msg) { //console.log(msg); that.xhr = undefined; if(msg.statusText !== 'abort') { that.retries_on_data_failures++; if(that.retries_on_data_failures > NETDATA.options.current.retries_on_data_failures) { // that.log('failed ' + that.retries_on_data_failures.toString() + ' times - giving up'); that.retries_on_data_failures = 0; error('data download failed for url: ' + that.data_url); } else { that.tm.last_autorefreshed = Date.now(); // that.log('failed ' + that.retries_on_data_failures.toString() + ' times, but I will retry'); } } NETDATA.statistics.refreshes_active--; that._updating = false; if(typeof callback === 'function') return callback(); }); /*this.xhr = $.ajax( { url: this.data_url, cache: false, async: true, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' } //,xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { that.xhr = undefined; that.retries_on_data_failures = 0; if(that.debug === true) that.log('data received. updating chart.'); that.updateChartWithData(data); }) .fail(function(msg) { that.xhr = undefined; if(msg.statusText !== 'abort') { that.retries_on_data_failures++; if(that.retries_on_data_failures > NETDATA.options.current.retries_on_data_failures) { // that.log('failed ' + that.retries_on_data_failures.toString() + ' times - giving up'); that.retries_on_data_failures = 0; error('data download failed for url: ' + that.data_url); } else { that.tm.last_autorefreshed = Date.now(); // that.log('failed ' + that.retries_on_data_failures.toString() + ' times, but I will retry'); } } }) .always(function() { that.xhr = undefined; NETDATA.statistics.refreshes_active--; that._updating = false; if(typeof callback === 'function') return callback(); });*/ }; this.isVisible = function(nocache) { if(typeof nocache === 'undefined') nocache = false; // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll); // caching - we do not evaluate the charts visibility // if the page has not been scrolled since the last check if(nocache === false && this.tm.last_visible_check > NETDATA.options.last_page_scroll) return this.___isVisible___; // tolerance is the number of pixels a chart can be off-screen // to consider it as visible and refresh it as if was visible var tolerance = 0; this.tm.last_visible_check = Date.now(); var rect = this.element.getBoundingClientRect(); var screenTop = window.scrollY; var screenBottom = screenTop + window.innerHeight; var chartTop = rect.top + screenTop; var chartBottom = chartTop + rect.height; if(rect.width === 0 || rect.height === 0) { hideChart(); this.___isVisible___ = false; return this.___isVisible___; } if(chartBottom + tolerance < screenTop || chartTop - tolerance > screenBottom) { // the chart is too far // this.log('nocache: ' + nocache.toString() + ', screen top: ' + screenTop.toString() + ', bottom: ' + screenBottom.toString() + ', chart top: ' + chartTop.toString() + ', bottom: ' + chartBottom.toString() + ', OFF SCREEN'); hideChart(); this.___isVisible___ = false; return this.___isVisible___; } else { // the chart is inside or very close // this.log('nocache: ' + nocache.toString() + ', screen top: ' + screenTop.toString() + ', bottom: ' + screenBottom.toString() + ', chart top: ' + chartTop.toString() + ', bottom: ' + chartBottom.toString() + ', VISIBLE'); unhideChart(); this.___isVisible___ = true; return this.___isVisible___; } }; this.isAutoRefreshable = function() { return (this.current.autorefresh); }; this.canBeAutoRefreshed = function() { var now = Date.now(); if(this.running === true) { if(this.debug === true) this.log('I am already running'); return false; } if(this.enabled === false) { if(this.debug === true) this.log('I am not enabled'); return false; } if(this.library === null || this.library.enabled === false) { error('charting library "' + this.library_name + '" is not available'); if(this.debug === true) this.log('My chart library ' + this.library_name + ' is not available'); return false; } if(this.isVisible() === false) { if(NETDATA.options.debug.visibility === true || this.debug === true) this.log('I am not visible'); return false; } if(this.current.force_update_at !== 0 && this.current.force_update_at < now) { if(this.debug === true) this.log('timed force update detected - allowing this update'); this.current.force_update_at = 0; return true; } if(this.isAutoRefreshable() === true) { // allow the first update, even if the page is not visible if(this.updates_counter && this.updates_since_last_unhide && NETDATA.options.page_is_visible === false) { // if(NETDATA.options.debug.focus === true || this.debug === true) // this.log('canBeAutoRefreshed(): page does not have focus'); return false; } if(this.needsRecreation() === true) { if(this.debug === true) this.log('canBeAutoRefreshed(): needs re-creation.'); return true; } // options valid only for autoRefresh() if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) { if(NETDATA.globalPanAndZoom.isActive()) { if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) { if(this.debug === true) this.log('canBeAutoRefreshed(): global panning: I need an update.'); return true; } else { if(this.debug === true) this.log('canBeAutoRefreshed(): global panning: I am already up to date.'); return false; } } if(this.selected === true) { if(this.debug === true) this.log('canBeAutoRefreshed(): I have a selection in place.'); return false; } if(this.paused === true) { if(this.debug === true) this.log('canBeAutoRefreshed(): I am paused.'); return false; } if(now - this.tm.last_autorefreshed >= this.data_update_every) { if(this.debug === true) this.log('canBeAutoRefreshed(): It is time to update me.'); return true; } } } return false; }; this.autoRefresh = function(callback) { if(this.canBeAutoRefreshed() === true && this.running === false) { var state = this; state.running = true; state.updateChart(function() { console.log('autoRefresh with updateChart') state.running = false; if(typeof callback !== 'undefined') return callback(); }); } else { console.log('autoRefresh with undefined') if(typeof callback !== 'undefined') return callback(); } }; this._defaultsFromDownloadedChart = function(chart) { this.chart = chart; this.chart_url = chart.url; this.data_update_every = chart.update_every * 1000; this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint()); this.tm.last_info_downloaded = Date.now(); if(this.title === null) this.title = chart.title; if(this.units === null) this.units = chart.units; }; // fetch the chart description from the netdata server this.getChart = function(callback) { console.log('Rico trace in getChart:', this.host) this.chart = NETDATA.chartRegistry.get(this.host, this.id); if(this.chart) { this._defaultsFromDownloadedChart(this.chart); if(typeof callback === 'function') return callback(); } else { this.chart_url = "/api/v1/chart?chart=" + this.id; if(this.debug === true) this.log('downloading ' + this.chart_url); console.log(' <<<<<<<<<<< Rico trace in getChart:', this.host + this.chart_url) // NETDATA.instance.get('/hostgroups?detail=true', { // params: { // ID: 12345 // } // }) // .then(function (response) { // console.log(response); // $("#api1").text(JSON.stringify(response)); // }) // .catch(function (error) { // console.log(error); // }); NETDATA.IAM.get(this.chart_url) .then(function (res) { var chart = res.data $("#iam").text(JSON.stringify(chart)); console.log(chart); chart.url = that.chart_url; that._defaultsFromDownloadedChart(chart); NETDATA.chartRegistry.add(that.host, that.id, chart); console.log('========== come into always to callback with ok===========') if(typeof callback === 'function') return callback(); }) .catch(function (error) { console.log(error); NETDATA.error(404, that.chart_url); error('chart not found on url "' + that.chart_url + '"'); console.log('========== come into always to callback with error===========') if(typeof callback === 'function') return callback(); }) // $.ajax( { // url: this.host + this.chart_url, // cache: false, // async: true, // //xhrFields: { withCredentials: true } // required for the cookie // }) // .done(function(chart) { // chart.url = that.chart_url; // that._defaultsFromDownloadedChart(chart); // NETDATA.chartRegistry.add(that.host, that.id, chart); // }) // .fail(function() { // NETDATA.error(404, that.chart_url); // error('chart not found on url "' + that.chart_url + '"'); // }) // .always(function() { // console.log('========== come into always to callback ===========') // if(typeof callback === 'function') // return callback(); // }); } }; // ============================================================================================================ // INITIALIZATION init(); }; NETDATA.resetAllCharts = function(state) { console.log('Rico trace in resetAllCharts') // first clear the global selection sync // to make sure no chart is in selected state state.globalSelectionSyncStop(); // there are 2 possibilities here // a. state is the global Pan and Zoom master // b. state is not the global Pan and Zoom master var master = true; if(NETDATA.globalPanAndZoom.isMaster(state) === false) master = false; // clear the global Pan and Zoom // this will also refresh the master // and unblock any charts currently mirroring the master NETDATA.globalPanAndZoom.clearMaster(); // if we were not the master, reset our status too // this is required because most probably the mouse // is over this chart, blocking it from auto-refreshing if(master === false && (state.paused === true || state.selected === true)) state.resetChart(); }; // get or create a chart state, given a DOM element NETDATA.chartState = function(element) { console.log('Rico trace in resetAllCharts') var state = $(element).data('netdata-state-object') || null; if(state === null) { state = new chartState(element); $(element).data('netdata-state-object', state); } return state; }; // ---------------------------------------------------------------------------------------------------------------- // Library functions // Load a script without jquery // This is used to load jquery - after it is loaded, we use jquery NETDATA._loadjQuery = function(callback) { if(typeof jQuery === 'undefined') { if(NETDATA.options.debug.main_loop === true) console.log('loading ' + NETDATA.jQuery); var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = NETDATA.jQuery; // script.onabort = onError; script.onerror = function() { NETDATA.error(101, NETDATA.jQuery); }; if(typeof callback === "function") script.onload = callback; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s); } else if(typeof callback === "function") return callback(); }; NETDATA._loadCSS = function(filename) { // don't use jQuery here // styles are loaded before jQuery // to eliminate showing an unstyled page to the user var fileref = document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", filename); if (typeof fileref !== 'undefined') document.getElementsByTagName("head")[0].appendChild(fileref); }; NETDATA.colorHex2Rgb = function(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; }; NETDATA.colorLuminance = function(hex, lum) { // validate hex string hex = String(hex).replace(/[^0-9a-f]/gi, ''); if (hex.length < 6) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]; lum = lum || 0; // convert to decimal and change luminosity var rgb = "#", c, i; for (i = 0; i < 3; i++) { c = parseInt(hex.substr(i*2,2), 16); c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); rgb += ("00"+c).substr(c.length); } return rgb; }; NETDATA.guid = function() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; NETDATA.zeropad = function(x) { if(x > -10 && x < 10) return '0' + x.toString(); else return x.toString(); }; // user function to signal us the DOM has been // updated. NETDATA.updatedDom = function() { NETDATA.options.updated_dom = true; }; NETDATA.ready = function(callback) { NETDATA.options.pauseCallback = callback; }; NETDATA.pause = function(callback) { if(typeof callback === 'function') { if (NETDATA.options.pause === true) return callback(); else NETDATA.options.pauseCallback = callback; } }; NETDATA.unpause = function() { NETDATA.options.pauseCallback = null; NETDATA.options.updated_dom = true; NETDATA.options.pause = false; }; // ---------------------------------------------------------------------------------------------------------------- // this is purely sequential charts refresher // it is meant to be autonomous NETDATA.chartRefresherNoParallel = function(index) { if(NETDATA.options.debug.main_loop === true) console.log('NETDATA.chartRefresherNoParallel(' + index + ')'); if(NETDATA.options.updated_dom === true) { // the dom has been updated // get the dom parts again NETDATA.parseDom(NETDATA.chartRefresher); return; } if(index >= NETDATA.options.targets.length) { if(NETDATA.options.debug.main_loop === true) console.log('waiting to restart main loop...'); NETDATA.options.auto_refresher_fast_weight = 0; setTimeout(function() { NETDATA.chartRefresher(); }, NETDATA.options.current.idle_between_loops); } else { var state = NETDATA.options.targets[index]; if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) { if(NETDATA.options.debug.main_loop === true) console.log('fast rendering...'); setTimeout(function() { state.autoRefresh(function () { NETDATA.chartRefresherNoParallel(++index); }); }, 0); } else { if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...'); NETDATA.options.auto_refresher_fast_weight = 0; setTimeout(function() { state.autoRefresh(function() { NETDATA.chartRefresherNoParallel(++index); }); }, NETDATA.options.current.idle_between_charts); } } }; NETDATA.chartRefresherWaitTime = function() { return NETDATA.options.current.idle_parallel_loops; }; // the default refresher NETDATA.chartRefresher = function() { console.log('auto-refresher...'); if(NETDATA.options.pause === true) { // console.log('auto-refresher is paused'); setTimeout(NETDATA.chartRefresher, NETDATA.chartRefresherWaitTime()); return; } if(typeof NETDATA.options.pauseCallback === 'function') { // console.log('auto-refresher is calling pauseCallback'); NETDATA.options.pause = true; NETDATA.options.pauseCallback(); NETDATA.chartRefresher(); return; } if(NETDATA.options.current.parallel_refresher === false) { // console.log('auto-refresher is calling chartRefresherNoParallel(0)'); NETDATA.chartRefresherNoParallel(0); return; } if(NETDATA.options.updated_dom === true) { // the dom has been updated // get the dom parts again // console.log('auto-refresher is calling parseDom()'); NETDATA.parseDom(NETDATA.chartRefresher); return; } var parallel = []; var targets = NETDATA.options.targets; var len = targets.length; console.log('Rico trace in chartRefresher with len=', len) var state; while(len--) { state = targets[len]; if(state.isVisible() === false || state.running === true) continue; if(state.library.initialized === false) { if(state.library.enabled === true) { state.library.initialize(NETDATA.chartRefresher); return; } else { console.log('chart library "' + state.library_name + '" is not enabled.') state.error('chart library "' + state.library_name + '" is not enabled.'); } } parallel.unshift(state); } if(parallel.length > 0) { // console.log('auto-refresher executing in parallel for ' + parallel.length.toString() + ' charts'); // this will execute the jobs in parallel $(parallel).each(function() { console.log('parallel to autoRefresh') this.autoRefresh(); }) } else { console.log('auto-refresher nothing to do'); } // run the next refresh iteration setTimeout(NETDATA.chartRefresher, NETDATA.chartRefresherWaitTime()); }; NETDATA.parseDom = function(callback) { NETDATA.options.last_page_scroll = Date.now(); NETDATA.options.updated_dom = false; var targets = $('div[data-netdata]'); //.filter(':visible'); if(NETDATA.options.debug.main_loop === true) console.log('DOM updated - there are ' + targets.length + ' charts on page.'); NETDATA.options.targets = []; var len = targets.length; while(len--) { // the initialization will take care of sizing // and the "loading..." message NETDATA.options.targets.push(NETDATA.chartState(targets[len])); console.log('targets looks like: ',targets[len]) console.log('NETDATA.options.targets looks like: ', NETDATA.chartState(targets[len])) } if(typeof callback === 'function') return callback(); }; // this is the main function - where everything starts NETDATA.start = function() { // this should be called only once NETDATA.options.page_is_visible = true; $(window).blur(function() { if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) { NETDATA.options.page_is_visible = false; if(NETDATA.options.debug.focus === true) console.log('Lost Focus!'); } }); $(window).focus(function() { if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) { NETDATA.options.page_is_visible = true; if(NETDATA.options.debug.focus === true) console.log('Focus restored!'); } }); if(typeof document.hasFocus === 'function' && !document.hasFocus()) { if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) { NETDATA.options.page_is_visible = false; if(NETDATA.options.debug.focus === true) console.log('Document has no focus!'); } } // bootstrap tab switching $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll); // bootstrap modal switching var $modal = $('.modal'); $modal.on('hidden.bs.modal', NETDATA.onscroll); $modal.on('shown.bs.modal', NETDATA.onscroll); // bootstrap collapse switching var $collapse = $('.collapse'); $collapse.on('hidden.bs.collapse', NETDATA.onscroll); $collapse.on('shown.bs.collapse', NETDATA.onscroll); NETDATA.parseDom(NETDATA.chartRefresher); // Alarms initialization setTimeout(NETDATA.alarms.init, 1000); // Registry initialization setTimeout(NETDATA.registry.init, netdataRegistryAfterMs); if(typeof netdataCallback === 'function') netdataCallback(); }; // ---------------------------------------------------------------------------------------------------------------- // peity NETDATA.peityInitialize = function(callback) { if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) { $.ajax({ url: NETDATA.peity_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('peity', NETDATA.peity_js); }) .fail(function() { NETDATA.chartLibraries.peity.enabled = false; NETDATA.error(100, NETDATA.peity_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.peity.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.peityChartUpdate = function(state, data) { state.peity_instance.innerHTML = data.result; if(state.peity_options.stroke !== state.chartCustomColors()[0]) { state.peity_options.stroke = state.chartCustomColors()[0]; if(state.chart.chart_type === 'line') state.peity_options.fill = NETDATA.themes.current.background; else state.peity_options.fill = NETDATA.colorLuminance(state.chartCustomColors()[0], NETDATA.chartDefaults.fill_luminance); } $(state.peity_instance).peity('line', state.peity_options); return true; }; NETDATA.peityChartCreate = function(state, data) { state.peity_instance = document.createElement('div'); state.element_chart.appendChild(state.peity_instance); var self = $(state.element); state.peity_options = { stroke: NETDATA.themes.current.foreground, strokeWidth: self.data('peity-strokewidth') || 1, width: state.chartWidth(), height: state.chartHeight(), fill: NETDATA.themes.current.foreground }; NETDATA.peityChartUpdate(state, data); return true; }; // ---------------------------------------------------------------------------------------------------------------- // sparkline NETDATA.sparklineInitialize = function(callback) { if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) { $.ajax({ url: NETDATA.sparkline_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js); }) .fail(function() { NETDATA.chartLibraries.sparkline.enabled = false; NETDATA.error(100, NETDATA.sparkline_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.sparkline.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.sparklineChartUpdate = function(state, data) { state.sparkline_options.width = state.chartWidth(); state.sparkline_options.height = state.chartHeight(); $(state.element_chart).sparkline(data.result, state.sparkline_options); return true; }; NETDATA.sparklineChartCreate = function(state, data) { var self = $(state.element); var type = self.data('sparkline-type') || 'line'; var lineColor = self.data('sparkline-linecolor') || state.chartCustomColors()[0]; var fillColor = self.data('sparkline-fillcolor') || ((state.chart.chart_type === 'line')?NETDATA.themes.current.background:NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance)); var chartRangeMin = self.data('sparkline-chartrangemin') || undefined; var chartRangeMax = self.data('sparkline-chartrangemax') || undefined; var composite = self.data('sparkline-composite') || undefined; var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined; var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined; var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined; var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined; var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined; var spotColor = self.data('sparkline-spotcolor') || undefined; var minSpotColor = self.data('sparkline-minspotcolor') || undefined; var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined; var spotRadius = self.data('sparkline-spotradius') || undefined; var valueSpots = self.data('sparkline-valuespots') || undefined; var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined; var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined; var lineWidth = self.data('sparkline-linewidth') || undefined; var normalRangeMin = self.data('sparkline-normalrangemin') || undefined; var normalRangeMax = self.data('sparkline-normalrangemax') || undefined; var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined; var xvalues = self.data('sparkline-xvalues') || undefined; var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined; var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined; var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined; var disableInteraction = self.data('sparkline-disableinteraction') || false; var disableTooltips = self.data('sparkline-disabletooltips') || false; var disableHighlight = self.data('sparkline-disablehighlight') || false; var highlightLighten = self.data('sparkline-highlightlighten') || 1.4; var highlightColor = self.data('sparkline-highlightcolor') || undefined; var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined; var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined; var tooltipFormat = self.data('sparkline-tooltipformat') || undefined; var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined; var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units; var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true; var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined; var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined; var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined; var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); }; var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined; var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined; var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined; var animatedZooms = self.data('sparkline-animatedzooms') || false; if(spotColor === 'disable') spotColor=''; if(minSpotColor === 'disable') minSpotColor=''; if(maxSpotColor === 'disable') maxSpotColor=''; // state.log('sparkline type ' + type + ', lineColor: ' + lineColor + ', fillColor: ' + fillColor); state.sparkline_options = { type: type, lineColor: lineColor, fillColor: fillColor, chartRangeMin: chartRangeMin, chartRangeMax: chartRangeMax, composite: composite, enableTagOptions: enableTagOptions, tagOptionPrefix: tagOptionPrefix, tagValuesAttribute: tagValuesAttribute, disableHiddenCheck: disableHiddenCheck, defaultPixelsPerValue: defaultPixelsPerValue, spotColor: spotColor, minSpotColor: minSpotColor, maxSpotColor: maxSpotColor, spotRadius: spotRadius, valueSpots: valueSpots, highlightSpotColor: highlightSpotColor, highlightLineColor: highlightLineColor, lineWidth: lineWidth, normalRangeMin: normalRangeMin, normalRangeMax: normalRangeMax, drawNormalOnTop: drawNormalOnTop, xvalues: xvalues, chartRangeClip: chartRangeClip, chartRangeMinX: chartRangeMinX, chartRangeMaxX: chartRangeMaxX, disableInteraction: disableInteraction, disableTooltips: disableTooltips, disableHighlight: disableHighlight, highlightLighten: highlightLighten, highlightColor: highlightColor, tooltipContainer: tooltipContainer, tooltipClassname: tooltipClassname, tooltipChartTitle: state.title, tooltipFormat: tooltipFormat, tooltipPrefix: tooltipPrefix, tooltipSuffix: tooltipSuffix, tooltipSkipNull: tooltipSkipNull, tooltipValueLookups: tooltipValueLookups, tooltipFormatFieldlist: tooltipFormatFieldlist, tooltipFormatFieldlistKey: tooltipFormatFieldlistKey, numberFormatter: numberFormatter, numberDigitGroupSep: numberDigitGroupSep, numberDecimalMark: numberDecimalMark, numberDigitGroupCount: numberDigitGroupCount, animatedZooms: animatedZooms, width: state.chartWidth(), height: state.chartHeight() }; $(state.element_chart).sparkline(data.result, state.sparkline_options); return true; }; // ---------------------------------------------------------------------------------------------------------------- // dygraph NETDATA.dygraph = { smooth: false }; NETDATA.dygraphToolboxPanAndZoom = function(state, after, before) { if(after < state.netdata_first) after = state.netdata_first; if(before > state.netdata_last) before = state.netdata_last; state.setMode('zoom'); state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); state.dygraph_user_action = true; state.dygraph_force_zoom = true; state.updateChartPanOrZoom(after, before); NETDATA.globalPanAndZoom.setMaster(state, after, before); }; NETDATA.dygraphSetSelection = function(state, t) { if(typeof state.dygraph_instance !== 'undefined') { var r = state.calculateRowForTime(t); if(r !== -1) state.dygraph_instance.setSelection(r); else { state.dygraph_instance.clearSelection(); state.legendShowUndefined(); } } return true; }; NETDATA.dygraphClearSelection = function(state) { if(typeof state.dygraph_instance !== 'undefined') { state.dygraph_instance.clearSelection(); } return true; }; NETDATA.dygraphSmoothInitialize = function(callback) { $.ajax({ url: NETDATA.dygraph_smooth_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.dygraph.smooth = true; smoothPlotter.smoothing = 0.3; }) .fail(function() { NETDATA.dygraph.smooth = false; }) .always(function() { if(typeof callback === "function") return callback(); }); }; NETDATA.dygraphInitialize = function(callback) { if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) { $.ajax({ url: NETDATA.dygraph_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js); }) .fail(function() { NETDATA.chartLibraries.dygraph.enabled = false; NETDATA.error(100, NETDATA.dygraph_js); }) .always(function() { if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true) NETDATA.dygraphSmoothInitialize(callback); else if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.dygraph.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.dygraphChartUpdate = function(state, data) { var dygraph = state.dygraph_instance; if(typeof dygraph === 'undefined') return NETDATA.dygraphChartCreate(state, data); // when the chart is not visible, and hidden // if there is a window resize, dygraph detects // its element size as 0x0. // this will make it re-appear properly if(state.tm.last_unhidden > state.dygraph_last_rendered) dygraph.resize(); var options = { file: data.result.data, colors: state.chartColors(), labels: data.result.labels, labelsDivWidth: state.chartWidth() - 70, visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names) }; if(state.dygraph_force_zoom === true) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphChartUpdate() forced zoom update'); options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null; options.isZoomedIgnoreProgrammaticZoom = true; state.dygraph_force_zoom = false; } else if(state.current.name !== 'auto') { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphChartUpdate() loose update'); } else { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphChartUpdate() strict update'); options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null; options.isZoomedIgnoreProgrammaticZoom = true; } options.valueRange = state.dygraph_options.valueRange; var oldMax = null, oldMin = null; if (state.__commonMin !== null) { state.data.min = state.dygraph_instance.axes_[0].extremeRange[0]; oldMin = options.valueRange[0] = NETDATA.commonMin.get(state); } if (state.__commonMax !== null) { state.data.max = state.dygraph_instance.axes_[0].extremeRange[1]; oldMax = options.valueRange[1] = NETDATA.commonMax.get(state); } if(state.dygraph_smooth_eligible === true) { if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter) || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) { NETDATA.dygraphChartCreate(state, data); return; } } dygraph.updateOptions(options); var redraw = false; if(oldMin !== null && oldMin > state.dygraph_instance.axes_[0].extremeRange[0]) { state.data.min = state.dygraph_instance.axes_[0].extremeRange[0]; options.valueRange[0] = NETDATA.commonMin.get(state); redraw = true; } if(oldMax !== null && oldMax < state.dygraph_instance.axes_[0].extremeRange[1]) { state.data.max = state.dygraph_instance.axes_[0].extremeRange[1]; options.valueRange[1] = NETDATA.commonMax.get(state); redraw = true; } if(redraw === true) { // state.log('forcing redraw to adapt to common- min/max'); dygraph.updateOptions(options); } state.dygraph_last_rendered = Date.now(); return true; }; NETDATA.dygraphChartCreate = function(state, data) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphChartCreate()'); var self = $(state.element); var chart_type = self.data('dygraph-type') || state.chart.chart_type; if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area'; var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state) === true)?3:4; var smooth = (NETDATA.dygraph.smooth === true) ?(self.data('dygraph-smooth') || (chart_type === 'line' && NETDATA.chartLibraries.dygraph.isSparkline(state) === false)) :false; state.dygraph_options = { colors: self.data('dygraph-colors') || state.chartColors(), // leave a few pixels empty on the right of the chart rightGap: self.data('dygraph-rightgap') || 5, showRangeSelector: self.data('dygraph-showrangeselector') || false, showRoller: self.data('dygraph-showroller') || false, title: self.data('dygraph-title') || state.title, titleHeight: self.data('dygraph-titleheight') || 19, legend: self.data('dygraph-legend') || 'always', // we need this to get selection events labels: data.result.labels, labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden, labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' }, labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70, labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true, labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true, labelsKMB: false, labelsKMG2: false, showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true, hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true, includeZero: self.data('dygraph-includezero') || (chart_type === 'stacked'), xRangePad: self.data('dygraph-xrangepad') || 0, yRangePad: self.data('dygraph-yrangepad') || 1, valueRange: self.data('dygraph-valuerange') || [ null, null ], ylabel: state.units, yLabelWidth: self.data('dygraph-ylabelwidth') || 12, // the function to plot the chart plotter: null, // The width of the lines connecting data points. // This can be used to increase the contrast or some graphs. strokeWidth: self.data('dygraph-strokewidth') || ((chart_type === 'stacked')?0.1:((smooth === true)?1.5:0.7)), strokePattern: self.data('dygraph-strokepattern') || undefined, // The size of the dot to draw on each point in pixels (see drawPoints). // A dot is always drawn when a point is "isolated", // i.e. there is a missing point on either side of it. // This also controls the size of those dots. drawPoints: self.data('dygraph-drawpoints') || false, // Draw points at the edges of gaps in the data. // This improves visibility of small data segments or other data irregularities. drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true, connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false, pointSize: self.data('dygraph-pointsize') || 1, // enabling this makes the chart with little square lines stepPlot: self.data('dygraph-stepplot') || false, // Draw a border around graph lines to make crossing lines more easily // distinguishable. Useful for graphs with many lines. strokeBorderColor: self.data('dygraph-strokebordercolor') || NETDATA.themes.current.background, strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0, fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked'), fillAlpha: self.data('dygraph-fillalpha') || ((chart_type === 'stacked') ?NETDATA.options.current.color_fill_opacity_stacked :NETDATA.options.current.color_fill_opacity_area), stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked'), stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none', drawAxis: self.data('dygraph-drawaxis') || true, axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10, axisLineColor: self.data('dygraph-axislinecolor') || NETDATA.themes.current.axis, axisLineWidth: self.data('dygraph-axislinewidth') || 1.0, drawGrid: self.data('dygraph-drawgrid') || true, gridLinePattern: self.data('dygraph-gridlinepattern') || null, gridLineWidth: self.data('dygraph-gridlinewidth') || 1.0, gridLineColor: self.data('dygraph-gridlinecolor') || NETDATA.themes.current.grid, maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8, sigFigs: self.data('dygraph-sigfigs') || null, digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2, valueFormatter: self.data('dygraph-valueformatter') || undefined, highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize, highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 }, highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5, pointClickCallback: self.data('dygraph-pointclickcallback') || undefined, visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names), axes: { x: { pixelsPerLabel: 50, ticker: Dygraph.dateTicker, axisLabelFormatter: function (d, gran) { void(gran); return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds()); } }, y: { pixelsPerLabel: 15, axisLabelFormatter: function (y) { // unfortunately, we have to call this every single time state.legendFormatValueDecimalsFromMinMax( this.axes_[0].extremeRange[0], this.axes_[0].extremeRange[1] ); return state.legendFormatValue(y); } } }, legendFormatter: function(data) { var elements = state.element_legend_childs; // if the hidden div is not there // we are not managing the legend if(elements.hidden === null) return; if (typeof data.x !== 'undefined') { state.legendSetDate(data.x); var i = data.series.length; while(i--) { var series = data.series[i]; if(series.isVisible === true) state.legendSetLabelValue(series.label, series.y); else state.legendSetLabelValue(series.label, null); } } return ''; }, drawCallback: function(dygraph, is_initial) { if(state.current.name !== 'auto' && state.dygraph_user_action === true) { state.dygraph_user_action = false; var x_range = dygraph.xAxisRange(); var after = Math.round(x_range[0]); var before = Math.round(x_range[1]); if(NETDATA.options.debug.dygraph === true) state.log('dygraphDrawCallback(dygraph, ' + is_initial + '): ' + (after / 1000).toString() + ' - ' + (before / 1000).toString()); if(before <= state.netdata_last && after >= state.netdata_first) state.updateChartPanOrZoom(after, before); } }, zoomCallback: function(minDate, maxDate, yRanges) { void(yRanges); if(NETDATA.options.debug.dygraph === true) state.log('dygraphZoomCallback()'); state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); state.setMode('zoom'); // refresh it to the greatest possible zoom level state.dygraph_user_action = true; state.dygraph_force_zoom = true; state.updateChartPanOrZoom(minDate, maxDate); }, highlightCallback: function(event, x, points, row, seriesName) { void(seriesName); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphHighlightCallback()'); state.pauseChart(); // there is a bug in dygraph when the chart is zoomed enough // the time it thinks is selected is wrong // here we calculate the time t based on the row number selected // which is ok // var t = state.data_after + row * state.data_update_every; // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':(Math.abs(x-t)<=state.data_update_every)?'SIMILAR':'DIFFERENT') + ', rows in db: ' + state.data_points + ' visible(x) = ' + state.timeIsVisible(x) + ' visible(t) = ' + state.timeIsVisible(t) + ' r(x) = ' + state.calculateRowForTime(x) + ' r(t) = ' + state.calculateRowForTime(t) + ' range: ' + state.data_after + ' - ' + state.data_before + ' real: ' + state.data.after + ' - ' + state.data.before + ' every: ' + state.data_update_every); state.globalSelectionSync(x); // fix legend zIndex using the internal structures of dygraph legend module // this works, but it is a hack! // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000; }, unhighlightCallback: function(event) { void(event); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('dygraphUnhighlightCallback()'); state.unpauseChart(); state.globalSelectionSyncStop(); }, interactionModel : { mousedown: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.mousedown()'); state.dygraph_user_action = true; state.globalSelectionSyncStop(); if(NETDATA.options.debug.dygraph === true) state.log('dygraphMouseDown()'); // Right-click should not initiate a zoom. if(event.button && event.button === 2) return; context.initializeMouseDown(event, dygraph, context); if(event.button && event.button === 1) { if (event.altKey || event.shiftKey) { state.setMode('pan'); state.globalSelectionSyncDelay(); Dygraph.startPan(event, dygraph, context); } else { state.setMode('zoom'); state.globalSelectionSyncDelay(); Dygraph.startZoom(event, dygraph, context); } } else { if (event.altKey || event.shiftKey) { state.setMode('zoom'); state.globalSelectionSyncDelay(); Dygraph.startZoom(event, dygraph, context); } else { state.setMode('pan'); state.globalSelectionSyncDelay(); Dygraph.startPan(event, dygraph, context); } } }, mousemove: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.mousemove()'); if(context.isPanning) { state.dygraph_user_action = true; state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); state.setMode('pan'); context.is2DPan = false; Dygraph.movePan(event, dygraph, context); } else if(context.isZooming) { state.dygraph_user_action = true; state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); state.setMode('zoom'); Dygraph.moveZoom(event, dygraph, context); } }, mouseup: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.mouseup()'); if (context.isPanning) { state.dygraph_user_action = true; state.globalSelectionSyncDelay(); Dygraph.endPan(event, dygraph, context); } else if (context.isZooming) { state.dygraph_user_action = true; state.globalSelectionSyncDelay(); Dygraph.endZoom(event, dygraph, context); } }, click: function(event, dygraph, context) { void(dygraph); void(context); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.click()'); event.preventDefault(); }, dblclick: function(event, dygraph, context) { void(event); void(dygraph); void(context); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.dblclick()'); NETDATA.resetAllCharts(state); }, wheel: function(event, dygraph, context) { void(context); if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.wheel()'); // Take the offset of a mouse event on the dygraph canvas and // convert it to a pair of percentages from the bottom left. // (Not top left, bottom is where the lower value is.) function offsetToPercentage(g, offsetX, offsetY) { // This is calculating the pixel offset of the leftmost date. var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0]; var yar0 = g.yAxisRange(0); // This is calculating the pixel of the highest value. (Top pixel) var yOffset = g.toDomCoords(null, yar0[1])[1]; // x y w and h are relative to the corner of the drawing area, // so that the upper corner of the drawing area is (0, 0). var x = offsetX - xOffset; var y = offsetY - yOffset; // This is computing the rightmost pixel, effectively defining the // width. var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset; // This is computing the lowest pixel, effectively defining the height. var h = g.toDomCoords(null, yar0[0])[1] - yOffset; // Percentage from the left. var xPct = w === 0 ? 0 : (x / w); // Percentage from the top. var yPct = h === 0 ? 0 : (y / h); // The (1-) part below changes it from "% distance down from the top" // to "% distance up from the bottom". return [xPct, (1-yPct)]; } // Adjusts [x, y] toward each other by zoomInPercentage% // Split it so the left/bottom axis gets xBias/yBias of that change and // tight/top gets (1-xBias)/(1-yBias) of that change. // // If a bias is missing it splits it down the middle. function zoomRange(g, zoomInPercentage, xBias, yBias) { xBias = xBias || 0.5; yBias = yBias || 0.5; function adjustAxis(axis, zoomInPercentage, bias) { var delta = axis[1] - axis[0]; var increment = delta * zoomInPercentage; var foo = [increment * bias, increment * (1-bias)]; return [ axis[0] + foo[0], axis[1] - foo[1] ]; } var yAxes = g.yAxisRanges(); var newYAxes = []; for (var i = 0; i < yAxes.length; i++) { newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias); } return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias); } if(event.altKey || event.shiftKey) { state.dygraph_user_action = true; state.globalSelectionSyncStop(); state.globalSelectionSyncDelay(); // http://dygraphs.com/gallery/interaction-api.js var normal_def; if(typeof event.wheelDelta === 'number' && !isNaN(event.wheelDelta)) // chrome normal_def = event.wheelDelta / 40; else // firefox normal_def = event.deltaY * -1.2; var normal = (event.detail) ? event.detail * -1 : normal_def; var percentage = normal / 50; if (!(event.offsetX && event.offsetY)){ event.offsetX = event.layerX - event.target.offsetLeft; event.offsetY = event.layerY - event.target.offsetTop; } var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY); var xPct = percentages[0]; var yPct = percentages[1]; var new_x_range = zoomRange(dygraph, percentage, xPct, yPct); var after = new_x_range[0]; var before = new_x_range[1]; var first = state.netdata_first + state.data_update_every; var last = state.netdata_last + state.data_update_every; if(before > last) { after -= (before - last); before = last; } if(after < first) { after = first; } state.setMode('zoom'); if(state.updateChartPanOrZoom(after, before) === true) dygraph.updateOptions({ dateWindow: [ after, before ] }); event.preventDefault(); } }, touchstart: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.touchstart()'); state.dygraph_user_action = true; state.setMode('zoom'); state.pauseChart(); Dygraph.defaultInteractionModel.touchstart(event, dygraph, context); // we overwrite the touch directions at the end, to overwrite // the internal default of dygraph context.touchDirections = { x: true, y: false }; state.dygraph_last_touch_start = Date.now(); state.dygraph_last_touch_move = 0; if(typeof event.touches[0].pageX === 'number') state.dygraph_last_touch_page_x = event.touches[0].pageX; else state.dygraph_last_touch_page_x = 0; }, touchmove: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.touchmove()'); state.dygraph_user_action = true; Dygraph.defaultInteractionModel.touchmove(event, dygraph, context); state.dygraph_last_touch_move = Date.now(); }, touchend: function(event, dygraph, context) { if(NETDATA.options.debug.dygraph === true || state.debug === true) state.log('interactionModel.touchend()'); state.dygraph_user_action = true; Dygraph.defaultInteractionModel.touchend(event, dygraph, context); // if it didn't move, it is a selection if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) { // internal api of dygraph var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w; var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct); if(NETDATA.dygraphSetSelection(state, t) === true) state.globalSelectionSync(t); } // if it was double tap within double click time, reset the charts var now = Date.now(); if(typeof state.dygraph_last_touch_end !== 'undefined') { if(state.dygraph_last_touch_move === 0) { var dt = now - state.dygraph_last_touch_end; if(dt <= NETDATA.options.current.double_click_speed) NETDATA.resetAllCharts(state); } } // remember the timestamp of the last touch end state.dygraph_last_touch_end = now; } } }; if(NETDATA.chartLibraries.dygraph.isSparkline(state)) { state.dygraph_options.drawGrid = false; state.dygraph_options.drawAxis = false; state.dygraph_options.title = undefined; state.dygraph_options.ylabel = undefined; state.dygraph_options.yLabelWidth = 0; state.dygraph_options.labelsDivWidth = 120; state.dygraph_options.labelsDivStyles.width = '120px'; state.dygraph_options.labelsSeparateLines = true; state.dygraph_options.rightGap = 0; state.dygraph_options.yRangePad = 1; } if(smooth === true) { state.dygraph_smooth_eligible = true; if(NETDATA.options.current.smooth_plot === true) state.dygraph_options.plotter = smoothPlotter; } else state.dygraph_smooth_eligible = false; state.dygraph_instance = new Dygraph(state.element_chart, data.result.data, state.dygraph_options); state.dygraph_force_zoom = false; state.dygraph_user_action = false; state.dygraph_last_rendered = Date.now(); if(state.dygraph_options.valueRange[0] === null && state.dygraph_options.valueRange[1] === null) { if (typeof state.dygraph_instance.axes_[0].extremeRange !== 'undefined') { state.__commonMin = self.data('common-min') || null; state.__commonMax = self.data('common-max') || null; } else { state.log('incompatible version of Dygraph detected'); state.__commonMin = null; state.__commonMax = null; } } else { // if the user gave a valueRange, respect it state.__commonMin = null; state.__commonMax = null; } return true; }; // ---------------------------------------------------------------------------------------------------------------- // morris NETDATA.morrisInitialize = function(callback) { if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) { // morris requires raphael if(!NETDATA.chartLibraries.raphael.initialized) { if(NETDATA.chartLibraries.raphael.enabled) { NETDATA.raphaelInitialize(function() { NETDATA.morrisInitialize(callback); }); } else { NETDATA.chartLibraries.morris.enabled = false; if(typeof callback === "function") return callback(); } } else { NETDATA._loadCSS(NETDATA.morris_css); $.ajax({ url: NETDATA.morris_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('morris', NETDATA.morris_js); }) .fail(function() { NETDATA.chartLibraries.morris.enabled = false; NETDATA.error(100, NETDATA.morris_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } } else { NETDATA.chartLibraries.morris.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.morrisChartUpdate = function(state, data) { state.morris_instance.setData(data.result.data); return true; }; NETDATA.morrisChartCreate = function(state, data) { state.morris_options = { element: state.element_chart.id, data: data.result.data, xkey: 'time', ykeys: data.dimension_names, labels: data.dimension_names, lineWidth: 2, pointSize: 3, smooth: true, hideHover: 'auto', parseTime: true, continuousLine: false, behaveLikeLine: false }; if(state.chart.chart_type === 'line') state.morris_instance = new Morris.Line(state.morris_options); else if(state.chart.chart_type === 'area') { state.morris_options.behaveLikeLine = true; state.morris_instance = new Morris.Area(state.morris_options); } else // stacked state.morris_instance = new Morris.Area(state.morris_options); return true; }; // ---------------------------------------------------------------------------------------------------------------- // raphael NETDATA.raphaelInitialize = function(callback) { if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) { $.ajax({ url: NETDATA.raphael_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js); }) .fail(function() { NETDATA.chartLibraries.raphael.enabled = false; NETDATA.error(100, NETDATA.raphael_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.raphael.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.raphaelChartUpdate = function(state, data) { $(state.element_chart).raphael(data.result, { width: state.chartWidth(), height: state.chartHeight() }); return false; }; NETDATA.raphaelChartCreate = function(state, data) { $(state.element_chart).raphael(data.result, { width: state.chartWidth(), height: state.chartHeight() }); return false; }; // ---------------------------------------------------------------------------------------------------------------- // C3 NETDATA.c3Initialize = function(callback) { if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) { // C3 requires D3 if(!NETDATA.chartLibraries.d3.initialized) { if(NETDATA.chartLibraries.d3.enabled) { NETDATA.d3Initialize(function() { NETDATA.c3Initialize(callback); }); } else { NETDATA.chartLibraries.c3.enabled = false; if(typeof callback === "function") return callback(); } } else { NETDATA._loadCSS(NETDATA.c3_css); $.ajax({ url: NETDATA.c3_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('c3', NETDATA.c3_js); }) .fail(function() { NETDATA.chartLibraries.c3.enabled = false; NETDATA.error(100, NETDATA.c3_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } } else { NETDATA.chartLibraries.c3.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.c3ChartUpdate = function(state, data) { state.c3_instance.destroy(); return NETDATA.c3ChartCreate(state, data); //state.c3_instance.load({ // rows: data.result, // unload: true //}); //return true; }; NETDATA.c3ChartCreate = function(state, data) { state.element_chart.id = 'c3-' + state.uuid; // console.log('id = ' + state.element_chart.id); state.c3_instance = c3.generate({ bindto: '#' + state.element_chart.id, size: { width: state.chartWidth(), height: state.chartHeight() }, color: { pattern: state.chartColors() }, data: { x: 'time', rows: data.result, type: (state.chart.chart_type === 'line')?'spline':'area-spline' }, axis: { x: { type: 'timeseries', tick: { format: function(x) { return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds()); } } } }, grid: { x: { show: true }, y: { show: true } }, point: { show: false }, line: { connectNull: false }, transition: { duration: 0 }, interaction: { enabled: true } }); // console.log(state.c3_instance); return true; }; // ---------------------------------------------------------------------------------------------------------------- // D3 NETDATA.d3Initialize = function(callback) { if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) { $.ajax({ url: NETDATA.d3_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('d3', NETDATA.d3_js); }) .fail(function() { NETDATA.chartLibraries.d3.enabled = false; NETDATA.error(100, NETDATA.d3_js); }) .always(function() { if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.d3.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.d3ChartUpdate = function(state, data) { void(state); void(data); return false; }; NETDATA.d3ChartCreate = function(state, data) { void(state); void(data); return false; }; // ---------------------------------------------------------------------------------------------------------------- // google charts NETDATA.googleInitialize = function(callback) { if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) { $.ajax({ url: NETDATA.google_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('google', NETDATA.google_js); google.load('visualization', '1.1', { 'packages': ['corechart', 'controls'], 'callback': callback }); }) .fail(function() { NETDATA.chartLibraries.google.enabled = false; NETDATA.error(100, NETDATA.google_js); if(typeof callback === "function") return callback(); }); } else { NETDATA.chartLibraries.google.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.googleChartUpdate = function(state, data) { var datatable = new google.visualization.DataTable(data.result); state.google_instance.draw(datatable, state.google_options); return true; }; NETDATA.googleChartCreate = function(state, data) { var datatable = new google.visualization.DataTable(data.result); state.google_options = { colors: state.chartColors(), // do not set width, height - the chart resizes itself //width: state.chartWidth(), //height: state.chartHeight(), lineWidth: 1, title: state.title, fontSize: 11, hAxis: { // title: "Time of Day", // format:'HH:mm:ss', viewWindowMode: 'maximized', slantedText: false, format:'HH:mm:ss', textStyle: { fontSize: 9 }, gridlines: { color: '#EEE' } }, vAxis: { title: state.units, viewWindowMode: 'pretty', minValue: -0.1, maxValue: 0.1, direction: 1, textStyle: { fontSize: 9 }, gridlines: { color: '#EEE' } }, chartArea: { width: '65%', height: '80%' }, focusTarget: 'category', annotation: { '1': { style: 'line' } }, pointsVisible: 0, titlePosition: 'out', titleTextStyle: { fontSize: 11 }, tooltip: { isHtml: false, ignoreBounds: true, textStyle: { fontSize: 9 } }, curveType: 'function', areaOpacity: 0.3, isStacked: false }; switch(state.chart.chart_type) { case "area": state.google_options.vAxis.viewWindowMode = 'maximized'; state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area; state.google_instance = new google.visualization.AreaChart(state.element_chart); break; case "stacked": state.google_options.isStacked = true; state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked; state.google_options.vAxis.viewWindowMode = 'maximized'; state.google_options.vAxis.minValue = null; state.google_options.vAxis.maxValue = null; state.google_instance = new google.visualization.AreaChart(state.element_chart); break; default: case "line": state.google_options.lineWidth = 2; state.google_instance = new google.visualization.LineChart(state.element_chart); break; } state.google_instance.draw(datatable, state.google_options); return true; }; // ---------------------------------------------------------------------------------------------------------------- NETDATA.easypiechartPercentFromValueMinMax = function(value, min, max) { if(typeof value !== 'number') value = 0; if(typeof min !== 'number') min = 0; if(typeof max !== 'number') max = 0; if(min > value) min = value; if(max < value) max = value; // make sure it is zero based if(min > 0) min = 0; if(max < 0) max = 0; var pcent = 0; if(value >= 0) { if(max !== 0) pcent = Math.round(value * 100 / max); if(pcent === 0) pcent = 0.1; } else { if(min !== 0) pcent = Math.round(-value * 100 / min); if(pcent === 0) pcent = -0.1; } return pcent; }; // ---------------------------------------------------------------------------------------------------------------- // easy-pie-chart NETDATA.easypiechartInitialize = function(callback) { if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) { $.ajax({ url: NETDATA.easypiechart_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js); }) .fail(function() { NETDATA.chartLibraries.easypiechart.enabled = false; NETDATA.error(100, NETDATA.easypiechart_js); }) .always(function() { if(typeof callback === "function") return callback(); }) } else { NETDATA.chartLibraries.easypiechart.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.easypiechartClearSelection = function(state) { if(typeof state.easyPieChartEvent !== 'undefined') { if(state.easyPieChartEvent.timer !== undefined) { clearTimeout(state.easyPieChartEvent.timer); } state.easyPieChartEvent.timer = undefined; } if(state.isAutoRefreshable() === true && state.data !== null) { NETDATA.easypiechartChartUpdate(state, state.data); } else { state.easyPieChartLabel.innerText = state.legendFormatValue(null); state.easyPieChart_instance.update(0); } state.easyPieChart_instance.enableAnimation(); return true; }; NETDATA.easypiechartSetSelection = function(state, t) { if(state.timeIsVisible(t) !== true) return NETDATA.easypiechartClearSelection(state); var slot = state.calculateRowForTime(t); if(slot < 0 || slot >= state.data.result.length) return NETDATA.easypiechartClearSelection(state); if(typeof state.easyPieChartEvent === 'undefined') { state.easyPieChartEvent = { timer: undefined, value: 0, pcent: 0 }; } var value = state.data.result[state.data.result.length - 1 - slot]; var min = (state.easyPieChartMin === null)?NETDATA.commonMin.get(state):state.easyPieChartMin; var max = (state.easyPieChartMax === null)?NETDATA.commonMax.get(state):state.easyPieChartMax; var pcent = NETDATA.easypiechartPercentFromValueMinMax(value, min, max); state.easyPieChartEvent.value = value; state.easyPieChartEvent.pcent = pcent; state.easyPieChartLabel.innerText = state.legendFormatValue(value); if(state.easyPieChartEvent.timer === undefined) { state.easyPieChart_instance.disableAnimation(); state.easyPieChartEvent.timer = setTimeout(function() { state.easyPieChartEvent.timer = undefined; state.easyPieChart_instance.update(state.easyPieChartEvent.pcent); }, NETDATA.options.current.charts_selection_animation_delay); } return true; }; NETDATA.easypiechartChartUpdate = function(state, data) { var value, min, max, pcent; if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshable() === false) { value = null; pcent = 0; } else { value = data.result[0]; min = (state.easyPieChartMin === null)?NETDATA.commonMin.get(state):state.easyPieChartMin; max = (state.easyPieChartMax === null)?NETDATA.commonMax.get(state):state.easyPieChartMax; pcent = NETDATA.easypiechartPercentFromValueMinMax(value, min, max); } state.easyPieChartLabel.innerText = state.legendFormatValue(value); state.easyPieChart_instance.update(pcent); return true; }; NETDATA.easypiechartChartCreate = function(state, data) { var self = $(state.element); var chart = $(state.element_chart); var value = data.result[0]; var min = self.data('easypiechart-min-value') || null; var max = self.data('easypiechart-max-value') || null; var adjust = self.data('easypiechart-adjust') || null; if(min === null) { min = NETDATA.commonMin.get(state); state.easyPieChartMin = null; } else state.easyPieChartMin = min; if(max === null) { max = NETDATA.commonMax.get(state); state.easyPieChartMax = null; } else state.easyPieChartMax = max; var pcent = NETDATA.easypiechartPercentFromValueMinMax(value, min, max); chart.data('data-percent', pcent); var size; switch(adjust) { case 'width': size = state.chartHeight(); break; case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break; case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break; case 'height': default: size = state.chartWidth(); break; } state.element.style.width = size + 'px'; state.element.style.height = size + 'px'; var stroke = Math.floor(size / 22); if(stroke < 3) stroke = 2; var valuefontsize = Math.floor((size * 2 / 3) / 5); var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2); state.easyPieChartLabel = document.createElement('span'); state.easyPieChartLabel.className = 'easyPieChartLabel'; state.easyPieChartLabel.innerText = state.legendFormatValue(value); state.easyPieChartLabel.style.fontSize = valuefontsize + 'px'; state.easyPieChartLabel.style.top = valuetop.toString() + 'px'; state.element_chart.appendChild(state.easyPieChartLabel); var titlefontsize = Math.round(valuefontsize * 1.6 / 3); var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40)); state.easyPieChartTitle = document.createElement('span'); state.easyPieChartTitle.className = 'easyPieChartTitle'; state.easyPieChartTitle.innerText = state.title; state.easyPieChartTitle.style.fontSize = titlefontsize + 'px'; state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px'; state.easyPieChartTitle.style.top = titletop.toString() + 'px'; state.element_chart.appendChild(state.easyPieChartTitle); var unitfontsize = Math.round(titlefontsize * 0.9); var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40)); state.easyPieChartUnits = document.createElement('span'); state.easyPieChartUnits.className = 'easyPieChartUnits'; state.easyPieChartUnits.innerText = state.units; state.easyPieChartUnits.style.fontSize = unitfontsize + 'px'; state.easyPieChartUnits.style.top = unittop.toString() + 'px'; state.element_chart.appendChild(state.easyPieChartUnits); var barColor = self.data('easypiechart-barcolor'); if(typeof barColor === 'undefined' || barColor === null) barColor = state.chartCustomColors()[0]; else { // <div ... data-easypiechart-barcolor="(function(percent){return(percent < 50 ? '#5cb85c' : percent < 85 ? '#f0ad4e' : '#cb3935');})" ...></div> var tmp = eval(barColor); if(typeof tmp === 'function') barColor = tmp; } chart.easyPieChart({ barColor: barColor, trackColor: self.data('easypiechart-trackcolor') || NETDATA.themes.current.easypiechart_track, scaleColor: self.data('easypiechart-scalecolor') || NETDATA.themes.current.easypiechart_scale, scaleLength: self.data('easypiechart-scalelength') || 5, lineCap: self.data('easypiechart-linecap') || 'round', lineWidth: self.data('easypiechart-linewidth') || stroke, trackWidth: self.data('easypiechart-trackwidth') || undefined, size: self.data('easypiechart-size') || size, rotate: self.data('easypiechart-rotate') || 0, animate: self.data('easypiechart-animate') || {duration: 500, enabled: true}, easing: self.data('easypiechart-easing') || undefined }); // when we just re-create the chart // do not animate the first update var animate = true; if(typeof state.easyPieChart_instance !== 'undefined') animate = false; state.easyPieChart_instance = chart.data('easyPieChart'); if(animate === false) state.easyPieChart_instance.disableAnimation(); state.easyPieChart_instance.update(pcent); if(animate === false) state.easyPieChart_instance.enableAnimation(); return true; }; // ---------------------------------------------------------------------------------------------------------------- // gauge.js NETDATA.gaugeInitialize = function(callback) { console.log('------ come into gaugeInitialize -------') if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) { $.ajax({ url: NETDATA.gauge_js, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js); }) .fail(function() { NETDATA.chartLibraries.gauge.enabled = false; NETDATA.error(100, NETDATA.gauge_js); }) .always(function() { if(typeof callback === "function") return callback(); }) } else { NETDATA.chartLibraries.gauge.enabled = false; if(typeof callback === "function") return callback(); } }; NETDATA.gaugeAnimation = function(state, status) { var speed = 32; if(typeof status === 'boolean' && status === false) speed = 1000000000; else if(typeof status === 'number') speed = status; // console.log('gauge speed ' + speed); state.gauge_instance.animationSpeed = speed; state.___gaugeOld__.speed = speed; }; NETDATA.gaugeSet = function(state, value, min, max) { if(typeof value !== 'number') value = 0; if(typeof min !== 'number') min = 0; if(typeof max !== 'number') max = 0; if(value > max) max = value; if(value < min) min = value; if(min > max) { var t = min; min = max; max = t; } else if(min === max) max = min + 1; // gauge.js has an issue if the needle // is smaller than min or larger than max // when we set the new values // the needle will go crazy // to prevent it, we always feed it // with a percentage, so that the needle // is always between min and max var pcent = (value - min) * 100 / (max - min); // bug fix for gauge.js 1.3.1 // if the value is the absolute min or max, the chart is broken if(pcent < 0.001) pcent = 0.001; if(pcent > 99.999) pcent = 99.999; state.gauge_instance.set(pcent); // console.log('gauge set ' + pcent + ', value ' + value + ', min ' + min + ', max ' + max); state.___gaugeOld__.value = value; state.___gaugeOld__.min = min; state.___gaugeOld__.max = max; }; NETDATA.gaugeSetLabels = function(state, value, min, max) { if(state.___gaugeOld__.valueLabel !== value) { state.___gaugeOld__.valueLabel = value; state.gaugeChartLabel.innerText = state.legendFormatValue(value); } if(state.___gaugeOld__.minLabel !== min) { state.___gaugeOld__.minLabel = min; state.gaugeChartMin.innerText = state.legendFormatValue(min); } if(state.___gaugeOld__.maxLabel !== max) { state.___gaugeOld__.maxLabel = max; state.gaugeChartMax.innerText = state.legendFormatValue(max); } }; NETDATA.gaugeClearSelection = function(state) { if(typeof state.gaugeEvent !== 'undefined') { if(state.gaugeEvent.timer !== undefined) { clearTimeout(state.gaugeEvent.timer); } state.gaugeEvent.timer = undefined; } if(state.isAutoRefreshable() === true && state.data !== null) { NETDATA.gaugeChartUpdate(state, state.data); } else { NETDATA.gaugeAnimation(state, false); NETDATA.gaugeSet(state, null, null, null); NETDATA.gaugeSetLabels(state, null, null, null); } NETDATA.gaugeAnimation(state, true); return true; }; NETDATA.gaugeSetSelection = function(state, t) { if(state.timeIsVisible(t) !== true) return NETDATA.gaugeClearSelection(state); var slot = state.calculateRowForTime(t); if(slot < 0 || slot >= state.data.result.length) return NETDATA.gaugeClearSelection(state); if(typeof state.gaugeEvent === 'undefined') { state.gaugeEvent = { timer: undefined, value: 0, min: 0, max: 0 }; } var value = state.data.result[state.data.result.length - 1 - slot]; var min = (state.gaugeMin === null)?NETDATA.commonMin.get(state):state.gaugeMin; var max = (state.gaugeMax === null)?NETDATA.commonMax.get(state):state.gaugeMax; // make sure it is zero based if(min > 0) min = 0; if(max < 0) max = 0; state.gaugeEvent.value = value; state.gaugeEvent.min = min; state.gaugeEvent.max = max; NETDATA.gaugeSetLabels(state, value, min, max); if(state.gaugeEvent.timer === undefined) { NETDATA.gaugeAnimation(state, false); state.gaugeEvent.timer = setTimeout(function() { state.gaugeEvent.timer = undefined; NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max); }, NETDATA.options.current.charts_selection_animation_delay); } return true; }; NETDATA.gaugeChartUpdate = function(state, data) { var value, min, max; if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshable() === false) { value = 0; min = 0; max = 1; NETDATA.gaugeSetLabels(state, null, null, null); } else { value = data.result[0]; min = (state.gaugeMin === null)?NETDATA.commonMin.get(state):state.gaugeMin; max = (state.gaugeMax === null)?NETDATA.commonMax.get(state):state.gaugeMax; if(value < min) min = value; if(value > max) max = value; // make sure it is zero based if(min > 0) min = 0; if(max < 0) max = 0; NETDATA.gaugeSetLabels(state, value, min, max); } NETDATA.gaugeSet(state, value, min, max); return true; }; NETDATA.gaugeChartCreate = function(state, data) { var self = $(state.element); // var chart = $(state.element_chart); var value = data.result[0]; var min = self.data('gauge-min-value') || null; var max = self.data('gauge-max-value') || null; var adjust = self.data('gauge-adjust') || null; var pointerColor = self.data('gauge-pointer-color') || NETDATA.themes.current.gauge_pointer; var strokeColor = self.data('gauge-stroke-color') || NETDATA.themes.current.gauge_stroke; var startColor = self.data('gauge-start-color') || state.chartCustomColors()[0]; var stopColor = self.data('gauge-stop-color') || void 0; var generateGradient = self.data('gauge-generate-gradient') || false; if(min === null) { min = NETDATA.commonMin.get(state); state.gaugeMin = null; } else state.gaugeMin = min; if(max === null) { max = NETDATA.commonMax.get(state); state.gaugeMax = null; } else state.gaugeMax = max; // make sure it is zero based if(min > 0) min = 0; if(max < 0) max = 0; var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5; //switch(adjust) { // case 'width': width = height * ratio; break; // case 'height': // default: height = width / ratio; break; //} //state.element.style.width = width.toString() + 'px'; //state.element.style.height = height.toString() + 'px'; var lum_d = 0.05; var options = { lines: 12, // The number of lines to draw angle: 0.15, // The span of the gauge arc lineWidth: 0.50, // The line thickness radiusScale: 0.85, // Relative radius pointer: { length: 0.8, // 0.9 The radius of the inner circle strokeWidth: 0.035, // The rotation offset color: pointerColor // Fill color }, limitMax: true, // If false, the max value of the gauge will be updated if value surpass max limitMin: true, // If true, the min value of the gauge will be fixed unless you set it manually colorStart: startColor, // Colors colorStop: stopColor, // just experiment with them strokeColor: strokeColor, // to see which ones work best for you generateGradient: (generateGradient === true), gradientType: 0, highDpiSupport: true // High resolution support }; if (generateGradient.constructor === Array) { // example options: // data-gauge-generate-gradient="[0, 50, 100]" // data-gauge-gradient-percent-color-0="#FFFFFF" // data-gauge-gradient-percent-color-50="#999900" // data-gauge-gradient-percent-color-100="#000000" options.percentColors = []; var len = generateGradient.length; while(len--) { var pcent = generateGradient[len]; var color = self.attr('data-gauge-gradient-percent-color-' + pcent.toString()) || false; if(color !== false) { var a = []; a[0] = pcent / 100; a[1] = color; options.percentColors.unshift(a); } } if(options.percentColors.length === 0) delete options.percentColors; } else if(generateGradient === false && NETDATA.themes.current.gauge_gradient === true) { //noinspection PointlessArithmeticExpressionJS options.percentColors = [ [0.0, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 0))], [0.1, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 1))], [0.2, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 2))], [0.3, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 3))], [0.4, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 4))], [0.5, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 5))], [0.6, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 6))], [0.7, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 7))], [0.8, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 8))], [0.9, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 9))], [1.0, NETDATA.colorLuminance(startColor, 0.0)]]; } state.gauge_canvas = document.createElement('canvas'); state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas'; state.gauge_canvas.className = 'gaugeChart'; state.gauge_canvas.width = width; state.gauge_canvas.height = height; state.element_chart.appendChild(state.gauge_canvas); var valuefontsize = Math.floor(height / 6); var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2); state.gaugeChartLabel = document.createElement('span'); state.gaugeChartLabel.className = 'gaugeChartLabel'; state.gaugeChartLabel.style.fontSize = valuefontsize + 'px'; state.gaugeChartLabel.style.top = valuetop.toString() + 'px'; state.element_chart.appendChild(state.gaugeChartLabel); var titlefontsize = Math.round(valuefontsize / 2); var titletop = 0; state.gaugeChartTitle = document.createElement('span'); state.gaugeChartTitle.className = 'gaugeChartTitle'; state.gaugeChartTitle.innerText = state.title; state.gaugeChartTitle.style.fontSize = titlefontsize + 'px'; state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px'; state.gaugeChartTitle.style.top = titletop.toString() + 'px'; state.element_chart.appendChild(state.gaugeChartTitle); var unitfontsize = Math.round(titlefontsize * 0.9); state.gaugeChartUnits = document.createElement('span'); state.gaugeChartUnits.className = 'gaugeChartUnits'; state.gaugeChartUnits.innerText = state.units; state.gaugeChartUnits.style.fontSize = unitfontsize + 'px'; state.element_chart.appendChild(state.gaugeChartUnits); state.gaugeChartMin = document.createElement('span'); state.gaugeChartMin.className = 'gaugeChartMin'; state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px'; state.element_chart.appendChild(state.gaugeChartMin); state.gaugeChartMax = document.createElement('span'); state.gaugeChartMax.className = 'gaugeChartMax'; state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px'; state.element_chart.appendChild(state.gaugeChartMax); // when we just re-create the chart // do not animate the first update var animate = true; if(typeof state.gauge_instance !== 'undefined') animate = false; state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge! state.___gaugeOld__ = { value: value, min: min, max: max, valueLabel: null, minLabel: null, maxLabel: null }; // we will always feed a percentage state.gauge_instance.minValue = 0; state.gauge_instance.maxValue = 100; NETDATA.gaugeAnimation(state, animate); NETDATA.gaugeSet(state, value, min, max); NETDATA.gaugeSetLabels(state, value, min, max); NETDATA.gaugeAnimation(state, true); return true; }; // ---------------------------------------------------------------------------------------------------------------- // Charts Libraries Registration NETDATA.chartLibraries = { "dygraph": { initialize: NETDATA.dygraphInitialize, create: NETDATA.dygraphChartCreate, update: NETDATA.dygraphChartUpdate, resize: function(state) { if(typeof state.dygraph_instance.resize === 'function') state.dygraph_instance.resize(); }, setSelection: NETDATA.dygraphSetSelection, clearSelection: NETDATA.dygraphClearSelection, toolboxPanAndZoom: NETDATA.dygraphToolboxPanAndZoom, initialized: false, enabled: true, format: function(state) { void(state); return 'json'; }, options: function(state) { void(state); return 'ms|flip'; }, legend: function(state) { return (this.isSparkline(state) === false)?'right-side':null; }, autoresize: function(state) { void(state); return true; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return true; }, pixels_per_point: function(state) { return (this.isSparkline(state) === false)?3:2; }, isSparkline: function(state) { if(typeof state.dygraph_sparkline === 'undefined') { var t = $(state.element).data('dygraph-theme'); state.dygraph_sparkline = (t === 'sparkline'); } return state.dygraph_sparkline; } }, "sparkline": { initialize: NETDATA.sparklineInitialize, create: NETDATA.sparklineChartCreate, update: NETDATA.sparklineChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'array'; }, options: function(state) { void(state); return 'flip|abs'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 3; } }, "peity": { initialize: NETDATA.peityInitialize, create: NETDATA.peityChartCreate, update: NETDATA.peityChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'ssvcomma'; }, options: function(state) { void(state); return 'null2zero|flip|abs'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 3; } }, "morris": { initialize: NETDATA.morrisInitialize, create: NETDATA.morrisChartCreate, update: NETDATA.morrisChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'json'; }, options: function(state) { void(state); return 'objectrows|ms'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 50; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 15; } }, "google": { initialize: NETDATA.googleInitialize, create: NETDATA.googleChartCreate, update: NETDATA.googleChartUpdate, resize: null, setSelection: undefined, //function(state, t) { void(state); return true; }, clearSelection: undefined, //function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'datatable'; }, options: function(state) { void(state); return ''; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 300; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 4; } }, "raphael": { initialize: NETDATA.raphaelInitialize, create: NETDATA.raphaelChartCreate, update: NETDATA.raphaelChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'json'; }, options: function(state) { void(state); return ''; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 3; } }, "c3": { initialize: NETDATA.c3Initialize, create: NETDATA.c3ChartCreate, update: NETDATA.c3ChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'csvjsonarray'; }, options: function(state) { void(state); return 'milliseconds'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 15; } }, "d3": { initialize: NETDATA.d3Initialize, create: NETDATA.d3ChartCreate, update: NETDATA.d3ChartUpdate, resize: null, setSelection: undefined, // function(state, t) { void(state); return true; }, clearSelection: undefined, // function(state) { void(state); return true; }, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'json'; }, options: function(state) { void(state); return ''; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return false; }, pixels_per_point: function(state) { void(state); return 3; } }, "easypiechart": { initialize: NETDATA.easypiechartInitialize, create: NETDATA.easypiechartChartCreate, update: NETDATA.easypiechartChartUpdate, resize: null, setSelection: NETDATA.easypiechartSetSelection, clearSelection: NETDATA.easypiechartClearSelection, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'array'; }, options: function(state) { void(state); return 'absolute'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return true; }, pixels_per_point: function(state) { void(state); return 3; }, aspect_ratio: 100 }, "gauge": { initialize: NETDATA.gaugeInitialize, create: NETDATA.gaugeChartCreate, update: NETDATA.gaugeChartUpdate, resize: null, setSelection: NETDATA.gaugeSetSelection, clearSelection: NETDATA.gaugeClearSelection, toolboxPanAndZoom: null, initialized: false, enabled: true, format: function(state) { void(state); return 'array'; }, options: function(state) { void(state); return 'absolute'; }, legend: function(state) { void(state); return null; }, autoresize: function(state) { void(state); return false; }, max_updates_to_recreate: function(state) { void(state); return 5000; }, track_colors: function(state) { void(state); return true; }, pixels_per_point: function(state) { void(state); return 3; }, aspect_ratio: 70 } }; NETDATA.registerChartLibrary = function(library, url) { if(NETDATA.options.debug.libraries === true) console.log("registering chart library: " + library); NETDATA.chartLibraries[library].url = url; NETDATA.chartLibraries[library].initialized = true; NETDATA.chartLibraries[library].enabled = true; }; // ---------------------------------------------------------------------------------------------------------------- // Load required JS libraries and CSS NETDATA.requiredJs = [ { url: NETDATA.serverDefault + 'lib/bootstrap-3.3.7.min.js', async: false, isAlreadyLoaded: function() { // check if bootstrap is loaded if(typeof $().emulateTransitionEnd === 'function') return true; else { return (typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap === true); } } }, { url: NETDATA.serverDefault + 'lib/perfect-scrollbar-0.6.15.min.js', isAlreadyLoaded: function() { return false; } } ]; NETDATA.requiredCSS = [ { url: NETDATA.themes.current.bootstrap_css, isAlreadyLoaded: function() { return (typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap === true); } }, { url: NETDATA.serverDefault + 'css/font-awesome.min.css?v4.7.0', isAlreadyLoaded: function() { return false; } }, { url: NETDATA.themes.current.dashboard_css, isAlreadyLoaded: function() { return false; } } ]; NETDATA.loadedRequiredJs = 0; NETDATA.loadRequiredJs = function(index, callback) { console.log('============NETDATA.requiredJs[%d] with length=%d', index, NETDATA.requiredJs.length) console.dir( NETDATA.requiredJs[index] ) if(index >= NETDATA.requiredJs.length) { if(typeof callback === 'function') return callback(); return; } if(NETDATA.requiredJs[index].isAlreadyLoaded()) { console.log(' come into isAlreadyLoaded()') NETDATA.loadedRequiredJs++; NETDATA.loadRequiredJs(++index, callback); return; } let currentURL = NETDATA.requiredJs[index].url if(NETDATA.options.debug.main_loop === true) console.log('xxxxxx loading ' + currentURL); var async = true; if(typeof NETDATA.requiredJs[index].async !== 'undefined' && NETDATA.requiredJs[index].async === false) async = false; $.ajax({ url: currentURL, cache: true, dataType: "script", xhrFields: { withCredentials: true } // required for the cookie }) .done(function() { console.log('============NETDATA.requiredJs[%d] url= %s', index, currentURL) if(NETDATA.options.debug.main_loop === true) console.log('loaded ' + currentURL); }) .fail(function() { alert('Cannot load required JS library: ' + currentURL); }) .always(function() { NETDATA.loadedRequiredJs++; if(async === false) NETDATA.loadRequiredJs(++index, callback); }); if(async === true) NETDATA.loadRequiredJs(++index, callback); }; NETDATA.loadRequiredCSS = function(index) { if(index >= NETDATA.requiredCSS.length) return; if(NETDATA.requiredCSS[index].isAlreadyLoaded()) { NETDATA.loadRequiredCSS(++index); return; } if(NETDATA.options.debug.main_loop === true) console.log('loading ' + NETDATA.requiredCSS[index].url); NETDATA._loadCSS(NETDATA.requiredCSS[index].url); NETDATA.loadRequiredCSS(++index); }; // ---------------------------------------------------------------------------------------------------------------- // Registry of netdata hosts NETDATA.alarms = { onclick: null, // the callback to handle the click - it will be called with the alarm log entry chart_div_offset: -50, // give that space above the chart when scrolling to it chart_div_id_prefix: 'chart_', // the chart DIV IDs have this prefix (they should be NETDATA.name2id(chart.id)) chart_div_animation_duration: 0,// the duration of the animation while scrolling to a chart ms_penalty: 0, // the time penalty of the next alarm ms_between_notifications: 500, // firefox moves the alarms off-screen (above, outside the top of the screen) // if alarms are shown faster than: one per 500ms notifications: false, // when true, the browser supports notifications (may not be granted though) last_notification_id: 0, // the id of the last alarm_log we have raised an alarm for first_notification_id: 0, // the id of the first alarm_log entry for this session // this is used to prevent CLEAR notifications for past events // notifications_shown: [], server: null, // the server to connect to for fetching alarms current: null, // the list of raised alarms - updated in the background callback: null, // a callback function to call every time the list of raised alarms is refreshed notify: function(entry) { // console.log('alarm ' + entry.unique_id); if(entry.updated === true) { // console.log('alarm ' + entry.unique_id + ' has been updated by another alarm'); return; } var value_string = entry.value_string; if(NETDATA.alarms.current !== null) { // get the current value_string var t = NETDATA.alarms.current.alarms[entry.chart + '.' + entry.name]; if(typeof t !== 'undefined' && entry.status === t.status && typeof t.value_string !== 'undefined') value_string = t.value_string; } var name = entry.name.replace(/_/g, ' '); var status = entry.status.toLowerCase(); var title = name + ' = ' + value_string.toString(); var tag = entry.alarm_id; var icon = 'images/seo-performance-128.png'; var interaction = false; var data = entry; var show = true; // console.log('alarm ' + entry.unique_id + ' ' + entry.chart + '.' + entry.name + ' is ' + entry.status); switch(entry.status) { case 'REMOVED': show = false; break; case 'UNDEFINED': return; case 'UNINITIALIZED': return; case 'CLEAR': if(entry.unique_id < NETDATA.alarms.first_notification_id) { // console.log('alarm ' + entry.unique_id + ' is not current'); return; } if(entry.old_status === 'UNINITIALIZED' || entry.old_status === 'UNDEFINED') { // console.log('alarm' + entry.unique_id + ' switch to CLEAR from ' + entry.old_status); return; } if(entry.no_clear_notification === true) { // console.log('alarm' + entry.unique_id + ' is CLEAR but has no_clear_notification flag'); return; } title = name + ' back to normal (' + value_string.toString() + ')'; icon = 'images/check-mark-2-128-green.png'; interaction = false; break; case 'WARNING': if(entry.old_status === 'CRITICAL') status = 'demoted to ' + entry.status.toLowerCase(); icon = 'images/alert-128-orange.png'; interaction = false; break; case 'CRITICAL': if(entry.old_status === 'WARNING') status = 'escalated to ' + entry.status.toLowerCase(); icon = 'images/alert-128-red.png'; interaction = true; break; default: console.log('invalid alarm status ' + entry.status); return; } /* // cleanup old notifications with the same alarm_id as this one // FIXME: it does not seem to work on any web browser! var len = NETDATA.alarms.notifications_shown.length; while(len--) { var n = NETDATA.alarms.notifications_shown[len]; if(n.data.alarm_id === entry.alarm_id) { console.log('removing old alarm ' + n.data.unique_id); // close the notification n.close.bind(n); // remove it from the array NETDATA.alarms.notifications_shown.splice(len, 1); len = NETDATA.alarms.notifications_shown.length; } } */ if(show === true) { setTimeout(function() { // show this notification // console.log('new notification: ' + title); var n = new Notification(title, { body: entry.hostname + ' - ' + entry.chart + ' (' + entry.family + ') - ' + status + ': ' + entry.info, tag: tag, requireInteraction: interaction, icon: NETDATA.serverDefault + icon, data: data }); n.onclick = function(event) { event.preventDefault(); NETDATA.alarms.onclick(event.target.data); }; // console.log(n); // NETDATA.alarms.notifications_shown.push(n); // console.log(entry); }, NETDATA.alarms.ms_penalty); NETDATA.alarms.ms_penalty += NETDATA.alarms.ms_between_notifications; } }, scrollToChart: function(chart_id) { if(typeof chart_id === 'string') { var offset = $('#' + NETDATA.alarms.chart_div_id_prefix + NETDATA.name2id(chart_id)).offset(); if(typeof offset !== 'undefined') { $('html, body').animate({ scrollTop: offset.top + NETDATA.alarms.chart_div_offset }, NETDATA.alarms.chart_div_animation_duration); return true; } } return false; }, scrollToAlarm: function(alarm) { if(typeof alarm === 'object') { var ret = NETDATA.alarms.scrollToChart(alarm.chart); if(ret === true && NETDATA.options.page_is_visible === false) window.focus(); // alert('netdata dashboard will now scroll to chart: ' + alarm.chart + '\n\nThis alarm opened to bring the browser window in front of the screen. Click on the dashboard to prevent it from appearing again.'); } }, notifyAll: function() { // console.log('FETCHING ALARM LOG'); NETDATA.alarms.get_log(NETDATA.alarms.last_notification_id, function(data) { // console.log('ALARM LOG FETCHED'); if(data === null || typeof data !== 'object') { console.log('invalid alarms log response'); return; } if(data.length === 0) { console.log('received empty alarm log'); return; } // console.log('received alarm log of ' + data.length + ' entries, from ' + data[data.length - 1].unique_id.toString() + ' to ' + data[0].unique_id.toString()); data.sort(function(a, b) { if(a.unique_id > b.unique_id) return -1; if(a.unique_id < b.unique_id) return 1; return 0; }); NETDATA.alarms.ms_penalty = 0; var len = data.length; while(len--) { if(data[len].unique_id > NETDATA.alarms.last_notification_id) { NETDATA.alarms.notify(data[len]); } //else // console.log('ignoring alarm (older) with id ' + data[len].unique_id.toString()); } NETDATA.alarms.last_notification_id = data[0].unique_id; NETDATA.localStorageSet('last_notification_id', NETDATA.alarms.last_notification_id, null); // console.log('last notification id = ' + NETDATA.alarms.last_notification_id); }) }, check_notifications: function() { // returns true if we should fire 1+ notifications if(NETDATA.alarms.notifications !== true) { // console.log('notifications not available'); return false; } if(Notification.permission !== 'granted') { // console.log('notifications not granted'); return false; } if(typeof NETDATA.alarms.current !== 'undefined' && typeof NETDATA.alarms.current.alarms === 'object') { // console.log('can do alarms: old id = ' + NETDATA.alarms.last_notification_id + ' new id = ' + NETDATA.alarms.current.latest_alarm_log_unique_id); if(NETDATA.alarms.current.latest_alarm_log_unique_id > NETDATA.alarms.last_notification_id) { // console.log('new alarms detected'); return true; } //else console.log('no new alarms'); } // else console.log('cannot process alarms'); return false; }, get: function(what, callback) { $.ajax({ url: NETDATA.alarms.server + '/api/v1/alarms?' + what.toString(), async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(NETDATA.alarms.first_notification_id === 0 && typeof data.latest_alarm_log_unique_id === 'number') NETDATA.alarms.first_notification_id = data.latest_alarm_log_unique_id; if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(415, NETDATA.alarms.server); if(typeof callback === 'function') return callback(null); }); }, update_forever: function() { NETDATA.alarms.get('active', function(data) { if(data !== null) { NETDATA.alarms.current = data; if(NETDATA.alarms.check_notifications() === true) { NETDATA.alarms.notifyAll(); } if (typeof NETDATA.alarms.callback === 'function') { NETDATA.alarms.callback(data); } // Health monitoring is disabled on this netdata if(data.status === false) return; } setTimeout(NETDATA.alarms.update_forever, 10000); }); }, get_log: function(last_id, callback) { // console.log('fetching all log after ' + last_id.toString()); $.ajax({ url: NETDATA.alarms.server + '/api/v1/alarm_log?after=' + last_id.toString(), async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(416, NETDATA.alarms.server); if(typeof callback === 'function') return callback(null); }); }, init: function() { NETDATA.alarms.server = NETDATA.fixHost(NETDATA.serverDefault); console.log('Rico trace in alarms.init:', NETDATA.alarms.server) NETDATA.alarms.last_notification_id = NETDATA.localStorageGet('last_notification_id', NETDATA.alarms.last_notification_id, null); if(NETDATA.alarms.onclick === null) NETDATA.alarms.onclick = NETDATA.alarms.scrollToAlarm; if(netdataShowAlarms === true) { NETDATA.alarms.update_forever(); if('Notification' in window) { // console.log('notifications available'); NETDATA.alarms.notifications = true; if(Notification.permission === 'default') Notification.requestPermission(); } } } }; // ---------------------------------------------------------------------------------------------------------------- // Registry of netdata hosts NETDATA.registry = { server: null, // the netdata registry server person_guid: null, // the unique ID of this browser / user machine_guid: null, // the unique ID the netdata server that served dashboard.js hostname: 'unknown', // the hostname of the netdata server that served dashboard.js machines: null, // the user's other URLs machines_array: null, // the user's other URLs in an array person_urls: null, parsePersonUrls: function(person_urls) { // console.log(person_urls); NETDATA.registry.person_urls = person_urls; if(person_urls) { NETDATA.registry.machines = {}; NETDATA.registry.machines_array = []; var apu = person_urls; var i = apu.length; while(i--) { if(typeof NETDATA.registry.machines[apu[i][0]] === 'undefined') { // console.log('adding: ' + apu[i][4] + ', ' + ((now - apu[i][2]) / 1000).toString()); var obj = { guid: apu[i][0], url: apu[i][1], last_t: apu[i][2], accesses: apu[i][3], name: apu[i][4], alternate_urls: [] }; obj.alternate_urls.push(apu[i][1]); NETDATA.registry.machines[apu[i][0]] = obj; NETDATA.registry.machines_array.push(obj); } else { // console.log('appending: ' + apu[i][4] + ', ' + ((now - apu[i][2]) / 1000).toString()); var pu = NETDATA.registry.machines[apu[i][0]]; if(pu.last_t < apu[i][2]) { pu.url = apu[i][1]; pu.last_t = apu[i][2]; pu.name = apu[i][4]; } pu.accesses += apu[i][3]; pu.alternate_urls.push(apu[i][1]); } } } if(typeof netdataRegistryCallback === 'function') netdataRegistryCallback(NETDATA.registry.machines_array); }, init: function() { if(netdataRegistry !== true) return; NETDATA.registry.hello(NETDATA.serverDefault, function(data) { if(data) { NETDATA.registry.server = data.registry; NETDATA.registry.machine_guid = data.machine_guid; NETDATA.registry.hostname = data.hostname; NETDATA.registry.access(2, function (person_urls) { NETDATA.registry.parsePersonUrls(person_urls); }); } }); }, hello: function(host, callback) { host = this.host; //NETDATA.fixHost(host); // send HELLO to a netdata server: // 1. verifies the server is reachable // 2. responds with the registry URL, the machine GUID of this netdata server and its hostname $.ajax({ url: host + '/api/v1/registry?action=hello', async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(408, host + ' response: ' + JSON.stringify(data)); data = null; } if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(407, host); if(typeof callback === 'function') return callback(null); }); }, access: function(max_redirects, callback) { // send ACCESS to a netdata registry: // 1. it lets it know we are accessing a netdata server (its machine GUID and its URL) // 2. it responds with a list of netdata servers we know // the registry identifies us using a cookie it sets the first time we access it // the registry may respond with a redirect URL to send us to another registry $.ajax({ url: NETDATA.registry.server + '/api/v1/registry?action=access&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault), // + '&visible_url=' + encodeURIComponent(document.location), async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { var redirect = null; if(typeof data.registry === 'string') redirect = data.registry; if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(409, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data)); data = null; } if(data === null) { if(redirect !== null && max_redirects > 0) { NETDATA.registry.server = redirect; NETDATA.registry.access(max_redirects - 1, callback); } else { if(typeof callback === 'function') return callback(null); } } else { if(typeof data.person_guid === 'string') NETDATA.registry.person_guid = data.person_guid; if(typeof callback === 'function') return callback(data.urls); } }) .fail(function() { NETDATA.error(410, NETDATA.registry.server); if(typeof callback === 'function') return callback(null); }); }, delete: function(delete_url, callback) { // send DELETE to a netdata registry: $.ajax({ url: NETDATA.registry.server + '/api/v1/registry?action=delete&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&delete_url=' + encodeURIComponent(delete_url), async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(411, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data)); data = null; } if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(412, NETDATA.registry.server); if(typeof callback === 'function') return callback(null); }); }, search: function(machine_guid, callback) { // SEARCH for the URLs of a machine: $.ajax({ url: NETDATA.registry.server + '/api/v1/registry?action=search&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&for=' + machine_guid, async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(417, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data)); data = null; } if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(418, NETDATA.registry.server); if(typeof callback === 'function') return callback(null); }); }, switch: function(new_person_guid, callback) { // impersonate $.ajax({ url: NETDATA.registry.server + '/api/v1/registry?action=switch&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&to=' + new_person_guid, async: true, cache: false, headers: { 'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache' }, xhrFields: { withCredentials: true } // required for the cookie }) .done(function(data) { if(typeof data.status !== 'string' || data.status !== 'ok') { NETDATA.error(413, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data)); data = null; } if(typeof callback === 'function') return callback(data); }) .fail(function() { NETDATA.error(414, NETDATA.registry.server); if(typeof callback === 'function') return callback(null); }); } }; // ---------------------------------------------------------------------------------------------------------------- // Boot it! if(typeof netdataPrepCallback === 'function') netdataPrepCallback(); NETDATA.errorReset(); NETDATA.loadRequiredCSS(0); NETDATA._loadjQuery(function() { NETDATA.loadRequiredJs(0, function() { if(typeof $().emulateTransitionEnd !== 'function') { // bootstrap is not available NETDATA.options.current.show_help = false; } if(typeof netdataDontStart === 'undefined' || !netdataDontStart) { if(NETDATA.options.debug.main_loop === true) console.log('starting chart refresh thread'); NETDATA.start(); } }); }); })(window, document);
41.698545
540
0.510708
3b5fd608e73533894b8fba1fa43377f301b56b93
2,875
js
JavaScript
api_ref_doxygen/html/search/functions_7.js
abakobo/Box2D
c33d5a982fef9c391f01d0155e272f936faaa2f5
[ "Zlib" ]
null
null
null
api_ref_doxygen/html/search/functions_7.js
abakobo/Box2D
c33d5a982fef9c391f01d0155e272f936faaa2f5
[ "Zlib" ]
null
null
null
api_ref_doxygen/html/search/functions_7.js
abakobo/Box2D
c33d5a982fef9c391f01d0155e272f936faaa2f5
[ "Zlib" ]
null
null
null
var searchData= [ ['initialize',['Initialize',['../structb2_world_manifold.html#a896dd7e7d4d6f6a5bc69e19fbd6871bd',1,'b2WorldManifold::Initialize()'],['../structb2_distance_joint_def.html#a99788a534638cc28cd1e44e0036503f0',1,'b2DistanceJointDef::Initialize()'],['../structb2_friction_joint_def.html#aee104f2aeb34dec4e17e3c52a98f7915',1,'b2FrictionJointDef::Initialize()'],['../structb2_motor_joint_def.html#a90eb924b6e04da8d75d9cefad0655960',1,'b2MotorJointDef::Initialize()'],['../structb2_prismatic_joint_def.html#ae60043bc22b077e8c59ab248dc34652f',1,'b2PrismaticJointDef::Initialize()'],['../structb2_pulley_joint_def.html#abef614a93562b82aa3b5f8cac17d1ce8',1,'b2PulleyJointDef::Initialize()'],['../structb2_revolute_joint_def.html#a6401b2a663533415d032a525e4fa2806',1,'b2RevoluteJointDef::Initialize()'],['../structb2_weld_joint_def.html#a9f6592c2a7eba6ce6e07e40c4e82aab5',1,'b2WeldJointDef::Initialize()'],['../structb2_wheel_joint_def.html#af26887092d36c3cd03898401a38783e2',1,'b2WheelJointDef::Initialize()']]], ['isactive',['IsActive',['../classb2_body.html#a825f37f457d3674ace96e2b8a9b4cae6',1,'b2Body::IsActive()'],['../classb2_joint.html#ae9cfbd158216c9855c2f018ff3c9c922',1,'b2Joint::IsActive()']]], ['isawake',['IsAwake',['../classb2_body.html#a697f708427cdf7d31a626e80e694682c',1,'b2Body']]], ['isbullet',['IsBullet',['../classb2_body.html#ad99db1c7a19e8de333ff7f65b0b953f4',1,'b2Body']]], ['isenabled',['IsEnabled',['../classb2_contact.html#af81964f40dce556efbc83ae760f166b0',1,'b2Contact']]], ['isfixedrotation',['IsFixedRotation',['../classb2_body.html#a0920b7a770f7c876cf6d149e227036b5',1,'b2Body']]], ['islimitenabled',['IsLimitEnabled',['../classb2_prismatic_joint.html#a22e2442a17832f718447c63c9c6263c8',1,'b2PrismaticJoint::IsLimitEnabled()'],['../classb2_revolute_joint.html#a84ff9c4f82b3e7d27a4390164f81f3ab',1,'b2RevoluteJoint::IsLimitEnabled()']]], ['islocked',['IsLocked',['../classb2_world.html#a71ca09a3082945a7e77f3f39fb021237',1,'b2World']]], ['ismotorenabled',['IsMotorEnabled',['../classb2_prismatic_joint.html#a06492dabf33439efdebceb29899c7fc9',1,'b2PrismaticJoint::IsMotorEnabled()'],['../classb2_revolute_joint.html#a37d5744e89991ebe01b974c4d15a21b5',1,'b2RevoluteJoint::IsMotorEnabled()'],['../classb2_wheel_joint.html#aef7948a18ec2784397a1d3745824cd78',1,'b2WheelJoint::IsMotorEnabled()']]], ['issensor',['IsSensor',['../classb2_fixture.html#aedd23d27ff7ce2d53b6c5b7a878a35d3',1,'b2Fixture']]], ['issleepingallowed',['IsSleepingAllowed',['../classb2_body.html#ac47251de3a8c0ccff620be7bd5ae696a',1,'b2Body']]], ['istouching',['IsTouching',['../classb2_contact.html#a681346f93e2a27403383775a752c06a0',1,'b2Contact']]], ['isvalid',['IsValid',['../structb2_a_a_b_b.html#a70bb45c086fcc2d7ee8694deb386070e',1,'b2AABB::IsValid()'],['../structb2_vec2.html#abad59bf9a0269f02cda9dc919592c0ee',1,'b2Vec2::IsValid()']]] ];
169.117647
1,002
0.78713
3b5ff2644c951308a33b3607d25a7d3e9a19d96f
29,998
js
JavaScript
asset/lodash/dist/lodash.fp.js
majac6/majac-angular1-tutorial
cfc691b60943743ef07216153dfb0a260d0c1e5c
[ "MIT" ]
78
2016-06-23T13:11:22.000Z
2022-03-12T19:32:11.000Z
asset/lodash/dist/lodash.fp.js
majac6/majac-angular1-tutorial
cfc691b60943743ef07216153dfb0a260d0c1e5c
[ "MIT" ]
18
2016-09-23T12:48:57.000Z
2021-11-21T08:17:38.000Z
asset/lodash/dist/lodash.fp.js
majac6/majac-angular1-tutorial
cfc691b60943743ef07216153dfb0a260d0c1e5c
[ "MIT" ]
35
2016-06-20T17:27:03.000Z
2021-11-17T13:04:14.000Z
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["fp"] = factory(); else root["fp"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var baseConvert = __webpack_require__(1); /** * Converts `lodash` to an immutable auto-curried iteratee-first data-last * version with conversion `options` applied. * * @param {Function} lodash The lodash function to convert. * @param {Object} [options] The options object. See `baseConvert` for more details. * @returns {Function} Returns the converted `lodash`. */ function browserConvert(lodash, options) { return baseConvert(lodash, lodash, options); } if (typeof _ == 'function' && typeof _.runInContext == 'function') { _ = browserConvert(_.runInContext()); } module.exports = browserConvert; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var mapping = __webpack_require__(2), fallbackHolder = __webpack_require__(3); /** Built-in value reference. */ var push = Array.prototype.push; /** * Creates a function, with an arity of `n`, that invokes `func` with the * arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} n The arity of the new function. * @returns {Function} Returns the new function. */ function baseArity(func, n) { return n == 2 ? function(a, b) { return func.apply(undefined, arguments); } : function(a) { return func.apply(undefined, arguments); }; } /** * Creates a function that invokes `func`, with up to `n` arguments, ignoring * any additional arguments. * * @private * @param {Function} func The function to cap arguments for. * @param {number} n The arity cap. * @returns {Function} Returns the new function. */ function baseAry(func, n) { return n == 2 ? function(a, b) { return func(a, b); } : function(a) { return func(a); }; } /** * Creates a clone of `array`. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the cloned array. */ function cloneArray(array) { var length = array ? array.length : 0, result = Array(length); while (length--) { result[length] = array[length]; } return result; } /** * Creates a function that clones a given object using the assignment `func`. * * @private * @param {Function} func The assignment function. * @returns {Function} Returns the new cloner function. */ function createCloner(func) { return function(object) { return func({}, object); }; } /** * This function is like `_.spread` except that it includes arguments after those spread. * * @private * @param {Function} func The function to spread arguments over. * @param {number} start The start position of the spread. * @returns {Function} Returns the new function. */ function spread(func, start) { return function() { var length = arguments.length, args = Array(length); while (length--) { args[length] = arguments[length]; } var array = args[start], lastIndex = args.length - 1, otherArgs = args.slice(0, start); if (array) { push.apply(otherArgs, array); } if (start != lastIndex) { push.apply(otherArgs, args.slice(start + 1)); } return func.apply(this, otherArgs); }; } /** * Creates a function that wraps `func` and uses `cloner` to clone the first * argument it receives. * * @private * @param {Function} func The function to wrap. * @param {Function} cloner The function to clone arguments. * @returns {Function} Returns the new immutable function. */ function wrapImmutable(func, cloner) { return function() { var length = arguments.length; if (!length) { return; } var args = Array(length); while (length--) { args[length] = arguments[length]; } var result = args[0] = cloner.apply(undefined, args); func.apply(undefined, args); return result; }; } /** * The base implementation of `convert` which accepts a `util` object of methods * required to perform conversions. * * @param {Object} util The util object. * @param {string} name The name of the function to convert. * @param {Function} func The function to convert. * @param {Object} [options] The options object. * @param {boolean} [options.cap=true] Specify capping iteratee arguments. * @param {boolean} [options.curry=true] Specify currying. * @param {boolean} [options.fixed=true] Specify fixed arity. * @param {boolean} [options.immutable=true] Specify immutable operations. * @param {boolean} [options.rearg=true] Specify rearranging arguments. * @returns {Function|Object} Returns the converted function or object. */ function baseConvert(util, name, func, options) { var setPlaceholder, isLib = typeof name == 'function', isObj = name === Object(name); if (isObj) { options = func; func = name; name = undefined; } if (func == null) { throw new TypeError; } options || (options = {}); var config = { 'cap': 'cap' in options ? options.cap : true, 'curry': 'curry' in options ? options.curry : true, 'fixed': 'fixed' in options ? options.fixed : true, 'immutable': 'immutable' in options ? options.immutable : true, 'rearg': 'rearg' in options ? options.rearg : true }; var forceCurry = ('curry' in options) && options.curry, forceFixed = ('fixed' in options) && options.fixed, forceRearg = ('rearg' in options) && options.rearg, placeholder = isLib ? func : fallbackHolder, pristine = isLib ? func.runInContext() : undefined; var helpers = isLib ? func : { 'ary': util.ary, 'assign': util.assign, 'clone': util.clone, 'curry': util.curry, 'forEach': util.forEach, 'isArray': util.isArray, 'isFunction': util.isFunction, 'iteratee': util.iteratee, 'keys': util.keys, 'rearg': util.rearg, 'toInteger': util.toInteger, 'toPath': util.toPath }; var ary = helpers.ary, assign = helpers.assign, clone = helpers.clone, curry = helpers.curry, each = helpers.forEach, isArray = helpers.isArray, isFunction = helpers.isFunction, keys = helpers.keys, rearg = helpers.rearg, toInteger = helpers.toInteger, toPath = helpers.toPath; var aryMethodKeys = keys(mapping.aryMethod); var wrappers = { 'castArray': function(castArray) { return function() { var value = arguments[0]; return isArray(value) ? castArray(cloneArray(value)) : castArray.apply(undefined, arguments); }; }, 'iteratee': function(iteratee) { return function() { var func = arguments[0], arity = arguments[1], result = iteratee(func, arity), length = result.length; if (config.cap && typeof arity == 'number') { arity = arity > 2 ? (arity - 2) : 1; return (length && length <= arity) ? result : baseAry(result, arity); } return result; }; }, 'mixin': function(mixin) { return function(source) { var func = this; if (!isFunction(func)) { return mixin(func, Object(source)); } var pairs = []; each(keys(source), function(key) { if (isFunction(source[key])) { pairs.push([key, func.prototype[key]]); } }); mixin(func, Object(source)); each(pairs, function(pair) { var value = pair[1]; if (isFunction(value)) { func.prototype[pair[0]] = value; } else { delete func.prototype[pair[0]]; } }); return func; }; }, 'nthArg': function(nthArg) { return function(n) { var arity = n < 0 ? 1 : (toInteger(n) + 1); return curry(nthArg(n), arity); }; }, 'rearg': function(rearg) { return function(func, indexes) { var arity = indexes ? indexes.length : 0; return curry(rearg(func, indexes), arity); }; }, 'runInContext': function(runInContext) { return function(context) { return baseConvert(util, runInContext(context), options); }; } }; /*--------------------------------------------------------------------------*/ /** * Casts `func` to a function with an arity capped iteratee if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @returns {Function} Returns the cast function. */ function castCap(name, func) { if (config.cap) { var indexes = mapping.iterateeRearg[name]; if (indexes) { return iterateeRearg(func, indexes); } var n = !isLib && mapping.iterateeAry[name]; if (n) { return iterateeAry(func, n); } } return func; } /** * Casts `func` to a curried function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity of `func`. * @returns {Function} Returns the cast function. */ function castCurry(name, func, n) { return (forceCurry || (config.curry && n > 1)) ? curry(func, n) : func; } /** * Casts `func` to a fixed arity function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity cap. * @returns {Function} Returns the cast function. */ function castFixed(name, func, n) { if (config.fixed && (forceFixed || !mapping.skipFixed[name])) { var data = mapping.methodSpread[name], start = data && data.start; return start === undefined ? ary(func, n) : spread(func, start); } return func; } /** * Casts `func` to an rearged function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity of `func`. * @returns {Function} Returns the cast function. */ function castRearg(name, func, n) { return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name])) ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n]) : func; } /** * Creates a clone of `object` by `path`. * * @private * @param {Object} object The object to clone. * @param {Array|string} path The path to clone by. * @returns {Object} Returns the cloned object. */ function cloneByPath(object, path) { path = toPath(path); var index = -1, length = path.length, lastIndex = length - 1, result = clone(Object(object)), nested = result; while (nested != null && ++index < length) { var key = path[index], value = nested[key]; if (value != null) { nested[path[index]] = clone(index == lastIndex ? value : Object(value)); } nested = nested[key]; } return result; } /** * Converts `lodash` to an immutable auto-curried iteratee-first data-last * version with conversion `options` applied. * * @param {Object} [options] The options object. See `baseConvert` for more details. * @returns {Function} Returns the converted `lodash`. */ function convertLib(options) { return _.runInContext.convert(options)(undefined); } /** * Create a converter function for `func` of `name`. * * @param {string} name The name of the function to convert. * @param {Function} func The function to convert. * @returns {Function} Returns the new converter function. */ function createConverter(name, func) { var realName = mapping.aliasToReal[name] || name, methodName = mapping.remap[realName] || realName, oldOptions = options; return function(options) { var newUtil = isLib ? pristine : helpers, newFunc = isLib ? pristine[methodName] : func, newOptions = assign(assign({}, oldOptions), options); return baseConvert(newUtil, realName, newFunc, newOptions); }; } /** * Creates a function that wraps `func` to invoke its iteratee, with up to `n` * arguments, ignoring any additional arguments. * * @private * @param {Function} func The function to cap iteratee arguments for. * @param {number} n The arity cap. * @returns {Function} Returns the new function. */ function iterateeAry(func, n) { return overArg(func, function(func) { return typeof func == 'function' ? baseAry(func, n) : func; }); } /** * Creates a function that wraps `func` to invoke its iteratee with arguments * arranged according to the specified `indexes` where the argument value at * the first index is provided as the first argument, the argument value at * the second index is provided as the second argument, and so on. * * @private * @param {Function} func The function to rearrange iteratee arguments for. * @param {number[]} indexes The arranged argument indexes. * @returns {Function} Returns the new function. */ function iterateeRearg(func, indexes) { return overArg(func, function(func) { var n = indexes.length; return baseArity(rearg(baseAry(func, n), indexes), n); }); } /** * Creates a function that invokes `func` with its first argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function() { var length = arguments.length; if (!length) { return func(); } var args = Array(length); while (length--) { args[length] = arguments[length]; } var index = config.rearg ? 0 : (length - 1); args[index] = transform(args[index]); return func.apply(undefined, args); }; } /** * Creates a function that wraps `func` and applys the conversions * rules by `name`. * * @private * @param {string} name The name of the function to wrap. * @param {Function} func The function to wrap. * @returns {Function} Returns the converted function. */ function wrap(name, func) { var result, realName = mapping.aliasToReal[name] || name, wrapped = func, wrapper = wrappers[realName]; if (wrapper) { wrapped = wrapper(func); } else if (config.immutable) { if (mapping.mutate.array[realName]) { wrapped = wrapImmutable(func, cloneArray); } else if (mapping.mutate.object[realName]) { wrapped = wrapImmutable(func, createCloner(func)); } else if (mapping.mutate.set[realName]) { wrapped = wrapImmutable(func, cloneByPath); } } each(aryMethodKeys, function(aryKey) { each(mapping.aryMethod[aryKey], function(otherName) { if (realName == otherName) { var spreadData = mapping.methodSpread[realName], afterRearg = spreadData && spreadData.afterRearg; result = afterRearg ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey) : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey); result = castCap(realName, result); result = castCurry(realName, result, aryKey); return false; } }); return !result; }); result || (result = wrapped); if (result == func) { result = forceCurry ? curry(result, 1) : function() { return func.apply(this, arguments); }; } result.convert = createConverter(realName, func); if (mapping.placeholder[realName]) { setPlaceholder = true; result.placeholder = func.placeholder = placeholder; } return result; } /*--------------------------------------------------------------------------*/ if (!isObj) { return wrap(name, func); } var _ = func; // Convert methods by ary cap. var pairs = []; each(aryMethodKeys, function(aryKey) { each(mapping.aryMethod[aryKey], function(key) { var func = _[mapping.remap[key] || key]; if (func) { pairs.push([key, wrap(key, func)]); } }); }); // Convert remaining methods. each(keys(_), function(key) { var func = _[key]; if (typeof func == 'function') { var length = pairs.length; while (length--) { if (pairs[length][0] == key) { return; } } func.convert = createConverter(key, func); pairs.push([key, func]); } }); // Assign to `_` leaving `_.prototype` unchanged to allow chaining. each(pairs, function(pair) { _[pair[0]] = pair[1]; }); _.convert = convertLib; if (setPlaceholder) { _.placeholder = placeholder; } // Assign aliases. each(keys(_), function(key) { each(mapping.realToAlias[key] || [], function(alias) { _[alias] = _[key]; }); }); return _; } module.exports = baseConvert; /***/ }, /* 2 */ /***/ function(module, exports) { /** Used to map aliases to their real names. */ exports.aliasToReal = { // Lodash aliases. 'each': 'forEach', 'eachRight': 'forEachRight', 'entries': 'toPairs', 'entriesIn': 'toPairsIn', 'extend': 'assignIn', 'extendAll': 'assignInAll', 'extendAllWith': 'assignInAllWith', 'extendWith': 'assignInWith', 'first': 'head', // Methods that are curried variants of others. 'conforms': 'conformsTo', 'matches': 'isMatch', 'property': 'get', // Ramda aliases. '__': 'placeholder', 'F': 'stubFalse', 'T': 'stubTrue', 'all': 'every', 'allPass': 'overEvery', 'always': 'constant', 'any': 'some', 'anyPass': 'overSome', 'apply': 'spread', 'assoc': 'set', 'assocPath': 'set', 'complement': 'negate', 'compose': 'flowRight', 'contains': 'includes', 'dissoc': 'unset', 'dissocPath': 'unset', 'dropLast': 'dropRight', 'dropLastWhile': 'dropRightWhile', 'equals': 'isEqual', 'identical': 'eq', 'indexBy': 'keyBy', 'init': 'initial', 'invertObj': 'invert', 'juxt': 'over', 'omitAll': 'omit', 'nAry': 'ary', 'path': 'get', 'pathEq': 'matchesProperty', 'pathOr': 'getOr', 'paths': 'at', 'pickAll': 'pick', 'pipe': 'flow', 'pluck': 'map', 'prop': 'get', 'propEq': 'matchesProperty', 'propOr': 'getOr', 'props': 'at', 'symmetricDifference': 'xor', 'symmetricDifferenceBy': 'xorBy', 'symmetricDifferenceWith': 'xorWith', 'takeLast': 'takeRight', 'takeLastWhile': 'takeRightWhile', 'unapply': 'rest', 'unnest': 'flatten', 'useWith': 'overArgs', 'where': 'conformsTo', 'whereEq': 'isMatch', 'zipObj': 'zipObject' }; /** Used to map ary to method names. */ exports.aryMethod = { '1': [ 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create', 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow', 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll', 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse', 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', 'uniqueId', 'words', 'zipAll' ], '2': [ 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith', 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN', 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference', 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit', 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll', 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', 'zipObjectDeep' ], '3': [ 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight', 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', 'xorWith', 'zipWith' ], '4': [ 'fill', 'setWith', 'updateWith' ] }; /** Used to map ary to rearg configs. */ exports.aryRearg = { '2': [1, 0], '3': [2, 0, 1], '4': [3, 2, 0, 1] }; /** Used to map method names to their iteratee ary. */ exports.iterateeAry = { 'dropRightWhile': 1, 'dropWhile': 1, 'every': 1, 'filter': 1, 'find': 1, 'findFrom': 1, 'findIndex': 1, 'findIndexFrom': 1, 'findKey': 1, 'findLast': 1, 'findLastFrom': 1, 'findLastIndex': 1, 'findLastIndexFrom': 1, 'findLastKey': 1, 'flatMap': 1, 'flatMapDeep': 1, 'flatMapDepth': 1, 'forEach': 1, 'forEachRight': 1, 'forIn': 1, 'forInRight': 1, 'forOwn': 1, 'forOwnRight': 1, 'map': 1, 'mapKeys': 1, 'mapValues': 1, 'partition': 1, 'reduce': 2, 'reduceRight': 2, 'reject': 1, 'remove': 1, 'some': 1, 'takeRightWhile': 1, 'takeWhile': 1, 'times': 1, 'transform': 2 }; /** Used to map method names to iteratee rearg configs. */ exports.iterateeRearg = { 'mapKeys': [1] }; /** Used to map method names to rearg configs. */ exports.methodRearg = { 'assignInAllWith': [1, 0], 'assignInWith': [1, 2, 0], 'assignAllWith': [1, 0], 'assignWith': [1, 2, 0], 'differenceBy': [1, 2, 0], 'differenceWith': [1, 2, 0], 'getOr': [2, 1, 0], 'intersectionBy': [1, 2, 0], 'intersectionWith': [1, 2, 0], 'isEqualWith': [1, 2, 0], 'isMatchWith': [2, 1, 0], 'mergeAllWith': [1, 0], 'mergeWith': [1, 2, 0], 'padChars': [2, 1, 0], 'padCharsEnd': [2, 1, 0], 'padCharsStart': [2, 1, 0], 'pullAllBy': [2, 1, 0], 'pullAllWith': [2, 1, 0], 'rangeStep': [1, 2, 0], 'rangeStepRight': [1, 2, 0], 'setWith': [3, 1, 2, 0], 'sortedIndexBy': [2, 1, 0], 'sortedLastIndexBy': [2, 1, 0], 'unionBy': [1, 2, 0], 'unionWith': [1, 2, 0], 'updateWith': [3, 1, 2, 0], 'xorBy': [1, 2, 0], 'xorWith': [1, 2, 0], 'zipWith': [1, 2, 0] }; /** Used to map method names to spread configs. */ exports.methodSpread = { 'assignAll': { 'start': 0 }, 'assignAllWith': { 'start': 0 }, 'assignInAll': { 'start': 0 }, 'assignInAllWith': { 'start': 0 }, 'defaultsAll': { 'start': 0 }, 'defaultsDeepAll': { 'start': 0 }, 'invokeArgs': { 'start': 2 }, 'invokeArgsMap': { 'start': 2 }, 'mergeAll': { 'start': 0 }, 'mergeAllWith': { 'start': 0 }, 'partial': { 'start': 1 }, 'partialRight': { 'start': 1 }, 'without': { 'start': 1 }, 'zipAll': { 'start': 0 } }; /** Used to identify methods which mutate arrays or objects. */ exports.mutate = { 'array': { 'fill': true, 'pull': true, 'pullAll': true, 'pullAllBy': true, 'pullAllWith': true, 'pullAt': true, 'remove': true, 'reverse': true }, 'object': { 'assign': true, 'assignAll': true, 'assignAllWith': true, 'assignIn': true, 'assignInAll': true, 'assignInAllWith': true, 'assignInWith': true, 'assignWith': true, 'defaults': true, 'defaultsAll': true, 'defaultsDeep': true, 'defaultsDeepAll': true, 'merge': true, 'mergeAll': true, 'mergeAllWith': true, 'mergeWith': true, }, 'set': { 'set': true, 'setWith': true, 'unset': true, 'update': true, 'updateWith': true } }; /** Used to track methods with placeholder support */ exports.placeholder = { 'bind': true, 'bindKey': true, 'curry': true, 'curryRight': true, 'partial': true, 'partialRight': true }; /** Used to map real names to their aliases. */ exports.realToAlias = (function() { var hasOwnProperty = Object.prototype.hasOwnProperty, object = exports.aliasToReal, result = {}; for (var key in object) { var value = object[key]; if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } } return result; }()); /** Used to map method names to other names. */ exports.remap = { 'assignAll': 'assign', 'assignAllWith': 'assignWith', 'assignInAll': 'assignIn', 'assignInAllWith': 'assignInWith', 'curryN': 'curry', 'curryRightN': 'curryRight', 'defaultsAll': 'defaults', 'defaultsDeepAll': 'defaultsDeep', 'findFrom': 'find', 'findIndexFrom': 'findIndex', 'findLastFrom': 'findLast', 'findLastIndexFrom': 'findLastIndex', 'getOr': 'get', 'includesFrom': 'includes', 'indexOfFrom': 'indexOf', 'invokeArgs': 'invoke', 'invokeArgsMap': 'invokeMap', 'lastIndexOfFrom': 'lastIndexOf', 'mergeAll': 'merge', 'mergeAllWith': 'mergeWith', 'padChars': 'pad', 'padCharsEnd': 'padEnd', 'padCharsStart': 'padStart', 'propertyOf': 'get', 'rangeStep': 'range', 'rangeStepRight': 'rangeRight', 'restFrom': 'rest', 'spreadFrom': 'spread', 'trimChars': 'trim', 'trimCharsEnd': 'trimEnd', 'trimCharsStart': 'trimStart', 'zipAll': 'zip' }; /** Used to track methods that skip fixing their arity. */ exports.skipFixed = { 'castArray': true, 'flow': true, 'flowRight': true, 'iteratee': true, 'mixin': true, 'rearg': true, 'runInContext': true }; /** Used to track methods that skip rearranging arguments. */ exports.skipRearg = { 'add': true, 'assign': true, 'assignIn': true, 'bind': true, 'bindKey': true, 'concat': true, 'difference': true, 'divide': true, 'eq': true, 'gt': true, 'gte': true, 'isEqual': true, 'lt': true, 'lte': true, 'matchesProperty': true, 'merge': true, 'multiply': true, 'overArgs': true, 'partial': true, 'partialRight': true, 'propertyOf': true, 'random': true, 'range': true, 'rangeRight': true, 'subtract': true, 'zip': true, 'zipObject': true, 'zipObjectDeep': true }; /***/ }, /* 3 */ /***/ function(module, exports) { /** * The default argument placeholder value for methods. * * @type {Object} */ module.exports = {}; /***/ } /******/ ]) }); ;
28.899807
95
0.580739
3b608dd2a75defbf17268f96e382e84dd28d1c7d
3,112
js
JavaScript
app.js
avnishere/zuzu
8d1e14bf98a7af82c871e53709eb7d8f8a2a678f
[ "MIT" ]
null
null
null
app.js
avnishere/zuzu
8d1e14bf98a7af82c871e53709eb7d8f8a2a678f
[ "MIT" ]
1
2017-11-05T10:01:02.000Z
2017-11-05T16:27:18.000Z
app.js
avnishere/zuzu
8d1e14bf98a7af82c871e53709eb7d8f8a2a678f
[ "MIT" ]
null
null
null
var http = require('http'); var url = require('url'); var convertExcel = require('excel-as-json').processFile; var fs = require('fs'); http.createServer(function (req,resp) { if(req.url === "/dashboard"){ fs.createReadStream(__dirname + "/pages/p_dashboard.html").pipe(resp); } if(req.url === "/menu"){ fs.createReadStream(__dirname + "/pages/p_menu.html").pipe(resp); } if(req.url === "/aadhaar"){ fs.createReadStream(__dirname + "/pages/p_aadhaar.html").pipe(resp); } if(req.url === "/allotment"){ fs.createReadStream(__dirname + "/pages/p_allotment.html").pipe(resp); } if(req.url === "/passbook"){ fs.createReadStream(__dirname + "/pages/p_passbook.html").pipe(resp); } if(req.url === "/payment_folder"){ fs.createReadStream(__dirname + "/pages/p_payment_folder.html").pipe(resp); } if(req.url === "/pension_auto"){ fs.createReadStream(__dirname + "/pages/p_pension_auto.html").pipe(resp); } if(req.url === "/pension_manual"){ fs.createReadStream(__dirname + "/pages/p_pension_manual.html").pipe(resp); } if(req.url === "/reports"){ fs.createReadStream(__dirname + "/pages/p_reports.html").pipe(resp); } if(req.url === "/sanct_allot"){ fs.createReadStream(__dirname + "/pages/p_sanct_allot.html").pipe(resp); } if(req.url === "/sanction"){ fs.createReadStream(__dirname + "/pages/p_sanction.html").pipe(resp); } if(req.url === "/uc"){ fs.createReadStream(__dirname + "/pages/p_uc.html").pipe(resp); } if(req.url === "/excel"){ var jsonString = ""; req.on('data', function (data) { jsonString += data; }); req.on('end', function () { convertExcel("Payment_File_Sample.xlsx", null, null, function (err,data) { resp.setHeader('content-type', 'application/json'); resp.writeHead(200); resp.end(JSON.stringify(data)); }); }); } if(req.url.indexOf('.css') !== -1){ fs.readFile(__dirname + req.url, function (err, data) { if(!err){ resp.writeHead(200, {'Content-Type': 'text/css'}); resp.write(data); resp.end(); } }); } if(req.url.indexOf('.js') !== -1){ fs.readFile(__dirname + req.url, function (err, data) { resp.writeHead(200, {'Content-Type': 'text/javascript'}); resp.write(data); resp.end(); }); } if(req.url.indexOf('.png') !== -1){ fs.readFile(__dirname + req.url, function (err, data) { resp.writeHead(200, {'Content-Type': 'image/png'}); resp.write(data); resp.end(); }); } if(req.url.indexOf('.jpg') !== -1){ fs.readFile(__dirname + req.url, function (err, data) { resp.writeHead(200, {'Content-Type': 'image/jpg'}); resp.write(data); resp.end(); }); } }).listen(1337,"0.0.0.0");
28.814815
86
0.537918
3b6180d7d08052748aac69fd8180bd3b3055173b
1,106
js
JavaScript
node_modules/svg-center/index.js
wolfiex/svg-centre
92253f4bee9a5bad4736a1aa7cd7554ad8e195cf
[ "MIT" ]
null
null
null
node_modules/svg-center/index.js
wolfiex/svg-centre
92253f4bee9a5bad4736a1aa7cd7554ad8e195cf
[ "MIT" ]
null
null
null
node_modules/svg-center/index.js
wolfiex/svg-centre
92253f4bee9a5bad4736a1aa7cd7554ad8e195cf
[ "MIT" ]
null
null
null
'use strict'; /* * * Escape special characters in the given string of html. * * @param {String} html * @return {String} */ module.exports = { shrink: function(s) { var btop =[],bbottom =[],bleft=[],bright=[]; //var s = document.getElementsByTagName('svg')[3]; [...s.children].forEach(c =>{ var val = c.getBoundingClientRect(); btop.push(val.top); bbottom.push(val.bottom); bleft.push(val.left); bright.push(val.right); }) btop = Math.min(...btop); bbottom = Math.max(...bbottom); bleft = Math.min(...bleft); bright = Math.max(...bright); var bx= Math.abs(btop-bbottom); var by= Math.abs(bleft-bright); s.setAttribute('preserveAspectRatio',"none"); s.style.width = bx; s.style.height = by; s.setAttribute('viewBox',''+0+' '+0+ ' '+bx+' '+by); s.setAttribute('preserveAspectRatio',"xMinYMin meet"); return s }, shrinkall: function() { [...document.getElementsByTagName('svg')].forEach(s=>shrink(s)) } };
26.97561
71
0.546112
3b61d644a0c9f70d86a9d4746efd7045602117ff
4,351
js
JavaScript
src/dict/encn_Youdao.js
Greapi/ODH
0ebe0ffcf58e477cdb74022bf6aa23e8c9af5950
[ "MIT" ]
1
2021-02-15T03:17:58.000Z
2021-02-15T03:17:58.000Z
src/dict/encn_Youdao.js
Greapi/ODH
0ebe0ffcf58e477cdb74022bf6aa23e8c9af5950
[ "MIT" ]
null
null
null
src/dict/encn_Youdao.js
Greapi/ODH
0ebe0ffcf58e477cdb74022bf6aa23e8c9af5950
[ "MIT" ]
4
2020-04-08T06:15:19.000Z
2021-09-10T16:29:24.000Z
/* global api */ class encn_Youdao { constructor() { this.options = null; this.maxexample = 2; this.word = ''; } async displayName() { let locale = await api.locale(); if (locale.indexOf('CN') != -1) return '有道英汉简明'; if (locale.indexOf('TW') != -1) return '有道英漢簡明'; return 'Youdao Concise EN->CN Dictionary'; } setOptions(options) { this.options = options; this.maxexample = options.maxexample; } async findTerm(word) { this.word = word; //let deflection = await api.deinflect(word); let results = await Promise.all([this.findYoudao(word)]); return [].concat(...results).filter(x => x); } async findYoudao(word) { if (!word) return []; let base = 'http://dict.youdao.com/w/'; let url = base + encodeURIComponent(word); let doc = ''; try { let data = await api.fetch(url); let parser = new DOMParser(); doc = parser.parseFromString(data, 'text/html'); let youdao = getYoudao(doc); let ydtrans = youdao.length ? [] : getYDTrans(doc); //downgrade to Youdao Translation (if any) to the end. return [].concat(youdao, ydtrans); } catch (err) { return []; } function getYoudao(doc) { let notes = []; //get Youdao EC data: check data availability let defNodes = doc.querySelectorAll('#phrsListTab .trans-container ul li'); if (!defNodes || !defNodes.length) return notes; //get headword and phonetic let expression = T(doc.querySelector('#phrsListTab .wordbook-js .keyword')); //headword let reading = ''; let readings = doc.querySelectorAll('#phrsListTab .wordbook-js .pronounce'); if (readings) { let reading_uk = T(readings[0]); let reading_us = T(readings[1]); reading = (reading_uk || reading_us) ? `${reading_uk} ${reading_us}` : ''; } let audios = []; audios[0] = `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(expression)}&type=1`; audios[1] = `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(expression)}&type=2`; let definition = '<ul class="ec">'; for (const defNode of defNodes) { let pos = ''; let def = T(defNode); let match = /(^.+?\.)\s/gi.exec(def); if (match && match.length > 1) { pos = match[1]; def = def.replace(pos, ''); } pos = pos ? `<span class="pos simple">${pos}</span>` : ''; definition += `<li class="ec">${pos}<span class="ec_chn">${def}</span></li>`; } definition += '</ul>'; let css = ` <style> span.pos {text-transform:lowercase; font-size:0.9em; margin-right:5px; padding:2px 4px; color:white; background-color:#0d47a1; border-radius:3px;} span.simple {background-color: #999!important} ul.ec, li.ec {margin:0; padding:0;} </style>`; notes.push({ css, expression, reading, definitions: [definition], audios }); return notes; } function getYDTrans(doc) { let notes = []; //get Youdao EC data: check data availability let transNode = doc.querySelectorAll('#ydTrans .trans-container p')[1]; if (!transNode) return notes; let definition = `${T(transNode)}`; let css = ` <style> .odh-expression { font-size: 1em!important; font-weight: normal!important; } </style>`; notes.push({ css, definitions: [definition], }); return notes; } function T(node) { if (!node) return ''; else return node.innerText.trim(); } } }
34.808
167
0.482418
3b625df48303d31d7de69eace0bc4054f956ccf7
36,006
js
JavaScript
resources/views/admin/js/script.js
JhonatanMartimiano/laravel-mobile
668d374394a2e5b478322e44480bffef0a9683e5
[ "MIT" ]
null
null
null
resources/views/admin/js/script.js
JhonatanMartimiano/laravel-mobile
668d374394a2e5b478322e44480bffef0a9683e5
[ "MIT" ]
null
null
null
resources/views/admin/js/script.js
JhonatanMartimiano/laravel-mobile
668d374394a2e5b478322e44480bffef0a9683e5
[ "MIT" ]
null
null
null
$(function () { /* * ========================================================== * ======================== THEME FNCs ============================ * ========================================================== * */ // ============================================================== // Auto select left navbar // ============================================================== $('#sidebarnav a').on('click', function (e) { console.log("click"); if (!$(this).hasClass("active")) { // hide any open menus and remove all other classes $("ul", $(this).parents("ul:first")).removeClass("in"); $("a", $(this).parents("ul:first")).removeClass("active"); // open our new menu and add the open class $(this).next("ul").addClass("in"); $(this).addClass("active"); } else if ($(this).hasClass("active")) { $(this).removeClass("active"); $(this).parents("ul:first").removeClass("active"); $(this).next("ul").removeClass("in"); } }) $('#sidebarnav >li >a.has-arrow').on('click', function (e) { e.preventDefault(); }); // ============================================================== // This is for the top header part and sidebar part // ============================================================== var set = function () { var width = (window.innerWidth > 0) ? window.innerWidth : this.screen.width; var topOffset = 55; if (width < 1170) { $("body").addClass("mini-sidebar"); $('.navbar-brand span').hide(); $(".sidebartoggler i").addClass("ti-menu"); } else { $("body").removeClass("mini-sidebar"); $('.navbar-brand span').show(); } var height = ((window.innerHeight > 0) ? window.innerHeight : this.screen.height) - 1; height = height - topOffset; if (height < 1) height = 1; if (height > topOffset) { $(".page-wrapper").css("min-height", (height) + "px"); } }; $(window).ready(set); $(window).on("resize", set); $('.navbar-brand b').hide(); // ============================================================== // Theme options // ============================================================== $(".sidebartoggler").on('click', function () { if ($("body").hasClass("mini-sidebar")) { $("body").trigger("resize"); $("body").removeClass("mini-sidebar"); $('.navbar-brand b').hide(); $('.navbar-brand span').show(); } else { $("body").trigger("resize"); $("body").addClass("mini-sidebar"); $('.navbar-brand b').show(); $('.navbar-brand span').hide(); } }); // this is for close icon when navigation open in mobile view $(".nav-toggler").click(function () { $("body").toggleClass("show-sidebar"); $(".nav-toggler i").toggleClass("ti-menu"); $(".nav-toggler i").addClass("ti-close"); }); $(".search-box a, .search-box .app-search .srh-btn").on('click', function () { $(".app-search").toggle(200); }); // ============================================================== // Perfact scrollbar // ============================================================== $('.scroll-sidebar, .right-side-panel, .message-center, .right-sidebar').perfectScrollbar(); $('#chat, #msg, #comment, #todo').perfectScrollbar(); /* * ====================== END THEME FNCs ========================== * */ /* * ========================================================== * ======================== GERAL ============================ * ========================================================== * */ jQuery(document).on('click', '.mega-dropdown', function (e) { e.stopPropagation(); }); $("body").trigger("resize"); $('[data-toggle="tooltip"]').tooltip() $('[data-toggle="popover"]').popover() /* Preloader fadeOut() */ $(document).ready(function () { $(".preloader").fadeOut(700); }); /* * ====================== END GERAL ========================== * */ /* * ========================================================== * ======================== AJAX ============================ * ========================================================== * */ $('html').on('submit', 'form.j_show_loader', function () { $(".ajax-loader").fadeIn('fast'); $(".loader-form").fadeIn('500'); setTimeout(function () { $(".ajax-loader").fadeOut('fast'); $(".loader-form").fadeOut('500'); }, 5000); }); /* Formulario é disparado no change do input */ $('html').on('change', '.j_input_form_submit', function (e) { var valorSetado = ($(this).val() != "" ? $(this).val() : "0,00"); var prev_valor = (typeof $(this).data('val') === 'undefined' ? "0,00" : $(this).data('val')); if (valorSetado != prev_valor) { var trigger = $(this).attr("id"); var form = $($(this).attr('data-form')); var url = form.attr('action'); $(".ajax-loader").fadeIn('fast'); $(".loader-form").fadeIn('500'); form.find("button[type='submit']").attr("disabled", "disabled"); form.ajaxSubmit({ url: url, dataType: 'json', data: {trigger: trigger}, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, success: function (data) { $(".ajax-loader").fadeOut('500'); $(".loader-form").fadeOut('400'); form.find("button").removeAttr("disabled"); // <--------------------------------------------------------------- // Abre modal if (data.modalOpen) { $(data.modalOpen).modal('show'); } else { /* Seto o valor atual em todos os campos do formulario para evitar erros (somente se o modal não for aberto) */ form.find(".form-control").each(function (key, value) { $(this).data('val', ($(this).val() === "" ? 0 : $(this).val())); }); } if (data.modalClose) { $(data.modalClose).modal('hide'); } // Atualiza o data-targe do botão de fechamento do modal, utilizado para retornar o valor antigo de um input if (data.modalBtnTarget) { $("#closeModalMasterPassword").attr('data-target', data.modalBtnTarget); } if (data.show) { $(data.show).slideDown(); } if (data.toast) { toastMake(data); } if (data.contentHtml) { $.each(data.contentHtml, function (key, value) { $(key).html(value); }); } // Popula inputs de formulario if (data.content) { $.each(data.content, function (key, value) { $("#" + key).val(value); }); } /* Desmarca check do input */ if (data.removeChecked) { $(data.removeChecked).prop('checked', false); } // Popula inputs de formulario if (data.inputData) { $.each(data.inputData, function (key, value) { $("#" + key).val(value); }); } // Retorna valor do input ao estado anterior if (data.inputLoad) { $.each(data.inputLoad, function (key, value) { $("#" + value).val($("#" + value).data('val')); }); } // Insere HTML no container if (data.htmlData) { $.each(data.htmlData, function (key, value) { $(key).html(value); }); } } }); } }); /* FORM AUTOSAVE ACTION */ $('html').on('change', 'form.auto_save', function (e) { e.preventDefault(); e.stopPropagation(); /* Não executa a requisição se data-off = true */ var isOff = $("#" + e.target.id).attr('data-off'); if (isOff !== 'true') { var form = $(this); var url = form.attr('action'); $(".ajax-loader").fadeIn('500'); $(".loader-form").fadeIn('500'); form.ajaxSubmit({ url: url, dataType: 'json', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, success: function (data) { $(".ajax-loader").fadeOut('500'); $(".loader-form").fadeOut('500'); if (data.toast) { toastMake(data); } /* Seto o valor atual em todos os campos do formulario para evitar erros (somente se o modal não for aberto) */ form.find(".form-control").each(function (key, value) { $(this).data('val', ($(this).val() === "" ? 0 : $(this).val())); }); if (data.contentHtml) { $.each(data.contentHtml, function (key, value) { $(key).html(value); }); } // Popula inputs de formulario if (data.content) { $.each(data.content, function (key, value) { $("#" + key).val(value); }); } /* Desmarca check do input */ if (data.removeChecked) { $(data.removeChecked).prop('checked', false); } if (data.sweet) { sweetMake(data.sweet); } /* Receber Crediario */ if (data.receber_crediario) { // if (data.success) { // $("#crediario_identificar").slideUp(600, function () { // $("#crediario_receber").slideDown(600, function () { // var y = parseInt($("#crediario_receber").offset().top) - 200; // $('html, body').animate({scrollTop: y}, 400); // }); // }); // } } } }); } }); /* Formulario é salvo automaticamente mas primeiro é exibido uma popup de confirmação */ $('html').on('change', 'form.auto_save_verify', function (e) { e.preventDefault(); e.stopPropagation(); var form = $(this); var form_data = form.serializeArray(); var url = form.attr('action'); var max_value = form.attr('data-verify'); // Se o valor setado for maior que o valor definido pelo sistema no atributo data-verify exibe a mensagem do atributo data-verify-msg if (form_data[1].value > max_value) { var message = form.attr('data-verify-msg'); } else { var message = "A alteração deste valor tem grande impacto em sua loja, prossiga apenas se estiver certo desta ação."; } Swal.fire({ titleText: "Atenção!", text: message, icon: "warning", allowOutsideClick: false, allowEscapeKey: false, allowEnterKey: false, showCancelButton: true, confirmButtonText: "Prosseguir!", confirmButtonColor: "#23903c", cancelButtonText: "Cancelar e retornar", cancelButtonColor: "#dd3c4c", focusCancel: true, backdrop: "rgba(0,0,0,0.8)", }).then((result) => { /* * Se o usuário abortar a alteração será recuperado o valor antigo do input e setado nele novamente * */ if (result.dismiss === Swal.DismissReason.cancel) { var prev = form.find('input[name="valor"]').data('val'); form.find('input[name="valor"]').val(prev); } else { /* Ao confirmar a ação, o submit é disparado e o fluxo segue a diante */ $(".ajax-loader").fadeIn('500'); form.ajaxSubmit({ url: url, dataType: 'json', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, beforeSend: function () { }, success: function (data) { $(".ajax-loader").fadeOut('500'); if (data.toast) { toastMake(data); } } }); } }); }); /* FORM AJAX SUBMIT */ $('html').on('submit', 'form.ajax_submit', function (e) { e.preventDefault(); e.stopPropagation(); var form = $(this); var modalToClose = form.attr('data-modalclose'); /* Utilizado para indicar ao backend que a ação do submit foi disparada pelo botão de submit */ if (form.attr('data-verify') == 1) { $("input#verify").val(1); } form.ajaxSubmit({ url: form.attr('action'), dataType: 'json', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, beforeSend: function () { if (modalToClose) { $(modalToClose).modal('hide') } if (form.attr('data-modal')) { $(".ajax-loader-modal").fadeIn('fast'); $("#" + form.attr('data-modal') + "Error").html("").slideUp(400); $("#" + form.attr('data-modal')).find('button.close').attr('disabled', true); } else { $(".ajax-loader").fadeIn('fast'); $(".loader-form").fadeIn('500'); } form.find("button[type='submit']").attr('disabled', true); }, success: function (data) { if (form.attr('data-modal')) { $(".ajax-loader-modal").fadeOut('fast'); $("#" + form.attr('data-modal')).find('button.close').attr('disabled', false); } if (form.attr('data-verify') == 1) { $("input#verify").val(0); } $(".ajax-loader").fadeOut('fast'); $(".loader-form").fadeOut('fast'); form.find("button[type='submit']").attr('disabled', false); /* Mensagem de erro exibida no modal */ if (data.modal_error) { $("#" + form.attr('data-modal') + "Error").html(data.modal_error).slideDown(400); } if (data.dataSlide) { $.each(data.dataSlide, function (key, item) { $(item).slideDown(600); }); } /* Exibir/Esconder elementos */ if (data.hide && data.show) { $(data.hide).fadeOut(300, function () { $(data.show).fadeIn(300); }); } if (data.show && !data.hide) { $(data.show).fadeIn(300); } if (!data.show && data.hide) { $(data.hide).fadeOut(300); } // <--------------------------- END /* Mensagens de alerta */ if (data.toast) { toastMake(data); } if (data.removeChecked) { $(data.removeChecked).prop('checked', false); } if (data.redirect) { setTimeout(function () { window.location.href = data.redirect; }, 900) } if (data.modalClose) { $(data.modalClose).modal('hide'); } if (data.modalOpen) { $(data.modalOpen).modal('show'); } if (data.inputClear) { $(data.inputClear).val(""); } if (data.refresh) { document.location.reload(true); } if (data.contentHtml) { $.each(data.contentHtml, function (key, value) { $(key).html(value); }); } // Popula inputs de formulario if (data.content) { $.each(data.content, function (key, value) { $("#" + key).val(value); }); } // Limpa inputs if (data.clearInput) { $.each(data.clearInput, function (key, value) { $("#" + value).val(''); }); } // Desabilita Inputs if (data.disableInput) { $.each(data.disableInput, function (key, value) { $("#" + value).attr('readonly', true); }); } if (data.dataTableInit) { var iniData = { "dom": 'Bfrtip', "pageLength": data.dataTableInit.pageLength, "order": [data.dataTableInit.orderColumn, data.dataTableInit.orderDir], "language": { "sLengthMenu": "Mostrar _MENU_ registros por página", "sZeroRecords": "Nenhum registro encontrado", "sInfo": "Mostrando _START_ / _END_ de _TOTAL_ registro(s)", "sInfoEmpty": "Mostrando 0 / 0 de 0 registros", "sInfoFiltered": "(filtrado de _MAX_ registros)", "search": "Pesquisar: ", "processing": "Buscando dados aguarde...", "oPaginate": { "sFirst": "Início", "sPrevious": "Anterior", "sNext": "Próximo", "sLast": "Último" } }, }; if (data.dataTableInit.print) { iniData.buttons = { dom: { button: { tag: 'button', className: '' } }, "buttons": [ { extend: 'print', autoPrint: false, text: 'Imprimir Relatório<i class="fas fa-print ml-2"></i>', title: '', className: 'btn btn-info', exportOptions: { columns: data.dataTableInit.printCols }, customize: function (win) { if (data.dataTableInit.print) { $(win.document.body).prepend(data.dataTableInit.printHeader); $(win.document).find("table").addClass('table-sm').removeClass('table-bordered'); if(data.dataTableInit.printFooter){ $(win.document.body).append(data.dataTableInit.printFooter); } var imprimir = win.document.querySelector("#print-open"); imprimir.onclick = function () { imprimir.style.display = 'none'; win.window.print(); var time = win.window.setTimeout(function () { imprimir.style.display = 'block'; }, 1000); } win.window.onafterprint = function () { win.window.close(); } } } } ] }; } $(data.dataTableInit.key).DataTable(iniData); } if (data.showElement) { $("#" + data.showElement).slideDown(400, function () { var y = parseInt($("#" + data.showElement).offset().top) - 200; $('html, body').animate({scrollTop: y}, 500); }); } } }); }); /* Input Ajax Request */ $('html').on('change', '.ajax-input', function () { var _this = $(this); var route = $(this).attr('data-action'); var showAfter = $(this).attr('data-showafter'); var hideAfter = $(this).attr('data-hideafter'); var block = $(this).attr('data-block'); var isModal = $(this).attr('data-modal'); var adicionalData = $($(this).attr('data-adicional')).val(); // Valor localizado em outro input var complementarData = $(this).attr('data-complementar'); // Valor de texto literal var isChecked = ($(this).is(":checked") ? true : false); var value = $(this).val(); if ($(this).attr('minlength')) { if (value.length < $(this).attr('minlength') && value.length > 0) { $.toast({ heading: "Atenção", text: "É necessário informar ao menos " + $(this).attr('minlength') + " caracteres para pesquisar!", position: 'top-right', icon: "warning", hideAfter: 5000 }); return false; } else if (value.length < 1) { return false; } } $.ajax({ url: route, type: 'POST', dataType: 'json', data: {data: value, dataAdd: adicionalData, dataComplementar: complementarData, checked: isChecked}, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, beforeSend: function () { if (isModal == "true") { $(".modal").find('.ajax-loader').fadeIn('500'); } if (block == "true") { $(this).attr("disabled", true); } $(".loader-form").fadeIn('500'); $("#modalError").fadeOut(); }, success: function (data) { $(".loader-form").fadeOut('500'); if (isModal == "true") { $(".modal").find('.ajax-loader').fadeOut('500'); } if (block == "true") { $(this).attr("disabled", false); } // Mostrar elemento apos o retorno if (showAfter && data.success) { $("#" + showAfter).slideDown(400, function () { var y = parseInt($("#" + showAfter).offset().top) - 200; $('html, body').animate({scrollTop: y}, 500); }); } // Esconder elemento após o retorno if (hideAfter && data.success) { $("#" + hideAfter).fadeOut(200); } /* RESPONSE ACTIONS */ if (data.toast) { toastMake(data); } if (data.focus) { $(data.focus).focus(); } if (data.refresh) { document.location.reload(true); } if (data.redirect) { } if (data.consulta) { $("#consulta").html(data.consulta); } if (data.nova_consulta) { $("#nova_consulta").fadeIn(500); } // Limpa inputs if (data.clearInput) { $.each(data.clearInput, function (key, value) { $("#" + value).val(''); }); } // Desabilita Inputs if (data.disableInput) { $.each(data.disableInput, function (key, value) { $("#" + value).attr('readonly', true); }); } if (data.modalClose) { $(data.modalClose).modal('hide'); } if (data.liberaInput) { $.each(data.liberaInput, function (key, value) { $(value).attr("disabled", false); }); } if (data.modalError) { $("#modalError").html(data.modalError).fadeIn(); } if (data.master_pass_ok) { /* Necessario para saber se a função que calcula automaticamente o valor do desconto/acrescimo deve ou não executar o calculo. Se o campo foi alterado com uma senha master não deve fazer esse calculo no automatico */ $("#m_" + $("#closeModalMasterPassword").attr('data-master')).val("1"); $("#total_produtos").change(); // $("#m_" + $("#closeModalMasterPassword").attr('data-master')).val("0"); } if (data.contentHtml) { $.each(data.contentHtml, function (key, value) { $(key).html(value); }); } // Popula inputs de formulario if (data.content) { $.each(data.content, function (key, value) { $("#" + key).val(value); }); } /* Receber Crediario */ if (data.receber_crediario) { if (data.success) { $("#crediario_identificar").slideUp(600, function () { $("#crediario_receber").slideDown(600, function () { var y = parseInt($("#crediario_receber").offset().top) - 200; $('html, body').animate({scrollTop: y}, 400); }); }); } } if (data.dataSlide) { $.each(data.dataSlide, function (key, item) { $(item).slideDown(600); }); } /* Efetivar Venda Crediario */ if (data.venda_crediario) { if (data.success) { $("#crediario_identificar").slideUp(600, function () { $("#crediario_vender").slideDown(600, function () { var y = parseInt($("#crediario_vender").offset().top) - 200; $('html, body').animate({scrollTop: y}, 400); $("input#nome").val(''); $("input#documento").val(''); $("input#id").val(''); $("#html").html(""); }); }); if ($("#selectPerfilDaVenda option").length == 2) { $("#selectPerfilDaVenda option:eq(1)").attr('selected', 'selected'); $("#selectPerfilDaVenda").change(); } } } /* Ativa o recurso popover do Bootstrap */ if (data.popover) { $('[data-toggle="popover"]').popover({ trigger: 'hover' }); } } }); }); /* Click Ajax Request */ $('html').on('click', '.ajax-click', function () { var route = $(this).attr('data-action'); var showAfter = $(this).attr('data-showafter'); var hideAfter = $(this).attr('data-hideafter'); var block = $(this).attr('data-block'); var isModal = $(this).attr('data-modal'); var value = $(this).attr('data-value'); if (confirm("Deseja realmente executar esta ação?")) { $.ajax({ url: route, type: 'POST', dataType: 'json', data: {data: value}, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, beforeSend: function () { if (isModal == "true") { $(".modal").find('.ajax-loader').fadeIn('500'); } if (block == "true") { $(this).attr("disabled", true); } $(".loader-form").fadeIn('500'); $("#modalError").fadeOut(); }, success: function (data) { $(".loader-form").fadeOut('500'); if (isModal == "true") { $(".modal").find('.ajax-loader').fadeOut('500'); } if (block == "true") { $(this).attr("disabled", false); } // Mostrar elemento apos o retorno if (showAfter && data.success) { $("#" + showAfter).slideDown(400, function () { var y = parseInt($("#" + showAfter).offset().top) - 200; $('html, body').animate({scrollTop: y}, 900); }); } // Esconder elemento após o retorno if (hideAfter && data.success) { $("#" + hideAfter).fadeOut(200); } /* RESPONSE ACTIONS */ if (data.toast) { toastMake(data); } if (data.focus) { $(data.focus).focus(); } if (data.refresh) { document.location.reload(true); } if (data.redirect) { setTimeout(function () { window.location.href = data.redirect; }, 300) } // Popula inputs de formulario if (data.content) { $.each(data.content, function (key, value) { $("#" + key).val(value); }); } // Limpa inputs if (data.clearInput) { $.each(data.clearInput, function (key, value) { $("#" + value).val(''); }); } // Desabilita Inputs if (data.disableInput) { $.each(data.disableInput, function (key, value) { $("#" + value).attr('readonly', true); }); } if (data.modalClose) { $(data.modalClose).modal('hide'); } if (data.liberaInput) { $.each(data.liberaInput, function (key, value) { $(value).attr("disabled", false); }); } if (data.modalError) { $("#modalError").html(data.modalError).fadeIn(); } } }); } }); /* * ====================== END AJAX ========================== * */ /* * ========================================================== * =================== JQUERY MASK INIT ===================== * ========================================================== * */ if ($('.jmask-integer').length) { $('.jmask-integer').mask('00000000000'); } if ($('.jmask-decimal').length) { $('.jmask-decimal').mask('##0,0#', {reverse: true}); } if ($('.jmask-date').length) { $('.jmask-date').mask('00/00/0000', {placeholder: "__/__/____"}); } if ($('.jmask-rg').length) { $('.jmask-rg').mask('00.000.000-0', {placeholder: "__.___.___-_", reverse: true}); } if ($('.jmask-cpf').length) { $('.jmask-cpf').mask('000.000.000-00', {placeholder: "___.___.___-__"}); } if ($('.jmask-cpf-textual').length) { $('.jmask-cpf-textual').mask('000.000.000-00', {placeholder: "CPF (somente números)"}); } if ($('.jmask-cpf-noplaceholder').length) { $('.jmask-cpf-noplaceholder').mask('000.000.000-00', {placeholder: "CPF (somente números)"}); } if ($('.jmask-cnpj').length) { $('.jmask-cnpj').mask('00.000.000/0000-00', {placeholder: "__.___.___/_____-__"}); } if ($('.jmask-cep').length) { $('.jmask-cep').mask('00000-000', { placeholder: "_____-___" }); } if ($('.jmask-fone').length) { $('.jmask-fone').mask('(00)000000009', {placeholder: "(__)________"}); } if ($('.jmask-money').length) { $('.jmask-money').mask('000.000.000.000.000,00', {reverse: true}); // $('.money2').mask("#.##0,00", {reverse: true}); } if ($('.jmask-percent').length) { $('.jmask-percent').mask('##0,0#', {reverse: true}); } /* * ====================== END MASK ========================== * */ });
39.009751
143
0.372688
3b6288d02578fb2cfd96c3dd93023de8c0ac75d9
572
js
JavaScript
src/components/pages/SignUp.js
rosenbergmichael/react-app-april-2021
945d5e28bc193416a0b1c901f5732d730a5d6d68
[ "MIT" ]
null
null
null
src/components/pages/SignUp.js
rosenbergmichael/react-app-april-2021
945d5e28bc193416a0b1c901f5732d730a5d6d68
[ "MIT" ]
null
null
null
src/components/pages/SignUp.js
rosenbergmichael/react-app-april-2021
945d5e28bc193416a0b1c901f5732d730a5d6d68
[ "MIT" ]
null
null
null
import React from 'react'; import '../../App.css'; import Footer from '../Footer'; import '../../components/SignUp.css'; export default function SignUp() { return ( <div> <img src="/images/signup2.jpeg" alt="signup-img" /> <h1 className="sign-up">SIGN UP</h1> <form className="sign-up-form"> <input type="text" placeholder="Name"/> <input type="text" placeholder="Email"/> <input type="text" placeholder="Password"/> <button className="form-button">Submit</button> </form> <Footer /> </div> ) }
28.6
57
0.589161
3b62a972a289e7e2b09c854aa0d1f280dcfc8c5b
1,115
js
JavaScript
packages/render/src/primitives/renderBackground.js
shin0602/react-pdf
a549bcf2524577fff039ba58cc19740fbd9911d1
[ "MIT" ]
1
2021-05-02T06:48:51.000Z
2021-05-02T06:48:51.000Z
packages/render/src/primitives/renderBackground.js
shin0602/react-pdf
a549bcf2524577fff039ba58cc19740fbd9911d1
[ "MIT" ]
null
null
null
packages/render/src/primitives/renderBackground.js
shin0602/react-pdf
a549bcf2524577fff039ba58cc19740fbd9911d1
[ "MIT" ]
1
2017-09-14T03:06:11.000Z
2017-09-14T03:06:11.000Z
import * as R from 'ramda'; import colorString from 'color-string'; import save from '../operations/save'; import restore from '../operations/restore'; import clipNode from '../operations/clipNode'; const parseColor = hex => { const parsed = colorString.get(hex); const value = colorString.to.hex(parsed.value.slice(0, 3)); const opacity = parsed.value[3]; return { value, opacity }; }; const drawBackground = (ctx, node) => { if (node.box && node.style.backgroundColor) { const { top, left, width, height } = node.box; const color = parseColor(node.style.backgroundColor); const opacity = R.defaultTo(color.opacity, node.style?.opacity); ctx .fillOpacity(opacity) .fillColor(color.value) .rect(left, top, width, height) .fill(); } return node; }; const renderBackground = (ctx, node) => { const hasBackground = !!node.box && !!node.style?.backgroundColor; if (hasBackground) { save(ctx, node); clipNode(ctx, node); drawBackground(ctx, node); restore(ctx, node); } return node; }; export default R.curryN(2, renderBackground);
24.23913
68
0.66278
3b6313c6343480b807b844cc20812c773dc23165
3,364
js
JavaScript
webpack-server.config.js
stevenkaspar/react-redux-webpack-keystone-boilerplate
f11dcd8f1f9f8a30e48e35dedd3bf83f7d44ad10
[ "MIT" ]
5
2017-11-18T20:12:21.000Z
2019-10-01T06:43:00.000Z
webpack-server.config.js
stevenkaspar/react-redux-webpack-keystone-boilerplate
f11dcd8f1f9f8a30e48e35dedd3bf83f7d44ad10
[ "MIT" ]
null
null
null
webpack-server.config.js
stevenkaspar/react-redux-webpack-keystone-boilerplate
f11dcd8f1f9f8a30e48e35dedd3bf83f7d44ad10
[ "MIT" ]
1
2018-11-11T10:19:10.000Z
2018-11-11T10:19:10.000Z
var webpack = require('webpack'); const path = require('path') const UglifyJSPlugin = require('uglifyjs-webpack-plugin') const output = { development: { path: path.resolve(__dirname, './routes/redux-render'), filename: '[name].js', libraryTarget: "commonjs2" }, production: { path: path.resolve(__dirname, './routes/redux-render'), filename: '[name].js', libraryTarget: "commonjs2" } } const devtool = { development: '', production: '' } const entry = { development: { 'render': './routes/redux-render/src/render.jsx', }, production: { 'render': './routes/redux-render/src/render.jsx', } } const plugins = { development: [], production: [] } const env_key = process.env.NODE_ENV === 'development' ? 'development' : 'production' module.exports = { context: __dirname, target: 'node', entry: entry[env_key], output: output[env_key], devtool: devtool[env_key], plugins: plugins[env_key], module: { rules: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: "babel-loader", options: { presets: [ 'es2015', 'react', 'stage-2' ] }, }, { test: /\.scss$/, loaders: ['css-loader', 'sass-loader'] } ] } }; // const path = require('path'); // const webpack = require('webpack'); // // require('dotenv').config(); // // module.exports = { // entry: [ // 'react-hot-loader/patch', // // 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', // './public/js/src/app.js' // ], // output: { // filename: 'bundle.js', // path: path.resolve(__dirname, '/public/js/dist'), // publicPath: '/' // }, // devServer: { // hot: true, // contentBase: './public', // inline: true, // publicPath: 'http://localhost:8080/', // port: 8080 // }, // devtool: process.env.NODE_ENV === 'development' ? 'source-map' : 'false', // plugins: [ // new webpack.ProvidePlugin({ // $: 'jquery', // jQuery: 'jquery', // 'window.jQuery': 'jquery', // Popper: ['popper.js', 'default'], // // In case you imported plugins individually, you must also require them here: // Util: "exports-loader?Util!bootstrap/js/dist/util", // Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown", // }), // // new CleanWebpackPlugin(['dist']), // // new HtmlWebpackPlugin({ // // title: 'Hot Module Replacement' // // }), // new webpack.NamedModulesPlugin(), // new webpack.HotModuleReplacementPlugin() // ], // module: { // rules: [ // { // test: /\.(html|css|txt)$/, // use: 'raw-loader' // }, // { // test: /\.scss$/, // use: [{ // loader: "style-loader" // creates style nodes from JS strings // }, { // loader: "css-loader" // translates CSS into CommonJS // }, { // loader: "sass-loader" // compiles Sass to CSS // }] // }, // { // test: /\.js$/, // exclude: /(node_modules|bower_components)/, // loader: "babel-loader", // options: { // presets: [ // 'es2015', // 'react', // 'stage-2' // ] // }, // } // ] // } // };
24.376812
87
0.522889
3b63332ba47ab25c0847238631d5063d28020d44
1,309
js
JavaScript
src/views/Components/Areas/CreateAreaForm.js
yaser-elbatal/Annat
558287328bb64112664877d980e9b00325a22188
[ "MIT" ]
null
null
null
src/views/Components/Areas/CreateAreaForm.js
yaser-elbatal/Annat
558287328bb64112664877d980e9b00325a22188
[ "MIT" ]
null
null
null
src/views/Components/Areas/CreateAreaForm.js
yaser-elbatal/Annat
558287328bb64112664877d980e9b00325a22188
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import { Form, FormGroup, Label, Input, } from 'reactstrap'; export default class CreateAreaForm extends Component { constructor(props) { super(props); if (this.props.clearData) this.props.clearData(); } componentDidMount() { } changeHandle = (e) => { if (this.props.updateData) this.props.updateData({ [e.target.name]: e.target.value }) } createHandle = (e) => { e.preventDefault(); this.props.onSubmit && this.props.onSubmit(); } render() { return ( <Form> <FormGroup> <Label for="name_ar">الاسم باللغة العربية</Label> <Input type="text" name="name_ar" onChange={this.changeHandle} defaultValue="" id="name_ar" placeholder="الاسم باللغة العربية" /> </FormGroup> <FormGroup> <Label for="name">الاسم باللغة الإنجليزية</Label> <Input type="text" name="name" onChange={this.changeHandle} defaultValue="" id="name" placeholder="الاسم باللغة الإنجليزية" /> </FormGroup> <button class="btn btn-primary" onClick={this.createHandle} >إضافة</button> </Form> ); } }
31.926829
149
0.551566
3b637e0b118fb414d0c68d56d48fb4a44c00439a
6,274
js
JavaScript
third_party/google_input_tools/src/chrome/os/inputview/config/compact_symbol_characters.js
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/google_input_tools/src/chrome/os/inputview/config/compact_symbol_characters.js
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/google_input_tools/src/chrome/os/inputview/config/compact_symbol_characters.js
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
// Copyright 2014 The ChromeOS IME Authors. All Rights Reserved. // limitations under the License. // See the License for the specific language governing permissions and // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // distributed under the License is distributed on an "AS-IS" BASIS, // Unless required by applicable law or agreed to in writing, software // // http://www.apache.org/licenses/LICENSE-2.0 // // You may obtain a copy of the License at // you may not use this file except in compliance with the License. // Licensed under the Apache License, Version 2.0 (the "License"); // goog.provide('i18n.input.chrome.inputview.content.compact.symbol'); goog.require('i18n.input.chrome.inputview.content.constants'); goog.scope(function() { var NonLetterKeys = i18n.input.chrome.inputview.content.constants.NonLetterKeys; /** * Gets North American Symbol keyset characters. * * @return {!Array.<!Object>} */ i18n.input.chrome.inputview.content.compact.symbol.keyNASymbolCharacters = function() { return [ /* 0 */ { 'text': '1', 'moreKeys': { 'characters': ['\u00B9', '\u00BD', '\u2153', '\u00BC', '\u215B']}}, /* 1 */ { 'text': '2', 'moreKeys': { 'characters': ['\u00B2', '\u2154']}}, /* 2 */ { 'text': '3', 'moreKeys': { 'characters': ['\u00B3', '\u00BE', '\u215C']}}, /* 3 */ { 'text': '4', 'moreKeys': { 'characters': ['\u2074']}}, /* 4 */ { 'text': '5', 'moreKeys': { 'characters': ['\u215D']}}, /* 5 */ { 'text': '6' }, /* 6 */ { 'text': '7', 'moreKeys': { 'characters': ['\u215E']}}, /* 7 */ { 'text': '8' }, /* 8 */ { 'text': '9' }, /* 9 */ { 'text': '0', 'moreKeys': { 'characters': ['\u207F', '\u2205']}}, /* 10 */ NonLetterKeys.BACKSPACE, /* 11 */ { 'text': '@', 'marginLeftPercent': 0.33 }, /* 12 */ { 'text': '#' }, /* 13 */ { 'text': '$', 'moreKeys': { 'characters': ['\u00A2', '\u00A3', '\u20AC', '\u00A5', '\u20B1']}}, /* 14 */ { 'text': '%', 'moreKeys': { 'characters': ['\u2030']}}, /* 15 */ { 'text': '&' }, // Keep in sync with rowkeys_symbols2.xml in android input tool. /* 16 */ { 'text': '-', 'moreKeys': { 'characters': ['_', '\u2013', '\u2014', '\u00B7']}}, /* 17 */ { 'text': '+', 'moreKeys': { 'characters': ['\u00B1']}}, /* 18 */ { 'text': '(', 'moreKeys': { 'characters': ['<', '{', '[']}}, /* 19 */ { 'text': ')', 'moreKeys': { 'characters': ['>', '}', ']']}}, /* 20 */ NonLetterKeys.ENTER, /* 21 */ NonLetterKeys.SWITCHER, /* 22 */ { 'text': '\\' }, /* 23 */ { 'text': '=' }, /* 24 */ { 'text': '*', 'moreKeys': { 'characters': ['\u2020', '\u2021', '\u2605']}}, /* 25 */ { 'text': '"', 'moreKeys': { 'characters': ['\u201E', '\u201C', '\u201D', '\u00AB', '\u00BB']}}, /* 26 */ { 'text': '\'', 'moreKeys': { 'characters': ['\u201A', '\u2018', '\u2019', '\u2039', '\u203A']}}, /* 27 */ { 'text': ':' }, /* 28 */ { 'text': ';' }, /* 29 */ { 'text': '!', 'moreKeys': { 'characters': ['\u00A1']}}, /* 30 */ { 'text': '?', 'moreKeys': { 'characters': ['\u00BF']}}, /* 31 */ NonLetterKeys.SWITCHER, /* 32 */ NonLetterKeys.SWITCHER, /* 33 */ { 'text': '_', 'isGrey': true }, /* 34 */ NonLetterKeys.MENU, /* 35 */ { 'text': '/', 'isGrey': true }, /* 36 */ NonLetterKeys.SPACE, /* 37 */ { 'text': ',', 'isGrey': true }, // Keep in sync with row_symbols4.xml in android input tool. /* 38 */ { 'text': '.', 'isGrey': true, 'moreKeys': { 'characters': ['\u2026']}}, /* 39 */ NonLetterKeys.HIDE ]; }; /** * Gets United Kingdom Symbol keyset characters. * * @return {!Array.<!Object>} */ i18n.input.chrome.inputview.content.compact.symbol.keyUKSymbolCharacters = function() { // Copy North America symbol characters. var data = i18n.input.chrome.inputview.content.compact.symbol. keyNASymbolCharacters(); // UK uses pound sign instead of dollar sign. data[13] = { 'text': '\u00A3', 'moreKeys': { 'characters': ['\u00A2', '$', '\u20AC', '\u00A5', '\u20B1']}}; return data; }; /** * Gets European Symbol keyset characters. * * @return {!Array.<!Object>} */ i18n.input.chrome.inputview.content.compact.symbol.keyEUSymbolCharacters = function() { // Copy UK symbol characters. var data = i18n.input.chrome.inputview.content.compact.symbol. keyUKSymbolCharacters(); // European uses euro sign instead of pound sign. data[13] = { 'text': '\u20AC', 'moreKeys': { 'characters': ['\u00A2', '$', '\u00A3', '\u00A5', '\u20B1']}}; return data; }; /** * Gets Pinyin Symbol keyset characters. * * @return {!Array.<!Object>} */ i18n.input.chrome.inputview.content.compact.symbol.keyPinyinSymbolCharacters = function() { var data = i18n.input.chrome.inputview.content.compact.symbol. keyNASymbolCharacters(); data[13]['text'] = '\u00A5'; data[13]['moreKeys'] = { 'characters': ['\u0024', '\u00A2', '\u00A3', '\u20AC', '\u20B1']}; data[15]['text'] = '&'; data[18]['text'] = '\uff08'; data[18]['moreKeys'] = { 'characters': ['\uff5b', '\u300a', '\uff3b', '\u3010']}; data[19]['text'] = '\uff09'; data[19]['moreKeys'] = { 'characters': ['\uff5d', '\u300b', '\uff3d', '\u3001']}; data[22]['text'] = '\u3001'; data[25]['text'] = '\u201C'; data[25]['moreKeys'] = { 'characters': ['\u0022', '\u00AB']}; data[26]['text'] = '\u201D'; data[26]['moreKeys'] = { 'characters': ['\u0022', '\u00BB']}; data[27]['text'] = '\uff1a'; data[28]['text'] = '\uff1b'; data[29]['text'] = '\u2018'; data[29]['moreKeys'] = { 'characters': ['\u0027', '\u2039']}; data[30]['text'] = '\u2019'; data[30]['moreKeys'] = { 'characters': ['\u0027', '\u203a']}; data[33]['text'] = ' \u2014'; data[33]['moreKeys'] = undefined; data[35]['text'] = '\u2026'; data[35]['moreKeys'] = undefined; data[37]['text'] = '\uff0c'; data[38]['text'] = '\u3002'; return data; }; }); // goog.scope
32.507772
80
0.521039
3b644e96906838aaf30fc223b06501ade44150a4
138
js
JavaScript
app/app.js
jmccutchanwd/mushroom-mania
1cab2f7baf3db02205b4bbece6f88fe2f86a9730
[ "MIT" ]
null
null
null
app/app.js
jmccutchanwd/mushroom-mania
1cab2f7baf3db02205b4bbece6f88fe2f86a9730
[ "MIT" ]
null
null
null
app/app.js
jmccutchanwd/mushroom-mania
1cab2f7baf3db02205b4bbece6f88fe2f86a9730
[ "MIT" ]
null
null
null
/* John McCutchan ========================================= */ console.log('Begin'); const app = angular.module('Mushrooms', ['ngRoute'])
34.5
62
0.471014
3b6466e943ed78662ef3be469bbcbc0dbcb1fc99
1,903
js
JavaScript
iMusic bug test/plugins/script.js
hanslindetorp/iMusicXML
eedef7607c8e70757f628b32ffda57f38614e317
[ "MIT" ]
4
2017-09-05T05:32:20.000Z
2019-07-14T17:10:13.000Z
iMusic bug test/plugins/script.js
hanslindetorp/iMusicXML
eedef7607c8e70757f628b32ffda57f38614e317
[ "MIT" ]
null
null
null
iMusic bug test/plugins/script.js
hanslindetorp/iMusicXML
eedef7607c8e70757f628b32ffda57f38614e317
[ "MIT" ]
1
2021-05-28T00:04:02.000Z
2021-05-28T00:04:02.000Z
console.log("Mall 2021. Version 1.1"); iMus.debug = true; window.addEventListener("load", e => { let transitionTime = 1000; let navigateOnVideoEnd = e => { location.href = e.target.dataset.url; } // auto stop videos playing after `transitionTime` in current section // and remove any onended function document.querySelectorAll("a").forEach(el => { el.addEventListener("click", e => { let targetVideos = document.querySelectorAll(`${location.hash} video`); targetVideos.forEach(video => { video.removeEventListener("onended", navigateOnVideoEnd); }); setTimeout(() => { targetVideos.forEach(video => { video.pause(); }); }, transitionTime); }); }); // play specified video at specified time and navigate to // specified target onended document.querySelectorAll("a[data-video-play]").forEach(el => { let target = el.dataset.videoPlay.split(","); let url = target.pop(); let pos = target.pop(); let floatPos = parseFloat(pos); let videos = document.querySelectorAll(target.join(",")); videos.forEach(video => { video.dataset.url = url; video.addEventListener("ended", navigateOnVideoEnd); }); el.addEventListener("click", e => { videos.forEach(video => { video.pause(); video.currentTime = floatPos; video.play(); }); }); }); // stop specified video directly document.querySelectorAll("a[data-video-stop]").forEach(el => { el.addEventListener("click", e => { document.querySelectorAll(e.target.dataset.videoStop).forEach(video => { video.stop(); }); }); }); });
31.716667
84
0.547031
3b656d53e7fc690e42ab87969c75e52e355cc4ef
1,031
js
JavaScript
packages/chakra-ui/src/InputAddon/index.js
export-mike/chakra-ui
902cddcaafd9756bf9b9873a6cf121fee5eb703b
[ "MIT" ]
11
2020-03-30T20:56:44.000Z
2021-12-26T20:46:10.000Z
packages/chakra-ui/src/InputAddon/index.js
export-mike/chakra-ui
902cddcaafd9756bf9b9873a6cf121fee5eb703b
[ "MIT" ]
54
2020-02-27T16:18:45.000Z
2021-08-02T07:52:04.000Z
packages/chakra-ui/src/InputAddon/index.js
export-mike/chakra-ui
902cddcaafd9756bf9b9873a6cf121fee5eb703b
[ "MIT" ]
5
2020-10-06T14:23:28.000Z
2021-12-22T11:56:39.000Z
/** @jsx jsx */ import { jsx } from "@emotion/core"; import Box from "../Box"; import useInputStyle from "../Input/styles"; import { useColorMode } from "../ColorModeProvider"; const InputAddon = ({ placement = "left", size = "md", ...props }) => { const { colorMode } = useColorMode(); const bg = { dark: "whiteAlpha.300", light: "gray.100" }; const _placement = { left: { mr: "-1px", roundedRight: 0, borderRightColor: "transparent", }, right: { order: 1, roundedLeft: 0, borderLeftColor: "transparent", }, }; const styleProps = { ...useInputStyle({ size, variant: "outline" }), flex: "0 0 auto", whiteSpace: "nowrap", bg: bg[colorMode], ..._placement[placement], }; return <Box {...styleProps} {...props} />; }; const InputLeftAddon = props => <InputAddon placement="left" {...props} />; const InputRightAddon = props => <InputAddon placement="right" {...props} />; export { InputLeftAddon, InputRightAddon }; export default InputAddon;
26.435897
77
0.606208
3b65a52f42d4a77f3bcf5095833fc0d512a87ecc
91
js
JavaScript
react-bootstrap/AffixMixin.js
u9520107/component-react-bootstrap
2fe74d4954a0a1492817c6aedc7c6ef537fd8cbe
[ "MIT" ]
null
null
null
react-bootstrap/AffixMixin.js
u9520107/component-react-bootstrap
2fe74d4954a0a1492817c6aedc7c6ef537fd8cbe
[ "MIT" ]
null
null
null
react-bootstrap/AffixMixin.js
u9520107/component-react-bootstrap
2fe74d4954a0a1492817c6aedc7c6ef537fd8cbe
[ "MIT" ]
null
null
null
var AffixMixin = require('./transpiled/AffixMixin')['default']; module.exports = AffixMixin
45.5
63
0.769231
3b670134603a9e1e68f449c5a585482b39df521f
6,212
js
JavaScript
src/core_modules/capture-core/components/Pages/NewRelationship/TeiRelationship/TeiRelationship.component.js
karolinelien/capture-app
717eafd38d10450a661445dfc59fc5270ff12d6a
[ "BSD-2-Clause" ]
null
null
null
src/core_modules/capture-core/components/Pages/NewRelationship/TeiRelationship/TeiRelationship.component.js
karolinelien/capture-app
717eafd38d10450a661445dfc59fc5270ff12d6a
[ "BSD-2-Clause" ]
null
null
null
src/core_modules/capture-core/components/Pages/NewRelationship/TeiRelationship/TeiRelationship.component.js
karolinelien/capture-app
717eafd38d10450a661445dfc59fc5270ff12d6a
[ "BSD-2-Clause" ]
null
null
null
// @flow import * as React from 'react'; import i18n from '@dhis2/d2-i18n'; import SearchIcon from '@material-ui/icons/Search'; import AddIcon from '@material-ui/icons/AddCircleOutline'; import withStyles from '@material-ui/core/styles/withStyles'; import type { SelectedRelationshipType } from '../newRelationship.types'; import Button from '../../../Buttons/Button.component'; import TeiSearch from '../../../TeiSearch/TeiSearch.container'; import TeiRelationshipSearchResults from './SearchResults/TeiRelationshipSearchResults.component'; import { makeTrackedEntityTypeSelector } from './teiRelationship.selectors'; import { TrackedEntityType } from '../../../../metaData'; import { findModes } from '../findModes'; import withDefaultNavigation from '../../../Pagination/withDefaultNavigation'; import withPaginationData from './SearchResults/withPaginationData'; import getTeiDisplayName from '../../../../trackedEntityInstances/getDisplayName'; import { RegisterTei } from '../RegisterTei'; const SearchResultsWithPager = withPaginationData()(withDefaultNavigation()(TeiRelationshipSearchResults)); type Props = { findMode?: ?$Values<typeof findModes>, onOpenSearch: (trackedEntityTypeId: string, programId: ?string) => void, onSelectFindMode: (findMode: $Values<typeof findModes>) => void, onAddRelationship: (entity: Object) => void, selectedRelationshipType: SelectedRelationshipType, classes: { container: string, button: string, buttonIcon: string, modeSelectionsContainer: string, }, onGetUnsavedAttributeValues?: ?Function, } const getStyles = theme => ({ modeSelectionsContainer: { display: 'flex', }, button: { height: theme.typography.pxToRem(150), width: theme.typography.pxToRem(250), margin: theme.typography.pxToRem(10), padding: theme.typography.pxToRem(10), display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', backgroundColor: theme.palette.grey.lighter, }, buttonIcon: { flexGrow: 1, fontSize: theme.typography.pxToRem(80), }, }); const defaultTrackedEntityTypeName = 'Tracked entity instance'; class TeiRelationship extends React.Component<Props> { trackedEntityTypeSelector: (props: Props) => TrackedEntityType; constructor(props: Props) { super(props); this.trackedEntityTypeSelector = makeTrackedEntityTypeSelector(); } getTrackedEntityTypeName = () => { const trackedEntityType = this.trackedEntityTypeSelector(this.props); if (!trackedEntityType) { return defaultTrackedEntityTypeName; } return trackedEntityType.name; } handleAddRelationship = (teiId: string, values: Object) => { const trackedEntityType = this.trackedEntityTypeSelector(this.props); this.props.onAddRelationship({ id: teiId, name: getTeiDisplayName(values, trackedEntityType.attributes, trackedEntityType.name), }); } handleAddRelationshipWithNewTei = (itemId: string, dataEntryId: string) => { this.props.onAddRelationship({ itemId, dataEntryId, }); } renderModeSelections = () => { const { classes } = this.props; const trackedEntityTypeName = this.getTrackedEntityTypeName(); return ( <div className={classes.modeSelectionsContainer} > <div className={classes.button}> <SearchIcon fontSize="large" className={classes.buttonIcon} /> <Button color="primary" onClick={() => this.props.onSelectFindMode(findModes.TEI_SEARCH)} > {i18n.t( 'Link to an existing {{trackedEntityType}}', { trackedEntityType: trackedEntityTypeName }, )} </Button> </div> <div className={classes.button}> <AddIcon className={classes.buttonIcon} /> <Button color="primary" onClick={() => this.props.onSelectFindMode(findModes.TEI_REGISTER)} > {i18n.t('Create new {{trackedEntityType}}', { trackedEntityType: trackedEntityTypeName })} </Button> </div> </div> ); } renderSearch = (props: Object) => { const { selectedRelationshipType, onAddRelationship, ...passOnProps } = props; const trackedEntityTypeName = this.getTrackedEntityTypeName(); return ( <TeiSearch id="relationshipTeiSearch" getResultsView={viewProps => ( <SearchResultsWithPager onAddRelationship={this.handleAddRelationship} trackedEntityTypeName={trackedEntityTypeName} {...viewProps} /> )} {...passOnProps} /> ); } renderRegister = () => ( <RegisterTei onLink={this.handleAddRelationship} onSave={this.handleAddRelationshipWithNewTei} onGetUnsavedAttributeValues={this.props.onGetUnsavedAttributeValues} /> ); renderByMode = (findMode, props) => { if (findMode === findModes.TEI_SEARCH) { return this.renderSearch(props); } if (findMode === findModes.TEI_REGISTER) { return this.renderRegister(); } return null; } render() { const { classes, findMode, onOpenSearch, onSelectFindMode, ...passOnProps } = this.props; return ( <div className={classes.container}> {findMode ? this.renderByMode(findMode, passOnProps) : this.renderModeSelections() } </div> ); } } export default withStyles(getStyles)(TeiRelationship);
35.295455
114
0.592885
3b680a104fa9b52e6489fe8b70a04245d52175d9
14,380
js
JavaScript
src/core/ui5ApiFormatter.js
wozjac/brackets-ui5
2199a53e09e2e72757d40085dc26e9ccf5228172
[ "MIT" ]
4
2018-06-03T14:01:28.000Z
2021-01-09T01:22:25.000Z
src/core/ui5ApiFormatter.js
wozjac/brackets-ui5
2199a53e09e2e72757d40085dc26e9ccf5228172
[ "MIT" ]
1
2019-08-08T22:39:59.000Z
2019-08-08T22:39:59.000Z
src/core/ui5ApiFormatter.js
wozjac/brackets-ui5
2199a53e09e2e72757d40085dc26e9ccf5228172
[ "MIT" ]
null
null
null
define((require, exports) => { "use strict"; const codeEditor = require("src/editor/codeEditor"), constants = require("src/core/constants"), ui5ApiService = require("src/core/ui5ApiService"); function getFormattedObjectApi(ui5ObjectApi, cleanHtml = false, inheritedAsArray = false, flatStatic = false) { const api = { name: ui5ObjectApi.name, extends: ui5ObjectApi.extends, apiDocUrl: ui5ObjectApi.apiDocUrl, isDeprecated: false, hasMethods: false, hasEvents: false, hasConstructor: false, hasConstructorParams: false, hasProperties: false, hasInheritedMethods: false, hasBaseObject: false, hasAggregations: false }; api.description = codeEditor.formatJsDoc(ui5ObjectApi.description, cleanHtml); if (ui5ObjectApi.extends) { api.hasBaseObject = true; } if (ui5ObjectApi.methods) { api.hasMethods = true; api.methods = ui5ObjectApi.methods.filter((element) => { return element.visibility === "public"; }); api.methods = JSON.parse(JSON.stringify(api.methods)); api.methods.forEach((method) => { method.objectName = ui5ObjectApi.name; method.description = codeEditor.formatJsDoc(method.description, cleanHtml); if (method.deprecated) { method.description = `[DEPRECATED! ${codeEditor.formatJsDoc(method.deprecated.text, true)}] ${method.description}`; } if (method.static) { if (flatStatic === true) { method.name = method.name; } else { method.name = `${ui5ObjectApi.name}.${method.name}`; } } if (method.parameters) { prepareParameters(method, cleanHtml); } let path = method.name; if (path.indexOf("module:") !== -1) { path = path.replace("module:", ""); path = encodeURIComponent(path); } if (method.returnValue && method.returnValue.type) { const returnType = method.returnValue.type.replace("[]", ""); const returnObject = ui5ApiService.getUi5Objects()[returnType]; if (returnObject) { method.hasUi5ObjectReturnType = true; method.ui5ObjectReturnType = returnType; } else { method.hasUi5ObjectReturnType = false; } } method.apiDocUrl = `${ui5ObjectApi.apiDocUrl}/methods/${path}`; }); } if (ui5ObjectApi.events) { api.hasEvents = true; api.events = ui5ObjectApi.events.filter((element) => { return element.visibility === "public"; }); api.events = JSON.parse(JSON.stringify(api.events)); api.events.forEach((event) => { event.objectName = ui5ObjectApi.name; event.description = codeEditor.formatJsDoc(event.description, cleanHtml); if (event.deprecated) { event.description = `[DEPRECATED! ${codeEditor.formatJsDoc(event.deprecated.text, true)}] ${event.description}`; } if (event.parameters) { prepareParameters(event, cleanHtml); } event.apiDocUrl = `${ui5ObjectApi.apiDocUrl}/events/${event.name}`; }); } let properties; switch (ui5ObjectApi.kind) { case "class": try { properties = ui5ObjectApi["ui5-metadata"].properties; } catch (error) { properties = []; } if (ui5ObjectApi.hasOwnProperty("constructor")) { api.hasConstructor = true; api.constructor = JSON.parse(JSON.stringify(ui5ObjectApi.constructor)); api.constructor.description = codeEditor.formatJsDoc(api.constructor.description, cleanHtml); if (ui5ObjectApi.constructor.parameters) { api.hasConstructorParams = true; api.constructorParams = JSON.parse(JSON.stringify(ui5ObjectApi.constructor.parameters)); api.constructorParams.forEach((param) => { param.description = codeEditor.formatJsDoc(param.description, cleanHtml); param.objectName = ui5ObjectApi.name; if (param.parameterProperties) { param.hasProperties = true; param.parameterProperties = JSON.parse(JSON.stringify(param.parameterProperties)); const properties = []; for (const prop in param.parameterProperties) { const parameterProperty = param.parameterProperties[prop]; parameterProperty.description = codeEditor.formatJsDoc(parameterProperty.description, cleanHtml); parameterProperty.objectName = ui5ObjectApi.name; properties.push(parameterProperty); } param.parameterProperties = properties; } }); } } break; case "enum": case "namespace": properties = ui5ObjectApi.properties; break; } if (properties && properties.length > 0) { properties = properties.filter((property) => { return property.visibility === "public"; }); api.hasProperties = true; api.properties = JSON.parse(JSON.stringify(properties)); api.properties.forEach((property) => { if (!property.type || property.type === "undefined") { property.type = ""; } else { const theType = property.type.replace("[]", ""); const typeObject = ui5ApiService.getUi5Objects()[theType]; if (typeObject) { property.hasUi5ObjectType = true; property.ui5ObjectType = theType; } else { property.hasUi5ObjectType = false; } } property.objectName = ui5ObjectApi.name; property.description = codeEditor.formatJsDoc(property.description, cleanHtml); if (property.deprecated) { property.description = `[DEPRECATED! ${codeEditor.formatJsDoc(property.deprecated.text, true)}] ${property.description}`; } property.apiDocUrl = `${ui5ObjectApi.apiDocUrl}/controlProperties`; }); } if (ui5ObjectApi.deprecated) { api.isDeprecated = true; } if (ui5ObjectApi["ui5-metadata"] && ui5ObjectApi["ui5-metadata"].aggregations) { api.hasAggregations = true; api.aggregations = ui5ObjectApi["ui5-metadata"].aggregations.filter((element) => { return element.visibility === "public"; }); api.aggregations = JSON.parse(JSON.stringify(api.aggregations)); api.aggregations.forEach((aggregation) => { aggregation.objectName = ui5ObjectApi.name; const theType = aggregation.type.replace("[]", ""); const typeObject = ui5ApiService.getUi5Objects()[theType]; if (typeObject) { aggregation.hasUi5ObjectType = true; aggregation.ui5ObjectType = theType; } else { aggregation.hasUi5ObjectType = false; } aggregation.description = codeEditor.formatJsDoc(aggregation.description, cleanHtml); aggregation.apiDocUrl = `${ui5ObjectApi.apiDocUrl}/aggregations`; }); } if (ui5ObjectApi.inheritedApi) { api.inheritedApi = {}; for (const objectKey in ui5ObjectApi.inheritedApi) { api.inheritedApi[objectKey] = getFormattedObjectApi(ui5ObjectApi.inheritedApi[objectKey], cleanHtml); if (ui5ObjectApi.inheritedApi[objectKey].methods) { api.hasInheritedMethods = true; } } } if (inheritedAsArray === true) { const inheritedApiAsArray = []; let inheritedObject; for (const objectName in api.inheritedApi) { inheritedObject = api.inheritedApi[objectName]; inheritedApiAsArray.push(inheritedObject); } api.inheritedApi = inheritedApiAsArray; } return api; } function prepareParameters(object, cleanHtml) { object.parameters.forEach((parameter) => { parameter.description = codeEditor.formatJsDoc(parameter.description, cleanHtml); if (parameter.parameterProperties) { const paramProperties = []; for (const p in parameter.parameterProperties) { const param = parameter.parameterProperties[p]; param.name = p; param.description = codeEditor.formatJsDoc(param.description, cleanHtml); paramProperties.push(param); } parameter.parameterProperties = paramProperties; } }); } function filterApiMembers(ui5ObjectApi, memberSearchString, memberGroupFilter) { const objectApi = JSON.parse(JSON.stringify(ui5ObjectApi)); function filterMembers(key1, key2) { let filterable; if (key2) { filterable = objectApi[key1][key2]; } else { filterable = objectApi[key1]; } if (filterable) { return filterable.filter((member) => { if (member.visibility !== "public") { return false; } return new RegExp(memberSearchString, "i").test(member.name); }); } } const filterableKeys = ["methods", "events", "properties", "aggregations"]; if (memberSearchString) { for (const key of filterableKeys) { if (objectApi.kind === "class" && (key === "properties" || key === "aggregations")) { objectApi["ui5-metadata"][key] = filterMembers("ui5-metadata", key); if (!objectApi["ui5-metadata"][key] || (objectApi["ui5-metadata"][key] && objectApi["ui5-metadata"][key].length === 0)) { delete objectApi["ui5-metadata"][key]; } } else { objectApi[key] = filterMembers(key); if (!objectApi[key] || (objectApi[key] && objectApi[key].length === 0)) { delete objectApi[key]; } } } delete objectApi.constructor; } if (memberGroupFilter) { const deleteMarkers = { properties: true, methods: true, events: true, aggregations: true, construct: true }; switch (memberGroupFilter) { case constants.memberGroupFilter.aggregations: deleteMarkers.aggregations = false; break; case constants.memberGroupFilter.methods: deleteMarkers.methods = false; break; case constants.memberGroupFilter.properties: deleteMarkers.properties = false; break; case constants.memberGroupFilter.events: deleteMarkers.events = false; break; case constants.memberGroupFilter.construct: deleteMarkers.construct = false; break; } _deleteMembers(objectApi, deleteMarkers); } if (objectApi.inheritedApi) { for (const name in objectApi.inheritedApi) { objectApi.inheritedApi[name] = filterApiMembers(objectApi.inheritedApi[name], memberSearchString, memberGroupFilter); } } return objectApi; } function _deleteMembers(objectApi, deleteMarkers) { if (deleteMarkers.properties === true) { if (objectApi.kind === "class") { delete objectApi["ui5-metadata"].properties; } else { delete objectApi.properties; } } if (deleteMarkers.aggregations === true) { if (objectApi.kind === "class") { delete objectApi["ui5-metadata"].aggregations; } else { delete objectApi.aggregations; } } if (deleteMarkers.events === true) { delete objectApi.events; } if (deleteMarkers.methods === true) { delete objectApi.methods; } if (deleteMarkers.construct === true) { delete objectApi.constructor; } } function convertModuleNameToPath(moduleName) { return moduleName.replace("module:", "").replace(/\//g, "."); } exports.getFormattedObjectApi = getFormattedObjectApi; exports.filterApiMembers = filterApiMembers; exports.convertModuleNameToPath = convertModuleNameToPath; });
36.0401
142
0.509318
3b681a47fc492ed906ac7050dd56d2bc621a514c
1,194
js
JavaScript
src/setter.js
devebot/envcloak
55d3285fa1fb5f88b06bb7df969548dbf890f54d
[ "MIT" ]
null
null
null
src/setter.js
devebot/envcloak
55d3285fa1fb5f88b06bb7df969548dbf890f54d
[ "MIT" ]
null
null
null
src/setter.js
devebot/envcloak
55d3285fa1fb5f88b06bb7df969548dbf890f54d
[ "MIT" ]
null
null
null
'use strict'; function Constructor(kwargs = {}) { const _store = {}; this.setup = function(vars) { vars = vars || {}; Object.keys(vars).forEach(function(key) { _store[key] = process.env[key]; if (vars[key] == null) { delete process.env[key]; } else { process.env[key] = vars[key]; } }); return this; } this.reset = function() { Object.keys(_store).forEach(function(key) { delete process.env[key]; if (typeof(_store[key]) === 'string') { process.env[key] = _store[key]; } delete _store[key]; }); return this; } this.toJSON = function() { let info = { variables: [] }; for (let key in _store) { info.variables.push({ name: key, backup: _store[key], value: process.env[key] }); } return info; } this.toString = function() { return JSON.stringify(this.toJSON()); } return this.setup(kwargs.presets); } module.exports = Constructor; let _instance = null; Object.defineProperty(Constructor, 'instance', { get: function() { return (_instance = _instance || new Constructor()); }, set: function(val) {} });
20.237288
56
0.561977
3b6820caac67064d8febebfa1fb6e7bd99cbcf17
20,112
js
JavaScript
test/tx-test.js
rdewilde-ion/ioncoin
996c00621058774e3befc91f8b3d640bc080a38d
[ "MIT" ]
1
2018-02-19T01:23:56.000Z
2018-02-19T01:23:56.000Z
test/tx-test.js
rdewilde-ion/ioncoin
996c00621058774e3befc91f8b3d640bc080a38d
[ "MIT" ]
null
null
null
test/tx-test.js
rdewilde-ion/ioncoin
996c00621058774e3befc91f8b3d640bc080a38d
[ "MIT" ]
null
null
null
/* eslint-env mocha */ /* eslint prefer-arrow-callback: "off" */ 'use strict'; const assert = require('assert'); const util = require('../lib/utils/util'); const encoding = require('../lib/utils/encoding'); const random = require('../lib/crypto/random'); const consensus = require('../lib/protocol/consensus'); const TX = require('../lib/primitives/tx'); const Coin = require('../lib/primitives/coin'); const Output = require('../lib/primitives/output'); const Outpoint = require('../lib/primitives/outpoint'); const Script = require('../lib/script/script'); const Witness = require('../lib/script/witness'); const Input = require('../lib/primitives/input'); const CoinView = require('../lib/coins/coinview'); const KeyRing = require('../lib/primitives/keyring'); const common = require('./util/common'); const opcodes = Script.opcodes; const validTests = require('./data/tx-valid.json'); const invalidTests = require('./data/tx-invalid.json'); const sighashTests = require('./data/sighash-tests.json'); const tx1 = common.parseTX('data/tx1.hex'); const tx2 = common.parseTX('data/tx2.hex'); const tx3 = common.parseTX('data/tx3.hex'); const tx4 = common.parseTX('data/tx4.hex'); const tx5 = common.parseTX('data/tx5.hex'); const tx6 = common.parseTX('data/tx6.hex'); const tx7 = common.parseTX('data/tx7.hex'); const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; const MAX_SAFE_ADDITION = 0xfffffffffffff; function clearCache(tx, noCache) { if (!noCache) { assert.strictEqual(tx.hash('hex'), tx.clone().hash('hex')); return; } tx.refresh(); } function parseTXTest(data) { const [coins, hex, names] = data; let flags = 0; for (const name of (names || '').trim().split(/,\s*/)) { const flag = `VERIFY_${name}`; assert(Script.flags[flag] != null, 'Unknown flag.'); flags |= Script.flags[flag]; } const view = new CoinView(); for (const [txid, index, str, amount] of coins) { const hash = util.revHex(txid); const script = Script.fromString(str); const value = parseInt(amount || '0', 10); if (index === -1) continue; const coin = new Coin({ version: 1, height: -1, coinbase: false, hash: hash, index: index, script: script, value: value }); view.addCoin(coin); } const raw = Buffer.from(hex, 'hex'); const tx = TX.fromRaw(raw); const coin = view.getOutputFor(tx.inputs[0]); return { tx: tx, flags: flags, view: view, comments: coin ? util.inspectify(coin.script, false) : 'coinbase', data: data }; } function parseSighashTest(data) { const [txHex, scriptHex, index, type, hash] = data; const tx = TX.fromRaw(txHex, 'hex'); const script = Script.fromRaw(scriptHex, 'hex'); const expected = util.revHex(hash); let hex = type & 3; if (type & 0x80) hex |= 0x80; hex = hex.toString(16); if (hex.length % 2 !== 0) hex = '0' + hex; return { tx: tx, script: script, index: index, type: type, hash: hash, expected: expected, hex: hex }; } function createInput(value, view) { const hash = random.randomBytes(32).toString('hex'); const input = { prevout: { hash: hash, index: 0 } }; const output = new Output(); output.value = value; if (!view) view = new CoinView(); view.addOutput(new Outpoint(hash, 0), output); return [input, view]; }; function sigopContext(scriptSig, witness, scriptPubkey) { const fund = new TX(); { fund.version = 1; const input = new Input(); fund.inputs.push(input); const output = new Output(); output.value = 1; output.script = scriptPubkey; fund.outputs.push(output); fund.refresh(); } const spend = new TX(); { spend.version = 1; const input = new Input(); input.prevout.hash = fund.hash('hex'); input.prevout.index = 0; input.script = scriptSig; input.witness = witness; spend.inputs.push(input); const output = new Output(); output.value = 1; spend.outputs.push(output); spend.refresh(); } const view = new CoinView(); view.addTX(fund, 0); return { fund: fund, spend: spend, view: view }; } describe('TX', function() { for (const noCache of [false, true]) { const suffix = noCache ? 'without cache' : 'with cache'; it(`should verify non-minimal output ${suffix}`, () => { const {tx, view} = tx1; clearCache(tx, noCache); assert(tx.verify(view, Script.flags.VERIFY_P2SH)); }); it(`should verify tx.version == 0 ${suffix}`, () => { const {tx, view} = tx2; clearCache(tx, noCache); assert(tx.verify(view, Script.flags.VERIFY_P2SH)); }); it(`should verify sighash_single bug w/ findanddelete ${suffix}`, () => { const {tx, view} = tx3; clearCache(tx, noCache); assert(tx.verify(view, Script.flags.VERIFY_P2SH)); }); it(`should verify high S value with only DERSIG enabled ${suffix}`, () => { const {tx, view} = tx4; const coin = view.getOutputFor(tx.inputs[0]); const flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_DERSIG; clearCache(tx, noCache); assert(tx.verifyInput(0, coin, flags)); }); it(`should parse witness tx properly ${suffix}`, () => { const {tx} = tx5; clearCache(tx, noCache); assert.strictEqual(tx.inputs.length, 5); assert.strictEqual(tx.outputs.length, 1980); assert(tx.hasWitness()); assert.notStrictEqual(tx.hash('hex'), tx.witnessHash('hex')); assert.strictEqual(tx.witnessHash('hex'), '088c919cd8408005f255c411f786928385688a9e8fdb2db4c9bc3578ce8c94cf'); assert.strictEqual(tx.getSize(), 62138); assert.strictEqual(tx.getVirtualSize(), 61813); assert.strictEqual(tx.getWeight(), 247250); const raw1 = tx.toRaw(); clearCache(tx, true); const raw2 = tx.toRaw(); assert.deepStrictEqual(raw1, raw2); const tx2 = TX.fromRaw(raw2); clearCache(tx2, noCache); assert.strictEqual(tx.hash('hex'), tx2.hash('hex')); assert.strictEqual(tx.witnessHash('hex'), tx2.witnessHash('hex')); }); it(`should verify the coolest tx ever sent ${suffix}`, () => { const {tx, view} = tx6; clearCache(tx, noCache); assert(tx.verify(view, Script.flags.VERIFY_NONE)); }); it(`should verify a historical transaction ${suffix}`, () => { const {tx, view} = tx7; clearCache(tx, noCache); assert(tx.verify(view)); }); for (const tests of [validTests, invalidTests]) { let comment = ''; for (const json of tests) { if (json.length === 1) { comment += ' ' + json[0]; continue; } const data = parseTXTest(json); const {tx, view, flags} = data; const comments = comment.trim() || data.comments; comment = ''; if (tests === validTests) { if (comments.indexOf('Coinbase') === 0) { it(`should handle valid tx test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(tx.isSane()); }); continue; } it(`should handle valid tx test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(tx.verify(view, flags)); }); } else { if (comments === 'Duplicate inputs') { it(`should handle invalid tx test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(tx.verify(view, flags)); assert.ok(!tx.isSane()); }); continue; } if (comments === 'Negative output') { it(`should handle invalid tx test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(tx.verify(view, flags)); assert.ok(!tx.isSane()); }); continue; } if (comments.indexOf('Coinbase') === 0) { it(`should handle invalid tx test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(!tx.isSane()); }); continue; } it(`should handle invalid tx test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(!tx.verify(view, flags)); }); } } } for (const json of sighashTests) { if (json.length === 1) continue; const test = parseSighashTest(json); const {tx, script, index, type} = test; const {hash, hex, expected} = test; clearCache(tx, noCache); it(`should get sighash of ${hash} (${hex}) ${suffix}`, () => { const subscript = script.getSubscript(0).removeSeparators(); const hash = tx.signatureHash(index, subscript, 0, type, 0); assert.strictEqual(hash.toString('hex'), expected); }); } } it('should fail on >51 bit coin values', () => { const [input, view] = createInput(consensus.MAX_MONEY + 1); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: consensus.MAX_MONEY }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should handle 51 bit coin values', () => { const [input, view] = createInput(consensus.MAX_MONEY); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: consensus.MAX_MONEY }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(tx.verifyInputs(view, 0)); }); it('should fail on >51 bit output values', () => { const [input, view] = createInput(consensus.MAX_MONEY); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: consensus.MAX_MONEY + 1 }], locktime: 0 }); assert.ok(!tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should handle 51 bit output values', () => { const [input, view] = createInput(consensus.MAX_MONEY); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: consensus.MAX_MONEY }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(tx.verifyInputs(view, 0)); }); it('should fail on >51 bit fees', () => { const [input, view] = createInput(consensus.MAX_MONEY + 1); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: 0 }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should fail on >51 bit values from multiple', () => { const view = new CoinView(); const tx = new TX({ version: 1, inputs: [ createInput(Math.floor(consensus.MAX_MONEY / 2), view)[0], createInput(Math.floor(consensus.MAX_MONEY / 2), view)[0], createInput(Math.floor(consensus.MAX_MONEY / 2), view)[0] ], outputs: [{ script: [], value: consensus.MAX_MONEY }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should fail on >51 bit output values from multiple', () => { const [input, view] = createInput(consensus.MAX_MONEY); const tx = new TX({ version: 1, inputs: [input], outputs: [ { script: [], value: Math.floor(consensus.MAX_MONEY / 2) }, { script: [], value: Math.floor(consensus.MAX_MONEY / 2) }, { script: [], value: Math.floor(consensus.MAX_MONEY / 2) } ], locktime: 0 }); assert.ok(!tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should fail on >51 bit fees from multiple', () => { const view = new CoinView(); const tx = new TX({ version: 1, inputs: [ createInput(Math.floor(consensus.MAX_MONEY / 2), view)[0], createInput(Math.floor(consensus.MAX_MONEY / 2), view)[0], createInput(Math.floor(consensus.MAX_MONEY / 2), view)[0] ], outputs: [{ script: [], value: 0 }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should fail to parse >53 bit values', () => { const [input] = createInput(Math.floor(consensus.MAX_MONEY / 2)); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: 0xdeadbeef }], locktime: 0 }); let raw = tx.toRaw(); assert.strictEqual(encoding.readU64(raw, 47), 0xdeadbeef); raw[54] = 0x7f; assert.throws(() => TX.fromRaw(raw)); tx.outputs[0].value = 0; tx.refresh(); raw = tx.toRaw(); assert.strictEqual(encoding.readU64(raw, 47), 0x00); raw[54] = 0x80; assert.throws(() => TX.fromRaw(raw)); }); it('should fail on 53 bit coin values', () => { const [input, view] = createInput(MAX_SAFE_INTEGER); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: consensus.MAX_MONEY }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should fail on 53 bit output values', () => { const [input, view] = createInput(consensus.MAX_MONEY); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: MAX_SAFE_INTEGER }], locktime: 0 }); assert.ok(!tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should fail on 53 bit fees', () => { const [input, view] = createInput(MAX_SAFE_INTEGER); const tx = new TX({ version: 1, inputs: [input], outputs: [{ script: [], value: 0 }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); [MAX_SAFE_ADDITION, MAX_SAFE_INTEGER].forEach((MAX) => { it('should fail on >53 bit values from multiple', () => { const view = new CoinView(); const tx = new TX({ version: 1, inputs: [ createInput(MAX, view)[0], createInput(MAX, view)[0], createInput(MAX, view)[0] ], outputs: [{ script: [], value: consensus.MAX_MONEY }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should fail on >53 bit output values from multiple', () => { const [input, view] = createInput(consensus.MAX_MONEY); const tx = new TX({ version: 1, inputs: [input], outputs: [ { script: [], value: MAX }, { script: [], value: MAX }, { script: [], value: MAX } ], locktime: 0 }); assert.ok(!tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); it('should fail on >53 bit fees from multiple', () => { const view = new CoinView(); const tx = new TX({ version: 1, inputs: [ createInput(MAX, view)[0], createInput(MAX, view)[0], createInput(MAX, view)[0] ], outputs: [{ script: [], value: 0 }], locktime: 0 }); assert.ok(tx.isSane()); assert.ok(!tx.verifyInputs(view, 0)); }); }); it('should count sigops for multisig', () => { const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; const key = KeyRing.generate(); const pub = key.publicKey; const output = Script.fromMultisig(1, 2, [pub, pub]); const input = new Script([ opcodes.OP_0, opcodes.OP_0 ]); const witness = new Witness(); const ctx = sigopContext(input, witness, output); assert.strictEqual(ctx.spend.getSigopsCost(ctx.view, flags), 0); assert.strictEqual(ctx.fund.getSigopsCost(ctx.view, flags), consensus.MAX_MULTISIG_PUBKEYS * consensus.WITNESS_SCALE_FACTOR); }); it('should count sigops for p2sh multisig', () => { const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; const key = KeyRing.generate(); const pub = key.publicKey; const redeem = Script.fromMultisig(1, 2, [pub, pub]); const output = Script.fromScripthash(redeem.hash160()); const input = new Script([ opcodes.OP_0, opcodes.OP_0, redeem.toRaw() ]); const witness = new Witness(); const ctx = sigopContext(input, witness, output); assert.strictEqual(ctx.spend.getSigopsCost(ctx.view, flags), 2 * consensus.WITNESS_SCALE_FACTOR); }); it('should count sigops for p2wpkh', () => { const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; const key = KeyRing.generate(); const witness = new Witness([ Buffer.from([0]), Buffer.from([0]) ]); const input = new Script(); { const output = Script.fromProgram(0, key.getKeyHash()); const ctx = sigopContext(input, witness, output); assert.strictEqual(ctx.spend.getSigopsCost(ctx.view, flags), 1); assert.strictEqual( ctx.spend.getSigopsCost(ctx.view, flags & ~Script.flags.VERIFY_WITNESS), 0); } { const output = Script.fromProgram(1, key.getKeyHash()); const ctx = sigopContext(input, witness, output); assert.strictEqual(ctx.spend.getSigopsCost(ctx.view, flags), 0); } { const output = Script.fromProgram(0, key.getKeyHash()); const ctx = sigopContext(input, witness, output); ctx.spend.inputs[0].prevout.hash = encoding.NULL_HASH; ctx.spend.inputs[0].prevout.index = 0xffffffff; ctx.spend.refresh(); assert.strictEqual(ctx.spend.getSigopsCost(ctx.view, flags), 0); } }); it('should count sigops for nested p2wpkh', () => { const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; const key = KeyRing.generate(); const redeem = Script.fromProgram(0, key.getKeyHash()); const output = Script.fromScripthash(redeem.hash160()); const input = new Script([ redeem.toRaw() ]); const witness = new Witness([ Buffer.from([0]), Buffer.from([0]) ]); const ctx = sigopContext(input, witness, output); assert.strictEqual(ctx.spend.getSigopsCost(ctx.view, flags), 1); }); it('should count sigops for p2wsh', () => { const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; const key = KeyRing.generate(); const pub = key.publicKey; const redeem = Script.fromMultisig(1, 2, [pub, pub]); const output = Script.fromProgram(0, redeem.sha256()); const input = new Script(); const witness = new Witness([ Buffer.from([0]), Buffer.from([0]), redeem.toRaw() ]); const ctx = sigopContext(input, witness, output); assert.strictEqual(ctx.spend.getSigopsCost(ctx.view, flags), 2); assert.strictEqual( ctx.spend.getSigopsCost(ctx.view, flags & ~Script.flags.VERIFY_WITNESS), 0); }); it('should count sigops for nested p2wsh', () => { const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; const key = KeyRing.generate(); const pub = key.publicKey; const wscript = Script.fromMultisig(1, 2, [pub, pub]); const redeem = Script.fromProgram(0, wscript.sha256()); const output = Script.fromScripthash(redeem.hash160()); const input = new Script([ redeem.toRaw() ]); const witness = new Witness([ Buffer.from([0]), Buffer.from([0]), wscript.toRaw() ]); const ctx = sigopContext(input, witness, output); assert.strictEqual(ctx.spend.getSigopsCost(ctx.view, flags), 2); }); });
26.221643
80
0.569411
3b683592e7ad0594082af7df7622a44ffe307cdb
799
js
JavaScript
src/day15.js
irisfffff/advent-of-code-2020
2ddca59b2d9fd798469c8a1afd236f371e384c33
[ "MIT" ]
null
null
null
src/day15.js
irisfffff/advent-of-code-2020
2ddca59b2d9fd798469c8a1afd236f371e384c33
[ "MIT" ]
null
null
null
src/day15.js
irisfffff/advent-of-code-2020
2ddca59b2d9fd798469c8a1afd236f371e384c33
[ "MIT" ]
null
null
null
const readFile = require('./inputReader') const input = readFile('./resources/day15')[0].split(',').map(item => parseInt(item)) const memoryGame = (turnLimit) => { const spoken = new Map() // spoken number: turnOld input.forEach((number, idx) => spoken.set(number, idx + 1)) let prev = input[input.length - 1] spoken.delete(prev) let newSpoken for (let turn = input.length + 1; turn <= turnLimit; turn ++) { if (spoken.has(prev)) { newSpoken = turn - 1 - spoken.get(prev) } else { newSpoken = 0 } spoken.set(prev, turn - 1) prev = newSpoken } return newSpoken } const task1 = () => { console.log(memoryGame(2020)) } const task2 = () => { console.log(memoryGame(30000000)) } task1() task2()
24.212121
85
0.579474
3b68785f5892d80a76b9cf6204b5a153e9c48e4a
22,170
js
JavaScript
unlock-app/src/__tests__/middlewares/walletMiddleware.test.js
OIEIEIO/unlock
fafd1a256a56ec5eab1ba9c706068620389c43ba
[ "MIT" ]
null
null
null
unlock-app/src/__tests__/middlewares/walletMiddleware.test.js
OIEIEIO/unlock
fafd1a256a56ec5eab1ba9c706068620389c43ba
[ "MIT" ]
null
null
null
unlock-app/src/__tests__/middlewares/walletMiddleware.test.js
OIEIEIO/unlock
fafd1a256a56ec5eab1ba9c706068620389c43ba
[ "MIT" ]
null
null
null
import EventEmitter from 'events' import walletMiddleware from '../../middlewares/walletMiddleware' import { CREATE_LOCK, DELETE_LOCK, WITHDRAW_FROM_LOCK, UPDATE_LOCK_KEY_PRICE, UPDATE_LOCK, } from '../../actions/lock' import { LAUNCH_MODAL, DISMISS_MODAL, waitForWallet, dismissWalletCheck, } from '../../actions/fullScreenModals' import { SET_ACCOUNT, UPDATE_ACCOUNT } from '../../actions/accounts' import { SET_NETWORK } from '../../actions/network' import { PROVIDER_READY } from '../../actions/provider' import { NEW_TRANSACTION } from '../../actions/transaction' import { SET_ERROR } from '../../actions/error' import { ACCOUNT_POLLING_INTERVAL } from '../../constants' import { TransactionType } from '../../unlockTypes' import { FATAL_NO_USER_ACCOUNT, FATAL_NON_DEPLOYED_CONTRACT, FATAL_WRONG_NETWORK, } from '../../errors' import { HIDE_FORM } from '../../actions/lockFormVisibility' import { GET_STORED_PAYMENT_DETAILS } from '../../actions/user' import { SIGN_DATA } from '../../actions/signature' import { SIGN_BULK_METADATA_REQUEST, SIGN_BULK_METADATA_RESPONSE, } from '../../actions/keyMetadata' let mockConfig /** * Fake state */ let account = {} let lock = {} let state = {} const transaction = {} const network = {} /** * This is a "fake" middleware caller * Taken from https://redux.js.org/recipes/writing-tests#middleware */ const create = (dispatchImplementation = () => true) => { const store = { getState: jest.fn(() => state), dispatch: jest.fn((...args) => dispatchImplementation(...args)), } const next = jest.fn() const handler = walletMiddleware(mockConfig)(store) const invoke = action => handler(next)(action) return { next, invoke, store } } /** * Mocking walletService * Default objects yielded by promises */ class MockWalletService extends EventEmitter { constructor() { super() this.ready = true } connect() {} } let mockWalletService = new MockWalletService() jest.mock('@unlock-protocol/unlock-js', () => { const mockUnlock = require.requireActual('@unlock-protocol/unlock-js') // Original module return { ...mockUnlock, WalletService: function() { return mockWalletService }, } }) jest.useFakeTimers() beforeEach(() => { mockConfig = jest.requireActual('../../config').default() // Reset the mock mockWalletService = new MockWalletService() // Reset state! account = { address: '0xabc', } lock = { address: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', keyPrice: '100', owner: account.address, expirationDuration: 60 * 60 * 24 * 30, maxNumberOfKeys: -1, name: 'My Fancy Lock', } state = { account, network, provider: 'HTTP', locks: { [lock.address]: lock, }, transactions: {}, keys: {}, walletStatus: { waiting: true, }, } }) describe('Wallet middleware', () => { describe('when receiving account.updated events triggered by the walletService', () => { it('should handle non-redundant account.updated events', () => { expect.assertions(2) const { store } = create() const emailAddress = 'geoff@bitconnect.gov' const update = { emailAddress, } mockWalletService.emit('account.updated', update) expect(store.dispatch).toHaveBeenNthCalledWith( 1, expect.objectContaining({ type: UPDATE_ACCOUNT, update: { emailAddress, }, }) ) expect(store.dispatch).toHaveBeenNthCalledWith( 2, expect.objectContaining({ type: GET_STORED_PAYMENT_DETAILS, emailAddress, }) ) }) it('should not dispatch redundant updates triggered by the walletService', () => { expect.assertions(1) const { store } = create() const update = { address: '0xabc', } mockWalletService.emit('account.updated', update) expect(store.dispatch).not.toHaveBeenCalled() }) }) it('should handle account.changed events triggered by the walletService', () => { expect.assertions(3) const { store } = create() const address = '0x123' const account = { address, } setTimeout.mockClear() mockWalletService.getAccount = jest.fn() mockWalletService.emit('account.changed', address) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: SET_ACCOUNT, account, }) ) expect(setTimeout).toHaveBeenCalledTimes(1) expect(setTimeout).toHaveBeenCalledWith( expect.any(Function), ACCOUNT_POLLING_INTERVAL ) }) it('on the server, it should not handle account.changed events triggered by the walletService', () => { expect.assertions(2) setTimeout.mockClear() mockConfig.isServer = true const { store } = create() const address = '0x123' const account = { address, } mockWalletService.getAccount = jest.fn() mockWalletService.emit('account.changed', address) expect(store.dispatch).not.toHaveBeenCalledWith( expect.objectContaining({ type: SET_ACCOUNT, account, }) ) expect(setTimeout).not.toHaveBeenCalled() }) it('should handle transaction.pending events triggered by the walletService', () => { expect.assertions(1) const { store } = create() mockWalletService.emit('transaction.pending') expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: LAUNCH_MODAL }) ) }) it('should handle transaction.new events triggered by the walletService', () => { expect.assertions(2) const { store } = create() const from = '0xjulien' const to = '0xunlock' const input = 'input' const type = 'LOCK_CREATION' const status = 'submitted' mockWalletService.emit( 'transaction.new', transaction.hash, from, to, input, type, status ) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: DISMISS_MODAL }) ) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: NEW_TRANSACTION, transaction: expect.objectContaining({ hash: transaction.hash, to, from, input, type: 'Lock Creation', status, }), }) ) }) it('should handle overlay.dismissed events triggered by walletService', () => { expect.assertions(1) const { store } = create() mockWalletService.emit('overlay.dismissed') expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: DISMISS_MODAL }) ) }) it('it should handle lock.updated events triggered by the walletService', () => { expect.assertions(2) const { store } = create() const update = { transaction: '0x123', } mockWalletService.emit('lock.updated', lock.address, update) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: UPDATE_LOCK, address: lock.address, update, }) ) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: HIDE_FORM, }) ) }) describe('when receiving a network.changed event triggered by the walletService', () => { describe('when the network.changed is different from the store value', () => { describe('when the network does not match the required network', () => { it('should dispatch an error', () => { expect.assertions(2) const { store } = create() const networkId = 1984 mockWalletService.isUnlockContractDeployed = jest.fn() mockConfig.isRequiredNetwork = jest.fn(() => false) mockWalletService.emit('network.changed', networkId) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: SET_ERROR, error: { level: 'Fatal', kind: 'Application', message: FATAL_WRONG_NETWORK, data: { currentNetwork: 'Winston', requiredNetworkId: 1984, }, }, }) ) expect( mockWalletService.isUnlockContractDeployed ).not.toHaveBeenCalled() }) }) it('should dispatch an error if it could not check whether the contract was deployed', () => { expect.assertions(2) const { store } = create() const networkId = 1984 const error = new Error('An error') mockWalletService.getAccount = jest.fn() mockWalletService.isUnlockContractDeployed = jest.fn(callback => { return callback(error) }) mockWalletService.emit('network.changed', networkId) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: SET_ERROR, error: { level: 'Fatal', kind: 'Application', message: 'An error', }, }) ) expect(mockWalletService.getAccount).not.toHaveBeenCalled() }) it('should dispatch FATAL_NON_DEPLOYED_CONTRACT if the contract was not deployed', () => { expect.assertions(2) const { store } = create() const networkId = 1984 mockWalletService.getAccount = jest.fn() mockWalletService.isUnlockContractDeployed = jest.fn(callback => { return callback(null, false /* non deployed */) }) mockWalletService.emit('network.changed', networkId) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: SET_ERROR, error: { level: 'Fatal', kind: 'Application', message: FATAL_NON_DEPLOYED_CONTRACT, }, }) ) expect(mockWalletService.getAccount).not.toHaveBeenCalled() }) describe('if the contract was deployed', () => { it('should get a new account', () => { expect.assertions(1) create() const networkId = 1984 state.network.name = 1773 mockWalletService.getAccount = jest.fn() mockWalletService.isUnlockContractDeployed = jest.fn(callback => { return callback(null, true /* deployed */) }) mockWalletService.emit('network.changed', networkId) expect(mockWalletService.getAccount).toHaveBeenCalledWith(true) // create an account if none is set }) }) it('should dispatch a SET_NETWORK action', () => { expect.assertions(1) const { store } = create() const networkId = 1984 state.network.name = 1773 mockWalletService.getAccount = jest.fn() mockWalletService.isUnlockContractDeployed = jest.fn() mockWalletService.emit('network.changed', networkId) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: SET_NETWORK, network: networkId, }) ) }) }) }) describe('error events triggered by the walletService', () => { it('should handle error triggered when creating a lock', () => { expect.assertions(3) const { store } = create() const transaction = { hash: '123', type: TransactionType.LOCK_CREATION, lock: '0x123', } state.transactions = { [transaction.hash]: transaction, } mockWalletService.emit( 'error', { message: 'this was broken' }, transaction.hash ) expect(store.dispatch).toHaveBeenNthCalledWith( 1, expect.objectContaining({ type: DISMISS_MODAL }) ) expect(store.dispatch).toHaveBeenNthCalledWith(2, { type: DELETE_LOCK, address: transaction.lock, }) expect(store.dispatch).toHaveBeenNthCalledWith( 3, expect.objectContaining({ type: SET_ERROR, error: { level: 'Warning', kind: 'Transaction', message: 'Failed to create lock. Did you decline the transaction?', }, }) ) }) it('it should handle error events triggered by the walletService', () => { expect.assertions(1) const { store } = create() mockWalletService.emit('error', { message: 'this was broken' }) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: SET_ERROR, error: { level: 'Warning', kind: 'Transaction', message: 'this was broken', }, }) ) }) }) it('should handle PROVIDER_READY and connect', () => { expect.assertions(2) const { next, invoke } = create() const action = { type: PROVIDER_READY } mockWalletService.connect = jest.fn() invoke(action) expect(mockWalletService.connect).toHaveBeenCalledWith( mockConfig.providers[state.provider] ) expect(next).toHaveBeenCalledWith(action) }) describe('WITHDRAW_FROM_LOCK', () => { it('when the service is not ready it should set an error and not try to withdraw from the lock', () => { expect.assertions(3) const { next, invoke, store } = create() const action = { type: WITHDRAW_FROM_LOCK, lock } mockWalletService.withdrawFromLock = jest.fn() mockWalletService.ready = false invoke(action) expect(store.dispatch).toHaveBeenCalledWith({ type: SET_ERROR, error: { level: 'Fatal', kind: 'Application', message: FATAL_NO_USER_ACCOUNT, }, }) expect(mockWalletService.withdrawFromLock).not.toHaveBeenCalled() expect(next).toHaveBeenCalledWith(action) }) it('should handle WITHDRAW_FROM_LOCK by calling withdrawFromLock from walletService', () => { expect.assertions(2) const { next, invoke } = create() const action = { type: WITHDRAW_FROM_LOCK, lock } mockWalletService.withdrawFromLock = jest.fn() mockWalletService.ready = true invoke(action) expect(mockWalletService.withdrawFromLock).toHaveBeenCalledWith({ lockAddress: lock.address, }) expect(next).toHaveBeenCalledWith(action) }) }) describe('CREATE_LOCK', () => { describe('when the lock has an address', () => { it('when the service is not ready it should set an error and not try to create the lock', () => { expect.assertions(3) const { next, invoke, store } = create() const action = { type: CREATE_LOCK, lock } mockWalletService.createLock = jest.fn() mockWalletService.ready = false invoke(action) expect(store.dispatch).toHaveBeenCalledWith({ type: SET_ERROR, error: { level: 'Fatal', kind: 'Application', message: FATAL_NO_USER_ACCOUNT, }, }) expect(mockWalletService.createLock).not.toHaveBeenCalled() expect(next).toHaveBeenCalledWith(action) }) it("should handle CREATE_LOCK by calling walletService's createLock", () => { expect.assertions(2) const { next, invoke } = create() const action = { type: CREATE_LOCK, lock } mockWalletService.createLock = jest .fn() .mockImplementation(() => Promise.resolve()) mockWalletService.ready = true invoke(action) expect(mockWalletService.createLock).toHaveBeenCalledWith({ currencyContractAddress: lock.currencyContractAddress, expirationDuration: lock.expirationDuration, keyPrice: lock.keyPrice, maxNumberOfKeys: lock.maxNumberOfKeys, name: lock.name, owner: lock.owner, }) expect(next).toHaveBeenCalledWith(action) }) }) describe('when the lock does not have an address', () => { it('should not try to createLock', () => { expect.assertions(2) let lock = { keyPrice: '100', owner: account, } mockWalletService.createLock = jest.fn() const { next, invoke } = create() const action = { type: CREATE_LOCK, lock } mockWalletService.ready = true invoke(action) expect(next).toHaveBeenCalled() expect(mockWalletService.createLock).not.toHaveBeenCalled() }) }) }) describe('UPDATE_LOCK_KEY_PRICE', () => { it('when the service is not ready it should set an error and not try to update the key price', () => { expect.assertions(3) const { next, invoke, store } = create() const action = { type: UPDATE_LOCK_KEY_PRICE, lock } mockWalletService.updateKeyPrice = jest.fn() mockWalletService.ready = false invoke(action) expect(store.dispatch).toHaveBeenCalledWith({ type: SET_ERROR, error: { level: 'Fatal', kind: 'Application', message: FATAL_NO_USER_ACCOUNT, }, }) expect(mockWalletService.updateKeyPrice).not.toHaveBeenCalled() expect(next).toHaveBeenCalledWith(action) }) it('should invoke updateKeyPrice on receiving an update request', () => { expect.assertions(2) const { next, invoke } = create() const action = { type: UPDATE_LOCK_KEY_PRICE, address: lock.address, price: '0.03', } mockWalletService.updateKeyPrice = jest.fn() mockWalletService.ready = true invoke(action) expect(mockWalletService.updateKeyPrice).toHaveBeenCalledWith({ lockAddress: lock.address, keyPrice: '0.03', }) expect(next).toHaveBeenCalledWith(action) }) }) describe('SIGN_DATA', () => { it("should handle SIGN_DATA by calling walletService's signDataPersonal", () => { expect.assertions(2) const { next, invoke } = create() const action = { type: SIGN_DATA, data: 'neat', id: 'track this signature', } mockWalletService.signDataPersonal = jest .fn() .mockImplementation(() => Promise.resolve()) mockWalletService.ready = true invoke(action) expect(mockWalletService.signDataPersonal).toHaveBeenCalledWith( '', 'neat', expect.any(Function) ) expect(next).toHaveBeenCalledWith(action) }) it('should dispatch an error if the error param in the callback is defined', () => { expect.assertions(1) const { invoke, store } = create() const action = { type: SIGN_DATA, data: 'neat' } mockWalletService.signDataPersonal = jest .fn() .mockImplementation((_address, _data, callback) => callback(new Error('an error'), undefined) ) mockWalletService.ready = true invoke(action) expect(store.dispatch).toHaveBeenCalledWith( expect.objectContaining({ type: 'error/SET_ERROR', }) ) }) it('should dispatch some typed data if there is no error', () => { expect.assertions(1) const { invoke, store } = create() const action = { type: SIGN_DATA, data: 'neat', id: 'track this signature', } mockWalletService.signDataPersonal = jest .fn() .mockImplementation((_address, _data, callback) => callback(undefined, 'here is your signature') ) mockWalletService.ready = true invoke(action) expect(store.dispatch).toHaveBeenCalledWith({ type: 'signature/SIGNED_DATA', data: 'neat', signature: 'here is your signature', id: 'track this signature', }) }) }) describe('SIGN_BULK_METADATA_REQUEST', () => { const action = { type: SIGN_BULK_METADATA_REQUEST, lockAddress: '0xe29ec42F0b620b1c9A716f79A02E9DC5A5f5F98a', owner: '0xAaAdEED4c0B861cB36f4cE006a9C90BA2E43fdc2', timestamp: 1234567890, } const expectedTypedData = expect.objectContaining({ primaryType: 'KeyMetadata', }) it("should handle SIGN_BULK_METADATA_REQUEST by calling walletService's signData", () => { expect.assertions(2) const { invoke, store } = create() mockWalletService.signData = jest.fn() mockWalletService.ready = true invoke(action) expect(store.dispatch).toHaveBeenCalledWith(waitForWallet()) expect(mockWalletService.signData).toHaveBeenCalledWith( action.owner, expectedTypedData, expect.any(Function) ) }) it('should dispatch some typed data on success', () => { expect.assertions(3) const { invoke, store } = create() mockWalletService.signData = jest .fn() .mockImplementation((_address, _data, callback) => { callback(undefined, 'a signature') }) mockWalletService.ready = true invoke(action) expect(store.dispatch).toHaveBeenNthCalledWith(1, waitForWallet()) expect(store.dispatch).toHaveBeenNthCalledWith(2, dismissWalletCheck()) expect(store.dispatch).toHaveBeenNthCalledWith(3, { type: SIGN_BULK_METADATA_RESPONSE, data: expectedTypedData, signature: 'a signature', lockAddress: action.lockAddress, keyIds: action.keyIds, }) }) it('should dispatch an error on failure', () => { expect.assertions(1) const { invoke, store } = create() mockWalletService.signData = jest .fn() .mockImplementation((_address, _data, callback) => { callback(new Error('it broke'), undefined) }) mockWalletService.ready = true invoke(action) expect(store.dispatch).toHaveBeenCalledWith({ type: SET_ERROR, error: { kind: 'Wallet', level: 'Warning', message: 'Could not sign typed data for metadata request.', }, }) }) }) })
28.792208
109
0.60866
3b68f8b0bc405619c3b9fd7f5fa8a4da99442c63
1,396
js
JavaScript
component---src-pages-index-jsx-fe3023585ada6d856659.js
jeanarjean/rorscharg.github.io
4b9b3566ef1e418671e8334b705fd50f7f19390f
[ "MIT" ]
null
null
null
component---src-pages-index-jsx-fe3023585ada6d856659.js
jeanarjean/rorscharg.github.io
4b9b3566ef1e418671e8334b705fd50f7f19390f
[ "MIT" ]
null
null
null
component---src-pages-index-jsx-fe3023585ada6d856659.js
jeanarjean/rorscharg.github.io
4b9b3566ef1e418671e8334b705fd50f7f19390f
[ "MIT" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[10],{Dtc0:function(e,t,a){"use strict";a.r(t);var n=a("dI71"),l=a("q1tI"),r=a.n(l),o=a("Wbzz"),s=a("mwIZ"),c=a.n(s),p=a("Kvkj"),m=(a("pxef"),function(e){function t(){return e.apply(this,arguments)||this}return Object(n.a)(t,e),t.prototype.render=function(){c()(this,"props.data.site.siteMetadata.title");var e=c()(this,"props.data.allMarkdownRemark.edges")[0].node,t=c()(e,"frontmatter.title")||e.fields.slug;return r.a.createElement(p.d,null,r.a.createElement("div",{className:"home-container"},r.a.createElement("div",{className:"home-content"},r.a.createElement("h1",null,"Last Post:"),r.a.createElement("div",{key:e.fields.slug},r.a.createElement("h3",null,r.a.createElement(o.a,{style:{boxShadow:"none"},to:e.fields.slug},t)),r.a.createElement("small",null,e.frontmatter.date),r.a.createElement("p",{dangerouslySetInnerHTML:{__html:e.excerpt}})),r.a.createElement("h1",null,"Last Photography Project:"),r.a.createElement("div",{className:"latest-photography-card"},r.a.createElement(p.g,{name:"2021",link:"/projects/photography/2021",image:"/projects/photography/2021/2021-1.jpg",alt:"/projects/photography/2021/2021-1.jpg",className:"latest-photography-card"}," ")),r.a.createElement(p.e,null))))},t}(r.a.Component));t.default=m},pxef:function(e,t,a){}}]); //# sourceMappingURL=component---src-pages-index-jsx-fe3023585ada6d856659.js.map
698
1,315
0.722063
3b6922968d9d90daad6287ec43bbf6edb50396d0
4,146
js
JavaScript
src/pages/index.js
krossdev/iam-docs
181284f56b43a2355ebf1d63962fb6be16a924cf
[ "Apache-2.0" ]
null
null
null
src/pages/index.js
krossdev/iam-docs
181284f56b43a2355ebf1d63962fb6be16a924cf
[ "Apache-2.0" ]
null
null
null
src/pages/index.js
krossdev/iam-docs
181284f56b43a2355ebf1d63962fb6be16a924cf
[ "Apache-2.0" ]
null
null
null
import React from 'react'; import clsx from 'clsx'; import Layout from '@theme/Layout'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import styles from './index.module.css'; function HomepageHeader() { const {siteConfig} = useDocusaurusContext(); return ( <header className={clsx('hero hero--primary', styles.hero)}> <div className="container" style={{ color: 'white' }}> <h1 className="hero__title">{siteConfig.tagline}</h1> <p className="hero__subtitle">面向 KrossIAM 开发人员的资料库</p> <div className='margin-top--xl margin-bottom--lg'> <Link to="/docs/quickstart" className="button button--lg button--secondary">文档</Link> <Link to="/blog" className="button button--lg button--secondary margin-left--md">博客</Link> <Link to="/demo" className="button button--lg button--info margin-left--md" style={{color:'black'}}>演示</Link> </div> </div> </header> ); } export default function Home() { const {siteConfig} = useDocusaurusContext(); return ( <Layout title={`${siteConfig.title}`} description="统一身份管理及访问规则编排服务器"> <HomepageHeader /> <div class="alert alert--info" role="alert" style={{ borderRadius: 0, textAlign: 'center' }}> 本站点主要面向 KrossIAM 开发人员,KrossIAM 用户请访问 &nbsp;<Link to='https://iam.kross.work'>KrossIAM 文档站</Link> </div> <main className={styles.main}> <div className="row"> <div className="col col--7"> <h3>介绍</h3> <p> KrossIAM 是以安全作为优先设计的身份管理和访问规则编排系统,实现了大多数系统都需要, 但却不太容易正确处理的部分--身份管理(或账户管理), 包括基本的注册、认证、存储,密码找回,2FA 认证,OIDC 登录, OAuth2 身份提供,SAML 单点登录,等等... &nbsp; <Link to='#'> 看看可以使用 KrossIAM 做些什么? </Link> </p> <p> KrossIAM 内置灵活的授权子系统,可以应对各种不同的授权场景, 与常见的(例如基于角色的访问控制系统(RBAC),基于属性的访问授权系统(ABAC),等) 不太一样,KrossIAM 的授权子系统基于可编程的规则语言,这让事情变得些微复杂, 但是却足够灵活及强大。 &nbsp; <Link to='#'> 看看如何使用 KrossIAM 授权编排系统实现常见的访问控制模式? </Link> </p> <p> KrossIAM 提供 2 种方式将这些功能添加到现有应用中,<em>代理</em> 和 <em>API 接口</em>, 使用代理是最简单的方法,无需对现有应用进行修改,既可以让一个没有账户管理的系统摇身一变, 成为一个带有账户管理的系统。API 接口提供深度整合能力,将 KrossIAM 的功能融合到现有应用中。 &nbsp; <Link to='#'> 看看如何使用 KrossIAM 代理为现有系统添加账户管理功能? </Link> </p> <h3>特征</h3> <ul> <li>基于 OPA 的规则编排系统,精细的授权模式;</li> <li>支持 Sqlite、PostgreSQL、MySQL、CockroachDB 数据库;</li> <li>支持多项目,各项目间使用数据库 schema 实现数据隔离;</li> </ul> </div> <div className="col col--5"> <h3>文档</h3> <ul> <li> <Link to='/docs/quickstart'>快速上手</Link> </li> </ul> <h3>博客</h3> <ul> <li> <Link to='/blog/email'>KrossIAM 邮件发送模块</Link> </li> <li> <Link to='/blog/ms'>KrossIAM 中的消息服务</Link> </li> <li> <Link to='/blog/password-hashing'>KrossIAM 中的密码哈希</Link> </li> <li> <Link to='/blog/kiam-datastore'>KrossIAM 后台数据存储</Link> </li> <li> <Link to='/blog/log'>KrossIAM 中的日志处理</Link> </li> <li> <Link to='/blog/i18n'>KrossIAM 中的 i18n</Link> </li> <li> <Link to='/blog/fenotes'>KrossIAM 前端开发说明</Link> </li> </ul> <h3>资源</h3> <ul> <li> <Link to='https://github.com/krossdev/iam'>代码仓库</Link> </li> <li> <Link to='/'>Slack 聊天室</Link> </li> </ul> </div> </div> </main> </Layout> ); }
33.435484
100
0.488905
b72091eef5d765651430fa1a598496c41bf8cbd9
859
js
JavaScript
FinalProject/screen/MainScreen.js
Vanagas420/FinanceApp
3d5b40464452183acffe1b45ac6fd67d7ec3e978
[ "MIT" ]
null
null
null
FinalProject/screen/MainScreen.js
Vanagas420/FinanceApp
3d5b40464452183acffe1b45ac6fd67d7ec3e978
[ "MIT" ]
2
2021-10-06T14:08:25.000Z
2022-02-27T01:44:58.000Z
FinalProject/screen/MainScreen.js
Vanagas420/FinanceApp
3d5b40464452183acffe1b45ac6fd67d7ec3e978
[ "MIT" ]
null
null
null
import React, { Component } from "react"; import { StyleSheet } from 'react-native'; import { Container, Content } from "native-base"; import Card from "../parts/component/Card"; export default class HomeTab extends Component { render() { return ( <Container styles={styles.container}> <Content> <Card CityImg={require("../img/Athens.jpg")} Name={"Athens"} Country={"Greece"} /> <Card CityImg={require("../img/Madrid.jpg")} Name={"Madrid"} Country={"Spain"} /> <Card CityImg={require("../img/Paris.jpg")} Name={"Paris"} Country={"France"} /> </Content> </Container> ) } } const styles = StyleSheet.create({ container: { flex: 1, } })
20.95122
50
0.501746
b720f10fbfc079a810f699e733c14ba88b5c32e4
452
js
JavaScript
node_modules/dbd.js/package/functions/funcs/isMentionable.js
XEOCORP/eniobot
778364b8c09de9e0ca312a3cf9fa05d0f902cb5d
[ "MIT" ]
null
null
null
node_modules/dbd.js/package/functions/funcs/isMentionable.js
XEOCORP/eniobot
778364b8c09de9e0ca312a3cf9fa05d0f902cb5d
[ "MIT" ]
null
null
null
node_modules/dbd.js/package/functions/funcs/isMentionable.js
XEOCORP/eniobot
778364b8c09de9e0ca312a3cf9fa05d0f902cb5d
[ "MIT" ]
null
null
null
module.exports = async d => { const code = d.command.code const r = code.split("$isMentionable[").length - 1 const inside = code.split("$isMentionable[")[r].split("]")[0] const role = d.message.guild.roles.cache.get(inside) if (!role) return d.error(`❌ Invalid role ID in \`$isMentionable[${inside}]\``) return { code: code.replaceLast(`$isMentionable[${inside}]`, role.mentionable) } }
30.133333
84
0.590708
b7215367f3ee63c060619c3a6885be1eca4fb78a
417
js
JavaScript
docs/html/dir_17b4a9b5ba749112246522facd776253.js
wrathematics/fml
e6db9c67a530b31f80a7fc0fe16d0f88c1d9a18e
[ "BSL-1.0" ]
15
2020-01-29T08:59:34.000Z
2020-01-31T04:21:52.000Z
docs/html/dir_17b4a9b5ba749112246522facd776253.js
wrathematics/fml
e6db9c67a530b31f80a7fc0fe16d0f88c1d9a18e
[ "BSL-1.0" ]
null
null
null
docs/html/dir_17b4a9b5ba749112246522facd776253.js
wrathematics/fml
e6db9c67a530b31f80a7fc0fe16d0f88c1d9a18e
[ "BSL-1.0" ]
null
null
null
var dir_17b4a9b5ba749112246522facd776253 = [ [ "gpublas.hh", "hip_2gpublas_8hh_source.html", null ], [ "gpulapack.hh", "hip_2gpulapack_8hh_source.html", null ], [ "gpuprims.hh", "hip_2gpuprims_8hh_source.html", null ], [ "gpurand.hh", "hip_2gpurand_8hh_source.html", null ], [ "rocm_smi.hh", "rocm__smi_8hh_source.html", null ], [ "types.hh", "gpu_2arch_2hip_2types_8hh_source.html", null ] ];
46.333333
65
0.695444
b721fae0c0f79d1f307ec0fc3ef196f335ab4d22
344
js
JavaScript
Js/Backend/App.js
Webiny/BackupApp
e755566058531b0f5a315f9748bd3edaca5c1657
[ "MIT" ]
null
null
null
Js/Backend/App.js
Webiny/BackupApp
e755566058531b0f5a315f9748bd3edaca5c1657
[ "MIT" ]
null
null
null
Js/Backend/App.js
Webiny/BackupApp
e755566058531b0f5a315f9748bd3edaca5c1657
[ "MIT" ]
null
null
null
import Webiny from 'webiny'; import Backups from './Modules/Backups'; import Settings from './Modules/Settings'; class Backup extends Webiny.App { constructor() { super('BackupApp.Backend'); this.modules = [ new Backups(this), new Settings(this) ]; } } Webiny.registerApp(new Backup());
22.933333
42
0.613372
b72293976a6a6c263e583cff48a60a8189f523ac
211
js
JavaScript
src/plugins/loader/loaderFactory.js
BrunoDSouza/simulador-cardiopulmonar
27aacaf8b109898492ed77552b29e2a26e11a5b9
[ "MIT" ]
null
null
null
src/plugins/loader/loaderFactory.js
BrunoDSouza/simulador-cardiopulmonar
27aacaf8b109898492ed77552b29e2a26e11a5b9
[ "MIT" ]
5
2020-07-17T06:09:34.000Z
2022-02-12T11:34:54.000Z
src/plugins/loader/loaderFactory.js
BrunoDSouza/simulador-cardiopulmonar
27aacaf8b109898492ed77552b29e2a26e11a5b9
[ "MIT" ]
null
null
null
const loaderFactory = context => { return { show () { context.$store.dispatch('showLoader') }, hide () { context.$store.dispatch('hideLoader') } } } export default loaderFactory
16.230769
43
0.592417
b722a34e347908147d50893e86ea1b0e79456b24
82
js
JavaScript
src/p2p/getIdentifier.js
Asd11178/stremio-addon-sdk
461f9236b43af9b951e22d943cb476e2b06aca9c
[ "MIT" ]
13
2020-04-20T00:05:25.000Z
2021-11-16T11:20:23.000Z
src/p2p/getIdentifier.js
Asd11178/stremio-addon-sdk
461f9236b43af9b951e22d943cb476e2b06aca9c
[ "MIT" ]
9
2020-04-21T20:59:35.000Z
2022-01-22T11:42:45.000Z
src/p2p/getIdentifier.js
Asd11178/stremio-addon-sdk
461f9236b43af9b951e22d943cb476e2b06aca9c
[ "MIT" ]
4
2021-01-07T20:52:56.000Z
2022-01-31T19:36:43.000Z
module.exports = (msgIdentifier, xpub) => `${xpub.slice(4, 16)}.${msgIdentifier}`
41
81
0.670732
b722fa844e76f2dcaed0f67355963e4561e1129e
3,032
js
JavaScript
src/auctions/assisting-auctions.ent.js
degen-heroes/degenking
6b54b3e62892cfe3099a94d4166735703329211f
[ "ISC" ]
8
2022-01-26T16:59:10.000Z
2022-03-11T13:10:15.000Z
src/auctions/assisting-auctions.ent.js
degen-heroes/degenking
6b54b3e62892cfe3099a94d4166735703329211f
[ "ISC" ]
4
2022-02-01T21:33:37.000Z
2022-03-19T10:39:36.000Z
src/auctions/assisting-auctions.ent.js
degen-heroes/degenking
6b54b3e62892cfe3099a94d4166735703329211f
[ "ISC" ]
1
2022-02-04T00:12:51.000Z
2022-02-04T00:12:51.000Z
/** * @fileoverview Query rental auctions. */ const { gqlQuery } = require('../graphql/gql-query.ent'); const { assistingAuctions, } = require('../graphql/queries/assisting-auctions.gql'); const { normalizeGqlHero } = require('../heroes-helpers/normalize-gql.ent'); exports.MAX_RECORDS = 1000; /** * Query for all rental market via GQL, will fetch all records. * * @param {Object=} optCriteria Optionally define criteria. * @return {Promise<Array<Object>>} Array with normalized heroes. */ exports.queryAssistingAuctionsAllGql = async (optCriteria) => { let criteria = null; if (optCriteria) { criteria = exports._parseCriteria(optCriteria); } return exports._queryActual(criteria); }; /** * Will parse and convert criteria to GQL filtering where clause. * * @param {Object} criteria The criteria to filter with. * @return {string} GQL Where clause. * @private */ exports._parseCriteria = (criteria) => { // First empty string required to force a comma at the start const gqlQueryAr = ['']; if (criteria.mainClass) { if (Array.isArray(criteria.mainClass)) { gqlQueryAr.push(`mainClass_in: ["${criteria.mainClass.join('", "')}"]`); } else { gqlQueryAr.push(`mainClass: "${criteria.mainClass}"`); } } if (criteria.subClass) { gqlQueryAr.push(`subClass: "${criteria.subClass}"`); } if (Number.isInteger(criteria.generation)) { if (Array.isArray(criteria.generation)) { gqlQueryAr.push(`generation_in: [${criteria.generation.join(',')}]`); } else { gqlQueryAr.push(`generation: ${criteria.generation}`); } } if (criteria.profession) { if (Array.isArray(criteria.profession)) { gqlQueryAr.push(`profession_in: ["${criteria.profession.join('", "')}"]`); } else { gqlQueryAr.push(`profession: "${criteria.profession}"`); } } if (criteria.summonsRemaining) { gqlQueryAr.push(`summonsRemaining_gte: "${criteria.summonsRemaining}"`); } const gqlWhere = gqlQueryAr.join(','); return gqlWhere; }; /** * Actual query for all rental market via GQL, will recurse to fetch all records. * * @param {string|null} criteria Filtering string or null for no filter. * @param {number=} first Overwrite to fetch less heroes. * @param {number=} skip Used for recurssion to fetch all records. * @param {Array<Object>=} heroesFetched Execution state containing all fetched heroes. * @return {Promise<Array<Object>>} Array with normalized heroes. * @private */ exports._queryActual = async ( criteria, first = exports.MAX_RECORDS, skip = 0, heroesFetched = [], ) => { const res = await gqlQuery(assistingAuctions(criteria), { first, skip, }); const { heroes } = res.data; const allHeroes = heroesFetched.concat(heroes); if (heroes.length < exports.MAX_RECORDS) { return allHeroes.map((heroGql) => { return normalizeGqlHero(heroGql); }); } const nextSkip = skip + exports.MAX_RECORDS; return exports._queryActual(criteria, first, nextSkip, allHeroes); };
28.074074
87
0.675792
b72338ed8418113f6bc5721d68e2122b607dd1c8
1,478
js
JavaScript
frontend/src/views/Root/hooks/useLangSwitch.js
haungrui777/iotdb-web-workbench
b1f00b98589c3168d5b84af4006ecf4bb130cc47
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
frontend/src/views/Root/hooks/useLangSwitch.js
haungrui777/iotdb-web-workbench
b1f00b98589c3168d5b84af4006ecf4bb130cc47
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
frontend/src/views/Root/hooks/useLangSwitch.js
haungrui777/iotdb-web-workbench
b1f00b98589c3168d5b84af4006ecf4bb130cc47
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { ref } from 'vue'; import i18n from '@/i18n/index'; import enLocale from 'element-plus/lib/locale/lang/en'; import zhLocale from 'element-plus/lib/locale/lang/zh-cn'; function useLangSwitch() { const langMap = { cn: 0, en: 1 }; const lang = langMap[localStorage.getItem('lang') || 'cn']; const langIndex = ref(lang); const handleLangCommand = (val) => { const langIndexMap = { 0: 'cn', 1: 'en', }; localStorage.setItem('lang', langIndexMap[val]); langIndex.value = +val; i18n.global.locale = [zhLocale.name, enLocale.name][val]; }; return { langIndex, handleLangCommand, }; } export default useLangSwitch;
33.590909
63
0.70433
b7234528aa573e75c3cca2959a8fe3388bb6fdf4
592
js
JavaScript
nodeAxosoft.js
Axosoft/AxoSlackBot
58d027d0cc6536dfe8ea75b24fe287b451c0e28d
[ "MIT" ]
2
2017-01-17T22:26:28.000Z
2019-06-05T00:45:14.000Z
nodeAxosoft.js
Axosoft/AxoSlackBot
58d027d0cc6536dfe8ea75b24fe287b451c0e28d
[ "MIT" ]
11
2016-12-06T20:44:30.000Z
2017-02-10T21:13:56.000Z
nodeAxosoft.js
Axosoft/AxoSlackBot
58d027d0cc6536dfe8ea75b24fe287b451c0e28d
[ "MIT" ]
2
2016-11-17T16:06:54.000Z
2020-01-30T19:22:50.000Z
"use strict"; const AxosoftApi = require('node-axosoft'); class Axosoft { constructor(accountUrl, accessToken) { const axosoftApi = this.axosoftApi = new AxosoftApi(accountUrl, { access_token: accessToken }); } promisify(apiFunction, args) { args = args || []; return new Promise((resolve, reject) => { args.push((error, response) => { if (error) reject(error); else resolve(response); }); apiFunction.apply(null, args); }); } } module.exports = Axosoft;
25.73913
73
0.547297
b72400e573367d25706f84f79582768122eda649
4,673
js
JavaScript
test/linker/snippet.spec.js
mentat-collective/shadergraph
4a4600a9349f877f588d1b5ba06c99f63ad82b85
[ "MIT" ]
null
null
null
test/linker/snippet.spec.js
mentat-collective/shadergraph
4a4600a9349f877f588d1b5ba06c99f63ad82b85
[ "MIT" ]
null
null
null
test/linker/snippet.spec.js
mentat-collective/shadergraph
4a4600a9349f877f588d1b5ba06c99f63ad82b85
[ "MIT" ]
null
null
null
/* global ShaderGraph */ describe("snippet", function () { const { GLSL, Linker } = ShaderGraph.ShaderGraph; const { Snippet } = Linker; let snippet = null; const configLocal = { globalAttributes: false, globalVaryings: false, globalUniforms: false, }; const configGlobal = { globalAttributes: true, globalVaryings: true, globalUniforms: true, }; beforeEach(function () { const code = `\ uniform float uni1; uniform vec3 uni2; attribute vec3 att1; attribute vec4 att2; varying vec4 var1; varying vec3 var2; void callback1(in vec3 color); void callback2(out vec3 color); void testSnippet(float param) { };\ `; return (snippet = Snippet.load(GLSL, "test", code)); }); it("loads", function () { expect(snippet).toBeTruthy(); }); it("compiles locals with namespace", function () { snippet.bind(configLocal, "_sgtest_"); expect(snippet.entry).toBe("_sgtest_testSnippet"); expect(snippet.main).toBeTruthy(); expect(snippet.main.signature.length).toBe(1); expect(snippet.main.signature[0].name).toBe("param"); expect(snippet.main.signature[0].type).toBe("f"); expect(snippet.uniforms["_sgtest_uni1"].name).toBe("uni1"); expect(snippet.uniforms["_sgtest_uni1"].type).toBe("f"); expect(snippet.uniforms["_sgtest_uni2"].name).toBe("uni2"); expect(snippet.uniforms["_sgtest_uni2"].type).toBe("v3"); expect(snippet.externals["_sgtest_callback1"].name).toBe("callback1"); expect(snippet.externals["_sgtest_callback1"].type).toBe("(v3)()"); expect(snippet.externals["_sgtest_callback2"].name).toBe("callback2"); expect(snippet.externals["_sgtest_callback2"].type).toBe("()(v3)"); expect(snippet.attributes["_sgtest_att1"].name).toBe("att1"); expect(snippet.attributes["_sgtest_att1"].type).toBe("v3"); expect(snippet.attributes["_sgtest_att2"].name).toBe("att2"); expect(snippet.attributes["_sgtest_att2"].type).toBe("v4"); expect(snippet.varyings["_sgtest_var1"].name).toBe("var1"); expect(snippet.varyings["_sgtest_var1"].type).toBe("v4"); expect(snippet.varyings["_sgtest_var2"].name).toBe("var2"); expect(snippet.varyings["_sgtest_var2"].type).toBe("v3"); }); it("compiles globals without namespace", function () { snippet.bind(configGlobal, "_sgtest_"); expect(snippet.entry).toBe("_sgtest_testSnippet"); expect(snippet.main).toBeTruthy(); expect(snippet.main.signature.length).toBe(1); expect(snippet.main.signature[0].name).toBe("param"); expect(snippet.main.signature[0].type).toBe("f"); expect(snippet.uniforms["uni1"].name).toBe("uni1"); expect(snippet.uniforms["uni1"].type).toBe("f"); expect(snippet.uniforms["uni2"].name).toBe("uni2"); expect(snippet.uniforms["uni2"].type).toBe("v3"); expect(snippet.externals["_sgtest_callback1"].name).toBe("callback1"); expect(snippet.externals["_sgtest_callback1"].type).toBe("(v3)()"); expect(snippet.externals["_sgtest_callback2"].name).toBe("callback2"); expect(snippet.externals["_sgtest_callback2"].type).toBe("()(v3)"); expect(snippet.attributes["att1"].name).toBe("att1"); expect(snippet.attributes["att1"].type).toBe("v3"); expect(snippet.attributes["att2"].name).toBe("att2"); expect(snippet.attributes["att2"].type).toBe("v4"); expect(snippet.varyings["var1"].name).toBe("var1"); expect(snippet.varyings["var1"].type).toBe("v4"); expect(snippet.varyings["var2"].name).toBe("var2"); expect(snippet.varyings["var2"].type).toBe("v3"); }); it("binds uniforms", function () { const uniforms = { uni1: { type: "f", value: 1.0, }, }; snippet.bind(configLocal, uniforms, "_bind_"); expect(snippet.uniforms["_bind_uni1"]).toBe(uniforms.uni1); }); it("binds uniforms (backwards arguments)", function () { const uniforms = { uni1: { type: "f", value: 1.0, }, }; snippet.bind(configLocal, "_bind_", uniforms); expect(snippet.uniforms["_bind_uni1"]).toBe(uniforms.uni1); }); it("adds defines", function () { snippet.bind(configLocal, "_sgtest_", {}, { FOOBAR: "", BARFOO: 1 }); expect(snippet.code).toMatch(/#define FOOBAR\s+#define BARFOO 1\s/m); }); it("adds defines (backwards arguments)", function () { snippet.bind(configLocal, "_sgtest_", {}, { FOOBAR: "", BARFOO: 1 }); expect(snippet.code).toMatch(/#define FOOBAR\s+#define BARFOO 1\s/m); }); it("adds defines (shorthand syntax)", function () { snippet.bind(configLocal, {}, { FOOBAR: "", BARFOO: 1 }); expect(snippet.code).toMatch(/#define FOOBAR\s+#define BARFOO 1\s/m); }); });
33.378571
74
0.659747
b724205c4b874645a3530393b6c0b16b24191823
2,097
js
JavaScript
routes/relatorio.js
ArthurFritz/Mock-Curso-F-rias
83e88a40fc710e60979393c832840ea98c8d9ded
[ "MIT" ]
null
null
null
routes/relatorio.js
ArthurFritz/Mock-Curso-F-rias
83e88a40fc710e60979393c832840ea98c8d9ded
[ "MIT" ]
null
null
null
routes/relatorio.js
ArthurFritz/Mock-Curso-F-rias
83e88a40fc710e60979393c832840ea98c8d9ded
[ "MIT" ]
null
null
null
var express = require('express'); var router = express.Router(); var user = [ {id: 1, nome: 'José da Silva', login: "jose", email: 'jose@ponto.com.br', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 2, nome: 'Mariano das Neves', login: "mariano", email: 'marino@ponto.com.br', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 3, nome: 'Magyver da Silva', login: "magyver", email: 'magyver@ponto.com.br', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 4, nome: 'Irineu Nunes', login: "irineu", email: 'irineu@ponto.com.br', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 5, nome: 'Carlos Silva', login: "carlos", email: 'carlos@ponto.com.br', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 6, nome: 'Carlos Silva', login: "carlos", email: 'carlos@ponto.com.br', perfil:"ALUNO", urlFoto: null, senha:123456}, {id: 7, nome: 'Carlos Silva', login: "carlos", email: 'carlos@ponto.com.br', perfil:"ALUNO", urlFoto: null, senha:123456} ]; var mockInfo = [ { usuario : user[0], presenca : ["2018-01-22","2018-01-23","2018-01-24","2018-01-25","2018-01-26"], frequencia: 50 }, { usuario : user[1], presenca : ["2018-01-22","2018-01-23","2018-01-24"], frequencia: 30 }, { usuario : user[2], presenca : ["2018-01-22","2018-01-23","2018-01-24","2018-01-25"], frequencia: 40 }, { usuario : user[3], presenca : ["2018-01-22","2018-01-23","2018-01-24","2018-01-25","2018-01-26","2018-01-29"], frequencia: 60 }, { usuario : user[4], presenca : ["2018-01-22"], frequencia: 10 }, { usuario : user[5], presenca : ["2018-01-22","2018-01-23","2018-01-24","2018-01-25","2018-01-26","2018-01-29","2018-01-30","2018-01-31"], frequencia: 80 } ]; router.get('/:disciplina', function(req, res) { var result = JSON.parse(JSON.stringify(mockInfo)); if(req.params.disciplina > 2){ var remover = req.params.disciplina - 1; for(var a=0; a< remover && result.length > 0; a++){ if(result.length > 0 ){ result.splice(-1,1) } } } res.send(result); }); module.exports = router;
33.822581
132
0.607535
b7242ff542f6211e019fd414ad30f845c957d7b6
454
js
JavaScript
models/User.js
chopetdee/snack
7679238d2e6d1bd33a78b4e0a67d4961a3d2cc87
[ "MIT" ]
null
null
null
models/User.js
chopetdee/snack
7679238d2e6d1bd33a78b4e0a67d4961a3d2cc87
[ "MIT" ]
null
null
null
models/User.js
chopetdee/snack
7679238d2e6d1bd33a78b4e0a67d4961a3d2cc87
[ "MIT" ]
null
null
null
const Sequelize = require('sequelize'); const db = require('../config/database'); const User = db.define('user', { google_id: { type: Sequelize.STRING }, name: { type: Sequelize.STRING }, token: { type: Sequelize.STRING }, user_name: { type: Sequelize.STRING }, roll: { type: Sequelize.STRING }, token: { type: Sequelize.STRING } }) module.exports = User;
17.461538
41
0.54185
b7244e97d6e8e267c05d7cc7a198e645208ea203
135
js
JavaScript
node_modules/bungie-platform/platform.js
JohnOfTheWater/MEAN-Stack-Template
e9d51a0f1b4ad3bfa8c9161ae0c150f513a0058f
[ "MIT" ]
null
null
null
node_modules/bungie-platform/platform.js
JohnOfTheWater/MEAN-Stack-Template
e9d51a0f1b4ad3bfa8c9161ae0c150f513a0058f
[ "MIT" ]
null
null
null
node_modules/bungie-platform/platform.js
JohnOfTheWater/MEAN-Stack-Template
e9d51a0f1b4ad3bfa8c9161ae0c150f513a0058f
[ "MIT" ]
null
null
null
var bootstrap = require('./lib/bootstrap'); module.exports = function(cookieVal) { return bootstrap({ cookie: cookieVal }); };
19.285714
43
0.674074
b7248687aa1bdb74e457ddb95a9a2dd592fc8c89
12,712
js
JavaScript
src/caching/_route.js
v0krat/EmuTarkov-Server
42c26729b7093e20fa4e3f9608ff3a5e7f47d618
[ "MIT" ]
null
null
null
src/caching/_route.js
v0krat/EmuTarkov-Server
42c26729b7093e20fa4e3f9608ff3a5e7f47d618
[ "MIT" ]
null
null
null
src/caching/_route.js
v0krat/EmuTarkov-Server
42c26729b7093e20fa4e3f9608ff3a5e7f47d618
[ "MIT" ]
null
null
null
"use strict"; require('../libs.js'); function flush() { filepaths = json.parse(json.read("db/cache/filepaths.json")); } function dump() { json.write("user/cache/filepaths.json", filepaths); } function genericFilepathCacher(type, basepath) { logger.logInfo("Routing: " + basepath + "/"); let inputDir = basepath + "/"; let inputFiles = fs.readdirSync(inputDir); for (let file in inputFiles) { let filePath = inputDir + inputFiles[file]; let fileName = inputFiles[file].replace(".json", ""); switch (type) { case "items": filepaths.items[fileName] = filePath; break; case "quests": filepaths.quests[fileName] = filePath; break; case "traders": filepaths.traders[fileName] = filePath; break; case "locations": filepaths.locations[fileName] = filePath; break; case "customOutfits": filepaths.customization.outfits[fileName] = filePath; break; case "customOffers": filepaths.customization.offers[fileName] = filePath; break; case "hideoutAreas": filepaths.hideout.areas[fileName] = filePath; break; case "hideoutProd": filepaths.hideout.production[fileName] = filePath; break; case "hideoutScav": filepaths.hideout.scavcase[fileName] = filePath; break; case "weather": filepaths.weather[fileName] = filePath; break; case "maps": filepaths.maps[fileName] = filePath; break; case "userCache": filepaths.user.cache[fileName] = filePath; break; case "profileTraders": filepaths.user.profiles.traders[fileName] = "user/profiles/__REPLACEME__/traders/" + fileName + ".json"; break; case "profileEditions": filepaths.profile.character[fileName] = filePath; break; } } } function items() { genericFilepathCacher("items", "db/items"); } function quests() { genericFilepathCacher("quests", "db/quests"); } function traders() { genericFilepathCacher("traders", "db/traders"); genericFilepathCacher("profileTraders", "db/traders"); } function locations() { genericFilepathCacher("locations", "db/locations"); } function customizationOutfits() { genericFilepathCacher("customOutfits", "db/customization/outfits"); } function customizationOffers() { genericFilepathCacher("customOffers", "db/customization/offers"); } function hideoutAreas() { genericFilepathCacher("hideoutAreas", "db/hideout/areas"); } function hideoutProduction() { genericFilepathCacher("hideoutProd", "db/hideout/production"); } function hideoutScavcase() { genericFilepathCacher("hideoutScav", "db/hideout/scavcase"); } function templates() { logger.logInfo("Routing: db/templates/"); let inputDir = [ "db/templates/categories/", "db/templates/items/" ]; for (let path in inputDir) { let inputFiles = fs.readdirSync(inputDir[path]); for (let file in inputFiles) { let filePath = inputDir[path] + inputFiles[file]; let fileName = inputFiles[file].replace(".json", ""); if (path == 0) { filepaths.templates.categories[fileName] = filePath; } else { filepaths.templates.items[fileName] = filePath; } } } } function assort() { let dirList = utility.getDirList("db/assort/"); for (let trader in dirList) { let assortName = dirList[trader]; let assortFilePath = {"items":{}, "barter_scheme":{}, "loyal_level_items":{}}; let inputDir = [ "db/assort/" + assortName + "/items/", "db/assort/" + assortName + "/barter/", "db/assort/" + assortName + "/level/" ]; logger.logInfo("Routing: db/assort/" + assortName + "/"); for (let path in inputDir) { let inputFiles = fs.readdirSync(inputDir[path]); for (let file in inputFiles) { let filePath = inputDir[path] + inputFiles[file]; let fileName = inputFiles[file].replace(".json", ""); let fileData = json.parse(json.read(filePath)); if (path == 0) { assortFilePath.items[fileData._id] = filePath; } else if (path == 1) { assortFilePath.barter_scheme[fileName] = filePath; } else if (path == 2) { assortFilePath.loyal_level_items[fileName] = filePath; } } } filepaths.assort[assortName] = assortFilePath; filepaths.user.profiles.assort[assortName] = "user/profiles/__REPLACEME__/assort/" + assortName + ".json" } } function weather() { genericFilepathCacher("weather", "db/weather"); } function maps() { genericFilepathCacher("maps", "db/maps"); } function bots() { logger.logInfo("Routing: bots"); filepaths.bots.base = "db/bots/base.json"; let inputDir = [ "db/bots/pmc/bear/", "db/bots/pmc/usec/", "db/bots/scav/assault/", "db/bots/scav/bossbully/", "db/bots/scav/bossgluhar/", "db/bots/scav/bosskilla/", "db/bots/scav/bosskojaniy/", "db/bots/scav/followerbully/", "db/bots/scav/followergluharassault/", "db/bots/scav/followergluharscout/", "db/bots/scav/followergluharsecurity/", "db/bots/scav/followerkojaniy/", "db/bots/scav/marksman/", "db/bots/scav/pmcbot/" ]; let cacheDir = [ "appearance/body/", "appearance/head/", "appearance/hands/", "appearance/feet/", "appearance/voice/", "health/", "inventory/", "experience/", "names/" ]; for (let path in inputDir) { let baseNode = json.parse(json.read("db/cache/bots.json")); for (let item in cacheDir) { let inputFiles = fs.readdirSync(inputDir[path] + cacheDir[item]); for (let file in inputFiles) { let filePath = inputDir[path] + cacheDir[item] + inputFiles[file]; let fileName = inputFiles[file].replace(".json", ""); if (item == 0) { baseNode.appearance.body[fileName] = filePath; } else if (item == 1) { baseNode.appearance.head[fileName] = filePath; } else if (item == 2) { baseNode.appearance.hands[fileName] = filePath; } else if (item == 3) { baseNode.appearance.feet[fileName] = filePath; } else if (item == 4) { baseNode.appearance.voice[fileName] = filePath; } else if (item == 5) { baseNode.health[fileName] = filePath; } else if (item == 6) { baseNode.inventory[fileName] = filePath; } else if (item == 7) { baseNode.experience[fileName] = filePath; } else if (item == 8) { baseNode.names[fileName] = filePath; } } } if (path == 0) { filepaths.bots.pmc.bear = baseNode; } else if (path == 1) { filepaths.bots.pmc.usec = baseNode; } else if (path == 2) { filepaths.bots.scav.assault = baseNode; } else if (path == 3) { filepaths.bots.scav.bossbully = baseNode; } else if (path == 4) { filepaths.bots.scav.bossgluhar = baseNode; } else if (path == 5) { filepaths.bots.scav.bosskilla = baseNode; } else if (path == 6) { filepaths.bots.scav.bosskojaniy = baseNode; } else if (path == 7) { filepaths.bots.scav.followerbully = baseNode; } else if (path == 8) { filepaths.bots.scav.followergluharassault = baseNode; } else if (path == 9) { filepaths.bots.scav.followergluharscout = baseNode; } else if (path == 10) { filepaths.bots.scav.followergluharsecurity = baseNode; } else if (path == 11) { filepaths.bots.scav.followerkojaniy = baseNode; } else if (path == 12) { filepaths.bots.scav.marksman = baseNode; } else if (path == 13) { filepaths.bots.scav.pmcbot = baseNode; } } } function images() { logger.logInfo("Routing: images"); let inputDir = [ "res/banners/", "res/handbook/", "res/hideout/", "res/quest/", "res/trader/", ]; for (let path in inputDir) { let inputFiles = fs.readdirSync(inputDir[path]); for (let file in inputFiles) { let filePath = inputDir[path] + inputFiles[file]; let fileName = inputFiles[file].replace(".png", "").replace(".jpg", ""); if (path == 0) { filepaths.images.banners[fileName] = filePath; } else if (path == 1) { filepaths.images.handbook[fileName] = filePath; } else if (path == 2) { filepaths.images.hideout[fileName] = filePath; } else if (path == 3) { filepaths.images.quest[fileName] = filePath; } else if (path == 4) { filepaths.images.trader[fileName] = filePath; } } } } function profile() { logger.logInfo("Routing: profile"); filepaths.profile.storage = "db/profile/storage.json"; filepaths.profile.userbuilds = "db/profile/userbuilds.json"; genericFilepathCacher("profileEditions", "db/profile/character"); } function others() { logger.logInfo("Routing: others"); filepaths.user.profiles.list = "user/profiles/list.json"; filepaths.user.profiles.character = "user/profiles/__REPLACEME__/character.json"; filepaths.user.profiles.scav = "user/profiles/__REPLACEME__/scav.json"; filepaths.user.profiles.dialogue = "user/profiles/__REPLACEME__/dialogue.json"; filepaths.user.profiles.storage = "user/profiles/__REPLACEME__/storage.json"; filepaths.user.profiles.userbuilds = "user/profiles/__REPLACEME__/userbuilds.json"; filepaths.user.profiles.assort["579dc571d53a0658a154fbec"] = "user/profiles/__REPLACEME__/assort/579dc571d53a0658a154fbec.json"; filepaths.user.config = "user/server.config.json"; filepaths.globals = "db/globals.json"; filepaths.hideout.settings = "db/hideout/settings.json"; filepaths.ragfair.offer = "db/ragfair/offer.json"; filepaths.ragfair.search = "db/ragfair/search.json"; filepaths.cert.server.cert = "cert/server.cert"; filepaths.cert.server.key = "cert/server.key"; } function cache() { let assortList = utility.getDirList("db/assort/"); filepaths.user.cache.items = "user/cache/items.json"; filepaths.user.cache.quests = "user/cache/quests.json"; filepaths.user.cache.locations = "user/cache/locations.json"; filepaths.user.cache.languages = "user/cache/languages.json"; filepaths.user.cache.customization_outfits = "user/cache/customization_outfits.json"; filepaths.user.cache.customization_offers = "user/cache/customization_offers.json"; filepaths.user.cache.hideout_areas = "user/cache/hideout_areas.json"; filepaths.user.cache.hideout_production = "user/cache/hideout_production.json"; filepaths.user.cache.hideout_scavcase = "user/cache/hideout_scavcase.json"; filepaths.user.cache.weather = "user/cache/weather.json"; filepaths.user.cache.templates = "user/cache/templates.json"; filepaths.user.cache.mods = "user/cache/mods.json"; filepaths.user.cache.globals = filepaths.globals; for (let assort in assortList) { filepaths.user.cache["assort_" + assortList[assort]] = "user/cache/assort_" + assortList[assort] + ".json"; } } function routeDatabase() { flush(); items(); quests(); traders(); locations(); customizationOutfits(); customizationOffers(); hideoutAreas(); hideoutProduction(); hideoutScavcase(); templates(); assort(); weather(); maps(); bots(); images(); profile(); others(); cache(); } function all() { // force rebuilding routes let force = false; // force if rebuild is required if (mods.isRebuildRequired()) { logger.logWarning("Modslist mismatch, force rebuilding cache"); force = true; } // generate routes if (force || !fs.existsSync("user/cache/filepaths.json")) { routeDatabase(); mods.load(); dump(); } else { filepaths = json.parse(json.read("user/cache/filepaths.json")); } } module.exports.all = all;
34.356757
146
0.595972
b724d8ca9c031d52066acd17c42bdf8d72b6bfd2
361
js
JavaScript
projects/angular-line-awesome/icons/build/-las-headphones.icon.js
daniol/angular-line-awesome
2510a44c23dab25478b4338d0a7bcf1c2b1da3fd
[ "MIT" ]
3
2020-04-27T12:20:25.000Z
2020-08-14T06:48:02.000Z
projects/angular-line-awesome/icons/build/-las-headphones.icon.js
daniol/angular-line-awesome
2510a44c23dab25478b4338d0a7bcf1c2b1da3fd
[ "MIT" ]
4
2021-01-30T20:08:02.000Z
2022-02-18T17:09:11.000Z
projects/angular-line-awesome/icons/build/-las-headphones.icon.js
daniol/angular-line-awesome
2510a44c23dab25478b4338d0a7bcf1c2b1da3fd
[ "MIT" ]
1
2022-02-17T11:17:30.000Z
2022-02-17T11:17:30.000Z
export const lasHeadphones = { name: 'las-headphones', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M16 5C9.937 5 5 9.938 5 16v8c0 1.645 1.355 3 3 3h3v-9H7v-2c0-4.984 4.016-9 9-9s9 4.016 9 9v2h-4v9h3c1.645 0 3-1.355 3-3v-8c0-6.063-4.938-11-11-11zM7 20h2v5H8c-.566 0-1-.434-1-1zm16 0h2v4c0 .566-.434 1-1 1h-1z"/></svg>` };
72.2
298
0.66205
b7250eed9cafeffd3401f2b3f8d628df8b9a8bed
2,009
js
JavaScript
src/pages/components/actions/guidelines.js
Nevren/dashbydeploy
934c8c9106df141b8e5f82acd5470af94f012756
[ "MIT" ]
null
null
null
src/pages/components/actions/guidelines.js
Nevren/dashbydeploy
934c8c9106df141b8e5f82acd5470af94f012756
[ "MIT" ]
null
null
null
src/pages/components/actions/guidelines.js
Nevren/dashbydeploy
934c8c9106df141b8e5f82acd5470af94f012756
[ "MIT" ]
null
null
null
import React from 'react' import { Link } from 'gatsby' import Layout from '../../../components/layout' import SubNav from '../../../components/subnavigation' import AppContent from '../../../components/appcontent' const currentPageName = "Actions"; const currentPageNameLower = currentPageName.toLowerCase(); export default () => ( <Layout> <header className="subnav"> <h1>{currentPageName}</h1> <SubNav pageName={currentPageNameLower}/> </header> <AppContent> <div className="row"> <div className="column column--full"> <h2 className="has-number has-number--one no-margin--top">Action Verbs</h2> <p>Buttons should be written in short, concise words that describe the action taken. Your user shouldn’t have to guess what happens when they click. Rather, use one or two words that quickly describe the action taken.</p> <div className="image-container"> <div className="image" id="actions--action-verb"></div> </div> <h2 className="has-number has-number--two">Button Hierarchy</h2> <p>Not all buttons have equal importance. Knowing which kind of button to use is important in order to grab your user’s attention at the right time. The following buttons have been sorted from greatest hierarchy to least.</p> <div className="image-container"> <div className="image" id="actions--hierarchy"></div> </div> <h2 className="has-number has-number--three">Purposeful Color</h2> <p>The Dashing <Link to="style/color/guidelines">color library</Link> has been purposefully crafted for interaction. All interface colors have been tested to meet web accessibility standards, and should be used intentionally to draw attention and signify different types of action.</p> <div className="image-container"> <div className="image" id="actions--color"></div> </div> </div> </div> </AppContent> </Layout> )
46.72093
295
0.66899
b725ab2c970e0ecc5c3affed85f75989c644313f
31,470
js
JavaScript
engine-old/bot/common/shop.js
KwakTeddy/bot-web
fe2eee3888cf946dbd7a447edf53fc76b58ef354
[ "MIT" ]
null
null
null
engine-old/bot/common/shop.js
KwakTeddy/bot-web
fe2eee3888cf946dbd7a447edf53fc76b58ef354
[ "MIT" ]
null
null
null
engine-old/bot/common/shop.js
KwakTeddy/bot-web
fe2eee3888cf946dbd7a447edf53fc76b58ef354
[ "MIT" ]
null
null
null
var path = require('path'); // var bot = require(path.resolve('./engine2/bot.js')).getTemplateBot('restaurant'); var type = require(path.resolve('./engine2/bot/action/common/type')); var dateformat = require('dateformat'); var messages = require(path.resolve('engine2/messages/server/controllers/messages.server.controller')); var botUser= require(path.resolve('engine2/bot-users/server/controllers/bot-users.server.controller')) var mongoModule = require(path.resolve('engine2/bot/action/common/mongo')); var mongoose = require('mongoose'); var request = require('request'); var _ = require('lodash'); var globals = require(path.resolve('engine2/bot/engine/common/globals')); var config = require(path.resolve('./config/config')); var async = require('async'); var startTask = { action: function (task, context, callback) { if(context.bot.authKey != undefined && context.botUser.options && context.bot.authKey == context.botUser.options.authKey) { context.botUser.isOwner = true; // context.bot.authKey = null; } task.result = {smartReply: ['예약', '위치', '영업시간', '메뉴']}; context.dialog.날짜입력최초 = undefined; context.dialog.시간입력최초 = undefined; context.dialog.인원선택최초 = undefined; if(context.botUser.isOwner) { reserveCheck.action(task, context, function(_task, context) { callback(task, context); }) } else { callback(task, context); } } }; exports.startTask = startTask; exports.mapTask = { action: function(task, context, callback) { task.address = context.bot.address; task.name = context.bot.name; daumgeoCode(task, context, function(_task, context) { task.result = { buttons: [ {text: '지도보기', url: task.url} ] }; callback(task, context); }); } }; exports.menuImageTask = { action: function(task, context, callback) { if(context.bot.menuImage) { var img = context.bot.menuImage.startsWith('http') ? context.bot.menuImage : config.host + context.bot.menuImage; task.result = { image: {url: img}, buttons: [ {text: '자세히보기', url: img} ] }; } callback(task, context); } }; function naverGeocode(task, context, callback) { var query = {query: task.address}; var request = require('request'); request({ url: 'https://openapi.naver.com/v1/map/geocode?encoding=utf-8&coord=latlng&output=json', method: 'GET', qs: query, headers: { 'Host': 'openapi.naver.com', 'Accept': '*/*', 'Content-Type': 'application/json', 'X-Naver-Client-Id': context.bot.naver.clientId, 'X-Naver-Client-Secret': context.bot.naver.clientSecret } }, function(error, response, body) { if (!error && response.statusCode == 200) { // console.log(body); var doc = JSON.parse(body); task.lng=doc.result.items[0].point.x; task.lat=doc.result.items[0].point.y; console.log('lat: ' + task.lat + ', lng: ' + task.lng); } callback(task, context); }); } exports.naverGeocode = naverGeocode; function daumgeoCode (task, context, callback) { // if (context.dialog.bank == undefined) { // callback(false); // } else { naverGeocode(task, context, function(task, context) { var request = require('request'); var query = {q: task.address, output: "json"}; task._doc = { lng: '', lat: '', link_find: '', link_map: '', address: '' }; request({ url: 'https://apis.daum.net/local/geo/addr2coord?apikey=1b44a3a00ebe0e33eece579e1bc5c6d2', method: 'GET', qs: query }, function (error, response, body) { if (!error && response.statusCode == 200) { // console.log(body); var doc = JSON.parse(body); task._doc.link_map = 'http://map.daum.net/link/map/' + task.name + ',' + task.lat + ',' + task.lng; task.url = task._doc.link_map; task.urlMessage = '지도에서 위치보기'; } callback(task, context); }); }) // } } exports.daumgeoCode = daumgeoCode; function numOfPersonTypeCheck(inRaw, _type, inDoc, context, callback) { var re; if(_type.init) re = /(\d)\s*명?/g; else re = /(\d)(?:\s*명)?/g; var matched = inRaw.match(re); if(matched != null) { try { context.dialog.numOfPerson = parseInt(matched[0]); callback(inRaw, inDoc, true); } catch(e) { console.log(e); callback(inRaw, inDoc, false); } } else { var num = type.parseNumber(inRaw); if(num != inRaw) { try { context.dialog.numOfPerson = parseInt(num); callback(inRaw, inDoc, true); } catch(e) { console.log(e); callback(inRaw, inDoc, false); } } else { callback(inRaw, inDoc, false); } } } globals.setGlobalTypeCheck('numOfPersonTypeCheck', numOfPersonTypeCheck); function checkTime(task, context, callback) { // var day = new Date().getDay(); // var holiday = dateStringToNumber(context.bot.holiday); // if (context.dialog.time.length == 4) context.dialog.time = "0" + context.dialog.time; // if (day == holiday) { if (false) { context.dialog.check = true; } else { if (context.dialog.time == 're') { context.dialog.check = 're'; } else if (context.dialog.time > context.bot.endTime || context.dialog.time < context.bot.startTime) { context.dialog.check = true; } else { context.dialog.check = false; } } var now = new Date(); var reserve = context.dialog.date; reserve.setDate(reserve.getDate()-1); reserve.setHours(context.dialog.time.substring(0,2)); reserve.setMinutes(context.dialog.time.substring(3,5)); // console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); // console.log(reserve); // console.log(now); if(reserve < now) { context.dialog.check = 'past'; } callback(task, context); } exports.checkTime = checkTime; function checkDate(task, context, callback) { var day = context.dialog.date.getDay(); var holiday = dateStringToNumber(context.bot.holiday); if (day == holiday) { context.dialog.check = true; } else { context.dialog.check = false; } var now = new Date(); var reserve = new Date(context.dialog.date.getTime()); reserve.setDate(reserve.getDate()+1); if(reserve.setDate(reserve.getDate()+1) < now) { context.dialog.check = 'past'; } callback(task, context); } exports.checkDate = checkDate; function dateStringToNumber(dateString) { if(dateString == '일요일' || dateString == '일' || dateString == 'sunday' ) return 0; else if(dateString == '월요일' || dateString == '월'|| dateString == 'monday' ) return 1; else if(dateString == '화요일' || dateString == '화'|| dateString == 'tuesday' ) return 2; else if(dateString == '수요일' || dateString == '수'|| dateString == 'wednesday' ) return 3; else if(dateString == '목요일' || dateString == '목'|| dateString == 'thursday' ) return 4; else if(dateString == '금요일' || dateString == '금'|| dateString == 'friday' ) return 5; else if(dateString == '토요일' || dateString == '토'|| dateString == 'saturday' ) return 6; else return dateString; } /********************* SMS *********************/ var smsAuth = { preCallback: function(task, context, callback) { if (task.mobile == undefined) task.mobile = context.dialog['mobile']; callback(task, context); }, action: messages.sendSMSAuth }; globals.setGlobalTask('smsAuth', smsAuth); function smsAuthValid(dialog, context, callback) { console.log(context.dialog.smsAuth); callback(dialog.inRaw.replace(/\s*/g, '') == context.dialog.smsAuth); } exports.smsAuthValid = smsAuthValid; function smsAuthinValid(dialog, context, callback) { callback(dialog.inRaw.replace(/\s*/g, '') != context.dialog.smsAuth); } exports.smsAuthinValid = smsAuthinValid; var smsAuthTask = { action: function (task, context, callback) { context.user['mobile'] = context.dialog['mobile']; context.user.updates = ['mobile']; botUser.updateUserContext(context.user, context, function () { context.user.updates = null; context.dialog.smsAuth == null; callback(task, context); }); } }; globals.setGlobalTask('smsAuthTask', smsAuthTask); /********************* 예약 *********************/ function reserveConfirm(task, context, callback) { context.dialog['dateStr'] = dateformat(context.dialog.date + 9 * 60 * 60, 'mm월dd일'); callback(task, context); } globals.setGlobalAction('reserveConfirm', reserveConfirm); function reserveRequest(task, context, callback) { var doc = { name: context.dialog.name, mobile: context.dialog.mobile || context.user.mobile, date: context.dialog.date, time: context.dialog.time, // numOfPerson: context.dialog.numOfPerson, status: '예약요청중', upTemplateId: context.bot.templateDataId, userKey: context.user.userKey }; var fields = context.bot.reserveFields || []; for(var i = 0; i < fields.length; i++) { var field = fields[i]; doc[field.name] = context.dialog[field.name]; } var TemplateReservation = mongoModule.getModel('TemplateReservation'); var templateReservation = new TemplateReservation(doc); templateReservation.save(function(err) { if(!context.bot.testMode) { var randomNum = ''; randomNum += '' + Math.floor(Math.random() * 10); randomNum += '' + Math.floor(Math.random() * 10); randomNum += '' + Math.floor(Math.random() * 10); randomNum += '' + Math.floor(Math.random() * 10); var url = config.host + '/mobile#/chat/' + context.bot.id + '?authKey=' + randomNum; context.bot.authKey = randomNum; var query = {url: url}; var request = require('request'); request({ url: 'https://openapi.naver.com/v1/util/shorturl', method: 'POST', form: query, headers: { 'Host': 'openapi.naver.com', 'Accept': '*/*', 'Content-Type': 'application/json', 'X-Naver-Client-Id': context.bot.naver.clientId, 'X-Naver-Client-Secret': context.bot.naver.clientSecret } }, function(error, response, body) { if (!error && response.statusCode == 200) { var shorturl; try {shorturl = JSON.parse(body).result.url; } catch(e) {console.log(e);} var message = '[플레이챗]' + '\n' + context.dialog.name + '/' + context.dialog.dateStr + '/'; // context.dialog.numOfPerson + '명\n' + if (context.dialog.time) { messages += context.dialog.time + '/'; } for(var i = 0; i < fields.length; i++) { var field = fields[i]; if(field.name == 'numOfPerson') { message += context.dialog[field.name] + '명/'; } else { message += context.dialog[field.name] + '/'; } } message += '\n' + (context.dialog.mobile || context.user.mobile) + '\n' + '예약접수(클릭) ' + shorturl; request.post( 'https://bot.moneybrain.ai/api/messages/sms/send', {json: {callbackPhone: context.bot.phone, phone: context.bot.mobile.replace(/,/g, ''), message: message}}, function (error, response, body) { callback(task, context); } ); } else { callback(task, context); } }); } else { callback(task, context); } }); } globals.setGlobalAction('reserveRequest', reserveRequest); var reserveCheck = { action: function (task, context, callback) { if(context.botUser.isOwner) { var TemplateReservation = mongoModule.getModel('TemplateReservation'); TemplateReservation.find({ upTemplateId: context.bot.templateDataId, status: '예약요청중', date: {$gte: new Date()} }).lean().sort({date: -1, time: -1}).exec(function(err, docs) { if(docs && docs.length > 0) { for(var i in docs) { docs[i].dateStr = dateformat(docs[i].date + 9 * 60 * 60, 'mm월dd일'); } context.dialog.reserves = docs; context.dialog.reserve = undefined; } else { context.dialog.reserves = undefined; context.dialog.reserve = undefined; } callback(task, context); }); } else { var TemplateReservation = mongoModule.getModel('TemplateReservation'); TemplateReservation.find({ upTemplateId: context.bot.templateDataId, userKey: context.user.userKey, status: {$ne: '취소'}, date: {$gte: new Date()} }).lean().sort({date: -1, time: -1}).exec(function(err, docs) { if(docs && docs.length > 1) { for(var i in docs) { docs[i].dateStr = dateformat(docs[i].date + 9 * 60 * 60, 'mm월dd일'); } context.dialog.reserves = docs; context.dialog.reserve = undefined; } else if(docs && docs.length > 0) { docs[0].dateStr = dateformat(docs[0].date + 9 * 60 * 60, 'mm월dd일'); context.dialog.reserve = docs[0]; context.dialog.reserves = undefined; } else { context.dialog.reserves = undefined; context.dialog.reserve = undefined; } callback(task, context); }) } } }; // bot.setTask('reserveCheck', reserveCheck); exports.reserverCheck = reserveCheck; var reserveCancel = { action: function (task, context, callback) { if(context.dialog.reserve) { var TemplateReservation = mongoModule.getModel('TemplateReservation'); TemplateReservation.update({_id: context.dialog.reserve._id}, {$set: {status: '취소'}}, function (err) { if(!context.bot.testMode) { var message = '[' + context.bot.name + ']' + '\n' + context.dialog.reserve.name + '/' + context.dialog.reserve.dateStr + '/' + context.dialog.reserve.time + '/'; // context.dialog.reserve.numOfPerson + '명\n' + // context.dialog.reserve.mobile + '\n' + // '예약취소'; var fields = context.bot.reserveFields || []; for(var i = 0; i < fields.length; i++) { var field = fields[i]; if(field.name == 'numOfPerson') { message += context.dialog[field.name] + '명/'; } else { message += context.dialog[field.name] + '/'; } } message += '\n' + context.dialog.reserve.mobile + '\n' + '예약취소'; request.post( 'https://bot.moneybrain.ai/api/messages/sms/send', {json: {callbackPhone: '02-858-5683' || context.bot.phone, phone: context.bot.mobile.replace(/,/g, ''), message: message}}, function (error, response, body) { callback(task, context); } ); } else { callback(task, context); } }); } else { callback(task, context); } } }; globals.setGlobalTask('reserveCancel', reserveCancel); var reserveOwnerCancel = { action: function (task, context, callback) { if(context.dialog.reserve) { var TemplateReservation = mongoModule.getModel('TemplateReservation'); TemplateReservation.update({_id: context.dialog.reserve._id}, {$set: {status: '업주취소'}}, function (err) { if(!context.bot.testMode) { var message = '[' + context.bot.name + ']' + '\n' + context.dialog.reserve.name + '/' + context.dialog.reserve.dateStr + '/' + context.dialog.reserve.time + '/'; // context.dialog.reserve.numOfPerson + '명\n' + // '예약취소: '+ // task.inRaw + '\n' + // '매장전화: ' + context.bot.phone; var fields = context.bot.reserveFields || []; for(var i = 0; i < fields.length; i++) { var field = fields[i]; if(field.name == 'numOfPerson') { message += context.dialog.reserve[field.name] + '명/'; } else { message += context.dialog.reserve[field.name] + '/'; }s } message += '\n예약취소: '+ task.inRaw + '\n' + '매장전화: ' + context.bot.phone; request.post( 'https://bot.moneybrain.ai/api/messages/sms/send', {json: {callbackPhone: '02-858-5683' || context.bot.phone, phone: context.dialog.reserve.mobile.replace(/,/g, ''), message: message}}, function (error, response, body) { reserveCheck.action(task, context, function(_task, context) { callback(task, context); }); } ); } else { callback(task, context); } }); } else { callback(task, context); } } }; globals.setGlobalTask('reserveOwnerCancel', reserveOwnerCancel); var reserveOwnerConfirm = { action: function (task, context, callback) { if(context.dialog.reserve) { var TemplateReservation = mongoModule.getModel('TemplateReservation'); TemplateReservation.update({_id: context.dialog.reserve._id}, {$set: {status: '확정'}}, function (err) { if(!context.bot.testMode) { var message = '[' + context.bot.name + ']' + '\n' + context.dialog.reserve.name + '/' + context.dialog.reserve.dateStr + '/' + context.dialog.reserve.time + '/'; // context.dialog.reserve.numOfPerson + '명\n' + // '예약확정\n'+ // '매장전화: ' + context.bot.phone; var fields = context.bot.reserveFields || []; for(var i = 0; i < fields.length; i++) { var field = fields[i]; if(field.name == 'numOfPerson') { message += context.dialog.reserve[field.name] + '명/'; } else { message += context.dialog.reserve[field.name] + '/'; } } message += '\n예약확정\n'+ '매장전화: ' + context.bot.phone; request.post( 'https://bot.moneybrain.ai/api/messages/sms/send', {json: {callbackPhone: '02-858-5683' || context.bot.phone, phone: context.dialog.reserve.mobile.replace(/,/g, ''), message: message}}, function (error, response, body) { reserveCheck.action(task, context, function(_task, context) { callback(task, context); }) } ); } else { callback(task, context); } }); } else { callback(task, context); } } }; globals.setGlobalTask('reserveOwnerConfirm', reserveOwnerConfirm); var reserveNameTask = { action: function (task, context, callback) { context.dialog.name = task.inRaw; context.user.reserveName = task.inRaw; callback(task, context); } }; globals.setGlobalTask('reserveNameTask', reserveNameTask); var reserveMemoTask = { action: function (task, context, callback) { context.dialog.memo = task.inRaw; callback(task, context); } }; globals.setGlobalTask('reserveMemoTask', reserveMemoTask); var reservePeriodTask = { action: function (task, context, callback) { context.dialog.period = task.inRaw; callback(task, context); } }; globals.setGlobalTask('reservePeriodTask', reservePeriodTask); var menuType = { name: 'menus', typeCheck: type.mongoDbTypeCheck, limit: 5, mongo: { model: 'templatemenu', queryFields: ['name'], fields: 'name price image' , taskFields: ['_id', 'name', 'price', 'image'], taskSort: function(a, b) { if(b.matchCount > a.matchCount) return 1; else if(b.matchCount < a.matchCount) return -1; else { if(a.created && b.created) { if(b.created.getTime() < a.created.getTime()) return 1; else if(b.created.getTime() > a.created.getTime()) return -1; } return 0; } }, //query: {}, // sort: "-created", // limit: 5, minMatch: 1 } }; exports.menuType = menuType; var menuTask = { action: function (task, context, callback) { context.dialog.menus = task.typeDoc; // var items = []; // for(var i = 0; i < menus.length; i++) { // items.push({ // title: menus[i].name, // text: menus[i].price + '원', // imageUrl: menus[i].image, buttons: [{input: menus[i].name, text: '상세보기'}] // }); // } // // if(items.length > 0) task.result = {items: items}; callback(task, context); } }; globals.setGlobalTask('menuTask', menuTask); function eventCategoryAction(task, context, callback) { var model, query, sort; model = mongoModule.getModel('templateevent'); query = {upTemplateId: context.bot.templateDataId}; sort = {'_id': -1}; model.aggregate([ {$match: query}, {$sort: sort}, {$group: { _id: '$category', category: {$first: '$category'} }} ], function(err, docs) { if(docs == undefined) { callback(task, context); } else { var categorys = []; for (var i = 0; i < docs.length; i++) { var doc = docs[i]; var category = doc.category; if(!_.includes(categorys, category)){ categorys.push({name: category}); } // for (var j = 0; j < doc.category.length; j++) { // var category = doc.category[j]; // if(!_.includes(categorys, category)){ // categorys.push({name: category}); // } // } } if (categorys.length == 1) { task.doc = categorys; context.dialog.categorys = categorys; eventAction(task,context, function(task,context) { callback(task,context); }); } else if (categorys.length > 1) { task.doc = categorys; context.dialog.categorys = categorys; callback(task,context); } else { callback(task,context); } } }); } exports.eventCategoryAction = eventCategoryAction; function eventAction(task, context, callback) { var model, query, sort; if (context.dialog.categorys.length == 1) { context.dialog.category = context.dialog.categorys[0]; } model = mongoModule.getModel('templateevent'); query = {upTemplateId: context.bot.templateDataId, category: context.dialog.category.name}; sort = {'_id': +1}; model.find(query).limit(type.MAX_LIST).sort(sort).lean().exec(function(err, docs) { task.doc = docs; context.dialog.menus = docs; var result = []; async.eachSeries(task.doc, function(doc, cb) { var _doc = {}; if (doc.name) { _doc.title = doc.name; } if (doc.description) { _doc.text = doc.description; } if (doc.price) { _doc.text = _doc.text + ' ' + doc.title + '원'; } if (doc.image) { _doc.imageUrl = doc.image; } result.push(_doc); cb(null) }, function (err) { task.result = {items: result}; if (task.result.items.length == 0) { task.result = null; } callback(task, context); }); }); } exports.eventAction = eventAction; function peopleCategoryAction(task, context, callback) { var model, query, sort; model = mongoModule.getModel('templatepeople'); query = {upTemplateId: context.bot.templateDataId}; sort = {'_id': -1}; model.aggregate([ {$match: query}, {$sort: sort}, {$group: { _id: '$category', category: {$first: '$category'} }} ], function(err, docs) { if(docs == undefined) { callback(task, context); } else { var categorys = []; for (var i = 0; i < docs.length; i++) { var doc = docs[i]; var category = doc.category; if(!_.includes(categorys, category)){ categorys.push({name: category}); } // for (var j = 0; j < doc.category.length; j++) { // var category = doc.category[j]; // if(!_.includes(categorys, category)){ // categorys.push({name: category}); // } // } } if (categorys.length == 1) { task.doc = categorys; context.dialog.categorys = categorys; peopleAction(task,context, function(task,context) { callback(task,context); }); } else if (categorys.length > 1) { task.doc = categorys; context.dialog.categorys = categorys; callback(task,context); } else { callback(task,context); } } }); } exports.peopleCategoryAction = peopleCategoryAction; function peopleAction(task, context, callback) { var model, query, sort; if (context.dialog.categorys.length == 1) { context.dialog.category = context.dialog.categorys[0]; } model = mongoModule.getModel('templatepeople'); query = {upTemplateId: context.bot.templateDataId, category: context.dialog.category.name}; sort = {'_id': +1}; model.find(query).limit(type.MAX_LIST).sort(sort).lean().exec(function(err, docs) { task.doc = docs; context.dialog.menus = docs; var result = []; async.eachSeries(task.doc, function(doc, cb) { var _doc = {}; if (doc.name) { _doc.title = doc.name; } if (doc.description) { _doc.text = doc.description; } if (doc.price) { _doc.text = _doc.text + ' ' + doc.title + '원'; } if (doc.image) { _doc.imageUrl = doc.image; } result.push(_doc); cb(null) }, function (err) { task.result = {items: result}; if (task.result.items.length == 0) { task.result = null; } callback(task, context); }); }); } exports.peopleAction = peopleAction; function previewCategoryAction(task, context, callback) { var model, query, sort; model = mongoModule.getModel('templatepreview'); query = {upTemplateId: context.bot.templateDataId}; sort = {'_id': -1}; model.aggregate([ {$match: query}, {$sort: sort}, {$group: { _id: '$category', category: {$first: '$category'} }} ], function(err, docs) { if(docs == undefined) { callback(task, context); } else { var categorys = []; for (var i = 0; i < docs.length; i++) { var doc = docs[i]; var category = doc.category; if(!_.includes(categorys, category)){ categorys.push({name: category}); } // for (var j = 0; j < doc.category.length; j++) { // var category = doc.category[j]; // if(!_.includes(categorys, category)){ // categorys.push({name: category}); // } // } } if (categorys.length == 1) { task.doc = categorys; context.dialog.categorys = categorys; previewAction(task,context, function(task,context) { callback(task,context); }); } else if (categorys.length > 1) { task.doc = categorys; context.dialog.categorys = categorys; callback(task,context); } else { callback(task,context); } } }); } exports.previewCategoryAction = previewCategoryAction; function previewAction(task, context, callback) { var model, query, sort; if (context.dialog.categorys.length == 1) { context.dialog.category = context.dialog.categorys[0]; } model = mongoModule.getModel('templatepreview'); query = {upTemplateId: context.bot.templateDataId, category: context.dialog.category.name}; sort = {'_id': +1}; model.find(query).limit(type.MAX_LIST).sort(sort).lean().exec(function(err, docs) { task.doc = docs; context.dialog.menus = docs; var result = []; async.eachSeries(task.doc, function(doc, cb) { var _doc = {}; if (doc.name) { _doc.title = doc.name; } if (doc.description) { _doc.text = doc.description; } if (doc.price) { _doc.text = _doc.text + ' ' + doc.title + '원'; } if (doc.image) { _doc.imageUrl = doc.image; } result.push(_doc); cb(null) }, function (err) { task.result = {items: result}; if (task.result.items.length == 0) { task.result = null; } callback(task, context); }); }); } exports.previewAction = previewAction; function menuCategoryAction(task, context, callback) { if(context.bot.menuImage) { var img = context.bot.menuImage.startsWith('http') ? context.bot.menuImage : config.host + context.bot.menuImage; task.result = { image: {url: img}, buttons: [ {text: '메뉴판 사진 보기', url: img} ] }; } var model, query, sort; model = mongoose.model('TemplateMenu'); query = {upTemplateId: context.bot.templateDataId}; sort = {'_id': -1}; model.aggregate([ {$match: query}, {$sort: sort}, {$group: { _id: '$category', category: {$first: '$category'} }} ], function(err, docs) { if(docs == undefined) { callback(task, context); } else { var categorys = []; for (var i = 0; i < docs.length; i++) { var doc = docs[i]; var category = doc.category; if(!_.includes(categorys, category)){ categorys.push({name: category}); } // for (var j = 0; j < doc.category.length; j++) { // var category = doc.category[j]; // if(!_.includes(categorys, category)){ // categorys.push({name: category}); // } // } } if (categorys.length == 1) { task.doc = categorys; context.dialog.categorys = categorys; menuAction(task,context, function(task,context) { callback(task,context); }); } else if (categorys.length > 1) { task.doc = categorys; context.dialog.categorys = categorys; callback(task,context); } else { callback(task,context); } } }); } exports.menuCategoryAction = menuCategoryAction; function menuAction(task, context, callback) { var model, query, sort; if (context.dialog.categorys.length == 1) { context.dialog.category = context.dialog.categorys[0]; } model = mongoose.model('TemplateMenu'); query = {upTemplateId: context.bot.templateDataId, category: context.dialog.category.name}; sort = {'_id': +1}; model.find(query).limit(type.MAX_LIST).sort(sort).lean().exec(function(err, docs) { task.doc = docs; context.dialog.menus = docs; var result = []; async.eachSeries(task.doc, function(doc, cb) { var _doc = {}; if (doc.name) { _doc.title = doc.name; } if (doc.description) { _doc.text = doc.description; } else { _doc.text = ''; } if (doc.price) { _doc.text = _doc.text + ' ' + doc.price + '원'; } if (doc.image) { _doc.imageUrl = doc.image; } result.push(_doc); cb(null) }, function (err) { task.result = {items: result}; if (task.result.items.length == 0) { task.result = null; } callback(task, context); }); }); } exports.menuAction = menuAction; var menuDetailTask = { action: function(task, context, callback) { if(context.dialog.menu.image) { task.result = { image: {url: context.dialog.menu.image}, buttons: [ {text: '사진보기', url: context.dialog.menu.image.startsWith('http') ? context.dialog.menu.image : config.host + context.dialog.menu.image} ] }; } callback(task, context); } }; exports.menuDetailTask = menuDetailTask;
29.111933
146
0.574134
b7266bd4703fd456473be74accb67a72255491a2
1,119
js
JavaScript
src/components/WebGL/AppUIs/EditorWorks/archive/mesh/src/work/work.js
wonglok/compute-platform-gui
399c52f8af1847b533b3fbf28fcc2f0b6deef311
[ "MIT" ]
null
null
null
src/components/WebGL/AppUIs/EditorWorks/archive/mesh/src/work/work.js
wonglok/compute-platform-gui
399c52f8af1847b533b3fbf28fcc2f0b6deef311
[ "MIT" ]
null
null
null
src/components/WebGL/AppUIs/EditorWorks/archive/mesh/src/work/work.js
wonglok/compute-platform-gui
399c52f8af1847b533b3fbf28fcc2f0b6deef311
[ "MIT" ]
null
null
null
export const use = async ({ box, work, works, arrows }) => { let { Color, Mesh, PlaneBufferGeometry, MeshBasicMaterial } = box.deps.THREE let { workspaces } = box let api = { replaceGeometry: ({ geometry }) => { api.drawItem.geometry = geometry geometry.needsUpdate = true api.drawItem.needsUpdate = true }, replaceMaterial: ({ material }) => { api.drawItem.material = material material.needsUpdate = true api.drawItem.needsUpdate = true }, replaceDrawItem: ({ drawItem }) => { box.scene.remove(api.drawItem) api.drawItem = drawItem box.scene.add(api.drawItem) api.drawItem.needsUpdate = true }, drawItem: false } workspaces.set(work._id, api) let geo = new PlaneBufferGeometry(200, 200, 128, 128) // let geo = new BoxBufferGeometry(80, 80, 80, 24, 24, 24) let mat = new MeshBasicMaterial({ color: new Color('#bebebe') }) api.drawItem = new Mesh(geo, mat) box.scene.add(api.drawItem) // console.log('context of run time', api.drawItem, box, works, arrows) // box.scene.background = new Color('#ffba00') }
32.911765
78
0.643432
b72722c9c21b39ea75deccbc96f6afc54e8856a2
1,587
js
JavaScript
style-guide/src/components/design-system-partials/otkit-icons.js
neha-ot/design-tokens
2ef4ffa877aca1fea1900e94a0e092d02ab523e6
[ "MIT" ]
73
2017-07-26T16:12:37.000Z
2022-01-08T07:47:02.000Z
style-guide/src/components/design-system-partials/otkit-icons.js
neha-ot/design-tokens
2ef4ffa877aca1fea1900e94a0e092d02ab523e6
[ "MIT" ]
296
2017-08-01T21:55:08.000Z
2021-08-18T02:32:08.000Z
style-guide/src/components/design-system-partials/otkit-icons.js
neha-ot/design-tokens
2ef4ffa877aca1fea1900e94a0e092d02ab523e6
[ "MIT" ]
67
2017-07-31T23:05:25.000Z
2022-03-03T20:34:47.000Z
import React, { useState } from 'react'; import _ from 'lodash'; import icons from 'otkit-icons/token.common'; import SectionHeader from '../section-header'; import styles from '../../styles/otkit-icons.module.scss'; const Icons = () => { const [filter, setFilter] = useState(''); const keys = _.keys(icons).sort(); const actualIcons = _.without(keys, 'iconSize'); const getFilter = event => { const key = event.target.value || ''; setFilter(key.toLowerCase()); }; const renderHeaderContent = () => ( <input className={styles.form} type="text" onChange={getFilter} placeholder="Search icon" /> ); const tokens = actualIcons .filter(name => { if (filter === '') { return true; } const iconName = _.kebabCase(name); const regex = RegExp(`.*${filter}.*`, 'g'); return iconName.match(regex); }) .map(name => { const value = icons[name]; return ( <div className={styles.card} key={name}> <div className={styles.iconBlock}> <div className={styles.icon} dangerouslySetInnerHTML={{ __html: value }} /> </div> <div className={styles.iconName}>{_.kebabCase(name)}</div> </div> ); }); return ( <div className={styles.mainContainer}> <SectionHeader text="Icons" type="SectionHeader__small" content={renderHeaderContent()} /> <div className={styles.sectionIcon}>{tokens}</div> </div> ); }; export default Icons;
24.415385
68
0.567738
b72748d21a6b010caa14bfb56b9c52e2a718bd77
53,722
js
JavaScript
lib/sources/tests/zz.views.febase_test.js
buntarb/zz.views
8da6723d685a5e631e1513967213ee0420c165b1
[ "Apache-2.0" ]
null
null
null
lib/sources/tests/zz.views.febase_test.js
buntarb/zz.views
8da6723d685a5e631e1513967213ee0420c165b1
[ "Apache-2.0" ]
null
null
null
lib/sources/tests/zz.views.febase_test.js
buntarb/zz.views
8da6723d685a5e631e1513967213ee0420c165b1
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 Artem Lytvynov <buntarb@gmail.com>. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @license Apache-2.0 * @copyright Artem Lytvynov <buntarb@gmail.com> */ goog.provide( 'zz.views.FEBaseTest' ); goog.require( 'goog.testing.jsunit' ); goog.setTestOnly( 'zz.views.FEBaseTest' ); goog.require( 'goog.ui.ControlRenderer' ); goog.require( 'goog.ui.IdGenerator' ); goog.require( 'zz.views.FEBase' ); goog.require( 'zz.environment.services.Environment' ); goog.require( 'zz.environment.services.MVCRegistry' ); goog.require( 'zz.views.templates.default' ); goog.require( 'zz.views.enums.FEBaseUidSeparator' ); goog.require( 'zz.views.enums.FEBaseElementAttributeCode' ); goog.require( 'zz.views.enums.FEBaseElementAttribute' ); var zz_views_FEBaseTest_members = [ 'env_', 'mvcRegistry_' ]; var zz_views_FEBaseTest_methods = [ /* by default must be a function */ 'model_soy_', 'dataset_soy_', 'datarow_soy_', 'getEnvironment', 'getMVCRegistry', 'getInternalSeparator', 'getExternalSeparator', 'getFieldByUid', 'getViewElementAttribute_', 'getDataClassKeys_', 'getAttributeCode_', 'generateUid_', 'setNode_', 'getElementUid', 'getElementValue', 'setElementValue', 'isHoverHandled', 'isActionHandled', 'getActionElement', 'attachElement_', 'detachElement_', 'createDatarowElements_', 'createModelElements_', 'updateElementsClasses_', 'createElementsControllers_', 'createDom', 'setState', 'renderDatarow', 'removeDatarow', 'updateDatarow' ]; var zz_views_FEBaseTest_testSubj = new zz.views.FEBase( ); function test_zz_views_FEBaseTest_availableMembers( ){ var checkIfIsFun = true; zz.tests.checkMembers( zz_views_FEBaseTest_members, zz_views_FEBaseTest_testSubj ); zz.tests.checkMembers( zz_views_FEBaseTest_methods, zz_views_FEBaseTest_testSubj, checkIfIsFun, 'Methods:' ); } function test_zz_views_FEBaseTest_constructor( ){ assertTrue( 'Instance must be non-null and have the expected type', zz_views_FEBaseTest_testSubj instanceof zz.views.FEBase ); } function test_zz_views_FEBaseTest_inheritance( ){ assertTrue( 'Instance must be non-null and have the expected class', zz_views_FEBaseTest_testSubj instanceof goog.ui.ControlRenderer ); } function test_zz_views_FEBaseTest_env( ){ assertTrue( 'Property must have the expected type', zz_views_FEBaseTest_testSubj.env_ instanceof zz.environment.services.Environment ); } function test_zz_views_FEBaseTest_mvcRegistry( ){ assertTrue( 'Property must have the expected type', zz_views_FEBaseTest_testSubj.mvcRegistry_ instanceof zz.environment.services.MVCRegistry ); } function test_zz_views_FEBaseTest_model_soy( ){ assertEquals( 'Expected certain default value', zz.views.templates.default.model, zz_views_FEBaseTest_testSubj.model_soy_ ); } function test_zz_views_FEBaseTest_dataset_soy( ){ assertEquals( 'Expected certain default value', zz.views.templates.default.dataset, zz_views_FEBaseTest_testSubj.dataset_soy_ ); } function test_zz_views_FEBaseTest_datarow_soy( ){ assertEquals( 'Expected certain default value', zz.views.templates.default.datarow, zz_views_FEBaseTest_testSubj.datarow_soy_ ); } function test_zz_views_FEBaseTest_getEnvironment( ){ assertEquals( 'Expected certain value', zz_views_FEBaseTest_testSubj.env_, zz_views_FEBaseTest_testSubj.getEnvironment( ) ); } function test_zz_views_FEBaseTest_getMVCRegistry( ){ assertEquals( 'Expected certain value', zz_views_FEBaseTest_testSubj.mvcRegistry_, zz_views_FEBaseTest_testSubj.getMVCRegistry( ) ); } function test_zz_views_FEBaseTest_getInternalSeparator( ){ assertEquals( 'Expected certain value', zz.views.enums.FEBaseUidSeparator.INTERNAL, zz_views_FEBaseTest_testSubj.getInternalSeparator( ) ); } function test_zz_views_FEBaseTest_getExternalSeparator( ){ assertEquals( 'Expected certain value', zz.views.enums.FEBaseUidSeparator.EXTERNAL, zz_views_FEBaseTest_testSubj.getExternalSeparator( ) ); } function test_zz_views_FEBaseTest_getFieldByUid( ){ var name = 'name'; var uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + zz.views.enums.FEBaseElementAttributeCode.INPUT + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + name; assertEquals( 'Expected certain value', name, zz_views_FEBaseTest_testSubj.getFieldByUid( uid ) ); uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + zz.views.enums.FEBaseElementAttributeCode.INPUT + zz_views_FEBaseTest_testSubj.getInternalSeparator( ); assertTrue( 'Expected certain type', typeof zz_views_FEBaseTest_testSubj.getFieldByUid( uid ) === 'string' ); uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'NoInputAttributeCode' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.getFieldByUid( uid ) ); uid = 'prefix_'; assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.getFieldByUid( uid ) ); } function test_zz_views_FEBaseTest_getViewElementAttribute( ){ var elementName = 'span'; var attrId = 'attrId'; var attrClass = 'attrClass1 attrClass2'; var attrNoExists = 'attrNoExists'; var attrEmpty = 'attrEmpty'; var dir = 'someDir'; var attrs = [ zz.views.enums.FEBaseElementAttribute.ACTION, zz.views.enums.FEBaseElementAttribute.FOCUS, zz.views.enums.FEBaseElementAttribute.BLUR, zz.views.enums.FEBaseElementAttribute.KEY, zz.views.enums.FEBaseElementAttribute.SCROLL, zz.views.enums.FEBaseElementAttribute.HOVER ]; var i = 0; var attributes = { 'id': attrId, 'class': attrClass, attrEmpty: '', title: '', dir: dir }; for( i = 0; i < attrs.length; i++ ){ attributes[ attrs[ i ] ] = ""; } var element = goog.dom.createDom( elementName, attributes ); assertEquals( 'Expected certain value', attrId, zz_views_FEBaseTest_testSubj.getViewElementAttribute_( element, 'id' ) ); assertEquals( 'Expected certain value', attrClass, zz_views_FEBaseTest_testSubj.getViewElementAttribute_( element, 'class' ) ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.getViewElementAttribute_( element, attrNoExists ) ); for( i = 0; i < attrs.length; i++ ){ assertEquals( 'Expected certain value', attrs[ i ], zz_views_FEBaseTest_testSubj.getViewElementAttribute_( element, attrs[ i ] ) ); } assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.getViewElementAttribute_( element, attrEmpty ) ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.getViewElementAttribute_( element, 'title' ) ); assertEquals( 'Expected certain value', dir, zz_views_FEBaseTest_testSubj.getViewElementAttribute_( element, 'dir' ) ); } function test_zz_views_FEBaseTest_getDataClassKeys( ){ var dataClass = 'c1:v1,c2:v2, c3:v3, :v4,:v5,c4, c5, c6 ,:, :, : , ,,'; var expectedArray = [ 'c1', 'c2', 'c3', 'c4', 'c5', 'c6' ]; assertArrayEquals( 'Returned value is not correct', expectedArray, zz_views_FEBaseTest_testSubj.getDataClassKeys_( dataClass ) ); dataClass = ''; assertTrue( 'Expected certain type', goog.isArray( zz_views_FEBaseTest_testSubj.getDataClassKeys_( dataClass ) ) ); } function test_zz_views_FEBaseTest_getAttributeCode( ){ var attrNoCode = 'attrNoCode'; var attrNames = [ zz.views.enums.FEBaseElementAttribute.UID, zz.views.enums.FEBaseElementAttribute.SET, zz.views.enums.FEBaseElementAttribute.ROW, zz.views.enums.FEBaseElementAttribute.MODEL, zz.views.enums.FEBaseElementAttribute.INPUT, zz.views.enums.FEBaseElementAttribute.FOCUS, zz.views.enums.FEBaseElementAttribute.BLUR, zz.views.enums.FEBaseElementAttribute.KEY, zz.views.enums.FEBaseElementAttribute.ACTION, zz.views.enums.FEBaseElementAttribute.SCROLL, zz.views.enums.FEBaseElementAttribute.CLASS, zz.views.enums.FEBaseElementAttribute.HOVER ]; var attrCodes = [ zz.views.enums.FEBaseElementAttributeCode.UID, zz.views.enums.FEBaseElementAttributeCode.SET, zz.views.enums.FEBaseElementAttributeCode.ROW, zz.views.enums.FEBaseElementAttributeCode.MODEL, zz.views.enums.FEBaseElementAttributeCode.INPUT, zz.views.enums.FEBaseElementAttributeCode.FOCUS, zz.views.enums.FEBaseElementAttributeCode.BLUR, zz.views.enums.FEBaseElementAttributeCode.KEY, zz.views.enums.FEBaseElementAttributeCode.ACTION, zz.views.enums.FEBaseElementAttributeCode.SCROLL, zz.views.enums.FEBaseElementAttributeCode.CLASS, zz.views.enums.FEBaseElementAttributeCode.HOVER ]; var i = 0; var attrCodeMap = { }; for( i = 0; i < attrNames.length; i++ ){ attrCodeMap[ attrNames[ i ] ] = attrCodes[ i ]; } for( var attr in attrCodeMap ){ assertEquals( 'Expected certain value', attrCodeMap[ attr ], zz_views_FEBaseTest_testSubj.getAttributeCode_( attr ) ); } assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.getAttributeCode_( attrNoCode ) ); } function test_zz_views_FEBaseTest_generateUid( ){ var idGenerator = goog.ui.IdGenerator.getInstance( ); var nextUniqueId = 'nextUniqueId'; stubs.replace( idGenerator, 'getNextUniqueId', function( ){ return nextUniqueId; } ); var attr; var uid = 'uid'; var opt_val = 'key:val'; var attrNames = [ zz.views.enums.FEBaseElementAttribute.SET, zz.views.enums.FEBaseElementAttribute.ROW ]; var i = 0; for( i = 0; i < attrNames.length; i++ ){ attr = attrNames[ i ]; assertEquals( 'Expected certain value', uid, zz_views_FEBaseTest_testSubj.generateUid_( uid, attr, opt_val ) ); } attrNames = [ zz.views.enums.FEBaseElementAttribute.MODEL, zz.views.enums.FEBaseElementAttribute.INPUT ]; for( i = 0; i < attrNames.length; i++ ){ attr = attrNames[ i ]; assertEquals( 'Expected certain value', ( uid + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + zz_views_FEBaseTest_testSubj.getAttributeCode_( attr ) + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + opt_val ), zz_views_FEBaseTest_testSubj.generateUid_( uid, attr, opt_val ) ); } attrNames = [ zz.views.enums.FEBaseElementAttribute.ACTION, zz.views.enums.FEBaseElementAttribute.FOCUS, zz.views.enums.FEBaseElementAttribute.BLUR, zz.views.enums.FEBaseElementAttribute.KEY, zz.views.enums.FEBaseElementAttribute.SCROLL, zz.views.enums.FEBaseElementAttribute.HOVER ]; for( i = 0; i < attrNames.length; i++ ){ attr = attrNames[ i ]; assertEquals( 'Expected certain value', ( uid + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + zz_views_FEBaseTest_testSubj.getAttributeCode_( attr ) + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + idGenerator.getNextUniqueId( ) ), zz_views_FEBaseTest_testSubj.generateUid_( uid, attr, opt_val ) ); } attr = zz.views.enums.FEBaseElementAttribute.CLASS; assertEquals( 'Expected certain value', ( uid + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + zz_views_FEBaseTest_testSubj.getAttributeCode_( attr ) + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'key' ), zz_views_FEBaseTest_testSubj.generateUid_( uid, attr, opt_val ) ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.generateUid_( uid, 'noAttr', opt_val ) ); } function test_zz_views_FEBaseTest_setNode( ){ var elementName = 'span'; var enableFocusHandlingAttr = 'enableFocusHandling'; var enableKeyHandlingAttr = 'enableKeyHandling'; var attrs = [ enableFocusHandlingAttr ,enableKeyHandlingAttr ]; var i = 0; var attributes = { }; for( i = 0; i < attrs.length; i++ ){ attributes[ attrs[ i ] ] = false; } var modelUid = 'modelUid'; var model = { getUid: function( ){ return modelUid; } }; var controller = { enableFocusHandling: function( element ){ element.setAttribute( enableFocusHandlingAttr, true ); }, enableKeyHandling: function( element ){ element.setAttribute( enableKeyHandlingAttr, true ); } } var idGenerator = goog.ui.IdGenerator.getInstance( ); var nextUniqueId = 'nextUniqueId'; stubs.replace( idGenerator, 'getNextUniqueId', function( ){ return nextUniqueId; } ); stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'set', function( uid ){ assertTrue( 'Must start with ' + modelUid, goog.string.startsWith( uid, modelUid ) ); } ); goog.object.forEach( zz.views.enums.FEBaseElementAttribute, function( attribute ){ if( zz.views.enums.FEBaseElementAttribute.UID !== attribute ){ attributes[ attribute ] = false; } } ); var element = goog.dom.createDom( elementName, attributes ); goog.define( 'goog.DEBUG', false ); zz_views_FEBaseTest_testSubj.setNode_( model, element, controller ); goog.object.forEach( zz.views.enums.FEBaseElementAttribute, function( attribute ){ if( attribute === zz.views.enums.FEBaseElementAttribute.UID || attribute === zz.views.enums.FEBaseElementAttribute.CLASS || attribute === zz.views.enums.FEBaseElementAttribute.CONTROLLER || attribute === zz.views.enums.FEBaseElementAttribute.VIEW){ assertTrue( 'Must have an attribute ' + attribute, element.hasAttribute( attribute ) ) } else { assertFalse( 'Must not have an attribute ' + attribute, element.hasAttribute( attribute ) ) } } ); goog.object.forEach( attrs, function( attribute ){ assertTrue( 'Must have an attribute ' + attribute, element.hasAttribute( attribute ) ); } ); element = goog.dom.createDom( elementName, attributes ); goog.define( 'goog.DEBUG', true ); zz_views_FEBaseTest_testSubj.setNode_( model, element, controller ); goog.object.forEach( zz.views.enums.FEBaseElementAttribute, function( attribute ){ if( attribute === zz.views.enums.FEBaseElementAttribute.UID || attribute === zz.views.enums.FEBaseElementAttribute.CLASS || attribute === zz.views.enums.FEBaseElementAttribute.CONTROLLER || attribute === zz.views.enums.FEBaseElementAttribute.VIEW){ assertTrue( 'Must have an attribute ' + attribute, element.hasAttribute( attribute ) ) } else { assertTrue( 'Must have an attribute ' + attribute, element.hasAttribute( attribute ) ) } } ); goog.object.forEach( attrs, function( attribute ){ assertTrue( 'Must have an attribute ' + attribute, element.hasAttribute( attribute ) ); } ); var predefinedId = 'predefinedId'; attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = predefinedId; element = goog.dom.createDom( elementName, attributes ); zz_views_FEBaseTest_testSubj.setNode_( model, element, controller ); assertTrue( 'Must have an attribute ' + zz.views.enums.FEBaseElementAttribute.UID, element.hasAttribute( zz.views.enums.FEBaseElementAttribute.UID ) ) element.removeAttribute( zz.views.enums.FEBaseElementAttribute.UID ); assertFalse( 'Must have no attributes ', element.hasAttributes( ) ) } function test_zz_views_FEBaseTest_getElementUid( ){ var predefinedId = 'predefinedId'; var elementName = 'span'; var attributes = { }; var element = goog.dom.createDom( elementName, attributes ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.getElementUid( element ) ); attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = ''; element = goog.dom.createDom( elementName, attributes ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.getElementUid( element ) ); attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = predefinedId; element = goog.dom.createDom( elementName, attributes ); assertEquals( 'Expected certain value', predefinedId, zz_views_FEBaseTest_testSubj.getElementUid( element ) ); } function test_zz_views_FEBaseTest_getElementValue( ){ var elementName = 'span'; var text = 'text'; var value = 'value'; var element = goog.dom.createDom( elementName, undefined, text ); assertEquals( 'Expected certain value', text, zz_views_FEBaseTest_testSubj.getElementValue( element ) ); zz_views_FEBaseTest_testSubj.setElementValue( element, value ); assertEquals( 'Expected certain value', value, zz_views_FEBaseTest_testSubj.getElementValue( element ) ); zz_views_FEBaseTest_testSubj.setElementValue( element, null ); assertEquals( 'Expected certain value', '', zz_views_FEBaseTest_testSubj.getElementValue( element ) ); zz_views_FEBaseTest_testSubj.setElementValue( element, undefined ); assertEquals( 'Expected certain value', '', zz_views_FEBaseTest_testSubj.getElementValue( element ) ); zz_views_FEBaseTest_testSubj.setElementValue( element ); assertEquals( 'Expected certain value', '', zz_views_FEBaseTest_testSubj.getElementValue( element ) ); } function test_zz_views_FEBaseTest_setElementValue( ){ var elementName = 'span'; var value = 'value'; var element = goog.dom.createDom( elementName ); zz_views_FEBaseTest_testSubj.setElementValue( element, value ); assertEquals( 'Expected certain value', value, zz_views_FEBaseTest_testSubj.getElementValue( element ) ); zz_views_FEBaseTest_testSubj.setElementValue( element, null ); assertEquals( 'Expected certain value', '', zz_views_FEBaseTest_testSubj.getElementValue( element ) ); zz_views_FEBaseTest_testSubj.setElementValue( element, undefined ); assertEquals( 'Expected certain value', '', zz_views_FEBaseTest_testSubj.getElementValue( element ) ); zz_views_FEBaseTest_testSubj.setElementValue( element ); assertEquals( 'Expected certain value', '', zz_views_FEBaseTest_testSubj.getElementValue( element ) ); } function test_zz_views_FEBaseTest_isHoverHandled( ){ var elementName = 'span'; var element = goog.dom.createDom( elementName ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.isHoverHandled( element ) ); var uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'someAttr' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'suffix'; var attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = uid; element = goog.dom.createDom( elementName, attributes ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.isHoverHandled( element ) ); uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + zz.views.enums.FEBaseElementAttributeCode.HOVER + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'suffix'; attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = uid; element = goog.dom.createDom( elementName, attributes ); assertTrue( 'Expected certain value', zz_views_FEBaseTest_testSubj.isHoverHandled( element ) ); } function test_zz_views_FEBaseTest_isActionHandled( ){ var elementName = 'span'; var element = goog.dom.createDom( elementName ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.isActionHandled( element ) ); var uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'someAttr' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'suffix'; var attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = uid; element = goog.dom.createDom( elementName, attributes ); assertFalse( 'Expected certain value', zz_views_FEBaseTest_testSubj.isActionHandled( element ) ); uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + zz.views.enums.FEBaseElementAttributeCode.ACTION + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'suffix'; attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = uid; element = goog.dom.createDom( elementName, attributes ); assertTrue( 'Expected certain value', zz_views_FEBaseTest_testSubj.isActionHandled( element ) ); } function test_zz_views_FEBaseTest_getActionElement( ){ var controller = undefined; var elementName = 'span'; var element = goog.dom.createDom( elementName ); assertNull( 'Expected certain value', zz_views_FEBaseTest_testSubj.getActionElement( controller, element ) ); var uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'someAttr' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'suffix'; var attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = uid; element = goog.dom.createDom( elementName, attributes ); assertNull( 'Expected certain value', zz_views_FEBaseTest_testSubj.getActionElement( controller, element ) ); uid = 'prefix_' + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + zz.views.enums.FEBaseElementAttributeCode.ACTION + zz_views_FEBaseTest_testSubj.getInternalSeparator( ) + 'suffix'; attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.UID ] = uid; element = goog.dom.createDom( elementName, attributes ); assertEquals( 'Expected certain value', element, zz_views_FEBaseTest_testSubj.getActionElement( controller, element ) ); var childElement = goog.dom.createDom( elementName ); element = goog.dom.createDom( elementName, attributes, childElement ); assertEquals( 'Expected certain value', element, zz_views_FEBaseTest_testSubj.getActionElement( controller, childElement ) ); } function test_zz_views_FEBaseTest_attachElement( ){ var elementName = 'span'.toLowerCase( ); var element = goog.dom.createDom( // 1 on top level 0 elementName, undefined, [ // 3 on next level 1 goog.dom.createDom( elementName, undefined, [ // 2 on next level 2 goog.dom.createDom( elementName, undefined, [ // 1 on next level 3 goog.dom.createDom( elementName ) ] ), goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ) ] ), goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ), goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ) ] ), goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ), goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ) ] ) ] ); var expectedCount = 1 + ( 1 * 3 ) + ( 3 * 2 ) + ( ( 3 * 2 ) * 1 ); // = 1 + 3 + 6 + 6 = 16 var count = 0; stubs.replace( zz_views_FEBaseTest_testSubj, 'setNode_', function( datarow, element, controller ){ assertEquals( 'Must be an Element', elementName, element.nodeName.toLowerCase( ) ); count++; } ); zz_views_FEBaseTest_testSubj.attachElement_( undefined, element, undefined ); assertEquals( 'Not all elements were processed in the tree', expectedCount, count ); } function test_zz_views_FEBaseTest_detachElement( ){ var elementName = 'span'.toLowerCase( ); var attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.CONTROLLER ] = true; var uid = 'id1' + zz.views.enums.FEBaseUidSeparator.EXTERNAL + 'id2' + zz.views.enums.FEBaseUidSeparator.EXTERNAL + 'id3'; var countGetElementUid = 0; var countDisposed = 0; var countDeleted = 0; var node = { controller: { dispose: function( ){ countDisposed++; } } } stubs.replace( zz_views_FEBaseTest_testSubj, 'getElementUid', function( element ){ assertEquals( 'Must be an Element', elementName, element.nodeName.toLowerCase( ) ); countGetElementUid++; return uid; } ); stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'get', function( uid ){ return node; } ); stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'delete', function( uid ){ countDeleted++; } ); var element = goog.dom.createDom( // 1 on top level 0 elementName, undefined, [ // 3 on next level 1 goog.dom.createDom( elementName, attributes, // has controller attribute [ // 2 on next level 2 goog.dom.createDom( elementName, undefined, [ // 1 on next level 3 goog.dom.createDom( elementName ) ] ), goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ) ] ), goog.dom.createDom( elementName, attributes, // has controller attribute [ goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ), goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ) ] ), goog.dom.createDom( elementName, attributes, // has controller attribute [ goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ), goog.dom.createDom( elementName, undefined, [ goog.dom.createDom( elementName ) ] ) ] ) ] ); var expectedCountGetElementUid = 16; // actually 19 var expectedCountDisposed = 3; // is exact number of elements with controller attribute var expectedCountDeleted = expectedCountGetElementUid + ( expectedCountGetElementUid * uid.split( zz.views.enums.FEBaseUidSeparator.EXTERNAL).length ); zz_views_FEBaseTest_testSubj.detachElement_( element ); assertTrue( 'Not all elements were processed in the tree', countGetElementUid >= expectedCountGetElementUid ); assertEquals( 'Not all elements were disposed', expectedCountDisposed, countDisposed ); assertEquals( 'Not all elements were deleted', expectedCountDeleted, countDeleted ); } function test_zz_views_FEBaseTest_createDatarowElements( ){ var expectedIndex = 5; var foundIndex = undefined; var datarow = { getUid: function( ){ return expectedIndex; } }; var dataset = { index: undefined, firstDatarow: function( ){ this.index = 0; }, currentDatarow: function( ){ var self = this; return { getUid: function( ){ return self.index; } }; }, nextDatarow: function( ){ this.index++; if( this.index > expectedIndex * 2 ){ return false; } return true; }, getUid: function( ){ return null; } }; stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'get', function( ){ return { elements: [ goog.dom.createDom( 'span' ) ], controller: null }; } ); stubs.replace( soy, 'renderAsElement', function( ){ return null; } ); stubs.replace( goog.dom, 'insertChildAt', function( datasetElement, datarowElement, index ){ foundIndex = index; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'setNode_', function( ){ } ); zz_views_FEBaseTest_testSubj.createDatarowElements_( dataset, datarow ); assertEquals( 'Expected certain value', expectedIndex, foundIndex ); } function test_zz_views_FEBaseTest_createModelElements( ){ var isMvcRegistryGet = false; var isSoyRenderAsElement = false; var isGoogDomAppendChild = false; var isAttachElement = false; var datarow = { getUid: function( ){ return null; } }; var dataset = { getUid: function( ){ return null; } }; stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'get', function( ){ isMvcRegistryGet = true; return { elements: [ goog.dom.createDom( 'span' ) ], controller: { getModel: function( ){ return { datafield: null } } } }; } ); stubs.replace( soy, 'renderAsElement', function( ){ isSoyRenderAsElement = true; return null; } ); stubs.replace( goog.dom, 'appendChild', function( ){ isGoogDomAppendChild = true; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'attachElement_', function( ){ isAttachElement = true; } ); zz_views_FEBaseTest_testSubj.createModelElements_( dataset, datarow ); assertEquals( 'Expected using a chain of methods', true, isMvcRegistryGet && isSoyRenderAsElement && isGoogDomAppendChild && isAttachElement ); } function test_zz_views_FEBaseTest_updateElementsClasses( ){ var elementName = 'span'.toLowerCase( ); var i = 1; var fieldCount = 4; var dataset = { datafield: { } }; var datarow = { getUid: function( ){ return 'datarowUid'; } }; for( i = 1; i <= fieldCount; i++ ){ dataset.datafield[ 'field' + i ] = 'field' + i; if( i % 2 ){ datarow[ 'field' + i ] = 'field' + i; } } i = 0; var j = 0; var elementsArray; var element; var nodes = { }; for( var field in dataset.datafield ){ var attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.CLASS ] = 'prefix' + field + zz.views.enums.FEBaseUidSeparator.CLASS_INTERNAL + 'className1' + zz.views.enums.FEBaseUidSeparator.CLASS_EXTERNAL + 'className2' + zz.views.enums.FEBaseUidSeparator.CLASS_EXTERNAL + 'className3'; elementsArray = [ ]; for( j = 0; j < 3; j++ ){ element = goog.dom.createDom( elementName, attributes ); if( i % 2 ){ goog.dom.classlist.add( element, 'className1' ); } elementsArray.push( element ); } nodes[ datarow.getUid( ) + zz.views.enums.FEBaseUidSeparator.INTERNAL + zz.views.enums.FEBaseElementAttributeCode.CLASS + zz.views.enums.FEBaseUidSeparator.INTERNAL + field ] = { model: undefined, controller: undefined, elements: elementsArray }; i++; } stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'get', function( uid ){ return nodes[ uid ]; } ); zz_views_FEBaseTest_testSubj.updateElementsClasses_( dataset, datarow ); for( i = 1; i <= fieldCount; i++ ){ elementsArray = nodes[ datarow.getUid( ) + zz.views.enums.FEBaseUidSeparator.INTERNAL + zz.views.enums.FEBaseElementAttributeCode.CLASS + zz.views.enums.FEBaseUidSeparator.INTERNAL + 'field' + i ][ 'elements' ]; for( j = 0; j < elementsArray.length; j++ ){ element = elementsArray[ j ]; if( i % 2 ){ assertTrue( 'Element must contain class', goog.dom.classlist.contains( element, 'className1' ) ); } else { assertFalse( 'Element must not contain class', goog.dom.classlist.contains( element, 'className1' ) ); } } } } function test_zz_views_FEBaseTest_createElementsControllers( ){ var elementName = 'span'.toLowerCase( ); var i = 1; var fieldCount = 4; var rootControllers = { }; var dataset = { datafield: { }, getDatarowSchema: function( ){ var datarowSchema = { }; for( var f in this.datafield ){ datarowSchema[ f ] = { type: function( ){ } }; } return datarowSchema; } }; var datarow = { getUid: function( ){ return 'datarowUid'; } }; var expectedRendered = 0; var factRendered = 0; for( i = 1; i <= fieldCount; i++ ){ dataset.datafield[ 'field' + i ] = 'field' + i; rootControllers[ 'field' + i ] = new goog.ui.Component( ); stubs.replace( rootControllers[ 'field' + i ], 'render', function( ){ factRendered++; } ); } i = 0; var j = 0; var elementsArray; var element; var nodes = { }; for( var field in dataset.datafield ){ var attributes = { }; attributes[ zz.views.enums.FEBaseElementAttribute.VIEW ] = 'viewName'; attributes[ zz.views.enums.FEBaseElementAttribute.CONTROLLER ] = field; elementsArray = [ ]; for( j = 0; j < 3; j++ ){ element = goog.dom.createDom( elementName, attributes ); elementsArray.push( element ); expectedRendered++; } var controller = new goog.ui.Component( ); nodes[ datarow.getUid( ) + zz.views.enums.FEBaseUidSeparator.INTERNAL + zz.views.enums.FEBaseElementAttributeCode.MODEL + zz.views.enums.FEBaseUidSeparator.INTERNAL + field ] = { model: undefined, controller: controller, elements: elementsArray }; assertFalse( 'Node controller must not have its child controllers before', controller.hasChildren( ) ); i++; } stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'get', function( uid ){ return nodes[ uid ]; } ); stubs.replace( zz.environment.services.MVCRegistry, 'getView', function( viewName ){ return viewName; // no matter what it is } ); stubs.replace( zz.environment.services.MVCRegistry, 'getController', function( controllerName, field, view ){ return rootControllers[ controllerName ]; } ); zz_views_FEBaseTest_testSubj.createElementsControllers_( dataset, datarow ); for( i = 1; i <= fieldCount; i++ ){ var node = nodes[ datarow.getUid( ) + zz.views.enums.FEBaseUidSeparator.INTERNAL + zz.views.enums.FEBaseElementAttributeCode.MODEL + zz.views.enums.FEBaseUidSeparator.INTERNAL + 'field' + i ]; var nodeController = node.controller; assertTrue( 'Node controller must have its child field controllers', nodeController.hasChildren( ) ); assertFalse( 'Field controller must not have its child controllers and must be as is', rootControllers[ 'field' + i ].hasChildren( ) ); } assertEquals( 'Expected certain number of elements are rendered', expectedRendered, factRendered ); } function test_zz_views_FEBaseTest_createDom( ){ var controller = { getModel: function( ){ return this.model; }, model: { getUid: function( ){ return 'modelUid'; }, datarows : [ 1, 2, 3, 4 ], currentDatarow: -1, firstDatarow: function( ){ this.currentDatarow = 0; return this.datarows[ this.currentDatarow ]; }, nextDatarow: function( ){ this.currentDatarow++; if( this.currentDatarow >= this.datarows.length ){ return false; } else { return this.datarows[ this.currentDatarow ]; } } } }; var expectedDatasetElement = { }; var isSetNode = false; var countCreateDatarowElements = 0; var countCreateModelElements = 0; var countUpdateElementsClasses = 0; var countCreateElementsControllers = 0; var expectedCount = controller.model.datarows.length; stubs.replace( soy, 'renderAsElement', function( ){ return expectedDatasetElement; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'setNode_', function( ){ isSetNode = true; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'createDatarowElements_', function( ){ countCreateDatarowElements++; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'createModelElements_', function( ){ countCreateModelElements++; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'updateElementsClasses_', function( ){ countUpdateElementsClasses++; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'createElementsControllers_', function( ){ countCreateElementsControllers++; } ); var factDatasetElement = zz_views_FEBaseTest_testSubj.createDom( controller ); assertTrue( 'Must return element that was given by soy.renderAsElement', factDatasetElement === expectedDatasetElement ); assertTrue( 'Expected calling setNode_ in chain', isSetNode ); assertEquals( 'Expected creation datarows elements for each datarow', expectedCount, countCreateDatarowElements ); assertEquals( 'Expected creation model element for each datarow', expectedCount, countCreateModelElements ); assertEquals( 'Expected updating classes for each datarow', expectedCount, countUpdateElementsClasses ); assertEquals( 'Expected updating controllers for each datarow', expectedCount, countCreateElementsControllers ); } function test_zz_views_FEBaseTest_renderDatarow( ){ var message = { dataset: undefined, datarow: { getUid: function( ){ } } }; var isCreateDatarowElements = false; var isCreateModelElements = false; var isUpdateElementsClasses = false; var isCreateElementsControllers = false; stubs.replace( zz_views_FEBaseTest_testSubj, 'createDatarowElements_', function( ){ isCreateDatarowElements = true; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'createModelElements_', function( ){ isCreateModelElements = true; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'updateElementsClasses_', function( ){ isUpdateElementsClasses = true; } ); stubs.replace( zz_views_FEBaseTest_testSubj, 'createElementsControllers_', function( ){ isCreateElementsControllers = true; } ); var expectedElement = 'someElement'; stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'get', function( ){ return { elements: [ expectedElement ] }; } ); var actualElement = zz_views_FEBaseTest_testSubj.renderDatarow( message ); assertTrue( 'Expected calling createDatarowElements_ in chain', isCreateDatarowElements ); assertTrue( 'Expected calling createModelElements_ in chain', isCreateModelElements ); assertTrue( 'Expected calling updateElementsClasses_ in chain', isUpdateElementsClasses ); assertTrue( 'Expected calling createElementsControllers_ in chain', isCreateElementsControllers ); assertEquals( 'Expected return certain datarow element', expectedElement, actualElement ); } function test_zz_views_FEBaseTest_removeDatarow( ){ var message = { datarow: { getUid: function( ){ } } }; var childElement = goog.dom.createDom( 'span' ); var parentElement = goog.dom.createDom( 'span', undefined, [ childElement ] ); assertTrue( 'Parent element must have its child node before', parentElement.hasChildNodes( ) ); stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'get', function( ){ return { elements: [ childElement ] }; } ); zz_views_FEBaseTest_testSubj.removeDatarow( message ); assertFalse( 'Parent element must not have its child node after', parentElement.hasChildNodes( ) ); } function test_zz_views_FEBaseTest_updateDatarow( ){ var elementName = 'span'; var oldValue = 'oldValue'; var newValue = 'newValue'; var message = { datarow: { getUid: function( ){ return 'datarowUid'; } }, datafield: 'datafield', new_value: newValue }; var attributes = { }; attributes[ 'title' ] = 'value'; // we must use a valid attribute for span var modelNode = { elements: [ goog.dom.createDom( elementName, attributes, oldValue ) ,goog.dom.createDom( elementName, attributes, oldValue ) ], controller: null }; var inputNode = { elements: [ goog.dom.createDom( elementName, attributes, oldValue ) ,goog.dom.createDom( elementName, attributes, oldValue ) ], controller: null }; var className = 'className'; attributes = { }; attributes[ 'title' ] = 'class'; attributes[ zz.views.enums.FEBaseElementAttribute.CLASS ] = 'prefix' + message.datafield + zz.views.enums.FEBaseUidSeparator.CLASS_INTERNAL + className + zz.views.enums.FEBaseUidSeparator.CLASS_EXTERNAL + 'suffix'; var classNode = { elements: [ goog.dom.createDom( elementName, attributes, oldValue ) ,goog.dom.createDom( elementName, attributes, oldValue ) ], controller: null }; var nodes = { }; nodes[ message.datarow.getUid( ) + zz.views.enums.FEBaseUidSeparator.INTERNAL + zz.views.enums.FEBaseElementAttributeCode.MODEL + zz.views.enums.FEBaseUidSeparator.INTERNAL + message.datafield ] = modelNode; nodes[ message.datarow.getUid( ) + zz.views.enums.FEBaseUidSeparator.INTERNAL + zz.views.enums.FEBaseElementAttributeCode.INPUT + zz.views.enums.FEBaseUidSeparator.INTERNAL + message.datafield ] = inputNode; nodes[ message.datarow.getUid( ) + zz.views.enums.FEBaseUidSeparator.INTERNAL + zz.views.enums.FEBaseElementAttributeCode.CLASS + zz.views.enums.FEBaseUidSeparator.INTERNAL + message.datafield ] = classNode; var node; var elements; var element; var i = 0; for( node in nodes ){ elements = nodes[ node ].elements; for( i = 0; i < elements.length; i++ ){ element = elements[ i ]; if( 'value' === element.getAttribute( 'title' ) ){ assertEquals( 'Expected old value for element before', oldValue, goog.dom.getTextContent( element ) ); } if( 'class' === element.getAttribute( 'title' ) ){ assertFalse( 'Element must not contain class before', goog.dom.classlist.contains( element, className ) ); } } } stubs.replace( zz_views_FEBaseTest_testSubj.mvcRegistry_, 'get', function( uid ){ return nodes[ uid ]; } ); zz_views_FEBaseTest_testSubj.updateDatarow( message ); for( node in nodes ){ elements = nodes[ node ].elements; for( i = 0; i < elements.length; i++ ){ element = elements[ i ]; if( 'value' === element.getAttribute( 'title' ) ){ assertEquals( 'Expected new value for element after', newValue, goog.dom.getTextContent( element ) ); } if( 'class' === element.getAttribute( 'title' ) ){ assertTrue( 'Element must contain class after', goog.dom.classlist.contains( element, className ) ); } } } message.new_value = undefined; zz_views_FEBaseTest_testSubj.updateDatarow( message ); for( node in nodes ){ elements = nodes[ node ].elements; for( i = 0; i < elements.length; i++ ){ element = elements[ i ]; if( 'value' === element.getAttribute( 'title' ) ){ assertEquals( 'Expected empty value for element after', '', goog.dom.getTextContent( element ) ); } if( 'class' === element.getAttribute( 'title' ) ){ assertFalse( 'Element must not contain class after', goog.dom.classlist.contains( element, className ) ); } } } }
24.297603
105
0.555322
b727dd444217d214f1e43154cd6422a559500973
29,713
js
JavaScript
src/test/components/addApplication/AddApplication.test.js
lpichler/sources-ui
b83c33f91dc9533aff973dcac1fa578282a067f6
[ "Apache-2.0" ]
1
2022-03-29T11:00:32.000Z
2022-03-29T11:00:32.000Z
src/test/components/addApplication/AddApplication.test.js
lpichler/sources-ui
b83c33f91dc9533aff973dcac1fa578282a067f6
[ "Apache-2.0" ]
517
2019-11-18T11:28:45.000Z
2022-03-29T10:09:56.000Z
src/test/components/addApplication/AddApplication.test.js
lindgrenj6/sources-ui
e6838488bbc07591aac90fff1cdcf0763078dca5
[ "Apache-2.0" ]
22
2019-11-17T15:23:35.000Z
2022-03-24T15:22:31.000Z
import React from 'react'; import { mount } from 'enzyme'; import { EmptyStateBody, EmptyStateSecondaryActions, Title, Radio } from '@patternfly/react-core'; import { Route, MemoryRouter } from 'react-router-dom'; import CloseModal from '../../../components/CloseModal'; import SummaryStep from '../../../components/FormComponents/SourceWizardSummary'; import LoadingStep from '../../../components/steps/LoadingStep'; import FinishedStep from '../../../components/steps/FinishedStep'; import AmazonFinishedStep from '../../../components/steps/AmazonFinishedStep'; import TimeoutStep from '../../../components/steps/TimeoutStep'; import ErroredStep from '../../../components/steps/ErroredStep'; import { act } from 'react-dom/test-utils'; import SourcesFormRenderer from '../../../utilities/SourcesFormRenderer'; import * as entities from '../../../api/entities'; import * as attachSource from '../../../api/doAttachApp'; import AddApplication from '../../../components/AddApplication/AddApplication'; import { componentWrapperIntl } from '../../../utilities/testsHelpers'; import { sourceTypesData, OPENSHIFT_ID, AMAZON_ID } from '../../__mocks__/sourceTypesData'; import { SOURCE_NO_APS_ID } from '../../__mocks__/sourcesData'; import { applicationTypesData, COSTMANAGEMENT_APP } from '../../__mocks__/applicationTypesData'; import { routes, replaceRouteId } from '../../../Routes'; import { AuthTypeSetter } from '../../../components/AddApplication/AuthTypeSetter'; import reducer from '../../../components/AddApplication/reducer'; import * as removeAppSubmit from '../../../components/AddApplication/removeAppSubmit'; import mockStore from '../../__mocks__/mockStore'; describe('AddApplication', () => { let store; let initialEntry; let checkAvailabilitySource; beforeEach(() => { checkAvailabilitySource = jest.fn().mockImplementation(() => Promise.resolve()); initialEntry = [ replaceRouteId(routes.sourcesDetailAddApp.path, SOURCE_NO_APS_ID).replace(':app_type_id', COSTMANAGEMENT_APP.id), ]; store = mockStore({ sources: { entities: [ { id: SOURCE_NO_APS_ID, source_type_id: OPENSHIFT_ID, applications: [], }, ], appTypes: applicationTypesData.data, sourceTypes: sourceTypesData.data, appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); entities.getSourcesApi = () => ({ listEndpointAuthentications: jest.fn().mockImplementation(() => Promise.resolve({ data: [] })), checkAvailabilitySource, }); }); it('loads with endpoint values - not removing of source', async () => { const loadAuthsSpy = jest.fn().mockImplementation(() => Promise.resolve({ data: [] })); entities.getSourcesApi = () => ({ listEndpointAuthentications: loadAuthsSpy, }); const ENDPOINT_ID = '21312'; store = mockStore({ sources: { entities: [ { id: SOURCE_NO_APS_ID, source_type_id: OPENSHIFT_ID, applications: [], endpoints: [{ id: ENDPOINT_ID }], }, ], appTypes: applicationTypesData.data, sourceTypes: sourceTypesData.data, appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); let wrapper; await act(async () => { wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); }); wrapper.update(); expect(loadAuthsSpy).toHaveBeenCalledWith(ENDPOINT_ID); expect(wrapper.find(SourcesFormRenderer).length).toEqual(1); }); it('renders loading state when is not loaded', async () => { store = mockStore({ sources: { entities: [], appTypes: applicationTypesData.data, sourceTypes: sourceTypesData.data, appTypesLoaded: false, sourceTypesLoaded: true, }, }); let wrapper; await act(async () => { wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); }); wrapper.update(); expect(wrapper.find(LoadingStep)).toHaveLength(1); }); describe('redirects', () => { const APP = { id: '1543897', name: 'custom-app', supported_source_types: [], }; initialEntry = [replaceRouteId(routes.sourcesDetailAddApp.path, SOURCE_NO_APS_ID).replace(':app_type_id', APP.id)]; it('when type does exist', async () => { store = mockStore({ sources: { entities: [{ id: SOURCE_NO_APS_ID, source_type_id: AMAZON_ID, applications: [] }], appTypes: [], sourceTypes: sourceTypesData.data, appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); let wrapper; await act(async () => { wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); }); wrapper.update(); expect(wrapper.find(MemoryRouter).instance().history.location.pathname).toEqual( replaceRouteId(routes.sourcesDetail.path, SOURCE_NO_APS_ID) ); }); it('when type does is not supported', async () => { store = mockStore({ sources: { entities: [{ id: SOURCE_NO_APS_ID, source_type_id: AMAZON_ID, applications: [] }], appTypes: [APP], sourceTypes: sourceTypesData.data, appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); let wrapper; await act(async () => { wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); }); wrapper.update(); expect(wrapper.find(MemoryRouter).instance().history.location.pathname).toEqual( replaceRouteId(routes.sourcesDetail.path, SOURCE_NO_APS_ID) ); }); it('when type is already attached', async () => { store = mockStore({ sources: { entities: [ { id: SOURCE_NO_APS_ID, source_type_id: AMAZON_ID, applications: [{ id: '234', application_type_id: APP.id }] }, ], appTypes: [{ ...APP, supported_source_types: ['amazon'] }], sourceTypes: sourceTypesData.data, appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); let wrapper; await act(async () => { wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); }); wrapper.update(); expect(wrapper.find(MemoryRouter).instance().history.location.pathname).toEqual( replaceRouteId(routes.sourcesDetail.path, SOURCE_NO_APS_ID) ); }); }); describe('custom type - integration tests', () => { const customSourceType = { name: 'custom_type', product_name: 'Custom Type', id: '6844', schema: { authentication: [ { type: 'receptor', name: 'receptor', fields: [ { component: 'text-field', label: 'Another value', name: 'source.nested.another_value', }, { component: 'text-field', label: 'Receptor ID', name: 'source.nested.source_ref', }, ], }, ], endpoint: { hidden: true, fields: [{ name: 'endpoint_id', hideField: true, component: 'text-field' }], }, }, }; const application = { name: 'custom-app', display_name: 'Custom app', id: '15654165', supported_source_types: ['custom_type'], supported_authentication_types: { custom_type: ['receptor'] }, }; const another_value = 'do not remove this when retry'; let wrapper; let source; beforeEach(async () => { source = { id: SOURCE_NO_APS_ID, source_type_id: customSourceType.id, applications: [], nested: { source_ref: 'original', another_value, }, }; store = mockStore({ sources: { entities: [source], appTypes: [application], sourceTypes: [customSourceType], appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); initialEntry = [replaceRouteId(routes.sourcesDetailAddApp.path, SOURCE_NO_APS_ID).replace(':app_type_id', application.id)]; await act(async () => { wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); }); wrapper.update(); }); it('closes immedietaly when no value is filled', async () => { await act(async () => { const closeButton = wrapper.find('Button').at(0); closeButton.simulate('click'); }); wrapper.update(); expect(wrapper.find(MemoryRouter).instance().history.location.pathname).toEqual( replaceRouteId(routes.sourcesDetail.path, SOURCE_NO_APS_ID) ); }); it('opens a modal on cancel and closes the wizard', async () => { const value = 'SOURCE_REF_CHANGED'; await act(async () => { const sourceRefInput = wrapper.find('input[name="source.nested.source_ref"]'); sourceRefInput.instance().value = value; sourceRefInput.simulate('change'); }); wrapper.update(); await act(async () => { const closeButton = wrapper.find('Button').at(0); closeButton.simulate('click'); }); wrapper.update(); expect(wrapper.find(CloseModal)).toHaveLength(1); await act(async () => { const leaveButton = wrapper.find('Button').at(1); leaveButton.simulate('click'); }); wrapper.update(); expect(wrapper.find(MemoryRouter).instance().history.location.pathname).toEqual( replaceRouteId(routes.sourcesDetail.path, SOURCE_NO_APS_ID) ); }); it('opens a modal on cancel and stay on the wizard', async () => { const value = 'SOURCE_REF_CHANGED'; await act(async () => { const sourceRefInput = wrapper.find('input[name="source.nested.source_ref"]'); sourceRefInput.instance().value = value; sourceRefInput.simulate('change'); }); wrapper.update(); await act(async () => { const closeButton = wrapper.find('Button').at(0); closeButton.simulate('click'); }); wrapper.update(); expect(wrapper.find(CloseModal)).toHaveLength(1); await act(async () => { const stayButton = wrapper.find('Button').at(0); stayButton.simulate('click'); }); wrapper.update(); expect(wrapper.find(CloseModal)).toHaveLength(0); expect(wrapper.find('input[name="source.nested.source_ref"]').instance().value).toEqual(value); }); it('renders authentication selection', async () => { const authentication = { id: 'authid', authtype: 'receptor', username: 'customusername', password: 'somepassword', }; entities.getSourcesApi = () => ({ listEndpointAuthentications: jest.fn().mockImplementation(() => Promise.resolve({ data: [authentication], }) ), checkAvailabilitySource, }); const application2 = { name: 'custom-app-second', display_name: 'Custom app second', id: '097JDS', supported_source_types: ['custom_type'], supported_authentication_types: { custom_type: ['receptor'] }, }; source = { ...source, endpoints: [{ id: '189298' }], applications: [ { id: '87658787878586', application_type_id: application2.id, authentications: [ { id: 'authid', }, ], }, ], }; store = mockStore({ sources: { entities: [source], appTypes: [application, application2], sourceTypes: [customSourceType], appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); await act(async () => { wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); }); wrapper.update(); expect(wrapper.find(Radio)).toHaveLength(2); expect(wrapper.find(AuthTypeSetter)).toHaveLength(1); await act(async () => { const selectExistingAuth = wrapper.find('input').at(1); selectExistingAuth.simulate('change'); }); wrapper.update(); await act(async () => { const nextButton = wrapper.find('Button').at(1); nextButton.simulate('click'); }); wrapper.update(); const value = 'SOURCE_REF_CHANGED'; await act(async () => { const sourceRefInput = wrapper.find('input[name="source.nested.source_ref"]'); sourceRefInput.instance().value = value; sourceRefInput.simulate('change'); }); wrapper.update(); await act(async () => { const nextButton = wrapper.find('Button').at(1); nextButton.simulate('click'); }); wrapper.update(); entities.doLoadEntities = jest .fn() .mockImplementation(() => Promise.resolve({ sources: [], sources_aggregate: { aggregate: { total_count: 0 } } })); attachSource.doAttachApp = jest.fn().mockImplementation(() => Promise.resolve({ availability_status: 'available', }) ); await act(async () => { const submitButton = wrapper.find('Button').at(1); submitButton.simulate('click'); }); wrapper.update(); expect(wrapper.find(FinishedStep)).toHaveLength(1); expect(checkAvailabilitySource).toHaveBeenCalledWith(source.id); expect(attachSource.doAttachApp.mock.calls[0][1].getState().values).toEqual({ application: { application_type_id: application.id }, source: { ...source, nested: { source_ref: value, another_value } }, authentication, selectedAuthentication: 'authid', url: undefined, endpoint: { id: '189298', }, }); }); }); describe('imported source - not need to edit any value', () => { let initialValues; let source; beforeEach(() => { source = { id: SOURCE_NO_APS_ID, source_type_id: OPENSHIFT_ID, applications: [], imported: 'cfme', }; store = mockStore({ sources: { entities: [source], appTypes: applicationTypesData.data, sourceTypes: sourceTypesData.data, appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); initialValues = { application: undefined, source }; }); it('renders review', async () => { const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); expect(wrapper.find(SummaryStep)).toHaveLength(1); expect(wrapper.find('Button').at(1).text()).toEqual('Add'); }); it('calls on submit function', async () => { attachSource.doAttachApp = jest.fn().mockImplementation(() => Promise.resolve({ availability_status: 'available', }) ); entities.doLoadEntities = jest .fn() .mockImplementation(() => Promise.resolve({ sources: [], sources_aggregate: { aggregate: { total_count: 0 } } })); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); const formValues = { application: { application_type_id: '2', }, }; const formApi = expect.any(Object); const authenticationValues = expect.any(Array); const appTypes = expect.any(Array); expect(checkAvailabilitySource).toHaveBeenCalledWith(source.id); expect(attachSource.doAttachApp).toHaveBeenCalledWith(formValues, formApi, authenticationValues, initialValues, appTypes); expect(wrapper.find(FinishedStep).length).toEqual(1); expect(wrapper.find(Title).last().text()).toEqual('Configuration successful'); expect(wrapper.find(EmptyStateBody).last().text()).toEqual('Your application was successfully added.'); expect(wrapper.find('Button').at(1).text()).toEqual('Exit'); }); it('shows aws specific step', async () => { source = { ...source, source_type_id: AMAZON_ID, }; store = mockStore({ sources: { entities: [source], appTypes: applicationTypesData.data, sourceTypes: sourceTypesData.data, appTypesLoaded: true, sourceTypesLoaded: true, loaded: 0, }, }); initialValues = { application: undefined, source }; attachSource.doAttachApp = jest.fn().mockImplementation(() => Promise.resolve({ availability_status: 'available', }) ); entities.doLoadEntities = jest .fn() .mockImplementation(() => Promise.resolve({ sources: [], sources_aggregate: { aggregate: { total_count: 0 } } })); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); const formValues = { application: { application_type_id: '2', }, }; const formApi = expect.any(Object); const authenticationValues = expect.any(Array); const appTypes = expect.any(Array); expect(checkAvailabilitySource).toHaveBeenCalledWith(source.id); expect(attachSource.doAttachApp).toHaveBeenCalledWith(formValues, formApi, authenticationValues, initialValues, appTypes); expect(wrapper.find(AmazonFinishedStep).length).toEqual(1); expect(wrapper.find(Title).last().text()).toEqual('Amazon Web Services connection established'); expect(wrapper.find(EmptyStateBody).last().text()).toEqual( 'Discover the benefits of your connection or exit to manage your new source.View enabled AWS gold imagesSubscription Watch usageGet started with Red Hat InsightsCost Management reporting' ); expect(wrapper.find('Button').at(1).text()).toEqual('Exit'); }); it('renders timeouted step when endpoint', async () => { attachSource.doAttachApp = jest.fn().mockImplementation(() => Promise.resolve({ endpoint: [ { availability_status: null, }, ], }) ); entities.doLoadEntities = jest .fn() .mockImplementation(() => Promise.resolve({ sources: [], sources_aggregate: { aggregate: { total_count: 0 } } })); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); expect(wrapper.find(TimeoutStep)).toHaveLength(1); expect(wrapper.find(Title).last().text()).toEqual('Configuration in progress'); expect(wrapper.find(EmptyStateBody).last().text()).toEqual( 'We are still working to confirm credentials and app settings.To track progress, check the Status column in the Sources table.' ); expect(wrapper.find('Button').at(1).text()).toEqual('Exit'); }); it('renders timeouted step', async () => { attachSource.doAttachApp = jest.fn().mockImplementation(() => Promise.resolve({ applications: [ { availability_status: null, }, ], }) ); entities.doLoadEntities = jest .fn() .mockImplementation(() => Promise.resolve({ sources: [], sources_aggregate: { aggregate: { total_count: 0 } } })); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); expect(wrapper.find(TimeoutStep)).toHaveLength(1); expect(wrapper.find(Title).last().text()).toEqual('Configuration in progress'); expect(wrapper.find(EmptyStateBody).last().text()).toEqual( 'We are still working to confirm credentials and app settings.To track progress, check the Status column in the Sources table.' ); expect(wrapper.find('Button').at(1).text()).toEqual('Exit'); }); it('redirects to edit when unavailable', async () => { const ERROR = 'ARN is wrong'; attachSource.doAttachApp = jest.fn().mockImplementation(() => Promise.resolve({ applications: [ { availability_status: 'unavailable', availability_status_error: ERROR, }, ], }) ); entities.doLoadEntities = jest .fn() .mockImplementation(() => Promise.resolve({ sources: [], sources_aggregate: { aggregate: { total_count: 0 } } })); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); expect(attachSource.doAttachApp).toHaveBeenCalled(); expect(wrapper.find(ErroredStep).length).toEqual(1); expect(wrapper.find(Title).last().text()).toEqual('Configuration unsuccessful'); expect(wrapper.find(EmptyStateBody).last().text()).toEqual(ERROR); expect(wrapper.find('Button').at(1).text()).toEqual('Edit source'); expect(wrapper.find('Button').at(2).text()).toEqual('Remove application'); await act(async () => { wrapper.find('Button').at(1).simulate('click', { button: 0 }); }); wrapper.update(); expect(wrapper.find(MemoryRouter).instance().history.location.pathname).toEqual( replaceRouteId(routes.sourcesDetail.path, source.id) ); }); it('remove source when unavailable', async () => { const ERROR = 'ARN is wrong'; const APP_ID = 'some-id'; attachSource.doAttachApp = jest.fn().mockImplementation(() => Promise.resolve({ id: APP_ID, applications: [ { availability_status: 'unavailable', availability_status_error: ERROR, id: APP_ID, }, ], }) ); entities.doLoadEntities = jest .fn() .mockImplementation(() => Promise.resolve({ sources: [], sources_aggregate: { aggregate: { total_count: 0 } } })); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); expect(attachSource.doAttachApp).toHaveBeenCalled(); expect(wrapper.find(ErroredStep).length).toEqual(1); expect(wrapper.find(Title).last().text()).toEqual('Configuration unsuccessful'); expect(wrapper.find(EmptyStateBody).last().text()).toEqual(ERROR); expect(wrapper.find('Button').at(1).text()).toEqual('Edit source'); expect(wrapper.find('Button').at(2).text()).toEqual('Remove application'); removeAppSubmit.default = jest.fn().mockImplementation(() => Promise.resolve('OK')); expect(removeAppSubmit.default).not.toHaveBeenCalled(); await act(async () => { wrapper.find('Button').at(2).simulate('click'); }); wrapper.update(); expect(removeAppSubmit.default).toHaveBeenCalledWith( { id: APP_ID, display_name: undefined }, expect.objectContaining({ formatMessage: expect.any(Function) }), // intl undefined, // oncancel expect.any(Function), // dispatch expect.any(Object) // source ); }); it('catch errors after submit', async () => { const ERROR_MESSAGE = 'Something went wrong :('; attachSource.doAttachApp = jest.fn().mockImplementation(() => new Promise((res, reject) => reject(ERROR_MESSAGE))); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); const formValues = { application: { application_type_id: '2', }, }; const formApi = expect.any(Object); const authenticationValues = expect.any(Array); const appTypes = expect.any(Array); expect(attachSource.doAttachApp).toHaveBeenCalledWith(formValues, formApi, authenticationValues, initialValues, appTypes); expect(wrapper.find(ErroredStep)).toHaveLength(1); expect(wrapper.find(Title).last().text()).toEqual('Something went wrong'); expect(wrapper.find(EmptyStateBody).last().text()).toEqual( 'There was a problem while trying to add your source. Please try again. If the error persists, open a support case.' ); expect(wrapper.find('Button').at(1).text()).toEqual('Retry'); expect(wrapper.find(EmptyStateSecondaryActions).text()).toEqual('Open a support case'); }); it('retry submit after fail', async () => { const ERROR_MESSAGE = 'Something went wrong :('; attachSource.doAttachApp = jest.fn().mockImplementation(() => new Promise((res, reject) => reject(ERROR_MESSAGE))); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); const formValues = { application: { application_type_id: '2', }, }; const formApi = expect.any(Object); const authenticationValues = expect.any(Array); const appTypes = expect.any(Array); expect(attachSource.doAttachApp).toHaveBeenCalledWith(formValues, formApi, authenticationValues, initialValues, appTypes); expect(wrapper.find(ErroredStep)).toHaveLength(1); attachSource.doAttachApp.mockReset(); attachSource.doAttachApp = jest.fn().mockImplementation(() => Promise.resolve({ availability_status: 'available', }) ); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); wrapper.update(); expect(wrapper.find(FinishedStep)).toHaveLength(1); }); it('show loading step', async () => { attachSource.doAttachApp = jest.fn().mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve('ok'), 2))); const wrapper = mount( componentWrapperIntl( <Route path={routes.sourcesDetailAddApp.path} render={(...args) => <AddApplication {...args} />} />, store, initialEntry ) ); jest.useFakeTimers(); await act(async () => { wrapper.find('Button').at(1).simulate('click'); }); jest.useRealTimers(); wrapper.update(); expect(wrapper.find(LoadingStep).length).toEqual(1); }); }); describe('reducer', () => { it('default', () => { expect(reducer({ progressStep: 3 }, {})).toEqual({ progressStep: 3 }); }); }); });
31.3098
195
0.57914
b7282f54b212e465546a84e7ce410d3e79b70291
5,482
js
JavaScript
public/mabolib/services.js
mabotech/maboss
cad6466979aa4df97a672512414b587074bbeba4
[ "MIT" ]
null
null
null
public/mabolib/services.js
mabotech/maboss
cad6466979aa4df97a672512414b587074bbeba4
[ "MIT" ]
null
null
null
public/mabolib/services.js
mabotech/maboss
cad6466979aa4df97a672512414b587074bbeba4
[ "MIT" ]
1
2019-11-29T10:42:29.000Z
2019-11-29T10:42:29.000Z
"use strict"; //uglifyjs services.js -b --comments all /** *Mabo Services */ angular.module("maboss.services", []).factory("auth", function() { return { check: function() { return true; } }; }).factory("storageService", function() { //localStorage //var STORAGE_ID = 'blockSettings'; return { get: function(key) { return JSON.parse(localStorage.getItem(key) || "[]"); }, put: function(key, val) { localStorage.setItem(key, JSON.stringify(val)); }, remove: function(key) { localStorage.removeItem(key); } }; }).factory("sessionService", function() { //sessionStorage //var STORAGE_ID = 'sessionStorage'; return { get: function(key) { return JSON.parse(sessionStorage.getItem(key) || "{}"); }, put: function(key, val) { sessionStorage.setItem(key, JSON.stringify(val)); }, remove: function(key) { sessionStorage.removeItem(key); } }; }).factory("common", function() { //utils, helpers var ID = 0; var MID = 0; Messenger.options = { extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right', theme: 'air' } return { elog: function(message) { console.log(message); }, post:function(level, message){ MID = MID +1; //var dt = new Date(); if (level == 'info'){ Messenger().post({ message: "[ "+MID+" ] &nbsp;&nbsp;&nbsp;"+message, type: 'info', hideAfter:2 //showCloseButton: true }); }else if (level == 'error'){ Messenger().post({ message:message, type: 'error', showCloseButton: true }); } }, getId: function() { ID = ID + 1; return "r" + ID; }, auth: function() { return true; } }; }) .factory("callproc", function($http, common) { return{ call:function(method, params, callback){ var jsonrpc_params = { jsonrpc: "2.0", id: common.getId(), method: "call", params: { method: "mtp_upsert_cs8", table: params.table, pkey:params.pkey, columns: params.model, context: { user: params.user, languageid: parmas.languageid } } }; //elog($scope.jsonrpc_params); // $scope.params = JSON.stringify($scope.jsonrpc_params,null, 4) // call ajax $http({ method: "POST", url: "/api/callproc.call", data: jsonrpc_params }).success(function(data, status) { $scope.data = JSON.stringify(data, null, 4); if (data.result.returning.length === 0) { return 0; } callback(result); }).error(function(data, status) { }); } } } ) .factory("initSelect2", function($http, common){ return{ get:function(method, params, callback){ var id = 10; var jsonrpc_params = { jsonrpc: "2.0", id: common.getId(), method: "call", params: { method: "mtp_select_cf2", table: params.table, key: params.pkey, value: params.ptext, languageid: params.languageid //filter: term } }; var result = []; $http({ method: "POST", url: "/api/callproc.call", data: jsonrpc_params }).success(function(data, status) { if (data.result.rows) { result = data.result.rows; } callback(result); }).error(function(data, status) { // post msg }); } } }) .factory("webService", function($http) { //webService var ID = 0; return { //post post: function(method, params, successCallback) { //var d = $q.defer(); ID = ID + 1; var bodyRequest = JSON.stringify({ jsonrpc: "2.0", method: method, params: params, id: "MT" + ID }); var headers = { "Content-Type": "application/json" }; $http({ url: "/api", method: "POST", data: bodyRequest, headers: headers }).success(function(data, status, headers, config) { return successCallback(data, status, headers, config); }).error(function(data, status, headers, config) { return successCallback(data, status, headers, config); }); } }; });
25.37963
75
0.423386
b72894af86cbbac328db1ba1176f78354740e49f
563
js
JavaScript
presentation/slides/title/index.js
jonsamp/redux-first-router-deck
f3162d87181a86c5f343aa35c615de37a33474bb
[ "MIT" ]
null
null
null
presentation/slides/title/index.js
jonsamp/redux-first-router-deck
f3162d87181a86c5f343aa35c615de37a33474bb
[ "MIT" ]
null
null
null
presentation/slides/title/index.js
jonsamp/redux-first-router-deck
f3162d87181a86c5f343aa35c615de37a33474bb
[ "MIT" ]
null
null
null
import React from "react"; import { Heading, Slide, Text } from "spectacle"; const coverImage = "https://images.unsplash.com/photo-1508930883516-7f594c5b68b9?auto=format&fit=crop&w=2250&q=80"; export default ( <Slide transition={["slide"]} bgColor="secondary" bgImage={coverImage} align="flex-start flex-start" > <Heading size={1} lineHeight={1} textColor="black" textAlign="left"> Redux First Router </Heading> <Text textColor="black" textAlign="left"> Routing, actions, and loading data </Text> </Slide> );
25.590909
98
0.669627
b728bb084984984d491541cb442e152d1db7d696
572
js
JavaScript
src/functions/askYesOrNo.js
L1lith/Emerald-Templates
0e044b92725f8bc3fb419026f0221dbb1c9d4425
[ "MIT" ]
null
null
null
src/functions/askYesOrNo.js
L1lith/Emerald-Templates
0e044b92725f8bc3fb419026f0221dbb1c9d4425
[ "MIT" ]
15
2020-09-04T22:07:35.000Z
2021-09-27T08:06:21.000Z
src/functions/askYesOrNo.js
L1lith/Emerald-Templates
0e044b92725f8bc3fb419026f0221dbb1c9d4425
[ "MIT" ]
null
null
null
const askQuestion = require('./askQuestion') const yesOrNo = ['yes', 'no'] const nonAlphabetical = /[^a-z]*/gi async function askYesOrNo(question, retry = false) { let answer = (await askQuestion(question)).replace(nonAlphabetical, '').toLowerCase() if (!yesOrNo.includes(answer)) { if (retry === true) { while (!yesOrNo.includes(answer)) answer = (await askQuestion(question)).replace(nonAlphabetical, '').toLowerCase() } else { throw new Error('Must answer yes or no') } } return answer === 'yes' } module.exports = askYesOrNo
28.6
89
0.659091
b7290d419b9d5fb8368661c190d7ba282d43870c
5,068
js
JavaScript
test/unit/mongoosePaginateSpec.js
tesfaldet/mongoose-range-paginate
2995767db78e8c27146bbc6aae32eafb72cdd1df
[ "MIT" ]
1
2016-03-04T01:50:05.000Z
2016-03-04T01:50:05.000Z
test/unit/mongoosePaginateSpec.js
tesfaldet/mongoose-range-paginate
2995767db78e8c27146bbc6aae32eafb72cdd1df
[ "MIT" ]
7
2015-06-03T01:08:44.000Z
2016-02-15T22:52:02.000Z
test/unit/mongoosePaginateSpec.js
tesfaldet/mongoose-range-paginate
2995767db78e8c27146bbc6aae32eafb72cdd1df
[ "MIT" ]
5
2015-06-02T14:59:09.000Z
2016-02-03T17:09:24.000Z
var mongoose = require('mongoose'), _ = require('lodash'); require('chai').should(); describe('mongoosePaginate', function () { var mongoosePaginate = require('../../lib/mongoosePaginate'); mongoose.plugin(mongoosePaginate); require('../utils/testDb')('course'); // populate db with test data var Course = require('../fixtures/models/course'); it('should return a paginated collection upon request', function() { var currentPage = '1', page = '2', resultsPerPage = '10'; return Course.paginate( {}, currentPage, page, resultsPerPage, {} ) .then(function(pagingData) { pagingData.newCurrentPage.should.equal('2'); pagingData.before.should.equal('X2lkPTU0MjMwZDJjMjgyYTExMTUwMDM1NDJlYg%3D%3D'); pagingData.after.should.equal('X2lkPTU0MjMwZjE1MjgyYTExMTUwMDM1NDJmNQ%3D%3D'); pagingData.pageCount.should.equal(4); pagingData.numPages.should.equal(2); pagingData.total.should.equal(14); pagingData.items.should.be.Array; pagingData.items.should.not.be.empty; }); }); it('should return a paginated collection consisting of _id and specified columns', function() { var currentPage = '1', page = '2', resultsPerPage = '10'; return Course.paginate( {}, currentPage, page, resultsPerPage, { columns: 'name' } ) .then(function(pagingData) { pagingData.newCurrentPage.should.equal('2'); pagingData.before.should.equal('X2lkPTU0MjMwZDJjMjgyYTExMTUwMDM1NDJlYg%3D%3D'); pagingData.after.should.equal('X2lkPTU0MjMwZjE1MjgyYTExMTUwMDM1NDJmNQ%3D%3D'); pagingData.pageCount.should.equal(4); pagingData.numPages.should.equal(2); pagingData.total.should.equal(14); pagingData.items.should.be.Array; pagingData.items.should.not.be.empty; pagingData.items[0].name.should.equal('MS Lync'); mongoose.Types.ObjectId.isValid(pagingData.items[0]._id).should.be.truthy; pagingData.items[0]._id.should.deep.equal(mongoose.Types.ObjectId('54230d2c282a1115003542eb')); _.size(pagingData.items[0].toObject()).should.equal(2); }); }); it('should return a filtered paginated collection upon providing options.after', function() { var currentPage = '1', page = '2', resultsPerPage = '10'; return Course.paginate( {}, currentPage, page, resultsPerPage, { after: { _id: '54230b67282a1115003542d8' } } ) .then(function(pagingData) { pagingData.newCurrentPage.should.equal('2'); pagingData.before.should.equal('X2lkPTU0MjMwZDJjMjgyYTExMTUwMDM1NDJlYg%3D%3D'); pagingData.after.should.equal('X2lkPTU0MjMwZjE1MjgyYTExMTUwMDM1NDJmNQ%3D%3D'); pagingData.pageCount.should.equal(4); pagingData.numPages.should.equal(2); pagingData.total.should.equal(14); pagingData.items.should.be.Array; pagingData.items.should.not.be.empty; }); }); it('should return a filtered paginated collection upon providing options.before', function() { var currentPage = '2', page = '1', resultsPerPage = '10'; return Course.paginate( {}, currentPage, page, resultsPerPage, { before: { _id: '54230d2c282a1115003542eb' } } ) .then(function(pagingData) { pagingData.newCurrentPage.should.equal('1'); pagingData.before.should.equal('X2lkPTUzYmFiZmE1MTlhNGI0MDAwMGJjYjJkYQ%3D%3D'); pagingData.after.should.equal('X2lkPTU0MjMwYjY3MjgyYTExMTUwMDM1NDJkOA%3D%3D'); pagingData.pageCount.should.equal(10); pagingData.numPages.should.equal(2); pagingData.total.should.equal(14); pagingData.items.should.be.Array; pagingData.items.should.not.be.empty; }); }); it('should return the last page of a paginated collection upon providing options.last', function() { var currentPage = '1', page = '2', resultsPerPage = '10'; return Course.paginate( {}, currentPage, page, resultsPerPage, { last: 'true' } ) .then(function(pagingData) { pagingData.newCurrentPage.should.equal('2'); pagingData.before.should.equal('X2lkPTU0MjMwZDJjMjgyYTExMTUwMDM1NDJlYg%3D%3D'); pagingData.after.should.equal('X2lkPTU0MjMwZjE1MjgyYTExMTUwMDM1NDJmNQ%3D%3D'); pagingData.pageCount.should.equal(4); pagingData.numPages.should.equal(2); pagingData.total.should.equal(14); pagingData.items.should.be.Array; pagingData.items.should.not.be.empty; }); }); // not done it('should return a paginated collection upon request', function() { var currentPage = '1', page = '2', resultsPerPage = '10'; return Course.paginate( {}, currentPage, page, resultsPerPage, { populate: {path: 'facilitator', select: 'firstname lastname'} } ) .then(function(pagingData) { pagingData.newCurrentPage.should.equal('2'); pagingData.before.should.equal('X2lkPTU0MjMwZDJjMjgyYTExMTUwMDM1NDJlYg%3D%3D'); pagingData.after.should.equal('X2lkPTU0MjMwZjE1MjgyYTExMTUwMDM1NDJmNQ%3D%3D'); pagingData.pageCount.should.equal(4); pagingData.numPages.should.equal(2); pagingData.total.should.equal(14); pagingData.items.should.be.Array; pagingData.items.should.not.be.empty; }); }); });
28.632768
101
0.706788
b72a3afdcae9aba11b15f09e18640fef28825ac2
1,195
js
JavaScript
index.js
Sayan751/app-settings-loader
34cc1441ebcdc9da10df37842faae98f4c017821
[ "MIT" ]
6
2019-05-19T22:41:50.000Z
2022-03-21T11:31:59.000Z
index.js
Sayan751/app-settings-loader
34cc1441ebcdc9da10df37842faae98f4c017821
[ "MIT" ]
6
2020-01-12T09:45:24.000Z
2022-03-22T09:28:55.000Z
index.js
Sayan751/app-settings-loader
34cc1441ebcdc9da10df37842faae98f4c017821
[ "MIT" ]
1
2020-04-18T21:39:39.000Z
2020-04-18T21:39:39.000Z
const fs = require('fs'); const path = require('path'); const { getOptions } = require('loader-utils'); const { validate } = require('schema-utils'); const { sealedMerge } = require("./sealedMerge"); const loaderName = 'app-settings-loader'; const schema = { env: 'string' }; const defaultOptions = { env: "development" }; const parseFileContent = (content, filePath) => { try { return JSON.parse(content); } catch (e) { throw new Error(`Unable to parse the file ${filePath}; ${loaderName} can only be used to load and transform well-formed json files.`); } } module.exports = function (source) { const options = Object.assign(defaultOptions, getOptions(this)); validate(schema, options, loaderName); const ext = path.extname(this.resourcePath); const envFile = path.join(path.dirname(this.resourcePath), `${path.basename(this.resourcePath, ext)}.${options.env}${ext}`); let envConfig = {}; if (fs.existsSync(envFile)) { envConfig = parseFileContent(fs.readFileSync(envFile), envFile); } const sourceConfig = parseFileContent(source, this.resourcePath); return JSON.stringify(sealedMerge(sourceConfig, envConfig)); };
36.212121
142
0.682008
b72a9c0de2cdd319ec5a20aaf8cb20ab8182b162
38,182
js
JavaScript
public/dist/application.js
kejack/workbench
2590f8601aab8db0549c1fd467fceb7b370f27ab
[ "MIT" ]
null
null
null
public/dist/application.js
kejack/workbench
2590f8601aab8db0549c1fd467fceb7b370f27ab
[ "MIT" ]
null
null
null
public/dist/application.js
kejack/workbench
2590f8601aab8db0549c1fd467fceb7b370f27ab
[ "MIT" ]
null
null
null
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'workbench'; var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ngTable', 'ui.router','mwl.calendar', 'ui.bootstrap', 'ui.utils', 'formly', 'formlyBootstrap']; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })(); 'use strict'; //Start by defining the main module and adding the module dependencies angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); // Setting HTML5 Location Mode angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix('!'); } ]); //Then define the init function for starting up the application angular.element(document).ready(function() { //Fixing facebook bug with redirect if (window.location.hash === '#_=_') window.location.hash = '#!'; //Then init the app angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); }); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('categories', ['core']); 'use strict'; // Use Applicaion configuration module to register a new module ApplicationConfiguration.registerModule('core'); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('events', ['core']); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('files', ['core']); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('projects', ['core']); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('tasks', ['core', 'ui.bootstrap']); 'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('users'); 'use strict'; // Configuring the new module angular.module('categories').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Categories', 'categories', 'dropdown', '/categories(/create)?'); Menus.addSubMenuItem('topbar', 'categories', 'List Categories', 'categories'); Menus.addSubMenuItem('topbar', 'categories', 'New Category', 'categories/create'); } ]); 'use strict'; //Setting up route angular.module('categories').config(['$stateProvider', function($stateProvider) { // Categories state routing $stateProvider. state('listCategories', { url: '/categories', templateUrl: 'modules/categories/views/list-categories.client.view.html' }). state('createCategory', { url: '/categories/create', templateUrl: 'modules/categories/views/create-category.client.view.html' }). state('viewCategory', { url: '/categories/:categoryId', templateUrl: 'modules/categories/views/view-category.client.view.html' }). state('editCategory', { url: '/categories/:categoryId/edit', templateUrl: 'modules/categories/views/edit-category.client.view.html' }); } ]); 'use strict'; // Categories controller angular.module('categories').controller('CategoriesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Categories', 'TableSettings', 'CategoriesForm', function($scope, $stateParams, $location, Authentication, Categories, TableSettings, CategoriesForm ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Categories); $scope.category = {}; $scope.setFormFields = function(disabled) { $scope.formFields = CategoriesForm.getFormFields(disabled); }; // Create new Category $scope.create = function() { var category = new Categories($scope.category); // Redirect after save category.$save(function(response) { $location.path('categories/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Category $scope.remove = function(category) { if ( category ) { category = Categories.get({categoryId:category._id}, function() { category.$remove(); $scope.tableParams.reload(); }); } else { $scope.category.$remove(function() { $location.path('categories'); }); } }; // Update existing Category $scope.update = function() { var category = $scope.category; category.$update(function() { $location.path('categories/' + category._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewCategory = function() { $scope.category = Categories.get( {categoryId: $stateParams.categoryId} ); $scope.setFormFields(true); }; $scope.toEditCategory = function() { $scope.category = Categories.get( {categoryId: $stateParams.categoryId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Categories service used to communicate Categories REST endpoints angular.module('categories').factory('Categories', ['$resource', function($resource) { return $resource('categories/:categoryId', { categoryId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('categories') .factory('CategoriesForm', factory); function factory() { var getFormFields = function(disabled) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }); } ]); 'use strict'; angular.module('core').controller('HeaderController', ['$scope', 'Authentication', 'Menus', function($scope, Authentication, Menus) { $scope.authentication = Authentication; $scope.isCollapsed = false; $scope.menu = Menus.getMenu('topbar'); $scope.toggleCollapsibleMenu = function() { $scope.isCollapsed = !$scope.isCollapsed; }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function() { $scope.isCollapsed = false; }); } ]); 'use strict'; angular.module('core').controller('HomeController', ['$scope', 'Authentication', function($scope, Authentication) { // This provides Authentication context. $scope.authentication = Authentication; } ]); 'use strict'; angular.module('core') .directive('ngReallyClick', ['$modal', function($modal) { var ModalInstanceCtrl = ["$scope", "$modalInstance", function($scope, $modalInstance) { $scope.ok = function() { $modalInstance.close(); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }]; return { restrict: 'A', scope: { ngReallyClick: '&' }, link: function(scope, element, attrs) { element.bind('click', function() { var message = attrs.ngReallyMessage || 'Are you sure ?'; var modalHtml = '<div class="modal-body">' + message + '</div>'; modalHtml += '<div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>'; var modalInstance = $modal.open({ template: modalHtml, controller: ModalInstanceCtrl }); modalInstance.result.then(function() { scope.ngReallyClick(); }, function() { //Modal dismissed }); }); } }; } ]); 'use strict'; //Menu service used for managing menus angular.module('core').service('Menus', [ function() { // Define a set of default roles this.defaultRoles = ['*']; // Define the menus object this.menus = {}; // A private function for rendering decision var shouldRender = function(user) { if (user) { if (!!~this.roles.indexOf('*')) { return true; } else { for (var userRoleIndex in user.roles) { for (var roleIndex in this.roles) { if (this.roles[roleIndex] === user.roles[userRoleIndex]) { return true; } } } } } else { return this.isPublic; } return false; }; // Validate menu existance this.validateMenuExistance = function(menuId) { if (menuId && menuId.length) { if (this.menus[menuId]) { return true; } else { throw new Error('Menu does not exists'); } } else { throw new Error('MenuId was not provided'); } return false; }; // Get the menu object by menu id this.getMenu = function(menuId) { // Validate that the menu exists this.validateMenuExistance(menuId); // Return the menu object return this.menus[menuId]; }; // Add new menu object by menu id this.addMenu = function(menuId, isPublic, roles) { // Create the new menu this.menus[menuId] = { isPublic: isPublic || false, roles: roles || this.defaultRoles, items: [], shouldRender: shouldRender }; // Return the menu object return this.menus[menuId]; }; // Remove existing menu object by menu id this.removeMenu = function(menuId) { // Validate that the menu exists this.validateMenuExistance(menuId); // Return the menu object delete this.menus[menuId]; }; // Add menu item object this.addMenuItem = function(menuId, menuItemTitle, menuItemURL, menuItemType, menuItemUIRoute, isPublic, roles, position) { // Validate that the menu exists this.validateMenuExistance(menuId); // Push new menu item this.menus[menuId].items.push({ title: menuItemTitle, link: menuItemURL, menuItemType: menuItemType || 'item', menuItemClass: menuItemType, uiRoute: menuItemUIRoute || ('/' + menuItemURL), isPublic: ((isPublic === null || typeof isPublic === 'undefined') ? this.menus[menuId].isPublic : isPublic), roles: ((roles === null || typeof roles === 'undefined') ? this.menus[menuId].roles : roles), position: position || 0, items: [], shouldRender: shouldRender }); // Return the menu object return this.menus[menuId]; }; // Add submenu item object this.addSubMenuItem = function(menuId, rootMenuItemURL, menuItemTitle, menuItemURL, menuItemUIRoute, isPublic, roles, position) { // Validate that the menu exists this.validateMenuExistance(menuId); // Search for menu item for (var itemIndex in this.menus[menuId].items) { if (this.menus[menuId].items[itemIndex].link === rootMenuItemURL) { // Push new submenu item this.menus[menuId].items[itemIndex].items.push({ title: menuItemTitle, link: menuItemURL, uiRoute: menuItemUIRoute || ('/' + menuItemURL), isPublic: ((isPublic === null || typeof isPublic === 'undefined') ? this.menus[menuId].items[itemIndex].isPublic : isPublic), roles: ((roles === null || typeof roles === 'undefined') ? this.menus[menuId].items[itemIndex].roles : roles), position: position || 0, shouldRender: shouldRender }); } } // Return the menu object return this.menus[menuId]; }; // Remove existing menu object by menu id this.removeMenuItem = function(menuId, menuItemURL) { // Validate that the menu exists this.validateMenuExistance(menuId); // Search for menu item to remove for (var itemIndex in this.menus[menuId].items) { if (this.menus[menuId].items[itemIndex].link === menuItemURL) { this.menus[menuId].items.splice(itemIndex, 1); } } // Return the menu object return this.menus[menuId]; }; // Remove existing menu object by menu id this.removeSubMenuItem = function(menuId, submenuItemURL) { // Validate that the menu exists this.validateMenuExistance(menuId); // Search for menu item to remove for (var itemIndex in this.menus[menuId].items) { for (var subitemIndex in this.menus[menuId].items[itemIndex].items) { if (this.menus[menuId].items[itemIndex].items[subitemIndex].link === submenuItemURL) { this.menus[menuId].items[itemIndex].items.splice(subitemIndex, 1); } } } // Return the menu object return this.menus[menuId]; }; //Adding the topbar menu this.addMenu('topbar'); } ]); (function() { 'use strict'; angular .module('core') .factory('TableSettings', ['NgTableParams', function(NgTableParams) { var getData = function(Entity) { return function($defer, params) { Entity.get(params.url(), function(response) { params.total(response.total); $defer.resolve(response.results); }); }; }; var params = { page: 1, count: 5 }; var settings = { total: 0, counts: [5, 10, 15], filterDelay: 0, }; var getParams = function(Entity) { var tableParams = new NgTableParams(params, settings); tableParams.settings({getData: getData(Entity)}); return tableParams; }; var service = { getParams: getParams }; return service; }]); })(); 'use strict'; // Configuring the new module angular.module('events').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Events', 'events', 'dropdown', '/events(/create)?'); Menus.addSubMenuItem('topbar', 'events', 'List Events', 'events'); Menus.addSubMenuItem('topbar', 'events', 'New Event', 'events/create'); } ]); 'use strict'; //Setting up route angular.module('events').config(['$stateProvider', function($stateProvider) { // Events state routing $stateProvider. state('listEvents', { url: '/events', templateUrl: 'modules/events/views/list-events.client.view.html' }). state('createEvent', { url: '/events/create', templateUrl: 'modules/events/views/create-event.client.view.html' }). state('viewEvent', { url: '/events/:eventId', templateUrl: 'modules/events/views/view-event.client.view.html' }). state('editEvent', { url: '/events/:eventId/edit', templateUrl: 'modules/events/views/edit-event.client.view.html' }); } ]); 'use strict'; // Events controller angular.module('events').controller('EventsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Events', 'TableSettings', 'EventsForm', function($scope, $stateParams, $location, Authentication, Events, TableSettings, EventsForm ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Events); $scope.event = {}; $scope.setFormFields = function(disabled) { $scope.formFields = EventsForm.getFormFields(disabled); }; // Create new Event $scope.create = function() { var event = new Events($scope.event); // Redirect after save event.$save(function(response) { $location.path('events/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Event $scope.remove = function(event) { if ( event ) { event = Events.get({eventId:event._id}, function() { event.$remove(); $scope.tableParams.reload(); }); } else { $scope.event.$remove(function() { $location.path('events'); }); } }; // Update existing Event $scope.update = function() { var event = $scope.event; event.$update(function() { $location.path('events/' + event._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewEvent = function() { $scope.event = Events.get( {eventId: $stateParams.eventId} ); $scope.setFormFields(true); }; $scope.toEditEvent = function() { $scope.event = Events.get( {eventId: $stateParams.eventId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Events service used to communicate Events REST endpoints angular.module('events').factory('Events', ['$resource', function($resource) { return $resource('events/:eventId', { eventId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('events') .factory('EventsForm', factory); function factory() { var getFormFields = function(disabled) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Configuring the new module angular.module('files').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Files', 'files', 'dropdown', '/files(/create)?'); Menus.addSubMenuItem('topbar', 'files', 'List Files', 'files'); Menus.addSubMenuItem('topbar', 'files', 'New File', 'files/create'); } ]); 'use strict'; //Setting up route angular.module('files').config(['$stateProvider', function($stateProvider) { // Files state routing $stateProvider. state('listFiles', { url: '/files', templateUrl: 'modules/files/views/list-files.client.view.html' }). state('createFile', { url: '/files/create', templateUrl: 'modules/files/views/create-file.client.view.html' }). state('viewFile', { url: '/files/:fileId', templateUrl: 'modules/files/views/view-file.client.view.html' }). state('editFile', { url: '/files/:fileId/edit', templateUrl: 'modules/files/views/edit-file.client.view.html' }); } ]); 'use strict'; // Files controller angular.module('files').controller('FilesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Files', 'TableSettings', 'FilesForm', function($scope, $stateParams, $location, Authentication, Files, TableSettings, FilesForm ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Files); $scope.file = {}; $scope.setFormFields = function(disabled) { $scope.formFields = FilesForm.getFormFields(disabled); }; // Create new File $scope.create = function() { var file = new Files($scope.file); // Redirect after save file.$save(function(response) { $location.path('files/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing File $scope.remove = function(file) { if ( file ) { file = Files.get({fileId:file._id}, function() { file.$remove(); $scope.tableParams.reload(); }); } else { $scope.file.$remove(function() { $location.path('files'); }); } }; // Update existing File $scope.update = function() { var file = $scope.file; file.$update(function() { $location.path('files/' + file._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewFile = function() { $scope.file = Files.get( {fileId: $stateParams.fileId} ); $scope.setFormFields(true); }; $scope.toEditFile = function() { $scope.file = Files.get( {fileId: $stateParams.fileId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Files service used to communicate Files REST endpoints angular.module('files').factory('Files', ['$resource', function($resource) { return $resource('files/:fileId', { fileId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('files') .factory('FilesForm', factory); function factory() { var getFormFields = function(disabled) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Configuring the new module angular.module('projects').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Projects', 'projects', 'dropdown', '/projects(/create)?'); Menus.addSubMenuItem('topbar', 'projects', 'List Projects', 'projects'); Menus.addSubMenuItem('topbar', 'projects', 'New Project', 'projects/create'); } ]); 'use strict'; //Setting up route angular.module('projects').config(['$stateProvider', function($stateProvider) { // Projects state routing $stateProvider. state('listProjects', { url: '/projects', templateUrl: 'modules/projects/views/list-projects.client.view.html' }). state('createProject', { url: '/projects/create', templateUrl: 'modules/projects/views/create-project.client.view.html' }). state('viewProject', { url: '/projects/:projectId', templateUrl: 'modules/projects/views/view-project.client.view.html' }). state('editProject', { url: '/projects/:projectId/edit', templateUrl: 'modules/projects/views/edit-project.client.view.html' }); } ]); 'use strict'; // Projects controller angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Projects', 'TableSettings', 'ProjectsForm', function($scope, $stateParams, $location, Authentication, Projects, TableSettings, ProjectsForm ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Projects); $scope.project = {}; $scope.setFormFields = function(disabled) { $scope.formFields = ProjectsForm.getFormFields(disabled); }; // Create new Project $scope.create = function() { var project = new Projects($scope.project); // Redirect after save project.$save(function(response) { $location.path('projects/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Project $scope.remove = function(project) { if ( project ) { project = Projects.get({projectId:project._id}, function() { project.$remove(); $scope.tableParams.reload(); }); } else { $scope.project.$remove(function() { $location.path('projects'); }); } }; // Update existing Project $scope.update = function() { var project = $scope.project; project.$update(function() { $location.path('projects/' + project._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewProject = function() { $scope.project = Projects.get( {projectId: $stateParams.projectId} ); $scope.setFormFields(true); }; $scope.toEditProject = function() { $scope.project = Projects.get( {projectId: $stateParams.projectId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Projects service used to communicate Projects REST endpoints angular.module('projects').factory('Projects', ['$resource', function($resource) { return $resource('projects/:projectId', { projectId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('projects') .factory('ProjectsForm', factory); function factory() { var getFormFields = function(disabled) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Configuring the new module angular.module('tasks').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Tasks', 'tasks', 'dropdown', '/tasks(/create)?'); Menus.addSubMenuItem('topbar', 'tasks', 'List Tasks', 'tasks'); Menus.addSubMenuItem('topbar', 'tasks', 'New Task', 'tasks/create'); } ]); 'use strict'; //Setting up route angular.module('tasks').config(['$stateProvider', function($stateProvider) { // Tasks state routing $stateProvider. state('listTasks', { url: '/tasks', templateUrl: 'modules/tasks/views/list-tasks.client.view.html' }). state('createTask', { url: '/tasks/create', templateUrl: 'modules/tasks/views/create-task.client.view.html' }). state('viewTask', { url: '/tasks/:taskId', templateUrl: 'modules/tasks/views/view-task.client.view.html' }). state('editTask', { url: '/tasks/:taskId/edit', templateUrl: 'modules/tasks/views/edit-task.client.view.html' }); } ]); 'use strict'; // Tasks controller angular.module('tasks').controller('TasksController', ['$scope', '$stateParams', '$location', 'Authentication', 'Tasks', 'TableSettings', 'TasksForm', 'Users', 'Projects', 'Categories', function($scope, $stateParams, $location, Authentication, Tasks, TableSettings, TasksForm, Users, Projects, Categories ) { $scope.authentication = Authentication; $scope.tableParams = TableSettings.getParams(Tasks); $scope.task = {}; $scope.userOptions = Users.query(); $scope.projectOptions = Projects.query(); $scope.categoryOptions = Categories.query(); $scope.setFormFields = function(disabled ) { $scope.formFields = TasksForm.getFormFields(disabled, $scope.userOptions, $scope.projectOptions, $scope.categoryOptions); }; // Create new Task $scope.create = function() { var task = new Tasks($scope.task); // Redirect after save task.$save(function(response) { $location.path('tasks/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Task $scope.remove = function(task) { if ( task ) { task = Tasks.get({taskId:task._id}, function() { task.$remove(); $scope.tableParams.reload(); }); } else { $scope.task.$remove(function() { $location.path('tasks'); }); } }; // Update existing Task $scope.update = function() { var task = $scope.task; task.$update(function() { $location.path('tasks/' + task._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.toViewTask = function() { $scope.task = Tasks.get( {taskId: $stateParams.taskId} ); $scope.setFormFields(true); }; $scope.toEditTask = function() { $scope.task = Tasks.get( {taskId: $stateParams.taskId} ); $scope.setFormFields(false); }; } ]); 'use strict'; //Tasks service used to communicate Tasks REST endpoints angular.module('tasks').factory('Tasks', ['$resource', function($resource) { return $resource('tasks/:taskId', { taskId: '@_id' }, { update: { method: 'PUT' } }); } ]); (function() { 'use strict'; angular .module('tasks') .factory('TasksForm', factory); function factory() { var getFormFields = function(disabled, userOptions, projectOptions, categoryOptions) { var fields = [ { key: 'name', type: 'input', templateOptions: { label: 'Name:', disabled: disabled } }, { key: 'description', type: 'textarea', templateOptions: { label: 'Description:', disabled: disabled } }, { key: 'assignee', // ng-model name, saved in formData type: 'select', // field templateOptions: { label: 'Aassignee', //multiple: true, labelProp: 'displayName', valueProp: '_id', options: userOptions, disabled: disabled } }, { key: 'watcher', // ng-model name, saved in formData type: 'select', // field templateOptions: { label: 'Watcher', //multiple: true, labelProp: 'displayName', valueProp: '_id', options: userOptions, disabled: disabled } }, { key: 'project', // ng-model name, saved in formData type: 'select', // field templateOptions: { label: 'Project', //multiple: true, labelProp: 'name', valueProp: '_id', options: projectOptions, disabled: disabled } }, { key: 'category', // ng-model name, saved in formData type: 'select', // field templateOptions: { label: 'Category', //multiple: true, labelProp: 'name', valueProp: '_id', options: categoryOptions, disabled: disabled } } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })(); 'use strict'; // Config HTTP Error Handling angular.module('users').config(['$httpProvider', function($httpProvider) { // Set the httpProvider "not authorized" interceptor $httpProvider.interceptors.push(['$q', '$location', 'Authentication', function($q, $location, Authentication) { return { responseError: function(rejection) { switch (rejection.status) { case 401: // Deauthenticate the global user Authentication.user = null; // Redirect to signin page $location.path('signin'); break; case 403: // Add unauthorized behaviour break; } return $q.reject(rejection); } }; } ]); } ]); 'use strict'; // Setting up route angular.module('users').config(['$stateProvider', function($stateProvider) { // Users state routing $stateProvider. state('profile', { url: '/settings/profile', templateUrl: 'modules/users/views/settings/edit-profile.client.view.html' }). state('password', { url: '/settings/password', templateUrl: 'modules/users/views/settings/change-password.client.view.html' }). state('accounts', { url: '/settings/accounts', templateUrl: 'modules/users/views/settings/social-accounts.client.view.html' }). state('signup', { url: '/signup', templateUrl: 'modules/users/views/authentication/signup.client.view.html' }). state('signin', { url: '/signin', templateUrl: 'modules/users/views/authentication/signin.client.view.html' }). state('forgot', { url: '/password/forgot', templateUrl: 'modules/users/views/password/forgot-password.client.view.html' }). state('reset-invalid', { url: '/password/reset/invalid', templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html' }). state('reset-success', { url: '/password/reset/success', templateUrl: 'modules/users/views/password/reset-password-success.client.view.html' }). state('reset', { url: '/password/reset/:token', templateUrl: 'modules/users/views/password/reset-password.client.view.html' }); } ]); 'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/'); $scope.signup = function() { $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; } ]); 'use strict'; angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$http', '$location', 'Authentication', function($scope, $stateParams, $http, $location, Authentication) { $scope.authentication = Authentication; //If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/'); // Submit forgotten password account id $scope.askForPasswordReset = function() { $scope.success = $scope.error = null; $http.post('/auth/forgot', $scope.credentials).success(function(response) { // Show user success message and clear form $scope.credentials = null; $scope.success = response.message; }).error(function(response) { // Show user error message and clear form $scope.credentials = null; $scope.error = response.message; }); }; // Change user password $scope.resetUserPassword = function() { $scope.success = $scope.error = null; $http.post('/auth/reset/' + $stateParams.token, $scope.passwordDetails).success(function(response) { // If successful show success message and clear form $scope.passwordDetails = null; // Attach user profile Authentication.user = response; // And redirect to the index page $location.path('/password/reset/success'); }).error(function(response) { $scope.error = response.message; }); }; } ]); 'use strict'; angular.module('users').controller('SettingsController', ['$scope', '$http', '$location', 'Users', 'Authentication', function($scope, $http, $location, Users, Authentication) { $scope.user = Authentication.user; // If user is not signed in then redirect back home if (!$scope.user) $location.path('/'); // Check if there are additional accounts $scope.hasConnectedAdditionalSocialAccounts = function(provider) { for (var i in $scope.user.additionalProvidersData) { return true; } return false; }; // Check if provider is already in use with current user $scope.isConnectedSocialAccount = function(provider) { return $scope.user.provider === provider || ($scope.user.additionalProvidersData && $scope.user.additionalProvidersData[provider]); }; // Remove a user social account $scope.removeUserSocialAccount = function(provider) { $scope.success = $scope.error = null; $http.delete('/users/accounts', { params: { provider: provider } }).success(function(response) { // If successful show success message and clear form $scope.success = true; $scope.user = Authentication.user = response; }).error(function(response) { $scope.error = response.message; }); }; // Update a user profile $scope.updateUserProfile = function(isValid) { if (isValid) { $scope.success = $scope.error = null; var user = new Users($scope.user); user.$update(function(response) { $scope.success = true; Authentication.user = response; }, function(response) { $scope.error = response.data.message; }); } else { $scope.submitted = true; } }; // Change user password $scope.changeUserPassword = function() { $scope.success = $scope.error = null; $http.post('/users/password', $scope.passwordDetails).success(function(response) { // If successful show success message and clear form $scope.success = true; $scope.passwordDetails = null; }).error(function(response) { $scope.error = response.message; }); }; } ]); 'use strict'; // Authentication service for user variables angular.module('users').factory('Authentication', [ function() { var _this = this; _this._data = { user: window.user }; return _this._data; } ]); 'use strict'; // Users service used for communicating with the users REST endpoint angular.module('users').factory('Users', ['$resource', function($resource) { return $resource('users', {}, { update: { method: 'PUT' } }); } ]);
25.574012
209
0.61914
b72aac4789593f3b255b182804c2bb4a32df9c11
1,969
js
JavaScript
src/legacy/core_plugins/kibana/public/dashboard/viewport/dashboard_viewport.js
LAFINAL/kibana
5251267bb952f890edba8260f79771a8694d802d
[ "Apache-2.0" ]
null
null
null
src/legacy/core_plugins/kibana/public/dashboard/viewport/dashboard_viewport.js
LAFINAL/kibana
5251267bb952f890edba8260f79771a8694d802d
[ "Apache-2.0" ]
null
null
null
src/legacy/core_plugins/kibana/public/dashboard/viewport/dashboard_viewport.js
LAFINAL/kibana
5251267bb952f890edba8260f79771a8694d802d
[ "Apache-2.0" ]
null
null
null
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import { DashboardGrid } from '../grid'; import { ExitFullScreenButton } from '../components/exit_full_screen_button'; export function DashboardViewport({ maximizedPanelId, getEmbeddableFactory, panelCount, title, description, useMargins, isFullScreenMode, onExitFullScreenMode, }) { return ( <div data-shared-items-count={panelCount} data-shared-items-container data-title={title} data-description={description} className={useMargins ? 'dshDashboardViewport-withMargins' : 'dshDashboardViewport'} > { isFullScreenMode && <ExitFullScreenButton onExitFullScreenMode={onExitFullScreenMode} /> } <DashboardGrid getEmbeddableFactory={getEmbeddableFactory} maximizedPanelId={maximizedPanelId} /> </div> ); } DashboardViewport.propTypes = { getEmbeddableFactory: PropTypes.func, maximizedPanelId: PropTypes.string, panelCount: PropTypes.number, title: PropTypes.string, description: PropTypes.string, useMargins: PropTypes.bool.isRequired, };
32.816667
99
0.715592
b72accdccc47175f2ad7a4394d7078e43f067f1a
1,252
js
JavaScript
packages/aws-fargate/src/metrics/container/SecondaryEcsContainerFactory.js
ThisIsMissEm/nodejs-sensor
81322940d857d8a222bc4a285f692331c75804a2
[ "MIT" ]
null
null
null
packages/aws-fargate/src/metrics/container/SecondaryEcsContainerFactory.js
ThisIsMissEm/nodejs-sensor
81322940d857d8a222bc4a285f692331c75804a2
[ "MIT" ]
null
null
null
packages/aws-fargate/src/metrics/container/SecondaryEcsContainerFactory.js
ThisIsMissEm/nodejs-sensor
81322940d857d8a222bc4a285f692331c75804a2
[ "MIT" ]
null
null
null
'use strict'; const { DataProcessor } = require('@instana/metrics-util'); /** * Uses the response from ${metadataUri}/task to create processors for all secondary (non-instrumented containers). */ class SecondaryContainerFactory extends DataProcessor { constructor(rootDataSource, taskDataSource) { super('com.instana.plugin.dummy'); this.addSource('root', rootDataSource); this.addSource('task', taskDataSource); } getEntityId() { // does not participate in producing entity data return null; } processData(rawDataPerSource) { const rootMetadata = rawDataPerSource.root; const taskMetadata = rawDataPerSource.task; if ( !rootMetadata || rootMetadata.Name == null || !taskMetadata || taskMetadata.TaskARN == null || !taskMetadata.Containers ) { return {}; } const instrumentedDockerId = rootMetadata.DockerId; const taskArn = taskMetadata.TaskARN; const secondaryContainers = taskMetadata.Containers.map(c => ({ dockerId: c.DockerId, containerId: `${taskArn}::${c.Name}` })).filter(({ dockerId }) => dockerId !== instrumentedDockerId); return { secondaryContainers }; } } module.exports = exports = SecondaryContainerFactory;
29.116279
115
0.684505
b72b3274048e7dd54a3682f6c46e260e98ff9ba8
3,411
js
JavaScript
spec/Control.spec.js
je-an/jean-control
6769f18b2f70655a71e2bc3c81fdcc8b8b30f167
[ "MIT" ]
null
null
null
spec/Control.spec.js
je-an/jean-control
6769f18b2f70655a71e2bc3c81fdcc8b8b30f167
[ "MIT" ]
null
null
null
spec/Control.spec.js
je-an/jean-control
6769f18b2f70655a71e2bc3c81fdcc8b8b30f167
[ "MIT" ]
null
null
null
// jscs:disable // jshint ignore:start define([ "Control" ], function (Control) { describe('Control.spec.js', function () { var instance, containerId = "container-id"; describe("Control", function () { it("Is defined", function () { expect(Control).not.toBeUndefined(); }); it("Provides a private variable <this._options> for all inheriting classes", function () { var c = new Control({}, { containerId: containerId }); expect(c._options).not.toBeUndefined(); }); it("Provides a private variable <this._element> for all inheriting classes", function () { var c = new Control({}, { containerId: containerId }); expect(c._element).not.toBeUndefined(); }); it("Provides a private variable <this._container> for all inheriting classes", function () { var c = new Control({}, { containerId: containerId }); expect(c._container).not.toBeUndefined(); }); it("Merges the user provided options which the default options", function () { var instance = new Control({ id: "id" }, { containerId: containerId, name: "name" }); expect(instance._options.id).toEqual("id"); expect(instance._options.name).toEqual("name"); }); it("Throws exception, if constructor is called without parameters", function () { try { instance = new Control(); } catch (e) { expect(e instanceof Error).toBe(true); } }); it("Throws exception, if options are not an object", function () { try { instance = new Control("", {}); } catch (e) { expect(e instanceof TypeError).toBe(true); } }); it("Throws exception, if defaultOptions are not an object", function () { try { instance = new Control({}, ""); } catch (e) { expect(e instanceof TypeError).toBe(true); } }); it("Throws exception, if no containerId is passed", function () { try { instance = new Control({}, {}); } catch (e) { expect(e instanceof Error).toBe(true); } }); afterEach(function () { $("#" + containerId).remove(); }); }); describe("After creation,", function () { it("the container element is part of the DOM", function () { var instance = new Control({}, { containerId: containerId }); instance.create(); expect($("#" + containerId).length).toEqual(1); }); it("the control element is part of the DOM", function () { var instance = new Control({}, { containerId: containerId }); instance._element = $("<div id='dummy'></div>"); instance.create(); expect($("#dummy").length).toEqual(1); }); afterEach(function () { $("#" + containerId).remove(); }); }); }); });
42.6375
104
0.473761
b72bd9724601a7f99ac9c2188aec41d614e63a3c
180
js
JavaScript
src/query-helper/normalize/group-by.js
learn-by-do/mysql-orm
881e641c9a62828dcce513dc08e75bfd1cced1b4
[ "MIT" ]
1
2019-08-28T21:04:42.000Z
2019-08-28T21:04:42.000Z
src/query-helper/normalize/group-by.js
learn-by-do/mysql-orm
881e641c9a62828dcce513dc08e75bfd1cced1b4
[ "MIT" ]
2
2021-05-08T22:03:42.000Z
2021-09-01T05:37:29.000Z
src/query-helper/normalize/group-by.js
learn-by-do/mysql-orm
881e641c9a62828dcce513dc08e75bfd1cced1b4
[ "MIT" ]
null
null
null
const { escapeId } = require('mysql2') function normalizeGroupBy (field) { if (!field) { return } return escapeId(field) } exports.normalizeGroupBy = normalizeGroupBy
15
43
0.7
b72c10655de54956b9b6d39a737a05b3d649bc9f
2,849
js
JavaScript
modul/request.js
andreseloysv/digystar
107718ff3c4f104943359e36d2f6c1ae41c9510c
[ "MIT" ]
null
null
null
modul/request.js
andreseloysv/digystar
107718ff3c4f104943359e36d2f6c1ae41c9510c
[ "MIT" ]
1
2021-05-10T08:40:48.000Z
2021-05-10T08:40:48.000Z
modul/request.js
andreseloysv/digystar
107718ff3c4f104943359e36d2f6c1ae41c9510c
[ "MIT" ]
null
null
null
const databaseConnection = require('../globals/db.js'); async function queryGetRequestInfo(client) { const query = `SELECT count(id), country FROM "user".request group by country;`; const result = await client.query(query); console.log('query request', query); return result.rows; } async function queryGetRegisteredUsers(client) { const query = `SELECT count(id) FROM "user".user;`; const result = await client.query(query); console.log('query number of registered users', query); return result.rows; } async function getRequestInfo() { const client = databaseConnection.getDBClient(); client.connect(); const requestInfo = await queryGetRequestInfo(client); client.end(); return JSON.stringify(requestInfo); } async function getRegisteredUsers() { const client = databaseConnection.getDBClient(); client.connect(); const requestInfo = await queryGetRegisteredUsers(client); client.end(); return JSON.stringify(requestInfo); } async function querySaveUserEmail(client, email) { const query = `INSERT into "user".user ("email") VALUES ($1);`; const values = [email]; console.log('query insert user email', query,values); return await client.query(query, values); } async function saveUserEmail(email = '') { let client = databaseConnection.getDBClient(); client.connect(); await querySaveUserEmail(client, email); client.end(); } async function querySaveRequestInfo( client, ip, country, host, userAgen, browserName, browserVersion, osName, osVersion, deviceVendor, deviceModel, deviceType, acceptLanguage ) { const query = `INSERT into "user".request ("ip", "country", "host", "useragen", "browsername", "browserversion", "osname","osversion","devicevendor", "devicemodel","devicetype", "acceptlanguage") VALUES ($1,$2, $3,$4,$5,$6,$7, $8,$9,$10,$11,$12);`; const values = [ ip, country, host, userAgen, browserName, browserVersion, osName, osVersion, deviceVendor, deviceModel, deviceType, acceptLanguage ]; console.log('query insert request', query, values); return await client.query(query, values); } async function saveRequestInfo( ip = '', country = '', host = '', userAgen = '', browserName = '', browserVersion = '', osName = '', osVersion = '', deviceVendor = '', deviceModel = '', deviceType = '', acceptLanguage = '' ) { let client = databaseConnection.getDBClient(); client.connect(); await querySaveRequestInfo( client, ip, country, host, userAgen, browserName, browserVersion, osName, osVersion, deviceVendor, deviceModel, deviceType, acceptLanguage ); client.end(); } module.exports = { getRegisteredUsers, getRequestInfo, saveUserEmail, saveRequestInfo };
22.257813
82
0.674623
b72c17d6872aada024db3f58aea187b2045e26ff
1,956
js
JavaScript
app/shared/excelLoader.js
ArjaaAine/WorldConqueror
e7f63fad01c786d40b79aaafe480180438dcf137
[ "MIT" ]
1
2017-12-09T20:49:35.000Z
2017-12-09T20:49:35.000Z
app/shared/excelLoader.js
ArjaaAine/WorldConqueror
e7f63fad01c786d40b79aaafe480180438dcf137
[ "MIT" ]
1
2018-03-02T06:52:55.000Z
2018-03-02T06:52:55.000Z
app/shared/excelLoader.js
ArjaaAine/WorldConqueror
e7f63fad01c786d40b79aaafe480180438dcf137
[ "MIT" ]
1
2018-08-08T05:15:36.000Z
2018-08-08T05:15:36.000Z
// Universal excel loader, all you need to do is specify "sheets" array, which tells the function what to return to you. // for example ["BuildingType", "Units"] as long as those 2 sheets are part of same excel file. const getDataFromExcel = function ($q, sheets, fileName) { return $q((resolve, reject) => { // Pass an url or load default + Date string to load new file instead of cached. const path = `assets/excel/${fileName}`; const fileUrl = `${path}?_=${new Date().getTime()}`; const oReq = new XMLHttpRequest(); oReq.open("GET", fileUrl, true); oReq.responseType = "arraybuffer"; oReq.onload = function () { const arraybuffer = oReq.response; /* Convert data to binary string */ const data = new Uint8Array(arraybuffer); const arr = []; for (let i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); const bstr = arr.join(""); /* Call XLSX */ const workbook = XLSX.read(bstr, { type: "binary" }); /* DO SOMETHING WITH workbook HERE */ const workbookSheets = {}; for (let j = 0; j < sheets.length; j++) { const workbookSheet = workbook.Sheets[sheets[j]]; // Raw so we get numbers instead of strings, header: 1 creates a 2D array const sheetData = XLSX.utils.sheet_to_json(workbookSheet, { header: 1, raw : true }); workbookSheets[sheets[j]] = {}; const arra = []; // Work with 2d array and create an object. for (let l = 1; l < sheetData.length; l++) { const obj = {}; for (let k = 0; k < sheetData[0].length; k++) { const property = sheetData[0][k]; obj[property] = sheetData[l][k]; } arra.push(obj); } workbookSheets[sheets[j]] = arra; } console.log("Finished initializing data from excel"); resolve(workbookSheets); }; oReq.send(); }); };
32.6
120
0.581288
b72d02646ed5f48a004f8fd481aaf7a8775d6790
122
js
JavaScript
ruoyi-ui/src/utils/errorCode.js
cat0501/RuoYi-Cloud
841fb22e539c856a0041ddbc206ff7ef89a2a827
[ "MIT" ]
1,544
2020-03-21T12:31:07.000Z
2022-03-29T10:27:06.000Z
ruoyi-ui/src/utils/errorCode.js
cat0501/RuoYi-Cloud
841fb22e539c856a0041ddbc206ff7ef89a2a827
[ "MIT" ]
2
2021-03-09T14:24:14.000Z
2021-03-22T06:09:51.000Z
ruoyi-ui/src/utils/errorCode.js
cat0501/RuoYi-Cloud
841fb22e539c856a0041ddbc206ff7ef89a2a827
[ "MIT" ]
83
2020-04-19T11:37:35.000Z
2022-03-31T03:01:03.000Z
export default { '401': '认证失败,无法访问系统资源', '403': '当前操作没有权限', '404': '访问资源不存在', 'default': '系统未知错误,请反馈给管理员' }
17.428571
30
0.565574
b72d42619db0948deaaa43bf2bc6d37963070347
533
js
JavaScript
testServer/index.js
kgroat/BuildingBlox
34d7104033501f3c5a0a1389d17a31f1c1e9c765
[ "MIT" ]
2
2017-01-18T03:52:21.000Z
2017-06-16T01:33:26.000Z
testServer/index.js
thegrtman/BuildingBlox
34d7104033501f3c5a0a1389d17a31f1c1e9c765
[ "MIT" ]
null
null
null
testServer/index.js
thegrtman/BuildingBlox
34d7104033501f3c5a0a1389d17a31f1c1e9c765
[ "MIT" ]
null
null
null
/*jshint -W024*/ /*jslint node: true*/ 'use strict'; var express = require('express'); var http = require('http'); var port = 3000; var app = express(); app.use(require('express-markdown')({ directory: __dirname + '/..' })); app.use('/', express.static(__dirname + '/pages')); app.use('/dist', express.static(__dirname + '/../dist')); app.use('/node_modules', express.static(__dirname + '/../node_modules')); http.createServer(app).listen(port, function () { console.log('Express server listening on port ' + port); });
24.227273
73
0.64728
b72fbff8491921599b3dbc0320538ca232a0041b
3,972
js
JavaScript
web/components/navbar/index.js
nwplus/nwhacks2019
7dc5a75913bd4f1e78ff2149252969baa5bba117
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
10
2018-10-30T01:55:42.000Z
2021-05-19T11:04:52.000Z
web/components/navbar/index.js
nwplus/nwhacks2019
7dc5a75913bd4f1e78ff2149252969baa5bba117
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
95
2018-09-19T19:34:09.000Z
2019-01-25T07:38:42.000Z
web/components/navbar/index.js
nwplus/nwhacks2019
7dc5a75913bd4f1e78ff2149252969baa5bba117
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
4
2018-11-01T22:09:17.000Z
2020-05-24T02:16:21.000Z
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { DISPLAY_TYPE } from '../../containers/navbar/DisplayTypes'; import { BUTTON_TYPE } from '../../containers/navbar/ButtonTypes'; import { SECTION } from '../home/Sections'; import { SecondaryButton } from '../input/buttons'; import logo from '../../assets/logo.svg'; const getButton = (buttonType) => { switch (buttonType) { case BUTTON_TYPE.SIGN_IN: return (<Link to="/login"><SecondaryButton text="Sign in" /></Link>); case BUTTON_TYPE.SIGN_OUT: return (<Link to="/logout"><SecondaryButton text="Sign out" /></Link>); case BUTTON_TYPE.DASHBOARD: return (<Link to="/dashboard"><SecondaryButton text="My application" /></Link>); default: return (<div />); } }; const NAVBAR_HEIGHT = 96; const LINK_CLASS = 'flex ai-center margin-sides-l scale-margin-sides-tablet'; class Navbar extends React.Component { constructor(props) { super(props); this.state = { hidden: false, transparent: true, lastY: 0, }; } componentDidMount() { window.addEventListener('scroll', this.handleScroll, { passive: true }); } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll); } handleScroll = () => { // Calculate scroll direction const { lastY } = this.state; const scrollingDown = (window.scrollY - lastY) >= 0; // Calculate position const offset = window.pageYOffset || document.documentElement.scrollTop; const atTop = offset < NAVBAR_HEIGHT; // Calculate transparency - turn navbar transparent if some distance under // the navbar const transparent = offset < (NAVBAR_HEIGHT * 3); // Update state this.setState({ transparent, hidden: (!atTop && scrollingDown), lastY: window.scrollY, }); } render() { const { hidden, transparent } = this.state; const { displayType, buttonType } = this.props; const button = getButton(buttonType); const linkElements = [ <Link to={{ pathname: '/', hash: SECTION.ABOUT }}><b>About</b></Link>, <Link to={{ pathname: '/', hash: SECTION.STORIES }}><b>Stories</b></Link>, <Link to={{ pathname: '/', hash: SECTION.FAQ }}><b>FAQ</b></Link>, <Link to={{ pathname: '/', hash: SECTION.SPONSORS }}><b>Sponsors</b></Link>, <a href="http://nwplus.github.io/nwhacks2018_static" target="_blank" rel="noopener noreferrer"> <b>2018</b> </a>, ]; let navbarRight; let key = 0; switch (displayType) { case DISPLAY_TYPE.ONLY_LOGO: break; case DISPLAY_TYPE.LOGO_AND_BUTTON: navbarRight = <div className={LINK_CLASS}>{button}</div>; break; case DISPLAY_TYPE.LOGO_AND_LINKS: navbarRight = linkElements.map(l => ( <div key={key += 1} className={`${LINK_CLASS} scale-hide-phablet`}> {l} </div> )); break; default: navbarRight = linkElements.map(l => ( <div key={key += 1} className={`${LINK_CLASS} scale-hide-phablet`}> {l} </div> )); navbarRight.push(( <div key={key += 1} className={LINK_CLASS}> {button} </div> )); } return ( <nav className={`fill-width flex ${hidden ? 'hide' : ''} ${transparent ? 'transparent' : 'shadow'}`}> <div className="flex ai-center jc-start margin-sides-l scale-margin-sides-tablet"> <div className="flex ai-center"> <Link to="/"><img alt="nwHacks" src={logo} /></Link> </div> </div> <div className="flex jc-end fill-width pad-right-s"> {navbarRight} </div> </nav> ); } } Navbar.propTypes = { displayType: PropTypes.symbol, buttonType: PropTypes.symbol, }; export default Navbar;
29.422222
107
0.589124
b730b56ff5590c471c17b28a451ec8e7f25ebe9b
1,857
js
JavaScript
src/fa/piedPiperAlt.js
danielkov/react-icons-kit
160bc967ed1ba9cad75a86fb40a449e1f79d1fe0
[ "MIT" ]
372
2017-01-07T01:54:27.000Z
2022-03-02T10:16:01.000Z
src/fa/piedPiperAlt.js
danielkov/react-icons-kit
160bc967ed1ba9cad75a86fb40a449e1f79d1fe0
[ "MIT" ]
72
2016-12-17T04:04:02.000Z
2022-02-26T03:35:19.000Z
src/fa/piedPiperAlt.js
qza7849467chensh5/react-icons-kit
09aeaf39d13e33c45bd032cc1b42a64c5a334dd9
[ "MIT" ]
66
2017-05-14T21:52:41.000Z
2021-12-08T12:15:09.000Z
export const piedPiperAlt = {"viewBox":"0 0 2038 1792","children":[{"name":"path","attribs":{"d":"M1222 929q75-3 143.5 20.5t118 58.5 101 94.5 84 108 75.5 120.5q33 56 78.5 109t75.5 80.5 99 88.5q-48 30-108.5 57.5t-138.5 59-114 47.5q-44-37-74-115t-43.5-164.5-33-180.5-42.5-168.5-72.5-123-122.5-48.5l-10 2-6 4q4 5 13 14 6 5 28 23.5t25.5 22 19 18 18 20.5 11.5 21 10.5 27.5 4.5 31 4 40.5l1 33q1 26-2.5 57.5t-7.5 52-12.5 58.5-11.5 53q-35-1-101 9.5t-98 10.5q-39 0-72-10-2-16-2-47 0-74 3-96 2-13 31.5-41.5t57-59 26.5-51.5q-24-2-43 24-36 53-111.5 99.5t-136.5 46.5q-25 0-75.5-63t-106.5-139.5-84-96.5q-6-4-27-30-482 112-513 112-16 0-28-11t-12-27q0-15 8.5-26.5t22.5-14.5l486-106q-8-14-8-25t5.5-17.5 16-11.5 20-7 23-4.5 18.5-4.5q4-1 15.5-7.5t17.5-6.5q15 0 28 16t20 33q163-37 172-37 17 0 29.5 11t12.5 28q0 15-8.5 26t-23.5 14l-182 40-1 16q-1 26 81.5 117.5t104.5 91.5q47 0 119-80t72-129q0-36-23.5-53t-51-18.5-51-11.5-23.5-34q0-16 10-34l-68-19q43-44 43-117 0-26-5-58 82-16 144-16 44 0 71.5 1.5t48.5 8.5 31 13.5 20.5 24.5 15.5 33.5 17 47.5 24 60l50-25q-3 40-23 60t-42.5 21-40 6.5-16.5 20.5zM1282 694q-5-5-13.5-15.5t-12-14.5-10.5-11.5-10-10.5l-8-8t-8.5-7.5-8-5-8.5-4.5q-7-3-14.5-5t-20.5-2.5-22-0.5h-32.5-37.5q-126 0-217 43 16-30 36-46.5t54-29.5 65.5-36 46-36.5 50-55 43.5-50.5q12 9 28 31.5t32 36.5 38 13l12-1v76l22 1q247-95 371-190 28-21 50-39t42.5-37.5 33-31 29.5-34 24-31 24.5-37 23-38 27-47.5 29.5-53l7-9q-2 53-43 139-79 165-205 264t-306 142q-14 3-42 7.5t-50 9.5-39 14q3 19 24.5 46t21.5 34q0 11-26 30zM1061 1615q39-26 131.5-47.5t146.5-21.5q9 0 22.5 15.5t28 42.5 26 50 24 51 14.5 33q-121 45-244 45-61 0-125-11zM822 968l48-12 109 177-73 48zM1323 1485q3 15 3 16 0 7-17.5 14.5t-46 13-54 9.5-53.5 7.5-32 4.5l-7-43q21-2 60.5-8.5t72-10 60.5-3.5h14zM866 857l-96 20-6-17q10-1 32.5-7t34.5-6q19 0 35 10zM1061 1491h31l10 83-41 12v-95zM1950 1v-1 1zM1950 1l-1 5-2 2 1-3zM1950 1l1-1z"}}]};
1,857
1,857
0.67636
b7313c29613ef3597e7bda9b4537bc5de10a518a
559
js
JavaScript
arcgisapi/Clatsop County Parcel Viewer/widgets/TimeSlider/setting/nls/Setting_pl.js
brian32768/map46
df51fa3d8c92ea26ff442da0046076cd09096d28
[ "MIT" ]
null
null
null
arcgisapi/Clatsop County Parcel Viewer/widgets/TimeSlider/setting/nls/Setting_pl.js
brian32768/map46
df51fa3d8c92ea26ff442da0046076cd09096d28
[ "MIT" ]
1
2020-04-30T00:06:00.000Z
2020-04-30T00:06:00.000Z
arcgisapi/Clatsop County Parcel Viewer/widgets/TimeSlider/setting/nls/Setting_pl.js
brian32768/map46
df51fa3d8c92ea26ff442da0046076cd09096d28
[ "MIT" ]
null
null
null
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://js.arcgis.com/3.15/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details. //>>built define({"widgets/TimeSlider/setting/nls/strings":{showLayerLabels:"Wy\u015bwietl nazwy warstw czasowych na wid\u017cecie.",autoPlay:"Rozpocznij odtwarzanie po otwarciu wid\u017cetu.",dateAndTimeFormat:"Format daty i czasu",mapDefault:"Mapa domy\u015blna",custom:"Niestandardowy",formatInstruction:"Formatuj instrukcj\u0119",_localized:{}}});
139.75
341
0.794275
b7316bbf414faba77121f610f8ef51ad076f80f4
671
js
JavaScript
node_modules/mdi-material-ui/SpeakerMultiple.js
wh00sh/Tanda-DAPP
c8b21ca87dfa5e88ea6e975311e15e9009c48f75
[ "Apache-2.0" ]
null
null
null
node_modules/mdi-material-ui/SpeakerMultiple.js
wh00sh/Tanda-DAPP
c8b21ca87dfa5e88ea6e975311e15e9009c48f75
[ "Apache-2.0" ]
null
null
null
node_modules/mdi-material-ui/SpeakerMultiple.js
wh00sh/Tanda-DAPP
c8b21ca87dfa5e88ea6e975311e15e9009c48f75
[ "Apache-2.0" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _createIcon = _interopRequireDefault(require("./util/createIcon")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _default = (0, _createIcon["default"])('M14,10A3,3 0 0,0 11,13A3,3 0 0,0 14,16A3,3 0 0,0 17,13A3,3 0 0,0 14,10M14,18A5,5 0 0,1 9,13A5,5 0 0,1 14,8A5,5 0 0,1 19,13A5,5 0 0,1 14,18M14,2A2,2 0 0,1 16,4A2,2 0 0,1 14,6A2,2 0 0,1 12,4A2,2 0 0,1 14,2M19,0H9A2,2 0 0,0 7,2V18A2,2 0 0,0 9,20H19A2,2 0 0,0 21,18V2A2,2 0 0,0 19,0M5,22H17V24H5A2,2 0 0,1 3,22V4H5'); exports["default"] = _default;
47.928571
357
0.676602
b7325cf7e6f0abd5a083c73186d7f2bf620f4057
45,300
js
JavaScript
contentcuration/contentcuration/static/js/edit_channel/models.js
jayoshih/content-curation
0306dd8eb20e591eeb196a46969b0d3b0d82918e
[ "MIT" ]
null
null
null
contentcuration/contentcuration/static/js/edit_channel/models.js
jayoshih/content-curation
0306dd8eb20e591eeb196a46969b0d3b0d82918e
[ "MIT" ]
4
2016-05-06T17:19:30.000Z
2019-03-15T01:51:24.000Z
contentcuration/contentcuration/static/js/edit_channel/models.js
jayoshih/content-curation
0306dd8eb20e591eeb196a46969b0d3b0d82918e
[ "MIT" ]
4
2016-10-18T22:49:08.000Z
2019-09-17T11:20:51.000Z
var Backbone = require("backbone"); var _ = require("underscore"); var mail_helper = require("edit_channel/utils/mail"); const Constants = require("./constants/index"); const DEFAULT_ADMIN_PAGE_SIZE = 25 /**** BASE MODELS ****/ var BaseModel = Backbone.Model.extend({ root_list: null, model_name: "Model", urlRoot: function () { return window.Urls[this.root_list](); }, toJSON: function () { var json = Backbone.Model.prototype.toJSON.apply(this, arguments); json.cid = this.cid; return json; }, getName: function () { return this.model_name; } }); var BaseCollection = Backbone.Collection.extend({ list_name: null, model_name: "Collection", url: function () { return window.Urls[this.list_name](); }, save: function (callback) { Backbone.sync("update", this, { url: this.model.prototype.urlRoot() }); }, set_comparator: function (comparator) { this.comparator = comparator; }, get_all_fetch: function (ids, force_fetch) { force_fetch = (force_fetch) ? true : false; var self = this; var promise = new Promise(function (resolve, reject) { var promises = []; ids.forEach(function (id) { promises.push(new Promise(function (modelResolve, modelReject) { var model = self.get({ 'id': id }); if (force_fetch || !model) { model = self.add({ 'id': id }); model.fetch({ success: function (returned) { modelResolve(returned); }, error: function (obj, error) { modelReject(error); } }); } else { modelResolve(model); } })); }); Promise.all(promises).then(function (fetchedModels) { var to_fetch = self.clone(); to_fetch.reset(); fetchedModels.forEach(function (entry) { to_fetch.add(entry); }); resolve(to_fetch); }); }); return promise; }, destroy: function () { var self = this; return new Promise(function (resolve, reject) { var promise_list = []; self.forEach(function (model) { promise_list.push(new Promise(function (subresolve, subreject) { model.destroy({ success: subresolve, error: subreject }) })) }); Promise.all(promise_list).then(function () { resolve(true); }); }); }, getName: function () { return this.model_name; } }); var PageableCollection = require("backbone.paginator"); var BasePageableCollection = PageableCollection.extend({ save: function (callback) { Backbone.sync("update", this, { url: this.model.prototype.urlRoot() }); }, set_comparator: function (comparator) { this.comparator = comparator; }, get_all_fetch: function (ids, force_fetch) { force_fetch = (force_fetch) ? true : false; var self = this; var promise = new Promise(function (resolve, reject) { var promises = []; ids.forEach(function (id) { promises.push(new Promise(function (modelResolve, modelReject) { var model = self.get({ 'id': id }); if (force_fetch || !model) { model = self.add({ 'id': id }); model.fetch({ success: function (returned) { modelResolve(returned); }, error: function (obj, error) { modelReject(error); } }); } else { modelResolve(model); } })); }); Promise.all(promises).then(function (fetchedModels) { var to_fetch = self.clone(); to_fetch.reset(); fetchedModels.forEach(function (entry) { to_fetch.add(entry); }); resolve(to_fetch); }); }); return promise; }, destroy: function () { var self = this; return new Promise(function (resolve, reject) { var promise_list = []; self.forEach(function (model) { promise_list.push(new Promise(function (subresolve, subreject) { model.destroy({ success: subresolve, error: subreject }) })) }); Promise.all(promise_list).then(function () { resolve(true); }); }); }, getName: function () { return this.model_name; }, parseRecords: function (resp) { return resp.results; }, parseState: function (resp, queryParams, state) { state.totalRecords = resp.count; state.totalPages = resp.total_pages; return state; }, state: { pageSize: DEFAULT_ADMIN_PAGE_SIZE, firstPage: 1, currentPage: 1, filterQuery: {}, order: -1, }, baseQueryParams: { currentPage: "page", pageSize: "page_size", totalRecords: "count", order: null, ordering: function () { var sortKey = this.state.sortKey, order = this.state.order; if (sortKey && order !== 0) { return (order === 1 ? '-' : '') + sortKey; } return null; } }, fetch: function (options) { // Construct the queryParams this.queryParams = Object.assign({}, this.baseQueryParams) this.queryParams = Object.assign(this.queryParams, this.state.filterQuery) //Call PageableCollection's fetch return PageableCollection.prototype.fetch.call(this, options); }, }); Object.assign(PageableCollection.prototype, BaseCollection) /**** USER-CENTERED MODELS ****/ var UserModel = BaseModel.extend({ root_list: "user-list", model_name: "UserModel", defaults: { first_name: "Guest" }, send_invitation_email: function (email, channel, share_mode) { return mail_helper.send_mail(channel, email, share_mode); }, get_clipboard: function () { return new ContentNodeModel(this.get("clipboard_tree")); }, get_full_name: function () { return this.get('first_name') + " " + this.get('last_name'); }, get_channels: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_user_edit_channels(), error: reject, success: function (data) { var collection = new ChannelCollection(data); collection.each(function (item) { item.set("is_bookmarked", _.contains(self.get("bookmarks"), item.id)); }); resolve(collection); } }); }); }, get_view_only_channels: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_user_view_channels(), error: reject, success: function (data) { var collection = new ChannelCollection(data); collection.each(function (item) { item.set("is_bookmarked", _.contains(self.get("bookmarks"), item.id)); }); resolve(collection); } }); }); }, get_bookmarked_channels: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_user_bookmarked_channels(), error: reject, success: function (data) { var collection = new ChannelCollection(data); collection.each(function (item) { item.set("is_bookmarked", true); }); resolve(collection); } }); }); }, get_public_channels: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_user_public_channels(), error: reject, success: function (data) { var collection = new ChannelCollection(data); collection.each(function (item) { item.set("is_bookmarked", _.contains(self.get("bookmarks"), item.id)); }); resolve(collection); } }); }); }, get_pending_invites: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_user_pending_channels(), error: reject, success: function (data) { resolve(new InvitationCollection(data)); } }); }); } }); var UserCollection = BasePageableCollection.extend({ model: UserModel, list_name: "user-list", model_name: "UserCollection", send_custom_email: function (subject, message) { return mail_helper.send_custom_email(this.pluck('email'), subject, message); }, url: window.Urls.get_users(), }); var InvitationModel = BaseModel.extend({ root_list: "invitation-list", model_name: "InvitationModel", defaults: { first_name: "Guest" }, resend_invitation_email: function (channel) { return mail_helper.send_mail(channel, this.get("email"), this.get("share_mode")); }, get_full_name: function () { return this.get('first_name') + " " + this.get('last_name'); }, accept_invitation: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", url: window.Urls.accept_channel_invite(), data: JSON.stringify({ "invitation_id": self.id }), error: reject, success: function (data) { resolve(new ChannelModel(JSON.parse(data))); } }); }); }, decline_invitation: function () { var self = this; return new Promise(function (resolve, reject) { self.destroy({ success: resolve, error: reject }); }); } }); var InvitationCollection = BaseCollection.extend({ model: InvitationModel, list_name: "invitation-list", model_name: "InvitationCollection" }); /**** CHANNEL AND CONTENT MODELS ****/ function fetch_nodes(ids, url) { return new Promise(function (resolve, reject) { // Getting "Request Line is too large" error on some channels, so chunk the requests var promises = _.chain(ids).chunk(50).map(function (id_list) { return new Promise(function (promise_resolve, promise_reject) { if (id_list.length === 0) { promise_resolve([]); // No need to make a call to the server } $.ajax({ method: "GET", url: url(id_list.join(",")), error: promise_reject, success: promise_resolve }); }); }).value(); Promise.all(promises).then(function (values) { resolve(new ContentNodeCollection(_.flatten(values))); }); }); } function fetch_nodes_by_ids(ids) { return fetch_nodes(ids, window.Urls.get_nodes_by_ids); } var ContentNodeModel = BaseModel.extend({ root_list: "contentnode-list", model_name: "ContentNodeModel", defaults: { title: "Untitled", children: [], tags: [], assessment_items: [], metadata: { "resource_size": 0, "resource_count": 0 }, created: new Date(), ancestors: [], extra_fields: {} }, generate_thumbnail: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", url: window.Urls.generate_thumbnail(self.id), success: function (result) { result = JSON.parse(result); result.file = new FileModel(JSON.parse(result.file)); resolve(result); }, error: reject }); }); }, fetch_details: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_topic_details(self.id), success: function (result) { self.set('metadata', JSON.parse(result)) resolve(self); }, error: reject }); }); }, has_related_content: function () { return this.get('prerequisite').length || this.get('is_prerequisite_of').length; }, get_original_channel_id: function () { var original_channel = this.get('original_channel'); return original_channel ? original_channel['id'] : 'unknown_channel_id'; }, get_original_channel_title: function () { var original_channel = this.get('original_channel'); return original_channel ? original_channel['name'] : ''; }, get_original_channel_thumbnail: function () { var original_channel = this.get('original_channel'); return original_channel ? original_channel['thumbnail_url'] : ''; }, initialize: function () { if (this.get("extra_fields") && typeof this.get("extra_fields") !== "object") { this.set("extra_fields", JSON.parse(this.get("extra_fields"))) } if (this.get("thumbnail_encoding") && typeof this.get("thumbnail_encoding") !== "object") { this.set("thumbnail_encoding", JSON.parse(this.get("thumbnail_encoding"))) } }, parse: function (response) { if (response !== undefined && response.extra_fields) { response.extra_fields = JSON.parse(response.extra_fields); } if (response !== undefined && response.thumbnail_encoding) { response.thumbnail_encoding = JSON.parse(response.thumbnail_encoding); } return response; }, toJSON: function () { var attributes = _.clone(this.attributes); if (typeof attributes.extra_fields !== "string") { attributes.extra_fields = JSON.stringify(attributes.extra_fields); } if (attributes.thumbnail_encoding !== null && typeof attributes.thumbnail_encoding !== "string") { attributes.thumbnail_encoding = JSON.stringify(attributes.thumbnail_encoding); } return attributes; }, setExtraFields: function () { const State = require("./state"); if (typeof this.get('extra_fields') === 'string') { this.set('extra_fields', JSON.parse(this.get('extra_fields'))); } if (this.get('kind') === 'exercise') { var data = (this.get('extra_fields')) ? this.get('extra_fields') : {}; data['mastery_model'] = (data['mastery_model']) ? data['mastery_model'] : State.preferences.mastery_model; data['m'] = (data['m'])? data['m'] : State.preferences.m_value; data['n'] = (data['n'])? data['n'] : State.preferences.n_value; data['randomize'] = (data['randomize'] !== undefined) ? data['randomize'] : State.preferences.auto_randomize_questions; this.set('extra_fields', data); } }, calculate_size: function () { var self = this; var promise = new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_total_size(self.id), error: reject, success: function (data) { resolve(JSON.parse(data).size); } }); }); return promise; }, make_copy: function (target_parent) { const State = require("./state"); var self = this; return new Promise(function (resolve, reject) { var data = { "node_id": self.id, "target_parent": target_parent.get("id"), "channel_id": State.current_channel.id }; $.ajax({ method: "POST", url: window.Urls.duplicate_node_inline(), data: JSON.stringify(data), success: function (data) { resolve(new ContentNodeCollection(JSON.parse(data))); }, error: reject }); }); } }); var ContentNodeCollection = BaseCollection.extend({ model: ContentNodeModel, list_name: "contentnode-list", highest_sort_order: 1, model_name: "ContentNodeCollection", save: function () { var self = this; return new Promise(function (saveResolve, saveReject) { var numParser = require("edit_channel/utils/number_parser"); var fileCollection = new FileCollection(); var assessmentCollection = new AssessmentItemCollection(); self.forEach(function (node) { node.get("files").forEach(function (file) { var to_add = new FileModel(file); var preset_data = to_add.get("preset"); preset_data.id = file.preset.name || file.preset.id; fileCollection.add(to_add); }); node.get('assessment_items').forEach(function (item) { item = new AssessmentItemModel(item); item.set('contentnode', node.id); if (item.get('type') === 'input_question') { item.get('answers').each(function (a) { var answer = a.get('answer'); if (answer) { var value = numParser.parse(answer); a.set('answer', value !== null && value.toString()); } }); } assessmentCollection.add(item); }) }); Promise.all([fileCollection.save(), assessmentCollection.save()]).then(function () { Backbone.sync("update", self, { url: self.model.prototype.urlRoot(), success: function (data) { saveResolve(new ContentNodeCollection(data)); }, error: function (obj, error) { saveReject(error); } }); }).catch(saveReject); }); }, has_prerequisites: function () { return this.some(function (model) { return model.get('prerequisite').length; }) }, has_postrequisites: function () { return this.some(function (model) { return model.get('is_prerequisite_of').length; }) }, has_related_content: function () { return this.has_prerequisites() || this.has_postrequisites(); }, get_prerequisites: function (ids, get_postrequisites) { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_prerequisites((get_postrequisites || false).toString(), ids.join(",")), success: function (data) { var nodes = JSON.parse(data); resolve({ "prerequisite_mapping": nodes.prerequisite_mapping, "postrequisite_mapping": nodes.postrequisite_mapping, "prerequisite_tree_nodes": new ContentNodeCollection(JSON.parse(nodes.prerequisite_tree_nodes)), }); }, error: reject }); }); }, get_node_path: function (topic_id, tree_id, node_id) { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_node_path(topic_id, tree_id, node_id), success: function (result) { var data = JSON.parse(result); var returnCollection = new ContentNodeCollection(JSON.parse(data.path)); self.add(returnCollection.toJSON()); var node = null; if (data.node) { node = new ContentNodeModel(JSON.parse(data.node)); self.add(node); } resolve({ "collection": returnCollection, "node": node, "parent_node_id": data.parent_node_id }); }, error: reject }); }); }, calculate_size: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_total_size(self.pluck('id').join(",")), success: function (data) { resolve(JSON.parse(data).size); }, error: reject }); }); }, create_new_node: function (data) { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", url: window.Urls.create_new_node(), data: JSON.stringify(data), success: function (data) { var new_node = new ContentNodeModel(JSON.parse(data)); self.add(new_node); resolve(new_node); }, error: reject }); }); }, has_all_data: function () { return this.every(function (node) { var files_objects = _.every(node.get('files'), function (file) { return typeof file == 'object'; }); var ai_objects = _.every(node.get('assessment_items'), function (ai) { return typeof ai == 'object'; }); return files_objects && ai_objects; }); }, get_all_fetch: function (ids, force_fetch) { return this.get_fetch_nodes(ids, window.Urls.get_nodes_by_ids, force_fetch); }, get_all_fetch_simplified: function (ids, force_fetch) { return this.get_fetch_nodes(ids, window.Urls.get_nodes_by_ids_simplified, force_fetch); }, fetch_nodes_by_ids_complete: function (ids, force_fetch) { return this.get_fetch_nodes(ids, window.Urls.get_nodes_by_ids_complete, force_fetch); }, get_fetch_nodes: function (ids, url, force_fetch) { force_fetch = (force_fetch) ? true : false; var self = this; return new Promise(function (resolve, reject) { var idlists = _.partition(ids, function (id) { return force_fetch || !self.get({ 'id': id }); }); var returnCollection = new ContentNodeCollection(self.filter(function (n) { return idlists[1].indexOf(n.id) >= 0; })) fetch_nodes(idlists[0], url).then(function (fetched) { returnCollection.add(fetched.toJSON()); self.add(fetched.toJSON()); self.sort(); resolve(returnCollection); }); }); }, comparator: function (node) { return node.get("sort_order"); }, sort_by_order: function () { this.sort(); this.highest_sort_order = (this.length > 0) ? this.at(this.length - 1).get("sort_order") : 1; }, duplicate: function (target_parent) { const State = require("./state"); var self = this; return new Promise(function (resolve, reject) { var sort_order = (target_parent) ? target_parent.get("metadata").max_sort_order + 1 : 1; var parent_id = target_parent.get("id"); var data = { "node_ids": self.models.map(node => node.id), "sort_order": sort_order, "target_parent": parent_id, "channel_id": State.current_channel.id }; $.ajax({ method: "POST", url: window.Urls.duplicate_nodes(), data: JSON.stringify(data), success: function (data) { resolve(new ContentNodeCollection(JSON.parse(data))); }, error: reject }); }); }, move: function (target_parent, max_order, min_order) { const State = require("./state"); var self = this; return new Promise(function (resolve, reject) { var data = { "nodes": self.toJSON(), "target_parent": target_parent.get("id"), "channel_id": State.current_channel.id, "max_order": max_order, "min_order": min_order }; $.ajax({ method: "POST", url: window.Urls.move_nodes(), data: JSON.stringify(data), error: reject, success: function (moved) { resolve(new ContentNodeCollection(JSON.parse(moved))); } }); }); }, delete: function () { const State = require("./state"); var self = this; return new Promise(function (resolve, reject) { var data = { "nodes": self.pluck('id'), "channel_id": State.current_channel.id }; $.ajax({ method: "POST", url: window.Urls.delete_nodes(), data: JSON.stringify(data), success: resolve, error: reject }); }); }, sync_nodes: function (models) { const State = require("./state"); var self = this; return new Promise(function (resolve, reject) { var data = { "nodes": _.pluck(models, 'id'), "channel_id": State.current_channel.id }; $.ajax({ method: "POST", url: window.Urls.sync_nodes(), data: JSON.stringify(data), error: reject, success: function (synced) { resolve(new ContentNodeCollection(JSON.parse(synced))); } }); }); } }); var ChannelModel = BaseModel.extend({ //idAttribute: "channel_id", root_list: "channel-list", defaults: { name: "", description: "", thumbnail_url: "/static/img/kolibri_placeholder.png", count: 0, size: 0, published: false, view_only: false, viewers: [], modified: new Date(), }, model_name: "ChannelModel", get_root: function (tree_name) { var root_node = new ContentNodeModel(this.get(tree_name)); root_node.set({ 'title': this.get('name') }); return root_node; }, publish: function (callback) { var self = this; return new Promise(function (resolve, reject) { var data = { "channel_id": self.get("id") }; $.ajax({ method: "POST", url: window.Urls.publish_channel(), data: JSON.stringify(data), success: function () { resolve(true); }, error: function (error) { reject(error); } }); }); }, get_accessible_channel_roots: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.accessible_channels(self.id), success: function (data) { resolve(new ContentNodeCollection(data)); }, error: function (e) { reject(e); } }); }); }, get_node_diff: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_node_diff(self.id), success: function (data) { var nodes = JSON.parse(data); resolve({ "original": new ContentNodeCollection(JSON.parse(nodes.original)), "changed": new ContentNodeCollection(JSON.parse(nodes.changed)) }); }, error: reject }); }); }, sync_channel: function (options) { var self = this; return new Promise(function (resolve, reject) { var data = { 'channel_id': self.id, 'attributes': options.attributes, 'tags': options.tags, 'files': options.files, 'assessment_items': options.assessment_items, 'sort': options.sort } $.ajax({ method: "POST", url: window.Urls.sync_channel(), data: JSON.stringify(data), success: function (data) { resolve(new ContentNodeCollection(JSON.parse(data))); }, error: reject }); }); }, activate_channel: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", data: JSON.stringify({ 'channel_id': self.id }), url: window.Urls.activate_channel(), success: resolve, error: function (error) { reject(error.responseText); } }); }); }, get_staged_diff: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", data: JSON.stringify({ 'channel_id': self.id }), url: window.Urls.get_staged_diff(), success: function (data) { resolve(JSON.parse(data)) }, error: function (error) { reject(error.responseText); } }); }); }, add_editor: function (user_id) { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", data: JSON.stringify({ "channel_id": self.id, "user_id": user_id }), url: window.Urls.make_editor(), success: resolve, error: function (error) { reject(error.responseText); } }); }); }, remove_editor: function (user_id) { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", data: JSON.stringify({ "channel_id": self.id, "user_id": user_id }), url: window.Urls.remove_editor(), success: resolve, error: function (error) { reject(error.responseText); } }); }); }, add_bookmark: function (user_id) { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", data: JSON.stringify({ "channel_id": self.id, "user_id": user_id }), url: window.Urls.add_bookmark(), success: resolve, error: function (error) { reject(error.responseText); } }); }); }, remove_bookmark: function (user_id) { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", data: JSON.stringify({ "channel_id": self.id, "user_id": user_id }), url: window.Urls.remove_bookmark(), success: resolve, error: function (error) { reject(error.responseText); } }); }); }, get_channel_counts: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_channel_kind_count(self.id), error: reject, success: function (data) { resolve(JSON.parse(data)); } }); }); }, set_priority: function (priority) { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "POST", data: JSON.stringify({ "channel_id": self.id, "priority": priority }), url: window.Urls.set_channel_priority(), success: resolve, error: function (error) { reject(error.responseText); } }); }); }, fetch_editors: function () { var self = this; return new Promise(function (resolve, reject) { $.ajax({ method: "GET", url: window.Urls.get_editors(self.id), success: function (editors) { self.set("editors", editors); resolve(self); }, error: function (error) { reject(error.responseText); } }); }); } }); var ChannelCollection = BasePageableCollection.extend({ model: ChannelModel, list_name: "channel-list", model_name: "ChannelCollection", url: window.Urls.get_channels(), }); var TagModel = BaseModel.extend({ root_list: "contenttag-list", model_name: "TagModel", defaults: { tag_name: "Untagged" } }); var TagCollection = BaseCollection.extend({ model: TagModel, list_name: "contenttag-list", model_name: "TagCollection", get_all_fetch: function (ids) { var self = this; var fetched_collection = new TagCollection(); ids.forEach(function (id) { var tag = self.get(id); if (!tag) { tag = new TagModel({ "id": id }); tag.fetch({ async: false }); if (tag) { self.add(tag); } } fetched_collection.add(tag); }); return fetched_collection; } }); /**** MODELS SPECIFIC TO FILE NODES ****/ var FileModel = BaseModel.extend({ root_list: "file-list", model_name: "FileModel", get_preset: function () { return Constants.FormatPresets.find(preset => preset.id === this.get("id")); }, initialize: function () { this.set_preset(this.get("preset"), this.get("language")); }, set_preset: function (preset, language) { if (preset && language && !preset.id.endsWith("_" + language.id)) { var preset_data = preset; preset_data.name = preset_data.id; preset_data.id = preset_data.id + "_" + language.id; preset_data.readable_name = language.readable_name; this.set("preset", preset_data); } } }); var FileCollection = BaseCollection.extend({ model: FileModel, list_name: "file-list", model_name: "FileCollection", get_or_fetch: function (data) { var newCollection = new FileCollection(); newCollection.fetch({ traditional: true, data: data }); var file = newCollection.findWhere(data); return file; }, save: function () { var self = this; return new Promise(function (resolve, reject) { Backbone.sync("update", self, { url: self.model.prototype.urlRoot(), success: function (data) { resolve(new FileCollection(data)); }, error: reject }); }); } }); var FormatPresetModel = BaseModel.extend({ root_list: "formatpreset-list", attached_format: null, model_name: "FormatPresetModel" }); var FormatPresetCollection = BaseCollection.extend({ model: FormatPresetModel, list_name: "formatpreset-list", model_name: "FormatPresetCollection", comparator: function (preset) { return [preset.get('order'), preset.get('readable_name')]; } }); /**** PRESETS AUTOMATICALLY GENERATED UPON FIRST USE ****/ var FileFormatModel = Backbone.Model.extend({ root_list: "fileformat-list", model_name: "FileFormatModel", defaults: { extension: "invalid" } }); var FileFormatCollection = BaseCollection.extend({ model: FileFormatModel, list_name: "fileformat-list", model_name: "FileFormatCollection" }); var LicenseModel = BaseModel.extend({ root_list: "license-list", model_name: "LicenseModel", defaults: { license_name: "Unlicensed", exists: false } }); var LicenseCollection = BaseCollection.extend({ model: LicenseModel, list_name: "license-list", model_name: "LicenseCollection", get_default: function () { return this.findWhere({ license_name: "CC-BY" }); }, comparator: function (license) { return license.id; } }); var LanguageModel = BaseModel.extend({ root_list: "language-list", model_name: "LanguageModel" }); var LanguageCollection = BaseCollection.extend({ model: LanguageModel, list_name: "language-list", model_name: "LanguageCollection", comparator: function (language) { return language.readable_name; } }); var ContentKindModel = BaseModel.extend({ root_list: "contentkind-list", model_name: "ContentKindModel", defaults: { kind: "topic" }, get_presets: function () { Constants.FormatPresets.filter(preset => preset.kind_id === this.get("kind")) } }); var ContentKindCollection = BaseCollection.extend({ model: ContentKindModel, list_name: "contentkind-list", model_name: "ContentKindCollection", get_default: function () { return this.findWhere({ kind: "topic" }); } }); var ExerciseModel = BaseModel.extend({ root_list: "exercise-list", model_name: "ExerciseModel" }); var ExerciseCollection = BaseCollection.extend({ model: ExerciseModel, list_name: "exercise-list", model_name: "ExerciseCollection" }); var ExerciseItemCollection = Backbone.Collection.extend({ comparator: function (item) { return item.get('order'); } }); var AssessmentItemModel = BaseModel.extend({ root_list: "assessmentitem-list", model_name: "AssessmentItemModel", defaults: { type: "single_selection", question: "", answers: "[]", hints: "[]", files: [] }, initialize: function () { if (typeof this.get("answers") !== "object") { this.set("answers", new ExerciseItemCollection(JSON.parse(this.get("answers"))), { silent: true }); } if (typeof this.get("hints") !== "object") { this.set("hints", new ExerciseItemCollection(JSON.parse(this.get("hints"))), { silent: true }); } }, parse: function (response) { if (response !== undefined) { if (response.answers) { response.answers = new ExerciseItemCollection(JSON.parse(response.answers)); } if (response.hints) { response.hints = new ExerciseItemCollection(JSON.parse(response.hints)); } } return response; }, toJSON: function () { var attributes = _.clone(this.attributes); if (typeof attributes.answers !== "string") { // Add answer images to the files list attributes.files = _.chain(attributes.answers.models) .map(function (item) { return item.get('files'); }) .flatten() .filter(function (item) { return item; }) .union(attributes.files) .value(); attributes.answers = JSON.stringify(attributes.answers.toJSON()); } if (typeof attributes.hints !== "string") { // Add hint images to the files list attributes.files = _.chain(attributes.hints.models) .map(function (item) { return item.get('files'); }) .flatten() .filter(function (item) { return item; }) .union(attributes.files) .value(); attributes.hints = JSON.stringify(attributes.hints.toJSON()); } return attributes; } }); var AssessmentItemCollection = BaseCollection.extend({ model: AssessmentItemModel, model_name: "AssessmentItemCollection", comparator: function (assessment_item) { return assessment_item.get("order"); }, get_all_fetch: function (ids, force_fetch) { force_fetch = (force_fetch) ? true : false; var self = this; var promise = new Promise(function (resolve, reject) { var promises = []; ids.forEach(function (id) { promises.push(new Promise(function (modelResolve, modelReject) { var model = self.get(id); if (force_fetch || !model) { model = self.add(id); model.fetch({ success: function (returned) { modelResolve(returned); }, error: function (obj, error) { modelReject(error); } }); } else { modelResolve(model); } })); }); Promise.all(promises).then(function (fetchedModels) { var to_fetch = self.clone(); to_fetch.reset(); fetchedModels.forEach(function (entry) { to_fetch.add(entry); }); resolve(to_fetch); }); }); return promise; }, save: function () { var self = this; return new Promise(function (resolve, reject) { Backbone.sync("update", self, { url: self.model.prototype.urlRoot(), success: function (data) { resolve(new AssessmentItemCollection(data)); }, error: function (error) { reject(error); } }); }); } }); module.exports = { fetch_nodes_by_ids: fetch_nodes_by_ids, ContentNodeModel: ContentNodeModel, ContentNodeCollection: ContentNodeCollection, ChannelModel: ChannelModel, ChannelCollection: ChannelCollection, TagModel: TagModel, TagCollection: TagCollection, FileFormatCollection: FileFormatCollection, LicenseCollection: LicenseCollection, FileCollection: FileCollection, FileModel: FileModel, FormatPresetModel: FormatPresetModel, FormatPresetCollection: FormatPresetCollection, LanguageModel: LanguageModel, LanguageCollection: LanguageCollection, ContentKindModel: ContentKindModel, ContentKindCollection: ContentKindCollection, UserModel: UserModel, UserCollection: UserCollection, InvitationModel: InvitationModel, InvitationCollection: InvitationCollection, ExerciseModel: ExerciseModel, ExerciseCollection: ExerciseCollection, AssessmentItemModel: AssessmentItemModel, AssessmentItemCollection: AssessmentItemCollection, }
34.846154
131
0.512892
b733a4ef15fae158bcef5c624292940b7d3baa46
989
js
JavaScript
config.js
kenzostore/WhatsGram
e6e1591b8e4e56f75c70bd9a22ccdeb19f134421
[ "Apache-2.0" ]
101
2021-05-17T07:37:56.000Z
2022-03-27T07:03:29.000Z
config.js
kenzostore/WhatsGram
e6e1591b8e4e56f75c70bd9a22ccdeb19f134421
[ "Apache-2.0" ]
12
2021-05-19T11:40:44.000Z
2022-03-27T07:00:22.000Z
config.js
kenzostore/WhatsGram
e6e1591b8e4e56f75c70bd9a22ccdeb19f134421
[ "Apache-2.0" ]
87
2021-05-17T15:35:13.000Z
2022-03-26T12:43:52.000Z
require('dotenv').config() const fs = require('fs'); // const SESSION_DATA = process.env.SESSION_DATA || fs.existsSync('session.json') ? fs.readFileSync(__dirname + '/session.json', { encoding: 'utf8' }) : ''; const TG_BOT_TOKEN = process.env.TG_BOT_TOKEN || ''; const TG_OWNER_ID = process.env.TG_OWNER_ID || ''; const REMOVE_BG_API = process.env.REMOVE_BG_API || undefined; const HEROKU_API_KEY = process.env.HEROKU_API_KEY || ''; const HEROKU_APP_NAME = process.env.HEROKU_APP_NAME || ''; const DB_URL = process.env.DB_URL || ''; const pmguard_enabled = process.env.PMGUARD_ENABLED || 'false'; const PMGUARD_ACTION = process.env.PMGUARD_ACTION && (process.env.PMGUARD_ACTION == 'mute' || process.env.PMGUARD_ACTION == 'block') ? process.env.PMGUARD_ACTION : 'mute'; const OCR_SPACE_API_KEY = process.env.OCR_SPACE_API_KEY || ''; module.exports = { TG_BOT_TOKEN , TG_OWNER_ID , REMOVE_BG_API, HEROKU_API_KEY, HEROKU_APP_NAME, DB_URL, pmguard_enabled, PMGUARD_ACTION, OCR_SPACE_API_KEY}
65.933333
171
0.749242
b733e808b4b4d616e9070e2e8d228c6d0a9bedf7
3,157
js
JavaScript
src/templates/steps-pagination.js
mattdvhope/source
6410741fb34ef88917d0d423b4e5c778b49e6dce
[ "MIT" ]
null
null
null
src/templates/steps-pagination.js
mattdvhope/source
6410741fb34ef88917d0d423b4e5c778b49e6dce
[ "MIT" ]
null
null
null
src/templates/steps-pagination.js
mattdvhope/source
6410741fb34ef88917d0d423b4e5c778b49e6dce
[ "MIT" ]
null
null
null
import React, { Component } from "react"; import { graphql } from "gatsby"; import Img from "gatsby-image"; import { Link } from "gatsby"; import moment from "moment"; import Layout from "../components/layout"; import SEO from "../components/seo"; import Pagination from "../components/Pagination"; export default class Steps extends Component { render() { const { data } = this.props; const { currentPage } = this.props.data.allContentfulSteps.pageInfo; const { totalPageCount } = this.props.pathContext; return ( <Layout> <SEO title="Step Out" keywords={[`Tertullian`, `Assembler of knowledge`, `Developer`, `Pages`]} /> <div className="site-container steps-page" id="Steps"> <div className="container"> <div className="section-head"> <h3 className="line-heading h3">Steps....</h3> </div> <ul className={`steps-list ${ data.allContentfulSteps.edges.length < 5 ? "few-steps" : "" }`} > {data.allContentfulSteps.edges.map((item, index) => { return ( <li key={index} className="item"> <div className="inner"> <Link className="link" to={`/${item.node.slug}`} /> {item.node.featureImage ? ( <Img fluid={item.node.featureImage.fluid} objectFit="cover" objectPosition="50% 50%" /> ) : ( <div className="no-image"></div> )} <div className="details"> <h3 className="title">{item.node.title}</h3> <span className="date"> <i className="fas fa-calendar-alt"></i>{" "} {moment(item.node.createdAt).format("LL")} </span> </div> </div> </li> ); })} </ul> <div className="text-center mt-4"> <Pagination totalPageCount={totalPageCount} url={"/steps"} currentPage={currentPage} /> </div> </div> </div> </Layout> ); } } export const pageQuery = graphql` query StepsQuery($skip: Int, $limit: Int = 5, $tag: String) { allContentfulSteps( skip: $skip limit: $limit sort: { fields: createdAt, order: DESC } filter: { tags: { eq: $tag } } ) { edges { node { title slug featureImage { fluid(maxWidth: 1500) { base64 aspectRatio src srcSet srcWebp srcSetWebp sizes } } createdAt } } pageInfo { hasNextPage hasPreviousPage perPage currentPage pageCount itemCount } } } `;
29.783019
101
0.450744
b7345f6909a708940bf203e4ff8370ed0510052b
6,612
js
JavaScript
src/main/preload/mattermost.js
hoanglm97/desktop
5ed84270c8e76306dd61ee2fa1c61d5e587ecb4a
[ "Apache-2.0" ]
null
null
null
src/main/preload/mattermost.js
hoanglm97/desktop
5ed84270c8e76306dd61ee2fa1c61d5e587ecb4a
[ "Apache-2.0" ]
null
null
null
src/main/preload/mattermost.js
hoanglm97/desktop
5ed84270c8e76306dd61ee2fa1c61d5e587ecb4a
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // Copyright (c) 2015-2016 Yuya Ochiai 'use strict'; /* eslint-disable no-magic-numbers */ import {ipcRenderer, webFrame} from 'electron'; import log from 'electron-log'; import {NOTIFY_MENTION, IS_UNREAD, UNREAD_RESULT, SESSION_EXPIRED, SET_SERVER_NAME, REACT_APP_INITIALIZED, USER_ACTIVITY_UPDATE} from 'common/communication'; const UNREAD_COUNT_INTERVAL = 1000; const CLEAR_CACHE_INTERVAL = 6 * 60 * 60 * 1000; // 6 hours Reflect.deleteProperty(global.Buffer); // http://electron.atom.io/docs/tutorial/security/#buffer-global let appVersion; let appName; let sessionExpired; let serverName; log.info('Initializing preload'); ipcRenderer.invoke('get-app-version').then(({name, version}) => { appVersion = version; appName = name; }); function isReactAppInitialized() { const initializedRoot = document.querySelector('#root.channel-view') || // React 16 webapp document.querySelector('#root .signup-team__container') || // React 16 login document.querySelector('div[data-reactroot]'); // Older React apps if (initializedRoot === null) { return false; } return initializedRoot.children.length !== 0; } function watchReactAppUntilInitialized(callback) { let count = 0; const interval = 500; const timeout = 30000; const timer = setInterval(() => { count += interval; if (isReactAppInitialized() || count >= timeout) { // assumed as webapp has been initialized. clearTimeout(timer); callback(); } }, interval); } window.addEventListener('load', () => { if (document.getElementById('root') === null) { console.log('The guest is not assumed as mattermost-webapp'); return; } watchReactAppUntilInitialized(() => { ipcRenderer.send(REACT_APP_INITIALIZED, serverName); }); }); const parentTag = (target) => { if (target.parentNode) { return target.parentNode.tagName.toUpperCase(); } return null; }; document.addEventListener('mouseover', (event) => { if (event.target && (event.target.tagName === 'A')) { ipcRenderer.send('update-target-url', event.target.href); } else if (event.target && (parentTag(event.target) === 'A')) { ipcRenderer.send('update-target-url', event.target.parentNode.href); } }); document.addEventListener('mouseout', (event) => { if (event.target && event.target.tagName === 'A') { ipcRenderer.send('delete-target-url', event.target.href); } }); // listen for messages from the webapp window.addEventListener('message', ({origin, data = {}} = {}) => { const {type, message = {}} = data; if (origin !== window.location.origin) { return; } switch (type) { case 'webapp-ready': { // register with the webapp to enable custom integration functionality console.log(`registering ${appName} v${appVersion} with the server`); window.postMessage( { type: 'register-desktop', message: { version: appVersion, name: appName, }, }, window.location.origin || '*', ); break; } case 'register-desktop': // it will be captured by itself too break; case 'dispatch-notification': { const {title, body, channel, teamId, silent, data: messageData} = message; ipcRenderer.send(NOTIFY_MENTION, title, body, channel, teamId, silent, messageData); break; } default: if (typeof type === 'undefined') { console.log('ignoring message of undefined type:'); console.log(data); } else { console.log(`ignored message of type: ${type}`); } } }); const handleNotificationClick = ({channel, teamId}) => { window.postMessage( { type: 'notification-clicked', message: { channel, teamId, }, }, window.location.origin, ); }; ipcRenderer.on('notification-clicked', (event, data) => { handleNotificationClick(data); }); const findUnread = (favicon) => { const classes = ['team-container unreads', 'SidebarChannel unread', 'sidebar-item unread-title']; const isUnread = classes.some((classPair) => { const result = document.getElementsByClassName(classPair); return result && result.length > 0; }); ipcRenderer.send(UNREAD_RESULT, favicon, serverName, isUnread); }; ipcRenderer.on(IS_UNREAD, (event, favicon, server) => { if (typeof serverName === 'undefined') { serverName = server; } if (isReactAppInitialized()) { findUnread(favicon); } else { watchReactAppUntilInitialized(() => { findUnread(favicon); }); } }); ipcRenderer.on(SET_SERVER_NAME, (_, name) => { serverName = name; }); function getUnreadCount() { // LHS not found => Log out => Count should be 0, but session may be expired. if (typeof serverName !== 'undefined') { let isExpired; if (document.getElementById('sidebar-left') === null) { const extraParam = (new URLSearchParams(window.location.search)).get('extra'); isExpired = extraParam === 'expired'; } else { isExpired = false; } if (isExpired !== sessionExpired) { sessionExpired = isExpired; ipcRenderer.send(SESSION_EXPIRED, sessionExpired, serverName); } } } setInterval(getUnreadCount, UNREAD_COUNT_INTERVAL); // push user activity updates to the webapp ipcRenderer.on(USER_ACTIVITY_UPDATE, (event, {userIsActive, isSystemEvent}) => { if (window.location.origin !== 'null') { window.postMessage({type: USER_ACTIVITY_UPDATE, message: {userIsActive, manual: isSystemEvent}}, window.location.origin); } }); // exit fullscreen embedded elements like youtube - https://mattermost.atlassian.net/browse/MM-19226 ipcRenderer.on('exit-fullscreen', () => { if (document.fullscreenElement && document.fullscreenElement.nodeName.toLowerCase() === 'iframe') { document.exitFullscreen(); } }); // mattermost-webapp is SPA. So cache is not cleared due to no navigation. // We needed to manually clear cache to free memory in long-term-use. // http://seenaburns.com/debugging-electron-memory-usage/ setInterval(() => { webFrame.clearCache(); }, CLEAR_CACHE_INTERVAL); /* eslint-enable no-magic-numbers */
31.636364
157
0.628252
b734ee84233cf43edde5b658caabda2b591802c3
1,120
js
JavaScript
src/app/stores/recipe.js
webcoding/reactui-starter
f0b9edabe1e5db74f7fe4d2f1beb6d87cd92180b
[ "Unlicense" ]
79
2015-07-29T00:11:11.000Z
2020-11-24T18:51:56.000Z
src/app/stores/recipe.js
webcoding/reactui-starter
f0b9edabe1e5db74f7fe4d2f1beb6d87cd92180b
[ "Unlicense" ]
63
2015-07-29T08:17:44.000Z
2019-09-07T22:48:17.000Z
src/app/stores/recipe.js
webcoding/reactui-starter
f0b9edabe1e5db74f7fe4d2f1beb6d87cd92180b
[ "Unlicense" ]
23
2015-08-10T23:24:45.000Z
2021-09-01T11:54:05.000Z
import _ from 'lodash'; import Reflux from 'reflux'; import recipeActions from 'actions/recipe'; import RecipeModel from 'models/recipe'; import OilModel from 'models/oil'; export default Reflux.createStore( { store: null, init() { this.store = new RecipeModel(); this.store.on( 'calculated', doTrigger.bind( this ) ); this.listenTo( recipeActions.getRecipeById.completed, gotRecipe.bind( this ) ); this.listenTo( recipeActions.getRecipeById.failed, setError.bind( this ) ); }, getInitialState() { return this.store; }, ///public methods calculate() { this.store.calculateRecipe(); } } ); ////////////////////////// //// Private function gotRecipe( recipe ) { //a recipe has also oils, which needs to be extended recipe.oils = _.map( recipe.oils, oil => ( new OilModel( oil ).getExtendedOil() ) ); this.store.setRecipe( recipe ); doTrigger.call( this ); } function setError( error ) { this.trigger( { error: error.responseJSON } ); } function doTrigger() { this.trigger( this.store ); }
20.363636
88
0.621429
b735b7bb4213814dc2cdfeb44959c23f947819fd
20,032
js
JavaScript
ShadowEditor.Web/src/loader/lol/HiddenBones.js
qingqibing/ShadowEditor
b7145b92ba6be50fb55fa1ec466582e0abb5d6f1
[ "MIT" ]
5
2020-03-10T05:55:55.000Z
2021-08-09T08:29:37.000Z
ShadowEditor.Web/src/loader/lol/HiddenBones.js
doc22940/ShadowEditor
25e1a751101c6cb2eea384c37b0d08be935398ff
[ "MIT" ]
1
2021-05-11T05:50:38.000Z
2021-05-11T05:50:38.000Z
ShadowEditor.Web/src/loader/lol/HiddenBones.js
doc22940/ShadowEditor
25e1a751101c6cb2eea384c37b0d08be935398ff
[ "MIT" ]
3
2019-12-20T16:01:45.000Z
2020-12-02T09:15:23.000Z
/** * @author lolking / http://www.lolking.net/models * @author tengge / https://github.com/tengge1 */ var HiddenBones = { 12: { 9: { recall: {}, all: { recall_chair: true } }, 10: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 11: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 12: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 13: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 14: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 15: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 16: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 17: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} }, 18: { recall: { cowbell: true, stick: true }, dancein: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, danceloop: { cata_root: true, catb_root: true, catc_root: true, cork: true, bowl: true, bowl_milk: true, milk_root: true, bottle: true }, all: {} } }, 21: { 9: { all: { orange: true }, recall: { l_weapon: true, r_weapon: true } }, 10: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } }, 11: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } }, 12: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } }, 13: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } }, 14: { recall: {}, all: { tv_joint: true, tv_rabit_ears_joints: true } } }, 22: { 8: { all: { c_drone_base: true }, joke: {}, dance: {} } }, 36: { 9: { all: { recall_chair: true }, recall: {} } }, 41: { 0: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 1: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 2: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 3: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 4: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 5: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 6: { all: { orange1: true, orange2: true, orange3: true }, joke: {} }, 7: { all: { orange1: true, orange2: true, orange3: true }, joke: {} } }, 44: { 4: { all: { jacket: true }, dance: { jacket: true, weapon: true }, recall: { weapon: true } } }, 55: { 7: { recall: {}, all: { xmas_pole_skin07: true } } }, 61: { 7: { recall: {}, all: { planet1: true, planet2: true, planet3: true, planet4: true, planet5: true, planet6: true } } }, 69: { 4: { all: { l_fan: true, r_fan: true }, recall: {} } }, 80: { 8: { all: { oven: true }, recall: {} } }, 83: { 0: { all: {}, idle2: { weapon: true } }, 1: { all: {}, idle2: { weapon: true } }, 2: { all: {}, idle2: { weapon: true } } }, 103: { 7: { recall: {}, all: { arcade: true } } }, 114: { 5: { all: { weapon_krab: true, root_krab: true }, recall: {} } }, 115: { 4: { all: { sled: true }, satcheljump: { bomb: true, bomb_b: true } } }, 119: { 4: { all: { chair_root: true, sun_reflector_root: true }, recall: {} } }, 136: { 0: { all: { shades_sunglass: true }, joke: {} }, 1: { all: { shades_sunglass: true }, joke: {} } }, 143: { 4: { attack1: { r_wing: true, l_wing: true }, attack2: { r_wing: true, l_wing: true }, dance: { r_wing: true, l_wing: true }, idle1: { r_wing: true, l_wing: true }, idle3: { r_wing: true, l_wing: true }, idle4: { r_wing: true, l_wing: true }, laugh: { r_wing: true, l_wing: true }, run: { r_wing: true, l_wing: true }, spell2: { r_wing: true, l_wing: true }, all: {} } }, 157: { 4: { all: { flute: true }, dance: {} }, 5: { all: { flute: true }, dance: {} }, 6: { all: { flute: true }, dance: {} }, 7: { all: { flute: true }, dance: {} }, 8: { all: { flute: true }, dance: {} } }, 201: { 3: { all: { poro: true } } }, 222: { 4: { all: { rocket_launcher: true }, r_attack1: {}, r_attack2: {}, r_idle1: {}, r_idle_in: {}, r_run: {}, r_run_fast: {}, r_run_haste: {}, r_spell2: {}, r_spell3: {}, r_spell3_run: {}, r_spell4: {}, respawn_trans_rlauncher: {}, rlauncher_spell3: {}, spell1a: {} } }, 238: { 10: { all: { chair_skin10: true, step1_skin10: true, step2_skin10: true }, recall: {} } }, 245: { 0: { deathrespawn: {}, all: { book_pen: true } }, 1: { deathrespawn: {}, all: { book_pen: true } }, 2: { deathrespawn: {}, all: { book_pen: true } }, 3: { deathrespawn: {}, all: { book_pen: true } }, 4: { deathrespawn: {}, all: { book_pen: true } }, 5: { deathrespawn: {}, all: { book_pen: true } }, 6: { deathrespawn: {}, all: { book_pen: true } }, 7: { deathrespawn: {}, all: { book_pen: true } }, 8: { deathrespawn: {}, all: { book_pen: true } }, 9: { deathrespawn: {}, all: { book_pen: true } }, 10: { deathrespawn: {}, all: { book_pen: true } } }, 254: { 0: { all: { teacup: true }, taunt2: {} }, 1: { all: { teacup: true }, taunt2: {} }, 3: { all: { teacup: true }, taunt2: {} }, 4: { all: { teacup: true }, taunt2: {} } }, 412: { 1: { all: { coin1: true, coin2: true, coin3: true, coin4: true, coin5: true, coin6: true, coin7: true, treasure_chest: true, treasure_chest_cover: true, tire: true }, recall: { tire: true }, undersea_recall_loop: { tire: true }, undersea_recall_loop2: { coin1: true, coin2: true, coin3: true, coin4: true, coin5: true, coin6: true, coin7: true, treasure_chest: true, treasure_chest_cover: true }, undersea_recall_windup: { tire: true }, undersea_recall_windup2: { coin1: true, coin2: true, coin3: true, coin4: true, coin5: true, coin6: true, coin7: true, treasure_chest: true, treasure_chest_cover: true } }, 5: { all: { mini_root: true }, joke: {} } }, 420: { 0: { all: { c_tentacle1: true } }, 1: { all: { c_tentacle1: true } } }, 429: { 3: { death: { altar_spear: true, buffbone_cstm_back_spear1: true, buffbone_cstm_back_spear2: true, buffbone_cstm_back_spear3: true } } }, 432: { 0: { all: { follower_root: true }, dance: {} }, 2: { all: { follower_root: true }, dance: {} }, 3: { all: { follower_root: true }, dance: {} }, 4: { all: { follower_root: true }, dance: {} } }, gnarbig: { 0: { all: { rock: true }, spell1: {}, laugh: {} }, 1: { all: { rock: true }, spell1: {}, laugh: {} }, 2: { all: { rock: true, cane_bot: true, cane_top: true }, spell1: { cane_bot: true, cane_top: true }, laugh: { cane_bot: true, cane_top: true }, recall: { rock: true } }, 3: { all: { rock: true }, spell1: {}, laugh: {} }, 4: { all: { rock: true }, spell1: {}, laugh: {} }, 5: { all: { rock: true }, spell1: {}, laugh: {} }, 6: { all: { rock: true }, spell1: {}, laugh: {} }, 7: { all: { rock: true }, spell1: {}, laugh: {} }, 8: { all: { rock: true }, spell1: {}, laugh: {} }, 9: { all: { rock: true }, spell1: {}, laugh: {} }, 10: { all: { rock: true }, spell1: {}, laugh: {} }, 11: { all: { rock: true }, spell1: {}, laugh: {} }, 12: { all: { rock: true }, spell1: {}, laugh: {} } } }; export default HiddenBones;
21.750271
50
0.271815
b735cd489b37791b6dbeab685e6a17931a6d8e9c
2,636
js
JavaScript
React/covid-19-tracker/src/components/Cards/Cards.js
saanyalall/Hacktoberfest2021-2
3b9aea4ff320976e7c2bcb85f5265be87b0c33be
[ "MIT" ]
null
null
null
React/covid-19-tracker/src/components/Cards/Cards.js
saanyalall/Hacktoberfest2021-2
3b9aea4ff320976e7c2bcb85f5265be87b0c33be
[ "MIT" ]
null
null
null
React/covid-19-tracker/src/components/Cards/Cards.js
saanyalall/Hacktoberfest2021-2
3b9aea4ff320976e7c2bcb85f5265be87b0c33be
[ "MIT" ]
null
null
null
import React from 'react'; import { Card, CardContent, Typography, Grid } from '@material-ui/core'; import CountUp from 'react-countup'; import cx from 'classnames'; //for multiple classes on one element import styles from './Cards.module.css'; const Cards = ({data: {confirmed, recovered, deaths, lastUpdate}}) => { if(!confirmed){ return 'Loading....' } return( <div className={styles.container}> <Grid container spacing={3} justify="center"> <Grid item component = {Card} xs={12} md={3} className={cx(styles.card, styles.infected)}> <CardContent> <Typography color="textSecondary" gutterBottom>Infected</Typography> <Typography variant="h5"> <CountUp start={0} end={confirmed.value} duration={2.5} separator="," /> </Typography> <Typography color="textSecondary">{new Date(lastUpdate).toDateString()}</Typography> <Typography variant="body2">Number of active cases of COVID-19</Typography> </CardContent> </Grid> <Grid item component = {Card} xs={12} md={3} className={cx(styles.card, styles.recovered)}> <CardContent> <Typography color="textSecondary" gutterBottom>Recovered</Typography> <Typography variant="h5"> <CountUp start={0} end={recovered.value} duration={2.5} separator="," /> </Typography> <Typography color="textSecondary" gutterBottom>{new Date(lastUpdate).toDateString()}</Typography> <Typography variant="body2">Number of recoveries from COVID-19</Typography> </CardContent> </Grid> <Grid item component = {Card} xs={12} md={3} className={cx(styles.card, styles.deaths)}> <CardContent> <Typography color="textSecondary" gutterBottom>Deaths</Typography> <Typography variant="h5"> <CountUp start={0} end={deaths.value} duration={2.5} separator="," /> </Typography> <Typography color="textSecondary">{new Date(lastUpdate).toDateString()}</Typography> <Typography variant="body2">Number of deaths caused by COVID-19</Typography> </CardContent> </Grid> </Grid> </div> ) } export default Cards;
52.72
121
0.536039