language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | _toCursor(cursor) {
if (cursor) {
const values = cursor.values.map(val => this._serializer.encodeValue(val));
return { before: cursor.before, values };
}
return undefined;
} | _toCursor(cursor) {
if (cursor) {
const values = cursor.values.map(val => this._serializer.encodeValue(val));
return { before: cursor.before, values };
}
return undefined;
} |
JavaScript | toProto(transactionId) {
const projectId = this.firestore.projectId;
const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(projectId);
const reqOpts = {
parent: parentPath.formattedName,
structuredQuery: {
from: [
{
collectionId: this._queryOptions.collectionId,
},
],
},
};
if (this._queryOptions.allDescendants) {
reqOpts.structuredQuery.from[0].allDescendants = true;
}
const structuredQuery = reqOpts.structuredQuery;
if (this._queryOptions.fieldFilters.length === 1) {
structuredQuery.where = this._queryOptions.fieldFilters[0].toProto();
}
else if (this._queryOptions.fieldFilters.length > 1) {
const filters = [];
for (const fieldFilter of this._queryOptions.fieldFilters) {
filters.push(fieldFilter.toProto());
}
structuredQuery.where = {
compositeFilter: {
op: 'AND',
filters,
},
};
}
if (this._queryOptions.fieldOrders.length) {
const orderBy = [];
for (const fieldOrder of this._queryOptions.fieldOrders) {
orderBy.push(fieldOrder.toProto());
}
structuredQuery.orderBy = orderBy;
}
if (this._queryOptions.limit) {
structuredQuery.limit = { value: this._queryOptions.limit };
}
structuredQuery.offset = this._queryOptions.offset;
structuredQuery.startAt = this._toCursor(this._queryOptions.startAt);
structuredQuery.endAt = this._toCursor(this._queryOptions.endAt);
structuredQuery.select = this._queryOptions.projection;
reqOpts.transaction = transactionId;
return reqOpts;
} | toProto(transactionId) {
const projectId = this.firestore.projectId;
const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(projectId);
const reqOpts = {
parent: parentPath.formattedName,
structuredQuery: {
from: [
{
collectionId: this._queryOptions.collectionId,
},
],
},
};
if (this._queryOptions.allDescendants) {
reqOpts.structuredQuery.from[0].allDescendants = true;
}
const structuredQuery = reqOpts.structuredQuery;
if (this._queryOptions.fieldFilters.length === 1) {
structuredQuery.where = this._queryOptions.fieldFilters[0].toProto();
}
else if (this._queryOptions.fieldFilters.length > 1) {
const filters = [];
for (const fieldFilter of this._queryOptions.fieldFilters) {
filters.push(fieldFilter.toProto());
}
structuredQuery.where = {
compositeFilter: {
op: 'AND',
filters,
},
};
}
if (this._queryOptions.fieldOrders.length) {
const orderBy = [];
for (const fieldOrder of this._queryOptions.fieldOrders) {
orderBy.push(fieldOrder.toProto());
}
structuredQuery.orderBy = orderBy;
}
if (this._queryOptions.limit) {
structuredQuery.limit = { value: this._queryOptions.limit };
}
structuredQuery.offset = this._queryOptions.offset;
structuredQuery.startAt = this._toCursor(this._queryOptions.startAt);
structuredQuery.endAt = this._toCursor(this._queryOptions.endAt);
structuredQuery.select = this._queryOptions.projection;
reqOpts.transaction = transactionId;
return reqOpts;
} |
JavaScript | _stream(transactionId) {
const tag = util_1.requestTag();
const self = this;
const stream = through2.obj(function (proto, enc, callback) {
const readTime = timestamp_1.Timestamp.fromProto(proto.readTime);
if (proto.document) {
const document = self.firestore.snapshot_(proto.document, proto.readTime);
this.push({ document, readTime });
}
else {
this.push({ readTime });
}
callback();
});
this.firestore.initializeIfNeeded(tag).then(() => {
const request = this.toProto(transactionId);
this._firestore
.readStream('runQuery', request, tag, true)
.then(backendStream => {
backendStream.on('error', err => {
logger_1.logger('Query._stream', tag, 'Query failed with stream error:', err);
stream.destroy(err);
});
backendStream.resume();
backendStream.pipe(stream);
})
.catch(err => {
stream.destroy(err);
});
});
return stream;
} | _stream(transactionId) {
const tag = util_1.requestTag();
const self = this;
const stream = through2.obj(function (proto, enc, callback) {
const readTime = timestamp_1.Timestamp.fromProto(proto.readTime);
if (proto.document) {
const document = self.firestore.snapshot_(proto.document, proto.readTime);
this.push({ document, readTime });
}
else {
this.push({ readTime });
}
callback();
});
this.firestore.initializeIfNeeded(tag).then(() => {
const request = this.toProto(transactionId);
this._firestore
.readStream('runQuery', request, tag, true)
.then(backendStream => {
backendStream.on('error', err => {
logger_1.logger('Query._stream', tag, 'Query failed with stream error:', err);
stream.destroy(err);
});
backendStream.resume();
backendStream.pipe(stream);
})
.catch(err => {
stream.destroy(err);
});
});
return stream;
} |
JavaScript | comparator() {
return (doc1, doc2) => {
// Add implicit sorting by name, using the last specified direction.
const lastDirection = this._queryOptions.fieldOrders.length === 0
? 'ASCENDING'
: this._queryOptions.fieldOrders[this._queryOptions.fieldOrders.length - 1].direction;
const orderBys = this._queryOptions.fieldOrders.concat(new FieldOrder(path_1.FieldPath.documentId(), lastDirection));
for (const orderBy of orderBys) {
let comp;
if (path_1.FieldPath.documentId().isEqual(orderBy.field)) {
comp = doc1.ref._path.compareTo(doc2.ref._path);
}
else {
const v1 = doc1.protoField(orderBy.field);
const v2 = doc2.protoField(orderBy.field);
if (v1 === undefined || v2 === undefined) {
throw new Error('Trying to compare documents on fields that ' +
"don't exist. Please include the fields you are ordering on " +
'in your select() call.');
}
comp = order_1.compare(v1, v2);
}
if (comp !== 0) {
const direction = orderBy.direction === 'ASCENDING' ? 1 : -1;
return direction * comp;
}
}
return 0;
};
} | comparator() {
return (doc1, doc2) => {
// Add implicit sorting by name, using the last specified direction.
const lastDirection = this._queryOptions.fieldOrders.length === 0
? 'ASCENDING'
: this._queryOptions.fieldOrders[this._queryOptions.fieldOrders.length - 1].direction;
const orderBys = this._queryOptions.fieldOrders.concat(new FieldOrder(path_1.FieldPath.documentId(), lastDirection));
for (const orderBy of orderBys) {
let comp;
if (path_1.FieldPath.documentId().isEqual(orderBy.field)) {
comp = doc1.ref._path.compareTo(doc2.ref._path);
}
else {
const v1 = doc1.protoField(orderBy.field);
const v2 = doc2.protoField(orderBy.field);
if (v1 === undefined || v2 === undefined) {
throw new Error('Trying to compare documents on fields that ' +
"don't exist. Please include the fields you are ordering on " +
'in your select() call.');
}
comp = order_1.compare(v1, v2);
}
if (comp !== 0) {
const direction = orderBy.direction === 'ASCENDING' ? 1 : -1;
return direction * comp;
}
}
return 0;
};
} |
JavaScript | listDocuments() {
const tag = util_1.requestTag();
return this.firestore.initializeIfNeeded(tag).then(() => {
const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(this.firestore.projectId);
const request = {
parent: parentPath.formattedName,
collectionId: this.id,
showMissing: true,
mask: { fieldPaths: [] },
};
return this.firestore
.request('listDocuments', request, tag,
/*allowRetries=*/ true)
.then(documents => {
// Note that the backend already orders these documents by name,
// so we do not need to manually sort them.
return documents.map(doc => {
const path = path_1.QualifiedResourcePath.fromSlashSeparatedString(doc.name);
return this.doc(path.id);
});
});
});
} | listDocuments() {
const tag = util_1.requestTag();
return this.firestore.initializeIfNeeded(tag).then(() => {
const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(this.firestore.projectId);
const request = {
parent: parentPath.formattedName,
collectionId: this.id,
showMissing: true,
mask: { fieldPaths: [] },
};
return this.firestore
.request('listDocuments', request, tag,
/*allowRetries=*/ true)
.then(documents => {
// Note that the backend already orders these documents by name,
// so we do not need to manually sort them.
return documents.map(doc => {
const path = path_1.QualifiedResourcePath.fromSlashSeparatedString(doc.name);
return this.doc(path.id);
});
});
});
} |
JavaScript | doc(documentPath) {
if (arguments.length === 0) {
documentPath = util_1.autoId();
}
else {
path_1.validateResourcePath('documentPath', documentPath);
}
const path = this.resourcePath.append(documentPath);
if (!path.isDocument) {
throw new Error(`Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`);
}
return new DocumentReference(this.firestore, path);
} | doc(documentPath) {
if (arguments.length === 0) {
documentPath = util_1.autoId();
}
else {
path_1.validateResourcePath('documentPath', documentPath);
}
const path = this.resourcePath.append(documentPath);
if (!path.isDocument) {
throw new Error(`Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`);
}
return new DocumentReference(this.firestore, path);
} |
JavaScript | add(data) {
write_batch_1.validateDocumentData('data', data, /*allowDeletes=*/ false);
const documentRef = this.doc();
return documentRef.create(data).then(() => documentRef);
} | add(data) {
write_batch_1.validateDocumentData('data', data, /*allowDeletes=*/ false);
const documentRef = this.doc();
return documentRef.create(data).then(() => documentRef);
} |
JavaScript | function validateQueryOrder(arg, op) {
// For backwards compatibility, we support both lower and uppercase values.
op = typeof op === 'string' ? op.toLowerCase() : op;
validate_1.validateEnumValue(arg, op, Object.keys(directionOperators), { optional: true });
return op;
} | function validateQueryOrder(arg, op) {
// For backwards compatibility, we support both lower and uppercase values.
op = typeof op === 'string' ? op.toLowerCase() : op;
validate_1.validateEnumValue(arg, op, Object.keys(directionOperators), { optional: true });
return op;
} |
JavaScript | function validateQueryOperator(arg, op, fieldValue) {
// For backwards compatibility, we support both `=` and `==` for "equals".
op = op === '=' ? '==' : op;
validate_1.validateEnumValue(arg, op, Object.keys(comparisonOperators));
if (typeof fieldValue === 'number' && isNaN(fieldValue) && op !== '==') {
throw new Error('Invalid query. You can only perform equals comparisons on NaN.');
}
if (fieldValue === null && op !== '==') {
throw new Error('Invalid query. You can only perform equals comparisons on Null.');
}
return op;
} | function validateQueryOperator(arg, op, fieldValue) {
// For backwards compatibility, we support both `=` and `==` for "equals".
op = op === '=' ? '==' : op;
validate_1.validateEnumValue(arg, op, Object.keys(comparisonOperators));
if (typeof fieldValue === 'number' && isNaN(fieldValue) && op !== '==') {
throw new Error('Invalid query. You can only perform equals comparisons on NaN.');
}
if (fieldValue === null && op !== '==') {
throw new Error('Invalid query. You can only perform equals comparisons on Null.');
}
return op;
} |
JavaScript | function validateDocumentReference(arg, value) {
if (!(value instanceof DocumentReference)) {
throw new Error(validate_1.invalidArgumentMessage(arg, 'DocumentReference'));
}
} | function validateDocumentReference(arg, value) {
if (!(value instanceof DocumentReference)) {
throw new Error(validate_1.invalidArgumentMessage(arg, 'DocumentReference'));
}
} |
JavaScript | function validateQueryValue(arg, value) {
serializer_1.validateUserInput(arg, value, 'query constraint', {
allowDeletes: 'none',
allowTransforms: false,
});
} | function validateQueryValue(arg, value) {
serializer_1.validateUserInput(arg, value, 'query constraint', {
allowDeletes: 'none',
allowTransforms: false,
});
} |
JavaScript | function isArrayEqual(left, right) {
if (left.length !== right.length) {
return false;
}
for (let i = 0; i < left.length; ++i) {
if (!left[i].isEqual(right[i])) {
return false;
}
}
return true;
} | function isArrayEqual(left, right) {
if (left.length !== right.length) {
return false;
}
for (let i = 0; i < left.length; ++i) {
if (!left[i].isEqual(right[i])) {
return false;
}
}
return true;
} |
JavaScript | _listenForEvents() {
this.on('newListener', event => {
if (event === 'complete') {
this.completeListeners++;
if (!this.hasActiveListeners) {
this.hasActiveListeners = true;
this.startPolling_();
}
}
});
this.on('removeListener', event => {
if (event === 'complete' && --this.completeListeners === 0) {
this.hasActiveListeners = false;
}
});
} | _listenForEvents() {
this.on('newListener', event => {
if (event === 'complete') {
this.completeListeners++;
if (!this.hasActiveListeners) {
this.hasActiveListeners = true;
this.startPolling_();
}
}
});
this.on('removeListener', event => {
if (event === 'complete' && --this.completeListeners === 0) {
this.hasActiveListeners = false;
}
});
} |
JavaScript | cancel() {
if (this.currentCallPromise_) {
this.currentCallPromise_.cancel();
}
const operationsClient = this.longrunningDescriptor.operationsClient;
return operationsClient.cancelOperation({
name: this.latestResponse.name,
});
} | cancel() {
if (this.currentCallPromise_) {
this.currentCallPromise_.cancel();
}
const operationsClient = this.longrunningDescriptor.operationsClient;
return operationsClient.cancelOperation({
name: this.latestResponse.name,
});
} |
JavaScript | startPolling_() {
const self = this;
let now = new Date();
const delayMult = this.backoffSettings.retryDelayMultiplier;
const maxDelay = this.backoffSettings.maxRetryDelayMillis;
let delay = this.backoffSettings.initialRetryDelayMillis;
let deadline = Infinity;
if (this.backoffSettings.totalTimeoutMillis) {
deadline = now.getTime() + this.backoffSettings.totalTimeoutMillis;
}
let previousMetadataBytes;
if (this.latestResponse.metadata) {
previousMetadataBytes = this.latestResponse.metadata.value;
}
// tslint:disable-next-line no-any
function emit(event, ...args) {
self.emit(event, ...args);
}
// Helper function to replace nodejs buffer's equals()
function arrayEquals(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; ++i) {
if (a[i] !== b[i])
return false;
}
return true;
}
function retry() {
if (!self.hasActiveListeners) {
return;
}
if (now.getTime() >= deadline) {
const error = new googleError_1.GoogleError('Total timeout exceeded before any response was received');
error.code = status_1.Status.DEADLINE_EXCEEDED;
setImmediate(emit, 'error', error);
return;
}
self.getOperation((err, result, metadata, rawResponse) => {
if (err) {
setImmediate(emit, 'error', err);
return;
}
if (!result) {
if (rawResponse.metadata &&
(!previousMetadataBytes ||
(rawResponse &&
!arrayEquals(rawResponse.metadata.value, previousMetadataBytes)))) {
setImmediate(emit, 'progress', metadata, rawResponse);
previousMetadataBytes = rawResponse.metadata.value;
}
// special case: some APIs fail to set either result or error
// but set done = true (e.g. speech with silent file).
// Don't hang forever in this case.
if (rawResponse.done) {
const error = new googleError_1.GoogleError('Long running operation has finished but there was no result');
error.code = status_1.Status.UNKNOWN;
setImmediate(emit, 'error', error);
return;
}
setTimeout(() => {
now = new Date();
delay = Math.min(delay * delayMult, maxDelay);
retry();
}, delay);
return;
}
setImmediate(emit, 'complete', result, metadata, rawResponse);
});
}
retry();
} | startPolling_() {
const self = this;
let now = new Date();
const delayMult = this.backoffSettings.retryDelayMultiplier;
const maxDelay = this.backoffSettings.maxRetryDelayMillis;
let delay = this.backoffSettings.initialRetryDelayMillis;
let deadline = Infinity;
if (this.backoffSettings.totalTimeoutMillis) {
deadline = now.getTime() + this.backoffSettings.totalTimeoutMillis;
}
let previousMetadataBytes;
if (this.latestResponse.metadata) {
previousMetadataBytes = this.latestResponse.metadata.value;
}
// tslint:disable-next-line no-any
function emit(event, ...args) {
self.emit(event, ...args);
}
// Helper function to replace nodejs buffer's equals()
function arrayEquals(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; ++i) {
if (a[i] !== b[i])
return false;
}
return true;
}
function retry() {
if (!self.hasActiveListeners) {
return;
}
if (now.getTime() >= deadline) {
const error = new googleError_1.GoogleError('Total timeout exceeded before any response was received');
error.code = status_1.Status.DEADLINE_EXCEEDED;
setImmediate(emit, 'error', error);
return;
}
self.getOperation((err, result, metadata, rawResponse) => {
if (err) {
setImmediate(emit, 'error', err);
return;
}
if (!result) {
if (rawResponse.metadata &&
(!previousMetadataBytes ||
(rawResponse &&
!arrayEquals(rawResponse.metadata.value, previousMetadataBytes)))) {
setImmediate(emit, 'progress', metadata, rawResponse);
previousMetadataBytes = rawResponse.metadata.value;
}
// special case: some APIs fail to set either result or error
// but set done = true (e.g. speech with silent file).
// Don't hang forever in this case.
if (rawResponse.done) {
const error = new googleError_1.GoogleError('Long running operation has finished but there was no result');
error.code = status_1.Status.UNKNOWN;
setImmediate(emit, 'error', error);
return;
}
setTimeout(() => {
now = new Date();
delay = Math.min(delay * delayMult, maxDelay);
retry();
}, delay);
return;
}
setImmediate(emit, 'complete', result, metadata, rawResponse);
});
}
retry();
} |
JavaScript | function arrayEquals(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; ++i) {
if (a[i] !== b[i])
return false;
}
return true;
} | function arrayEquals(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; ++i) {
if (a[i] !== b[i])
return false;
}
return true;
} |
JavaScript | promise() {
// tslint:disable-next-line variable-name
const PromiseCtor = this._callOptions.promise;
return new PromiseCtor((resolve, reject) => {
this.on('error', reject).on('complete', (result, metadata, rawResponse) => {
resolve([result, metadata, rawResponse]);
});
});
} | promise() {
// tslint:disable-next-line variable-name
const PromiseCtor = this._callOptions.promise;
return new PromiseCtor((resolve, reject) => {
this.on('error', reject).on('complete', (result, metadata, rawResponse) => {
resolve([result, metadata, rawResponse]);
});
});
} |
JavaScript | createScopedRequired() {
// On compute engine, scopes are specified at the compute instance's
// creation time, and cannot be changed. For this reason, always return
// false.
messages.warn(messages.COMPUTE_CREATE_SCOPED_DEPRECATED);
return false;
} | createScopedRequired() {
// On compute engine, scopes are specified at the compute instance's
// creation time, and cannot be changed. For this reason, always return
// false.
messages.warn(messages.COMPUTE_CREATE_SCOPED_DEPRECATED);
return false;
} |
JavaScript | async refreshTokenNoCache(refreshToken) {
const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
let data;
try {
const instanceOptions = {
property: tokenPath,
};
if (this.scopes.length > 0) {
instanceOptions.params = {
scopes: this.scopes.join(','),
};
}
data = await gcpMetadata.instance(instanceOptions);
}
catch (e) {
e.message = `Could not refresh access token: ${e.message}`;
this.wrapError(e);
throw e;
}
const tokens = data;
if (data && data.expires_in) {
tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;
delete tokens.expires_in;
}
this.emit('tokens', tokens);
return { tokens, res: null };
} | async refreshTokenNoCache(refreshToken) {
const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
let data;
try {
const instanceOptions = {
property: tokenPath,
};
if (this.scopes.length > 0) {
instanceOptions.params = {
scopes: this.scopes.join(','),
};
}
data = await gcpMetadata.instance(instanceOptions);
}
catch (e) {
e.message = `Could not refresh access token: ${e.message}`;
this.wrapError(e);
throw e;
}
const tokens = data;
if (data && data.expires_in) {
tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;
delete tokens.expires_in;
}
this.emit('tokens', tokens);
return { tokens, res: null };
} |
JavaScript | function tickFormat(scale, count, specifier, formatType, noSkip) {
var type = scale.type,
format = (type === vegaScale.Time || formatType === vegaScale.Time) ? vegaTime.timeFormat(specifier)
: (type === vegaScale.UTC || formatType === vegaScale.UTC) ? vegaTime.utcFormat(specifier)
: scale.tickFormat ? scale.tickFormat(count, specifier)
: specifier ? d3Format.format(specifier)
: String;
if (vegaScale.isLogarithmic(type)) {
var logfmt = variablePrecision(specifier);
format = noSkip || scale.bins ? logfmt : filter(format, logfmt);
}
return format;
} | function tickFormat(scale, count, specifier, formatType, noSkip) {
var type = scale.type,
format = (type === vegaScale.Time || formatType === vegaScale.Time) ? vegaTime.timeFormat(specifier)
: (type === vegaScale.UTC || formatType === vegaScale.UTC) ? vegaTime.utcFormat(specifier)
: scale.tickFormat ? scale.tickFormat(count, specifier)
: specifier ? d3Format.format(specifier)
: String;
if (vegaScale.isLogarithmic(type)) {
var logfmt = variablePrecision(specifier);
format = noSkip || scale.bins ? logfmt : filter(format, logfmt);
}
return format;
} |
JavaScript | createDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.createDocument(request, options, callback);
} | createDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.createDocument(request, options, callback);
} |
JavaScript | updateDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
document_name: request.document.name || '',
});
return this._innerApiCalls.updateDocument(request, options, callback);
} | updateDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
document_name: request.document.name || '',
});
return this._innerApiCalls.updateDocument(request, options, callback);
} |
JavaScript | deleteDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.deleteDocument(request, options, callback);
} | deleteDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.deleteDocument(request, options, callback);
} |
JavaScript | beginTransaction(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.beginTransaction(request, options, callback);
} | beginTransaction(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.beginTransaction(request, options, callback);
} |
JavaScript | rollback(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.rollback(request, options, callback);
} | rollback(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
database: request.database || '',
});
return this._innerApiCalls.rollback(request, options, callback);
} |
JavaScript | batchGetDocuments(request, options) {
request = request || {};
options = options || {};
return this._innerApiCalls.batchGetDocuments(request, options);
} | batchGetDocuments(request, options) {
request = request || {};
options = options || {};
return this._innerApiCalls.batchGetDocuments(request, options);
} |
JavaScript | listDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listDocuments(request, options, callback);
} | listDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listDocuments(request, options, callback);
} |
JavaScript | listDocumentsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listDocuments.createStream(this._innerApiCalls.listDocuments, request, callSettings);
} | listDocumentsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listDocuments.createStream(this._innerApiCalls.listDocuments, request, callSettings);
} |
JavaScript | listCollectionIds(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listCollectionIds(request, options, callback);
} | listCollectionIds(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listCollectionIds(request, options, callback);
} |
JavaScript | listCollectionIdsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listCollectionIds.createStream(this._innerApiCalls.listCollectionIds, request, callSettings);
} | listCollectionIdsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listCollectionIds.createStream(this._innerApiCalls.listCollectionIds, request, callSettings);
} |
JavaScript | close() {
if (!this._terminated) {
return this.firestoreStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
} | close() {
if (!this._terminated) {
return this.firestoreStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
} |
JavaScript | fromJSON(json) {
if (!json) {
throw new Error('Must pass in a JSON object containing the user refresh token');
}
if (json.type !== 'authorized_user') {
throw new Error('The incoming JSON object does not have the "authorized_user" type');
}
if (!json.client_id) {
throw new Error('The incoming JSON object does not contain a client_id field');
}
if (!json.client_secret) {
throw new Error('The incoming JSON object does not contain a client_secret field');
}
if (!json.refresh_token) {
throw new Error('The incoming JSON object does not contain a refresh_token field');
}
this._clientId = json.client_id;
this._clientSecret = json.client_secret;
this._refreshToken = json.refresh_token;
this.credentials.refresh_token = json.refresh_token;
this.quotaProjectId = json.quota_project_id;
} | fromJSON(json) {
if (!json) {
throw new Error('Must pass in a JSON object containing the user refresh token');
}
if (json.type !== 'authorized_user') {
throw new Error('The incoming JSON object does not have the "authorized_user" type');
}
if (!json.client_id) {
throw new Error('The incoming JSON object does not contain a client_id field');
}
if (!json.client_secret) {
throw new Error('The incoming JSON object does not contain a client_secret field');
}
if (!json.refresh_token) {
throw new Error('The incoming JSON object does not contain a refresh_token field');
}
this._clientId = json.client_id;
this._clientSecret = json.client_secret;
this._refreshToken = json.refresh_token;
this.credentials.refresh_token = json.refresh_token;
this.quotaProjectId = json.quota_project_id;
} |
JavaScript | function lookup(tree, key, filter) {
var map = {};
tree.each(function(node) {
var t = node.data;
if (filter(t)) map[key(t)] = node;
});
tree.lookup = map;
return tree;
} | function lookup(tree, key, filter) {
var map = {};
tree.each(function(node) {
var t = node.data;
if (filter(t)) map[key(t)] = node;
});
tree.lookup = map;
return tree;
} |
JavaScript | cancelOperation(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.cancelOperation(request, options, callback);
} | cancelOperation(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.cancelOperation(request, options, callback);
} |
JavaScript | acquire(requestTag) {
let selectedClient = null;
let selectedRequestCount = 0;
this.activeClients.forEach((requestCount, client) => {
if (!selectedClient && requestCount < this.concurrentOperationLimit) {
logger_1.logger('ClientPool.acquire', requestTag, 'Re-using existing client with %s remaining operations', this.concurrentOperationLimit - requestCount);
selectedClient = client;
selectedRequestCount = requestCount;
}
});
if (!selectedClient) {
logger_1.logger('ClientPool.acquire', requestTag, 'Creating a new client');
selectedClient = this.clientFactory();
assert(!this.activeClients.has(selectedClient), 'The provided client factory returned an existing instance');
}
this.activeClients.set(selectedClient, selectedRequestCount + 1);
return selectedClient;
} | acquire(requestTag) {
let selectedClient = null;
let selectedRequestCount = 0;
this.activeClients.forEach((requestCount, client) => {
if (!selectedClient && requestCount < this.concurrentOperationLimit) {
logger_1.logger('ClientPool.acquire', requestTag, 'Re-using existing client with %s remaining operations', this.concurrentOperationLimit - requestCount);
selectedClient = client;
selectedRequestCount = requestCount;
}
});
if (!selectedClient) {
logger_1.logger('ClientPool.acquire', requestTag, 'Creating a new client');
selectedClient = this.clientFactory();
assert(!this.activeClients.has(selectedClient), 'The provided client factory returned an existing instance');
}
this.activeClients.set(selectedClient, selectedRequestCount + 1);
return selectedClient;
} |
JavaScript | async release(requestTag, client) {
let requestCount = this.activeClients.get(client) || 0;
assert(requestCount > 0, 'No active request');
requestCount = requestCount - 1;
this.activeClients.set(client, requestCount);
if (requestCount === 0) {
const deletedCount = await this.garbageCollect();
if (deletedCount) {
logger_1.logger('ClientPool.release', requestTag, 'Garbage collected %s clients', deletedCount);
}
}
} | async release(requestTag, client) {
let requestCount = this.activeClients.get(client) || 0;
assert(requestCount > 0, 'No active request');
requestCount = requestCount - 1;
this.activeClients.set(client, requestCount);
if (requestCount === 0) {
const deletedCount = await this.garbageCollect();
if (deletedCount) {
logger_1.logger('ClientPool.release', requestTag, 'Garbage collected %s clients', deletedCount);
}
}
} |
JavaScript | run(requestTag, op) {
if (this.terminated) {
throw new Error('The client has already been terminated');
}
const client = this.acquire(requestTag);
return op(client)
.catch(async (err) => {
await this.release(requestTag, client);
return Promise.reject(err);
})
.then(async (res) => {
await this.release(requestTag, client);
return res;
});
} | run(requestTag, op) {
if (this.terminated) {
throw new Error('The client has already been terminated');
}
const client = this.acquire(requestTag);
return op(client)
.catch(async (err) => {
await this.release(requestTag, client);
return Promise.reject(err);
})
.then(async (res) => {
await this.release(requestTag, client);
return res;
});
} |
JavaScript | async garbageCollect() {
let idleClients = 0;
const cleanUpTasks = [];
for (const [client, requestCount] of this.activeClients) {
if (requestCount === 0) {
++idleClients;
if (idleClients > 1) {
this.activeClients.delete(client);
cleanUpTasks.push(this.clientDestructor(client));
}
}
}
await Promise.all(cleanUpTasks);
return idleClients - 1;
} | async garbageCollect() {
let idleClients = 0;
const cleanUpTasks = [];
for (const [client, requestCount] of this.activeClients) {
if (requestCount === 0) {
++idleClients;
if (idleClients > 1) {
this.activeClients.delete(client);
cleanUpTasks.push(this.clientDestructor(client));
}
}
}
await Promise.all(cleanUpTasks);
return idleClients - 1;
} |
JavaScript | function eventExtend(view, event, item) {
var r = view._renderer,
el = r && r.canvas(),
p, e, translate;
if (el) {
translate = offset(view);
e = event.changedTouches ? event.changedTouches[0] : event;
p = vegaScenegraph.point(e, el);
p[0] -= translate[0];
p[1] -= translate[1];
}
event.dataflow = view;
event.item = item;
event.vega = extension(view, item, p);
return event;
} | function eventExtend(view, event, item) {
var r = view._renderer,
el = r && r.canvas(),
p, e, translate;
if (el) {
translate = offset(view);
e = event.changedTouches ? event.changedTouches[0] : event;
p = vegaScenegraph.point(e, el);
p[0] -= translate[0];
p[1] -= translate[1];
}
event.dataflow = view;
event.item = item;
event.vega = extension(view, item, p);
return event;
} |
JavaScript | function bind(view, el, binding) {
if (!el) return;
var param = binding.param,
bind = binding.state;
if (!bind) {
bind = binding.state = {
elements: null,
active: false,
set: null,
update: function(value) {
if (value !== view.signal(param.signal)) {
view.runAsync(null, function() {
bind.source = true;
view.signal(param.signal, value);
});
}
}
};
if (param.debounce) {
bind.update = vegaUtil.debounce(param.debounce, bind.update);
}
}
generate(bind, el, param, view.signal(param.signal));
if (!bind.active) {
view.on(view._signals[param.signal], null, function() {
bind.source
? (bind.source = false)
: bind.set(view.signal(param.signal));
});
bind.active = true;
}
return bind;
} | function bind(view, el, binding) {
if (!el) return;
var param = binding.param,
bind = binding.state;
if (!bind) {
bind = binding.state = {
elements: null,
active: false,
set: null,
update: function(value) {
if (value !== view.signal(param.signal)) {
view.runAsync(null, function() {
bind.source = true;
view.signal(param.signal, value);
});
}
}
};
if (param.debounce) {
bind.update = vegaUtil.debounce(param.debounce, bind.update);
}
}
generate(bind, el, param, view.signal(param.signal));
if (!bind.active) {
view.on(view._signals[param.signal], null, function() {
bind.source
? (bind.source = false)
: bind.set(view.signal(param.signal));
});
bind.active = true;
}
return bind;
} |
JavaScript | function generate(bind, el, param, value) {
var div = element('div', {'class': BindClass});
div.appendChild(element('span',
{'class': NameClass},
(param.name || param.signal)
));
el.appendChild(div);
var input = form;
switch (param.input) {
case 'checkbox': input = checkbox; break;
case 'select': input = select; break;
case 'radio': input = radio; break;
case 'range': input = range; break;
}
input(bind, div, param, value);
} | function generate(bind, el, param, value) {
var div = element('div', {'class': BindClass});
div.appendChild(element('span',
{'class': NameClass},
(param.name || param.signal)
));
el.appendChild(div);
var input = form;
switch (param.input) {
case 'checkbox': input = checkbox; break;
case 'select': input = select; break;
case 'radio': input = radio; break;
case 'range': input = range; break;
}
input(bind, div, param, value);
} |
JavaScript | function form(bind, el, param, value) {
var node = element('input');
for (var key in param) {
if (key !== 'signal' && key !== 'element') {
node.setAttribute(key === 'input' ? 'type' : key, param[key]);
}
}
node.setAttribute('name', param.signal);
node.value = value;
el.appendChild(node);
node.addEventListener('input', function() {
bind.update(node.value);
});
bind.elements = [node];
bind.set = function(value) { node.value = value; };
} | function form(bind, el, param, value) {
var node = element('input');
for (var key in param) {
if (key !== 'signal' && key !== 'element') {
node.setAttribute(key === 'input' ? 'type' : key, param[key]);
}
}
node.setAttribute('name', param.signal);
node.value = value;
el.appendChild(node);
node.addEventListener('input', function() {
bind.update(node.value);
});
bind.elements = [node];
bind.set = function(value) { node.value = value; };
} |
JavaScript | function checkbox(bind, el, param, value) {
var attr = {type: 'checkbox', name: param.signal};
if (value) attr.checked = true;
var node = element('input', attr);
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(node.checked);
});
bind.elements = [node];
bind.set = function(value) { node.checked = !!value || null; };
} | function checkbox(bind, el, param, value) {
var attr = {type: 'checkbox', name: param.signal};
if (value) attr.checked = true;
var node = element('input', attr);
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(node.checked);
});
bind.elements = [node];
bind.set = function(value) { node.checked = !!value || null; };
} |
JavaScript | function select(bind, el, param, value) {
var node = element('select', {name: param.signal}),
label = param.labels || [];
param.options.forEach(function(option, i) {
var attr = {value: option};
if (valuesEqual(option, value)) attr.selected = true;
node.appendChild(element('option', attr, (label[i] || option)+''));
});
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(param.options[node.selectedIndex]);
});
bind.elements = [node];
bind.set = function(value) {
for (var i=0, n=param.options.length; i<n; ++i) {
if (valuesEqual(param.options[i], value)) {
node.selectedIndex = i; return;
}
}
};
} | function select(bind, el, param, value) {
var node = element('select', {name: param.signal}),
label = param.labels || [];
param.options.forEach(function(option, i) {
var attr = {value: option};
if (valuesEqual(option, value)) attr.selected = true;
node.appendChild(element('option', attr, (label[i] || option)+''));
});
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(param.options[node.selectedIndex]);
});
bind.elements = [node];
bind.set = function(value) {
for (var i=0, n=param.options.length; i<n; ++i) {
if (valuesEqual(param.options[i], value)) {
node.selectedIndex = i; return;
}
}
};
} |
JavaScript | function radio(bind, el, param, value) {
var group = element('span', {'class': RadioClass}),
label = param.labels || [];
el.appendChild(group);
bind.elements = param.options.map(function(option, i) {
var id = OptionClass + param.signal + '-' + option;
var attr = {
id: id,
type: 'radio',
name: param.signal,
value: option
};
if (valuesEqual(option, value)) attr.checked = true;
var input = element('input', attr);
input.addEventListener('change', function() {
bind.update(option);
});
group.appendChild(input);
group.appendChild(element('label', {'for': id}, (label[i] || option)+''));
return input;
});
bind.set = function(value) {
var nodes = bind.elements,
i = 0,
n = nodes.length;
for (; i<n; ++i) {
if (valuesEqual(nodes[i].value, value)) nodes[i].checked = true;
}
};
} | function radio(bind, el, param, value) {
var group = element('span', {'class': RadioClass}),
label = param.labels || [];
el.appendChild(group);
bind.elements = param.options.map(function(option, i) {
var id = OptionClass + param.signal + '-' + option;
var attr = {
id: id,
type: 'radio',
name: param.signal,
value: option
};
if (valuesEqual(option, value)) attr.checked = true;
var input = element('input', attr);
input.addEventListener('change', function() {
bind.update(option);
});
group.appendChild(input);
group.appendChild(element('label', {'for': id}, (label[i] || option)+''));
return input;
});
bind.set = function(value) {
var nodes = bind.elements,
i = 0,
n = nodes.length;
for (; i<n; ++i) {
if (valuesEqual(nodes[i].value, value)) nodes[i].checked = true;
}
};
} |
JavaScript | function range(bind, el, param, value) {
value = value !== undefined ? value : ((+param.max) + (+param.min)) / 2;
var max = param.max != null ? param.max : Math.max(100, +value) || 100,
min = param.min || Math.min(0, max, +value) || 0,
step = param.step || d3Array.tickStep(min, max, 100);
var node = element('input', {
type: 'range',
name: param.signal,
min: min,
max: max,
step: step
});
node.value = value;
var label = element('label', {}, +value);
el.appendChild(node);
el.appendChild(label);
function update() {
label.textContent = node.value;
bind.update(+node.value);
}
// subscribe to both input and change
node.addEventListener('input', update);
node.addEventListener('change', update);
bind.elements = [node];
bind.set = function(value) {
node.value = value;
label.textContent = value;
};
} | function range(bind, el, param, value) {
value = value !== undefined ? value : ((+param.max) + (+param.min)) / 2;
var max = param.max != null ? param.max : Math.max(100, +value) || 100,
min = param.min || Math.min(0, max, +value) || 0,
step = param.step || d3Array.tickStep(min, max, 100);
var node = element('input', {
type: 'range',
name: param.signal,
min: min,
max: max,
step: step
});
node.value = value;
var label = element('label', {}, +value);
el.appendChild(node);
el.appendChild(label);
function update() {
label.textContent = node.value;
bind.update(+node.value);
}
// subscribe to both input and change
node.addEventListener('input', update);
node.addEventListener('change', update);
bind.elements = [node];
bind.set = function(value) {
node.value = value;
label.textContent = value;
};
} |
JavaScript | async function renderHeadless(view, type, scaleFactor, opt) {
const module = vegaScenegraph.renderModule(type),
ctr = module && module.headless;
if (!ctr) vegaUtil.error('Unrecognized renderer type: ' + type);
await view.runAsync();
return initializeRenderer(view, null, null, ctr, scaleFactor, opt)
.renderAsync(view._scenegraph.root);
} | async function renderHeadless(view, type, scaleFactor, opt) {
const module = vegaScenegraph.renderModule(type),
ctr = module && module.headless;
if (!ctr) vegaUtil.error('Unrecognized renderer type: ' + type);
await view.runAsync();
return initializeRenderer(view, null, null, ctr, scaleFactor, opt)
.renderAsync(view._scenegraph.root);
} |
JavaScript | async function renderToImageURL(type, scaleFactor) {
if (type !== vegaScenegraph.RenderType.Canvas && type !== vegaScenegraph.RenderType.SVG && type !== vegaScenegraph.RenderType.PNG) {
vegaUtil.error('Unrecognized image type: ' + type);
}
const r = await renderHeadless(this, type, scaleFactor);
return type === vegaScenegraph.RenderType.SVG
? toBlobURL(r.svg(), 'image/svg+xml')
: r.canvas().toDataURL('image/png');
} | async function renderToImageURL(type, scaleFactor) {
if (type !== vegaScenegraph.RenderType.Canvas && type !== vegaScenegraph.RenderType.SVG && type !== vegaScenegraph.RenderType.PNG) {
vegaUtil.error('Unrecognized image type: ' + type);
}
const r = await renderHeadless(this, type, scaleFactor);
return type === vegaScenegraph.RenderType.SVG
? toBlobURL(r.svg(), 'image/svg+xml')
: r.canvas().toDataURL('image/png');
} |
JavaScript | function View(spec, options) {
var view = this;
options = options || {};
vegaDataflow.Dataflow.call(view);
if (options.loader) view.loader(options.loader);
if (options.logger) view.logger(options.logger);
if (options.logLevel != null) view.logLevel(options.logLevel);
view._el = null;
view._elBind = null;
view._renderType = options.renderer || vegaScenegraph.RenderType.Canvas;
view._scenegraph = new vegaScenegraph.Scenegraph();
var root = view._scenegraph.root;
// initialize renderer, handler and event management
view._renderer = null;
view._tooltip = options.tooltip || defaultTooltip,
view._redraw = true;
view._handler = new vegaScenegraph.CanvasHandler().scene(root);
view._preventDefault = false;
view._timers = [];
view._eventListeners = [];
view._resizeListeners = [];
// initialize event configuration
view._eventConfig = initializeEventConfig(spec.eventConfig);
// initialize dataflow graph
var ctx = runtime(view, spec, options.functions);
view._runtime = ctx;
view._signals = ctx.signals;
view._bind = (spec.bindings || []).map(function(_) {
return {
state: null,
param: vegaUtil.extend({}, _)
};
});
// initialize scenegraph
if (ctx.root) ctx.root.set(root);
root.source = ctx.data.root.input;
view.pulse(
ctx.data.root.input,
view.changeset().insert(root.items)
);
// initialize background color
view._background = options.background || ctx.background || null;
// initialize view size
view._width = view.width();
view._height = view.height();
view._viewWidth = viewWidth(view, view._width);
view._viewHeight = viewHeight(view, view._height);
view._origin = [0, 0];
view._resize = 0;
view._autosize = 1;
initializeResize(view);
// initialize cursor
cursor(view);
// initialize hover proessing, if requested
if (options.hover) view.hover();
// initialize DOM container(s) and renderer
if (options.container) view.initialize(options.container, options.bind);
} | function View(spec, options) {
var view = this;
options = options || {};
vegaDataflow.Dataflow.call(view);
if (options.loader) view.loader(options.loader);
if (options.logger) view.logger(options.logger);
if (options.logLevel != null) view.logLevel(options.logLevel);
view._el = null;
view._elBind = null;
view._renderType = options.renderer || vegaScenegraph.RenderType.Canvas;
view._scenegraph = new vegaScenegraph.Scenegraph();
var root = view._scenegraph.root;
// initialize renderer, handler and event management
view._renderer = null;
view._tooltip = options.tooltip || defaultTooltip,
view._redraw = true;
view._handler = new vegaScenegraph.CanvasHandler().scene(root);
view._preventDefault = false;
view._timers = [];
view._eventListeners = [];
view._resizeListeners = [];
// initialize event configuration
view._eventConfig = initializeEventConfig(spec.eventConfig);
// initialize dataflow graph
var ctx = runtime(view, spec, options.functions);
view._runtime = ctx;
view._signals = ctx.signals;
view._bind = (spec.bindings || []).map(function(_) {
return {
state: null,
param: vegaUtil.extend({}, _)
};
});
// initialize scenegraph
if (ctx.root) ctx.root.set(root);
root.source = ctx.data.root.input;
view.pulse(
ctx.data.root.input,
view.changeset().insert(root.items)
);
// initialize background color
view._background = options.background || ctx.background || null;
// initialize view size
view._width = view.width();
view._height = view.height();
view._viewWidth = viewWidth(view, view._width);
view._viewHeight = viewHeight(view, view._height);
view._origin = [0, 0];
view._resize = 0;
view._autosize = 1;
initializeResize(view);
// initialize cursor
cursor(view);
// initialize hover proessing, if requested
if (options.hover) view.hover();
// initialize DOM container(s) and renderer
if (options.container) view.initialize(options.container, options.bind);
} |
JavaScript | constructSettings(serviceName, clientConfig, configOverrides, headers) {
function buildMetadata(abTests, moreHeaders) {
const metadata = {};
if (!headers) {
headers = {};
}
// Since gRPC expects each header to be an array,
// we are doing the same for fallback here.
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
metadata[key] = Array.isArray(headers[key])
? headers[key]
: [headers[key]];
}
}
// gRPC-fallback request must have 'grpc-web/' in 'x-goog-api-client'
const clientVersions = [];
if (metadata[CLIENT_VERSION_HEADER] &&
metadata[CLIENT_VERSION_HEADER][0]) {
clientVersions.push(...metadata[CLIENT_VERSION_HEADER][0].split(' '));
}
clientVersions.push(`grpc-web/${exports.version}`);
metadata[CLIENT_VERSION_HEADER] = [clientVersions.join(' ')];
if (!moreHeaders) {
return metadata;
}
for (const key in moreHeaders) {
if (key.toLowerCase() !== CLIENT_VERSION_HEADER &&
moreHeaders.hasOwnProperty(key)) {
const value = moreHeaders[key];
if (Array.isArray(value)) {
if (metadata[key] === undefined) {
metadata[key] = value;
}
else {
metadata[key].push(...value);
}
}
else {
metadata[key] = [value];
}
}
}
return metadata;
}
return gax.constructSettings(serviceName, clientConfig, configOverrides, status_1.Status, { metadataBuilder: buildMetadata }, this.promise);
} | constructSettings(serviceName, clientConfig, configOverrides, headers) {
function buildMetadata(abTests, moreHeaders) {
const metadata = {};
if (!headers) {
headers = {};
}
// Since gRPC expects each header to be an array,
// we are doing the same for fallback here.
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
metadata[key] = Array.isArray(headers[key])
? headers[key]
: [headers[key]];
}
}
// gRPC-fallback request must have 'grpc-web/' in 'x-goog-api-client'
const clientVersions = [];
if (metadata[CLIENT_VERSION_HEADER] &&
metadata[CLIENT_VERSION_HEADER][0]) {
clientVersions.push(...metadata[CLIENT_VERSION_HEADER][0].split(' '));
}
clientVersions.push(`grpc-web/${exports.version}`);
metadata[CLIENT_VERSION_HEADER] = [clientVersions.join(' ')];
if (!moreHeaders) {
return metadata;
}
for (const key in moreHeaders) {
if (key.toLowerCase() !== CLIENT_VERSION_HEADER &&
moreHeaders.hasOwnProperty(key)) {
const value = moreHeaders[key];
if (Array.isArray(value)) {
if (metadata[key] === undefined) {
metadata[key] = value;
}
else {
metadata[key].push(...value);
}
}
else {
metadata[key] = [value];
}
}
}
return metadata;
}
return gax.constructSettings(serviceName, clientConfig, configOverrides, status_1.Status, { metadataBuilder: buildMetadata }, this.promise);
} |
JavaScript | async createStub(service, opts) {
// an RPC function to be passed to protobufjs RPC API
function serviceClientImpl(method, requestData, callback) {
return [method, requestData, callback];
}
// decoder for google.rpc.Status messages
const statusDecoder = new fallbackError_1.FallbackErrorDecoder();
if (!this.authClient) {
if (this.auth && 'getClient' in this.auth) {
this.authClient = await this.auth.getClient();
}
else if (this.auth && 'getRequestHeaders' in this.auth) {
this.authClient = this.auth;
}
}
if (!this.authClient) {
throw new Error('No authentication was provided');
}
const authHeader = await this.authClient.getRequestHeaders();
const serviceStub = service.create(serviceClientImpl, false, false);
const methods = this.getServiceMethods(service);
const newServiceStub = service.create(serviceClientImpl, false, false);
for (const methodName of methods) {
newServiceStub[methodName] = (req, options, metadata, callback) => {
const [method, requestData, serviceCallback] = serviceStub[methodName].apply(serviceStub, [req, callback]);
let cancelController, cancelSignal;
if (isbrowser_1.isBrowser && typeof AbortController !== 'undefined') {
cancelController = new AbortController();
}
else {
cancelController = new abort_controller_1.AbortController();
}
if (cancelController) {
cancelSignal = cancelController.signal;
}
let cancelRequested = false;
const headers = Object.assign({}, authHeader);
headers['Content-Type'] = 'application/x-protobuf';
for (const key of Object.keys(options)) {
headers[key] = options[key][0];
}
const grpcFallbackProtocol = opts.protocol || 'https';
let servicePath = opts.servicePath;
if (!servicePath &&
service.options &&
service.options['(google.api.default_host)']) {
servicePath = service.options['(google.api.default_host)'];
}
if (!servicePath) {
serviceCallback(new Error('Service path is undefined'));
return;
}
let servicePort;
const match = servicePath.match(/^(.*):(\d+)$/);
if (match) {
servicePath = match[1];
servicePort = match[2];
}
if (opts.port) {
servicePort = opts.port;
}
else if (!servicePort) {
servicePort = 443;
}
const protoNamespaces = [];
let currNamespace = method.parent;
while (currNamespace.name !== '') {
protoNamespaces.unshift(currNamespace.name);
currNamespace = currNamespace.parent;
}
const protoServiceName = protoNamespaces.join('.');
const rpcName = method.name;
const url = `${grpcFallbackProtocol}://${servicePath}:${servicePort}/$rpc/${protoServiceName}/${rpcName}`;
const fetch = isbrowser_1.isBrowser() ? window.fetch : nodeFetch;
fetch(url, {
headers,
method: 'post',
body: requestData,
signal: cancelSignal,
})
.then(response => {
return Promise.all([
Promise.resolve(response.ok),
response.arrayBuffer(),
]);
})
.then(([ok, buffer]) => {
if (!ok) {
const status = statusDecoder.decodeRpcStatus(buffer);
throw new Error(JSON.stringify(status));
}
serviceCallback(null, new Uint8Array(buffer));
})
.catch(err => {
if (!cancelRequested || err.name !== 'AbortError') {
serviceCallback(err);
}
});
return {
cancel: () => {
if (!cancelController) {
console.warn('AbortController not found: Cancellation is not supported in this environment');
return;
}
cancelRequested = true;
cancelController.abort();
},
};
};
}
return newServiceStub;
} | async createStub(service, opts) {
// an RPC function to be passed to protobufjs RPC API
function serviceClientImpl(method, requestData, callback) {
return [method, requestData, callback];
}
// decoder for google.rpc.Status messages
const statusDecoder = new fallbackError_1.FallbackErrorDecoder();
if (!this.authClient) {
if (this.auth && 'getClient' in this.auth) {
this.authClient = await this.auth.getClient();
}
else if (this.auth && 'getRequestHeaders' in this.auth) {
this.authClient = this.auth;
}
}
if (!this.authClient) {
throw new Error('No authentication was provided');
}
const authHeader = await this.authClient.getRequestHeaders();
const serviceStub = service.create(serviceClientImpl, false, false);
const methods = this.getServiceMethods(service);
const newServiceStub = service.create(serviceClientImpl, false, false);
for (const methodName of methods) {
newServiceStub[methodName] = (req, options, metadata, callback) => {
const [method, requestData, serviceCallback] = serviceStub[methodName].apply(serviceStub, [req, callback]);
let cancelController, cancelSignal;
if (isbrowser_1.isBrowser && typeof AbortController !== 'undefined') {
cancelController = new AbortController();
}
else {
cancelController = new abort_controller_1.AbortController();
}
if (cancelController) {
cancelSignal = cancelController.signal;
}
let cancelRequested = false;
const headers = Object.assign({}, authHeader);
headers['Content-Type'] = 'application/x-protobuf';
for (const key of Object.keys(options)) {
headers[key] = options[key][0];
}
const grpcFallbackProtocol = opts.protocol || 'https';
let servicePath = opts.servicePath;
if (!servicePath &&
service.options &&
service.options['(google.api.default_host)']) {
servicePath = service.options['(google.api.default_host)'];
}
if (!servicePath) {
serviceCallback(new Error('Service path is undefined'));
return;
}
let servicePort;
const match = servicePath.match(/^(.*):(\d+)$/);
if (match) {
servicePath = match[1];
servicePort = match[2];
}
if (opts.port) {
servicePort = opts.port;
}
else if (!servicePort) {
servicePort = 443;
}
const protoNamespaces = [];
let currNamespace = method.parent;
while (currNamespace.name !== '') {
protoNamespaces.unshift(currNamespace.name);
currNamespace = currNamespace.parent;
}
const protoServiceName = protoNamespaces.join('.');
const rpcName = method.name;
const url = `${grpcFallbackProtocol}://${servicePath}:${servicePort}/$rpc/${protoServiceName}/${rpcName}`;
const fetch = isbrowser_1.isBrowser() ? window.fetch : nodeFetch;
fetch(url, {
headers,
method: 'post',
body: requestData,
signal: cancelSignal,
})
.then(response => {
return Promise.all([
Promise.resolve(response.ok),
response.arrayBuffer(),
]);
})
.then(([ok, buffer]) => {
if (!ok) {
const status = statusDecoder.decodeRpcStatus(buffer);
throw new Error(JSON.stringify(status));
}
serviceCallback(null, new Uint8Array(buffer));
})
.catch(err => {
if (!cancelRequested || err.name !== 'AbortError') {
serviceCallback(err);
}
});
return {
cancel: () => {
if (!cancelController) {
console.warn('AbortController not found: Cancellation is not supported in this environment');
return;
}
cancelRequested = true;
cancelController.abort();
},
};
};
}
return newServiceStub;
} |
JavaScript | function add(init, update, params, react) {
var shift = 1,
op;
if (init instanceof Operator) {
op = init;
} else if (init && init.prototype instanceof Operator) {
op = new init();
} else if (vegaUtil.isFunction(init)) {
op = new Operator(null, init);
} else {
shift = 0;
op = new Operator(init, update);
}
this.rank(op);
if (shift) {
react = params;
params = update;
}
if (params) this.connect(op, op.parameters(params, react));
this.touch(op);
return op;
} | function add(init, update, params, react) {
var shift = 1,
op;
if (init instanceof Operator) {
op = init;
} else if (init && init.prototype instanceof Operator) {
op = new init();
} else if (vegaUtil.isFunction(init)) {
op = new Operator(null, init);
} else {
shift = 0;
op = new Operator(init, update);
}
this.rank(op);
if (shift) {
react = params;
params = update;
}
if (params) this.connect(op, op.parameters(params, react));
this.touch(op);
return op;
} |
JavaScript | async function request(url, format) {
const df = this;
let status = 0, data;
try {
data = await df.loader().load(url, {
context: 'dataflow',
response: vegaLoader.responseType(format && format.type)
});
try {
data = parse(data, format);
} catch (err) {
status = -2;
df.warn('Data ingestion failed', url, err);
}
} catch (err) {
status = -1;
df.warn('Loading failed', url, err);
}
return {data, status};
} | async function request(url, format) {
const df = this;
let status = 0, data;
try {
data = await df.loader().load(url, {
context: 'dataflow',
response: vegaLoader.responseType(format && format.type)
});
try {
data = parse(data, format);
} catch (err) {
status = -2;
df.warn('Data ingestion failed', url, err);
}
} catch (err) {
status = -1;
df.warn('Loading failed', url, err);
}
return {data, status};
} |
JavaScript | function rerank(op) {
var queue = [op],
cur, list, i;
while (queue.length) {
this.rank(cur = queue.pop());
if (list = cur._targets) {
for (i=list.length; --i >= 0;) {
queue.push(cur = list[i]);
if (cur === op) vegaUtil.error('Cycle detected in dataflow graph.');
}
}
}
} | function rerank(op) {
var queue = [op],
cur, list, i;
while (queue.length) {
this.rank(cur = queue.pop());
if (list = cur._targets) {
for (i=list.length; --i >= 0;) {
queue.push(cur = list[i]);
if (cur === op) vegaUtil.error('Cycle detected in dataflow graph.');
}
}
}
} |
JavaScript | async function evaluate(encode, prerun, postrun) {
const df = this,
level = df.logLevel(),
async = [];
// if the pulse value is set, this is a re-entrant call
if (df._pulse) return reentrant(df);
// wait for pending datasets to load
if (df._pending) {
await df._pending;
}
// invoke prerun function, if provided
if (prerun) await asyncCallback(df, prerun);
// exit early if there are no updates
if (!df._touched.length) {
df.info('Dataflow invoked, but nothing to do.');
return df;
}
// increment timestamp clock
let stamp = ++df._clock,
count = 0, op, next, dt, error;
// set the current pulse
df._pulse = new Pulse(df, stamp, encode);
if (level >= vegaUtil.Info) {
dt = Date.now();
df.debug('-- START PROPAGATION (' + stamp + ') -----');
}
// initialize priority queue, reset touched operators
df._touched.forEach(op => df._enqueue(op, true));
df._touched = UniqueList(vegaUtil.id);
try {
while (df._heap.size() > 0) {
// dequeue operator with highest priority
op = df._heap.pop();
// re-queue if rank changed
if (op.rank !== op.qrank) { df._enqueue(op, true); continue; }
// otherwise, evaluate the operator
next = op.run(df._getPulse(op, encode));
if (next.then) {
// await if operator returns a promise directly
next = await next;
} else if (next.async) {
// queue parallel asynchronous execution
async.push(next.async);
next = StopPropagation;
}
if (level >= vegaUtil.Debug) {
df.debug(op.id, next === StopPropagation ? 'STOP' : next, op);
}
// propagate evaluation, enqueue dependent operators
if (next !== StopPropagation) {
if (op._targets) op._targets.forEach(op => df._enqueue(op));
}
// increment visit counter
++count;
}
} catch (err) {
df._heap.clear();
error = err;
}
// reset pulse map
df._input = {};
df._pulse = null;
if (level >= vegaUtil.Info) {
dt = Date.now() - dt;
df.info('> Pulse ' + stamp + ': ' + count + ' operators; ' + dt + 'ms');
}
if (error) {
df._postrun = [];
df.error(error);
}
// invoke callbacks queued via runAfter
if (df._postrun.length) {
const pr = df._postrun.sort((a, b) => b.priority - a.priority);
df._postrun = [];
for (let i=0; i<pr.length; ++i) {
await asyncCallback(df, pr[i].callback);
}
}
// invoke postrun function, if provided
if (postrun) await asyncCallback(df, postrun);
// handle non-blocking asynchronous callbacks
if (async.length) {
Promise.all(async).then(cb => df.runAsync(null, () => {
cb.forEach(f => { try { f(df); } catch (err) { df.error(err); } });
}));
}
return df;
} | async function evaluate(encode, prerun, postrun) {
const df = this,
level = df.logLevel(),
async = [];
// if the pulse value is set, this is a re-entrant call
if (df._pulse) return reentrant(df);
// wait for pending datasets to load
if (df._pending) {
await df._pending;
}
// invoke prerun function, if provided
if (prerun) await asyncCallback(df, prerun);
// exit early if there are no updates
if (!df._touched.length) {
df.info('Dataflow invoked, but nothing to do.');
return df;
}
// increment timestamp clock
let stamp = ++df._clock,
count = 0, op, next, dt, error;
// set the current pulse
df._pulse = new Pulse(df, stamp, encode);
if (level >= vegaUtil.Info) {
dt = Date.now();
df.debug('-- START PROPAGATION (' + stamp + ') -----');
}
// initialize priority queue, reset touched operators
df._touched.forEach(op => df._enqueue(op, true));
df._touched = UniqueList(vegaUtil.id);
try {
while (df._heap.size() > 0) {
// dequeue operator with highest priority
op = df._heap.pop();
// re-queue if rank changed
if (op.rank !== op.qrank) { df._enqueue(op, true); continue; }
// otherwise, evaluate the operator
next = op.run(df._getPulse(op, encode));
if (next.then) {
// await if operator returns a promise directly
next = await next;
} else if (next.async) {
// queue parallel asynchronous execution
async.push(next.async);
next = StopPropagation;
}
if (level >= vegaUtil.Debug) {
df.debug(op.id, next === StopPropagation ? 'STOP' : next, op);
}
// propagate evaluation, enqueue dependent operators
if (next !== StopPropagation) {
if (op._targets) op._targets.forEach(op => df._enqueue(op));
}
// increment visit counter
++count;
}
} catch (err) {
df._heap.clear();
error = err;
}
// reset pulse map
df._input = {};
df._pulse = null;
if (level >= vegaUtil.Info) {
dt = Date.now() - dt;
df.info('> Pulse ' + stamp + ': ' + count + ' operators; ' + dt + 'ms');
}
if (error) {
df._postrun = [];
df.error(error);
}
// invoke callbacks queued via runAfter
if (df._postrun.length) {
const pr = df._postrun.sort((a, b) => b.priority - a.priority);
df._postrun = [];
for (let i=0; i<pr.length; ++i) {
await asyncCallback(df, pr[i].callback);
}
}
// invoke postrun function, if provided
if (postrun) await asyncCallback(df, postrun);
// handle non-blocking asynchronous callbacks
if (async.length) {
Promise.all(async).then(cb => df.runAsync(null, () => {
cb.forEach(f => { try { f(df); } catch (err) { df.error(err); } });
}));
}
return df;
} |
JavaScript | function Dataflow() {
this.logger(vegaUtil.logger());
this.logLevel(vegaUtil.Error);
this._clock = 0;
this._rank = 0;
try {
this._loader = vegaLoader.loader();
} catch (e) {
// do nothing if loader module is unavailable
}
this._touched = UniqueList(vegaUtil.id);
this._input = {};
this._pulse = null;
this._heap = Heap((a, b) => a.qrank - b.qrank);
this._postrun = [];
} | function Dataflow() {
this.logger(vegaUtil.logger());
this.logLevel(vegaUtil.Error);
this._clock = 0;
this._rank = 0;
try {
this._loader = vegaLoader.loader();
} catch (e) {
// do nothing if loader module is unavailable
}
this._touched = UniqueList(vegaUtil.id);
this._input = {};
this._pulse = null;
this._heap = Heap((a, b) => a.qrank - b.qrank);
this._postrun = [];
} |
JavaScript | function loaderFactory(fetch, fs) {
return function(options) {
return {
options: options || {},
sanitize: sanitize,
load: load,
fileAccess: !!fs,
file: fileLoader(fs),
http: httpLoader(fetch)
};
};
} | function loaderFactory(fetch, fs) {
return function(options) {
return {
options: options || {},
sanitize: sanitize,
load: load,
fileAccess: !!fs,
file: fileLoader(fs),
http: httpLoader(fetch)
};
};
} |
JavaScript | async function sanitize(uri, options) {
options = vegaUtil.extend({}, this.options, options);
const fileAccess = this.fileAccess,
result = {href: null};
let isFile, loadFile, base;
const isAllowed = allowed_re.test(uri.replace(whitespace_re, ''));
if (uri == null || typeof uri !== 'string' || !isAllowed) {
vegaUtil.error('Sanitize failure, invalid URI: ' + vegaUtil.stringValue(uri));
}
const hasProtocol = protocol_re.test(uri);
// if relative url (no protocol/host), prepend baseURL
if ((base = options.baseURL) && !hasProtocol) {
// Ensure that there is a slash between the baseURL (e.g. hostname) and url
if (!uri.startsWith('/') && base[base.length-1] !== '/') {
uri = '/' + uri;
}
uri = base + uri;
}
// should we load from file system?
loadFile = (isFile = uri.startsWith(fileProtocol))
|| options.mode === 'file'
|| options.mode !== 'http' && !hasProtocol && fileAccess;
if (isFile) {
// strip file protocol
uri = uri.slice(fileProtocol.length);
} else if (uri.startsWith('//')) {
if (options.defaultProtocol === 'file') {
// if is file, strip protocol and set loadFile flag
uri = uri.slice(2);
loadFile = true;
} else {
// if relative protocol (starts with '//'), prepend default protocol
uri = (options.defaultProtocol || 'http') + ':' + uri;
}
}
// set non-enumerable mode flag to indicate local file load
Object.defineProperty(result, 'localFile', {value: !!loadFile});
// set uri
result.href = uri;
// set default result target, if specified
if (options.target) {
result.target = options.target + '';
}
// set default result rel, if specified (#1542)
if (options.rel) {
result.rel = options.rel + '';
}
// return
return result;
} | async function sanitize(uri, options) {
options = vegaUtil.extend({}, this.options, options);
const fileAccess = this.fileAccess,
result = {href: null};
let isFile, loadFile, base;
const isAllowed = allowed_re.test(uri.replace(whitespace_re, ''));
if (uri == null || typeof uri !== 'string' || !isAllowed) {
vegaUtil.error('Sanitize failure, invalid URI: ' + vegaUtil.stringValue(uri));
}
const hasProtocol = protocol_re.test(uri);
// if relative url (no protocol/host), prepend baseURL
if ((base = options.baseURL) && !hasProtocol) {
// Ensure that there is a slash between the baseURL (e.g. hostname) and url
if (!uri.startsWith('/') && base[base.length-1] !== '/') {
uri = '/' + uri;
}
uri = base + uri;
}
// should we load from file system?
loadFile = (isFile = uri.startsWith(fileProtocol))
|| options.mode === 'file'
|| options.mode !== 'http' && !hasProtocol && fileAccess;
if (isFile) {
// strip file protocol
uri = uri.slice(fileProtocol.length);
} else if (uri.startsWith('//')) {
if (options.defaultProtocol === 'file') {
// if is file, strip protocol and set loadFile flag
uri = uri.slice(2);
loadFile = true;
} else {
// if relative protocol (starts with '//'), prepend default protocol
uri = (options.defaultProtocol || 'http') + ':' + uri;
}
}
// set non-enumerable mode flag to indicate local file load
Object.defineProperty(result, 'localFile', {value: !!loadFile});
// set uri
result.href = uri;
// set default result target, if specified
if (options.target) {
result.target = options.target + '';
}
// set default result rel, if specified (#1542)
if (options.rel) {
result.rel = options.rel + '';
}
// return
return result;
} |
JavaScript | deleteIndex(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.deleteIndex(request, options, callback);
} | deleteIndex(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.deleteIndex(request, options, callback);
} |
JavaScript | createIndex(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.createIndex(request, options, callback);
} | createIndex(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.createIndex(request, options, callback);
} |
JavaScript | updateField(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
field_name: request.field.name || '',
});
return this._innerApiCalls.updateField(request, options, callback);
} | updateField(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
field_name: request.field.name || '',
});
return this._innerApiCalls.updateField(request, options, callback);
} |
JavaScript | exportDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.exportDocuments(request, options, callback);
} | exportDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.exportDocuments(request, options, callback);
} |
JavaScript | importDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.importDocuments(request, options, callback);
} | importDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
name: request.name || '',
});
return this._innerApiCalls.importDocuments(request, options, callback);
} |
JavaScript | listIndexes(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listIndexes(request, options, callback);
} | listIndexes(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listIndexes(request, options, callback);
} |
JavaScript | listIndexesStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listIndexes.createStream(this._innerApiCalls.listIndexes, request, callSettings);
} | listIndexesStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listIndexes.createStream(this._innerApiCalls.listIndexes, request, callSettings);
} |
JavaScript | listFields(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listFields(request, options, callback);
} | listFields(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({
parent: request.parent || '',
});
return this._innerApiCalls.listFields(request, options, callback);
} |
JavaScript | listFieldsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listFields.createStream(this._innerApiCalls.listFields, request, callSettings);
} | listFieldsStream(request, options) {
request = request || {};
const callSettings = new gax.CallSettings(options);
return this._descriptors.page.listFields.createStream(this._innerApiCalls.listFields, request, callSettings);
} |
JavaScript | collectiongroupPath(project, database, collection) {
return this._pathTemplates.collectiongroupPathTemplate.render({
project,
database,
collection,
});
} | collectiongroupPath(project, database, collection) {
return this._pathTemplates.collectiongroupPathTemplate.render({
project,
database,
collection,
});
} |
JavaScript | indexPath(project, database, collection, index) {
return this._pathTemplates.indexPathTemplate.render({
project,
database,
collection,
index,
});
} | indexPath(project, database, collection, index) {
return this._pathTemplates.indexPathTemplate.render({
project,
database,
collection,
index,
});
} |
JavaScript | fieldPath(project, database, collection, field) {
return this._pathTemplates.fieldPathTemplate.render({
project,
database,
collection,
field,
});
} | fieldPath(project, database, collection, field) {
return this._pathTemplates.fieldPathTemplate.render({
project,
database,
collection,
field,
});
} |
JavaScript | databasePath(project, database) {
return this._pathTemplates.databasePathTemplate.render({
project,
database,
});
} | databasePath(project, database) {
return this._pathTemplates.databasePathTemplate.render({
project,
database,
});
} |
JavaScript | close() {
if (!this._terminated) {
return this.firestoreAdminStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
} | close() {
if (!this._terminated) {
return this.firestoreAdminStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
} |
JavaScript | function density2D() {
var x = d => d[0],
y = d => d[1],
weight = vegaUtil.one,
bandwidth = [-1, -1],
dx = 960,
dy = 500,
k = 2; // log2(cellSize)
function density(data, counts) {
const rx = radius(bandwidth[0], data, x) >> k, // blur x-radius
ry = radius(bandwidth[1], data, y) >> k, // blur y-radius
ox = rx ? rx + 2 : 0, // x-offset padding for blur
oy = ry ? ry + 2 : 0, // y-offset padding for blur
n = 2 * ox + (dx >> k), // grid width
m = 2 * oy + (dy >> k), // grid height
values0 = new Float32Array(n * m),
values1 = new Float32Array(n * m);
let values = values0;
data.forEach(d => {
const xi = ox + (+x(d) >> k),
yi = oy + (+y(d) >> k);
if (xi >= 0 && xi < n && yi >= 0 && yi < m) {
values0[xi + yi * n] += +weight(d);
}
});
if (rx > 0 && ry > 0) {
blurX(n, m, values0, values1, rx);
blurY(n, m, values1, values0, ry);
blurX(n, m, values0, values1, rx);
blurY(n, m, values1, values0, ry);
blurX(n, m, values0, values1, rx);
blurY(n, m, values1, values0, ry);
} else if (rx > 0) {
blurX(n, m, values0, values1, rx);
blurX(n, m, values1, values0, rx);
blurX(n, m, values0, values1, rx);
values = values1;
} else if (ry > 0) {
blurY(n, m, values0, values1, ry);
blurY(n, m, values1, values0, ry);
blurY(n, m, values0, values1, ry);
values = values1;
}
// scale density estimates
// density in points per square pixel or probability density
let s = counts ? Math.pow(2, -2 * k) : 1 / d3Array.sum(values);
for (let i=0, sz=n*m; i<sz; ++i) values[i] *= s;
return {
values: values,
scale: 1 << k,
width: n,
height: m,
x1: ox,
y1: oy,
x2: ox + (dx >> k),
y2: oy + (dy >> k)
};
}
density.x = function(_) {
return arguments.length ? (x = number(_), density) : x;
};
density.y = function(_) {
return arguments.length ? (y = number(_), density) : y;
};
density.weight = function(_) {
return arguments.length ? (weight = number(_), density) : weight;
};
density.size = function(_) {
if (!arguments.length) return [dx, dy];
var _0 = Math.ceil(_[0]), _1 = Math.ceil(_[1]);
if (!(_0 >= 0) && !(_0 >= 0)) vegaUtil.error('invalid size');
return dx = _0, dy = _1, density;
};
density.cellSize = function(_) {
if (!arguments.length) return 1 << k;
if (!((_ = +_) >= 1)) vegaUtil.error('invalid cell size');
k = Math.floor(Math.log(_) / Math.LN2);
return density;
};
density.bandwidth = function(_) {
if (!arguments.length) return bandwidth;
_ = vegaUtil.array(_);
if (_.length === 1) _ = [+_[0], +_[0]];
if (_.length !== 2) vegaUtil.error('invalid bandwidth');
return bandwidth = _, density;
};
return density;
} | function density2D() {
var x = d => d[0],
y = d => d[1],
weight = vegaUtil.one,
bandwidth = [-1, -1],
dx = 960,
dy = 500,
k = 2; // log2(cellSize)
function density(data, counts) {
const rx = radius(bandwidth[0], data, x) >> k, // blur x-radius
ry = radius(bandwidth[1], data, y) >> k, // blur y-radius
ox = rx ? rx + 2 : 0, // x-offset padding for blur
oy = ry ? ry + 2 : 0, // y-offset padding for blur
n = 2 * ox + (dx >> k), // grid width
m = 2 * oy + (dy >> k), // grid height
values0 = new Float32Array(n * m),
values1 = new Float32Array(n * m);
let values = values0;
data.forEach(d => {
const xi = ox + (+x(d) >> k),
yi = oy + (+y(d) >> k);
if (xi >= 0 && xi < n && yi >= 0 && yi < m) {
values0[xi + yi * n] += +weight(d);
}
});
if (rx > 0 && ry > 0) {
blurX(n, m, values0, values1, rx);
blurY(n, m, values1, values0, ry);
blurX(n, m, values0, values1, rx);
blurY(n, m, values1, values0, ry);
blurX(n, m, values0, values1, rx);
blurY(n, m, values1, values0, ry);
} else if (rx > 0) {
blurX(n, m, values0, values1, rx);
blurX(n, m, values1, values0, rx);
blurX(n, m, values0, values1, rx);
values = values1;
} else if (ry > 0) {
blurY(n, m, values0, values1, ry);
blurY(n, m, values1, values0, ry);
blurY(n, m, values0, values1, ry);
values = values1;
}
// scale density estimates
// density in points per square pixel or probability density
let s = counts ? Math.pow(2, -2 * k) : 1 / d3Array.sum(values);
for (let i=0, sz=n*m; i<sz; ++i) values[i] *= s;
return {
values: values,
scale: 1 << k,
width: n,
height: m,
x1: ox,
y1: oy,
x2: ox + (dx >> k),
y2: oy + (dy >> k)
};
}
density.x = function(_) {
return arguments.length ? (x = number(_), density) : x;
};
density.y = function(_) {
return arguments.length ? (y = number(_), density) : y;
};
density.weight = function(_) {
return arguments.length ? (weight = number(_), density) : weight;
};
density.size = function(_) {
if (!arguments.length) return [dx, dy];
var _0 = Math.ceil(_[0]), _1 = Math.ceil(_[1]);
if (!(_0 >= 0) && !(_0 >= 0)) vegaUtil.error('invalid size');
return dx = _0, dy = _1, density;
};
density.cellSize = function(_) {
if (!arguments.length) return 1 << k;
if (!((_ = +_) >= 1)) vegaUtil.error('invalid cell size');
k = Math.floor(Math.log(_) / Math.LN2);
return density;
};
density.bandwidth = function(_) {
if (!arguments.length) return bandwidth;
_ = vegaUtil.array(_);
if (_.length === 1) _ = [+_[0], +_[0]];
if (_.length !== 2) vegaUtil.error('invalid bandwidth');
return bandwidth = _, density;
};
return density;
} |
JavaScript | function dependency(f) {
if (!vegaUtil.isFunction(f)) return false;
const set = vegaUtil.toSet(vegaUtil.accessorFields(f));
return set.$x || set.$y || set.$value || set.$max;
} | function dependency(f) {
if (!vegaUtil.isFunction(f)) return false;
const set = vegaUtil.toSet(vegaUtil.accessorFields(f));
return set.$x || set.$y || set.$value || set.$max;
} |
JavaScript | function create(type, constructor) {
return function projection() {
var p = constructor();
p.type = type;
p.path = d3Geo.geoPath().projection(p);
p.copy = p.copy || function() {
var c = projection();
projectionProperties.forEach(function(prop) {
if (p[prop]) c[prop](p[prop]());
});
c.path.pointRadius(p.path.pointRadius());
return c;
};
return p;
};
} | function create(type, constructor) {
return function projection() {
var p = constructor();
p.type = type;
p.path = d3Geo.geoPath().projection(p);
p.copy = p.copy || function() {
var c = projection();
projectionProperties.forEach(function(prop) {
if (p[prop]) c[prop](p[prop]());
});
c.path.pointRadius(p.path.pointRadius());
return c;
};
return p;
};
} |
JavaScript | encodeFields(obj) {
const fields = {};
for (const prop of Object.keys(obj)) {
const val = this.encodeValue(obj[prop]);
if (val) {
fields[prop] = val;
}
}
return fields;
} | encodeFields(obj) {
const fields = {};
for (const prop of Object.keys(obj)) {
const val = this.encodeValue(obj[prop]);
if (val) {
fields[prop] = val;
}
}
return fields;
} |
JavaScript | encodeValue(val) {
if (val instanceof field_value_1.FieldTransform) {
return null;
}
if (typeof val === 'string') {
return {
stringValue: val,
};
}
if (typeof val === 'boolean') {
return {
booleanValue: val,
};
}
if (typeof val === 'number') {
if (Number.isSafeInteger(val)) {
return {
integerValue: val,
};
}
else {
return {
doubleValue: val,
};
}
}
if (val instanceof Date) {
const timestamp = timestamp_1.Timestamp.fromDate(val);
return {
timestampValue: {
seconds: timestamp.seconds,
nanos: timestamp.nanoseconds,
},
};
}
if (val === null) {
return {
nullValue: 'NULL_VALUE',
};
}
if (val instanceof Buffer || val instanceof Uint8Array) {
return {
bytesValue: val,
};
}
if (util_1.isObject(val)) {
const toProto = val['toProto'];
if (typeof toProto === 'function') {
return toProto.bind(val)();
}
}
if (val instanceof Array) {
const array = {
arrayValue: {},
};
if (val.length > 0) {
array.arrayValue.values = [];
for (let i = 0; i < val.length; ++i) {
const enc = this.encodeValue(val[i]);
if (enc) {
array.arrayValue.values.push(enc);
}
}
}
return array;
}
if (typeof val === 'object' && isPlainObject(val)) {
const map = {
mapValue: {},
};
// If we encounter an empty object, we always need to send it to make sure
// the server creates a map entry.
if (!util_1.isEmpty(val)) {
map.mapValue.fields = this.encodeFields(val);
if (util_1.isEmpty(map.mapValue.fields)) {
return null;
}
}
return map;
}
throw new Error(`Cannot encode value: ${val}`);
} | encodeValue(val) {
if (val instanceof field_value_1.FieldTransform) {
return null;
}
if (typeof val === 'string') {
return {
stringValue: val,
};
}
if (typeof val === 'boolean') {
return {
booleanValue: val,
};
}
if (typeof val === 'number') {
if (Number.isSafeInteger(val)) {
return {
integerValue: val,
};
}
else {
return {
doubleValue: val,
};
}
}
if (val instanceof Date) {
const timestamp = timestamp_1.Timestamp.fromDate(val);
return {
timestampValue: {
seconds: timestamp.seconds,
nanos: timestamp.nanoseconds,
},
};
}
if (val === null) {
return {
nullValue: 'NULL_VALUE',
};
}
if (val instanceof Buffer || val instanceof Uint8Array) {
return {
bytesValue: val,
};
}
if (util_1.isObject(val)) {
const toProto = val['toProto'];
if (typeof toProto === 'function') {
return toProto.bind(val)();
}
}
if (val instanceof Array) {
const array = {
arrayValue: {},
};
if (val.length > 0) {
array.arrayValue.values = [];
for (let i = 0; i < val.length; ++i) {
const enc = this.encodeValue(val[i]);
if (enc) {
array.arrayValue.values.push(enc);
}
}
}
return array;
}
if (typeof val === 'object' && isPlainObject(val)) {
const map = {
mapValue: {},
};
// If we encounter an empty object, we always need to send it to make sure
// the server creates a map entry.
if (!util_1.isEmpty(val)) {
map.mapValue.fields = this.encodeFields(val);
if (util_1.isEmpty(map.mapValue.fields)) {
return null;
}
}
return map;
}
throw new Error(`Cannot encode value: ${val}`);
} |
JavaScript | function isPlainObject(input) {
return (util_1.isObject(input) &&
(Object.getPrototypeOf(input) === Object.prototype ||
Object.getPrototypeOf(input) === null));
} | function isPlainObject(input) {
return (util_1.isObject(input) &&
(Object.getPrototypeOf(input) === Object.prototype ||
Object.getPrototypeOf(input) === null));
} |
JavaScript | function validateUserInput(arg, value, desc, options, path, level, inArray) {
if (path && path.size > MAX_DEPTH) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Input object is deeper than ${MAX_DEPTH} levels or contains a cycle.`);
}
options = options || {};
level = level || 0;
inArray = inArray || false;
const fieldPathMessage = path ? ` (found in field ${path})` : '';
if (Array.isArray(value)) {
for (let i = 0; i < value.length; ++i) {
validateUserInput(arg, value[i], desc, options, path ? path.append(String(i)) : new path_1.FieldPath(String(i)), level + 1,
/* inArray= */ true);
}
}
else if (isPlainObject(value)) {
for (const prop of Object.keys(value)) {
validateUserInput(arg, value[prop], desc, options, path ? path.append(new path_1.FieldPath(prop)) : new path_1.FieldPath(prop), level + 1, inArray);
}
}
else if (value === undefined) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}.`);
}
else if (value instanceof field_value_2.DeleteTransform) {
if (inArray) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`);
}
else if ((options.allowDeletes === 'root' && level !== 0) ||
options.allowDeletes === 'none') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() must appear at the top-level and can only be used in update() or set() with {merge:true}${fieldPathMessage}.`);
}
}
else if (value instanceof field_value_1.FieldTransform) {
if (inArray) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`);
}
else if (!options.allowTransforms) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() can only be used in set(), create() or update()${fieldPathMessage}.`);
}
}
else if (value instanceof path_1.FieldPath) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Cannot use object of type "FieldPath" as a Firestore value${fieldPathMessage}.`);
}
else if (value instanceof index_1.DocumentReference) {
// Ok.
}
else if (value instanceof geo_point_1.GeoPoint) {
// Ok.
}
else if (value instanceof timestamp_1.Timestamp || value instanceof Date) {
// Ok.
}
else if (value instanceof Buffer || value instanceof Uint8Array) {
// Ok.
}
else if (value === null) {
// Ok.
}
else if (typeof value === 'object') {
throw new Error(validate_1.customObjectMessage(arg, value, path));
}
} | function validateUserInput(arg, value, desc, options, path, level, inArray) {
if (path && path.size > MAX_DEPTH) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Input object is deeper than ${MAX_DEPTH} levels or contains a cycle.`);
}
options = options || {};
level = level || 0;
inArray = inArray || false;
const fieldPathMessage = path ? ` (found in field ${path})` : '';
if (Array.isArray(value)) {
for (let i = 0; i < value.length; ++i) {
validateUserInput(arg, value[i], desc, options, path ? path.append(String(i)) : new path_1.FieldPath(String(i)), level + 1,
/* inArray= */ true);
}
}
else if (isPlainObject(value)) {
for (const prop of Object.keys(value)) {
validateUserInput(arg, value[prop], desc, options, path ? path.append(new path_1.FieldPath(prop)) : new path_1.FieldPath(prop), level + 1, inArray);
}
}
else if (value === undefined) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}.`);
}
else if (value instanceof field_value_2.DeleteTransform) {
if (inArray) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`);
}
else if ((options.allowDeletes === 'root' && level !== 0) ||
options.allowDeletes === 'none') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() must appear at the top-level and can only be used in update() or set() with {merge:true}${fieldPathMessage}.`);
}
}
else if (value instanceof field_value_1.FieldTransform) {
if (inArray) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`);
}
else if (!options.allowTransforms) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() can only be used in set(), create() or update()${fieldPathMessage}.`);
}
}
else if (value instanceof path_1.FieldPath) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Cannot use object of type "FieldPath" as a Firestore value${fieldPathMessage}.`);
}
else if (value instanceof index_1.DocumentReference) {
// Ok.
}
else if (value instanceof geo_point_1.GeoPoint) {
// Ok.
}
else if (value instanceof timestamp_1.Timestamp || value instanceof Date) {
// Ok.
}
else if (value instanceof Buffer || value instanceof Uint8Array) {
// Ok.
}
else if (value === null) {
// Ok.
}
else if (typeof value === 'object') {
throw new Error(validate_1.customObjectMessage(arg, value, path));
}
} |
JavaScript | function lookup$1(config, orient) {
const opt = config[orient] || {};
return (key, d) => opt[key] != null ? opt[key]
: config[key] != null ? config[key]
: d;
} | function lookup$1(config, orient) {
const opt = config[orient] || {};
return (key, d) => opt[key] != null ? opt[key]
: config[key] != null ? config[key]
: d;
} |
JavaScript | update(documentRef, dataOrField, ...preconditionOrValues) {
validate_1.validateMinNumberOfArguments('Transaction.update', arguments, 2);
this._writeBatch.update.apply(this._writeBatch, [
documentRef,
dataOrField,
...preconditionOrValues,
]);
return this;
} | update(documentRef, dataOrField, ...preconditionOrValues) {
validate_1.validateMinNumberOfArguments('Transaction.update', arguments, 2);
this._writeBatch.update.apply(this._writeBatch, [
documentRef,
dataOrField,
...preconditionOrValues,
]);
return this;
} |
JavaScript | begin() {
const request = {
database: this._firestore.formattedName,
};
if (this._transactionId) {
request.options = {
readWrite: {
retryTransaction: this._transactionId,
},
};
}
return this._firestore
.request('beginTransaction', request, this._requestTag, ALLOW_RETRIES)
.then(resp => {
this._transactionId = resp.transaction;
});
} | begin() {
const request = {
database: this._firestore.formattedName,
};
if (this._transactionId) {
request.options = {
readWrite: {
retryTransaction: this._transactionId,
},
};
}
return this._firestore
.request('beginTransaction', request, this._requestTag, ALLOW_RETRIES)
.then(resp => {
this._transactionId = resp.transaction;
});
} |
JavaScript | commit() {
return this._writeBatch
.commit_({
transactionId: this._transactionId,
requestTag: this._requestTag,
})
.then(() => { });
} | commit() {
return this._writeBatch
.commit_({
transactionId: this._transactionId,
requestTag: this._requestTag,
})
.then(() => { });
} |
JavaScript | rollback() {
const request = {
database: this._firestore.formattedName,
transaction: this._transactionId,
};
return this._firestore.request('rollback', request, this._requestTag,
/* allowRetries= */ false);
} | rollback() {
const request = {
database: this._firestore.formattedName,
transaction: this._transactionId,
};
return this._firestore.request('rollback', request, this._requestTag,
/* allowRetries= */ false);
} |
JavaScript | function parseGetAllArguments(documentRefsOrReadOptions) {
let documents;
let readOptions = undefined;
if (Array.isArray(documentRefsOrReadOptions[0])) {
throw new Error('getAll() no longer accepts an array as its first argument. ' +
'Please unpack your array and call getAll() with individual arguments.');
}
if (documentRefsOrReadOptions.length > 0 &&
serializer_1.isPlainObject(documentRefsOrReadOptions[documentRefsOrReadOptions.length - 1])) {
readOptions = documentRefsOrReadOptions.pop();
documents = documentRefsOrReadOptions;
}
else {
documents = documentRefsOrReadOptions;
}
for (let i = 0; i < documents.length; ++i) {
reference_1.validateDocumentReference(i, documents[i]);
}
validateReadOptions('options', readOptions, { optional: true });
const fieldMask = readOptions && readOptions.fieldMask
? readOptions.fieldMask.map(fieldPath => path_1.FieldPath.fromArgument(fieldPath))
: null;
return { fieldMask, documents };
} | function parseGetAllArguments(documentRefsOrReadOptions) {
let documents;
let readOptions = undefined;
if (Array.isArray(documentRefsOrReadOptions[0])) {
throw new Error('getAll() no longer accepts an array as its first argument. ' +
'Please unpack your array and call getAll() with individual arguments.');
}
if (documentRefsOrReadOptions.length > 0 &&
serializer_1.isPlainObject(documentRefsOrReadOptions[documentRefsOrReadOptions.length - 1])) {
readOptions = documentRefsOrReadOptions.pop();
documents = documentRefsOrReadOptions;
}
else {
documents = documentRefsOrReadOptions;
}
for (let i = 0; i < documents.length; ++i) {
reference_1.validateDocumentReference(i, documents[i]);
}
validateReadOptions('options', readOptions, { optional: true });
const fieldMask = readOptions && readOptions.fieldMask
? readOptions.fieldMask.map(fieldPath => path_1.FieldPath.fromArgument(fieldPath))
: null;
return { fieldMask, documents };
} |
JavaScript | function showConnect () {
$("#connect").show();
$("#loading").hide();
$("#toolbar").hide();
$("#nickInput").focus();
} | function showConnect () {
$("#connect").show();
$("#loading").hide();
$("#toolbar").hide();
$("#nickInput").focus();
} |
JavaScript | function showLoad () {
$("#connect").hide();
$("#loading").show();
$("#toolbar").hide();
} | function showLoad () {
$("#connect").hide();
$("#loading").show();
$("#toolbar").hide();
} |
JavaScript | function showChat (nick) {
$("#toolbar").show();
$("#entry").focus();
$("#connect").hide();
$("#loading").hide();
} | function showChat (nick) {
$("#toolbar").show();
$("#entry").focus();
$("#connect").hide();
$("#loading").hide();
} |
JavaScript | function outputUsers () {
var nick_string = nicks.length > 0 ? nicks.join(", ") : "(none)";
addMessage("users:", nick_string, new Date(), "notice");
return false;
} | function outputUsers () {
var nick_string = nicks.length > 0 ? nicks.join(", ") : "(none)";
addMessage("users:", nick_string, new Date(), "notice");
return false;
} |
JavaScript | function who () {
jQuery.get("/who", {}, function (data, status) {
if (status != "success") return;
nicks = data.nicks;
outputUsers();
}, "json");
} | function who () {
jQuery.get("/who", {}, function (data, status) {
if (status != "success") return;
nicks = data.nicks;
outputUsers();
}, "json");
} |
JavaScript | function onKeyPressed(e,callingFunction){
var eventOccured = (!e) ? window.event : e;
if(eventOccured.keyCode == 13 || eventOccured.type == "click"){ // 13 is keycode of Enter Key Pressed
eval(callingFunction); // function wants to execute..
}
} | function onKeyPressed(e,callingFunction){
var eventOccured = (!e) ? window.event : e;
if(eventOccured.keyCode == 13 || eventOccured.type == "click"){ // 13 is keycode of Enter Key Pressed
eval(callingFunction); // function wants to execute..
}
} |
JavaScript | function createDatePicker(elementId,format,gotoToday)
{
try
{
$("#"+elementId).datepicker({
dateFormat: format,
gotoCurrent: gotoToday
});
}
catch(x)
{
//alert(x);
}
} | function createDatePicker(elementId,format,gotoToday)
{
try
{
$("#"+elementId).datepicker({
dateFormat: format,
gotoCurrent: gotoToday
});
}
catch(x)
{
//alert(x);
}
} |
JavaScript | function clearCombo(obj,selectedLabel,selectedValue)
{
try
{
var width="8em";
if(width==undefined)
{
width="8em";
}
$(obj).empty();
var option=new Option(""+selectedLabel,""+selectedValue,false,true);
option.style.width=width;
$(obj).append(option);
$(obj).attr("width",width);
}
catch(x)
{
//alert("Error"+x);
}
} | function clearCombo(obj,selectedLabel,selectedValue)
{
try
{
var width="8em";
if(width==undefined)
{
width="8em";
}
$(obj).empty();
var option=new Option(""+selectedLabel,""+selectedValue,false,true);
option.style.width=width;
$(obj).append(option);
$(obj).attr("width",width);
}
catch(x)
{
//alert("Error"+x);
}
} |
JavaScript | function processNewsArticleSearch(){
$("#newsArticleDetailFrnt").hide();
$("#newsArticleDetailFrnt").html("");
$('#loadingMsg').fadeIn(1000);
var pageNoNewsArticle = $("#newsArticlePaginator #ajaxPaginationPageNo").val();
var recordLimitNewsArticle = $("#newsArticlePaginator #ajaxPaginationRecordLimit").val();
if(pageNoNewsArticle == undefined){
pageNoNewsArticle = 1;
}
if(recordLimitNewsArticle == undefined){
recordLimitNewsArticle = 10;
}
var txtsearchText=$("#divnewsArticleSearchFrnt #txtsearchText").val();
var cmbnewsArticleType=$("#divnewsArticleSearchFrnt #cmbsnewsArticleType").val();
var url="/newsandarticles";
var urlParams={'page':pageNoNewsArticle,'limit':recordLimitNewsArticle,'txtsearchText':txtsearchText,'cmbnewsArticleType':cmbnewsArticleType};
ajaxRequestAsyncrs(url,urlParams,"POST","setNewsArticleList()","N");
return false;
} | function processNewsArticleSearch(){
$("#newsArticleDetailFrnt").hide();
$("#newsArticleDetailFrnt").html("");
$('#loadingMsg').fadeIn(1000);
var pageNoNewsArticle = $("#newsArticlePaginator #ajaxPaginationPageNo").val();
var recordLimitNewsArticle = $("#newsArticlePaginator #ajaxPaginationRecordLimit").val();
if(pageNoNewsArticle == undefined){
pageNoNewsArticle = 1;
}
if(recordLimitNewsArticle == undefined){
recordLimitNewsArticle = 10;
}
var txtsearchText=$("#divnewsArticleSearchFrnt #txtsearchText").val();
var cmbnewsArticleType=$("#divnewsArticleSearchFrnt #cmbsnewsArticleType").val();
var url="/newsandarticles";
var urlParams={'page':pageNoNewsArticle,'limit':recordLimitNewsArticle,'txtsearchText':txtsearchText,'cmbnewsArticleType':cmbnewsArticleType};
ajaxRequestAsyncrs(url,urlParams,"POST","setNewsArticleList()","N");
return false;
} |
JavaScript | async function createBlogPostPages (graphql, actions, reporter) {
const { createPage } = actions
const result = await graphql(`
{
allSanityPost(filter: { slug: { current: { ne: null } } }) {
edges {
node {
id
publishedAt
slug {
current
}
}
}
}
}
`)
if (result.errors) throw result.errors
const postEdges = (result.data.allSanityPost || {}).edges || []
postEdges.forEach((edge, index) => {
const { id, slug = {}, publishedAt } = edge.node
const dateSegment = format(publishedAt, 'YYYY/MM')
const path = `/blog/${dateSegment}/${slug.current}/`
reporter.info(`Creating blog post page: ${path}`)
createPage({
path,
component: require.resolve('./src/templates/blog-post.js'),
context: { id }
})
})
} | async function createBlogPostPages (graphql, actions, reporter) {
const { createPage } = actions
const result = await graphql(`
{
allSanityPost(filter: { slug: { current: { ne: null } } }) {
edges {
node {
id
publishedAt
slug {
current
}
}
}
}
}
`)
if (result.errors) throw result.errors
const postEdges = (result.data.allSanityPost || {}).edges || []
postEdges.forEach((edge, index) => {
const { id, slug = {}, publishedAt } = edge.node
const dateSegment = format(publishedAt, 'YYYY/MM')
const path = `/blog/${dateSegment}/${slug.current}/`
reporter.info(`Creating blog post page: ${path}`)
createPage({
path,
component: require.resolve('./src/templates/blog-post.js'),
context: { id }
})
})
} |
JavaScript | function dropCursor(options) {
if ( options === void 0 ) options = {};
return new Plugin({
view: function view(editorView) { return new DropCursorView(editorView, options) }
})
} | function dropCursor(options) {
if ( options === void 0 ) options = {};
return new Plugin({
view: function view(editorView) { return new DropCursorView(editorView, options) }
})
} |
JavaScript | function useForm(_ref, watch) {
var loadInitialValues = _ref.loadInitialValues,
options = _objectWithoutPropertiesLoose(_ref, ["loadInitialValues"]);
if (watch === void 0) {
watch = {};
}
/**
* `initialValues` will be usually be undefined if `loadInitialValues` is used.
*
* If the form helper is using `watch.values`, which would contain
* the current state of the form, then we set that to the `initialValues`
* so the form is initialized with some state.
*
* This is beneficial for SSR and will hopefully not be noticeable
* when editing the site as the actual `initialValues` will be set
* behind the scenes.
*/
options.initialValues = options.initialValues || watch.values;
var _React$useState = useState(options.initialValues),
setValues = _React$useState[1];
var _React$useState2 = useState(function () {
return createForm(options, function (form) {
setValues(form.values);
});
}),
form = _React$useState2[0],
setForm = _React$useState2[1];
useEffect(function () {
if (form.id === options.id) return;
setForm(createForm(options, function (form) {
setValues(form.values);
}));
}, [options.id]);
useEffect(function () {
if (loadInitialValues) {
loadInitialValues().then(function (values) {
form.updateInitialValues(values);
});
}
}, [form]);
useUpdateFormFields(form, watch.fields);
useUpdateFormLabel(form, watch.label);
useUpdateFormValues(form, watch.values);
return [form ? form.values : options.initialValues, form];
} | function useForm(_ref, watch) {
var loadInitialValues = _ref.loadInitialValues,
options = _objectWithoutPropertiesLoose(_ref, ["loadInitialValues"]);
if (watch === void 0) {
watch = {};
}
/**
* `initialValues` will be usually be undefined if `loadInitialValues` is used.
*
* If the form helper is using `watch.values`, which would contain
* the current state of the form, then we set that to the `initialValues`
* so the form is initialized with some state.
*
* This is beneficial for SSR and will hopefully not be noticeable
* when editing the site as the actual `initialValues` will be set
* behind the scenes.
*/
options.initialValues = options.initialValues || watch.values;
var _React$useState = useState(options.initialValues),
setValues = _React$useState[1];
var _React$useState2 = useState(function () {
return createForm(options, function (form) {
setValues(form.values);
});
}),
form = _React$useState2[0],
setForm = _React$useState2[1];
useEffect(function () {
if (form.id === options.id) return;
setForm(createForm(options, function (form) {
setValues(form.values);
}));
}, [options.id]);
useEffect(function () {
if (loadInitialValues) {
loadInitialValues().then(function (values) {
form.updateInitialValues(values);
});
}
}, [form]);
useUpdateFormFields(form, watch.fields);
useUpdateFormLabel(form, watch.label);
useUpdateFormValues(form, watch.values);
return [form ? form.values : options.initialValues, form];
} |
JavaScript | function useUpdateFormFields(form, fields) {
useEffect(function () {
if (typeof fields === 'undefined') return;
form.updateFields(fields);
}, [form, fields]);
} | function useUpdateFormFields(form, fields) {
useEffect(function () {
if (typeof fields === 'undefined') return;
form.updateFields(fields);
}, [form, fields]);
} |
JavaScript | function useUpdateFormLabel(form, label) {
useEffect(function () {
if (typeof label === 'undefined') return;
form.label = label;
}, [form, label]);
} | function useUpdateFormLabel(form, label) {
useEffect(function () {
if (typeof label === 'undefined') return;
form.label = label;
}, [form, label]);
} |
JavaScript | function useUpdateFormValues(form, values) {
useEffect(function () {
if (typeof values === 'undefined') return;
form.updateValues(values);
}, [form, values]);
} | function useUpdateFormValues(form, values) {
useEffect(function () {
if (typeof values === 'undefined') return;
form.updateValues(values);
}, [form, values]);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.