language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class MetadataType {
/**
* Instantiates a metadata constructor to avoid passing variables.
*
* @param {Util.ET_Client} client client for sfmc fuelsdk
* @param {string} businessUnit Name of business unit (corresponding to their keys in 'properties.json' file). Used to access correct directories
* @param {Object} cache metadata cache
* @param {Object} properties mcdev config
* @param {string} [subType] limit retrieve to specific subType
*/
constructor(client, businessUnit, cache, properties, subType) {
this.client = client;
this.businessUnit = businessUnit;
this.cache = cache;
this.properties = properties;
this.subType = subType;
}
/**
* Returns file contents mapped to their filename without '.json' ending
* @param {string} dir directory that contains '.json' files to be read
* @param {boolean} [listBadKeys=false] do not print errors, used for badKeys()
* @returns {Object} fileName => fileContent map
*/
static getJsonFromFS(dir, listBadKeys) {
const fileName2FileContent = {};
try {
const files = File.readdirSync(dir);
files.forEach((fileName) => {
try {
if (fileName.endsWith('.json')) {
const fileContent = File.readJSONFile(dir, fileName, true, false);
const fileNameWithoutEnding = File.reverseFilterIllegalFilenames(
fileName.split(/\.(\w|-)+-meta.json/)[0]
);
// We always store the filename using the External Key (CustomerKey or key) to avoid duplicate names.
// to ensure any changes are done to both the filename and external key do a check here
if (
fileContent[this.definition.keyField] === fileNameWithoutEnding ||
listBadKeys
) {
fileName2FileContent[fileNameWithoutEnding] = fileContent;
} else {
Util.metadataLogger(
'error',
this.definition.type,
'getJsonFromFS',
'Name of the Metadata and the External Identifier must match',
JSON.stringify({
Filename: fileNameWithoutEnding,
ExternalIdentifier: fileContent[this.definition.keyField],
})
);
}
}
} catch (ex) {
// by catching this in the loop we gracefully handle the issue and move on to the next file
Util.metadataLogger('debug', this.definition.type, 'getJsonFromFS', ex);
}
});
} catch (ex) {
// this will catch issues with readdirSync
Util.metadataLogger('debug', this.definition.type, 'getJsonFromFS', ex);
throw new Error(ex);
}
return fileName2FileContent;
}
/**
* Returns fieldnames of Metadata Type. 'this.definition.fields' variable only set in child classes.
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {string[]} Fieldnames
*/
static getFieldNamesToRetrieve(additionalFields) {
const fieldNames = [];
for (const fieldName in this.definition.fields) {
if (
(additionalFields && additionalFields.includes(fieldName)) ||
this.definition.fields[fieldName].retrieving
) {
fieldNames.push(fieldName);
}
}
if (!fieldNames.includes(this.definition.idField)) {
// Always retrieve the ID because it may be used in references
fieldNames.push(this.definition.idField);
}
return fieldNames;
}
/**
* Deploys metadata
* @param {MetadataTypeMap} metadata metadata mapped by their keyField
* @param {string} deployDir directory where deploy metadata are saved
* @param {string} retrieveDir directory where metadata after deploy should be saved
* @param {Util.BuObject} buObject properties for auth
* @returns {Promise<Object>} Promise of keyField => metadata map
*/
static async deploy(metadata, deployDir, retrieveDir, buObject) {
const upsertResults = await this.upsert(metadata, deployDir, buObject);
await this.postDeployTasks(upsertResults, metadata);
const savedMetadata = await this.saveResults(upsertResults, retrieveDir, null);
if (this.properties.metaDataTypes.documentOnRetrieve.includes(this.definition.type)) {
// * do not await here as this might take a while and has no impact on the deploy
this.document(buObject, savedMetadata, true);
}
return upsertResults;
}
/**
* Gets executed after deployment of metadata type
* @param {MetadataTypeMap} metadata metadata mapped by their keyField
* @param {MetadataTypeMap} originalMetadata metadata to be updated (contains additioanl fields)
* @returns {void}
*/
static postDeployTasks(metadata, originalMetadata) {}
/**
* Gets executed after retreive of metadata type
* @param {MetadataTypeItem} metadata a single item
* @param {string} targetDir folder where retrieves should be saved
* @param {boolean} [isTemplating] signals that we are retrieving templates
* @returns {MetadataTypeItem} cloned metadata
*/
static postRetrieveTasks(metadata, targetDir, isTemplating) {
return JSON.parse(JSON.stringify(metadata));
}
/**
* used to synchronize name and external key during retrieveAsTemplate
* @param {MetadataTypeItem} metadata a single item
* @param {string} [warningMsg] optional msg to show the user
* @returns {void}
*/
static overrideKeyWithName(metadata, warningMsg) {
if (
this.definition.nameField &&
this.definition.keyField &&
metadata[this.definition.nameField] !== metadata[this.definition.keyField]
) {
Util.logger.warn(
`Reset external key of ${this.definition.type} ${
metadata[this.definition.nameField]
} to its name (${metadata[this.definition.keyField]})`
);
if (warningMsg) {
Util.logger.warn(warningMsg);
}
// do this after printing to cli or we lost the info
metadata[this.definition.keyField] = metadata[this.definition.nameField];
}
}
/**
* Gets metadata from Marketing Cloud
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {Util.BuObject} buObject properties for auth
* @param {string} [subType] optionally limit to a single subtype
* @returns {Promise<{metadata:MetadataTypeMap,type:string}>} metadata
*/
static retrieve(retrieveDir, additionalFields, buObject, subType) {
Util.metadataLogger('error', this.definition.type, 'retrieve', `Not Supported`);
const metadata = {};
return { metadata: null, type: this.definition.type };
}
/**
* Gets metadata from Marketing Cloud
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {Util.BuObject} buObject properties for auth
* @param {string} [subType] optionally limit to a single subtype
* @returns {Promise<{metadata:MetadataTypeMap,type:string}>} metadata
*/
static retrieveChangelog(additionalFields, buObject, subType) {
return this.retrieve(null, additionalFields, buObject, subType);
}
/**
* Gets metadata cache with limited fields and does not store value to disk
* @param {Util.BuObject} buObject properties for auth
* @param {string} [subType] optionally limit to a single subtype
* @returns {Promise<{metadata:MetadataTypeMap,type:string}>} metadata
*/
static async retrieveForCache(buObject, subType) {
return this.retrieve(null, null, buObject, subType);
}
/**
* Gets metadata cache with limited fields and does not store value to disk
* @param {string} templateDir Directory where retrieved metadata directory will be saved
* @param {string} name name of the metadata file
* @param {Util.TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} [subType] optionally limit to a single subtype
* @returns {Promise<{metadata:MetadataTypeMap,type:string}>} metadata
*/
static retrieveAsTemplate(templateDir, name, templateVariables, subType) {
Util.logger.error('retrieveAsTemplate is not supported yet for ' + this.definition.type);
Util.metadataLogger(
'debug',
this.definition.type,
'retrieveAsTemplate',
`(${templateDir}, ${name}, ${templateVariables}) no templating function`
);
return { metadata: null, type: this.definition.type };
}
/**
* Gets executed before deploying metadata
* @param {MetadataTypeItem} metadata a single metadata item
* @param {string} deployDir folder where files for deployment are stored
* @returns {Promise<MetadataTypeItem>} Promise of a single metadata item
*/
static async preDeployTasks(metadata, deployDir) {
return metadata;
}
/**
* Abstract create method that needs to be implemented in child metadata type
* @param {MetadataTypeItem} metadata single metadata entry
* @param {string} deployDir directory where deploy metadata are saved
* @returns {void}
*/
static create(metadata, deployDir) {
Util.metadataLogger('error', this.definition.type, 'create', 'create not supported');
return;
}
/**
* Abstract update method that needs to be implemented in child metadata type
* @param {MetadataTypeItem} metadata single metadata entry
* @param {MetadataTypeItem} [metadataBefore] metadata mapped by their keyField
* @returns {void}
*/
static update(metadata, metadataBefore) {
Util.metadataLogger('error', this.definition.type, 'update', 'update not supported');
return;
}
/**
* MetadataType upsert, after retrieving from target and comparing to check if create or update operation is needed.
* @param {MetadataTypeMap} metadata metadata mapped by their keyField
* @param {string} deployDir directory where deploy metadata are saved
* @param {Util.BuObject} [buObject] properties for auth
* @returns {Promise<MetadataTypeMap>} keyField => metadata map
*/
static async upsert(metadata, deployDir, buObject) {
const metadataToUpdate = [];
const metadataToCreate = [];
for (const metadataKey in metadata) {
try {
// preDeployTasks parsing
const deployableMetadata = await this.preDeployTasks(
metadata[metadataKey],
deployDir
);
// if preDeploy returns nothing then it cannot be deployed so skip deployment
if (deployableMetadata) {
metadata[metadataKey] = deployableMetadata;
const normalizedKey = File.reverseFilterIllegalFilenames(metadataKey);
// Update if it already exists; Create it if not
if (
Util.logger.level === 'debug' &&
metadata[metadataKey][this.definition.idField]
) {
// TODO: re-evaluate in future releases if & when we managed to solve folder dependencies once and for all
// only used if resource is excluded from cache and we still want to update it
// needed e.g. to rewire lost folders
Util.logger.warn(
'Hotfix for non-cachable resource found in deploy folder. Trying update:'
);
Util.logger.warn(JSON.stringify(metadata[metadataKey]));
metadataToUpdate.push({
before: {},
after: metadata[metadataKey],
});
} else if (this.cache[this.definition.type][normalizedKey]) {
// normal way of processing update files
metadata[metadataKey][this.definition.idField] =
this.cache[this.definition.type][normalizedKey][
this.definition.idField
];
metadataToUpdate.push({
before: this.cache[this.definition.type][normalizedKey],
after: metadata[metadataKey],
});
} else {
metadataToCreate.push(metadata[metadataKey]);
}
}
} catch (ex) {
Util.metadataLogger('error', this.definition.type, 'upsert', ex, metadataKey);
}
}
const createResults = (
await Promise.map(
metadataToCreate,
(metadataEntry) => this.create(metadataEntry, deployDir),
{ concurrency: 10 }
)
).filter((r) => r !== undefined && r !== null);
const updateResults = (
await Promise.map(
metadataToUpdate,
(metadataEntry) => this.update(metadataEntry.after, metadataEntry.before),
{ concurrency: 10 }
)
).filter((r) => r !== undefined && r !== null);
// Logging
Util.metadataLogger(
'info',
this.definition.type,
'upsert',
`${createResults.length} of ${metadataToCreate.length} created / ${updateResults.length} of ${metadataToUpdate.length} updated`
);
// if Results then parse as SOAP
if (this.definition.bodyIteratorField === 'Results') {
// put in Retrieve Format for parsing
// todo add handling when response does not contain items.
// @ts-ignore
const metadataResults = createResults
.concat(updateResults)
.filter((r) => r !== undefined && r !== null)
.map((r) => r.body.Results)
.flat()
.map((r) => r.Object);
return this.parseResponseBody({ Results: metadataResults });
} else {
// put in Retrieve Format for parsing
// todo add handling when response does not contain items.
// @ts-ignore
const metadataResults = createResults
.concat(updateResults)
.filter((r) => r !== undefined && r !== null && r.res && r.res.body)
.map((r) => r.res.body);
return this.parseResponseBody({ items: metadataResults });
}
}
/**
* Creates a single metadata entry via REST
* @param {MetadataTypeItem} metadataEntry a single metadata Entry
* @param {string} uri rest endpoint for POST
* @returns {Promise} Promise
*/
static async createREST(metadataEntry, uri) {
this.removeNotCreateableFields(metadataEntry);
const options = {
uri: uri,
json: metadataEntry,
headers: {},
};
try {
let response;
await Util.retryOnError(
`Retrying ${this.definition.type}: ${metadataEntry[this.definition.nameField]}`,
async () => (response = await this.client.RestClient.post(options))
);
this.checkForErrors(response);
Util.logger.info(
`- created ${this.definition.type}: ${metadataEntry[this.definition.keyField]}`
);
return response;
} catch (ex) {
Util.logger.error(
`- error creating ${this.definition.type}: ${
metadataEntry[this.definition.keyField]
} (${ex.message})`
);
return null;
}
}
/**
* Creates a single metadata entry via fuel-soap (generic lib not wrapper)
* @param {MetadataTypeItem} metadataEntry single metadata entry
* @param {string} [overrideType] can be used if the API type differs from the otherwise used type identifier
* @param {boolean} [handleOutside] if the API reponse is irregular this allows you to handle it outside of this generic method
* @returns {Promise} Promise
*/
static async createSOAP(metadataEntry, overrideType, handleOutside) {
try {
this.removeNotCreateableFields(metadataEntry);
let response;
await Util.retryOnError(
`Retrying to create ${this.definition.type}: ${
metadataEntry[this.definition.nameField]
}`,
async () =>
(response = await new Promise((resolve, reject) => {
this.client.SoapClient.create(
overrideType ||
this.definition.type.charAt(0).toUpperCase() +
this.definition.type.slice(1),
metadataEntry,
null,
(error, response) => (error ? reject(error) : resolve(response))
);
}))
);
if (!handleOutside) {
Util.logger.info(
`- created ${this.definition.type}: ${metadataEntry[this.definition.keyField]}`
);
}
return response;
} catch (ex) {
if (!handleOutside) {
let errorMsg;
if (ex.results && ex.results.length) {
errorMsg = `${ex.results[0].StatusMessage} (Code ${ex.results[0].ErrorCode})`;
} else {
errorMsg = ex.message;
}
Util.logger.error(
`- error creating ${this.definition.type} '${
metadataEntry[this.definition.keyField]
}': ${errorMsg}`
);
} else {
throw ex;
}
return {};
}
}
/**
* Updates a single metadata entry via REST
* @param {MetadataTypeItem} metadataEntry a single metadata Entry
* @param {string} uri rest endpoint for PATCH
* @returns {Promise} Promise
*/
static async updateREST(metadataEntry, uri) {
this.removeNotUpdateableFields(metadataEntry);
const options = {
uri: uri,
json: metadataEntry,
headers: {},
};
try {
let response;
await Util.retryOnError(
`Retrying ${this.definition.type}: ${metadataEntry[this.definition.nameField]}`,
async () => (response = await this.client.RestClient.patch(options))
);
this.checkForErrors(response);
// some times, e.g. automation dont return a key in their update response and hence we need to fall back to name
Util.logger.info(
`- updated ${this.definition.type}: ${
metadataEntry[this.definition.keyField] ||
metadataEntry[this.definition.nameField]
}`
);
return response;
} catch (ex) {
Util.logger.error(
`- error updating ${this.definition.type}: ${
metadataEntry[this.definition.keyField]
} (${ex.message})`
);
return null;
}
}
/**
* Updates a single metadata entry via fuel-soap (generic lib not wrapper)
* @param {MetadataTypeItem} metadataEntry single metadata entry
* @param {string} [overrideType] can be used if the API type differs from the otherwise used type identifier
* @param {boolean} [handleOutside] if the API reponse is irregular this allows you to handle it outside of this generic method
* @returns {Promise} Promise
*/
static async updateSOAP(metadataEntry, overrideType, handleOutside) {
let response;
try {
this.removeNotUpdateableFields(metadataEntry);
await Util.retryOnError(
`Retrying to update ${this.definition.type}: ${
metadataEntry[this.definition.nameField]
}`,
async () =>
(response = await new Promise((resolve, reject) => {
this.client.SoapClient.update(
overrideType ||
this.definition.type.charAt(0).toUpperCase() +
this.definition.type.slice(1),
metadataEntry,
null,
(error, response) => (error ? reject(error) : resolve(response))
);
}))
);
if (!handleOutside) {
Util.logger.info(
`- updated ${this.definition.type}: ${metadataEntry[this.definition.keyField]}`
);
}
return response;
} catch (ex) {
if (!handleOutside) {
let errorMsg;
if (ex.results && ex.results.length) {
errorMsg = `${ex.results[0].StatusMessage} (Code ${ex.results[0].ErrorCode})`;
} else {
errorMsg = ex.message;
}
Util.logger.error(
`- error updating ${this.definition.type} '${
metadataEntry[this.definition.keyField]
}': ${errorMsg}`
);
} else {
throw ex;
}
return {};
}
}
/**
* Retrieves SOAP via generic fuel-soap wrapper based metadata of metadata type into local filesystem. executes callback with retrieved metadata
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {Util.BuObject} buObject properties for auth
* @param {Object} [options] required for the specific request (filter for example)
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {string} [overrideType] can be used if the API type differs from the otherwise used type identifier
* @returns {Promise<{metadata:MetadataTypeMap,type:string}>} Promise of item map
*/
static async retrieveSOAPgeneric(
retrieveDir,
buObject,
options,
additionalFields,
overrideType
) {
const fields = this.getFieldNamesToRetrieve(additionalFields);
const metadata = await this.retrieveSOAPBody(fields, options, overrideType);
if (retrieveDir) {
const savedMetadata = await this.saveResults(metadata, retrieveDir, null);
Util.logger.info(
`Downloaded: ${this.definition.type} (${Object.keys(savedMetadata).length})`
);
if (
buObject &&
this.properties.metaDataTypes.documentOnRetrieve.includes(this.definition.type)
) {
await this.document(buObject, savedMetadata);
}
}
return { metadata: metadata, type: this.definition.type };
}
/**
* helper that handles batched retrieve via SOAP
* @param {string[]} fields list of fields that we want to see retrieved
* @param {Object} [options] required for the specific request (filter for example)
* @param {string} [type] optionally overwrite the API type of the metadata here
* @returns {Promise<MetadataTypeMap>} keyField => metadata map
*/
static async retrieveSOAPBody(fields, options, type) {
let status;
let batchCounter = 1;
const defaultBatchSize = 2500; // 2500 is the typical batch size
options = options || {};
let metadata = {};
do {
let resultsBatch;
await Util.retryOnError(`Retrying ${this.definition.type}`, async () => {
resultsBatch = await new Promise((resolve, reject) => {
this.client.SoapClient.retrieve(
type || this.definition.type,
fields,
options || {},
(error, response) => {
if (error) {
Util.logger.debug(`SOAP.retrieve Error: ${error.message}`);
reject(error);
}
if (response) {
resolve(response.body);
} else {
// fallback, lets make sure surrounding methods know we got an empty result back
resolve({});
}
}
);
});
});
status = resultsBatch.OverallStatus;
if (status === 'MoreDataAvailable') {
options.continueRequest = resultsBatch.RequestID;
Util.logger.info(
`- more than ${batchCounter * defaultBatchSize} ${
this.definition.typeName
}s found in Business Unit - loading next batch...`
);
batchCounter++;
}
const metadataBatch = this.parseResponseBody(resultsBatch);
metadata = { ...metadata, ...metadataBatch };
} while (status === 'MoreDataAvailable');
return metadata;
}
/**
* Retrieves Metadata for Rest Types
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {string} uri rest endpoint for GET
* @param {string} [overrideType] force a metadata type (mainly used for Folders)
* @param {Util.TemplateMap} [templateVariables] variables to be replaced in the metadata
* @returns {Promise<{metadata:MetadataTypeMap,type:string}>} Promise of item map
*/
static async retrieveREST(retrieveDir, uri, overrideType, templateVariables) {
const options = {
uri: uri,
headers: {},
};
let moreResults;
let lastPage = null;
let results = {};
do {
options.uri = this.paginate(options.uri, lastPage);
let response;
await Util.retryOnError(`Retrying ${this.definition.type}`, async () => {
response = await this.client.RestClient.get(options);
});
const metadata = this.parseResponseBody(response.body);
results = Object.assign(results, metadata);
if (
this.definition.restPagination &&
Object.keys(metadata).length > 0 &&
response.body.page * response.body.pageSize < response.body.count
) {
lastPage = Number(response.body.page);
moreResults = true;
} else {
moreResults = false;
}
} while (moreResults);
// get extended metadata if applicable
if (this.definition.hasExtended) {
const extended = await Promise.all(
Object.keys(results).map((key) =>
this.client.RestClient.get({
uri: uri + results[key][this.definition.idField],
})
)
);
for (const ext of extended) {
const key = ext.body[this.definition.keyField];
results[key] = Object.assign(results[key], ext.body);
}
}
if (retrieveDir) {
const savedMetadata = await this.saveResults(
results,
retrieveDir,
overrideType,
templateVariables
);
Util.logger.info(
`Downloaded: ${overrideType || this.definition.type} (${
Object.keys(savedMetadata).length
})`
);
}
return { metadata: results, type: overrideType || this.definition.type };
}
/**
* Builds map of metadata entries mapped to their keyfields
* @param {Object} body json of response body
* @returns {Promise<MetadataTypeMap>} keyField => metadata map
*/
static parseResponseBody(body) {
const bodyIteratorField = this.definition.bodyIteratorField;
const keyField = this.definition.keyField;
const metadataStructure = {};
if (body !== null) {
// in some cases data is just an array
if (Array.isArray(bodyIteratorField)) {
for (const item of body) {
const key = item[keyField];
metadataStructure[key] = item;
}
} else if (body[bodyIteratorField]) {
for (const item of body[bodyIteratorField]) {
const key = item[keyField];
metadataStructure[key] = item;
}
}
}
return metadataStructure;
}
/**
* Deletes a field in a metadata entry if the selected definition property equals false.
* @example
* Removes field (or nested fields childs) that are not updateable
* deleteFieldByDefinition(metadataEntry, 'CustomerKey', 'isUpdateable');
* @param {MetadataTypeItem} metadataEntry One entry of a metadataType
* @param {string} fieldPath field path to be checked if it conforms to the definition (dot seperated if nested): 'fuu.bar'
* @param {'isCreateable'|'isUpdateable'|'retrieving'|'templating'} definitionProperty delete field if definitionProperty equals false for specified field. Options: [isCreateable | isUpdateable]
* @param {string} origin string of parent object, required when using arrays as these are parsed slightly differently.
* @returns {void}
*/
static deleteFieldByDefinition(metadataEntry, fieldPath, definitionProperty, origin) {
// Get content of nested property
let fieldContent;
try {
fieldContent = fieldPath.split('.').reduce((field, key) => field[key], metadataEntry);
} catch (e) {
// when we hit fields that have dots in their name (e.g. interarction, metaData['simulation.id']) then this will fail
// decided to skip these cases for now entirely
return;
}
let originHelper;
// revert back placeholder to dots
if (origin) {
originHelper = origin + '.' + fieldPath;
} else {
originHelper = fieldPath;
}
if (
this.definition.fields[originHelper] &&
this.definition.fields[originHelper].skipValidation
) {
// skip if current field should not be validated
return;
} else if (
Array.isArray(fieldContent) &&
this.definition.fields[originHelper] &&
this.definition.fields[originHelper][definitionProperty] === true
) {
for (const subObject of fieldContent) {
// for simple arrays skip, only process object or array arrays further
if (Array.isArray(subObject) || typeof subObject === 'object') {
for (const subField in subObject) {
this.deleteFieldByDefinition(
subObject,
subField,
definitionProperty,
originHelper + '[]'
);
}
}
}
} else if (
typeof fieldContent === 'object' &&
!Array.isArray(fieldContent) &&
(this.definition.fields[originHelper] == null ||
this.definition.fields[originHelper][definitionProperty] === true)
) {
// Recursive call of this method if there are nested fields
for (const subField in fieldContent) {
this.deleteFieldByDefinition(
metadataEntry,
originHelper + '.' + subField,
definitionProperty,
null
);
}
} else if (!this.definition.fields[originHelper]) {
// Display warining if there is no definition for the current field
Util.logger.verbose(
`MetadataType[${this.definition.type}].deleteFieldByDefinition[${definitionProperty}]:: Field ${originHelper} not in metadata info`
);
} else if (this.definition.fields[originHelper][definitionProperty] === false) {
// Check if field/nested field should be deleted depending on the definitionProperty
fieldPath.split('.').reduce((field, key, index) => {
if (index === fieldPath.split('.').length - 1) {
delete field[key];
} else {
return field[key];
}
}, metadataEntry);
}
}
/**
* Remove fields from metadata entry that are not createable
* @param {MetadataTypeItem} metadataEntry metadata entry
* @returns {void}
*/
static removeNotCreateableFields(metadataEntry) {
for (const field in metadataEntry) {
this.deleteFieldByDefinition(metadataEntry, field, 'isCreateable', null);
}
}
/**
* Remove fields from metadata entry that are not updateable
* @param {MetadataTypeItem} metadataEntry metadata entry
* @returns {void}
*/
static removeNotUpdateableFields(metadataEntry) {
for (const field in metadataEntry) {
this.deleteFieldByDefinition(metadataEntry, field, 'isUpdateable', null);
}
}
/**
* Remove fields from metadata entry that are not needed in the template
* @param {MetadataTypeItem} metadataEntry metadata entry
* @returns {void}
*/
static keepTemplateFields(metadataEntry) {
for (const field in metadataEntry) {
this.deleteFieldByDefinition(metadataEntry, field, 'template', null);
}
}
/**
* Remove fields from metadata entry that are not needed in the stored metadata
* @param {MetadataTypeItem} metadataEntry metadata entry
* @returns {void}
*/
static keepRetrieveFields(metadataEntry) {
for (const field in metadataEntry) {
this.deleteFieldByDefinition(metadataEntry, field, 'retrieving', null);
}
}
/**
* checks if the current metadata entry should be saved on retrieve or not
* @static
* @param {MetadataTypeItem} metadataEntry metadata entry
* @param {boolean} [include=false] true: use definition.include / options.include; false=exclude: use definition.filter / options.exclude
* @returns {boolean} true: skip saving == filtered; false: continue with saving
* @memberof MetadataType
*/
static isFiltered(metadataEntry, include) {
if (include) {
// check include-only filters (== discard rest)
const includeByDefinition = this._filterOther(this.definition.include, metadataEntry);
const includeByConfig = this._filterOther(
this.properties.options.include[this.definition.type],
metadataEntry
);
if (includeByDefinition === false || includeByConfig === false) {
Util.logger.debug(
`Filtered ${this.definition.type} '${
metadataEntry[this.definition.nameField]
}' (${metadataEntry[this.definition.keyField]}): not matching include filter`
);
return true;
}
} else {
// check exclude-only filters (== keep rest)
const excludeByDefinition = this._filterOther(this.definition.filter, metadataEntry);
const excludeByConfig = this._filterOther(
this.properties.options.exclude[this.definition.type],
metadataEntry
);
if (excludeByDefinition || excludeByConfig) {
Util.logger.debug(
`Filtered ${this.definition.type} '${
metadataEntry[this.definition.nameField]
}' (${metadataEntry[this.definition.keyField]}): matching exclude filter`
);
return true;
}
}
// this metadata type has no filters defined or no match was found
return false;
}
/**
* optionally filter by what folder something is in
* @static
* @param {Object} metadataEntry metadata entry
* @param {boolean} [include=false] true: use definition.include / options.include; false=exclude: use definition.filter / options.exclude
* @returns {boolean} true: filtered == do NOT save; false: not filtered == do save
* @memberof MetadataType
*/
static isFilteredFolder(metadataEntry, include) {
if (metadataEntry.json && metadataEntry.json.r__folder_Path) {
// r__folder_Path found in sub-object
metadataEntry = metadataEntry.json;
} else if (!metadataEntry.r__folder_Path) {
// no r__folder_Path found at all
return false;
}
// r__folder_Path found
if (include) {
const errorMsg = `Filtered ${this.definition.type} '${
metadataEntry[this.definition.nameField]
}' (${
metadataEntry[this.definition.keyField]
}): not matching include filter for folder`;
// check include-only filters (== discard rest)
const includeByDefinition = this._filterFolder(
this.definition.include,
metadataEntry.r__folder_Path
);
if (includeByDefinition === false) {
Util.logger.debug(errorMsg + ' (Accenture SFMC DevTools default)');
return true;
}
const includeByConfig = this._filterFolder(
this.properties.options.include[this.definition.type],
metadataEntry.r__folder_Path
);
if (includeByConfig === false) {
Util.logger.debug(errorMsg + ' (project config)');
return true;
}
} else {
const errorMsg = `Filtered ${this.definition.type} '${
metadataEntry[this.definition.nameField]
}' (${metadataEntry[this.definition.keyField]}): matching exclude filter for folder`;
// check exclude-only filters (== keep rest)
const excludeByDefinition = this._filterFolder(
this.definition.filter,
metadataEntry.r__folder_Path
);
if (excludeByDefinition) {
Util.logger.debug(errorMsg + ' (project config)');
return true;
}
const excludeByConfig = this._filterFolder(
this.properties.options.exclude[this.definition.type],
metadataEntry.r__folder_Path
);
if (excludeByConfig) {
Util.logger.debug(errorMsg + ' (Accenture SFMC DevTools default)');
return true;
}
}
// this metadata type has no filters defined or no match was found
return false;
}
/**
* internal helper
* @private
* @param {Object} myFilter include/exclude filter object
* @param {string} r__folder_Path already determined folder path
* @returns {?boolean} true: filter value found; false: filter value not found; null: no filter defined
*/
static _filterFolder(myFilter, r__folder_Path) {
if (!myFilter || !myFilter.r__folder_Path) {
// no filter defined
return null;
}
// consolidate input: could be String[] or String
const filteredValues = Array.isArray(myFilter.r__folder_Path)
? myFilter.r__folder_Path
: [myFilter.r__folder_Path];
for (const path of filteredValues) {
if (r__folder_Path.startsWith(path)) {
// filter matched
// this filters the given folder and anything below it.
// to only filter subfolders, end with "/", to also filter the given folder, omit the "/"
return true;
}
}
// no filters matched
return false;
}
/**
* internal helper
* @private
* @param {Object} myFilter include/exclude filter object
* @param {Object} metadataEntry metadata entry
* @returns {?boolean} true: filter value found; false: filter value not found; null: no filter defined
*/
static _filterOther(myFilter, metadataEntry) {
// not possible to check r__folder_Path before parseMetadata was run; handled in `isFilteredFolder()`
if (
!myFilter ||
!Object.keys(myFilter).filter((item) => item !== 'r__folder_Path').length
) {
// no filter defined
return null;
}
for (const key in myFilter) {
// consolidate input: could be String[] or String
const filteredValues = Array.isArray(myFilter[key]) ? myFilter[key] : [myFilter[key]];
if (filteredValues.includes(metadataEntry[key])) {
// filter matched
return true;
}
}
// no filters matched
return false;
}
/**
* Paginates a URL
* @param {string} url url of the request
* @param {number} last Number of the page of the last request
* @returns {string} new url with pagination
*/
static paginate(url, last) {
if (this.definition.restPagination) {
const baseUrl = url.split('?')[0];
const queryParams = new URLSearchParams(url.split('?')[1]);
// if no page add page
if (!queryParams.has('$page')) {
queryParams.append('$page', (1).toString());
}
// if there is a page and a last value, then add to it.
else if (queryParams.has('$page') && last) {
queryParams.set('$page', (Number(last) + 1).toString());
}
return baseUrl + '?' + decodeURIComponent(queryParams.toString());
} else {
return url;
}
}
/**
* Helper for writing Metadata to disk, used for Retrieve and deploy
* @param {MetadataTypeMap} results metadata results from deploy
* @param {string} retrieveDir directory where metadata should be stored after deploy/retrieve
* @param {string} [overrideType] for use when there is a subtype (such as folder-queries)
* @param {Util.TemplateMap} [templateVariables] variables to be replaced in the metadata
* @returns {Promise<MetadataTypeMap>} Promise of saved metadata
*/
static async saveResults(results, retrieveDir, overrideType, templateVariables) {
const savedResults = {};
const subtypeExtension = '.' + (overrideType || this.definition.type) + '-meta';
let filterCounter = 0;
for (const originalKey in results) {
try {
if (
this.isFiltered(results[originalKey], true) ||
this.isFiltered(results[originalKey], false)
) {
// if current metadata entry is filtered don't save it
filterCounter++;
continue;
}
// define directory into which the current metdata shall be saved
const baseDir = [retrieveDir, ...(overrideType || this.definition.type).split('-')];
results[originalKey] = await this.postRetrieveTasks(
results[originalKey],
retrieveDir,
templateVariables ? true : false
);
if (!results[originalKey] || results[originalKey] === null) {
// we encountered a situation in our postRetrieveTasks that made us want to filter this record
delete results[originalKey];
filterCounter++;
continue;
}
if (
this.isFilteredFolder(results[originalKey], true) ||
this.isFilteredFolder(results[originalKey], false)
) {
// if current metadata entry is filtered don't save it
filterCounter++;
continue;
}
// for complex types like asset, script, query we need to save the scripts that were extracted from the JSON
if (results[originalKey].json && results[originalKey].codeArr) {
// replace market values with template variable placeholders (do not do it on .codeArr)
if (templateVariables) {
results[originalKey].json = Util.replaceByObject(
results[originalKey].json,
templateVariables
);
results[originalKey].subFolder = Util.replaceByObject(
results[originalKey].subFolder,
templateVariables
);
}
const postRetrieveData = results[originalKey];
if (postRetrieveData.subFolder) {
// very complex types have their own subfolder
baseDir.push(...postRetrieveData.subFolder);
}
// save extracted scripts
for (const script of postRetrieveData.codeArr) {
const dir = [...baseDir];
if (script.subFolder) {
// some files shall be saved in yet a deeper subfolder
dir.push(...script.subFolder);
}
File.writePrettyToFile(
dir,
script.fileName + subtypeExtension,
script.fileExt,
script.content,
templateVariables
);
}
// normalize results[metadataEntry]
results[originalKey] = postRetrieveData.json;
} else {
// not a complex type, run the the entire JSON through templating
// replace market values with template variable placeholders
if (templateVariables) {
results[originalKey] = Util.replaceByObject(
results[originalKey],
templateVariables
);
}
}
// we dont store Id on local disk, but we need it for caching logic,
// so its in retrieve but not in save. Here we put into the clone so that the original
// object used for caching doesnt have the Id removed.
const saveClone = JSON.parse(JSON.stringify(results[originalKey]));
if (!this.definition.keepId) {
delete saveClone[this.definition.idField];
}
if (templateVariables) {
this.keepTemplateFields(saveClone);
} else {
this.keepRetrieveFields(saveClone);
}
savedResults[originalKey] = saveClone;
File.writeJSONToFile(
// manage subtypes
baseDir,
originalKey + subtypeExtension,
saveClone
);
} catch (ex) {
console.log(ex.stack);
Util.metadataLogger('error', this.definition.type, 'saveResults', ex, originalKey);
}
}
if (filterCounter) {
if (this.definition.type !== 'asset') {
// interferes with progress bar in assets and is printed 1-by-1 otherwise
Util.logger.info(
`Filtered ${this.definition.type}: ${filterCounter} (downloaded but not saved to disk)`
);
}
}
return savedResults;
}
/**
* helper for buildDefinition
* handles extracted code if any are found for complex types (e.g script, asset, query)
* @param {string} templateDir Directory where metadata templates are stored
* @param {string} targetDir Directory where built definitions will be saved
* @param {MetadataTypeItem} metadata main JSON file that was read from file system
* @param {Util.TemplateMap} variables variables to be replaced in the metadata
* @param {string} templateName name of the template to be built
* @returns {Promise<void>} Promise
*/
static async buildDefinitionForExtracts(
templateDir,
targetDir,
metadata,
variables,
templateName
) {
// generic version here does nothing. actual cases handled in type classes
return null;
}
/**
* check template directory for complex types that open subfolders for their subtypes
* @param {string} templateDir Directory where metadata templates are stored
* @param {string} templateName name of the metadata file
* @returns {string} subtype name
*/
static findSubType(templateDir, templateName) {
return null;
}
/**
* optional method used for some types to try a different folder structure
* @param {string} templateDir Directory where metadata templates are stored
* @param {string[]} typeDirArr current subdir for this type
* @param {string} templateName name of the metadata template
* @param {string} fileName name of the metadata template file w/o extension
* @param {Error} ex error from first attempt
* @returns {Object} metadata
*/
static async readSecondaryFolder(templateDir, typeDirArr, templateName, fileName, ex) {
// we just want to push the method into the catch here
throw new Error(ex);
}
/**
* Builds definition based on template
* NOTE: Most metadata files should use this generic method, unless custom
* parsing is required (for example scripts & queries)
* @param {string} templateDir Directory where metadata templates are stored
* @param {String|String[]} targetDir (List of) Directory where built definitions will be saved
* @param {string} templateName name of the metadata file
* @param {Util.TemplateMap} variables variables to be replaced in the metadata
* @returns {Promise<{metadata:MetadataTypeMap,type:string}>} Promise of item map
*/
static async buildDefinition(templateDir, targetDir, templateName, variables) {
// retrieve metadata template
let metadataStr;
let typeDirArr = [this.definition.type];
const subType = this.findSubType(templateDir, templateName);
if (subType) {
typeDirArr.push(subType);
}
const suffix = subType ? `-${subType}-meta` : '-meta';
const fileName = templateName + '.' + this.definition.type + suffix;
try {
// ! do not load via readJSONFile to ensure we get a string, not parsed JSON
// templated files might contain illegal json before the conversion back to the file that shall be saved
metadataStr = await File.readFile([templateDir, ...typeDirArr], fileName, 'json');
} catch (ex) {
try {
metadataStr = await this.readSecondaryFolder(
templateDir,
typeDirArr,
templateName,
fileName,
ex
);
} catch (ex) {
throw new Error(
`${this.definition.type}:: Could not find ./${File.normalizePath([
templateDir,
...typeDirArr,
fileName + '.json',
])}.`
);
}
// return;
}
let metadata;
try {
// update all initial variables & create metadata object
metadata = JSON.parse(Mustache.render(metadataStr, variables));
typeDirArr = typeDirArr.map((el) => Mustache.render(el, variables));
} catch (ex) {
throw new Error(
`${this.definition.type}:: Error applying template variables on ${
templateName + '.' + this.definition.type
}${suffix}.json. Please check if your replacement values will result in valid json.`
);
}
// handle extracted code
// run after metadata was templated and converted into JS-object
// templating to extracted content is applied inside of buildDefinitionForExtracts()
await this.buildDefinitionForExtracts(
templateDir,
targetDir,
metadata,
variables,
templateName
);
try {
// write to file
let targetDirArr;
if (!Array.isArray(targetDir)) {
targetDirArr = [targetDir];
} else {
targetDirArr = targetDir;
}
for (const targetDir of targetDirArr) {
File.writeJSONToFile(
[targetDir, ...typeDirArr],
metadata[this.definition.keyField] + '.' + this.definition.type + suffix,
metadata
);
}
Util.logger.info(
'MetadataType[' +
this.definition.type +
'].buildDefinition:: Complete - ' +
metadata[this.definition.keyField]
);
return { metadata: metadata, type: this.definition.type };
} catch (ex) {
throw new Error(`${this.definition.type}:: ${ex.message}`);
}
}
/**
*
* @param {Object} response response payload from REST API
* @returns {void}
*/
static checkForErrors(response) {
if (response && response.res.statusCode >= 400 && response.res.statusCode < 600) {
const errors = [];
if (response.body.errors) {
for (const errMsg of response.body.errors) {
errors.push(errMsg.message.split('<br />').join(''));
}
} else if (response.body.validationErrors) {
for (const errMsg of response.body.validationErrors) {
errors.push(errMsg.message.split('<br />').join(''));
}
} else if (response.body.message) {
errors.push(response.body.message);
} else {
errors.push(`Undefined Errors: ${JSON.stringify(response.body)}`);
}
throw new Error(
`Errors on upserting metadata at ${response.res.request.path}: ${errors.join(
'<br />'
)}`
);
}
}
/**
* Gets metadata cache with limited fields and does not store value to disk
* @param {Util.BuObject} [buObject] properties for auth
* @param {MetadataTypeMap} [metadata] a list of type definitions
* @param {boolean} [isDeploy] used to skip non-supported message during deploy
* @returns {void}
*/
static document(buObject, metadata, isDeploy) {
if (!isDeploy) {
Util.logger.error(`Documenting type ${this.definition.type} is not supported.`);
}
}
/**
* Delete a data extension from the specified business unit
* @param {Util.BuObject} buObject references credentials
* @param {string} customerKey Identifier of data extension
* @returns {void} -
*/
static deleteByKey(buObject, customerKey) {
Util.logger.error(`Deleting type ${this.definition.type} is not supported.`);
}
/**
* Returns metadata of a business unit that is saved locally
* @param {string} readDir root directory of metadata.
* @param {boolean} [listBadKeys=false] do not print errors, used for badKeys()
* @param {Object} [buMetadata] Metadata of BU in local directory
* @returns {Object} Metadata of BU in local directory
*/
static readBUMetadataForType(readDir, listBadKeys, buMetadata) {
buMetadata = buMetadata || {};
readDir = File.normalizePath([readDir, this.definition.type]);
try {
if (File.existsSync(readDir)) {
// check if folder name is a valid metadataType, then check if the user limited to a certain type in the command params
buMetadata[this.definition.type] = this.getJsonFromFS(readDir, listBadKeys);
return buMetadata;
} else {
throw new Error(`Directory '${readDir}' does not exist.`);
}
} catch (ex) {
throw new Error(ex.message);
}
}
} |
JavaScript | class Service {
constructor(host, apiToken, insecure, threshold, operator, unit, type, errorOnMissing, breachOnMissing, interval) {
this.host = host;
this.insecure = insecure;
this.obj = {
apiToken: apiToken,
threshold: threshold,
operator: operator,
unit: unit,
interval: interval,
errorOnMissing: errorOnMissing,
breachOnMissing: breachOnMissing,
type: type,
data: []
}
}
Metric(service, element, qualifier, value) {
const metric = new ServiceMetric(service, element, qualifier, value)
this.obj.data.push(metric);
return metric;
}
Send() {
return new Promise((resolve, reject) => {
try {
const api = new API(this.host, this.insecure);
const result = api.post(URL, this.obj);
this.obj.data = [];
resolve(result);
}
catch(e) {
reject(e);
}
} )
}
} |
JavaScript | class SimpleAlertExampleBlock extends React.Component {
render() {
return (
<View>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
alertMessage,
)}>
<View style={styles.button}>
<Text>Alert with message and default button</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
alertMessage,
[
{text: 'OK', onPress: () => console.log('OK Pressed!')},
]
)}>
<View style={styles.button}>
<Text>Alert with one button</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
alertMessage,
[
{text: 'Cancel', onPress: () => console.log('Cancel Pressed!')},
{text: 'OK', onPress: () => console.log('OK Pressed!')},
]
)}>
<View style={styles.button}>
<Text>Alert with two buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
null,
[
{text: 'Foo', onPress: () => console.log('Foo Pressed!')},
{text: 'Bar', onPress: () => console.log('Bar Pressed!')},
{text: 'Baz', onPress: () => console.log('Baz Pressed!')},
]
)}>
<View style={styles.button}>
<Text>Alert with three buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Foo Title',
alertMessage,
'..............'.split('').map((dot, index) => ({
text: 'Button ' + index,
onPress: () => console.log('Pressed ' + index)
}))
)}>
<View style={styles.button}>
<Text>Alert with too many buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
null,
[
{text: 'OK', onPress: () => console.log('OK Pressed!')},
],
{
cancelable: false
}
)}>
<View style={styles.button}>
<Text>Alert that cannot be dismissed</Text>
</View>
</TouchableHighlight>
</View>
);
}
} |
JavaScript | class Swipe extends Group {
/**
* 统一定位时使用的对象
* @param {(MouseEvent|TouchEvent)} e - 事件对象
* @return {(MouseEvent|Touch)}
* @public
*/
static unify(e) {
return e.changedTouches ? e.changedTouches[0] : e;
}
/**
* 获取尺寸信息
* @param {number} x0 - 起始x坐标
* @param {number} y0 - 起始y坐标
* @param {number} x1 - 结束x坐标
* @param {number} y1 - 结束y坐标
* @return {Dimention} 尺寸信息
* @public
*/
static dimention(x0, y0, x1, y1) {
const dx = x1 - x0;
const dy = y1 - y0;
return {
dx,
dy,
absDx: Math.abs(dx),
absDy: Math.abs(dy),
};
}
/**
* 是否在边缘页且正在向空白部分滑动
* @param {number} length - 总页数
* @param {number} focus - 当前聚焦页编号
* @param {number} dx - 水平方向移动距离
* @return {boolean}
* @public
*/
static isEdge(length, focus, dx) {
return (focus === 1 && dx > 0) || (focus === length && dx < 0);
}
constructor(group = 'main') {
super(group);
/**
* 状态
* @type {Object}
* @property {string} swipe - swipe当前状态
* @property {number} x0 - swipe起始x坐标
* @property {number} y0 - swipe起始y坐标
* @property {number} x1 - swipe当前/结束x坐标
* @property {number} y1 - swipe当前/结束y坐标
*/
this.state = {
swipe: 'end',
x0: 0,
y0: 0,
x1: 0,
y1: 0,
};
}
/**
* 事件调度
* @description 绑定fsm和对象实例,依照fsm信息完成匹配动作
* @param {string} action - fsm输入
* @return {Function}
* @private
*/
dispatch(action) {
/**
* @param {(MouseEvent|TouchEvent)} e - 事件对象
* @ignore
*/
return (e) => {
const { swipe: currentState } = this.state;
const nextState = swipeMachine(currentState)(action);
if (nextState) {
const {
clientX,
clientY,
} = this.constructor.unify(e);
const pos = {
clientX,
clientY,
};
if (nextState === 'start') {
this.swipeStart(pos);
} else if (nextState === 'move') {
this.swipeMove(pos);
} else if (nextState === 'end') {
this.swipeEnd(pos);
}
}
};
}
/**
* 滑动动作开始
* @param {Position} pos - 位置信息
* @protected
* @ignore
*/
swipeStart(pos) {
const {
clientX: x0,
clientY: y0,
} = pos;
this.setState({
swipe: 'start',
x0,
y0,
});
}
/**
* 滑动动作
* @param {Position} pos - 位置信息
* @protected
* @ignore
*/
swipeMove(pos) {
const {
clientX: x1,
clientY: y1,
} = pos;
this.setState({
swipe: 'move',
x1,
y1,
});
}
/**
* 滑动动作结束
* @param {Position} pos - 位置信息
* @protected
* @ignore
*/
swipeEnd(pos) {
const {
clientX: x1,
clientY: y1,
} = pos;
this.setState({
swipe: 'end',
x1,
y1,
});
}
/**
* 触发SWIPESTART事件
* @param {(MouseEvent|TouchEvent)} e - 事件对象
* @public
*/
start(e) {
this.dispatch('SWIPESTART')(e);
}
/**
* 触发SWIPEMOVE事件
* @param {(MouseEvent|TouchEvent)} e - 事件对象
* @public
*/
move(e) {
this.dispatch('SWIPEMOVE')(e);
}
/**
* 触发SWIPEEND事件
* @param {(MouseEvent|TouchEvent)} e - 事件对象
* @public
*/
end(e) {
this.dispatch('SWIPEEND')(e);
}
} |
JavaScript | class VigenereCipheringMachine {
constructor(isDirect) {
if (isDirect === false) {
this.isDirect = false;
}
}
encrypt(message, key) {
if (Object.prototype.toString.call(message) !== "[object String]" && Object.prototype.toString.call(key) !== "[object String]") {
throw Error('');
}
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let square = [];
for (let i = 0; i < alphabet.length; i++) {
square.push(alphabet.slice(i, alphabet.length) + alphabet.slice(0, i));
}
message = message.toUpperCase();
key = key.toUpperCase();
if (message.length > key.length) {
let length = message.length - key.length;
let repeat = (Math.ceil(length / key.length)) + 1;
key = key.repeat(repeat).substr(0, message.length);
} else {
key = key.substr(0, message.length);
}
let index = 0;
let result = '';
for (let i = 0; i < message.length; i++) {
if (alphabet.includes(message[i]) && alphabet.includes(key[index])) {
result += square[alphabet.indexOf(message[i])].charAt(alphabet.indexOf(key[index]));
index++;
} else {
result += message[i];
}
}
if (this.isDirect == false) {
return result.split("").reverse().join("");
} else {
return result;
}
}
decrypt(encryptedMessage, key) {
if (Object.prototype.toString.call(encryptedMessage) !== "[object String]" && Object.prototype.toString.call(key) !== "[object String]") {
throw Error('');
}
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let square = [];
for (let i = 0; i < alphabet.length; i++) {
square.push(alphabet.slice(i, alphabet.length) + alphabet.slice(0, i));
}
encryptedMessage = encryptedMessage.toUpperCase();
key = key.toUpperCase();
if (encryptedMessage.length > key.length) {
let length = encryptedMessage.length - key.length;
let repeat = (Math.ceil(length / key.length)) + 1;
key = key.repeat(repeat).substr(0, encryptedMessage.length);
} else {
key = key.substr(0, encryptedMessage.length);
}
let index = 0;
let result = '';
for (let i = 0; i < encryptedMessage.length; i++) {
if (alphabet.includes(encryptedMessage[i]) && alphabet.includes(key[index])) {
result += alphabet[square[alphabet.indexOf(key[index])].indexOf(encryptedMessage[i])];
index++;
} else {
result += encryptedMessage[i];
}
}
if (this.isDirect == false) {
return result.split("").reverse().join("");
} else {
return result;
}
}
} |
JavaScript | class NavigationBarView extends PureComponent {
static propTypes = {
...NavigationHeader.propTypes,
/**
* The title to display in the navigation bar.
*/
title: PropTypes.string,
/**
* If this prop exists, and has a valid link,
* a share control will be rendered as the right
* component of the navigation bar.
*/
share: PropTypes.shape({
title: PropTypes.string,
text: PropTypes.string,
link: PropTypes.string,
}),
style: PropTypes.object,
useNativeAnimations: PropTypes.bool,
// Whether the navigation bar is rendered inline
// with the screen.
inline: PropTypes.bool,
hidden: PropTypes.bool,
child: PropTypes.bool,
};
static defaultProps = {
// Clear the RN default render functions
renderTitleComponent: () => null,
renderLeftComponent: () => null,
renderRightComponent: () => null,
};
static contextTypes = {
transformProps: PropTypes.func.isRequired,
getNavBarProps: PropTypes.func.isRequired,
};
componentWillReceiveProps(nextProps) {
if (!_.get(nextProps, 'scene.isActive')) {
// Ignore inactive scenes
return;
}
if (this.props.inline || this.props.style !== nextProps.style) {
// We need to refresh the status bar style each
// time the inline navigation bar gets new props.
// This is because there will be multiple instances
// of the navigation bar, and the style will not change
// when the active instance is swapped out.
InteractionManager.runAfterInteractions(() => {
this.cleanupStatusBarStyleListeners();
this.setStatusBarStyle(nextProps.style);
});
}
}
componentWillUnmount() {
this.cleanupStatusBarStyleListeners();
}
hasNavigationBarImage(props = this.props) {
return !!props.navigationBarImage;
}
/**
* Gets the next navigation bar props for a given scene.
*
* @param scene The scene to get the props for.
* @returns {*} The navigation bar props.
*/
getNavBarProps(scene = {}) {
return this.context.getNavBarProps(scene.route);
}
/**
* Gets a navigation bar color for props.
*
* @param colorName The color property name to get.
* @param props The props to get the color from.
* @returns {*} The background color.
*/
getColor(colorName, props) {
const color = _.get(props, `style.container.${colorName}`, 'white');
return getAnimatedStyleValue(color);
}
/**
* Returns the array of previous, current, and next color by getting
* the color with the given name from the props.
*
* @param colorName The name of the color property to get.
* @param props The props to extract the color from.
* @return {*[]} The colors array.
*/
getColors(colorName, ...props) {
return _.map(props, _.partial(this.getColor, colorName));
}
/**
* Determine the iOS status bar style based on the backgroundColor
* of the navigation bar, or the status bar color if provided.
*
* @param color The navigation bar background color.
* @param animated If the color change should be animated, iOS only
*/
resolveStatusBarStyle(color, animated) {
const colorValue = getAnimatedStyleValue(color);
const barStyle = tinyColor(colorValue).isDark() ? 'dark-content' : 'light-content';
StatusBar.setBarStyle(barStyle, animated);
}
setStatusBarStyleIos(statusBarColor, backgroundColor, hasImage) {
if (isAnimatedStyleValue(backgroundColor) && !Device.isIphoneX && !Device.isIphoneXR) {
// If the backgroundColor is animated, we want to listen for
// color changes, so that we can update the bar style as the
// animation runs.
this.backgroundListenerId = addAnimatedValueListener(backgroundColor, () => {
this.resolveStatusBarStyle(backgroundColor);
});
}
// Set the bar style based on the current background color value
hasImage ?
this.resolveStatusBarStyle(statusBarColor, true) :
this.resolveStatusBarStyle(backgroundColor, true);
}
setStatusBarStyleAndroid(containerBackgroundColor, backgroundColor, statusBarStyle = {}) {
// Android cannot resolve interpolated values for animated status bar
// background colors so we fall back to default Android status bar styling
if (isAnimatedStyleValue(containerBackgroundColor)) {
StatusBar.setBackgroundColor('rgba(0, 0, 0, 0.2)');
StatusBar.setBarStyle('default');
} else {
StatusBar.setBackgroundColor(containerBackgroundColor);
}
if (isAnimatedStyleValue(backgroundColor)) {
this.backgroundListenerId = addAnimatedValueListener(backgroundColor, () => {
this.resolveStatusBarStyle(backgroundColor);
});
}
this.resolveStatusBarStyle(backgroundColor, true);
if (!_.isUndefined(statusBarStyle.transluscent)) {
StatusBar.setTranslucent(statusBarStyle.transluscent);
}
}
/**
* Set the status bar style based on the style values provided
* to this component.
*
* @param style The component style.
* @param style.statusBar The status bar style.
*/
setStatusBarStyle(style = {}) {
const { styleName } = this.props;
const statusBarColor = _.get(style, 'statusBar.backgroundColor', '#000');
const statusBarStyle = style.statusBar || {};
const isTransparent = styleName ? styleName.includes('clear') : false;
const hasImage = this.hasNavigationBarImage()
// Determine the bar style based on the background color
// or status bar color as a fallback if the style is not
// specified explicitly.
const containerBackgroundColor = _.get(style, 'container.backgroundColor', '#fff');
const screenBackgroundColor = _.get(style, 'screenBackground', '#fff');
const backgroundColor =
isTransparent ?
screenBackgroundColor :
containerBackgroundColor;
Platform.OS === 'ios' ?
this.setStatusBarStyleIos(statusBarColor, backgroundColor, hasImage) :
this.setStatusBarStyleAndroid(containerBackgroundColor, backgroundColor, statusBarStyle);
}
/**
* Stop listening to animated style changes required to determine
* the status bar style.
*/
cleanupStatusBarStyleListeners() {
if (this.backgroundListenerId) {
// Stop listening to background color changes on the
// old style. The listeners will be registered again,
// if necessary in `setStatusBarStyle`.
removeAnimatedValueListener(
this.props.style.container.backgroundColor,
this.backgroundListenerId,
);
this.backgroundListenerId = null;
}
}
/**
* Manually resolves the next props to match the props that would
* be received by the component during a normal render cycle. This
* usually means that we need t manually apply everything that any
* HOCs do to the props before passing them to this component. We
* currently only resolve the style by using the functions provided by
* the parent StyledComponent.
*
* @param scene The scene to resolve the props for.
* @returns {*} The resolved props.
*/
resolveSceneProps(scene) {
const nextProps = this.getNavBarProps(scene);
return this.context.transformProps(nextProps);
}
/**
* Creates a NavBar interpolation by using timed animations
* instead of relying on the navigation position animated value.
* This is a workaround in situations when native animations are
* used, because color animations are not supported by native
* animation driver at the moment.
*
* @param previousProps The props of the previous scene.
* @param currentProps The props of the current scene.
* @returns {*} The interpolated style.
*/
createFallbackNavBarInterpolation(previousProps, currentProps) {
// Use 250ms as transition duration
const driver = new TimingDriver({ duration: 250 });
driver.runTimer(1);
return {
backgroundColor: driver.value.interpolate({
inputRange: [0, 1],
outputRange: this.getColors('backgroundColor', previousProps, currentProps),
extrapolate: 'clamp',
}),
borderBottomColor: driver.value.interpolate({
inputRange: [0, 1],
outputRange: this.getColors('borderBottomColor', previousProps, currentProps),
extrapolate: 'clamp',
}),
};
}
/**
* Creates the interpolated style in order to animate the
* navigation bar transition between the current one, and
* the surrounding scenes.
* @returns {*} The animated style.
*/
interpolateNavBarStyle() {
const { position, scene, scenes } = this.props;
const { index } = scene;
const positionValue = getAnimatedStyleValue(position);
if (positionValue === index) {
// We are not in a transition, do not override the
// default style to allow any custom animations that
// the screen may want to perform on the NavigationBar
return {};
} else if (this.props.inline) {
// The navigation bar is rendered inline with the screen,
// it will be animated together with the screen, so there
// is no need for custom animations in this case.
return {};
}
// resolveSceneProps will return the latest version of the props
// from the parent component. This is necessary to perform the
// animations to the final state of the navigation bar. Otherwise
// we are often getting various delays and flickers during transitions.
const currentProps = this.resolveSceneProps(scene);
if (this.props.useNativeAnimations) {
// Some animations are not yet implemented in native, so we
// create JS animations here instead.
// The position will start at the index of the active scene,
// and the index will be the index of the scene that will become active.
const previousProps = this.resolveSceneProps(scenes[positionValue]);
return this.createFallbackNavBarInterpolation(previousProps, currentProps);
}
const previousProps = this.resolveSceneProps(scenes[index - 1]);
const nextProps = this.resolveSceneProps(scenes[index + 1]);
return {
backgroundColor: position.interpolate({
inputRange: [index - 1, index, index + 1],
outputRange: this.getColors('backgroundColor', previousProps, currentProps, nextProps),
extrapolate: 'clamp',
}),
borderBottomColor: position.interpolate({
inputRange: [index - 1, index, index + 1],
outputRange: this.getColors('borderBottomColor', previousProps, currentProps, nextProps),
extrapolate: 'clamp',
}),
};
}
/**
* Wraps the header component render function in a wrapper that
* exposes the navBarProps to the wrapped functions.
*
* @param renderer The function to wrap.
* @return {function(*): *} The wrapped renderer function.
*/
createHeaderComponentRenderer(renderer) {
return (props) => renderer({
...props,
navBarProps: this.props,
});
}
createNavigationHeaderProps(style) {
const headerProps = {
...this.props,
style: [navigationHeaderStyle, style.navigationHeader],
};
if (headerProps.renderLeftComponent) {
headerProps.renderLeftComponent =
this.createHeaderComponentRenderer(headerProps.renderLeftComponent);
}
if (headerProps.renderTitleComponent) {
headerProps.renderTitleComponent =
this.createHeaderComponentRenderer(headerProps.renderTitleComponent);
}
if (headerProps.renderRightComponent) {
headerProps.renderRightComponent =
this.createHeaderComponentRenderer(headerProps.renderRightComponent);
}
return headerProps;
}
renderLinearGradient() {
const { style, animationName } = this.props;
const animation = _.has(style.gradient, `${animationName}Animation`) ?
animationName : '';
if (style.gradient) {
return (
<LinearGradient
animationName={animation}
style={style.gradient}
/>
);
}
return null;
}
renderBackground() {
const { renderBackground } = this.props;
if (renderBackground) {
return renderBackground(this.props);
}
return null;
}
render() {
const { scene } = this.props;
const { style, hidden, child } = this.resolveSceneProps(scene);
if (hidden || child) {
// Navigation bar is explicitly hidden, or it just
// overrides props of a child navigation bar.
return null;
}
return (
<Animated.View style={[style.container, this.interpolateNavBarStyle()]}>
{this.renderBackground()}
{this.renderLinearGradient()}
<NavigationHeader
{...this.createNavigationHeaderProps(style)}
/>
</Animated.View>
);
}
} |
JavaScript | class FirebaseAuth {
constructor() {
this.accessToken = null;
this.user = null;
this.provider = new firebase.auth.GithubAuthProvider();
this.provider.addScope('gist');
firebase.initializeApp({
apiKey: 'AIzaSyApMz8FHTyJNqqUtA51tik5Mro8j-2qMcM',
authDomain: 'lighthouse-viewer.firebaseapp.com',
databaseURL: 'https://lighthouse-viewer.firebaseio.com',
storageBucket: 'lighthouse-viewer.appspot.com',
messagingSenderId: '962507201498'
});
// Wrap auth state callback in a promise so other parts of the app that
// require login can hook into the changes.
this.ready = new Promise((resolve, reject) => {
firebase.auth().onAuthStateChanged(user => {
idb.get('accessToken').then(token => {
if (user && token) {
this.accessToken = token;
this.user = user;
}
resolve(user);
});
});
});
}
getAccessToken() {
return this.accessToken ? Promise.resolve(this.accessToken) : this.signIn();
}
/**
* Signs in the user to Github using the Firebase API.
* @return {!Promise<string>} The logged in user.
*/
signIn() {
return firebase.auth().signInWithPopup(this.provider).then(result => {
this.accessToken = result.credential.accessToken;
this.user = result.user;
// A limitation of firebase auth is that it doesn't return an oauth token
// after a page refresh. We'll get a firebase token, but not an oauth token
// for GH. Since GH's tokens never expire, stash the access token in IDB.
return idb.set('accessToken', this.accessToken).then(_ => {
return this.accessToken;
});
});
}
/**
* Signs the user out.
* @return {!Promise}
*/
signOut() {
return firebase.auth().signOut().then(_ => {
this.accessToken = null;
return idb.delete('accessToken');
});
}
} |
JavaScript | class Modal extends Component {
static propTypes = {
buttons: PropTypes.arrayOf(PropTypes.object),
className: PropTypes.string,
headerClassName: PropTypes.string,
icon: PropTypes.string,
message: PropTypes.node,
style: PropTypes.object,
title: PropTypes.node,
onClose: PropTypes.func,
};
static defaultProps = {
buttons: [{ label: 'OK', className: 'Btn--secondary' }],
className: '',
headerClassName: '',
onClose() {},
};
render() {
let {
className,
style,
title,
icon,
headerClassName,
message,
buttons,
onClose,
} = this.props;
return (
<div className={'Modal ' + className} style={style}>
<div className="Modal-box">
<header className={'Modal-header ' + headerClassName}>
{icon && <Icon className="Icon--mR" glyph={icon} />}
<h3 className="Modal-title">{title}</h3>
</header>
<div className="Modal-message">
{typeof message === 'string'
? message
.split(/\s*\n\s*/)
.map((line, i) => <p key={i}>{line}</p>)
: message}
</div>
<footer className="Modal-footer">
{buttons.map((btn, i) => (
<Btn
key={i}
className={'Btn--plain ' + (btn.className || '')}
onClick={() => {
btn.action && btn.action();
onClose();
}}
>
{btn.label}
</Btn>
))}
</footer>
</div>
</div>
);
}
} |
JavaScript | class ViewerImageAPI {
constructor(imagedata) {
this.images = [];
// iterate over images
imagedata.forEach((elem, index) => { this.images.push(new ViewerImage(elem, index)) });
this.currentImageId; // initially set in ViewerFloorAPI:const, updated in ViewerPanoAPI:display
}
get currentImage() {
return this.images[this.currentImageId];
}
all(callback) {
// Get all panorama images.
// Parameters: Function called with all images ([ViewerImage]): Array of panorama images
callback(this.images);
}
changed() {
// Signal changed image data (e.g. hidden flag) to the viewer.
}
get get() {
// Get the currently displayed panorama image.
return this.currentImage();
}
calcImagesInPanoSphere(radius, viewerAPI) {
if (this.currentImage.imagesInRadius != null) return this.currentImage.imagesInRadius; // already calculated
this.currentImage.imagesInRadius = [];
const currGlobalPos = this.currentImage.pos;
const currLocalPos = viewerAPI.toLocal([currGlobalPos[0], currGlobalPos[1], currGlobalPos[2]]);
viewerAPI.floor.currentFloor.viewerImages.forEach(element => {
const loopLocalPos = viewerAPI.toLocal(element.pos);
const [dx, dy] = [currLocalPos.x - loopLocalPos.x, currLocalPos.y - loopLocalPos.y];
const currDistance = Math.sqrt(dx * dx + dy * dy);
if (currDistance <= radius) {
this.currentImage.imagesInRadius.push(element);
}
});
if (this.currentImage.imagesInRadius == []) {
console.error("No other positions found in sphere radius");
}
return this.currentImage.imagesInRadius;
}
} |
JavaScript | class ProductDetailResponse {
/**
* The detail records retrieved for the student based on the sorting, filtering and paging values.
*/
details;
/**
* The total number of detail records that exist for the student.
* NOTE: this is not the number of detail records retrieved.
*/
totalDetails;
constructor(details, totalDetails) {
this.details = details;
this.totalDetails = totalDetails;
}
} |
JavaScript | class GseClient extends AbstractClient {
constructor(credential, region, profile) {
super("gse.tencentcloudapi.com", "2019-11-12", credential, region, profile);
}
/**
* 用于查询服务部署的动态扩缩容配置
* @param {DescribeScalingPoliciesRequest} req
* @param {function(string, DescribeScalingPoliciesResponse):void} cb
* @public
*/
DescribeScalingPolicies(req, cb) {
let resp = new DescribeScalingPoliciesResponse();
this.request("DescribeScalingPolicies", req, resp, cb);
}
/**
* 用于查询服务器实例列表
* @param {DescribeInstancesRequest} req
* @param {function(string, DescribeInstancesResponse):void} cb
* @public
*/
DescribeInstances(req, cb) {
let resp = new DescribeInstancesResponse();
this.request("DescribeInstances", req, resp, cb);
}
/**
* 本接口(DescribeGameServerSessions)用于查询游戏服务器会话列表
* @param {DescribeGameServerSessionsRequest} req
* @param {function(string, DescribeGameServerSessionsResponse):void} cb
* @public
*/
DescribeGameServerSessions(req, cb) {
let resp = new DescribeGameServerSessionsResponse();
this.request("DescribeGameServerSessions", req, resp, cb);
}
/**
* 获取实例登录所需要的凭据
* @param {GetInstanceAccessRequest} req
* @param {function(string, GetInstanceAccessResponse):void} cb
* @public
*/
GetInstanceAccess(req, cb) {
let resp = new GetInstanceAccessResponse();
this.request("GetInstanceAccess", req, resp, cb);
}
/**
* 本接口(JoinGameServerSession)用于加入游戏服务器会话
* @param {JoinGameServerSessionRequest} req
* @param {function(string, JoinGameServerSessionResponse):void} cb
* @public
*/
JoinGameServerSession(req, cb) {
let resp = new JoinGameServerSessionResponse();
this.request("JoinGameServerSession", req, resp, cb);
}
/**
* 本接口(DescribeGameServerSessionPlacement)用于查询游戏服务器会话的放置
* @param {DescribeGameServerSessionPlacementRequest} req
* @param {function(string, DescribeGameServerSessionPlacementResponse):void} cb
* @public
*/
DescribeGameServerSessionPlacement(req, cb) {
let resp = new DescribeGameServerSessionPlacementResponse();
this.request("DescribeGameServerSessionPlacement", req, resp, cb);
}
/**
* 本接口(DescribeGameServerSessionDetails)用于查询游戏服务器会话详情列表
* @param {DescribeGameServerSessionDetailsRequest} req
* @param {function(string, DescribeGameServerSessionDetailsResponse):void} cb
* @public
*/
DescribeGameServerSessionDetails(req, cb) {
let resp = new DescribeGameServerSessionDetailsResponse();
this.request("DescribeGameServerSessionDetails", req, resp, cb);
}
/**
* 用于设置动态扩缩容配置
* @param {PutScalingPolicyRequest} req
* @param {function(string, PutScalingPolicyResponse):void} cb
* @public
*/
PutScalingPolicy(req, cb) {
let resp = new PutScalingPolicyResponse();
this.request("PutScalingPolicy", req, resp, cb);
}
/**
* 本接口(StartGameServerSessionPlacement)用于开始放置游戏服务器会话
* @param {StartGameServerSessionPlacementRequest} req
* @param {function(string, StartGameServerSessionPlacementResponse):void} cb
* @public
*/
StartGameServerSessionPlacement(req, cb) {
let resp = new StartGameServerSessionPlacementResponse();
this.request("StartGameServerSessionPlacement", req, resp, cb);
}
/**
* 设置服务器权重
* @param {SetServerWeightRequest} req
* @param {function(string, SetServerWeightResponse):void} cb
* @public
*/
SetServerWeight(req, cb) {
let resp = new SetServerWeightResponse();
this.request("SetServerWeight", req, resp, cb);
}
/**
* 本接口(UpdateGameServerSession)用于更新游戏服务器会话
* @param {UpdateGameServerSessionRequest} req
* @param {function(string, UpdateGameServerSessionResponse):void} cb
* @public
*/
UpdateGameServerSession(req, cb) {
let resp = new UpdateGameServerSessionResponse();
this.request("UpdateGameServerSession", req, resp, cb);
}
/**
* 本接口(StopGameServerSessionPlacement)用于停止放置游戏服务器会话
* @param {StopGameServerSessionPlacementRequest} req
* @param {function(string, StopGameServerSessionPlacementResponse):void} cb
* @public
*/
StopGameServerSessionPlacement(req, cb) {
let resp = new StopGameServerSessionPlacementResponse();
this.request("StopGameServerSessionPlacement", req, resp, cb);
}
/**
* 本接口(DescribePlayerSessions)用于获取玩家会话列表
* @param {DescribePlayerSessionsRequest} req
* @param {function(string, DescribePlayerSessionsResponse):void} cb
* @public
*/
DescribePlayerSessions(req, cb) {
let resp = new DescribePlayerSessionsResponse();
this.request("DescribePlayerSessions", req, resp, cb);
}
/**
* 本接口(GetGameServerSessionLogUrl)用于获取游戏服务器会话的日志URL
* @param {GetGameServerSessionLogUrlRequest} req
* @param {function(string, GetGameServerSessionLogUrlResponse):void} cb
* @public
*/
GetGameServerSessionLogUrl(req, cb) {
let resp = new GetGameServerSessionLogUrlResponse();
this.request("GetGameServerSessionLogUrl", req, resp, cb);
}
/**
* 本接口(SearchGameServerSessions)用于搜索游戏服务器会话列表
* @param {SearchGameServerSessionsRequest} req
* @param {function(string, SearchGameServerSessionsResponse):void} cb
* @public
*/
SearchGameServerSessions(req, cb) {
let resp = new SearchGameServerSessionsResponse();
this.request("SearchGameServerSessions", req, resp, cb);
}
/**
* 用于删除扩缩容配置
* @param {DeleteScalingPolicyRequest} req
* @param {function(string, DeleteScalingPolicyResponse):void} cb
* @public
*/
DeleteScalingPolicy(req, cb) {
let resp = new DeleteScalingPolicyResponse();
this.request("DeleteScalingPolicy", req, resp, cb);
}
/**
* 本接口(CreateGameServerSession)用于创建游戏服务会话
* @param {CreateGameServerSessionRequest} req
* @param {function(string, CreateGameServerSessionResponse):void} cb
* @public
*/
CreateGameServerSession(req, cb) {
let resp = new CreateGameServerSessionResponse();
this.request("CreateGameServerSession", req, resp, cb);
}
/**
* 本接口(DescribeGameServerSessionQueues)用于查询游戏服务器会话队列
* @param {DescribeGameServerSessionQueuesRequest} req
* @param {function(string, DescribeGameServerSessionQueuesResponse):void} cb
* @public
*/
DescribeGameServerSessionQueues(req, cb) {
let resp = new DescribeGameServerSessionQueuesResponse();
this.request("DescribeGameServerSessionQueues", req, resp, cb);
}
} |
JavaScript | class DeleteItem extends Component {
_confirm = () => {
this.props.cancelDelete();
if (this.props.after_path) this.props.history.push(this.props.after_path);
else this.props.refetch();
};
render() {
const { classes } = this.props;
let name = '';
let chosen_mutation = '';
switch (this.props.type) {
case 'job':
name = this.props.item.name;
chosen_mutation = DELETE_JOB;
break;
case 'part':
name = this.props.item.name;
chosen_mutation = DELETE_PART;
break;
case 'note':
name = this.props.item.title;
chosen_mutation = DELETE_NOTE;
break;
case 'client':
if (this.props.item.businessName) name = this.props.item.businessName;
else name = `${this.props.item.firstName} ${this.props.item.lastName}`;
chosen_mutation = DELETE_CLIENT;
break;
default:
break;
}
return (
<Paper className={classes.paper}>
<Grid container>
<Grid item xs={10} className={classes.delete}>
<Typography variant='h6' paragraph>
Are you sure you want to delete {name}?
</Typography>
</Grid>
<Grid item xs={10} className={classes.delete}>
<Grid container justify='space-around'>
<Mutation
mutation={chosen_mutation}
variables={{ id: this.props.item.id }}
onCompleted={(data) => this._confirm(data)}
>
{(mutation) => (
<Button
variant='contained'
color='secondary'
onClick={mutation}
type='submit'
>
Delete
</Button>
)}
</Mutation>
<Button
variant='contained'
color='primary'
onClick={this.props.cancelDelete}
>
Cancel
</Button>
</Grid>
</Grid>
</Grid>
</Paper>
);
}
} |
JavaScript | class Scene extends PIXI.Application {
constructor(width, height, renderOptions, noWebGL) {
super(width, height, renderOptions, noWebGL);
/**
* Reference to the global sound object
* @name PIXI.animate.Scene#sound
* @type {PIXI.animate.sound}
* @readOnly
*/
this.sound = sound;
/**
* The stage object created.
* @name PIXI.animate.Scene#instance
* @type {PIXI.animate.MovieClip}
* @readOnly
*/
this.instance = null;
}
/**
* Load a stage scene and add it to the stage.
* @method PIXI.animate.Scene#load
* @param {Function} StageRef Reference to the stage class.
* @param {Function} [complete] Callback when finished loading.
* @param {String} [basePath] Optional base directory to prepend to assets.
* @return {PIXI.loaders.Loader} instance of PIXI resource loader
*/
load(StageRef, complete, basePath) {
return load(StageRef, this.stage, (instance) => {
this.instance = instance;
if (complete) {
complete(instance);
}
}, basePath);
}
/**
* Destroy and don't use after calling.
* @method PIXI.animate.Scene#destroy
* @param {Boolean} [removeView=false] `true` to remove canvas element.
*/
destroy(removeView) {
if (this.instance) {
this.instance.destroy(true);
this.instance = null;
}
super.destroy(removeView);
}
} |
JavaScript | class AppSearchBar extends Component {
constructor() {
super();
this.state = {
value: '',
};
}
onChange = (event, { newValue }) => {
this.setState({
value: newValue
});
};
render() {
const { value, suggestions } = this.state;
// Autosuggest will pass through all these props to the input.
const inputProps = {
placeholder: 'Search for ...',
value,
onChange: this.onChange
}
return (
<div>
</div>
);
}
} |
JavaScript | class ClientRequestCache {
/**
* @param ttl {Number} How old a result can be before it gets expired.
* @param size {Number} How many results to store before we trim.
* @param requestFunc The function to use on cache miss.
*/
constructor (ttl, size, requestFunc) {
if (!Number.isInteger(ttl) || ttl <= 0) {
throw Error("'ttl' must be greater than 0");
}
if (!Number.isInteger(size) || ttl <= 0) {
throw Error("'size' must be greater than 0");
}
if (typeof(requestFunc) !== "function") {
throw Error("'requestFunc' must be a function");
}
this._requestContent = new Map(); // key => {ts, content}
this.requestFunc = requestFunc;
this.ttl = ttl;
this.maxSize = size;
}
/**
* Gets a result of a request from the cache, or otherwise
* tries to fetch the the result with this.requestFunc
*
* @param {string}} key Key of the item to get/store.
* @param {any[]} args A set of arguments to pass to the request func.
* @returns {Promise} The request, or undefined if not retrievable.
* @throws {Error} If the key is not a string.
*/
get(key, ...args) {
if (typeof(key) !== "string") {
throw Error("'key' must be a string");
}
const cachedResult = this._requestContent.get(key);
if (cachedResult !== undefined && cachedResult.ts >= Date.now() - this.ttl) {
return cachedResult.content;
}
// Delete the old req.
this._requestContent.delete(key);
return new Promise((resolve, reject) => {
resolve(this.requestFunc.apply(null, [key].concat(args)))
}).then((result) => {
if (result !== undefined) {
this._requestContent.set(key, {
ts: Date.now(),
content: result,
});
if (this._requestContent.size > this.maxSize) {
const oldKey = this._requestContent.keys().next().value;
this._requestContent.delete(oldKey);
}
}
return result;
});
// Not catching here because we want to pass
// through any failures.
}
/**
* Clone the current request result cache, mapping keys to their cache records.
* @returns {Map<string,any>}
*/
getCachedResults() {
return new Map(this._requestContent);
}
/**
* @callback requestFunc
* @param {any[]} args A set of arguments passed from get().
* @param {string} key The key for the cached item.
*/
} |
JavaScript | class DefaultMember extends Node {
constructor(member, location) {
super();
this.type = 'default-member';
this.member = member;
this.location = location;
}
transpile() {
return this.member;
}
compile(o) {
return this.sourceNode(o.file, this.member);
}
} |
JavaScript | class Player {
constructor(name, cost) {
this.name = name;
this.cost = cost;
}
} |
JavaScript | class TextInclude {
get linkEntityKind() {
return 'LINK';
}
get tagEntityKind() {
return 'TAG';
}
get userEntityKind() {
return 'USER';
}
get linkEntityKindShort() {
return 'l';
}
get tagEntityKindShort() {
return 't';
}
get userEntityKindShort() {
return 'u';
}
get kinds() {
const oThis = this;
return {
'1': oThis.linkEntityKind,
'2': oThis.tagEntityKind,
'3': oThis.userEntityKind
};
}
get invertedKinds() {
const oThis = this;
invertedKinds = invertedKinds || util.invert(oThis.kinds);
return invertedKinds;
}
get shortToLongNamesMap() {
return {
text_id: 'textId',
entity_identifier: 'entityIdentifier',
replaceable_text: 'replaceableText'
};
}
get longToShortNamesMap() {
const oThis = this;
longToShortNamesMap = longToShortNamesMap || util.invert(oThis.shortToLongNamesMap);
return longToShortNamesMap;
}
get shortToLongNamesMapForEntityKind() {
const oThis = this;
return {
[oThis.linkEntityKind]: oThis.linkEntityKindShort,
[oThis.tagEntityKind]: oThis.tagEntityKindShort,
[oThis.userEntityKind]: oThis.userEntityKindShort
};
}
get longToShortNamesMapForEntityKind() {
const oThis = this;
longToShortNamesForEntityKindsMap =
longToShortNamesForEntityKindsMap || util.invert(oThis.shortToLongNamesMapForEntityKind);
return longToShortNamesForEntityKindsMap;
}
/**
* Create entity identifier to find entity kind and id.
*
* @param entityKind
* @param entityId
* @returns {string}
*/
createEntityIdentifier(entityKind, entityId) {
return entityKind + '_' + entityId;
}
} |
JavaScript | class Presentation extends React.Component {
constructor(props) {
super(props);
// Create global message list
this.messageList = new MessageListModel();
// Create global websocket connection
this.remoteDispatcher = new RemoteDispatcher((getConnectionConfiguration()));
}
// Make messageList available in the tree
getChildContext() {
return {
remoteDispatcher: this.remoteDispatcher,
messageList: this.messageList,
};
}
componentDidMount() {
// Try to update the title
if (this.props.notebook) {
replaceIdWithSlug(this.props.notebook.get('id'), this.props.notebook.get('slug'));
const title = this.props.notebook.getIn(['metadata', 'title'], 'Ohne Titel');
document.title = `${title} - trycoding`;
}
}
/**
* Renders a cell depending on its "cell_type". Any unknown types will be rendered as empty text (no content!).
*
* @param {Object} cell - cell to render
* @param {Number} index - current index of cell in the document
* @param {Object} notebook - notebook object
* @returns {React.Component} - returns react component representing cell
* @memberof Presentation
*/
renderCell(cell, index, notebook) {
const id = cell.get('id');
const activeBlock = -1;
const isEditModeActive = false;
const dispatch = this.props.dispatch;
const isVisible = cell.getIn(['metadata', 'isVisible'], true);
let height;
let lang;
let executionLanguage;
let notebookLanguageInformation;
let embedType;
let source = sourceFromCell(cell);
// Do not render the cell, if it is hidden!
if (isVisible === false) {
return null;
}
// Push cell
switch (cell.get('cell_type')) {
case 'markdown':
return toMarkdownComponent({source: source, key: id});
case 'code':
notebookLanguageInformation = notebookMetadataToSourceboxLanguage(notebook.get('metadata'));
lang = cell.getIn(['metadata', 'mode'], notebookLanguageInformation.languageName);
executionLanguage = cell.getIn(['metadata', 'executionLanguage'], notebookLanguageInformation.executionLanguage);
embedType = cell.getIn(['metadata', 'embedType'], notebook.get('embedType'));
return <CodeCellView key={id} className="present-mode" viewComponent={Highlight} code={source} cell={cell} executionLanguage={{executionLanguage: executionLanguage}} notebookLanguage={lang} embedType={embedType}/>;
/*return (
<Window title={lang}>
<CodeCellView className="present-mode" viewComponent={Highlight} code={source} cell={cell} executionLanguage={{executionLanguage: executionLanguage}} notebookLanguage={lang} embedType={embedType}/>
</Window>
);*/
case 'codeembed':
height = parseInt(cell.getIn(['metadata', 'height'], 350), 10);
height = isNaN(height) ? 350 : height;
return <CodeEmbedCell style={{textAlign: 'center'}} /*course={course}*/ className="present-mode" dispatch={dispatch} key={id} cellIndex={index} id={id} cell={cell} isEditModeActive={isEditModeActive} editing={index === activeBlock}/>;
case 'raw':
return <RawCell dispatch={dispatch} cellIndex={index} key={id} id={id} cell={cell} isEditModeActive={isEditModeActive} editing={id === activeBlock}/>;
default:
// Should only occur for some flawed notebook files
return <Text></Text>;
}
}
/**
* Renders the cells to slides depending on the given "slide_type" in the metadata.
*
* @returns {array} tree of slides and their content
*/
renderSlides() {
let i;
//let bgColor;
let cell;
let children = [];
const slides = [];
//let slideCell;
let renderResult;
const cells = this.props.notebook.get('cells');
const cellOrder = this.props.notebook.get('cellOrder');
let slideType;
let isInSlide = false;
let slideCounter = 0;
let isVisible;
// Dynamically create slides, depending on the slide_type in the metadata
for (i = 0; i < cellOrder.size; i++) {
cell = cells.get(cellOrder.get(i)); // Get current cell
isVisible = cell.getIn(['metadata', 'isVisible'], true);
// Skip invisible cells from rendering an empty slide
if (isVisible === false) {
continue;
}
slideType = cell.getIn(['metadata', 'slideshow', 'slide_type'], 'slide');
//console.info('bgColor:', bgColor, slideCounter, slideType);
// start new slide
if (isInSlide === false && slideType === 'slide') {
children.push(this.renderCell(cell, i, this.props.notebook)); //Render current cell and add to children
isInSlide = true;
} else if (isInSlide === true && slideType === 'slide') {
// End current slide and start new one
slideCounter += 1;
//let bgColor = slideCell.getIn(['metadata', 'slideshow', 'bgColor'], 'primary');
slides.push(<Slide /*bgColor={bgColor}*/ transition={[]} maxHeight={maxHeight} maxWidth={maxWidth} key={`slide-${slideCounter}`}>{children}</Slide>);
children = []; // reset children
children.push(this.renderCell(cell, i, this.props.notebook)); // add first new child
} else {
// Add all cells execept skip (and slide, which is handled above)
if (slideType !== 'skip') {
renderResult = this.renderCell(cell, i, this.props.notebook);
// Fragments are wrapped with the Appear Tag
if (slideType === 'fragment') {
children.push(<Appear key={`slide-${slideCounter}-appear-${i}`}><div>{renderResult}</div></Appear>);
} else {
children.push(renderResult);
}
}
}
}
// Final Slide
if (isInSlide === true) {
slideCounter += 1;
//let bgColor = slideCell.getIn(['metadata', 'slideshow', 'bgColor'], 'primary');
slides.push(<Slide /*bgColor={bgColor}*/ transition={[]} maxHeight={maxHeight} maxWidth={maxWidth} key={`slide-${slideCounter}`}>{children}</Slide>);
}
return slides;
}
render() {
const slides = this.renderSlides();
if (slides.length > 0) {
return (
<div>
<div className="global-message-list">
<MessageList messageList={this.messageList} />
</div>
<Deck theme={theme} progress="number" transition={[]} transitionDuration={200}>
{ slides }
</Deck>
</div>
);
} else {
return <p>Keine Folien vorhanden. Sie müssen ggf. die Metadaten der ersten Zelle bearbeiten.</p>;
}
}
} |
JavaScript | class Contacts {
constructor (client) {
this._client = client;
}
/**
* Lists the contacts in the account.
*
* @see https://developer.dnsimple.com/v2/contacts/#list
*
* @example List contacts in the first page
* client.contacts.listContacts(1010).then(function(response) {
* // handle response
* }, function(error) {
* // handle error
* });
*
* @example List contacts, provide a specific page
* client.contacts.listContacts(1010, {page: 2}).then(function(response) {
* // handle response
* }, function(error) {
* // handle error
* });
*
* @example List contacts, provide a sorting policy
* client.contacts.listContacts(1010, {sort: 'email:asc'}).then(function(response) {
* // handle response
* }, function(error) {
* // handle error
* });
*
* @param {number} accountId The account ID
* @param {Object} [options] The filtering and sorting options
* @param {number} [options.page] The current page number
* @param {number} [options.per_page] The number of items per page
* @param {string} [options.sort] The sort definition in the form `key:direction`
* @return {Promise}
*/
listContacts (accountId, options = {}) {
return this._client.get(`/${accountId}/contacts`, options);
}
/**
* List ALL the contacts in the account.
*
* This method is similar to {#listContacts}, but instead of returning the results of a
* specific page it iterates all the pages and returns the entire collection.
*
* Please use this method carefully, as fetching the entire collection will increase the
* number of requests you send to the API server and you may eventually risk to hit the
* throttle limit.
*
* @example List all contacts
* client.contacts.allContacts(1010).then(function(contacts) {
* // use contacts list
* }, function(error) {
* // handle error
* });
*
* @example List contacts, provide a sorting policy
* client.contacts.allContacts(1010, {sort: 'name:asc'}).then(function(contacts) {
* // use contacts list
* }, function(error) {
* // handle error
* });
*
* @param {number} accountId The account ID
* @param {Object} [options] The filtering and sorting options
* @param {string} [options.sort] The sort definition in the form `key:direction`
* @return {Promise}
*/
allContacts (accountId, options = {}) {
return new Paginate(this).paginate(this.listContacts, [accountId, options]);
}
/**
* Get a specific contact associated to an account using the contact's ID.
*
* @see https://developer.dnsimple.com/v2/contacts/#get
*
* @param {number} accountId The account ID
* @param {number} contactId The contact ID
* @param {Object} [options]
* @return {Promise}
*/
getContact (accountId, contactId, options = {}) {
return this._client.get(`/${accountId}/contacts/${contactId}`, options);
}
/**
* Create a contact in the account.
*
* @see https://developer.dnsimple.com/v2/contacts/#create
*
* @param {number} accountId The account ID
* @param {Object} attributes The contact attributes
* @param {Object} [options]
* @return {Promise}
*/
createContact (accountId, attributes, options = {}) {
return this._client.post(`/${accountId}/contacts`, attributes, options);
}
/**
* Update a contact in the account.
*
* @see https://developer.dnsimple.com/v2/contacts/#update
*
* @param {number} accountId The account ID
* @param {number} contactId The contact ID
* @param {Object} attributes The updated contact attributes
* @param {Object} [options]
* @return {Promise}
*/
updateContact (accountId, contactId, attributes, options = {}) {
return this._client.patch(`/${accountId}/contacts/${contactId}`, attributes, options);
}
/**
* Delete a contact from the account.
*
* @see https://developer.dnsimple.com/v2/contacts/#delete
*
* @param {number} accountId The account ID
* @param {number} contactId The contact ID
* @param {Object} [options]
* @return {Promise}
*/
deleteContact (accountId, contactId, options = {}) {
return this._client.delete(`/${accountId}/contacts/${contactId}`, options);
}
} |
JavaScript | class Invoke extends base_1.Node {
/**
* @param code External callback or intrinsic code. Can be created with
* `builder.code.*()` methods.
* @param map Map from callback return codes to target nodes
*/
constructor(code, map) {
super('invoke_' + code.name);
this.code = code;
Object.keys(map).forEach((mapKey) => {
const numKey = parseInt(mapKey, 10);
const targetNode = map[numKey];
assert.strictEqual(numKey, numKey | 0, 'Invoke\'s map keys must be integers');
this.addEdge(new edge_1.Edge(targetNode, true, numKey, undefined));
});
}
} |
JavaScript | class Store {
constructor() {
this.lineItems = [];
this.products = {};
this.productsFetchPromise = null;
this.displayPaymentSummary();
}
// Compute the total for the payment based on the line items (SKUs and quantity).
getPaymentTotal() {
return Object.values(this.lineItems).reduce(
(total, {product, sku, quantity}) =>
total + quantity * this.products[product].skus.data[0].price,
0
);
}
// Expose the line items for the payment using products and skus stored in Stripe.
getLineItems() {
let items = [];
this.lineItems.forEach(item =>
items.push({
type: 'sku',
parent: item.sku,
quantity: item.quantity,
})
);
return items;
}
// Retrieve the configuration from the API.
async getConfig() {
try {
const response = await fetch('/config');
const config = await response.json();
if (config.stripePublishableKey.includes('live')) {
// Hide the demo notice if the publishable key is in live mode.
document.querySelector('#order-total .demo').style.display = 'none';
}
return config;
} catch (err) {
return {error: err.message};
}
}
// Retrieve a SKU for the Product where the API Version is newer and doesn't include them on v1/product
async loadSkus(product_id) {
try {
const response = await fetch(`/products/${product_id}/skus`);
const skus = await response.json();
this.products[product_id].skus = skus;
} catch (err) {
return {error: err.message};
}
}
// Load the product details.
loadProducts() {
if (!this.productsFetchPromise) {
this.productsFetchPromise = new Promise(async resolve => {
const productsResponse = await fetch('/products');
const products = (await productsResponse.json()).data;
if (!products.length) {
throw new Error(
'No products on Stripe account! Make sure the setup script has run properly.'
);
}
// Check if we have SKUs on the product, otherwise load them separately.
for (const product of products) {
this.products[product.id] = product;
if (!product.skus) {
await this.loadSkus(product.id);
}
}
resolve();
});
}
return this.productsFetchPromise;
}
// Create the PaymentIntent with the cart details.
async createPaymentIntent(currency, items) {
try {
const response = await fetch('/payment_intents', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
currency,
items,
}),
});
const data = await response.json();
if (data.error) {
return {error: data.error};
} else {
return data;
}
} catch (err) {
return {error: err.message};
}
}
// Create the PaymentIntent with the cart details.
async updatePaymentIntentWithShippingCost(
paymentIntent,
items,
shippingOption
) {
try {
const response = await fetch(
`/payment_intents/${paymentIntent}/shipping_change`,
{
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
shippingOption,
items,
}),
}
);
const data = await response.json();
if (data.error) {
return {error: data.error};
} else {
return data;
}
} catch (err) {
return {error: err.message};
}
}
// Update the PaymentIntent with the the currency and payment value.
async updatePaymentIntentCurrency(
paymentIntent,
currency,
payment_methods,
) {
try {
const response = await fetch(
`/payment_intents/${paymentIntent}/update_currency`,
{
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
currency,
payment_methods,
}),
}
);
const data = await response.json();
if (data.error) {
return {error: data.error};
} else {
return data;
}
} catch (err) {
return {error: err.message};
}
}
} |
JavaScript | class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
const styledJSXStyles = flush();
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
{styledJSXStyles}
</>
),
};
} finally {
sheet.seal();
}
}
render() {
return (
<Html lang="en">
<Head>
<meta name="description" content={description} />
<meta property="og:title" content="Tina Cloud" />
<meta property="og:description" content={description} />
<meta
property="og:image"
content="https://tina.io/img/tina-twitter-share.png"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
} |
JavaScript | class ImageUploadConfiguration {
/** Detemines whether this configuration applies to the provided request */
isProperConfiguration(req) {
throw new Error('not implemented');
}
/** Verify that the currently logged in user has permissions to upload */
async verifyUserPermissions(objectManager, req) {
throw new Error('not implemented');
}
/** Generates local, and returned, file name for the upload */
async generateFileNames_async(
objectManager,
req)
{
throw new Error('not implemented');
}} |
JavaScript | class Transform{
/**
* the class constructor
* @param {Joints} _joints
*/
constructor(_joints){
this.joints = _joints;
}
/**
* Updates joints data
* @param {array} _keypoints raw joints data from posenet
* @param {float} treshHoldScore for determining whether to update or no
*/
updateKeypoints(_keypoints, treshHoldScore){
this.keypoints = {};
_keypoints.forEach(({ score, part, position }) => {
if (score > treshHoldScore) this.keypoints[part] = position;
});
this.distance = null;
this.headCenter = null;
this.shoulderCenter = null;
this.calibrate();
};
/**
* Makes the system invariant to scale and translations,
* given joints data
*/
calibrate(){
if (this.keypoints['leftEye'] && this.keypoints['rightEye']){
const left_x = this.keypoints['leftEye'].x;
const left_y = this.keypoints['leftEye'].y;
const right_x = this.keypoints['rightEye'].x;
const right_y = this.keypoints['rightEye'].y;
this.distance = Math.sqrt(Math.pow(left_x - right_x, 2) + Math.pow(left_y - right_y, 2));
this.headCenter = {'x':(left_x + right_x) / 2.0, 'y':(left_y + right_y) / 2.0};
}
if (this.keypoints['leftShoulder'] && this.keypoints['rightShoulder']) {
const left_x = this.keypoints['leftShoulder'].x;
const left_y = this.keypoints['leftShoulder'].y;
const right_x = this.keypoints['rightShoulder'].x;
const right_y = this.keypoints['rightShoulder'].y;
this.shoulderCenter = { 'x': (left_x + right_x) / 2.0, 'y': (left_y + right_y) / 2.0 };
}
}
/** Updates head joint data */
head(){
if(this.keypoints['nose'] && this.headCenter && this.shoulderCenter){
var x = this.keypoints['nose'].x;
var y = this.keypoints['nose'].y;
// get nose relative points from origin
x = (this.headCenter.x - x)/(this.distance/15);
y = this.shoulderCenter.y - y;
// normalize (i.e. scale it)
y = this.map(y,this.distance*1.5,this.distance*2.8,-2,2);
// console.log(140/this.distance,260/this.distance);
this.joints.update('head', { x, y });
return { x, y };
}
}
/**
* Updates joints data and returns angle between three joints
* @param {integer} jointA index of a joint
* @param {intger} jointB index of a joint
* @param {intger} jointC index of a joint
* @returns {float} angle
*/
rotateJoint(jointA, jointB, jointC){
if (this.keypoints[jointA] && this.keypoints[jointB] && this.keypoints[jointC]){
const angle = this.findAngle(this.keypoints[jointA], this.keypoints[jointB], this.keypoints[jointC]);
const sign = (this.keypoints[jointC].y > this.keypoints[jointB].y) ? 1 : -1;
this.joints.update(jointB, sign * angle);
return angle;
}
}
/** Maps from one linear interpolation into another one */
map(original, in_min, in_max, out_min, out_max) {
return (original - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
/**
* Returns angle in radians given three points p1, p2, p3
* @param {integer} p1
* @param {integer} p2
* @param {integer} p3
* @returns {float}
*/
findAngle(p1,p2,p3){
const p12 = Math.sqrt(Math.pow((p1.x - p2.x), 2) + Math.pow((p1.y - p2.y), 2));
const p13 = Math.sqrt(Math.pow((p1.x - p3.x), 2) + Math.pow((p1.y - p3.y), 2));
const p23 = Math.sqrt(Math.pow((p2.x - p3.x), 2) + Math.pow((p2.y - p3.y), 2));
const resultRadian = Math.acos(((Math.pow(p12, 2)) + (Math.pow(p13, 2)) - (Math.pow(p23, 2))) / (2 * p12 * p13));
return resultRadian;
}
} |
JavaScript | class LROs {
constructor(client) {
this.client = client;
this._put200Succeeded = _put200Succeeded;
this._put200SucceededNoState = _put200SucceededNoState;
this._put202Retry200 = _put202Retry200;
this._put201CreatingSucceeded200 = _put201CreatingSucceeded200;
this._put200UpdatingSucceeded204 = _put200UpdatingSucceeded204;
this._put201CreatingFailed200 = _put201CreatingFailed200;
this._put200Acceptedcanceled200 = _put200Acceptedcanceled200;
this._putNoHeaderInRetry = _putNoHeaderInRetry;
this._putAsyncRetrySucceeded = _putAsyncRetrySucceeded;
this._putAsyncNoRetrySucceeded = _putAsyncNoRetrySucceeded;
this._putAsyncRetryFailed = _putAsyncRetryFailed;
this._putAsyncNoRetrycanceled = _putAsyncNoRetrycanceled;
this._putAsyncNoHeaderInRetry = _putAsyncNoHeaderInRetry;
this._putNonResource = _putNonResource;
this._putAsyncNonResource = _putAsyncNonResource;
this._putSubResource = _putSubResource;
this._putAsyncSubResource = _putAsyncSubResource;
this._deleteProvisioning202Accepted200Succeeded = _deleteProvisioning202Accepted200Succeeded;
this._deleteProvisioning202DeletingFailed200 = _deleteProvisioning202DeletingFailed200;
this._deleteProvisioning202Deletingcanceled200 = _deleteProvisioning202Deletingcanceled200;
this._delete204Succeeded = _delete204Succeeded;
this._delete202Retry200 = _delete202Retry200;
this._delete202NoRetry204 = _delete202NoRetry204;
this._deleteNoHeaderInRetry = _deleteNoHeaderInRetry;
this._deleteAsyncNoHeaderInRetry = _deleteAsyncNoHeaderInRetry;
this._deleteAsyncRetrySucceeded = _deleteAsyncRetrySucceeded;
this._deleteAsyncNoRetrySucceeded = _deleteAsyncNoRetrySucceeded;
this._deleteAsyncRetryFailed = _deleteAsyncRetryFailed;
this._deleteAsyncRetrycanceled = _deleteAsyncRetrycanceled;
this._post200WithPayload = _post200WithPayload;
this._post202Retry200 = _post202Retry200;
this._post202NoRetry204 = _post202NoRetry204;
this._postAsyncRetrySucceeded = _postAsyncRetrySucceeded;
this._postAsyncNoRetrySucceeded = _postAsyncNoRetrySucceeded;
this._postAsyncRetryFailed = _postAsyncRetryFailed;
this._postAsyncRetrycanceled = _postAsyncRetrycanceled;
this._beginPut200Succeeded = _beginPut200Succeeded;
this._beginPut200SucceededNoState = _beginPut200SucceededNoState;
this._beginPut202Retry200 = _beginPut202Retry200;
this._beginPut201CreatingSucceeded200 = _beginPut201CreatingSucceeded200;
this._beginPut200UpdatingSucceeded204 = _beginPut200UpdatingSucceeded204;
this._beginPut201CreatingFailed200 = _beginPut201CreatingFailed200;
this._beginPut200Acceptedcanceled200 = _beginPut200Acceptedcanceled200;
this._beginPutNoHeaderInRetry = _beginPutNoHeaderInRetry;
this._beginPutAsyncRetrySucceeded = _beginPutAsyncRetrySucceeded;
this._beginPutAsyncNoRetrySucceeded = _beginPutAsyncNoRetrySucceeded;
this._beginPutAsyncRetryFailed = _beginPutAsyncRetryFailed;
this._beginPutAsyncNoRetrycanceled = _beginPutAsyncNoRetrycanceled;
this._beginPutAsyncNoHeaderInRetry = _beginPutAsyncNoHeaderInRetry;
this._beginPutNonResource = _beginPutNonResource;
this._beginPutAsyncNonResource = _beginPutAsyncNonResource;
this._beginPutSubResource = _beginPutSubResource;
this._beginPutAsyncSubResource = _beginPutAsyncSubResource;
this._beginDeleteProvisioning202Accepted200Succeeded = _beginDeleteProvisioning202Accepted200Succeeded;
this._beginDeleteProvisioning202DeletingFailed200 = _beginDeleteProvisioning202DeletingFailed200;
this._beginDeleteProvisioning202Deletingcanceled200 = _beginDeleteProvisioning202Deletingcanceled200;
this._beginDelete204Succeeded = _beginDelete204Succeeded;
this._beginDelete202Retry200 = _beginDelete202Retry200;
this._beginDelete202NoRetry204 = _beginDelete202NoRetry204;
this._beginDeleteNoHeaderInRetry = _beginDeleteNoHeaderInRetry;
this._beginDeleteAsyncNoHeaderInRetry = _beginDeleteAsyncNoHeaderInRetry;
this._beginDeleteAsyncRetrySucceeded = _beginDeleteAsyncRetrySucceeded;
this._beginDeleteAsyncNoRetrySucceeded = _beginDeleteAsyncNoRetrySucceeded;
this._beginDeleteAsyncRetryFailed = _beginDeleteAsyncRetryFailed;
this._beginDeleteAsyncRetrycanceled = _beginDeleteAsyncRetrycanceled;
this._beginPost200WithPayload = _beginPost200WithPayload;
this._beginPost202Retry200 = _beginPost202Retry200;
this._beginPost202NoRetry204 = _beginPost202NoRetry204;
this._beginPostAsyncRetrySucceeded = _beginPostAsyncRetrySucceeded;
this._beginPostAsyncNoRetrySucceeded = _beginPostAsyncNoRetrySucceeded;
this._beginPostAsyncRetryFailed = _beginPostAsyncRetryFailed;
this._beginPostAsyncRetrycanceled = _beginPostAsyncRetrycanceled;
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Succeeded’.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
put200SucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._put200Succeeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Succeeded’.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
put200Succeeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._put200Succeeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._put200Succeeded(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that does not contain ProvisioningState=’Succeeded’.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
put200SucceededNoStateWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._put200SucceededNoState(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that does not contain ProvisioningState=’Succeeded’.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
put200SucceededNoState(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._put200SucceededNoState(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._put200SucceededNoState(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 202 to the initial request, with
* a location header that points to a polling URL that returns a 200 and an
* entity that doesn't contains ProvisioningState
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
put202Retry200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._put202Retry200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 202 to the initial request, with
* a location header that points to a polling URL that returns a 200 and an
* entity that doesn't contains ProvisioningState
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
put202Retry200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._put202Retry200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._put202Retry200(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
put201CreatingSucceeded200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._put201CreatingSucceeded200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
put201CreatingSucceeded200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._put201CreatingSucceeded200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._put201CreatingSucceeded200(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Updating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
put200UpdatingSucceeded204WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._put200UpdatingSucceeded204(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Updating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
put200UpdatingSucceeded204(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._put200UpdatingSucceeded204(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._put200UpdatingSucceeded204(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Created’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Failed’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
put201CreatingFailed200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._put201CreatingFailed200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Created’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Failed’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
put201CreatingFailed200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._put201CreatingFailed200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._put201CreatingFailed200(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
put200Acceptedcanceled200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._put200Acceptedcanceled200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
put200Acceptedcanceled200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._put200Acceptedcanceled200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._put200Acceptedcanceled200(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 202 to the initial request with
* location header. Subsequent calls to operation status do not contain
* location header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putNoHeaderInRetryWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putNoHeaderInRetry(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 202 to the initial request with
* location header. Subsequent calls to operation status do not contain
* location header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putNoHeaderInRetry(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putNoHeaderInRetry(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putNoHeaderInRetry(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putAsyncRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putAsyncRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putAsyncRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putAsyncRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putAsyncRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putAsyncNoRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putAsyncNoRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putAsyncNoRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putAsyncNoRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putAsyncNoRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putAsyncRetryFailedWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putAsyncRetryFailed(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putAsyncRetryFailed(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putAsyncRetryFailed(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putAsyncRetryFailed(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putAsyncNoRetrycanceledWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putAsyncNoRetrycanceled(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putAsyncNoRetrycanceled(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putAsyncNoRetrycanceled(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putAsyncNoRetrycanceled(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 202 to the initial request with
* Azure-AsyncOperation header. Subsequent calls to operation status do not
* contain Azure-AsyncOperation header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putAsyncNoHeaderInRetryWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putAsyncNoHeaderInRetry(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 202 to the initial request with
* Azure-AsyncOperation header. Subsequent calls to operation status do not
* contain Azure-AsyncOperation header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putAsyncNoHeaderInRetry(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putAsyncNoHeaderInRetry(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putAsyncNoHeaderInRetry(options, optionalCallback);
}
}
/**
* Long running put request with non resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.sku] sku to put
*
* @param {string} [options.sku.name]
*
* @param {string} [options.sku.id]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Sku>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putNonResourceWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putNonResource(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request with non resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.sku] sku to put
*
* @param {string} [options.sku.name]
*
* @param {string} [options.sku.id]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Sku} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Sku} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putNonResource(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putNonResource(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putNonResource(options, optionalCallback);
}
}
/**
* Long running put request with non resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.sku] Sku to put
*
* @param {string} [options.sku.name]
*
* @param {string} [options.sku.id]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Sku>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putAsyncNonResourceWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putAsyncNonResource(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request with non resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.sku] Sku to put
*
* @param {string} [options.sku.name]
*
* @param {string} [options.sku.id]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Sku} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Sku} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putAsyncNonResource(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putAsyncNonResource(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putAsyncNonResource(options, optionalCallback);
}
}
/**
* Long running put request with sub resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.provisioningState]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubProduct>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putSubResourceWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putSubResource(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request with sub resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.provisioningState]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {SubProduct} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link SubProduct} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putSubResource(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putSubResource(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putSubResource(options, optionalCallback);
}
}
/**
* Long running put request with sub resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.provisioningState]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubProduct>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
putAsyncSubResourceWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._putAsyncSubResource(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request with sub resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.provisioningState]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {SubProduct} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link SubProduct} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
putAsyncSubResource(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._putAsyncSubResource(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._putAsyncSubResource(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Accepted’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteProvisioning202Accepted200SucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteProvisioning202Accepted200Succeeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Accepted’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteProvisioning202Accepted200Succeeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteProvisioning202Accepted200Succeeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteProvisioning202Accepted200Succeeded(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Failed’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteProvisioning202DeletingFailed200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteProvisioning202DeletingFailed200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Failed’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteProvisioning202DeletingFailed200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteProvisioning202DeletingFailed200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteProvisioning202DeletingFailed200(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Canceled’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteProvisioning202Deletingcanceled200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteProvisioning202Deletingcanceled200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Canceled’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteProvisioning202Deletingcanceled200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteProvisioning202Deletingcanceled200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteProvisioning202Deletingcanceled200(options, optionalCallback);
}
}
/**
* Long running delete succeeds and returns right away
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
delete204SucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._delete204Succeeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete succeeds and returns right away
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
delete204Succeeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._delete204Succeeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._delete204Succeeded(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Polls return this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
delete202Retry200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._delete202Retry200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Polls return this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
delete202Retry200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._delete202Retry200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._delete202Retry200(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Polls return this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
delete202NoRetry204WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._delete202NoRetry204(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Polls return this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
delete202NoRetry204(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._delete202NoRetry204(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._delete202NoRetry204(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a location header in the
* initial request. Subsequent calls to operation status do not contain
* location header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteNoHeaderInRetryWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteNoHeaderInRetry(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a location header in the
* initial request. Subsequent calls to operation status do not contain
* location header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteNoHeaderInRetry(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteNoHeaderInRetry(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteNoHeaderInRetry(options, optionalCallback);
}
}
/**
* Long running delete request, service returns an Azure-AsyncOperation header
* in the initial request. Subsequent calls to operation status do not contain
* Azure-AsyncOperation header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteAsyncNoHeaderInRetryWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteAsyncNoHeaderInRetry(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns an Azure-AsyncOperation header
* in the initial request. Subsequent calls to operation status do not contain
* Azure-AsyncOperation header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteAsyncNoHeaderInRetry(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteAsyncNoHeaderInRetry(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteAsyncNoHeaderInRetry(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteAsyncRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteAsyncRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteAsyncRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteAsyncRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteAsyncRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteAsyncNoRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteAsyncNoRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteAsyncNoRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteAsyncNoRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteAsyncNoRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteAsyncRetryFailedWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteAsyncRetryFailed(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteAsyncRetryFailed(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteAsyncRetryFailed(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteAsyncRetryFailed(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteAsyncRetrycanceledWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteAsyncRetrycanceled(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteAsyncRetrycanceled(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteAsyncRetrycanceled(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteAsyncRetrycanceled(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' header. Poll returns a 200 with a response body after
* success.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Sku>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
post200WithPayloadWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._post200WithPayload(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' header. Poll returns a 200 with a response body after
* success.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Sku} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Sku} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
post200WithPayload(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._post200WithPayload(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._post200WithPayload(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' and 'Retry-After' headers, Polls return a 200 with a
* response body after success
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
post202Retry200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._post202Retry200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' and 'Retry-After' headers, Polls return a 200 with a
* response body after success
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
post202Retry200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._post202Retry200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._post202Retry200(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' header, 204 with noresponse body after success
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
post202NoRetry204WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._post202NoRetry204(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' header, 204 with noresponse body after success
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
post202NoRetry204(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._post202NoRetry204(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._post202NoRetry204(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
postAsyncRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._postAsyncRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
postAsyncRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._postAsyncRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._postAsyncRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
postAsyncNoRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._postAsyncNoRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
postAsyncNoRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._postAsyncNoRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._postAsyncNoRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
postAsyncRetryFailedWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._postAsyncRetryFailed(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
postAsyncRetryFailed(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._postAsyncRetryFailed(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._postAsyncRetryFailed(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
postAsyncRetrycanceledWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._postAsyncRetrycanceled(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
postAsyncRetrycanceled(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._postAsyncRetrycanceled(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._postAsyncRetrycanceled(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Succeeded’.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPut200SucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPut200Succeeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Succeeded’.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPut200Succeeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPut200Succeeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPut200Succeeded(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that does not contain ProvisioningState=’Succeeded’.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPut200SucceededNoStateWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPut200SucceededNoState(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that does not contain ProvisioningState=’Succeeded’.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPut200SucceededNoState(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPut200SucceededNoState(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPut200SucceededNoState(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 202 to the initial request, with
* a location header that points to a polling URL that returns a 200 and an
* entity that doesn't contains ProvisioningState
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPut202Retry200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPut202Retry200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 202 to the initial request, with
* a location header that points to a polling URL that returns a 200 and an
* entity that doesn't contains ProvisioningState
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPut202Retry200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPut202Retry200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPut202Retry200(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPut201CreatingSucceeded200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPut201CreatingSucceeded200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPut201CreatingSucceeded200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPut201CreatingSucceeded200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPut201CreatingSucceeded200(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Updating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPut200UpdatingSucceeded204WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPut200UpdatingSucceeded204(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Updating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPut200UpdatingSucceeded204(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPut200UpdatingSucceeded204(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPut200UpdatingSucceeded204(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Created’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Failed’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPut201CreatingFailed200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPut201CreatingFailed200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Created’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Failed’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPut201CreatingFailed200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPut201CreatingFailed200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPut201CreatingFailed200(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPut200Acceptedcanceled200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPut200Acceptedcanceled200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 201 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Polls return this
* value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPut200Acceptedcanceled200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPut200Acceptedcanceled200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPut200Acceptedcanceled200(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 202 to the initial request with
* location header. Subsequent calls to operation status do not contain
* location header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutNoHeaderInRetryWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutNoHeaderInRetry(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 202 to the initial request with
* location header. Subsequent calls to operation status do not contain
* location header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutNoHeaderInRetry(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutNoHeaderInRetry(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutNoHeaderInRetry(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutAsyncRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutAsyncRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutAsyncRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutAsyncRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutAsyncRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutAsyncNoRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutAsyncNoRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutAsyncNoRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutAsyncNoRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutAsyncNoRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutAsyncRetryFailedWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutAsyncRetryFailed(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutAsyncRetryFailed(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutAsyncRetryFailed(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutAsyncRetryFailed(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutAsyncNoRetrycanceledWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutAsyncNoRetrycanceled(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 200 to the initial request, with
* an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutAsyncNoRetrycanceled(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutAsyncNoRetrycanceled(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutAsyncNoRetrycanceled(options, optionalCallback);
}
}
/**
* Long running put request, service returns a 202 to the initial request with
* Azure-AsyncOperation header. Subsequent calls to operation status do not
* contain Azure-AsyncOperation header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutAsyncNoHeaderInRetryWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutAsyncNoHeaderInRetry(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request, service returns a 202 to the initial request with
* Azure-AsyncOperation header. Subsequent calls to operation status do not
* contain Azure-AsyncOperation header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutAsyncNoHeaderInRetry(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutAsyncNoHeaderInRetry(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutAsyncNoHeaderInRetry(options, optionalCallback);
}
}
/**
* Long running put request with non resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.sku] sku to put
*
* @param {string} [options.sku.name]
*
* @param {string} [options.sku.id]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Sku>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutNonResourceWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutNonResource(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request with non resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.sku] sku to put
*
* @param {string} [options.sku.name]
*
* @param {string} [options.sku.id]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Sku} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Sku} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutNonResource(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutNonResource(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutNonResource(options, optionalCallback);
}
}
/**
* Long running put request with non resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.sku] Sku to put
*
* @param {string} [options.sku.name]
*
* @param {string} [options.sku.id]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Sku>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutAsyncNonResourceWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutAsyncNonResource(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request with non resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.sku] Sku to put
*
* @param {string} [options.sku.name]
*
* @param {string} [options.sku.id]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Sku} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Sku} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutAsyncNonResource(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutAsyncNonResource(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutAsyncNonResource(options, optionalCallback);
}
}
/**
* Long running put request with sub resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.provisioningState]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubProduct>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutSubResourceWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutSubResource(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request with sub resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.provisioningState]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {SubProduct} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link SubProduct} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutSubResource(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutSubResource(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutSubResource(options, optionalCallback);
}
}
/**
* Long running put request with sub resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.provisioningState]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubProduct>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPutAsyncSubResourceWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPutAsyncSubResource(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running put request with sub resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.provisioningState]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {SubProduct} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link SubProduct} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPutAsyncSubResource(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPutAsyncSubResource(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPutAsyncSubResource(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Accepted’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteProvisioning202Accepted200SucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteProvisioning202Accepted200Succeeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Accepted’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteProvisioning202Accepted200Succeeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteProvisioning202Accepted200Succeeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteProvisioning202Accepted200Succeeded(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Failed’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteProvisioning202DeletingFailed200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteProvisioning202DeletingFailed200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Failed’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteProvisioning202DeletingFailed200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteProvisioning202DeletingFailed200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteProvisioning202DeletingFailed200(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Canceled’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteProvisioning202Deletingcanceled200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteProvisioning202Deletingcanceled200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Polls return
* this value until the last poll returns a ‘200’ with
* ProvisioningState=’Canceled’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteProvisioning202Deletingcanceled200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteProvisioning202Deletingcanceled200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteProvisioning202Deletingcanceled200(options, optionalCallback);
}
}
/**
* Long running delete succeeds and returns right away
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDelete204SucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDelete204Succeeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete succeeds and returns right away
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDelete204Succeeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDelete204Succeeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDelete204Succeeded(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Polls return this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDelete202Retry200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDelete202Retry200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Polls return this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDelete202Retry200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDelete202Retry200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDelete202Retry200(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Polls return this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDelete202NoRetry204WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDelete202NoRetry204(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Polls return this value until the last poll returns a ‘200’ with
* ProvisioningState=’Succeeded’
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDelete202NoRetry204(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDelete202NoRetry204(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDelete202NoRetry204(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a location header in the
* initial request. Subsequent calls to operation status do not contain
* location header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteNoHeaderInRetryWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteNoHeaderInRetry(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a location header in the
* initial request. Subsequent calls to operation status do not contain
* location header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteNoHeaderInRetry(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteNoHeaderInRetry(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteNoHeaderInRetry(options, optionalCallback);
}
}
/**
* Long running delete request, service returns an Azure-AsyncOperation header
* in the initial request. Subsequent calls to operation status do not contain
* Azure-AsyncOperation header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteAsyncNoHeaderInRetryWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteAsyncNoHeaderInRetry(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns an Azure-AsyncOperation header
* in the initial request. Subsequent calls to operation status do not contain
* Azure-AsyncOperation header.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteAsyncNoHeaderInRetry(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteAsyncNoHeaderInRetry(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteAsyncNoHeaderInRetry(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteAsyncRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteAsyncRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteAsyncRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteAsyncRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteAsyncRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteAsyncNoRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteAsyncNoRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteAsyncNoRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteAsyncNoRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteAsyncNoRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteAsyncRetryFailedWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteAsyncRetryFailed(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteAsyncRetryFailed(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteAsyncRetryFailed(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteAsyncRetryFailed(options, optionalCallback);
}
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginDeleteAsyncRetrycanceledWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginDeleteAsyncRetrycanceled(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running delete request, service returns a 202 to the initial request.
* Poll the endpoint indicated in the Azure-AsyncOperation header for operation
* status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteAsyncRetrycanceled(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginDeleteAsyncRetrycanceled(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginDeleteAsyncRetrycanceled(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' header. Poll returns a 200 with a response body after
* success.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Sku>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPost200WithPayloadWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPost200WithPayload(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' header. Poll returns a 200 with a response body after
* success.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Sku} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Sku} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPost200WithPayload(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPost200WithPayload(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPost200WithPayload(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' and 'Retry-After' headers, Polls return a 200 with a
* response body after success
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPost202Retry200WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPost202Retry200(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' and 'Retry-After' headers, Polls return a 200 with a
* response body after success
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPost202Retry200(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPost202Retry200(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPost202Retry200(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' header, 204 with noresponse body after success
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPost202NoRetry204WithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPost202NoRetry204(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with 'Location' header, 204 with noresponse body after success
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPost202NoRetry204(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPost202NoRetry204(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPost202NoRetry204(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPostAsyncRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPostAsyncRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPostAsyncRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPostAsyncRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPostAsyncRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Product>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPostAsyncNoRetrySucceededWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPostAsyncNoRetrySucceeded(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Product} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Product} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPostAsyncNoRetrySucceeded(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPostAsyncNoRetrySucceeded(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPostAsyncNoRetrySucceeded(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPostAsyncRetryFailedWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPostAsyncRetryFailed(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPostAsyncRetryFailed(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPostAsyncRetryFailed(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPostAsyncRetryFailed(options, optionalCallback);
}
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginPostAsyncRetrycanceledWithHttpOperationResponse(options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginPostAsyncRetrycanceled(options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Long running post request, service returns a 202 to the initial request,
* with an entity that contains ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.product] Product to put
*
* @param {string} [options.product.provisioningState]
*
* @param {object} [options.product.tags]
*
* @param {string} [options.product.location] Resource Location
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginPostAsyncRetrycanceled(options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginPostAsyncRetrycanceled(options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginPostAsyncRetrycanceled(options, optionalCallback);
}
}
} |
JavaScript | class UsersBackend {
get(resolve) {
this.db.all('SELECT id, displayName, chats, trivia, raffle, ignoreStats, autoGreet FROM users ORDER BY displayName ASC', (err, rows) => {
resolve({ users: rows });
});
}
post(resolve, req) {
const filter = (input) => {
const params = [];
params.push(input.chats ? Math.max(0, input.chats) : 0);
params.push(input.trivia ? Math.max(0, input.trivia) : 0);
params.push(input.raffle ? Math.max(0, input.raffle) : 0);
params.push(!!input.ignoreStats);
params.push(!!input.autoGreet);
return params;
};
let count = 0;
if (Array.isArray(req.body.update)) {
count += req.body.update.length;
}
if (!count) {
resolve();
}
if (Array.isArray(req.body.update)) {
const stmt = this.db.prepare('UPDATE users SET chats = ?, trivia = ?, raffle = ?, ignoreStats = ?, autoGreet = ? WHERE id = ?');
req.body.update.forEach((row) => {
const params = filter(row);
params.push(+row.id);
stmt.run(params, () => {
if (!--count) {
resolve();
}
});
});
stmt.finalize();
}
}
} |
JavaScript | class Span extends opentracing.Span {
/**
* Constructor for internal use only. To start a span call {@link Tracer#startSpan}
*
* @param {Tracer} tracer
* @param {object} fields
*/
constructor (tracer, fields) {
super()
this.debug = fields.debug
this._tracer = tracer
this._fields = fields
}
// ---------------------------------------------------------------------- //
// OpenTracing API methods
// ---------------------------------------------------------------------- //
/**
* Returns the SpanContext object associated with this Span.
*
* @return {SpanContext}
*/
context () {
return this._fields.baggage ? {
traceId: this._fields.traceId,
spanId: this._fields.spanId,
baggage: this._fields.baggage
} : {
traceId: this._fields.traceId,
spanId: this._fields.spanId
}
}
/**
* Returns the Tracer object used to create this Span.
*
* @return {Tracer}
*/
tracer () {
return this._tracer
}
/**
* Sets the string name for the logical operation this span represents.
*
* @param {string} name
* @return {Span} this
*/
setOperationName (name) {
this._fields.operation = name
return this
}
/**
* Sets a key:value pair on this Span that also propagates to future
* children of the associated Span.
*
* setBaggageItem() enables powerful functionality given a full-stack
* opentracing integration (e.g., arbitrary application data from a web
* client can make it, transparently, all the way into the depths of a
* storage system), and with it some powerful costs: use this feature with
* care.
*
* IMPORTANT NOTE #1: setBaggageItem() will only propagate baggage items to
* *future* causal descendants of the associated Span.
*
* IMPORTANT NOTE #2: Use this thoughtfully and with care. Every key and
* value is copied into every local *and remote* child of the associated
* Span, and that can add up to a lot of network and cpu overhead.
*
* @param {string} key
* @param {string} value
*/
setBaggageItem (key, value) {
if (!this._fields.baggage) this._fields.baggage = {}
this._fields.baggage[key] = value
return this
}
/**
* Returns the value for a baggage item given its key.
*
* @param {string} key
* The key for the given trace attribute.
* @return {string}
* String value for the given key, or undefined if the key does not
* correspond to a set trace attribute.
*/
getBaggageItem (key) {
return this._fields.baggage && this._fields.baggage[key]
}
/**
* Adds a single tag to the span. See `addTags()` for details.
*
* @param {string} key
* @param {object} value
* @return {Span} this
*/
setTag (key, value) {
this.addTags({ [key]: value })
return this
}
/**
* Adds the given key value pairs to the set of span tags.
*
* Multiple calls to addTags() results in the tags being the superset of
* all calls.
*
* The behavior of setting the same key multiple times on the same span
* is undefined.
*
* The supported type of the values is implementation-dependent.
* Implementations are expected to safely handle all types of values but
* may choose to ignore unrecognized / unhandle-able values (e.g. objects
* with cyclic references, function objects).
*
* @param {object.<string, object>} keyValues
* @return {Span} this
*/
addTags (keyValues) {
const tags = this._fields.tags || {}
for (let key of Object.keys(keyValues)) {
tags[key] = keyValues[key]
}
this._fields.tags = tags
return this
}
/**
* Add a log record to this Span, optionally at a user-provided timestamp.
*
* For example:
*
* span.log({
* size: rpc.size(), // numeric value
* URI: rpc.URI(), // string value
* payload: rpc.payload(), // Object value
* "keys can be arbitrary strings": rpc.foo(),
* });
*
* span.log({
* "error.description": someError.description(),
* }, someError.timestampMillis());
*
* @param {object.<string, object>} keyValues
* An object mapping string keys to arbitrary value types. All
* Tracer implementations should support bool, string, and numeric
* value types, and some may also support Object values.
* @param {number} timestamp
* An optional parameter specifying the timestamp in milliseconds
* since the Unix epoch. Fractional values are allowed so that
* timestamps with sub-millisecond accuracy can be represented. If
* not specified, the implementation is expected to use its notion
* of the current time of the call.
* @return {Span} this
*/
log (keyValues, timestamp) {
let logFn = (this._tracer.logFn && typeof this._tracer.logFn === 'function') ? this._tracer.logFn : undefined
if (logFn && keyValues.debug) {
logFn('span this._tracer.debug: ' + this._tracer.debug + ', span keyValues.debug: ' + keyValues.debug)
logFn('span - should ignore log event: ' + (!this._tracer.debug && keyValues.debug))
}
if (!this._tracer.debug && keyValues.debug) {
if (logFn && keyValues.debug) {
logFn('span - Blocking logging for ' + JSON.stringify(keyValues))
}
return this
} else {
if (logFn && keyValues.debug) {
logFn('span - not Blocking logging for ' + JSON.stringify(keyValues))
}
}
if (!timestamp) timestamp = keyValues.timestamp || Date.now()
timestamp *= 1000
keyValues.timestamp = timestamp
if (!this._fields.logs) this._fields.logs = []
if (this._tracer.multiEvent) {
this._fields.logs[0] = keyValues
this._tracer.report(this._fields)
} else {
this._fields.logs.push(keyValues)
}
return this
}
/**
* Sets the end timestamp and finalizes Span state.
*
* With the exception of calls to Span.context() (which are always allowed),
* finish() must be the last call made to any span instance, and to do
* otherwise leads to undefined behavior.
*
* @param {number} finishTime
* Optional finish time in milliseconds as a Unix timestamp. Decimal
* values are supported for timestamps with sub-millisecond accuracy.
* If not specified, the current time (as defined by the
* implementation) will be used.
*/
finish (finishTime) {
if (this._finished) return
if (!finishTime) finishTime = Date.now() * 1000
this._fields.duration = finishTime - this._fields.start
let log = {
timestamp: finishTime,
event: 'Finish-Span'
}
if (!this._fields.logs) this._fields.logs = []
if (this._tracer.multiEvent) {
this._fields.logs[0] = log
} else {
this._fields.logs.push(log)
}
this._tracer.report(this._fields)
this._finished = true
}
} |
JavaScript | class mdTextObject {
/**
* Creates an instance of mdTextObject.
* @param {MarkdownEditor} mde - MarkdownEditor instance
* @param {object} range - range
* @memberof mdTextObject
*/
constructor(mde, range) {
this._mde = mde;
this.setRange(range || mde.getRange());
}
/**
* Set start
* @memberof mdTextObject
* @param {object} rangeStart Start of range
* @private
*/
_setStart(rangeStart) {
this._start = rangeStart;
}
/**
* Set end
* @private
* @memberof mdTextObject
* @param {object} rangeEnd End of range
* @private
*/
_setEnd(rangeEnd) {
this._end = rangeEnd;
}
/**
* Set range to given range
* @private
* @memberof mdTextObject
* @param {object} range Range object
*/
setRange(range) {
this._setStart(range.start);
this._setEnd(range.end);
}
/**
* Set start to end
* @private
* @memberof mdTextObject
* @param {object} range Range object
*/
setEndBeforeRange(range) {
this._setEnd(range.start);
}
/**
* Expand startOffset by 1
* @private
* @memberof mdTextObject
*/
expandStartOffset() {
const start = this._start;
if (start.ch !== 0) {
start.ch -= 1;
}
}
/**
* Expand endOffset by 1
* @private
* @memberof mdTextObject
*/
expandEndOffset() {
const end = this._end;
if (end.ch < this._mde.getEditor().getDoc().getLine(end.line).length) {
end.ch += 1;
}
}
/**
* Get current selection's text content
* @private
* @memberof mdTextObject
* @returns {{start: {line: number, ch: number}, end: {line: number, ch: number}}}
*/
getTextContent() {
return this._mde.getEditor().getRange(this._start, this._end);
}
/**
* Replace current selection's content with given text content
* @private
* @memberof mdTextObject
* @param {string} content Replacement content
*/
replaceContent(content) {
this._mde.getEditor().replaceRange(content, this._start, this._end, '+input');
}
/**
* Delete current selection's content
* @private
* @memberof mdTextObject
*/
deleteContent() {
this._mde.getEditor().replaceRange('', this._start, this._end, '+delete');
}
/**
* peek StartBeforeOffset
* @private
* @memberof mdTextObject
* @param {number} offset Offset
* @returns {{start: {line: number, ch: number}, end: {line: number, ch: number}}}
*/
peekStartBeforeOffset(offset) {
const peekStart = {
line: this._start.line,
ch: Math.max(this._start.ch - offset, 0)
};
return this._mde.getEditor().getRange(peekStart, this._start);
}
} |
JavaScript | class TreeSearch
{
constructor()
{
this._tempPoint = new Point();
}
/**
* Recursive implementation for findHit
*
* @private
* @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that
* is tested for collision
* @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject
* that will be hit test (recursively crawls its children)
* @param {Function} [func] - the function that will be called on each interactive object. The
* interactionEvent, displayObject and hit will be passed to the function
* @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point
* @param {boolean} [interactive] - Whether the displayObject is interactive
* @return {boolean} returns true if the displayObject hit the point
*/
recursiveFindHit(interactionEvent, displayObject, func, hitTest, interactive)
{
if (!displayObject || !displayObject.visible)
{
return false;
}
const point = interactionEvent.data.global;
// Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^
//
// This function will now loop through all objects and then only hit test the objects it HAS
// to, not all of them. MUCH faster..
// An object will be hit test if the following is true:
//
// 1: It is interactive.
// 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit.
//
// As another little optimization once an interactive object has been hit we can carry on
// through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests
// A final optimization is that an object is not hit test directly if a child has already been hit.
interactive = displayObject.interactive || interactive;
let hit = false;
let interactiveParent = interactive;
// Flag here can set to false if the event is outside the parents hitArea or mask
let hitTestChildren = true;
// If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea
// There is also no longer a need to hitTest children.
if (displayObject.hitArea)
{
if (hitTest)
{
displayObject.worldTransform.applyInverse(point, this._tempPoint);
if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y))
{
hitTest = false;
hitTestChildren = false;
}
else
{
hit = true;
}
}
interactiveParent = false;
}
// If there is a mask, no need to hitTest against anything else if the pointer is not within the mask.
// We still want to hitTestChildren, however, to ensure a mouseout can still be generated.
// https://github.com/pixijs/pixi.js/issues/5135
else if (displayObject._mask)
{
if (hitTest)
{
if (!(displayObject._mask.containsPoint && displayObject._mask.containsPoint(point)))
{
hitTest = false;
}
}
}
// ** FREE TIP **! If an object is not interactive or has no buttons in it
// (such as a game scene!) set interactiveChildren to false for that displayObject.
// This will allow PixiJS to completely ignore and bypass checking the displayObjects children.
if (hitTestChildren && displayObject.interactiveChildren && displayObject.children)
{
const children = displayObject.children;
for (let i = children.length - 1; i >= 0; i--)
{
const child = children[i];
// time to get recursive.. if this function will return if something is hit..
const childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent);
if (childHit)
{
// its a good idea to check if a child has lost its parent.
// this means it has been removed whilst looping so its best
if (!child.parent)
{
continue;
}
// we no longer need to hit test any more objects in this container as we we
// now know the parent has been hit
interactiveParent = false;
// If the child is interactive , that means that the object hit was actually
// interactive and not just the child of an interactive object.
// This means we no longer need to hit test anything else. We still need to run
// through all objects, but we don't need to perform any hit tests.
if (childHit)
{
if (interactionEvent.target)
{
hitTest = false;
}
hit = true;
}
}
}
}
// no point running this if the item is not interactive or does not have an interactive parent.
if (interactive)
{
// if we are hit testing (as in we have no hit any objects yet)
// We also don't need to worry about hit testing if once of the displayObjects children
// has already been hit - but only if it was interactive, otherwise we need to keep
// looking for an interactive child, just in case we hit one
if (hitTest && !interactionEvent.target)
{
// already tested against hitArea if it is defined
if (!displayObject.hitArea && displayObject.containsPoint)
{
if (displayObject.containsPoint(point))
{
hit = true;
}
}
}
if (displayObject.interactive)
{
if (hit && !interactionEvent.target)
{
interactionEvent.target = displayObject;
}
if (func)
{
func(interactionEvent, displayObject, !!hit);
}
}
}
return hit;
}
/**
* @private
*
* This function is provides a neat way of crawling through the scene graph and running a
* specified function on all interactive objects it finds. It will also take care of hit
* testing the interactive objects and passes the hit across in the function.
*
* @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that
* is tested for collision
* @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject
* that will be hit test (recursively crawls its children)
* @param {Function} [func] - the function that will be called on each interactive object. The
* interactionEvent, displayObject and hit will be passed to the function
* @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point
* @return {boolean} returns true if the displayObject hit the point
*/
findHit(interactionEvent, displayObject, func, hitTest)
{
this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false);
}
} |
JavaScript | class PromiseLoader extends React.Component {
constructor(props) {
super(props);
this.state = {
promiseData: initialPromiseState()
};
this.onResolved = this.onResolved.bind(this);
this.onRejected = this.onRejected.bind(this);
}
componentDidMount() {
const {promiseFn} = this.props;
promiseFn()
.then(this.onResolved)
.catch(this.onRejected);
}
onResolved(resolve) {
const {promiseData} = this.state;
this.setState({ promiseData: {
...promiseData,
isPending: false,
resolve
}});
}
onRejected(reject) {
const {promiseData} = this.state;
this.setState({ promiseData: {
...promiseData,
isPending:false,
reject
}});
}
render() {
const {promiseData} = this.state;
const {children} = this.props;
return children(promiseData);
}
} |
JavaScript | class ElementNumberInput {
constructor (domElement) {
this.component = document.querySelector(domElement);
if (this.component === undefined) {
console.warn(`ElementNumberInput could not find '${domElement}' DOM element!`)
} else {
this.minValue = 2;
this.maxValue = 30;
this.lastValue = this.component.value;
this.component.addEventListener("change", () => {
const newValue = this.validateInput();
if (newValue) {
console.log(`Updating number value to ${newValue}`);
this.component.value = newValue;
this.lastValue = newValue;
} else {
this.component.value = this.lastValue;
}
});
}
}
getNumber () {
return this.component.value;
}
validateInput () {
// input field value is string, but implicit conversion
// allows to test for number
if (!isNaN(this.component.value)) {
const newValue = this.clampInput();
console.log(`New value ${newValue}`);
return newValue;
}
return null;
}
clampInput () {
let clamped = this.component.value;
if (clamped > this.maxValue) {
clamped = this.maxValue;
} else if (clamped < this.minValue) {
clamped = this.minValue;
}
return clamped;
}
} |
JavaScript | class Text extends BaseComponent {
constructor(root, props) {
super(root, props);
this.text = props.children;
}
goToPosition(row = this.position[0], col = this.position[1]) {
this.terminal.write(`\x1b[${row};${col}H`);
}
replaceChild(text) {
// erase old text
this.goToPosition(this.position[0], this.position[1] + this.text.length);
this.terminal.write('\b \b'.repeat(this.text.length));
// write new text
this.terminal.write(`${text}`);
this.text = text;
}
appendChild(text) {
this.text = text;
// set this.position based off root's current position
this.position = [this.root.position[0], this.root.position[1]];
// adjust sibling positions if this text is in the place of current children
this.updateSiblingPositions(this.text.length);
// go to this.position
this.goToPosition();
// write the text to the terminal
this.terminal.write(`${text}`);
// update root's position to account for the text length
this.root.position = [
this.position[0],
this.position[1] + this.text.length
];
}
updateSiblingPositions(delta) {
const children = this.root.children;
const collidingChildren = children.filter(
child =>
child.position[0] === this.position[0] &&
child.position[1] >= this.position[1] &&
child !== this
);
// sort the array so that children are not overwritten
// by the deletion of future iterations
// that is required when we call updatePosition.
collidingChildren.sort((childA, childB) => {
if (delta > 0) {
return childB.position[1] - childA.position[1];
} else {
return childA.position[1] - childB.position[1];
}
});
for (let child of collidingChildren) {
console.log(
'updating child',
child,
child.position,
this.position,
this.text,
delta
);
child.updatePosition(0, delta);
}
}
updatePosition(deltaRow, deltaCol) {
// go to 'old' position
this.goToPosition(this.position[0], this.position[1] + this.text.length);
// remove current text
this.terminal.write('\b \b'.repeat(this.text.length));
// update position and go to it
this.position = [this.position[0] + deltaRow, this.position[1] + deltaCol];
this.goToPosition();
// write text back
this.terminal.write(`${this.text}`);
}
removeSelf() {
this.goToPosition(this.position[0], this.position[1] + this.text.length);
this.terminal.write('\b \b'.repeat(this.text.length));
// adjust sibling positions if this text is in the place of current children
this.updateSiblingPositions(-this.text.length);
// update root's position to account for the text length
this.root.position = [this.position[0], this.position[1]];
}
} |
JavaScript | class MetadataGenerator {
/**
* @param {PRData} data
*/
constructor(data) {
const { owner, repo, pr, reviewers, argv } = data;
this.owner = owner;
this.repo = repo;
this.pr = pr;
this.reviewers = reviewers;
this.argv = argv;
}
/**
* @returns {string}
*/
getMetadata() {
const {
reviewers: { approved: reviewedBy },
pr: { url: prUrl, bodyHTML: op },
owner,
repo
} = this;
const parser = new LinkParser(owner, repo, op);
const fixes = parser.getFixes();
const refs = parser.getRefs();
const altPrUrl = parser.getAltPrUrl();
const meta = [
...fixes.map((fix) => `Fixes: ${fix}`),
...refs.map((ref) => `Refs: ${ref}`)
];
const backport = this.argv ? this.argv.backport : undefined;
if (backport) {
meta.unshift(`Backport-PR-URL: ${prUrl}`);
meta.unshift(`PR-URL: ${altPrUrl}`);
} else {
// Reviews are only added here as backports should not contain reviews
// for the backport itself in the metadata
meta.unshift(`PR-URL: ${prUrl}`);
meta.push(
...reviewedBy.map((r) => `Reviewed-By: ${r.reviewer.getContact()}`)
);
}
meta.push(''); // creates final EOL
return meta.join('\n');
}
} |
JavaScript | class Divider extends Component {
static propTypes = {
classes: PropTypes.object.isRequired,
label: PropTypes.string
}
render() {
const { classes: { container, item, label: labelClass }, label } = this.props;
return (
<div className={container}>
<hr className={item} />
{!!label && <Typography component="span" className={labelClass}>{label}</Typography>}
<hr className={item} />
</div>
);
}
} |
JavaScript | class PullConsumerEndpointHandler extends BaseRequestHandler {
/**
* Get response code
*
* @returns {Integer} response code
*/
getCode() {
return this.code;
}
/**
* Get response body
*
* @returns {Any} response body
*/
getBody() {
return this.body;
}
/**
* Process request
*
* @returns {Promise<PullConsumerEndpointHandler>} resolved with instance of PullConsumerEndpointHandler
* once request processed
*/
process() {
return pullConsumers.getData(this.params.consumer, this.params.namespace)
.then((data) => {
this.code = 200;
this.body = data;
return this;
}).catch(error => new ErrorHandler(error).process());
}
} |
JavaScript | class Empty extends Node {
constructor () {
super()
this.termType = Empty.termType
}
toString () {
return '()'
}
} |
JavaScript | class App extends Component {
constructor() {
super();
this.state = {
isLoading: false,
erroremail: false,
filepath: ""
}
}
componentDidMount() {
}
handleLogin = () => {
this.setState({
isLoading: true
});
const url = require('../global').url;
axios.post(`${url}login`, {
email: this.state.email,
password: this.state.password,
}).then(res => {
AsyncStorage.setItem('token', res.data._token);
AsyncStorage.setItem('user', res.data.username);
AsyncStorage.setItem('userid', res.data._id);
// alert(JSON.stringify(res))
this.setState({
isLoading: false
});
// Toast.show({
// text: "Success Login",
// buttonText: "Okay",
// type: "success",
// duration:10000
// })
this.props.navigation.dispatch(StackActions.reset({
index: 0, // <-- currect active route from actions array
actions: [
NavigationActions.navigate({routeName: 'IndexPage'}),
],
}))
}).catch(err => {
this.setState({
isLoading: false
});
Toast.show({
text: err.response.data.message,
buttonText: "Okay",
type: "danger",
duration: 10000
})
})
};
showpicture = () => {
var options = {
title: 'Choose Profile Picture',
noData: true,
// storageOptions: {
// skipBackup: true,
// path: 'MyChat',
// },
};
ImagePicker.showImagePicker({
title: 'Choose Profile Picture',
storageOptions: {
skipBackup: true,
path: 'MyChat',
}
}, res => {
if(!res.error && res.uri){
this.setState({
filepath: res
})
}
})
};
// showcroppicture = () => {
// ImagePicker.openPicker({
// // multiple: true,
// cropping: true,
// mediaType:'photo',
// enableRotationGesture:true,
// hideBottomControls:true
// }).then(images => {
// console.log(images)
// this.setState({
// filepath:images
// })
// })
// }
render() {
let ScreenHeight = Dimensions.get("window").height;
return (
<Root>
<ScrollView style={{width: '100%', height: ScreenHeight}}>
<View style={styles.container}>
<View>
<Text><H1>Choose Profile Picture</H1></Text>
</View>
<View>
<TouchableOpacity onPress={this.showpicture.bind(this)}>
<Image style={{width: 100, height: 100, margin: 100}}
source={this.state.filepath !== "" ? {uri: this.state.filepath.uri} : require('../img/default-user.png')}
/>
</TouchableOpacity>
</View>
<Button iconRight bordered primary>
<Text>Next</Text>
<Icon name='arrow-forward' />
</Button>
</View>
</ScrollView>
</Root>
)
}
} |
JavaScript | class AugmentaObject {
#_initialized;
//Last augmenta scene frame it was seen on
#_lastSeen;
//Augmenta info
#_frame;
#_id;
#_oid;
#_age;
#_centroid;
#_velocity;
#_orientation;
#_boundingRect;
#_height;
//extra
#_highest;
#_distance;
#_reflectivity;
//For display
#_color;
constructor() {
this.#_initialized = false;
}
initialize() {
//Choose a random color
this.#_color = '#'+Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');
this.#_initialized = true;
}
// Parsing of the received messages and update info
//On update message
updateAugmentaObject(message)
{
if (!this.#_initialized) {
this.initialize();
}
let msg = JSON.parse(message.data);
this.#_frame = msg.object.update.frame;
this.#_id = msg.object.update.id;
this.#_oid = msg.object.update.oid;
this.#_age = msg.object.update.age;
this.#_centroid = new vec2(msg.object.update.centroid.x, msg.object.update.centroid.y);
this.#_velocity = new vec2(msg.object.update.velocity.x, msg.object.update.velocity.y);
this.#_orientation = msg.object.update.orientation;
this.#_boundingRect = new BoundingRect(msg.object.update.boundingRect.x, msg.object.update.boundingRect.y, msg.object.update.boundingRect.height, msg.object.update.boundingRect.width, msg.object.update.boundingRect.rotation);
this.#_height = msg.object.update.height;
// extra
this.#_highest = new vec2(msg.object.update.extra.highest.x, msg.object.update.extra.highest.y);
this.#_distance = msg.object.update.extra.distance;
this.#_reflectivity = msg.object.update.extra.reflectivity;
}
//On enter message
initializeAugmentaObject(message)
{
this.initialize();
let msg = JSON.parse(message.data);
this.#_frame = msg.object.enter.frame;
this.#_id = msg.object.enter.id;
this.#_oid = msg.object.enter.oid;
this.#_age = msg.object.enter.age;
this.#_centroid = new vec2(msg.object.enter.centroid.x, msg.object.enter.centroid.y);
this.#_velocity = new vec2(msg.object.enter.velocity.x, msg.object.enter.velocity.y);
this.#_orientation = msg.object.enter.orientation;
this.#_boundingRect = new BoundingRect(msg.object.enter.boundingRect.x, msg.object.enter.boundingRect.y, msg.object.enter.boundingRect.height, msg.object.enter.boundingRect.width, msg.object.enter.boundingRect.rotation);
this.#_height = msg.object.enter.height;
// extra
this.#_highest = new vec2(msg.object.enter.extra.highest.x, msg.object.enter.extra.highest.y);
this.#_distance = msg.object.enter.extra.distance;
this.#_reflectivity = msg.object.enter.extra.reflectivity;
}
//Augmenta info
get frame () {
return this.#_frame;
}
get id () {
return this.#_id;
}
get oid () {
return this.#_oid;
}
get age () {
return this.#_age;
}
get centroid () {
return this.#_centroid;
}
get velocity () {
return this.#_velocity;
}
get orientation () {
return this.#_orientation;
}
get boundingRect () {
return this.#_boundingRect;
}
get height () {
return this.#_height;
}
//extra
get highest () {
return this.#_highest;
}
get distance () {
return this.#_distance;
}
get reflectivity () {
return this.#_reflectivity;
}
//For display
get color () {
return this.#_color;
}
get lastSeen () {
return this.#_lastSeen;
}
set lastSeen (lastSeen) {
this.#_lastSeen = lastSeen;
}
} |
JavaScript | class ConsoleTerminateEvent extends ConsoleEvent {
/**
* Constructor.
*
* @param {Jymfony.Component.Console.Command.Command} [command]
* @param {Jymfony.Component.Console.Input.InputInterface} input
* @param {Jymfony.Component.Console.Output.OutputInterface} output
* @param {int} exitCode
*/
__construct(command, input, output, exitCode) {
super.__construct(command, input, output);
this.exitCode = exitCode;
}
/**
* Sets the exit code.
*
* @param {int} exitCode The command exit code
*/
set exitCode(exitCode) {
this._exitCode = ~~exitCode;
}
/**
* Gets the exit code.
*
* @returns {int} The command exit code
*/
get exitCode() {
return this._exitCode;
}
} |
JavaScript | class ConsoleJsonViewLayer {
render(bluebird, layout, data) {
console.log(JSON.stringify({ type: layout, data }, null, 2));
}
} |
JavaScript | class GingerApp extends LitElement {
static get properties() {
return {
// Asset metadata.
textures: { type: Object },
meshes: { type: Object },
morphs: { type: Object },
// Three.js scene objects.
scene: { type: Object },
camera: { type: THREE.PerspectiveCamera },
renderer: { type: THREE.WebGLRenderer },
ginger: { type: Object },
leftEye: { type: Object },
rightEye: { type: Object },
// Internal state.
queue: { type: Array },
aspect: { type: Number },
isMouseTracking: { type: Boolean },
isTakingScreenshot: { type: Boolean },
leftEyeOrigin: { type: Object },
rightEyeOrigin: { type: Object },
selected: { type: String },
screenshotCounter: { type: Number },
};
}
static get styles() {
return [thisDotTheme, styles];
}
/**
* Instance of the element is created/upgraded. Use: initializing state,
* set up event listeners, create shadow dom.
* @constructor
*/
constructor() {
super();
this.queue = [];
this.aspect = 0;
this.isMouseTracking = false;
this.selected = 'eyes';
this.screenshotCounter = 0;
this.ginger = new THREE.Object3D();
this.leftEye = new THREE.Object3D();
this.rightEye = new THREE.Object3D();
this.leftEyeOrigin = null;
this.rightEyeOrigin = null;
this.textures = {
gingercolor: {
path: 'static/model/ginger_color.jpg',
texture: null,
},
gingercolornormal: {
path: 'static/model/ginger_norm.jpg',
texture: null,
},
};
this.meshes = {
gingerhead: {
path: 'static/model/gingerhead.json',
texture: this.textures.gingercolor,
normalmap: null,
morphTargets: true,
mesh: null,
},
gingerheadband: {
path: 'static/model/gingerheadband.json',
texture: this.textures.gingercolor,
normalmap: null,
morphTargets: false,
mesh: null,
},
gingerheadphones: {
path: 'static/model/gingerheadphones.json',
texture: null,
normalmap: null,
color: new THREE.Color('rgb(180, 180, 180)'),
morphTargets: false,
mesh: null,
},
gingerlefteye: {
path: 'static/model/gingerlefteye.json',
texture: this.textures.gingercolor,
normalmap: null,
morphTargets: false,
parent: this.leftEye,
position: new THREE.Vector3(-0.96, -6.169, -1.305),
mesh: null,
},
gingerrighteye: {
path: 'static/model/gingerrighteye.json',
texture: this.textures.gingercolor,
normalmap: null,
morphTargets: false,
parent: this.rightEye,
position: new THREE.Vector3(0.96, -6.169, -1.305),
mesh: null,
},
gingerteethbot: {
path: 'static/model/gingerteethbot.json',
texture: this.textures.gingercolor,
normalmap: null,
morphTargets: true,
mesh: null,
},
gingerteethtop: {
path: 'static/model/gingerteethtop.json',
texture: this.textures.gingercolor,
normalmap: null,
morphTargets: true,
mesh: null,
},
gingertongue: {
path: 'static/model/gingertongue.json',
texture: this.textures.gingercolor,
normalmap: null,
morphTargets: true,
mesh: null,
},
};
this.morphs = {
eyes: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [0, 1, 7, 8],
thresholds: [-1, 0, 0, 0.1],
// Move the eyes based on the sex of ginger. Man eyes are smaller and
// are moved backed to fit the appearance.
behavior: function (value) {
var sex = this.morphs.sex.value;
var recede = this.linear(sex, 0, -0.125, 1);
if (this.leftEyeOrigin === null) {
this.leftEyeOrigin = this.leftEye.position.clone();
}
if (this.rightEyeOrigin === null) {
this.rightEyeOrigin = this.rightEye.position.clone();
}
this.leftEye.position.x = this.leftEyeOrigin.x + recede;
this.leftEye.position.z = this.leftEyeOrigin.z + recede;
this.rightEye.position.x = this.rightEyeOrigin.x - recede;
this.rightEye.position.z = this.rightEyeOrigin.z + recede;
},
},
eyelookside: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [2, 3],
thresholds: [-1, 0],
},
expression: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [20, 9],
thresholds: [-1, 0],
},
jawrange: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [10, 11],
thresholds: [0, 0],
// Move the tongue down when moving the jaw.
behavior: function (value) {
this.morphs.tonguedown.value = value;
},
},
jawtwist: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [12, 13],
thresholds: [-1, 0],
// Move the tongue down when moving the jaw.
behavior: function (value) {
this.morphs.tonguetwist.value = value;
},
},
symmetry: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [14],
thresholds: [0],
},
lipcurl: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [15, 16],
thresholds: [-1, 0],
},
lipsync: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [17, 18, 19],
thresholds: [-1, 0, 0.5],
},
sex: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [22],
thresholds: [0],
},
width: {
value: 0,
mesh: this.meshes.gingerhead,
targets: [23, 24],
thresholds: [-1, 0],
},
tongue: {
value: 0,
mesh: this.meshes.gingertongue,
targets: [4],
thresholds: [0],
},
tonguedown: {
value: 0,
mesh: this.meshes.gingertongue,
targets: [1],
thresholds: [0],
},
tonguetwist: {
value: 0,
mesh: this.meshes.gingertongue,
targets: [2, 3],
thresholds: [-1, 0],
},
teethopenbot: {
value: 0,
mesh: this.meshes.gingerteethbot,
targets: [3, 0],
thresholds: [0, 0],
behavior: function (value) {
var jawrange = this.morphs.jawrange.value;
this.morphs.teethopenbot.value = jawrange;
},
},
teethopentop: {
value: 0,
mesh: this.meshes.gingerteethtop,
targets: [3, 0],
thresholds: [0, 0],
behavior: function (value) {
var jawrange = this.morphs.jawrange.value;
this.morphs.teethopentop.value = jawrange;
},
},
teethsidebot: {
value: 0,
mesh: this.meshes.gingerteethbot,
targets: [1, 2],
thresholds: [-1, 0],
behavior: function (value) {
var jawtwist = this.morphs.jawtwist.value;
this.morphs.teethsidebot.value = jawtwist;
},
},
teethsidetop: {
value: 0,
mesh: this.meshes.gingerteethtop,
targets: [1, 2],
thresholds: [-1, 0],
behavior: function (value) {
var jawtwist = this.morphs.jawtwist.value;
this.morphs.teethsidetop.value = jawtwist;
},
},
};
this.controls = {
eyes: {
control: 'eyes',
min: -1,
max: 1,
morph: this.morphs.eyes,
},
expression: {
control: 'expression',
min: -1,
max: 1,
morph: this.morphs.expression,
},
jawrange: {
control: 'jawrange',
min: 0,
max: 1,
morph: this.morphs.jawrange,
},
jawtwist: {
control: 'jawtwist',
min: -1,
max: 1,
morph: this.morphs.jawtwist,
},
symmetry: {
control: 'symmetry',
min: 0,
max: 1,
morph: this.morphs.symmetry,
},
lipcurl: {
control: 'lipcurl',
min: -1,
max: 1,
morph: this.morphs.lipcurl,
},
lipsync: {
control: 'lipsync',
min: -1,
max: 1,
morph: this.morphs.lipsync,
},
sex: {
control: 'sex',
min: 0,
max: 1,
morph: this.morphs.sex,
},
width: {
control: 'width',
min: -1,
max: 1,
morph: this.morphs.width,
},
tongue: {
control: 'tongue',
min: 0,
max: 1,
morph: this.morphs.tongue,
},
};
}
/**
* Implement to describe the element's DOM using lit-html.
* Use the element current props to return a lit-html template result
* to render into the element.
*/
render() {
return html`
<div class="ginger-header">
<header id="header" class="td-header">
<div class="td-logo-container">
<a
href="https://labs.thisdot.co/"
class="td-logo"
title="This Dot Labs"
>
<svg
xmlns="http://www.w3.org/2000/svg"
id="Layer_1"
width="152"
height="34"
data-name="Layer 1"
viewBox="0 0 279.93 34.62"
>
<defs>
<style>
.cls-1 {
fill: #626d8e;
}
.cls-2 {
fill: #f46663;
}
.cls-3 {
fill: #9faccc;
}
</style>
</defs>
<title>
thisdot-publication
</title>
<path
d="M8.94,6.42H0V.59H24.77V6.42H15.83V34.07H8.94Z"
class="cls-1"
/>
<path
d="M40,.59h6.91V15.5h12V.59h6.88V34.07H58.9V21.35h-12V34.07H40Z"
class="cls-1"
/>
<path d="M90.58.59V34.07H83.7V.59Z" class="cls-1" />
<path
d="M106.84,25.16h7c.24,2.39,1.91,3.54,4.26,3.54S122,27.31,122,25.16s-1.34-3.4-5.89-5.26c-6.67-2.75-9-5.9-9-10.82,0-5.5,4-9.09,10.47-9.09C123.5,0,128,3.54,128,9.37h-7a3.28,3.28,0,0,0-3.59-3.44c-2.25,0-3.4,1.39-3.4,3.06,0,2,1.39,3.18,6.07,5.19,6.69,2.87,8.84,5.88,8.84,10.57,0,5.9-4.21,9.87-10.95,9.87S107.22,30.52,106.84,25.16Z"
class="cls-1"
/>
<path
d="M162.61,34.07H151.43V.59h11.19c10.85,0,18.17,6.12,18.17,16.74S173.47,34.07,162.61,34.07Zm.05-27.64h-4.35V28.22h4.35c6.27,0,11.14-3.63,11.14-10.85S168.93,6.42,162.66,6.42Z"
class="cls-1"
/>
<path
d="M264.11,6.42h-8.95V.59h24.77V6.42H271V34.07h-6.88Z"
class="cls-1"
/>
<circle cx="218.03" cy="17.03" r="10.41" class="cls-2" />
<polygon
points="234.1 0.29 225.53 0.29 238.38 17.03 225.53 33.76 234.1 33.76 246.96 17.03 234.1 0.29"
class="cls-3"
/>
<polygon
points="201.96 0.29 210.53 0.29 197.67 17.03 210.53 33.76 201.96 33.76 189.11 17.03 201.96 0.29"
class="cls-3"
/>
</svg>
</a>
</div>
<div>
<a
id="hide-header-btn"
class="td-button td-button-outline"
href="#"
@click="${this.handleHideHeader}"
>Hide This Header ❌</a
>
</div>
<div>
<a
href="${blogPostLink}"
target="_blank"
rel="noopener noreferrer"
class="td-button td-button-outline"
title="Learn how we built this"
>Learn More »</a
>
</div>
</header>
</div>
<div id="renderer"></div>
<div class="panel">
<div class="flex-container flex-stretch dual-pane">
<div>
<!-- Controls for changing the morphs. -->
<label for="range">Range of Motion</label>
<input
id="morph-range"
class="td-range"
type="range"
min="0"
max="1"
step="0.01"
value="0"
@change="${this.handleRangeSlide}"
@input="${this.handleRangeSlide}"
/>
</div>
<div>
<label for="morph">Morph Target</label>
<select
id="morph"
class="td-select"
@change="${this.handleMorphSelect}"
>
<option value="eyes">Eyes</option>
<option value="expression">Expression</option>
<option value="jawrange">Jaw Height</option>
<option value="jawtwist">Jaw Twist</option>
<option value="symmetry">Symmetry</option>
<option value="lipcurl">Lip Curl</option>
<option value="lipsync">Lip Sync</option>
<option value="sex">Face Structure</option>
<option value="width">Jaw Width</option>
<option value="tongue">Tongue</option>
</select>
</div>
</div>
<div class="flex-container button-container">
<div>
<button
id="share"
class="td-button"
type="button"
@click="${this.handleShare}"
>
Share Pose
</button>
</div>
<div>
<button
id="screenshot"
class="td-button"
type="button"
@click="${this.handleScreenshot}"
>
Take Screenshot
</button>
</div>
<div>
<button
id="mousetrack"
class="td-button"
type="button"
class="buttoncolor-OFF"
@click="${this.handleMouseTrack}"
>
Follow OFF
</button>
</div>
</div>
</div>
<div id="screenshot-modal" class="hidden">
<div class="full-shadow"></div>
<div class="modal">
<div class="title flex-container flex-space-between">
<h1>Screenshot</h1>
<button
id="copytoclipboard-image"
class="td-button"
type="button"
@click="${this.handleDownloadScreenshot}"
>
Download
</button>
</div>
<div id="screenshot-image-container">
<img id="screenshot-image" />
</div>
</div>
</div>
<div id="share-modal" class="hidden">
<div class="full-shadow"></div>
<div class="modal">
<div class="title flex-container flex-space-between">
<h1>Share Link</h1>
<button
id="copytoclipboard-share"
class="td-button"
data-clipboard-target="#share-link"
type="button"
>
Copy to Clipboard
</button>
</div>
<textarea id="share-link"></textarea>
</div>
</div>
<div id="counter" class="hidden"></div>
`;
}
/**
* Called when the element's DOM has been updated and rendered.
* @param {*} changedProperties
*/
updated(changedProperties) {
if (this.shadowRoot.querySelector('#renderer>canvas')) return;
this.init();
}
/**
* Called when the slider is moved and updates the selected morph target.
* @param {Event} event
*/
handleRangeSlide(event) {
const progress = event.target.valueAsNumber;
this.updateMorph(null, progress);
this.morph();
}
/**
* Changes the selected morph target.
* @param {Event} event
*/
handleMorphSelect(event) {
const value = event.target.value;
this.select(value);
}
/**
* Displays the share modal.
* @param {Event} event
*/
handleShare(event) {
const modal = this.shadowRoot.getElementById('share-modal');
modal.classList.remove('hidden');
const shareLink = this.shadowRoot.getElementById('share-link');
shareLink.value = this.generateShareLink();
}
/**
* Takes a screenshot after finishing a countdown.
* @param {Event} event
*/
handleScreenshot(event) {
const seconds = 3;
this.countdownScreenshot(seconds);
}
/**
* Toggles Ginger's mouse tracking. If enabled her head follows the cursor.
* @param {Event} event
*/
handleMouseTrack(event) {
this.isMouseTracking = !this.isMouseTracking;
const elButton = this.shadowRoot.getElementById('mousetrack');
const currentStateLabel = this.isMouseTracking ? 'ON' : 'OFF';
const currentState = this.isMouseTracking ? 'active' : 'inactive';
const oppositeState = !this.isMouseTracking ? 'active' : 'inactive';
elButton.textContent = `Follow ${currentStateLabel}`;
elButton.classList.add(`td-button-${currentState}`);
elButton.classList.remove(`td-button-${oppositeState}`);
}
/**
* Points Ginger's head at the cursor whenever the mouse moves.
* @param {Event} event
*/
handleMouseMove(event) {
// Mock a touch event so we don't need to handle both mouse and touch events
// inside the look at function.
const data = {
touches: [{ clientX: event.clientX, clientY: event.clientY }],
type: 'mousemove',
};
this.lookAtCursor(data);
}
/**
* Points Ginger's head at the cursor whenever the touch point moves.
* @param {Event} event
*/
handleTouchMove(event) {
this.lookAtCursor(event);
}
/**
* Called when the window is resized.
* @param {Event} event
*/
handleWindowResize(event) {
this.recalculateAspect();
this.renderer.setSize(this.clientWidth, this.clientHeight);
}
/**
* Called after the clipboard library successfully copies the share text.
* @param {Event} event
*/
handleCopy(event) {
const clipboardButton = this.shadowRoot.getElementById(
'copytoclipboard-share'
);
clipboardButton.textContent = 'Copied!';
setTimeout(() => {
clipboardButton.textContent = 'Copy to Clipboard';
}, 2000);
}
/**
* Downloads the screenshot that was taken last.
* @param {Event} event
*/
handleDownloadScreenshot(event) {
const image = this.shadowRoot.getElementById('screenshot-image').src;
const timestamp = Math.floor(Date.now() / 1000);
const download = document.createElement('a');
download.href = image;
download.download = 'ginger-' + timestamp + '.jpg';
download.click();
download.remove();
}
/**
* Removes the site header when the hide link is clicked.
* @param {Event} event
*/
handleHideHeader(event) {
this.shadowRoot.getElementById('header').remove();
this.camera.position.y = 4;
}
/**
* Shows the screenshot counter modal and takes a screenshot after finishing
* a countdown.
* @param {number} seconds
*/
async countdownScreenshot(seconds) {
if (this.isTakingScreenshot) return;
try {
this.isTakingScreenshot = true;
const counter = this.shadowRoot.getElementById('counter');
counter.classList.remove('hidden');
while (seconds > 0) {
this.screenshotCounter = seconds;
counter.innerHTML = seconds; // FIXME
await new Promise((resolve) => setTimeout(resolve, 1000));
seconds -= 1;
}
this.takeScreenshot();
counter.classList.add('hidden');
} finally {
this.isTakingScreenshot = false;
}
}
/**
* Show the screenshot modal, take a screenshot, and display it in the modal.
*/
takeScreenshot() {
const modal = this.shadowRoot.getElementById('screenshot-modal');
modal.classList.remove('hidden');
const image = this.shadowRoot.getElementById('screenshot-image');
image.src = this.renderer.domElement.toDataURL('image/jpeg', 0.8);
}
/**
* Points ginger's head at the cursor.
* @param {Event} event
*/
lookAtCursor(event) {
if (this.isMouseTracking) {
const mouse = new THREE.Vector3(
(event.touches[0].clientX / this.clientWidth) * 2 - 1,
-(event.touches[0].clientY / this.clientHeight) * 2 + 1,
0.5
);
mouse.unproject(this.camera);
// When getting the direction, flip the x and y axis or the eyes will
// look the wrong direction.
let direction = mouse.sub(this.camera.position).normalize();
direction.x *= -1;
direction.y *= -1;
const distance = this.camera.position.z / direction.z;
const position = this.camera.position
.clone()
.add(direction.multiplyScalar(distance));
// Track the cursor with the eyes with no adjustments.
this.leftEye.lookAt(position);
this.rightEye.lookAt(position);
// Track the cursor with the head, but dampened. If we don't dampen the
// head tracking then she will always try to face the cursor head on.
this.ginger.lookAt(position);
this.ginger.rotation.x /= 5;
this.ginger.rotation.y /= 5;
this.ginger.rotation.z = 0;
}
}
/**
* Calculates a new aspect using the size of the window and generate a new
* projection matrix for the main perspective camera.
*/
recalculateAspect() {
this.aspect = this.clientWidth / this.clientHeight;
this.camera.aspect = this.aspect;
this.camera.updateProjectionMatrix();
}
/**
* Adds a callback to the action queue that will be executed right before the
* next frame is rendered.
* @param {Function} callback
* @param {Object} args
*/
queueNextFrame(callback, args) {
this.queue.push({
callback: callback,
args: args,
});
}
/**
* The "game" loop where actions are executed and the renderer is invoked.
*/
animate() {
requestAnimationFrame(this.animate.bind(this));
let i = this.queue.length;
while (i--) {
const args = this.queue[i].args;
const callback = this.queue[i].callback;
callback(args);
this.queue.splice(i, 1);
}
this.renderer.render(this.scene, this.camera);
}
/**
* Selects a morph for editing.
* @param {string} morph
*/
select(morph) {
let selectControl;
let found = false;
for (const control in this.controls) {
if (this.controls[control].control == morph) {
this.selected = morph;
selectControl = this.controls[control];
found = true;
break;
}
}
if (!found) {
return;
}
const min = selectControl.min;
const max = selectControl.max;
const percent =
((selectControl.morph.value - min) * 100) / (max - min) / 100;
const slider = this.shadowRoot.getElementById('morph-range');
slider.value = percent;
}
/**
* Apply morph target influences to the objects in the scene.
*/
morph() {
for (let item in this.morphs) {
const morphTarget = this.morphs[item];
if (morphTarget.behavior !== undefined) {
morphTarget.behavior.bind(this)(morphTarget.value);
}
// Find which morph needs to have the value applied to. This is determined
// using thresholds.
let target;
for (let i = 0; i < morphTarget.thresholds.length; i++) {
const threshold = morphTarget.thresholds[i];
if (morphTarget.value >= threshold) {
target = i;
}
}
for (let i = 0; i < morphTarget.targets.length; i++) {
const index = morphTarget.targets[i];
let value = 0;
if (morphTarget.targets[i] === morphTarget.targets[target]) {
value = Math.abs(morphTarget.value);
}
morphTarget.mesh.mesh.morphTargetInfluences[index] = value;
}
}
}
/**
* Updates a morphs current value by name.
* @param {string} morph
* @param {number} progress
*/
updateMorph(morph, progress) {
let selectControl;
let found = false;
morph = morph || this.selected;
for (const control in this.controls) {
if (this.controls[control].control == morph) {
selectControl = this.controls[control];
found = true;
break;
}
}
if (!found) {
return;
}
const min = selectControl.min;
const max = selectControl.max;
const value = (max - min) * progress + min;
selectControl.morph.value = value;
}
/**
* Returns a share link to share the currently morphed model.
*/
generateShareLink() {
const params = [];
const url = `${location.protocol}//${location.host}${location.pathname}`;
for (const control in this.controls) {
const selectControl = this.controls[control];
const min = selectControl.min;
const max = selectControl.max;
const percent =
((selectControl.morph.value - min) * 100) / (max - min) / 100;
params.push([selectControl.control, percent.toString()]);
}
const paramsString = new URLSearchParams(params).toString();
return `${url}?${paramsString}`;
}
/**
* Loads in all required assets from the network.
*/
async loadAssets() {
const texturesPromise = this.loadTextures();
const meshesPromise = this.loadMeshes();
await meshesPromise;
// Add loaded meshes into the scene and apply initial transformations. We
// do the copies during the next animation frame so THREE doesn't
// overwrite them during initialization.
for (let mesh in this.meshes) {
if (this.meshes[mesh].position !== undefined) {
const args = {
mesh: this.meshes[mesh],
};
this.queueNextFrame((args) => {
args.mesh.mesh.position.copy(args.mesh.position);
}, args);
}
if (this.meshes[mesh].parent !== undefined) {
this.meshes[mesh].parent.add(this.meshes[mesh].mesh);
} else {
this.ginger.add(this.meshes[mesh].mesh);
}
}
await Promise.all([texturesPromise, meshesPromise]);
}
/**
* Loads a texture over the network.
* @param {THREE.TextureLoader} textureLoader
* @param {String} path
* @param {String} mesh
*/
async loadTexture(textureLoader, path, texture) {
const loadedTexture = new Promise((resolve, reject) => {
textureLoader.load(path, (loadedTexture) => {
resolve(loadedTexture);
});
}).catch((err) => {
throw err;
});
this.textures[texture].texture = loadedTexture;
return loadedTexture;
}
/**
* Loads in all required textures over the network.
*/
async loadTextures() {
const textureLoader = new THREE.TextureLoader();
const promises = [];
for (let texture in this.textures) {
const path = this.textures[texture].path;
promises.push(this.loadTexture(textureLoader, path, texture));
}
return Promise.all(promises);
}
/**
* Loads a mesh over the network and creates the THREE objects for it.
* @param {THREE.JSONLoader} jsonLoader
* @param {String} path
* @param {String} mesh
*/
async loadMesh(jsonLoader, path, mesh) {
const geometry = await new Promise((resolve, reject) => {
jsonLoader.load(path, (geometry) => {
resolve(geometry);
});
}).catch((err) => {
throw err;
});
const bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
let texture, normalmap, color;
if (this.meshes[mesh].texture !== null) {
texture = await this.meshes[mesh].texture.texture;
}
if (this.meshes[mesh].normalmap !== null) {
normalmap = await this.meshes[mesh].normalmap.texture;
}
if (this.meshes[mesh].color !== null) {
color = this.meshes[mesh].color;
}
const materialParams = {
vertexColors: THREE.FaceColors,
flatShading: false,
morphTargets: this.meshes[mesh].morphTargets,
};
if (texture) {
materialParams.map = texture;
}
if (normalmap) {
materialParams.normalMap = normalmap;
}
if (color) {
materialParams.color = color;
}
const material = new THREE.MeshStandardMaterial(materialParams);
this.meshes[mesh].mesh = new THREE.Mesh(bufferGeometry, material);
}
/**
* Loads in all required meshes over the network.
*/
async loadMeshes() {
// FIXME: Replace LegacyJSONLoader with a supported loader once we get the
// Ginger assets converted into a more modern format.
const jsonLoader = new LegacyJSONLoader();
const promises = [];
for (let mesh in this.meshes) {
const path = this.meshes[mesh].path;
promises.push(this.loadMesh(jsonLoader, path, mesh));
}
return Promise.all(promises);
}
/**
* Linear easing function.
* @param {*} t current time
* @param {*} b start value
* @param {*} c change in value
* @param {*} d duration
*/
linear(t, b, c, d) {
return (c * t) / d + b;
}
/**
* Setup the Ginger three.js scene.
*/
async init() {
// Initialize the clipboard library used for the copy button.
const clipboardButton = this.shadowRoot.getElementById(
'copytoclipboard-share'
);
const clipboard = new Clipboard(clipboardButton, {
target: (trigger) => this.shadowRoot.getElementById('share-link'),
});
clipboard.on('success', this.handleCopy.bind(this));
const overlay = this.shadowRoot.querySelectorAll('.full-shadow');
for (let i = 0; i < overlay.length; i++) {
overlay[i].addEventListener('click', function (e) {
var parent = e.target.parentNode;
parent.classList.add('hidden');
});
}
this.scene = new THREE.Scene();
this.aspect = this.clientWidth / this.clientHeight;
this.camera = new THREE.PerspectiveCamera(55, this.aspect, 0.1, 1000);
this.camera.position.y = 5;
this.camera.position.z = 14;
// Create a renderer the size of the window and attach it to the DOM.
this.renderer = new THREE.WebGLRenderer({
antialias: true,
preserveDrawingBuffer: true,
});
this.renderer.setSize(this.clientWidth, this.clientHeight);
this.shadowRoot
.getElementById('renderer')
.appendChild(this.renderer.domElement);
// Allow viewport resizing whenever the window resizes.
window.addEventListener('resize', this.handleWindowResize.bind(this));
// Setup mouse events so ginger's eyes can track the mouse.
const renderer = this.shadowRoot.getElementById('renderer');
this.addEventListener('mousemove', this.handleMouseMove.bind(this));
this.addEventListener('touchmove', this.handleTouchMove.bind(this));
// Set the initial values of ginger to the values in the GET params.
const shareParams = new URLSearchParams(window.location.search);
for (const control in this.controls) {
const selectedControl = this.controls[control];
if (shareParams.get(selectedControl.control) != null) {
this.updateMorph(
selectedControl.control,
shareParams.get(selectedControl.control)
);
}
}
// Add everything to the scene.
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(0, 0, 1);
this.scene.add(directionalLight);
this.scene.add(this.ginger);
this.leftEye.position.set(0.96, 6.169, 1.305);
this.ginger.add(this.leftEye);
this.rightEye.position.set(-0.96, 6.169, 1.305);
this.ginger.add(this.rightEye);
await this.loadAssets();
this.select(this.selected);
this.animate();
this.morph();
}
} |
JavaScript | class Parameter {
constructor(opts) {
opts = opts || {};
if (typeof opts.translate === 'function') {
this.translate = opts.translate;
}
if (opts.validateRoot) this.validateRoot = true;
if (opts.convert) this.convert = true;
if (opts.widelyUndefined) this.widelyUndefined = true;
}
t() {
var args = Array.prototype.slice.call(arguments);
if (typeof this.translate === 'function') {
return this.translate.apply(this, args);
} else {
return util.format.apply(util, args);
}
}
/**
* validate
*
* @param {Object} rules
* @return {Object} obj
* @api public
*/
validate(rules, obj) {
if (typeof rules !== 'object') {
throw new TypeError('need object type rule');
}
if (this.validateRoot && (typeof obj !== 'object' || !obj)) {
return [{
message: this.t('the validated value should be a object'),
code: this.t('invalid'),
field: undefined,
type: 'rule',
}];
}
var self = this;
var errors = [];
for (var key in rules) {
var rule = formatRule(rules[key]);
var value = obj[key];
if (typeof value === 'string' && rule.trim === true) {
value = obj[key] = value.trim();
}
// treat null / '' / NaN as undefined
let widelyUndefined = this.widelyUndefined;
if ('widelyUndefined' in rule) widelyUndefined = rule.widelyUndefined;
if (widelyUndefined &&
(value === '' || value === null || Number.isNaN(value))) {
value = obj[key] = undefined;
}
var has = value !== null && value !== undefined;
if (!has) {
if (rule.required !== false) {
errors.push({
message: this.t('required'),
field: key,
code: this.t('missing_field'),
type: 'required',
});
}
// support default value
if ('default' in rule) {
obj[key] = rule.default;
}
continue;
}
var checker = TYPE_MAP[rule.type];
if (!checker) {
throw new TypeError('rule type must be one of ' + Object.keys(TYPE_MAP).join(', ') +
', but the following type was passed: ' + rule.type);
}
convert(rule, obj, key, this.convert);
var msg = checker.call(self, rule, obj[key], obj);
if (typeof msg === 'string') {
errors.push({
message: msg,
code: this.t('invalid'),
field: key
});
}
if (typeof msg === 'object' && !Array.isArray(msg)) {
errors.push({
message: msg.message,
code: this.t('invalid'),
field: key,
type: msg.type,
})
}
if (Array.isArray(msg)) {
msg.forEach(function (e) {
var dot = rule.type === 'object' ? '.' : '';
e.field = key + dot + e.field;
errors.push(e);
});
}
}
if (errors.length) {
return errors;
}
}
} |
JavaScript | class ControllerMovementKey {
/**
*
* @param {boolean} forward
* @param {boolean} shift
* @param {boolean} backward
* @param {boolean} turnRight
* @param {boolean} turnLeft
* @param {boolean} strafeRight
* @param {boolean} strafeLeft
* @param {boolean} jump
*/
constructor(forward = false, shift = false, backward = false, turnRight = false, turnLeft = false, strafeRight = false, strafeLeft = false, jump = false) {
this.forward = forward;
this.shift = shift;
this.backward = backward;
this.turnRight = turnRight;
this.turnLeft = turnLeft;
this.strafeRight = strafeRight;
this.strafeLeft = strafeLeft;
this.jump = jump;
}
reset() {
this.forward = false;
this.shift = false;
this.backward = false;
this.turnRight = false;
this.turnLeft = false;
this.strafeRight = false;
this.strafeLeft = false;
this.jump = false;
}
copyFrom(controllerMovementKey) {
if (!(controllerMovementKey instanceof ControllerMovementKey)) {
return false;
}
this.forward = controllerMovementKey.forward;
this.shift = controllerMovementKey.shift;
this.backward = controllerMovementKey.backward;
this.turnRight = controllerMovementKey.turnRight;
this.turnLeft = controllerMovementKey.turnLeft;
this.strafeRight = controllerMovementKey.strafeRight;
this.strafeLeft = controllerMovementKey.strafeLeft;
this.jump = controllerMovementKey.jump;
}
clone() {
return new ControllerMovementKey(this.forward, this.shift, this.backward, this.turnRight, this.turnLeft, this.strafeRight, this.strafeLeft, this.jump);
}
equals(controllerMovementKey) {
if (!(controllerMovementKey instanceof ControllerMovementKey)) {
return false;
}
return (
this.forward == controllerMovementKey.forward &&
this.shift == controllerMovementKey.shift &&
this.backward == controllerMovementKey.backward &&
this.turnRight == controllerMovementKey.turnRight &&
this.turnLeft == controllerMovementKey.turnLeft &&
this.strafeRight == controllerMovementKey.strafeRight &&
this.strafeLeft == controllerMovementKey.strafeLeft &&
this.jump == controllerMovementKey.jump
)
}
toSource() {
return `new ControllerMovementKey(${this.forward ? "true" : "false"}, ${this.shift ? "true" : "false"}, ${this.backward ? "true" : "false"}, ${this.turnRight ? "true" : "false"}, ${this.turnLeft ? "true" : "false"}, ${this.strafeRight ? "true" : "false"}, ${this.strafeLeft ? "true" : "false"}, ${this.jump ? "true" : "false"})`;
}
toBinary() {
return this.toInteger().toString(2);
}
toInteger() {
let integer = 0;
if (this.forward) {
integer += 1;
}
if (this.shift) {
integer += 2;
}
if (this.backward) {
integer += 4;
}
if (this.turnRight) {
integer += 8;
}
if (this.turnLeft) {
integer += 16;
}
if (this.strafeRight) {
integer += 32;
}
if (this.strafeLeft) {
integer += 64;
}
if (this.jump) {
integer += 128;
}
return integer;
}
fromBinary(binary) {
return this.fromInteger(Number.parseInt(binary, 2));
}
fromInteger(integer) {
if (integer > 128) {
integer -= 128;
this.jump = true;
}
if (integer > 64) {
integer -= 64;
this.strafeLeft = true;
}
if (integer > 32) {
integer -= 32;
this.strafeRight = true;
}
if (integer > 16) {
integer -= 16;
this.turnLeft = true;
}
if (integer > 8) {
integer -= 8;
this.turnRight = true;
}
if (integer > 4) {
integer -= 4;
this.backward = true;
}
if (integer > 2) {
integer -= 2;
this.shift = true;
}
if (integer > 1) {
integer -= 1;
this.forward = true;
}
return true;
}
} |
JavaScript | class Address1 extends BaseModel {
/**
* @constructor
* @param {Object} obj The object passed to constructor
*/
constructor(obj) {
super(obj);
if (obj === undefined || obj === null) return;
this.type = this.constructor.getValue(obj.type);
this.street = this.constructor.getValue(obj.street);
this.number = this.constructor.getValue(obj.number);
this.complement = this.constructor.getValue(obj.complement);
this.zip = this.constructor.getValue(obj.zip);
this.neighborhood = this.constructor.getValue(obj.neighborhood);
this.city = this.constructor.getValue(obj.city);
this.state = this.constructor.getValue(obj.state);
this.country = this.constructor.getValue(obj.country);
}
/**
* Function containing information about the fields of this model
* @return {array} Array of objects containing information about the fields
*/
static mappingInfo() {
return super.mappingInfo().concat([
{ name: 'type', realName: 'type' },
{ name: 'street', realName: 'street' },
{ name: 'number', realName: 'number' },
{ name: 'complement', realName: 'complement' },
{ name: 'zip', realName: 'zip' },
{ name: 'neighborhood', realName: 'neighborhood' },
{ name: 'city', realName: 'city' },
{ name: 'state', realName: 'state' },
{ name: 'country', realName: 'country' },
]);
}
/**
* Function containing information about discriminator values
* mapped with their corresponding model class names
*
* @return {object} Object containing Key-Value pairs mapping discriminator
* values with their corresponding model classes
*/
static discriminatorMap() {
return {};
}
} |
JavaScript | class ExtractionResult {
constructor(messages, errors) {
this.messages = messages;
this.errors = errors;
}
} |
JavaScript | class MessageExtractor {
constructor(_htmlParser, _parser, _implicitTags, _implicitAttrs) {
this._htmlParser = _htmlParser;
this._parser = _parser;
this._implicitTags = _implicitTags;
this._implicitAttrs = _implicitAttrs;
}
extract(template, sourceUrl, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
this._messages = [];
this._errors = [];
const res = this._htmlParser.parse(template, sourceUrl, true);
if (res.errors.length == 0) {
this._recurse(res.rootNodes, interpolationConfig);
}
return new ExtractionResult(this._messages, this._errors.concat(res.errors));
}
_extractMessagesFromPart(part, interpolationConfig) {
if (part.hasI18n) {
this._messages.push(part.createMessage(this._parser, interpolationConfig));
this._recurseToExtractMessagesFromAttributes(part.children, interpolationConfig);
}
else {
this._recurse(part.children, interpolationConfig);
}
if (isPresent(part.rootElement)) {
this._extractMessagesFromAttributes(part.rootElement, interpolationConfig);
}
}
_recurse(nodes, interpolationConfig) {
if (isPresent(nodes)) {
let parts = partition(nodes, this._errors, this._implicitTags);
parts.forEach(part => this._extractMessagesFromPart(part, interpolationConfig));
}
}
_recurseToExtractMessagesFromAttributes(nodes, interpolationConfig) {
nodes.forEach(n => {
if (n instanceof HtmlElementAst) {
this._extractMessagesFromAttributes(n, interpolationConfig);
this._recurseToExtractMessagesFromAttributes(n.children, interpolationConfig);
}
});
}
_extractMessagesFromAttributes(p, interpolationConfig) {
let transAttrs = isPresent(this._implicitAttrs[p.name]) ? this._implicitAttrs[p.name] : [];
let explicitAttrs = [];
// `i18n-` prefixed attributes should be translated
p.attrs.filter(attr => attr.name.startsWith(I18N_ATTR_PREFIX)).forEach(attr => {
try {
explicitAttrs.push(attr.name.substring(I18N_ATTR_PREFIX.length));
this._messages.push(messageFromI18nAttribute(this._parser, interpolationConfig, p, attr));
}
catch (e) {
if (e instanceof I18nError) {
this._errors.push(e);
}
else {
throw e;
}
}
});
// implicit attributes should also be translated
p.attrs.filter(attr => !attr.name.startsWith(I18N_ATTR_PREFIX))
.filter(attr => explicitAttrs.indexOf(attr.name) == -1)
.filter(attr => transAttrs.indexOf(attr.name) > -1)
.forEach(attr => this._messages.push(messageFromAttribute(this._parser, interpolationConfig, attr)));
}
} |
JavaScript | class FilePicker extends SettingField {
/**
* @param {string} name - name label of the setting
* @param {string} note - help/note to show underneath or above the setting
* @param {callable} onChange - callback to perform on setting change, callback receives File object
*/
constructor(name, note, onChange) {
const ReactFilePicker = DOMTools.parseHTML(`<input type="file" class="${DiscordClasses.BasicInputs.inputDefault.add("file-input")}">`);
ReactFilePicker.addEventListener("change", (event) => {
this.onChange(event.target.files[0]);
});
super(name, note, onChange, ReactFilePicker);
}
} |
JavaScript | class MultiRegex {
constructor() {
this.matchIndexes = {};
// @ts-ignore
this.regexes = [];
this.matchAt = 1;
this.position = 0;
}
// @ts-ignore
addRule(re, opts) {
opts.position = this.position++;
// @ts-ignore
this.matchIndexes[this.matchAt] = opts;
this.regexes.push([opts, re]);
this.matchAt += countMatchGroups(re) + 1;
}
compile() {
if (this.regexes.length === 0) {
// avoids the need to check length every time exec is called
// @ts-ignore
this.exec = () => null;
}
const terminators = this.regexes.map(el => el[1]);
this.matcherRe = langRe(join(terminators), true);
this.lastIndex = 0;
}
/** @param {string} s */
exec(s) {
this.matcherRe.lastIndex = this.lastIndex;
const match = this.matcherRe.exec(s);
if (!match) { return null; }
// eslint-disable-next-line no-undefined
const i = match.findIndex((el, i) => i > 0 && el !== undefined);
// @ts-ignore
const matchData = this.matchIndexes[i];
// trim off any earlier non-relevant match groups (ie, the other regex
// match groups that make up the multi-matcher)
match.splice(0, i);
return Object.assign(match, matchData);
}
} |
JavaScript | class ResumableMultiRegex {
constructor() {
// @ts-ignore
this.rules = [];
// @ts-ignore
this.multiRegexes = [];
this.count = 0;
this.lastIndex = 0;
this.regexIndex = 0;
}
// @ts-ignore
getMatcher(index) {
if (this.multiRegexes[index]) return this.multiRegexes[index];
const matcher = new MultiRegex();
this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));
matcher.compile();
this.multiRegexes[index] = matcher;
return matcher;
}
resumingScanAtSamePosition() {
return this.regexIndex !== 0;
}
considerAll() {
this.regexIndex = 0;
}
// @ts-ignore
addRule(re, opts) {
this.rules.push([re, opts]);
if (opts.type === "begin") this.count++;
}
/** @param {string} s */
exec(s) {
const m = this.getMatcher(this.regexIndex);
m.lastIndex = this.lastIndex;
let result = m.exec(s);
// The following is because we have no easy way to say "resume scanning at the
// existing position but also skip the current rule ONLY". What happens is
// all prior rules are also skipped which can result in matching the wrong
// thing. Example of matching "booger":
// our matcher is [string, "booger", number]
//
// ....booger....
// if "booger" is ignored then we'd really need a regex to scan from the
// SAME position for only: [string, number] but ignoring "booger" (if it
// was the first match), a simple resume would scan ahead who knows how
// far looking only for "number", ignoring potential string matches (or
// future "booger" matches that might be valid.)
// So what we do: We execute two matchers, one resuming at the same
// position, but the second full matcher starting at the position after:
// /--- resume first regex match here (for [number])
// |/---- full match here for [string, "booger", number]
// vv
// ....booger....
// Which ever results in a match first is then used. So this 3-4 step
// process essentially allows us to say "match at this position, excluding
// a prior rule that was ignored".
//
// 1. Match "booger" first, ignore. Also proves that [string] does non match.
// 2. Resume matching for [number]
// 3. Match at index + 1 for [string, "booger", number]
// 4. If #2 and #3 result in matches, which came first?
if (this.resumingScanAtSamePosition()) {
if (result && result.index === this.lastIndex) ; else { // use the second matcher result
const m2 = this.getMatcher(0);
m2.lastIndex = this.lastIndex + 1;
result = m2.exec(s);
}
}
if (result) {
this.regexIndex += result.position + 1;
if (this.regexIndex === this.count) {
// wrap-around to considering all matches again
this.considerAll();
}
}
return result;
}
} |
JavaScript | class Emitter {
constructor(options) {
this._disposed = false;
this._options = options;
this._leakageMon = _globalLeakWarningThreshold > 0
? new LeakageMonitor(this._options && this._options.leakWarningThreshold)
: undefined;
}
/**
* For the public to allow to subscribe
* to events from this Emitter
*/
get event() {
if (!this._event) {
this._event = (listener, thisArgs, disposables) => {
if (!this._listeners) {
this._listeners = new linkedList_1.LinkedList();
}
const firstListener = this._listeners.isEmpty();
if (firstListener && this._options && this._options.onFirstListenerAdd) {
this._options.onFirstListenerAdd(this);
}
const remove = this._listeners.push(!thisArgs ? listener : [listener, thisArgs]);
if (firstListener && this._options && this._options.onFirstListenerDidAdd) {
this._options.onFirstListenerDidAdd(this);
}
if (this._options && this._options.onListenerDidAdd) {
this._options.onListenerDidAdd(this, listener, thisArgs);
}
// check and record this emitter for potential leakage
let removeMonitor;
if (this._leakageMon) {
removeMonitor = this._leakageMon.check(this._listeners.size);
}
let result;
result = {
dispose: () => {
if (removeMonitor) {
removeMonitor();
}
result.dispose = Emitter._noop;
if (!this._disposed) {
remove();
if (this._options && this._options.onLastListenerRemove) {
const hasListeners = (this._listeners && !this._listeners.isEmpty());
if (!hasListeners) {
this._options.onLastListenerRemove(this);
}
}
}
}
};
if (Array.isArray(disposables)) {
disposables.push(result);
}
return result;
};
}
return this._event;
}
/**
* To be kept private to fire an event to
* subscribers
*/
fire(event) {
if (this._listeners) {
// put all [listener,event]-pairs into delivery queue
// then emit all event. an inner/nested event might be
// the driver of this
if (!this._deliveryQueue) {
this._deliveryQueue = [];
}
for (let iter = this._listeners.iterator(), e = iter.next(); !e.done; e = iter.next()) {
this._deliveryQueue.push([e.value, event]);
}
while (this._deliveryQueue.length > 0) {
const [listener, event] = this._deliveryQueue.shift();
try {
if (typeof listener === 'function') {
listener.call(undefined, event);
}
else {
listener[0].call(listener[1], event);
}
}
catch (e) {
console.error(e);
}
}
}
}
dispose() {
if (this._listeners) {
this._listeners = undefined;
}
if (this._deliveryQueue) {
this._deliveryQueue.length = 0;
}
if (this._leakageMon) {
this._leakageMon.dispose();
}
this._disposed = true;
}
} |
JavaScript | class EventBufferer {
constructor() {
this.buffers = [];
}
wrapEvent(event) {
return (listener, thisArgs, disposables) => {
return event(i => {
const buffer = this.buffers[this.buffers.length - 1];
if (buffer) {
buffer.push(() => listener.call(thisArgs, i));
}
else {
listener.call(thisArgs, i);
}
}, undefined, disposables);
};
}
bufferEvents(fn) {
const buffer = [];
this.buffers.push(buffer);
const r = fn();
this.buffers.pop();
buffer.forEach(flush => flush());
return r;
}
} |
JavaScript | class Relay {
constructor() {
this.listening = false;
this.inputEvent = Event.None;
this.inputEventListener = lifecycle_1.Disposable.None;
this.emitter = new Emitter({
onFirstListenerDidAdd: () => {
this.listening = true;
this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);
},
onLastListenerRemove: () => {
this.listening = false;
this.inputEventListener.dispose();
}
});
this.event = this.emitter.event;
}
set input(event) {
this.inputEvent = event;
if (this.listening) {
this.inputEventListener.dispose();
this.inputEventListener = event(this.emitter.fire, this.emitter);
}
}
dispose() {
this.inputEventListener.dispose();
this.emitter.dispose();
}
} |
JavaScript | class JobParser {
/**
* @param {{bodyText: string, publishedAt: string}[]} thread
*/
constructor(thread) {
this.thread = thread.sort(
(a, b) => ascending(a.publishedAt, b.publishedAt)
);
}
/**
* @returns {Map<string, {link: string, date: string, jobid: number}>}
*/
parse() {
const thread = this.thread;
const result = new Map();
for (const c of thread) {
const text = c.bodyText;
if (!text.includes(CI_DOMAIN)) continue;
const jobs = this.parseText(text);
for (const job of jobs) {
// Always take the last one
// TODO(joyeecheung): exlcude links wrapped in `<del>`
result.set(job.type, {
link: job.link,
date: c.publishedAt,
jobid: job.jobid
});
}
}
return result;
}
/**
* @param {string} text
* @returns {{link: string, jobid: number, type: string}}
*/
parseText(text) {
const links = text.match(CI_URL_RE);
if (!links) {
return [];
}
const result = [];
for (const link of links) {
const parsed = parseJobFromURL(`https:${link}`);
if (parsed) {
result.push(parsed);
}
}
return result;
}
} |
JavaScript | class Plans extends BaseService {
/**
* Resource url.
* @type { string }
*/
resourceUrl = 'plans';
} |
JavaScript | class HandphonePage extends React.Component {
componentDidMount() {
const requestBody = {
query: `
query{
productsCategory(category:"${this.props.match.path.replace(
/[/]/i,
""
)}"){
_id
name
price
picture
}
}
`
};
this.props.getCategoryProduct(requestBody);
}
render() {
const resProducts = this.props.product.categoryProducts;
const listProduct =
resProducts.map(product => {
return (
<Col lg={3} md={6} sm={6} xs={12} key={product._id}>
<Card>
<CardImg
top
width="100%"
height="300px"
src={product.picture}
alt={product.name}
/>
<CardBody>
<CardTitle>{product.name}</CardTitle>
<CardSubtitle>{product.price}</CardSubtitle>
<NavLink to={"/detail/" + product._id}>
<Button>Preview</Button>
</NavLink>
</CardBody>
</Card>
</Col>
);
}) || "";
return (
<Page className="DashboardPage">
<Row>{listProduct}</Row>
</Page>
);
}
} |
JavaScript | class PersistentConversation extends ConversationBase {
constructor(
data,
{
creator,
createdAt,
updatedAt,
transient = false,
system = false,
muted = false,
mutedMembers = [],
...attributes
},
client
) {
super(
{
...data,
/**
* 对话创建者
* @memberof PersistentConversation#
* @type {String}
*/
creator,
/**
* 对话创建时间
* @memberof PersistentConversation#
* @type {Date}
*/
createdAt,
/**
* 对话更新时间
* @memberof PersistentConversation#
* @type {Date}
*/
updatedAt,
/**
* 对该对话设置了静音的用户列表
* @memberof PersistentConversation#
* @type {?String[]}
*/
mutedMembers,
/**
* 暂态对话标记
* @memberof PersistentConversation#
* @type {Boolean}
*/
transient,
/**
* 系统对话标记
* @memberof PersistentConversation#
* @type {Boolean}
* @since 3.3.0
*/
system,
/**
* 当前用户静音该对话标记
* @memberof PersistentConversation#
* @type {Boolean}
*/
muted,
_attributes: attributes,
},
client
);
this._reset();
}
set createdAt(value) {
this._createdAt = decodeDate(value);
}
get createdAt() {
return this._createdAt;
}
set updatedAt(value) {
this._updatedAt = decodeDate(value);
}
get updatedAt() {
return this._updatedAt;
}
/**
* 对话名字,对应 _Conversation 表中的 name
* @type {String}
*/
get name() {
return this.get('name');
}
set name(value) {
this.set('name', value);
}
/**
* 获取对话的自定义属性
* @since 3.2.0
* @param {String} key key 属性的键名,'x' 对应 Conversation 表中的 x 列
* @return {Any} 属性的值
*/
get(key) {
return internal(this).currentAttributes[key];
}
/**
* 设置对话的自定义属性
* @since 3.2.0
* @param {String} key 属性的键名,'x' 对应 Conversation 表中的 x 列,支持使用 'x.y.z' 来修改对象的部分字段。
* @param {Any} value 属性的值
* @return {this} self
* @example
*
* // 设置对话的 color 属性
* conversation.set('color', {
* text: '#000',
* background: '#DDD',
* });
* // 设置对话的 color.text 属性
* conversation.set('color.text', '#333');
*/
set(key, value) {
this._debug(`set [${key}]: ${value}`);
const { pendingAttributes } = internal(this);
const pendingKeys = Object.keys(pendingAttributes);
// suppose pendingAttributes = { 'a.b': {} }
// set 'a' or 'a.b': delete 'a.b'
const re = new RegExp(`^${key}`);
const childKeys = pendingKeys.filter(re.test.bind(re));
childKeys.forEach(k => {
delete pendingAttributes[k];
});
if (childKeys.length) {
pendingAttributes[key] = value;
} else {
// set 'a.c': nothing to do
// set 'a.b.c.d': assign c: { d: {} } to 'a.b'
// CAUTION: non-standard API, provided by core-js
const parentKey = Array.find(pendingKeys, k => key.indexOf(k) === 0); // 'a.b'
if (parentKey) {
setValue(
pendingAttributes[parentKey],
key.slice(parentKey.length + 1),
value
);
} else {
pendingAttributes[key] = value;
}
}
this._buildCurrentAttributes();
return this;
}
_buildCurrentAttributes() {
const { pendingAttributes } = internal(this);
internal(this).currentAttributes = Object.keys(pendingAttributes).reduce(
(target, k) => setValue(target, k, pendingAttributes[k]),
cloneDeep(this._attributes)
);
}
_updateServerAttributes(attributes) {
Object.keys(attributes).forEach(key =>
setValue(this._attributes, key, attributes[key])
);
this._buildCurrentAttributes();
}
_reset() {
Object.assign(internal(this), {
pendingAttributes: {},
currentAttributes: this._attributes,
});
}
/**
* 保存当前对话的属性至服务器
* @return {Promise.<this>} self
*/
async save() {
this._debug('save');
const attr = internal(this).pendingAttributes;
if (isEmpty(attr)) {
this._debug('nothing touched, resolve with self');
return this;
}
this._debug('attr: %O', attr);
const convMessage = new ConvCommand({
attr: new JsonObjectMessage({
data: JSON.stringify(encode(attr)),
}),
});
const resCommand = await this._send(
new GenericCommand({
op: 'update',
convMessage,
})
);
this.updatedAt = resCommand.convMessage.udate;
this._attributes = internal(this).currentAttributes;
internal(this).pendingAttributes = {};
return this;
}
/**
* 从服务器更新对话的属性
* @return {Promise.<this>} self
*/
async fetch() {
const query = this._client.getQuery().equalTo('objectId', this.id);
await query.find();
return this;
}
/**
* 静音,客户端拒绝收到服务器端的离线推送通知
* @return {Promise.<this>} self
*/
async mute() {
this._debug('mute');
await this._send(
new GenericCommand({
op: 'mute',
})
);
if (!this.transient) {
this.muted = true;
this.mutedMembers = union(this.mutedMembers, [this._client.id]);
}
return this;
}
/**
* 取消静音
* @return {Promise.<this>} self
*/
async unmute() {
this._debug('unmute');
await this._send(
new GenericCommand({
op: 'unmute',
})
);
if (!this.transient) {
this.muted = false;
this.mutedMembers = difference(this.mutedMembers, [this._client.id]);
}
return this;
}
async _appendConversationSignature(command, action, clientIds) {
if (this._client.options.conversationSignatureFactory) {
const params = [this.id, this._client.id, clientIds.sort(), action];
const signatureResult = await runSignatureFactory(
this._client.options.conversationSignatureFactory,
params
);
Object.assign(
command.convMessage,
keyRemap(
{
signature: 's',
timestamp: 't',
nonce: 'n',
},
signatureResult
)
);
}
}
async _appendBlacklistSignature(command, action, clientIds) {
if (this._client.options.blacklistSignatureFactory) {
const params = [this._client.id, this.id, clientIds.sort(), action];
const signatureResult = await runSignatureFactory(
this._client.options.blacklistSignatureFactory,
params
);
Object.assign(
command.blacklistMessage,
keyRemap(
{
signature: 's',
timestamp: 't',
nonce: 'n',
},
signatureResult
)
);
}
}
/**
* 增加成员
* @param {String|String[]} clientIds 新增成员 client id
* @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
*/
async add(clientIds) {
this._debug('add', clientIds);
if (typeof clientIds === 'string') {
clientIds = [clientIds]; // eslint-disable-line no-param-reassign
}
const command = new GenericCommand({
op: 'add',
convMessage: new ConvCommand({
m: clientIds,
}),
});
await this._appendConversationSignature(command, 'add', clientIds);
const {
convMessage,
convMessage: { allowedPids },
} = await this._send(command);
this._addMembers(allowedPids);
return createPartiallySuccess(convMessage);
}
/**
* 剔除成员
* @param {String|String[]} clientIds 成员 client id
* @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
*/
async remove(clientIds) {
this._debug('remove', clientIds);
if (typeof clientIds === 'string') {
clientIds = [clientIds]; // eslint-disable-line no-param-reassign
}
const command = new GenericCommand({
op: 'remove',
convMessage: new ConvCommand({
m: clientIds,
}),
});
await this._appendConversationSignature(command, 'remove', clientIds);
const {
convMessage,
convMessage: { allowedPids },
} = await this._send(command);
this._removeMembers(allowedPids);
return createPartiallySuccess(convMessage);
}
/**
* (当前用户)加入该对话
* @return {Promise.<this>} self
*/
async join() {
this._debug('join');
return this.add(this._client.id).then(({ failures }) => {
if (failures[0]) throw failures[0];
return this;
});
}
/**
* (当前用户)退出该对话
* @return {Promise.<this>} self
*/
async quit() {
this._debug('quit');
return this.remove(this._client.id).then(({ failures }) => {
if (failures[0]) throw failures[0];
return this;
});
}
/**
* 在该对话中禁言成员
* @param {String|String[]} clientIds 成员 client id
* @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
*/
async muteMembers(clientIds) {
this._debug('mute', clientIds);
clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
const command = new GenericCommand({
op: OpType.add_shutup,
convMessage: new ConvCommand({
m: clientIds,
}),
});
const { convMessage } = await this._send(command);
return createPartiallySuccess(convMessage);
}
/**
* 在该对话中解除成员禁言
* @param {String|String[]} clientIds 成员 client id
* @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
*/
async unmuteMembers(clientIds) {
this._debug('unmute', clientIds);
clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
const command = new GenericCommand({
op: OpType.remove_shutup,
convMessage: new ConvCommand({
m: clientIds,
}),
});
const { convMessage } = await this._send(command);
return createPartiallySuccess(convMessage);
}
/**
* 查询该对话禁言成员列表
* @param {Object} [options]
* @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
* @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页。
* @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
*/
async queryMutedMembers({ limit, next } = {}) {
this._debug('query muted: limit %O, next: %O', limit, next);
const command = new GenericCommand({
op: OpType.query_shutup,
convMessage: new ConvCommand({
limit,
next,
}),
});
const {
convMessage: { m, next: newNext },
} = await this._send(command);
return {
results: m,
next: newNext,
};
}
/**
* 将用户加入该对话黑名单
* @param {String|String[]} clientIds 成员 client id
* @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
*/
async blockMembers(clientIds) {
this._debug('block', clientIds);
clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
const command = new GenericCommand({
cmd: 'blacklist',
op: OpType.block,
blacklistMessage: new BlacklistCommand({
srcCid: this.id,
toPids: clientIds,
}),
});
await this._appendBlacklistSignature(
command,
'conversation-block-clients',
clientIds
);
const { blacklistMessage } = await this._send(command);
return createPartiallySuccess(blacklistMessage);
}
/**
* 将用户移出该对话黑名单
* @param {String|String[]} clientIds 成员 client id
* @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
*/
async unblockMembers(clientIds) {
this._debug('unblock', clientIds);
clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
const command = new GenericCommand({
cmd: 'blacklist',
op: OpType.unblock,
blacklistMessage: new BlacklistCommand({
srcCid: this.id,
toPids: clientIds,
}),
});
await this._appendBlacklistSignature(
command,
'conversation-unblock-clients',
clientIds
);
const { blacklistMessage } = await this._send(command);
return createPartiallySuccess(blacklistMessage);
}
/**
* 查询该对话黑名单
* @param {Object} [options]
* @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
* @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页
* @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
*/
async queryBlockedMembers({ limit, next } = {}) {
this._debug('query blocked: limit %O, next: %O', limit, next);
const command = new GenericCommand({
cmd: 'blacklist',
op: OpType.query,
blacklistMessage: new BlacklistCommand({
srcCid: this.id,
limit,
next,
}),
});
const {
blacklistMessage: { blockedPids, next: newNext },
} = await this._send(command);
return {
results: blockedPids,
next: newNext,
};
}
toFullJSON() {
const {
creator,
system,
transient,
createdAt,
updatedAt,
_attributes,
} = this;
return {
...super.toFullJSON(),
creator,
system,
transient,
createdAt: getTime(createdAt),
updatedAt: getTime(updatedAt),
..._attributes,
};
}
toJSON() {
const {
creator,
system,
transient,
muted,
mutedMembers,
createdAt,
updatedAt,
_attributes,
} = this;
return {
...super.toJSON(),
creator,
system,
transient,
muted,
mutedMembers,
createdAt,
updatedAt,
..._attributes,
};
}
} |
JavaScript | class ApiManagementServiceNameAvailabilityResult {
/**
* Create a ApiManagementServiceNameAvailabilityResult.
* @member {boolean} [nameAvailable] True if the name is available and can be
* used to create a new API Management service; otherwise false.
* @member {string} [message] If reason == invalid, provide the user with the
* reason why the given name is invalid, and provide the resource naming
* requirements so that the user can select a valid name. If reason ==
* AlreadyExists, explain that <resourceName> is already in use, and direct
* them to select a different name.
* @member {string} [reason] Invalid indicates the name provided does not
* match the resource provider’s naming requirements (incorrect length,
* unsupported characters, etc.) AlreadyExists indicates that the name is
* already in use and is therefore unavailable. Possible values include:
* 'Valid', 'Invalid', 'AlreadyExists'
*/
constructor() {
}
/**
* Defines the metadata of ApiManagementServiceNameAvailabilityResult
*
* @returns {object} metadata of ApiManagementServiceNameAvailabilityResult
*
*/
mapper() {
return {
required: false,
serializedName: 'ApiManagementServiceNameAvailabilityResult',
type: {
name: 'Composite',
className: 'ApiManagementServiceNameAvailabilityResult',
modelProperties: {
nameAvailable: {
required: false,
readOnly: true,
serializedName: 'nameAvailable',
type: {
name: 'Boolean'
}
},
message: {
required: false,
readOnly: true,
serializedName: 'message',
type: {
name: 'String'
}
},
reason: {
required: false,
serializedName: 'reason',
type: {
name: 'Enum',
allowedValues: [ 'Valid', 'Invalid', 'AlreadyExists' ]
}
}
}
}
};
}
} |
JavaScript | class Bookmarks extends React.Component {
static propTypes = {
form: PropTypes.object.isRequired,
refCb: PropTypes.func.isRequired
}
fontFamilyOptions() {
return [
['Monospace', 'monaco, Consolas, "Lucida Console", monospace'],
['Sans', '"Helvetica Neue", Helvetica, Arial, sans-serif'],
['Serif', '"Hoefler Text", "Baskerville Old Face", Garamond, "Times New Roman", serif']
].map(choice => {
const l = choice[0],
v = choice[1]
return <option value={v} key={l}>{l}</option>
})
}
render() {
const { refCb, form } = this.props
const ref = refCb
return (
<form rel='form'>
<div className="form-group">
<label htmlFor="fontFamily" className="control-label">Font Family:</label>
<select ref={ref} className='form-control' name='fontFamily' defaultValue={form.fontFamily}>
{this.fontFamilyOptions()}
</select>
</div>
<div className="form-group">
<label htmlFor="background_color" className="control-label">Color:</label>
<input ref={ref} type="color" defaultValue={form.background_color} className="form-control" name="background_color"/>
</div>
</form>
)
}
} |
JavaScript | class ModbusTCPResponse {
/** Create Modbus/TCP Response from a Modbus/TCP Request including
* the modbus function body.
* @param {ModbusTCPRequest} request
* @param {ModbusResponseBody} body
* @returns {ModbusTCPResponse}
*/
static fromRequest (tcpRequest, modbusBody) {
return new ModbusTCPResponse(
tcpRequest.id,
tcpRequest.protocol,
modbusBody.byteCount + 1,
tcpRequest.unitId,
modbusBody)
}
/** Create Modbus/TCP Response from a buffer
* @param {Buffer} buffer
* @returns {ModbusTCPResponse} Returns null if not enough data located in the buffer.
*/
static fromBuffer (buffer) {
try {
const id = buffer.readUInt16BE(0)
const protocol = buffer.readUInt16BE(2)
const length = buffer.readUInt16BE(4)
const unitId = buffer.readUInt8(6)
debug('tcp header complete, id', id, 'protocol', protocol, 'length', length, 'unitId', unitId)
debug('buffer', buffer)
const body = ResponseFactory.fromBuffer(buffer.slice(7, 7 + length - 1))
if (!body) {
debug('not enough data for a response body')
return null
}
debug('buffer contains a valid response body')
return new ModbusTCPResponse(id, protocol, length, unitId, body)
} catch (e) {
debug('not enough data available')
return null
}
}
/** Create new Modbus/TCP Response Object.
* @param {Number} id Transaction ID
* @param {Number} protocol Protcol version (Usually 0)
* @param {Number} bodyLength Body length + 1
* @param {Number} unitId Unit ID
* @param {ModbusResponseBody} body Modbus response body object
*/
constructor (id, protocol, bodyLength, unitId, body) {
this._id = id
this._protocol = protocol
this._bodyLength = bodyLength
this._unitId = unitId
this._body = body
}
/** Transaction ID */
get id () {
return this._id
}
/** Protocol version */
get protocol () {
return this._protocol
}
/** Body length */
get bodyLength () {
return this._bodyLength
}
/** Payload byte count */
get byteCount () {
return this._bodyLength + 6
}
/** Unit ID */
get unitId () {
return this._unitId
}
/** Modbus response body */
get body () {
return this._body
}
createPayload () {
/* Payload is a buffer with:
* Transaction ID = 2 Bytes
* Protocol ID = 2 Bytes
* Length = 2 Bytes
* Unit ID = 1 Byte
* Function code = 1 Byte
* Byte count = 1 Byte
* Coil status = n Bytes
*/
const payload = Buffer.alloc(this.byteCount)
payload.writeUInt16BE(this._id, 0)
payload.writeUInt16BE(this._protocol, 2)
payload.writeUInt16BE(this._bodyLength, 4)
payload.writeUInt8(this._unitId, 6)
this._body.createPayload().copy(payload, 7)
return payload
}
} |
JavaScript | class vidbg {
/**
* Setup our defualt options and config for our plugin.
*
* @param {String} selector The selector for the video background
* @param {object} options The options for the plugin
* @param {object} attributes The attributes for the HTML5 <video> attribute
*/
constructor(selector, options, attributes) {
if (!selector) {
console.error('Please provide a selector')
return false
}
// The element
this.el = document.querySelector(selector)
if (!this.el) {
console.error(`The selector you specified, "${selector}", does not exist!`)
return false
}
// These are the default options for vidbg
const defaultOptions = {
mp4: null,
webm: null,
poster: null,
overlay: false,
overlayColor: '#000',
overlayAlpha: 0.3
}
// Use the spread operator to merge our default options with user supplied options.
this.options = { ...defaultOptions, ...options }
/**
* Autoplay attribute has been removed from the default attributes as it was conflicting
* with playback in Safari with the play promise. Now, the play promise handles the
* autoplay.
*/
// These are the default attributes for the HTML5 <video> element.
const defaultAttributes = {
controls: false,
loop: true,
muted: true,
playsInline: true
}
// Use the spread operator to merge our default attributes with user supplied options.
this.attributes = { ...defaultAttributes, ...attributes }
if (!this.options.mp4 && !this.options.webm) {
console.error('Please provide an mp4, webm, or both.')
return false
}
this.init()
}
/**
* init the video background to the DOM.
*/
init() {
this.el.style.position = 'relative'
this.el.style.zIndex = 1
this.createContainer()
this.createVideo()
this.createOverlay()
window.addEventListener('resize', this.resize)
}
/**
* Create the container element and append it to the selector.
*/
createContainer = () => {
this.containerEl = document.createElement('div')
this.containerEl.className = 'vidbg-container'
this.createPoster()
this.el.appendChild(this.containerEl)
}
/**
* Create the overlay element and append it to the container.
*/
createOverlay = () => {
this.overlayEl = document.createElement('div')
this.overlayEl.className = 'vidbg-overlay'
if (this.options.overlay) {
const [r, g, b] = convert(this.options.overlayColor, { format: 'array' })
const rgba = [r, g, b, this.options.overlayAlpha]
this.overlayEl.style.backgroundColor = `rgba(${rgba.join(', ')})`
}
this.containerEl.appendChild(this.overlayEl)
}
/**
* If the poster option exists, add it to the container's backgroundImage style attribute.
*/
createPoster = () => {
if (this.options.poster) {
this.containerEl.style.backgroundImage = `url(${this.options.poster})`
}
}
/**
* Create the HTML5 video element and append it to the container.
*/
createVideo = () => {
this.videoEl = document.createElement('video')
this.videoEl.addEventListener('playing', this.onPlayEvent)
/**
* Set the attributes for the <video> element.
* It is important that these are added to the video element before the
* play promise since autoplay primarily only works when the video is
* muted.
*/
for (const key in this.attributes) {
this.videoEl[key] = this.attributes[key]
}
if (this.options.mp4) {
const mp4Source = document.createElement('source')
mp4Source.src = this.options.mp4
mp4Source.type = 'video/mp4'
this.videoEl.appendChild(mp4Source)
}
if (this.options.webm) {
const webmSource = document.createElement('source')
webmSource.src = this.options.webm
webmSource.type = 'video/webm'
this.videoEl.appendChild(webmSource)
}
this.containerEl.appendChild(this.videoEl)
/**
* Create a play promise for browsers that support it. If a browser
* supports promises, we can determine if a video can be played. If
* it can not, we will console an error message and remove the video
* instance.
*
* If the browser does not support promises, the initialization of the
* playPromise variable will call play() regardless, and the browser
* will try to play the video.
*/
let playPromise = this.videoEl.play()
if (playPromise !== undefined) {
playPromise
.catch(err => {
console.error(err)
console.error('Autoplay is not supported')
this.removeVideo()
})
}
}
/**
* The play event once the video starts playing.
*
* @param {Object} event The play event
*/
onPlayEvent = (event) => {
// Resize the video on play
this.resize()
// Show the video
this.videoEl.style.opacity = 1
}
/**
* Removes the HTML5 <video> element
*/
removeVideo = () => {
this.videoEl.remove()
}
/**
* Get the HTML <video> element
*/
getVideo = () => {
return this.videoEl
}
/**
* Destroy the vidbg instance
*/
destroy = () => {
this.containerEl.remove()
}
/**
* Our resize method on initial load and browser resize.
*/
resize = () => {
// Get the width and height of the container we created
const containerWidth = this.containerEl.offsetWidth
const containerHeight = this.containerEl.offsetHeight
// Get the width and height of the HTML5 <video> element we created
const videoWidth = this.videoEl.videoWidth
const videoHeight = this.videoEl.videoHeight
/**
* Depending on the width and height of the browser, we will either set the video width
* to the container's width and the height to auto, or the width to auto and the height
* to the container's height.
*/
if (containerWidth / videoWidth > containerHeight / videoHeight) {
this.videoEl.style.width = `${containerWidth}px`
this.videoEl.style.height = 'auto'
} else {
this.videoEl.style.width = 'auto'
this.videoEl.style.height = `${containerHeight}px`
}
}
} |
JavaScript | class BingMarkerService {
/**
* Creates an instance of BingMarkerService.
* \@memberof BingMarkerService
* @param {?} _mapService - {\@link MapService} instance. The concrete {\@link BingMapService} implementation is expected.
* @param {?} _layerService - {\@link LayerService} instance.
* The concrete {\@link BingLayerService} implementation is expected.
* @param {?} _clusterService - {\@link ClusterService} instance.
* The concrete {\@link BingClusterService} implementation is expected.
* @param {?} _zone - NgZone instance to support zone aware promises.
*
*/
constructor(_mapService, _layerService, _clusterService, _zone) {
this._mapService = _mapService;
this._layerService = _layerService;
this._clusterService = _clusterService;
this._zone = _zone;
this._markers = new Map();
}
/**
* Adds a marker. Depending on the marker context, the marker will either by added to the map or a correcsponding layer.
*
* \@memberof BingMarkerService
* @param {?} marker - The {\@link MapMarkerDirective} to be added.
*
* @return {?}
*/
AddMarker(marker) {
/** @type {?} */
const o = {
position: { latitude: marker.Latitude, longitude: marker.Longitude },
title: marker.Title,
label: marker.Label,
draggable: marker.Draggable,
icon: marker.IconUrl,
iconInfo: marker.IconInfo,
isFirst: marker.IsFirstInSet,
isLast: marker.IsLastInSet
};
if (marker.Width) {
o.width = marker.Width;
}
if (marker.Height) {
o.height = marker.Height;
}
if (marker.Anchor) {
o.anchor = marker.Anchor;
}
if (marker.Metadata) {
o.metadata = marker.Metadata;
}
/** @type {?} */
let markerPromise = null;
if (marker.InClusterLayer) {
markerPromise = this._clusterService.CreateMarker(marker.LayerId, o);
}
else if (marker.InCustomLayer) {
markerPromise = this._layerService.CreateMarker(marker.LayerId, o);
}
else {
markerPromise = this._mapService.CreateMarker(o);
}
this._markers.set(marker, markerPromise);
if (marker.IconInfo) {
markerPromise.then((m) => {
// update iconInfo to provide hook to do post icon creation activities and
// also re-anchor the marker
marker.DynamicMarkerCreated.emit(o.iconInfo);
/** @type {?} */
const p = {
x: (o.iconInfo.size && o.iconInfo.markerOffsetRatio) ? (o.iconInfo.size.width * o.iconInfo.markerOffsetRatio.x) : 0,
y: (o.iconInfo.size && o.iconInfo.markerOffsetRatio) ? (o.iconInfo.size.height * o.iconInfo.markerOffsetRatio.y) : 0,
};
m.SetAnchor(p);
});
}
}
/**
* Registers an event delegate for a marker.
*
* \@memberof BingMarkerService
* @template T
* @param {?} eventName - The name of the event to register (e.g. 'click')
* @param {?} marker - The {\@link MapMarker} for which to register the event.
* @return {?} - Observable emiting an instance of T each time the event occurs.
*
*/
CreateEventObservable(eventName, marker) {
/** @type {?} */
const b = new Subject();
if (eventName === 'mousemove') {
return b.asObservable();
}
if (eventName === 'rightclick') {
return b.asObservable();
}
return Observable.create((observer) => {
this._markers.get(marker).then((m) => {
m.AddListener(eventName, (e) => this._zone.run(() => observer.next(e)));
});
});
}
/**
* Deletes a marker.
*
* \@memberof BingMarkerService
* @param {?} marker - {\@link MapMarker} to be deleted.
* @return {?} - A promise fullfilled once the marker has been deleted.
*
*/
DeleteMarker(marker) {
/** @type {?} */
const m = this._markers.get(marker);
/** @type {?} */
let p = Promise.resolve();
if (m != null) {
p = m.then((ma) => {
if (marker.InClusterLayer) {
this._clusterService.GetNativeLayer(marker.LayerId).then(l => { l.RemoveEntity(ma); });
}
if (marker.InCustomLayer) {
this._layerService.GetNativeLayer(marker.LayerId).then(l => { l.RemoveEntity(ma); });
}
return this._zone.run(() => {
ma.DeleteMarker();
this._markers.delete(marker);
});
});
}
return p;
}
/**
* Obtains geo coordinates for the marker on the click location
*
* \@memberof BingMarkerService
* @param {?} e - The mouse event.
* @return {?} - {\@link ILatLong} containing the geo coordinates of the clicked marker.
*
*/
GetCoordinatesFromClick(e) {
if (!e) {
return null;
}
if (!e.primitive) {
return null;
}
if (!(e.primitive instanceof Microsoft.Maps.Pushpin)) {
return null;
}
/** @type {?} */
const p = e.primitive;
/** @type {?} */
const loc = p.getLocation();
return { latitude: loc.latitude, longitude: loc.longitude };
}
/**
* Obtains the marker model for the marker allowing access to native implementation functionatiliy.
*
* \@memberof BingMarkerService
* @param {?} marker - The {\@link MapMarker} for which to obtain the marker model.
* @return {?} - A promise that when fullfilled contains the {\@link Marker} implementation of the underlying platform.
*
*/
GetNativeMarker(marker) {
return this._markers.get(marker);
}
/**
* Obtains the marker pixel location for the marker on the click location
*
* \@memberof BingMarkerService
* @param {?} e - The mouse event.
* @return {?} - {\@link ILatLong} containing the pixels of the marker on the map canvas.
*
*/
GetPixelsFromClick(e) {
/** @type {?} */
const loc = this.GetCoordinatesFromClick(e);
if (loc == null) {
return null;
}
/** @type {?} */
const l = BingConversions.TranslateLocation(loc);
/** @type {?} */
const p = /** @type {?} */ ((/** @type {?} */ (this._mapService)).MapInstance.tryLocationToPixel(l, Microsoft.Maps.PixelReference.control));
if (p == null) {
return null;
}
return { x: p.x, y: p.y };
}
/**
* Converts a geo location to a pixel location relative to the map canvas.
*
* \@memberof BingMarkerService
* @param {?} target - Either a {\@link MapMarker} or a {\@link ILatLong} for the basis of translation.
* @return {?} - A promise that when fullfilled contains a {\@link IPoint}
* with the pixel coordinates of the MapMarker or ILatLong relative to the map canvas.
*
*/
LocationToPoint(target) {
if (target == null) {
return Promise.resolve(null);
}
if (target instanceof MapMarkerDirective) {
return this._markers.get(target).then((m) => {
/** @type {?} */
const l = m.Location;
/** @type {?} */
const p = this._mapService.LocationToPoint(l);
return p;
});
}
return this._mapService.LocationToPoint(target);
}
/**
* Updates the anchor position for the marker.
*
* \@memberof BingMarkerService
* @param {?} marker
* @return {?} - A promise that is fullfilled when the anchor position has been updated.
*
*/
UpdateAnchor(marker) {
return this._markers.get(marker).then((m) => {
m.SetAnchor(marker.Anchor);
});
}
/**
* Updates whether the marker is draggable.
*
* \@memberof BingMarkerService
* @param {?} marker
* @return {?} - A promise that is fullfilled when the marker has been updated.
*
*/
UpdateDraggable(marker) {
return this._markers.get(marker).then((m) => m.SetDraggable(marker.Draggable));
}
/**
* Updates the Icon on the marker.
*
* \@memberof BingMarkerService
* @param {?} marker
* @return {?} - A promise that is fullfilled when the icon information has been updated.
*
*/
UpdateIcon(marker) {
/** @type {?} */
const payload = (m, icon, iconInfo) => {
if (icon && icon !== '') {
m.SetIcon(icon);
marker.DynamicMarkerCreated.emit(iconInfo);
}
};
return this._markers.get(marker).then((m) => {
if (marker.IconInfo) {
/** @type {?} */
const s = Marker.CreateMarker(marker.IconInfo);
if (typeof (s) === 'string') {
return (payload(m, s, marker.IconInfo));
}
else {
return s.then(x => {
return (payload(m, x.icon, x.iconInfo));
});
}
}
else {
return (m.SetIcon(marker.IconUrl));
}
});
}
/**
* Updates the label on the marker.
*
* \@memberof BingMarkerService
* @param {?} marker
* @return {?} - A promise that is fullfilled when the label has been updated.
*
*/
UpdateLabel(marker) {
return this._markers.get(marker).then((m) => { m.SetLabel(marker.Label); });
}
/**
* Updates the geo coordinates for the marker.
*
* \@memberof BingMarkerService
* @param {?} marker
* @return {?} - A promise that is fullfilled when the position has been updated.
*
*/
UpdateMarkerPosition(marker) {
return this._markers.get(marker).then((m) => m.SetPosition({
latitude: marker.Latitude,
longitude: marker.Longitude
}));
}
/**
* Updates the title on the marker.
*
* \@memberof BingMarkerService
* @param {?} marker
* @return {?} - A promise that is fullfilled when the title has been updated.
*
*/
UpdateTitle(marker) {
return this._markers.get(marker).then((m) => m.SetTitle(marker.Title));
}
/**
* Updates the visibility on the marker.
*
* \@memberof BingMarkerService
* @param {?} marker
* @return {?} - A promise that is fullfilled when the visibility has been updated.
*
*/
UpdateVisible(marker) {
return this._markers.get(marker).then((m) => m.SetVisible(marker.Visible));
}
} |
JavaScript | class mcmInstUtils{
constructor() {
this.adapter=null;
}
async init(pAdapter) {
mcmLogger.debug( "INFO : initializing mcmInstUtils");
this.adapter=pAdapter;
}
async #convInstance(pInstanceRow){
mcmLogger.debug( "mcmInstUtils/convInstance - convert one instance");
mcmLogger.debug( "instance: "+pInstanceRow.id);
let native = pInstanceRow.value.native;
const cfgVers = native.cfgVers || '0';
// migrate from config version 0
if ( cfgVers == 0 ) {
const OIDs = native.OIDs;
if (OIDs && OIDs.length > 0) {
mcmLogger.info("instance "+pInstanceRow.id+" will be migrated");
const connectTimeout = native.connectTimeout/1000 || 5;
const pollInterval = native.pollInterval/1000 || 30;
const retryTimeout = native.retryTimeout/1000 || 5;
let IPs = {};
// create OID groups based on oid ip
for (let ii=0; ii<OIDs.length; ii++) {
const oid = OIDs[ii];
const ip = oid.ip;
const name = oid.name;
const OID = oid.OID;
const community = oid.publicCom;
// add new device
if ( ! IPs[ip] )
{
IPs[ip] = 'X'; // set marker
native.devs = native.devs || [];
const devs = native.devs;
const idx = devs.length || 0;
devs[idx] = {};
devs[idx].devAct = true;
devs[idx].devAuthId = 'public';
devs[idx].devComm = community;
devs[idx].devIpAddr = ip;
devs[idx].devName = ip;
devs[idx].devOidGroup = ip;
devs[idx].devPollIntvl = pollInterval;
devs[idx].devRetryIntvl = retryTimeout;
devs[idx].devSnmpVers = '1';
devs[idx].devTimeout = connectTimeout;
}
// add new OID
native.oids = native.oids || []
const oids = native.oids;
const idx = oids.length || 0;
oids[idx] = {};
oids[idx].oidAct = true;
oids[idx].oidGroup = ip;
oids[idx].oidName = name;
oids[idx].oidOid = OID;
oids[idx].oidOptional = false;
oids[idx].oidWriteable = false;
// update config version
native.cfgVers = '2.0';
// remove old configuration
}
// write object
await this.adapter.setForeignObjectAsync( pInstanceRow.id, pInstanceRow.value );
} else {
mcmLogger.debug("instance "+pInstanceRow.id+" provides no data to migrate");
}
} else if ( cfgVers == '2.0' ) {
mcmLogger.debug("instance "+pInstanceRow.id+" already up to date");
} else {
mcmLogger.warn("instance "+pInstanceRow.id+" reports unknown config version '"+cfgVers+"'");
};
}
async doUpgrade(){
mcmLogger.debug( "mcmInstUtils/doUpgrade - starting upgrade process");
const objView = await this.adapter.getObjectViewAsync('system', 'instance', {
startkey: 'system.adapter.snmp.',
endkey: 'system.adapter.snmp.\u9999'
});
for (let ii=0; ii<objView.rows.length; ii++) {
const instanceRow = objView.rows[ii];
await this.#convInstance(instanceRow);
}
// try {
// this.adapter.log.silly(pMsg);
// } catch {};
};
} |
JavaScript | class MeetupStoreRequest {
/**
* @param {Object} request
*/
constructor(request) {
this.request = request;
this.schema = Yup.object().shape({
title: Yup.string().required(),
description: Yup.string().required(),
localization: Yup.string().required(),
date: Yup.date().required(),
image_id: Yup.number().required(),
});
}
/**
* Validates the given request.
*
* @return {Object|boolean} an error object or true if it is valid.
*/
async isValid() {
if (await this.isSchemaInvalid()) {
return badRequest('Dados inválidos');
}
if (await this.imageDoesNotExists()) {
return badRequest('Banner não encontrado');
}
if (await this.isDateInPast()) {
return badRequest('A data precisa ser depois de hoje');
}
return true;
}
async isSchemaInvalid() {
return !(await this.schema.isValid(this.request.body));
}
async imageDoesNotExists() {
return !(await File.findByPk(this.request.body.image_id));
}
async isDateInPast() {
const parsedDate = parseISO(this.request.body.date);
const now = new Date();
return isBefore(parsedDate, now);
}
} |
JavaScript | class DragSelect extends React.Component {
static defaultProps = {enabled: true};
componentWillMount() {
var mousedown = new Rx.Subject();
var mousedrag = mousedown.flatMap((down) => {
var target = down.currentTarget,
bb = target.getBoundingClientRect(),
startX = targetXPos(target, down, bb.width),
startY = targetYPos(target, down, bb.height),
selection;
return Rx.Observable.fromEvent(window, 'mousemove').map(function (mm) {
var {width, height} = bb,
endX = targetXPos(target, mm, width),
endY = targetYPos(target, mm, height),
crosshairX = crosshairXPos(target, mm, width),
crosshairY = crosshairYPos(target, mm, height);
selection = {
start: {x: startX, y: startY},
end: {x: endX, y: endY},
offset: {x: bb.left, y: bb.top},
crosshair: {x: crosshairX, y: crosshairY}
};
return {dragging: true, ...selection};
}).takeUntil(Rx.Observable.fromEvent(window, 'mouseup'))
.concat(Rx.Observable.defer(() => Rx.Observable.of({selection})));
});
this.subscription = mousedrag.subscribe(ev => {
var {dragging, ...selection} = ev;
if (dragging) {
this.props.onDrag && this.props.onDrag(selection);
}
if (ev.selection) {
this.props.onSelect && this.props.onSelect(ev.selection);
}
});
this.dragStart = ev => this.props.enabled && mousedown.next(ev);
}
componentWillUnmount() {
this.subscription.unsubscribe();
}
render() {
var containerProps = _.omit(this.props, 'onSelect', 'enabled');
return (
<div {...containerProps} style={styles.wrapper} onMouseDown={this.dragStart}>
{this.props.children}
</div>);
}
} |
JavaScript | class VerticalProgressStep extends LightningElement {
/**
* Text label to title the step.
*
* @type {string}
* @public
*/
@api label;
_value;
iconName;
contentInLine = false;
connectedCallback() {
this.classList.add('slds-progress__item');
}
/**
* Text to name the step.
*
* @type {string}
* @public
*/
@api
get value() {
return this._value;
}
set value(value) {
this._value = value;
this.setAttribute('data-step', value);
}
/**
* Reserved for internal use. Attributes for in line and variant shade sent from avonni-vertical-progress-indicator.
*
* @param {boolean} contentInLine
* @param {string} shade
* @public
*/
@api
setAttributes(contentInLine, shade) {
if (contentInLine) {
this.contentInLine = contentInLine;
this.classList.add('avonni-content-in-line');
}
if (shade) {
this.classList.add('avonni-spread');
}
}
/**
* Reserved for internal use. Icon name sent from avonni-vertical-progress-indicator.
*
* @param {string} iconName
*/
@api
setIcon(iconName) {
this.iconName = iconName;
}
/**
* Get the item elements from the default slot.
*
* @type {Element}
*/
get slotItems() {
return this.template.querySelector('[data-element-id="slot-default"]');
}
/**
* Mouse enter event handler.
*/
handleMouseEnter() {
/**
* The event fired when the mouse enter the step.
*
* @event
* @name stepmouseenter
* @param {string} value the step value.
* @public
* @bubbles
* @cancelable
*/
this.dispatchEvent(
new CustomEvent('stepmouseenter', {
bubbles: true,
cancelable: true,
detail: {
value: this.value
}
})
);
}
/**
* Mouse leave event handler.
*/
handleMouseLeave() {
/**
* The event fired when the mouse leave the step.
*
* @event
* @name stepmouseleave
* @param {string} value The step value.
* @public
* @bubbles
* @cancelable
*/
this.dispatchEvent(
new CustomEvent('stepmouseleave', {
bubbles: true,
cancelable: true,
detail: {
value: this.value
}
})
);
}
/**
* Focus on step event handler.
*/
handleFocus() {
/**
* The event fired when the step receives focus.
*
* @event
* @name stepfocus
* @param {string} value The step value.
* @public
* @bubbles
* @cancelable
*/
this.dispatchEvent(
new CustomEvent('stepfocus', {
bubbles: true,
cancelable: true,
detail: {
value: this.value
}
})
);
}
/**
* Blur event handler.
*/
handleBlur() {
/**
* The event fired when the focus is removed from the step.
*
* @event
* @name stepblur
* @param {string} value The step value.
* @public
* @bubbles
* @cancelable
*/
this.dispatchEvent(
new CustomEvent('stepblur', {
bubbles: true,
cancelable: true,
detail: {
value: this.value
}
})
);
}
} |
JavaScript | class MrEditField extends LitElement {
/** @override */
createRenderRoot() {
return this;
}
/** @override */
render() {
return html`
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<style>
mr-edit-field {
display: block;
}
mr-edit-field[hidden] {
display: none;
}
mr-edit-field input,
mr-edit-field select {
width: var(--mr-edit-field-width);
padding: var(--mr-edit-field-padding);
}
</style>
${this._renderInput()}
`;
}
/**
* Renders a single input field.
* @return {TemplateResult}
*/
_renderInput() {
switch (this._widgetType) {
case CHECKBOX_INPUT:
return html`
<mr-multi-checkbox
.options=${this.options}
.values=${[...this.values]}
@change=${this._changeHandler}
></mr-multi-checkbox>
`;
case SELECT_INPUT:
return html`
<select
id="${this.label}"
class="editSelect"
aria-label=${this.name}
@change=${this._changeHandler}
>
<option value="">${EMPTY_FIELD_VALUE}</option>
${this.options.map((option) => html`
<option
value=${option.optionName}
.selected=${this.value === option.optionName}
>
${option.optionName}
${option.docstring ? ' = ' + option.docstring : ''}
</option>
`)}
</select>
`;
case AUTOCOMPLETE_INPUT:
return html`
<mr-react-autocomplete
.label=${this.label}
.vocabularyName=${this.acType || ''}
.inputType=${this._html5InputType}
.fixedValues=${this.derivedValues}
.value=${this.multi ? this.values : this.value}
.multiple=${this.multi}
.onChange=${this._changeHandlerReact.bind(this)}
></mr-react-autocomplete>
`;
default:
return '';
}
}
/** @override */
static get properties() {
return {
// TODO(zhangtiff): Redesign this a bit so we don't need two separate
// ways of specifying "type" for a field. Right now, "type" is mapped to
// the Monorail custom field types whereas "acType" includes additional
// data types such as components, and labels.
// String specifying what kind of autocomplete to add to this field.
acType: {type: String},
// "type" is based on the various custom field types available in
// Monorail.
type: {type: String},
label: {type: String},
multi: {type: Boolean},
name: {type: String},
// Only used for basic, non-repeated fields.
placeholder: {type: String},
initialValues: {
type: Array,
hasChanged(newVal, oldVal) {
// Prevent extra recomputations of the same initial value causing
// values to be reset.
return !deepEqual(newVal, oldVal);
},
},
// The current user-inputted values for a field.
values: {type: Array},
derivedValues: {type: Array},
// For enum fields, the possible options that you have. Each entry is a
// label type with an additional optionName field added.
options: {type: Array},
};
}
/** @override */
constructor() {
super();
this.initialValues = [];
this.values = [];
this.derivedValues = [];
this.options = [];
this.multi = false;
this.actType = '';
this.placeholder = '';
this.type = '';
}
/** @override */
update(changedProperties) {
if (changedProperties.has('initialValues')) {
// Assume we always want to reset the user's input when initial
// values change.
this.reset();
}
super.update(changedProperties);
}
/**
* @return {string}
*/
get value() {
return _getSingleValue(this.values);
}
/**
* @return {string}
*/
get _widgetType() {
const type = this.type;
const multi = this.multi;
if (type === fieldTypes.ENUM_TYPE) {
if (multi) {
return CHECKBOX_INPUT;
}
return SELECT_INPUT;
} else {
return AUTOCOMPLETE_INPUT;
}
}
/**
* @return {string} HTML type for the input.
*/
get _html5InputType() {
const type = this.type;
if (type === fieldTypes.INT_TYPE) {
return 'number';
} else if (type === fieldTypes.DATE_TYPE) {
return 'date';
}
return 'text';
}
/**
* Reset form values to initial state.
*/
reset() {
this.values = _wrapInArray(this.initialValues);
}
/**
* Return the values that the user added to this input.
* @return {Array<string>}åß
*/
getValuesAdded() {
if (!this.values || !this.values.length) return [];
return arrayDifference(
this.values, this.initialValues, equalsIgnoreCase);
}
/**
* Return the values that the userremoved from this input.
* @return {Array<string>}
*/
getValuesRemoved() {
if (!this.multi && (!this.values || this.values.length > 0)) return [];
return arrayDifference(
this.initialValues, this.values, equalsIgnoreCase);
}
/**
* Syncs form values and fires a change event as the user edits the form.
* @param {Event} e
* @fires Event#change
* @private
*/
_changeHandler(e) {
if (e instanceof KeyboardEvent) {
if (NON_EDITING_KEY_EVENTS.has(e.key)) return;
}
const input = e.target;
if (input.getValues) {
// <mr-multi-checkbox> support.
this.values = input.getValues();
} else {
// Is a native input element.
const value = input.value.trim();
this.values = _wrapInArray(value);
}
this.dispatchEvent(new Event('change'));
}
/**
* Syncs form values and fires a change event as the user edits the form.
* @param {React.SyntheticEvent} _e
* @param {string|Array<string>|null} value React autcoomplete form value.
* @fires Event#change
* @private
*/
_changeHandlerReact(_e, value) {
this.values = _wrapInArray(value);
this.dispatchEvent(new Event('change'));
}
} |
JavaScript | class SyncBreakpoints {
constructor() {
this._breakpoints = [];
}
/**
* @inheritdoc
*/
beginVisit(node, newNode) {
if (!node.isBreakpoint) {
return;
}
newNode.isBreakpoint = node.isBreakpoint;
const lineNumber = newNode.position.startLine;
this._breakpoints.push(lineNumber);
}
getBreakpoints() {
return _.sortedUniq(this._breakpoints);
}
/**
* @inheritdoc
*/
canVisit() {
return true;
}
/**
* At the end of node visit.
* @returns {any} Visit output.
* @memberof SyncBreakpoints
*/
endVisit() {
return undefined;
}
} |
JavaScript | class Horned extends Component {
constructor(props){
super(props);
this.state={
numberOfVotes:0
}
}
votes= ()=>{
this.setState({
numberOfVotes:this.state.numberOfVotes+1
})
}
modalhorned=()=>{
this.props.modal({
title:this.props.title,
image_url:this.props.image_url,
description:this.props.description
})
}
render() {
return (
<Col sm={12} md={9} lg={6} xl={4} style={{ paddingTop: "10vh", paddingLeft: "10vh" }} >
<Card style={{ width: '18.25rem',height:'32rem' , border: '2px solid black' }}>
<Card.Img onClick={this.modalhorned} variant="top" style={{ width: '18rem' , height:'20rem'}} src={this.props.image_url} />
<Card.Body>
<Card.Title>{this.props.title}</Card.Title>
<Card.Text>
{this.props.description}
</Card.Text>
<Button variant="primary" onClick={this.votes}>{this.state.numberOfVotes}</Button>
</Card.Body>
</Card>
</Col>
)
}
} |
JavaScript | class SpreadsheetSettingsSaveHistoryHashToken extends SpreadsheetSettingsHistoryHashToken {
constructor(value) {
super();
this.valueValue = value;
}
/**
* The value which may be null if the property was cleared or removed.
*/
value() {
return this.valueValue;
}
toHistoryHashToken() {
const value = this.value();
return "/" + SpreadsheetHistoryHashTokens.SAVE + "/" + (null != value ? encodeURIComponent(value) : "");
}
onSettingsAction(settingsWidget) {
settingsWidget.patchSpreadsheetMetadata(this.value());
}
equals(other) {
return this === other || (other instanceof SpreadsheetSettingsSaveHistoryHashToken && Equality.safeEquals(this.value(), other.value()));
}
} |
JavaScript | class ColliderSet {
constructor(raw) {
this.raw = raw || new raw_1.RawColliderSet();
}
/**
* Release the WASM memory occupied by this collider set.
*/
free() {
this.raw.free();
this.raw = undefined;
}
/**
* Creates a new collider and return its integer handle.
*
* @param bodies - The set of bodies where the collider's parent can be found.
* @param desc - The collider's description.
* @param parentHandle - The inteer handle of the rigid-body this collider is attached to.
*/
createCollider(bodies, desc, parentHandle) {
let hasParent = parentHandle != undefined && parentHandle != null;
if (hasParent && isNaN(parentHandle))
throw Error("Cannot create a collider with a parent rigid-body handle that is not a number.");
let rawShape = desc.shape.intoRaw();
let rawTra = math_1.VectorOps.intoRaw(desc.translation);
let rawRot = math_1.RotationOps.intoRaw(desc.rotation);
let rawCom = math_1.VectorOps.intoRaw(desc.centerOfMass);
// #if DIM3
let rawPrincipalInertia = math_1.VectorOps.intoRaw(desc.principalAngularInertia);
let rawInertiaFrame = math_1.RotationOps.intoRaw(desc.angularInertiaLocalFrame);
// #endif
let handle = this.raw.createCollider(rawShape, rawTra, rawRot, desc.useMassProps, desc.mass, rawCom,
// #if DIM3
rawPrincipalInertia, rawInertiaFrame,
// #endif
desc.density, desc.friction, desc.restitution, desc.frictionCombineRule, desc.restitutionCombineRule, desc.isSensor, desc.collisionGroups, desc.solverGroups, desc.activeCollisionTypes, desc.activeHooks, desc.activeEvents, hasParent, hasParent ? parentHandle : 0, bodies.raw);
rawShape.free();
rawTra.free();
rawRot.free();
rawCom.free();
// #if DIM3
rawPrincipalInertia.free();
rawInertiaFrame.free();
// #endif
return handle;
}
/**
* Remove a collider from this set.
*
* @param handle - The integer handle of the collider to remove.
* @param bodies - The set of rigid-body containing the rigid-body the collider is attached to.
* @param wakeUp - If `true`, the rigid-body the removed collider is attached to will be woken-up automatically.
*/
remove(handle, islands, bodies, wakeUp) {
this.raw.remove(handle, islands.raw, bodies.raw, wakeUp);
}
/**
* Gets the rigid-body with the given handle.
*
* @param handle - The handle of the rigid-body to retrieve.
*/
get(handle) {
if (this.raw.contains(handle)) {
return new collider_1.Collider(this.raw, handle);
}
else {
return null;
}
}
/**
* The number of colliders on this set.
*/
len() {
return this.raw.len();
}
/**
* Does this set contain a collider with the given handle?
*
* @param handle - The collider handle to check.
*/
contains(handle) {
return this.raw.contains(handle);
}
/**
* Applies the given closure to each collider contained by this set.
*
* @param f - The closure to apply.
*/
forEachCollider(f) {
this.forEachColliderHandle((handle) => {
f(new collider_1.Collider(this.raw, handle));
});
}
/**
* Applies the given closure to the handles of each collider contained by this set.
*
* @param f - The closure to apply.
*/
forEachColliderHandle(f) {
this.raw.forEachColliderHandle(f);
}
} |
JavaScript | class D600Utils {
constructor () {
this._indicationData = {}// per node indication data
}
/**
* @param {string} node Use this tag to keep track of partial data from multiple sources
*/
clearData (node = nodeIDdefault) {
if (node in this._indicationData) {
delete this._indicationData[node]
}
}
/**
* @param {string} hexStrData Hex string of input data. Data can be partial
* @param {string} node Use this tag to keep track of partial data from multiple sources
*/
parseFrame (hexStrData, node = nodeIDdefault) { // pass indication with device ID. Indication will be accumalated till '00'
if (this._isHexStr(hexStrData)) {
this._addData(hexStrData, node)
if (this._EOF(node)) {
const hexStr = this._getData(node)
const cardTypeStr = Buffer.from(hexStr.slice(0, 4), 'hex').toString('utf8')
this.clearData(node)
return { header: cardTypeStr, payload: hexStr.slice(4, -2) }
} else {
}
} else {
throw new Error('Input data is not hex string')
}
}
/**
* @param {Object} parsedFrame
*/
decode (parsedFrame) {
let ct = null
let outStr = null
let utf8decodeFlag = false
if (parsedFrame.header) {
let CtStr = parsedFrame.header.slice(0, 2)
if (CtStr === 'ht') { // starts with URL
CtStr = '4F'
}
const cType = parseInt(CtStr, 16)// first two chars denote card type or url
if (cardTypeMap.has(cType)) {
ct = cardTypeMap.get(cType).cardType
utf8decodeFlag = cardTypeMap.get(cType).utf8
} else {
ct = `Unknown type[${CtStr}]`
}
}
if (parsedFrame.payload && utf8decodeFlag) {
outStr = Buffer.from(parsedFrame.payload, 'hex').toString('utf8')
} else {
outStr = parsedFrame.payload
}
return { cardType: ct, utf8: utf8decodeFlag, cardData: outStr }
}
/**
*
* @param {*} hexStr
* @param {*} node
*/
_addData (hexStr, node = nodeIDdefault) {
if (node in this._indicationData) {
this._indicationData[node] += hexStr
} else {
this._indicationData[node] = hexStr
}
}
_getData (node = nodeIDdefault) {
if (node in this._indicationData) {
return this._indicationData[node]
} else {
}
}
_EOF (node = nodeIDdefault) {
if ((node in this._indicationData) && (this._indicationData[node].slice(-2) === '00')) { return true } else { return false }
}
_isHexStr (str) {
const regexp = /^[0-9a-fA-F]+$/
return regexp.test(str)
}
} |
JavaScript | class HCT {
constructor(internalHue, internalChroma, internalTone) {
this.internalHue = internalHue;
this.internalChroma = internalChroma;
this.internalTone = internalTone;
this.setInternalState(this.toInt());
}
/**
* @param hue 0 <= hue < 360; invalid values are corrected.
* @param chroma 0 <= chroma < ?; Informally, colorfulness. The color
* returned may be lower than the requested chroma. Chroma has a different
* maximum for any given hue and tone.
* @param tone 0 <= tone <= 100; invalid values are corrected.
* @return HCT representation of a color in default viewing conditions.
*/
static from(hue, chroma, tone) {
return new HCT(hue, chroma, tone);
}
/**
* @param argb ARGB representation of a color.
* @return HCT representation of a color in default viewing conditions
*/
static fromInt(argb) {
const cam = cam16_1.CAM16.fromInt(argb);
const tone = utils.lstarFromArgb(argb);
return new HCT(cam.hue, cam.chroma, tone);
}
toInt() {
return getInt(this.internalHue, this.internalChroma, this.internalTone);
}
/**
* A number, in degrees, representing ex. red, orange, yellow, etc.
* Ranges from 0 <= hue < 360.
*/
get hue() {
return this.internalHue;
}
/**
* @param newHue 0 <= newHue < 360; invalid values are corrected.
* Chroma may decrease because chroma has a different maximum for any given
* hue and tone.
*/
set hue(newHue) {
this.setInternalState(getInt(math.sanitizeDegreesDouble(newHue), this.internalChroma, this.internalTone));
}
get chroma() {
return this.internalChroma;
}
/**
* @param newChroma 0 <= newChroma < ?
* Chroma may decrease because chroma has a different maximum for any given
* hue and tone.
*/
set chroma(newChroma) {
this.setInternalState(getInt(this.internalHue, newChroma, this.internalTone));
}
/** Lightness. Ranges from 0 to 100. */
get tone() {
return this.internalTone;
}
/**
* @param newTone 0 <= newTone <= 100; invalid valids are corrected.
* Chroma may decrease because chroma has a different maximum for any given
* hue and tone.
*/
set tone(newTone) {
this.setInternalState(getInt(this.internalHue, this.internalChroma, newTone));
}
setInternalState(argb) {
const cam = cam16_1.CAM16.fromInt(argb);
const tone = utils.lstarFromArgb(argb);
this.internalHue = cam.hue;
this.internalChroma = cam.chroma;
this.internalTone = tone;
}
} |
JavaScript | class LinkedList {
constructor (value) {
this.head = { value, next: null }
this.tail = this.head
}
/*
* Inserts a new value to the end of the linked list
* @param {*} value - the value to insert
*/
insert (value) {
const node = { value, next: null }
this.tail.next = node
this.tail = node
return node
}
/*
* Deletes a node
* @param {*} node - the node to remove
* @return {*} value - the deleted node's value
*/
remove (node) {
let currentNode = this.head
let removedNodeValue = node.value
while (currentNode.next !== node) {
currentNode = currentNode.next
}
if (currentNode.next === node) currentNode.next = node.next
return removedNodeValue
}
/*
* Removes the value at the end of the linked list
* @return {*} - the removed value
*/
// {
// head: {value: 1, next: {value: 2, next: null}}
// tail: {value: 2, next: null}
// }
removeTail () {
let currentNode = this.head
while (currentNode.next !== this.tail) {
currentNode = currentNode.next
}
currentNode.next = null
this.tail = currentNode
return currentNode.value
}
/*
* Searches the linked list and returns true if it contains the value passed
* @param {*} value - the value to search for
* @return {boolean} - true if value is found, otherwise false
*/
contains (value) {
let currentNode = this.head
while (currentNode.value !== value) {
currentNode = currentNode.next
}
return currentNode.value === value
}
/*
* Checks if a node is the head of the linked list
* @param {{prev:Object|null, next:Object|null}} node - the node to check
* @return {boolean} - true if node is the head, otherwise false
*/
isHead (node) {
return node === this.head
}
/*
* Checks if a node is the tail of the linked list
* @param {{prev:Object|null, next:Object|null}} node - the node to check
* @return {boolean} - true if node is the tail, otherwise false
*/
isTail (node) {
return node === this.tail
}
} |
JavaScript | class ProductController {
/**
* @description Add product method
* @static
* @param {object} req
* @param {object} res
* @returns {object} Product
* @member ProductController
*/
static async addProduct(req, res) {
try {
const {
name,
description,
category,
price,
inStock
} = req.body;
const uploadedBy = req.id;
const product = await Product.create({
name,
description,
category,
price,
inStock,
uploadedBy
});
return handleSuccessResponse(res, product, 201);
} catch (error) {
return handleErrorResponse(res, error.message, 403);
}
}
/**
* @description Edit product method
* @static
* @param {object} req
* @param {object} res
* @returns {object} Product
* @member ProductController
*/
static async editProduct(req, res) {
try {
const {
productId: id
} = req.params;
const uploadedBy = req.id;
const {
name,
description,
category,
price,
inStock
} = req.body;
const found = await Product.findByPk(id);
if (!found) {
return handleErrorResponse(res, 'Product not found', 404);
}
await Product.update({
name,
description,
category,
price,
inStock,
uploadedBy
}, {
where: {
id
}
});
return res.status(200).json({
status: 'success',
message: 'Product updated successfully',
});
} catch (error) {
return handleErrorResponse(res, error.message, 403);
}
}
/**
* @description Add product image
* @static
* @param {object} req
* @param {object} res
* @returns {object} products
* @member ProductController
*/
static async uploadProductImage(req, res) {
try {
const {
productId: id
} = req.params;
const uploadedBy = req.id;
const found = await Product.findByPk(id);
if (!found) {
return handleErrorResponse(res, 'Product not found', 404);
}
// Delete old product image
if (found.imageName) {
await unLink(found.imageName);
}
// Upload new product image
if (req.file === undefined) {
return handleErrorResponse(res, 'Err: No file selected', 500);
}
const url = await cloudLink(req.file);
await Product.update({
imageUrl: url.url,
imageName: url.id,
uploadedBy
}, {
where: {
id
}
});
return res.status(200).json({
status: 'success',
message: 'Image added successfully',
});
} catch (error) {
return handleErrorResponse(res, error.message, 403);
}
}
/**
* @description Get all products
* @static
* @param {object} req
* @param {object} res
* @returns {object} products
* @member ProductController
*/
static async getProducts(req, res) {
try {
const products = await Product.findAll();
return handleSuccessResponse(res, products);
} catch (error) {
return handleErrorResponse(res, error.message, 500);
}
}
/**
* @description Delete product
* @static
* @param {object} req
* @param {object} res
* @returns {null} void
* @member ProductController
*/
static async deleteProduct(req, res) {
try {
const {
productId: id
} = req.params;
const product = await Product.findByPk(id);
if (!product) {
return handleErrorResponse(res, 'Product not found', 404);
}
await Product.destroy({
where: {
id
}
});
return res.status(204).json({
status: 'success',
message: 'product deleted successfully',
});
} catch (error) {
return handleErrorResponse(res, error.message, 500);
}
}
} |
JavaScript | class NamedRegExp {
/**
* Creates a regular expression with named capture groups
*
* Create a named capture group with `(?<name>.*)` or `(:<name>.*)` when using
* a RegExp.
* Named backreferences using `(?&name)` can be used either.
*
* For nodejs < v5.0 core-js polyfills are required.
* Use `npm i -S core-js` in your project and add:
*
* ```js
* // for node < v0.11
* require('core-js/es6/object')
* // for node < v5.0
* require('core-js/es6/string')
* require('core-js/es6/symbol')
* ```
*
* @param {String|RegExp} pattern - string or regex with named groups
* @param {String} [flags] - regex flags 'igm' if `regex` is a String
* @example
* import NamedRegExp from 'named-regexp-groups'
* //or
* const NamedRegExp = require('named-regexp-groups')
*
* // as string
* var r = new NamedRegExp('(?<foo>foo)(?<bar>)(-)(?:wat)(?<na>(?:na)+)(?&na)')
* // or as regex
* var r = new NamedRegExp(/(:<foo>foo)(:<bar>)(-)(?:wat)(:<na>(?:na)+)(:&na)/)
*
* r.source
* // => r.source === '(foo)([^]+)(-)(?:wat)((?:na)+)((?:na)+)'
*/
constructor (pattern, flags) {
var g = generate(pattern, flags)
this.regex = new RegExp(g.source, g.flags)
this.source = this.regex.source
this.groups = g.groups
}
/**
* Execute a search with `str`
* @param {String} str
* @return {Array} matching array with additional property `groups`
* @example
* var r = new NamedRegExp('(?<foo>foo)(bar)(?:waah)')
* r.exec('nanafoobarwaah')
* // => [ 'foobarwaah', 'foo', 'bar',
* // index: 4, input: 'nanafoobarwaah',
* // groups: { '0': 'bar', foo: 'foo' } ]
*/
exec (str) {
var res = this.regex.exec(str)
if (res) {
res.groups = {}
Object.keys(this.groups).forEach((name) => {
res.groups[name] = res[this.groups[name]]
})
}
return res
}
/**
* test for `str`
* @param {String} str
* @return {Boolean} matching array with additional property `groups`
* @example
* var r = new NamedRegExp('(?<foo>foo)(bar)(?:waah)')
* r.test('nanafoobarwaah')
* // => true
*/
test (str) {
return this.regex.test(str)
}
/**
* outputs regex as String
*/
toString () {
return this.regex.toString()
}
/**
* Replace `str` by `replacement` using named capture groups
*
* If using a string use `$+{name}` to define the placeholder for the capture group.
* This follows the Syntax of {@link http://perldoc.perl.org/perlretut.html#Named-backreferences|PCRE Named backreferences}.
*
* @name replace
* @param {String} str
* @param {String|Function} replacement
* @return {String} matching array with additional property `groups`
* @example
* var r = new NamedRegExp(/(:<year>\d+)-(:<month>\d+)-(:<day>\d+)/)
*
* // ---- using strings
* '2017-01-02'.replace(r, 'day: $+{day}, month: $+{month}, year: $+{year}')
* // => 'day: 02, month: 01, year: 2017')
*
* // ---- using function
* '2016-11-22'.replace(r, function () { // take care of NOT using an arrow function here!
* var args = [].slice.call(arguments)
* var g = this.groups
* return `day: ${args[g.day]}, month: ${args[g.month]}, year: ${args[g.year]}`
* })
* // => 'day: 22, month: 11, year: 2017')
*/
[Symbol.replace] (str, replacement) {
var repl = replacement
/* istanbul ignore next */
switch (typeof repl) {
case 'string':
repl = repl.replace(R_NAME_REPLACE, (m, name) => {
var idx = this.groups[name]
if (idx === undefined || idx === null) {
return ''
}
return '$' + this.groups[name]
})
break
case 'function':
repl = replacement.bind(this)
break
default:
return String(repl)
}
return str.replace(this.regex, repl)
}
/**
* Search for a match in `str`
* @name match
* @param {String} str
* @return {Array} matching array with additional property `groups`
* @example
* var r = new NamedRegExp('(?<foo>foo)(bar)(?:waah)')
* 'nanafoobarwaah'.match(r)
* // => [ 'foobarwaah', 'foo', 'bar',
* // index: 4, input: 'nanafoobarwaah',
* // groups: { '0': 'bar', foo: 'foo' } ]
*/
[Symbol.match] (str) {
return this.exec(str)
}
/**
* split `str`
* @name split
* @param {String} str
* @return {Array} matching array with additional property `groups`
* @example
* var r = new NamedRegExp('(?<foo>foo)')
* 'nanafoobarwaah'.split(r)
* // => [ 'nana', 'foo', 'barwaah' ]
*/
[Symbol.split] (str) {
return str.split(this.regex)
}
/**
* search `str`
* @name search
* @param {String} str
* @return {Number} position of index or -1
* @example
* var r = new NamedRegExp('(?<foo>foo)')
* 'nanafoobarwaah'.search(r)
* // => 4
*/
[Symbol.search] (str) {
return str.search(this.regex)
}
} |
JavaScript | class SourceRepository {
/**
* @type {Object.<string, string>} _repository An object containing the source code of the files that have been loaded.
*
* @protected
*/
static _repository = {};
/**
* Loads a single file into the repository.
*
* @param {string} path A string containing the path to the file to load.
*
* @return {Promise<void>}
*
* @throws {InvalidArgumentException} If an invalid file path is given.
*
* @async
*/
static async load(path){
if ( path === '' || typeof path !== 'string' ){
throw new InvalidArgumentException('Invalid path.', 1);
}
const contents = await filesystem.promises.readFile(path);
SourceRepository._repository[path] = contents.toString();
}
/**
* Loads a single file into the repository in synchronously way.
*
* @param {string} path A string containing the path to the file to load.
*
* @throws {InvalidArgumentException} If an invalid file path is given.
*/
static loadSync(path){
if ( path === '' || typeof path !== 'string' ){
throw new InvalidArgumentException('Invalid path.', 1);
}
SourceRepository._repository[path] = filesystem.readFileSync(path).toString();
}
/**
* Stores some given raw contents into the repository.
*
* @param {string} path A string containing the path representing the contents that will be stored.
* @param {string} contents A string containing the contents to store.
*
* @throws {InvalidArgumentException} If an invalid file path is given.
* @throws {InvalidArgumentException} If some invalid contents is given.
*/
static storeRaw(path, contents){
if ( path === '' || typeof path !== 'string' ){
throw new InvalidArgumentException('Invalid path.', 1);
}
if ( typeof contents !== 'string' ){
throw new InvalidArgumentException('Invalid contents.', 2);
}
SourceRepository._repository[path] = contents;
}
/**
* Loads multiple source files into the repository.
*
* @param {string[]} sources An array containing multiple paths to load.
*
* @return {Promise<void>}
*
* @throws {InvalidArgumentException} If an invalid array is given.
*/
static async preload(sources){
if ( !Array.isArray(sources) ){
throw new InvalidArgumentException('Invalid sources.', 1);
}
const processes = [], length = sources.length;
for ( let i = 0 ; i < length ; i++ ){
if ( sources[i] !== '' && typeof sources[i] === 'string' ){
processes.push(SourceRepository.load(sources[i]));
}
}
if ( processes.length > 0 ){
await Promise.all(processes);
}
}
/**
* Checks if a given source file has been loaded into the repository.
*
* @param {string} path A string containing the path of the source file to check.
*
* @returns {boolean} If the given file has been loaded will be returned "true".
*/
static isLoaded(path){
if ( path === '' || typeof path !== 'string' ){
throw new InvalidArgumentException('Invalid path.', 1);
}
return SourceRepository._repository.hasOwnProperty(path);
}
/**
* Returns the contents of the given source file.
*
* @param {string} path A string containing the path of the source file to return.
*
* @returns {?string} A string containing the source file contents or null if no such file has been loaded.
*
* @throws {InvalidArgumentException} If an invalid file path is given.
*/
static get(path){
if ( path === '' || typeof path !== 'string' ){
throw new InvalidArgumentException('Invalid path.', 1);
}
return SourceRepository._repository.hasOwnProperty(path) ? SourceRepository._repository[path] : null;
}
/**
* Removes a source file from the repository.
*
* @param {string} path A string containing the path of the source file to remove.
*
* @throws {InvalidArgumentException} If an invalid file path is given.
*/
static remove(path){
if ( path === '' || typeof path !== 'string' ){
throw new InvalidArgumentException('Invalid path.', 1);
}
delete SourceRepository._repository[path];
}
/**
* Drops all the source files that have been loaded into the repository.
*/
static clear(){
SourceRepository._repository = {};
}
/**
* Loads a source file from the repository, if no found, it is loaded from file and then both stored in the repository and returned.
*
* @param {string} path A string containing the path of the source file to load.
*
* @returns {Promise<string>} A string containing the source file contents.
*
* @throws {InvalidArgumentException} If an invalid file path is given.
*
* @async
*/
static async fetch(path){
let contents;
if ( SourceRepository._repository.hasOwnProperty(path) ){
contents = SourceRepository._repository[path];
}else{
contents = await filesystem.promises.readFile(path);
contents = contents.toString();
}
return contents;
}
/**
* Loads a source file from the repository, if no found, it is loaded from file and then both stored in the repository and returned.
*
* @param {string} path A string containing the path of the source file to load.
*
* @returns {string} A string containing the source file contents.
*
* @throws {InvalidArgumentException} If an invalid file path is given.
*/
static fetchSync(path){
let contents, useSourceRepository = BaseView.getUseSourceRepository();
if ( useSourceRepository && SourceRepository._repository.hasOwnProperty(path) ){
contents = SourceRepository._repository[path];
}else{
contents = filesystem.readFileSync(path).toString();
if ( useSourceRepository ){
SourceRepository.storeRaw(path, contents);
}
}
return contents;
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
// After a reload, we need to re-set the auth refresh interval
AuthHelper.setRefreshInterval(true);
}
render() {
return (
<div>
<AppRouter />
</div>
);
}
} |
JavaScript | class PartialPipe {
constructor(streams) {
this.streams = [];
for (const stream of streams) {
if (stream instanceof PartialPipe) this.streams.push(...stream.streams);
else this.streams.push(stream);
}
}
with(stream) { return new PartialPipe(this.streams.concat([ stream ])); }
pipeline(errCb) { return pipeline(this.streams, rejectIfError(errCb)); }
static of(...streams) { return new PartialPipe(streams); }
// really only used for testing purposes, to masquerade as a normal piped stream.
// do not use in general; use .with() and .pipeline() above instead.
pipe(out) { return reduce(((x, y) => x.pipe(y)), this.streams[0], this.streams.slice(1)).pipe(out); }
} |
JavaScript | class Dice extends Component {
render() {
return (
<div>
<ReactDice
numDice={1}
rollDone={this.rollDoneCallback}
ref={dice => this.reactDice = dice}
/>
</div>
)
}
rollAll() {
this.reactDice.rollAll()
}
won() {
for(let i=0; i < this.props.players.allplayers.length; i++){
if (this.props.players.allplayers[i].currentPostion >= 99){
alert(this.props.players.allplayers[i].name + " has won!")
this.props.players.winStatus = true;
this.props.players.winnerName = this.props.players.allplayers[i].name
const timestamp = Math.floor(Date.now()/1000)
// console.log(timestamp);
let newDate = new Date();
newDate.setTime(timestamp*1000);
let dateString = newDate.toUTCString();
// this.props.players.timeStamp = Intl.DateTimeFormat('en-US',{
// year: "numeric",
// month: "short",
// day: "2-digit",
// hour: "numeric",
// minute: "2-digit",
// second: "2-digit"
// }).format(timestamp);
this.props.players.timeStamp = dateString;
//timestamp logic change of state
// console.log(this.props.players.allplayers[i].name)
}
}
}
rollDoneCallback= (num) => {
// this.setState({side: `${num}`})
this.props.moveForward(num)
switch(this.props.players.allplayers[this.props.players.currPlayer].currentPostion){
case 74: {
this.props.jump(57)
break
}
case 71: {
this.props.jump(13)
break
}
case 35: {
this.props.jump(6)
break
}
case 53: {
this.props.jump(97)
break
}
case 28: {
this.props.jump(48)
break
}
case 14: {
this.props.jump(44)
break
}
default:
}
this.won()
this.props.changePlayer()
}
} |
JavaScript | class Widget {
constructor(DataProvider, draw = false,sizeX=false,sizeY=false) {
this._scheduledResize = false;
this.data = DataProvider;
this.drawCommnads = draw;
this.title=false;
this._draw = false;
if (draw && this.drawCommnads.drawtype) {
this.drawType = this.drawCommnads.drawtype.toUpperCase();
} else {
this.drawType = false;
}
// проверка результат с ошибкой или это текстовая строка
this.error = this.data.error;
this.text = this.data.text;
this.name = "Widget";
this.element = false;
this.init = false;
if (_.isNumber(sizeX)) {
this.sizeX = sizeX;
}
if (_.isNumber(sizeY)) {
this.sizeY = sizeY;
}
this.type = false;
// Адовый костылище, поскольку в конструктор должны передаваться
// dependency injecton, а не данные для работы класса. Поэтому я не могу
// передать в конструктор сервис и дергаю его по рабоче - крестьянски.
let isDark=angular.element('*[ng-app]').injector().get("ThemeService").isDark();
this.isDark = isDark;
window.isDarkTheme=isDark;
}
applySettings(o)
{
console.log('applySettings',o);
if (!_.isObject(o)) return;
if (o.title) this.title=o.title;
}
onDrag() {
// console.info("On widget Draw",this);
}
getSizeElementHeight()
{
// console.log("Height : clientHeight:",this.element[0].clientHeight);
// console.log("offsetHeight : element:",this.element[0].offsetHeight);
let $h=this.element[0].offsetHeight;
if ($h<100) $h=100;
return $h;
}
getSizeElementWidth()
{
// console.log("Width : element:",this.element[0].Width);
// console.log("offsetWidth : element:",this.element[0].offsetWidth);
return this.element[0].offsetWidth;
}
destroy(widget) {
console.info("Destroy widget is empty");
return false;
}
onResize() {
// console.info("On widget Resize",this);
}
scheduledResize() {
if (this._scheduledResize) {
return;
}
// отложенный ресайз , если много изменений
this._scheduledResize = true;
let th = this;
setTimeout(function () {
th._scheduledResize = false;
th.onResize();
}, 200);
}
toString() {
return '(' + this.name + ', ' + this.y + ')';
}
} |
JavaScript | class Processor {
/**
* @param {*} path
*/
constructor(options) {
this._image = sharp(options)
}
/**
* Resizes an image by keeping aspect
* ratio and not allowing to get larger
* than its original size.
*
* @public
* @param {int} width
* @param {int} height
* @returns {Processor}
*/
resize(width, height) {
this._image
.resize(width, height)
.withoutEnlargement(true)
return this
}
/**
* Resizes only the width of an image and
* sets the height automatically.
* Same as: resize(width, null)
*
* @public
* @param {int} width
* @returns {Processor}
*/
widen(width) {
return this.resize(width, null)
}
/**
* Resizes only the height of an image and
* sets the width automatically.
* Same as: resize(null, height)
*
* @public
* @param {int} height
* @returns {Processor}
*/
heighten(height) {
return this.resize(null, height)
}
/**
* Crops the image with one of the gravity
* or strategy constants. Must be called
* after resize().
*
* @public
* @param {int} gravity
* @returns {Processor}
*/
crop(gravity = 0) {
this._image.crop(gravity)
return this
}
/**
* Ignores aspect ratio. Must be called
* after resize().
*
* @public
* @returns {Processor}
*/
ignoreRatio() {
this._image.ignoreAspectRatio()
return this
}
/**
* Allows an image to be resized more than
* its original size. Must be called after
* resize().
*
* @public
* @returns {Processor}
*/
enlarge() {
this._image.withoutEnlargement(false)
return this
}
/**
* Rotates the image to the given angle in
* deegres. Angle must be a multiple of 90.
* If omitted, EXIF data will be used if
* present to automatically rotate the image.
*
* @public
* @param {int} angle
* @returns {Processor}
*/
rotate(angle = null) {
this._image.rotate(angle)
return this
}
/**
* Flips image in the X or Y axis.
*
* @public
* @param {string} axis
* @returns {Processor}
*/
flip(axis = 1) {
if (axis === 0)
this._image.flop()
else
this._image.flip()
return this
}
/**
* Sharpens the image using a mild,
* but fast algorithm.
*
* @public
* @returns {Processor}
*/
sharpen() {
this._image.sharpen()
return this
}
/**
* Blurs the image. Without an amount,
* it performs a mild, but fast blur.
* Amount must be a number between
* 0 and 100.
*
* @public
* @param {float} amount
* @returns {Processor}
*/
blur(amount = null) {
// Convert input 0-100 range to output
// 0.3 - 1000 range accepted by sharp.
const converted = amount
? amount / 100 * (1000 - 0.3) + 0.3
: amount
this._image.blur(converted)
return this
}
/**
* Extends the image filling the space
* with the background() color.
*
* @public
* @param {Object} extend
* @returns {Processor}
*/
extend(extend = {}) {
const options = {
...{
top: 0,
bottom: 0,
left: 0,
right: 0
},
...extend
}
this._image.extend(options)
return this
}
/**
* Merges the alpha transparency channel
* with the background, if provided.
*
* @public
* @returns {Processor}
*/
flatten() {
this._image.flatten()
return this
}
/**
* Applies gamma correction. Gamma must be
* a number between 1.0 and 3.0.
*
* @public
* @param {float} value
* @returns {Processor}
*/
gamma(value = 2.2) {
this._image.gamma(value)
return this
}
/**
* Converts the image to its negative.
*
* @public
* @returns {Processor}
*/
negative() {
this._image.negate()
return this
}
/**
* Enhances the image contrast.
*
* @public
* @returns {Processor}
*/
enhance() {
this._image.normalize()
return this
}
/**
* Sets a background color. Useful when using
* extend() or flatten().
*
* @public
* @param {Object} color
* @returns {Processor}
*/
background(color = {}) {
const options = { ...{ r: 0, g: 0, b: 0, alpha: 1 }, ...color }
this._image.background(options)
return this
}
/**
* Converts the image to 8-bit grayscale,
* 256 colors.
*
* @public
* @returns {Processor}
*/
grayscale() {
this._image.grayscale()
return this
}
/**
* Adds an overlay image on top of the original
* one. The overlay can be positioned using one
* of the gravity constants, and the top and
* left offsets.
*
* @public
* @param {string} path
* @param {Object} options
* @returns {Processor}
*/
overlay(path, options = { gravity: 0, top: 0, left: 0, tile: false }) {
this._image.overlayWith(path, options)
return this
}
/**
* Image information.
*
* @public
*/
metadata() {
this._image = this._image.metadata()
}
/**
* Exports to JPEG.
*
* @public
* @param {string} path
* @param {Object} options
*/
jpeg(path, options = { quality: 90, progressive: true }) {
this._image = this._image.jpeg(options).toFile(path)
}
/**
* Exports to PNG.
*
* @public
* @param {string} path
* @param {Object} options
*/
png(path, options = { progressive: true }) {
this._image = this._image.jpeg(options).toFile(path)
}
/**
* Exports to WebP.
*
* @public
* @param {string} path
* @param {Object} options
*/
webp(path, options = { quality: 90 }) {
this._image = this._image.jpeg(options).toFile(path)
}
/**
* Exports to a file by inferring the format
* from the extension.
*
* @public
* @param {string} path
* @param {Object} options
*/
save(path) {
this._image = this._image.toFile(path)
}
/**
* Raw sharp instance.
*
* @returns {Object}
*/
get raw() {
return this._image
}
} |
JavaScript | class ExtractFrameModule extends BaseModule {
constructor() {
super();
this.name = 'extractFrame';
this.lastInputDimensions=[0,0,0,0,0];
}
createDescription() {
return {
"name": "Extract Frame",
"description": "This element will extract a single frame from a time-series.",
"author": "Zach Saltzman and Xenios Papademetris",
"version": "1.0",
"inputs": baseutils.getImageToImageInputs(),
"outputs": baseutils.getImageToImageOutputs(),
"buttonName": "Extract",
"shortname" : "fr",
"slicer" : true,
"params": [
{
"name": "Frame",
"description": "Which frame in the time series to extract (fourth dimension)",
"priority": 1,
"advanced": false,
"gui": "slider",
"type": "int",
"varname": "frame",
"default" : 0,
},
{
"name": "Component",
"description": "Which component to extract a frame from (fifth dimension)",
"priority": 2,
"advanced": true,
"gui": "slider",
"type": "int",
"varname": "component",
"default" : 0,
},
{
"name": "UseJS",
"description": "Use the pure JS implementation of the algorithm",
"priority": 28,
"advanced": true,
"gui": "check",
"varname": "usejs",
"type": 'boolean',
"default": false,
"jsonly" : true,
},
baseutils.getDebugParam()
],
};
}
directInvokeAlgorithm(vals) {
console.log('oooo invoking: extractFrame with vals', JSON.stringify(vals));
let input = this.inputs['input'];
if (!super.parseBoolean(vals.usejs)) {
return new Promise((resolve, reject) => {
biswrap.initialize().then(() => {
this.outputs['output'] = biswrap.extractImageFrameWASM(input, {
"frame" : parseInt(vals.frame, 10),
"component" : parseInt(vals.component, 10)
},vals.debug);
resolve();
}).catch( (e) => {
reject(e.stack);
});
});
} else {
return new Promise((resolve,reject) => {
if (vals.debug)
console.log('oooo \t using pure JS implementation\noooo');
let dim=input.getDimensions();
let frame=vals.frame+vals.component*dim[3];
let out=smoothreslice.imageExtractFrame(input,frame);
if (out!==null) {
this.outputs['output']=out;
resolve();
}
reject('Failed to extract frame in JS');
});
}
}
updateOnChangedInput(inputs,guiVars=null) {
let newDes = this.getDescription();
inputs = inputs || this.inputs;
let img=inputs['input'] || null;
if (img===null)
return;
let dim = img.getDimensions();
if (this.compareArrays(dim,this.lastInputDimensions,3,4)<1) {
return;
}
this.lastInputDimensions=dim;
for (let i = 0; i < newDes.params.length; i++) {
let name = newDes.params[i].varname;
if (name==='frame' || name === 'component' ) {
if (name==='frame') {
newDes.params[i].low = 0;
if (dim[3]>1)
newDes.params[i].high = dim[3]-1;
else
newDes.params[i].high = 1;
} else if (name === 'component') {
newDes.params[i].low = 0;
if (dim[4]>1)
newDes.params[i].high = dim[4]-1;
else
newDes.params[i].high = 1;
}
}
if (guiVars)
guiVars[name]=newDes.params[i].default;
}
this.recreateGUI=true;
return newDes;
}
} |
JavaScript | class SdlPacketFactory {
/**
* Creates a heartbeat acknowlegement packet.
* @param {ServiceType} serviceType
* @param {Number} sessionID
* @param {Number} version
* @returns {SdlPacket}
*/
static createHeartbeatACK (serviceType, sessionID, version) {
return new SdlPacket(version, false, FrameType.CONTROL,
serviceType, SdlPacket.FRAME_INFO_HEART_BEAT_ACK, sessionID,
0, 0, null);
}
/**
* Creates an end session packet.
* @param {ServiceType} serviceType
* @param {Number} sessionID
* @param {Number} messageID
* @param {Number} version
* @param {Number} hashID
*/
static createEndSession (serviceType, sessionID, messageID, version, hashID) {
if (version < 5) {
const payload = new Uint8Array(BitConverter.int32ToArrayBuffer(hashID));
return new SdlPacket(version, false, FrameType.CONTROL,
serviceType, SdlPacket.FRAME_INFO_END_SERVICE, sessionID,
payload.length, messageID, payload, 0, payload.length);
} else {
const endSession = new SdlPacket(version, false, FrameType.CONTROL,
serviceType, SdlPacket.FRAME_INFO_END_SERVICE, sessionID,
0, messageID, null);
endSession.putTag(ControlFrameTags.RPC.EndService.HASH_ID, hashID);
return endSession;
}
}
} |
JavaScript | class RunError extends Error {
constructor(message) {
super(message);
/**
* A private field to help with RTTI that works in SxS scenarios.
*/
// tslint:disable-next-line:variable-name
/* @internal */ this.__pulumiRunError = true;
}
/**
* Returns true if the given object is an instance of a RunError. This is designed to work even when
* multiple copies of the Pulumi SDK have been loaded into the same process.
*/
static isInstance(obj) {
return obj && obj.__pulumiRunError;
}
} |
JavaScript | class ResourceError extends Error {
constructor(message, resource, hideStack) {
super(message);
this.resource = resource;
this.hideStack = hideStack;
/**
* A private field to help with RTTI that works in SxS scenarios.
*/
// tslint:disable-next-line:variable-name
/* @internal */ this.__pulumResourceError = true;
}
/**
* Returns true if the given object is an instance of a ResourceError. This is designed to work even when
* multiple copies of the Pulumi SDK have been loaded into the same process.
*/
static isInstance(obj) {
return obj && obj.__pulumResourceError;
}
} |
JavaScript | class Api extends HttpClient {
constructor() {
super(...arguments);
/**
* No description
*
* @tags Query
* @name QueryReadDelegate
* @summary Queries a list of delegates items.
* @request GET:/ancon/didregistry/delegates/{id}
*/
this.queryReadDelegate = (id, params = {}) => this.request(Object.assign({ path: `/ancon/didregistry/delegates/${id}`, method: "GET", format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryIdentifyOwner
* @summary Queries a list of owners items.
* @request GET:/ancon/didregistry/{address}
*/
this.queryIdentifyOwner = (address, params = {}) => this.request(Object.assign({ path: `/ancon/didregistry/${address}`, method: "GET", format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryGetAttributes
* @summary Queries a list of Attributes items.
* @request GET:/ancon/didregistry/{address}/attributes
*/
this.queryGetAttributes = (address, params = {}) => this.request(Object.assign({ path: `/ancon/didregistry/${address}/attributes`, method: "GET", format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryGetDidKey
* @request GET:/ancon/didregistry/{name}
*/
this.queryGetDidKey = (name, params = {}) => this.request(Object.assign({ path: `/ancon/didregistry/${name}`, method: "GET", format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryCollection
* @summary Collection queries the NFTs of the specified denom
* @request GET:/ancon/nft/collections/{denomId}
*/
this.queryCollection = (denomId, query, params = {}) => this.request(Object.assign({ path: `/ancon/nft/collections/${denomId}`, method: "GET", query: query, format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryDenoms
* @summary Denoms queries all the denoms
* @request GET:/ancon/nft/denoms
*/
this.queryDenoms = (query, params = {}) => this.request(Object.assign({ path: `/ancon/nft/denoms`, method: "GET", query: query, format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryDenom
* @summary Denom queries the definition of a given denom
* @request GET:/ancon/nft/denoms/{denomId}
*/
this.queryDenom = (denomId, params = {}) => this.request(Object.assign({ path: `/ancon/nft/denoms/${denomId}`, method: "GET", format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryOwner
* @summary Owner queries the NFTs of the specified owner
* @request GET:/ancon/nft/nfts
*/
this.queryOwner = (query, params = {}) => this.request(Object.assign({ path: `/ancon/nft/nfts`, method: "GET", query: query, format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryGetNft
* @summary NFT queries the NFT for the given denom and token ID
* @request GET:/ancon/nft/nfts/{denomId}/{tokenId}
*/
this.queryGetNft = (denomId, tokenId, params = {}) => this.request(Object.assign({ path: `/ancon/nft/nfts/${denomId}/${tokenId}`, method: "GET", format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryResource
* @summary Queries a list of resource items.
* @request GET:/ancon/resource/{cid}
*/
this.queryResource = (cid, query, params = {}) => this.request(Object.assign({ path: `/ancon/resource/${cid}`, method: "GET", query: query, format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryReadRoyaltyInfo
* @summary ReadRoyaltyInfo
* @request GET:/ancon/royalty/{cid}/{price}
*/
this.queryReadRoyaltyInfo = (cid, price, params = {}) => this.request(Object.assign({ path: `/ancon/royalty/${cid}/${price}`, method: "GET", format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryReadWithPath
* @summary Queries a list of resource items.
* @request GET:/ancon/{cid}/{path}
*/
this.queryReadWithPath = (cid, path, params = {}) => this.request(Object.assign({ path: `/ancon/${cid}/${path}`, method: "GET", format: "json" }, params));
/**
* No description
*
* @tags Query
* @name QueryResolveDidWeb
* @request GET:/user/{name}/did.json
*/
this.queryResolveDidWeb = (name, params = {}) => this.request(Object.assign({ path: `/user/${name}/did.json`, method: "GET", format: "json" }, params));
}
} |
JavaScript | class History {
static sortHistory (histories) {
return _.orderBy(histories, ['weight'],['desc']);
}
static getHistoryFailedTests(history) {
return history.visualTests.filter((test)=> {
return test.pass === false;
});
}
} |
JavaScript | class Helper {
/**
* It generates a uniqueId.
* @static
* @memberof Helper
* @returns {String} - A unique string.
*/
static generateId() {
return uuidV4();
}
/**
* It generates a unique Id.
* @static
* @memberof Helper
* @param {string} i - Short code required
* @returns {String} - A unique string.
*/
static generateUniqueId(i) {
return `${i}/${Math.random().toString(10).substr(2, 5)}`;
}
/**
* It generates a unique password.
* @static
* @memberof Helper
* @param {string} i - Short code required
* @returns {String} - A unique string.
*/
static generateUniquePassword() {
return `${Math.random().toString(32).substr(2, 9)}`;
}
/**
* It generates a unique Id.
* @static
* @memberof Helper
* @param {string} i - Short code required
* @param {string} query - query to perform
* @returns {String} - A unique string.
*/
static async regenerateUniqueId(i, query) {
const id = Helper.generateUniqueId(i);
const res = await db.oneOrNone(query, id);
if (res === null) {
return id;
}
Helper.regenerateUniqueId(i, query);
}
/**
* This is used for generating a hash and a salt from a user's password.
* @static
* @param {string} plainPassword - password to be encrypted.
* @memberof Helper
* @returns {Object} - An object containing the hash and salt of a password.
*/
static hashPassword(plainPassword) {
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(plainPassword, salt);
return {
salt, hash
};
}
/**
* This is used for generating a hash and a salt from a user's password.
* @static
* @param {string} plainPassword - password to be encrypted.
* @memberof Helper
* @returns {Object} - An object containing the hash and salt of a password.
*/
static hashPIN(plainPassword) {
const salt = bcrypt.genSaltSync(10);
return {
salt,
hash: Helper.generateHash(salt, plainPassword)
};
}
/**
* This generates a hash.
* @static
* @param {String} salt - A random string.
* @param {String} plain - A users' plain password or some sensitive data to be hashed.
* @memberof Helper
* @returns {String} - A hexadecimal string which is the hash value of
* the plain text passed as the second positional argument.
*/
static generateHash(salt, plain) {
const hash = sha256.hmac.create(salt);
hash.update(plain);
return hash.hex();
}
/**
* This checks if a plain text matches a certain hash value by generating
* a new hash with the salt used to create that hash.
* @static
* @param {string} plain - plain text to be used in the comparison.
* @param {string} hash - hashed value created with the salt.
* @param {string} salt - original salt value.
* @memberof Helper
* @returns {boolean} - returns a true or false, depending on the outcome of the comparison.
*/
static compareHash(plain, hash, salt) {
const hashMatch = Helper.generateHash(salt, plain);
return hash === hashMatch;
}
/**
* This checks if a plain text matches a certain hash value by generating
* a new hash with the salt used to create that hash.
* @static
* @param {string} plain - plain text to be used in the comparison.
* @param {string} hash - hashed value created with the salt.
* @param {string} salt - original salt value.
* @memberof Helper
* @returns {boolean} - returns a true or false, depending on the outcome of the comparison.
*/
static comparePassword(plain, hash) {
const validPassword = bcrypt.compareSync(plain, hash);
if (validPassword) {
return true;
}
return false;
}
/**
* Synchronously signs the given payload into a JSON Web Token string.
* @static
* @param {string | number | Buffer | object} payload - payload to sign
* @param {string | number} expiresIn - Expressed in seconds or a string describing a
* time span. Eg: 60, "2 days", "10h", "7d". Default specified is 2 hours.
* @memberof Helper
* @returns {string} - JWT Token
*/
static generateToken(payload, expiresIn = '2h') {
return jwt.sign(payload, SECRET, { expiresIn });
}
/**
* This verify the JWT token with the secret with which the token was issued with
* @static
* @param {string} token - JWT Token
* @memberof Helper
* @returns {string | number | Buffer | object } - Decoded JWT payload if
* token is valid or an error message if otherwise.
*/
static verifyToken(token) {
return jwt.verify(token, SECRET);
}
/**
* Adds jwt token to object.
* @static
* @param { Object } user - New User Instance.
* @param { Boolean } is_admin - A boolean that helps determine whether the user is an admin.
* @memberof Helpers
* @returns {object } - A new object containing essential user properties and jwt token.
*/
static addTokenToUser(user) {
const { id, first_name, last_name, email, username, phone_no } = user;
const token = Helper.generateToken({
id,
first_name,
last_name,
email,
username,
phone_no,
});
return token;
}
/**
* Parses data if it is a string as a javascript object or returns it if it is an object.
* @static
* @param { String | Object } data - The data.
* @memberof Helper
* @returns { string } - It returns the facility ame.
*/
static parseOrReturnData(data) {
return typeof data === 'string' ? JSON.parse(data) : data;
}
/**
* Creates DB Error object and logs it with respective error message and status.
* @static
* @param { String | Object } data - The data.
* @memberof Helper
* @returns { Object } - It returns an Error Object.
*/
static makeError({ error, status }) {
const dbError = new DBError({
status,
message: error.message,
});
Helper.moduleErrLogMessager(dbError);
return dbError;
}
/**
* Generates a JSON response for success scenarios.
* @static
* @param {Response} res - Response object.
* @param {object} options - An object containing response properties.
* @param {object} options.data - The payload.
* @param {string} options.message - HTTP Status code.
* @param {number} options.code - HTTP Status code.
* @memberof Helpers
* @returns {JSON} - A JSON success response.
*/
static successResponse(
res,
{ data, message = SUCCESS_RESPONSE, code = 200 }
) {
return res.status(code).json({
status: SUCCESS,
message,
data,
});
}
/**
* Generates a JSON response for failure scenarios.
* @static
* @param {Request} req - Request object.
* @param {Response} res - Response object.
* @param {object} error - The error object.
* @param {number} error.status - HTTP Status code, default is 500.
* @param {string} error.message - Error message.
* @param {object|array} error.errors - A collection of error message.
* @memberof Helpers
* @returns {JSON} - A JSON failure response.
*/
static errorResponse(req, res, error) {
const aggregateError = { ...serverError, ...error };
Helper.apiErrLogMessager(aggregateError, req);
return res.status(aggregateError.status).json({
status: FAIL,
message: aggregateError.message,
errors: aggregateError.errors,
});
}
/**
* Generates log for module errors.
* @static
* @param {object} error - The module error object.
* @memberof Helpers
* @returns { Null } - It returns null.
*/
static moduleErrLogMessager(error) {
return logger.error(`${error.status} - ${error.name} - ${error.message}`);
}
/**
* Generates log for api errors.
* @static
* @param {object} error - The API error object.
* @param {Request} req - Request object.
* @memberof Helpers
* @returns {String} - It returns null.
*/
static apiErrLogMessager(error, req) {
logger.error(
`${error.name} - ${error.status} - ${error.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`
);
}
/**
* Fetches a pagination collection of a resource.
* @static
* @param {Object} options - configuration options.
* @param {number} options.page - Current page e.g: 1 represents first
* 30 records by default and 2 represents the next 30 records.
* @param {number} options.limit - Max number of records.
* @param {number} options.getCount - Max number of records.
* @param {number} options.getResources - Max number of records.
* @param {Array} options.params - Extra parameters for the get resources query.
* @param {Array} options.countParams - Extra parameters for the get counts query.
* @memberof Helper
* @returns {Promise} - Returns a promise array of the count anf the resources
*/
static async fetchResourceByPage({
page,
limit,
getCount,
getResources,
params = [],
countParams = [],
}) {
const offSet = (page - 1) * limit;
const fetchCount = db.one(getCount, [...countParams]);
const fetchCountResource = db.any(getResources, [offSet, limit, ...params]);
return Promise.all([fetchCount, fetchCountResource]);
}
/**
* calculate number of pages
* @static
* @param { Number } total - Total number of a particular resource.
* @param { Number } limit - The total number of resource to be displayed per page
* @memberof Helper
* @returns { Number } - Returns the display page value.
*/
static calcPages(total, limit) {
const displayPage = Math.floor(total / limit);
return total % limit ? displayPage + 1 : displayPage;
}
/**
* Generate token for user verification
* @static
* @memberof Helper
* @returns {string} - Verification Token
*/
static generateVerificationToken() {
const token = crypto({ length: 16, type: 'url-safe' });
return token;
}
} |
JavaScript | class DependentSelectBoxes {
/**
* @constructor
* @param {HTMLSelectElement} parent - The parent select box.
* @param {HTMLSelectElement} child - The child select box.
* @param {Object} options - Specific options for this instance.
*/
constructor(parent, child, options = {}) {
if (!parent || parent.tagName !== 'SELECT') {
throw new Error('Parent element must be a select box');
}
if (!child || child.tagName !== 'SELECT') {
throw new Error('Child element must be a select box');
}
Object.assign(this, defaultOptions, options, {
parent,
child,
childOptions: Array.from(child.options),
});
this._onChangeParent = onChangeParent.bind(this);
this._onChangeChild = onChangeChild.bind(this);
this.parent.addEventListener('change', this._onChangeParent);
this.child.addEventListener('change', this._onChangeChild);
// trigger the change event of the parent to build the initial state
this._onChangeParent();
}
/**
* Destroys the functionality of the select boxes and
* resets the state of both.
*/
destroy() {
// remove the used event listener
this.parent.removeEventListener('change', this._onChangeParent);
this.child.removeEventListener('change', this._onChangeChild);
// make sure to show all child options
this._showChildOptions(() => true);
// delete everything that is bound to `this`
Object.keys(this).forEach(name => {
delete this[name];
});
}
/**
* Shows the child options that pass the filter.
* @param {Function} filter - Function that takes a child option and
* returns whether to show the option or not.
* @private
*/
_showChildOptions(filter) {
const currentSelectedOption = this.child.options[this.child.selectedIndex];
// remove all options
Array.from(this.child.children).forEach(child => {
this.child.removeChild(child);
});
// Loop through all possible child options and check whether
// to display them or not. We need to save whether the selection
// of the select box needs to change. This happens if the selected
// option won't get displayed in the new select box.
let needToChangeSelection = true;
this.childOptions.forEach(childOption => {
if (filter(childOption)) {
this.child.appendChild(childOption);
childOption.selected = false;
if (childOption === currentSelectedOption) {
needToChangeSelection = false;
}
}
});
// select the first option in the select box if we need
// to change the selection
if (needToChangeSelection) {
this._selectOption(head(this.child.options));
} else {
currentSelectedOption.selected = true;
}
}
/**
* Selects the `option` and dispatches a change event.
* @param {HTMLOptionElement} option - The option to be selected.
* @private
*/
_selectOption(option) {
if (!option || option.selected) return;
option.selected = true;
option.parentNode.dispatchEvent(new CustomEvent('change'));
}
} |
JavaScript | class SearchBar extends Component {
//Handling Events (to be written inside SearchBar class)
// 1. Declare event handler
// 2. pass it to the element being handled
// render() { // necessary for each class
// return <input onChange={this.onInputChange} />;
// }
// onInputChange(event) { //we need an event object to handle the event it has all data
// console.log(event.target.value);
// }
// more compact code using arrow function
// render() { //more compact code
// return <input onChange={ event => console.log(event.target.value)} />;
// //for single argument and single line code of function we can drop of the brackets
// }
//State is plain javaScript object used to record and react to user Events
//each class based component that we define has its own State object
//whenever component state is changed , component immediately rerenders and all of its children too
//each instance has a different copy of State
// we need to initialize before using it
//for that we set property state to plain js abject inside class's constructor method
//Control field is a form element whose value is set by the state rather the other way around
constructor(props) {
super(props); // calling parent class method using super
this.state = {term: ''}; //state is initialized and only in constructor written like this everywhere else we use setState
}
render() { //more compact code
// input is controlled element its value is updated rerendering while term updates as user types text
return (
<div className = "search-bar">
<input
value={this.state.term}
onChange={ event => this.onInputChange(event.target.value)} />
</div>
);
//Value of the input: {this.state.term}
// we are just showing its value not updating it
}
onInputChange(term){
this.setState({term});
this.props.onSearchTermChange(term);
}
} |
JavaScript | class FuroDataContextMenuItem extends FBP(LitElement) {
/**
* @private
* @return {Object}
*/
static get properties() {
return {
/**
* focused state
*/
focused: { type: Boolean, reflect: true },
};
}
/**
* flow is ready lifecycle method
* @private
*/
_FBPReady() {
super._FBPReady();
// this._FBPTraceWires()
this.addEventListener('mouseover', () => {
this._mouseFocus = true;
// do not reopen when submenu exist
const customEvent = new Event('mousefocus', { composed: true, bubbles: true });
customEvent.detail = this._index;
this.dispatchEvent(customEvent);
});
}
bindData(menuNode) {
this.menuitem = menuNode;
if (this.menuitem.children.repeats.length > 0) {
this._FBPTriggerWire('--submenu', this.menuitem);
}
if (this.menuitem.leading_divider._value === true) {
const separator = document.createElement('div');
separator.classList.add('separator');
this.parentNode.insertBefore(separator, this);
}
}
/**
* send event to open the submenu
* @param byKeyboard Boolean
* @private
*/
_openSub(byKeyboard) {
const customEvent = new Event('opensub-requested', { composed: true, bubbles: true });
customEvent.detail = { menu: this.menuitem, initiator: this };
customEvent.byKeyboard = byKeyboard;
this.dispatchEvent(customEvent);
this._submenu = customEvent.submenu;
}
/**
* The submenu item was set from the _openSub() event response
* @private
*/
_closeSub() {
if (this._submenu) {
this._submenu.hideMenu();
}
}
/**
* Select the item, furo-data-context-menu callback will be called
* @private
*/
_selectItem() {
const customEvent = new Event('item-selected', { composed: true, bubbles: true });
customEvent.detail = this.menuitem;
this.dispatchEvent(customEvent);
}
/**
* selects the item if it does not have child elements
*/
select(key) {
switch (key) {
case 'Enter':
// select
if (this.menuitem.children.repeats.length === 0) {
this._selectItem();
}
break;
case 'ArrowLeft':
// closes subnav
if (this.menuitem.children.repeats.length > 0) {
this._closeSub();
}
break;
case 'ArrowRight':
// opens subnav
if (this.menuitem.children.repeats.length > 0) {
this._openSub(true);
}
break;
default:
}
}
/**
* Open the item if it have children
* @private
*/
_mouseSelect() {
// select
if (this.menuitem.children.repeats.length === 0) {
this._selectItem();
}
}
/**
* store the index for mouseover focus
* @param i
*/
index(i) {
this._index = i;
}
/**
* mark item as focused
*/
setFocused() {
this.focused = true;
// opens subnav on mousefocus
if (this._mouseFocus && this.menuitem.children.repeats.length > 0) {
this._openSub();
this._mouseFocus = false;
}
}
/**
* mark item as unfocused
*/
unsetFocused() {
this.focused = false;
if (this.menuitem.children.repeats.length > 0) {
this._closeSub();
}
}
disconnectedCallback() {
this._closeSub();
}
/**
* Themable Styles
* @private
* @return {CSSResult}
*/
static get styles() {
// language=CSS
return (
Theme.getThemeForComponent('FuroDataContextMenuItem') ||
css`
:host {
display: block;
padding: 8px 0;
}
:host([hidden]) {
display: none;
}
.children {
display: none;
padding-right: 24px;
}
furo-icon[children] {
display: block;
}
/* 4px from left comes from horizontal-flex*/
furo-icon {
padding: 6px 4px 0px 20px;
}
/* the display name */
.name {
padding: 0 16px;
overflow: hidden;
}
.command {
color: #838383;
padding-right: 24px;
}
furo-horizontal-flex {
height: 32px;
line-height: 32px;
cursor: pointer;
box-sizing: border-box;
padding-left: 4px;
}
`
);
}
/**
* @private
* @returns {TemplateResult}
* @private
*/
render() {
// language=HTML
return html`
<furo-horizontal-flex @click="${this._mouseSelect}"
><furo-icon ?hidden="${this.menuitem._noicon}" icon="${this.menuitem.icon}"></furo-icon>
<div flex class="name">${this.menuitem.display_name}</div>
<div class="command">${this.menuitem.command}</div>
<furo-icon
icon="chevron-right"
class="children"
@click="${this._openSub}"
?children="${this.menuitem.children.repeats.length > 0}"
></furo-icon>
</furo-horizontal-flex>
`;
}
} |
JavaScript | class BaseLogger {
/**
* Initialize logger.
*/
constructor(agent, options = {}) {
this._agent = agent;
this._host = BaseLogger.host_lookup();
this._metadata_id = crypto.randomBytes(16).toString('hex');
this._queue = null;
this._skip_compression = false;
this._skip_submission = false;
this._url = null;
this._version = BaseLogger.version_lookup();
// read provided options
// ! (Code Review) it seems like these var_exists variables are only being used
// ! once. It seems like the conditionals could just be done in-place instead.
// ! especially since not all of them are even going to be accessed.
const enabled = options['enabled'];
const enabled_exists = (typeof enabled === 'boolean');
const queue = options['queue'];
const queue_exists = (typeof queue === 'object') && Array.isArray(queue);
const url = (typeof options === 'string') ? options : options['url'];
const url_exists = (typeof url === 'string');
// set options in priority order
/**
* ! (Code Review) If `enabled` should default to true, maybe that should be
* ! specified on its declaration instead of with this statement to make that
* ! more obvious.
*/
this._enabled = !enabled_exists || (enabled_exists && enabled === true);
if (queue_exists) {
this._queue = queue;
} else if (url_exists) {
this._url = url;
} else {
this._url = usage_loggers.urlByDefault();
// ! (Code Review) Could we use url_exists on this line?
this._enabled = (typeof this._url === 'string') && (this._url.length > 0);
}
// validate url when present
// ! (Code Review) Maybe we could go ahead and use this logic with url_exists and change it to url_valid
if (typeof this._url === 'undefined' || ((this._url !== null) && !BaseLogger.valid_url(this._url))) {
this._url = null;
this._enabled = false;
}
// parse and cache url properties
// ! (Code Review) Could use url_valid here to prevent confusion as to why url might be null
if (this._url != null) {
try {
const target = urls.parse(this._url);
this._url_library = target.protocol === 'https' ? https : http;
this._url_options = {
host: target.host.split(':')[0],
port: target.port,
path: target.path,
method: 'POST',
headers: {
'Content-Encoding': this._skip_compression ? 'identity' : 'deflated',
'Content-Type': 'application/json; charset=UTF-8'
}
};
} catch (e) {
// ! (Code Review) If this breaks, is there something we could do to alert
// ! the user beyond simply disabling the logger?
this._url = null;
this._url_library = null;
this._url_options = null;
this._enabled = false;
}
}
// finalize internal properties
// ! (Code Review) Why isn't this using queue_exists or url_exists (or url_valid)?
this._enableable = (this._queue !== null) || (this._url !== null);
this._submit_failures = new Uint32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
this._submit_successes = new Uint32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
// mark immutable properties
// ! (Code Review) Not specifically a critique of this code, just want to note
// ! that this block, and much of the type checking logic I've seen so far, would
// ! be much easier to implement and understand with TypeScript.
Object.defineProperty(this, '_agent', {configurable: false, writable: false});
Object.defineProperty(this, '_host', {configurable: false, writable: false});
Object.defineProperty(this, '_metadata_id', {configurable: false, writable: false});
Object.defineProperty(this, '_queue', {configurable: false, writable: false});
Object.defineProperty(this, '_submit_failures', {configurable: false, writable: false});
Object.defineProperty(this, '_submit_successes', {configurable: false, writable: false});
Object.defineProperty(this, '_url', {configurable: false, writable: false});
Object.defineProperty(this, '_url_library', {configurable: false, writable: false});
Object.defineProperty(this, '_url_options', {configurable: false, writable: false});
Object.defineProperty(this, '_version', {configurable: false, writable: false});
}
/**
* Returns agent string identifying this logger.
*/
get agent() {
return this._agent;
}
/**
* Disable this logger.
*/
disable() {
this._enabled = false;
return this;
}
/**
* Enable this logger.
*/
enable() {
this._enabled = this._enableable;
return this;
}
/**
* Returns true if this logger can ever be enabled.
*/
get enableable() {
return this._enableable;
}
/**
* Returns true if this logger is currently enabled.
*/
get enabled() {
return this._enableable && this._enabled && usage_loggers.enabled;
}
/**
* Returns cached host identifier.
*/
get host() {
return this._host;
}
/**
* Returns high-resolution time in milliseconds.
*/
get hrmillis() {
const [seconds, nanos] = process.hrtime();
return seconds * 1000 + nanos / 1000000;
}
/**
* Returns metadata id hash.
*/
get metadata_id() {
return this._metadata_id;
}
/**
* Returns queue destination where messages are sent.
*/
get queue() {
return this._queue;
}
/**
* Returns true if message compression is being skipped.
*/
get skip_compression() {
return this._skip_compression;
}
/**
* Sets if message compression will be skipped.
*/
set skip_compression(value) {
this._skip_compression = value;
}
/**
* Returns true if message submission is being skipped.
*/
get skip_submission() {
return this._skip_submission;
}
/**
* Sets if message submission will be skipped.
*/
set skip_submission(value) {
this._skip_submission = value;
}
/**
* Returns promise to submit JSON message to intended destination.
*/
submit(msg) {
// ! (Code Review) ===?
if (msg == null || this._skip_submission || !this.enabled) {
// ! (Code Review) Can leave out `reject`
return new Promise((resolve, reject) => resolve(true));
// ! (Code Review) Should any of the below code still run if the logger is not enabled?
} else if (this._queue !== null) {
this._queue.push(msg);
Atomics.add(this._submit_successes, 0, 1);
// ! (Code Review) Can leave out `reject`
return new Promise((resolve, reject) => resolve(true));
} else {
// ! (Code Review) Can leave out `reject`
return new Promise((resolve, reject) => {
try {
const request = this._url_library.request(this._url_options, (response) => {
if (response.statusCode === 204) {
Atomics.add(this._submit_successes, 0, 1);
resolve(true);
} else {
Atomics.add(this._submit_failures, 0, 1);
resolve(true);
}
});
request.on('error', () => {
Atomics.add(this._submit_failures, 0, 1);
resolve(true);
});
if (this._skip_compression) {
request.write(msg);
request.end();
} else {
zlib.deflate(msg, function (err, buffer) {
request.write(buffer);
request.end();
});
}
} catch (e) {
Atomics.add(this._submit_failures, 0, 1);
resolve(true);
}
});
}
}
/**
* Returns count of submissions that failed.
*/
get submit_failures() {
return Atomics.load(this._submit_failures, 0);
}
/**
* Returns count of submissions that succeeded.
*/
get submit_successes() {
return Atomics.load(this._submit_successes, 0);
}
/**
* Returns url destination where messages are sent.
*/
get url() {
return this._url;
}
/**
* Checks if provided value is a valid URL string.
* Copied from https://github.com/ogt/valid-url/blob/8d1fc52b21ceab99b68f415838035859b7237949/index.js#L22
*/
static valid_url(value) {
if (!value) return;
// check for illegal characters
if (/[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i.test(value)) return;
// check for hex escapes that aren't complete
if (/%[^0-9a-f]/i.test(value)) return;
if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return;
// from RFC 3986
let splitted = value.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
let scheme = splitted[1];
let authority = splitted[2];
let path = splitted[3];
let query = splitted[4];
let fragment = splitted[5];
let out = '';
// scheme and path are required, though the path can be empty
if (!(scheme && scheme.length && path.length >= 0)) return;
// if authority is present, the path must be empty or begin with a /
if (authority && authority.length) {
if (!(path.length === 0 || /^\//.test(path))) return;
} else {
// if authority is not present, the path must not start with //
if (/^\/\//.test(path)) return;
}
// scheme must begin with a letter, then consist of letters, digits, +, ., or -
if (!/^[a-z][a-z0-9\+\-\.]*$/.test(scheme.toLowerCase())) return;
// re-assemble the URL per section 5.3 in RFC 3986
out += scheme + ':';
if (authority && authority.length) {
out += '//' + authority;
}
out += path;
if (query && query.length) out += '?' + query;
if (fragment && fragment.length) out += '#' + fragment;
return out;
}
/**
* Returns cached version number.
*/
get version() {
return this._version;
}
/**
* Retrieves host identifier.
*/
static host_lookup() {
const dyno = process.env.DYNO;
if (typeof dyno !== 'undefined') return dyno;
try {
return os.hostname();
} catch (e) {
return 'unknown';
}
}
/**
* Retrieves version number from package file.
*/
static version_lookup() {
return require('../package.json').version;
}
} |
JavaScript | class TapeHarness {
/**
* @param {import('./types/pre-bundled__tape')} tape
* @param {new (options: object) => T} Harness
*/
constructor (tape, Harness) {
this.tape = tape
this.Harness = Harness
}
/**
* @param {string} testName
* @param {object} [options]
* @param {(harness: T, test: Test) => (void | Promise<void>)} [fn]
*/
test (testName, options, fn) {
this._test(this.tape, testName, options, fn)
}
/**
* @param {string} testName
* @param {object} [options]
* @param {(harness: T, test: Test) => (void | Promise<void>)} [fn]
*/
only (testName, options, fn) {
this._test(this.tape.only, testName, options, fn)
}
/**
* @param {string} testName
* @param {object} [options]
* @param {(harness: T, test: Test) => (void | Promise<void>)} [fn]
*/
skip (testName, options, fn) {
this._test(this.tape.skip, testName, options, fn)
}
/**
* @param {(str: string, fn?: TestCase) => void} tapeFn
* @param {string} testName
* @param {object} [options]
* @param {(harness: T, test: Test) => (void | Promise<void>)} [fn]
*/
_test (tapeFn, testName, options, fn) {
if (!fn && typeof options === 'function') {
fn = /** @type {(h: T, test: Test) => void} */ (options)
options = {}
}
if (!fn) {
return tapeFn(testName)
}
const testFn = fn
tapeFn(testName, (assert) => {
this._onAssert(assert, options || {}, testFn)
})
}
/**
* @param {Test} assert
* @param {object} options
* @param {(harness: T, test: Test) => (void | Promise<void>)} fn
*/
_onAssert (assert, options, fn) {
const _end = assert.end
let onlyOnce = false
assert.end = asyncEnd
const _plan = assert.plan
assert.plan = planFail
Reflect.set(options, 'assert', assert)
var harness = new this.Harness(options)
var ret = harness.bootstrap(onHarness)
if (ret && ret.then) {
ret.then(function success () {
process.nextTick(onHarness)
}, function fail (promiseError) {
process.nextTick(onHarness, promiseError)
})
}
/**
* @param {Error} [err]
*/
function onHarness (err) {
if (err) {
return assert.end(err)
}
var ret = fn(harness, assert)
if (ret && ret.then) {
ret.then(function success () {
// user may have already called end()
if (!onlyOnce) {
assert.end()
}
}, function fail (promiseError) {
var ret = harness.close((err2) => {
if (err2) {
console.error('TestHarness.close() has an err', {
error: err2
})
}
process.nextTick(() => {
throw promiseError
})
})
if (ret && ret.then) {
ret.then(() => {
process.nextTick(() => {
throw promiseError
})
}, (/** @type {Error} */ _failure) => {
console.error('TestHarness.close() has an err', {
error: _failure
})
process.nextTick(() => {
throw promiseError
})
})
}
})
}
}
/**
* @param {number} count
*/
function planFail (count) {
const e = new Error('temporary message')
const errorStack = e.stack || ''
const errorLines = errorStack.split('\n')
const caller = errorLines[2]
// TAP: call through because plan is called internally
if (/node_modules[/?][\\?\\?]?tap/.test(caller)) {
return _plan.call(assert, count)
}
throw new Error('tape-harness: t.plan() is not supported')
}
/**
* @param {Error} [err]
*/
function asyncEnd (err) {
if (onlyOnce) {
return _end.call(assert, err)
}
onlyOnce = true
if (err) {
assert.ifError(err)
}
var ret = harness.close((err2) => {
onEnd(err2, err)
})
if (ret && ret.then) {
ret.then(() => {
process.nextTick(onEnd)
}, (/** @type {Error} */ promiseError) => {
process.nextTick(onEnd, promiseError, err)
})
}
}
/**
* @param {Error} [err2]
* @param {Error} [err]
*/
function onEnd (err2, err) {
if (err2) {
assert.ifError(err2)
}
_end.call(assert, err || err2)
}
}
} |
JavaScript | class PackageManager extends PackageElement {
constructor(locationInEpub = "") {
super("package", undefined, {
xmlns: "http://www.idpf.org/2007/opf",
dir: undefined,
id: undefined,
prefix: undefined,
"xml:lang": undefined,
"unique-identifier": undefined,
version: "3.0",
});
this._location = locationInEpub; // the path relative to the epub root.
this.metadata = undefined;
this.manifest = undefined;
this.spine = undefined;
this.rawData = undefined;
}
set location(locationInEpub) {
this._location = locationInEpub; // the path relative to the epub root.
if (this.manifest) {
this.manifest.location = locationInEpub;
}
}
get location() {
return this._location;
}
/**
* Set the unique identifier of the ebook. This sets both the package
* 'unique-identifier' id value which refers to a meta tag as well as the
* meta tag value and id.
* Note that the uid has side-effects with epub font obfuscation. The UID
* is used as the obfuscation key and obfuscated fonts must be
* re-processed when changing this value.
* @param {string} value the UUID or other unique identifier
* @param {string} id - the id of the meta tag that marks it as the uid.
*/
setUniqueIdentifier(value, id = "pub-id") {
const existingId = this.attributes["unique-identifier"];
this.attributes["unique-identifier"] = id;
const uidMetadata = existingId
? this.metadata.findItemWithId("dc:identifier", existingId)
: undefined;
if (uidMetadata) {
uidMetadata.value = value;
uidMetadata.id = id;
} else {
this.metadata.addItem("dc:identifier", value, { id: id });
}
}
/**
* Find the epub unique-identifer value
*/
findUniqueIdentifier() {
const metadataId = this.attributes["unique-identifier"];
if (metadataId) {
const uidMetadata = this.metadata.findItemWithId(
"dc:identifier",
metadataId
);
if (uidMetadata) {
return uidMetadata.value;
}
}
}
/**
* Legacy Epub 2.0 specification states that a spine element with the 'toc' attribute
* identifies the idref of the NCX file in the manifest
* TODO - handle relative and absolute urls. resolve path
*/
findNcxFilePath() {
const tocId = this.spine.toc;
if (tocId) {
const ncxItem = this.manifest.findItemWithId(tocId);
if (ncxItem) {
return FileManager.resolveIriToEpubLocation(
ncxItem.href,
this.location
);
}
}
return;
}
/**
* Find the href of the manifest item with properties="nav" attribute
* https://www.w3.org/publishing/epub32/epub-packages.html#sec-package-nav
* TODO - handle relative and absolute urls. resolve path
*/
findNavigationFilePath() {
const spineItem = this.manifest.findNav();
if (spineItem) {
return FileManager.resolveIriToEpubLocation(
spineItem.href,
this.location
);
}
return;
}
/**
* Initialize a new empty package.
*/
create() {
const uuid = `urn:uuid:${uuidv4()}`;
this.metadata = new PackageMetadata();
this.manifest = new PackageManifest();
this.spine = new PackageSpine();
this.setUniqueIdentifier(uuid);
}
/**
* Initialize a new package object using the provided xml.
* @param {string | buffer} data - the xml data
*/
async loadXml(data) {
const result = await parseXml(data);
if (result) {
this.rawData = result;
if (this.rawData.package.attr) {
this.addAttributes(this.rawData.package.attr);
}
// construct metadata section
const rawMetadata = result.package.metadata[0];
const formatedMetadata = Object.entries(rawMetadata).flatMap(
([key, value]) => {
if (key === "attr") return [];
if (Array.isArray(value)) {
return value.flatMap((entry) => {
return {
element: key,
value: entry?.val,
attributes: entry?.attr,
};
});
}
}
);
this.metadata = new PackageMetadata(formatedMetadata, rawMetadata?.attr);
// construct the manifest section
const rawManifest = result.package.manifest[0];
const manifestItems = Object.entries(rawManifest).flatMap(
([key, value]) => {
if (key === "attr") return [];
if (Array.isArray(value)) {
return value.flatMap((entry) => {
return entry.attr;
});
}
}
);
this.manifest = new PackageManifest(
manifestItems,
rawManifest?.attr,
this._location
);
// construct the manifest section
const rawSpine = result.package.spine[0];
const spineItems = Object.entries(rawSpine).flatMap(([key, value]) => {
if (key === "attr") return [];
if (Array.isArray(value)) {
return value.flatMap((entry) => {
return entry.attr;
});
}
});
this.spine = new PackageSpine(spineItems, rawSpine?.attr);
} else {
console.error("Error parsing XML");
}
}
/**
* Get the xml string data
* @returns {string}
*/
async getXml() {
const xml = await generateXml(this.getXml2JsObject());
return xml;
}
/**
* Build the xml2Js object for conversion to raw xml
* @returns {object}
*/
getXml2JsObject() {
const filterAttributes = (attributes) => {
if (Object.keys(attributes).length) {
const attr = Object.entries(attributes)
.filter(([key, value]) => {
return value !== undefined;
})
.reduce((obj, [key, value]) => {
obj[key] = attributes[key];
return obj;
}, {});
if (Object.keys(attr).length) {
return attr;
}
}
return undefined;
};
const prepareChildrenForXml = (items) => {
const dataList = {};
items.forEach((item) => {
const data = {};
if (item.attributes) {
const attr = filterAttributes(item.attributes);
if (attr) {
data.attr = attr;
}
}
if (item.value) {
data.val = item.value;
}
if (Array.isArray(dataList[item.element])) {
dataList[item.element].push(data);
} else {
dataList[item.element] = [data];
}
});
return dataList;
};
/* Metadata */
let xmlJsMetadata = prepareChildrenForXml(this.metadata.items);
const metadataAttr = filterAttributes(this.metadata.attributes);
if (metadataAttr) {
xmlJsMetadata.attr = metadataAttr;
}
/* Manifest */
let xmlJsManifest = prepareChildrenForXml(this.manifest.items);
const manifestAttr = filterAttributes(this.manifest.attributes);
if (manifestAttr) {
xmlJsManifest.attr = manifestAttr;
}
/* Spine */
let xmlJsSpine = prepareChildrenForXml(this.spine.items);
const spineAttr = filterAttributes(this.manifest.attributes);
if (spineAttr) {
xmlJsSpine.attr = spineAttr;
}
return {
package: {
attr: filterAttributes(this.attributes),
metadata: [xmlJsMetadata],
manifest: [xmlJsManifest],
spine: [xmlJsSpine],
},
};
}
} |
JavaScript | class Options {
constructor(id, pos, description, urlLink, img) {
this.id = id;
this.position = pos;
this.urlLink = urlLink;
this.description = description;
this.img = img;
}
setListeners() {
var option = this;
$("#" + this.id).click(function () {
if (option.position === 0) {
rotateScreen("up");
return;
} else if (option.position === 2) {
rotateScreen("down");
return;
}
if (!option.urlLink) {
$(this).addClass('shake').on("animationend", function () {
$(this).removeClass('shake');
});
} else {
sessionStorage.setItem("activeOptions", JSON.stringify(options));
window.open(option.urlLink, "_self")
}
});
}
rotate(dir) {
var pos = this.position;
var next_pos = 0;
if (dir == "up")
next_pos = (pos + 1) % 4;
else if (dir == "down")
next_pos = pos != 0 ? pos - 1 : 3;
$("#" + this.id).removeClass(Positions[pos]);
$("#" + this.id).addClass(Positions[next_pos]);
this.position = next_pos;
var desc = this.description;
if (this.position == 1) {
$('#description-content').fadeOut(100, function () {
$('#description-content').html(desc);
$('#description-content').fadeIn("fast");
});
}
}
} |
JavaScript | class BufferStream extends Transform {
constructor() {
super({transform: (chunk, encoding, callback) => { callback(null, chunk) }, highWaterMark: 16384 * 100000})
}
} |
JavaScript | class JRPCEngine extends _safeEventEmitter__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"] {
constructor() {
super();
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(this, "_middleware", void 0);
this._middleware = [];
}
/**
* Serially executes the given stack of middleware.
*
* @returns An array of any error encountered during middleware execution,
* a boolean indicating whether the request was completed, and an array of
* middleware-defined return handlers.
*/
static async _runAllMiddleware(req, res, middlewareStack) {
const returnHandlers = [];
let error = null;
let isComplete = false; // Go down stack of middleware, call and collect optional returnHandlers
for (const middleware of middlewareStack) {
[error, isComplete] = await JRPCEngine._runMiddleware(req, res, middleware, returnHandlers);
if (isComplete) {
break;
}
}
return [error, isComplete, returnHandlers.reverse()];
}
/**
* Runs an individual middleware.
*
* @returns An array of any error encountered during middleware exection,
* and a boolean indicating whether the request should end.
*/
static _runMiddleware(req, res, middleware, returnHandlers) {
return new Promise(resolve => {
const end = err => {
const error = err || res.error;
if (error) {
res.error = Object(_jrpc__WEBPACK_IMPORTED_MODULE_2__[/* serializeError */ "h"])(error);
} // True indicates that the request should end
resolve([error, true]);
};
const next = returnHandler => {
if (res.error) {
end(res.error);
} else {
if (returnHandler) {
if (typeof returnHandler !== "function") {
end(new _serializableError__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"]({
code: -32603,
message: "JRPCEngine: 'next' return handlers must be functions"
}));
}
returnHandlers.push(returnHandler);
} // False indicates that the request should not end
resolve([null, false]);
}
};
try {
middleware(req, res, next, end);
} catch (error) {
end(error);
}
});
}
/**
* Serially executes array of return handlers. The request and response are
* assumed to be in their scope.
*/
static async _runReturnHandlers(handlers) {
for (const handler of handlers) {
await new Promise((resolve, reject) => {
handler(err => err ? reject(err) : resolve());
});
}
}
/**
* Throws an error if the response has neither a result nor an error, or if
* the "isComplete" flag is falsy.
*/
static _checkForCompletion(req, res, isComplete) {
if (!("result" in res) && !("error" in res)) {
throw new _serializableError__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"]({
code: -32603,
message: "Response has no error or result for request"
});
}
if (!isComplete) {
throw new _serializableError__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"]({
code: -32603,
message: "Nothing ended request"
});
}
}
/**
* Add a middleware function to the engine's middleware stack.
*
* @param middleware - The middleware function to add.
*/
push(middleware) {
this._middleware.push(middleware);
}
/**
* Handle a JSON-RPC request, and return a response.
*
* @param request - The request to handle.
* @param callback - An error-first callback that will receive the response.
*/
handle(req, cb) {
if (cb && typeof cb !== "function") {
throw new Error('"callback" must be a function if provided.');
}
if (Array.isArray(req)) {
if (cb) {
return this._handleBatch(req, cb);
}
return this._handleBatch(req);
}
if (cb) {
return this._handle(req, cb);
}
return this._promiseHandle(req);
}
/**
* Returns this engine as a middleware function that can be pushed to other
* engines.
*
* @returns This engine as a middleware function.
*/
asMiddleware() {
return async (req, res, next, end) => {
try {
const [middlewareError, isComplete, returnHandlers] = await JRPCEngine._runAllMiddleware(req, res, this._middleware);
if (isComplete) {
await JRPCEngine._runReturnHandlers(returnHandlers);
return end(middlewareError);
}
return next(async handlerCallback => {
try {
await JRPCEngine._runReturnHandlers(returnHandlers);
} catch (error) {
return handlerCallback(error);
}
return handlerCallback();
});
} catch (error) {
return end(error);
}
};
}
/**
* Like _handle, but for batch requests.
*/
async _handleBatch(reqs, cb) {
// The order here is important
try {
// 2. Wait for all requests to finish, or throw on some kind of fatal
// error
const responses = await Promise.all( // 1. Begin executing each request in the order received
reqs.map(this._promiseHandle.bind(this))); // 3. Return batch response
if (cb) {
return cb(null, responses);
}
return responses;
} catch (error) {
if (cb) {
return cb(error);
}
throw error;
}
}
/**
* A promise-wrapped _handle.
*/
_promiseHandle(req) {
return new Promise(resolve => {
this._handle(req, (_err, res) => {
// There will always be a response, and it will always have any error
// that is caught and propagated.
resolve(res);
});
});
}
/**
* Ensures that the request object is valid, processes it, and passes any
* error and the response object to the given callback.
*
* Does not reject.
*/
async _handle(callerReq, cb) {
if (!callerReq || Array.isArray(callerReq) || typeof callerReq !== "object") {
const error = new _serializableError__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"]({
code: -32603,
message: "request must be plain object"
});
return cb(error, {
id: undefined,
jsonrpc: "2.0",
error
});
}
if (typeof callerReq.method !== "string") {
const error = new _serializableError__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"]({
code: -32603,
message: "method must be string"
});
return cb(error, {
id: callerReq.id,
jsonrpc: "2.0",
error
});
}
const req = _objectSpread({}, callerReq);
const res = {
id: req.id,
jsonrpc: req.jsonrpc
};
let error = null;
try {
await this._processRequest(req, res);
} catch (_error) {
// A request handler error, a re-thrown middleware error, or something
// unexpected.
error = _error;
}
if (error) {
// Ensure no result is present on an errored response
delete res.result;
if (!res.error) {
res.error = Object(_jrpc__WEBPACK_IMPORTED_MODULE_2__[/* serializeError */ "h"])(error);
}
}
return cb(error, res);
}
/**
* For the given request and response, runs all middleware and their return
* handlers, if any, and ensures that internal request processing semantics
* are satisfied.
*/
async _processRequest(req, res) {
const [error, isComplete, returnHandlers] = await JRPCEngine._runAllMiddleware(req, res, this._middleware); // Throw if "end" was not called, or if the response has neither a result
// nor an error.
JRPCEngine._checkForCompletion(req, res, isComplete); // The return handlers should run even if an error was encountered during
// middleware processing.
await JRPCEngine._runReturnHandlers(returnHandlers); // Now we re-throw the middleware processing error, if any, to catch it
// further up the call chain.
if (error) {
throw error;
}
}
} |
JavaScript | class YamlDB {
constructor(gitConfig, tableConfig) {
this.tableConfig = tableConfig || DEFAULT_TABLE_CONFIG
this.gitClient = new GitAPI(gitConfig)
}
newKey() {
return uuid()
}
tableIndex(tableName) {
const t = this.tableConfig
return [t.prefix, tableName, t.version].join(SPLIT_CHAR)
}
path(tableName, key) {
const tableIndex = this.tableIndex(tableName)
key = key || this.newKey()
return `${DB_FOLDER}/${tableIndex}/${key}${DB_FILE_EXTENSION}`
}
fullPath(tableName, key) {
this.gitClient.getFileGitUrl(this.path(tableName, key))
}
yamlData(data) {
return yaml.safeDump(data)
}
async create(tableName, data) {
return this.upsert(tableName, data)
}
async update(tableName, data) {
if (!data || !data.key) return
return this.upsert(tableName, data)
}
async upsert(tableName, data) {
if (!tableName || !data) return
data.key = data.key || this.newKey()
await this.gitClient.upsertFile(this.path(tableName, data.key), {
content: this.yamlData(data)
})
return data
}
async delete(tableName, key) {
if (!tableName || !key) return
return this.gitClient.deleteFile(this.path(tableName, key))
}
async find(tableName, key) {
if (!tableName || !key) return
const content = await this.gitClient.getContent(this.path(tableName, key))
return yaml.safeLoad(content)
}
async query(tableName, esQueryBody) {
const result = await es.search({
index: this.tableIndex(tableName),
type: tableName,
body: esQueryBody || ''
})
if (result && result.hits) {
return {
total: result.hits.total,
list: result.hits.hits.map(val => ({ ...val._source, id: val._id }))
}
}
return { total: 0, list: [] }
}
} |
JavaScript | class ByGeneric {
/**
* @param {!BaseOperationBuilder} parent - this is a operationBaseBuilder.
* @param {!Date} date - Date when operation will be executed
* @param {string} periodicityName - Name associated to periodicity
* @param {!number or Date} end - When periodicity ends. By repetitions or by date
*/
constructor(parent, date, periodicityName, end, description) {
this._parent = parent;
this._skeleton = {
start: date,
stop: end,
name: periodicityName,
description: description,
repeating: {
pattern: {
time: moment(date).format(TIME_FORMAT)
}
}
};
if (typeof end !== "undefined") {
let stop;
if (typeof end === "number") {
stop = {
"executions": end
};
} else if (end.constructor === Date) {
let startDate = moment(date);
let stopDate = moment(end);
if (moment.max(startDate, stopDate) == startDate) {
throw new Error("Invalid stop date on executeEvery method. Start date must be earlier than stop date.");
}
stop = {
"date": end
};
}
this._skeleton.stop = stop;
}
}
_create() {
return merge(true, this._skeleton);
}
_build() {
this._parent._build.task = this._create();
return this._parent;
}
} |
Subsets and Splits