language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class IQCube extends DH3DObject {
/**
* constructor
* @access public
* @constructor
* @param {string} type - Cube type: 'advantage', 'forbidden', 'normal'
*/
constructor(type){
super()
/** @type {float} */
this.size = IQGameData.cubeSize
/** @type {string} */
this.state = ''
/** @type {string} */
this.type = ''
/** @type {Date} */
this.startTime = null
/** @type {int} */
this.moveTime = 0
/** @type {Date} */
this.deleteStartTime = null
/** @type {float} */
this.rotateCount = 0
/** @type {boolean} */
this.deleteStarted = false
/** @type {boolean} */
this.paused = false
switch(type){
case 'advantage':
this.setType('advantage')
break
case 'forbidden':
this.setType('forbidden')
break
case 'normal':
default:
this.setType('normal')
break
}
this.setModel(IQCube.model_n.clone())
this.setAnimating(false)
this.setRenderer(IQGameData.renderer)
this.setRotate(0, 1, 0, 0)
}
/**
* set cube type
* @access public
* @param {string} type - cube type: 'advantage', 'forbidden', 'normal'
* @returns {void}
*/
setType(type) {
if(this.type === type){
return 0
}
switch(type){
case 'normal':
this.setModel(IQCube.model_n.clone())
break
case 'advantage':
this.setModel(IQCube.model_a.clone())
break
case 'forbidden':
this.setModel(IQCube.model_f.clone())
break
default:
return -1
}
this.type = type
this.setScale(this.size)
return 0
}
/**
* erase cube by given marker
* @access public
* @param {IQMarker} marker - marker which erases this cube
* @returns {void}
*/
eraseWithMarker(marker) {
// FIXME: wait before delete
this.marker = marker
const obj = this
IQGameData.aCubeArray.forEach( (cubeLine) => {
const index = cubeLine.indexOf(obj)
if(index >= 0){
cubeLine[index] = null
}
})
if(this.type === 'forbidden'){
// penalty: nothing to do here
}else{
// get point
if(marker.advantage){
IQGameData.score += IQGameData.pointAdvantage
}else{
IQGameData.score += IQGameData.pointNormal
}
}
IQGameData.deleteCubeArray.push(this)
this.deleteStartTime = new Date(IQGameData.nowTime.getTime())
}
pause() {
if(this.paused){
return
}
this.paused = true
if(this.type !== 'normal'){
this.getModel().materialArray[0].texture = IQCube.model_n.materialArray[0].texture
}
}
resume(pausedTime = 0) {
if(!this.paused){
return
}
this.paused = false
IQCube.resetTexture()
this.addTime(pausedTime)
}
addTime(msec) {
const timerArray = [
this.startTime,
this.deleteStartTime
]
timerArray.forEach((timer) => {
if(timer){
timer.setMilliseconds(timer.getMilliseconds() + msec)
}
})
}
resetTexture() {
if(this.type === 'forbidden'){
this.getModel().materialArray[0].texture = TextureBank.getTexture(IQCube.texture_f)
}else if(this.type === 'advantage'){
this.getModel().materialArray[0].texture = TextureBank.getTexture(IQCube.texture_a)
}
}
} |
JavaScript | class BlobClient extends StorageClient {
constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) {
options = options || {};
let pipeline;
let url;
if (credentialOrPipelineOrContainerName instanceof Pipeline) {
// (url: string, pipeline: Pipeline)
url = urlOrConnectionString;
pipeline = credentialOrPipelineOrContainerName;
}
else if ((isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) ||
credentialOrPipelineOrContainerName instanceof AnonymousCredential ||
isTokenCredential(credentialOrPipelineOrContainerName)) {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
url = urlOrConnectionString;
options = blobNameOrOptions;
pipeline = newPipeline(credentialOrPipelineOrContainerName, options);
}
else if (!credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName !== "string") {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
// The second parameter is undefined. Use anonymous credential.
url = urlOrConnectionString;
pipeline = newPipeline(new AnonymousCredential(), options);
}
else if (credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName === "string" &&
blobNameOrOptions &&
typeof blobNameOrOptions === "string") {
// (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions)
const containerName = credentialOrPipelineOrContainerName;
const blobName = blobNameOrOptions;
const extractedCreds = extractConnectionStringParts(urlOrConnectionString);
if (extractedCreds.kind === "AccountConnString") {
if (isNode) {
const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey);
url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName));
options.proxyOptions = getDefaultProxySettings(extractedCreds.proxyUri);
pipeline = newPipeline(sharedKeyCredential, options);
}
else {
throw new Error("Account connection string is only supported in Node.js environment");
}
}
else if (extractedCreds.kind === "SASConnString") {
url =
appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) +
"?" +
extractedCreds.accountSas;
pipeline = newPipeline(new AnonymousCredential(), options);
}
else {
throw new Error("Connection string must be either an Account connection string or a SAS connection string");
}
}
else {
throw new Error("Expecting non-empty strings for containerName and blobName parameters");
}
super(url, pipeline);
({
blobName: this._name,
containerName: this._containerName
} = this.getBlobAndContainerNamesFromUrl());
this.blobContext = new StorageBlob(this.storageClientContext);
this._snapshot = getURLParameter(this.url, URLConstants.Parameters.SNAPSHOT);
this._versionId = getURLParameter(this.url, URLConstants.Parameters.VERSIONID);
}
/**
* The name of the blob.
*/
get name() {
return this._name;
}
/**
* The name of the storage container the blob is associated with.
*/
get containerName() {
return this._containerName;
}
/**
* Creates a new BlobClient object identical to the source but with the specified snapshot timestamp.
* Provide "" will remove the snapshot and return a Client to the base blob.
*
* @param snapshot - The snapshot timestamp.
* @returns A new BlobClient object identical to the source but with the specified snapshot timestamp
*/
withSnapshot(snapshot) {
return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);
}
/**
* Creates a new BlobClient object pointing to a version of this blob.
* Provide "" will remove the versionId and return a Client to the base blob.
*
* @param versionId - The versionId.
* @returns A new BlobClient object pointing to the version of this blob.
*/
withVersion(versionId) {
return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline);
}
/**
* Creates a AppendBlobClient object.
*
*/
getAppendBlobClient() {
return new AppendBlobClient(this.url, this.pipeline);
}
/**
* Creates a BlockBlobClient object.
*
*/
getBlockBlobClient() {
return new BlockBlobClient(this.url, this.pipeline);
}
/**
* Creates a PageBlobClient object.
*
*/
getPageBlobClient() {
return new PageBlobClient(this.url, this.pipeline);
}
/**
* Reads or downloads a blob from the system, including its metadata and properties.
* You can also call Get Blob to read a snapshot.
*
* * In Node.js, data returns in a Readable stream readableStreamBody
* * In browsers, data returns in a promise blobBody
*
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob
*
* @param offset - From which position of the blob to download, greater than or equal to 0
* @param count - How much data to be downloaded, greater than 0. Will download to the end when undefined
* @param options - Optional options to Blob Download operation.
*
*
* Example usage (Node.js):
*
* ```js
* // Download and convert a blob to a string
* const downloadBlockBlobResponse = await blobClient.download();
* const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody);
* console.log("Downloaded blob content:", downloaded.toString());
*
* async function streamToBuffer(readableStream) {
* return new Promise((resolve, reject) => {
* const chunks = [];
* readableStream.on("data", (data) => {
* chunks.push(data instanceof Buffer ? data : Buffer.from(data));
* });
* readableStream.on("end", () => {
* resolve(Buffer.concat(chunks));
* });
* readableStream.on("error", reject);
* });
* }
* ```
*
* Example usage (browser):
*
* ```js
* // Download and convert a blob to a string
* const downloadBlockBlobResponse = await blobClient.download();
* const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody);
* console.log(
* "Downloaded blob content",
* downloaded
* );
*
* async function blobToString(blob: Blob): Promise<string> {
* const fileReader = new FileReader();
* return new Promise<string>((resolve, reject) => {
* fileReader.onloadend = (ev: any) => {
* resolve(ev.target!.result);
* };
* fileReader.onerror = reject;
* fileReader.readAsText(blob);
* });
* }
* ```
*/
async download(offset = 0, count, options = {}) {
var _a;
options.conditions = options.conditions || {};
options.conditions = options.conditions || {};
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
const { span, updatedOptions } = createSpan("BlobClient-download", options);
try {
const res = await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: {
onDownloadProgress: isNode ? undefined : options.onProgress // for Node.js, progress is reported by RetriableReadableStream
}, range: offset === 0 && !count ? undefined : rangeToString({ offset, count }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions)));
const wrappedRes = Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) });
// Return browser response immediately
if (!isNode) {
return wrappedRes;
}
// We support retrying when download stream unexpected ends in Node.js runtime
// Following code shouldn't be bundled into browser build, however some
// bundlers may try to bundle following code and "FileReadResponse.ts".
// In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts"
// The config is in package.json "browser" field
if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) {
// TODO: Default value or make it a required parameter?
options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS;
}
if (res.contentLength === undefined) {
throw new RangeError(`File download response doesn't contain valid content length header`);
}
if (!res.etag) {
throw new RangeError(`File download response doesn't contain valid etag header`);
}
return new BlobDownloadResponse(wrappedRes, async (start) => {
var _a;
const updatedOptions = {
leaseAccessConditions: options.conditions,
modifiedAccessConditions: {
ifMatch: options.conditions.ifMatch || res.etag,
ifModifiedSince: options.conditions.ifModifiedSince,
ifNoneMatch: options.conditions.ifNoneMatch,
ifUnmodifiedSince: options.conditions.ifUnmodifiedSince,
ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions
},
range: rangeToString({
count: offset + res.contentLength - start,
offset: start
}),
rangeGetContentMD5: options.rangeGetContentMD5,
rangeGetContentCRC64: options.rangeGetContentCrc64,
snapshot: options.snapshot,
cpkInfo: options.customerProvidedKey
};
// Debug purpose only
// console.log(
// `Read from internal stream, range: ${
// updatedOptions.range
// }, options: ${JSON.stringify(updatedOptions)}`
// );
return (await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal }, updatedOptions))).readableStreamBody;
}, offset, res.contentLength, {
maxRetryRequests: options.maxRetryRequests,
onProgress: options.onProgress
});
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Returns true if the Azure blob resource represented by this client exists; false otherwise.
*
* NOTE: use this function with care since an existing blob might be deleted by other clients or
* applications. Vice versa new blobs might be added by other clients or applications after this
* function completes.
*
* @param options - options to Exists operation.
*/
async exists(options = {}) {
const { span, updatedOptions } = createSpan("BlobClient-exists", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
await this.getProperties({
abortSignal: options.abortSignal,
customerProvidedKey: options.customerProvidedKey,
conditions: options.conditions,
tracingOptions: updatedOptions.tracingOptions
});
return true;
}
catch (e) {
if (e.statusCode === 404) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: "Expected exception when checking blob existence"
});
return false;
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Returns all user-defined metadata, standard HTTP properties, and system properties
* for the blob. It does not return the content of the blob.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties
*
* WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if
* they originally contained uppercase characters. This differs from the metadata keys returned by
* the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which
* will retain their original casing.
*
* @param options - Optional options to Get Properties operation.
*/
async getProperties(options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-getProperties", options);
try {
options.conditions = options.conditions || {};
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
const res = await this.blobContext.getProperties(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions)));
return Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) });
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Marks the specified blob or snapshot for deletion. The blob is later deleted
* during garbage collection. Note that in order to delete a blob, you must delete
* all of its snapshots. You can delete both at the same time with the Delete
* Blob operation.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob
*
* @param options - Optional options to Blob Delete operation.
*/
async delete(options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-delete", options);
options.conditions = options.conditions || {};
try {
return await this.blobContext.delete(Object.assign({ abortSignal: options.abortSignal, deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted
* during garbage collection. Note that in order to delete a blob, you must delete
* all of its snapshots. You can delete both at the same time with the Delete
* Blob operation.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob
*
* @param options - Optional options to Blob Delete operation.
*/
async deleteIfExists(options = {}) {
var _a, _b;
const { span, updatedOptions } = createSpan("BlobClient-deleteIfExists", options);
try {
const res = await this.delete(updatedOptions);
return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable
});
}
catch (e) {
if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") {
span.setStatus({
code: SpanStatusCode.ERROR,
message: "Expected exception when deleting a blob or snapshot only if it exists."
});
return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Restores the contents and metadata of soft deleted blob and any associated
* soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29
* or later.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob
*
* @param options - Optional options to Blob Undelete operation.
*/
async undelete(options = {}) {
const { span, updatedOptions } = createSpan("BlobClient-undelete", options);
try {
return await this.blobContext.undelete(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Sets system properties on the blob.
*
* If no value provided, or no value provided for the specified blob HTTP headers,
* these blob HTTP headers without a value will be cleared.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties
*
* @param blobHTTPHeaders - If no value provided, or no value provided for
* the specified blob HTTP headers, these blob HTTP
* headers without a value will be cleared.
* @param options - Optional options to Blob Set HTTP Headers operation.
*/
async setHTTPHeaders(blobHTTPHeaders, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-setHTTPHeaders", options);
options.conditions = options.conditions || {};
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.blobContext.setHttpHeaders(Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Sets user-defined metadata for the specified blob as one or more name-value pairs.
*
* If no option provided, or no metadata defined in the parameter, the blob
* metadata will be removed.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata
*
* @param metadata - Replace existing metadata with this value.
* If no value provided the existing metadata will be removed.
* @param options - Optional options to Set Metadata operation.
*/
async setMetadata(metadata, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-setMetadata", options);
options.conditions = options.conditions || {};
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.blobContext.setMetadata(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Sets tags on the underlying blob.
* A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters.
* Valid tag key and value characters include lower and upper case letters, digits (0-9),
* space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_').
*
* @param tags -
* @param options -
*/
async setTags(tags, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-setTags", options);
try {
return await this.blobContext.setTags(Object.assign(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)), { tags: toBlobTags(tags) }));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Gets the tags associated with the underlying blob.
*
* @param options -
*/
async getTags(options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-getTags", options);
try {
const response = await this.blobContext.getTags(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)));
const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} });
return wrappedResponse;
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Get a {@link BlobLeaseClient} that manages leases on the blob.
*
* @param proposeLeaseId - Initial proposed lease Id.
* @returns A new BlobLeaseClient object for managing leases on the blob.
*/
getBlobLeaseClient(proposeLeaseId) {
return new BlobLeaseClient(this, proposeLeaseId);
}
/**
* Creates a read-only snapshot of a blob.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob
*
* @param options - Optional options to the Blob Create Snapshot operation.
*/
async createSnapshot(options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-createSnapshot", options);
options.conditions = options.conditions || {};
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.blobContext.createSnapshot(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Asynchronously copies a blob to a destination within the storage account.
* This method returns a long running operation poller that allows you to wait
* indefinitely until the copy is completed.
* You can also cancel a copy before it is completed by calling `cancelOperation` on the poller.
* Note that the onProgress callback will not be invoked if the operation completes in the first
* request, and attempting to cancel a completed copy will result in an error being thrown.
*
* In version 2012-02-12 and later, the source for a Copy Blob operation can be
* a committed blob in any Azure storage account.
* Beginning with version 2015-02-21, the source for a Copy Blob operation can be
* an Azure file in any Azure storage account.
* Only storage accounts created on or after June 7th, 2012 allow the Copy Blob
* operation to copy from another storage account.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob
*
* Example using automatic polling:
*
* ```js
* const copyPoller = await blobClient.beginCopyFromURL('url');
* const result = await copyPoller.pollUntilDone();
* ```
*
* Example using manual polling:
*
* ```js
* const copyPoller = await blobClient.beginCopyFromURL('url');
* while (!poller.isDone()) {
* await poller.poll();
* }
* const result = copyPoller.getResult();
* ```
*
* Example using progress updates:
*
* ```js
* const copyPoller = await blobClient.beginCopyFromURL('url', {
* onProgress(state) {
* console.log(`Progress: ${state.copyProgress}`);
* }
* });
* const result = await copyPoller.pollUntilDone();
* ```
*
* Example using a changing polling interval (default 15 seconds):
*
* ```js
* const copyPoller = await blobClient.beginCopyFromURL('url', {
* intervalInMs: 1000 // poll blob every 1 second for copy progress
* });
* const result = await copyPoller.pollUntilDone();
* ```
*
* Example using copy cancellation:
*
* ```js
* const copyPoller = await blobClient.beginCopyFromURL('url');
* // cancel operation after starting it.
* try {
* await copyPoller.cancelOperation();
* // calls to get the result now throw PollerCancelledError
* await copyPoller.getResult();
* } catch (err) {
* if (err.name === 'PollerCancelledError') {
* console.log('The copy was cancelled.');
* }
* }
* ```
*
* @param copySource - url to the source Azure Blob/File.
* @param options - Optional options to the Blob Start Copy From URL operation.
*/
async beginCopyFromURL(copySource, options = {}) {
const client = {
abortCopyFromURL: (...args) => this.abortCopyFromURL(...args),
getProperties: (...args) => this.getProperties(...args),
startCopyFromURL: (...args) => this.startCopyFromURL(...args)
};
const poller = new BlobBeginCopyFromUrlPoller({
blobClient: client,
copySource,
intervalInMs: options.intervalInMs,
onProgress: options.onProgress,
resumeFrom: options.resumeFrom,
startCopyFromURLOptions: options
});
// Trigger the startCopyFromURL call by calling poll.
// Any errors from this method should be surfaced to the user.
await poller.poll();
return poller;
}
/**
* Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero
* length and full metadata. Version 2012-02-12 and newer.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob
*
* @param copyId - Id of the Copy From URL operation.
* @param options - Optional options to the Blob Abort Copy From URL operation.
*/
async abortCopyFromURL(copyId, options = {}) {
const { span, updatedOptions } = createSpan("BlobClient-abortCopyFromURL", options);
try {
return await this.blobContext.abortCopyFromURL(copyId, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not
* return a response until the copy is complete.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url
*
* @param copySource - The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication
* @param options -
*/
async syncCopyFromURL(copySource, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-syncCopyFromURL", options);
options.conditions = options.conditions || {};
options.sourceConditions = options.sourceConditions || {};
try {
return await this.blobContext.copyFromURL(copySource, Object.assign({ abortSignal: options.abortSignal, metadata: options.metadata, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: {
sourceIfMatch: options.sourceConditions.ifMatch,
sourceIfModifiedSince: options.sourceConditions.ifModifiedSince,
sourceIfNoneMatch: options.sourceConditions.ifNoneMatch,
sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince
}, sourceContentMD5: options.sourceContentMD5, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Sets the tier on a blob. The operation is allowed on a page blob in a premium
* storage account and on a block blob in a blob storage account (locally redundant
* storage only). A premium page blob's tier determines the allowed size, IOPS,
* and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive
* storage type. This operation does not update the blob's ETag.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier
*
* @param tier - The tier to be set on the blob. Valid values are Hot, Cool, or Archive.
* @param options - Optional options to the Blob Set Tier operation.
*/
async setAccessTier(tier, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-setAccessTier", options);
try {
return await this.blobContext.setTier(toAccessTier(tier), Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), rehydratePriority: options.rehydratePriority }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
async downloadToBuffer(param1, param2, param3, param4 = {}) {
let buffer;
let offset = 0;
let count = 0;
let options = param4;
if (param1 instanceof Buffer) {
buffer = param1;
offset = param2 || 0;
count = typeof param3 === "number" ? param3 : 0;
}
else {
offset = typeof param1 === "number" ? param1 : 0;
count = typeof param2 === "number" ? param2 : 0;
options = param3 || {};
}
const { span, updatedOptions } = createSpan("BlobClient-downloadToBuffer", options);
try {
if (!options.blockSize) {
options.blockSize = 0;
}
if (options.blockSize < 0) {
throw new RangeError("blockSize option must be >= 0");
}
if (options.blockSize === 0) {
options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES;
}
if (offset < 0) {
throw new RangeError("offset option must be >= 0");
}
if (count && count <= 0) {
throw new RangeError("count option must be greater than 0");
}
if (!options.conditions) {
options.conditions = {};
}
// Customer doesn't specify length, get it
if (!count) {
const response = await this.getProperties(Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }));
count = response.contentLength - offset;
if (count < 0) {
throw new RangeError(`offset ${offset} shouldn't be larger than blob size ${response.contentLength}`);
}
}
// Allocate the buffer of size = count if the buffer is not provided
if (!buffer) {
try {
buffer = Buffer.alloc(count);
}
catch (error) {
throw new Error(`Unable to allocate the buffer of size: ${count}(in bytes). Please try passing your own buffer to the "downloadToBuffer" method or try using other methods like "download" or "downloadToFile".\t ${error.message}`);
}
}
if (buffer.length < count) {
throw new RangeError(`The buffer's size should be equal to or larger than the request count of bytes: ${count}`);
}
let transferProgress = 0;
const batch = new Batch(options.concurrency);
for (let off = offset; off < offset + count; off = off + options.blockSize) {
batch.addOperation(async () => {
// Exclusive chunk end position
let chunkEnd = offset + count;
if (off + options.blockSize < chunkEnd) {
chunkEnd = off + options.blockSize;
}
const response = await this.download(off, chunkEnd - off, {
abortSignal: options.abortSignal,
conditions: options.conditions,
maxRetryRequests: options.maxRetryRequestsPerBlock,
customerProvidedKey: options.customerProvidedKey,
tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions))
});
const stream = response.readableStreamBody;
await streamToBuffer(stream, buffer, off - offset, chunkEnd - offset);
// Update progress after block is downloaded, in case of block trying
// Could provide finer grained progress updating inside HTTP requests,
// only if convenience layer download try is enabled
transferProgress += chunkEnd - off;
if (options.onProgress) {
options.onProgress({ loadedBytes: transferProgress });
}
});
}
await batch.do();
return buffer;
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* ONLY AVAILABLE IN NODE.JS RUNTIME.
*
* Downloads an Azure Blob to a local file.
* Fails if the the given file path already exits.
* Offset and count are optional, pass 0 and undefined respectively to download the entire blob.
*
* @param filePath -
* @param offset - From which position of the block blob to download.
* @param count - How much data to be downloaded. Will download to the end when passing undefined.
* @param options - Options to Blob download options.
* @returns The response data for blob download operation,
* but with readableStreamBody set to undefined since its
* content is already read and written into a local file
* at the specified path.
*/
async downloadToFile(filePath, offset = 0, count, options = {}) {
const { span, updatedOptions } = createSpan("BlobClient-downloadToFile", options);
try {
const response = await this.download(offset, count, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }));
if (response.readableStreamBody) {
await readStreamToLocalFile(response.readableStreamBody, filePath);
}
// The stream is no longer accessible so setting it to undefined.
response.blobDownloadStream = undefined;
return response;
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
getBlobAndContainerNamesFromUrl() {
let containerName;
let blobName;
try {
// URL may look like the following
// "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString";
// "https://myaccount.blob.core.windows.net/mycontainer/blob";
// "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt?sasString";
// "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt";
// IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob`
// http://localhost:10001/devstoreaccount1/containername/blob
const parsedUrl = URLBuilder.parse(this.url);
if (parsedUrl.getHost().split(".")[1] === "blob") {
// "https://myaccount.blob.core.windows.net/containername/blob".
// .getPath() -> /containername/blob
const pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?");
containerName = pathComponents[1];
blobName = pathComponents[3];
}
else if (isIpEndpointStyle(parsedUrl)) {
// IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob
// Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob
// .getPath() -> /devstoreaccount1/containername/blob
const pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?");
containerName = pathComponents[2];
blobName = pathComponents[4];
}
else {
// "https://customdomain.com/containername/blob".
// .getPath() -> /containername/blob
const pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?");
containerName = pathComponents[1];
blobName = pathComponents[3];
}
// decode the encoded blobName, containerName - to get all the special characters that might be present in them
containerName = decodeURIComponent(containerName);
blobName = decodeURIComponent(blobName);
// Azure Storage Server will replace "\" with "/" in the blob names
// doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName
blobName = blobName.replace(/\\/g, "/");
if (!containerName) {
throw new Error("Provided containerName is invalid.");
}
return { blobName, containerName };
}
catch (error) {
throw new Error("Unable to extract blobName and containerName with provided information.");
}
}
/**
* Asynchronously copies a blob to a destination within the storage account.
* In version 2012-02-12 and later, the source for a Copy Blob operation can be
* a committed blob in any Azure storage account.
* Beginning with version 2015-02-21, the source for a Copy Blob operation can be
* an Azure file in any Azure storage account.
* Only storage accounts created on or after June 7th, 2012 allow the Copy Blob
* operation to copy from another storage account.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob
*
* @param copySource - url to the source Azure Blob/File.
* @param options - Optional options to the Blob Start Copy From URL operation.
*/
async startCopyFromURL(copySource, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlobClient-startCopyFromURL", options);
options.conditions = options.conditions || {};
options.sourceConditions = options.sourceConditions || {};
try {
return await this.blobContext.startCopyFromURL(copySource, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: {
sourceIfMatch: options.sourceConditions.ifMatch,
sourceIfModifiedSince: options.sourceConditions.ifModifiedSince,
sourceIfNoneMatch: options.sourceConditions.ifNoneMatch,
sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince,
sourceIfTags: options.sourceConditions.tagConditions
}, rehydratePriority: options.rehydratePriority, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), sealBlob: options.sealBlob }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Only available for BlobClient constructed with a shared key credential.
*
* Generates a Blob Service Shared Access Signature (SAS) URI based on the client properties
* and parameters passed in. The SAS is signed by the shared key credential of the client.
*
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas
*
* @param options - Optional parameters.
* @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token.
*/
generateSasUrl(options) {
return new Promise((resolve) => {
if (!(this.credential instanceof StorageSharedKeyCredential)) {
throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential");
}
const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), this.credential).toString();
resolve(appendToURLQuery(this.url, sas));
});
}
} |
JavaScript | class AppendBlobClient extends BlobClient {
constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) {
// In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead.
// super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options);
let pipeline;
let url;
options = options || {};
if (credentialOrPipelineOrContainerName instanceof Pipeline) {
// (url: string, pipeline: Pipeline)
url = urlOrConnectionString;
pipeline = credentialOrPipelineOrContainerName;
}
else if ((isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) ||
credentialOrPipelineOrContainerName instanceof AnonymousCredential ||
isTokenCredential(credentialOrPipelineOrContainerName)) {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString;
url = urlOrConnectionString;
options = blobNameOrOptions;
pipeline = newPipeline(credentialOrPipelineOrContainerName, options);
}
else if (!credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName !== "string") {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
url = urlOrConnectionString;
// The second parameter is undefined. Use anonymous credential.
pipeline = newPipeline(new AnonymousCredential(), options);
}
else if (credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName === "string" &&
blobNameOrOptions &&
typeof blobNameOrOptions === "string") {
// (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions)
const containerName = credentialOrPipelineOrContainerName;
const blobName = blobNameOrOptions;
const extractedCreds = extractConnectionStringParts(urlOrConnectionString);
if (extractedCreds.kind === "AccountConnString") {
if (isNode) {
const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey);
url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName));
options.proxyOptions = getDefaultProxySettings(extractedCreds.proxyUri);
pipeline = newPipeline(sharedKeyCredential, options);
}
else {
throw new Error("Account connection string is only supported in Node.js environment");
}
}
else if (extractedCreds.kind === "SASConnString") {
url =
appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) +
"?" +
extractedCreds.accountSas;
pipeline = newPipeline(new AnonymousCredential(), options);
}
else {
throw new Error("Connection string must be either an Account connection string or a SAS connection string");
}
}
else {
throw new Error("Expecting non-empty strings for containerName and blobName parameters");
}
super(url, pipeline);
this.appendBlobContext = new AppendBlob(this.storageClientContext);
}
/**
* Creates a new AppendBlobClient object identical to the source but with the
* specified snapshot timestamp.
* Provide "" will remove the snapshot and return a Client to the base blob.
*
* @param snapshot - The snapshot timestamp.
* @returns A new AppendBlobClient object identical to the source but with the specified snapshot timestamp.
*/
withSnapshot(snapshot) {
return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);
}
/**
* Creates a 0-length append blob. Call AppendBlock to append data to an append blob.
* @see https://docs.microsoft.com/rest/api/storageservices/put-blob
*
* @param options - Options to the Append Block Create operation.
*
*
* Example usage:
*
* ```js
* const appendBlobClient = containerClient.getAppendBlobClient("<blob name>");
* await appendBlobClient.create();
* ```
*/
async create(options = {}) {
var _a;
const { span, updatedOptions } = createSpan("AppendBlobClient-create", options);
options.conditions = options.conditions || {};
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.appendBlobContext.create(0, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Creates a 0-length append blob. Call AppendBlock to append data to an append blob.
* If the blob with the same name already exists, the content of the existing blob will remain unchanged.
* @see https://docs.microsoft.com/rest/api/storageservices/put-blob
*
* @param options -
*/
async createIfNotExists(options = {}) {
var _a, _b;
const { span, updatedOptions } = createSpan("AppendBlobClient-createIfNotExists", options);
const conditions = { ifNoneMatch: ETagAny };
try {
const res = await this.create(Object.assign(Object.assign({}, updatedOptions), { conditions }));
return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable
});
}
catch (e) {
if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") {
span.setStatus({
code: SpanStatusCode.ERROR,
message: "Expected exception when creating a blob only if it does not already exist."
});
return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Seals the append blob, making it read only.
*
* @param options -
*/
async seal(options = {}) {
var _a;
const { span, updatedOptions } = createSpan("AppendBlobClient-seal", options);
options.conditions = options.conditions || {};
try {
return await this.appendBlobContext.seal(Object.assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Commits a new block of data to the end of the existing append blob.
* @see https://docs.microsoft.com/rest/api/storageservices/append-block
*
* @param body - Data to be appended.
* @param contentLength - Length of the body in bytes.
* @param options - Options to the Append Block operation.
*
*
* Example usage:
*
* ```js
* const content = "Hello World!";
*
* // Create a new append blob and append data to the blob.
* const newAppendBlobClient = containerClient.getAppendBlobClient("<blob name>");
* await newAppendBlobClient.create();
* await newAppendBlobClient.appendBlock(content, content.length);
*
* // Append data to an existing append blob.
* const existingAppendBlobClient = containerClient.getAppendBlobClient("<blob name>");
* await existingAppendBlobClient.appendBlock(content, content.length);
* ```
*/
async appendBlock(body, contentLength, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("AppendBlobClient-appendBlock", options);
options.conditions = options.conditions || {};
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.appendBlobContext.appendBlock(contentLength, body, Object.assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: {
onUploadProgress: options.onProgress
}, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* The Append Block operation commits a new block of data to the end of an existing append blob
* where the contents are read from a source url.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url
*
* @param sourceURL -
* The url to the blob that will be the source of the copy. A source blob in the same storage account can
* be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is
* public, no authentication is required to perform the operation.
* @param sourceOffset - Offset in source to be appended
* @param count - Number of bytes to be appended as a block
* @param options -
*/
async appendBlockFromURL(sourceURL, sourceOffset, count, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("AppendBlobClient-appendBlockFromURL", options);
options.conditions = options.conditions || {};
options.sourceConditions = options.sourceConditions || {};
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, Object.assign({ abortSignal: options.abortSignal, sourceRange: rangeToString({ offset: sourceOffset, count }), sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, appendPositionAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: {
sourceIfMatch: options.sourceConditions.ifMatch,
sourceIfModifiedSince: options.sourceConditions.ifModifiedSince,
sourceIfNoneMatch: options.sourceConditions.ifNoneMatch,
sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince
}, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
} |
JavaScript | class BlockBlobClient extends BlobClient {
constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) {
// In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead.
// super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options);
let pipeline;
let url;
options = options || {};
if (credentialOrPipelineOrContainerName instanceof Pipeline) {
// (url: string, pipeline: Pipeline)
url = urlOrConnectionString;
pipeline = credentialOrPipelineOrContainerName;
}
else if ((isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) ||
credentialOrPipelineOrContainerName instanceof AnonymousCredential ||
isTokenCredential(credentialOrPipelineOrContainerName)) {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
url = urlOrConnectionString;
options = blobNameOrOptions;
pipeline = newPipeline(credentialOrPipelineOrContainerName, options);
}
else if (!credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName !== "string") {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
// The second parameter is undefined. Use anonymous credential.
url = urlOrConnectionString;
pipeline = newPipeline(new AnonymousCredential(), options);
}
else if (credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName === "string" &&
blobNameOrOptions &&
typeof blobNameOrOptions === "string") {
// (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions)
const containerName = credentialOrPipelineOrContainerName;
const blobName = blobNameOrOptions;
const extractedCreds = extractConnectionStringParts(urlOrConnectionString);
if (extractedCreds.kind === "AccountConnString") {
if (isNode) {
const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey);
url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName));
options.proxyOptions = getDefaultProxySettings(extractedCreds.proxyUri);
pipeline = newPipeline(sharedKeyCredential, options);
}
else {
throw new Error("Account connection string is only supported in Node.js environment");
}
}
else if (extractedCreds.kind === "SASConnString") {
url =
appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) +
"?" +
extractedCreds.accountSas;
pipeline = newPipeline(new AnonymousCredential(), options);
}
else {
throw new Error("Connection string must be either an Account connection string or a SAS connection string");
}
}
else {
throw new Error("Expecting non-empty strings for containerName and blobName parameters");
}
super(url, pipeline);
this.blockBlobContext = new BlockBlob(this.storageClientContext);
this._blobContext = new StorageBlob(this.storageClientContext);
}
/**
* Creates a new BlockBlobClient object identical to the source but with the
* specified snapshot timestamp.
* Provide "" will remove the snapshot and return a URL to the base blob.
*
* @param snapshot - The snapshot timestamp.
* @returns A new BlockBlobClient object identical to the source but with the specified snapshot timestamp.
*/
withSnapshot(snapshot) {
return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);
}
/**
* ONLY AVAILABLE IN NODE.JS RUNTIME.
*
* Quick query for a JSON or CSV formatted blob.
*
* Example usage (Node.js):
*
* ```js
* // Query and convert a blob to a string
* const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage");
* const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString();
* console.log("Query blob content:", downloaded);
*
* async function streamToBuffer(readableStream) {
* return new Promise((resolve, reject) => {
* const chunks = [];
* readableStream.on("data", (data) => {
* chunks.push(data instanceof Buffer ? data : Buffer.from(data));
* });
* readableStream.on("end", () => {
* resolve(Buffer.concat(chunks));
* });
* readableStream.on("error", reject);
* });
* }
* ```
*
* @param query -
* @param options -
*/
async query(query, options = {}) {
var _a;
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
const { span, updatedOptions } = createSpan("BlockBlobClient-query", options);
try {
if (!isNode) {
throw new Error("This operation currently is only supported in Node.js.");
}
const response = await this._blobContext.query(Object.assign({ abortSignal: options.abortSignal, queryRequest: {
queryType: "SQL",
expression: query,
inputSerialization: toQuerySerialization(options.inputTextConfiguration),
outputSerialization: toQuerySerialization(options.outputTextConfiguration)
}, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)));
return new BlobQueryResponse(response, {
abortSignal: options.abortSignal,
onProgress: options.onProgress,
onError: options.onError
});
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* Updating an existing block blob overwrites any existing metadata on the blob.
* Partial updates are not supported; the content of the existing blob is
* overwritten with the new content. To perform a partial update of a block blob's,
* use {@link stageBlock} and {@link commitBlockList}.
*
* This is a non-parallel uploading method, please use {@link uploadFile},
* {@link uploadStream} or {@link uploadBrowserData} for better performance
* with concurrency uploading.
*
* @see https://docs.microsoft.com/rest/api/storageservices/put-blob
*
* @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function
* which returns a new Readable stream whose offset is from data source beginning.
* @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a
* string including non non-Base64/Hex-encoded characters.
* @param options - Options to the Block Blob Upload operation.
* @returns Response data for the Block Blob Upload operation.
*
* Example usage:
*
* ```js
* const content = "Hello world!";
* const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
* ```
*/
async upload(body, contentLength, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("BlockBlobClient-upload", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.blockBlobContext.upload(contentLength, body, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: {
onUploadProgress: options.onProgress
}, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Creates a new Block Blob where the contents of the blob are read from a given URL.
* This API is supported beginning with the 2020-04-08 version. Partial updates
* are not supported with Put Blob from URL; the content of an existing blob is overwritten with
* the content of the new blob. To perform partial updates to a block blob’s contents using a
* source URL, use {@link stageBlockFromURL} and {@link commitBlockList}.
*
* @param sourceURL - Specifies the URL of the blob. The value
* may be a URL of up to 2 KB in length that specifies a blob.
* The value should be URL-encoded as it would appear
* in a request URI. The source blob must either be public
* or must be authenticated via a shared access signature.
* If the source blob is public, no authentication is required
* to perform the operation. Here are some examples of source object URLs:
* - https://myaccount.blob.core.windows.net/mycontainer/myblob
* - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot=<DateTime>
* @param options - Optional parameters.
*/
async syncUploadFromURL(sourceURL, options = {}) {
var _a, _b, _c, _d, _e;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("BlockBlobClient-syncUploadFromURL", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.blockBlobContext.putBlobFromUrl(0, sourceURL, Object.assign(Object.assign(Object.assign({}, options), { blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: options.conditions.tagConditions }), sourceModifiedAccessConditions: {
sourceIfMatch: (_a = options.sourceConditions) === null || _a === void 0 ? void 0 : _a.ifMatch,
sourceIfModifiedSince: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifModifiedSince,
sourceIfNoneMatch: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch,
sourceIfUnmodifiedSince: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifUnmodifiedSince,
sourceIfTags: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.tagConditions
}, cpkInfo: options.customerProvidedKey, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }), convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Uploads the specified block to the block blob's "staging area" to be later
* committed by a call to commitBlockList.
* @see https://docs.microsoft.com/rest/api/storageservices/put-block
*
* @param blockId - A 64-byte value that is base64-encoded
* @param body - Data to upload to the staging area.
* @param contentLength - Number of bytes to upload.
* @param options - Options to the Block Blob Stage Block operation.
* @returns Response data for the Block Blob Stage Block operation.
*/
async stageBlock(blockId, body, contentLength, options = {}) {
const { span, updatedOptions } = createSpan("BlockBlobClient-stageBlock", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.blockBlobContext.stageBlock(blockId, contentLength, body, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, requestOptions: {
onUploadProgress: options.onProgress
}, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* The Stage Block From URL operation creates a new block to be committed as part
* of a blob where the contents are read from a URL.
* This API is available starting in version 2018-03-28.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url
*
* @param blockId - A 64-byte value that is base64-encoded
* @param sourceURL - Specifies the URL of the blob. The value
* may be a URL of up to 2 KB in length that specifies a blob.
* The value should be URL-encoded as it would appear
* in a request URI. The source blob must either be public
* or must be authenticated via a shared access signature.
* If the source blob is public, no authentication is required
* to perform the operation. Here are some examples of source object URLs:
* - https://myaccount.blob.core.windows.net/mycontainer/myblob
* - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot=<DateTime>
* @param offset - From which position of the blob to download, greater than or equal to 0
* @param count - How much data to be downloaded, greater than 0. Will download to the end when undefined
* @param options - Options to the Block Blob Stage Block From URL operation.
* @returns Response data for the Block Blob Stage Block From URL operation.
*/
async stageBlockFromURL(blockId, sourceURL, offset = 0, count, options = {}) {
const { span, updatedOptions } = createSpan("BlockBlobClient-stageBlockFromURL", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset, count }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Writes a blob by specifying the list of block IDs that make up the blob.
* In order to be written as part of a blob, a block must have been successfully written
* to the server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to
* update a blob by uploading only those blocks that have changed, then committing the new and existing
* blocks together. Any blocks not specified in the block list and permanently deleted.
* @see https://docs.microsoft.com/rest/api/storageservices/put-block-list
*
* @param blocks - Array of 64-byte value that is base64-encoded
* @param options - Options to the Block Blob Commit Block List operation.
* @returns Response data for the Block Blob Commit Block List operation.
*/
async commitBlockList(blocks, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("BlockBlobClient-commitBlockList", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.blockBlobContext.commitBlockList({ latest: blocks }, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob
* using the specified block list filter.
* @see https://docs.microsoft.com/rest/api/storageservices/get-block-list
*
* @param listType - Specifies whether to return the list of committed blocks,
* the list of uncommitted blocks, or both lists together.
* @param options - Options to the Block Blob Get Block List operation.
* @returns Response data for the Block Blob Get Block List operation.
*/
async getBlockList(listType, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("BlockBlobClient-getBlockList", options);
try {
const res = await this.blockBlobContext.getBlockList(listType, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)));
if (!res.committedBlocks) {
res.committedBlocks = [];
}
if (!res.uncommittedBlocks) {
res.uncommittedBlocks = [];
}
return res;
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
// High level functions
/**
* Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob.
*
* When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is
* {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload.
* Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList}
* to commit the block list.
*
* @param data - Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView
* @param options -
*/
async uploadData(data, options = {}) {
const { span, updatedOptions } = createSpan("BlockBlobClient-uploadData", options);
try {
if (isNode) {
let buffer;
if (data instanceof Buffer) {
buffer = data;
}
else if (data instanceof ArrayBuffer) {
buffer = Buffer.from(data);
}
else {
data = data;
buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
}
return this.uploadSeekableInternal((offset, size) => buffer.slice(offset, offset + size), buffer.byteLength, updatedOptions);
}
else {
const browserBlob = new Blob([data]);
return this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions);
}
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* ONLY AVAILABLE IN BROWSERS.
*
* Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob.
*
* When buffer length lesser than or equal to 256MB, this method will use 1 upload call to finish the upload.
* Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call
* {@link commitBlockList} to commit the block list.
*
* @deprecated Use {@link uploadData} instead.
*
* @param browserData - Blob, File, ArrayBuffer or ArrayBufferView
* @param options - Options to upload browser data.
* @returns Response data for the Blob Upload operation.
*/
async uploadBrowserData(browserData, options = {}) {
const { span, updatedOptions } = createSpan("BlockBlobClient-uploadBrowserData", options);
try {
const browserBlob = new Blob([browserData]);
return await this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions);
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
*
* Uploads data to block blob. Requires a bodyFactory as the data source,
* which need to return a {@link HttpRequestBody} object with the offset and size provided.
*
* When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is
* {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload.
* Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList}
* to commit the block list.
*
* @param bodyFactory -
* @param size - size of the data to upload.
* @param options - Options to Upload to Block Blob operation.
* @returns Response data for the Blob Upload operation.
*/
async uploadSeekableInternal(bodyFactory, size, options = {}) {
if (!options.blockSize) {
options.blockSize = 0;
}
if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) {
throw new RangeError(`blockSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES}`);
}
if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) {
options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES;
}
if (options.maxSingleShotSize < 0 ||
options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) {
throw new RangeError(`maxSingleShotSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}`);
}
if (options.blockSize === 0) {
if (size > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) {
throw new RangeError(`${size} is too larger to upload to a block blob.`);
}
if (size > options.maxSingleShotSize) {
options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS);
if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) {
options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES;
}
}
}
if (!options.blobHTTPHeaders) {
options.blobHTTPHeaders = {};
}
if (!options.conditions) {
options.conditions = {};
}
const { span, updatedOptions } = createSpan("BlockBlobClient-uploadSeekableInternal", options);
try {
if (size <= options.maxSingleShotSize) {
return await this.upload(bodyFactory(0, size), size, updatedOptions);
}
const numBlocks = Math.floor((size - 1) / options.blockSize) + 1;
if (numBlocks > BLOCK_BLOB_MAX_BLOCKS) {
throw new RangeError(`The buffer's size is too big or the BlockSize is too small;` +
`the number of blocks must be <= ${BLOCK_BLOB_MAX_BLOCKS}`);
}
const blockList = [];
const blockIDPrefix = generateUuid();
let transferProgress = 0;
const batch = new Batch(options.concurrency);
for (let i = 0; i < numBlocks; i++) {
batch.addOperation(async () => {
const blockID = generateBlockID(blockIDPrefix, i);
const start = options.blockSize * i;
const end = i === numBlocks - 1 ? size : start + options.blockSize;
const contentLength = end - start;
blockList.push(blockID);
await this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, {
abortSignal: options.abortSignal,
conditions: options.conditions,
encryptionScope: options.encryptionScope,
tracingOptions: updatedOptions.tracingOptions
});
// Update progress after block is successfully uploaded to server, in case of block trying
// TODO: Hook with convenience layer progress event in finer level
transferProgress += contentLength;
if (options.onProgress) {
options.onProgress({
loadedBytes: transferProgress
});
}
});
}
await batch.do();
return this.commitBlockList(blockList, updatedOptions);
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* ONLY AVAILABLE IN NODE.JS RUNTIME.
*
* Uploads a local file in blocks to a block blob.
*
* When file size lesser than or equal to 256MB, this method will use 1 upload call to finish the upload.
* Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList
* to commit the block list.
*
* @param filePath - Full path of local file
* @param options - Options to Upload to Block Blob operation.
* @returns Response data for the Blob Upload operation.
*/
async uploadFile(filePath, options = {}) {
const { span, updatedOptions } = createSpan("BlockBlobClient-uploadFile", options);
try {
const size = (await fsStat(filePath)).size;
return await this.uploadSeekableInternal((offset, count) => {
return () => fsCreateReadStream(filePath, {
autoClose: true,
end: count ? offset + count - 1 : Infinity,
start: offset
});
}, size, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* ONLY AVAILABLE IN NODE.JS RUNTIME.
*
* Uploads a Node.js Readable stream into block blob.
*
* PERFORMANCE IMPROVEMENT TIPS:
* * Input stream highWaterMark is better to set a same value with bufferSize
* parameter, which will avoid Buffer.concat() operations.
*
* @param stream - Node.js Readable stream
* @param bufferSize - Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB
* @param maxConcurrency - Max concurrency indicates the max number of buffers that can be allocated,
* positive correlation with max uploading concurrency. Default value is 5
* @param options - Options to Upload Stream to Block Blob operation.
* @returns Response data for the Blob Upload operation.
*/
async uploadStream(stream, bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) {
if (!options.blobHTTPHeaders) {
options.blobHTTPHeaders = {};
}
if (!options.conditions) {
options.conditions = {};
}
const { span, updatedOptions } = createSpan("BlockBlobClient-uploadStream", options);
try {
let blockNum = 0;
const blockIDPrefix = generateUuid();
let transferProgress = 0;
const blockList = [];
const scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, async (body, length) => {
const blockID = generateBlockID(blockIDPrefix, blockNum);
blockList.push(blockID);
blockNum++;
await this.stageBlock(blockID, body, length, {
conditions: options.conditions,
encryptionScope: options.encryptionScope,
tracingOptions: updatedOptions.tracingOptions
});
// Update progress after block is successfully uploaded to server, in case of block trying
transferProgress += length;
if (options.onProgress) {
options.onProgress({ loadedBytes: transferProgress });
}
},
// concurrency should set a smaller value than maxConcurrency, which is helpful to
// reduce the possibility when a outgoing handler waits for stream data, in
// this situation, outgoing handlers are blocked.
// Outgoing queue shouldn't be empty.
Math.ceil((maxConcurrency / 4) * 3));
await scheduler.do();
return await this.commitBlockList(blockList, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
} |
JavaScript | class PageBlobClient extends BlobClient {
constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) {
// In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead.
// super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options);
let pipeline;
let url;
options = options || {};
if (credentialOrPipelineOrContainerName instanceof Pipeline) {
// (url: string, pipeline: Pipeline)
url = urlOrConnectionString;
pipeline = credentialOrPipelineOrContainerName;
}
else if ((isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) ||
credentialOrPipelineOrContainerName instanceof AnonymousCredential ||
isTokenCredential(credentialOrPipelineOrContainerName)) {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
url = urlOrConnectionString;
options = blobNameOrOptions;
pipeline = newPipeline(credentialOrPipelineOrContainerName, options);
}
else if (!credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName !== "string") {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
// The second parameter is undefined. Use anonymous credential.
url = urlOrConnectionString;
pipeline = newPipeline(new AnonymousCredential(), options);
}
else if (credentialOrPipelineOrContainerName &&
typeof credentialOrPipelineOrContainerName === "string" &&
blobNameOrOptions &&
typeof blobNameOrOptions === "string") {
// (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions)
const containerName = credentialOrPipelineOrContainerName;
const blobName = blobNameOrOptions;
const extractedCreds = extractConnectionStringParts(urlOrConnectionString);
if (extractedCreds.kind === "AccountConnString") {
if (isNode) {
const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey);
url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName));
options.proxyOptions = getDefaultProxySettings(extractedCreds.proxyUri);
pipeline = newPipeline(sharedKeyCredential, options);
}
else {
throw new Error("Account connection string is only supported in Node.js environment");
}
}
else if (extractedCreds.kind === "SASConnString") {
url =
appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) +
"?" +
extractedCreds.accountSas;
pipeline = newPipeline(new AnonymousCredential(), options);
}
else {
throw new Error("Connection string must be either an Account connection string or a SAS connection string");
}
}
else {
throw new Error("Expecting non-empty strings for containerName and blobName parameters");
}
super(url, pipeline);
this.pageBlobContext = new PageBlob(this.storageClientContext);
}
/**
* Creates a new PageBlobClient object identical to the source but with the
* specified snapshot timestamp.
* Provide "" will remove the snapshot and return a Client to the base blob.
*
* @param snapshot - The snapshot timestamp.
* @returns A new PageBlobClient object identical to the source but with the specified snapshot timestamp.
*/
withSnapshot(snapshot) {
return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);
}
/**
* Creates a page blob of the specified length. Call uploadPages to upload data
* data to a page blob.
* @see https://docs.microsoft.com/rest/api/storageservices/put-blob
*
* @param size - size of the page blob.
* @param options - Options to the Page Blob Create operation.
* @returns Response data for the Page Blob Create operation.
*/
async create(size, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-create", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.pageBlobContext.create(0, size, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Creates a page blob of the specified length. Call uploadPages to upload data
* data to a page blob. If the blob with the same name already exists, the content
* of the existing blob will remain unchanged.
* @see https://docs.microsoft.com/rest/api/storageservices/put-blob
*
* @param size - size of the page blob.
* @param options -
*/
async createIfNotExists(size, options = {}) {
var _a, _b;
const { span, updatedOptions } = createSpan("PageBlobClient-createIfNotExists", options);
try {
const conditions = { ifNoneMatch: ETagAny };
const res = await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions }));
return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable
});
}
catch (e) {
if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") {
span.setStatus({
code: SpanStatusCode.ERROR,
message: "Expected exception when creating a blob only if it does not already exist."
});
return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });
}
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512.
* @see https://docs.microsoft.com/rest/api/storageservices/put-page
*
* @param body - Data to upload
* @param offset - Offset of destination page blob
* @param count - Content length of the body, also number of bytes to be uploaded
* @param options - Options to the Page Blob Upload Pages operation.
* @returns Response data for the Page Blob Upload Pages operation.
*/
async uploadPages(body, offset, count, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-uploadPages", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.pageBlobContext.uploadPages(count, body, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: {
onUploadProgress: options.onProgress
}, range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* The Upload Pages operation writes a range of pages to a page blob where the
* contents are read from a URL.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url
*
* @param sourceURL - Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication
* @param sourceOffset - The source offset to copy from. Pass 0 to copy from the beginning of source page blob
* @param destOffset - Offset of destination page blob
* @param count - Number of bytes to be uploaded from source page blob
* @param options -
*/
async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) {
var _a;
options.conditions = options.conditions || {};
options.sourceConditions = options.sourceConditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-uploadPagesFromURL", options);
try {
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), Object.assign({ abortSignal: options.abortSignal, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: {
sourceIfMatch: options.sourceConditions.ifMatch,
sourceIfModifiedSince: options.sourceConditions.ifModifiedSince,
sourceIfNoneMatch: options.sourceConditions.ifNoneMatch,
sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince
}, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Frees the specified pages from the page blob.
* @see https://docs.microsoft.com/rest/api/storageservices/put-page
*
* @param offset - Starting byte position of the pages to clear.
* @param count - Number of bytes to clear.
* @param options - Options to the Page Blob Clear Pages operation.
* @returns Response data for the Page Blob Clear Pages operation.
*/
async clearPages(offset = 0, count, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-clearPages", options);
try {
return await this.pageBlobContext.clearPages(0, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Returns the list of valid page ranges for a page blob or snapshot of a page blob.
* @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges
*
* @param offset - Starting byte position of the page ranges.
* @param count - Number of bytes to get.
* @param options - Options to the Page Blob Get Ranges operation.
* @returns Response data for the Page Blob Get Ranges operation.
*/
async getPageRanges(offset = 0, count, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-getPageRanges", options);
try {
return await this.pageBlobContext
.getPageRanges(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions)))
.then(rangeResponseFromModel);
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Gets the collection of page ranges that differ between a specified snapshot and this page blob.
* @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges
*
* @param offset - Starting byte position of the page blob
* @param count - Number of bytes to get ranges diff.
* @param prevSnapshot - Timestamp of snapshot to retrieve the difference.
* @param options - Options to the Page Blob Get Page Ranges Diff operation.
* @returns Response data for the Page Blob Get Page Range Diff operation.
*/
async getPageRangesDiff(offset, count, prevSnapshot, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-getPageRangesDiff", options);
try {
return await this.pageBlobContext
.getPageRangesDiff(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevsnapshot: prevSnapshot, range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions)))
.then(rangeResponseFromModel);
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks.
* @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges
*
* @param offset - Starting byte position of the page blob
* @param count - Number of bytes to get ranges diff.
* @param prevSnapshotUrl - URL of snapshot to retrieve the difference.
* @param options - Options to the Page Blob Get Page Ranges Diff operation.
* @returns Response data for the Page Blob Get Page Range Diff operation.
*/
async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options);
try {
return await this.pageBlobContext
.getPageRangesDiff(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevSnapshotUrl, range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions)))
.then(rangeResponseFromModel);
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Resizes the page blob to the specified size (which must be a multiple of 512).
* @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties
*
* @param size - Target size
* @param options - Options to the Page Blob Resize operation.
* @returns Response data for the Page Blob Resize operation.
*/
async resize(size, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-resize", options);
try {
return await this.pageBlobContext.resize(size, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Sets a page blob's sequence number.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties
*
* @param sequenceNumberAction - Indicates how the service should modify the blob's sequence number.
* @param sequenceNumber - Required if sequenceNumberAction is max or update
* @param options - Options to the Page Blob Update Sequence Number operation.
* @returns Response data for the Page Blob Update Sequence Number operation.
*/
async updateSequenceNumber(sequenceNumberAction, sequenceNumber, options = {}) {
var _a;
options.conditions = options.conditions || {};
const { span, updatedOptions } = createSpan("PageBlobClient-updateSequenceNumber", options);
try {
return await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, Object.assign({ abortSignal: options.abortSignal, blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
/**
* Begins an operation to start an incremental copy from one page blob's snapshot to this page blob.
* The snapshot is copied such that only the differential changes between the previously
* copied snapshot are transferred to the destination.
* The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual.
* @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob
* @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots
*
* @param copySource - Specifies the name of the source page blob snapshot. For example,
* https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot=<DateTime>
* @param options - Options to the Page Blob Copy Incremental operation.
* @returns Response data for the Page Blob Copy Incremental operation.
*/
async startCopyIncremental(copySource, options = {}) {
var _a;
const { span, updatedOptions } = createSpan("PageBlobClient-startCopyIncremental", options);
try {
return await this.pageBlobContext.copyIncremental(copySource, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e.message
});
throw e;
}
finally {
span.end();
}
}
} |
JavaScript | class MigrateModule {
constructor(mergedOptions, userOptions, defaults){
$ = mergedOptions.plugins;
this.mergedOptions = mergedOptions || {};
this.userOptions = userOptions || {};
this.defaults = defaults || {};
this.migrateWarnings = [];
this.warnedAbout = {};
this.migrateMessages = {
soon : 'and will be removed soon',
soonTo : 'and will be removed soon, use $newValue instead',
removed : 'and has been removed',
removedTo : 'and has been removed, use $newValue instead',
};
}
migrate() {
this.migrateGeneralOptions();
/**
* migrate.manager must be a function
*/
if(this.mergedOptions.migrate){
let manager = this.mergedOptions.migrate.optionsManager;
try {
manager(this.mergedOptions, this.userOptions, this.defaults);
} catch (err){
new manager(this.mergedOptions, this.userOptions, this.defaults);
}
}
}
migrateGeneralOptions(){
this.migrateWarnProp({
obj : this.mergedOptions,
prop : 'modulesData',
dotLocation : 'options',
value : this.mergedOptions.modulesData,
msg : getMessage({
type : 'soonTo',
newValue : 'modules'
})
});
}
getMessage(args) {
args = args || {};
let message = this.migrateMessages[args.type];
for(let key in args){
message = message.replace('$' + key, $.chalk.red(args[key]) );
}
return message;
}
migrateWarn(msg, prop, dotLocation) {
if ( !this.warnedAbout[ msg ] ) {
this.warnedAbout[ msg ] = true;
this.migrateWarnings.push( msg );
if ( console && console.warn ) {
console.warn( utilsModule.getBaseBuildName() + $.chalk.yellow( "Migrate warning: property " + $.chalk.red(prop) + " of " + $.chalk.red(dotLocation) + " is deprecated " + msg) );
if ( this.mergedOptions.migrate.trace && console.trace ) {
console.trace();
}
}
}
}
migrateWarnProp( args ) {
if ( Object.defineProperty ) {
try {
Object.defineProperty( args.obj, args.prop, {
configurable: true,
enumerable: true,
get: function() {
this.migrateWarn( args.msg, args.prop, args.dotLocation );
return args.value;
},
set: function( newValue ) {
this.migrateWarn( args.msg, args.prop, args.dotLocation );
args.value = newValue;
}
});
return;
} catch( err ) {}
}
// obj[ args.prop ] = args.value;
}
} |
JavaScript | class PageResponse {
/**
* Constructs a new <code>PageResponse</code>.
* Represents page information in Roadkill.
* @alias module:model/PageResponse
* @param title {String} The title of the page.
* @param createdBy {String} The user who created the page.
* @param isLocked {Boolean} Whether the page is locked so no edits can be made (except by admins).
* @param tagsAsCsv {String} The list of tags, comma seperated, for the page.
*/
constructor(title, createdBy, isLocked, tagsAsCsv) {
PageResponse.initialize(this, title, createdBy, isLocked, tagsAsCsv);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, title, createdBy, isLocked, tagsAsCsv) {
obj['title'] = title;
obj['createdBy'] = createdBy;
obj['isLocked'] = isLocked;
obj['tagsAsCsv'] = tagsAsCsv;
}
/**
* Constructs a <code>PageResponse</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/PageResponse} obj Optional instance to populate.
* @return {module:model/PageResponse} The populated <code>PageResponse</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PageResponse();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('title')) {
obj['title'] = ApiClient.convertToType(data['title'], 'String');
}
if (data.hasOwnProperty('seoFriendlyTitle')) {
obj['seoFriendlyTitle'] = ApiClient.convertToType(data['seoFriendlyTitle'], 'String');
}
if (data.hasOwnProperty('createdBy')) {
obj['createdBy'] = ApiClient.convertToType(data['createdBy'], 'String');
}
if (data.hasOwnProperty('createdOn')) {
obj['createdOn'] = ApiClient.convertToType(data['createdOn'], 'Date');
}
if (data.hasOwnProperty('lastModifiedBy')) {
obj['lastModifiedBy'] = ApiClient.convertToType(data['lastModifiedBy'], 'String');
}
if (data.hasOwnProperty('lastModifiedOn')) {
obj['lastModifiedOn'] = ApiClient.convertToType(data['lastModifiedOn'], 'Date');
}
if (data.hasOwnProperty('isLocked')) {
obj['isLocked'] = ApiClient.convertToType(data['isLocked'], 'Boolean');
}
if (data.hasOwnProperty('tagsAsCsv')) {
obj['tagsAsCsv'] = ApiClient.convertToType(data['tagsAsCsv'], 'String');
}
if (data.hasOwnProperty('tagList')) {
obj['tagList'] = ApiClient.convertToType(data['tagList'], ['String']);
}
}
return obj;
}
} |
JavaScript | class QualifiedNameCache {
constructor(_model) {
/** @internal */
this._cache = mobx_1.observable.map({}, { deep: false });
/** @internal */
this.listeners = [];
this._model = _model;
}
/**
* @param structureTypeName type name in syntax "MetaModelname$ElementName"
* @param qualifiedName
* @returns The element found, or `null` when no element is found.
*/
resolve(structureTypeName, qualifiedName) {
if (!qualifiedName) {
return null;
}
const elements = this._cache.get(qualifiedName);
if (!elements) {
return null;
}
if (!structureTypeName) {
throw new Error("please provide a structure type name");
}
const initializer = instances_1.instancehelpers.lookupClass(structureTypeName, this._model._allModelClasses());
const result = elements.find(elem => elem instanceof initializer);
return result || null;
}
observe(listener) {
this.listeners.push(listener);
}
size() {
return mobx_1.keys(this._cache)
.map(key => this._cache.get(key).length)
.reduce((prev, curr) => prev + curr, 0);
}
keys() {
return mobx_1.keys(this._cache);
}
/**
* Updates the cache as far as it is affected by the addition or rename of this element.
* Child entries are updated automatically as well.
*/
addStructureToCache(structure) {
structure.traversePublicParts(s => this._addElementToCache(s));
this._callListeners();
}
/**
* Removes the structure and its children from the cache.
*/
removeStructureFromCache(structure) {
structure.traversePublicParts(s => this._removeElementFromCache(s));
this._callListeners();
}
/** @internal */
_callListeners() {
this.listeners.forEach(listener => listener());
}
/** @internal */
_addElementToCache(structure) {
if (instances_1.instancehelpers.structureIsByNameReferrable(structure)) {
const oldName = structure._registeredQualifiedName;
const newName = structure._getQualifiedName();
if (oldName === newName) {
return;
}
structure._registeredQualifiedName = newName;
if (oldName !== null) {
const cachedElementsForOldName = this._cache.get(oldName);
if (cachedElementsForOldName) {
utils_1.utils.removeFromArray(cachedElementsForOldName, structure);
}
}
if (newName === null) {
return;
}
this._getOrCreateEntry(newName).push(structure);
if (oldName !== null) {
this._updateByNameReferences(structure, oldName, newName);
}
}
}
/** @internal */
_removeElementFromCache(structure) {
if (structure instanceof elements_1.AbstractElement && structure._registeredQualifiedName) {
const cachedElements = this._cache.get(structure._registeredQualifiedName);
if (cachedElements) {
utils_1.utils.removeFromArray(cachedElements, structure);
}
}
}
/** @internal */
_updateByNameReferences(namedStructure, oldName, newName) {
const structureInitializer = instances_1.instancehelpers.lookupClass(namedStructure.structureTypeName, this._model._allModelClasses());
const root = namedStructure.model.root;
root.traverse(structure => {
structure.loadedProperties().forEach(prop => {
if (prop instanceof ByNameReferenceProperty_1.ByNameReferenceProperty && prop.qualifiedName() === oldName) {
const propTargetInitializer = instances_1.instancehelpers.lookupClass(prop.targetType, this._model._allModelClasses());
if (propTargetInitializer === structureInitializer || propTargetInitializer.isPrototypeOf(structureInitializer)) {
prop.updateQualifiedNameForRename(newName);
}
}
else if (prop instanceof ByNameReferenceProperty_1.ByNameReferenceListProperty) {
const propTargetInitializer = instances_1.instancehelpers.lookupClass(prop.targetType, this._model._allModelClasses());
if (propTargetInitializer === structureInitializer || propTargetInitializer.isPrototypeOf(structureInitializer)) {
prop.updateQualifiedNamesForRename(prop.qualifiedNames().map(name => (name === oldName ? newName : name)));
}
}
});
});
}
/** @internal */
_getOrCreateEntry(key) {
let result = this._cache.get(key);
if (!result) {
result = mobx_1.observable.array([], { deep: false });
this._cache.set(key, result);
}
return result;
}
} |
JavaScript | class Store {
/**
* Creates an instance of Store.
* @param {Boolean} debug
*/
constructor(debug = false) {
this.debug = debug;
this.state = {};
this.namespaces = {};
this.registerCallback = new RegisterCallback();
this[TICK] = null;
this[MICRO_TASK] = () => {
this.registerCallback.next();
this[TICK] = null;
};
if (debug === true || /* istanbul ignore next */typeof window.aoflDevtools !== 'undefined') {
this.debug = true;
this.state = deepFreeze(this.state);
/* istanbul ignore next */
if (typeof window.aoflDevtools === 'undefined') {
window.aoflDevtools = {};
}
/* istanbul ignore next */
if (!Array.isArray(window.aoflDevtools.storeInstances)) {
window
.aoflDevtools
.storeInstances = [];
}
window.aoflDevtools.storeInstances.push(this);
}
}
/**
* subscribe() register the callback function with registerCallback and returns
* the unsubscribe function.
*
* @param {Furtion} callback
* @return {Function}
*/
subscribe(callback) {
return this.registerCallback.register(callback);
}
/**
* getState() return the current state.
*
* @return {Object}
*/
getState() {
return this.state;
}
/**
*
* @param {SDO} sdo
*/
addState(sdo) {
/* istanbul ignore next */
if (typeof this.namespaces[sdo.namespace] !== 'undefined') {
throw new Error(`${this.constructor.name}: Cannot redefine existing namespace ${sdo.namespace}`);
}
this.namespaces[sdo.namespace] = sdo;
this.commit(sdo.namespace, sdo.initialState || sdo.constructor.initialState);
}
/**
* Copies staged changes to state and notifies subscribers
*/
commit(namespace, subState) {
const state = Object.assign({}, this.state, {
[namespace]: subState
});
this.replaceState(state);
}
/**
* replaceState() take a state object, replaces the state property and notifies subscribers.
*
* @param {Object} state
*/
replaceState(state) {
this.state = state;
if (this.debug) {
this.state = deepFreeze(this.state);
}
this.dispatch();
}
/**
* Resets the state to the initial state of Sdos.
*/
flushState() {
const state = {};
for (const key in this.namespaces) {
/* istanbul ignore next */
if (!Object.hasOwnProperty.call(this.namespaces, key)) continue;
const sdo = this.namespaces[key];
state[sdo.namespace] = Object.assign({}, sdo.constructor.initialState);
}
this.replaceState(state);
}
/**
* Batches all calls to dispatch and notifies subscribers on next tick.
*/
dispatch() {
if (this[TICK]) {
return;
}
this[TICK] = setTimeout(this[MICRO_TASK]);
}
} |
JavaScript | class Control extends Component {
constructor(player, options) {
super(player, options);
this.emitTapEvents();
this.disable = this.options.disable != null? this.options.disable : true;
this.player.on('inited', (e) => {
this.disable = this.options.disable != null? this.options.disable : false;
})
this.element.on({
click : this.onClick.bind(this),
tap : this.onClick.bind(this),
});
this.player.on('inited', this.onPlayerInited.bind(this))
}
/**
* @override
*/
createElement() {
if (this.options.iconName) {
this.icon = new Icon(this.player, {
iconName : this.options.iconName
});
}
let attrs = {
title : this.options.title
}
this.element = $(`<${this.options.tag || 'button'} />`)
.addClass(this.buildCSSClass())
.append(this.icon && this.icon.element)
.attr(attrs);
return this.element;
}
/**
* @override
*/
buildCSSClass() {
let result = `control ${this.options.className} ${super.buildCSSClass()}`;
/**
* @see https://stackoverflow.com/questions/23885255/how-to-remove-ignore-hover-css-style-on-touch-devices
* We should ignore hover effetcs on iphone, because we show hover effect on tap
*/
if(!this.player.hasClass('leplayer--iphone')) {
result += ' control--no-iphone';
}
return result;
}
/**
* @override
*/
set tap(value) {
this.toggleClass('control--tap', value);
}
set disable(value) {
this._disable = value;
this.toggleClass('disabled', value);
}
get disable() {
return this._disable
}
/**
*
* On click event handler
* @abstact
*/
onClick (e) {
e.preventDefault();
if (this.disable) {
return false;
}
this.player.trigger('controlclick', { control : this });
if (typeof this.options.onClick === 'function') {
this.options.onClick.call(this, arguments);
}
}
onPlayerInited (e, data) {
}
static registerControl(name, control) {
if(name == null) {
return;
}
if(Control._controls == null) {
Control._controls = {};
}
Control._controls[name] = control;
return control;
}
static getControl(name) {
if(name == null) {
return;
}
if(Control._controls && Control._controls[name]) {
return Control._controls[name];
}
}
static create(player, name, options) {
var controlClass = this.getControl(name);
if(controlClass == null) {
console.error(`Control ${name} doesn't exist`);
return null;
}
return new controlClass(player, options);
}
} |
JavaScript | class GroupCheckCommand {
static registerCommand() {
Hooks.on('chatMessage', (chatLog, messageText, chatData) => {
let match = this.checkCommand(messageText);
if (match) {
let content = messageText.replace(match[1], '');
log(`Chat command received: "${content}"`);
if (content == 'CREATE') {
new CreateGroupCheck().render(true);
} else {
this.createGroupCheck(content);
}
return false;
}
});
}
static checkCommand(messageText) {
const regex = new RegExp('^(\\/(?:gc|groupcheck) )', 'i');
return messageText.match(regex);
}
static async createGroupCheck(content) {
let parts = content.trim().split(' ');
parts = parts.map(s => s.trim());
let checkDC = undefined;
if (parts.length > 1) {
checkDC = Number.parseInt(parts[parts.length - 1]);
if (checkDC) {
parts.pop();
}
}
return GroupCheck.create({
check_codes: parts,
dc: checkDC
});
};
} |
JavaScript | class ServiceStateManager {
constructor (serviceRequests, $rootScope, $state) {
this.state = '';
this.tableSettings = {
order: '',
reverse: false,
currentPage: 1
};
this.filter = {
isOpen: false,
query: ''
};
this.filterTimeline = {
isOpen: false,
rangeMin: '',
rangeMax: ''
};
this.viewsSettings = {
activeView: ''
};
/* istanbul ignore next */
this.getFilter = function () {
this.checkChangeState();
return this.filter;
};
/* istanbul ignore next */
this.setFilter = function (filter) {
if (typeof filter === "undefined") return;
if (filter.isOpen) {
this.filter.isOpen = filter.isOpen;
} else {
this.filter.isOpen = filter.isOpen;
}
if (filter.query) {
this.filter.query = filter.query;
} else {
this.filter.query = '';
}
};
/* istanbul ignore next */
this.getFilterTimeline = function () {
this.checkChangeState();
return this.filterTimeline;
};
/* istanbul ignore next */
this.setFilterTimeline = function (filterTimeline) {
if (typeof filterTimeline === "undefined") return;
if (filterTimeline.isOpen) {
this.filterTimeline.isOpen = filterTimeline.isOpen;
}
if (filterTimeline.rangeMin) {
this.filterTimeline.rangeMin = filterTimeline.rangeMin;
}
if (filterTimeline.rangeMax) {
this.filterTimeline.rangeMax = filterTimeline.rangeMax;
}
};
/* istanbul ignore next */
this.getTableSettings = function () {
this.checkChangeState();
return this.tableSettings;
};
/* istanbul ignore next */
this.setTableSettings = function (tableSettings) {
if (typeof tableSettings === "undefined") return;
/* istanbul ignore if */
if (tableSettings.order !== undefined) {
this.tableSettings.order = tableSettings.order;
}
if (tableSettings.reverse !== undefined) {
this.tableSettings.reverse = tableSettings.reverse;
}
if (tableSettings.currentPage !== undefined) {
this.tableSettings.currentPage = tableSettings.currentPage;
}
};
/* istanbul ignore next */
this.clearData = function () {
this.tableSettings = {
order: '',
reverse: false,
currentPage: 1
};
this.filter = {
isOpen: false,
query: ''
};
this.filterTimeline = {
isOpen: false,
rangeMin: '',
rangeMax: ''
};
this.viewsSettings = {
activeView: ''
};
};
/* istanbul ignore next */
this.getViewsSettings = function () {
this.checkChangeState();
return this.viewsSettings;
};
/* istanbul ignore next */
this.setViewsSettings = function (viewSettings) {
if (typeof viewSettings === "undefined") return;
/* istanbul ignore if */
if (viewSettings.activeView) {
this.viewsSettings.activeView = viewSettings.activeView;
}
};
/* istanbul ignore next */
this.checkChangeState = function () {
var nameState = $state.router.globals.$current.name.replace(/-(detail|create)/, '');
if (this.state !== nameState) {
this.state = nameState;
this.clearData();
}
};
$rootScope.$on('$locationChangeStart', function(e) {
this.checkChangeState();
}.bind(this));
}
} |
JavaScript | class Strategy {
/**
*
* @param {Number} id
* @param {Array} states
* @param {Number} initIndex - Defines which state is initial
* @param {Array<String>} indicators - Identifiers (names) of indicators
*/
constructor(id, states, initIndex, indicators) {
this.id = id;
this.states = states;
this.state = states[initIndex];
this.indicators = indicators;
// Default setting of strategies transitions
this.transitions = [
{
name: "INIT",
nextStates: [
{
name: "SELL",
predicate: (price, indicators) => price < indicators.get("ma15")
},
{
name: "BUY",
predicate: (price, indicators) => price >= indicators.get("ma15")
}
]
},
{
name: "SELL",
nextStates: [
{
name: "BUY",
predicate: (price, indicators) => price >= indicators.get("ma15")
}
]
},
{
name: "BUY",
nextStates: [
{
name: "SELL",
predicate: (price, indicators) => price < indicators.get("ma15")
}
]
}
];
}
/**
* Reference on indicators
* @returns {Array<String>}
*/
getIndicators() {
return this.indicators;
}
/**
* Updates state by the transition table.
* @param {Number} price
* @param {Map} indicatorsValuesMap
*/
updateState(price, indicatorsValuesMap) {
console.log("price: ");
console.log(price);
console.log("indicatorsValuesMap: ");
console.log(indicatorsValuesMap);
console.log("current state:");
console.log(this.state);
// Loops throught the transitions
for (const t of this.transitions) {
//
// Finds the current state
if (this.state.name == t.name) {
//
// Loops throught the possible next states
for (const ns of t.nextStates) {
//
// Skip the current state
if (ns.name == this.state.name) continue;
//
// If predicate is satisfied
if (ns.predicate(price, indicatorsValuesMap)) {
//
// set the current state and finish update
this.state = this.states.find(obj => {
return obj.name === ns.name;
});
console.log("---- new state:");
console.log(this.state);
// TODO: apply transition function of the state
this.state.applyTransition(price);
return;
}
}
}
}
}
} |
JavaScript | class AccountPolicyController
{
/**
* Retrieve a Account Policy [GET /account-policies/{id}]
*
* @static
* @public
* @param {string} id The Account Policy ID
* @return {Promise<AccountPolicyModel>}
*/
static getOne(id)
{
return new Promise((resolve, reject) => {
RequestHelper.getRequest(`/account-policies/${id}`)
.then((result) => {
let resolveValue = (function(){
return AccountPolicyModel.fromJSON(result);
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Update a Account Policy [PATCH /account-policies/{id}]
*
* @static
* @public
* @param {string} id The Account Policy ID
* @param {AccountPolicyController.UpdateData} updateData The Account Policy Update Data
* @return {Promise<AccountPolicyModel>}
*/
static update(id, updateData)
{
return new Promise((resolve, reject) => {
RequestHelper.patchRequest(`/account-policies/${id}`, updateData)
.then((result) => {
let resolveValue = (function(){
return AccountPolicyModel.fromJSON(result);
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Delete a Account Policy [DELETE /account-policies/{id}]
*
* @static
* @public
* @param {string} id The Account Policy ID
* @return {Promise<boolean>}
*/
static delete(id)
{
return new Promise((resolve, reject) => {
RequestHelper.deleteRequest(`/account-policies/${id}`)
.then((result) => {
resolve(result ?? true);
})
.catch(error => reject(error));
});
}
/**
* List all Account Policies [GET /account-policies]
*
* @static
* @public
* @param {AccountPolicyController.GetAllQueryParameters} [queryParameters] The Optional Query Parameters
* @return {Promise<AccountPolicyModel[]>}
*/
static getAll(queryParameters = {})
{
return new Promise((resolve, reject) => {
RequestHelper.getRequest(`/account-policies`, queryParameters)
.then((result) => {
let resolveValue = (function(){
if(Array.isArray(result) !== true)
{
return [];
}
return result.map((resultItem) => {
return (function(){
return AccountPolicyModel.fromJSON(resultItem);
}());
});
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Create a Account Policy [POST /account-policies]
*
* @static
* @public
* @param {AccountPolicyController.CreateData} createData The Account Policy Create Data
* @return {Promise<AccountPolicyModel>}
*/
static create(createData)
{
return new Promise((resolve, reject) => {
RequestHelper.postRequest(`/account-policies`, createData)
.then((result) => {
let resolveValue = (function(){
return AccountPolicyModel.fromJSON(result);
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
} |
JavaScript | class Installation extends Resource {
/**
* Return API endpoint for this application
*/
url(...args) {
return super.url('installation', ...args);
}
/**
* List repositroy for an user or all.
* @param {String} userID?
* @return {Authorization}
*/
repos(userID, options = {}) {
const params = {};
if (userID) {
params.user_id = userID;
}
return this.page('repositories', params, {
...options,
headers: DEFAULT_HEADERS
});
}
} |
JavaScript | class Inspections extends BaseRecordUtils {
/**
* Creates an instance of Inspections.
*
* @param {*} auth_payload user information for auditing
* @param {*} recordType an item from record-type-enum.js -> RECORD_TYPE
* @param {*} csvRow an object containing the values from a single csv row.
* @memberof Inspections
*/
constructor(auth_payload, recordType, csvRow) {
super(auth_payload, recordType, csvRow);
}
/**
* Convert the csv row object into the object expected by the API record post/put controllers.
*
* @returns a inspection object matching the format expected by the API record post/put controllers.
* @memberof Inspections
*/
transformRecord(csvRow) {
if (!csvRow) {
throw Error('transformRecord - required csvRow must be non-null.');
}
csvRow = this.cleanCsvRow(csvRow);
const inspection = { ...super.transformRecord(csvRow) };
inspection['_sourceRefOgcInspectionId'] = csvRow['inspection number'] || null;
inspection['_sourceRefOgcDeficiencyId'] = csvRow['deficiency objectid'] || null;
inspection['recordType'] = RECORD_TYPE.Inspection.displayName;
try {
inspection['dateIssued'] = csvRow['inspection date'] ? moment.tz(csvRow['inspection date'], "DD-MMM-YYYY", "America/Vancouver").toDate() : null;
} catch (error) {
defaultLog.debug(csvRow['inspection date'] + ' is not in the expected format DD-MMM-YYYY');
defaultLog.debug(error);
inspection['dateIssued'] = null;
}
inspection['issuingAgency'] = 'BC Oil and Gas Commission';
inspection['author'] = 'BC Oil and Gas Commission';
inspection['recordName'] =
(csvRow['inspection number'] && `Inspection Number ${csvRow['inspection number']}`) || '-';
inspection['legislation'] = {
act: 'Oil and Gas Activities Act',
section: '57',
subSection: '4'
};
inspection['issuedTo'] = {
type: 'Company',
companyName: csvRow['operator'] || ''
};
const projectDetails = CsvUtils.getProjectNameAndEpicProjectId(csvRow);
// Only update NRPTI project details if the csv contains known project information
if (projectDetails) {
inspection['projectName'] = projectDetails.projectName;
inspection['_epicProjectId'] =
(projectDetails._epicProjectId && new ObjectID(projectDetails._epicProjectId)) || null;
}
inspection['location'] = 'British Columbia';
inspection['legislationDescription'] = 'Inspection to verify compliance with regulatory requirement';
inspection['outcomeDescription'] = CsvUtils.getOutcomeDescription(csvRow);
inspection['description'] =
'Inspection to verify compliance with regulatory requirements. ' + CsvUtils.getOutcomeDescription(csvRow);
inspection['summary'] = (csvRow['inspection number'] && `Inspection Number ${csvRow['inspection number']}`) || '-';
return inspection;
}
/**
* The OGC csv contains `-` in place of empty fields, which need to be replaced with proper empty values.
*
* @param {*} csvRow
* @returns csvRow with filler `-` removed
* @memberof Inspections
*/
cleanCsvRow(csvRow) {
if (!csvRow) {
return null;
}
Object.entries(csvRow).forEach(([key, value]) => {
if (value === '-') {
csvRow[key] = '';
} else {
csvRow[key] = value;
}
});
return csvRow;
}
} |
JavaScript | class UiModule {
/**
* @param {ClickToDialApp} app - The application object.
*/
constructor(app) {
this.app = app
$(() => {
this.addListeners()
})
Object.assign(Object.getPrototypeOf(this), ui())
}
addListeners() {
// The popout behaves different from the popover. The contacts
// widget is open by default.
if (this.app.env.isExtension && this.app.env.role.popout) $('html').addClass('popout')
this._$ = {}
this._$.allViews = $('.view')
this._$.telemetryView = $('.telemetry-opt-in')
this._$.loginView = $('.login-section')
if (this.app.store.get('user') && this.app.store.get('username') && this.app.store.get('token')) {
this._$.currentView = $('.view-app')
} else {
this._$.currentView = $('.view-login')
}
this.app.on('ui:widget.close', (data) => {
// Popout has only the contacts widget open. It can't be closed.
if (!this.app.env.isExtension || (this.app.env.isExtension && !this.app.env.role.popout)) {
this.closeWidget(data.name)
}
})
this.app.on('ui:widget.busy', (data) => {
this.busyWidget(data.name)
})
this.app.on('ui.widget.open', (data) => {
this.openWidget(data.name)
})
this.app.on('ui:widget.reset', (data) => {
this.resetWidget(data.name)
})
this.app.on('ui:widget.unauthorized', (data) => {
this.unauthorizeWidget(data.name)
})
this.app.on('ui:mainpanel.loading', (data) => {
$('#refresh').addClass('fa-spin')
})
// Spin refresh icon while reloading widgets.
this.app.on('ui:mainpanel.ready', (data) => {
setTimeout(() => {
$('#refresh').removeClass('fa-spin')
}, 1000)
})
/**
* Toggles the widget's content visibility when clicking its header.
* Popout has only the contacts widget open and it can't be closed.
*/
if (!this.app.env.isExtension || (this.app.env.isExtension && !this.app.env.role.popout)) {
$('html').on('click', '.widget .widget-header', (e) => {
let widget = $(e.currentTarget).closest('[data-opened]')
if (this.isWidgetOpen(widget)) {
if (!$(e.target).is(':input')) {
this.app.emit('ui:widget.close', {
name: $(widget).data('widget'),
})
this.closeWidget(widget)
}
} else {
this.openWidget(widget)
}
})
}
$('#close').click((e) => {
this._checkCloseMainPanel()
})
/**
* Emit that we want to logout.
*/
$('#logout').click((e) => {
this.app.emit('user:logout.attempt')
})
$('#popout').click((e) => {
browser.tabs.create({url: browser.runtime.getURL('index.html?popout=true')})
this._checkCloseMainPanel()
})
$('#help').click((e) => {
this.app.emit('help')
this._checkCloseMainPanel()
})
$('#refresh').click((e) => {
this.app.emit('ui:ui.refresh')
})
$('#settings').click((e) => {
this.app.emit('ui:settings')
this._checkCloseMainPanel()
})
if (!this.app.store.validSchema()) {
this.app.emit('user:logout.attempt')
}
this._$.telemetryView.find('.js-telemetry-allow').on('click', (e) => {
this.app.emit('telemetry', {enabled: true})
this.showActiveView()
})
this._$.telemetryView.find('.js-telemetry-deny').on('click', (e) => {
this.app.emit('telemetry', {enabled: false})
this.showActiveView()
})
// Show the telemetry view if the user didn't make a choice yet.
if (this.app.store.get('telemetry') === null) this.showTelemetryView()
else this.showActiveView()
// Focus the first input field.
$(window).on('load', () => {
// Keep track whether this popup is open or closed.
this.app.store.set('isMainPanelOpen', true)
// setTimeout fix for FireFox.
setTimeout(() => {
$('.login-form :input:visible:first').focus()
}, 100)
})
$(window).on('unload', () => {
this.app.store.set('isMainPanelOpen', false)
})
}
/**
* Display a loading indicator on the widget, used when
* retrieving data for widget.
* @param {String} widgetOrWidgetName - Reference to widget to set to busy.
*/
busyWidget(widgetOrWidgetName) {
let widget = this.getWidget(widgetOrWidgetName)
if (!widget) return
const data = widget.data()
this.app.logger.debug(`${this}set ui state for widget '${data.widget}' to busy`)
this.resetWidget(widget)
$(widget).addClass('busy')
// The popout doesn't change the open/closed status of ANY widget.
if (this.app.env.isExtension && this.app.env.role.popout) return
if (this.isWidgetOpen(widget)) {
this.openWidget(widget)
}
}
/**
* Popup action; used to close a widget by setting some DOM properties.
* @param {String} widgetOrWidgetName - Reference to widget to close.
*/
closeWidget(widgetOrWidgetName) {
let widget = this.getWidget(widgetOrWidgetName)
// Cannot rely on just data.('opened') because this is
// not transparent to CSS.
$(widget).data('opened', false).attr('data-opened', false)
}
/**
* Get the element for a widget by return the same (already a jquery)
* object or finding it by class name.
* @param {String} widgetOrWidgetName - Reference to widget to find.
* @returns {Jquery} - Selector to the widget container.
*/
getWidget(widgetOrWidgetName) {
if (widgetOrWidgetName instanceof $) {
return widgetOrWidgetName
}
return $(`.container:not(.static) .widget.${widgetOrWidgetName}`)
}
/**
* Return a boolean indicating whether widget is open.
* @param {String} widgetOrWidgetName - Reference to widget to check.
* @returns {Boolean} - Whether the widget is currently open or not.
*/
isWidgetOpen(widgetOrWidgetName) {
let widget = this.getWidget(widgetOrWidgetName)
return $(widget).data('opened') === true
}
/**
* Open/close a widget's content and resize.
* @param {String} widgetOrWidgetName - Reference to widget to open.
*/
openWidget(widgetOrWidgetName) {
let widget = this.getWidget(widgetOrWidgetName)
const data = widget.data()
this.app.logger.debug(`${this}open widget ${data.widget}`)
let widgetState = this.app.store.get('widgets') ? this.app.store.get('widgets') : {}
if (!widgetState.isOpen) widgetState.isOpen = {}
// Opening widgets act as an accordeon. All other widgets are closed,
// except the widget that needs to be open.
for (const widgetName of ['contacts', 'availability', 'queues']) {
let _widget = this.getWidget(widgetName)
if (widgetName !== data.widget) {
widgetState.isOpen[widgetName] = false
this.closeWidget(widgetName)
} else {
widgetState.isOpen[widgetName] = true
$(_widget).data('opened', true).attr('data-opened', true)
}
}
this.app.store.set('widgets', widgetState)
this.app.emit('ui:widget.open', {name: data.widget})
}
/**
* Set the busy indicator.
* @param {String} widgetOrWidgetName - Reference to widget to reset.
*/
resetWidget(widgetOrWidgetName) {
let widget = this.getWidget(widgetOrWidgetName)
const data = widget.data()
this.app.logger.debug(`${this}resetting ui state for widget '${data.widget}'`)
$(widget).removeClass('busy').removeClass('unauthorized')
}
/**
* Restore the widget state from localstorage.
*/
restoreWidgetState() {
// The popout doesn't change the open/closed status of ANY widget.
if (this.app.env.isExtension && this.app.env.role.popout) return
let widgetState = this.app.store.get('widgets')
if (widgetState && widgetState.isOpen) {
for (const moduleName of Object.keys(widgetState.isOpen)) {
if (widgetState.isOpen[moduleName]) this.openWidget(moduleName)
else this.closeWidget(moduleName)
}
}
}
/**
* Set the login view when the user is not authenticated or the
* application view for an authenticated user.
*/
showActiveView() {
// Switch between logged-in and login state.
if (this.app.store.get('user') && this.app.store.get('username') && this.app.store.get('token')) {
this.app.emit('ui:ui.restore')
$('#user-name').text(this.app.store.get('username'))
this.showAppView()
} else {
this.showLoginView()
}
}
/**
* Shows the application view for authenticated users.
*/
showAppView() {
this._$.allViews.addClass('hide').filter('.view-app').removeClass('hide')
this.restoreWidgetState()
// This is an OSX-related racing bug, caused by the popup animation
// that prevents the popup height to be calculated properly.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=307912
// for more information.
if (this.app.env.isOsx) {
setTimeout(() => {
// Don't set the width when the html has a popout class
// because the popout is responsible and has a fluid width.
if (!$('html').hasClass('popout')) {
const width = $('body').width()
$('body').width(width + 1)
}
}, 150)
}
}
/**
* Shows the login view for unauthenticated users.
*/
showLoginView() {
this._$.allViews.addClass('hide').filter('.view-login').removeClass('hide')
}
/**
* Shows the login view for unauthenticated users.
*/
showTwoFactorView() {
this._$.allViews.addClass('hide').filter('.view-two-factor').removeClass('hide')
}
/**
* Shows the telemetry consent view.
*/
showTelemetryView() {
this._$.allViews.addClass('hide').filter('.view-telemetry').removeClass('hide')
}
toString() {
return `${this.app}[ui] `
}
/**
* Show the unauthorized warning for a widget.
* @param {String} widgetOrWidgetName - Reference to widget to set to
* unauthorized.
*/
unauthorizeWidget(widgetOrWidgetName) {
const widget = this.getWidget(widgetOrWidgetName)
this.resetWidget(widget)
widget.addClass('unauthorized')
}
/**
* Called when an external action occurs, like opening a new tab,
* which requires to shift the focus of the user to the new
* content. Don't close the existing window when it is called
* from the popout.
*/
_checkCloseMainPanel() {
this.app.emit('ui:mainpanel.close')
// Only close the existing window.
if (this.app.env.isExtension && !this.app.env.role.popout) {
window.close()
}
}
} |
JavaScript | class Cylinder extends Generable {
/**
* Protected method to actually build the cylinder.
*
* @param {number} precision the precision to use when generating the shape
*
* @returns {vertexes, uvs, normals, tangents, triangles, lines}
*/
static _build(precision) {
precision = Math.max(precision, 5);
const vertexes = [];
const uvs = [];
const normals = [];
const tangents = [];
const triangles = [];
let lines = [];
// Precision represents the num of vertical slices
const step = toRad(360 / (precision - 1));
for (let i = 0; i < precision; ++i) {
// Each slice has fixed angle
const angle = i * step;
const sin = Math.sin(angle);
const cos = Math.cos(angle);
// Creates slice vertexes
vertexes.push(new Vec3( 0, +1, 0)); // Top central vertex
vertexes.push(new Vec3(cos, +1, sin)); // Top side vertex (1)
vertexes.push(new Vec3(cos, +1, sin)); // Top side vertex (2)
vertexes.push(new Vec3(cos, -1, sin)); // Bottom side vertex (1)
vertexes.push(new Vec3(cos, -1, sin)); // Bottom side vertex (2)
vertexes.push(new Vec3( 0, -1, 0)); // Bottom central vertex
normals.push(new Vec3(0, +1, 0));
normals.push(new Vec3(0, +1, 0));
normals.push(new Vec3(cos, 0, sin).normalize());
normals.push(new Vec3(cos, 0, sin).normalize());
normals.push(new Vec3(0, -1, 0));
normals.push(new Vec3(0, -1, 0));
}
// Num of vertexes per slice
const N = 6;
// Generates 4 triangles for each slice
for (let i = 0; i < precision; ++i) {
// Index begin for vertexes of this slice (i-th)
const b = i * N;
// Index begin for vertexes of the next slice
const n = ((i + 1) % precision) * N;
// Create faces
triangles.push(new Vec3(b + 0, b + 1, n + 1)); // Top face
triangles.push(new Vec3(b + 2, b + 3, n + 2)); // Side quad (1)
triangles.push(new Vec3(b + 3, n + 2, n + 3)); // Side quad (2)
triangles.push(new Vec3(b + 4, b + 5, n + 4)); // Bottom face
}
// TODO
uvs.push(...new Array(vertexes.length).fill(Vec2.Zeros()));
tangents.push(...new Array(vertexes.length).fill(Vec3.Zeros()));
// Lines
lines = LinesFromTriangles(vertexes, triangles);
// To ensure height and diameter of 1
vertexes.forEach((v) => v.div(2));
return { vertexes, uvs, normals, tangents, triangles, lines };
}
} |
JavaScript | class GraphMap extends Component {
state = {
allCoords: [],
allLinks: [],
clickedDescription: '',
clickedTitle: '',
coords: { x: 50, y: 60 },
cooldown: 2,
description: '',
encumbrance: null,
error: '',
exits: [],
items: [],
isClicked: false,
isExploring: false,
generating: false,
gold: null,
graph: {},
graphLoaded: false,
inventory: [],
inverse: { n: 's', s: 'n', w: 'e', e: 'w' },
loaded: false,
messages: [],
name: '',
players: [],
progress: 0,
room_id: null,
speed: null,
strength: null,
title: '',
visited: new Set()
};
// LIFE CYCLE METHODS
componentDidMount() {
if (!localStorage.hasOwnProperty('graph')) {
localStorage.setItem('graph', JSON.stringify(data));
}
let value = JSON.parse(localStorage.getItem('graph'));
this.setState({ graph: value, graphLoaded: true });
this.init();
}
componentDidUpdate(prevState) {
if (!this.state.allCoords.length && this.state.graph) {
this.mapLinks();
this.mapCoords();
this.updateProgress();
setTimeout(() => this.setState({ loaded: true }), 3000);
}
}
// Init methods
// used to update the loading bar
updateProgress = async (ms = 10) => {
while (this.state.progress <= 100) {
await this.setState(prevState => ({
progress: (prevState.progress += 1)
}));
await this.wait(ms);
}
};
// inits player location and status
init = async () => {
const { cooldown } = this.state;
await this.getLocation();
await this.wait(1000 * cooldown);
await this.getStatus();
};
// API METHODS (The name describes what they do)
changeName = async () => {
try {
const res = await axios({
method: 'post',
url: 'https://lambda-treasure-hunt.herokuapp.com/api/adv/change_name/',
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
},
data: {
name: 'Pirate Ry'
}
});
console.log(res.data);
this.setState({ messages: [...res.data.messages] }, () =>
this.wait(1000 * res.data.cooldown).then(() => this.getStatus())
);
} catch (err) {
console.log('There was an error.');
console.dir(err);
}
};
dash = async (direction, num_rooms, next_room_ids) => {
try {
const res = await axios({
method: 'post',
url: 'https://lambda-treasure-hunt.herokuapp.com/api/adv/dash/',
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
},
data: {
direction,
num_rooms,
next_room_ids
}
});
console.log(res.data);
this.setState(
{
messages: [...res.data.messages],
cooldown: res.data.cooldown,
room_id: res.data.room_id,
description: res.data.description,
players: [...res.data.players],
items: [...res.data.items]
},
() => this.wait(1000 * res.data.cooldown).then(() => this.getStatus())
);
} catch (err) {
console.log('There was an error.');
console.dir(err);
}
};
examine = async name => {
try {
const res = await axios({
method: 'post',
url: 'https://lambda-treasure-hunt.herokuapp.com/api/adv/examine/',
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
},
data: {
name
}
});
this.setState({
clickedTitle: res.data.name,
clickedDescription: res.data.description,
cooldown: res.data.cooldown,
isClicked: true
});
} catch (err) {
console.log('There was an error.');
console.dir(err);
}
};
flyToRooms = async (move, next_room_id = null) => {
let data;
if (next_room_id !== null) {
data = {
direction: move,
next_room_id: next_room_id.toString()
};
} else {
data = {
direction: move
};
}
try {
const res = await axios({
method: 'post',
url: `https://lambda-treasure-hunt.herokuapp.com/api/adv/fly/`,
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
},
data
});
let previous_room_id = this.state.room_id;
// Update graph
let graph = this.updateGraph(
res.data.room_id,
this.parseCoords(res.data.coordinates),
res.data.exits,
previous_room_id,
move
);
this.setState({
room_id: res.data.room_id,
coords: this.parseCoords(res.data.coordinates),
exits: [...res.data.exits],
cooldown: res.data.cooldown,
messages: [...res.data.messages],
description: res.data.description,
title: res.data.title,
players: [...res.data.players],
items: [...res.data.items],
graph
});
console.log(res.data);
await this.wait(1000 * res.data.cooldown);
} catch (error) {
console.log('Something went wrong moving...');
console.dir(error);
this.setState({
cooldown: error.response.data.cooldown,
messages: [...error.response.data.errors],
isExploring: false
});
throw error;
}
};
getLocation = async () => {
try {
const res = await axios({
method: 'get',
url: 'https://lambda-treasure-hunt.herokuapp.com/api/adv/init/',
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
}
});
console.log(res.data);
let graph = this.updateGraph(
res.data.room_id,
this.parseCoords(res.data.coordinates),
res.data.exits
);
this.setState(prevState => ({
room_id: res.data.room_id,
coords: this.parseCoords(res.data.coordinates),
cooldown: res.data.cooldown,
exits: [...res.data.exits],
description: res.data.description,
title: res.data.title,
players: [...res.data.players],
items: [...res.data.items],
graph
}));
this.updateVisited();
} catch (err) {
console.log('There was an error.');
console.dir(err);
this.setState({ cooldown: err.response.data.cooldown });
}
};
getStatus = async () => {
try {
const res = await axios({
method: 'post',
url: 'https://lambda-treasure-hunt.herokuapp.com/api/adv/status/',
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
}
});
console.log(res.data);
this.setState(prevState => ({
name: res.data.name,
cooldown: res.data.cooldown,
encumbrance: res.data.encumbrance,
strength: res.data.strength,
speed: res.data.speed,
gold: res.data.gold,
inventory: [...res.data.inventory],
status: [...res.data.status],
errors: [...res.data.errors]
}));
} catch (err) {
console.log('There was an error.');
console.dir(err);
}
};
moveRooms = async (move, next_room_id = null) => {
let data;
if (next_room_id !== null) {
data = {
direction: move,
next_room_id: next_room_id.toString()
};
} else {
data = {
direction: move
};
}
try {
const res = await axios({
method: 'post',
url: `https://lambda-treasure-hunt.herokuapp.com/api/adv/move/`,
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
},
data
});
let previous_room_id = this.state.room_id;
// Update graph
let graph = this.updateGraph(
res.data.room_id,
this.parseCoords(res.data.coordinates),
res.data.exits,
previous_room_id,
move
);
this.setState({
room_id: res.data.room_id,
coords: this.parseCoords(res.data.coordinates),
exits: [...res.data.exits],
cooldown: res.data.cooldown,
messages: [...res.data.messages],
description: res.data.description,
title: res.data.title,
players: [...res.data.players],
items: [...res.data.items],
graph
});
console.log(res.data);
} catch (error) {
console.log('Something went wrong moving...');
console.dir(error);
}
};
prayToShrine = async () => {
try {
const res = await axios({
method: 'post',
url: 'https://lambda-treasure-hunt.herokuapp.com/api/adv/pray/',
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
}
});
console.log(res.data);
this.setState({ messages: [...res.data.messages] }, () =>
this.wait(1000 * res.data.cooldown).then(() => this.getStatus())
);
} catch (err) {
console.log('There was an error.');
console.dir(err);
}
};
sellTreasure = async name => {
try {
const res = await axios({
method: 'post',
url: 'https://lambda-treasure-hunt.herokuapp.com/api/adv/sell/',
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
},
data: {
name,
confirm: 'yes'
}
});
console.log(res);
this.setState({
messages: [...res.data.messages],
cooldown: res.data.cooldown
});
await this.wait(1000 * res.data.cooldown);
} catch (err) {
console.log('There was an error.');
console.dir(err);
this.setState({ cooldown: err.response.data.cooldown });
throw new Error(err.response.data.errors[0]);
}
};
takeTreasure = async name => {
try {
const res = await axios({
method: 'post',
url: 'https://lambda-treasure-hunt.herokuapp.com/api/adv/take/',
headers: {
Authorization: 'Token 895925acf149cba29f6a4c23d85ec0e47d614cdb'
},
data: {
name
}
});
console.log(res.data);
this.setState({
messages: [...res.data.messages],
items: [...res.data.items],
players: [...res.data.players],
cooldown: res.data.cooldown
});
await this.wait(1000 * res.data.cooldown);
} catch (err) {
console.log('There was an error.');
console.dir(err);
this.setState({ cooldown: err.response.data.cooldown });
throw err;
}
};
// AUTOMATED METHODS
/*
This my looping function. It searches for treasure and picks it up when it finds it. When encumbrance gets too high, it returns to the shop to sell items, then returns to finding treasure.
*/
exploreMap = async () => {
const { cooldown, graph, isExploring, room_id, items } = this.state;
let exits = [...this.state.exits];
let random = Math.floor(Math.random() * exits.length);
let nextRoom = graph[room_id][1][exits[random]];
if (isExploring) {
if (this.state.encumbrance >= 9) {
this.travelToShop()
.then(() => this.sellAllTreasure())
.then(() => this.exploreMap());
} else if (items.length) {
this.takeAllTreasures().then(() => this.exploreMap());
} else {
// await this.wait(1000 * cooldown);
this.flyToRooms(exits[random], nextRoom).then(() => {
console.log(cooldown);
this.exploreMap();
});
}
}
};
/*
This automates selling multiple treasures to the store.
*/
sellAllTreasure = async () => {
const { inventory } = this.state;
for (let treasure of inventory) {
await this.sellTreasure(treasure);
}
await this.getStatus();
};
/*
This actually only takes one treasure, getting multiple from a room is in the explore logic. Will update.
*/
takeAllTreasures = async () => {
const { items } = this.state;
for (let treasure of items) {
await this.takeTreasure(treasure);
}
await this.getStatus();
};
/*
Finds the shortest path to the shop and then moves there.
*/
travelToShop = async () => {
const path = this.findShortestPath(this.state.room_id, 1);
console.log(path);
if (typeof path === 'string') {
console.log(path);
} else {
for (let direction of path) {
console.log(direction);
for (let d in direction) {
// await this.wait(1000 * this.state.cooldown);
await this.flyToRooms(d, direction[d]);
}
}
}
};
/*
This was my traversal logic to populate the graph. I want to insert part of this back into my Explore method to account for new connections. On the to-do list.
*/
traverseMap = () => {
let count = 1;
let unknownDirections = this.getUnknownDirections();
console.log(`UNKNOWN DIRECTIONS: ${unknownDirections}`);
if (unknownDirections.length) {
let move = unknownDirections[0];
this.moveRooms(move);
} else {
let path = this.findShortestPath();
if (typeof path === 'string') {
console.log(path);
} else {
for (let direction of path) {
console.log(direction);
for (let d in direction) {
setTimeout(() => {
this.moveRooms(d, direction[d]);
}, this.state.cooldown * 1000 * count);
count++;
}
}
}
}
if (this.state.visited.size < 499) {
setTimeout(this.traverseMap, this.state.cooldown * 1000 * count + 1000);
this.updateVisited();
count = 1;
} else {
console.log('Traversal Complete');
this.setState({ generating: false });
}
};
// HELPER MATHODS
/*
Breadth First Search algorithm to find the shortest path.
*/
findShortestPath = (start = this.state.room_id, target = '?') => {
let { graph } = this.state;
let queue = [];
let visited = new Set();
for (let room in graph[start][1]) {
queue = [...queue, [{ [room]: graph[start][1][room] }]];
}
while (queue.length) {
let dequeued = queue.shift();
let last_room = dequeued[dequeued.length - 1];
for (let exit in last_room) {
if (last_room[exit] === target) {
if (target === '?') {
dequeued.pop();
}
dequeued.forEach(item => {
for (let key in item) {
graph[item[key]][0].color = '#9A4F53';
}
});
return dequeued;
} else {
visited.add(last_room[exit]);
for (let path in graph[last_room[exit]][1]) {
if (visited.has(graph[last_room[exit]][1][path]) === false) {
let path_copy = Array.from(dequeued);
path_copy.push({ [path]: graph[last_room[exit]][1][path] });
queue.push(path_copy);
}
}
}
}
}
return 'That target does not exisit.';
};
/*
Gets directions unknown to node in graph
*/
getUnknownDirections = () => {
let unknownDirections = [];
let directions = this.state.graph[this.state.room_id][1];
for (let direction in directions) {
if (directions[direction] === '?') {
unknownDirections.push(direction);
}
}
return unknownDirections;
};
/*
This takes the graph data and puts the necessary info into an array to be used by the map component.
*/
mapCoords = () => {
const { graph, room_id } = this.state;
const setCoords = [];
for (let room in graph) {
let data = graph[room][0];
// eslint-disable-next-line
if (room != room_id) {
data.color = '#525959';
}
setCoords.push(data);
}
this.setState({ allCoords: setCoords });
};
/*
This takes the graph data and puts the necessary info into an array to be used by the map component for the edges.
*/
mapLinks = () => {
const { graph } = this.state;
const setLinks = [];
for (let room in graph) {
for (let linkedRoom in graph[room][1]) {
setLinks.push([graph[room][0], graph[graph[room][1][linkedRoom]][0]]);
}
}
this.setState({ allLinks: setLinks });
};
/*
Gets the correct format for coords from the graph data.
*/
parseCoords = coords => {
const coordsObject = {};
const coordsArr = coords.replace(/[{()}]/g, '').split(',');
coordsArr.forEach(coord => {
coordsObject['x'] = parseInt(coordsArr[0]);
coordsObject['y'] = parseInt(coordsArr[1]);
});
return coordsObject;
};
/*
This handles updating the graph at any point when it changes including color things.
*/
updateGraph = (id, coords, exits, previous_room_id = null, move = null) => {
const { inverse } = this.state;
let graph = Object.assign({}, this.state.graph);
// Make node if none
if (!this.state.graph[id]) {
let payload = [];
payload.push(coords);
const moves = {};
exits.forEach(exit => {
moves[exit] = '?';
});
payload.push(moves);
graph = { ...graph, [id]: payload };
}
if (
previous_room_id !== null &&
move &&
previous_room_id !== id &&
graph[previous_room_id][1][move] === '?'
) {
graph[previous_room_id][1][move] = id;
graph[id][1][inverse[move]] = previous_room_id;
}
if (previous_room_id !== null) {
graph[previous_room_id][0].color = '#525959';
graph[id][0].color = '#7dcdbe';
} else {
graph[0][0].color = '#525959';
graph[id][0].color = '#7dcdbe';
}
localStorage.setItem('graph', JSON.stringify(graph));
return graph;
};
/*
A method that kept track of how many graph nodes were fully explored.
*/
updateVisited = () => {
// UPDATE PROGRESS
let visited = new Set(this.state.set);
for (let key in this.state.graph) {
if (!visited.has(key)) {
let qms = [];
for (let direction in key) {
if (key[direction] === '?') {
qms.push(direction);
}
}
if (!qms.length) {
visited.add(key);
}
}
}
let progress = Math.round((visited.size / 500) * 100);
this.setState({ visited, progress });
};
/*
A life saver! This wraps setTimeout in a promise turning it into and async function
*/
wait = async ms => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
// EVENT METHODS
manualMove = move => {
const { graph, room_id } = this.state;
if (graph[room_id][1][move] || graph[room_id][1][move] === 0) {
this.flyToRooms(move, graph[room_id][1][move]);
} else {
this.setState({ messages: ["You can't go that way."] });
}
};
// DASH... Figuring it out
// dashToNode = async node => {
// const path = this.findShortestPath(this.state.room_id, node);
// console.log(path);
// if (typeof path === 'string') {
// console.log(path);
// } else {
// console.log('path');
// let arr = [];
// let string;
// for (let direction of path) {
// for (let d in direction) {
// arr.push(direction[d]);
// string = arr.join(',');
// console.log(string);
// }
// }
// this.dash('s', arr.length.toString(), string);
// }
// };
/*
Finds the shortest path to a node clicked on and travels there.
*/
travelToNode = async node => {
const path = this.findShortestPath(this.state.room_id, node);
console.log(path);
if (typeof path === 'string') {
console.log(path);
} else {
console.log('path');
for (let direction of path) {
for (let d in direction) {
await this.flyToRooms(d, direction[d]);
}
}
}
};
/*
The logic for handling the init and stopping of the Explore function.
*/
handleClick = () => {
const { isExploring } = this.state;
// this.prayToShrine();
// this.getStatus();
// this.travelToNode(461);
if (isExploring) {
this.setState({
isExploring: false,
messages: ['Stopped auto exploring.']
});
} else {
this.setState({ isExploring: true }, () =>
this.wait(1000 * this.state.cooldown).then(() => this.exploreMap())
);
}
};
handleClickable = () => this.setState({ isClicked: false });
render() {
const {
clickedDescription,
clickedTitle,
coords,
description,
encumbrance,
gold,
graph,
inventory,
isClicked,
isExploring,
items,
loaded,
messages,
name,
players,
progress,
room_id,
speed,
strength,
title,
travelToNode
} = this.state;
return (
<StyledGraphMap onKeyPress={this.handleKeyPress}>
{loaded ? (
<>
<Map
coords={this.state.allCoords}
graph={graph}
links={this.state.allLinks}
travelToNode={this.travelToNode}
/>
<Sidebar
clickedDescription={clickedDescription}
clickedTitle={clickedTitle}
coords={coords}
description={description}
encumbrance={encumbrance}
examine={this.examine}
gold={gold}
handleClickable={this.handleClickable}
inventory={inventory}
isClicked={isClicked}
items={items}
name={name}
players={players}
room_id={room_id}
speed={speed}
strength={strength}
title={title}
travelToNode={travelToNode}
/>
<Bottombar
inventory={inventory}
isExploring={isExploring}
items={items}
manualMove={this.manualMove}
messages={messages}
onclick={this.handleClick}
sellTreasure={this.sellAllTreasure}
takeTreasure={this.takeAllTreasures}
travelToShop={this.travelToShop}
/>
</>
) : (
<Loading progress={progress} />
)}
</StyledGraphMap>
);
}
} |
JavaScript | class MeshInsert {
constructor() {
this.selectControl = document.querySelector('#insert select');
this.bindEvents();
}
/**
* Attaches events to various controls
*/
bindEvents() {
document.querySelector('#insert .btn-primary').addEventListener('click', debounce(() => { this.insertSelectedMesh() }, 250));
}
/**
* According to the selected mesh type, a new mesh is inserted into the scene
*/
insertSelectedMesh() {
const entityName = this.selectControl.value;
switch (entityName.toUpperCase()) {
case MESH_TYPES.WALL:
Config.addWall();
break;
case MESH_TYPES.POLE:
Config.addPole();
break;
case MESH_TYPES.ROOF:
Config.addRoof();
break;
case MESH_TYPES.DOOR:
Config.addDoor();
break;
default:
Utils.displayError('Invalid mesh type.');
break;
}
}
} |
JavaScript | class Driver extends (0, _hasEngine.default)() {
/**
* Add event listener.
*
* @param {string} event - The event to listen.
* @param {Function} listener - The listener.
* @returns {events.services.Dispatcher.drivers.Driver} The current driver instance.
* @abstract
*/
on(event, listener) {
// eslint-disable-line no-unused-vars
throw new _NotImplementedError.default(this, 'on', 'Driver');
}
/**
* Remove event listener for single listener.
*
* @param {string} event - The event that has been listen.
* @param {Function} listener - The listener.
* @returns {events.services.Dispatcher.drivers.Driver} The current driver instance.
* @abstract
*/
off(event, listener) {
// eslint-disable-line no-unused-vars
throw new _NotImplementedError.default(this, 'off', 'Driver');
}
/**
* Add event listener for first event dispatch only.
*
* @param {string} event - The event to listen.
* @param {Function} listener - The listener.
* @returns {events.services.Dispatcher.drivers.Driver} The current driver instance.
* @abstract
*/
once(event, listener) {
// eslint-disable-line no-unused-vars
throw new _NotImplementedError.default(this, 'once', 'Driver');
}
/**
* Dispatch an event with a given payload.
*
* @param {string} event - The event to dispatch.
* @param {*} [payload] - The payload to send into the listeners.
* @returns {events.services.Dispatcher.drivers.Driver} The current driver instance.
* @abstract
*/
emit(event, payload) {
// eslint-disable-line no-unused-vars
throw new _NotImplementedError.default(this, 'emit', 'Driver');
}
/**
* Remove listeners for a given event.
*
* @param {string} event - The event that has been listen.
* @returns {events.services.Dispatcher.drivers.Driver} The current driver instance.
* @abstract
*/
removeListeners(event) {
// eslint-disable-line no-unused-vars
throw new _NotImplementedError.default(this, 'removeListeners', 'Driver');
}
/**
* Remove all listeners for all events.
*
* @returns {events.services.Dispatcher.drivers.Driver} The current driver instance.
* @abstract
*/
removeAllListeners() {
throw new _NotImplementedError.default(this, 'removeAllListeners', 'Driver');
}
} |
JavaScript | class SimpleDialog extends React.Component {
render() {
const actions = [
<FlatButton
label="No, it was mistake"
primary={true}
keyboardFocused={true}
onTouchTap={this.props.onRequestClose}
/>,
<RaisedButton
label={this.props.yesLabel}
primary={true}
onTouchTap={this.props.onSuccess}
/>,
];
return (
<div>
<Dialog title={this.props.title} actions={actions} modal={false} open={this.props.open} onRequestClose={this.props.onRequestClose}>
{this.props.body}
</Dialog>
</div>
);
}
} |
JavaScript | class NominatimSearch extends AbstractUrlSearch {
/**
* Constructor.
* @param {string} name The search provider name.
*/
constructor(name) {
super(nom.ID, name);
this.type = nom.ID;
/**
* The geo search extent.
* @type {Array<number>|undefined}
* @protected
*/
this.geoExtent = undefined;
}
/**
* @inheritDoc
*/
shouldNormalize() {
return false;
}
/**
* @inheritDoc
*/
getSearchUrl(term, opt_start, opt_pageSize) {
var url = /** @type {string} */ (Settings.getInstance().get(nom.SettingKey.URL, ''));
if (url) {
if (opt_pageSize) {
// limit the number of results
url += '&limit=' + opt_pageSize;
}
if (this.geoExtent) {
// restrict the query to the current extent
url += '&bounded=1';
url += '&viewbox=' + this.geoExtent.join(',');
}
}
return url;
}
/**
* @inheritDoc
*/
onSearchSuccess(evt) {
var request = /** @type {Request} */ (evt.target);
var response = /** @type {string} */ (request.getResponse());
if (response) {
var parser = new NominatimParser();
parser.setSource(response);
while (parser.hasNext()) {
var next = parser.parseNext();
if (next) {
if (Array.isArray(next)) {
this.results.concat(next.map(function(f) {
return f ? new SearchResult(f) : undefined;
}).filter(fn.filterFalsey));
} else {
this.results.push(new SearchResult(next));
}
}
}
}
// superclass takes care of cleaning up request and sending events
super.onSearchSuccess(evt);
}
/**
* @inheritDoc
*/
supportsGeoDistance() {
return false;
}
/**
* @inheritDoc
*/
supportsGeoExtent() {
return true;
}
/**
* @inheritDoc
*/
supportsGeoShape() {
return false;
}
/**
* @inheritDoc
*/
setGeoDistance(center, distance) {
// not supported
}
/**
* @inheritDoc
*/
setGeoExtent(extent, opt_center, opt_distance) {
this.geoExtent = extent;
}
/**
* @inheritDoc
*/
setGeoShape(shape, opt_center, opt_distance) {
// not supported
}
} |
JavaScript | class DatepickerNative extends Widget {
static get selector() {
return '.question input[type="date"]';
}
static condition( element ) {
// Do not instantiate if DatepickerExtended was instantiated on element or if mobile device is used.
return !data.has( element, 'DatepickerExtended' ) && !support.touch;
}
_init() {
this.element.type = 'text';
this.element.classList.add( 'mask-date' );
}
} |
JavaScript | class CpFaq extends Rhelement {
constructor() {
super("cp-faq", template);
}
connectedCallback() {
super.connectedCallback();
const accordion = this.querySelector("cp-accordion");
const headings = this.querySelectorAll("cp-accordion-heading");
const headingsAndPanels = this.querySelectorAll(
"cp-accordion-heading, cp-accordion-panel"
);
const markInstance = new Mark(headingsAndPanels);
const input = this.shadowRoot.querySelector("input");
const inputHandler = evt => {
const keyword = input.value.toUpperCase().trim();
const children = [...accordion.children];
let timeout;
clearTimeout(timeout);
timeout = setTimeout(() => {
if (keyword === "") {
accordion.collapseAll();
[...headings].forEach((heading, index) => {
const panel = heading.nextElementSibling;
requestAnimationFrame(() => {
requestAnimationFrame(() => {
heading.style.display = "";
panel.style.display = "";
panel.style.height = "";
panel.classList.remove("animating");
});
});
});
} else {
[...headings].forEach((heading, index) => {
const panel = heading.nextElementSibling;
const headingTextContent = heading.innerText.toUpperCase();
const panelTextContent = panel.innerText.toUpperCase();
if (
!headingTextContent.includes(keyword) &&
!panelTextContent.includes(keyword)
) {
heading.style.display = "none";
panel.style.display = "none";
} else {
heading.style.display = "";
panel.style.display = "";
accordion.expand(index);
}
});
}
}, 100);
markInstance.unmark({
done: () => {
markInstance.mark(keyword, {
separateWordSearch: false
});
}
});
};
input.addEventListener("input", inputHandler);
}
} |
JavaScript | class ViewPreset extends Model {
static get fields() {
return [
/**
* The name of the view preset
* @field {String} name
*/
{ name : 'name', type : 'string' },
/**
* The height of the row in horizontal orientation
* @field {Number} rowHeight
* @default
*/
{
name : 'rowHeight',
defaultValue : 24
},
/**
* The width of the time tick column in horizontal orientation
* @field {Number} tickWidth
* @default
*/
{
name : 'tickWidth',
defaultValue : 50
},
/**
* The height of the time tick column in vertical orientation
* @field {Number} tickHeight
* @default
*/
{
name : 'tickHeight',
defaultValue : 50
},
/**
* Defines how dates will be formatted in tooltips etc
* @field {String} displayDateFormat
* @default
*/
{
name : 'displayDateFormat',
defaultValue : 'HH:mm'
},
/**
* The unit to shift when calling shiftNext/shiftPrevious to navigate in the chart.
* Valid values are "millisecond", "second", "minute", "hour", "day", "week", "month", "quarter", "year".
* @field {String} shiftUnit
* @default
*/
{
name : 'shiftUnit',
defaultValue : 'hour'
},
/**
* The amount to shift (in shiftUnits)
* @field {Number} shiftIncrement
* @default
*/
{
name : 'shiftIncrement',
defaultValue : 1
},
/**
* The amount of time to show by default in a view (in the unit defined by the middle header)
* @field {Number} defaultSpan
* @default
*/
{
name : 'defaultSpan',
defaultValue : 12
},
/**
* An object containing a unit identifier and an increment variable. This value means minimal task duration you can create using UI.
* For example when you drag create a task or drag & drop a task, if increment is 5 and unit is 'minute'
* that means that you can create a 5 min long task, or move it 5 min forward/backward. This config maps to
* scheduler's {@link Scheduler.view.mixin.TimelineDateMapper#property-timeResolution timeResolution} config.
*
* ```javascript
* timeResolution : {
* unit : 'minute', //Valid values are "millisecond", "second", "minute", "hour", "day", "week", "month", "quarter", "year".
* increment : 5
* }
* ```
*
* @field {Object} timeResolution
*/
'timeResolution',
/**
* An array containing one or more {@link Scheduler.preset.ViewPresetHeaderRow} config objects, each of which defines a level of headers for the scheduler.
* The 'main' unit will be the last header's unit, but this can be changed using the `mainHeaderLevel` field.
* @field {Object} headers
*/
'headers',
/**
* Defines which {@link #field-headers header} level defines the 'main' header. Defaults to the bottom header.
* @field {Number} mainHeaderLevel
*/
'mainHeaderLevel',
/**
* Defines which {@link #field-headers header} level the column lines will be drawn for. See {@link Scheduler.feature.ColumnLines}.
* Defaults to the bottom header.
* @field {Number} columnLinesFor
*/
'columnLinesFor'
];
}
construct(data) {
super.construct(...arguments);
this.normalizeUnits();
}
static processData(data, ...args) {
// Process legacy headerConfig config into a headers array.
// TODO: remove deprecated compatibility layer in V4
if (data.headerConfig) {
VersionHelper.deprecate('Scheduler', '4.0.0', 'ViewPreset headerConfig config replaced by headers config. See https://www.bryntum.com/docs/scheduler/#guides/upgrades/3.0.0.md');
data = ObjectHelper.assign({}, data);
this.normalizeHeaderConfig(data);
}
return super.processData(data, ...args);
}
generateId(owner) {
const
me = this,
{
headers
} = me,
parts = [];
// If we were subclassed from a base, use that id as the basis of oure.
let result = Object.getPrototypeOf(me.data).id;
if (!result) {
for (let { length } = headers, i = length - 1; i >= 0; i--) {
parts.push(i ? headers[i].unit : StringHelper.capitalize(headers[i].unit));
}
// Use upwards header units at so eg "monthAndYear"
result = parts.join('And');
}
// If duplicate, make it "hourAndDay-50by80"
if (owner.includes(result)) {
result += `-${me.tickWidth}by${me.tickHeight || me.tickWidth}`;
// If still duplicate use increment
if (owner.includes(result)) {
result += `-${me.bottomHeader.increment}`;
// And if STILL duplicate, make it unique with a suffix
if (owner.includes(result)) {
result = IdHelper.generateId(`${result}-`);
}
}
}
return result;
}
normalizeUnits() {
const
me = this,
{ timeResolution, headers } = me;
// Make sure date "unit" constant specified in the preset are resolved
for (let i = 0, { length } = headers; i < length; i++) {
const header = headers[i];
header.unit = DH.normalizeUnit(header.unit);
if (header.splitUnit) {
header.splitUnit = DH.normalizeUnit(header.splitUnit);
}
if (!('increment' in header)) {
headers[i] = Object.assign({
increment : 1
}, header);
}
}
if (timeResolution) {
timeResolution.unit = DH.normalizeUnit(timeResolution.unit);
}
if (me.shiftUnit) {
me.shiftUnit = DH.normalizeUnit(me.shiftUnit);
}
}
// Process legacy columnLines config into a headers array.
static normalizeHeaderConfig(data) {
const
{ headerConfig, columnLinesFor, mainHeaderLevel } = data,
headers = data.headers = [];
if (headerConfig.top) {
if (columnLinesFor == 'top') {
data.columnLinesFor = 0;
}
if (mainHeaderLevel == 'top') {
data.mainHeaderLevel = 0;
}
headers[0] = headerConfig.top;
}
if (headerConfig.middle) {
if (columnLinesFor == 'middle') {
data.columnLinesFor = headers.length;
}
if (mainHeaderLevel == 'middle') {
data.mainHeaderLevel = headers.length;
}
headers.push(headerConfig.middle);
}
else {
throw new Error('ViewPreset.headerConfig must be configured with a middle');
}
if (headerConfig.bottom) {
// Main level is middle when using headerConfig object.
data.mainHeaderLevel = headers.length - 1;
// There *must* be a middle above this bottom header
// so that is the columnLines one by default.
if (columnLinesFor == null) {
data.columnLinesFor = headers.length - 1;
}
else if (columnLinesFor == 'bottom') {
data.columnLinesFor = headers.length;
}
// There *must* be a middle above this bottom header
// so that is the main one by default.
if (mainHeaderLevel == null) {
data.mainHeaderLevel = headers.length - 1;
}
if (mainHeaderLevel == 'bottom') {
data.mainHeaderLevel = headers.length;
}
headers.push(headerConfig.bottom);
}
}
// These are read-only once configured.
set() {}
inSet() {}
get columnLinesFor() {
return ('columnLinesFor' in this.data) ? this.data.columnLinesFor : this.headers.length - 1;
}
get tickSize() {
return this._tickSize || this.tickWidth;
}
get tickWidth() {
return ('tickWidth' in this.data) ? this.data.tickWidth : 50;
}
get tickHeight() {
return ('tickHeight' in this.data) ? this.data.tickHeight : 50;
}
get headerConfig() {
// Configured in the legacy manner, just return the configured value.
if (this.data.headerConfig) {
return this.data.headerConfig;
}
// Rebuild the object based upon the configured headers array.
const
result = {},
{ headers } = this,
{ length } = headers;
switch (length) {
case 1 :
result.middle = headers[0];
break;
case 2:
if (this.mainHeaderLevel === 0) {
result.middle = headers[0];
result.bottom = headers[1];
}
else {
result.top = headers[0];
result.middle = headers[1];
}
break;
case 3:
result.top = headers[0];
result.middle = headers[1];
result.bottom = headers[2];
break;
default:
throw new Error('headerConfig object not supported for >3 header levels');
}
return result;
}
set mainHeaderLevel(mainHeaderLevel) {
this.data.mainHeaderLevel = mainHeaderLevel;
}
get mainHeaderLevel() {
if ('mainHeaderLevel' in this.data) {
return this.data.mainHeaderLevel;
}
// 3 headers, then it's the middle
if (this.data.headers.length === 3) {
return 1;
};
// Assume it goes top, middle.
// If it's middle, top, use mainHeaderLevel : 0
return this.headers.length - 1;
}
get mainHeader() {
return this.headers[this.mainHeaderLevel];
}
get bottomHeader() {
return this.headers[this.headers.length - 1];
}
get leafUnit() {
return this.bottomHeader.unit;
}
get mainUnit() {
return this.mainHeader;
}
get msPerPixel() {
const { bottomHeader } = this;
return Math.round(DH.asMilliseconds(bottomHeader.increment || 1, bottomHeader.unit) / this.tickWidth);
}
get isValid() {
const me = this;
let valid = true;
// Make sure all date "unit" constants are valid
for (const header of me.headers) {
valid = valid && Boolean(DH.normalizeUnit(header.unit));
}
if (me.timeResolution) {
valid = valid && DH.normalizeUnit(me.timeResolution.unit);
}
if (me.shiftUnit) {
valid = valid && DH.normalizeUnit(me.shiftUnit);
}
return valid;
}
} |
JavaScript | class GameBuilder {
/**
* Instantiates a game builder.
*/
constructor() {
}
/**
* @param gameRepresentationPath {?} A given game representation file under any format.
* @param callback {function} A callback function to call on game built.
*/
buildFrom(gameRepresentationPath, callback) {
}
} |
JavaScript | class JSONGameBuilder extends GameBuilder {
/**
* Instantiates a JSON game builder.
*/
constructor() {
super();
}
/**
* @override GameBuilder.buildFrom
* @param gameRepresentationPath {string} A JSON file representation of the game.
* @param callback {function} A callback function to call on game built.
*/
buildFrom(gameRepresentationPath, callback) {
loadJsonFile(gameRepresentationPath, (response) => {
// Parsing text response to JSON object.
let jsonContent = JSON.parse(response);
// Building levels.
let levels = [];
jsonContent.forEach(currentLevel => {
// Build song.
let levelSongElement = currentLevel.levelSong;
let newLevelSong = new LevelSong(levelSongElement.songAuthor, levelSongElement.songTitle, levelSongElement.songUrl);
// Build milestones list.
let levelSongMilestonesElement = currentLevel.levelMilestones;
let levelSongMilestonesList = [];
levelSongMilestonesElement.forEach(milestone => {
levelSongMilestonesList.push(new LevelMilestone(milestone.gestureId, milestone.levelMilestoneTimestampStart));
});
// Build level.
let newLevel = new Level(currentLevel.levelId, currentLevel.levelName, currentLevel.levelIndexOrder, currentLevel.levelDifficulty, currentLevel.levelColor, newLevelSong, levelSongMilestonesList);
// Add level to the list.
levels.push(newLevel);
});
let newGame = new Game(levels);
// Callback on levels loaded.
callback(newGame);
});
}
} |
JavaScript | class MachineStep {
constructor(nextState, rewrite, direction) {
this.nextState = nextState
this.rewrite = rewrite
this.direction = direction
}
} |
JavaScript | class Entity {
/** @type {EntitySystem|null} */
get owner() {
return this._owner;
}
/** @type {string|null} */
get name() {
return this._name;
}
/** @type {string|null} */
set name(value) {
if (!!value && typeof value != 'string') {
throw new Error('`value` is not type of String!');
}
this._name = value || '';
}
/** @type {string|null} */
get tag() {
return this._tag;
}
/** @type {string|null} */
set tag(value) {
if (!!value && typeof value != 'string') {
throw new Error('`value` is not type of String!');
}
this._tag = value || '';
}
/** @type {boolean} */
get active() {
return this._active;
}
/** @type {boolean} */
set active(value) {
if (typeof value !== 'boolean') {
throw new Error('`value` is not type of Boolean!');
}
this._active = value;
}
/** @type {string} */
get path() {
let result = `/${this._name}`;
let current = this._parent;
while (!!current) {
result = `/${current.name}${result}`;
current = current._parent;
}
return result;
}
/** @type {Entity} */
get root() {
let result = this;
let current = this._parent;
while (!!current) {
result = current;
current = current._parent;
}
return result;
}
/** @type {Entity|null} */
get parent() {
return this._parent;
}
/** @type {Entity|null} */
set parent(value) {
this.reparent(value);
}
/** @type {number} */
get childrenCount() {
return this._children.length;
}
/** @type {number} */
get indexInParent() {
const { _parent } = this;
return !_parent ? -1 : _parent._children.indexOf(this);
}
/** @type {mat4} */
get transformLocal() {
return this._transformLocal;
}
/** @type {mat4} */
get transform() {
return this._transform;
}
/** @type {mat4} */
get inverseTransform() {
return this._inverseTransform;
}
/** @type {vec3} */
get position() {
return this._position;
}
/** @type {quat} */
get rotation() {
return this._rotation;
}
/** @type {vec3} */
get scale() {
return this._scale;
}
/** @type {vec3} */
get globalPosition() {
const result = vec3.create();
vec3.set(cachedTempVec3, 0, 0, 0);
return vec3.transformMat4(result, cachedTempVec3, this._transform);
}
/** @type {*} */
get componentNames() {
return this._components.keys();
}
/** @type {Function|null} */
get childrenSorting() {
return this._childrenSorting;
}
/** @type {Function|null} */
set childrenSorting(value) {
if (!value) {
this._childrenSorting = null;
return;
}
if (!(value instanceof Function)) {
throw new Error('`value` is not type of Function!');
}
this._childrenSorting = value;
this.sortChildren();
}
/** @type {*} */
get meta() {
return this._meta;
}
/**
* Constructor.
*/
constructor() {
this._owner = null;
this._name = '';
this._tag = '';
this._active = true;
this._children = [];
this._parent = null;
this._components = new Map();
this._transformLocal = mat4.create();
this._transform = mat4.create();
this._inverseTransform = mat4.create();
this._position = vec3.create();
this._rotation = quat.create();
this._scale = vec3.fromValues(1, 1, 1);
this._childrenSorting = null;
this._meta = {};
this._dirty = true;
}
/**
* Destructor (disposes internal resources).
*
* @example
* entity.dispose();
* entity = null;
*/
dispose() {
const { _children, _components } = this;
this.reparent(null);
for (let i = _children.length - 1; i >= 0; --i) {
_children[i].dispose();
}
for (const component of _components.values()) {
component.dispose();
}
this._owner = null;
this._name = null;
this._tag = null;
this._children = null;
this._parent = null;
this._components = null;
this._transformLocal = null;
this._transform = null;
this._inverseTransform = null;
this._position = null;
this._rotation = null;
this._scale = null;
this._childrenSorting = null;
this._meta = null;
}
/**
* Make this entity and it's children active.
*
* @example
* entity.activete();
* entity.active === true;
*/
activate() {
this.active = true;
const { _children } = this;
for (let i = 0, c = _children.length; i < c; ++i) {
_children[i].activate();
}
}
/**
* Make this entity and it's children inactive.
*
* @example
* entity.deactivete();
* entity.active === false;
*/
deactivate() {
this.active = false;
const { _children } = this;
for (let i = 0, c = _children.length; i < c; ++i) {
_children[i].deactivate();
}
}
/**
* Serialize this entity into JSON data.
*
* @return {*} Serialized JSON data.
*
* @example
* entity.name = 'serialized';
* const json = entity.serialize();
* json.name === 'serialized';
*/
serialize() {
const name = this._name || '';
const tag = this._tag || '';
const active = this._active;
const position = [ ...this._position ];
const scale = [ ...this._scale ];
const rotation = this.getRotation() * 180 / Math.PI;
const result = {
name,
tag,
active,
meta: {},
transform: {
position,
rotation,
scale
},
components: {},
children: []
};
for (const key in this._meta) {
result.meta[key] = this._meta[key];
}
for (const [key, value] of this._components) {
result.components[key] = value.serialize();
}
for (const child of this._children) {
result.children.push(child.serialize());
}
return result;
}
/**
* Deserialize JSON data into this entity.
*
* @param {*} json - Serialized entity JSON data.
*
* @example
* entity.deserialize({ name: 'deserialized' });
* entity.name === 'deserialized';
*/
deserialize(json) {
if (!json) {
return;
}
if (typeof json.name !== 'undefined') {
this.name = json.name;
}
if (typeof json.tag !== 'undefined') {
this.tag = json.tag;
}
if (typeof json.active !== 'undefined') {
this.active = json.active;
}
const { meta, transform, components } = json;
if (!!meta) {
const { _meta } = this;
for (const name in meta) {
_meta[name] = meta[name];
}
}
if (!!transform) {
const { position, rotation, scale } = transform;
if (typeof position === 'number') {
this.setPosition(position, position);
} else if (!!position && position.length >= 2) {
this.setPosition(position[0], position[1]);
}
if (typeof rotation === 'number') {
this.setRotation(rotation * Math.PI / 180);
}
if (typeof scale === 'number') {
this.setScale(scale, scale);
} else if (!!scale && scale.length >= 2) {
this.setScale(scale[0], scale[1]);
}
}
if (!!components) {
const { _components } = this;
for (const name in components) {
if (_components.has(name)) {
_components.get(name).deserialize(components[name]);
}
}
}
}
/**
* Set entity local position.
*
* @param {number} x - Local X position.
* @param {number} y - Local Y position.
* @param {number} z - Local Z position.
*
* @example
* entity.setPosition(40, 2);
*/
setPosition(x, y, z = 0) {
if (typeof x !== 'number') {
throw new Error('`x` is not type of Number!');
}
if (typeof y !== 'number') {
throw new Error('`y` is not type of Number!');
}
if (typeof z !== 'number') {
throw new Error('`z` is not type of Number!');
}
vec3.set(this._position, x, y, z);
this._dirty = true;
}
/**
* Set entity local Z axis rotation.
*
* @param {number} rad - Z axis radian angle.
*
* @example
* entity.setRotation(90 * Math.PI / 180);
*/
setRotation(rad) {
if (typeof rad !== 'number') {
throw new Error('`rad` is not type of Number!');
}
quat.setAxisAngle(this._rotation, zVector, rad);
this._dirty = true;
}
/**
* Set entity local rotation from euler degrees.
*
* @param {number} x - X axis degree rotation.
* @param {number} y - Y axis degree rotation.
* @param {number} z - Z axis degree rotation.
*
* @example
* entity.setRotationEuler(15, 30, 45);
*/
setRotationEuler(x, y, z) {
if (typeof x !== 'number') {
throw new Error('`x` is not type of Number!');
}
if (typeof y !== 'number') {
throw new Error('`y` is not type of Number!');
}
if (typeof z !== 'number') {
throw new Error('`z` is not type of Number!');
}
quat.fromEuler(this._rotation, x, y, z);
this._dirty = true;
}
/**
* Get entity local Z axis radian rotation.
*
* @return {number} Z axis local radian rotation.
*
* @example
* console.log(entity.getRotation());
*/
getRotation() {
return quat.getAxisAngle(cachedTempVec3, this._rotation) * cachedTempVec3[2];
}
/**
* Get entity local euler axis rotation in degrees.
*
* @param {vec3} result - Result vec3 object.
*
* @example
* const euler = vec3.create();
* entity.getRotationEuler(euler);
* console.log(euler);
*/
getRotationEuler(result) {
if (!result) {
throw new Error('`result` cannot be null!');
}
const rad2deg = 180 / Math.PI;
const angle = quat.getAxisAngle(cachedTempVec3, this._rotation);
vec3.set(
result,
cachedTempVec3[0] * angle * rad2deg,
cachedTempVec3[1] * angle * rad2deg,
cachedTempVec3[2] * angle * rad2deg
);
}
/**
* Set entity local scale.
*
* @param {number} x - Local X scale.
* @param {number} y - Local Y scale.
* @param {number} z - Local Z scale.
*
* @example
* entity.setScale(2, 3);
*/
setScale(x, y, z = 1) {
if (typeof x !== 'number') {
throw new Error('`x` is not type of Number!');
}
if (typeof y !== 'number') {
throw new Error('`y` is not type of Number!');
}
if (typeof z !== 'number') {
throw new Error('`z` is not type of Number!');
}
vec3.set(this._scale, x, y, z);
this._dirty = true;
}
/**
* Get entity children at given index.
*
* @param {number} index - Child index.
*
* @return {Entity} Child entity instance.
*/
getChild(index) {
if (typeof index !== 'number') {
throw new Error('`index` is not type of Number!');
}
const { _children } = this;
if (index < 0 || index >= _children.length) {
throw new Error('`index` is out of bounds!');
}
return _children[index];
}
/**
* Kills all entity children (calls dispose on them and removes them from entity).
*
* @example
* entity.killChildren();
*/
killChildren() {
const { _children } = this;
const container = new Set(_children);
for (const child of container) {
child.dispose();
}
container.clear();
}
/**
* Rebind entity to different parent.
*
* @param {Entity|null} entity - New parent entity or null if not bound to any entity.
* @param {number} insertAt - Child index at given should be placed this entity in new parent
*
* @example
* entity.reparent(system.root);
*/
reparent(entity, insertAt = -1) {
if (!!entity && !(entity instanceof Entity)) {
throw new Error('`entity` is not type of Entity!');
}
if (typeof insertAt !== 'number') {
throw new Error('`insertAt` is not type of Number!');
}
const { _parent } = this;
if (entity === _parent) {
return;
}
this._parent = entity;
if (!!_parent) {
const { _children } = _parent;
const found = _children.indexOf(this);
if (found >= 0) {
this._setOwner(null);
_children.splice(found, 1);
}
_parent.sortChildren();
}
if (!!entity) {
if (insertAt < 0) {
entity._children.push(this);
} else {
entity._children.splice(insertAt, 0, this);
}
this._setOwner(entity.owner);
entity.sortChildren();
}
}
/**
* Find entity by it's name or path in scene tree.
*
* @param {string} name - Entity name or path.
*
* @return {Entity|null} Found entity instance or null if not found.
*
* @example
* entity.findEntity('./some-child');
* entity.findEntity('/root-child');
* entity.findEntity('/root-child/some-child');
*/
findEntity(name) {
if (typeof name !== 'string') {
throw new Error('`name` is not type of String!');
}
let current = this;
while (!!current && name.length > 0) {
const found = name.indexOf('/');
if (found === 0) {
while (!!current._parent) {
current = current._parent;
}
name = name.substr(found + 1);
} else {
const part = found > 0 ? name.substr(0, found) : name;
if (part === '.') {
// do nothing
} else if (part === '..') {
current = current._parent;
} else {
const { _children } = current;
let found = false;
for (let i = 0, c = _children.length; i < c; ++i) {
const child = _children[i];
if (child.name === part) {
current = child;
found = true;
break;
}
}
if (!found) {
return null;
}
}
if (found < 0) {
return current;
}
name = name.substr(found + 1);
}
}
return current;
}
/**
* Attach component to this entity.
*
* @param {string} typename - Component type name.
* @param {Component} component - Component instance.
*
* @example
* entity.attachComponent('MyComponent', new MyComponent());
* entity.attachComponent('Hello', new Hello());
*/
attachComponent(typename, component) {
if (typeof typename !== 'string') {
throw new Error('`typename` is not type of String!');
}
if (!(component instanceof Component)) {
throw new Error('`component` is not type of Component!');
}
const { _components } = this;
if (_components.has(typename)) {
throw new Error(
`Given component type is already attached to entity: ${typename}`
);
}
_components.set(typename, component);
component._owner = this;
if (!!this._owner && !!this._owner.triggerEvents) {
component.onAttach();
}
}
/**
* Detach component by it's type name.
*
* @param {string} typename - Component type name.
*
* @example
* entity.detachComponent('Hello');
*/
detachComponent(typename) {
const { _components } = this;
let component = typename;
if (typeof typename === 'string') {
component = _components.get(typename);
} else if (component instanceof Component) {
typename = findMapKeyOfValue(_components, component);
} else {
throw new Error('`typename` is not type of either Component or String!');
}
if (_components.delete(typename)) {
component._owner = null;
if (!!this._owner && !!this._owner.triggerEvents) {
component.onDetach();
}
} else {
throw new Error(`Trying to remove non-attached component type: ${typename}`);
}
}
/**
* Find component by it's type name.
*
* @param {string|Function} typename - Component type (class or name).
*
* @return {Component|null} Component instance if found or null otherwise.
*
* @example
* class Hello extends Component {}
* entity.attachComponent('Hello', new Hello());
* const hello1 = entity.getComponent('Hello');
* const hello2 = entity.getComponent(Hello);
*/
getComponent(typename) {
if (typeof typename === 'string') {
return this._components.get(typename) || null;
} else if (typename instanceof Function) {
for (const c of this._components.values()) {
if (c instanceof typename) {
return c;
}
}
return null;
}
throw new Error('`typename` is not type of either String or Function!');
}
/**
* Perform action on entity.
*
* @param {string} name - Action name.
* @param {*} args - Action parameters.
*
* @example
* class Hi extends Component { onAction(name, wat) { if (name === 'hi') console.log(wat); } }
* entity.attachComponent('Hi', new Hi());
* entity.performAction('hi', 'hello');
*/
performAction(name, ...args) {
if (typeof name !== 'string') {
throw new Error('`name` is not type of String!');
}
if (!this._active) {
return;
}
const { _components, _children } = this;
let status = false;
let a = args;
for (const component of _components.values()) {
status = !!component.onAction(name, ...a) || status;
a = component.onAlterActionArguments(name, a) || a;
}
if (status) {
return;
}
for (let i = 0, c = _children.length; i < c; ++i) {
_children[i].performAction(name, ...a);
}
}
/**
* Perform action only on components (do not pass action further to children).
* See: {@link performAction}
*
* @param {string} name - Action name.
* @param {*} args - Action parameters.
*/
performActionOnComponents(name, ...args) {
if (typeof name !== 'string') {
throw new Error('`name` is not type of String!');
}
if (!this._active) {
return;
}
const { _components } = this;
let a = args;
for (const component of _components.values()) {
!!component.onAction(name, ...a);
a = component.onAlterActionArguments(name, a) || a;
}
}
/**
* Perform custom callback action on entity components of given type and it's children.
*
* @param {string|null} id - Affected component type (can be null if want to call every component).
* @param {Function} action - Custom action callback. Callback gets one argument with component instance.
*
* @example
* entity.performOnComponents('Hello', component => console.log(component.hello));
*/
performOnComponents(id, action) {
if (!!id && typeof id !== 'string') {
throw new Error('`id` is not type of String!');
}
if (!(action instanceof Function)) {
throw new Error('`action` is not type of Function!');
}
if (!!id) {
const component = this.getComponent(id);
if (!!component) {
action(component);
}
} else {
const { _components } = this;
for (const component of _components.values()) {
action(component);
}
}
const { _children } = this;
for (let i = 0, c = _children.length; i < c; ++i) {
_children[i].performOnComponents(id, action);
}
}
/**
* Perform custom callback action only on entity and optionally it's children.
*
* @param {Function} action - Custom action callback. Callback gets one argument with child instance.
* @param {boolean} deep - True if should be called on it's children.
*
* @example
* entity.performOnChildren(e => console.log(e.name));
*/
performOnChildren(action, deep = false) {
if (!(action instanceof Function)) {
throw new Error('`action` is not type of Function!');
}
const { _children } = this;
for (let i = 0, c = _children.length; i < c; ++i) {
const child = _children[i];
action(child);
if (!!deep) {
child.performOnChildren(action, deep);
}
}
}
/**
* Update entity ant it's children transforms.
*
* @param {mat4} parentTransform - Parent transformation.
* @param {boolean} forced - If true ignore optimizations and update anyway.
*
* @example
* entity.updateTransforms();
*/
updateTransforms(parentTransform, forced = false) {
if (!this._active) {
return;
}
const {
_children,
_transform,
_inverseTransform,
_transformLocal,
_position,
_rotation,
_scale
} = this;
if (!!forced || this._dirty) {
mat4.fromRotationTranslationScale(
_transformLocal,
_rotation,
_position,
_scale
);
mat4.multiply(_transform, parentTransform, _transformLocal);
mat4.invert(_inverseTransform, _transform);
forced = true;
this._dirty = false;
}
for (let i = 0, c = _children.length; i < c; ++i) {
_children[i].updateTransforms(_transform, forced);
}
}
/**
* Sort children by entity childrenSorting function if set.
*/
sortChildren() {
const { _childrenSorting, _children } = this;
if (!_childrenSorting) {
return;
}
_children.sort(_childrenSorting);
}
/**
* Transform coordinate from this entity local space into other entity local space.
*
* @param {vec3} target - Result vec3 value.
* @param {vec3} coord - Input vec3 value.
* @param {Entity} entity - Other entity.
*/
transformCoord(target, coord, entity) {
if (!(entity instanceof Entity)) {
throw new Error('`entity` is not type of Entity!');
}
vec3.transformMat4(cachedTempVec3, coord, this.transform);
vec3.transformMat4(cachedTempVec3, cachedTempVec3, entity.inverseTransform);
}
_setOwner(owner) {
const { _owner, _components, _children } = this;
if (!!owner === !!_owner) {
return;
}
if (!!_owner && !!_owner.triggerEvents) {
for (const component of _components.values()) {
component.onDetach();
}
}
this._owner = owner;
if (!!owner && !!owner.triggerEvents) {
for (const component of _components.values()) {
component.onAttach();
}
}
for (let i = 0, c = _children.length; i < c; ++i) {
_children[i]._setOwner(owner);
}
}
} |
JavaScript | class BankAccount {
constructor(firstName, lastName, middleName = "", balance = 0, accountType) {
this.balance = balance
this.firstName = firstName
this.lastName = lastName
this.middleName = middleName
this.accountType = accountType
if (this.balance >= 100) {
this.accountStatus = "Open"
} else {
accountStatus = "Closed"
}
}
depositInAccount(depositAmount){
this.balance += depositAmount
console.log("Deposited " + depositAmount + " dollars")
}
withdrawFromAccount(withdrawalAmount){
this.balance -= withdrawalAmount
console.log("Withdrew " + withdrawAmount + " dollars")
}
transferToAccount(transferAmount, targetAccount){
this.balance -= transferAmount
targetAccount += transferAmount
console.log(`Transfered ${transferAmount} from ${this.accountType} with current balance of ${targetAccount.balance} \
to ${targetAccount} with current balance of ${this.balance}`)
}
accountStatusUpdater(status){
this.status = status
}
overDrawPenalty(){
if (this.balance < 0){
balance -= 35
}
}
} |
JavaScript | class cartoaxes {
constructor(params) {
var me = this;
this.data = [];
this.titre = params.titre ? params.titre : '';
this.crible = params.crible ? params.crible : [{
'label': 'clair',
'id': '0',
'idP': '0'
}, {
'label': 'obscur',
'id': '1',
'idP': '0'
}, {
'label': 'pertinent',
'id': '2',
'idP': '0'
}, {
'label': 'inadapté',
'id': '3',
'idP': '0'
}];
this.urlData = params.urlData ? params.urlData : false;
this.fctCallBackInit = params.fctCallBackInit ? params.fctCallBackInit : false;
this.svg = d3.select("#" + params.idSvg),
this.width = params.width ? params.width : this.svg.attr("width"),
this.height = params.height ? params.height : this.svg.attr("height"),
this.xMin = params.xMin ? params.xMin : 0;
this.xMax = params.xMax ? params.xMax : 100;
this.yMin = params.yMin ? params.yMin : 0;
this.yMax = params.yMax ? params.yMax : 100;
this.colorFond = params.colorFond ? params.colorFond : "transparent";
this.tick = params.tick ? params.tick : 0;
this.rayons = d3.range(params.nbRayon ? params.nbRayon : 6); // Création d'un tableau pour les rayons des cercles
this.fctGetGrad = params.fctGetGrad ? params.fctGetGrad : false;
this.fctSavePosi = params.fctSavePosi ? params.fctSavePosi : false;
this.idDoc = params.idDoc ? params.idDoc : false;
this.typeSrc = params.typeSrc ? params.typeSrc : false;
this.hasRatingSystem = params.hasRatingSystem ? params.hasRatingSystem : false;
//variable pour les axes
var labelFactor = 1, //How much farther than the radius of the outer circle should the labels be placed
marges = {
'top': 10
},
radius = Math.min(this.width / 2, (this.height - marges.top) / 2),
angleSlice = Math.PI * 2 / this.crible.length,
scCircle = d3.scalePoint()
.domain(this.rayons)
.range([0, radius]),
//variables pour les débgradés
svgDefs, degrad,
//drag variables
onDrag = true,
svgDrag,
//distance variable
pointCentral,
tooltip, fontSize = 16;
//création des dégradé
svgDefs = this.svg.append('defs');
let lg = svgDefs.append('linearGradient')
.attr('id', "degraxeH")
.attr('x1', "0%")
.attr('y1', "0%")
.attr('x2', "0%")
.attr('y2', "100%")
lg.append('stop').attr('offset', "5%").attr('stop-color', "rgb(173, 158, 253)")
lg.append('stop').attr('offset', "95%").attr('stop-color', "rgb(252, 161, 205)")
lg = svgDefs.append('linearGradient')
.attr('id', "degraxeV")
.attr('x1', "0%")
.attr('y1', "0%")
.attr('x2', "100%")
.attr('y2', "0%")
lg.append('stop').attr('offset', "0%").attr('stop-color', "rgb(3, 246, 162)")
lg.append('stop').attr('offset', "100%").attr('stop-color', "rgb(84, 214, 255)")
lg = svgDefs.append('linearGradient')
.attr('id', "degradCenter")
.attr('x1', "0.717")
.attr('y1', "1")
.attr('x2', "0")
.attr('y2', "1")
.attr('gradientUnits', "objectBoundingBox")
lg.append('stop').attr('offset', "0").attr('stop-color', "#5ffd8a")
lg.append('stop').attr('offset', "0.65").attr('stop-color', "#58e6ce")
lg.append('stop').attr('offset', "1").attr('stop-color', "#55daf2")
//positionnement du graphique
this.transform = params.transform ? params.transform : "translate(" + me.width / 2 + ',' + me.height / 2 + ") scale(0.9)";
this.g = this.svg.append("g")
.attr("class", "cartoaxes")
.attr("transform", this.transform);
//calcule des échelles
this.x = d3.scaleLinear()
.domain(padExtent([this.xMin, this.xMax]))
.range(padExtent([0, this.width]));
this.y = d3.scaleLinear()
.domain(padExtent([this.yMin, this.yMax]))
.range(padExtent([this.height - marges.top, 0]));
this.rScale = d3.scaleLinear()
.range([0, radius])
.domain([this.xMin, this.xMax]);
this.vScale = d3.scaleLinear()
.range([0, 100])
.domain([0, radius]);
this.init = function () {
me.g.append("rect")
.attr("width", me.width)
.attr("height", me.height)
.attr("fill", me.colorFond)
.on('mousemove', function (e) {
/*
console.log(d3.mouse(this)[0]);
console.log(me.x.invert(d3.mouse(this)[0]));
console.log(me.y.invert(d3.mouse(this)[1]));
*/
});
me.drawAxes();
me.drawCible();
me.drawData();
//Ajoute le titre de la carto
me.g.append("text")
.attr("class", "txtTitreAxehaut")
.style("font-size", "18px")
.style("font-style", "italic")
.attr("text-anchor", "middle")
.attr("x", 0)
.attr("y", -(me.height / 2) - (marges.top / 2))
.text(me.titre);
//ajout du tooltip
d3.select(".tooltipCartoAxes").remove();
tooltip = d3.select("body").append("div")
.attr("class", "tooltipCartoAxes")
.style('position', 'absolute')
.style('padding', '4px')
.style('background-color', 'black')
.style('color', 'white')
.style('pointer-events', 'none');
};
function showTooltip(e, d) {
//calcule les élément du tooltip
console.log(d);
const event = new Date(d["o:created"]["@value"]);
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
tooltip.html("<h3>" + d["jdc:hasActant"][0].display_title + "</h3>" +
"<h4>" + event.toLocaleDateString('fr-FR', options) + " " + event.toLocaleTimeString('fr-FR') + "</h4>"
)
.style("display", "block")
.style("left", (e.pageX) + "px")
.style("top", (e.pageY) + "px");
}
function hideTooltip() {
tooltip.style("display", "none");
}
function getTextWidth(text, font = fontSize + "px Times New Roman") {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
context.font = font;
return context.measureText(text).width;
}
function breakString(word, maxWidth, hyphenCharacter = '-') {
const characters = word.split("");
const lines = [];
let currentLine = "";
characters.forEach((character, index) => {
const nextLine = `${currentLine}${character}`;
const lineWidth = getTextWidth(nextLine);
if (lineWidth >= maxWidth) {
const currentCharacter = index + 1;
const isLastLine = characters.length === currentCharacter;
const hyphenatedNextLine = `${nextLine}${hyphenCharacter}`;
lines.push(isLastLine ? nextLine : hyphenatedNextLine);
currentLine = "";
} else {
currentLine = nextLine;
}
});
return {
hyphenatedStrings: lines,
remainingWord: currentLine
};
}
function wrapLabel(label, maxWidth) {
if (!label) return [];
const words = label.split(" ");
const completedLines = [];
let nextLine = "";
words.forEach((word, index) => {
const wordLength = getTextWidth(`${word} `);
const nextLineLength = getTextWidth(nextLine);
if (wordLength > maxWidth) {
const {
hyphenatedStrings,
remainingWord
} = breakString(word, maxWidth);
completedLines.push(nextLine, ...hyphenatedStrings);
nextLine = remainingWord;
} else if (nextLineLength + wordLength >= maxWidth) {
completedLines.push(nextLine);
nextLine = word;
} else {
nextLine = [nextLine, word].filter(Boolean).join(" ");
}
const currentWord = index + 1;
const isLastWord = currentWord === words.length;
if (isLastWord) {
completedLines.push(nextLine);
}
});
return completedLines.filter(line => line !== "");
}
// Fonction pour créer la cible
this.drawCible = function (d) {
//ajoute les cercles concentriques
//le cercle 0 sert de point central pour la distance
//le cercle 1 sert de curseur d'intensité
me.g.selectAll('.cFond').data(me.rayons).enter().append('circle') // Création des cercles + attributs
.attr('class', 'cFond')
.attr('id', function (d, i) {
return 'orbit' + i;
})
.attr('r', function (d) {
//on affiche ni le premier ni le dernier
let r = scCircle(d)
if (d == 0) r = 0;
if (d == 1) r = scCircle(d) / 2;
if (d == me.rayons.length - 1) r = 0;
return r;
})
.attr('cx', 0)
.attr('cy', 0);
d3.select("#orbit1").call(me.drag);
let center = d3.select("#orbit1").node();
pointCentral = {
'X': center.getAttribute("cx"),
'Y': center.getAttribute("cy")
};
}
// Fonction pour créer les axes
this.drawAxes = function (d) {
//Create the straight lines radiating outward from the center
var axis = me.g.selectAll(".axis")
.data(me.crible)
.enter()
.append("g")
.attr("class", "axis");
//Append the lines
axis.append("line")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", function (d, i) {
d.x = me.rScale(me.xMax * labelFactor) * Math.cos(angleSlice * i - Math.PI / 2);
d.x2 = me.rScale(me.xMax - 10) * Math.cos(angleSlice * i - Math.PI / 2);
return d.x2;
})
.attr("y2", function (d, i) {
d.y = me.rScale(me.xMax * labelFactor) * Math.sin(angleSlice * i - Math.PI / 2);
d.y2 = (me.rScale(me.xMax - 10) * Math.sin(angleSlice * i - Math.PI / 2)) + 1;
return d.y2;
});
//Append the labels at each axis
let txt = axis.append("text")
.attr("class", "txtTitreAxehaut")
//.style("font-size", "11px")
.attr("text-anchor", "middle");
txt.selectAll("tspan")
.data((d,i) => {
d.wl = wrapLabel(d.label, me.xMax*1.5)
return d.wl;
})
.join("tspan")
.text(d => d);
//modifient les éléments suite au wrap
txt.attr('transform',d=>{
return `translate(${d.x},${d.y})`;
});
txt.selectAll("tspan")
.attr("x", 3)
.attr("y", (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + 1.1 + i * 0.9}em`);
/*
axis.append("text")
.attr("class", "txtTitreAxehaut")
//.style("font-size", "11px")
.attr("text-anchor", "middle")
.attr("dy", function (d, i) {
return i == 0 ? "1.2em" : "";
})
.attr("x", function (d, i) {
return me.rScale(me.xMax * labelFactor) * Math.cos(angleSlice * i - Math.PI / 2);
})
.attr("y", function (d, i) {
return me.rScale(me.xMax * labelFactor) * Math.sin(angleSlice * i - Math.PI / 2);
})
.text(function (d) {
return d.label;
});
*/
}
// Fonction pour l'event "drag" d3js
this.dragstarted = function (e, d) {
//on ne peut déplacer que le cercle 1
if (d != 1) return;
me.setSvgDrag([e.x, e.y]);
d3.select(this).raise().classed("active", true);
me.onDrag = true;
}
this.dragged = function (e, d) {
//console.log(me.width+','+me.height+' : '+d3.event.x+','+d3.event.y);
//pour limiter le drag
//if(d3.event.x < me.width && d3.event.x > 0 && d3.event.y < me.height && d3.event.y > 0)
svgDrag.attr("cx", e.x).attr("cy", e.y);
}
this.dragended = function (e, d) {
//récupère les données du points
let posi = [e.x, e.y];
//calcule la distance et la pondération du crible
let v = me.getValorisation(posi[0], posi[1]);
//formate les données
let r = {
'x': posi[0],
'y': posi[1],
'numX': me.x.invert(posi[0]),
'numY': me.y.invert(posi[1]),
'degrad': degrad //récupère les couleurs et la date
,
'distance': v.d,
'crible': v.s,
'id': me.idDoc,
'infos': me.data
};
console.log(r);
if (me.fctSavePosi) me.fctSavePosi(r);
}
this.setSvgDrag = function (p) {
//console.log(p);
let c = me.getGradient();
svgDrag = me.g.append("circle")
.attr('class', 'evals')
.attr('r', scCircle.step() / 3)
.attr('cx', p[0])
.attr('cy', p[1])
.attr('fill', c)
.attr('stroke', 'black')
.attr("stroke-width", '1');
}
this.drag = d3.drag()
.on("start", me.dragstarted)
.on("drag", me.dragged)
.on("end", me.dragended);
this.drawData = function () {
if (me.urlData) {
//cherche sur le serveur les évaluations existantes
mdPatienter.show();
$.get(me.urlData, {}, function (data) {
me.drawPosi(data);
}, "json")
.fail(function (e) {
throw new Error("Chargement des données imposible : " + e);
})
.always(function () {
mdPatienter.close();
});
}
};
this.drawPosi = function (data) {
//enlève les anciennes évaluations
me.g.selectAll(".evals").remove();
//ajoute toutes les évaluations
me.g.selectAll(".evals")
.data(data)
.enter().append("circle")
.attr("class", "evals")
.attr('r', scCircle.step() / 3)
.attr('cx', function (d) {
//return me.x(d.valeur.numX);
return me.x(parseFloat(d['jdc:xRatingValue'][0]['@value']));
})
.attr('cy', function (d) {
//return me.y(d.valeur.numY);
return me.y(parseFloat(d['jdc:yRatingValue'][0]['@value']));
})
.attr('fill', function (d) {
d.degrad = {
'nom': d['jdc:degradName'][0]['@value'],
'colors': []
}
d['jdc:degradColors'].forEach(function (c) {
d.degrad.colors.push(c['@value']);
});
return me.setGradient(d.degrad);
})
.attr('stroke', 'black')
.attr("stroke-width", '1')
.on('mouseenter', showTooltip)
.on('mouseleave', hideTooltip);
}
function padExtent(e, p) {
if (p === undefined) p = 1;
return ([e[0] - p, e[1] + p]);
}
this.getGradient = function () {
if (!me.fctGetGrad) return 'white';
degrad = me.fctGetGrad();
return me.setGradient(degrad);
}
this.setGradient = function (degrad) {
if (!document.getElementById(degrad.nom)) {
var radialG = svgDefs.append('radialGradient')
.attr('id', degrad.nom);
// Create the stops of the main gradient. Each stop will be assigned
radialG.selectAll('stop').data(degrad.colors).enter().append('stop')
.attr('stop-color', function (d) {
return d;
})
.attr('offset', function (d, i) {
let pc = 100 / degrad.colors.length * i;
return pc + '%';
});
}
return "url(#" + degrad.nom + ")";
}
// Credits goes to Stackoverflow: http://stackoverflow.com/a/14413632
this.getAngleFromPoint = function (point1, point2) {
var dy = (point1.Y - point2.Y),
dx = (point1.X - point2.X);
var theta = Math.atan2(dy, dx);
var angle = (((theta * 180) / Math.PI)) % 360;
angle = (angle < 0) ? 360 + angle : angle;
return angle;
}
// Credits goes to http://snipplr.com/view/47207/
this.getDistance = function (point1, point2) {
var xs = 0;
var ys = 0;
xs = point2.X - point1.X;
xs = xs * xs;
ys = point2.Y - point1.Y;
ys = ys * ys;
return Math.sqrt(xs + ys);
}
//credit goes to https://codepen.io/netsi1964/pen/WrRGoo
this.getValorisation = function (x, y) {
let angle = Math.round(100 * me.getAngleFromPoint({
'X': x,
'Y': y
}, pointCentral)) / 100;
let distance = Math.round(me.getDistance({
'X': x,
'Y': y
}, pointCentral));
let angleAxe = 0;
let valo = [];
//pondération du crible
//0 de crible = 270 angle
me.crible.forEach(function (s, i) {
angleAxe = angleSlice * i * (180 / Math.PI);
angleAxe = angleAxe >= 90 ? angleAxe - 90 : angleAxe + 270;
valo.push({
't': s,
'p': angle - angleAxe
});
})
return {
's': valo,
'd': me.vScale(distance)
};
}
this.init();
}
} |
JavaScript | class Oauth2 extends Model {
static get tableName() {
return 'oauth2';
}
static get modifiers() {
return {
selectOauth2: (builder) => {
builder.select('id', 'oauth2.userId', 'provider');
}
};
}
} |
JavaScript | class MediatedQuadSource {
constructor(mediatorRdfDereferencePaged, uriConstructor, context) {
this.mediatorRdfDereferencePaged = mediatorRdfDereferencePaged;
this.uriConstructor = uriConstructor;
this.context = context;
}
/**
* Check if the given pattern matches with the given quad.
* @param {Quad} pattern A quad pattern.
* @param {Quad} quad A quad.
* @return {boolean} If they match.
*/
static matchPattern(pattern, quad) {
for (const termName of rdf_terms_1.QUAD_TERM_NAMES) {
const patternTerm = pattern[termName];
if (patternTerm && patternTerm.termType !== 'Variable') {
const quadTerm = quad[termName];
if (!patternTerm.equals(quadTerm)) {
return false;
}
}
}
return true;
}
/**
* A helper function to find a hash with quad elements that have duplicate variables.
*
* @param {RDF.Term} subject An optional subject term.
* @param {RDF.Term} predicate An optional predicate term.
* @param {RDF.Term} object An optional object term.
* @param {RDF.Term} graph An optional graph term.
*
* @return {{[p: string]: string[]}} If no equal variable names are present in the four terms, this returns null.
* Otherwise, this maps quad elements ('subject', 'predicate', 'object', 'graph')
* to the list of quad elements it shares a variable name with.
* If no links for a certain element exist, this element will
* not be included in the hash.
* Note 1: Quad elements will never have a link to themselves.
* So this can never occur: { subject: [ 'subject'] },
* instead 'null' would be returned.
* Note 2: Links only exist in one direction,
* this means that { subject: [ 'predicate'], predicate: [ 'subject' ] }
* will not occur, instead only { subject: [ 'predicate'] }
* will be returned.
*/
getDuplicateElementLinks(subject, predicate, object, graph) {
// Collect a variable to quad elements mapping.
const variableElements = {};
let duplicateVariables = false;
const input = { subject, predicate, object, graph };
for (const key of Object.keys(input)) {
if (input[key] && input[key].termType === 'Variable') {
const val = rdf_string_1.termToString(input[key]);
const length = (variableElements[val] || (variableElements[val] = [])).push(key);
duplicateVariables = duplicateVariables || length > 1;
}
}
if (!duplicateVariables) {
return null;
}
// Collect quad element to elements with equal variables mapping.
const duplicateElementLinks = {};
for (const variable in variableElements) {
const elements = variableElements[variable];
const remainingElements = elements.slice(1);
// Only store the elements that have at least one equal element.
if (remainingElements.length) {
duplicateElementLinks[elements[0]] = remainingElements;
}
}
return duplicateElementLinks;
}
matchLazy(subject, predicate, object, graph) {
if (subject instanceof RegExp
|| predicate instanceof RegExp
|| object instanceof RegExp
|| graph instanceof RegExp) {
throw new Error("MediatedQuadSource does not support matching by regular expressions.");
}
const quads = new asynciterator_promiseproxy_1.PromiseProxyIterator(async () => {
const url = await this.uriConstructor(subject, predicate, object, graph);
const output = await this.mediatorRdfDereferencePaged.mediate({ context: this.context, url });
// Emit metadata in the stream, so we can attach it later to the actor's promise output
quads.emit('metadata', output.firstPageMetadata);
// The server is free to send any data in its response (such as metadata),
// including quads that do not match the given matter.
// Therefore, we have to filter away all non-matching quads here.
let filteredOutput = output.data.filter(MediatedQuadSource.matchPattern.bind(null, DataFactory.quad(subject, predicate, object, graph || DataFactory.variable('v'))));
// Detect duplicate variables in the pattern
const duplicateElementLinks = this
.getDuplicateElementLinks(subject, predicate, object, graph);
// If there are duplicate variables in the search pattern,
// make sure that we filter out the triples that don't have equal values for those triple elements,
// as QPF ignores variable names.
if (duplicateElementLinks) {
filteredOutput = filteredOutput.filter((quad) => {
// No need to check the graph, because an equal element already would have to be found in s, p, or o.
for (const element1 of rdf_terms_1.TRIPLE_TERM_NAMES) {
for (const element2 of (duplicateElementLinks[element1] || [])) {
if (!quad[element1].equals(quad[element2])) {
return false;
}
}
}
return true;
});
}
return filteredOutput;
});
quads.on('newListener', (eventName) => {
if (eventName === 'metadata') {
setImmediate(() => quads._fillBuffer());
}
});
return quads;
}
match(subject, predicate, object, graph) {
return this.matchLazy(subject, predicate, object, graph);
}
} |
JavaScript | class FetchError {
/**
* The fetch response
* @type {Response}
*/
response = null;
constructor(response) {
this.response = response;
}
} |
JavaScript | class LndEngine {
/**
* LndEngine Constructor
*
* @class
* @param {string} host - host gRPC address
* @param {string} symbol - Common symbol of the currency this engine supports (e.g. `BTC`)
* @param {object} [options={}]
* @param {Logger} [options.logger=console] - logger used by the engine
* @param {string} [options.tlsCertPath] - file path to the TLS certificate for LND
* @param {string} [options.macaroonPath] - file path to the macaroon file for LND
* @param {string} [options.minVersion] - minimum LND version required
* @param {number} [options.finalHopTimeLock] - value of property on engine
* that suggests a time lock to use on time locks for the final hop of a
* payment
* @param {number} [options.retrieveWindowDuration] - value of property on
* engine corresponding to the max expected time it might take to retrieve a
* preimage, to be used to calculate the forwarding delta
* @param {number} [options.claimWindowDuration] - value of property on
* engine corresponding the max expected time it might take to publish
* a claim for a payment on the blockchain using a preimage, to be used to
* calculate the forwarding delta
* @param {number} [options.blockBuffer] - Buffer to apply to swaps to take
* into account blocks being mined during swaps.
*/
constructor (host, symbol, { logger = console, tlsCertPath, macaroonPath,
minVersion, finalHopTimeLock, retrieveWindowDuration, claimWindowDuration, blockBuffer } = {}) {
if (!host) {
throw new Error('Host is required for lnd-engine initialization')
}
this.CHANNEL_ROUNDING = CHANNEL_ROUNDING
this.host = host
this.symbol = symbol
this.minVersion = minVersion
this.currencyConfig = currencies.find(({ symbol }) => symbol === this.symbol)
this.secondsPerBlock = 600 // can be overridden by config.json setting
if (!this.currencyConfig) {
throw new Error(`${symbol} is not a valid symbol for this engine.`)
}
// Expose config publicly that we expect to be used by consumers
PUBLIC_CONFIG.forEach((configKey) => {
if (this.currencyConfig && !this.currencyConfig.hasOwnProperty(configKey)) {
throw new Error(`Currency config for ${this.symbol} is missing for '${configKey}'`)
}
// @ts-ignore
this[configKey] = this.currencyConfig[configKey]
})
// ~9 blocks, from BOLT #2
// see https://github.com/lightningnetwork/lightning-rfc/blob/master/
// 02-peer-protocol.md#cltv_expiry_delta-selection
this.finalHopTimeLock = finalHopTimeLock || 9 * this.secondsPerBlock
// based on a forward time lock delta of 40 blocks from LND
// see https://github.com/lightningnetwork/lnd/pull/2759
this.retrieveWindowDuration = retrieveWindowDuration || 6000
this.claimWindowDuration = claimWindowDuration || 30 * this.secondsPerBlock
// The recipient requires a minimum number of blocks for the time lock on an inbound HTLC.
// If we use this exact value to create the HTLC on the sending side, there is a small chance
// that a block will be mined during the time it takes for the HTLC to be sent over the network
// to the recipient, and this will cause the recipient to reject the HTLC.
// @see {@link https://github.com/lightningnetwork/lnd/issues/535}
this.blockBuffer = blockBuffer || 2 * this.secondsPerBlock
// Default status of the lnd-engine is unknown as we have not run any validations
// up to this point. We need to define this BEFORE generating the Lightning client
// to suppress invalid macaroon warnings.
this.status = ENGINE_STATUSES.UNKNOWN
this.logger = logger
this.tlsCertPath = tlsCertPath
this.macaroonPath = macaroonPath
this.protoPath = LND_PROTO_PATH
this.client = generateLightningClient(this)
this.walletUnlocker = generateWalletUnlockerClient(this)
// We wrap all validation dependent actions in a callback so we can prevent
// their use if the current engine is in a state that prevents a call from
// functioning correctly.
Object.entries(validationDependentActions).forEach(([name, action]) => {
this[name] = (...args) => {
if (!this.validated) {
throw new Error(`${symbol} Engine is not validated. Engine Status: ${this.status}`)
}
return action.call(this, ...args)
}
})
Object.entries(unlockedDependentActions).forEach(([name, action]) => {
this[name] = (...args) => {
if (!this.isUnlocked) {
throw new Error(`${symbol} Engine is not available and unlocked. ` +
`Engine Status: ${this.status}`)
}
return action.call(this, ...args)
}
})
Object.entries(validationIndependentActions).forEach(([name, action]) => {
this[name] = action.bind(this)
})
}
get validated () {
return (this.status === ENGINE_STATUSES.VALIDATED)
}
get isUnlocked () {
// note that we don't include the UNLOCKED state because it means that
// there is a configuration problem
const { NOT_SYNCED, VALIDATED } = ENGINE_STATUSES
return (this.status === NOT_SYNCED || this.status === VALIDATED)
}
get isLocked () {
return (this.status === ENGINE_STATUSES.LOCKED)
}
} |
JavaScript | class Cast {
/**
* Instantiates a new Cast instance.
*
* @param {Object} cast Cast template object
* @constructor
*/
constructor({script, size, setup, validate} = {}) {
this.script = script || []
this.size = size
if (setup && typeof setup === 'function') {
this.setup = setup
}
if (validate && typeof validate === 'function') {
this.validate = validate
}
}
/**
* Instantiates a `lockingScript` Cast instance.
*
* The following parameters are required:
*
* * `satoshis` - the amount to send in the output (also accepts `amount`)
*
* Additional parameters may be required, depending on the Cast template.
*
* @param {Object} cast Cast template object
* @param {Object} params Cast parameters
* @constructor
*/
static lockingScript(cast, params = {}) {
requiresAny(params, 'lockingScript', [
['satoshis', 'amount']
])
const satoshis = params.satoshis || params.amount || 0
delete params.satoshis && delete params.amount
return new LockingScript(cast.lockingScript, satoshis, params)
}
/**
* Instantiates an `unlockingScript` Cast instance.
*
* The following parameters are required:
*
* * `txid` - txid of the UTXO
* * `script` - hex encoded script of the UTXO
* * `satoshis` - the amount in the UTXO (also accepts `amount`)
* * `vout` - the UTXO output index (also accepts `outputIndex` and `txOutNum`)
*
* Additional parameters may be required, depending on the Cast template.
*
* @param {Object} cast Cast template object
* @param {Object} params Cast parameters
* @constructor
*/
static unlockingScript(cast, params = {}) {
requires(params, 'unlockingScript', ['txid', 'script'])
requiresAny(params, 'unlockingScript', [
['satoshis', 'amount'],
['vout', 'outputIndex', 'txOutNum']
])
const txid = params.txid,
script = Script.fromHex(params.script),
satoshis = params.satoshis || params.amount,
satoshisBn = Bn(satoshis),
txOut = TxOut.fromProperties(satoshisBn, script),
nSequence = params.nSequence
let txOutNum
['vout', 'outputIndex', 'txOutNum']
.some(attr => {
if (typeof params[attr] === 'number') return txOutNum = params[attr]
})
delete params.txid && delete params.script
delete params.satoshis && delete params.amount
delete params.vout && delete params.outputIndex && delete params.txOutNum
return new UnlockingScript(cast.unlockingScript, txid, txOutNum, txOut, nSequence, params)
}
/**
* Returns the full generated script.
*
* Iterrates over the template and builds the script chunk by chunk.
*
* @returns {Script}
*/
getScript(ctx, params) {
let args
if (typeof params === 'undefined') {
params = { ...this.params, ...ctx }
params = { ...params, ...this.setup(params) }
args = [params]
} else {
params = { ...this.params, ...params }
params = { ...params, ...this.setup(params) }
args = [ctx, params]
}
this.validate(...args)
return this.script.reduce((script, chunk) => {
let data = typeof chunk === 'function' ? chunk(...args) : chunk
if (typeof data === 'undefined') return script;
if (data.buffer instanceof ArrayBuffer) {
script.writeBuffer(data)
} else if (typeof data === 'number') {
script.writeOpCode(data)
} else if (data.chunks) {
script.writeScript(data)
}
return script
}, new Script())
}
/**
* Returns the estimated size of the script, based on the Cast template.
*
* @returns {Number}
*/
getSize() {
let size
if (typeof this.size === 'function') {
size = this.size(this.params)
} else if (typeof this.size === 'number') {
size = this.size
} else {
// If no size prop is given on the cast, we must roughly estimate
console.warn("No 'size' prop given on the template. Size estimate may be innacurate.")
size = this.script.reduce((sum, chunk) => {
if (typeof chunk === 'function') {
// This is horrible. We have no idea how large the data will be so
// we just pluck a number out of thin air and say 20 bytes
sum += 21
} else if (chunk.buffer instanceof ArrayBuffer) {
sum += VarInt.fromNumber(chunk.length).buf.length + chunk.length
} else {
sum += 1
}
return sum
}, 0)
}
return VarInt.fromNumber(size).buf.length + size
}
/**
* Callback function that can be overriden in the Cast template.
*
* Returning an Object from this function will make all properties in that
* Object available to all chunks of the template.
*
* @returns {Object}
*/
setup() {
// noop
}
/**
* Callback function that can be overriden in the Cast template.
*
* This is called after `setup()` and receives all parameters that the template
* build functions receive. This provides a way to check parameters and throw
* appropriate errors if the parameters aren't correct to build the script.
*
* @param {Obejct} ctx
* @param {Obejct} params
*/
validate(...args) {
// noop
}
} |
JavaScript | class ViewWatchlists extends HTMLElement{
static TAG_NAME = 'view-watchlists';
static ONE_SECOND_DELAY = 3000;
static MESSAGE_CLOSE_DEPLAY = 3000;
/*
* data-watchlist-url: Url to load watch list from
* data-fire-event: Suppress the href click and just dispatch a click event.
*/
static get observedAttributes() { return ['data-watchlist-url', 'data-fire-event']; }
constructor() {
super();
logger.debug('Creating view watch list element');
this.userId = '';
this._loaded = false;
this._shouldFireOnly = false;
this._setUserId(window.location.searchObj.id);
this.attachShadow({mode: 'open'});
this._promiseOfContent = this._loadContent(
['/components/ViewWatchlists-Depricated/list.partial.html'],
[/*'/components/ViewWatchlists-Depricated/main.css'*/]
).then(()=>{
this._init(this.shadowRoot);
this._loaded = true;
});
}
attributeChangedCallback(name, oldValue, newValue) {
if(!this._loaded) {
this._promiseOfContent.then(()=> {
this.attributeChangedCallback(name, oldValue, newValue);
});
return;
}
if(oldValue === newValue) return;
switch(name) {
case 'data-watchlist-url':
this._loadWarchlistFromUrl(newValue);
break;
case 'data-fire-event':
this._shouldFireOnly = newValue === null ? false : true;
break;
}
}
_loadContent(html, css) {
return Promise.allSettled([
fetchHtmlElements(html).then(elems => this.shadowRoot.append(...elems)),
fetchStyleElements(css).then(elems => this.shadowRoot.append(...elems))
]).finally(()=>{
this.dispatchEvent(new CustomEvent('dynamic-content-loaded', {bubbles: true}));
logger.debug(ViewWatchlists.TAG_NAME + ' created');
});
}
_init(rootElem) {
this.watchlist = rootElem.querySelector('#watchlist');
this.listItemTemplate = rootElem.querySelector('#li-template');
this._attachEventListeners();
}
_setUserId(id) {
this.userId = id || '';
return this;
}
_attachEventListeners() {
this.addEventListener('add-list-item', (e)=>{
let elem = this.addListItem(e.detail.link, e.detail.listName),
detail = elem instanceof Error ? {error: elem, link: e.detail.link, listName: e.detail.listName} : {elem: elem};
this.dispatchEvent(new CustomEvent('list-item-added', {bubbles: true, detail: detail}));
});
this.addEventListener('remove-list-item', (e)=>{
let elems = this.removeListItem(e.detail.link),
detail = elems.length ? {elem: elems} : {error: new Error('Not found'), link: e.detail.link};
this.dispatchEvent(new CustomEvent('list-item-removed', {bubbles: true, detail: detail}));
});
this.addEventListener('load-list', (e)=>{
this._loadWarchlistFromUrl(e.detail.url);
});
}
/*
* Expected Response:
* {
* "watchlists": {
* "wine list":"9XcsXa1ZWvItsdXtK2gmFpgkbcY=",
* "wine list4":"9XcsXa1ZWvItsdXtK2gmFpgkbcY="
* }
* }
*/
_requestWatchlist(url) {
return fetch(url, {
method: 'GET',
redirect: 'follow'
}).then(response=>response.json())
.then(data=>data.watchlists);
}
_loadWatchlist(watchlists) {
let elems = [];
for(let list in watchlists) {
elems.push(this.addListItem(`/api/user/${this.userId}/watchlist/${watchlists[list]}`, list));
}
return elems;
}
_loadWarchlistFromUrl(url) {
return this._requestWatchlist(url)
.then(this._loadWatchlist.bind(this))
.then((elems)=>{
let detail = elems.length ? {elem: elems} : {error: new Error('Failed to load'), url: url};
this.dispatchEvent(new CustomEvent('watchlist-loaded', {bubbles: true, detail: detail}));
}).catch(e=>{
logger.error(e);
});
}
_createListItem(link, listName) {
let docFrag = this.listItemTemplate.content.cloneNode(true),
anchor = docFrag.querySelector('a');
anchor.innerText = listName;
anchor.href = link;
anchor.addEventListener('click', (e)=> {
e.preventDefault();
this.dispatchEvent(new CustomEvent('watchlist-item-click', {bubbles: true, detail: {href: link, name: listName}}));
return false;
});
return docFrag;
}
addListItem(link, listName) {
if(!link || !listName) return new Error('Name and link are required.');
let elem = this._createListItem(link, listName);
this.watchlist.appendChild(elem);
return elem;
}
removeListItem(link) {
let removed = [];
Array.prototype.slice.call(this.watchlist.querySelectorAll(`a[href="${link}"]`)).map(e=> {
while(e.tagName !== 'li') e = e.parent;
if(e.tagName === 'li') {
removed.push(e);
e.remove();
}
});
return removed;
}
static __registerElement() {
customElements.define(ViewWatchlists.TAG_NAME, ViewWatchlists);
}
} |
JavaScript | class Validate {
/**
* This return a validation chain for signup data.
* @returns {[{ValidationChain}]}.
*/
static signup() {
return [
check('firstName', 'First name should be valid.').isString(),
check('lastName', 'Last name should be valid.').isString(),
check('email', 'Invalid email address, example: [email protected].').isEmail(),
check('password', 'Password should be provided and must be alphanumeric with atleast 8 charactors.').isLength({ min: 8 }).isAlphanumeric(),
check('country', 'Provided country is not valid.').isString().isLength({ min: 3 }),
check('gender', 'Provided gender is not valid.').isString().isLength({ min: 3 }).optional(),
check('birthday', 'Provided birthday is not valid.').isString().isLength({ min: 3 }).optional(),
check('phoneNumber', 'Provided phone number is not valid.').isString().isLength({ min: 10, max: 13 }).optional()
];
}
/**
* validating User Inputs
* @returns {Object} A user object with selected fields
* excluing the password
*/
static signin() {
return [
// username must be an email
check('email', 'Invalid email address, example: [email protected].').isEmail(),
// password must be at least 5 chars long
check('password', 'Invalid password, your password should be alphanumeric with atleast 8 charactors.').isLength({ min: 8 }).isAlphanumeric()
];
}
/**
* this function validate reset password form
* @returns {Object} user response
*/
static resetPassword() {
return [
check('password', 'Password should be provided and must be alphanumeric with atleast 8 charactors.').isLength({ min: 8 }).isAlphanumeric(),
check('confirmPassword', 'conform Password should be provided and must be alphanumeric with atleast 8 charactors.').isLength({ min: 8 }).isAlphanumeric()
];
}
/**
* this function send reset password link via email
* @returns {Object} user response
*/
static sendResetPasswordLink() {
return [
check('email', 'Invalid email address, example: [email protected].').isEmail()
];
}
/**
* this function validate trip requests
* @returns {Object} user response
*/
static tripsValidation() {
return [
check('From', 'origin should be valid.').isInt(),
check('To', 'destination should be valid.').isInt(),
check('reason', 'reason should be valid.').isString(),
check('accommodation', 'accomodation should be valid.').isInt().optional(),
];
}
/**
* Validate user preference data
* @returns {[{ValidationChain}]}.
*/
static userPreference() {
return [
check('appNotification', 'App notification need to be boolean').isBoolean(),
check('emailNotification', 'Email notification need to be boolean').isBoolean()
];
}
/**
* Validate when updating notification
* @returns {[{ValidationChain}]}.
*/
static validateOnUpdateNotification() {
return [
check('isRead', 'isRead needs to be a boolean').isBoolean(),
];
}
/**
* This method validate a comment on trip request
* @returns { Object } user message
*/
static CommentValidation() {
return [
check('comment', 'Comment should be valid.').isLength({ min: 3 }).isString()
];
}
/**
* this function validate creating accomodation
* @returns {Object} user response
*/
static accomodationValidation() {
return [
check('accommodationName', 'accomodation name should be valid.').isString(),
check('description', 'accomodation description should be valid.').isString().optional(),
check('locationId', 'accommodation location should be valid.').isInt(),
check('owner', 'owner name should be valid.').isString(),
check('category', 'accomodation category should be valid.').isString().optional(),
check('images', 'images should be valid.').isArray().optional(),
check('rooms', 'rooms should be valid.').isArray().optional(),
check('services', 'accomodation services should be valid.').isArray().optional(),
check('amenities', 'accomodation amenities should be valid.').isArray().optional(),
];
}
/**
* This method validate a booking an accommodation facility request
* @returns {[{ValidationChain}]}.
*/
static bookingValidation() {
return [
check('tripId', 'tripId needs to be a number').isInt(),
check('accommodationId', 'accommodationId needs to be a number').isInt(),
check('roomTypeId', 'roomTypeId needs to be a number').isInt(),
check('departureDate', 'departureDate needs to be a date format').toDate(),
check('checkoutDate', 'checkoutDate needs to be a date format').toDate(),
];
}
/**
* This method validate a like or unlike accommodation request
* @returns { Object } user message
*/
static likeOrUnlikeValidation() {
return [
check('isLike', 'isLike needs to be a boolean').isBoolean(),
];
}
} |
JavaScript | class Result {
constructor(result, {odd}) {
this.result = result;
eventable(this);
gui_helpers(this);
const classes = [isUnfree(result["meta"]["license"]) ? "is-unfree" : "is-free"];
const $row = tr(`class="result ${odd ? "odd" : "even"} ${classes.join(" ")}"`);
[
"name",
"attr",
"meta.description",
].forEach((attr) => {
const $td = td();
if (get(result, attr)) {
if (attr === "name") {
const $button = html(`<button />`)[0];
$button.innerText = get(result, attr);
$td.appendChild($button);
}
else {
$td.innerText = get(result, attr);
}
}
$row.appendChild($td);
});
const $details_row = tr(`class="details is-hidden ${odd ? "odd" : "even"} ${classes.join(" ")}"`);
$details_row.appendChild(td(`colspan="3"`));
$details_row.querySelectorAll("td")[0]
.appendChild(html(`
<div class="search-details">
<table>
<tbody>
</tbody>
</table>
</div>
`)[0]);
const $details = $details_row.querySelectorAll(".search-details tbody")[0];
each({
"install": "Install command",
"unfree": "unfree",
"meta_position": "Nix expression",
"meta_platforms": "Platforms",
"meta_homepage": "Homepage",
"meta_license": "License",
"meta_maintainers": "Maintainers",
"meta_long_description": "Long description",
}, (label, attr) => {
const $tr = tr();
if (attr === "unfree") {
if (isUnfree(get(result, "meta.license"))) {
const $td = td(`colspan="2" className="unfree-note"`);
append(
$td,
html(`
<em>
This package is unfree.
See <a href="https://nixos.org/nixpkgs/manual/#sec-allow-unfree">chapter 6.2</a> of
the manual for more informations.
</em>
`)
);
$tr.appendChild($td);
}
}
else {
const $th = th();
$tr.appendChild($th);
$th.innerText = label;
const $td = td();
$tr.appendChild($td);
const fn = "node_" + attr;
if (this[fn]) {
append($td, this[fn]());
}
else {
append($td, html("<code>TODO</code>"));
}
}
$details.appendChild($tr);
});
this.$nodes = [
$row,
$details_row,
];
this.$details_row = $details_row;
this.$row = $row;
$row.addEventListener("click", (...args) => this.on_click(...args));
}
on_click(...args) {
const {shown} = this;
this.sendEvent("click", ...args);
this.shown = shown;
this.toggle();
}
show() {
this.shown = true;
this.$details_row.classList.remove("is-hidden");
}
hide() {
this.shown = false;
this.$details_row.classList.add("is-hidden");
}
toggle() {
if (this.shown) {
this.hide();
}
else {
this.show();
}
}
node_install() {
const {result} = this;
// FIXME : fetch likely channel name (nixpkgs/nixos)
const channel = "nixos";
const node = html(`
<tt>
<span class="command">
nix-env -iA ${channel}.<span class="attrname"></span>
</span>
</tt>
<em class="muted">(NixOS channel)</em>
`);
node[0].querySelectorAll(".attrname")[0].innerText = result["attr"];
return node;
}
node_meta_position() {
const {result} = this;
const {meta: {position}} = result;
// FIXME : get the commit in a less hacky manner
const commit = window.APP.channel_data["commit"];
if (!position) {
return not_specified();
}
const $link = html(`<a />`);
$link[0].innerText = position.replace(/:[0-9]+$/, "");
$link[0].href = githubLink(commit, position||"");
return $link;
}
node_meta_platforms() {
const {result} = this;
const {attr, meta: {platforms}} = result;
// FIXME : fetch branch name.
const branch = "release-17.09";
if (!platforms || platforms.length < 1) {
return not_specified();
}
const $list = html(`<ul class="platforms-list" />`);
append(
$list[0],
platforms
.filter((platform) => PLATFORMS.indexOf(platform) > -1)
.map((platform) => {
const $li = html(`<li />`)[0];
const $link = html(`<a />`)[0];
$link.appendChild(html(`<tt>${platform}</tt>`)[0]);
$link.href = hydraLink(attr, platform, branch);
$li.appendChild($link);
return $li;
})
);
return $list;
}
node_meta_homepage() {
const {result} = this;
const {meta: {homepage}} = result;
if (homepage && homepage.length > 0) {
const $link = html(`<a />`);
$link[0].innerText = homepage;
$link[0].href = homepage;
$link[0].rel = "nofollow";
return $link;
}
return not_specified();
}
node_meta_license() {
const {result} = this;
const {meta: {license}} = result;
if (license) {
return licenseHTML(license);
}
return not_specified();
}
node_meta_maintainers() {
const {result} = this;
const {meta: {maintainers}} = result;
if (maintainers && maintainers.length > 0) {
const $span = html(`<span />`);
$span[0].innerText = maintainers.join(", ");
return $span;
}
return not_specified();
}
node_meta_long_description() {
const {result} = this;
const {meta: {longDescription}} = result;
if (longDescription && longDescription.length > 0) {
const $pre = html(`<pre />`);
$pre[0].innerText = longDescription;
return $pre;
}
return not_specified();
}
} |
JavaScript | class PromotionOrderEntryConsumed {
/**
* Constructs a new <code>PromotionOrderEntryConsumed</code>.
* @alias module:models/PromotionOrderEntryConsumed
* @class
*/
constructor() {
/**
*
* @member {String} code
*/
this.code = undefined
/**
*
* @member {Number} adjustedUnitPrice
*/
this.adjustedUnitPrice = undefined
/**
*
* @member {Number} orderEntryNumber
*/
this.orderEntryNumber = undefined
/**
*
* @member {Number} quantity
*/
this.quantity = undefined
}
/**
* Constructs a <code>PromotionOrderEntryConsumed</code> from a plain
* JavaScript object, optionally creating a new instance. Copies all relevant
* properties from <code>data</code> to <code>obj</code> if supplied or a new
* instance if not.
* @param {Object} data The plain JavaScript object bearing properties of
* interest.
* @param {module:models/PromotionOrderEntryConsumed} obj Optional
* instance to populate.
* @return {module:models/PromotionOrderEntryConsumed} The populated
* <code>PromotionOrderEntryConsumed</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PromotionOrderEntryConsumed()
if (data.hasOwnProperty('code')) {
obj.code = ApiClient.convertToType(data.code, 'String')
}
if (data.hasOwnProperty('adjustedUnitPrice')) {
obj.adjustedUnitPrice = ApiClient.convertToType(data.adjustedUnitPrice, 'Number')
}
if (data.hasOwnProperty('orderEntryNumber')) {
obj.orderEntryNumber = ApiClient.convertToType(data.orderEntryNumber, 'Number')
}
if (data.hasOwnProperty('quantity')) {
obj.quantity = ApiClient.convertToType(data.quantity, 'Number')
}
}
return obj
}
} |
JavaScript | @MJMLElement({
tagName: 'mj-body',
attributes: {
'width': '600'
},
inheritedAttributes: [
'width'
]
})
class Body extends Component {
styles = this.getStyles()
getStyles () {
const { mjAttribute } = this.props
return {
div: {
backgroundColor: mjAttribute('background-color'),
fontSize: mjAttribute('font-size')
}
}
}
render () {
const { renderWrappedOutlookChildren, mjAttribute, children } = this.props
const { width } = widthParser(mjAttribute('width'))
return (
<div
className="mj-body"
data-background-color={mjAttribute('background-color')}
data-width={width}
style={this.styles.div}>
{renderWrappedOutlookChildren(children)}
</div>
)
}
} |
JavaScript | class Tree {
/**
* Creates a Tree Object
*/
constructor() {
}
/**
* Creates a node/edge structure and renders a tree layout based on the input data
*
* @param treeData an array of objects that contain parent/child information.
*/
createTree(treeData) {
// ******* TODO: PART VI *******
//Create a tree and give it a size() of 800 by 300.
let size = [800, 400];
let tree = d3.stratify()
.id((d, i) => i)
.parentId(d => d.ParentGame)(treeData)
.each(d => (d.Name = d.data.Team, d.Winner = d.data.Wins));
let treemap = d3.tree().size(size);
this.nodes = treemap(d3.hierarchy(tree, d => d.children));
let g = d3.select('#tree')
.attr('transform', 'translate(100, 25)');
let links = g.selectAll('.link')
.data(this.nodes.descendants().slice(1))
.enter()
.append('path')
.attr('class', 'link')
.attr('d', d => ('M' + d.y + ',' + d.x
+ 'C' + (d.y + d.parent.y) / 2 + ',' + d.x
+ ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x
+ ' ' + d.parent.y + ',' + d.parent.x));
let nodes = g.selectAll('.node')
.data(this.nodes.descendants())
.enter()
.append('g')
.attr('class', d => (d.data.Winner === "1" ? 'node winner' : 'node'))
.attr('transform', d => ('translate(' + d.y + ',' + d.x + ')'));
nodes.append('circle')
.attr('r', 6);
// Align based on parents position:
nodes.append('text')
.attr('x', d => (d.children ? -13 : 13))
.attr('y', d => (d.parent && d.children ? (d.data.Name === d.parent.children[0].data.Name ? -13 : 13) : 0))
.attr('dy', '0.33em')
.style('text-anchor', d => (d.children ? 'end' : 'start'))
.text(d => d.data.Name);
};
/**
* Updates the highlighting in the tree based on the selected team.
* Highlights the appropriate team nodes and labels.
*
* @param row a string specifying which team was selected in the table.
*/
updateTree(row) {
// ******* TODO: PART VII *******
d3.selectAll('.link')
.filter(d=> {
if(row.value.type==='game') {
let one = row.key===d.data.Name && row.value.opponent===d.data.data.Opponent;
let two = row.key===d.data.data.Opponent && row.value.opponent===d.data.Name;
return one || two;
}
else {
return row.key===d.data.Name && row.key===d.parent.data.Name;
}
})
.classed('selected', true);
d3.selectAll('.node')
.selectAll('text')
.filter(d=> {
if(row.value.type==='game') {
let one = row.key===d.data.Name && row.value.opponent===d.data.data.Opponent;
let two = row.key===d.data.data.Opponent && row.value.opponent===d.data.Name;
return one || two;
}
else {
return row.key===d.data.Name;
}
})
.classed('selectedLabel', true);
}
/**
* Removes all highlighting from the tree.
*/
clearTree() {
// ******* TODO: PART VII *******
d3.selectAll('.link')
.classed('selected', false);
d3.selectAll('.node')
.selectAll('text')
.classed('selectedLabel', false);
}
} |
JavaScript | class Sprite extends WebGLObject {
/**
* @param {Object} opts
* @constructor
*/
constructor(opts) {
super(opts);
this.isSprite = true;
}
} |
JavaScript | class UtilInherits {
constructor() {
this.inheritsNode = undefined;
this.detectors = [
new RequireUtilDetector(),
new RequireUtilInheritsDetector(),
new ImportUtilDetector(),
];
}
/**
* Process a node and return inheritance details if found.
* @param {Object} node
* @param {Object} parent
* @returns {Object/undefined} m
* {String} m.className
* {Node} m.superClass
* {Object[]} m.relatedExpressions
*/
process(node, parent) {
let m;
if (parent && parent.type === 'Program' && (m = this.detectInheritsNode(node))) {
this.inheritsNode = m;
}
else if (this.inheritsNode && (m = this.matchUtilInherits(node))) {
return {
className: m.className,
superClass: m.superClass,
relatedExpressions: [{node, parent}]
};
}
}
detectInheritsNode(node) {
for (const detector of this.detectors) {
let inheritsNode;
if ((inheritsNode = detector.detect(node))) {
return inheritsNode;
}
}
}
// Discover usage of this.inheritsNode
//
// Matches: <this.utilInherits>(<className>, <superClass>);
matchUtilInherits(node) {
return matches({
type: 'ExpressionStatement',
expression: {
type: 'CallExpression',
callee: this.inheritsNode,
arguments: [
{
type: 'Identifier',
name: extractAny('className')
},
extractAny('superClass')
]
}
}, node);
}
} |
JavaScript | class HomebridgeForm extends api.exported.FormObject.class {
/**
* Constructor
*
* @param {number} id Identifier
* @param {string} alexaUsername The Alexa username
* @param {string} alexaPassword The Alexa password
* @param {boolean} displayHomekitTile The tile value
* @param {boolean} clearHomebridgeCache Clear cache
* @param {string} homebridgeIdentifier The homebridge identifier - auto filled
* @returns {HomebridgeForm} The instance
*/
constructor(id, alexaUsername, alexaPassword, displayHomekitTile = true, clearHomebridgeCache = false, homebridgeIdentifier = null) {
super(id);
/**
* @Property("alexaUsername");
* @Type("string");
* @Title("homebridge.alexa.username");
*/
this.alexaUsername = alexaUsername;
/**
* @Property("alexaPassword");
* @Type("string");
* @Display("password");
* @Title("homebridge.alexa.password");
*/
this.alexaPassword = alexaPassword;
/**
* @Property("displayHomekitTile");
* @Type("boolean");
* @Default(true);
* @Title("homebridge.tile.qr");
*/
this.displayHomekitTile = displayHomekitTile;
/**
* @Property("clearHomebridgeCache");
* @Type("boolean");
* @Default(false);
* @Title("homebridge.clear.cache");
*/
this.clearHomebridgeCache = clearHomebridgeCache;
/**
* @Property("homebridgeIdentifier");
* @Type("string");
* @Hidden(true);
*/
this.homebridgeIdentifier = homebridgeIdentifier;
}
/**
* Convert json data
*
* @param {object} data Some key / value data
* @returns {HomebridgeForm} A form object
*/
json(data) {
return new HomebridgeForm(data.id, data.alexaUsername, data.alexaPassword, data.displayHomekitTile, data.clearHomebridgeCache, data.homebridgeIdentifier);
}
} |
JavaScript | class Homebridge {
/**
* Constructor
*
* @param {PluginAPI} api A plugin api
* @returns {Homebridge} The instance
*/
constructor(api) {
this.api = api;
this.devices = [];
this.sensors = [];
this.alarm = [];
this.cameras = [];
this.camerasToken = api.webAPI.getTokenWithIdentifier("23c3543b", 50000000); // 578 days
this.generateHapDevices();
this.generateHapSensors();
this.generateHapAlarm();
this.generateHapCameras();
if (!process.env.TEST) {
this.service = new HomebridgeService(api, this.devices, this.sensors);
api.servicesManagerAPI.add(this.service);
api.coreAPI.registerEvent(api.deviceAPI.constants().EVENT_UPDATE_CONFIG_DEVICES, () => {
this.service.stop();
this.service.init(this.devices, this.sensors, this.cameras);
this.service.start(() => {
this.generateHapDevices();
this.generateHapSensors();
this.generateHapAlarm();
this.generateHapCameras();
this.service.init(this.devices, this.sensors, this.cameras);
});
});
api.coreAPI.registerEvent(api.constants().CORE_EVENT_READY, () => {
this.service.stop();
this.service.start(() => {
this.generateHapDevices();
this.generateHapSensors();
this.generateHapAlarm();
this.generateHapCameras();
this.service.init(this.devices, this.sensors, this.cameras);
});
});
api.configurationAPI.setUpdateCb((conf) => {
this.service.stop();
if (conf.clearHomebridgeCache) {
this.service.clearCache();
conf.clearHomebridgeCache = false;
conf.homebridgeIdentifier = null;
api.configurationAPI.saveData(conf);
}
this.service.init(this.devices, this.sensors, this.cameras);
this.service.start(() => {
this.generateHapDevices();
this.generateHapSensors();
this.generateHapAlarm();
this.generateHapCameras();
this.service.init(this.devices, this.sensors, this.cameras);
});
});
}
}
/**
* Generate cameras config
*/
generateHapCameras() {
this.cameras = [];
Object.keys(api.cameraAPI.getCameras()).forEach((cameraId) => {
const camera = api.cameraAPI.getCamera(cameraId);
let mode = "static";
let url = api.environmentAPI.getLocalAPIUrl() + "camera/get/" + mode + "/" + cameraId + "/?t=" + this.camerasToken;
if (camera.rtspSupport()) {
url = camera.rtspUrl;
} else if (camera.mjpegSupport()) {
url = camera.mjpegUrl;
}
const urlStill = api.environmentAPI.getLocalAPIUrl() + "camera/get/static/" + cameraId + "/?t=" + this.camerasToken;
this.cameras.push({
name: this.api.translateAPI.t("homebridge.camera", camera.configuration.name),
videoConfig: {
source: "-i " + url,
stillImageSource: "-i " + urlStill,
maxStreams: 2,
maxWidth: 1280,
maxHeight: 720,
maxFPS: 30
}
});
});
}
/**
* Generate lights config
*/
generateHapDevices() {
this.devices = [];
this.devicesName = [];
this.api.deviceAPI.getDevices().forEach((device) => {
if (device.visible) {
let i = 2;
let name = device.name;
if (this.devicesName.indexOf(name) >= 0) {
name = name + " " + i;
i++;
} else {
this.devicesName.push(name);
}
if (device.bestDeviceType == this.api.deviceAPI.constants().DEVICE_TYPE_LIGHT_DIMMABLE_COLOR || device.bestDeviceType == this.api.deviceAPI.constants().DEVICE_TYPE_LIGHT_DIMMABLE || device.bestDeviceType == this.api.deviceAPI.constants().DEVICE_TYPE_LIGHT || device.bestDeviceType == this.api.deviceAPI.constants().DEVICE_TYPE_AUTOMATIC_WATERING) {
this.devices.push({
accessory: "Smarties lights",
identifier: device.id,
name: name,
coreApi: null,
status: device.status,
device: device,
deviceTypes: api.deviceAPI.getDeviceTypes(device),
deviceConstants: api.deviceAPI.constants()
});
} else if (device.bestDeviceType == this.api.deviceAPI.constants().DEVICE_TYPE_GATE) {
this.devices.push({
accessory: "Smarties gate",
identifier: device.id,
name: name,
coreApi: null,
status: device.status,
device: device,
deviceTypes: api.deviceAPI.getDeviceTypes(device),
deviceConstants: api.deviceAPI.constants()
});
} else if (device.bestDeviceType == this.api.deviceAPI.constants().DEVICE_TYPE_SHUTTER) {
this.devices.push({
accessory: "Smarties shutter",
identifier: device.id,
name: this.api.translateAPI.t("homebridge.shutter", name),
coreApi: null,
status: device.status,
device: device,
deviceTypes: api.deviceAPI.getDeviceTypes(device),
deviceConstants: api.deviceAPI.constants()
});
} else if (device.bestDeviceType == this.api.deviceAPI.constants().DEVICE_TYPE_LOCK) {
this.devices.push({
accessory: "Smarties lock",
identifier: device.id,
name: name,
coreApi: null,
status: device.status,
device: device,
deviceTypes: api.deviceAPI.getDeviceTypes(device),
deviceConstants: api.deviceAPI.constants()
});
}
}
});
}
/**
* Generate alarm config
*/
generateHapAlarm() {
this.alarm = [];
this.alarm.push({
accessory: "Smarties alarm",
name: api.translateAPI.t("alarm.tile.title")
});
}
/**
* Generate lights config
*/
generateHapSensors() {
this.sensors = [];
this.sensorsName = [];
let i = 2;
const temperatureSensors = this.api.sensorAPI.getSensors("TEMPERATURE");
Object.keys(temperatureSensors).forEach((sensorKey) => {
let sensor = this.api.translateAPI.t("homebridge.sensor", temperatureSensors[sensorKey]);
if (this.sensorsName.indexOf(sensor) >= 0) {
sensor = sensor + " " + i;
i++;
} else {
this.sensorsName.push(sensor);
}
this.sensors.push({
accessory: "Smarties temperature sensor",
identifier: sensorKey,
name: sensor
});
});
const humiditySensors = this.api.sensorAPI.getSensors("HUMIDITY");
Object.keys(humiditySensors).forEach((sensorKey) => {
let sensor = this.api.translateAPI.t("homebridge.sensor", humiditySensors[sensorKey]);
if (this.sensorsName.indexOf(sensor) >= 0) {
sensor = sensor + " " + i;
i++;
} else {
this.sensorsName.push(sensor);
}
this.sensors.push({
accessory: "Smarties humidity sensor",
identifier: sensorKey,
name: sensor
});
});
const contactSensors = this.api.sensorAPI.getSensors("CONTACT");
Object.keys(contactSensors).forEach((sensorKey) => {
let sensor = this.api.translateAPI.t("homebridge.sensor", contactSensors[sensorKey]);
if (this.sensorsName.indexOf(sensor) >= 0) {
sensor = sensor + " " + i;
i++;
} else {
this.sensorsName.push(sensor);
}
this.sensors.push({
accessory: "Smarties contact sensor",
identifier: sensorKey,
name: sensor
});
});
const presenceSensors = this.api.sensorAPI.getSensors("PRESENCE");
Object.keys(presenceSensors).forEach((sensorKey) => {
let sensor = this.api.translateAPI.t("homebridge.sensor", presenceSensors[sensorKey]);
if (this.sensorsName.indexOf(sensor) >= 0) {
sensor = sensor + " " + i;
i++;
} else {
this.sensorsName.push(sensor);
}
this.sensors.push({
accessory: "Smarties motion sensor",
identifier: sensorKey,
name: sensor
});
});
const lightSensors = this.api.sensorAPI.getSensors("LIGHT");
Object.keys(lightSensors).forEach((sensorKey) => {
let sensor = this.api.translateAPI.t("homebridge.sensor", lightSensors[sensorKey]);
if (this.sensorsName.indexOf(sensor) >= 0) {
sensor = sensor + " " + i;
i++;
} else {
this.sensorsName.push(sensor);
}
this.sensors.push({
accessory: "Smarties light sensor",
identifier: sensorKey,
name: sensor
});
});
const waterLeakSensors = this.api.sensorAPI.getSensors("WATER-LEAK");
Object.keys(waterLeakSensors).forEach((sensorKey) => {
let sensor = this.api.translateAPI.t("homebridge.sensor", waterLeakSensors[sensorKey]);
if (this.sensorsName.indexOf(sensor) >= 0) {
sensor = sensor + " " + i;
i++;
} else {
this.sensorsName.push(sensor);
}
this.sensors.push({
accessory: "Smarties leak sensor",
identifier: sensorKey,
name: sensor
});
});
const smokeSensors = this.api.translateAPI.t("homebridge.sensor", this.api.sensorAPI.getSensors("SMOKE"));
Object.keys(smokeSensors).forEach((sensorKey) => {
let sensor = smokeSensors[sensorKey];
if (this.sensorsName.indexOf(sensor) >= 0) {
sensor = sensor + " " + i;
i++;
} else {
this.sensorsName.push(sensor);
}
this.sensors.push({
accessory: "Smarties smoke sensor",
identifier: sensorKey,
name: sensor
});
});
}
} |
JavaScript | class EzsigntemplateResponseCompoundAllOf {
/**
* Constructs a new <code>EzsigntemplateResponseCompoundAllOf</code>.
* @alias module:eZmaxAPI/model/EzsigntemplateResponseCompoundAllOf
* @param a_objEzsigntemplatesigner {Array.<module:eZmaxAPI/model/EzsigntemplatesignerResponseCompound>}
*/
constructor(a_objEzsigntemplatesigner) {
EzsigntemplateResponseCompoundAllOf.initialize(this, a_objEzsigntemplatesigner);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, a_objEzsigntemplatesigner) {
obj['a_objEzsigntemplatesigner'] = a_objEzsigntemplatesigner;
}
/**
* Constructs a <code>EzsigntemplateResponseCompoundAllOf</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:eZmaxAPI/model/EzsigntemplateResponseCompoundAllOf} obj Optional instance to populate.
* @return {module:eZmaxAPI/model/EzsigntemplateResponseCompoundAllOf} The populated <code>EzsigntemplateResponseCompoundAllOf</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new EzsigntemplateResponseCompoundAllOf();
if (data.hasOwnProperty('objEzsigntemplatedocument')) {
obj['objEzsigntemplatedocument'] = EzsigntemplatedocumentResponse.constructFromObject(data['objEzsigntemplatedocument']);
}
if (data.hasOwnProperty('a_objEzsigntemplatesigner')) {
obj['a_objEzsigntemplatesigner'] = ApiClient.convertToType(data['a_objEzsigntemplatesigner'], [EzsigntemplatesignerResponseCompound]);
}
}
return obj;
}
/**
* @return {module:eZmaxAPI/model/EzsigntemplatedocumentResponse}
*/
getObjEzsigntemplatedocument() {
return this.objEzsigntemplatedocument;
}
/**
* @param {module:eZmaxAPI/model/EzsigntemplatedocumentResponse} objEzsigntemplatedocument
*/
setObjEzsigntemplatedocument(objEzsigntemplatedocument) {
this['objEzsigntemplatedocument'] = objEzsigntemplatedocument;
}
/**
* @return {Array.<module:eZmaxAPI/model/EzsigntemplatesignerResponseCompound>}
*/
getAObjEzsigntemplatesigner() {
return this.a_objEzsigntemplatesigner;
}
/**
* @param {Array.<module:eZmaxAPI/model/EzsigntemplatesignerResponseCompound>} a_objEzsigntemplatesigner
*/
setAObjEzsigntemplatesigner(a_objEzsigntemplatesigner) {
this['a_objEzsigntemplatesigner'] = a_objEzsigntemplatesigner;
}
} |
JavaScript | class WidgetList extends Array {
constructor(elements) {
super();
// convert single item to array of items
if (!Array.isArray(elements)) {
elements = [elements];
}
elements.forEach((el) => {
this.push(el);
});
}
/**
* Convert array-like object containing HTMLElements or Widgets
* to WidgetList.
* @param {array} other Array-like object.
* @return {WidgetList} Created WidgetList from items.
*/
static from(other) {
// ensure that `other` is an Array
other = Array.from(other);
return new WidgetList(other);
}
/**
* Returns an array that contains the HTMLElements from Widget items.
* @return {array} Array of HTMLElements
*/
elements() {
return this.map((item) => item.el);
}
/**
* Push one or more HTMLElements or Widgets to WidgetList.
* @param {HTMLElement|Widget} el Element to add.
* @return {number} The new length property of the list.
*/
push(el) {
if (DomUtil.isElement(el)) {
el = new Widget(el);
}
if (el instanceof Widget) {
return Array.prototype.push.call(this, el);
}
return this.length;
}
/**
* Unshift one or more HTMLElements or Widgets to WidgetList.
* @param {HTMLElement|Widget} el Element to add.
* @return {number} The new length property of the list.
*/
unshift(el) {
if (DomUtil.isElement(el)) {
el = new Widget(el);
}
if (el instanceof Widget) {
return Array.prototype.unshift.call(this, el);
}
return this.length;
}
/**
* Set every items html to the given value.
* @param {string} value HTML string
*/
setHTML(value) {
this.forEach((el) => {
el.html = value;
});
}
/**
* Set every items text to the given value.
* @param {string} value Text string
*/
setText(value) {
this.forEach((el) => {
el.text = value;
});
}
} |
JavaScript | class Connectable {
/**
* for input
*/
INPUT() {}
/**
* for output
*/
OUTPUT() {}
} |
JavaScript | class HomePage extends React.Component {
render (fname, lname) {
return <h1>Hello, {this.props.firstName} {this.props.lastName}</h1>;
}
} |
JavaScript | class Either {
constructor(type, l, r) {
this.type = type;
this.l = l;
this.r = r;
this.of = this.unit;
}
static left(l) {
return new Either(EitherType.Left, l);
}
static right(r) {
return new Either(EitherType.Right, null, r);
}
isLeft() {
return this.caseOf({ left: () => true, right: () => false });
}
isRight() {
return !this.isLeft();
}
unit(t) {
return Either.right(t);
}
flatMap(f, transf) {
if (transf === undefined) {
const g = f;
return this.flatMap(g, leftUnitTransformer());
}
if (this.type === EitherType.Right) {
return f(this.r);
}
else {
return transf.left(this.l);
}
}
map(f) {
return this.flatMap(v => this.unit(f(v)));
}
caseOf(pattern) {
return this.type === EitherType.Right ?
pattern.right(this.r) :
pattern.left(this.l);
}
toRight() {
if (this.isRight()) {
return typescript_optional_1.default.ofNullable(this.r);
}
return typescript_optional_1.default.empty();
}
toLeft() {
if (this.isLeft()) {
return typescript_optional_1.default.ofNullable(this.l);
}
return typescript_optional_1.default.empty();
}
} |
JavaScript | class Buy extends Component {
constructor(props) {
super(props);
this.state = {
formOpen: false,
resultsMessage: ''
};
this.toggleFormVisibility = this.toggleFormVisibility.bind(this);
}
async componentDidMount() {
await this.props.getOrderDetails(this.props.orderId);
}
componentWillReceiveProps(nextProps) {
if (nextProps.buyOrderError !== null) {
this.setState({
resultsMessage: `Error: ${this.props.buyOrderError}`,
formOpen: false
});
} else if (this.props.buyOrderTx) {
this.setState({
resultsMessage: `Buy Order result ${this.props.buyOrderTx}`,
formOpen: false
});
}
}
toggleFormVisibility() {
this.setState({
formOpen: !this.state.formOpen
});
}
render() {
return (
<div className="container">
<div id="buy-button">
<button className="btn btn-info" onClick={this.toggleFormVisibility}>
Buy Order
</button>
</div>
<Collapse isOpen={this.state.formOpen}>
<div id="buy-form">
<h4 className="center-text">Buy Order</h4>
<BuyFormContainer />
</div>
</Collapse>
{this.state.resultsMessage && (
<div id="results-message" className="text-center">
{this.state.resultsMessage}
</div>
)}
</div>
);
}
} |
JavaScript | class FeeManager {
constructor(
regularTransactionFee,
invitationToChannelFee,
metisChannelMemberFee,
arbitraryMessageFee,
aliasAssigmentFee,
accountPropertyFee,
accountPropertyDeletionFee,
newUserFundingFee,
newTableFundingFee,
accountRecordFee,
ordinaryPaymentFee,
metisMessageFee
) {
if(!regularTransactionFee){throw new Error('missing regularTransactionFee')}
if(!invitationToChannelFee){throw new Error('missing invitationToChannelFee')}
if(!metisChannelMemberFee){throw new Error('missing metisChannelMemberFee')}
if(!arbitraryMessageFee){throw new Error('missing arbitraryMessageFee')}
if(!aliasAssigmentFee){throw new Error('missing aliasAssigmentFee')}
if(!accountPropertyFee){throw new Error('missing accountPropertyFee')}
if(!accountPropertyDeletionFee){throw new Error('missing accountPropertyDeletionFee')}
if(!newUserFundingFee){throw new Error('missing newUserFundingFee')}
if(!newTableFundingFee){throw new Error('missing newTableFundingFee')}
if(!accountRecordFee){throw new Error('missing accountRecordFee')}
if(!ordinaryPaymentFee){throw new Error('missing ordinaryPaymentFee')}
if(!metisMessageFee){throw new Error('missing metisMessageFee')}
this.fees = [];
this.fees.push({
feeType: FeeManager.feeTypes.metisMessage,
fee: metisMessageFee,
type: FeeManager.TransactionTypes.messaging_voting_aliases,
subtype: FeeManager.JupiterTypeOneSubtypes.metisMessage
})
this.fees.push({
feeType: FeeManager.feeTypes.regular_transaction,
fee: regularTransactionFee,
type: FeeManager.TransactionTypes.messaging_voting_aliases,
subtype: FeeManager.JupiterTypeOneSubtypes.arbitraryMessage
})
this.fees.push({
feeType: FeeManager.feeTypes.account_record,
fee: accountRecordFee,
type: FeeManager.TransactionTypes.messaging_voting_aliases,
subtype: FeeManager.JupiterTypeOneSubtypes.metisAccountRecord
})
this.fees.push({
feeType: FeeManager.feeTypes.invitation_to_channel,
fee: invitationToChannelFee,
type: FeeManager.TransactionTypes.messaging_voting_aliases,
subtype: FeeManager.JupiterTypeOneSubtypes.metisChannelInvitation
})
this.fees.push({
feeType: FeeManager.feeTypes.metis_channel_member,
fee: metisChannelMemberFee,
type: FeeManager.TransactionTypes.messaging_voting_aliases,
subtype: FeeManager.JupiterTypeOneSubtypes.metisChannelMember
});
this.fees.push({
feeType: FeeManager.feeTypes.alias_assignment,
fee: aliasAssigmentFee,
type: FeeManager.TransactionTypes.messaging_voting_aliases,
subtype: FeeManager.JupiterTypeOneSubtypes.aliasAssignment
});
this.fees.push({
feeType: FeeManager.feeTypes.account_property,
fee: accountPropertyFee,
type: FeeManager.TransactionTypes.messaging_voting_aliases,
subtype: FeeManager.JupiterTypeOneSubtypes.accountProperty
});
this.fees.push({
feeType: FeeManager.feeTypes.account_property_deletion,
fee: accountPropertyDeletionFee,
type: FeeManager.TransactionTypes.messaging_voting_aliases,
subtype: FeeManager.JupiterTypeOneSubtypes.accountPropertyDeletion
});
this.fees.push({
feeType: FeeManager.feeTypes.new_user_funding,
fee: newUserFundingFee,
type: FeeManager.TransactionTypes.payment,
subtype: FeeManager.JupiterTypZeroSubtypes.ordinaryPayment
});
this.fees.push({
feeType: FeeManager.feeTypes.new_table_funding,
fee: newTableFundingFee,
type: FeeManager.TransactionTypes.payment,
subtype: FeeManager.JupiterTypZeroSubtypes.ordinaryPayment
});
this.fees.push({
feeType: FeeManager.feeTypes.ordinary_payment,
fee: ordinaryPaymentFee ,
type: FeeManager.TransactionTypes.payment,
subtype: FeeManager.JupiterTypZeroSubtypes.ordinaryPayment
});
}
static feeTypes = {
'nft_creation': 'nft_creation',
'asset_creation': 'asset_creation',
'storage': 'storage',
'regular_transaction': 'regular_transaction',
'account_record': 'account_record',
'table_account_record':'table_account_record',
'invitation_to_channel': 'invitation_to_channel',
'metis_channel_member': 'accept_channel_invitation',
'arbitrary_message': 'arbitrary_message', //subtype 0
'alias_assignment': 'alias_assignment',
'account_property': 'account_property',
'account_property_deletion': 'account_property_deletion',
'new_user_funding':'new_user_funding',
'new_table_funding':'new_table_funding',
'ordinary_payment': 'ordinary_payment',
'metisMessage': 'metisMessage',
}
static TransactionTypes = {
'payment': 0,
'messaging_voting_aliases': 1,
'asset_exchange': 2,
'market_place': 3,
'account_control': 4,
'monetary_system': 5,
'data_cloud': 6
}
static JupiterTypZeroSubtypes = {
ordinaryPayment: 0,
}
static JupiterTypeOneSubtypes = {
arbitraryMessage: 0,
aliasAssignment: 1,
pollCreation: 2,
voteCasting: 3,
hubAnnouncement: 4,
accountInfo: 5,
aliasTransfer: 6,
aliasBuy: 7,
aliasDeletion: 8,
transactionApproval: 9,
accountProperty: 10,
accountPropertyDeletion: 11,
metisAccountRecord: 12,
metisChannelInvitation: 13,
metisChannelMember: 14,
metisMessage: 15
}
/**
*
* @param {FeeManager.feeTypes} feeType
* @returns {number}
*/
getFee(feeType) {
logger.verbose(`#### getFee(feeType= ${feeType})`);
const fees = this.fees.filter(fee => {
return feeType === fee.feeType
})
if (fees.length) {
return fees[0].fee
}
throw new Error('Fee doesnt exist');
}
/**
*
* @param {FeeManager.feeTypes} feeType
* @returns {type,subtype}
*/
getTransactionTypeAndSubType(feeType) {
const typeSubType = this.fees.reduce((reducer, fee) => {
if (feeType === fee.feeType) {
reducer.push({type: fee.type, subtype: fee.subtype});
}
return reducer;
}, [])
if (typeSubType.length < 1) {
throw new Error('Type doesnt exist');
}
return typeSubType[0]
}
getTotalDataFee(bufferData){
const total = bufferData.reduce( (reduced,item)=>{
reduced = reduced + this.getCalculatedMessageFee(item);
}, 0 )
return total * 1.03
}
getCalculatedMessageFee(message) {
const size = message.length;
const fee = this.getFee(FeeManager.feeTypes.metisMessage);
if (size === 0) return fee
if (size <= 5000) return 800000
if (size <= 10000) return 1600000
if (size <= 15000) return 2300000
if (size <= 20000) return 3100000
if (size <= 25000) return 3900000
if (size <= 30000) return 4700000
if (size <= 35000) return 5500000
if (size <= 40000) return 6300000
return 6500000
}
// export function calculateExpectedFees(data: Array<string>): number {
// let expectedFees = 0;
// data.forEach((data) => expectedFees += calculateMessageFee(data.length));
// return expectedFees*1.03;
// }
} |
JavaScript | class LogInfo extends React.Component {
/**
* Render function
* @return {Component} Name of user and a logout button
*/
render() {
if (this.props.name == '') {
return null;
}
return (
<div>
{this.props.name} <LogoutButton />
</div>
);
}
} |
JavaScript | class ActivityObject {
/**
* Constructs a new <code>ActivityObject</code>.
* @alias module:model/ActivityObject
*/
constructor() {
ActivityObject.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>ActivityObject</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/ActivityObject} obj Optional instance to populate.
* @return {module:model/ActivityObject} The populated <code>ActivityObject</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ActivityObject();
if (data.hasOwnProperty('@context')) {
obj['@context'] = ApiClient.convertToType(data['@context'], 'String');
}
if (data.hasOwnProperty('accuracy')) {
obj['accuracy'] = ApiClient.convertToType(data['accuracy'], 'Number');
}
if (data.hasOwnProperty('actor')) {
obj['actor'] = ActivityObject.constructFromObject(data['actor']);
}
if (data.hasOwnProperty('altitude')) {
obj['altitude'] = ApiClient.convertToType(data['altitude'], 'Number');
}
if (data.hasOwnProperty('anyOf')) {
obj['anyOf'] = ActivityObject.constructFromObject(data['anyOf']);
}
if (data.hasOwnProperty('attachment')) {
obj['attachment'] = ActivityObject.constructFromObject(data['attachment']);
}
if (data.hasOwnProperty('attributedTo')) {
obj['attributedTo'] = ActivityObject.constructFromObject(data['attributedTo']);
}
if (data.hasOwnProperty('audience')) {
obj['audience'] = ActivityObject.constructFromObject(data['audience']);
}
if (data.hasOwnProperty('bcc')) {
obj['bcc'] = ActivityObject.constructFromObject(data['bcc']);
}
if (data.hasOwnProperty('bto')) {
obj['bto'] = ActivityObject.constructFromObject(data['bto']);
}
if (data.hasOwnProperty('cc')) {
obj['cc'] = ActivityObject.constructFromObject(data['cc']);
}
if (data.hasOwnProperty('closed')) {
obj['closed'] = ApiClient.convertToType(data['closed'], 'Date');
}
if (data.hasOwnProperty('content')) {
obj['content'] = ActivityObject.constructFromObject(data['content']);
}
if (data.hasOwnProperty('context')) {
obj['context'] = ActivityObject.constructFromObject(data['context']);
}
if (data.hasOwnProperty('current')) {
obj['current'] = ActivityObject.constructFromObject(data['current']);
}
if (data.hasOwnProperty('deleted')) {
obj['deleted'] = ApiClient.convertToType(data['deleted'], 'Date');
}
if (data.hasOwnProperty('duration')) {
obj['duration'] = ApiClient.convertToType(data['duration'], 'Date');
}
if (data.hasOwnProperty('endTime')) {
obj['endTime'] = ApiClient.convertToType(data['endTime'], 'Date');
}
if (data.hasOwnProperty('first')) {
obj['first'] = ActivityObject.constructFromObject(data['first']);
}
if (data.hasOwnProperty('formerType')) {
obj['formerType'] = ActivityObjectType.constructFromObject(data['formerType']);
}
if (data.hasOwnProperty('generator')) {
obj['generator'] = ActivityObject.constructFromObject(data['generator']);
}
if (data.hasOwnProperty('height')) {
obj['height'] = ApiClient.convertToType(data['height'], 'Number');
}
if (data.hasOwnProperty('href')) {
obj['href'] = ApiClient.convertToType(data['href'], 'String');
}
if (data.hasOwnProperty('hreflang')) {
obj['hreflang'] = ApiClient.convertToType(data['hreflang'], 'String');
}
if (data.hasOwnProperty('icon')) {
obj['icon'] = ActivityObject.constructFromObject(data['icon']);
}
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('image')) {
obj['image'] = ActivityObject.constructFromObject(data['image']);
}
if (data.hasOwnProperty('inReplyTo')) {
obj['inReplyTo'] = ActivityObject.constructFromObject(data['inReplyTo']);
}
if (data.hasOwnProperty('instrument')) {
obj['instrument'] = ActivityObject.constructFromObject(data['instrument']);
}
if (data.hasOwnProperty('items')) {
obj['items'] = ApiClient.convertToType(data['items'], [ActivityObject]);
}
if (data.hasOwnProperty('last')) {
obj['last'] = ActivityObject.constructFromObject(data['last']);
}
if (data.hasOwnProperty('latitude')) {
obj['latitude'] = ApiClient.convertToType(data['latitude'], 'Number');
}
if (data.hasOwnProperty('location')) {
obj['location'] = ActivityObject.constructFromObject(data['location']);
}
if (data.hasOwnProperty('longitude')) {
obj['longitude'] = ApiClient.convertToType(data['longitude'], 'Number');
}
if (data.hasOwnProperty('markdown')) {
obj['markdown'] = ApiClient.convertToType(data['markdown'], 'String');
}
if (data.hasOwnProperty('mediaType')) {
obj['mediaType'] = ApiClient.convertToType(data['mediaType'], 'String');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('next')) {
obj['next'] = ActivityObject.constructFromObject(data['next']);
}
if (data.hasOwnProperty('object')) {
obj['object'] = ActivityObject.constructFromObject(data['object']);
}
if (data.hasOwnProperty('oneOf')) {
obj['oneOf'] = ActivityObject.constructFromObject(data['oneOf']);
}
if (data.hasOwnProperty('origin')) {
obj['origin'] = ActivityObject.constructFromObject(data['origin']);
}
if (data.hasOwnProperty('partOf')) {
obj['partOf'] = ActivityObject.constructFromObject(data['partOf']);
}
if (data.hasOwnProperty('prev')) {
obj['prev'] = ActivityObject.constructFromObject(data['prev']);
}
if (data.hasOwnProperty('preview')) {
obj['preview'] = ActivityObject.constructFromObject(data['preview']);
}
if (data.hasOwnProperty('published')) {
obj['published'] = ApiClient.convertToType(data['published'], 'Date');
}
if (data.hasOwnProperty('radius')) {
obj['radius'] = ApiClient.convertToType(data['radius'], 'Number');
}
if (data.hasOwnProperty('rel')) {
obj['rel'] = ApiClient.convertToType(data['rel'], 'String');
}
if (data.hasOwnProperty('relationship')) {
obj['relationship'] = ActivityObject.constructFromObject(data['relationship']);
}
if (data.hasOwnProperty('replies')) {
obj['replies'] = ActivityObject.constructFromObject(data['replies']);
}
if (data.hasOwnProperty('result')) {
obj['result'] = ActivityObject.constructFromObject(data['result']);
}
if (data.hasOwnProperty('startTime')) {
obj['startTime'] = ApiClient.convertToType(data['startTime'], 'Date');
}
if (data.hasOwnProperty('subject')) {
obj['subject'] = ActivityObject.constructFromObject(data['subject']);
}
if (data.hasOwnProperty('summary')) {
obj['summary'] = ApiClient.convertToType(data['summary'], 'String');
}
if (data.hasOwnProperty('tag')) {
obj['tag'] = ActivityObject.constructFromObject(data['tag']);
}
if (data.hasOwnProperty('target')) {
obj['target'] = ActivityObject.constructFromObject(data['target']);
}
if (data.hasOwnProperty('to')) {
obj['to'] = ActivityObject.constructFromObject(data['to']);
}
if (data.hasOwnProperty('totalItems')) {
obj['totalItems'] = ApiClient.convertToType(data['totalItems'], 'Number');
}
if (data.hasOwnProperty('type')) {
obj['type'] = ActivityObjectType.constructFromObject(data['type']);
}
if (data.hasOwnProperty('units')) {
obj['units'] = ApiClient.convertToType(data['units'], 'String');
}
if (data.hasOwnProperty('updated')) {
obj['updated'] = ApiClient.convertToType(data['updated'], 'Date');
}
if (data.hasOwnProperty('url')) {
obj['url'] = ActivityObject.constructFromObject(data['url']);
}
if (data.hasOwnProperty('width')) {
obj['width'] = ApiClient.convertToType(data['width'], 'Number');
}
}
return obj;
}
} |
JavaScript | class SpeedyPipelineNodeGreyscale extends SpeedyPipelineNode
{
/**
* Constructor
* @param {string} [name] name of the node
*/
constructor(name = undefined)
{
super(name, 1, [
InputPort().expects(SpeedyPipelineMessageType.Image),
OutputPort().expects(SpeedyPipelineMessageType.Image),
]);
}
/**
* Run the specific task of this node
* @param {SpeedyGPU} gpu
* @returns {void|SpeedyPromise<void>}
*/
_run(gpu)
{
const { image, format } = /** @type {SpeedyPipelineMessageWithImage} */ ( this.input().read() );
const width = image.width, height = image.height;
const outputTexture = this._tex[0];
const filters = gpu.programs.filters;
filters.rgb2grey.outputs(width, height, outputTexture);
filters.rgb2grey(image);
this.output().swrite(outputTexture, ImageFormat.GREY);
}
} |
JavaScript | class StructureArtGenerator {
constructor() {
this.imgDir = 'img/structures/';
this.backgroundsDir = 'backgrounds/';
this.mobileDir = 'mobile/';
this.staticDir = 'static/';
}
/* Backgrounds */
backgroundDefault(layers) {
layers.push(`${this.imgDir}${this.backgroundsDir}structure-bg-default.png`)
}
backgroundLand(layers, structure) {
if (structure.hasAmbitLand()) {
layers.push(`${this.imgDir}${this.backgroundsDir}structure-bg-land.png`);
}
}
backgroundSky(layers, structure) {
if (structure.hasAmbitSky()) {
layers.push(`${this.imgDir}${this.backgroundsDir}structure-bg-sky.png`);
}
}
backgroundSpace(layers, structure) {
if (structure.hasAmbitSpace()) {
layers.push(`${this.imgDir}${this.backgroundsDir}structure-bg-space.png`);
}
}
backgroundWater(layers, structure) {
if (structure.hasAmbitWater()) {
layers.push(`${this.imgDir}${this.backgroundsDir}structure-bg-water.png`);
}
}
backgroundLayerFilter(layers) {
layers.push(`${this.imgDir}${this.backgroundsDir}structure-bg-lighten-15.png`);
}
/* Mobile Structure Base */
mobileStructureChassis(layers) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-chassis.png`);
}
/* Mobile Structure Ambit Parts */
mobileStructureLand(layers, structure) {
if (structure.hasAmbitLand()) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-land.png`);
}
}
mobileStructureSky(layers, structure) {
if (structure.hasAmbitSky()) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-sky.png`);
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-space.png`);
}
}
mobileStructureSpace(layers, structure) {
if (structure.hasAmbitSpace()) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-space.png`);
}
}
mobileStructureWater(layers, structure) {
if (structure.hasAmbitWater()) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-water.png`);
}
}
/* Mobile Structure Feature Parts */
mobileStructureAttack(layers, structure) {
if (structure.hasFeatureAttack()) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-attack.png`);
}
}
mobileStructureDefensive(layers, structure) {
if (structure.hasFeatureDefensive()) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-defense.png`);
}
}
mobileStructureEngineering(layers, structure) {
if (structure.hasFeatureEngineering()) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-engineering.png`);
}
}
mobileStructurePower(layers, structure) {
if (structure.hasFeaturePower()) {
layers.push(`${this.imgDir}${this.mobileDir}structure-mobile-power.png`);
}
}
mobileStructure(layers, structure) {
this.mobileStructureChassis(layers);
this.mobileStructureLand(layers, structure);
this.mobileStructureSky(layers, structure);
this.mobileStructureSpace(layers, structure);
this.mobileStructureWater(layers, structure);
this.mobileStructureAttack(layers, structure);
this.mobileStructureDefensive(layers, structure);
this.mobileStructureEngineering(layers, structure);
this.mobileStructurePower(layers, structure);
}
/* Static Structure Base */
staticStructureBuildings(layers) {
layers.push(`${this.imgDir}${this.staticDir}structure-static-buildings.png`);
}
/* Static Structure Ambit Parts */
staticStructureSky(layers, structure) {
if (structure.hasAmbitSky()) {
layers.push(`${this.imgDir}${this.staticDir}structure-static-buildings-base.png`);
layers.push(`${this.imgDir}${this.staticDir}structure-static-sky.png`);
}
}
staticStructureSpace(layers, structure) {
if (structure.hasAmbitSpace()) {
layers.push(`${this.imgDir}${this.staticDir}structure-static-buildings-base.png`);
layers.push(`${this.imgDir}${this.staticDir}structure-static-space.png`);
}
}
staticStructureWater(layers, structure) {
if (structure.hasAmbitWater()) {
layers.push(`${this.imgDir}${this.staticDir}structure-static-buildings-base.png`);
layers.push(`${this.imgDir}${this.staticDir}structure-static-water.png`);
}
}
/* Static Structure Feature Parts */
staticStructureAttack(layers, structure) {
if (structure.hasFeatureAttack()) {
layers.push(`${this.imgDir}${this.staticDir}structure-static-attack.png`);
}
}
staticStructureDefensive(layers, structure) {
if (structure.hasFeatureDefensive()) {
layers.push(`${this.imgDir}${this.staticDir}structure-static-defense.png`);
}
}
staticStructureEngineering(layers, structure) {
if (structure.hasFeatureEngineering()) {
layers.push(`${this.imgDir}${this.staticDir}structure-static-engineering.png`);
}
}
staticStructurePower(layers, structure) {
if (structure.hasFeaturePower()) {
layers.push(`${this.imgDir}${this.staticDir}structure-static-power.png`);
}
}
staticStructure(layers, structure) {
this.staticStructureBuildings(layers);
this.staticStructureSky(layers, structure);
this.staticStructureSpace(layers, structure);
this.staticStructureWater(layers, structure);
this.staticStructureAttack(layers, structure);
this.staticStructureDefensive(layers, structure);
this.staticStructureEngineering(layers, structure);
this.staticStructurePower(layers, structure);
}
/**
* Generate the art for a given structure or schematic.
* @param {Structure|Schematic} structure
*/
generate(structure) {
let layers = [];
this.backgroundDefault(layers);
this.backgroundSpace(layers, structure);
this.backgroundSky(layers, structure);
this.backgroundLand(layers, structure);
this.backgroundWater(layers, structure);
this.backgroundLayerFilter(layers);
if (structure.isMobile()) {
this.mobileStructure(layers, structure);
} else {
this.staticStructure(layers, structure);
}
return layers;
}
} |
JavaScript | class Main extends Component {
constructor(props) {
super(props);
this.state = { testValue: 0 };
// this.readTestData = this.readTestData.bind(this);
}
// test method for reading data from firebase DB
// readTestData() {
// firebase.database().ref('/locations/').once('value')
// .then(snapshot => {
// const testValue = snapshot.val() || 'no value present';
// console.log('FIREBASEDEBUG1');
// console.log(snapshot.val().toString, snapshot.val().test.lat);
// console.log(testValue.key, testValue.value);
// this.setState({ testValue: snapshot.val().test.lat });
// })
// .catch(error => console.log('FIREBASEDEBUGERROR', error.toSTring));
// }
render() {
return (
<View style={styles.container}>
<Card>
<Text style={styles.welcome}>
Hi this is me
</Text>
</Card>
{/* <Button
onPress={this.readTestData}
title='Press this to test for read from firebase db'
/>
<Text style={styles.instructions} >
Firebase Debug: {this.state.testValue}
</Text> */}
</View>
);
}
} |
JavaScript | class FlowsDao {
/**
* Find an array of flows ready to be scheduled.
* @returns {Promise<Flow>} An array of Flows.
*/
async findForScheduling() { //eslint-disable-line no-unused-vars
throw new Error('To be implemented');
}
/**
* Schedule a next flow execution.
* @param {Flow} flow
* @returns {Promise<void>}
*/
async planNextRun(flow) { //eslint-disable-line no-unused-vars
throw new Error('To be implemented');
}
} |
JavaScript | class SearchableDropdown extends PureComponent {
static defaultProps = {
value: null,
component: false,
endComponent: false,
defaultEmptyText: 'No options found',
placeholder: 'Select',
groups: [],
hideEmptyGroups: false,
allowEmpty: false,
emptyOptionText: 'None',
}
static propTypes = {
/**
* Gets called whenever the user selects an option
*
* @param {string|number|boolean} value The new value
* @param {string|number|Object} meta The entire value
*/
onChange: PropTypes.func.isRequired,
/**
* An array of values available to the user. For objects, use `id` for the value and `text`
* for display value. Additionally, provide a `group` attribute to specify which group the
* value belongs to.
*/
values: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.shape({
id: PropTypes.any,
text: PropTypes.any,
group: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
}),
PropTypes.string,
PropTypes.number,
PropTypes.bool,
]),
).isRequired,
/** The current selected value(s) */
value: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.bool,
PropTypes.arrayOf(PropTypes.any),
]),
/** Placeholder text */
placeholder: PropTypes.oneOfType([
PropTypes.number,
PropTypes.bool,
PropTypes.string,
PropTypes.node,
]),
/** Optionally provide a unique component to render each option from */
component: PropTypes.oneOfType([
PropTypes.func,
PropTypes.bool,
]),
/** Optionally provide a unique component that gets rendered at the bottom of the option menu */
endComponent: PropTypes.oneOfType([
PropTypes.func,
PropTypes.bool,
]),
/** The text to render if no option is found in a search */
defaultEmptyText: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node,
]),
/**
* Groups the provided values into the provided groups. `key` matches to the `group` attribute
* on each value. `name` is the displayed group name. `emptyText` is the text displayed if
* there are no options for the group.
*/
groups: PropTypes.arrayOf(PropTypes.shape({
key: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
name: PropTypes.string,
emptyText: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
})),
/** If a group is empty, it will not show the group in the option menu. */
hideEmptyGroups: PropTypes.bool,
/** Allow for the users to select `none`, clearing the value. */
allowEmpty: PropTypes.bool,
/** The text for the select none option. */
emptyOptionText: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
}
render() {
const dropdownButton = props => (
<Button onClick={props.onClick} className={props.hasSelection ? '' : 'no-selection'}>
{props.selectedValue}
</Button>
);
return (
<SearchableDropdownBase
{...this.props}
className="toggle-select-arrows"
dropdownToggleComponent={dropdownButton}
closeOnSelect
/>
);
}
} |
JavaScript | class LightTextureAtlas {
constructor(device) {
this.device = device;
this.subdivision = 0;
this.shadowAtlasResolution = 2048;
this.shadowAtlas = null;
// number of additional pixels to render past the required shadow camera angle (90deg for omni, outer for spot) of the shadow camera for clustered lights.
// This needs to be a pixel more than a shadow filter needs to access.
this.shadowEdgePixels = 3;
this.cookieAtlasResolution = 2048;
this.cookieAtlas = null;
this.cookieRenderTarget = null;
// available slots
this.slots = [];
// offsets to individual faces of a cubemap inside 3x3 grid in an atlas slot
this.cubeSlotsOffsets = [
new Vec2(0, 0),
new Vec2(0, 1),
new Vec2(1, 0),
new Vec2(1, 1),
new Vec2(2, 0),
new Vec2(2, 1)
];
this.allocateShadowAtlas(1); // placeholder as shader requires it
this.allocateCookieAtlas(1); // placeholder as shader requires it
this.allocateUniforms();
}
destroy() {
this.destroyShadowAtlas();
this.destroyCookieAtlas();
}
destroyShadowAtlas() {
if (this.shadowAtlas) {
this.shadowAtlas.destroy();
this.shadowAtlas = null;
}
}
destroyCookieAtlas() {
if (this.cookieAtlas) {
this.cookieAtlas.destroy();
this.cookieAtlas = null;
}
if (this.cookieRenderTarget) {
this.cookieRenderTarget.destroy();
this.cookieRenderTarget = null;
}
}
allocateShadowAtlas(resolution) {
if (!this.shadowAtlas || this.shadowAtlas.texture.width !== resolution) {
this.destroyShadowAtlas();
this.shadowAtlas = ShadowMap.createAtlas(this.device, resolution, SHADOW_PCF3);
// avoid it being destroyed by lights
this.shadowAtlas.cached = true;
}
}
allocateCookieAtlas(resolution) {
if (!this.cookieAtlas || this.cookieAtlas.width !== resolution) {
this.destroyCookieAtlas();
this.cookieAtlas = CookieRenderer.createTexture(this.device, resolution);
this.cookieRenderTarget = new RenderTarget({
colorBuffer: this.cookieAtlas,
depth: false,
flipY: true
});
}
}
allocateUniforms() {
this._shadowAtlasTextureId = this.device.scope.resolve("shadowAtlasTexture");
this._shadowAtlasParamsId = this.device.scope.resolve("shadowAtlasParams");
this._shadowAtlasParams = new Float32Array(2);
this._cookieAtlasTextureId = this.device.scope.resolve("cookieAtlasTexture");
}
updateUniforms() {
// shadow atlas texture
const isShadowFilterPcf = true;
const rt = this.shadowAtlas.renderTargets[0];
const shadowBuffer = (this.device.webgl2 && isShadowFilterPcf) ? rt.depthBuffer : rt.colorBuffer;
this._shadowAtlasTextureId.setValue(shadowBuffer);
// shadow atlas params
this._shadowAtlasParams[0] = this.shadowAtlasResolution;
this._shadowAtlasParams[1] = this.shadowEdgePixels;
this._shadowAtlasParamsId.setValue(this._shadowAtlasParams);
// cookie atlas textures
this._cookieAtlasTextureId.setValue(this.cookieAtlas);
}
subdivide(numLights) {
// required grid size
const gridSize = Math.ceil(Math.sqrt(numLights));
// subdivide the texture to required grid size
if (this.subdivision !== gridSize) {
this.subdivision = gridSize;
this.slots.length = 0;
const invSize = 1 / gridSize;
for (let i = 0; i < gridSize; i++) {
for (let j = 0; j < gridSize; j++) {
this.slots.push(new Vec4(i * invSize, j * invSize, invSize, invSize));
}
}
}
}
collectLights(spotLights, omniLights, lightingParams) {
const cookiesEnabled = lightingParams.cookiesEnabled;
const shadowsEnabled = lightingParams.shadowsEnabled;
// get all lights that need shadows or cookies, if those are enabled
let needsShadow = false;
let needsCookie = false;
const lights = _tempArray;
lights.length = 0;
const processLights = (list) => {
for (let i = 0; i < list.length; i++) {
const light = list[i];
if (light.visibleThisFrame) {
needsShadow ||= shadowsEnabled && light.castShadows;
needsCookie ||= cookiesEnabled && !!light.cookie;
if (needsShadow || needsCookie) {
lights.push(light);
}
}
}
};
if (cookiesEnabled || shadowsEnabled) {
processLights(spotLights);
processLights(omniLights);
}
if (needsShadow) {
this.allocateShadowAtlas(this.shadowAtlasResolution);
}
if (needsCookie) {
this.allocateCookieAtlas(this.cookieAtlasResolution);
}
if (needsShadow || needsCookie) {
this.subdivide(lights.length);
}
return lights;
}
// update texture atlas for a list of lights
update(spotLights, omniLights, lightingParams) {
// update texture resolutions
this.shadowAtlasResolution = lightingParams.shadowAtlasResolution;
this.cookieAtlasResolution = lightingParams.cookieAtlasResolution;
// process lights
const lights = this.collectLights(spotLights, omniLights, lightingParams);
if (lights.length > 0) {
// leave gap between individual tiles to avoid shadow / cookie sampling other tiles (5 pixels is enough for PCF5)
// note that this only fades / removes shadows on the edges, which is still not correct - a shader clipping is needed?
const scissorOffset = 4 / this.shadowAtlasResolution;
const scissorVec = new Vec4(scissorOffset, scissorOffset, -2 * scissorOffset, -2 * scissorOffset);
// assign atlas slots to lights
let usedCount = 0;
for (let i = 0; i < lights.length; i++) {
const light = lights[i];
if (light.castShadows)
light._shadowMap = this.shadowAtlas;
// use a single slot for spot, and single slot for all 6 faces of cubemap as well
const slot = this.slots[usedCount];
usedCount++;
light.atlasViewport.copy(slot);
const faceCount = light.numShadowFaces;
for (let face = 0; face < faceCount; face++) {
// setup slot for shadow and cookie
if (light.castShadows || light._cookie) {
_viewport.copy(slot);
_scissor.copy(slot);
// for spot lights in the atlas, make viewport slightly smaller to avoid sampling past the edges
if (light._type === LIGHTTYPE_SPOT) {
_viewport.add(scissorVec);
}
// for cube map, allocate part of the slot
if (light._type === LIGHTTYPE_OMNI) {
const smallSize = _viewport.z / 3;
const offset = this.cubeSlotsOffsets[face];
_viewport.x += smallSize * offset.x;
_viewport.y += smallSize * offset.y;
_viewport.z = smallSize;
_viewport.w = smallSize;
_scissor.copy(_viewport);
}
if (light.castShadows) {
const lightRenderData = light.getRenderData(null, face);
lightRenderData.shadowViewport.copy(_viewport);
lightRenderData.shadowScissor.copy(_scissor);
}
}
}
}
}
this.updateUniforms();
}
} |
JavaScript | class HexGameState extends AbstractHexState {
/**
* Constructs a new game state
* @param {object|number} init either an object representing the board layout and move number or one of the preset board layouts (see DEFAULT_BOARDS)
*/
constructor(init) {
super(init);
this._totalMoves = 0;
this._currentMove = 0;
this._board = [];
this._name = '';
this._fieldVals = [];
this._sum = 0;
if (typeof init === 'number') {
this._totalMoves = DEFAULT_BOARDS[init].moves;
this._board = DEFAULT_BOARDS[init].board;
this._name = DEFAULT_BOARDS[init].name;
} else {
this._totalMoves = init.moves;
this._board = init.board;
if (init.name) this._name = init.name;
if (init.currentMove) this._currentMove = init.currentMove;
if (init.fieldVals && (typeof init.sum === 'number')) { this._fieldVals = init.fieldVals; this._sum = init.sum; }
}
if (this._fieldVals.length == 0) {
let [fV, s] = calcSums(this._board);
this._fieldVals = fV;
this._sum = s;
}
}
/**
* The current board position
* @return {number[][]} the board: NaN fields cannot be played, 0 fields are empty, other numbers represent the numbers that were played so far
*/
get board() {
return this._board;
}
/**
* The current sums on empty fields of the board
* @return {number[][]} the field values: NaN for non-empty fields, otherwise the sum of the values on neighboring fields
*/
get fieldVals() {
return this._fieldVals;
}
/**
* The number of total moves per player
* @return {number} the total moves
*/
get totalMoves() {
return this._totalMoves;
}
/**
* The current move number
* @return {number} the current move
*/
get currentMove() {
return this._currentMove;
}
/**
* The current sum of all numbers bordering on empty fields, or the sum of the values of empty fields in fieldVals
* @return {number} the current sum
*/
get sum() {
return this._sum;
}
/**
* The name of the game board
* @return {string} the name
*/
get name() {
return this._name;
}
/**
* Perform a move
* @param {number} x the x coordinate of the field the next number should be placed on
* @param {number} y the y coordinate of the field the next number should be placed on
* @return {boolean|HexGameState} false if the move was invalid, the new game state if it was valid
*/
play(x, y) {
if (Math.floor(this._currentMove / 2) >= this._totalMoves) return false;
if (x < 0 || x >= this._board[0].length) return false;
if (y < 0 || y >= this._board.length) return false;
y = this._board.length - y - 1;
if (this._board[y][x] !== 0) return false;
let nextNumber = (1 + Math.floor(this._currentMove / 2)) * (this._currentMove % 2 ? -1 : 1);
let newBoard = []; let nfv = [];
for (let yc = 0; yc < this._board.length; yc++) {
newBoard[yc] = []; nfv[yc] = [];
for (let xc = 0; xc < this._board[yc].length; xc++) {
newBoard[yc][xc] = yc == y && xc == x ? nextNumber : this._board[yc][xc];
nfv[yc][xc] = yc == y && xc == x ? NaN : this._fieldVals[yc][xc];
}
}
let ns = this._sum;
let addNewVal = false;
let neighb = getNeighbors([x, y], this._board.length);
for (let i = 0; i < neighb.length; i++) {
let [x2, y2] = neighb[i];
if (x2 >= 0 && x2 < this._board[0].length && y2 >= 0 && y2 < this._board.length && !isNaN(this._board[y2][x2])) {
if (!isNaN(nfv[y2][x2])) {
nfv[y2][x2] += nextNumber;
addNewVal = true;
}
let removeVal = true;
let neighb2 = getNeighbors([x2, y2], this._board.length);
for (let k = 0; k < neighb2.length; k++) {
let [x3, y3] = neighb2[k];
if (x3 >= 0 && x3 < this._board[0].length && y3 >= 0 && y3 < this._board.length && !isNaN(nfv[y3][x3])) {
removeVal = false;
break;
}
}
if (removeVal) ns -= this._board[y2][x2];
}
}
if (addNewVal) ns += nextNumber;
return new HexGameState({ name: this._name, moves: this._totalMoves, currentMove: this._currentMove + 1, board: newBoard, fieldVals: nfv, sum: ns });
}
/**
* Check who won the game
* @return {number} -1: player 1 (minimizer) won / 1: player 2 (maximizer) won / 0: draw / NaN: game not over yet
*/
checkWinner() {
if (Math.floor(this._currentMove / 2) < this._totalMoves) return NaN;
if (this._sum < 0) return -1;
if (this._sum > 0) return 1;
return 0;
}
} |
JavaScript | class ShrImmunizationObjectFactory {
/**
* Create an instance of a class from its JSON representation.
* @param {Object} json - The element data in JSON format (use `{}` and provide `type` for a blank instance)
* @param {string} [type] - The (optional) type of the element (e.g., 'http://standardhealthrecord.org/spec/shr/demographics/PersonOfRecord'). This is only used if the type cannot be extracted from the JSON.
* @returns {Object} An instance of the requested class populated with the provided data
*/
static createInstance(json, type) {
const { namespace, elementName } = getNamespaceAndName(json, type);
if (namespace !== 'shr.immunization') {
throw new Error(`Unsupported type in ShrImmunizationObjectFactory: ${type}`);
}
switch (elementName) {
case 'Vaccine': return Vaccine.fromJSON(json);
case 'ImmunizationAction': return ImmunizationAction.fromJSON(json);
case 'ImmunizationGiven': return ImmunizationGiven.fromJSON(json);
case 'ImmunizationNotGiven': return ImmunizationNotGiven.fromJSON(json);
case 'ImmunizationRequested': return ImmunizationRequested.fromJSON(json);
case 'ImmunizationRequestedAgainst': return ImmunizationRequestedAgainst.fromJSON(json);
default: throw new Error(`Unsupported type in ShrImmunizationObjectFactory: ${type}`);
}
}
} |
JavaScript | class I18n {
constructor(syntax) {
// Define default placeholder syntax
this.msg = syntax || {
start: '__MSG_',
end: '__'
};
}
localize(text) {
while(text.includes(this.msg.start)) {
let keyStart = text.indexOf(this.msg.start) + this.msg.start.length;
let key = text.substring(keyStart, text.indexOf(this.msg.end, keyStart));
let placeholder = `${this.msg.start}${key}${this.msg.end}`;
let localized = chrome.i18n.getMessage(key);
// Replace all instances of this placeholder with the localized text
text = text.replace(new RegExp(placeholder, 'g'), localized);
}
return text;
}
/**
* Finds and replaces placeholder strings with localized text
*/
populateText() {
let node = null;
let walker = document.createTreeWalker(
document.body,
// Only look at text nodes
NodeFilter.SHOW_TEXT,
// Ignore script and style tags
node => 'script style'.includes(node.tagName) ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT,
false
);
// Localize text nodes
while(node = walker.nextNode()) {
node.textContent = this.localize(node.textContent);
}
// Localize attributes of elements tagged with the 'data-i18n' attribute
document.querySelectorAll('[data-i18n]').forEach($elem => {
Array.from($elem.attributes).forEach(({ nodeName, nodeValue }) => {
$elem.setAttribute(nodeName, this.localize(nodeValue));
});
});
}
} |
JavaScript | class BinarySearchTreeWithDisplay extends BinarySearchTree {
constructor() {
super()
this.root = null
this.treeVisualizerData = {}
}
insert(val) {
const newNode = new Node(val)
// handle adding the first node
if (this.root === null) {
this.root = newNode
this.treeVisualizerData = {
name: newNode.val,
children: [],
}
return this.root
}
// adding a node to an existing tree
this._insertNode(this.root, newNode, this.treeVisualizerData)
return newNode
}
// helper method for recursively finding the correct place to insert the new node
_insertNode(currentNode, newNode, currentTreeVisualizerDataNode) {
if (currentNode.val > newNode.val && currentNode.left === null) {
currentNode.left = newNode
currentTreeVisualizerDataNode.children.unshift({
name: newNode.val,
children: [],
})
return newNode
} else if (currentNode.val > newNode.val) {
return this._insertNode(
currentNode.left,
newNode,
currentTreeVisualizerDataNode.children[0]
)
} else if (
(currentNode.val < newNode.val || currentNode.val === newNode.val) &&
currentNode.right === null
) {
currentNode.right = newNode
currentTreeVisualizerDataNode.children.push({
name: newNode.val,
children: [],
})
return newNode
} else {
return this._insertNode(
currentNode.right,
newNode,
currentTreeVisualizerDataNode.children[1] ||
currentTreeVisualizerDataNode.children[0]
)
}
}
remove(val) {
// the root is re-initialized with the root of a modified tree
this.root = this._removeNode(this.root, val, this.treeVisualizerData, null)
return this.root
}
_removeNode(
currentNode,
key,
currentTreeVisualizerDataNode,
currentTreeVisualizerDataNodeParent
) {
// if the root is null then tree is empty
if (currentNode === null) {
this.treeVisualizerData = {}
return null
}
// if the value to be deleted is less than the root's value, then move to the left subtree
if (key < currentNode.val) {
currentNode.left = this._removeNode(
currentNode.left,
key,
currentTreeVisualizerDataNode.children[0],
currentTreeVisualizerDataNode
)
return currentNode
}
// if the value to be deleted is greater than the root's value, then move to the right subtree
if (key > currentNode.val) {
currentNode.right = this._removeNode(
currentNode.right,
key,
currentTreeVisualizerDataNode.children[1] ||
currentTreeVisualizerDataNode.children[0],
currentTreeVisualizerDataNode
)
return currentNode
}
// if the value to be deleted is equal to the root's data, then delete this node.
// the node could have 0, 1, or 2 children
// deleting a node with no children
if (currentNode.left === null && currentNode.right === null) {
currentNode = null
currentTreeVisualizerDataNodeParent.children =
currentTreeVisualizerDataNodeParent.children.filter(
childNode => childNode.name !== currentTreeVisualizerDataNode.name
)
return currentNode
}
// deleting a node with one child (right)
if (currentNode.left === null) {
currentNode = currentNode.right
currentTreeVisualizerDataNodeParent.children =
currentTreeVisualizerDataNode.children
return currentNode
}
// deleting a node with one child (left)
if (currentNode.right === null) {
currentNode = currentNode.left
currentTreeVisualizerDataNodeParent.children =
currentTreeVisualizerDataNode.children
return currentNode
}
// deleting a node with two children.
// the minimum node of the right subtree is stored in a temporary variable
const temp = this._findMinNode(currentNode.right)
currentNode.val = temp.val
currentTreeVisualizerDataNode.name = temp.val
currentNode.right = this._removeNode(
currentNode.right,
temp.val,
currentTreeVisualizerDataNode.children[1] ||
currentTreeVisualizerDataNode.children[0],
currentTreeVisualizerDataNode
)
return currentNode
}
clear() {
this.root = null
this.treeVisualizerData = {}
return this.root
}
} |
JavaScript | class TypeAheadInput extends Component {
state = {
items: [],
prevPropsItems: null,
selectStart: 0
};
requests = 0;
static getDerivedStateFromProps(props, state) {
if (!props.getItems && props.items !== state.prevPropsItems) {
return {
prevPropsItems: props.items,
items: sortBy(props.items, props.getItemValue).map(props.getItemValue)
};
}
return null;
}
propsOnChange(ev) {
const { onChange } = this.props;
if (typeof onChange === 'function') onChange(ev);
}
selectText = () => {
const { selectStart } = this.state;
this.input.setSelectionRange(selectStart, this.input.value.length);
};
shouldSelectionUpdate(ev) {
let value = this.props.value;
const { items } = this.state;
if (this.deleteChar) return;
if (
this.input.selectionEnd === value.length &&
this.input.selectionStart < this.input.selectionEnd
) {
value = this.props.value.slice(0, this.input.selectionStart);
}
const autocomplete = find(items, item =>
item.toLowerCase().startsWith(value.toLowerCase())
);
if (autocomplete === this.props.value) return;
ev.target.value = value;
this.completeFromState(ev);
}
completeFromState(ev) {
const { items } = this.state;
const autocomplete = find(items, item =>
item.toLowerCase().startsWith(ev.target.value.toLowerCase())
);
if (autocomplete) {
this.setState(
{
selectStart: ev.target.value.length
},
this.selectText
);
ev.target.value = autocomplete;
}
this.propsOnChange(ev);
}
getItems(query, ev) {
clearTimeout(this.getterTimeout);
ev.persist();
this.getterTimeout = setTimeout(() => {
this.requests++;
const request = this.requests;
const { getItems, getItemValue } = this.props;
getItems(query)
.then(items => {
if (this.requests !== request) {
return Promise.reject(null);
}
return sortBy(items, getItemValue).map(getItemValue);
})
.then(items => {
this.setState({ items }, () => this.shouldSelectionUpdate(ev));
})
.catch(err => {
if (err) throw err;
});
}, 200);
}
onKeyDown = ev => {
const { onKeyDown } = this.props;
// Backspace & delete
if (ev.keyCode === 8 || ev.keyCode === 46) {
this.deleteChar = true;
}
if (typeof onKeyDown === 'function') onKeyDown(ev);
};
onChange = ev => {
const { getItems } = this.props;
if (!this.deleteChar && ev.target.value.length > 0) {
const { value } = ev.target;
this.completeFromState(ev);
if (getItems) {
this.getItems(value, ev);
}
}
this.deleteChar = false;
this.propsOnChange(ev);
};
setRef = ref => {
const { innerRef } = this.props;
this.input = ref;
if (typeof innerRef === 'function') {
innerRef(ref);
}
};
render() {
const {
getItemValue,
getItems,
innerRef,
items,
onChange,
...props
} = this.props;
return (
<TextInput
onChange={this.onChange}
onKeyDown={this.onKeyDown}
innerRef={this.setRef}
{...props}
/>
);
}
static propTypes = {
/** Selector function to get value from item in items array. Defaults to (item) => item */
getItemValue: p.func,
/** Async function / promise to retreive items */
getItems: p.func,
/** Array of items (if getItems is not specified) */
items: p.array
};
static defaultProps = {
getItemValue: item => item,
items: []
};
} |
JavaScript | class LrnCssReset extends LitElement {
/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/
static get tag() {
return "lrn-css-reset";
}
static get styles() {
return LrnCssResetStyles;
}
static get properties() {
return {
applyToHead: {
type: Boolean,
attribute: "apply-to-head",
},
};
}
/**
* HTMLElement
*/
constructor() {
super();
}
firstUpdated(changedProperties) {
if (super.firstUpdated) super.firstUpdated(changedProperties);
if (this.applyToHead)
AttachStylesToHead(LrnCssResetStyles, "LrnCssResetStyles");
}
render() {
return html`<slot></slot>`;
}
} |
JavaScript | class Line {
/**
* Creates an instance of Line.
* @param {String} src text in source language
* @param {String} dest translated text
* @memberof Line
*/
constructor(src, dest) {
this.src = src;
this.dest = dest;
this.id = -1; // Id will be regenerated when add to TableTest
}
/**
* Dress the line in HTML
*
* @returns {HTMLDivElement} a div containing 2 textarea
*/
getHTML() {
let div = document.createElement("div");
div.className += " line form-inline";
div.setAttribute(datalineid, this.id);
// Src
let txtSrc = document.createElement("textarea");
div.appendChild(txtSrc);
txtSrc.value = this.src;
txtSrc.className += " src form-control";
autosize(txtSrc);
txtSrc.oninput = _ => {
// Regularly update content
this.src = txtSrc.value;
autosize.update(txtSrc);
}
// Control buttons
div.appendChild(controlButtons(this));
// Dest
let txtDest = document.createElement("textarea");
div.appendChild(txtDest);
txtDest.value = this.dest;
txtDest.className += " dest form-control";
autosize(txtDest);
txtDest.oninput = _ => {
// Regularly update content
this.dest = txtDest.value;
autosize.update(txtDest);
}
return div;
}
} |
JavaScript | class TableTest {
/**
* Creates an instance of TableTest.
* @memberof TableTest
*/
constructor() {
this.data = [];
// Other metadata
this.metadata = {
title: "", // Title of chosen text
nickname: "", // SNK Nickname
attempt: 0, // Number of attempts candidate has tried
}
this.counter = 0;
}
generateId() {
this.counter++;
return this.counter;
}
/**
* Add a new line at the end
*
* @param {Line} line
* @memberof TableTest
*/
push(line) {
line.id = this.generateId();
this.data.push(line);
}
/**
* Add a new line at a specific index
*
* @param {Number} index
* @param {Line} line not having ID. Otherwise, its ID will be reset
* @memberof TableTest
*/
insertAt(index, line) {
line.id = this.generateId();
this.data.splice(index, 0, line);
}
/**
* Delete a line having specified id. Do nothing if not found
*
* @param {Number} id
* @memberof TableTest
*/
deleteLineHavingId(id) {
let pos = this.data.findIndex(line => line.id == id);
if (pos > -1) {
this.data.splice(pos, 1);
}
}
/**
* Delete a line "equal" to value. Do nothing if not found
*
* @param {Line} value
* @memberof TableTest
*/
deleteLineEqualTo(value) {
let pos = this.findIndexOfLineEqualTo(value);
if (pos > -1) {
this.data.splice(pos, 1);
}
}
/**
* Find the index of a line
*
* @param {Line} content
* @returns {Number} -1 if not found
* @memberof TableTest
*/
findIndexOfLineEqualTo(content) {
return this.data.findIndex(line => line.id == content.id
&& line.src == content.src
&& line.dest == content.dest
);
}
/**
* Find the index of the line having submitted value
*
* @param {Number} id
* @returns {Number} -1 if not found
* @memberof TableTest
*/
findIndexOfLineHavingId(id) {
return this.data.findIndex(line => line.id == id);
}
/**
* Set the name of candidate
*
* @param {String} name
* @memberof TableTest
*/
setNickname(name) {
this.metadata.nickname = name.replace("_", " ");
}
/**
* Set the name of chosen test
*
* @param {String} name
* @memberof TableTest
*/
setTitle(name) {
this.metadata.title = name.replace("_", " ");
}
/**
* Set the order of this test
*
* @param {Number} num
* @memberof TableTest
*/
setAttempt(num) {
this.metadata.attempt = (num > 0 ? num : 1);
}
/**
* The full title of test according to rule
*
* @returns {String} "SNKTEST\_<Nickname>\_<LN Title>\_<N° of Attempt>"
* @memberof TableTest
*/
getTestTitle() {
return "SNKTEST_" + this.metadata.nickname
+ "_" + this.metadata.title
+ "_" + this.metadata.attempt;
}
/**
* Initialize data from input text
*
* @param {String} srctext including the title
* @param {Object} options other process options
* @param {Boolean} options.removeBlank automatically remove blank line
* @memberof TableTest
*/
initFromText(srctext, options) {
let self = this;
srctext.split(/\n/)
.forEach(linetext => {
let newline = new Line(linetext, "");
if (options.removeBlank) {
if (newline.src.trim() != "" || newline.dest.trim() != "") {
self.push(newline);
}
} else {
self.push(newline);
}
});
}
/**
* Initialize data from loaded json
*
* @param {String} jsonstring a string in format of json
* @param {Object} options other process options
* @param {Boolean} options.removeBlank automatically remove blank line
* @memberof TableTest
*/
initFromJSON(jsonstring, options) {
let json = JSON.parse(jsonstring);
/* Set metadata */
this.reset();
this.setTitle(json.metadata.title);
this.setNickname(json.metadata.nickname);
this.setAttempt(json.metadata.attempt);
/* Set data */
for (let index = 0; index < json.data.length; index++) {
const storedLine = json.data[index];
let newline = new Line(storedLine.src, storedLine.dest);
if (options.removeBlank) {
if (newline.src.trim() != "" || newline.dest.trim() != "") {
this.push(newline);
}
} else {
this.push(newline);
}
}
}
/**
* Initialize from a html page. It should have:
* + LN title with id "title"
* + nickname of candidate with id "nickname"
* + the attempt of candidation with id "attempt"
*
* Furthermore, this will parse all tr elements having exactly
* 2 td inside, assuming the one on the left is "source" while
* the other is "destination".
*
* @param {String} htmlstring
* @param {Object} options other process options
* @param {Boolean} options.removeBlank automatically remove blank line
* @memberof TableTest
*/
initFromHTML(htmlstring, options) {
let parser = new DOMParser(),
html = parser.parseFromString(htmlstring, "text/html");
this.reset();
this.setTitle(html.querySelector("#title").innerText);
this.setNickname(html.querySelector("#nickname").innerText);
this.setAttempt(html.querySelector("#attempt").innerText);
// Retrieve all tr having exactly 2 td inside,
// assuming td td on the left is "source"
// and the other on the right is "destination"
html.querySelectorAll("tr").forEach(tr => {
let listtd = tr.querySelectorAll("td");
if (listtd.length == 2) {
let newline = new Line(listtd.item(0).innerText, listtd.item(1).innerText);
if (options.removeBlank) {
if (newline.src.trim() != "" || newline.dest.trim() != "") {
this.push(newline);
}
} else {
this.push(newline);
}
}
});
}
/**
* Dress the table in HTML
*
* @returns {HTMLDivElement}
* @memberof TableTest
*/
getHTML() {
// Outer HTML
let div = document.createElement("div");
div.id = "table-test";
// Test content
this.data.forEach(line => div.appendChild(line.getHTML()));
return div;
}
/**
* In order to save into browser's memory
*
* @returns {String} stringified version of this table
* @memberof TableTest
*/
JSONStringify() {
return JSON.stringify(this);
}
/**
* In order to create a html file
*
* @see https://effectiveinc.com/effective-thinking/articles/generating-downloadable-word-document-browser/
*
* @returns {HTMLHtmlElement} a basic table in html with a title
* @memberof TableTest
*/
getHTMLPage() {
let html = document.createElement("html"),
head = document.createElement("head"),
body = document.createElement("body");
html.appendChild(head);
html.appendChild(body);
// Set the header
// Charset
let charset = document.createElement("meta");
head.appendChild(charset);
charset.setAttribute("charset", "utf-8");
// Title
let title = document.createElement("title");
head.appendChild(title);
title.innerText = this.getTestTitle();
// Style
let style = document.createElement("style");
head.appendChild(style);
style.innerText = "table {border-collapse: collapse;}"
+ "table, td, tr {border: solid 1px black}"
+ "td {width: 50%; vertical-align: top}";
// Set the body
// Title
let heading = document.createElement("h1");
body.appendChild(heading);
heading.innerText = this.metadata.title;
heading.id = "testtitle";
// Nickname
body.appendChild(metadataBanner("nickname",
"Nickname trên Sonako:",
this.metadata.nickname));
// Attempt
body.appendChild(metadataBanner("attempt",
"Lần test thứ:",
this.metadata.attempt));
// LN Title
body.appendChild(metadataBanner("title",
"Tiêu đề truyện:",
this.metadata.title));
// Calculate the table
let content = document.createElement("table");
body.appendChild(content);
let tbody = document.createElement("tbody");
content.appendChild(tbody);
for (let index = 0; index < this.data.length; index++) {
const line = this.data[index];
let row = document.createElement("tr");
tbody.appendChild(row);
row.id = line.id;
let srcTxt = document.createElement("td"),
destTxt = document.createElement("td");
row.appendChild(srcTxt);
row.appendChild(destTxt);
srcTxt.innerText = line.src;
srcTxt.className += " src";
destTxt.innerText = line.dest;
destTxt.className += " dest";
}
return html;
}
/**
* Check if the table has been set
*
* @returns {Boolean} true if there is no line in data. False otherwise
* @memberof TableTest
*/
isEmpty() {
if (this.data.length == 0) {
return true;
} else {
return false;
}
}
/**
* Reset all properties
*
* @memberof TableTest
*/
reset() {
this.data = [];
this.counter = 0;
this.setAttempt(0);
this.setNickname("");
this.setTitle("");
}
} |
JavaScript | class CoreApi {
/**
* Initiate with options
* @param {Object} options - should have these props:
* isProduction, serverKey, clientKey
*/
constructor(options = {isProduction: false, serverKey: '', clientKey: ''}) {
this.apiConfig = new ApiConfig(options);
this.httpClient = new HttpClient(this);
this.transaction = new Transaction(this);
}
/**
* Do `/v2/charge` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
charge(parameter = {}) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v2/charge';
let responsePromise = this.httpClient.request(
'post',
this.apiConfig.get().serverKey,
apiUrl,
parameter);
return responsePromise;
}
/**
* Do `/v2/capture` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
capture(parameter = {}) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v2/capture';
let responsePromise = this.httpClient.request(
'post',
this.apiConfig.get().serverKey,
apiUrl,
parameter);
return responsePromise;
}
/**
* Do `/v2/card/register` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
cardRegister(parameter = {}) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v2/card/register';
let responsePromise = this.httpClient.request(
'get',
this.apiConfig.get().serverKey,
apiUrl,
parameter);
return responsePromise;
}
/**
* Do `/v2/token` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
cardToken(parameter = {}) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v2/token';
let responsePromise = this.httpClient.request(
'get',
this.apiConfig.get().serverKey,
apiUrl,
parameter);
return responsePromise;
}
/**
* Do `/v2/point_inquiry/<tokenId>` API request to Core API
* @param {String} tokenId - tokenId of credit card (more params detail refer to: https://api-docs.midtrans.com)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
cardPointInquiry(tokenId) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v2/point_inquiry/' + tokenId;
let responsePromise = this.httpClient.request(
'get',
this.apiConfig.get().serverKey,
apiUrl,
null);
return responsePromise;
}
/**
* Create `/v2/pay/account` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com/#create-pay-account)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
linkPaymentAccount(parameter = {}) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v2/pay/account';
let responsePromise = this.httpClient.request(
'post',
this.apiConfig.get().serverKey,
apiUrl,
parameter);
return responsePromise;
}
/**
* Do `/v2/pay/account/<accountId>` API request to Core API
* @param {String} accountId - accountId for specific payment channel (more params detail refer to: https://api-docs.midtrans.com/#get-pay-account)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
getPaymentAccount(accountId) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v2/pay/account/' + accountId;
let responsePromise = this.httpClient.request(
'get',
this.apiConfig.get().serverKey,
apiUrl,
null);
return responsePromise;
}
/**
* Unbind `/v2/pay/account/<accountId>/unbind` API request to Core API
* @param {String} accountId - accountId for specific payment channel (more params detail refer to: https://api-docs.midtrans.com/#unbind-pay-account)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
unlinkPaymentAccount(accountId) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v2/pay/account/' + accountId + '/unbind';
let responsePromise = this.httpClient.request(
'post',
this.apiConfig.get().serverKey,
apiUrl,
null);
return responsePromise;
}
/**
* Create `/v1/subscription` API request to Core API
* @param {Object} parameter - object of Core API JSON body as parameter, will be converted to JSON (more params detail refer to: https://api-docs.midtrans.com/#create-subscription)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
createSubscription(parameter = {}) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v1/subscriptions';
let responsePromise = this.httpClient.request(
'post',
this.apiConfig.get().serverKey,
apiUrl,
parameter);
return responsePromise;
}
/**
* Do `/v1/subscription/<subscriptionId>` API request to Core API
* @param {String} subscriptionId - subscriptionId given by Midtrans (more params detail refer to: https://api-docs.midtrans.com/#get-subscription)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
getSubscription(subscriptionId) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v1/subscriptions/' + subscriptionId;
let responsePromise = this.httpClient.request(
'get',
this.apiConfig.get().serverKey,
apiUrl,
null);
return responsePromise;
}
/**
* Do `/v1/subscription/<subscriptionId>/disable` API request to Core API
* @param {String} subscriptionId - subscriptionId given by Midtrans (more params detail refer to: https://api-docs.midtrans.com/#disable-subscription)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
disableSubscription(subscriptionId) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v1/subscriptions/' + subscriptionId + '/disable';
let responsePromise = this.httpClient.request(
'post',
this.apiConfig.get().serverKey,
apiUrl,
null);
return responsePromise;
}
/**
* Do `/v1/subscription/<subscriptionId>/enable` API request to Core API
* @param {String} subscriptionId - subscriptionId given by Midtrans (more params detail refer to: https://api-docs.midtrans.com/#enable-subscription)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
enableSubscription(subscriptionId) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v1/subscriptions/' + subscriptionId + '/enable';
let responsePromise = this.httpClient.request(
'post',
this.apiConfig.get().serverKey,
apiUrl,
null);
return responsePromise;
}
/**
* Do update subscription `/v1/subscription/<subscriptionId>` API request to Core API
* @param {String} subscriptionId - subscriptionId given by Midtrans (more params detail refer to: https://api-docs.midtrans.com/#update-subscription)
* @return {Promise} - Promise contains Object from JSON decoded response
*/
updateSubscription(subscriptionId, parameter = {} ) {
let apiUrl = this.apiConfig.getCoreApiBaseUrl() + '/v1/subscriptions/' + subscriptionId;
let responsePromise = this.httpClient.request(
'patch',
this.apiConfig.get().serverKey,
apiUrl,
parameter);
return responsePromise;
}
} |
JavaScript | class MapEditorDialog extends L.Control.Dialog {
initialize(options) {
this.options = JSON.parse(JSON.stringify(this.options));
L.setOptions(this, options);
this.state = 'custom'; /* alternatives: maximized, minimized */
}
_initLayout() {
super._initLayout();
let innerContainer = this._innerContainer;
var className = "leaflet-control-dialog";
var minimizeNode = (this._minimizeNode = L.DomUtil.create(
"div",
className + "-minimize"
));
var minimizeIcon = L.DomUtil.create("i", "fa fa-window-minimize");
minimizeNode.appendChild(minimizeIcon);
L.DomEvent.on(minimizeNode, "click", this._handleMinimize, this);
var maximizeNode = (this._maximizeNode = L.DomUtil.create(
"div",
className + "-maximize"
));
var maximizeIcon = L.DomUtil.create("i", "fa fa-window-maximize");
maximizeNode.appendChild(maximizeIcon);
L.DomEvent.on(maximizeNode, "click", this._handleMaximize, this);
innerContainer.appendChild(minimizeNode);
innerContainer.appendChild(maximizeNode);
this._map.on('resize', () => {
this._handleMapResize();
});
}
close() {
this._map.off('resize', () => {
this._handleMapResize();
});
return super.close()
}
_handleMinimize() {
let map_size = map.getSize();
let height = 600;
if (map_size.y < 1000) {
height = map_size.y - 200;
if (height < 0) height = 100;
}
let width = 300;
super.setLocation([ map_size.y - height - 20, map_size.x - width - 20 ]);
super.setSize([ width, height ]);
this.state = 'minimized';
}
_handleMaximize() {
let map_size = this._map.getSize();
super.setLocation([ 10, 50 ]);
super.setSize([ map_size.x - 300, map_size.y - 120 ]);
this.state = 'maximized';
}
_handleMapResize() {
if (this.state == 'minimized') this._handleMinimize();
if (this.state == 'maximized') this._handleMaximize();
}
} |
JavaScript | class DeviceAxisEvent extends Event {
/**
* Creates a DeviceAxisEvent object.
*
* @param type {string} Event name.
*/
constructor (type) {
super(type, false, false)
/**
* The InputDevice that generated this event.
*
* @type {InputDevice}
*/
this.device = null
/**
* The axis index associated with this event.
*
* @type {number}
*/
this.axis = -1
/**
* The current value of the axis, a number between -1 and 1, inclusive.
*
* @type {number}
*/
this.value = 0
}
_reset (device, timestamp, axis, value) {
this.device = device
this.axis = axis
this.value = value
return super._reset(timestamp)
}
} |
JavaScript | class LineAtlas {
constructor(resources, options) {
this.resources = resources;
this.options = options || {};
this.atlas = {};
}
getAtlas(symbol) {
const key = JSON.stringify(symbol);
if (!this.atlas[key]) {
const atlas = this.addAtlas(symbol);
if (atlas) {
this.atlas[key] = atlas;
}
}
return this.atlas[key];
}
addAtlas(symbol) {
if (!symbol['lineDasharray'] && !symbol['linePatternFile']) {
return null;
}
const size = this._getSize(symbol, this.resources);
const canvas = this._createCanvas(size);
if (!canvas) {
throw new Error('can not initialize canvas container.');
}
const ctx = canvas.getContext('2d');
maptalks.Canvas.prepareCanvas(ctx, symbol, this.resources);
ctx.moveTo(0, size[1] / 2);
ctx.lineTo(size[0], size[1] / 2);
ctx.stroke();
return {
'canvas' : canvas,
'offset' : new maptalks.Point(0, 0)
};
}
/**
* Get size of the atlas of symbol.
* @param {Object} symbol - atlas's symbol
* @return {Number[]} size : [width, height]
*/
_getSize(symbol, resources) {
let w = 0, h = 0;
const dashArray = symbol['lineDasharray'];
if (dashArray) {
for (let i = 0; i < dashArray.length; i++) {
w += dashArray[i];
}
// If the number of elements in the array is odd,
// the elements of the array get copied and concatenated.
// For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25].
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash
if (dashArray.length % 2 === 1) {
w *= 2;
}
h = (symbol['lineWidth'] == null ? 2 : symbol['lineWidth']);
}
if (symbol['linePatternFile']) {
const image = resources.getImage(symbol['linePatternFile']);
if (image.width > w) {
w = image.width;
}
if (image.height > h) {
h = image.height;
}
}
return [w, h];
}
_createCanvas(size) {
if (this.options['canvasClass']) {
return new this.options['canvasClass'](size[0], size[1]);
}
if ((typeof document) !== 'undefined') {
const canvas = document.createElement('canvas');
canvas.width = size[0];
canvas.height = size[1];
return canvas;
}
return null;
}
} |
JavaScript | class Vec2 {
constructor(x,y) {
this.x = x;
this.y = y;
}
//returns a new vector which is the sum of this vector and the input vector
add(otherVec) {
return new Vec2(this.x+otherVec.x,this.y+otherVec.y);
}
addX(scalar) {
return new Vec2(this.x + scalar,this.y);
}
addY(scalar) {
return new Vec2(this.x,this.y + scalar);
}
subtract(otherVec) {
return new Vec2(this.x-otherVec.x,this.y-otherVec.y);
}
//adds the input vector to this one
addToThis(otherVec) {
this.x+=otherVec.x;
this.y+=otherVec.y;
}
//returns a new vector which is the negative of this one
neg() {
return this.scale(-1);
}
//negates this vector
negThis() {
this.x*=-1;
this.y*=-1;
}
scale(amount) {
return new Vec2(this.x*amount,this.y*amount);
}
clone() {
return new Vec2(this.x,this.y);
}
magnitude() {
return Math.sqrt((this.x*this.x)+(this.y*this.y));
}
normalize() {
let magnitude = this.magnitude();
return new Vec2(this.x/magnitude,this.y/magnitude);
}
normal() {
let magnitude = this.magnitude();
if(magnitude == 0) {
return new Vec2(0,0);
}
if(this.x===0) {
return new Vec2(-this.y/magnitude,this.x/magnitude);
}
else {
return new Vec2(this.y/magnitude,-this.x/magnitude);
}
}
dot(otherVector) {
return this.x*otherVector.x+this.y*otherVector.y;
}
get angle() {
return Math.atan2(this.y,this.x);
}
rotateDeg(angleInDeg) {
let angleInRad = Math.PI*angleInDeg/180;
return this.rotate(angleInRad);
}
/**
* Multiplies this vector with a 2x2 matrix
* @param {number} x11 the top-left number in a 2x2 matrix
* @param {number} x21 the top-right number in a 2x2 matrix
* @param {number} x12 the bottom-left number in a 2x2 matrix
* @param {number} x22 the bottom-right number in a 2x2 matrix
* @returns {Vec2} the resulting vector after the matrix multiplication
*/
matrix(x11,x21,x12,x22) {
return new Vec2(this.x*x11+this.y*x21,this.x*x12+this.y*x22);
}
isometric() {
return this.matrix(1,-1,0.5,0.5);
// same thing as below
//return this.rotateDeg(-45).matrix(1,0,0,0.5).scale(Math.sqrt(2));
}
inverseIsometric() {
return this.matrix(0.5,1,-0.5,1);
// same thing as below
//return this.scale(1/Math.sqrt(2)).matrix(1,0,0,2).rotateDeg(45);
}
rotate(angleInRad) {
let cos = Math.cos(angleInRad);
let sin = Math.sin(angleInRad);
return this.matrix(cos,sin,-sin,cos);
}
} |
JavaScript | class DeserializationPolicy extends BaseRequestPolicy {
constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) {
var _a;
super(nextPolicy, requestPolicyOptions);
this.jsonContentTypes =
(deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes;
this.xmlContentTypes =
(deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes;
this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY;
}
async sendRequest(request) {
return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, {
xmlCharKey: this.xmlCharKey,
}));
}
} |
JavaScript | class UniqueList {
constructor(max = Infinity) {
this.max = max;
this.count = 0;
this._items = {};
}
add(item) {
if (this._items[item] !== undefined) {
return;
}
this._items[item] = this.count++;
}
find(item) {
return this._items[item];
}
destroy() {
this._items = {};
this.count = 0;
}
} |
JavaScript | class ZdsUser {
/**
* Create a user.
* @param {string} username - The user's public name.
* @param {string} avatar_url - The URL of the avatar (should point to a valid image).
*/
constructor(username, avatar_url) {
this.username = username
this.avatar_url = avatar_url
}
} |
JavaScript | class TestConnector {
constructor (prng) {
/**
* @type {Set<TestYInstance>}
*/
this.allConns = new Set()
/**
* @type {Set<TestYInstance>}
*/
this.onlineConns = new Set()
/**
* @type {random.PRNG}
*/
this.prng = prng
}
/**
* Create a new Y instance and add it to the list of connections
* @param {number} clientID
*/
createY (clientID) {
return new TestYInstance(this, clientID)
}
/**
* Choose random connection and flush a random message from a random sender.
*
* If this function was unable to flush a message, because there are no more messages to flush, it returns false. true otherwise.
* @return {boolean}
*/
flushRandomMessage () {
const prng = this.prng
const conns = Array.from(this.onlineConns).filter(conn => conn.receiving.size > 0)
if (conns.length > 0) {
const receiver = random.oneOf(prng, conns)
const [sender, messages] = random.oneOf(prng, Array.from(receiver.receiving))
const m = messages.shift()
if (messages.length === 0) {
receiver.receiving.delete(sender)
}
const encoder = encoding.createEncoder()
receiver.mMux(() => {
console.log('receive (' + sender.userID + '->' + receiver.userID + '):\n', syncProtocol.stringifySyncMessage(decoding.createDecoder(m), receiver))
// do not publish data created when this function is executed (could be ss2 or update message)
syncProtocol.readSyncMessage(decoding.createDecoder(m), encoder, receiver)
})
if (encoding.length(encoder) > 0) {
// send reply message
sender._receive(encoding.toBuffer(encoder), receiver)
}
return true
}
return false
}
/**
* @return {boolean} True iff this function actually flushed something
*/
flushAllMessages () {
let didSomething = false
while (this.flushRandomMessage()) {
didSomething = true
}
return didSomething
}
reconnectAll () {
this.allConns.forEach(conn => conn.connect())
}
disconnectAll () {
this.allConns.forEach(conn => conn.disconnect())
}
syncAll () {
this.reconnectAll()
this.flushAllMessages()
}
/**
* @return {boolean} Whether it was possible to disconnect a randon connection.
*/
disconnectRandom () {
if (this.onlineConns.size === 0) {
return false
}
random.oneOf(this.prng, Array.from(this.onlineConns)).disconnect()
return true
}
/**
* @return {boolean} Whether it was possible to reconnect a random connection.
*/
reconnectRandom () {
const reconnectable = []
this.allConns.forEach(conn => {
if (!this.onlineConns.has(conn)) {
reconnectable.push(conn)
}
})
if (reconnectable.length === 0) {
return false
}
random.oneOf(this.prng, reconnectable).connect()
return true
}
} |
JavaScript | class List {
constructor(){
this._list = [];
this.size = 0;
}
add(element){
this._list.push(element);
this._list.sort(List.sort);
this.size++;
return this;
}
remove(index){
this._validate(index);
this._list.splice(index, 1);
this.size--;
return this;
}
get(index){
this._validate(index);
return this._list[index];
}
_validate(index){
if (index < 0 || index >= this._list.length) {
throw new Error("Index is out of bounds");
}
}
static sort(a, b){
return a-b;
}
} |
JavaScript | class Search extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props, context) {
super(props, context);
this.state = {
name: ''
};
this.onClick = this.onClick.bind(this);
this.onChange = this.onChange.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
onClick(e){
this.props.findPokemon(this.state.name);
}
onChange(e){
this.setState({ name: e.target.value });
}
handleKeyPress(e){
if (e.key === 'Enter') {
this.onClick(e);
}
}
render() {
return (
<Row className="show-grid">
<Col xs={12} md={12}>
<Form>
<FormGroup controlId="searchForm">
<ControlLabel>Pokemon name:</ControlLabel>
<InputGroup>
<FormControl type="text" value={this.state.name} onKeyPress={this.handleKeyPress} placeholder="Name" onChange={this.onChange}></FormControl>
<InputGroup.Button>
<Button type="button" bsStyle="primary" onClick={this.onClick}>
<Glyphicon glyph="search" />
</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
</Form>
</Col>
</Row>
);
}
} |
JavaScript | class OrderController {
/**
* @function addToCart
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static addToCart(req, res) {
const { userId } = req;
let { foodId, quantity } = req.body;
foodId = foodId ? foodId.toString().replace(/\s+/g, '') : foodId;
quantity = quantity ? quantity.toString().replace(/\s+/g, '') : quantity;
db.task('add to cart', data => data.menu.findById(foodId)
.then((meal) => {
if (!meal) {
return res.status(400).json({
success: 'false',
message: 'meal not found',
});
}
const total = quantity * meal.price;
return db.cart.create({ userId, foodId, quantity, total })
.then(() => {
return res.status(201).json({
success: 'true',
message: 'meal added to cart successfully',
});
})
.catch(() => {
return res.status(409).json({
success: 'false',
message: 'This food is already on the cart, you can modify the quantity on the cart',
});
})
})
.catch((err) => {
return res.status(500).json({
success: 'false',
message: 'so sorry, try again later',
err: err.message,
});
}));
}
/**
* @function modifyCart
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static modifyCart(req, res) {
const { userId } = req;
const id = parseInt(req.params.id, 10);
const { quantity } = req.body;
db.task('modify cart', data => data.cart.findById(id)
.then((mealFound) => {
if (!mealFound) {
return res.status(400).json({
success: 'false',
message: 'cart item not found',
});
}
if (userId !== mealFound.user_id) {
return res.status(401).json({
success: 'false',
message: 'you are unauthorized to modify this cart',
});
}
const foodId = mealFound.food_id;
return db.menu.findById(foodId)
.then((foodItem) => {
const total = quantity * foodItem.price;
const updateCart = {
quantity,
total,
};
return db.cart.modify(updateCart, id)
.then(() => {
res.status(200).json({
success: 'true',
message: 'successful! quantity has been updated',
});
});
});
})
.catch((err) => {
console.log(err);
return res.status(500).json({
success: 'false',
message: 'so sorry, try again later',
err: err.message,
});
}));
}
/**
* @function deleteCart
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static deleteCart(req, res) {
const { userId } = req;
db.task('find food for user', data => data.cart.findByUserId(userId)
.then((itemFound) => {
if (!itemFound || itemFound.length === 0) {
return res.status(401).json({
success: 'false',
message: 'nothing found on the cart',
});
}
return db.cart.remove(userId);
})
.catch(() => {
return res.status(500).json({
success: 'true',
message: 'deleted',
});
}));
}
/**
* @function getCart
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static getCart(req, res) {
const { userId } = req;
db.task('add to cart', data => data.cart.findByUserId(userId)
.then((meals) => {
if (!meals || meals.length === 0) {
return res.status(404).json({
success: 'false',
message: 'your cart list is empty, add an item to it',
});
}
const cart = [];
const foodItems = [...meals];
foodItems.forEach((meal) => {
const itemName = meal.item_name;
const itemPrice = meal.price;
const itemQuantity = meal.quantity;
const itemTotal = meal.total;
const food = {
itemName,
itemPrice,
itemQuantity,
itemTotal,
};
cart.push(food);
});
return res.status(200).json({
success: 'true',
cart,
});
})
.catch((err) => {
return res.status(500).json({
success: 'false',
message: 'so sorry, try again later',
err: err.message,
});
}));
}
/**
* @function orderFood
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static orderFood(req, res) {
const { userId } = req;
const status = 'New';
let { deliveryAddress, telephone } = req.body;
deliveryAddress = deliveryAddress ? deliveryAddress.toString().replace(/\s+/g, '') : deliveryAddress;
telephone = telephone ? telephone.toString().replace(/\s+/g, '') : telephone;
db.task('post order', data => data.cart.findByUserId(userId)
.then((meals) => {
if (!meals || meals.length === 0) {
return res.status(404).json({
success: 'false',
message: 'your cart list is empty, add an item to it',
});
}
let total = 0;
meals.forEach((meal) => {
total += parseInt(meal.total, 10);
});
return db.order.create({ userId, deliveryAddress, telephone, total, status })
.then((order) => {
const orderId = order.id;
meals.forEach((meal) => {
const foodId = meal.food_id;
const quantity = meal.quantity;
const totalPrice = meal.total;
return db.foodOrdered.create({ userId, orderId, foodId, quantity, totalPrice })
.then(() => {
db.none('DELETE FROM cart;');
return res.status(200).json({
success: 'true',
message: 'your order was successful',
});
});
});
})
.catch((err) => {
db.none('DELETE FROM placed_order WHERE id = ${order.id}');
return res.status(500).json({
success: 'false',
message: 'so sorry, something went wrong, try again',
err: err.message,
});
});
})
.catch((err) => {
return res.status(500).json({
success: 'false',
message: 'so sorry, try again later',
err: err.message,
});
}));
}
/**
* @function orderHistory
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static orderHistory(req, res) {
const { userId } = req;
const paramUserId = parseInt(req.params.id, 10);
if (userId !== paramUserId) {
return res.status(400).json({
success: 'false',
message: 'user unauthorized to get order history',
});
}
return db.order.userOrderData(userId)
.then((orders) => {
const allOrders = [...orders];
if (allOrders.length === 0) {
return res.status(404).json({
success: 'false',
message: 'There are no pending orders in the database',
});
}
return res.status(200).json({
success: 'true',
message: 'here goes your order history',
allOrders,
});
})
.catch((err) => {
res.status(500).json({
success: 'false',
message: err.message,
});
});
}
/**
* @function getOrders
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static getOrders(req, res) {
const { userId } = req;
const publicUser = process.env.PUBLIC_USER;
db.task('get orders', data => data.users.findById(userId)
.then((user) => {
if (user.admin_user == publicUser) {
return res.status(401).json({
success: 'false',
message: 'user unauthorized to get all orders',
});
}
return db.order.allData()
.then((orders) => {
const allOrders = [...orders];
if (allOrders.length === 0) {
return res.status(404).json({
success: 'false',
message: 'There are no pending orders in the database',
});
}
return res.status(200).json({
success: 'true',
allOrders,
});
});
})
.catch((err) => {
res.status(500).json({
success: 'false',
message: err.message,
});
}));
}
/**
* @function getOrder
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static getOrder(req, res) {
const { userId } = req;
const orderId = parseInt(req.params.id, 10);
const publicUser = process.env.PUBLIC_USER;
if (isNaN(orderId)) {
return res.status(400).json({
success: 'false',
message: 'param should be a number not an alphabet',
});
}
return db.task('fetch user', data => data.users.findById(userId)
.then((user) => {
if (user.admin_user == publicUser) {
return res.status(401).json({
success: 'false',
message: 'user unauthorized to get fetch an order',
});
}
return db.order.findById(orderId)
.then((order) => {
if (!order && order.length === 0) {
return res.status(404).json({
success: 'false',
message: 'This order does not exist',
});
}
let grandTotal = 0;
const itemsOnOrder = [];
order.forEach((order) => {
const itemName = order.item_name;
const itemQuantity = order.quantity;
const itemPrice = order.price;
const total = order.total;
grandTotal = order.total_price;
itemsOnOrder.push({ itemName, itemPrice, itemQuantity, total });
});
return res.status(200).json({
success: 'true',
itemsOnOrder,
grandTotal,
});
})
.catch(() => {
res.status(404).json({
success: 'false',
message: 'this ordered item does not exist',
});
});
})
.catch((err) => {
res.status(500).json({
success: 'false',
message: err.message,
});
}));
}
/**
* @function orderStatus
* @memberof OrderController
*
* @param {Object} req - this is a request object that contains whatever is requested for
* @param {Object} res - this is a response object to be sent after attending to a request
*
* @static
*/
static orderStatus(req, res) {
const { userId } = req;
const orderId = parseInt(req.params.id, 10);
let { orderStatus } = req.body;
orderStatus = orderStatus && orderStatus
.toLowerCase().toString().replace(/\s+/g, '');
const publicUser = process.env.PUBLIC_USER;
if (isNaN(orderId)) {
return res.status(400).json({
success: 'false',
message: 'param should be a number not an alphabet',
});
}
return db.task('fetch user', data => data.users.findById(userId)
.then((user) => {
if (user.admin_user === publicUser) {
return res.status(401).json({
success: 'false',
message: 'user unauthorized to update status order',
});
}
return db.order.findById(orderId)
.then((order) => {
order.order_status = orderStatus;
if (!order) {
return res.status(404).json({
success: 'false',
message: 'This order does not exist',
});
}
const updatedStatus = {
orderStatus: orderStatus || orderStatus.user,
};
return db.order.modify(updatedStatus, orderId)
.then((result) => {
res.status(200).json({
success: 'true',
message: 'successful! status modified by you',
orderStatus: result,
});
})
.catch((err) => {
return res.status(500).json({
success: 'false',
message: 'status could not be modified',
err: err.message,
});
});
});
})
.catch((err) => {
res.status(500).json({
success: 'false',
message: err.message,
});
}));
}
} |
JavaScript | class CourseCard extends Component {
render() {
return (
<NavLink tag={Link} className="course-card" to={"/course-front-page/" + this.props.routeName}>
<img src={process.env.PUBLIC_URL + "/thumbnails/courses/" + this.props.routeName + ".png"} alt={"Course: " + this.props.title}/>
<h6>{this.props.title}</h6>
<p className="dim-text">{this.props.desc}</p>
<p><span className="difficulty-tag">{this.props.difficulty}</span></p>
</NavLink>
);
}
} |
JavaScript | class ExchangeReport extends Component {
state = {
dataList: [],
activePage:1,
startDate: moment().startOf('isoWeek').format('YYYY-MM-DD'),
endDate: moment().endOf('isoWeek').format('YYYY-MM-DD'),
picker_startDate:'',
picker_endDate:'',
btnActive:"thisWeek",
loading: true,
downloadData:''
};
handlePageChange (pageNumber) { // 切換頁面
this.setState({
activePage: pageNumber
})
this.getInitialData(pageNumber)
}
handleStartChange = (date) => { //datePicker的起始日
this.setState({
startDate: moment(date).format('YYYY-MM-DD'),
btnActive:'date-picker-search'
},()=>{this.getInitialData()})
}
handleEndChange = (date) => { //datePicker的結束日
this.setState({
endDate: moment(date).format('YYYY-MM-DD'),
btnActive:'date-picker-search'
},()=>{this.getInitialData()})
}
// onClickDatePickerSearch = (e) => {
// let format_picker_startDate = moment(this.state.picker_startDate).format('YYYY-MM-DD');
// let format_picker_endDate = moment(this.state.picker_endDate).format('YYYY-MM-DD');
// this.setState({
// btnActive:'date-picker-search'
// })
// setTimeout(() => {
// this.getInitialData(format_picker_startDate,format_picker_endDate)
// }, 300);
// }
clearDatePickerInput =()=>{
this.setState({
picker_startDate: '',
picker_endDate: ''
})
}
getToday = (e) => {
this.clearDatePickerInput()
this.setState({
startDate: moment().format('YYYY-MM-DD'),
endDate: moment().format('YYYY-MM-DD'),
btnActive:e.target.name
},()=>{this.getInitialData()})
}
getYesterday = (e) => {
this.clearDatePickerInput()
this.setState({
startDate: moment().subtract(1, 'days').format('YYYY-MM-DD'),
endDate: moment().subtract(1, 'days').format('YYYY-MM-DD'),
btnActive:e.target.name
},()=>{this.getInitialData()})
}
getThisWeek = (e) => {
this.clearDatePickerInput()
this.setState({
startDate: moment().startOf('isoWeek').format('YYYY-MM-DD'),
endDate: moment().endOf('isoWeek').format('YYYY-MM-DD'),
btnActive:e.target.name
},()=>{this.getInitialData()})
}
getLastWeek = (e) => {
this.clearDatePickerInput()
this.setState({
startDate: moment().subtract(1,'isoWeek').startOf('isoWeek').format('YYYY-MM-DD'),
endDate: moment().subtract(1,'isoWeek').endOf('isoWeek').format('YYYY-MM-DD'),
btnActive:e.target.name
},()=>{this.getInitialData()})
}
getThisMonth = (e) => {
this.clearDatePickerInput()
this.setState({
startDate: moment().startOf('month').format('YYYY-MM-DD'),
endDate: moment().endOf('month').format('YYYY-MM-DD'),
btnActive:e.target.name
},()=>{this.getInitialData()})
}
getLastMonth = (e) => {
this.clearDatePickerInput()
this.setState({
startDate: moment().subtract(1,'month').startOf('month').format('YYYY-MM-DD'),
endDate: moment().subtract(1,'month').endOf('month').format('YYYY-MM-DD'),
btnActive:e.target.name
},()=>{this.getInitialData()})
}
getDownloadData = async() => { //取得下載資料
try {
let resCsv = await apiDownloadExchangeReport(this.state.startDate,this.state.endDate,this.props.i18n.language)
if(resCsv.data.code===2 || resCsv.data === undefined ){
return false
}
else{
this.setState({downloadData : resCsv.data})
}
} catch (err) {
console.log(err);
}
}
getInitialData = async() => {
this.showLoading()
try {
let res = await apiGetExchangeReport(this.state.startDate,this.state.endDate);
if(res.data.code===1){
let resData = res.data.data
let resultList = Object.entries(resData).map(([currency, amount]) => ({currency,amount}))
this.setState({
dataList: resultList,
}
,()=>{this.getDownloadData()}
)
}
} catch(err) {
console.log(err);
}
}
showLoading = () => {
this.setState({
showLoading:true,
},()=>{
setTimeout(() => {
this.setState({
showLoading:false,
})
}, 500);
})
}
componentDidMount() {
this.getInitialData();
}
componentWillReceiveProps(){
this.getDownloadData()
}
render() {
const { t } = this.props;
const { dataList,btnActive } = this.state;
// console.log(this.props.i18n.language);
// console.log(this.props.i18n.languages[1]);
return (
<div className="container-fluid">
<div className="row">
<div className="col-md-12">
<div className="card card-exchange">
<div className="header text-center">
<h4 className="title">{t('app.exchange_report')}</h4>
</div>
<div className="filter-section">
<div className="datepicker-input-search-section">
<span className="datepicker-search-label">{t('app.data_date_range')} :</span>
<span className="datepicker-search-from-to">{t('app.from')}</span>
<DatePicker
className="date-search-input"
dateFormat="yyyy-MM-dd"
selected={this.state.picker_startDate}
onChange={this.handleStartChange}
value={this.state.picker_startDate===''?this.state.startDate:this.state.picker_startDate}
maxDate={new Date(this.state.picker_endDate===''?this.state.endDate:this.state.picker_endDate)}
/>
<span className="datepicker-search-from-to">{t('app.to')}</span>
<DatePicker
className="date-search-input"
dateFormat="yyyy-MM-dd"
selected={this.state.picker_endDate}
onChange={this.handleEndChange}
value={this.state.picker_endDate===''?this.state.endDate:this.state.picker_endDate}
minDate={new Date(this.state.picker_startDate===''?this.state.startDate:this.state.picker_startDate)}
/>
</div>
<div className="date-btn-section">
<button onClick={this.getToday} name="today"
className={`date-btn ${btnActive==="today"?'date-btn-active':''}`}>
{t('app.today')}
</button>
<button onClick={this.getYesterday} name="yesterday"
className={`date-btn ${btnActive==="yesterday"?'date-btn-active':''}`}>
{t('app.yesterday')}
</button>
<button onClick={this.getThisWeek} name="thisWeek"
className={`date-btn ${btnActive==="thisWeek"?'date-btn-active':''}`}>
{t('app.thisWeek')}
</button>
<button onClick={this.getLastWeek} name="lastWeek"
className={`date-btn ${btnActive==="lastWeek"?'date-btn-active':''}`}>
{t('app.lastWeek')}
</button>
<button onClick={this.getThisMonth} name="thisMonth"
className={`date-btn ${btnActive==="thisMonth"?'date-btn-active':''}`}>
{t('app.thisMonth')}
</button>
<button onClick={this.getLastMonth} name="lastMonth"
className={`date-btn ${btnActive==="lastMonth"?'date-btn-active':''}`}>
{t('app.lastMonth')}
</button>
<CSVLink className="download-btn" data={this.state.downloadData} filename={"Exchange_Report.csv"}>
<IoMdDownload/>
{t('app.download')}
</CSVLink>
</div>
</div>
<div className="content table-responsive table-full-width">
<div className="table-head-exchange-report">
<span className="title-currency">{t('app.currency_type')}</span>
<span className="title-spacing">/</span>
<span className="title-amount">{t('app.amount')}</span>
</div>
{this.state.showLoading?
<table className="table table-exchange text-center m-tb-30">
<ClipLoader
sizeUnit={"px"}
size={40}
color={'#999'}
loading={this.state.loading}
/>
</table>
:
<table className="table table-exchange">
{dataList===undefined
|| !dataList instanceof Array
|| dataList.length === 0?
<td className="table-no-data" colSpan="12">
{t('app.no_data')}
</td>
:
<tbody className="table-body-exchange-report">
{dataList.map((item, index) => (
<ExchangeReportListTitle
key={index}
{...item}
startDate={this.state.startDate}
endDate={this.state.endDate}
refreshData={this.getInitialData.bind(this,1)}
prop_startDate ={this.state.startDate}
prop_endDate ={this.state.endDate}
/>
))}
</tbody>
}
</table>
}
</div>
{this.state.total_page > 0 ?
<div className="page-section">
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={20}
totalItemsCount={this.state.total_page*20}
pageRangeDisplayed={3}
onChange={e=>this.handlePageChange(e)}
/>
</div>
:''}
</div>
</div>
</div>
</div>
);
}
} |
JavaScript | class Planet extends React.Component {
constructor() {
super();
this.state = {items: []}
}
componentDidMount() {
new Promise((resolve, reject) => {
getPlanets('https://swapi.dev/api/planets', [], resolve, reject)
})
.then((data) => data
.filter((resident) => isNaN(parseInt(resident.diameter)))
.concat(data.filter((resident) => !isNaN(parseInt(resident.diameter)))
.sort((a, b) => a.diameter - b.diameter)))
.then(response => this.setState({items: response, loading: false}))
.catch((err) => console.log('err:', err));
}
render(){
let items = this.state.items;
return (
<Grid>
{items.filter(item=>item.residents.length > 0).map(item => {
return (
<div className="container" key={item.name}>
<GridImage src={planetImages[item.name]}/>
<PlanetName>{item.name}</PlanetName>
<Diameter>Diameter : {item.diameter}</Diameter>
<Residents id={item.url} residentCount={item.residents.length} residents={item.residents}/>
</div>
)
}
)}</Grid>
);
}
} |
JavaScript | class MultipleChoiceGame extends React.Component {
constructor(props) {
super(props);
this.timer = 0;
this.state = {
value: undefined,
streakMCG: 0,
bonus: 1.0,
internalStartedAt: new Date().getTime
}
this.handleSubmit = this.handleSubmit.bind(this)
window.onunload = function () { window.location.href = '/' }
}
/**
* Extra care is taken here to ensure that the quiz images are refreshed only when the questionnaire is transiting from one question to next.
* Should the component mount freely (without the confusing if-else-logic), the result would be that each time the window is resized in order
* to switch the game ui layout between horizontal/vertical, the question and the timer would be reset. This would pretty much amount to cheating,
* as you could just keep resizing the window until you get a question you know for certain.
*
* There would absolutely be a 'better' way to circumvent this problem, but that would possibly require major refactoring with the way a
* multiplechoice/imagemultiplechoice games are initialized and the subsequent questions served. This is an ugly hack, but hopefully it
* works reasonably well...
*
*/
componentDidMount() {
if (this.props.game.needToChangeQuestion) {
this.props.setImagesToMultipleChoiceGame(this.props.game.images, this.props.game.answers, this.props.game.gameDifficulty)
this.props.startGameClock()
this.props.setNeedToChangeQuestionFalse()
}
setInterval(() => {
this.setState(() => {
return { unseen: "does not display" }
});
}, 1000)
}
componentDidUpdate(prevProps) {
if (this.props.game.endCounter !== prevProps.game.endCounter) {
this.props.setImagesToMultipleChoiceGame(this.props.game.images, this.props.game.answers, this.props.game.gameDifficulty)
this.props.startGameClock()
this.props.setNeedToChangeQuestionFalse()
}
}
/**
* As the player submits the answer, the points will be calculated, gameplay stats will be stored and player message will be generated.
* @param {*} event
*/
handleSubmit(event) {
this.props.stopGameClock()
this.setState({ value: event.target.value })
const correctness = this.checkCorrectness(event.target.value)
this.props.setAnswerSound(correctness)
let current = new Date().getTime()
let started = this.props.game.startedAt
if (started < 1 || isNaN(started) || started === undefined) {
started = this.state.internalStartedAt
}
//let points = (Math.round((this.checkCorrectness(event.target.value) * Math.max(10, this.props.game.currentImage.bone.nameLatin.length)) * ((300 + Math.max(0, (300 - this.state.seconds))) / 600))) / 20
let points = (Math.round((correctness * Math.min(10, this.props.game.currentImage.bone.nameLatin.length)) * ((30 + Math.max(0, (30 - ((current - started) / 1000)) / 60))))) / 80
if (this.checkCorrectness(event.target.value) > 99) {
points = points * 10
}
points = Math.round(points / 20) * 20
if (this.checkCorrectness(event.target.value) < 70) {
points = 0
}
let streakEmoji = require('node-emoji')
streakEmoji = emoji.get('yellow_heart')
let streakNote = ''
let currentStreak = this.state.streakMCG
let currentBonus = this.state.bonus
let streakStyle = 'correct'
if (correctness === 100) {
this.setState({ streakMCG: currentStreak + 1, bonus: currentBonus + 0.5 })
streakNote = currentBonus + 'x!'
} else {
points = 0
streakStyle = 'incorrect'
streakEmoji = require('node-emoji')
streakEmoji = streakEmoji.get('poop')
streakNote = ''
this.setState({ streakMCG: 0, bonus: 1.0 })
}
let scoreFlashRowtext = '' + streakNote + '' + streakEmoji + '' + points + ' PTS!!!' + streakEmoji
this.props.setScoreFlash(points, streakNote, streakEmoji, scoreFlashRowtext, streakStyle, 3, true)
setTimeout(() => {
this.props.setAnswer(this.props.game.currentImage, this.checkCorrectness(this.state.value), this.state.value, this.props.game.currentImage.animal.name, current - started, points)
this.setState({ value: undefined })
}, 3000)
}
/**
* This method returns 100 if the answer is correct and 0 if the answer is incorrect.
*/
checkCorrectness(answer) {
if (this.props.game.currentImage.bone.nameLatin.toLowerCase() === answer.toLowerCase()) {
return 100
} else {
return 0
}
}
/**
* This method generates the buttons to be displayed. If the answer is correct, the selected button is green.
* If wrongly answered, the selected button is red and the correct answer is green.
*/
style(choice) {
if (choice.correct && choice.nameLatin === this.state.value) {
return 'success'
} else if (choice.correct === false && choice.nameLatin === this.state.value) {
return 'danger'
}
if (choice.correct === true && undefined !== this.state.value && choice.nameLatin !== this.state.value) {
return 'success'
}
return 'info'
}
render() {
const imageWidth = () => {
const windowWidth = Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
)
if (windowWidth > 400) {
return 600
}
return windowWidth - 40
}
const debug = () => {
if (process.env.NODE_ENV === 'development') {
return (
<p>Oikea vastaus: {this.props.game.currentImage.bone.nameLatin}</p>
)
}
return null
}
const houseEmoji = emoji.get('house')
return (
<div className="bottom">
<div className="row" id="image-holder">
<div className="intro">
<CloudinaryContext cloudName="luupeli">
<div className="height-restricted">
<Image publicId={this.props.game.currentImage.url} style={{ borderRadius: 10 }}>
<Transformation width={imageWidth()} />
</Image>
</div>
</CloudinaryContext>
</div>
</div>
<div>
{this.props.game.wrongAnswerOptions.map(choice => <Button bsStyle={this.style(choice)} disabled={undefined !== this.state.value} value={choice.nameLatin} onClick={this.handleSubmit}>{choice.nameLatin}</Button>)}
{debug()}
</div>
<div className="homeicon">
<Link to='/'>
<p>{houseEmoji}</p><p>Lopeta</p>
</Link>
</div>
</div>
)
}
} |
JavaScript | class Register extends Component {
constructor(props) {
super(props);
let view = VIEWS.LOADING;
if (props.keyData) {
view = VIEWS.READY;
} else if (props.errors.length) {
view = VIEWS.ERROR;
}
this.state = {
view,
registrationData: null,
};
this.handleBack = this.handleBack.bind(this);
this.handleNext = this.handleNext.bind(this);
this.handleStartRegistration = this.handleStartRegistration.bind(this);
}
/**
* Monitor for the introduction of keyData to transition into READY state if it isn't present
* during initial render.
*/
componentDidUpdate() {
const { keyData } = this.props;
const { view } = this.state;
if (view === VIEWS.LOADING && keyData) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({ view: VIEWS.READY });
}
}
/**
* Send the user back to the "select method" UI
*/
handleBack() {
this.props.onBack();
}
/**
* Submit the registration and take the user to the next screen when processing is complete
*/
handleNext() {
const { registrationData } = this.state;
// Something went wrong here...
if (registrationData === null) {
this.setState({ view: VIEWS.FAILURE });
return;
}
this.props.onCompleteRegistration(registrationData);
}
/**
* Trigger the WebAuthn registration handler, which will present a prompt in some browsers.
*/
handleStartRegistration() {
this.setState({ view: VIEWS.PROMPTING });
performRegistration(this.props.keyData)
.then(registrationData => this.setState({ view: VIEWS.SUCCESS, registrationData }))
.catch(() => this.setState({ view: VIEWS.FAILURE }));
}
/**
* Render instructions for registering with this method
*
* @return {HTMLElement}
*/
renderDescription() {
const { ss: { i18n } } = window;
const { method: { supportLink, supportText } } = this.props;
const registerKeyT = i18n._t(
'MFAWebAuthnRegister.REGISTER',
fallbacks['MFAWebAuthnRegister.REGISTER']
);
// As this part of the message requires formatting, we render it using dangerouslySetInnerHTML
const instructions = i18n.inject(
i18n._t('MFAWebAuthnRegister.INSTRUCTION', fallbacks['MFAWebAuthnRegister.INSTRUCTION']),
{ button: `<strong>${registerKeyT}</strong>` }
);
return (
<div className="mfa-registration-container__description">
<p>
{i18n._t('MFAWebAuthnRegister.DESCRIPTION', fallbacks['MFAWebAuthnRegister.DESCRIPTION'])}
{supportLink &&
<a
href={supportLink}
target="_blank"
rel="noopener noreferrer"
>
{supportText || i18n._t('MFAWebAuthnRegister.HELP', fallbacks['MFAWebAuthnRegister.HELP'])}
</a>
}
</p>
{/* eslint-disable-next-line react/no-danger */}
<p dangerouslySetInnerHTML={{ __html: instructions }} />
</div>
);
}
/**
* Render the status of the registration, with relevant iconography
*
* @returns {HTMLElement}
*/
renderStatus() {
const { errors } = this.props;
const { ss: { i18n } } = window;
switch (this.state.view) {
case VIEWS.READY:
return (<div className="mfa-registration-container__status status-message--empty" />);
case VIEWS.PROMPTING:
case VIEWS.LOADING:
default:
return (
<div className="mfa-registration-container__status status-message--loading">
<LoadingIndicator size="3em" />
<span className="status-message__description">
{i18n._t('MFAWebAuthnRegister.WAITING', fallbacks['MFAWebAuthnRegister.WAITING'])}
</span>
</div>
);
case VIEWS.SUCCESS:
return (
<div className="mfa-registration-container__status status-message--success">
<span className="status-message__icon"><CircleTick size="32px" /></span>
<span className="status-message__description">
{i18n._t('MFAWebAuthnRegister.SUCCESS', fallbacks['MFAWebAuthnRegister.SUCCESS'])}
</span>
</div>
);
case VIEWS.FAILURE:
return (
<div className="mfa-registration-container__status status-message--failure">
<span className="status-message__icon"><CircleWarning size="32px" /></span>
<span className="status-message__description">
{i18n._t('MFAWebAuthnRegister.FAILURE', fallbacks['MFAWebAuthnRegister.FAILURE'])}
</span>
</div>
);
case VIEWS.ERROR:
return (
<div className="mfa-registration-container__status status-message--error">
<span className="status-message__icon"><CircleWarning size="32px" /></span>
<span className="status-message__description">
{errors.join(', ')}
</span>
</div>
);
}
}
/**
* Render the icon related to this method
*
* @returns {HTMLElement}
*/
renderThumbnail() {
return (
<div className="mfa-registration-container__thumbnail">
<ActivateToken />
</div>
);
}
/**
* Render available actions based on current state of registration flow
*
* @return {HTMLElement}
*/
renderActions() {
const { ss: { i18n } } = window;
const { view } = this.state;
let actions = [];
switch (view) {
case VIEWS.FAILURE:
actions = [
{
action: this.handleStartRegistration,
name: i18n._t('MFAWebAuthnRegister.RETRY', fallbacks['MFAWebAuthnRegister.RETRY'])
},
{
action: this.handleBack,
name: i18n._t('MFAWebAuthnRegister.BACK', fallbacks['MFAWebAuthnRegister.BACK'])
},
];
break;
case VIEWS.ERROR:
// Deliberately do not provide any actions for backend errors, a refresh is required
actions = [];
break;
case VIEWS.READY:
actions = [
{
action: this.handleStartRegistration,
name: i18n._t('MFAWebAuthnRegister.REGISTER', fallbacks['MFAWebAuthnRegister.REGISTER'])
},
{
action: this.handleBack,
name: i18n._t('MFAWebAuthnRegister.BACK', fallbacks['MFAWebAuthnRegister.BACK'])
},
];
break;
case VIEWS.PROMPTING:
actions = [
{
action: this.handleStartRegistration,
name: i18n._t(
'MFAWebAuthnRegister.REGISTERING',
fallbacks['MFAWebAuthnRegister.REGISTERING']
),
disabled: true
},
{
action: this.handleBack,
name: i18n._t('MFAWebAuthnRegister.BACK', fallbacks['MFAWebAuthnRegister.BACK']),
disabled: true
},
];
break;
case VIEWS.LOADING:
default:
actions = [
{
action: this.handleStartRegistration,
name: i18n._t(
'MFAWebAuthnRegister.REGISTERING',
fallbacks['MFAWebAuthnRegister.REGISTERING']
),
disabled: true,
},
{
action: this.handleBack,
name: i18n._t('MFAWebAuthnRegister.BACK', fallbacks['MFAWebAuthnRegister.BACK']),
},
];
break;
case VIEWS.SUCCESS:
actions = [
{
action: this.handleNext,
name: i18n._t(
'MFAWebAuthnRegister.COMPLETEREGISTRATION',
fallbacks['MFAWebAuthnRegister.COMPLETEREGISTRATION']
),
}];
break;
}
return (
<div className="mfa-registration-container__actions mfa-action-list">
{
actions.map((action, i) => {
const firstAction = i === 0;
const className = classNames('btn', 'mfa-action-list__item', {
'btn-primary': firstAction,
'btn-secondary': !firstAction,
});
return (
<button
key={action.name}
className={className}
disabled={action.disabled || false}
onClick={action.action}
type="button"
>
{action.name}
</button>
);
})
}
</div>
);
}
render() {
return (
<div className="mfa-registration-container mfa-registration-container--web-authn">
{this.renderDescription()}
{this.renderStatus()}
{this.renderThumbnail()}
{this.renderActions()}
</div>
);
}
} |
JavaScript | class Customer_Retrieve extends Retrieve_Update_Delete {
_display_name = "Customer_Retrieve";
_last_verified_square_api_version = "2021-12-15";
_help = this.display_name + ": " + man;
constructor(id) {
super(id);
this._method = "GET";
this._delivery;
}
} |
JavaScript | class Feeds {
/**
* Constructs a new <code>Feeds</code>.
* @alias module:model/Feeds
*/
constructor() {
Feeds.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>Feeds</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/Feeds} obj Optional instance to populate.
* @return {module:model/Feeds} The populated <code>Feeds</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new Feeds();
if (data.hasOwnProperty('_links')) {
obj['_links'] = FeedsLinks.constructFromObject(data['_links']);
}
if (data.hasOwnProperty('current_user_actor_url')) {
obj['current_user_actor_url'] = ApiClient.convertToType(data['current_user_actor_url'], 'String');
}
if (data.hasOwnProperty('current_user_organization_url')) {
obj['current_user_organization_url'] = ApiClient.convertToType(data['current_user_organization_url'], 'String');
}
if (data.hasOwnProperty('current_user_public')) {
obj['current_user_public'] = ApiClient.convertToType(data['current_user_public'], 'String');
}
if (data.hasOwnProperty('current_user_url')) {
obj['current_user_url'] = ApiClient.convertToType(data['current_user_url'], 'String');
}
if (data.hasOwnProperty('timeline_url')) {
obj['timeline_url'] = ApiClient.convertToType(data['timeline_url'], 'String');
}
if (data.hasOwnProperty('user_url')) {
obj['user_url'] = ApiClient.convertToType(data['user_url'], 'String');
}
}
return obj;
}
} |
JavaScript | class SplTokenCoder {
constructor(idl) {
this.instruction = new instruction_js_1.SplTokenInstructionCoder(idl);
this.accounts = new accounts_js_1.SplTokenAccountsCoder(idl);
this.events = new events_js_1.SplTokenEventsCoder(idl);
this.state = new state_js_1.SplTokenStateCoder(idl);
}
} |
JavaScript | class Tremolo extends StereoEffect {
constructor() {
super(optionsFromArguments(Tremolo.getDefaults(), arguments, ["frequency", "depth"]));
this.name = "Tremolo";
const options = optionsFromArguments(Tremolo.getDefaults(), arguments, ["frequency", "depth"]);
this._lfoL = new LFO({
context: this.context,
type: options.type,
min: 1,
max: 0,
});
this._lfoR = new LFO({
context: this.context,
type: options.type,
min: 1,
max: 0,
});
this._amplitudeL = new Gain({ context: this.context });
this._amplitudeR = new Gain({ context: this.context });
this.frequency = new Signal({
context: this.context,
value: options.frequency,
units: "frequency",
});
this.depth = new Signal({
context: this.context,
value: options.depth,
units: "normalRange",
});
readOnly(this, ["frequency", "depth"]);
this.connectEffectLeft(this._amplitudeL);
this.connectEffectRight(this._amplitudeR);
this._lfoL.connect(this._amplitudeL.gain);
this._lfoR.connect(this._amplitudeR.gain);
this.frequency.fan(this._lfoL.frequency, this._lfoR.frequency);
this.depth.fan(this._lfoR.amplitude, this._lfoL.amplitude);
this.spread = options.spread;
}
static getDefaults() {
return Object.assign(StereoEffect.getDefaults(), {
frequency: 10,
type: "sine",
depth: 0.5,
spread: 180,
});
}
/**
* Start the tremolo.
*/
start(time) {
this._lfoL.start(time);
this._lfoR.start(time);
return this;
}
/**
* Stop the tremolo.
*/
stop(time) {
this._lfoL.stop(time);
this._lfoR.stop(time);
return this;
}
/**
* Sync the effect to the transport.
*/
sync() {
this._lfoL.sync();
this._lfoR.sync();
this.context.transport.syncSignal(this.frequency);
return this;
}
/**
* Unsync the filter from the transport
*/
unsync() {
this._lfoL.unsync();
this._lfoR.unsync();
this.context.transport.unsyncSignal(this.frequency);
return this;
}
/**
* The oscillator type.
*/
get type() {
return this._lfoL.type;
}
set type(type) {
this._lfoL.type = type;
this._lfoR.type = type;
}
/**
* Amount of stereo spread. When set to 0, both LFO's will be panned centrally.
* When set to 180, LFO's will be panned hard left and right respectively.
*/
get spread() {
return this._lfoR.phase - this._lfoL.phase; // 180
}
set spread(spread) {
this._lfoL.phase = 90 - (spread / 2);
this._lfoR.phase = (spread / 2) + 90;
}
dispose() {
super.dispose();
this._lfoL.dispose();
this._lfoR.dispose();
this._amplitudeL.dispose();
this._amplitudeR.dispose();
this.frequency.dispose();
this.depth.dispose();
return this;
}
} |
JavaScript | class N3hRealMode extends N3hMode {
async init (workDir, rawConfigData) {
await super.init(workDir, rawConfigData)
this._requestBook = new Map()
// "Map" of dnaDhts
this._dhtPerDna = {}
// machineId -> (dnaId -> [agentId])
this._peerTracks = {}
await Promise.all([
this._initP2p()
])
this.$pushDestructor(async () => {
if (this._p2p) {
await this._p2p.destroy()
}
this._p2p = null
})
// make sure this is output despite our log settings
console.log('#P2P-BINDING#:' + this._p2p.getAdvertise())
console.log('#P2P-READY#')
}
// -- private -- //
/**
* Convert a peerAddress into log friendly format
*/
nick (peerAddress) {
return '(' + peerAddress.substring(2, 6) + ')'
}
/**
* Convert my peerAddress into log friendly format
*/
me () {
return this.nick(this._p2p.getId())
}
/**
* remove 'hc://'
*/
toMachineId (peerTransport) {
return peerTransport.substring(5)
}
/**
* Add 'hc://'
*/
toDnaPeerTransport (mId) {
return 'hc://' + mId
}
/**
* @private
*/
async _initP2p () {
// Create p2p config
const p2pConf = {
dht: {},
connection: {
// TODO - allow some kind of environment var?? for setting passphrase
passphrase: 'hello',
rsaBits: this._config.webproxy.connection.rsaBits,
bind: this._config.webproxy.connection.bind
},
workDir: this._workDir
}
if (this._config.webproxy.wssRelayPeers) {
p2pConf.wssRelayPeers = this._config.webproxy.wssRelayPeers
} else {
p2pConf.wssAdvertise = this._config.webproxy.wssAdvertise
}
// Create P2p
this._p2p = (await new P2pBackendHackmodePeer(p2pConf)).interfaceP2p
this._p2p.on('event', evt => this._handleP2pEvent(evt))
// Done
log.i(this.me() + 'p2p bound', this._p2p.getAdvertise())
}
/**
* @private
*/
async _handleIpcJson (data, ipcSenderId) {
log.t(this.me() + ' Received from Core:', data)
let mId
let bucketId
let result
let ipcMsg
switch (data.method) {
case 'failureResult':
// Note: data is a FailureResultData
// Check if its a response to our own request
bucketId = this._checkRequest(data._id)
if (bucketId !== '') {
return
}
// if not relay to receipient if possible
mId = this._getPeerAddressOrFail(data.dnaAddress, data.toAgentId)
if (mId === null) {
return
}
this._p2pSend(mId, {
type: 'failureResult',
dnaAddress: data.dnaAddress,
_id: data._id,
toAgentId: data.toAgentId,
errorInfo: data.errorInfo
})
return
case 'requestState':
this._ipcSend('json', {
method: 'state',
state: 'ready',
id: this._p2p.getId(),
bindings: [this._p2p.getAdvertise()]
})
return
case 'connect':
// Note: data.address must be an Advertise
// Connect to Peer
this._p2p.transportConnect(data.address).then(() => {
log.t(this.me() + ' connected', data.address)
}, (err) => {
log.e(this.me() + '.connect (' + data.address + ') failed', err.toString())
})
return
case 'trackDna':
// Note: data is a TrackDnaData
this._track(data.dnaAddress, data.agentId)
return
case 'untrackDna':
// Note: data is a TrackDnaData
this._untrack(data.dnaAddress, data.agentId)
return
case 'sendMessage':
// Note: data is a MessageData
// Sender must TrackDna
if (!this._hasTrackOrFail(data.fromAgentId, data.dnaAddress, data._id)) {
return
}
// Receiver must TrackDna
mId = this._getPeerAddressOrFail(data.dnaAddress, data.toAgentId, data.fromAgentId, data._id)
if (mId === null) {
return
}
this._p2pSend(mId, {
type: 'handleSendMessage',
_id: data._id,
dnaAddress: data.dnaAddress,
toAgentId: data.toAgentId,
fromAgentId: data.fromAgentId,
data: data.data
})
return
case 'handleSendMessageResult':
// Note: data is a MessageData
// Sender must TrackDna
if (!this._hasTrackOrFail(data.fromAgentId, data.dnaAddress, data._id)) {
return
}
// Receiver must TrackDna
mId = this._getPeerAddressOrFail(data.dnaAddress, data.toAgentId, data.fromAgentId, data._id)
if (mId === null) {
return
}
this._p2pSend(mId, {
type: 'sendMessageResult',
_id: data._id,
dnaAddress: data.dnaAddress,
toAgentId: data.toAgentId,
fromAgentId: data.fromAgentId,
data: data.data
})
return
case 'publishEntry':
// Note: data is a EntryData
if (!this._hasTrackOrFail(data.providerAgentId, data.dnaAddress, data._id)) {
return
}
// Bookkeep
log.t(this.me() + ' publish Entry', data)
this._bookkeepAddress(this._publishedEntryBook, data.dnaAddress, data.address)
// publish
this._getMemRef(data.dnaAddress).insert({
type: 'dhtEntry',
providerAgentId: data.providerAgentId,
address: data.address,
content: data.content
})
return
case 'publishMeta':
// Note: data is a DhtMetaData
if (!this._hasTrackOrFail(data.providerAgentId, data.dnaAddress, data._id)) {
return
}
// Bookkeep each metaId
for (const metaContent of data.contentList) {
let metaId = this._metaIdFromTuple(data.entryAddress, data.attribute, metaContent)
log.t(this.me() + ' publish Meta', metaId)
this._bookkeepAddress(this._publishedMetaBook, data.dnaAddress, metaId)
}
// publish
log.t('publishMeta', data.contentList)
this._getMemRef(data.dnaAddress).insertMeta({
type: 'dhtMeta',
providerAgentId: data.providerAgentId,
entryAddress: data.entryAddress,
attribute: data.attribute,
contentList: data.contentList
})
return
case 'fetchEntry':
// Note: data is a FetchEntryData
if (!this._hasTrackOrFail(data.requesterAgentId, data.dnaAddress, data._id)) {
return
}
// Ask my data DHT
// TODO: might need to do dht.post(DhtEvent.fetchData) instead for non-fullsync DHT
result = await this._getDhtRef(data.dnaAddress).fetchDataLocal(data.address)
// log.d(this.me() + ' fetchDataLocal', result)
if (result) {
result = JSON.parse(Buffer.from(result, 'base64').toString('utf8'))
log.d(this.me() + ' fetchDataLocal', result)
ipcMsg = {
method: 'fetchEntryResult',
_id: data._id,
dnaAddress: data.dnaAddress,
requesterAgentId: data.requesterAgentId,
providerAgentId: result.entry.providerAgentId,
address: data.address,
content: result.entry.content
}
} else {
ipcMsg = {
method: 'failureResult',
_id: data._id,
dnaAddress: data.dnaAddress,
toAgentId: data.requesterAgentId,
errorInfo: 'Entry not found:' + data.address
}
}
this._ipcSend('json', ipcMsg)
return
case 'handleFetchEntryResult':
// Note: data is a FetchEntryResultData
// Local node should be tracking DNA
if (!this._hasTrackOrFail(data.providerAgentId, data.dnaAddress, data._id)) {
return
}
// if this message is a response from our own request, do a publish
bucketId = this._checkRequest(data._id)
if (bucketId !== '') {
const isPublish = data.providerAgentId === '__publish'
this._bookkeepAddress(isPublish ? this._publishedEntryBook : this._storedEntryBook, data.dnaAddress, data.address)
log.t(this.me() + ' handleFetchEntryResult insert:', data, isPublish)
this._getMemRef(data.dnaAddress).insert({
type: 'dhtEntry',
providerAgentId: data.providerAgentId,
address: data.address,
content: data.content
})
return
}
// Requester must TrackDna
mId = this._getPeerAddressOrFail(data.dnaAddress, data.requesterAgentId, data.providerAgentId, data._id)
if (mId === null) {
return
}
this._p2pSend(mId, {
type: 'fetchEntryResult',
_id: data._id,
dnaAddress: data.dnaAddress,
requesterAgentId: data.requesterAgentId,
providerAgentId: data.providerAgentId,
agentId: data.agentId,
address: data.address,
content: data.content
})
return
case 'fetchMeta':
// Note: data is a FetchMetaData
if (!this._hasTrackOrFail(data.requesterAgentId, data.dnaAddress, data._id)) {
return
}
// Ask my data DGT
// TODO: might need to do dht.post(DhtEvent.fetchData) instead for non-fullsync DHT
result = await this._getDhtRef(data.dnaAddress).fetchDataLocal(data.entryAddress)
if (result) {
result = JSON.parse(Buffer.from(result, 'base64').toString('utf8'))
log.d(this.me() + ' fetchMeta.fetchDataLocal', result)
// Search for meta of requested attribute
let contentList = []
for (const meta of result.meta) {
if (meta.attribute === data.attribute) {
contentList.push(meta.contentList[0])
}
}
// Determine providerAgentId ; Entry might not exist
let fromAgentId = result.dataFetchProviderAgentId
if (!(Object.entries(result.entry).length === 0 && result.entry.constructor === Object)) {
fromAgentId = result.entry.providerAgentId
}
// Create ipc message
ipcMsg = {
method: 'fetchMetaResult',
_id: data._id,
dnaAddress: data.dnaAddress,
requesterAgentId: data.requesterAgentId,
providerAgentId: fromAgentId,
entryAddress: data.entryAddress,
attribute: data.attribute,
contentList: contentList
}
} else {
ipcMsg = {
method: 'failureResult',
_id: data._id,
dnaAddress: data.dnaAddress,
toAgentId: data.requesterAgentId,
errorInfo: 'Entry not found during fetchMeta for:' + data.entryAddress
}
}
this._ipcSend('json', ipcMsg)
return
case 'handleFetchMetaResult':
// Note: data is a FetchMetaResultData
// Local node should be tracking DNA
if (!this._hasTrackOrFail(data.providerAgentId, data.dnaAddress, data._id)) {
return
}
// if its from our own request, do a publish for each new/unknown meta content
bucketId = this._checkRequest(data._id)
if (bucketId !== '') {
const isPublish = data.providerAgentId === '__publish'
// get already known list
let knownMetaList = []
if (isPublish) {
if (bucketId in this._publishedMetaBook) {
knownMetaList = this._publishedMetaBook[bucketId]
}
} else {
if (bucketId in this._storedMetaBook) {
knownMetaList = this._storedMetaBook[bucketId]
}
}
for (const metaContent of data.contentList) {
let metaId = this._metaIdFromTuple(data.entryAddress, data.attribute, metaContent)
if (knownMetaList.includes(metaId)) {
continue
}
this._bookkeepAddress(isPublish ? this._publishedMetaBook : this._storedMetaBook, data.dnaAddress, metaId)
log.t(this.me() + ' handleFetchMetaResult insert:', metaContent, data.providerAgentId, metaId, isPublish)
this._getMemRef(data.dnaAddress).insertMeta({
type: 'dhtMeta',
providerAgentId: data.providerAgentId,
entryAddress: data.entryAddress,
attribute: data.attribute,
contentList: [metaContent]
})
}
return
}
// Requester must TrackDna
mId = this._getPeerAddressOrFail(data.dnaAddress, data.requesterAgentId, data.providerAgentId, data._id)
if (mId === null) {
return
}
this._p2pSend(mId, {
type: 'fetchMetaResult',
_id: data._id,
dnaAddress: data.dnaAddress,
requesterAgentId: data.requesterAgentId,
providerAgentId: data.providerAgentId,
agentId: data.agentId,
entryAddress: data.entryAddress,
attribute: data.attribute,
contentList: data.contentList
})
return
case 'handleGetPublishingEntryListResult':
// Note: data is EntryListData
// Mark my request as resolved and get bucketId from request
bucketId = this._checkRequest(data._id)
if (bucketId === '') {
return
}
// get already known publishing list
let knownPublishingList = []
if (bucketId in this._publishedEntryBook) {
knownPublishingList = this._publishedEntryBook[bucketId]
}
// Update my book-keeping on what this agent has.
// and do a getEntry for every new entry
for (const entryAddress of data.entryAddressList) {
if (knownPublishingList.includes(entryAddress)) {
log.t('Entry is known ', entryAddress)
continue
}
let fetchEntry = {
method: 'handleFetchEntry',
dnaAddress: data.dnaAddress,
_id: this._createRequestWithBucket(bucketId),
requesterAgentId: '__publish',
address: entryAddress
}
// log.t(this.me() + 'Sending IPC:', fetchEntry)
this._ipcSend('json', fetchEntry)
}
return
case 'handleGetHoldingEntryListResult':
// Note: data is EntryListData
// Mark my request as resolved and get bucketId from request
bucketId = this._checkRequest(data._id)
if (bucketId === '') {
return
}
// get already known publishing list
let knownHoldingList = []
if (bucketId in this._storedEntryBook) {
knownHoldingList = this._storedEntryBook[bucketId]
}
// Update my book-keeping on what this agent has.
// and do a getEntry for every new entry
for (const entryAddress of data.entryAddressList) {
if (knownHoldingList.includes(entryAddress)) {
continue
}
let fetchEntry = {
method: 'handleFetchEntry',
dnaAddress: data.dnaAddress,
_id: this._createRequestWithBucket(bucketId),
requesterAgentId: '__hold',
address: entryAddress
}
// log.t(this.me() + 'Sending IPC:', fetchEntry)
this._ipcSend('json', fetchEntry)
}
return
case 'handleGetPublishingMetaListResult':
// Note: data is MetaListData
// Mark my request as resolved and get bucketId from request
bucketId = this._checkRequest(data._id)
if (bucketId === '') {
return
}
// get already known publishing list
let knownPublishingMetaList = []
if (bucketId in this._publishedMetaBook) {
knownPublishingMetaList = this._publishedMetaBook[bucketId]
}
// Update my book-keeping on what this agent has.
// and do a getEntry for every new entry
let requestedMetaKey = []
for (const metaTuple of data.metaList) {
let metaId = this._metaIdFromTuple(metaTuple[0], metaTuple[1], metaTuple[2])
if (knownPublishingMetaList.includes(metaId)) {
continue
}
log.t(this.me() + ' handleGetPublishingMetaListResult, unknown metaId = ', metaId)
// dont send same request twice
const metaKey = '' + metaTuple[0] + '+' + metaTuple[1]
if (requestedMetaKey.includes(metaKey)) {
continue
}
requestedMetaKey.push(metaKey)
let fetchMeta = {
method: 'handleFetchMeta',
dnaAddress: data.dnaAddress,
_id: this._createRequestWithBucket(bucketId),
requesterAgentId: '__publish',
entryAddress: metaTuple[0],
attribute: metaTuple[1]
}
// log.t(this.me() + 'Sending IPC:', fetchMeta)
this._ipcSend('json', fetchMeta)
}
return
case 'handleGetHoldingMetaListResult':
// Note: data is MetaListData
// Mark my request as resolved and get bucketId from request
bucketId = this._checkRequest(data._id)
if (bucketId === '') {
return
}
// get already known publishing list
let knownHoldingMetaList = []
if (bucketId in this._storedMetaBook) {
knownHoldingMetaList = this._storedMetaBook[bucketId]
}
// Update my book-keeping on what this agent has.
// and do a getEntry for every new entry
// for (let entryAddress in data.metaList) {
for (const metaTuple of data.metaList) {
let metaId = this._metaIdFromTuple(metaTuple[0], metaTuple[1], metaTuple[2])
if (knownHoldingMetaList.includes(metaId)) {
continue
}
let fetchMeta = {
method: 'handleFetchMeta',
dnaAddress: data.dnaAddress,
_id: this._createRequestWithBucket(bucketId),
requesterAgentId: '__hold',
entryAddress: metaTuple[0],
attribute: metaTuple[1]
}
// log.t(this.me() + ' Sending to Core:', fetchMeta)
this._ipcSend('json', fetchMeta)
}
return
}
throw new Error('unexpected input ' + JSON.stringify(data))
}
/**
* @private
*/
_checkRequest (requestId) {
if (!this._requestBook.has(requestId)) {
return ''
}
let bucketId = this._requestBook.get(requestId)
this._requestBook.delete(requestId)
return bucketId
}
/**
* a dnaDht (or myself) is notifying me of a DHT event
* @private
*/
async _handleDhtEvent (e, dnaAddress) {
// log.t(this.me() + '._handleDhtEvent(' + e.type + ') - ' + dnaAddress)
// Handle event by type
switch (e.type) {
// issued by dht._handlePeerMap() (i.e. when receiving peer data from gossip)
// or when receiving 'tracking gossip' (gossipNewTrack, gossipAllTracks)
case 'peerHoldRequest':
const agentId = e.peerAddress
const machineId = this.toMachineId(e.peerTransport)
log.t(this.me() + ' received PEER-AGENT', agentId, this.nick(machineId))
// Bookkeep machineId -> (dnaId -> agentId)
let peerTracks = this._getPeerRef(machineId)
let agentList = [agentId]
if (peerTracks.has(dnaAddress)) {
agentList.concat(peerTracks.get(dnaAddress))
}
peerTracks.set(dnaAddress, agentList)
// Store peer data in dnaDht
if (!(dnaAddress in this._dhtPerDna)) {
log.w('Received peerHoldRequest for untracked DNA', dnaAddress)
break
}
this._getDhtRef(dnaAddress).post(e)
// Notify my Core of connected Agent
log.t(this.me() + ' PEER-AGENT INDEXED', this.nick(machineId), agentId)
this._ipcSend('json', {
method: 'peerConnected',
agentId
})
break
case 'gossipTo':
// issued by dht._gossip() or dht._onRemoteGossipHandle()
// log.t(this.me() + ' gossipTo:', e)
for (const peerAddress of e.peerList) {
// Unless its 'reply/response' gossip,
// peerAddress is actually an agentId, so get agent's real peerAddress from dht peer data
let mId = peerAddress
const peer = this._getDhtRef(dnaAddress).getPeerLocal(peerAddress)
if (peer) {
mId = this.toMachineId(peer.peerTransport)
}
this._p2pSend(mId, {
type: 'dnaDhtGossip', dnaAddress, bundle: e.bundle
})
}
break
case 'dataHoldRequest':
// issued by dht._handleDataMap() which got triggered by a 'fetchAddressListResp'
// data should be an entryWithMeta
// log.t(this.me() + ' dataHoldRequest: ', e.data)
const data = JSON.parse(Buffer.from(e.data, 'base64'))
// Check if we are receiving only meta
const hasEntry = !(Object.entries(data.entry).length === 0 && data.entry.constructor === Object)
log.t(this.me() + ' dataHoldRequest:', hasEntry, data)
// Store data in Mem & data DHT (done by indexers
let fromAgentId = data.dataFetchProviderAgentId
if (hasEntry) {
fromAgentId = data.entry.providerAgentId
this._getMemRef(data.dnaAddress).insert(data.entry)
}
for (const metaItem of data.meta) {
this._getMemRef(data.dnaAddress).insertMeta({
type: 'dhtMeta',
providerAgentId: fromAgentId,
entryAddress: data.entryAddress,
attribute: metaItem.attribute,
contentList: metaItem.contentList
})
}
break
case 'dataFetch':
// Issued by dht._fetchDataLocal()
// My dht asked me for all the data of an entry, give it a response
log.t(this.me() + ' dataFetch', e)
// Get entryAddress
const entryAddress = e.dataAddress
// log.e(this.me() + ' entryAddress', entryAddress)
// Check if DNA has that entryAddress
const mem = this._getMemRef(dnaAddress)
// If data not found, respond with 'null'
if (!mem.has(entryAddress)) {
log.e(this.me() + ' doest not have entry ' + entryAddress)
const nullB64 = Buffer.from(JSON.stringify(null), 'utf8').toString('base64')
this._getDhtRef(dnaAddress).post(Dht.DhtEvent.dataFetchResponse(e.msgId, nullB64))
break
}
// Create DHT data item
let dhtData = mem.get(entryAddress)
dhtData.entryAddress = entryAddress
dhtData.dnaAddress = dnaAddress
dhtData.dataFetchProviderAgentId = null
// Pick first agent who tracks this DNA as the provider
// WARNING non-deterministic if many agents track the same DNA
for (const [agentId, dnas] of this._ipcDnaByAgent) {
if (dnas.has(dnaAddress)) {
dhtData.dataFetchProviderAgentId = agentId
break
}
}
if (!dhtData.dataFetchProviderAgentId) {
log.e(this.me() + ' AgentId not found for DNA ' + dnaAddress + ' ; during handleDhtEvent(dataFetch)')
}
log.t(this.me() + ' dataFetchResponse:', dhtData)
dhtData = Buffer.from(JSON.stringify(dhtData), 'utf8').toString('base64')
this._getDhtRef(dnaAddress).post(Dht.DhtEvent.dataFetchResponse(e.msgId, dhtData))
break
case 'peerTimedOut':
// For now, we don't care about dnaDht peers timing out because we are handling this when
// a transportDht peer times out.
log.t(this.me() + ' dnaDht peer timed-out:', e.peerAddress, dnaAddress)
break
default:
throw new Error('unhandled dht event type ' + e.type + ' ' + JSON.stringify(e))
}
}
/**
* send/publish a p2p message to a Peer
* @private
*/
async _p2pSend (peerAddress, obj) {
// log.t(this.me() + ' >>> ' + this.nick(peerAddress) + ' - ' + obj.type)
return this._p2p.publishReliable(
[peerAddress],
msgpack.encode(obj).toString('base64')
)
}
/**
* send/publish a p2p message to all know Peers
* @private
*/
async _p2pSendAll (obj) {
// log.t(this.me() + ' >>> ' + this._getPeerList() + ' - ' + obj.type)
return this._p2p.publishReliable(
this._getPeerList(),
msgpack.encode(obj).toString('base64')
)
}
/**
* _p2p is notifying me of p2p events
* @private
*/
_handleP2pEvent (evt) {
// log.t(this.me() + '._handleP2pEvent()', evt.type)
let peerTracks
switch (evt.type) {
case 'peerConnect':
log.t(this.me() + '.peerConnect:', this.nick(evt.peerAddress))
// Bookkeep known peers
peerTracks = this._getPeerRef(evt.peerAddress)
if (peerTracks.size > 0) {
log.w(this.me() + ' received peerConnect from a known peer', this.nick(evt.peerAddress), peerTracks.size)
}
// Gossip back my tracked DNA+Agents
// convert to array
let dnaByAgent = []
for (const [agentId, dnas] of this._ipcDnaByAgent) {
// log.t(this.me() + '.gossipAllTracks.' + agentId, Array.from(dnas))
for (const dnaAddress of dnas) {
let dnaAgent = []
dnaAgent.push(agentId)
dnaAgent.push(dnaAddress)
dnaByAgent.push(dnaAgent)
}
}
// log.t(this.me() + '.gossipAllTracks', this._ipcDnaByAgent)
log.t(this.me() + '.gossipAllTracks', dnaByAgent)
this._p2pSend(evt.peerAddress, {
type: 'gossipAllTracks',
dnaByAgent: dnaByAgent
})
break
case 'peerDisconnect':
log.t(this.me() + '.peerDisconnect:', this.nick(evt.peerAddress))
// For each DNA+agent this peer was part of
// tell dnaDht to drop peer data
peerTracks = this._getPeerRef(evt.peerAddress)
for (const [dnaId, agentIdList] of peerTracks) {
let dnaDht = this._getDhtRef(dnaId)
for (const agentId of agentIdList) {
log.t(this.me() + ' PEER-AGENT DISCONNECTED', this.nick(evt.peerAddress), dnaId, agentId)
// // Notify my Core of agent disconnection
// this._ipcSend('json', {
// method: 'peerDisconnected',
// agentId
// })
dnaDht.dropPeer(agentId)
}
}
// bookdrop
delete this._peerTracks[evt.peerAddress]
break
case 'handlePublish':
// Handle 'publish' message sent from some other peer's _p2pSend()
this._handleP2pPublish({
from: evt.fromPeerAddress,
data: msgpack.decode(Buffer.from(evt.data, 'base64'))
})
break
// case 'handleRequest':
default:
throw new Error('unexpected event type: ' + evt.type)
}
}
/**
* Received P2P message from other Peer
* Might send some messages back and also
* transcribe received message into a local IPC message.
* @private
*/
_handleP2pPublish (opt) {
// log.t(this.me() + ' << ' + this.nick(opt.from) + ' - ' + opt.data.type)
let peerTracks
switch (opt.data.type) {
case 'dnaDhtGossip':
// log.t(this.me() + ' bundle =', opt.data.bundle)
this._getDhtRef(opt.data.dnaAddress).post(
DhtEvent.remoteGossipBundle(opt.from, opt.data.bundle)
)
return
case 'gossipNewTrack':
// Some peer is telling us its tracking a new DNA
log.t(this.me() + ' @@@@ ' + ' new track', opt.data.agentId, opt.data.dnaAddress)
// get peer's machineId
peerTracks = this._getPeerRef(opt.from)
if (peerTracks.size === 0) {
log.w('received gossipNewTrack from unknown peer', this.nick(opt.from))
}
// Add peer to dnaDht if we also track the same DNA
// (this will store agentId -> machineId)
const peerHoldEvent = DhtEvent.peerHoldRequest(
opt.data.agentId,
this.toDnaPeerTransport(opt.from),
Buffer.from('').toString('base64'),
Date.now())
// dht.post(peerHoldEvent)
this._handleDhtEvent(peerHoldEvent, opt.data.dnaAddress)
return
case 'gossipAllTracks':
// Some peer is telling us of all the DNA it is tracking
// log.t(this.me() + ' << ' + this.nick(opt.from) + ' - gossipAllTracks', opt.data)
// Bookkeep peer's machineId
peerTracks = this._getPeerRef(opt.from)
if (peerTracks.size === 0) {
log.w(this.me() + ' received gossipAllTracks from unknown peer', this.nick(opt.from))
}
// Tell each tracked dnaDht to store peer's agentIds
for (const [agentId, dnaAddress] of opt.data.dnaByAgent) {
log.t(this.me() + ' @@@@ ' + this.me() + ' new track(s)', agentId, dnaAddress)
// Store for this dnaDht: agentId -> machineId
const peerHoldEvent = DhtEvent.peerHoldRequest(agentId, this.toDnaPeerTransport(opt.from), Buffer.from('').toString('base64'), Date.now())
this._handleDhtEvent(peerHoldEvent, dnaAddress)
}
return
case 'handleSendMessage':
log.t(this.me() + ' Received P2P handleSendMessage', opt.data)
// Send error back to sender if we untracked this DNA
if (!this._ipcHasTrack(opt.data.toAgentId, opt.data.dnaAddress)) {
log.e(this.me() + ' #### P2P hasTrack() failed for agent "' + opt.data.toAgentId + '" ; DNA = "' + opt.data.dnaAddress + '"')
const mId = this._getPeerAddressOrFail(opt.data.dnaAddress, opt.data.fromAgentId)
if (mId === null) {
return
}
this._p2pSend(mId, {
type: 'failureResult',
dnaAddress: opt.data.dnaAddress,
_id: opt.data._id,
toAgentId: opt.data.fromAgentId,
errorInfo: 'Agent "' + opt.data.toAgentId + '" is not tracking DNA' + opt.data.dnaAddress
})
return
}
// forward to Core
this._ipcSend('json', {
method: 'handleSendMessage',
_id: opt.data._id,
dnaAddress: opt.data.dnaAddress,
toAgentId: opt.data.toAgentId,
fromAgentId: opt.data.fromAgentId,
data: opt.data.data
})
return
case 'sendMessageResult':
log.t('Received P2P sendMessageResult', opt.data)
// forward to Core
this._ipcSend('json', {
method: 'sendMessageResult',
_id: opt.data._id,
dnaAddress: opt.data.dnaAddress,
toAgentId: opt.data.toAgentId,
fromAgentId: opt.data.fromAgentId,
data: opt.data.data
})
return
case 'fetchEntryResult':
// forward to Core
this._ipcSend('json', {
method: 'fetchEntryResult',
_id: opt.data._id,
dnaAddress: opt.data.dnaAddress,
requesterAgentId: opt.data.requesterAgentId,
providerAgentId: opt.data.providerAgentId,
agentId: opt.data.agentId,
address: opt.data.address,
content: opt.data.content
})
return
case 'fetchMetaResult':
// forward to Core
this._ipcSend('json', {
method: 'fetchMetaResult',
_id: opt.data._id,
dnaAddress: opt.data.dnaAddress,
requesterAgentId: opt.data.requesterAgentId,
providerAgentId: opt.data.providerAgentId,
agentId: opt.data.agentId,
entryAddress: opt.data.entryAddress,
attribute: opt.data.attribute,
contentList: opt.data.contentList
})
return
case 'failureResult':
// forward to Core
this._ipcSend('json', {
method: 'failureResult',
_id: opt.data._id,
dnaAddress: opt.data.dnaAddress,
toAgentId: opt.data.toAgentId,
errorInfo: opt.data.errorInfo
})
return
}
throw new Error('Received unexpected p2p message from "' + opt.from + '" ' + JSON.stringify(
opt.data))
}
/**
* Create and initialize a new DHT for a dnaAddress
* @param dnaAddress
* @param agentId
* @returns {Dht}
* @private
*/
async _initDht (dnaAddress, agentId) {
// log.t(this.me() + '_initDht', dnaAddress, agentId)
// pre-conditions
if (!dnaAddress || typeof dnaAddress !== 'string' || !dnaAddress.length) {
throw new Error('cannot _initDht without dnaAddress string')
}
if (!agentId || typeof agentId !== 'string' || !agentId.length) {
throw new Error('cannot _initDht without agentId string')
}
// Setup init data
const dhtInitOptions = {
thisPeer: DhtEvent.peerHoldRequest(
agentId,
this.toDnaPeerTransport(this._p2p.getId()),
Buffer.from('self').toString('base64'),
Date.now()
)
}
// Construct
let dht = (await new DhtBackendFullsync(dhtInitOptions)).interfaceDht
// Set event handler
dht.on('event', e => this._handleDhtEvent(e, dnaAddress).catch(err => {
console.error('Error while handling dnaDhtEvent', e, err)
process.exit(1)
}))
// Add to "Map"
this._dhtPerDna[dnaAddress] = dht
}
_getPeerList () {
return Object.keys(this._peerTracks)
}
/**
* @private
*/
_getPeerRef (machineId) {
if (!machineId || typeof machineId !== 'string' || !machineId.length) {
throw new Error('_getPeerRef() call missing machineId string argument')
}
if (!(machineId in this._peerTracks)) {
this._peerTracks[machineId] = new Map()
}
return this._peerTracks[machineId]
}
/**
* @private
*/
_getDhtRef (dnaAddress) {
if (!dnaAddress || typeof dnaAddress !== 'string' || !dnaAddress.length) {
throw new Error('_getDhtRef() call missing dnaAddress string argument')
}
if (!(dnaAddress in this._dhtPerDna)) {
throw new Error('Unknown / untracked DNA:' + dnaAddress)
}
return this._dhtPerDna[dnaAddress]
}
/**
* @private
*/
_getMemRef (dnaAddress) {
if (!(dnaAddress in this._memory)) {
const mem = new RealMem()
// send IPC handleStoreEntry on inserting a dhtEntry
mem.registerIndexer((store, data) => {
if (data && data.type === 'dhtEntry') {
// Store hash in DHT
log.t(this.me() + ' got dhtEntry', data)
const contentHash = getHash(JSON.stringify(data.content))
this._getDhtRef(dnaAddress).post(DhtEvent.dataHoldRequest(data.address, contentHash))
// Store in Core if it isn't already holding it
if (this._hasEntry(dnaAddress, data.address)) {
log.t(this.me() + ' dhtEntry is known:', data.address)
return
}
log.t(this.me() + ' dhtEntry is unknown', data.address)
// bookkeep
this._bookkeepAddress(this._storedEntryBook, dnaAddress, data.address)
// log.t(this.me() + ' Sending IPC handleStoreEntry: ', data.address)
this._ipcSend('json', {
method: 'handleStoreEntry',
dnaAddress,
providerAgentId: data.providerAgentId,
address: data.address,
content: data.content
})
}
})
// send IPC handleStoreMeta on inserting a dhtMeta
mem.registerIndexer((store, data) => {
if (data && data.type === 'dhtMeta') {
log.t(this.me() + ' got dhtMeta', data)
let toStoreList = []
let dht = this._getDhtRef(dnaAddress)
for (const metaContent of data.contentList) {
const metaId = this._metaIdFromTuple(data.entryAddress, data.attribute, metaContent)
// Store hash of metaContent in DHT
const contentHash = getHash(metaId)
dht.post(DhtEvent.dataHoldRequest(data.entryAddress, contentHash))
// Store in Core if Core isn't already holding it
if (this._hasMeta(dnaAddress, metaId)) {
log.t('metaContent is known:', metaContent)
continue
}
log.t('metaContent is unknown:', metaContent)
this._bookkeepAddress(this._storedMetaBook, dnaAddress, metaId)
toStoreList.push(metaContent)
}
// Send toStoreList to Core
// log.t(this.me() + ' Sending IPC handleStoreMeta: ', toStoreList)
this._ipcSend('json', {
method: 'handleStoreMeta',
dnaAddress,
providerAgentId: data.providerAgentId,
entryAddress: data.entryAddress,
attribute: data.attribute,
contentList: toStoreList
})
}
})
this._memory[dnaAddress] = mem
}
return this._memory[dnaAddress]
}
/**
* Check if agent is tracking dna.
* If not, will try to send a FailureResult back to sender (if sender info is provided).
* Returns peerAddress of receiverAgentId if agent is tracking dna.
* @private
*/
_getPeerAddressOrFail (dnaAddress, receiverAgentId, senderAgentId, requestId) {
const recvPeer = this._getDhtRef(dnaAddress).getPeerLocal(receiverAgentId)
if (!recvPeer) {
// Send FailureResult back to IPC, should be senderAgentId
log.e(this.me() + ' #### CHECK FAILED for (agent) "' + receiverAgentId + '" + (DNA) "' + dnaAddress + '" (sender: ' + senderAgentId + ')')
this._ipcSend('json', {
method: 'failureResult',
dnaAddress: dnaAddress,
_id: requestId,
toAgentId: senderAgentId,
errorInfo: 'No routing for agent id "' + receiverAgentId + '"'
})
return null
}
const recvPeerAddress = this.toMachineId(recvPeer.peerTransport)
log.t(this.me() + ' oooo CHECK OK for (agent)"' + receiverAgentId + '" + (DNA) "' + dnaAddress + '" = ' + this.nick(recvPeerAddress))
return recvPeerAddress
}
/**
* @private
*/
_untrack (dnaAddress, agentId) {
log.t(this.me() + ' _untrack() for "' + agentId + '" for DNA "' + dnaAddress + '"')
this._ipcRemoveTrack(agentId, dnaAddress)
}
/**
* @private
*/
async _track (dnaAddress, agentId) {
log.t(this.me() + ' _track', dnaAddress, agentId)
// Bookkeep agentId -> dnaAddress
this._ipcAddTrack(agentId, dnaAddress)
// Init DHT for this DNA and bookkeep agentId -> peerAddress for self
if (!(dnaAddress in this._dhtPerDna)) {
await this._initDht(dnaAddress, agentId)
} else {
const peerHoldEvent = DhtEvent.peerHoldRequest(
agentId,
this.toDnaPeerTransport(this._p2p.getId()),
Buffer.from('').toString('base64'),
Date.now())
this._handleDhtEvent(peerHoldEvent, agentId)
}
// Make sure thisPeer data is stored
const dht = this._getDhtRef(dnaAddress)
let time = 0
while (!dht.getPeerLocal(agentId) && time < 1000) {
await $sleep(10)
time += 10
}
if (time >= 1000) {
throw new Error('peerHoldRequest timed out during _track')
}
log.i(this.me() + ' REGISTERED AGENT', agentId, dnaAddress, dht.getPeerLocal(agentId).peerTransport)
// Send 'peerConnected' of self to Core
this._ipcSend('json', {
method: 'peerConnected',
agentId: agentId
})
// Notify all known peers of DNA tracking by this agent
this._p2pSendAll({ type: 'gossipNewTrack', agentId, dnaAddress })
// Send get * lists requests to Core
let requestId = this._createRequest(dnaAddress, agentId)
this._ipcSend('json', {
method: 'handleGetPublishingEntryList',
dnaAddress,
_id: requestId
})
requestId = this._createRequest(dnaAddress, agentId)
this._ipcSend('json', {
method: 'handleGetHoldingEntryList',
dnaAddress,
_id: requestId
})
requestId = this._createRequest(dnaAddress, agentId)
this._ipcSend('json', {
method: 'handleGetPublishingMetaList',
dnaAddress,
_id: requestId
})
requestId = this._createRequest(dnaAddress, agentId)
this._ipcSend('json', {
method: 'handleGetHoldingMetaList',
dnaAddress,
_id: requestId
})
}
/**
* Make a metaId out of an DhtMetaData
* @private
*/
_metaIdFromTuple (entryAddress, attribute, metaContentJson) {
var metaContent = Buffer.from(JSON.stringify(metaContentJson))
const hashedContent = getHash(metaContent)
return '' + entryAddress + '||' + attribute + '||' + hashedContent
}
_generateRequestId () {
this._requestCount += 1
return 'req_' + this._requestCount
}
/**
* create and return a new request_id
* @private
*/
_createRequest (dnaAddress, agentId) {
return this._createRequestWithBucket(dnaAddress)
}
/**
* @private
*/
_createRequestWithBucket (bucketId) {
let reqId = this._generateRequestId()
this._requestBook.set(reqId, bucketId)
return reqId
}
/**
* @private
*/
_bookkeepAddress (book, dnaAddress, address) {
if (!(dnaAddress in book)) {
book[dnaAddress] = []
}
book[dnaAddress].push(address)
}
/**
* @private
*/
_hasEntry (dnaAddress, entryAddress) {
const isStored = dnaAddress in this._storedEntryBook
? this._storedEntryBook[dnaAddress].includes(entryAddress)
: false
return isStored
}
/**
* @private
*/
_hasMeta (dnaAddress, metaId) {
const isStored = dnaAddress in this._storedMetaBook
? this._storedMetaBook[dnaAddress].includes(metaId)
: false
return isStored
}
} |
JavaScript | class Manager extends Employee {
constructor(name, id, email, officeNumber) {
super(name, id, email);
this.officeNumber = officeNumber;
}
// function to insert role of manager vs employee
getRole() {
return 'Manager';
}
// function to return office number
getOfficeNumber() {
return this.officeNumber;
}
} |
JavaScript | class FacebookShare extends Component {
render() {
return (<div>Share</div>);
// return (
// <FacebookProvider appId="259035427863157">
// <Share href={window.location.href}>
// <div className="btn btn-primary">
// <i className="fa fa-facebook"></i>
// Поширити
// </div>
// </Share>
// </FacebookProvider>
// );
}
} |
JavaScript | class SwUpdateServerMock {
constructor() {
this.available = new Subject();
this.activated = new Subject();
this.isEnabled = false;
}
/**
* @return {?}
*/
checkForUpdate() {
return new Promise((resolve) => resolve());
}
/**
* @return {?}
*/
activateUpdate() {
return new Promise((resolve) => resolve());
}
} |
JavaScript | class SwPushServerMock {
/**
* @param {?} options
* @return {?}
*/
requestSubscription(options) {
console.log(`requested subscription with options: ${options}`);
return new Promise((resolve) => resolve());
}
/**
* @return {?}
*/
unsubscribe() {
return new Promise((resolve) => resolve());
}
} |
JavaScript | class RaphaelIconMuleDirective extends RaphaelBase {
/**
* @param {?} elementRef
* @param {?} raphaelService
*/
constructor(elementRef, raphaelService) {
super(elementRef, raphaelService);
this.elementRef = elementRef;
this.error = new EventEmitter();
}
/**
* @return {?}
*/
ngOnInit() {
this.draw(this.position);
}
/**
* @param {?} position
* @return {?}
*/
draw(position) {
/** @type {?} */
const path1 = this.paper.path(`M 8,0 C 3.581722,0 0,3.5817 0,8 c 0,4.4183 3.581722,8 8,8 4.418278,0 8,-3.5817 8,-8 L 16,7.6562
C 15.813571,3.3775 12.282847,0 8,0 z M 5.1875,2.7812 8,7.3437 10.8125,2.7812 c 1.323522,0.4299 2.329453,1.5645 2.8125,2.8438
1.136151,2.8609 -0.380702,6.4569 -3.25,7.5937 -0.217837,-0.6102 -0.438416,-1.2022 -0.65625,-1.8125 0.701032,-0.2274
1.313373,-0.6949 1.71875,-1.3125 0.73624,-1.2317 0.939877,-2.6305 -0.03125,-4.3125 l -2.75,4.0625 -0.65625,0 -0.65625,0 -2.75,-4
C 3.5268433,7.6916 3.82626,8.862 4.5625,10.0937 4.967877,10.7113 5.580218,11.1788 6.28125,11.4062 6.063416,12.0165 5.842837,12.6085
5.625,13.2187 2.755702,12.0819 1.238849,8.4858 2.375,5.625 2.858047,4.3457 3.863978,3.2112 5.1875,2.7812 z`).attr({
'stroke': this.stroke,
'fill': this.fillColors
});
return path1.transform('T' + position.x + ',' + position.y);
}
} |
JavaScript | class HttpError {
/**
* Default constructor
* @param {*} http
* @param {*} message
* @param {*} code
* @param {*} from
*/
constructor(http, message, code, from) {
this._http = http;
if (!code) code = http;
if (!message) message = http;
this._err = from ? from : new Error(message);
this.message = message;
this.code = code;
this.details = 'https://<domain>/support/' + code;
}
/**
* Serialize the error
*/
toString() {
return "HTTP Error " + this._http + " (#" + this.code + ") : " + this.message +
"\nCaused by : " + this._err.toString()
;
}
} |
JavaScript | class Updates extends models['BaseModel'] {
/**
* Create a Updates.
* @member {string} [deviceVersion] The current Device version.
* @member {date} [deviceLastScannedTime] The last time when the device did
* an update scan.
* @member {boolean} [regularUpdatesAvailable] Set to true if regular updates
* were detected for the current version of the device.
* @member {boolean} [rebootRequiredForInstall] Set to true if
* RegularUpdatesAvailable is true and if atleast one of the updateItems
* detected has needs a reboot to install.
* @member {number} [totalItemsPendingForDownload] The total number of items
* pending for download.
* @member {number} [totalItemsPendingForInstall] The total number of items
* pending for install.
* @member {string} [status] The current update operation. Possible values
* include: 'Idle', 'Scanning', 'Downloading', 'Installing'
* @member {date} [lastCompletedScanTime] The time when the last scan job was
* completed (success|cancelled|failed) on the device.
* @member {date} [lastCompletedDownloadJobTime] The time when the last
* Download job was completed (success|cancelled|failed) on the device.
* @member {date} [lastCompletedInstallJobTime] The time when the last
* Install job was completed (success|cancelled|failed) on the device.
* @member {string} [inProgressDownloadJobId] If a download is in progress,
* this field contains the JobId of that particular download job
* @member {string} [inProgressInstallJobId] If an install is in progress,
* this field contains the JobId of that particular install job
* @member {date} [inProgressScanStartedTime] The time when the currently
* running scan (if any) started
* @member {date} [inProgressDownloadJobStartedTime] The time when the
* currently running download (if any) started
* @member {date} [inProgressInstallJobStartedTime] The time when the
* currently running install (if any) started
*/
constructor() {
super();
}
/**
* Defines the metadata of Updates
*
* @returns {object} metadata of Updates
*
*/
mapper() {
return {
required: false,
serializedName: 'Updates',
type: {
name: 'Composite',
className: 'Updates',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
deviceVersion: {
required: false,
serializedName: 'properties.deviceVersion',
type: {
name: 'String'
}
},
deviceLastScannedTime: {
required: false,
serializedName: 'properties.deviceLastScannedTime',
type: {
name: 'DateTime'
}
},
regularUpdatesAvailable: {
required: false,
serializedName: 'properties.regularUpdatesAvailable',
type: {
name: 'Boolean'
}
},
rebootRequiredForInstall: {
required: false,
serializedName: 'properties.rebootRequiredForInstall',
type: {
name: 'Boolean'
}
},
totalItemsPendingForDownload: {
required: false,
serializedName: 'properties.totalItemsPendingForDownload',
type: {
name: 'Number'
}
},
totalItemsPendingForInstall: {
required: false,
serializedName: 'properties.totalItemsPendingForInstall',
type: {
name: 'Number'
}
},
status: {
required: false,
serializedName: 'properties.status',
type: {
name: 'Enum',
allowedValues: [ 'Idle', 'Scanning', 'Downloading', 'Installing' ]
}
},
lastCompletedScanTime: {
required: false,
serializedName: 'properties.lastCompletedScanTime',
type: {
name: 'DateTime'
}
},
lastCompletedDownloadJobTime: {
required: false,
serializedName: 'properties.lastCompletedDownloadJobTime',
type: {
name: 'DateTime'
}
},
lastCompletedInstallJobTime: {
required: false,
serializedName: 'properties.lastCompletedInstallJobTime',
type: {
name: 'DateTime'
}
},
inProgressDownloadJobId: {
required: false,
serializedName: 'properties.inProgressDownloadJobId',
type: {
name: 'String'
}
},
inProgressInstallJobId: {
required: false,
serializedName: 'properties.inProgressInstallJobId',
type: {
name: 'String'
}
},
inProgressScanStartedTime: {
required: false,
serializedName: 'properties.inProgressScanStartedTime',
type: {
name: 'DateTime'
}
},
inProgressDownloadJobStartedTime: {
required: false,
serializedName: 'properties.inProgressDownloadJobStartedTime',
type: {
name: 'DateTime'
}
},
inProgressInstallJobStartedTime: {
required: false,
serializedName: 'properties.inProgressInstallJobStartedTime',
type: {
name: 'DateTime'
}
}
}
}
};
}
} |
JavaScript | class AlertQueue {
/**
* Constructs a new message queue
* @param {HTMLElement} element - element to change
*/
constructor(element) {
this.messages = [];
this.lock = false;
this.element = element;
}
/**
* Queues the message to be displayed
* @param {string} message - the message to queue
* @public
*/
queueMessage(message) {
this.messages.push(message);
this.displayMessages();
}
/**
* Displays the messages in the order they appear in the queue and continues
* until the queue is empty
* @private
*/
displayMessages() {
if (this.lock) {
setTimeout(() => {
this.displayMessages();
}, 1000);
} else {
this.lock = true;
const message = this.messages.pop();
this.element.innerText = message;
// audio.play();
setTimeout(() => {
this.element.innerText = '';
this.lock = false;
}, 5000);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.