language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | static sendIntegerArray(integers, callback) {
// Validating required parameters
if (integers === null || integers === undefined) {
callback({ errorMessage: 'The parameter `integers` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/{integers}'}`;
// Process template parameters
_queryBuilder = _APIHelper.appendUrlWithTemplateParameters(_queryBuilder, {
integers,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _EchoResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static sendIntegerArray(integers, callback) {
// Validating required parameters
if (integers === null || integers === undefined) {
callback({ errorMessage: 'The parameter `integers` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/{integers}'}`;
// Process template parameters
_queryBuilder = _APIHelper.appendUrlWithTemplateParameters(_queryBuilder, {
integers,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _EchoResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static sendStringArray(strings, callback) {
// Validating required parameters
if (strings === null || strings === undefined) {
callback({ errorMessage: 'The parameter `strings` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/{strings}'}`;
// Process template parameters
_queryBuilder = _APIHelper.appendUrlWithTemplateParameters(_queryBuilder, {
strings,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _EchoResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static sendStringArray(strings, callback) {
// Validating required parameters
if (strings === null || strings === undefined) {
callback({ errorMessage: 'The parameter `strings` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/{strings}'}`;
// Process template parameters
_queryBuilder = _APIHelper.appendUrlWithTemplateParameters(_queryBuilder, {
strings,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _EchoResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static sendHeaders(customHeader, value, callback) {
// Validating required parameters
if (customHeader === null || customHeader === undefined) {
callback({ errorMessage: 'The parameter `customHeader` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
} else if (value === null || value === undefined) {
callback({ errorMessage: 'The parameter `value` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
const _queryBuilder = `${_baseUri}${'/header'}`;
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'custom-header': customHeader,
'user-agent': 'Stamplay SDK',
};
// prepare form data
const _form = {
value,
};
// Remove null values
_APIHelper.cleanObject(_form);
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'POST',
headers: _headers,
form: _form,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static sendHeaders(customHeader, value, callback) {
// Validating required parameters
if (customHeader === null || customHeader === undefined) {
callback({ errorMessage: 'The parameter `customHeader` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
} else if (value === null || value === undefined) {
callback({ errorMessage: 'The parameter `value` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
const _queryBuilder = `${_baseUri}${'/header'}`;
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'custom-header': customHeader,
'user-agent': 'Stamplay SDK',
};
// prepare form data
const _form = {
value,
};
// Remove null values
_APIHelper.cleanObject(_form);
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'POST',
headers: _headers,
form: _form,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static validateResponse(_context) {
const errorObj = {
errorMessage: '',
errorCode: '',
errorResponse: _context.response.body,
};
const returnObj = {
error: errorObj,
response: null,
context: _context,
};
if (_context.response.statusCode === 400) {
returnObj.error.errorMessage = '400 Global';
returnObj.error.errorCode = 400;
} else if (_context.response.statusCode === 402) {
returnObj.error.errorMessage = '402 Global';
returnObj.error.errorCode = 402;
} else if (_context.response.statusCode === 403) {
returnObj.error.errorMessage = '403 Global';
returnObj.error.errorCode = 403;
} else if (_context.response.statusCode === 404) {
returnObj.error.errorMessage = '404 Global';
returnObj.error.errorCode = 404;
} else if (_context.response.statusCode === 500) {
returnObj.error.errorMessage = '500 Global';
returnObj.error.errorCode = 500;
returnObj.error.errorResponse = new GlobalTestException('500 Global', _context);
} else if (_context.response.statusCode === 0) {
returnObj.error.errorMessage = 'Invalid response.';
returnObj.error.errorCode = 0;
returnObj.error.errorResponse = new GlobalTestException('Invalid response.', _context);
} else {
returnObj.error.errorMessage = 'HTTP Response Not OK';
returnObj.error.errorCode = _context.response.statusCode;
}
return returnObj;
} | static validateResponse(_context) {
const errorObj = {
errorMessage: '',
errorCode: '',
errorResponse: _context.response.body,
};
const returnObj = {
error: errorObj,
response: null,
context: _context,
};
if (_context.response.statusCode === 400) {
returnObj.error.errorMessage = '400 Global';
returnObj.error.errorCode = 400;
} else if (_context.response.statusCode === 402) {
returnObj.error.errorMessage = '402 Global';
returnObj.error.errorCode = 402;
} else if (_context.response.statusCode === 403) {
returnObj.error.errorMessage = '403 Global';
returnObj.error.errorCode = 403;
} else if (_context.response.statusCode === 404) {
returnObj.error.errorMessage = '404 Global';
returnObj.error.errorCode = 404;
} else if (_context.response.statusCode === 500) {
returnObj.error.errorMessage = '500 Global';
returnObj.error.errorCode = 500;
returnObj.error.errorResponse = new GlobalTestException('500 Global', _context);
} else if (_context.response.statusCode === 0) {
returnObj.error.errorMessage = 'Invalid response.';
returnObj.error.errorCode = 0;
returnObj.error.errorResponse = new GlobalTestException('Invalid response.', _context);
} else {
returnObj.error.errorMessage = 'HTTP Response Not OK';
returnObj.error.errorCode = _context.response.statusCode;
}
return returnObj;
} |
JavaScript | static integerEnumArray(suites, callback) {
// Validating required parameters
if (suites === null || suites === undefined) {
callback({ errorMessage: 'The parameter `suites` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/integerenumarray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
suites: (suites !== null) ? suites : null,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static integerEnumArray(suites, callback) {
// Validating required parameters
if (suites === null || suites === undefined) {
callback({ errorMessage: 'The parameter `suites` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/integerenumarray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
suites: (suites !== null) ? suites : null,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static stringEnumArray(days, callback) {
// Validating required parameters
if (days === null || days === undefined) {
callback({ errorMessage: 'The parameter `days` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/stringenumarray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
days: (days !== null) ? days : null,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static stringEnumArray(days, callback) {
// Validating required parameters
if (days === null || days === undefined) {
callback({ errorMessage: 'The parameter `days` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/stringenumarray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
days: (days !== null) ? days : null,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static stringArray(strings, callback) {
// Validating required parameters
if (strings === null || strings === undefined) {
callback({ errorMessage: 'The parameter `strings` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/stringarray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
strings,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static stringArray(strings, callback) {
// Validating required parameters
if (strings === null || strings === undefined) {
callback({ errorMessage: 'The parameter `strings` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/stringarray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
strings,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static numberArray(integers, callback) {
// Validating required parameters
if (integers === null || integers === undefined) {
callback({ errorMessage: 'The parameter `integers` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/numberarray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
integers,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static numberArray(integers, callback) {
// Validating required parameters
if (integers === null || integers === undefined) {
callback({ errorMessage: 'The parameter `integers` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/numberarray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
integers,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static urlParam(url, callback) {
// Validating required parameters
if (url === null || url === undefined) {
callback({ errorMessage: 'The parameter `url` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/urlparam'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
url,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static urlParam(url, callback) {
// Validating required parameters
if (url === null || url === undefined) {
callback({ errorMessage: 'The parameter `url` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/urlparam'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
url,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static stringParam(string, callback) {
// Validating required parameters
if (string === null || string === undefined) {
callback({ errorMessage: 'The parameter `string` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/stringparam'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
string,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static stringParam(string, callback) {
// Validating required parameters
if (string === null || string === undefined) {
callback({ errorMessage: 'The parameter `string` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/stringparam'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
string,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static noParams(callback) {
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
const _queryBuilder = `${_baseUri}${'/query/noparams'}`;
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static noParams(callback) {
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
const _queryBuilder = `${_baseUri}${'/query/noparams'}`;
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static rfc3339DateTime(datetime, callback) {
// Validating required parameters
if (datetime === null || datetime === undefined) {
callback({ errorMessage: 'The parameter `datetime` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/rfc3339datetime'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetime,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static rfc3339DateTime(datetime, callback) {
// Validating required parameters
if (datetime === null || datetime === undefined) {
callback({ errorMessage: 'The parameter `datetime` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/rfc3339datetime'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetime,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static rfc3339DateTimeArray(datetimes, callback) {
// Validating required parameters
if (datetimes === null || datetimes === undefined) {
callback({ errorMessage: 'The parameter `datetimes` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/rfc3339datetimearray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetimes,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static rfc3339DateTimeArray(datetimes, callback) {
// Validating required parameters
if (datetimes === null || datetimes === undefined) {
callback({ errorMessage: 'The parameter `datetimes` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/rfc3339datetimearray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetimes,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static rfc1123DateTimeArray(datetimes, callback) {
// Validating required parameters
if (datetimes === null || datetimes === undefined) {
callback({ errorMessage: 'The parameter `datetimes` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/rfc1123datetimearray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetimes,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static rfc1123DateTimeArray(datetimes, callback) {
// Validating required parameters
if (datetimes === null || datetimes === undefined) {
callback({ errorMessage: 'The parameter `datetimes` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/rfc1123datetimearray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetimes,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static rfc1123DateTime(datetime, callback) {
// Validating required parameters
if (datetime === null || datetime === undefined) {
callback({ errorMessage: 'The parameter `datetime` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/rfc1123datetime'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetime,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static rfc1123DateTime(datetime, callback) {
// Validating required parameters
if (datetime === null || datetime === undefined) {
callback({ errorMessage: 'The parameter `datetime` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/rfc1123datetime'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetime,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static unixDateTime(datetime, callback) {
// Validating required parameters
if (datetime === null || datetime === undefined) {
callback({ errorMessage: 'The parameter `datetime` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/unixdatetime'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetime,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static unixDateTime(datetime, callback) {
// Validating required parameters
if (datetime === null || datetime === undefined) {
callback({ errorMessage: 'The parameter `datetime` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/unixdatetime'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetime,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static unixDateTimeArray(datetimes, callback) {
// Validating required parameters
if (datetimes === null || datetimes === undefined) {
callback({ errorMessage: 'The parameter `datetimes` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/unixdatetimearray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetimes,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static unixDateTimeArray(datetimes, callback) {
// Validating required parameters
if (datetimes === null || datetimes === undefined) {
callback({ errorMessage: 'The parameter `datetimes` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/unixdatetimearray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
datetimes,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static date(date, callback) {
// Validating required parameters
if (date === null || date === undefined) {
callback({ errorMessage: 'The parameter `date` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/date'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
date,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static date(date, callback) {
// Validating required parameters
if (date === null || date === undefined) {
callback({ errorMessage: 'The parameter `date` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/date'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
date,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | static dateArray(dates, callback) {
// Validating required parameters
if (dates === null || dates === undefined) {
callback({ errorMessage: 'The parameter `dates` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/datearray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
dates,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} | static dateArray(dates, callback) {
// Validating required parameters
if (dates === null || dates === undefined) {
callback({ errorMessage: 'The parameter `dates` is a required parameter and cannot be null.',
errorCode: -1 }, null, null);
return;
}
// prepare query string for API call;
const _baseUri = _configuration.getBaseUri();
let _queryBuilder = `${_baseUri}${'/query/datearray'}`;
// Process query parameters
_queryBuilder = _APIHelper.appendUrlWithQueryParameters(_queryBuilder, {
dates,
});
// validate and preprocess url
const _queryUrl = _APIHelper.cleanUrl(_queryBuilder);
// prepare headers
const _headers = {
accept: 'application/json',
'user-agent': 'Stamplay SDK',
};
// Construct the request
const _options = {
queryUrl: _queryUrl,
method: 'GET',
headers: _headers,
};
// Build the response processing.
const cb = function cb(_error, _response, _context) {
let errorResponse;
if (_error) {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
} else if (_response.statusCode >= 200 && _response.statusCode <= 206) {
let parsed = JSON.parse(_response.body);
parsed = new _ServerResponse(parsed);
callback(null, parsed, _context);
} else {
errorResponse = _BaseController.validateResponse(_context);
callback(errorResponse.error, errorResponse.response, errorResponse.context);
}
};
_request(_options, cb);
} |
JavaScript | async function syncCoin() {
const date = moment().utc().startOf('minute').toDate();
// Setup the coinmarketcap.com api url.
const url = `${ config.coinMarketCap.api }${ config.coinMarketCap.ticker }`;
const info = await rpc.call('getinfo');
const masternodes = await rpc.call('getmasternodecount');
const nethashps = await rpc.call('getnetworkhashps');
let market = await fetch(url);
if (Array.isArray(market)) {
market = market.length ? market[0] : {};
}
const coin = new Coin({
cap: market.market_cap_usd,
createdAt: date,
blocks: info.blocks,
btc: market.price_btc,
diff: info.difficulty,
mnsOff: masternodes.total - masternodes.stable,
mnsOn: masternodes.stable,
netHash: nethashps,
peers: info.connections,
status: 'Online',
supply: market.available_supply, // TODO: change to actual count from db.
usd: market.price_usd
});
await coin.save();
} | async function syncCoin() {
const date = moment().utc().startOf('minute').toDate();
// Setup the coinmarketcap.com api url.
const url = `${ config.coinMarketCap.api }${ config.coinMarketCap.ticker }`;
const info = await rpc.call('getinfo');
const masternodes = await rpc.call('getmasternodecount');
const nethashps = await rpc.call('getnetworkhashps');
let market = await fetch(url);
if (Array.isArray(market)) {
market = market.length ? market[0] : {};
}
const coin = new Coin({
cap: market.market_cap_usd,
createdAt: date,
blocks: info.blocks,
btc: market.price_btc,
diff: info.difficulty,
mnsOff: masternodes.total - masternodes.stable,
mnsOn: masternodes.stable,
netHash: nethashps,
peers: info.connections,
status: 'Online',
supply: market.available_supply, // TODO: change to actual count from db.
usd: market.price_usd
});
await coin.save();
} |
JavaScript | function handleMissingRoutine () {
if (!_.isFunction(routine)) {
throw new Exception('Cannot create an action from ' + ftn);
}
} | function handleMissingRoutine () {
if (!_.isFunction(routine)) {
throw new Exception('Cannot create an action from ' + ftn);
}
} |
JavaScript | function handleOptionalInverse () {
if (!_.isFunction(inverse)) {
inverse = function () {
this.message = 'Cannot undo previous action.';
};
}
} | function handleOptionalInverse () {
if (!_.isFunction(inverse)) {
inverse = function () {
this.message = 'Cannot undo previous action.';
};
}
} |
JavaScript | function toHaveContent($element) {
expect($element.length).to.exist;
expect($element.length).to.be.at.least(1);
expect($element.attr('content').length).to.be.at.least(1);
} | function toHaveContent($element) {
expect($element.length).to.exist;
expect($element.length).to.be.at.least(1);
expect($element.attr('content').length).to.be.at.least(1);
} |
JavaScript | function mockContext(context) {
context.callback = context.callback || Function.prototype;
return context;
} | function mockContext(context) {
context.callback = context.callback || Function.prototype;
return context;
} |
JavaScript | function validate(fhirHealthCardText) {
return __awaiter(this, void 0, void 0, function () {
var log, fhirHealthCard, param;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
log = new logger_1.default('FHIR $health-cards-issue response');
if (fhirHealthCardText.trim() !== fhirHealthCardText) {
log.warn("FHIR Health Card response has leading or trailing spaces", error_1.ErrorCode.TRAILING_CHARACTERS);
fhirHealthCardText = fhirHealthCardText.trim();
}
fhirHealthCard = utils.parseJson(fhirHealthCardText);
if (fhirHealthCard == undefined) {
return [2 /*return*/, log.fatal("Failed to parse FHIR Health Card response data as JSON.", error_1.ErrorCode.JSON_PARSE_ERROR)];
}
param = fhirHealthCard.parameter;
if (!param ||
!(param instanceof Array) ||
param.length === 0) {
return [2 /*return*/, log.fatal("fhirHealthCard.parameter array required to continue.", error_1.ErrorCode.CRITICAL_DATA_MISSING)];
}
return [4 /*yield*/, Promise.all(param.filter(function (p) { return p.name === 'verifiableCredential'; }).map(function (vc, i, VCs) { return __awaiter(_this, void 0, void 0, function () {
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!!vc.valueString) return [3 /*break*/, 1];
log.error("Missing FHIR Health Card response data verifiableCredential #" + (i + 1) + " valueString", i);
return [3 /*break*/, 3];
case 1:
_b = (_a = log.child).push;
return [4 /*yield*/, jws.validate(vc.valueString, VCs.length > 1 ? i.toString() : '')];
case 2:
_b.apply(_a, [_c.sent()]);
_c.label = 3;
case 3: return [2 /*return*/];
}
});
}); }))];
case 1:
_a.sent();
return [2 /*return*/, log];
}
});
});
} | function validate(fhirHealthCardText) {
return __awaiter(this, void 0, void 0, function () {
var log, fhirHealthCard, param;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
log = new logger_1.default('FHIR $health-cards-issue response');
if (fhirHealthCardText.trim() !== fhirHealthCardText) {
log.warn("FHIR Health Card response has leading or trailing spaces", error_1.ErrorCode.TRAILING_CHARACTERS);
fhirHealthCardText = fhirHealthCardText.trim();
}
fhirHealthCard = utils.parseJson(fhirHealthCardText);
if (fhirHealthCard == undefined) {
return [2 /*return*/, log.fatal("Failed to parse FHIR Health Card response data as JSON.", error_1.ErrorCode.JSON_PARSE_ERROR)];
}
param = fhirHealthCard.parameter;
if (!param ||
!(param instanceof Array) ||
param.length === 0) {
return [2 /*return*/, log.fatal("fhirHealthCard.parameter array required to continue.", error_1.ErrorCode.CRITICAL_DATA_MISSING)];
}
return [4 /*yield*/, Promise.all(param.filter(function (p) { return p.name === 'verifiableCredential'; }).map(function (vc, i, VCs) { return __awaiter(_this, void 0, void 0, function () {
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!!vc.valueString) return [3 /*break*/, 1];
log.error("Missing FHIR Health Card response data verifiableCredential #" + (i + 1) + " valueString", i);
return [3 /*break*/, 3];
case 1:
_b = (_a = log.child).push;
return [4 /*yield*/, jws.validate(vc.valueString, VCs.length > 1 ? i.toString() : '')];
case 2:
_b.apply(_a, [_c.sent()]);
_c.label = 3;
case 3: return [2 /*return*/];
}
});
}); }))];
case 1:
_a.sent();
return [2 /*return*/, log];
}
});
});
} |
JavaScript | function objPathToSchema(path) {
var schema = fhir_schema_json_1.default;
var properties = path.split('.');
var p = schema.definitions[properties[0]];
if (p == null)
return 'unknown';
var t = properties[0];
for (var i = 1; i < properties.length; i++) {
if (p.properties) {
p = p.properties[properties[i]];
// this property is not valid according to the schema
if (p == null) {
t = "unknown";
break;
}
// directly has a ref, then it is that type
if (p.$ref) {
t = p.$ref.slice(p.$ref.lastIndexOf('/') + 1);
p = schema.definitions[t];
continue;
}
// has and items prop of ref, then it is an array of that type
if (p.items && '$ref' in p.items) {
t = p.items.$ref.slice(p.items.$ref.lastIndexOf('/') + 1);
p = schema.definitions[t];
continue;
}
// has and items prop of ref, then it is an array of that type
if (p.enum) {
t = "enum";
continue;
}
}
if (p.const) {
t = 'const';
continue;
}
if (p.type) {
t = p.type;
continue;
}
throw new Error('Should not get here.');
}
return t;
} | function objPathToSchema(path) {
var schema = fhir_schema_json_1.default;
var properties = path.split('.');
var p = schema.definitions[properties[0]];
if (p == null)
return 'unknown';
var t = properties[0];
for (var i = 1; i < properties.length; i++) {
if (p.properties) {
p = p.properties[properties[i]];
// this property is not valid according to the schema
if (p == null) {
t = "unknown";
break;
}
// directly has a ref, then it is that type
if (p.$ref) {
t = p.$ref.slice(p.$ref.lastIndexOf('/') + 1);
p = schema.definitions[t];
continue;
}
// has and items prop of ref, then it is an array of that type
if (p.items && '$ref' in p.items) {
t = p.items.$ref.slice(p.items.$ref.lastIndexOf('/') + 1);
p = schema.definitions[t];
continue;
}
// has and items prop of ref, then it is an array of that type
if (p.enum) {
t = "enum";
continue;
}
}
if (p.const) {
t = 'const';
continue;
}
if (p.type) {
t = p.type;
continue;
}
throw new Error('Should not get here.');
}
return t;
} |
JavaScript | function generateImagesFromSvg(dir, force) {
if (force === void 0) { force = false; }
return __awaiter(this, void 0, void 0, function () {
var files, i, file;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
files = fs_1.default.readdirSync(dir);
i = 0;
_a.label = 1;
case 1:
if (!(i < files.length)) return [3 /*break*/, 4];
file = path_1.default.join(dir, files[i]);
if (!(path_1.default.extname(file) === '.svg')) return [3 /*break*/, 3];
// TODO make use of force option
return [4 /*yield*/, image_1.svgToQRImage(file)];
case 2:
// TODO make use of force option
_a.sent();
_a.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/];
}
});
});
} | function generateImagesFromSvg(dir, force) {
if (force === void 0) { force = false; }
return __awaiter(this, void 0, void 0, function () {
var files, i, file;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
files = fs_1.default.readdirSync(dir);
i = 0;
_a.label = 1;
case 1:
if (!(i < files.length)) return [3 /*break*/, 4];
file = path_1.default.join(dir, files[i]);
if (!(path_1.default.extname(file) === '.svg')) return [3 /*break*/, 3];
// TODO make use of force option
return [4 /*yield*/, image_1.svgToQRImage(file)];
case 2:
// TODO make use of force option
_a.sent();
_a.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/];
}
});
});
} |
JavaScript | function svgToImageBuffer(svgPath, log) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
// TODO: create a test that causes failure here
return [2 /*return*/, new Promise(function (resolve, reject) {
svg2img_1.default(svgPath, { width: svgImageWidth, height: svgImageWidth }, function (error, buffer) {
if (error) {
log.fatal("Could not convert SVG to image. Error: " + error.message);
reject(undefined);
}
resolve(buffer);
});
})];
});
});
} | function svgToImageBuffer(svgPath, log) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
// TODO: create a test that causes failure here
return [2 /*return*/, new Promise(function (resolve, reject) {
svg2img_1.default(svgPath, { width: svgImageWidth, height: svgImageWidth }, function (error, buffer) {
if (error) {
log.fatal("Could not convert SVG to image. Error: " + error.message);
reject(undefined);
}
resolve(buffer);
});
})];
});
});
} |
JavaScript | function decodeQrBuffer(fileInfo, log) {
var result = undefined;
//const png = PNG.sync.read(image);
var data = fileInfo.image;
if (!data) {
log.fatal('Could not read image data from : ' + fileInfo.name);
return undefined;
}
var code = jsqr_1.default(new Uint8ClampedArray(data.data.buffer), data.width, data.height);
if (code == null) {
log.fatal('Could not decode QR image from : ' + fileInfo.name, error_1.ErrorCode.QR_DECODE_ERROR);
return result;
}
if (code.version > 22) {
log.error("QR code version of " + code.version + " is larger than the maximum allowed of 22", error_1.ErrorCode.INVALID_QR_VERSION);
}
// check chunks. Note: jsQR calls chunks and type what the SMART Health Cards spec call segments and mode,
// we use the later in error messages
code.chunks.forEach(function (c, i) {
var _a;
var chunkText = c.text || ((_a = c.bytes) === null || _a === void 0 ? void 0 : _a.join(',')) || "<can't parse>";
log.debug("segment " + (i + 1) + ": type: " + c.type + ", content: " + chunkText);
});
if (!code.chunks || code.chunks.length !== 2) {
log.error("Wrong number of segments in QR code: found " + code.chunks.length + ", expected 2" +
("\nSegments types: " + code.chunks.map(function (chunk, i) { return i + 1 + ": " + chunk.type; }).join("; ")), error_1.ErrorCode.INVALID_QR);
}
else {
if (code.chunks[0].type !== 'byte') {
// unlikely, since 'shc:/' can only be legally encoded as with byte mode;
// was not able to create test case for this
log.error("Wrong encoding mode for first QR segment: found " + code.chunks[0].type + ", expected \"byte\"", error_1.ErrorCode.INVALID_QR);
}
if (code.chunks[1].type !== 'numeric') {
log.error("Wrong encoding mode for second QR segment: found " + code.chunks[0].type + ", expected \"numeric\"", error_1.ErrorCode.INVALID_QR);
}
// let's make sure the QR code's version is tight
try {
var qrCode = qrcode_1.create(code.data, { errorCorrectionLevel: 'low' });
if (qrCode.version < code.version) {
log.warn("QR code has version " + code.version + ", but could have been created with version " + qrCode.version + " (with low error-correcting level). Make sure the larger version was chosen on purpose (e.g., not hardcoded).", error_1.ErrorCode.INVALID_QR_VERSION);
}
}
catch (err) {
log.warn("Can't re-create QR to check optimal version choice: ", err);
}
}
// the proper formatting of the QR code data is done later in the pipeline
return code.data;
} | function decodeQrBuffer(fileInfo, log) {
var result = undefined;
//const png = PNG.sync.read(image);
var data = fileInfo.image;
if (!data) {
log.fatal('Could not read image data from : ' + fileInfo.name);
return undefined;
}
var code = jsqr_1.default(new Uint8ClampedArray(data.data.buffer), data.width, data.height);
if (code == null) {
log.fatal('Could not decode QR image from : ' + fileInfo.name, error_1.ErrorCode.QR_DECODE_ERROR);
return result;
}
if (code.version > 22) {
log.error("QR code version of " + code.version + " is larger than the maximum allowed of 22", error_1.ErrorCode.INVALID_QR_VERSION);
}
// check chunks. Note: jsQR calls chunks and type what the SMART Health Cards spec call segments and mode,
// we use the later in error messages
code.chunks.forEach(function (c, i) {
var _a;
var chunkText = c.text || ((_a = c.bytes) === null || _a === void 0 ? void 0 : _a.join(',')) || "<can't parse>";
log.debug("segment " + (i + 1) + ": type: " + c.type + ", content: " + chunkText);
});
if (!code.chunks || code.chunks.length !== 2) {
log.error("Wrong number of segments in QR code: found " + code.chunks.length + ", expected 2" +
("\nSegments types: " + code.chunks.map(function (chunk, i) { return i + 1 + ": " + chunk.type; }).join("; ")), error_1.ErrorCode.INVALID_QR);
}
else {
if (code.chunks[0].type !== 'byte') {
// unlikely, since 'shc:/' can only be legally encoded as with byte mode;
// was not able to create test case for this
log.error("Wrong encoding mode for first QR segment: found " + code.chunks[0].type + ", expected \"byte\"", error_1.ErrorCode.INVALID_QR);
}
if (code.chunks[1].type !== 'numeric') {
log.error("Wrong encoding mode for second QR segment: found " + code.chunks[0].type + ", expected \"numeric\"", error_1.ErrorCode.INVALID_QR);
}
// let's make sure the QR code's version is tight
try {
var qrCode = qrcode_1.create(code.data, { errorCorrectionLevel: 'low' });
if (qrCode.version < code.version) {
log.warn("QR code has version " + code.version + ", but could have been created with version " + qrCode.version + " (with low error-correcting level). Make sure the larger version was chosen on purpose (e.g., not hardcoded).", error_1.ErrorCode.INVALID_QR_VERSION);
}
}
catch (err) {
log.warn("Can't re-create QR to check optimal version choice: ", err);
}
}
// the proper formatting of the QR code data is done later in the pipeline
return code.data;
} |
JavaScript | function serializeStore(store) {
const storeObject =
typeof store.getState === 'function' ? store.getState() : store;
return serialize(storeObject, { isJSON: true });
} | function serializeStore(store) {
const storeObject =
typeof store.getState === 'function' ? store.getState() : store;
return serialize(storeObject, { isJSON: true });
} |
JavaScript | async loadUnsignedCertificate(pathToUnsignedCertificate) {
try {
const cert = fs.readFileSync(pathToUnsignedCertificate, 'utf8')
return JSON.parse(cert)
} catch(err) {
console.log('Error: loadUnsignedCertificate->> ', err)
return err
}
} | async loadUnsignedCertificate(pathToUnsignedCertificate) {
try {
const cert = fs.readFileSync(pathToUnsignedCertificate, 'utf8')
return JSON.parse(cert)
} catch(err) {
console.log('Error: loadUnsignedCertificate->> ', err)
return err
}
} |
JavaScript | async function canonizeData(dataset){
try {
return await jsonld.normalize(dataset, {algorithm: 'URDNA2015', format: 'application/n-quads'});
} catch(err) {
console.log('Error: canonizeData->> ', err)
return err
}
} | async function canonizeData(dataset){
try {
return await jsonld.normalize(dataset, {algorithm: 'URDNA2015', format: 'application/n-quads'});
} catch(err) {
console.log('Error: canonizeData->> ', err)
return err
}
} |
JavaScript | function navigateToStory(category, name, cb) {
cy.visit("/");
// Navigate to story with the name
const storySideBar =
"#" + category.replace(/\s+/g, "-").toLowerCase() + name.toLowerCase();
cy.log(`Open story ${category} ${name} - ${storySideBar}`);
cy.get(storySideBar).click();
cy.get("#storybook-panel-root").contains(name);
// Get story ID to visit iframe directly
cy.window().then(win => {
const storyId = win.location.href.split("?path=/story/")[1];
cy.visit("/iframe.html?id=" + storyId).then(iframeWin => {
const consoleErrorSpy = cy.spy(iframeWin.console, "error");
const consoleWarnSpy = cy.spy(iframeWin.console, "warn");
(cb || noOp)();
// Wait for app to render
cy.contains(name).then(() => {
expect(consoleErrorSpy).not.to.be.called;
expect(consoleWarnSpy).not.to.be.called;
});
});
});
} | function navigateToStory(category, name, cb) {
cy.visit("/");
// Navigate to story with the name
const storySideBar =
"#" + category.replace(/\s+/g, "-").toLowerCase() + name.toLowerCase();
cy.log(`Open story ${category} ${name} - ${storySideBar}`);
cy.get(storySideBar).click();
cy.get("#storybook-panel-root").contains(name);
// Get story ID to visit iframe directly
cy.window().then(win => {
const storyId = win.location.href.split("?path=/story/")[1];
cy.visit("/iframe.html?id=" + storyId).then(iframeWin => {
const consoleErrorSpy = cy.spy(iframeWin.console, "error");
const consoleWarnSpy = cy.spy(iframeWin.console, "warn");
(cb || noOp)();
// Wait for app to render
cy.contains(name).then(() => {
expect(consoleErrorSpy).not.to.be.called;
expect(consoleWarnSpy).not.to.be.called;
});
});
});
} |
JavaScript | function drawCharts(dataUrl) {
// TODO Using window["location"]["hostname"] instead of
// window.location.hostname because when deno runs app_test.js it gets a type
// error here, not knowing about window.location. Ideally Deno would skip
// type check entirely on JS files.
if (window["location"]["hostname"] != "deno.github.io") {
dataUrl = "https://denoland.github.io/deno/" + dataUrl;
}
drawChartsFromBenchmarkData(dataUrl);
} | function drawCharts(dataUrl) {
// TODO Using window["location"]["hostname"] instead of
// window.location.hostname because when deno runs app_test.js it gets a type
// error here, not knowing about window.location. Ideally Deno would skip
// type check entirely on JS files.
if (window["location"]["hostname"] != "deno.github.io") {
dataUrl = "https://denoland.github.io/deno/" + dataUrl;
}
drawChartsFromBenchmarkData(dataUrl);
} |
JavaScript | async function drawChartsFromBenchmarkData(dataUrl) {
const data = await getJson(dataUrl);
const execTimeColumns = createExecTimeColumns(data);
const throughputColumns = createThroughputColumns(data);
const reqPerSecColumns = createReqPerSecColumns(data);
const binarySizeColumns = createBinarySizeColumns(data);
const threadCountColumns = createThreadCountColumns(data);
const syscallCountColumns = createSyscallCountColumns(data);
const sha1List = createSha1List(data);
const sha1ShortList = sha1List.map(sha1 => sha1.substring(0, 6));
const viewCommitOnClick = _sha1List => d => {
// @ts-ignore
window.open(
`https://github.com/denoland/deno/commit/${_sha1List[d["index"]]}`
);
};
function gen(id, columns, yLabel = "", yTickFormat = null) {
generate(
id,
sha1ShortList,
columns,
viewCommitOnClick(sha1List),
yLabel,
yTickFormat
);
}
gen("#exec-time-chart", execTimeColumns, "seconds", logScale);
gen("#throughput-chart", throughputColumns, "seconds", logScale);
gen("#req-per-sec-chart", reqPerSecColumns, "1000 req/sec", formatReqSec);
gen("#binary-size-chart", binarySizeColumns, "megabytes", formatMB);
gen("#thread-count-chart", threadCountColumns, "threads");
gen("#syscall-count-chart", syscallCountColumns, "syscalls");
} | async function drawChartsFromBenchmarkData(dataUrl) {
const data = await getJson(dataUrl);
const execTimeColumns = createExecTimeColumns(data);
const throughputColumns = createThroughputColumns(data);
const reqPerSecColumns = createReqPerSecColumns(data);
const binarySizeColumns = createBinarySizeColumns(data);
const threadCountColumns = createThreadCountColumns(data);
const syscallCountColumns = createSyscallCountColumns(data);
const sha1List = createSha1List(data);
const sha1ShortList = sha1List.map(sha1 => sha1.substring(0, 6));
const viewCommitOnClick = _sha1List => d => {
// @ts-ignore
window.open(
`https://github.com/denoland/deno/commit/${_sha1List[d["index"]]}`
);
};
function gen(id, columns, yLabel = "", yTickFormat = null) {
generate(
id,
sha1ShortList,
columns,
viewCommitOnClick(sha1List),
yLabel,
yTickFormat
);
}
gen("#exec-time-chart", execTimeColumns, "seconds", logScale);
gen("#throughput-chart", throughputColumns, "seconds", logScale);
gen("#req-per-sec-chart", reqPerSecColumns, "1000 req/sec", formatReqSec);
gen("#binary-size-chart", binarySizeColumns, "megabytes", formatMB);
gen("#thread-count-chart", threadCountColumns, "threads");
gen("#syscall-count-chart", syscallCountColumns, "syscalls");
} |
JavaScript | async function addItem(item) {
// Add item to db and state
let newDbUser = { ...dbUser };
newDbUser.lists[currentListID].items.unshift(item);
setDbUser(newDbUser);
updateDbLists(newDbUser.lists)
} | async function addItem(item) {
// Add item to db and state
let newDbUser = { ...dbUser };
newDbUser.lists[currentListID].items.unshift(item);
setDbUser(newDbUser);
updateDbLists(newDbUser.lists)
} |
JavaScript | function parseIDs( IDs ) {
var r={ albumID:'0', imageID:'0' };
var t=IDs.split('/');
if( t.length > 0 ) {
r.albumID=t[0];
if( t.length > 1 ) {
r.imageID=t[1];
}
}
return r;
} | function parseIDs( IDs ) {
var r={ albumID:'0', imageID:'0' };
var t=IDs.split('/');
if( t.length > 0 ) {
r.albumID=t[0];
if( t.length > 1 ) {
r.imageID=t[1];
}
}
return r;
} |
JavaScript | function GalleryNavigationBar( albumIdx ) {
// new navigation bar items are not build in the DOM, but in memory
G.GOM.navigationBar.$newContent=jQuery('<div class="nGY2Navigationbar"></div>');
//-- manage breadcrumb
if( G.O.displayBreadcrumb == true && !G.O.thumbnailAlbumDisplayImage) {
// retrieve new folder level
var newLevel = 0,
lstItems=[];
if( albumIdx != 0 ) {
var l=G.I.length,
parentID=0;
lstItems.push(albumIdx);
var curIdx=albumIdx;
newLevel++;
while( G.I[curIdx].albumID != 0 && G.I[curIdx].albumID != -1) {
for(var i=1; i < l; i++ ) {
if( G.I[i].GetID() == G.I[curIdx].albumID ) {
curIdx=i;
lstItems.push(curIdx);
newLevel++;
break;
}
}
}
}
// build breadcrumb
if( !(G.O.breadcrumbAutoHideTopLevel && newLevel == 0) ) {
BreadcrumbBuild( lstItems );
}
}
//-- manage tag filters
if( G.galleryFilterTags.Get() != false ) {
var nTags=G.I[albumIdx].albumTagList.length;
if( nTags > 0 ) {
for(var i=0; i <nTags; i++ ) {
var s=G.I[albumIdx].albumTagList[i];
var ic=G.O.icons.navigationFilterUnselected;
var tagClass='Unselected';
if( jQuery.inArray(s, G.I[albumIdx].albumTagListSel) >= 0 ) {
tagClass='Selected';
ic=G.O.icons.navigationFilterSelected;
}
var $newTag=jQuery('<div class="nGY2NavigationbarItem nGY2NavFilter'+tagClass+'">'+ic+' '+s+'</div>').appendTo(G.GOM.navigationBar.$newContent);
$newTag.click(function() {
var $this=jQuery(this);
var tag=$this.text().replace(/^\s*|\s*$/, ''); //trim trailing/leading whitespace
// if( $this.hasClass('oneTagUnselected') ){
if( $this.hasClass('nGY2NavFilterUnselected') ){
G.I[albumIdx].albumTagListSel.push(tag);
}
else {
var tidx=jQuery.inArray(tag,G.I[albumIdx].albumTagListSel);
if( tidx != -1 ) {
G.I[albumIdx].albumTagListSel.splice(tidx,1);
}
}
$this.toggleClass('nGY2NavFilters-oneTagUnselected nGY2NavFilters-oneTagSelected');
DisplayAlbum('-1', G.I[albumIdx].GetID());
});
}
var $newClearFilter=jQuery('<div class="nGY2NavigationbarItem nGY2NavFilterSelectAll">'+G.O.icons.navigationFilterSelectedAll+'</div>').appendTo(G.GOM.navigationBar.$newContent);
$newClearFilter.click(function() {
var nTags=G.I[albumIdx].albumTagList.length;
G.I[albumIdx].albumTagListSel=[];
for(var i=0; i <nTags; i++ ) {
var s=G.I[albumIdx].albumTagList[i];
G.I[albumIdx].albumTagListSel.push(s);
}
DisplayAlbum('-1', G.I[albumIdx].GetID());
});
}
}
} | function GalleryNavigationBar( albumIdx ) {
// new navigation bar items are not build in the DOM, but in memory
G.GOM.navigationBar.$newContent=jQuery('<div class="nGY2Navigationbar"></div>');
//-- manage breadcrumb
if( G.O.displayBreadcrumb == true && !G.O.thumbnailAlbumDisplayImage) {
// retrieve new folder level
var newLevel = 0,
lstItems=[];
if( albumIdx != 0 ) {
var l=G.I.length,
parentID=0;
lstItems.push(albumIdx);
var curIdx=albumIdx;
newLevel++;
while( G.I[curIdx].albumID != 0 && G.I[curIdx].albumID != -1) {
for(var i=1; i < l; i++ ) {
if( G.I[i].GetID() == G.I[curIdx].albumID ) {
curIdx=i;
lstItems.push(curIdx);
newLevel++;
break;
}
}
}
}
// build breadcrumb
if( !(G.O.breadcrumbAutoHideTopLevel && newLevel == 0) ) {
BreadcrumbBuild( lstItems );
}
}
//-- manage tag filters
if( G.galleryFilterTags.Get() != false ) {
var nTags=G.I[albumIdx].albumTagList.length;
if( nTags > 0 ) {
for(var i=0; i <nTags; i++ ) {
var s=G.I[albumIdx].albumTagList[i];
var ic=G.O.icons.navigationFilterUnselected;
var tagClass='Unselected';
if( jQuery.inArray(s, G.I[albumIdx].albumTagListSel) >= 0 ) {
tagClass='Selected';
ic=G.O.icons.navigationFilterSelected;
}
var $newTag=jQuery('<div class="nGY2NavigationbarItem nGY2NavFilter'+tagClass+'">'+ic+' '+s+'</div>').appendTo(G.GOM.navigationBar.$newContent);
$newTag.click(function() {
var $this=jQuery(this);
var tag=$this.text().replace(/^\s*|\s*$/, ''); //trim trailing/leading whitespace
// if( $this.hasClass('oneTagUnselected') ){
if( $this.hasClass('nGY2NavFilterUnselected') ){
G.I[albumIdx].albumTagListSel.push(tag);
}
else {
var tidx=jQuery.inArray(tag,G.I[albumIdx].albumTagListSel);
if( tidx != -1 ) {
G.I[albumIdx].albumTagListSel.splice(tidx,1);
}
}
$this.toggleClass('nGY2NavFilters-oneTagUnselected nGY2NavFilters-oneTagSelected');
DisplayAlbum('-1', G.I[albumIdx].GetID());
});
}
var $newClearFilter=jQuery('<div class="nGY2NavigationbarItem nGY2NavFilterSelectAll">'+G.O.icons.navigationFilterSelectedAll+'</div>').appendTo(G.GOM.navigationBar.$newContent);
$newClearFilter.click(function() {
var nTags=G.I[albumIdx].albumTagList.length;
G.I[albumIdx].albumTagListSel=[];
for(var i=0; i <nTags; i++ ) {
var s=G.I[albumIdx].albumTagList[i];
G.I[albumIdx].albumTagListSel.push(s);
}
DisplayAlbum('-1', G.I[albumIdx].GetID());
});
}
}
} |
JavaScript | function GalleryRenderPart2(albumIdx) {
G.GOM.lastZIndex = parseInt(G.$E.base.css('z-index'));
if( isNaN(G.GOM.lastZIndex) ) {
G.GOM.lastZIndex=0;
}
G.$E.conTnParent.css({'opacity': 0 });
// G.$E.conTn.hide(0).off().show(0).html('');
// G.$E.conTn.off().html('');
G.$E.conTn.off().empty();
var l=G.I.length;
for( var i=0; i < l ; i++ ) {
// reset each item
var item=G.I[i];
item.hovered=false;
item.$elt=null;
item.$Elts=[];
item.eltTransform=[];
item.eltFilter=[];
item.width=0;
item.height=0;
item.left=0;
item.top=0;
item.resizedContentWidth=0;
item.resizedContentHeight=0;
}
G.$E.conTn.css( G.CSStransformName , 'translateX('+0+'px)');
G.$E.conTnParent.css({ left:0, opacity:1 });
GalleryRenderPart3(albumIdx);
} | function GalleryRenderPart2(albumIdx) {
G.GOM.lastZIndex = parseInt(G.$E.base.css('z-index'));
if( isNaN(G.GOM.lastZIndex) ) {
G.GOM.lastZIndex=0;
}
G.$E.conTnParent.css({'opacity': 0 });
// G.$E.conTn.hide(0).off().show(0).html('');
// G.$E.conTn.off().html('');
G.$E.conTn.off().empty();
var l=G.I.length;
for( var i=0; i < l ; i++ ) {
// reset each item
var item=G.I[i];
item.hovered=false;
item.$elt=null;
item.$Elts=[];
item.eltTransform=[];
item.eltFilter=[];
item.width=0;
item.height=0;
item.left=0;
item.top=0;
item.resizedContentWidth=0;
item.resizedContentHeight=0;
}
G.$E.conTn.css( G.CSStransformName , 'translateX('+0+'px)');
G.$E.conTnParent.css({ left:0, opacity:1 });
GalleryRenderPart3(albumIdx);
} |
JavaScript | function GalleryRenderPart3(albumIdx) {
var d=new Date();
G.GOM.items = [];
G.GOM.displayedMoreSteps=0;
// retrieve annotation height
var annotationHeight = 0;
if( G.O.thumbnailLabel.get('position') == 'onBottom' ) {
// retrieve height each time because size can change depending on thumbnail's settings
annotationHeight=ThumbnailGetAnnotationHeight();
G.tn.labelHeight[G.GOM.curNavLevel]=annotationHeight;
}
else {
G.tn.labelHeight[G.GOM.curNavLevel]=0;
}
G.GOM.albumIdx=albumIdx;
TriggerCustomEvent('galleryRenderEnd');
if( typeof G.O.fnGalleryRenderEnd == 'function' ) {
G.O.fnGalleryRenderEnd(albumIdx);
}
// Step 1: populate GOM
if( GalleryPopulateGOM() ) {
// step 2: calculate layout
GallerySetLayout();
// step 3: display gallery
GalleryDisplay( false );
G.galleryResizeEventEnabled=true;
}
else {
G.galleryResizeEventEnabled=true;
}
if( G.O.debugMode ) {
console.log('GalleryRenderPart3: '+ (new Date()-d));
}
} | function GalleryRenderPart3(albumIdx) {
var d=new Date();
G.GOM.items = [];
G.GOM.displayedMoreSteps=0;
// retrieve annotation height
var annotationHeight = 0;
if( G.O.thumbnailLabel.get('position') == 'onBottom' ) {
// retrieve height each time because size can change depending on thumbnail's settings
annotationHeight=ThumbnailGetAnnotationHeight();
G.tn.labelHeight[G.GOM.curNavLevel]=annotationHeight;
}
else {
G.tn.labelHeight[G.GOM.curNavLevel]=0;
}
G.GOM.albumIdx=albumIdx;
TriggerCustomEvent('galleryRenderEnd');
if( typeof G.O.fnGalleryRenderEnd == 'function' ) {
G.O.fnGalleryRenderEnd(albumIdx);
}
// Step 1: populate GOM
if( GalleryPopulateGOM() ) {
// step 2: calculate layout
GallerySetLayout();
// step 3: display gallery
GalleryDisplay( false );
G.galleryResizeEventEnabled=true;
}
else {
G.galleryResizeEventEnabled=true;
}
if( G.O.debugMode ) {
console.log('GalleryRenderPart3: '+ (new Date()-d));
}
} |
JavaScript | function GalleryPopulateGOM() {
// G.galleryResizeEventEnabled=false;
var preloadImages='';
var imageSizeRequested=false;
//var nbTn=G.GOM.items.length;
var albumID=G.I[G.GOM.albumIdx].GetID();
var l=G.I.length;
var cnt=0;
for( var idx=0; idx<l; idx++ ) {
var item=G.I[idx];
// check album
if( item.albumID == albumID && item.checkTagFilter() && item.isSearchFound() ) {
var w=item.thumbImg().width;
var h=item.thumbImg().height;
// if unknown image size and layout is not grid --> we need to retrieve the size of the images
if( G.layout.prerequisite.imageSize && ( w == 0 || h == 0) ) {
imageSizeRequested=true;
preloadImages+='<img src="'+item.thumbImg().src+'" data-idx="'+cnt+'" data-albumidx="'+G.GOM.albumIdx+'">';
}
// set default size if required
if( h == 0 ) {
h=G.tn.defaultSize.getHeight();
}
if( w == 0 ) {
w=G.tn.defaultSize.getWidth();
}
var tn=new GTn(idx, w, h);
G.GOM.items.push(tn);
cnt++;
}
}
// G.$E.base.trigger('galleryObjectModelBuilt.nanogallery2', new Event('galleryObjectModelBuilt.nanogallery2'));
TriggerCustomEvent('galleryObjectModelBuilt');
if( typeof G.O.fnGalleryObjectModelBuilt == 'function' ) {
G.O.fnGalleryObjectModelBuilt();
}
if( imageSizeRequested ) {
// preload images to retrieve their size and then resize the gallery (=GallerySetLayout()+ GalleryDisplay())
var $newImg=jQuery(preloadImages);
var gi_imgLoad = ngimagesLoaded( $newImg );
$newImg=null;
gi_imgLoad.on( 'progress', function( instance, image ) {
if( image.isLoaded ) {
var idx=image.img.getAttribute('data-idx');
var albumIdx=image.img.getAttribute('data-albumidx');
if( albumIdx == G.GOM.albumIdx ) {
// ignore event if not on current album
var curTn=G.GOM.items[idx];
curTn.imageWidth=image.img.naturalWidth;
curTn.imageHeight=image.img.naturalHeight;
var item=G.I[curTn.thumbnailIdx];
item.thumbs.width[G.GOM.curNavLevel][G.GOM.curWidth]=curTn.imageWidth;
item.thumbs.height[G.GOM.curNavLevel][G.GOM.curWidth]=curTn.imageHeight;
if( G.layout.engine == 'GRID' && G.thumbnailCrop.Get() === true && item.$getElt('.nGY2GThumbnailImg') !== null ) {
// special case (GRID + cropped thumbnails) -> just reposition the image in the thumbnail
if( item.thumbImg().height > item.thumbImg().width ) {
// portrait
item.$getElt('.nGY2GThumbnailImg').css({ width: G.tn.settings.getW()+'px' });
}
else {
// paysage
// step 1: adjust height
var r2=G.tn.settings.getH()/item.thumbImg().height;
var newH= G.tn.settings.getH();
var newW= item.thumbImg().width*r2;
// step 2: check if width needs to be adjusted
if( newW >= G.tn.settings.getW() ) {
// no adjustement
var d=(item.thumbImg().width*r2-G.tn.settings.getW()) / 2;
item.$getElt('.nGY2GThumbnailImg').css({ height: G.tn.settings.getH()+'px',left: d+'px' });
}
else {
// yes, adjust width
// after scaling to adjust the height, the width is too narrow => upscale again to fit width
var rW=G.tn.settings.getW()/item.thumbImg().width;
var w=item.thumbImg().width*rW;
item.$getElt('.nGY2GThumbnailImg').css({ width: w+'px' });
}
}
}
// resize the gallery
G.GalleryResizeThrottled();
// set the retrieved size to all levels with same configuration
var object=item.thumbs.width.l1;
for (var property in object) {
if (object.hasOwnProperty(property)) {
if( property != G.GOM.curWidth ) {
if( G.tn.settings.width.l1[property] == G.tn.settings.getW() && G.tn.settings.height.l1[property] == G.tn.settings.getH() ) {
item.thumbs.width.l1[property]=curTn.imageWidth;
item.thumbs.height.l1[property]=curTn.imageHeight;
}
}
}
}
object=item.thumbs.width.lN;
for (var property in object) {
if (object.hasOwnProperty(property)) {
if( property != G.GOM.curWidth ) {
if( G.tn.settings.width.lN[property] == G.tn.settings.getW() && G.tn.settings.height.lN[property] == G.tn.settings.getH() ) {
item.thumbs.width.lN[property]=curTn.imageWidth;
item.thumbs.height.lN[property]=curTn.imageHeight;
}
}
}
}
}
}
});
G.galleryResizeEventEnabled=true;
return false;
}
else {
return true;
}
} | function GalleryPopulateGOM() {
// G.galleryResizeEventEnabled=false;
var preloadImages='';
var imageSizeRequested=false;
//var nbTn=G.GOM.items.length;
var albumID=G.I[G.GOM.albumIdx].GetID();
var l=G.I.length;
var cnt=0;
for( var idx=0; idx<l; idx++ ) {
var item=G.I[idx];
// check album
if( item.albumID == albumID && item.checkTagFilter() && item.isSearchFound() ) {
var w=item.thumbImg().width;
var h=item.thumbImg().height;
// if unknown image size and layout is not grid --> we need to retrieve the size of the images
if( G.layout.prerequisite.imageSize && ( w == 0 || h == 0) ) {
imageSizeRequested=true;
preloadImages+='<img src="'+item.thumbImg().src+'" data-idx="'+cnt+'" data-albumidx="'+G.GOM.albumIdx+'">';
}
// set default size if required
if( h == 0 ) {
h=G.tn.defaultSize.getHeight();
}
if( w == 0 ) {
w=G.tn.defaultSize.getWidth();
}
var tn=new GTn(idx, w, h);
G.GOM.items.push(tn);
cnt++;
}
}
// G.$E.base.trigger('galleryObjectModelBuilt.nanogallery2', new Event('galleryObjectModelBuilt.nanogallery2'));
TriggerCustomEvent('galleryObjectModelBuilt');
if( typeof G.O.fnGalleryObjectModelBuilt == 'function' ) {
G.O.fnGalleryObjectModelBuilt();
}
if( imageSizeRequested ) {
// preload images to retrieve their size and then resize the gallery (=GallerySetLayout()+ GalleryDisplay())
var $newImg=jQuery(preloadImages);
var gi_imgLoad = ngimagesLoaded( $newImg );
$newImg=null;
gi_imgLoad.on( 'progress', function( instance, image ) {
if( image.isLoaded ) {
var idx=image.img.getAttribute('data-idx');
var albumIdx=image.img.getAttribute('data-albumidx');
if( albumIdx == G.GOM.albumIdx ) {
// ignore event if not on current album
var curTn=G.GOM.items[idx];
curTn.imageWidth=image.img.naturalWidth;
curTn.imageHeight=image.img.naturalHeight;
var item=G.I[curTn.thumbnailIdx];
item.thumbs.width[G.GOM.curNavLevel][G.GOM.curWidth]=curTn.imageWidth;
item.thumbs.height[G.GOM.curNavLevel][G.GOM.curWidth]=curTn.imageHeight;
if( G.layout.engine == 'GRID' && G.thumbnailCrop.Get() === true && item.$getElt('.nGY2GThumbnailImg') !== null ) {
// special case (GRID + cropped thumbnails) -> just reposition the image in the thumbnail
if( item.thumbImg().height > item.thumbImg().width ) {
// portrait
item.$getElt('.nGY2GThumbnailImg').css({ width: G.tn.settings.getW()+'px' });
}
else {
// paysage
// step 1: adjust height
var r2=G.tn.settings.getH()/item.thumbImg().height;
var newH= G.tn.settings.getH();
var newW= item.thumbImg().width*r2;
// step 2: check if width needs to be adjusted
if( newW >= G.tn.settings.getW() ) {
// no adjustement
var d=(item.thumbImg().width*r2-G.tn.settings.getW()) / 2;
item.$getElt('.nGY2GThumbnailImg').css({ height: G.tn.settings.getH()+'px',left: d+'px' });
}
else {
// yes, adjust width
// after scaling to adjust the height, the width is too narrow => upscale again to fit width
var rW=G.tn.settings.getW()/item.thumbImg().width;
var w=item.thumbImg().width*rW;
item.$getElt('.nGY2GThumbnailImg').css({ width: w+'px' });
}
}
}
// resize the gallery
G.GalleryResizeThrottled();
// set the retrieved size to all levels with same configuration
var object=item.thumbs.width.l1;
for (var property in object) {
if (object.hasOwnProperty(property)) {
if( property != G.GOM.curWidth ) {
if( G.tn.settings.width.l1[property] == G.tn.settings.getW() && G.tn.settings.height.l1[property] == G.tn.settings.getH() ) {
item.thumbs.width.l1[property]=curTn.imageWidth;
item.thumbs.height.l1[property]=curTn.imageHeight;
}
}
}
}
object=item.thumbs.width.lN;
for (var property in object) {
if (object.hasOwnProperty(property)) {
if( property != G.GOM.curWidth ) {
if( G.tn.settings.width.lN[property] == G.tn.settings.getW() && G.tn.settings.height.lN[property] == G.tn.settings.getH() ) {
item.thumbs.width.lN[property]=curTn.imageWidth;
item.thumbs.height.lN[property]=curTn.imageHeight;
}
}
}
}
}
}
});
G.galleryResizeEventEnabled=true;
return false;
}
else {
return true;
}
} |
JavaScript | function GallerySetLayout( GOMidx ) {
var r = true;
// available area width
var areaWidth=G.$E.conTnParent.width();
G.GOM.displayArea={ width:0, height:0 };
switch( G.layout.engine ) {
case 'JUSTIFIED':
r= GallerySetLayoutWidthtAuto( areaWidth, GOMidx );
break;
case 'CASCADING':
r= GallerySetLayoutHeightAuto( areaWidth, GOMidx );
break;
case 'GRID':
default:
r= GallerySetLayoutGrid( areaWidth, GOMidx );
break;
}
TriggerCustomEvent('galleryLayoutApplied');
if( typeof G.O.fnGalleryLayoutApplied == 'function' ) {
G.O.fnGalleryLayoutApplied();
}
return r;
} | function GallerySetLayout( GOMidx ) {
var r = true;
// available area width
var areaWidth=G.$E.conTnParent.width();
G.GOM.displayArea={ width:0, height:0 };
switch( G.layout.engine ) {
case 'JUSTIFIED':
r= GallerySetLayoutWidthtAuto( areaWidth, GOMidx );
break;
case 'CASCADING':
r= GallerySetLayoutHeightAuto( areaWidth, GOMidx );
break;
case 'GRID':
default:
r= GallerySetLayoutGrid( areaWidth, GOMidx );
break;
}
TriggerCustomEvent('galleryLayoutApplied');
if( typeof G.O.fnGalleryLayoutApplied == 'function' ) {
G.O.fnGalleryLayoutApplied();
}
return r;
} |
JavaScript | function GalleryDisplay( forceTransition ) {
G.$E.conTn.css( G.CSStransformName , 'translateX('+0+'px)');
var nbTn=G.GOM.items.length;
G.GOM.itemsDisplayed=0;
var threshold = 50;
var cnt=0; // counter for delay between each thumbnail display
var vp=getViewport();
G.GOM.cache.viewport=vp;
var containerOffset=G.$E.conTnParent.offset();
G.GOM.cache.containerOffset=containerOffset;
GalleryRenderGetInterval();
for( var i=0; i < nbTn ; i++ ) {
var curTn=G.GOM.items[i];
if( i >= G.GOM.displayInterval.from && cnt < G.GOM.displayInterval.len ) {
curTn.inDisplayArea=true;
if( forceTransition ) {
curTn.neverDisplayed=true;
}
G.GOM.itemsDisplayed++;
cnt++;
}
else{
curTn.inDisplayArea=false;
}
}
// bottom of the gallery (pagination, more button...)
GalleryBottomManage();
var tnToDisplay = [];
var tnToReDisplay = [];
G.GOM.clipArea.top=-1;
cnt=0;
var lastTnIdx=-1;
G.GOM.clipArea.height=0;
// NOTE: loop always the whole GOM.items --> in case an already displayed thumbnail needs to be removed
for( var i=0; i < nbTn ; i++ ) {
var curTn=G.GOM.items[i];
if( curTn.inDisplayArea ) {
if( G.GOM.clipArea.top == - 1 ) {
G.GOM.clipArea.top=curTn.top;
}
G.GOM.clipArea.height=Math.max(G.GOM.clipArea.height, curTn.top-G.GOM.clipArea.top+curTn.height);
if( curTn.neverDisplayed ) {
// thumbnail is not displayed -> check if in viewport to display or not
var top=containerOffset.top+(curTn.top-G.GOM.clipArea.top);
// var left=containerOffset.left+curTn.left;
if( (top+curTn.height) >= (vp.t-threshold) && top <= (vp.t+vp.h+threshold) ) {
// build thumbnail
var item=G.I[curTn.thumbnailIdx];
if( item.$elt == null ) {
ThumbnailBuild( item, curTn.thumbnailIdx, i, (i+1)==nbTn );
}
tnToDisplay.push({idx:i, delay:cnt});
cnt++;
}
}
else {
tnToReDisplay.push({idx:i, delay:0});
}
// G.GOM.itemsDisplayed++;
lastTnIdx=i;
}
else {
curTn.displayed=false;
var item=G.I[curTn.thumbnailIdx];
if( item.$elt != null ){
item.$elt.css({ opacity: 0, display: 'none' });
}
}
}
var areaWidth=G.$E.conTnParent.width();
// set gallery area really used size
// if( G.GOM.displayArea.width != G.GOM.displayAreaLast.width || G.GOM.displayArea.height != G.GOM.displayAreaLast.height ) {
if( G.GOM.displayArea.width != G.GOM.displayAreaLast.width || G.GOM.clipArea.height != G.GOM.displayAreaLast.height ) {
G.$E.conTn.width(G.GOM.displayArea.width).height(G.GOM.clipArea.height);
G.GOM.displayAreaLast.width=G.GOM.displayArea.width;
G.GOM.displayAreaLast.height=G.GOM.clipArea.height;
// G.GOM.displayAreaLast.height=G.GOM.displayArea.height-G.GOM.clipArea.top;
}
if( areaWidth != G.$E.conTnParent.width() ) {
// gallery area width changed since layout calculation (for example when a scrollbar appeared)
// so we need re-calculate the layout before displaying the thumbnails
GallerySetLayout();
GalleryDisplay( forceTransition );
}
// counter of not displayed images (is displayed on the last thumbnail)
if( G.layout.support.rows ) {
if( G.galleryDisplayMode.Get() == 'ROWS' || (G.galleryDisplayMode.Get() == 'FULLCONTENT' && G.galleryLastRowFull.Get() && G.GOM.lastFullRow != -1) ){
if( lastTnIdx < (nbTn-1) ) {
G.GOM.lastDisplayedIdxNew=lastTnIdx;
}
else {
G.GOM.lastDisplayedIdxNew=-1;
}
// remove last displayed counter
if( G.GOM.lastDisplayedIdx != -1 ) {
var item=G.I[G.GOM.items[G.GOM.lastDisplayedIdx].thumbnailIdx];
item.$getElt('.nGY2GThumbnailIconsFullThumbnail').html('');
}
}
}
// batch set position (and display animation) to all thumbnails
// first display newly built thumbnails
var nbBuild=tnToDisplay.length;
for( var i=0; i < nbBuild ; i++ ) {
ThumbnailSetPosition(tnToDisplay[i].idx,tnToDisplay[i].delay+10);
}
// then re-position already displayed thumbnails
var n=tnToReDisplay.length;
for( var i=0; i < n ; i++ ) {
ThumbnailSetPosition(tnToReDisplay[i].idx,nbBuild+1);
}
if( G.tn.displayTransition == 'NONE' ) {
G.galleryResizeEventEnabled=true;
}
else {
setTimeout(function() {
// change value after the end of the display transistion of the newly built thumbnails
G.galleryResizeEventEnabled=true;
}, nbBuild*G.tn.displayInterval);
}
// G.$E.base.trigger('galleryDisplayed.nanogallery2', new Event('galleryDisplayed.nanogallery2'));
TriggerCustomEvent('galleryDisplayed');
} | function GalleryDisplay( forceTransition ) {
G.$E.conTn.css( G.CSStransformName , 'translateX('+0+'px)');
var nbTn=G.GOM.items.length;
G.GOM.itemsDisplayed=0;
var threshold = 50;
var cnt=0; // counter for delay between each thumbnail display
var vp=getViewport();
G.GOM.cache.viewport=vp;
var containerOffset=G.$E.conTnParent.offset();
G.GOM.cache.containerOffset=containerOffset;
GalleryRenderGetInterval();
for( var i=0; i < nbTn ; i++ ) {
var curTn=G.GOM.items[i];
if( i >= G.GOM.displayInterval.from && cnt < G.GOM.displayInterval.len ) {
curTn.inDisplayArea=true;
if( forceTransition ) {
curTn.neverDisplayed=true;
}
G.GOM.itemsDisplayed++;
cnt++;
}
else{
curTn.inDisplayArea=false;
}
}
// bottom of the gallery (pagination, more button...)
GalleryBottomManage();
var tnToDisplay = [];
var tnToReDisplay = [];
G.GOM.clipArea.top=-1;
cnt=0;
var lastTnIdx=-1;
G.GOM.clipArea.height=0;
// NOTE: loop always the whole GOM.items --> in case an already displayed thumbnail needs to be removed
for( var i=0; i < nbTn ; i++ ) {
var curTn=G.GOM.items[i];
if( curTn.inDisplayArea ) {
if( G.GOM.clipArea.top == - 1 ) {
G.GOM.clipArea.top=curTn.top;
}
G.GOM.clipArea.height=Math.max(G.GOM.clipArea.height, curTn.top-G.GOM.clipArea.top+curTn.height);
if( curTn.neverDisplayed ) {
// thumbnail is not displayed -> check if in viewport to display or not
var top=containerOffset.top+(curTn.top-G.GOM.clipArea.top);
// var left=containerOffset.left+curTn.left;
if( (top+curTn.height) >= (vp.t-threshold) && top <= (vp.t+vp.h+threshold) ) {
// build thumbnail
var item=G.I[curTn.thumbnailIdx];
if( item.$elt == null ) {
ThumbnailBuild( item, curTn.thumbnailIdx, i, (i+1)==nbTn );
}
tnToDisplay.push({idx:i, delay:cnt});
cnt++;
}
}
else {
tnToReDisplay.push({idx:i, delay:0});
}
// G.GOM.itemsDisplayed++;
lastTnIdx=i;
}
else {
curTn.displayed=false;
var item=G.I[curTn.thumbnailIdx];
if( item.$elt != null ){
item.$elt.css({ opacity: 0, display: 'none' });
}
}
}
var areaWidth=G.$E.conTnParent.width();
// set gallery area really used size
// if( G.GOM.displayArea.width != G.GOM.displayAreaLast.width || G.GOM.displayArea.height != G.GOM.displayAreaLast.height ) {
if( G.GOM.displayArea.width != G.GOM.displayAreaLast.width || G.GOM.clipArea.height != G.GOM.displayAreaLast.height ) {
G.$E.conTn.width(G.GOM.displayArea.width).height(G.GOM.clipArea.height);
G.GOM.displayAreaLast.width=G.GOM.displayArea.width;
G.GOM.displayAreaLast.height=G.GOM.clipArea.height;
// G.GOM.displayAreaLast.height=G.GOM.displayArea.height-G.GOM.clipArea.top;
}
if( areaWidth != G.$E.conTnParent.width() ) {
// gallery area width changed since layout calculation (for example when a scrollbar appeared)
// so we need re-calculate the layout before displaying the thumbnails
GallerySetLayout();
GalleryDisplay( forceTransition );
}
// counter of not displayed images (is displayed on the last thumbnail)
if( G.layout.support.rows ) {
if( G.galleryDisplayMode.Get() == 'ROWS' || (G.galleryDisplayMode.Get() == 'FULLCONTENT' && G.galleryLastRowFull.Get() && G.GOM.lastFullRow != -1) ){
if( lastTnIdx < (nbTn-1) ) {
G.GOM.lastDisplayedIdxNew=lastTnIdx;
}
else {
G.GOM.lastDisplayedIdxNew=-1;
}
// remove last displayed counter
if( G.GOM.lastDisplayedIdx != -1 ) {
var item=G.I[G.GOM.items[G.GOM.lastDisplayedIdx].thumbnailIdx];
item.$getElt('.nGY2GThumbnailIconsFullThumbnail').html('');
}
}
}
// batch set position (and display animation) to all thumbnails
// first display newly built thumbnails
var nbBuild=tnToDisplay.length;
for( var i=0; i < nbBuild ; i++ ) {
ThumbnailSetPosition(tnToDisplay[i].idx,tnToDisplay[i].delay+10);
}
// then re-position already displayed thumbnails
var n=tnToReDisplay.length;
for( var i=0; i < n ; i++ ) {
ThumbnailSetPosition(tnToReDisplay[i].idx,nbBuild+1);
}
if( G.tn.displayTransition == 'NONE' ) {
G.galleryResizeEventEnabled=true;
}
else {
setTimeout(function() {
// change value after the end of the display transistion of the newly built thumbnails
G.galleryResizeEventEnabled=true;
}, nbBuild*G.tn.displayInterval);
}
// G.$E.base.trigger('galleryDisplayed.nanogallery2', new Event('galleryDisplayed.nanogallery2'));
TriggerCustomEvent('galleryDisplayed');
} |
JavaScript | function ThumbnailGetAnnotationHeight() {
var newElt= [],
newEltIdx= 0;
// if( G.O.thumbnailLabel.get('display') == false && G.tn.toolbar.getWidth(item) <= 0 ) {
if( G.O.thumbnailLabel.get('display') == false ) {
return 0;
}
var desc='';
if( G.O.thumbnailLabel.get('displayDescription') == true ) {
desc='aAzZjJ';
}
// visibility set to hidden
newElt[newEltIdx++]='<div class="nGY2GThumbnail '+G.O.theme+'" style="display:block;visibility:hidden;position:absolute;top:-9999px;left:-9999px;" ><div class="nGY2GThumbnailSub">';
if( G.O.thumbnailLabel.get('display') == true ) {
// Labels: title and description
newElt[newEltIdx++]= ' <div class="nGY2GThumbnailLabel" '+ G.tn.style.getLabel() +'>';
newElt[newEltIdx++]= ' <div class="nGY2GThumbnailAlbumTitle" '+G.tn.style.getTitle()+'>aAzZjJ</div>';
newElt[newEltIdx++]= ' <div class="nGY2GThumbnailDescription" '+G.tn.style.getDesc()+'>'+desc+'</div>';
newElt[newEltIdx++]= ' </div>';
}
newElt[newEltIdx++]='</div></div>';
// var $newDiv =jQuery(newElt.join('')).appendTo('body');
var $newDiv =jQuery(newElt.join('')).appendTo(G.$E.conTn);
var h=$newDiv.find('.nGY2GThumbnailLabel').outerHeight(true);
$newDiv.remove();
return h;
} | function ThumbnailGetAnnotationHeight() {
var newElt= [],
newEltIdx= 0;
// if( G.O.thumbnailLabel.get('display') == false && G.tn.toolbar.getWidth(item) <= 0 ) {
if( G.O.thumbnailLabel.get('display') == false ) {
return 0;
}
var desc='';
if( G.O.thumbnailLabel.get('displayDescription') == true ) {
desc='aAzZjJ';
}
// visibility set to hidden
newElt[newEltIdx++]='<div class="nGY2GThumbnail '+G.O.theme+'" style="display:block;visibility:hidden;position:absolute;top:-9999px;left:-9999px;" ><div class="nGY2GThumbnailSub">';
if( G.O.thumbnailLabel.get('display') == true ) {
// Labels: title and description
newElt[newEltIdx++]= ' <div class="nGY2GThumbnailLabel" '+ G.tn.style.getLabel() +'>';
newElt[newEltIdx++]= ' <div class="nGY2GThumbnailAlbumTitle" '+G.tn.style.getTitle()+'>aAzZjJ</div>';
newElt[newEltIdx++]= ' <div class="nGY2GThumbnailDescription" '+G.tn.style.getDesc()+'>'+desc+'</div>';
newElt[newEltIdx++]= ' </div>';
}
newElt[newEltIdx++]='</div></div>';
// var $newDiv =jQuery(newElt.join('')).appendTo('body');
var $newDiv =jQuery(newElt.join('')).appendTo(G.$E.conTn);
var h=$newDiv.find('.nGY2GThumbnailLabel').outerHeight(true);
$newDiv.remove();
return h;
} |
JavaScript | function ThumbnailBuildAlbumpUp( item, idx, GOMidx ) {
var newElt= [],
newEltIdx= 0;
newElt[newEltIdx++]='<div class="nGY2GThumbnail" style="display:none;opacity:0;" >';
newElt[newEltIdx++]=' <div class="nGY2GThumbnailSub">';
var h=G.tn.defaultSize.getHeight(),
w=G.tn.defaultSize.getWidth();
newElt[newEltIdx++]=' <div class="nGY2GThumbnailImage" style="width:'+w+'px;height:'+h+'px;"><img class="nGY2GThumbnailImg" src="'+G.emptyGif+'" alt="" style="max-width:'+w+'px;max-height:'+h+'px;" ></div>';
newElt[newEltIdx++]=' <div class="nGY2GThumbnailAlbumUp" style="width:'+w+'px;height:'+h+'px;">'+G.O.icons.thumbnailAlbumUp+'</div>';
newElt[newEltIdx++]=' </div>';
newElt[newEltIdx++]='</div>';
var $newDiv =jQuery(newElt.join('')).appendTo(G.$E.conTn); //.animate({ opacity: 1},1000, 'swing'); //.show('slow'); //.fadeIn('slow').slideDown('slow');
item.$elt=$newDiv;
$newDiv.data('index',GOMidx);
item.$getElt('.nGY2GThumbnailImg').data('index',GOMidx);
return;
} | function ThumbnailBuildAlbumpUp( item, idx, GOMidx ) {
var newElt= [],
newEltIdx= 0;
newElt[newEltIdx++]='<div class="nGY2GThumbnail" style="display:none;opacity:0;" >';
newElt[newEltIdx++]=' <div class="nGY2GThumbnailSub">';
var h=G.tn.defaultSize.getHeight(),
w=G.tn.defaultSize.getWidth();
newElt[newEltIdx++]=' <div class="nGY2GThumbnailImage" style="width:'+w+'px;height:'+h+'px;"><img class="nGY2GThumbnailImg" src="'+G.emptyGif+'" alt="" style="max-width:'+w+'px;max-height:'+h+'px;" ></div>';
newElt[newEltIdx++]=' <div class="nGY2GThumbnailAlbumUp" style="width:'+w+'px;height:'+h+'px;">'+G.O.icons.thumbnailAlbumUp+'</div>';
newElt[newEltIdx++]=' </div>';
newElt[newEltIdx++]='</div>';
var $newDiv =jQuery(newElt.join('')).appendTo(G.$E.conTn); //.animate({ opacity: 1},1000, 'swing'); //.show('slow'); //.fadeIn('slow').slideDown('slow');
item.$elt=$newDiv;
$newDiv.data('index',GOMidx);
item.$getElt('.nGY2GThumbnailImg').data('index',GOMidx);
return;
} |
JavaScript | function NbThumbnailsPerRow(areaWidth) {
var tnW=G.tn.defaultSize.getOuterWidth();
var nbMaxTn=0;
if( G.O.thumbnailAlignment == 'justified' ) {
nbMaxTn=Math.floor((areaWidth)/(tnW));
}
else {
nbMaxTn=Math.floor((areaWidth+G.O.thumbnailGutterWidth)/(tnW+G.O.thumbnailGutterWidth));
}
if( G.O.maxItemsPerLine >0 && nbMaxTn > G.O.maxItemsPerLine ) {
nbMaxTn=G.O.maxItemsPerLine;
}
if( nbMaxTn < 1 ) { nbMaxTn=1; }
return nbMaxTn
} | function NbThumbnailsPerRow(areaWidth) {
var tnW=G.tn.defaultSize.getOuterWidth();
var nbMaxTn=0;
if( G.O.thumbnailAlignment == 'justified' ) {
nbMaxTn=Math.floor((areaWidth)/(tnW));
}
else {
nbMaxTn=Math.floor((areaWidth+G.O.thumbnailGutterWidth)/(tnW+G.O.thumbnailGutterWidth));
}
if( G.O.maxItemsPerLine >0 && nbMaxTn > G.O.maxItemsPerLine ) {
nbMaxTn=G.O.maxItemsPerLine;
}
if( nbMaxTn < 1 ) { nbMaxTn=1; }
return nbMaxTn
} |
JavaScript | function albumGetInfo( albumIdx, fnToCall ) {
var url='';
var kind='image';
//var albumIdx=NGY2Item.GetIdx(G, ID);
switch( G.O.kind ) {
case 'json':
// TODO
case 'flickr':
// TODO
case 'picasa':
case 'google':
case 'google2':
default:
url = G.Google.url() + 'user/'+G.O.userID+'/albumid/'+G.I[albumIdx].GetID()+'?alt=json&&max-results=1&fields=title';
break;
}
jQuery.ajaxSetup({ cache: false });
jQuery.support.cors = true;
var tId = setTimeout( function() {
// workaround to handle JSONP (cross-domain) errors
//PreloaderHide();
NanoAlert(G, 'Could not retrieve AJAX data...');
}, 60000 );
jQuery.getJSON(url, function(data, status, xhr) {
clearTimeout(tId);
//PreloaderHide();
fnToCall( G.I[albumIdx].GetID() );
})
.fail( function(jqxhr, textStatus, error) {
clearTimeout(tId);
//PreloaderHide();
var err = textStatus + ', ' + error;
NanoAlert('Could not retrieve ajax data: ' + err);
});
} | function albumGetInfo( albumIdx, fnToCall ) {
var url='';
var kind='image';
//var albumIdx=NGY2Item.GetIdx(G, ID);
switch( G.O.kind ) {
case 'json':
// TODO
case 'flickr':
// TODO
case 'picasa':
case 'google':
case 'google2':
default:
url = G.Google.url() + 'user/'+G.O.userID+'/albumid/'+G.I[albumIdx].GetID()+'?alt=json&&max-results=1&fields=title';
break;
}
jQuery.ajaxSetup({ cache: false });
jQuery.support.cors = true;
var tId = setTimeout( function() {
// workaround to handle JSONP (cross-domain) errors
//PreloaderHide();
NanoAlert(G, 'Could not retrieve AJAX data...');
}, 60000 );
jQuery.getJSON(url, function(data, status, xhr) {
clearTimeout(tId);
//PreloaderHide();
fnToCall( G.I[albumIdx].GetID() );
})
.fail( function(jqxhr, textStatus, error) {
clearTimeout(tId);
//PreloaderHide();
var err = textStatus + ', ' + error;
NanoAlert('Could not retrieve ajax data: ' + err);
});
} |
JavaScript | function AddToCart( idx ) {
// increment counter if already in shopping cart
var found=false;
for( var i=0; i<G.shoppingCart.length; i++ ) {
if( G.shoppingCart[i].idx == idx ) {
G.shoppingCart[i].cnt++;
if(typeof G.O.fnShoppingCartUpdated === 'function'){
G.O.fnShoppingCartUpdated(G.shoppingCart);
}
// G.$E.base.trigger('shoppingCartUpdated.nanogallery2', new Event('shoppingCartUpdated.nanogallery2'));
TriggerCustomEvent('shoppingCartUpdated');
return;
}
}
// add to shopping cart
if( !found) {
G.shoppingCart.push( { idx:idx, ID:G.I[idx].GetID(), cnt:1} );
if(typeof G.O.fnShoppingCartUpdated === 'function'){
G.O.fnShoppingCartUpdated(G.shoppingCart);
}
// G.$E.base.trigger('shoppingCartUpdated.nanogallery2', new Event('shoppingCartUpdated.nanogallery2'));
TriggerCustomEvent('shoppingCartUpdated');
}
} | function AddToCart( idx ) {
// increment counter if already in shopping cart
var found=false;
for( var i=0; i<G.shoppingCart.length; i++ ) {
if( G.shoppingCart[i].idx == idx ) {
G.shoppingCart[i].cnt++;
if(typeof G.O.fnShoppingCartUpdated === 'function'){
G.O.fnShoppingCartUpdated(G.shoppingCart);
}
// G.$E.base.trigger('shoppingCartUpdated.nanogallery2', new Event('shoppingCartUpdated.nanogallery2'));
TriggerCustomEvent('shoppingCartUpdated');
return;
}
}
// add to shopping cart
if( !found) {
G.shoppingCart.push( { idx:idx, ID:G.I[idx].GetID(), cnt:1} );
if(typeof G.O.fnShoppingCartUpdated === 'function'){
G.O.fnShoppingCartUpdated(G.shoppingCart);
}
// G.$E.base.trigger('shoppingCartUpdated.nanogallery2', new Event('shoppingCartUpdated.nanogallery2'));
TriggerCustomEvent('shoppingCartUpdated');
}
} |
JavaScript | function PopupShare(idx) {
// SEE SAMPLES: https://gist.github.com/chrisjlee/5196139
// https://github.com/Julienh/Sharrre
var item=G.I[idx];
var currentURL=document.location.protocol +'//'+document.location.hostname + document.location.pathname;
var newLocationHash='#nanogallery/'+G.baseEltID+'/';
if( item.kind == 'image' ) {
newLocationHash+=item.albumID + '/' + item.GetID();
}
else {
newLocationHash+=item.GetID();
}
var content ='';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="facebook">'+G.O.icons.shareFacebook+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="pinterest">'+G.O.icons.sharePinterest+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="tumblr">'+G.O.icons.shareTumblr+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="twitter">'+G.O.icons.shareTwitter+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="googleplus">'+G.O.icons.shareGooglePlus+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="mail">'+G.O.icons.shareMail+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;"></div>';
content+='<input class="nGY2PopupOneItemText" readonly type="text" value="'+currentURL+newLocationHash+'" style="width:100%;text-align:center;">';
content+='<br>';
currentURL=encodeURIComponent(document.location.protocol +'//'+document.location.hostname + document.location.pathname + newLocationHash);
var currentTitle=item.title;
var currentTn=item.thumbImg().src;
Popup('Share to:', content, 'Center');
G.popup.$elt.find('.nGY2PopupOneItem').on('click', function(e) {
e.stopPropagation();
var shareURL='';
var found=true;
switch(jQuery(this).attr('data-share').toUpperCase()) {
case 'FACEBOOK':
// <a name="fb_share" type="button" href="http://www.facebook.com/sharer.php?u={$url}&media={$imgPath}&description={$desc}" class="joinFB">Share Your Advertise</a>
//window.open("https://www.facebook.com/sharer.php?u="+currentURL,"","height=368,width=600,left=100,top=100,menubar=0");
shareURL='https://www.facebook.com/sharer.php?u='+currentURL;
break;
case 'GOOGLE+':
shareURL="https://plus.google.com/share?url="+currentURL;
break;
case 'TWITTER':
// shareURL="https://twitter.com/share?url="+currentURL+"&text="+currentTitle;
shareURL='https://twitter.com/intent/tweet?text='+currentTitle+'url='+ currentURL;
break;
case 'PINTEREST':
// shareURL='https://pinterest.com/pin/create/bookmarklet/?media='+currentTn+'&url='+currentURL+'&description='+currentTitle;
shareURL='https://pinterest.com/pin/create/button/?media='+currentTn+'&url='+currentURL+'&description='+currentTitle;
break;
case 'TUMBLR':
//shareURL='https://www.tumblr.com/widgets/share/tool/preview?caption=<strong>'+currentTitle+'</strong>&tags=nanogallery2&url='+currentURL+'&shareSource=legacy&posttype=photo&content='+currentTn+'&clickthroughUrl='+currentURL;
shareURL='http://www.tumblr.com/share/link?url='+currentURL+'&name='+currentTitle;
break;
case 'MAIL':
shareURL='mailto:?subject='+currentTitle;+'&body='+ currentURL;
break;
default:
found=false;
break;
}
if( found ) {
window.open(shareURL,"","height=550,width=500,left=100,top=100,menubar=0"); window.open(shareURL,"","height=550,width=500,left=100,top=100,menubar=0");
G.popup.close();
// $popup.remove();
}
});
} | function PopupShare(idx) {
// SEE SAMPLES: https://gist.github.com/chrisjlee/5196139
// https://github.com/Julienh/Sharrre
var item=G.I[idx];
var currentURL=document.location.protocol +'//'+document.location.hostname + document.location.pathname;
var newLocationHash='#nanogallery/'+G.baseEltID+'/';
if( item.kind == 'image' ) {
newLocationHash+=item.albumID + '/' + item.GetID();
}
else {
newLocationHash+=item.GetID();
}
var content ='';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="facebook">'+G.O.icons.shareFacebook+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="pinterest">'+G.O.icons.sharePinterest+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="tumblr">'+G.O.icons.shareTumblr+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="twitter">'+G.O.icons.shareTwitter+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="googleplus">'+G.O.icons.shareGooglePlus+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;" data-share="mail">'+G.O.icons.shareMail+'</div>';
content+='<div class="nGY2PopupOneItem" style="text-align:center;"></div>';
content+='<input class="nGY2PopupOneItemText" readonly type="text" value="'+currentURL+newLocationHash+'" style="width:100%;text-align:center;">';
content+='<br>';
currentURL=encodeURIComponent(document.location.protocol +'//'+document.location.hostname + document.location.pathname + newLocationHash);
var currentTitle=item.title;
var currentTn=item.thumbImg().src;
Popup('Share to:', content, 'Center');
G.popup.$elt.find('.nGY2PopupOneItem').on('click', function(e) {
e.stopPropagation();
var shareURL='';
var found=true;
switch(jQuery(this).attr('data-share').toUpperCase()) {
case 'FACEBOOK':
// <a name="fb_share" type="button" href="http://www.facebook.com/sharer.php?u={$url}&media={$imgPath}&description={$desc}" class="joinFB">Share Your Advertise</a>
//window.open("https://www.facebook.com/sharer.php?u="+currentURL,"","height=368,width=600,left=100,top=100,menubar=0");
shareURL='https://www.facebook.com/sharer.php?u='+currentURL;
break;
case 'GOOGLE+':
shareURL="https://plus.google.com/share?url="+currentURL;
break;
case 'TWITTER':
// shareURL="https://twitter.com/share?url="+currentURL+"&text="+currentTitle;
shareURL='https://twitter.com/intent/tweet?text='+currentTitle+'url='+ currentURL;
break;
case 'PINTEREST':
// shareURL='https://pinterest.com/pin/create/bookmarklet/?media='+currentTn+'&url='+currentURL+'&description='+currentTitle;
shareURL='https://pinterest.com/pin/create/button/?media='+currentTn+'&url='+currentURL+'&description='+currentTitle;
break;
case 'TUMBLR':
//shareURL='https://www.tumblr.com/widgets/share/tool/preview?caption=<strong>'+currentTitle+'</strong>&tags=nanogallery2&url='+currentURL+'&shareSource=legacy&posttype=photo&content='+currentTn+'&clickthroughUrl='+currentURL;
shareURL='http://www.tumblr.com/share/link?url='+currentURL+'&name='+currentTitle;
break;
case 'MAIL':
shareURL='mailto:?subject='+currentTitle;+'&body='+ currentURL;
break;
default:
found=false;
break;
}
if( found ) {
window.open(shareURL,"","height=550,width=500,left=100,top=100,menubar=0"); window.open(shareURL,"","height=550,width=500,left=100,top=100,menubar=0");
G.popup.close();
// $popup.remove();
}
});
} |
JavaScript | function OpenOriginal( item ) {
switch( G.O.kind ) {
case 'json':
case 'flickr':
var sU='https://www.flickr.com/photos/'+G.O.userID+'/'+item.GetID();
window.open(sU,'_blank');
break;
case 'picasa':
case 'google':
case 'google2':
var sU='https://plus.google.com/photos/'+G.O.userID+'/albums/'+item.albumID+'/'+item.GetID();
window.open(sU,'_blank');
break;
default:
break;
}
} | function OpenOriginal( item ) {
switch( G.O.kind ) {
case 'json':
case 'flickr':
var sU='https://www.flickr.com/photos/'+G.O.userID+'/'+item.GetID();
window.open(sU,'_blank');
break;
case 'picasa':
case 'google':
case 'google2':
var sU='https://plus.google.com/photos/'+G.O.userID+'/albums/'+item.albumID+'/'+item.GetID();
window.open(sU,'_blank');
break;
default:
break;
}
} |
JavaScript | function DisplayPhotoIdx( imageIdx ) {
if( !G.O.thumbnailOpenImage ) { return; }
if( G.O.thumbnailOpenOriginal ) {
// Open link to original image
OpenOriginal( G.I[imageIdx] );
return;
}
var items=[];
// G.VOM.currItemIdx=imageIdx;
G.VOM.currItemIdx=0;
G.VOM.items=[];
G.VOM.albumID=G.I[imageIdx].albumID;
var vimg=new VImg(imageIdx);
G.VOM.items.push(vimg);
items.push(G.I[imageIdx]);
//TODO -> danger -> pourquoi reconstruire la liste si d�j� ouvert (back/forward)
var l=G.I.length;
for( var idx=imageIdx+1; idx<l ; idx++) {
var item=G.I[idx];
if( item.kind == 'image' && item.albumID == G.VOM.albumID && item.checkTagFilter() && item.isSearchFound() && item.destinationURL == '' ) {
var vimg=new VImg(idx);
G.VOM.items.push(vimg);
items.push(item);
}
}
var last=G.VOM.items.length;
var cnt=1;
for( var idx=0; idx<imageIdx ; idx++) {
var item=G.I[idx];
if( item.kind == 'image' && item.albumID == G.VOM.albumID && item.checkTagFilter() && item.isSearchFound() && item.destinationURL == '' ) {
var vimg=new VImg(idx);
vimg.imageNumber=cnt;
G.VOM.items.push(vimg);
items.push(item);
cnt++;
}
}
for( var i=0; i<last; i++ ) {
G.VOM.items[i].imageNumber=cnt;
cnt++;
}
if( typeof G.O.fnThumbnailOpen == 'function' ) {
// opens image with external viewer
G.O.fnThumbnailOpen(items);
return;
}
if( !G.VOM.viewerDisplayed ) {
// build and display
OpenInternalViewer(0);
}
else {
// display
// DisplayInternalViewer(imageIdx, '');
G.VOM.$imgC.css({ opacity:0, left:0, visibility:'hidden' }).attr('src','');
G.VOM.$imgC.children().eq(0).attr('src',G.emptyGif).attr('src',G.VOM.Item(0).responsiveURL());
DisplayInternalViewer(0, '');
}
} | function DisplayPhotoIdx( imageIdx ) {
if( !G.O.thumbnailOpenImage ) { return; }
if( G.O.thumbnailOpenOriginal ) {
// Open link to original image
OpenOriginal( G.I[imageIdx] );
return;
}
var items=[];
// G.VOM.currItemIdx=imageIdx;
G.VOM.currItemIdx=0;
G.VOM.items=[];
G.VOM.albumID=G.I[imageIdx].albumID;
var vimg=new VImg(imageIdx);
G.VOM.items.push(vimg);
items.push(G.I[imageIdx]);
//TODO -> danger -> pourquoi reconstruire la liste si d�j� ouvert (back/forward)
var l=G.I.length;
for( var idx=imageIdx+1; idx<l ; idx++) {
var item=G.I[idx];
if( item.kind == 'image' && item.albumID == G.VOM.albumID && item.checkTagFilter() && item.isSearchFound() && item.destinationURL == '' ) {
var vimg=new VImg(idx);
G.VOM.items.push(vimg);
items.push(item);
}
}
var last=G.VOM.items.length;
var cnt=1;
for( var idx=0; idx<imageIdx ; idx++) {
var item=G.I[idx];
if( item.kind == 'image' && item.albumID == G.VOM.albumID && item.checkTagFilter() && item.isSearchFound() && item.destinationURL == '' ) {
var vimg=new VImg(idx);
vimg.imageNumber=cnt;
G.VOM.items.push(vimg);
items.push(item);
cnt++;
}
}
for( var i=0; i<last; i++ ) {
G.VOM.items[i].imageNumber=cnt;
cnt++;
}
if( typeof G.O.fnThumbnailOpen == 'function' ) {
// opens image with external viewer
G.O.fnThumbnailOpen(items);
return;
}
if( !G.VOM.viewerDisplayed ) {
// build and display
OpenInternalViewer(0);
}
else {
// display
// DisplayInternalViewer(imageIdx, '');
G.VOM.$imgC.css({ opacity:0, left:0, visibility:'hidden' }).attr('src','');
G.VOM.$imgC.children().eq(0).attr('src',G.emptyGif).attr('src',G.VOM.Item(0).responsiveURL());
DisplayInternalViewer(0, '');
}
} |
JavaScript | function ViewerToolsAction(e) {
var $this=$(this);
var ngy2action=$this.data('ngy2action');
switch( ngy2action ) {
case 'next':
e.stopPropagation();
e.preventDefault();
DisplayNextImage();
break;
case 'previous':
e.stopPropagation();
e.preventDefault();
DisplayPreviousImage();
break;
case 'playPause':
e.stopPropagation();
SlideshowToggle();
break;
case 'zoomIn':
e.stopPropagation();
e.preventDefault();
if( ViewerZoomStart() ) {
ViewerZoomIn( true );
}
break;
case 'zoomOut':
e.stopPropagation();
e.preventDefault();
if( ViewerZoomStart() ) {
ViewerZoomIn( false );
}
break;
case 'minimize':
// toggle toolbar visibility
e.stopPropagation();
e.preventDefault();
if( G.VOM.toolbarMode == 'std' ) {
ViewerToolbarForVisibilityMin();
}
else {
ViewerToolbarForVisibilityStd();
}
break;
case 'fullScreen':
// Toggle viewer fullscreen mode on/off
e.stopPropagation();
if( G.supportFullscreenAPI ) {
if( ngscreenfull.enabled ) {
ngscreenfull.toggle();
if( G.VOM.viewerIsFullscreen ) {
G.VOM.viewerIsFullscreen=false;
G.VOM.$viewer.find('.fullscreenButton').html(G.O.icons.viewerFullscreenOff);
}
else {
G.VOM.viewerIsFullscreen=true;
G.VOM.$viewer.find('.fullscreenButton').html(G.O.icons.viewerFullscreenOn);
}
}
}
break;
case 'info':
e.stopPropagation();
// if( typeof G.O.fnViewerInfo == 'function' ) {
// G.O.fnViewerInfo(G.VOM.Item(G.VOM.currItemIdx), ExposedObjects());
// }
ItemDisplayInfo(G.VOM.Item(G.VOM.currItemIdx));
break;
case 'close':
e.stopPropagation();
e.preventDefault();
if( (new Date().getTime()) - G.VOM.timeImgChanged < 400 ) { return; }
CloseInternalViewer(G.VOM.currItemIdx);
break;
case 'download':
e.stopPropagation();
e.preventDefault();
DownloadImage(G.VOM.items[G.VOM.currItemIdx].imageIdx);
break;
case 'share':
e.stopPropagation();
e.preventDefault();
PopupShare(G.VOM.items[G.VOM.currItemIdx].imageIdx);
break;
case 'custom':
e.stopPropagation();
e.preventDefault();
PopupShare(G.VOM.items[G.VOM.currItemIdx].imageIdx);
break;
case 'linkOriginal':
// $closeB.on( (G.isIOS ? "touchstart" : "click") ,function(e){ // IPAD
e.stopPropagation();
e.preventDefault();
OpenOriginal( G.VOM.Item(G.VOM.currItemIdx) );
if( G.O.kind == 'google' || G.O.kind == 'google2') {
var sU='https://plus.google.com/photos/'+G.O.userID+'/albums/'+G.VOM.Item(G.VOM.currItemIdx).albumID+'/'+G.VOM.Item(G.VOM.currItemIdx).GetID();
window.open(sU,'_blank');
}
if( G.O.kind == 'flickr') {
var sU='https://www.flickr.com/photos/'+G.O.userID+'/'+G.VOM.Item(G.VOM.currItemIdx).GetID();
window.open(sU,'_blank');
}
break;
}
// custom button
if( ngy2action.indexOf('custom') == 0 && typeof G.O.fnImgToolbarCustClick == 'function') {
// var n=ngy2action.substring(6);
G.O.fnImgToolbarCustClick(ngy2action, $this, G.VOM.Item(G.VOM.currItemIdx));
}
} | function ViewerToolsAction(e) {
var $this=$(this);
var ngy2action=$this.data('ngy2action');
switch( ngy2action ) {
case 'next':
e.stopPropagation();
e.preventDefault();
DisplayNextImage();
break;
case 'previous':
e.stopPropagation();
e.preventDefault();
DisplayPreviousImage();
break;
case 'playPause':
e.stopPropagation();
SlideshowToggle();
break;
case 'zoomIn':
e.stopPropagation();
e.preventDefault();
if( ViewerZoomStart() ) {
ViewerZoomIn( true );
}
break;
case 'zoomOut':
e.stopPropagation();
e.preventDefault();
if( ViewerZoomStart() ) {
ViewerZoomIn( false );
}
break;
case 'minimize':
// toggle toolbar visibility
e.stopPropagation();
e.preventDefault();
if( G.VOM.toolbarMode == 'std' ) {
ViewerToolbarForVisibilityMin();
}
else {
ViewerToolbarForVisibilityStd();
}
break;
case 'fullScreen':
// Toggle viewer fullscreen mode on/off
e.stopPropagation();
if( G.supportFullscreenAPI ) {
if( ngscreenfull.enabled ) {
ngscreenfull.toggle();
if( G.VOM.viewerIsFullscreen ) {
G.VOM.viewerIsFullscreen=false;
G.VOM.$viewer.find('.fullscreenButton').html(G.O.icons.viewerFullscreenOff);
}
else {
G.VOM.viewerIsFullscreen=true;
G.VOM.$viewer.find('.fullscreenButton').html(G.O.icons.viewerFullscreenOn);
}
}
}
break;
case 'info':
e.stopPropagation();
// if( typeof G.O.fnViewerInfo == 'function' ) {
// G.O.fnViewerInfo(G.VOM.Item(G.VOM.currItemIdx), ExposedObjects());
// }
ItemDisplayInfo(G.VOM.Item(G.VOM.currItemIdx));
break;
case 'close':
e.stopPropagation();
e.preventDefault();
if( (new Date().getTime()) - G.VOM.timeImgChanged < 400 ) { return; }
CloseInternalViewer(G.VOM.currItemIdx);
break;
case 'download':
e.stopPropagation();
e.preventDefault();
DownloadImage(G.VOM.items[G.VOM.currItemIdx].imageIdx);
break;
case 'share':
e.stopPropagation();
e.preventDefault();
PopupShare(G.VOM.items[G.VOM.currItemIdx].imageIdx);
break;
case 'custom':
e.stopPropagation();
e.preventDefault();
PopupShare(G.VOM.items[G.VOM.currItemIdx].imageIdx);
break;
case 'linkOriginal':
// $closeB.on( (G.isIOS ? "touchstart" : "click") ,function(e){ // IPAD
e.stopPropagation();
e.preventDefault();
OpenOriginal( G.VOM.Item(G.VOM.currItemIdx) );
if( G.O.kind == 'google' || G.O.kind == 'google2') {
var sU='https://plus.google.com/photos/'+G.O.userID+'/albums/'+G.VOM.Item(G.VOM.currItemIdx).albumID+'/'+G.VOM.Item(G.VOM.currItemIdx).GetID();
window.open(sU,'_blank');
}
if( G.O.kind == 'flickr') {
var sU='https://www.flickr.com/photos/'+G.O.userID+'/'+G.VOM.Item(G.VOM.currItemIdx).GetID();
window.open(sU,'_blank');
}
break;
}
// custom button
if( ngy2action.indexOf('custom') == 0 && typeof G.O.fnImgToolbarCustClick == 'function') {
// var n=ngy2action.substring(6);
G.O.fnImgToolbarCustClick(ngy2action, $this, G.VOM.Item(G.VOM.currItemIdx));
}
} |
JavaScript | function ImageSwipeTranslateX( posX ) {
G.VOM.swipePosX=posX;
if( G.CSStransformName == null ) {
G.VOM.$imgC.css({ left: posX });
}
else {
G.VOM.$imgC[0].style[G.CSStransformName]= 'translateX('+posX+'px)';
if( G.O.imageTransition == 'swipe' ) {
if( posX > 0 ) {
var $new=G.VOM.$imgP;
// var dir=getViewport().w;
var dir=G.VOM.$viewer.width();
G.VOM.$imgP.css({visibility:'visible', left:0, opacity:1});
G.VOM.$imgP[0].style[G.CSStransformName]= 'translateX('+(-dir+posX)+'px) '
G.VOM.$imgN[0].style[G.CSStransformName]= 'translateX('+(-dir)+'px) '
}
else {
var $new=G.VOM.$imgN;
// var dir=-getViewport().w;
var dir=-G.VOM.$viewer.width();
G.VOM.$imgN.css({visibility:'visible', left:0, opacity:1});
G.VOM.$imgN[0].style[G.CSStransformName]= 'translateX('+(-dir+posX)+'px) '
G.VOM.$imgP[0].style[G.CSStransformName]= 'translateX('+(-dir)+'px) '
}
}
}
} | function ImageSwipeTranslateX( posX ) {
G.VOM.swipePosX=posX;
if( G.CSStransformName == null ) {
G.VOM.$imgC.css({ left: posX });
}
else {
G.VOM.$imgC[0].style[G.CSStransformName]= 'translateX('+posX+'px)';
if( G.O.imageTransition == 'swipe' ) {
if( posX > 0 ) {
var $new=G.VOM.$imgP;
// var dir=getViewport().w;
var dir=G.VOM.$viewer.width();
G.VOM.$imgP.css({visibility:'visible', left:0, opacity:1});
G.VOM.$imgP[0].style[G.CSStransformName]= 'translateX('+(-dir+posX)+'px) '
G.VOM.$imgN[0].style[G.CSStransformName]= 'translateX('+(-dir)+'px) '
}
else {
var $new=G.VOM.$imgN;
// var dir=-getViewport().w;
var dir=-G.VOM.$viewer.width();
G.VOM.$imgN.css({visibility:'visible', left:0, opacity:1});
G.VOM.$imgN[0].style[G.CSStransformName]= 'translateX('+(-dir+posX)+'px) '
G.VOM.$imgP[0].style[G.CSStransformName]= 'translateX('+(-dir)+'px) '
}
}
}
} |
JavaScript | function ProcessLocationHash() {
// standard use case -> location hash processing
if( !G.O.locationHash ) { return false; }
var curGal='#nanogallery/'+G.baseEltID+'/',
newLocationHash=location.hash;
console.log('newLocationHash1: ' +newLocationHash);
console.log('G.locationHashLastUsed: ' +G.locationHashLastUsed);
if( newLocationHash == '' ) {
if( G.GOM.lastDisplayedIdx != -1 ) {
// back button and no hash --> display first album
G.locationHashLastUsed='';
DisplayAlbum( '', '0');
return true;
}
}
if( newLocationHash == G.locationHashLastUsed ) { return; }
if( newLocationHash.indexOf(curGal) == 0 ) {
// item IDs detected
var IDs=parseIDs( newLocationHash.substring(curGal.length) );
if( IDs.imageID != '0' ) {
console.log('display: ' + IDs.albumID +'-'+ IDs.imageID );
DisplayPhoto( IDs.imageID, IDs.albumID );
return true;
}
else {
DisplayAlbum( '-1', IDs.albumID );
return true;
}
}
return false;
} | function ProcessLocationHash() {
// standard use case -> location hash processing
if( !G.O.locationHash ) { return false; }
var curGal='#nanogallery/'+G.baseEltID+'/',
newLocationHash=location.hash;
console.log('newLocationHash1: ' +newLocationHash);
console.log('G.locationHashLastUsed: ' +G.locationHashLastUsed);
if( newLocationHash == '' ) {
if( G.GOM.lastDisplayedIdx != -1 ) {
// back button and no hash --> display first album
G.locationHashLastUsed='';
DisplayAlbum( '', '0');
return true;
}
}
if( newLocationHash == G.locationHashLastUsed ) { return; }
if( newLocationHash.indexOf(curGal) == 0 ) {
// item IDs detected
var IDs=parseIDs( newLocationHash.substring(curGal.length) );
if( IDs.imageID != '0' ) {
console.log('display: ' + IDs.albumID +'-'+ IDs.imageID );
DisplayPhoto( IDs.imageID, IDs.albumID );
return true;
}
else {
DisplayAlbum( '-1', IDs.albumID );
return true;
}
}
return false;
} |
JavaScript | function SetLocationHash(albumID, imageID ) {
if( !G.O.locationHash ) { return false; }
if( albumID == '-1' || albumID == '0' ) {
// root album level --> do not set top.location.hash if not already set
if( location.hash != '' ) {
// try to clear the hash if set
if ("pushState" in history) {
history.pushState("", document.title, window.location.pathname + window.location.search);
}
else {
location.hash='';
}
}
G.locationHashLastUsed='';
return;
}
var newLocationHash='#'+'nanogallery/'+G.baseEltID+'/'+ albumID;
if( imageID != '' ) {
newLocationHash+='/'+imageID;
}
var lH=location.hash;
console.log('newLocationHash2: '+newLocationHash);
console.log('lH: '+lH);
if( lH == '' || lH != newLocationHash ) {
// G.locationHashLastUsed='#'+newLocationHash;
G.locationHashLastUsed=newLocationHash;
console.log('new G.locationHashLastUsed: '+G.locationHashLastUsed);
try {
top.location.hash=newLocationHash;
}
catch(e) {
// location hash is not supported by current browser --> disable the option
G.O.locationHash=false;
}
}
} | function SetLocationHash(albumID, imageID ) {
if( !G.O.locationHash ) { return false; }
if( albumID == '-1' || albumID == '0' ) {
// root album level --> do not set top.location.hash if not already set
if( location.hash != '' ) {
// try to clear the hash if set
if ("pushState" in history) {
history.pushState("", document.title, window.location.pathname + window.location.search);
}
else {
location.hash='';
}
}
G.locationHashLastUsed='';
return;
}
var newLocationHash='#'+'nanogallery/'+G.baseEltID+'/'+ albumID;
if( imageID != '' ) {
newLocationHash+='/'+imageID;
}
var lH=location.hash;
console.log('newLocationHash2: '+newLocationHash);
console.log('lH: '+lH);
if( lH == '' || lH != newLocationHash ) {
// G.locationHashLastUsed='#'+newLocationHash;
G.locationHashLastUsed=newLocationHash;
console.log('new G.locationHashLastUsed: '+G.locationHashLastUsed);
try {
top.location.hash=newLocationHash;
}
catch(e) {
// location hash is not supported by current browser --> disable the option
G.O.locationHash=false;
}
}
} |
JavaScript | function inViewport( $elt, threshold ) {
var wp=getViewport(),
eltOS=$elt.offset(),
th=$elt.outerHeight(true),
tw=$elt.outerWidth(true);
if( eltOS.top >= (wp.t-threshold)
&& (eltOS.top+th) <= (wp.t+wp.h+threshold)
&& eltOS.left >= (wp.l-threshold)
&& (eltOS.left+tw) <= (wp.l+wp.w+threshold) ) {
return true;
}
else {
return false;
}
} | function inViewport( $elt, threshold ) {
var wp=getViewport(),
eltOS=$elt.offset(),
th=$elt.outerHeight(true),
tw=$elt.outerWidth(true);
if( eltOS.top >= (wp.t-threshold)
&& (eltOS.top+th) <= (wp.t+wp.h+threshold)
&& eltOS.left >= (wp.l-threshold)
&& (eltOS.left+tw) <= (wp.l+wp.w+threshold) ) {
return true;
}
else {
return false;
}
} |
JavaScript | function inViewportVert( $elt, threshold ) {
var wp=getViewport(),
eltOS=$elt.offset(),
th=$elt.outerHeight(true),
tw=$elt.outerWidth(true);
if( wp.t == 0 && (eltOS.top) <= (wp.t+wp.h ) ) { return true; }
if( eltOS.top >= (wp.t)
&& (eltOS.top+th) <= (wp.t+wp.h-threshold) ) {
return true;
}
else {
return false;
}
} | function inViewportVert( $elt, threshold ) {
var wp=getViewport(),
eltOS=$elt.offset(),
th=$elt.outerHeight(true),
tw=$elt.outerWidth(true);
if( wp.t == 0 && (eltOS.top) <= (wp.t+wp.h ) ) { return true; }
if( eltOS.top >= (wp.t)
&& (eltOS.top+th) <= (wp.t+wp.h-threshold) ) {
return true;
}
else {
return false;
}
} |
JavaScript | function GoogleParseData(albumIdx, kind, data) {
var albumID=G.I[albumIdx].GetID();
if( G.I[albumIdx].title == '' ) {
// set title of the album (=> root level not loaded at this time)
G.I[albumIdx].title=data.feed.title.$t;
}
// iterate and parse each item
jQuery.each(data.feed.entry, function(i,data){
//Get the title
var imgUrl=data.media$group.media$content[0].url;
var itemTitle = data.title.$t;
//Get the description
var filename='';
var itemDescription = data.media$group.media$description.$t;
if( kind == 'image') {
// if image, the title contains the image filename -> replace with content of description
filename=itemTitle;
if( itemDescription != '' ) {
itemTitle=itemDescription;
itemDescription='';
}
if( G.O.thumbnailLabel.get('title') != '' ) {
// use filename for the title (extract from URL)
itemTitle=GetImageTitleFromURL(unescape(unescape(unescape(unescape(imgUrl)))));
}
}
var itemID = data.gphoto$id.$t;
if( !(kind == 'album' && !FilterAlbumName(itemTitle, itemID)) ) {
var newItem=NGY2Item.New( G, itemTitle, itemDescription, itemID, albumID, kind, '' );
// set the image src
var src='';
if( kind == 'image' ) {
src=imgUrl;
if( !G.O.viewerZoom && G.O.viewerZoom != undefined ) {
var s=imgUrl.substring(0, imgUrl.lastIndexOf('/'));
s=s.substring(0, s.lastIndexOf('/')) + '/';
if( window.screen.width > window.screen.height ) {
src=s+'w'+window.screen.width+'/'+filename;
}
else {
src=s+'h'+window.screen.height+'/'+filename;
}
}
newItem.src=src; // image's URL
// image size
newItem.imageWidth=parseInt(data.gphoto$width.$t);
newItem.imageHeight=parseInt(data.gphoto$height.$t);
if( data.media$group != null && data.media$group.media$credit != null && data.media$group.media$credit.length > 0 ) {
newItem.author=data.media$group.media$credit[0].$t;
}
// exif data
if( data.exif$tags.exif$exposure != undefined ) {
newItem.exif.exposure= data.exif$tags.exif$exposure.$t;
}
if( data.exif$tags.exif$flash != undefined ) {
if( data.exif$tags.exif$flash.$t == 'true' ) {
newItem.exif.flash= 'flash';
}
}
if( data.exif$tags.exif$focallength != undefined ) {
newItem.exif.focallength= data.exif$tags.exif$focallength.$t;
}
if( data.exif$tags.exif$fstop != undefined ) {
newItem.exif.fstop= data.exif$tags.exif$fstop.$t;
}
if( data.exif$tags.exif$iso != undefined ) {
newItem.exif.iso= data.exif$tags.exif$iso.$t;
}
if( data.exif$tags.exif$model != undefined ) {
newItem.exif.model= data.exif$tags.exif$model.$t;
}
// geo location
if( data.gphoto$location != undefined ) {
newItem.exif.location= data.gphoto$location;
}
}
else {
newItem.author=data.author[0].name.$t;
newItem.numberItems=data.gphoto$numphotos.$t;
}
// set the URL of the thumbnails images
newItem.thumbs=GoogleThumbSetSizes('l1', 0, newItem.thumbs, data, kind );
newItem.thumbs=GoogleThumbSetSizes('lN', 5, newItem.thumbs, data, kind );
if( typeof G.O.fnProcessData == 'function' ) {
G.O.fnProcessData(newItem, 'google', data);
}
}
});
G.I[albumIdx].contentIsLoaded=true; // album's content is ready
} | function GoogleParseData(albumIdx, kind, data) {
var albumID=G.I[albumIdx].GetID();
if( G.I[albumIdx].title == '' ) {
// set title of the album (=> root level not loaded at this time)
G.I[albumIdx].title=data.feed.title.$t;
}
// iterate and parse each item
jQuery.each(data.feed.entry, function(i,data){
//Get the title
var imgUrl=data.media$group.media$content[0].url;
var itemTitle = data.title.$t;
//Get the description
var filename='';
var itemDescription = data.media$group.media$description.$t;
if( kind == 'image') {
// if image, the title contains the image filename -> replace with content of description
filename=itemTitle;
if( itemDescription != '' ) {
itemTitle=itemDescription;
itemDescription='';
}
if( G.O.thumbnailLabel.get('title') != '' ) {
// use filename for the title (extract from URL)
itemTitle=GetImageTitleFromURL(unescape(unescape(unescape(unescape(imgUrl)))));
}
}
var itemID = data.gphoto$id.$t;
if( !(kind == 'album' && !FilterAlbumName(itemTitle, itemID)) ) {
var newItem=NGY2Item.New( G, itemTitle, itemDescription, itemID, albumID, kind, '' );
// set the image src
var src='';
if( kind == 'image' ) {
src=imgUrl;
if( !G.O.viewerZoom && G.O.viewerZoom != undefined ) {
var s=imgUrl.substring(0, imgUrl.lastIndexOf('/'));
s=s.substring(0, s.lastIndexOf('/')) + '/';
if( window.screen.width > window.screen.height ) {
src=s+'w'+window.screen.width+'/'+filename;
}
else {
src=s+'h'+window.screen.height+'/'+filename;
}
}
newItem.src=src; // image's URL
// image size
newItem.imageWidth=parseInt(data.gphoto$width.$t);
newItem.imageHeight=parseInt(data.gphoto$height.$t);
if( data.media$group != null && data.media$group.media$credit != null && data.media$group.media$credit.length > 0 ) {
newItem.author=data.media$group.media$credit[0].$t;
}
// exif data
if( data.exif$tags.exif$exposure != undefined ) {
newItem.exif.exposure= data.exif$tags.exif$exposure.$t;
}
if( data.exif$tags.exif$flash != undefined ) {
if( data.exif$tags.exif$flash.$t == 'true' ) {
newItem.exif.flash= 'flash';
}
}
if( data.exif$tags.exif$focallength != undefined ) {
newItem.exif.focallength= data.exif$tags.exif$focallength.$t;
}
if( data.exif$tags.exif$fstop != undefined ) {
newItem.exif.fstop= data.exif$tags.exif$fstop.$t;
}
if( data.exif$tags.exif$iso != undefined ) {
newItem.exif.iso= data.exif$tags.exif$iso.$t;
}
if( data.exif$tags.exif$model != undefined ) {
newItem.exif.model= data.exif$tags.exif$model.$t;
}
// geo location
if( data.gphoto$location != undefined ) {
newItem.exif.location= data.gphoto$location;
}
}
else {
newItem.author=data.author[0].name.$t;
newItem.numberItems=data.gphoto$numphotos.$t;
}
// set the URL of the thumbnails images
newItem.thumbs=GoogleThumbSetSizes('l1', 0, newItem.thumbs, data, kind );
newItem.thumbs=GoogleThumbSetSizes('lN', 5, newItem.thumbs, data, kind );
if( typeof G.O.fnProcessData == 'function' ) {
G.O.fnProcessData(newItem, 'google', data);
}
}
});
G.I[albumIdx].contentIsLoaded=true; // album's content is ready
} |
JavaScript | function FlickrParsePhotoSets( albumIdx, source ) {
var albumID=G.I[albumIdx].GetID();
// var source = data.photosets.photoset;
jQuery.each(source, function(i,item){
//Get the title
itemTitle = item.title._content;
if( FilterAlbumName(itemTitle, item.id) ) {
itemID=item.id;
//Get the description
itemDescription='';
if (item.description._content != undefined) {
itemDescription=item.description._content;
}
var sizes = {};
for (var p in item.primary_photo_extras) {
sizes[p]=item.primary_photo_extras[p];
}
tags='';
if( item.primary_photo_extras !== undefined ) {
if( item.primary_photo_extras.tags !== undefined ) {
tags=item.primary_photo_extras.tags;
}
}
var newItem=NGY2Item.New( G, itemTitle, itemDescription, itemID, albumID, 'album', tags );
newItem.numberItems=item.photos;
newItem.thumbSizes=sizes;
var tn = {
url: { l1 : { xs:'', sm:'', me:'', la:'', xl:'' }, lN : { xs:'', sm:'', me:'', la:'', xl:'' } },
width: { l1 : { xs:0, sm:0, me:0, la:0, xl:0 }, lN : { xs:0, sm:0, me:0, la:0, xl:0 } },
height: { l1 : { xs:0, sm:0, me:0, la:0, xl:0 }, lN : { xs:0, sm:0, me:0, la:0, xl:0 } }
};
tn=FlickrRetrieveImages(tn, item.primary_photo_extras, 'l1' );
tn=FlickrRetrieveImages(tn, item.primary_photo_extras, 'lN' );
newItem.thumbs=tn;
}
});
G.I[albumIdx].contentIsLoaded=true;
} | function FlickrParsePhotoSets( albumIdx, source ) {
var albumID=G.I[albumIdx].GetID();
// var source = data.photosets.photoset;
jQuery.each(source, function(i,item){
//Get the title
itemTitle = item.title._content;
if( FilterAlbumName(itemTitle, item.id) ) {
itemID=item.id;
//Get the description
itemDescription='';
if (item.description._content != undefined) {
itemDescription=item.description._content;
}
var sizes = {};
for (var p in item.primary_photo_extras) {
sizes[p]=item.primary_photo_extras[p];
}
tags='';
if( item.primary_photo_extras !== undefined ) {
if( item.primary_photo_extras.tags !== undefined ) {
tags=item.primary_photo_extras.tags;
}
}
var newItem=NGY2Item.New( G, itemTitle, itemDescription, itemID, albumID, 'album', tags );
newItem.numberItems=item.photos;
newItem.thumbSizes=sizes;
var tn = {
url: { l1 : { xs:'', sm:'', me:'', la:'', xl:'' }, lN : { xs:'', sm:'', me:'', la:'', xl:'' } },
width: { l1 : { xs:0, sm:0, me:0, la:0, xl:0 }, lN : { xs:0, sm:0, me:0, la:0, xl:0 } },
height: { l1 : { xs:0, sm:0, me:0, la:0, xl:0 }, lN : { xs:0, sm:0, me:0, la:0, xl:0 } }
};
tn=FlickrRetrieveImages(tn, item.primary_photo_extras, 'l1' );
tn=FlickrRetrieveImages(tn, item.primary_photo_extras, 'lN' );
newItem.thumbs=tn;
}
});
G.I[albumIdx].contentIsLoaded=true;
} |
JavaScript | function CreateHoldemDeck(suits, names) {
var cardStack = [];
suits.forEach(suit => {
var valueCounter = 0;
names.forEach(name => {
valueCounter++;
var card = Object.create(Card);
card.suit = suit;
card.name = name;
card.value = valueCounter;
cardStack.push(card);
});
});
return cardStack;
} | function CreateHoldemDeck(suits, names) {
var cardStack = [];
suits.forEach(suit => {
var valueCounter = 0;
names.forEach(name => {
valueCounter++;
var card = Object.create(Card);
card.suit = suit;
card.name = name;
card.value = valueCounter;
cardStack.push(card);
});
});
return cardStack;
} |
JavaScript | function shuffle(deck) {
var i = 0;
var j = 0;
var temp = null;
for (var i = deck.length - 1; i > 0; i--){
j = Math.floor(Math.random() * (i + 1));
temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
} | function shuffle(deck) {
var i = 0;
var j = 0;
var temp = null;
for (var i = deck.length - 1; i > 0; i--){
j = Math.floor(Math.random() * (i + 1));
temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
} |
JavaScript | function isStraight(fiveCardSet) {
var sortedValues = fiveCardSet
.map(item => item.value)
.sort((a, b) => a - b);
var checkLowStraight = (sortedValues[0] === 1 && sortedValues[1] === 2 && sortedValues[2] === 3 && sortedValues[3] === 4 && sortedValues[4] === 13);
var checkIncreasing = sortedValues
.reduce( (acc, item) =>
(item + 1 === acc) ? item : false, );
var checkDecreasing = sortedValues
.reduce( (acc, item) =>
(item - 1 === acc) ? item : false, );
return !!checkIncreasing || !!checkDecreasing || !!checkLowStraight;
} | function isStraight(fiveCardSet) {
var sortedValues = fiveCardSet
.map(item => item.value)
.sort((a, b) => a - b);
var checkLowStraight = (sortedValues[0] === 1 && sortedValues[1] === 2 && sortedValues[2] === 3 && sortedValues[3] === 4 && sortedValues[4] === 13);
var checkIncreasing = sortedValues
.reduce( (acc, item) =>
(item + 1 === acc) ? item : false, );
var checkDecreasing = sortedValues
.reduce( (acc, item) =>
(item - 1 === acc) ? item : false, );
return !!checkIncreasing || !!checkDecreasing || !!checkLowStraight;
} |
JavaScript | merge (set) {
var combined = []
if (Array.isArray(set)) {
combined = this.values.reduce(concatArrays, [])
} else {
combined = this.values.concat(set.values)
}
var uniques = EntrySet._uniques(combined)
var newSet = new EntrySet(uniques)
return newSet.sort()
} | merge (set) {
var combined = []
if (Array.isArray(set)) {
combined = this.values.reduce(concatArrays, [])
} else {
combined = this.values.concat(set.values)
}
var uniques = EntrySet._uniques(combined)
var newSet = new EntrySet(uniques)
return newSet.sort()
} |
JavaScript | difference (b) {
// Indices for quick lookups
var processed = {}
var existing = {}
// Create an index of the first collection
var addToIndex = e => existing[e.hash] = true
this.values.forEach(addToIndex)
// Reduce to entries that are not in the first collection
var reducer = (res, entry) => {
var isInFirst = existing[entry.hash] !== undefined
var hasBeenProcessed = processed[entry.hash] !== undefined
if (!isInFirst && !hasBeenProcessed) {
res.push(entry)
processed[entry.hash] = true
}
return res
}
var reduced = b.values.reduce(reducer, [])
return new EntrySet(reduced)
} | difference (b) {
// Indices for quick lookups
var processed = {}
var existing = {}
// Create an index of the first collection
var addToIndex = e => existing[e.hash] = true
this.values.forEach(addToIndex)
// Reduce to entries that are not in the first collection
var reducer = (res, entry) => {
var isInFirst = existing[entry.hash] !== undefined
var hasBeenProcessed = processed[entry.hash] !== undefined
if (!isInFirst && !hasBeenProcessed) {
res.push(entry)
processed[entry.hash] = true
}
return res
}
var reduced = b.values.reduce(reducer, [])
return new EntrySet(reduced)
} |
JavaScript | intersection (b) {
// Indices for quick lookups
var processed = {}
var existing = {}
// Create an index of the first collection
var addToIndex = e => existing[e.hash] = true
this.values.forEach(addToIndex)
// Reduce to entries that are not in the first collection
var reducer = (res, entry) => {
var isInFirst = existing[entry.hash] !== undefined
var hasBeenProcessed = processed[entry.hash] !== undefined
if (isInFirst && !hasBeenProcessed) {
res.push(entry)
processed[entry.hash] = true
}
return res
}
var reduced = b.values.reduce(reducer, [])
return new EntrySet(reduced)
} | intersection (b) {
// Indices for quick lookups
var processed = {}
var existing = {}
// Create an index of the first collection
var addToIndex = e => existing[e.hash] = true
this.values.forEach(addToIndex)
// Reduce to entries that are not in the first collection
var reducer = (res, entry) => {
var isInFirst = existing[entry.hash] !== undefined
var hasBeenProcessed = processed[entry.hash] !== undefined
if (isInFirst && !hasBeenProcessed) {
res.push(entry)
processed[entry.hash] = true
}
return res
}
var reduced = b.values.reduce(reducer, [])
return new EntrySet(reduced)
} |
JavaScript | static isSet (set) {
return set !== undefined
&& set.values !== undefined
&& Array.isArray(set.values)
} | static isSet (set) {
return set !== undefined
&& set.values !== undefined
&& Array.isArray(set.values)
} |
JavaScript | static findHeads (entries) {
var indexReducer = (res, entry, idx, arr) => {
var addToResult = e => res[e] = entry.hash
entry.next.forEach(addToResult)
return res
}
var items = entries.reduce(indexReducer, {})
var exists = e => items[e.hash] === undefined
var compareIds = (a, b) => a.id > b.id
return entries.filter(exists).sort(compareIds)
} | static findHeads (entries) {
var indexReducer = (res, entry, idx, arr) => {
var addToResult = e => res[e] = entry.hash
entry.next.forEach(addToResult)
return res
}
var items = entries.reduce(indexReducer, {})
var exists = e => items[e.hash] === undefined
var compareIds = (a, b) => a.id > b.id
return entries.filter(exists).sort(compareIds)
} |
JavaScript | static findTailHashes (entries) {
var hashes = {}
var addToIndex = (e) => hashes[e.hash] = true
var reduceTailHashes = (res, entry, idx, arr) => {
var addToResult = (e) => {
if (hashes[e] === undefined) {
res.splice(0, 0, e)
}
}
entry.next.reverse().forEach(addToResult)
return res
}
entries.forEach(addToIndex)
return entries.reduce(reduceTailHashes, [])
} | static findTailHashes (entries) {
var hashes = {}
var addToIndex = (e) => hashes[e.hash] = true
var reduceTailHashes = (res, entry, idx, arr) => {
var addToResult = (e) => {
if (hashes[e] === undefined) {
res.splice(0, 0, e)
}
}
entry.next.reverse().forEach(addToResult)
return res
}
entries.forEach(addToIndex)
return entries.reduce(reduceTailHashes, [])
} |
JavaScript | static _uniques (entries) {
const contains = (entries, entry) => {
var isEqual = e => Entry.isEqual(e, entry)
return entries.find(isEqual) !== undefined
}
const reducer = (result, entry, idx, arr) => {
if (!contains(result, entry)) {
result.push(entry)
}
return result
}
return entries.reduce(reducer, [])
} | static _uniques (entries) {
const contains = (entries, entry) => {
var isEqual = e => Entry.isEqual(e, entry)
return entries.find(isEqual) !== undefined
}
const reducer = (result, entry, idx, arr) => {
if (!contains(result, entry)) {
result.push(entry)
}
return result
}
return entries.reduce(reducer, [])
} |
JavaScript | _onMessage(dbname, heads) {
// console.log(".MESSAGE", dbname, heads)
const store = this.stores[dbname]
store.sync(heads)
} | _onMessage(dbname, heads) {
// console.log(".MESSAGE", dbname, heads)
const store = this.stores[dbname]
store.sync(heads)
} |
JavaScript | static isLog (log) {
return log.id !== undefined
&& log.heads !== undefined
&& log.values !== undefined
} | static isLog (log) {
return log.id !== undefined
&& log.heads !== undefined
&& log.values !== undefined
} |
JavaScript | load() {
this._cache = {}
return new Promise((resolve, reject) => {
this._store.exists(this.filename, (err, exists) => {
if (err || !exists) {
return resolve()
}
this._lock(this.filename, (release) => {
pull(
this._store.read(this.filename),
pull.collect(release((err, res) => {
if (err) {
return reject(err)
}
try {
this._cache = JSON.parse(Buffer.concat(res).toString() || '{}')
} catch(e) {
return reject(e)
}
resolve()
}))
)
})
})
})
} | load() {
this._cache = {}
return new Promise((resolve, reject) => {
this._store.exists(this.filename, (err, exists) => {
if (err || !exists) {
return resolve()
}
this._lock(this.filename, (release) => {
pull(
this._store.read(this.filename),
pull.collect(release((err, res) => {
if (err) {
return reject(err)
}
try {
this._cache = JSON.parse(Buffer.concat(res).toString() || '{}')
} catch(e) {
return reject(e)
}
resolve()
}))
)
})
})
})
} |
JavaScript | start (callback) {
if (this.started) {
return setImmediate(() => callback(new Error('already started')))
}
this.libp2p.handle(multicodec, this._onConnection)
// Speed up any new peer that comes in my way
this.libp2p.swarm.on('peer-mux-established', this._dialPeer)
// Dial already connected peers
const peerInfos = values(this.libp2p.peerBook.getAll())
asyncEach(peerInfos, (peerInfo, cb) => {
this._dialPeer(peerInfo, cb)
}, (err) => {
setImmediate(() => {
this.started = true
callback(err)
})
})
} | start (callback) {
if (this.started) {
return setImmediate(() => callback(new Error('already started')))
}
this.libp2p.handle(multicodec, this._onConnection)
// Speed up any new peer that comes in my way
this.libp2p.swarm.on('peer-mux-established', this._dialPeer)
// Dial already connected peers
const peerInfos = values(this.libp2p.peerBook.getAll())
asyncEach(peerInfos, (peerInfo, cb) => {
this._dialPeer(peerInfo, cb)
}, (err) => {
setImmediate(() => {
this.started = true
callback(err)
})
})
} |
JavaScript | stop (callback) {
if (!this.started) {
return setImmediate(() => callback(new Error('not started yet')))
}
this.libp2p.unhandle(multicodec)
this.libp2p.swarm.removeListener('peer-mux-established', this._dialPeer)
asyncEach(this.peers.values(), (peer, cb) => peer.close(cb), (err) => {
if (err) {
return callback(err)
}
this.peers = new Map()
this.started = false
callback()
})
} | stop (callback) {
if (!this.started) {
return setImmediate(() => callback(new Error('not started yet')))
}
this.libp2p.unhandle(multicodec)
this.libp2p.swarm.removeListener('peer-mux-established', this._dialPeer)
asyncEach(this.peers.values(), (peer, cb) => peer.close(cb), (err) => {
if (err) {
return callback(err)
}
this.peers = new Map()
this.started = false
callback()
})
} |
JavaScript | function JSONWindow() {
var x = window.open();
x.document.open();
x.document.write('<html><head><title>JSON Response</title></head><body><pre>' + tokenJSONString + '</pre></body></html>');
x.document.close();
} | function JSONWindow() {
var x = window.open();
x.document.open();
x.document.write('<html><head><title>JSON Response</title></head><body><pre>' + tokenJSONString + '</pre></body></html>');
x.document.close();
} |
JavaScript | function toDlibXML(imgs){
var imgXMLStr = "";
var img_keys = Object.keys(imgs);
for(var img_i in img_keys){
var imgName = img_keys[ img_i] ;
var img = imgs [ imgName ];
imgXMLStr += "\t<image file='"+ imgName +"'>\n";
var shapes = img.shapes;
//Add boxes
for(var shape_i in shapes){
var box = shapes [ shape_i ].bbox;
imgXMLStr += "\t\t<box top='"+Math.floor(box.y)+"' left='"+Math.floor(box.x)+"' width='"+Math.ceil(box.w)+"' height='"+Math.ceil(box.h)+"'>\n";
imgXMLStr += "\t\t\t<label>"+ shapes [ shape_i ].label +"</label>\n";
//Add points
var fPoints = shapes [ shape_i ].featurePoints;
for(var fPoint_i in fPoints){
var fPoint = fPoints [ fPoint_i ];
//TODO: pad fPoint_i
imgXMLStr += "\t\t\t<part name='"+ fPoint_i +"' x='"+ Math.round(fPoint.x)+"' y='"+ Math.round(fPoint.y) +"'/>\n";
}
imgXMLStr += "\t\t</box>\n"
}
imgXMLStr += "\t</image>\n";
}
return dlib_header + imgXMLStr + dlib_footer;
} | function toDlibXML(imgs){
var imgXMLStr = "";
var img_keys = Object.keys(imgs);
for(var img_i in img_keys){
var imgName = img_keys[ img_i] ;
var img = imgs [ imgName ];
imgXMLStr += "\t<image file='"+ imgName +"'>\n";
var shapes = img.shapes;
//Add boxes
for(var shape_i in shapes){
var box = shapes [ shape_i ].bbox;
imgXMLStr += "\t\t<box top='"+Math.floor(box.y)+"' left='"+Math.floor(box.x)+"' width='"+Math.ceil(box.w)+"' height='"+Math.ceil(box.h)+"'>\n";
imgXMLStr += "\t\t\t<label>"+ shapes [ shape_i ].label +"</label>\n";
//Add points
var fPoints = shapes [ shape_i ].featurePoints;
for(var fPoint_i in fPoints){
var fPoint = fPoints [ fPoint_i ];
//TODO: pad fPoint_i
imgXMLStr += "\t\t\t<part name='"+ fPoint_i +"' x='"+ Math.round(fPoint.x)+"' y='"+ Math.round(fPoint.y) +"'/>\n";
}
imgXMLStr += "\t\t</box>\n"
}
imgXMLStr += "\t</image>\n";
}
return dlib_header + imgXMLStr + dlib_footer;
} |
JavaScript | function toDlibPts(shape){
var data = "version: 1\n"
+"n_points: "+shape.featurePoints.length+"\n"
+"{\n";
var l = shape.bbox.x, t = shape.bbox.y;
for(var fp_id=0; fp_id < shape.featurePoints.length; fp_id++){
data += Math.floor(shape.featurePoints[ fp_id ].x) + " " + Math.floor(shape.featurePoints[ fp_id ].y) + "\n";
}
data += "}";
return data;
} | function toDlibPts(shape){
var data = "version: 1\n"
+"n_points: "+shape.featurePoints.length+"\n"
+"{\n";
var l = shape.bbox.x, t = shape.bbox.y;
for(var fp_id=0; fp_id < shape.featurePoints.length; fp_id++){
data += Math.floor(shape.featurePoints[ fp_id ].x) + " " + Math.floor(shape.featurePoints[ fp_id ].y) + "\n";
}
data += "}";
return data;
} |
JavaScript | appendNumber(number) {
if (number === "." && this.currentOperand.includes(".")) {
return;
}
// show current operand
this.currentOperand = this.currentOperand.toString() + number.toString();
} | appendNumber(number) {
if (number === "." && this.currentOperand.includes(".")) {
return;
}
// show current operand
this.currentOperand = this.currentOperand.toString() + number.toString();
} |
JavaScript | function normalize(path) {
path = `${path}`;
let i = path.length;
if (slash(path, i - 1) && !slash(path, i - 2)) path = path.slice(0, -1);
return path[0] === "/" ? path : `/${path}`;
} | function normalize(path) {
path = `${path}`;
let i = path.length;
if (slash(path, i - 1) && !slash(path, i - 2)) path = path.slice(0, -1);
return path[0] === "/" ? path : `/${path}`;
} |
JavaScript | function tree() {
var separation = defaultSeparation,
dx = 1,
dy = 1,
nodeSize = null;
function tree(root) {
var t = treeRoot(root);
// Compute the layout using Buchheim et al.’s algorithm.
t.eachAfter(firstWalk), t.parent.m = -t.z;
t.eachBefore(secondWalk);
// If a fixed node size is specified, scale x and y.
if (nodeSize) root.eachBefore(sizeNode);
// If a fixed tree size is specified, scale x and y based on the extent.
// Compute the left-most, right-most, and depth-most nodes for extents.
else {
var left = root,
right = root,
bottom = root;
root.eachBefore(function(node) {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
if (node.depth > bottom.depth) bottom = node;
});
var s = left === right ? 1 : separation(left, right) / 2,
tx = s - left.x,
kx = dx / (right.x + s + tx),
ky = dy / (bottom.depth || 1);
root.eachBefore(function(node) {
node.x = (node.x + tx) * kx;
node.y = node.depth * ky;
});
}
return root;
}
// Computes a preliminary x-coordinate for v. Before that, FIRST WALK is
// applied recursively to the children of v, as well as the function
// APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the
// node v is placed to the midpoint of its outermost children.
function firstWalk(v) {
var children = v.children,
siblings = v.parent.children,
w = v.i ? siblings[v.i - 1] : null;
if (children) {
executeShifts(v);
var midpoint = (children[0].z + children[children.length - 1].z) / 2;
if (w) {
v.z = w.z + separation(v._, w._);
v.m = v.z - midpoint;
} else {
v.z = midpoint;
}
} else if (w) {
v.z = w.z + separation(v._, w._);
}
v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
}
// Computes all real x-coordinates by summing up the modifiers recursively.
function secondWalk(v) {
v._.x = v.z + v.parent.m;
v.m += v.parent.m;
}
// The core of the algorithm. Here, a new subtree is combined with the
// previous subtrees. Threads are used to traverse the inside and outside
// contours of the left and right subtree up to the highest common level. The
// vertices used for the traversals are vi+, vi-, vo-, and vo+, where the
// superscript o means outside and i means inside, the subscript - means left
// subtree and + means right subtree. For summing up the modifiers along the
// contour, we use respective variables si+, si-, so-, and so+. Whenever two
// nodes of the inside contours conflict, we compute the left one of the
// greatest uncommon ancestors using the function ANCESTOR and call MOVE
// SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.
// Finally, we add a new thread (if necessary).
function apportion(v, w, ancestor) {
if (w) {
var vip = v,
vop = v,
vim = w,
vom = vip.parent.children[0],
sip = vip.m,
sop = vop.m,
sim = vim.m,
som = vom.m,
shift;
while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {
vom = nextLeft(vom);
vop = nextRight(vop);
vop.a = v;
shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
if (shift > 0) {
moveSubtree(nextAncestor(vim, v, ancestor), v, shift);
sip += shift;
sop += shift;
}
sim += vim.m;
sip += vip.m;
som += vom.m;
sop += vop.m;
}
if (vim && !nextRight(vop)) {
vop.t = vim;
vop.m += sim - sop;
}
if (vip && !nextLeft(vom)) {
vom.t = vip;
vom.m += sip - som;
ancestor = v;
}
}
return ancestor;
}
function sizeNode(node) {
node.x *= dx;
node.y = node.depth * dy;
}
tree.separation = function(x) {
return arguments.length ? (separation = x, tree) : separation;
};
tree.size = function(x) {
return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree) : (nodeSize ? null : [dx, dy]);
};
tree.nodeSize = function(x) {
return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree) : (nodeSize ? [dx, dy] : null);
};
return tree;
} | function tree() {
var separation = defaultSeparation,
dx = 1,
dy = 1,
nodeSize = null;
function tree(root) {
var t = treeRoot(root);
// Compute the layout using Buchheim et al.’s algorithm.
t.eachAfter(firstWalk), t.parent.m = -t.z;
t.eachBefore(secondWalk);
// If a fixed node size is specified, scale x and y.
if (nodeSize) root.eachBefore(sizeNode);
// If a fixed tree size is specified, scale x and y based on the extent.
// Compute the left-most, right-most, and depth-most nodes for extents.
else {
var left = root,
right = root,
bottom = root;
root.eachBefore(function(node) {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
if (node.depth > bottom.depth) bottom = node;
});
var s = left === right ? 1 : separation(left, right) / 2,
tx = s - left.x,
kx = dx / (right.x + s + tx),
ky = dy / (bottom.depth || 1);
root.eachBefore(function(node) {
node.x = (node.x + tx) * kx;
node.y = node.depth * ky;
});
}
return root;
}
// Computes a preliminary x-coordinate for v. Before that, FIRST WALK is
// applied recursively to the children of v, as well as the function
// APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the
// node v is placed to the midpoint of its outermost children.
function firstWalk(v) {
var children = v.children,
siblings = v.parent.children,
w = v.i ? siblings[v.i - 1] : null;
if (children) {
executeShifts(v);
var midpoint = (children[0].z + children[children.length - 1].z) / 2;
if (w) {
v.z = w.z + separation(v._, w._);
v.m = v.z - midpoint;
} else {
v.z = midpoint;
}
} else if (w) {
v.z = w.z + separation(v._, w._);
}
v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
}
// Computes all real x-coordinates by summing up the modifiers recursively.
function secondWalk(v) {
v._.x = v.z + v.parent.m;
v.m += v.parent.m;
}
// The core of the algorithm. Here, a new subtree is combined with the
// previous subtrees. Threads are used to traverse the inside and outside
// contours of the left and right subtree up to the highest common level. The
// vertices used for the traversals are vi+, vi-, vo-, and vo+, where the
// superscript o means outside and i means inside, the subscript - means left
// subtree and + means right subtree. For summing up the modifiers along the
// contour, we use respective variables si+, si-, so-, and so+. Whenever two
// nodes of the inside contours conflict, we compute the left one of the
// greatest uncommon ancestors using the function ANCESTOR and call MOVE
// SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.
// Finally, we add a new thread (if necessary).
function apportion(v, w, ancestor) {
if (w) {
var vip = v,
vop = v,
vim = w,
vom = vip.parent.children[0],
sip = vip.m,
sop = vop.m,
sim = vim.m,
som = vom.m,
shift;
while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {
vom = nextLeft(vom);
vop = nextRight(vop);
vop.a = v;
shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
if (shift > 0) {
moveSubtree(nextAncestor(vim, v, ancestor), v, shift);
sip += shift;
sop += shift;
}
sim += vim.m;
sip += vip.m;
som += vom.m;
sop += vop.m;
}
if (vim && !nextRight(vop)) {
vop.t = vim;
vop.m += sim - sop;
}
if (vip && !nextLeft(vom)) {
vom.t = vip;
vom.m += sip - som;
ancestor = v;
}
}
return ancestor;
}
function sizeNode(node) {
node.x *= dx;
node.y = node.depth * dy;
}
tree.separation = function(x) {
return arguments.length ? (separation = x, tree) : separation;
};
tree.size = function(x) {
return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree) : (nodeSize ? null : [dx, dy]);
};
tree.nodeSize = function(x) {
return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree) : (nodeSize ? [dx, dy] : null);
};
return tree;
} |
JavaScript | function busyLoop(durationSeconds) {
for (let i = 0; i < testArr.length; i++) {
for (let j = 0; j < testArr[i].length; j++) {
testArr[i][j] = Math.sqrt(j * testArr[i][j]);
}
}
if (Date.now() - startTime < 1000 * durationSeconds) {
setTimeout(() => busyLoop(durationSeconds), 5);
}
} | function busyLoop(durationSeconds) {
for (let i = 0; i < testArr.length; i++) {
for (let j = 0; j < testArr[i].length; j++) {
testArr[i][j] = Math.sqrt(j * testArr[i][j]);
}
}
if (Date.now() - startTime < 1000 * durationSeconds) {
setTimeout(() => busyLoop(durationSeconds), 5);
}
} |
JavaScript | function markAsAdded (data, originator) {
if (data.status == 'success') {
originator.addClass('added');
}
} | function markAsAdded (data, originator) {
if (data.status == 'success') {
originator.addClass('added');
}
} |
JavaScript | function markAsRemoved (data, originator) {
if (data.status == 'success') {
originator.parent().remove();
}
} | function markAsRemoved (data, originator) {
if (data.status == 'success') {
originator.parent().remove();
}
} |
JavaScript | function updateLayoutEditorSpan(span) {
//$('.layout-editor section').each(function(){
// if (($(this).position().top + $(this).height() + 30) > height) {
// height = $(this).position().top + $(this).height() + 30;
// }
//});
$('.layout-editor').removeClass('col-2 col-4').addClass('col-'+span);
} | function updateLayoutEditorSpan(span) {
//$('.layout-editor section').each(function(){
// if (($(this).position().top + $(this).height() + 30) > height) {
// height = $(this).position().top + $(this).height() + 30;
// }
//});
$('.layout-editor').removeClass('col-2 col-4').addClass('col-'+span);
} |
JavaScript | function insertProductGalleryProduct(data, originator) {
$('.section-product-gallery').each(function () {
if ($(this).data('id') == data.meta.section) {
var container = $(this).children('ul.sortable');
var exists = false;
container.children('li').each(function () {
if ($(this).data('id') == data.meta.product) {
exists = true;
}
});
if (!exists) {
container.append(data.html);
}
}
});
} | function insertProductGalleryProduct(data, originator) {
$('.section-product-gallery').each(function () {
if ($(this).data('id') == data.meta.section) {
var container = $(this).children('ul.sortable');
var exists = false;
container.children('li').each(function () {
if ($(this).data('id') == data.meta.product) {
exists = true;
}
});
if (!exists) {
container.append(data.html);
}
}
});
} |
JavaScript | function updateProductGalleryProduct(data, originator) {
$('.section-product-gallery').each(function () {
if ($(this).data('id') == data.meta.section) {
var products = $(this).find('.section-product-gallery-form__item');
products.each(function () {
if ($(this).data('id') == data.meta.product) {
$(this).replaceWith(data.html);
}
});
}
});
} | function updateProductGalleryProduct(data, originator) {
$('.section-product-gallery').each(function () {
if ($(this).data('id') == data.meta.section) {
var products = $(this).find('.section-product-gallery-form__item');
products.each(function () {
if ($(this).data('id') == data.meta.product) {
$(this).replaceWith(data.html);
}
});
}
});
} |
JavaScript | function _resolver(option) {
const {
[option]: { path, prefix },
base,
} = config
return resolve(BASE_PATH, base, path, prefix)
} | function _resolver(option) {
const {
[option]: { path, prefix },
base,
} = config
return resolve(BASE_PATH, base, path, prefix)
} |
JavaScript | async function loader() {
const explorer = cosmiconfig(CONFIG_MODULE)
try {
const result = await explorer.search()
return resolver(result?.config)
} catch (error) {
const badFormation = Object.create(error)
badFormation.messsage += `Configuration file with bad formation`
throw badFormation
}
} | async function loader() {
const explorer = cosmiconfig(CONFIG_MODULE)
try {
const result = await explorer.search()
return resolver(result?.config)
} catch (error) {
const badFormation = Object.create(error)
badFormation.messsage += `Configuration file with bad formation`
throw badFormation
}
} |
JavaScript | function playMidiNoteSequence(midiNotes) {
/* console.log("play sequence"); */
if (myapp.buffers) {
midiNotes.map(playMidiNote);
myapp.ports.playSequenceStarted.send(true);
}
else {
myapp.ports.playSequenceStarted.send(false);
}
} | function playMidiNoteSequence(midiNotes) {
/* console.log("play sequence"); */
if (myapp.buffers) {
midiNotes.map(playMidiNote);
myapp.ports.playSequenceStarted.send(true);
}
else {
myapp.ports.playSequenceStarted.send(false);
}
} |
JavaScript | function Soundfont (ctx, nameToUrl) {
if (!(this instanceof Soundfont)) return new Soundfont(ctx)
this.nameToUrl = nameToUrl || Soundfont.nameToUrl || gleitzUrl
this.ctx = ctx
this.instruments = {}
this.promises = []
} | function Soundfont (ctx, nameToUrl) {
if (!(this instanceof Soundfont)) return new Soundfont(ctx)
this.nameToUrl = nameToUrl || Soundfont.nameToUrl || gleitzUrl
this.ctx = ctx
this.instruments = {}
this.promises = []
} |
JavaScript | function decodeBank (bank, notes) {
var promises = Object.keys(bank.data).map(function (note) {
// First check is notes are passed by as param
if (typeof notes !== 'undefined') {
// convert the notes to midi number
var notesMidi = notes.map(midi)
// if the current notes is needed for the instrument.
if (notesMidi.indexOf(midi(note)) !== -1) {
return decodeBuffer(bank.ctx, bank.data[note])
.then(function (buffer) {
bank.buffers[midi(note)] = buffer
})
}
} else {
return decodeBuffer(bank.ctx, bank.data[note])
.then(function (buffer) {
bank.buffers[midi(note)] = buffer
})
}
})
return Promise.all(promises).then(function () {
return bank
})
} | function decodeBank (bank, notes) {
var promises = Object.keys(bank.data).map(function (note) {
// First check is notes are passed by as param
if (typeof notes !== 'undefined') {
// convert the notes to midi number
var notesMidi = notes.map(midi)
// if the current notes is needed for the instrument.
if (notesMidi.indexOf(midi(note)) !== -1) {
return decodeBuffer(bank.ctx, bank.data[note])
.then(function (buffer) {
bank.buffers[midi(note)] = buffer
})
}
} else {
return decodeBuffer(bank.ctx, bank.data[note])
.then(function (buffer) {
bank.buffers[midi(note)] = buffer
})
}
})
return Promise.all(promises).then(function () {
return bank
})
} |
JavaScript | function updateSpan(span, price, priceToday) {
if (span.getAttribute("data-btcprice") === null){
let origText = span.innerText;
// Get a nicely formatted currency string (sorry, only US is supported at this time).
let usdFormatted = price.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
// Get the percent change.
let percentChange = (priceToday - price) / price * 100;
let percentChangeClass = "";
let percentChangeFormatted = "";
// Determine the css class and formatted text.
if (percentChange == 0) {
percentChangeClass = "percent-change-nochange";
percentChangeFormatted = "0%";
} else if (percentChange > 0) {
percentChangeClass = "percent-change-increase";
percentChangeFormatted = percentChange.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + '%';
} else {
percentChangeClass = "percent-change-decrease";
percentChangeFormatted = percentChange.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + '%';
}
// Create a span for percentage change.
let percentChangeSpan = '<span class="' + percentChangeClass + '">' + percentChangeFormatted + '</span>';
// Set the span html.
span.innerHTML = origText + ' (<span class="bitcoin-price">1₿=' + usdFormatted + '</span> ' + percentChangeSpan + ')';
span.setAttribute("data-btcprice", price);
}
} | function updateSpan(span, price, priceToday) {
if (span.getAttribute("data-btcprice") === null){
let origText = span.innerText;
// Get a nicely formatted currency string (sorry, only US is supported at this time).
let usdFormatted = price.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
// Get the percent change.
let percentChange = (priceToday - price) / price * 100;
let percentChangeClass = "";
let percentChangeFormatted = "";
// Determine the css class and formatted text.
if (percentChange == 0) {
percentChangeClass = "percent-change-nochange";
percentChangeFormatted = "0%";
} else if (percentChange > 0) {
percentChangeClass = "percent-change-increase";
percentChangeFormatted = percentChange.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + '%';
} else {
percentChangeClass = "percent-change-decrease";
percentChangeFormatted = percentChange.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + '%';
}
// Create a span for percentage change.
let percentChangeSpan = '<span class="' + percentChangeClass + '">' + percentChangeFormatted + '</span>';
// Set the span html.
span.innerHTML = origText + ' (<span class="bitcoin-price">1₿=' + usdFormatted + '</span> ' + percentChangeSpan + ')';
span.setAttribute("data-btcprice", price);
}
} |
JavaScript | function DicomImage(that, cb) {
"use strict";
this.parent = that;
this.callback = cb;
this.singleton = new TileShare();
this.pngLoader = new PngLoader(this, this.processBuffer, this.singleton.lookup);
} | function DicomImage(that, cb) {
"use strict";
this.parent = that;
this.callback = cb;
this.singleton = new TileShare();
this.pngLoader = new PngLoader(this, this.processBuffer, this.singleton.lookup);
} |
JavaScript | function TileViewer(canvas_id) {
"use strict";
this.master = null;
this.canvas = window.document.getElementById(canvas_id);
this.options = {
src: "",
width: 1024, //canvas width - not image width
height: 1024, //canvas height - not image height
zoom_sensitivity: 32,
maximum_pixelsize: 1, //set this to >1 if you want to let user to zoom image after reaching its original resolution
};
this.pan = {
//pan destination
xdest: null, //(pixel pos)
ydest: null, //(pixel pos)
leveldest: null
};
this.needdraw = false; //flag used to request for frame redraw
this.xnow = null;
this.ynow = null;
// reset singleton
var share = new TileShare();
share.lookup.header = undefined;
// touch event handing helpers
this.lastDelta = 0;
this.ignoreEvent = false;
this.pData = null;
this.baseUrl = "";
this.interactionMode = 0;
} | function TileViewer(canvas_id) {
"use strict";
this.master = null;
this.canvas = window.document.getElementById(canvas_id);
this.options = {
src: "",
width: 1024, //canvas width - not image width
height: 1024, //canvas height - not image height
zoom_sensitivity: 32,
maximum_pixelsize: 1, //set this to >1 if you want to let user to zoom image after reaching its original resolution
};
this.pan = {
//pan destination
xdest: null, //(pixel pos)
ydest: null, //(pixel pos)
leveldest: null
};
this.needdraw = false; //flag used to request for frame redraw
this.xnow = null;
this.ynow = null;
// reset singleton
var share = new TileShare();
share.lookup.header = undefined;
// touch event handing helpers
this.lastDelta = 0;
this.ignoreEvent = false;
this.pData = null;
this.baseUrl = "";
this.interactionMode = 0;
} |
JavaScript | function Tile(layerRef, viewRef, url) {
"use strict";
this.layer = layerRef;
this.view = viewRef;
this.level_loaded_for = layerRef.level;
this.request_src = url;
this.src = "";
this.json = null;
this.timestamp = new Date().getTime();
this.img = new DicomImage(this, this.onload);
this.loaded = false;
this.loading = false;
} | function Tile(layerRef, viewRef, url) {
"use strict";
this.layer = layerRef;
this.view = viewRef;
this.level_loaded_for = layerRef.level;
this.request_src = url;
this.src = "";
this.json = null;
this.timestamp = new Date().getTime();
this.img = new DicomImage(this, this.onload);
this.loaded = false;
this.loading = false;
} |
JavaScript | function secondDryListener(meta) {
// dry and damp handler secondary listener
if (meta.handler.fieldName === DAMP) {
meta.handler.removeProxyListener(secondDryListener);
return;
}
try {
meta.useShadowTarget("prepared");
}
catch (ex) {
meta.throwException(ex);
}
} | function secondDryListener(meta) {
// dry and damp handler secondary listener
if (meta.handler.fieldName === DAMP) {
meta.handler.removeProxyListener(secondDryListener);
return;
}
try {
meta.useShadowTarget("prepared");
}
catch (ex) {
meta.throwException(ex);
}
} |
JavaScript | function checkArgCount(a, b) {
argCount = arguments.length;
if (arguments.length > 0)
expect(arguments[0]).toBe(arg0);
if (arguments.length > 1)
expect(arguments[1]).toBe(arg1);
if (arguments.length > 2)
expect(arguments[2]).toBe(arg2);
} | function checkArgCount(a, b) {
argCount = arguments.length;
if (arguments.length > 0)
expect(arguments[0]).toBe(arg0);
if (arguments.length > 1)
expect(arguments[1]).toBe(arg1);
if (arguments.length > 2)
expect(arguments[2]).toBe(arg2);
} |
JavaScript | function ScriptPromise(url) {
// public, for chaining
let res, rej;
this.promise = new Promise(function(resolve, reject) {
// private
res = resolve;
rej = reject;
});
this.resolve = res;
this.reject = rej;
// private
this.scriptElem = document.createElement("script");
this.scriptElem.addEventListener("load", this, true);
window.addEventListener("error", this, true);
this.scriptElem.setAttribute("type", "application/javascript");
this.scriptElem.setAttribute("src", url);
// no async, no defer: load it now!
this.url = url;
} | function ScriptPromise(url) {
// public, for chaining
let res, rej;
this.promise = new Promise(function(resolve, reject) {
// private
res = resolve;
rej = reject;
});
this.resolve = res;
this.reject = rej;
// private
this.scriptElem = document.createElement("script");
this.scriptElem.addEventListener("load", this, true);
window.addEventListener("error", this, true);
this.scriptElem.setAttribute("type", "application/javascript");
this.scriptElem.setAttribute("src", url);
// no async, no defer: load it now!
this.url = url;
} |
JavaScript | function TabboxRadioEventHandler(form, inputName, target, attr) {
this.form = form;
this.inputName = inputName;
this.target = target;
this.attr = attr;
} | function TabboxRadioEventHandler(form, inputName, target, attr) {
this.form = form;
this.inputName = inputName;
this.target = target;
this.attr = attr;
} |
JavaScript | function handleArgv() {
if (process.argv.length !== 3) {
console.error(`Wrong argument count. Usage:\n\n${APP_NAME} /path/to/storage\n`);
} else {
let storagePath = process.argv[2];
try {
if (!statSync(storagePath).isDirectory()) {
console.error(`${storagePath} is not a directory.`);
}
return storagePath;
} catch (err) {
console.error(err.message);
}
}
loggy.errorHappened = true;
return undefined;
} | function handleArgv() {
if (process.argv.length !== 3) {
console.error(`Wrong argument count. Usage:\n\n${APP_NAME} /path/to/storage\n`);
} else {
let storagePath = process.argv[2];
try {
if (!statSync(storagePath).isDirectory()) {
console.error(`${storagePath} is not a directory.`);
}
return storagePath;
} catch (err) {
console.error(err.message);
}
}
loggy.errorHappened = true;
return undefined;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.