language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | async function withTestInstance(params, cb) {
const ec2 = new aws.EC2();
let instance;
try {
const response = await ec2.runInstances({
...params,
MinCount: 1,
MaxCount: 1,
TagSpecifications: [{
ResourceType: 'instance',
Tags: [{
Key: 'Name',
Value: 'TestInstance'
}]
}]
}).promise();
instance = response.Instances[0];
await ec2.waitFor('instanceRunning', {
InstanceIds: [instance.InstanceId]
}).promise();
await cb(instance);
} finally {
try {
if (instance) {
console.log(`Terminating instance ${instance.InstanceId}...`);
await ec2.terminateInstances({
InstanceIds: [instance.InstanceId]
}).promise();
await ec2.waitFor('instanceTerminated', {
InstanceIds: [instance.InstanceId]
}).promise();
}
} catch (err) {
console.log(err);
}
}
} | async function withTestInstance(params, cb) {
const ec2 = new aws.EC2();
let instance;
try {
const response = await ec2.runInstances({
...params,
MinCount: 1,
MaxCount: 1,
TagSpecifications: [{
ResourceType: 'instance',
Tags: [{
Key: 'Name',
Value: 'TestInstance'
}]
}]
}).promise();
instance = response.Instances[0];
await ec2.waitFor('instanceRunning', {
InstanceIds: [instance.InstanceId]
}).promise();
await cb(instance);
} finally {
try {
if (instance) {
console.log(`Terminating instance ${instance.InstanceId}...`);
await ec2.terminateInstances({
InstanceIds: [instance.InstanceId]
}).promise();
await ec2.waitFor('instanceTerminated', {
InstanceIds: [instance.InstanceId]
}).promise();
}
} catch (err) {
console.log(err);
}
}
} |
JavaScript | async function runTest(instance, keyPath) {
const ec2 = new aws.EC2();
const instanceInfo = await ec2.describeInstances({
InstanceIds: [instance.InstanceId]
}).promise();
const publicIpAddr = instanceInfo.Reservations[0].Instances[0].PublicIpAddress;
console.log(`Waiting for SSH port on ${publicIpAddr} to become available...`);
await waitPort({
host: publicIpAddr,
port: 22,
timeout: SSHWaitTimeout
});
return new Promise((resolve, reject) => {
console.log('Starting InSpec...');
const process = spawn('inspec', ['exec',
'-b', 'ssh',
'-i', keyPath,
'--host', publicIpAddr,
'--user', LoginName,
'--sudo',
'--no-color',
// Don't exit nonzero if tests are skipped
'--no-distinct-exit',
TestDir
], {
// Don't squelch stdout/stderr
stdio: 'inherit'
});
process.on('error', err => reject(err));
process.on('close', exitCode => resolve(exitCode));
});
} | async function runTest(instance, keyPath) {
const ec2 = new aws.EC2();
const instanceInfo = await ec2.describeInstances({
InstanceIds: [instance.InstanceId]
}).promise();
const publicIpAddr = instanceInfo.Reservations[0].Instances[0].PublicIpAddress;
console.log(`Waiting for SSH port on ${publicIpAddr} to become available...`);
await waitPort({
host: publicIpAddr,
port: 22,
timeout: SSHWaitTimeout
});
return new Promise((resolve, reject) => {
console.log('Starting InSpec...');
const process = spawn('inspec', ['exec',
'-b', 'ssh',
'-i', keyPath,
'--host', publicIpAddr,
'--user', LoginName,
'--sudo',
'--no-color',
// Don't exit nonzero if tests are skipped
'--no-distinct-exit',
TestDir
], {
// Don't squelch stdout/stderr
stdio: 'inherit'
});
process.on('error', err => reject(err));
process.on('close', exitCode => resolve(exitCode));
});
} |
JavaScript | async function tagImage(amiId, tags) {
const ec2 = new aws.EC2();
let tagArray = [];
for (let tagName in tags) {
if (Reflect.has(tags, tagName)) {
tagArray.push({
Key: tagName,
Value: tags[tagName]
});
}
}
const ami = await ec2.describeImages({
ImageIds: [amiId]
}).promise();
const snapshots = ami.Images[0].BlockDeviceMappings.map(mapping => mapping.Ebs.SnapshotId);
const resourcesToTag = [amiId].concat(snapshots);
const params = {
Resources: resourcesToTag,
Tags: tagArray
};
await ec2.createTags(params).promise();
} | async function tagImage(amiId, tags) {
const ec2 = new aws.EC2();
let tagArray = [];
for (let tagName in tags) {
if (Reflect.has(tags, tagName)) {
tagArray.push({
Key: tagName,
Value: tags[tagName]
});
}
}
const ami = await ec2.describeImages({
ImageIds: [amiId]
}).promise();
const snapshots = ami.Images[0].BlockDeviceMappings.map(mapping => mapping.Ebs.SnapshotId);
const resourcesToTag = [amiId].concat(snapshots);
const params = {
Resources: resourcesToTag,
Tags: tagArray
};
await ec2.createTags(params).promise();
} |
JavaScript | function printBinary(num){
if(num < 0){
return "-" + printBinary(-num);
}
if(num <= 1) {
return `${num}`;
}
return printBinary(Math.floor(num / 2)) + `${num % 2}`;
} | function printBinary(num){
if(num < 0){
return "-" + printBinary(-num);
}
if(num <= 1) {
return `${num}`;
}
return printBinary(Math.floor(num / 2)) + `${num % 2}`;
} |
JavaScript | function exp(n,m){
if(m < 0 || isNaN(m) || isNaN(n)){
throw "m should be alway >=0 and m,n should always be numbers"
}
if(m === 0 ) {
return 1;
}
return n * exp(n, m - 1)
} | function exp(n,m){
if(m < 0 || isNaN(m) || isNaN(n)){
throw "m should be alway >=0 and m,n should always be numbers"
}
if(m === 0 ) {
return 1;
}
return n * exp(n, m - 1)
} |
JavaScript | function pauseBoard () {
io.emit('pause board', '');
writeToLog('Board timer stopped');
updateTimeStatus('pause');
} | function pauseBoard () {
io.emit('pause board', '');
writeToLog('Board timer stopped');
updateTimeStatus('pause');
} |
JavaScript | function startBoard () {
io.emit('start board', '');
writeToLog('Board timer started');
updateTimeStatus('start');
} | function startBoard () {
io.emit('start board', '');
writeToLog('Board timer started');
updateTimeStatus('start');
} |
JavaScript | function generateHash(obj) {
var strin_fei = JSON.stringify(obj)
return SHA256(strin_fei)
} | function generateHash(obj) {
var strin_fei = JSON.stringify(obj)
return SHA256(strin_fei)
} |
JavaScript | async fetch () {
/**
* Apply all the scopes before fetching
* data
*/
this._applyScopes()
/**
* Execute query
*/
const rows = await this.query
/**
* Convert to an array of model instances
*/
const modelInstances = this._mapRowsToInstances(rows)
await this._eagerLoad(modelInstances)
/**
* Fire afterFetch event
*/
if (this.Model.$hooks) {
await this.Model.$hooks.after.exec('fetch', modelInstances)
}
const Serializer = this.Model.resolveSerializer()
return new Serializer(modelInstances)
} | async fetch () {
/**
* Apply all the scopes before fetching
* data
*/
this._applyScopes()
/**
* Execute query
*/
const rows = await this.query
/**
* Convert to an array of model instances
*/
const modelInstances = this._mapRowsToInstances(rows)
await this._eagerLoad(modelInstances)
/**
* Fire afterFetch event
*/
if (this.Model.$hooks) {
await this.Model.$hooks.after.exec('fetch', modelInstances)
}
const Serializer = this.Model.resolveSerializer()
return new Serializer(modelInstances)
} |
JavaScript | async firstOrFail () {
const returnValue = await this.first()
if (!returnValue) {
throw CE.ModelNotFoundException.raise(this.Model.name)
}
return returnValue
} | async firstOrFail () {
const returnValue = await this.first()
if (!returnValue) {
throw CE.ModelNotFoundException.raise(this.Model.name)
}
return returnValue
} |
JavaScript | has (relation, expression, value) {
const { relationInstance, nested } = this._parseRelation(relation)
if (nested) {
relationInstance.has(_.first(_.keys(nested)), expression, value)
this._has(relationInstance, 'whereExists')
} else {
this._has(relationInstance, 'whereExists', expression, value, 'whereRaw')
}
return this
} | has (relation, expression, value) {
const { relationInstance, nested } = this._parseRelation(relation)
if (nested) {
relationInstance.has(_.first(_.keys(nested)), expression, value)
this._has(relationInstance, 'whereExists')
} else {
this._has(relationInstance, 'whereExists', expression, value, 'whereRaw')
}
return this
} |
JavaScript | whereHas (relation, callback, expression, value) {
const { relationInstance, nested } = this._parseRelation(relation)
if (nested) {
relationInstance.whereHas(_.first(_.keys(nested)), callback, expression, value)
this._has(relationInstance, 'whereExists')
} else {
this._has(relationInstance, 'whereExists', expression, value, 'whereRaw', callback)
}
return this
} | whereHas (relation, callback, expression, value) {
const { relationInstance, nested } = this._parseRelation(relation)
if (nested) {
relationInstance.whereHas(_.first(_.keys(nested)), callback, expression, value)
this._has(relationInstance, 'whereExists')
} else {
this._has(relationInstance, 'whereExists', expression, value, 'whereRaw', callback)
}
return this
} |
JavaScript | clone () {
const clonedQuery = new QueryBuilder(this.Model, this.connectionString)
clonedQuery.query = this.query.clone()
clonedQuery.query.subQuery = this.query.subQuery
clonedQuery._eagerLoads = this._eagerLoads
clonedQuery._sideLoaded = this._sideLoaded
clonedQuery._visibleFields = this._visibleFields
clonedQuery._hiddenFields = this._hiddenFields
clonedQuery._withCountCounter = this._withCountCounter
clonedQuery.scopesIterator = this.scopesIterator
return clonedQuery
} | clone () {
const clonedQuery = new QueryBuilder(this.Model, this.connectionString)
clonedQuery.query = this.query.clone()
clonedQuery.query.subQuery = this.query.subQuery
clonedQuery._eagerLoads = this._eagerLoads
clonedQuery._sideLoaded = this._sideLoaded
clonedQuery._visibleFields = this._visibleFields
clonedQuery._hiddenFields = this._hiddenFields
clonedQuery._withCountCounter = this._withCountCounter
clonedQuery.scopesIterator = this.scopesIterator
return clonedQuery
} |
JavaScript | _formatDateFields (values) {
_(this.constructor.dates)
.filter((date) => {
return values[date] && typeof (this[util.getSetterName(date)]) !== 'function'
})
.each((date) => { values[date] = this.constructor.formatDates(date, values[date]) })
} | _formatDateFields (values) {
_(this.constructor.dates)
.filter((date) => {
return values[date] && typeof (this[util.getSetterName(date)]) !== 'function'
})
.each((date) => { values[date] = this.constructor.formatDates(date, values[date]) })
} |
JavaScript | async delete () {
/**
* Executing before hooks
*/
await this.constructor.$hooks.before.exec('delete', this)
const affected = await this.constructor
.query()
.where(this.constructor.primaryKey, this.primaryKeyValue)
.ignoreScopes()
.delete()
/**
* If model was delete then freeze it modifications
*/
if (affected > 0) {
this.freeze()
}
/**
* Executing after hooks
*/
await this.constructor.$hooks.after.exec('delete', this)
return !!affected
} | async delete () {
/**
* Executing before hooks
*/
await this.constructor.$hooks.before.exec('delete', this)
const affected = await this.constructor
.query()
.where(this.constructor.primaryKey, this.primaryKeyValue)
.ignoreScopes()
.delete()
/**
* If model was delete then freeze it modifications
*/
if (affected > 0) {
this.freeze()
}
/**
* Executing after hooks
*/
await this.constructor.$hooks.after.exec('delete', this)
return !!affected
} |
JavaScript | function runEnterHooks(routes, nextState, callback) {
var hooks = getEnterHooks(routes);
if (!hooks.length) {
callback();
return;
}
var redirectInfo = undefined;
function replace(location, deprecatedPathname, deprecatedQuery) {
if (deprecatedPathname) {
process.env.NODE_ENV !== 'production' ? _routerWarning2['default'](false, '`replaceState(state, pathname, query) is deprecated; use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated') : undefined;
redirectInfo = {
pathname: deprecatedPathname,
query: deprecatedQuery,
state: location
};
return;
}
redirectInfo = location;
}
_AsyncUtils.loopAsync(hooks.length, function (index, next, done) {
hooks[index](nextState, replace, function (error) {
if (error || redirectInfo) {
done(error, redirectInfo); // No need to continue.
} else {
next();
}
});
}, callback);
} | function runEnterHooks(routes, nextState, callback) {
var hooks = getEnterHooks(routes);
if (!hooks.length) {
callback();
return;
}
var redirectInfo = undefined;
function replace(location, deprecatedPathname, deprecatedQuery) {
if (deprecatedPathname) {
process.env.NODE_ENV !== 'production' ? _routerWarning2['default'](false, '`replaceState(state, pathname, query) is deprecated; use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated') : undefined;
redirectInfo = {
pathname: deprecatedPathname,
query: deprecatedQuery,
state: location
};
return;
}
redirectInfo = location;
}
_AsyncUtils.loopAsync(hooks.length, function (index, next, done) {
hooks[index](nextState, replace, function (error) {
if (error || redirectInfo) {
done(error, redirectInfo); // No need to continue.
} else {
next();
}
});
}, callback);
} |
JavaScript | function routerReducer() {
var state = arguments.length <= 0 || arguments[0] === undefined ? initialState : arguments[0];
var _ref = arguments[1];
var type = _ref.type;
var payload = _ref.payload;
if (type === LOCATION_CHANGE) {
return _extends({}, state, { locationBeforeTransitions: payload });
}
return state;
} | function routerReducer() {
var state = arguments.length <= 0 || arguments[0] === undefined ? initialState : arguments[0];
var _ref = arguments[1];
var type = _ref.type;
var payload = _ref.payload;
if (type === LOCATION_CHANGE) {
return _extends({}, state, { locationBeforeTransitions: payload });
}
return state;
} |
JavaScript | function syncHistoryWithStore(history, store) {
var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var _ref$selectLocationSt = _ref.selectLocationState;
var selectLocationState = _ref$selectLocationSt === undefined ? defaultSelectLocationState : _ref$selectLocationSt;
var _ref$adjustUrlOnRepla = _ref.adjustUrlOnReplay;
var adjustUrlOnReplay = _ref$adjustUrlOnRepla === undefined ? true : _ref$adjustUrlOnRepla;
// Ensure that the reducer is mounted on the store and functioning properly.
if (typeof selectLocationState(store.getState()) === 'undefined') {
throw new Error('Expected the routing state to be available either as `state.routing` ' + 'or as the custom expression you can specify as `selectLocationState` ' + 'in the `syncHistoryWithStore()` options. ' + 'Ensure you have added the `routerReducer` to your store\'s ' + 'reducers via `combineReducers` or whatever method you use to isolate ' + 'your reducers.');
}
var initialLocation = undefined;
var currentLocation = undefined;
var isTimeTraveling = undefined;
var unsubscribeFromStore = undefined;
var unsubscribeFromHistory = undefined;
// What does the store say about current location?
var getLocationInStore = function getLocationInStore(useInitialIfEmpty) {
var locationState = selectLocationState(store.getState());
return locationState.locationBeforeTransitions || (useInitialIfEmpty ? initialLocation : undefined);
};
// If the store is replayed, update the URL in the browser to match.
if (adjustUrlOnReplay) {
var handleStoreChange = function handleStoreChange() {
var locationInStore = getLocationInStore(true);
if (currentLocation === locationInStore) {
return;
}
// Update address bar to reflect store state
isTimeTraveling = true;
currentLocation = locationInStore;
history.transitionTo(_extends({}, locationInStore, {
action: 'PUSH'
}));
isTimeTraveling = false;
};
unsubscribeFromStore = store.subscribe(handleStoreChange);
handleStoreChange();
}
// Whenever location changes, dispatch an action to get it in the store
var handleLocationChange = function handleLocationChange(location) {
// ... unless we just caused that location change
if (isTimeTraveling) {
return;
}
// Remember where we are
currentLocation = location;
// Are we being called for the first time?
if (!initialLocation) {
// Remember as a fallback in case state is reset
initialLocation = location;
// Respect persisted location, if any
if (getLocationInStore()) {
return;
}
}
// Tell the store to update by dispatching an action
store.dispatch({
type: _reducer.LOCATION_CHANGE,
payload: location
});
};
unsubscribeFromHistory = history.listen(handleLocationChange);
// The enhanced history uses store as source of truth
return _extends({}, history, {
// The listeners are subscribed to the store instead of history
listen: function listen(listener) {
// Copy of last location.
var lastPublishedLocation = getLocationInStore(true);
// Keep track of whether we unsubscribed, as Redux store
// only applies changes in subscriptions on next dispatch
var unsubscribed = false;
var unsubscribeFromStore = store.subscribe(function () {
var currentLocation = getLocationInStore(true);
if (currentLocation === lastPublishedLocation) {
return;
}
lastPublishedLocation = currentLocation;
if (!unsubscribed) {
listener(lastPublishedLocation);
}
});
// History listeners expect a synchronous call. Make the first call to the
// listener after subscribing to the store, in case the listener causes a
// location change (e.g. when it redirects)
listener(lastPublishedLocation);
// Let user unsubscribe later
return function () {
unsubscribed = true;
unsubscribeFromStore();
};
},
// It also provides a way to destroy internal listeners
unsubscribe: function unsubscribe() {
if (adjustUrlOnReplay) {
unsubscribeFromStore();
}
unsubscribeFromHistory();
}
});
} | function syncHistoryWithStore(history, store) {
var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var _ref$selectLocationSt = _ref.selectLocationState;
var selectLocationState = _ref$selectLocationSt === undefined ? defaultSelectLocationState : _ref$selectLocationSt;
var _ref$adjustUrlOnRepla = _ref.adjustUrlOnReplay;
var adjustUrlOnReplay = _ref$adjustUrlOnRepla === undefined ? true : _ref$adjustUrlOnRepla;
// Ensure that the reducer is mounted on the store and functioning properly.
if (typeof selectLocationState(store.getState()) === 'undefined') {
throw new Error('Expected the routing state to be available either as `state.routing` ' + 'or as the custom expression you can specify as `selectLocationState` ' + 'in the `syncHistoryWithStore()` options. ' + 'Ensure you have added the `routerReducer` to your store\'s ' + 'reducers via `combineReducers` or whatever method you use to isolate ' + 'your reducers.');
}
var initialLocation = undefined;
var currentLocation = undefined;
var isTimeTraveling = undefined;
var unsubscribeFromStore = undefined;
var unsubscribeFromHistory = undefined;
// What does the store say about current location?
var getLocationInStore = function getLocationInStore(useInitialIfEmpty) {
var locationState = selectLocationState(store.getState());
return locationState.locationBeforeTransitions || (useInitialIfEmpty ? initialLocation : undefined);
};
// If the store is replayed, update the URL in the browser to match.
if (adjustUrlOnReplay) {
var handleStoreChange = function handleStoreChange() {
var locationInStore = getLocationInStore(true);
if (currentLocation === locationInStore) {
return;
}
// Update address bar to reflect store state
isTimeTraveling = true;
currentLocation = locationInStore;
history.transitionTo(_extends({}, locationInStore, {
action: 'PUSH'
}));
isTimeTraveling = false;
};
unsubscribeFromStore = store.subscribe(handleStoreChange);
handleStoreChange();
}
// Whenever location changes, dispatch an action to get it in the store
var handleLocationChange = function handleLocationChange(location) {
// ... unless we just caused that location change
if (isTimeTraveling) {
return;
}
// Remember where we are
currentLocation = location;
// Are we being called for the first time?
if (!initialLocation) {
// Remember as a fallback in case state is reset
initialLocation = location;
// Respect persisted location, if any
if (getLocationInStore()) {
return;
}
}
// Tell the store to update by dispatching an action
store.dispatch({
type: _reducer.LOCATION_CHANGE,
payload: location
});
};
unsubscribeFromHistory = history.listen(handleLocationChange);
// The enhanced history uses store as source of truth
return _extends({}, history, {
// The listeners are subscribed to the store instead of history
listen: function listen(listener) {
// Copy of last location.
var lastPublishedLocation = getLocationInStore(true);
// Keep track of whether we unsubscribed, as Redux store
// only applies changes in subscriptions on next dispatch
var unsubscribed = false;
var unsubscribeFromStore = store.subscribe(function () {
var currentLocation = getLocationInStore(true);
if (currentLocation === lastPublishedLocation) {
return;
}
lastPublishedLocation = currentLocation;
if (!unsubscribed) {
listener(lastPublishedLocation);
}
});
// History listeners expect a synchronous call. Make the first call to the
// listener after subscribing to the store, in case the listener causes a
// location change (e.g. when it redirects)
listener(lastPublishedLocation);
// Let user unsubscribe later
return function () {
unsubscribed = true;
unsubscribeFromStore();
};
},
// It also provides a way to destroy internal listeners
unsubscribe: function unsubscribe() {
if (adjustUrlOnReplay) {
unsubscribeFromStore();
}
unsubscribeFromHistory();
}
});
} |
JavaScript | function worker() {
let NODES
let LINKS
let SETTINGS
self.addEventListener('message', function (event) {
let data = event.data
if (data.nodes) NODES = new Float32Array(data.nodes)
if (data.links) LINKS = new Float32Array(data.links)
if (data.settings) SETTINGS = data.settings
// Running the iteration
iterate(SETTINGS, NODES, LINKS)
// Sending result to supervisor
self.postMessage({
nodes: NODES.buffer
})
})
} | function worker() {
let NODES
let LINKS
let SETTINGS
self.addEventListener('message', function (event) {
let data = event.data
if (data.nodes) NODES = new Float32Array(data.nodes)
if (data.links) LINKS = new Float32Array(data.links)
if (data.settings) SETTINGS = data.settings
// Running the iteration
iterate(SETTINGS, NODES, LINKS)
// Sending result to supervisor
self.postMessage({
nodes: NODES.buffer
})
})
} |
JavaScript | function computeTreeDepth(tree) {
let depth = 0;
let p = tree;
let q = [p];
while (q.length > 0) {
let qq = [];
for (const x of q) {
if (x.children) {
for (const y of x.children) {
qq.push(y);
}
}
}
if (qq.length > 0)
depth += 1;
q = qq;
}
return depth;
} | function computeTreeDepth(tree) {
let depth = 0;
let p = tree;
let q = [p];
while (q.length > 0) {
let qq = [];
for (const x of q) {
if (x.children) {
for (const y of x.children) {
qq.push(y);
}
}
}
if (qq.length > 0)
depth += 1;
q = qq;
}
return depth;
} |
JavaScript | synchronousLayout() {
let iterations = this._param.iterations;
if (iterations <= 0)
throw new Error('@netv/layout/forceatlas2: you should provide a positive number of iterations.');
// Validating settings
let settings = helpers.assign({}, this._param);
let validationError = helpers.validateSettings(settings);
if (validationError)
throw new Error('@netv/layout/forceatlas2: ' + validationError.message);
// Building matrices
let matrices = helpers.graphToByteArrays(this._data);
// Iterating
if (this._interval)
clearInterval(this._interval);
this._interval = setInterval(() => {
var _a;
iterate_1.default(settings, matrices.nodes, matrices.links);
helpers.assignLayoutChanges(this._data, matrices.nodes);
(_a = this._onEachCallback) === null || _a === void 0 ? void 0 : _a.call(this, this._data);
this._iterations++;
if (this._iterations >= this._param.iterations) {
this.stop();
}
}, 0);
} | synchronousLayout() {
let iterations = this._param.iterations;
if (iterations <= 0)
throw new Error('@netv/layout/forceatlas2: you should provide a positive number of iterations.');
// Validating settings
let settings = helpers.assign({}, this._param);
let validationError = helpers.validateSettings(settings);
if (validationError)
throw new Error('@netv/layout/forceatlas2: ' + validationError.message);
// Building matrices
let matrices = helpers.graphToByteArrays(this._data);
// Iterating
if (this._interval)
clearInterval(this._interval);
this._interval = setInterval(() => {
var _a;
iterate_1.default(settings, matrices.nodes, matrices.links);
helpers.assignLayoutChanges(this._data, matrices.nodes);
(_a = this._onEachCallback) === null || _a === void 0 ? void 0 : _a.call(this, this._data);
this._iterations++;
if (this._iterations >= this._param.iterations) {
this.stop();
}
}, 0);
} |
JavaScript | function delaunator_orient(rx, ry, qx, qy, px, py) {
const sign = orientIfSure(px, py, rx, ry, qx, qy) ||
orientIfSure(rx, ry, qx, qy, px, py) ||
orientIfSure(qx, qy, px, py, rx, ry);
return sign < 0;
} | function delaunator_orient(rx, ry, qx, qy, px, py) {
const sign = orientIfSure(px, py, rx, ry, qx, qy) ||
orientIfSure(rx, ry, qx, qy, px, py) ||
orientIfSure(qx, qy, px, py, rx, ry);
return sign < 0;
} |
JavaScript | function circleRadius(cosRadius, point) {
point = cartesian_cartesian(point), point[0] -= cosRadius;
cartesianNormalizeInPlace(point);
var radius = acos(-point[1]);
return ((-point[2] < 0 ? -radius : radius) + math_tau - src_math_epsilon) % math_tau;
} | function circleRadius(cosRadius, point) {
point = cartesian_cartesian(point), point[0] -= cosRadius;
cartesianNormalizeInPlace(point);
var radius = acos(-point[1]);
return ((-point[2] < 0 ? -radius : radius) + math_tau - src_math_epsilon) % math_tau;
} |
JavaScript | function intersect(a, b, two) {
var pa = cartesian_cartesian(a),
pb = cartesian_cartesian(b);
// We have two planes, n1.p = d1 and n2.p = d2.
// Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2).
var n1 = [1, 0, 0], // normal
n2 = cartesianCross(pa, pb),
n2n2 = cartesianDot(n2, n2),
n1n2 = n2[0], // cartesianDot(n1, n2),
determinant = n2n2 - n1n2 * n1n2;
// Two polar points.
if (!determinant) return !two && a;
var c1 = cr * n2n2 / determinant,
c2 = -cr * n1n2 / determinant,
n1xn2 = cartesianCross(n1, n2),
A = cartesianScale(n1, c1),
B = cartesianScale(n2, c2);
cartesianAddInPlace(A, B);
// Solve |p(t)|^2 = 1.
var u = n1xn2,
w = cartesianDot(A, u),
uu = cartesianDot(u, u),
t2 = w * w - uu * (cartesianDot(A, A) - 1);
if (t2 < 0) return;
var t = sqrt(t2),
q = cartesianScale(u, (-w - t) / uu);
cartesianAddInPlace(q, A);
q = cartesian_spherical(q);
if (!two) return q;
// Two intersection points.
var lambda0 = a[0],
lambda1 = b[0],
phi0 = a[1],
phi1 = b[1],
z;
if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;
var delta = lambda1 - lambda0,
polar = src_math_abs(delta - math_pi) < src_math_epsilon,
meridian = polar || delta < src_math_epsilon;
if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;
// Check that the first point is between a and b.
if (meridian
? polar
? phi0 + phi1 > 0 ^ q[1] < (src_math_abs(q[0] - lambda0) < src_math_epsilon ? phi0 : phi1)
: phi0 <= q[1] && q[1] <= phi1
: delta > math_pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {
var q1 = cartesianScale(u, (-w + t) / uu);
cartesianAddInPlace(q1, A);
return [q, cartesian_spherical(q1)];
}
} | function intersect(a, b, two) {
var pa = cartesian_cartesian(a),
pb = cartesian_cartesian(b);
// We have two planes, n1.p = d1 and n2.p = d2.
// Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2).
var n1 = [1, 0, 0], // normal
n2 = cartesianCross(pa, pb),
n2n2 = cartesianDot(n2, n2),
n1n2 = n2[0], // cartesianDot(n1, n2),
determinant = n2n2 - n1n2 * n1n2;
// Two polar points.
if (!determinant) return !two && a;
var c1 = cr * n2n2 / determinant,
c2 = -cr * n1n2 / determinant,
n1xn2 = cartesianCross(n1, n2),
A = cartesianScale(n1, c1),
B = cartesianScale(n2, c2);
cartesianAddInPlace(A, B);
// Solve |p(t)|^2 = 1.
var u = n1xn2,
w = cartesianDot(A, u),
uu = cartesianDot(u, u),
t2 = w * w - uu * (cartesianDot(A, A) - 1);
if (t2 < 0) return;
var t = sqrt(t2),
q = cartesianScale(u, (-w - t) / uu);
cartesianAddInPlace(q, A);
q = cartesian_spherical(q);
if (!two) return q;
// Two intersection points.
var lambda0 = a[0],
lambda1 = b[0],
phi0 = a[1],
phi1 = b[1],
z;
if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;
var delta = lambda1 - lambda0,
polar = src_math_abs(delta - math_pi) < src_math_epsilon,
meridian = polar || delta < src_math_epsilon;
if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;
// Check that the first point is between a and b.
if (meridian
? polar
? phi0 + phi1 > 0 ^ q[1] < (src_math_abs(q[0] - lambda0) < src_math_epsilon ? phi0 : phi1)
: phi0 <= q[1] && q[1] <= phi1
: delta > math_pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {
var q1 = cartesianScale(u, (-w + t) / uu);
cartesianAddInPlace(q1, A);
return [q, cartesian_spherical(q1)];
}
} |
JavaScript | function disable(name) {
const id = typeof name == 'string' ? name : name.id;
const nodeName = $(id).prop('nodeName');
if (nodeName == 'BUTTON' || nodeName == 'INPUT') {
$(id).prop('disabled', true);
}
else {
$(id).css('pointer-events', 'none');
}
} | function disable(name) {
const id = typeof name == 'string' ? name : name.id;
const nodeName = $(id).prop('nodeName');
if (nodeName == 'BUTTON' || nodeName == 'INPUT') {
$(id).prop('disabled', true);
}
else {
$(id).css('pointer-events', 'none');
}
} |
JavaScript | function enable(name) {
const id = typeof name == 'string' ? name : name.id;
const nodeName = $(id).prop('nodeName');
if (nodeName == 'BUTTON' || nodeName == 'INPUT') {
$(id).prop('disabled', false);
}
else {
$(id).css('pointer-events', 'auto');
}
} | function enable(name) {
const id = typeof name == 'string' ? name : name.id;
const nodeName = $(id).prop('nodeName');
if (nodeName == 'BUTTON' || nodeName == 'INPUT') {
$(id).prop('disabled', false);
}
else {
$(id).css('pointer-events', 'auto');
}
} |
JavaScript | function create_check(item, label, title, value // 由于 value 通常等于 label,因此 value 不常用,放在最后
) {
value = value ? value : label;
return m('div')
.addClass('form-check-inline')
.append(m(item).attr({ value: value, title: title }), m('label').text(label).attr({ for: item.raw_id, title: title }));
} | function create_check(item, label, title, value // 由于 value 通常等于 label,因此 value 不常用,放在最后
) {
value = value ? value : label;
return m('div')
.addClass('form-check-inline')
.append(m(item).attr({ value: value, title: title }), m('label').text(label).attr({ for: item.raw_id, title: title }));
} |
JavaScript | async generateExampleFiles(inputs, options) {
console.log("generateExampleFiles");
const projectNameInput = this.getInput(inputs, "name");
if (!projectNameInput || typeof projectNameInput.value !== "string") {
throw new Error("Unable to find name!");
}
const generateComponentAction = new generate_action_1.GenerateAction();
const generateComponent = await this.getInputsForGenerateExamples(projectNameInput.value, inputs, options, generateComponentAction, "component");
this.setInput(generateComponent.options, "flat", false);
await generateComponentAction.handle(generateComponent.inputs, generateComponent.options);
const generateBinderAction = new generate_action_1.GenerateAction();
const generateBinder = await this.getInputsForGenerateExamples(projectNameInput.value, inputs, options, generateBinderAction, "binder");
this.setInput(generateBinder.options, "flat", true);
await generateBinderAction.handle(generateBinder.inputs, generateBinder.options);
const generateFormatterAction = new generate_action_1.GenerateAction();
const generateFormatter = await this.getInputsForGenerateExamples(projectNameInput.value, inputs, options, generateFormatterAction, "formatter");
this.setInput(generateFormatter.options, "flat", true);
await generateFormatterAction.handle(generateFormatter.inputs, generateFormatter.options);
} | async generateExampleFiles(inputs, options) {
console.log("generateExampleFiles");
const projectNameInput = this.getInput(inputs, "name");
if (!projectNameInput || typeof projectNameInput.value !== "string") {
throw new Error("Unable to find name!");
}
const generateComponentAction = new generate_action_1.GenerateAction();
const generateComponent = await this.getInputsForGenerateExamples(projectNameInput.value, inputs, options, generateComponentAction, "component");
this.setInput(generateComponent.options, "flat", false);
await generateComponentAction.handle(generateComponent.inputs, generateComponent.options);
const generateBinderAction = new generate_action_1.GenerateAction();
const generateBinder = await this.getInputsForGenerateExamples(projectNameInput.value, inputs, options, generateBinderAction, "binder");
this.setInput(generateBinder.options, "flat", true);
await generateBinderAction.handle(generateBinder.inputs, generateBinder.options);
const generateFormatterAction = new generate_action_1.GenerateAction();
const generateFormatter = await this.getInputsForGenerateExamples(projectNameInput.value, inputs, options, generateFormatterAction, "formatter");
this.setInput(generateFormatter.options, "flat", true);
await generateFormatterAction.handle(generateFormatter.inputs, generateFormatter.options);
} |
JavaScript | function formatScale(x) {
if (x >= "1" && x <= "5") return satisfactionLabels[x];
if (x === '') return satisfactionLabels[0];
return x;
} | function formatScale(x) {
if (x >= "1" && x <= "5") return satisfactionLabels[x];
if (x === '') return satisfactionLabels[0];
return x;
} |
JavaScript | function formatResponse(resp) {
var retstr = "";
retstr += " <dl>";
retstr += " <b>Entry Number:</b> "+resp.Response;
retstr += " <b>Attend Forum:</b> "+formatScale(resp.Attend);
retstr += " <b>View online:</b> "+formatScale(resp.View);
retstr += " <br />";
retstr += " <b>Municipal Tax Value:</b> "+formatScale(resp.Muni);
retstr += " <b>School Tax Value:</b> "+formatScale(resp.School);
retstr += " <b>Overall Tax:</b> "+formatScale(resp.Taxes);
retstr += " <br /> <br />";
retstr += "<dt>Takeaway:</dt> <dd>"+cleanText(resp.Takeaway) + "</dd>";
retstr += "<dt>Like about Lyme:</dt> <dd>"+cleanText(resp.Like) + "</dd>";
retstr += "<dt>Desirable Changes:</dt> <dd>"+cleanText(resp.Change)+ "</dd>";
retstr += "<dt>How address:</dt> <dd>"+cleanText(resp["How-address"]) + "</dd>";
retstr += "<dt>Other thoughts:</dt> <dd>"+cleanText(resp.Other) + "</dd>";
retstr += "</dl>";
return retstr;
} | function formatResponse(resp) {
var retstr = "";
retstr += " <dl>";
retstr += " <b>Entry Number:</b> "+resp.Response;
retstr += " <b>Attend Forum:</b> "+formatScale(resp.Attend);
retstr += " <b>View online:</b> "+formatScale(resp.View);
retstr += " <br />";
retstr += " <b>Municipal Tax Value:</b> "+formatScale(resp.Muni);
retstr += " <b>School Tax Value:</b> "+formatScale(resp.School);
retstr += " <b>Overall Tax:</b> "+formatScale(resp.Taxes);
retstr += " <br /> <br />";
retstr += "<dt>Takeaway:</dt> <dd>"+cleanText(resp.Takeaway) + "</dd>";
retstr += "<dt>Like about Lyme:</dt> <dd>"+cleanText(resp.Like) + "</dd>";
retstr += "<dt>Desirable Changes:</dt> <dd>"+cleanText(resp.Change)+ "</dd>";
retstr += "<dt>How address:</dt> <dd>"+cleanText(resp["How-address"]) + "</dd>";
retstr += "<dt>Other thoughts:</dt> <dd>"+cleanText(resp.Other) + "</dd>";
retstr += "</dl>";
return retstr;
} |
JavaScript | function tableize(ary, prop, qID) {
var theResps = ary
.map(function(x) { return { resp: x[prop] , item: x.Response} } ) // return an object with the requested prop and its Response #
.map(function(x) { return Object.assign(x, { resp: x.resp.trim()} ) } ) // remove leading & trailing whitespace from the requested prop
.filter(function(x) { return /\S/.test(x.resp) } ) // filter out empty strings
.map(function(x) { /* console.log(x.resp); */ return Object.assign(x, {resp: x.resp.replace(/\n/g,"<br />")}) } ) // substitute \n with <br />
.map(function(x) { return x.resp + " <i>(Answer #" + x.item + ")</i>"}); // append the response # in paren's
document.getElementById("ct"+qID).innerHTML = theResps.length;
var theDom = theResps.reduce(tablerow,"");
document.getElementById("r"+qID).innerHTML = theDom;
} | function tableize(ary, prop, qID) {
var theResps = ary
.map(function(x) { return { resp: x[prop] , item: x.Response} } ) // return an object with the requested prop and its Response #
.map(function(x) { return Object.assign(x, { resp: x.resp.trim()} ) } ) // remove leading & trailing whitespace from the requested prop
.filter(function(x) { return /\S/.test(x.resp) } ) // filter out empty strings
.map(function(x) { /* console.log(x.resp); */ return Object.assign(x, {resp: x.resp.replace(/\n/g,"<br />")}) } ) // substitute \n with <br />
.map(function(x) { return x.resp + " <i>(Answer #" + x.item + ")</i>"}); // append the response # in paren's
document.getElementById("ct"+qID).innerHTML = theResps.length;
var theDom = theResps.reduce(tablerow,"");
document.getElementById("r"+qID).innerHTML = theDom;
} |
JavaScript | function countResponses(accum, x) {
if (accum[x] === undefined) {
accum[x] = 0;
}
accum[x]++;
return accum;
} | function countResponses(accum, x) {
if (accum[x] === undefined) {
accum[x] = 0;
}
accum[x]++;
return accum;
} |
JavaScript | function summarizeResponses(ary, prop, labels) {
var zeroAry = {};
labels.forEach(function(x) { zeroAry[x] = 0 });
var retary = ary
.map(function(x) { return x[prop] } )
.map(function(x) { if (x >= "1" && x <= "5") { x = labels[x] } return x; } )
.map(function(x) { if (x === '') { x = "N/A"; } return x; } ) // Fix up empty string
.map(function(x) { if (x === null) { x = "N/A"; } return x; } ) // Fix up "null"
.reduce(countResponses, zeroAry);
return retary;
} | function summarizeResponses(ary, prop, labels) {
var zeroAry = {};
labels.forEach(function(x) { zeroAry[x] = 0 });
var retary = ary
.map(function(x) { return x[prop] } )
.map(function(x) { if (x >= "1" && x <= "5") { x = labels[x] } return x; } )
.map(function(x) { if (x === '') { x = "N/A"; } return x; } ) // Fix up empty string
.map(function(x) { if (x === null) { x = "N/A"; } return x; } ) // Fix up "null"
.reduce(countResponses, zeroAry);
return retary;
} |
JavaScript | function formatResponse(resp) {
var retstr = "";
retstr += " <dl>";
retstr += " <b>Answer Number:</b> "+resp.Response;
retstr += " <b>Attend Forum:</b> "+formatScale(resp.Attend);
retstr += " <b>View online:</b> "+formatScale(resp.View);
retstr += " <br />";
retstr += " <b>Municipal Tax Value:</b> "+formatScale(resp.Muni);
retstr += " <b>School Tax Value:</b> "+formatScale(resp.School);
retstr += " <b>Overall Tax:</b> "+formatScale(resp.Taxes);
retstr += " <br /> <br />";
retstr += "<dt>Takeaway:</dt> <dd>"+cleanText(resp.Takeaway) + "</dd>";
retstr += "<dt>Like about Lyme:</dt> <dd>"+cleanText(resp.Like) + "</dd>";
retstr += "<dt>Desirable Changes:</dt> <dd>"+cleanText(resp.Change)+ "</dd>";
retstr += "<dt>How address:</dt> <dd>"+cleanText(resp["How-address"]) + "</dd>";
retstr += "<dt>Other thoughts:</dt> <dd>"+cleanText(resp.Other) + "</dd>";
retstr += "</dl>";
return retstr;
} | function formatResponse(resp) {
var retstr = "";
retstr += " <dl>";
retstr += " <b>Answer Number:</b> "+resp.Response;
retstr += " <b>Attend Forum:</b> "+formatScale(resp.Attend);
retstr += " <b>View online:</b> "+formatScale(resp.View);
retstr += " <br />";
retstr += " <b>Municipal Tax Value:</b> "+formatScale(resp.Muni);
retstr += " <b>School Tax Value:</b> "+formatScale(resp.School);
retstr += " <b>Overall Tax:</b> "+formatScale(resp.Taxes);
retstr += " <br /> <br />";
retstr += "<dt>Takeaway:</dt> <dd>"+cleanText(resp.Takeaway) + "</dd>";
retstr += "<dt>Like about Lyme:</dt> <dd>"+cleanText(resp.Like) + "</dd>";
retstr += "<dt>Desirable Changes:</dt> <dd>"+cleanText(resp.Change)+ "</dd>";
retstr += "<dt>How address:</dt> <dd>"+cleanText(resp["How-address"]) + "</dd>";
retstr += "<dt>Other thoughts:</dt> <dd>"+cleanText(resp.Other) + "</dd>";
retstr += "</dl>";
return retstr;
} |
JavaScript | function deleteUrl(req, res) {
let id = req.params.id;
Url.findByIdAndRemove(id, (err, urlDeleted) => {
if (err) {
return res.status(500).json({mensaje: "Error to delete url"});
}
if (!urlDeleted) {
return res.status(400).json({mensaje: "Url doesnt exist"});
}
res.status(200).json({
ok: true,
url: urlDeleted
});
});
} | function deleteUrl(req, res) {
let id = req.params.id;
Url.findByIdAndRemove(id, (err, urlDeleted) => {
if (err) {
return res.status(500).json({mensaje: "Error to delete url"});
}
if (!urlDeleted) {
return res.status(400).json({mensaje: "Url doesnt exist"});
}
res.status(200).json({
ok: true,
url: urlDeleted
});
});
} |
JavaScript | async function saveUrl(req, res) {
// init vars
let originalUrl = req.body.original; // original url
// check if url structure is all right
if (!services.isValidUrl(originalUrl)) {
res.status(400).send({ message: `Favor ingresar una url válida` })
}
// if url structure is fine then generate a short url with async-wait es6
else {
let existUrl = await generateUniqueShortUrl();
if(existUrl){
return res.status(400).json({ message: `this url is already in use` });
}
// Try to find shortUrl on BD
Url.findOne({ short: shortUrl })
.exec((err, urlExistDB) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: "Error finding url - mongodb",
errors: err
});
}
if (urlExistDB) {
return res.status(400).json({
ok: false,
mensaje: `Url: ${shortUrl} is already exist on db!`
});
}
// If code go far to this point is everything is OK, then save url !!!
let url = new Url({
short: `${shortUrl}`,
prettyUrl: `${config.host}:${config.port}/${shortUrl}`,
original: originalUrl,
});
url.save((err, urlSaved) => {
if (err) {
return res.status(400).json({
ok: false,
mensaje: "something went wrong to create a short url!! :(",
errors: err
});
}
res.status(200).json({
ok: true,
url: urlSaved
});
})
})
}
} | async function saveUrl(req, res) {
// init vars
let originalUrl = req.body.original; // original url
// check if url structure is all right
if (!services.isValidUrl(originalUrl)) {
res.status(400).send({ message: `Favor ingresar una url válida` })
}
// if url structure is fine then generate a short url with async-wait es6
else {
let existUrl = await generateUniqueShortUrl();
if(existUrl){
return res.status(400).json({ message: `this url is already in use` });
}
// Try to find shortUrl on BD
Url.findOne({ short: shortUrl })
.exec((err, urlExistDB) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: "Error finding url - mongodb",
errors: err
});
}
if (urlExistDB) {
return res.status(400).json({
ok: false,
mensaje: `Url: ${shortUrl} is already exist on db!`
});
}
// If code go far to this point is everything is OK, then save url !!!
let url = new Url({
short: `${shortUrl}`,
prettyUrl: `${config.host}:${config.port}/${shortUrl}`,
original: originalUrl,
});
url.save((err, urlSaved) => {
if (err) {
return res.status(400).json({
ok: false,
mensaje: "something went wrong to create a short url!! :(",
errors: err
});
}
res.status(200).json({
ok: true,
url: urlSaved
});
})
})
}
} |
JavaScript | async function generateUniqueShortUrl() {
// Get random short url generated
shortUrl = await services.generateShortUrl();
// Verify url doesn't exist
var exist = await services.alreadyUsed(shortUrl);
// return true or false
return new Promise((resolve) => { resolve(exist) })
} | async function generateUniqueShortUrl() {
// Get random short url generated
shortUrl = await services.generateShortUrl();
// Verify url doesn't exist
var exist = await services.alreadyUsed(shortUrl);
// return true or false
return new Promise((resolve) => { resolve(exist) })
} |
JavaScript | function parseDamage() {
let json = {};
fs.readFile(demoPath, function (err, buffer) {
assert.ifError(err);
let demoFile = new demofile.DemoFile();
let teamT;
let teamCT;
let totalDamages = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
demoFile.gameEvents.on('round_announce_match_start', () => {
teamT = demoFile.teams[demofile.TEAM_TERRORISTS];
teamCT = demoFile.teams[demofile.TEAM_CTS];
json['0'] = {};
json['0']['terrorists'] = {};
json['0']['terrorists']['teamName'] = teamT.clanName;
json['0']['terrorists']['players'] = [];
for (p of teamT.members) {
json['0']['terrorists']['players'].push({
'name': p.name,
'damage': 0,
'adr': 0
});
}
json['0']['cts'] = {};
json['0']['cts']['teamName'] = teamCT.clanName;
json['0']['cts']['players'] = [];
for (p of teamCT.members) {
json['0']['cts']['players'].push({
'name': p.name,
'damage': 0,
'adr': 0
});
}
});
demoFile.gameEvents.on('round_end', () => {
if (teamT == undefined || teamCT == undefined) return;
let roundNumber = demoFile.gameRules.roundsPlayed;
if (roundNumber > 30) return;
let time = Math.ceil(demoFile.currentTime);
let i = 0;
json[time] = {};
json[time]['terrorists'] = {};
json[time]['terrorists']['teamName'] = teamT.clanName;
json[time]['terrorists']['players'] = [];
for (p of teamT.members) {
totalDamages[i] += p.matchStats[roundNumber-1].damage;
json[time]['terrorists']['players'].push({
'name': p.name,
'damage': totalDamages[i],
'adr': totalDamages[i]/(roundNumber)
});
i++;
}
json[time]['cts'] = {};
json[time]['cts']['teamName'] = teamCT.clanName;
json[time]['cts']['players'] = [];
for (p of teamCT.members) {
totalDamages[i] += p.matchStats[roundNumber-1].damage;
json[time]['cts']['players'].push({
'name': p.name,
'damage': totalDamages[i],
'adr': totalDamages[i]/(roundNumber)
});
i++;
}
});
demoFile.on('end', () => {
let fileName = demoPath.substring(0, demoPath.length-4) + '-damage.json';
let dir = fileName.split('-', 3).join('-');
fs.writeFile('json/' + dir + '/' + fileName, JSON.stringify(json, null, 2), (err) => {
if (err) throw err;
console.log(fileName + ' has been saved.');
});
});
demoFile.parse(buffer);
});
} | function parseDamage() {
let json = {};
fs.readFile(demoPath, function (err, buffer) {
assert.ifError(err);
let demoFile = new demofile.DemoFile();
let teamT;
let teamCT;
let totalDamages = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
demoFile.gameEvents.on('round_announce_match_start', () => {
teamT = demoFile.teams[demofile.TEAM_TERRORISTS];
teamCT = demoFile.teams[demofile.TEAM_CTS];
json['0'] = {};
json['0']['terrorists'] = {};
json['0']['terrorists']['teamName'] = teamT.clanName;
json['0']['terrorists']['players'] = [];
for (p of teamT.members) {
json['0']['terrorists']['players'].push({
'name': p.name,
'damage': 0,
'adr': 0
});
}
json['0']['cts'] = {};
json['0']['cts']['teamName'] = teamCT.clanName;
json['0']['cts']['players'] = [];
for (p of teamCT.members) {
json['0']['cts']['players'].push({
'name': p.name,
'damage': 0,
'adr': 0
});
}
});
demoFile.gameEvents.on('round_end', () => {
if (teamT == undefined || teamCT == undefined) return;
let roundNumber = demoFile.gameRules.roundsPlayed;
if (roundNumber > 30) return;
let time = Math.ceil(demoFile.currentTime);
let i = 0;
json[time] = {};
json[time]['terrorists'] = {};
json[time]['terrorists']['teamName'] = teamT.clanName;
json[time]['terrorists']['players'] = [];
for (p of teamT.members) {
totalDamages[i] += p.matchStats[roundNumber-1].damage;
json[time]['terrorists']['players'].push({
'name': p.name,
'damage': totalDamages[i],
'adr': totalDamages[i]/(roundNumber)
});
i++;
}
json[time]['cts'] = {};
json[time]['cts']['teamName'] = teamCT.clanName;
json[time]['cts']['players'] = [];
for (p of teamCT.members) {
totalDamages[i] += p.matchStats[roundNumber-1].damage;
json[time]['cts']['players'].push({
'name': p.name,
'damage': totalDamages[i],
'adr': totalDamages[i]/(roundNumber)
});
i++;
}
});
demoFile.on('end', () => {
let fileName = demoPath.substring(0, demoPath.length-4) + '-damage.json';
let dir = fileName.split('-', 3).join('-');
fs.writeFile('json/' + dir + '/' + fileName, JSON.stringify(json, null, 2), (err) => {
if (err) throw err;
console.log(fileName + ' has been saved.');
});
});
demoFile.parse(buffer);
});
} |
JavaScript | function parseEconomy() {
let json = {};
json['0'] = [];
let rounds = [];
function getEconomy(demoFile) {
let teamT = demoFile.teams[demofile.TEAM_TERRORISTS];
let teamCT = demoFile.teams[demofile.TEAM_CTS];
if (teamT == undefined || teamCT == undefined) return;
let terroristsRoundStartAccount = 0;
let terroristsRoundSpendValue = 0;
let ctRoundStartAccount = 0;
let ctRoundSpendValue = 0;
for (p of teamT.members) {
terroristsRoundStartAccount += p.account;
terroristsRoundSpendValue += p.cashSpendThisRound;
}
for (p of teamCT.members) {
ctRoundStartAccount += p.account;
ctRoundSpendValue += p.cashSpendThisRound;
}
let time = Math.ceil(demoFile.currentTime);
rounds.push({
'roundNumber': demoFile.gameRules.roundsPlayed+1,
'terroristsRoundStartAccount': terroristsRoundStartAccount,
'terroristsRoundSpendValue': terroristsRoundSpendValue,
'ctRoundStartAccount': ctRoundStartAccount,
'ctRoundSpendValue': ctRoundSpendValue
});
json[time] = rounds.slice(0);
/*
json[time] = {};
json[time]['roundNumber'] = demoFile.gameRules.roundsPlayed+1;
json[time]['terroristsRoundStartAccount'] = terroristsRoundStartAccount;
json[time]['terroristsRoundSpendValue'] = terroristsRoundSpendValue;
json[time]['ctRoundStartAccount'] = ctRoundStartAccount;
json[time]['ctRoundSpendValue'] = ctRoundSpendValue;
*/
}
fs.readFile(demoPath, function (err, buffer) {
assert.ifError(err);
let demoFile = new demofile.DemoFile();
let teamT;
let teamCT;
demoFile.gameEvents.on('round_announce_match_start', () => {
getEconomy(demoFile);
});
demoFile.gameEvents.on('round_end', () => {
getEconomy(demoFile);
});
demoFile.on('end', () => {
let fileName = demoPath.substring(0, demoPath.length-4) + '-economy.json';
let dir = fileName.split('-', 3).join('-');
fs.writeFile('json/' + dir + '/' + fileName, JSON.stringify(json, null, 2), (err) => {
if (err) throw err;
console.log(fileName + ' has been saved.');
});
});
demoFile.parse(buffer);
});
} | function parseEconomy() {
let json = {};
json['0'] = [];
let rounds = [];
function getEconomy(demoFile) {
let teamT = demoFile.teams[demofile.TEAM_TERRORISTS];
let teamCT = demoFile.teams[demofile.TEAM_CTS];
if (teamT == undefined || teamCT == undefined) return;
let terroristsRoundStartAccount = 0;
let terroristsRoundSpendValue = 0;
let ctRoundStartAccount = 0;
let ctRoundSpendValue = 0;
for (p of teamT.members) {
terroristsRoundStartAccount += p.account;
terroristsRoundSpendValue += p.cashSpendThisRound;
}
for (p of teamCT.members) {
ctRoundStartAccount += p.account;
ctRoundSpendValue += p.cashSpendThisRound;
}
let time = Math.ceil(demoFile.currentTime);
rounds.push({
'roundNumber': demoFile.gameRules.roundsPlayed+1,
'terroristsRoundStartAccount': terroristsRoundStartAccount,
'terroristsRoundSpendValue': terroristsRoundSpendValue,
'ctRoundStartAccount': ctRoundStartAccount,
'ctRoundSpendValue': ctRoundSpendValue
});
json[time] = rounds.slice(0);
/*
json[time] = {};
json[time]['roundNumber'] = demoFile.gameRules.roundsPlayed+1;
json[time]['terroristsRoundStartAccount'] = terroristsRoundStartAccount;
json[time]['terroristsRoundSpendValue'] = terroristsRoundSpendValue;
json[time]['ctRoundStartAccount'] = ctRoundStartAccount;
json[time]['ctRoundSpendValue'] = ctRoundSpendValue;
*/
}
fs.readFile(demoPath, function (err, buffer) {
assert.ifError(err);
let demoFile = new demofile.DemoFile();
let teamT;
let teamCT;
demoFile.gameEvents.on('round_announce_match_start', () => {
getEconomy(demoFile);
});
demoFile.gameEvents.on('round_end', () => {
getEconomy(demoFile);
});
demoFile.on('end', () => {
let fileName = demoPath.substring(0, demoPath.length-4) + '-economy.json';
let dir = fileName.split('-', 3).join('-');
fs.writeFile('json/' + dir + '/' + fileName, JSON.stringify(json, null, 2), (err) => {
if (err) throw err;
console.log(fileName + ' has been saved.');
});
});
demoFile.parse(buffer);
});
} |
JavaScript | async Transfer(ctx,from, to, value) {
// const from = ctx.clientIdentity.getID();
const transferResp = await this._transfer(ctx, from, to, value);
if (!transferResp) {
throw new Error('Failed to transfer');
}
// // Emit the Transfer event
// const transferEvent = { from, to, value: parseInt(value) };
// ctx.stub.setEvent('Transfer', Buffer.from(JSON.stringify(transferEvent)));
return true;
} | async Transfer(ctx,from, to, value) {
// const from = ctx.clientIdentity.getID();
const transferResp = await this._transfer(ctx, from, to, value);
if (!transferResp) {
throw new Error('Failed to transfer');
}
// // Emit the Transfer event
// const transferEvent = { from, to, value: parseInt(value) };
// ctx.stub.setEvent('Transfer', Buffer.from(JSON.stringify(transferEvent)));
return true;
} |
JavaScript | async Mint(ctx, amount, recipient) {
// Check minter authorization - this sample assumes Org1 is the central banker with privilege to mint new tokens
const clientMSPID = ctx.clientIdentity.getMSPID();
if (clientMSPID !== 'Org1MSP') {
throw new Error('client is not authorized to mint new tokens');
}
// Get ID of submitting client identity
// const minter = ctx.clientIdentity.getID();
const minter = recipient;
console.log("minter : "+minter)
// console.log("minter2 : "+minter2)
const amountInt = parseInt(amount);
if (amountInt <= 0) {
throw new Error('mint amount must be a positive integer');
}
const balanceKey = ctx.stub.createCompositeKey(balancePrefix, [minter]);
const currentBalanceBytes = await ctx.stub.getState(balanceKey);
// If minter current balance doesn't yet exist, we'll create it with a current balance of 0
let currentBalance;
if (!currentBalanceBytes || currentBalanceBytes.length === 0) {
currentBalance = 0;
} else {
currentBalance = parseInt(currentBalanceBytes.toString());
}
const updatedBalance = currentBalance + amountInt;
await ctx.stub.putState(balanceKey, Buffer.from(updatedBalance.toString()));
// Increase totalSupply
const totalSupplyBytes = await ctx.stub.getState(totalSupplyKey);
let totalSupply;
if (!totalSupplyBytes || totalSupplyBytes.length === 0) {
console.log('Initialize the tokenSupply');
totalSupply = 0;
} else {
totalSupply = parseInt(totalSupplyBytes.toString());
}
totalSupply = totalSupply + amountInt;
await ctx.stub.putState(totalSupplyKey, Buffer.from(totalSupply.toString()));
// Emit the Transfer event
const transferEvent = { from: '0x0', to: minter, value: amountInt };
ctx.stub.setEvent('Transfer', Buffer.from(JSON.stringify(transferEvent)));
console.log(`minter account ${minter} balance updated from ${currentBalance} to ${updatedBalance}`);
return true;
} | async Mint(ctx, amount, recipient) {
// Check minter authorization - this sample assumes Org1 is the central banker with privilege to mint new tokens
const clientMSPID = ctx.clientIdentity.getMSPID();
if (clientMSPID !== 'Org1MSP') {
throw new Error('client is not authorized to mint new tokens');
}
// Get ID of submitting client identity
// const minter = ctx.clientIdentity.getID();
const minter = recipient;
console.log("minter : "+minter)
// console.log("minter2 : "+minter2)
const amountInt = parseInt(amount);
if (amountInt <= 0) {
throw new Error('mint amount must be a positive integer');
}
const balanceKey = ctx.stub.createCompositeKey(balancePrefix, [minter]);
const currentBalanceBytes = await ctx.stub.getState(balanceKey);
// If minter current balance doesn't yet exist, we'll create it with a current balance of 0
let currentBalance;
if (!currentBalanceBytes || currentBalanceBytes.length === 0) {
currentBalance = 0;
} else {
currentBalance = parseInt(currentBalanceBytes.toString());
}
const updatedBalance = currentBalance + amountInt;
await ctx.stub.putState(balanceKey, Buffer.from(updatedBalance.toString()));
// Increase totalSupply
const totalSupplyBytes = await ctx.stub.getState(totalSupplyKey);
let totalSupply;
if (!totalSupplyBytes || totalSupplyBytes.length === 0) {
console.log('Initialize the tokenSupply');
totalSupply = 0;
} else {
totalSupply = parseInt(totalSupplyBytes.toString());
}
totalSupply = totalSupply + amountInt;
await ctx.stub.putState(totalSupplyKey, Buffer.from(totalSupply.toString()));
// Emit the Transfer event
const transferEvent = { from: '0x0', to: minter, value: amountInt };
ctx.stub.setEvent('Transfer', Buffer.from(JSON.stringify(transferEvent)));
console.log(`minter account ${minter} balance updated from ${currentBalance} to ${updatedBalance}`);
return true;
} |
JavaScript | async ClientAccountBalance(ctx,userId) {
// Get ID of submitting client identity
const clientAccountID = ctx.clientIdentity.getID();
console.log(`client ACOUNT: ${clientAccountID}`)
// const clientAccountID = acountId;
const balanceKey = ctx.stub.createCompositeKey(balancePrefix, [clientAccountID]);
const balanceBytes = await ctx.stub.getState(balanceKey);
if (!balanceBytes || balanceBytes.length === 0) {
// throw new Error(`the account ${clientAccountID} does not exist`);
return 0;
}
let listMoneyDetention = await this.getMoneyDetention(ctx,userId)
console.log(`listMoneyDetention ${listMoneyDetention}`)
let allMoney = 0;
for(let el in listMoneyDetention){
allMoney += listMoneyDetention[el].value.MoneyDetention;
}
console.log(allMoney);
const balance = parseInt(balanceBytes.toString()) - parseInt(allMoney);
// const balance = parseInt(balanceBytes.toString());
return balance ;
} | async ClientAccountBalance(ctx,userId) {
// Get ID of submitting client identity
const clientAccountID = ctx.clientIdentity.getID();
console.log(`client ACOUNT: ${clientAccountID}`)
// const clientAccountID = acountId;
const balanceKey = ctx.stub.createCompositeKey(balancePrefix, [clientAccountID]);
const balanceBytes = await ctx.stub.getState(balanceKey);
if (!balanceBytes || balanceBytes.length === 0) {
// throw new Error(`the account ${clientAccountID} does not exist`);
return 0;
}
let listMoneyDetention = await this.getMoneyDetention(ctx,userId)
console.log(`listMoneyDetention ${listMoneyDetention}`)
let allMoney = 0;
for(let el in listMoneyDetention){
allMoney += listMoneyDetention[el].value.MoneyDetention;
}
console.log(allMoney);
const balance = parseInt(balanceBytes.toString()) - parseInt(allMoney);
// const balance = parseInt(balanceBytes.toString());
return balance ;
} |
JavaScript | function extractRange(ranges, coord) {
var axis, from, to, key, axes = plot.getAxes();
for (var k in axes) {
axis = axes[k];
if (axis.direction == coord) {
key = coord + axis.n + 'axis';
if (!ranges[key] && axis.n == 1)
key = coord + 'axis'; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == 'x' ? plot.getXAxes()[0] : plot.getYAxes()[0];
from = ranges[coord + '1'];
to = ranges[coord + '2'];
}
// auto-reverse as an added bonus
if (from !== null && to !== null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return {from: from, to: to, axis: axis};
} | function extractRange(ranges, coord) {
var axis, from, to, key, axes = plot.getAxes();
for (var k in axes) {
axis = axes[k];
if (axis.direction == coord) {
key = coord + axis.n + 'axis';
if (!ranges[key] && axis.n == 1)
key = coord + 'axis'; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == 'x' ? plot.getXAxes()[0] : plot.getYAxes()[0];
from = ranges[coord + '1'];
to = ranges[coord + '2'];
}
// auto-reverse as an added bonus
if (from !== null && to !== null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return {from: from, to: to, axis: axis};
} |
JavaScript | function lint () {
return gulp.src(paths.scripts)
.pipe(jshint())
.pipe(jshint.reporter(stylish))
;
} | function lint () {
return gulp.src(paths.scripts)
.pipe(jshint())
.pipe(jshint.reporter(stylish))
;
} |
JavaScript | function isAuthenticated() {
return compose()
// Validate jwt
.use(function(req, res, next) {
// allow access_token to be passed through query parameter as well
if(req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
}
validateJwt(req, res, next);
})
// Attach user to request
.use(function(req, res, next) {
User.findById(req.user._id, function (err, user) {
if (err) return next(err);
if (!user) return res.send(401);
req.user = user;
next();
});
});
} | function isAuthenticated() {
return compose()
// Validate jwt
.use(function(req, res, next) {
// allow access_token to be passed through query parameter as well
if(req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
}
validateJwt(req, res, next);
})
// Attach user to request
.use(function(req, res, next) {
User.findById(req.user._id, function (err, user) {
if (err) return next(err);
if (!user) return res.send(401);
req.user = user;
next();
});
});
} |
JavaScript | function isOptionallyAuthenticated() {
return compose()
// Validate jwt
.use(function(req, res, next) {
// allow access_token to be passed through query parameter as well
if(req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
} else {
req.headers.authorization = 'Bearer false'
}
unsecurelyValidateJwt(req, res, next);
})
// Attach user to request
.use(function(req, res, next) {
if (req.user) {
User.findById(req.user._id, function (err, user) {
if (err) return next(err);
if (!user) return res.send(401);
req.user = user;
next();
});
} else {
next();
}
});
} | function isOptionallyAuthenticated() {
return compose()
// Validate jwt
.use(function(req, res, next) {
// allow access_token to be passed through query parameter as well
if(req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
} else {
req.headers.authorization = 'Bearer false'
}
unsecurelyValidateJwt(req, res, next);
})
// Attach user to request
.use(function(req, res, next) {
if (req.user) {
User.findById(req.user._id, function (err, user) {
if (err) return next(err);
if (!user) return res.send(401);
req.user = user;
next();
});
} else {
next();
}
});
} |
JavaScript | function hasAdminOrTeacher() {
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (req.user.academicRole === 'Teacher' || req.user.role==='admin') {
next();
}
else {
res.send(403);
}
});
} | function hasAdminOrTeacher() {
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (req.user.academicRole === 'Teacher' || req.user.role==='admin') {
next();
}
else {
res.send(403);
}
});
} |
JavaScript | function hasClass(classToCheck) {
if (!classToCheck) throw new Error('Class needs to be set');
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (config.subjects.indexOf(classToCheck) === -1) {
throw new Error('Class is invalid.')
}
else if (req.user.subjects.indexOf(classToCheck) >= -1) {
next();
}
else {
res.send(403);
}
});
} | function hasClass(classToCheck) {
if (!classToCheck) throw new Error('Class needs to be set');
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (config.subjects.indexOf(classToCheck) === -1) {
throw new Error('Class is invalid.')
}
else if (req.user.subjects.indexOf(classToCheck) >= -1) {
next();
}
else {
res.send(403);
}
});
} |
JavaScript | function resetStatCounter(req, res) {
var resetDate = new Date(req.body.date);
config.statDate = resetDate;
console.log(resetDate);
console.log(typeof resetDate);
res.json(true);
} | function resetStatCounter(req, res) {
var resetDate = new Date(req.body.date);
config.statDate = resetDate;
console.log(resetDate);
console.log(typeof resetDate);
res.json(true);
} |
JavaScript | function onConnect(socket) {
// When the client emits 'info', this listens and executes
socket.on('info', function (data) {
console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2));
});
// Insert sockets below
require('../api/assignment/assignment.socket').register(socket);
require('../api/classroom/classroom.socket').register(socket);
require('../api/userAnalytic/userAnalytic.socket').register(socket);
require('../api/question/question.socket').register(socket);
require('../api/surveyResponse/surveyResponse.socket').register(socket);
require('../api/survey/survey.socket').register(socket);
require('../api/settings/settings.socket').register(socket);
require('../api/share/share.socket').register(socket);
require('../api/coupon/coupon.socket').register(socket);
require('../api/exam/exam.socket').register(socket);
require('../api/communityLeaders/communityLeaders.socket').register(socket);
require('../api/omnipoint/omnipoint.socket').register(socket);
require('../api/blockuser/blockuser.socket').register(socket);
require('../api/chatrooms/chatrooms.socket').register(socket);
require('../api/chatarchive/chatarchive.socket').register(socket);
require('../api/chatmessage/chatmessage.socket').register(socket);
require('../api/betaKey/betaKey.socket').register(socket);
require('../api/email/email.socket').register(socket);
require('../api/token/token.socket').register(socket);
require('../api/user/user.socket').register(socket);
} | function onConnect(socket) {
// When the client emits 'info', this listens and executes
socket.on('info', function (data) {
console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2));
});
// Insert sockets below
require('../api/assignment/assignment.socket').register(socket);
require('../api/classroom/classroom.socket').register(socket);
require('../api/userAnalytic/userAnalytic.socket').register(socket);
require('../api/question/question.socket').register(socket);
require('../api/surveyResponse/surveyResponse.socket').register(socket);
require('../api/survey/survey.socket').register(socket);
require('../api/settings/settings.socket').register(socket);
require('../api/share/share.socket').register(socket);
require('../api/coupon/coupon.socket').register(socket);
require('../api/exam/exam.socket').register(socket);
require('../api/communityLeaders/communityLeaders.socket').register(socket);
require('../api/omnipoint/omnipoint.socket').register(socket);
require('../api/blockuser/blockuser.socket').register(socket);
require('../api/chatrooms/chatrooms.socket').register(socket);
require('../api/chatarchive/chatarchive.socket').register(socket);
require('../api/chatmessage/chatmessage.socket').register(socket);
require('../api/betaKey/betaKey.socket').register(socket);
require('../api/email/email.socket').register(socket);
require('../api/token/token.socket').register(socket);
require('../api/user/user.socket').register(socket);
} |
JavaScript | function addContextElements() {
$('div[id] > :header:first').each(function () {
$('<a class="headerlink">\xB6</a>').attr('href', '#' + this.id).attr('title', _('Permalink to this headline')).appendTo(this);
});
$('dt[id]').each(function () {
$('<a class="headerlink">\xB6</a>').attr('href', '#' + this.id).attr('title', _('Permalink to this definition')).appendTo(this);
});
} | function addContextElements() {
$('div[id] > :header:first').each(function () {
$('<a class="headerlink">\xB6</a>').attr('href', '#' + this.id).attr('title', _('Permalink to this headline')).appendTo(this);
});
$('dt[id]').each(function () {
$('<a class="headerlink">\xB6</a>').attr('href', '#' + this.id).attr('title', _('Permalink to this definition')).appendTo(this);
});
} |
JavaScript | function highlightSearchWords() {
var params = $.getQueryParameters();
var terms = params.highlight ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
if (!body.length) {
body = $('body');
}
window.setTimeout(function () {
$.each(terms, function () {
body.highlightText(this.toLowerCase(), 'highlighted');
});
}, 10);
$('<p class="highlight-link"><a href="javascript:Documentation.' + 'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>').appendTo($('#searchbox'));
}
} | function highlightSearchWords() {
var params = $.getQueryParameters();
var terms = params.highlight ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
if (!body.length) {
body = $('body');
}
window.setTimeout(function () {
$.each(terms, function () {
body.highlightText(this.toLowerCase(), 'highlighted');
});
}, 10);
$('<p class="highlight-link"><a href="javascript:Documentation.' + 'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>').appendTo($('#searchbox'));
}
} |
JavaScript | function initIndexTable() {
var togglers = $('img.toggler').click(function () {
var src = $(this).attr('src');
var idnum = $(this).attr('id').substr(7);
$('tr.cg-' + idnum).toggle();
if (src.substr(-9) === 'minus.png') $(this).attr('src', src.substr(0, src.length - 9) + 'plus.png');else $(this).attr('src', src.substr(0, src.length - 8) + 'minus.png');
}).css('display', '');
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
togglers.click();
}
} | function initIndexTable() {
var togglers = $('img.toggler').click(function () {
var src = $(this).attr('src');
var idnum = $(this).attr('id').substr(7);
$('tr.cg-' + idnum).toggle();
if (src.substr(-9) === 'minus.png') $(this).attr('src', src.substr(0, src.length - 9) + 'plus.png');else $(this).attr('src', src.substr(0, src.length - 8) + 'minus.png');
}).css('display', '');
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
togglers.click();
}
} |
JavaScript | function arrayAtPolyfill(targetObj, parentArgLen, index) {
/**
* Checks whether the argument passed to the "targetObj" parameter is not
* undefined or null, which indicate empty "this" or target object values,
* and whether it has a "length" number data-type property. The "length"
* property must be included to indicate the number of entries as an
* integer in a consecutively-indexed range in the object.
*
* @throws -
* A TypeError exception if the argument to the "targetObj" parameter is
* undefined or null.
*
* @returns { boolean } -
* Boolean true or false depending on whether the value
*/
function checkTargetObj() {
if (typeof targetObj === "undefined" || targetObj === null) {
throw new TypeError("Parameter \"targetObj\" must not be null "
+ "or undefined.");
}
return typeof targetObj.length === "number";
}
/**
* Checks whether an argument was passed to the optional "index" parameter.
* If no index argument was specified or an index value is not a valid
* Number (NaN), defaults to an index value of 0 if the "targetObj"
* argument has entries.
*
* If it was, checks whether it represents a valid numerical index inside
* the range of values for the "targetObj" argument. An existing "index"
* argument is converted to a Number and has any decimal portion truncated
* to only include its integer portion. Negative integer values are
* subtracted from the end of the list, or "length" property, of the
* "targetObj" argument to try to determine a positive index inside of its
* entries range.
*
* @returns { boolean } -
* Boolean true if the index:
* - was not specified or is not a Number, and the "targetObj" argument has
* entries. This allows it to default to 0, or the first entry in the
* list.
* - is zero or positive and is in the range of entries in the "targetObj"
* argument, or less than the "length" property.
* - is negative and does not has an absolute value greater than the
* "length" property of "targetObj", allowing it to reference a valid
* positively or zero-indexed entry in the list.
*
* Boolean false if the index:
* - was not specified or is not a Number, and the "targetObj" argument has
* no entries. Thus, a default value of 0 does not reference an existing
* entry in the list.
* - is zero or positive and is greater than or equal to the "length"
* property of the "targetObj" argument of the list. The index value thus
* does not reference any entries in the range of the list.
* - is negative and has an absolute value greater than the "length"
* property of the "targetObj" parameter. The index value reaches before
* the start of the list, and thus does not reference any valid entries
* in its range.
*/
function checkIndex() {
index = Number(index);
if ( !parentArgLen || isNaN(index) ) {
if (targetObj.length) {
index = 0;
return true;
}
return false;
}
if (index >= 0) {
if (index < targetObj.length) {
index = Math.floor(index);
return true;
}
return false;
}
index = targetObj.length + Math.ceil(index);
return index >= 0;
}
/* Main function execution area */
return checkTargetObj() && checkIndex() ? targetObj[index] : undefined;
} | function arrayAtPolyfill(targetObj, parentArgLen, index) {
/**
* Checks whether the argument passed to the "targetObj" parameter is not
* undefined or null, which indicate empty "this" or target object values,
* and whether it has a "length" number data-type property. The "length"
* property must be included to indicate the number of entries as an
* integer in a consecutively-indexed range in the object.
*
* @throws -
* A TypeError exception if the argument to the "targetObj" parameter is
* undefined or null.
*
* @returns { boolean } -
* Boolean true or false depending on whether the value
*/
function checkTargetObj() {
if (typeof targetObj === "undefined" || targetObj === null) {
throw new TypeError("Parameter \"targetObj\" must not be null "
+ "or undefined.");
}
return typeof targetObj.length === "number";
}
/**
* Checks whether an argument was passed to the optional "index" parameter.
* If no index argument was specified or an index value is not a valid
* Number (NaN), defaults to an index value of 0 if the "targetObj"
* argument has entries.
*
* If it was, checks whether it represents a valid numerical index inside
* the range of values for the "targetObj" argument. An existing "index"
* argument is converted to a Number and has any decimal portion truncated
* to only include its integer portion. Negative integer values are
* subtracted from the end of the list, or "length" property, of the
* "targetObj" argument to try to determine a positive index inside of its
* entries range.
*
* @returns { boolean } -
* Boolean true if the index:
* - was not specified or is not a Number, and the "targetObj" argument has
* entries. This allows it to default to 0, or the first entry in the
* list.
* - is zero or positive and is in the range of entries in the "targetObj"
* argument, or less than the "length" property.
* - is negative and does not has an absolute value greater than the
* "length" property of "targetObj", allowing it to reference a valid
* positively or zero-indexed entry in the list.
*
* Boolean false if the index:
* - was not specified or is not a Number, and the "targetObj" argument has
* no entries. Thus, a default value of 0 does not reference an existing
* entry in the list.
* - is zero or positive and is greater than or equal to the "length"
* property of the "targetObj" argument of the list. The index value thus
* does not reference any entries in the range of the list.
* - is negative and has an absolute value greater than the "length"
* property of the "targetObj" parameter. The index value reaches before
* the start of the list, and thus does not reference any valid entries
* in its range.
*/
function checkIndex() {
index = Number(index);
if ( !parentArgLen || isNaN(index) ) {
if (targetObj.length) {
index = 0;
return true;
}
return false;
}
if (index >= 0) {
if (index < targetObj.length) {
index = Math.floor(index);
return true;
}
return false;
}
index = targetObj.length + Math.ceil(index);
return index >= 0;
}
/* Main function execution area */
return checkTargetObj() && checkIndex() ? targetObj[index] : undefined;
} |
JavaScript | function checkTargetObj() {
if (typeof targetObj === "undefined" || targetObj === null) {
throw new TypeError("Parameter \"targetObj\" must not be null "
+ "or undefined.");
}
return typeof targetObj.length === "number";
} | function checkTargetObj() {
if (typeof targetObj === "undefined" || targetObj === null) {
throw new TypeError("Parameter \"targetObj\" must not be null "
+ "or undefined.");
}
return typeof targetObj.length === "number";
} |
JavaScript | function checkIndex() {
index = Number(index);
if ( !parentArgLen || isNaN(index) ) {
if (targetObj.length) {
index = 0;
return true;
}
return false;
}
if (index >= 0) {
if (index < targetObj.length) {
index = Math.floor(index);
return true;
}
return false;
}
index = targetObj.length + Math.ceil(index);
return index >= 0;
} | function checkIndex() {
index = Number(index);
if ( !parentArgLen || isNaN(index) ) {
if (targetObj.length) {
index = 0;
return true;
}
return false;
}
if (index >= 0) {
if (index < targetObj.length) {
index = Math.floor(index);
return true;
}
return false;
}
index = targetObj.length + Math.ceil(index);
return index >= 0;
} |
JavaScript | function elementsByClass(className, container, getLive) {
/**
* - Checks whether the argument values passed to the parameters of the
* parent function are of the expected primitive data types, inherit from
* the proper Object classes, or implement the proper interfaces.
*
* - Checks if the "className" parameter's argument value is a string. If
* so, trims any leading or trailing whitespace characters and replaces
* any null characters in it.
*
* - Checks whether the "container" parameter had a value passed to it. If
* so, checks whether it is an Element or Document object container. If
* not, sets the "container" parameter's value to the current page's
* "document" object.
*
* @throws -
* A TypeError exception when:
* - The "className" parameter is not a string.
* - The "container" parameter is not an Element or Document object.
* A RangeError exception when:
* - The "className" parameter is an empty string.
*/
this.checkParameter = function() {
if (typeof className !== "string") {
throw new TypeError("Parameter \"className\" is not a string.");
}
if (className.trim) {
className = className.trim();
}
if (!className) {
throw new RangeError("Parameter \"className\" is an empty string.");
}
className = className.replace(/\0/g, '');
if (container) {
if (!this.isContainerElement(container)) {
throw new TypeError("Parameter \"container\" is not an "
+ "Element or HTMLDocument object.");
}
}
else {
container = document;
}
}
/**
* Checks whether a value is an Element or Document (HTMLDocument) object.
* If neither the Element class nor HTMLDocument interface is supported,
* checks whether the value:
* - is a non-null object;
* - has a nodeType "number" value of 1, indicating that it is an Element
* node, or 9, indicating that it is a Document node;
* - has the inline "style" property, indicating that it is an Element
* object; or
* - has the "documentElement" property, which references the "html" root
* element of the page's DOM "document" object.
*
* @param {any} obj - The value to be checked.
*
* @returns {boolean} -
* Boolean true or false depending on whether the "obj" parameter value is
* either an Element or a Document (HTMLDocument) object.
*/
this.isContainerElement = function(obj) {
if (typeof Element !== "undefined"
&& typeof HTMLDocument !== "undefined") {
return obj instanceof Element || obj instanceof HTMLDocument;
}
if (!obj) {
return false;
}
if (obj.nodeType === 1 && obj.style) {
return true;
}
return !!(obj.nodeType === 9 && obj.documentElement);
}
/**
* Checks whether a value is an Element object. If the Element is not
* supported, checks whether the value:
* - is a non-empty object;
* - has a nodeType "number" value of 1, indicating that it is an Element
* node; and
* - has the inline "style" property.
*
* @param {any} obj - The value to be checked.
*
* @returns {boolean} -
* Boolean true or false depending on whether the "obj" parameter value is
* an Element object.
*/
this.isElement = function(obj) {
if (typeof Element !== "undefined") {
return obj instanceof Element;
}
return !!(obj && obj.nodeType === 1 && obj.style);
}
/**
* Using the getElementsByClassName() method, tries to fetch a list of
* Element objects containing the target CSS class name(s) from within the
* child hierarchy of the "container" parameter Document or Element object.
* This functionality is the most modern and computionally the fastest out
* of all the list-retrieval methods in the parent function.
*
* @returns {HTMLCollection<Element> | undefined} -
* - If the getElementsByClassName() method is supported by the Element
* class or Document interface, returns a lively-updated HTMLCollection
* containing every Element object with the target CSS class name(s) under
* the "container" parameter value.
* - Returns undefined if the getElementsByClassName() method is not
* supported by the Element class or Document interface.
*/
this.byClassName = function() {
if (container.getElementsByClassName) {
return container.getElementsByClassName(className);
}
return undefined;
}
/**
* Using the querySelectorAll() method, tries to fetch a list of Element
* objects containing the target CSS class name(s) from within the child
* hierarchy of the "container" parameter Document or Element object. To be
* a valid CSS class selector, this method must escape any special,
* reserved CSS characters in the parent function's "className" parameter
* string argument with backslashes (\\), and any sequences of one or more
* whitespace characters separating CSS class names from one another must
* be replaced with a period (.) character.
*
* @returns {HTMLCollection<Element> | undefined} -
* - If the getElementsByClassName() method is supported by the Element
* class or Document interface, returns a lively-updated HTMLCollection
* containing every Element object containing the target CSS class name(s)
* under the "container" parameter value.
* - Returns undefined if the getElementsByClassName() method is not
* supported by the Element class or Document interface.
*/
this.byQuerySelector = function() {
if (!container.querySelectorAll) {
return undefined;
}
className = className.replace(
/([_!\"#\$%&\'\(\)\*\+-\.\/\\:;<=>\?@\[\,\]\^`\{\|\}~])/g,
function(match, specialChar) {
return '\\' + specialChar;
}
);
className = "." + className.replace(/[\s\uFEFF\xA0]+/g, ".");
return container.querySelectorAll(className);
}
/**
* Gets all of the Element objects from under the "container" parameter
* value's child hierarchy using the getElementsByTagName() method and adds
* the ones which contains the target CSS class name(s) to an Array.
*
* @throws -
* A ReferenceError exception if the containsCSSClass() function, which is
* used to check whether an Element contains the target CSS class names, is
* not currently loaded.
*
* @returns {Array<Element> | undefined} -
* - An Array containing any Element objects with the target CSS class
* name(s).
* - undefined if the getElementsByTagName() method is not supported by
* the Element class or the Document interface for the "container"
* parameter argument object.
*/
this.byTagNameBackup = function() {
if (!container.getElementsByTagName) {
return undefined;
}
if (typeof containsCSSClass !== "function") {
throw new ReferenceError("containsCSSClass() function "
+ "must be loaded in order to use the elementsByClass() "
+ "function.");
}
var elementList = container.getElementsByTagName("*");
var results = [], index, element;
for (index = 0; index < elementList.length; index++) {
element = elementList[index];
if (this.isElement(element)
&& containsCSSClass(element, className)) {
results.push(element);
}
}
return results;
}
/**
* Tries the various methods defined in the parent function for getting a
* list of Element objects with the target CSS class name(s) from the child
* hierarchy of the "container" parameter's argument object.
*
* @returns {HTMLCollection<Element> | NodeList<Element> | Array<Element> |
* null} -
* If the "getLive" parameter has a Boolean value passed to it, this method
* will try to return:
* - a lively-updated HTMLCollection of Element objects, if true; or
* - a static NodeList or Array of Element objects, if false.
*
* If the "getLive" parameter is undefined or not a Boolean value, this
* method may return either a lively-updated or a static list of Element
* objects with the target CSS class name(s). In this case, the method
* prioritizes more modern and computationally faster JavaScript methods
* over legacy and slower ones. More specifically, checked in the following
* order:
* - A live HTMLCollection of Element objects is returned if the Element
* class's or Document interface's getElementsByClassName() method is
* supported.
* - A static NodeList of Element objects is returned if the Element
* class's or Document interface's querySelectorAll() method is
* supported.
* - A static Array of Element objects is returned if the Element class's
* or Document interface's getElementsByTagName() method is supported and
* the external polyfill containsCSSClass() function is loaded.
*
* Returns null if none of the JavaScript methods used for retrieving a
* list of the target Element objects and relied on by the called methods
* are supported.
*/
this.tryMethods = function() {
if (typeof getLive === "boolean") {
return getLive ? this.liveMethods() : this.staticMethods();
}
return this.defaultMethods();
}
/**
* Tries any methods defined in the parent function for getting a
* lively-updated list of Element objects which contain the target CSS
* class name(s). Currently, this method only supports the Element class's
* and Document interface's getElementsByClassName() method for returning
* an Element HTMLCollection, which is always live. Implementing additional
* logic for fetching and updating a live list using JavaScript native
* methods can be very complex and computationally expensive.
*
* @returns {HTMLCollection<Element> | null} -
* - A lively-updated HTMLCollection containing Elements with the target
* CSS class name(s).
* - null if no additional JavaScript methods for returning a
* lively-updated list data structure of Element objects with the target
* CSS class names are supported.
*/
this.liveMethods = function() {
var result = this.byClassName();
return result === undefined ? null : result;
}
/**
* Tries any methods defined in the parent function for retrieving a static
* list of Element objects with the target CSS class name(s). Currently,
* this method relies on the Element class's and Document interface's:
* - querySelectorAll() method for returning a static NodeList; or
* - getElementsByTagName() method for getting all child Elements of the
* "container" parameter's argument object, searching through, and
* returning an Array of the target Element objects.
*
* @returns {NodeList<Element> | Array<Element> | null} -
* - A static NodeList or Array of the Element objects with the target CSS
* class name(s) in the child hierarchy of the "container" parameter's
* Element or Document argument object.
* - null if no JavaScript methods are supported for finding a static list
* of any target Element objects.
*/
this.staticMethods = function() {
var result = this.byQuerySelector();
if (result !== undefined) {
return result;
}
result = this.byTagNameBackup();
return result === undefined ? null : result;
}
/**
* Executes the methods of the parent function for retrieving a list data
* structure of Element objects with the target CSS class names in the
* child hierarchy of the "container" parameter's Element or Document
* value. Methods are executed in order of how modern the JavaScript
* functions which they use are and how quickly they perform. Either a
* lively-updated or a static NodeList of matching Element objects may be
* returned by this method.
*
* @returns {HTMLCollection<Element> | NodeList<Element> | Array<Element> |
* null} -
* A list data structure of one of the following types, containing any
* Element objects with the target CSS class name(s) from the child
* hierarchy of the "container" parameter's Element or Document value:
* - A lively-updated HTMLCollection if the Element class's or Document
* interface's getElementsByClassName() is supported.
* - A static NodeList if the Element class's or Document interface's
* querySelectorAll() method is supported.
* - An Array if the Element class's or Document interface's
* getElementsByTagName() method is supported and the containsCSSClass()
* external polyfill function is loaded.
* - null if none of the above methods are supported.
*/
this.defaultMethods = function() {
var result = this.byClassName();
if (result !== undefined) {
return result;
}
result = this.byQuerySelector();
if (result !== undefined) {
return result;
}
result = this.byTagNameBackup();
if (result !== undefined) {
return result;
}
return null;
}
/* Main area for method calling and execution */
this.checkParameter();
return this.tryMethods();
} | function elementsByClass(className, container, getLive) {
/**
* - Checks whether the argument values passed to the parameters of the
* parent function are of the expected primitive data types, inherit from
* the proper Object classes, or implement the proper interfaces.
*
* - Checks if the "className" parameter's argument value is a string. If
* so, trims any leading or trailing whitespace characters and replaces
* any null characters in it.
*
* - Checks whether the "container" parameter had a value passed to it. If
* so, checks whether it is an Element or Document object container. If
* not, sets the "container" parameter's value to the current page's
* "document" object.
*
* @throws -
* A TypeError exception when:
* - The "className" parameter is not a string.
* - The "container" parameter is not an Element or Document object.
* A RangeError exception when:
* - The "className" parameter is an empty string.
*/
this.checkParameter = function() {
if (typeof className !== "string") {
throw new TypeError("Parameter \"className\" is not a string.");
}
if (className.trim) {
className = className.trim();
}
if (!className) {
throw new RangeError("Parameter \"className\" is an empty string.");
}
className = className.replace(/\0/g, '');
if (container) {
if (!this.isContainerElement(container)) {
throw new TypeError("Parameter \"container\" is not an "
+ "Element or HTMLDocument object.");
}
}
else {
container = document;
}
}
/**
* Checks whether a value is an Element or Document (HTMLDocument) object.
* If neither the Element class nor HTMLDocument interface is supported,
* checks whether the value:
* - is a non-null object;
* - has a nodeType "number" value of 1, indicating that it is an Element
* node, or 9, indicating that it is a Document node;
* - has the inline "style" property, indicating that it is an Element
* object; or
* - has the "documentElement" property, which references the "html" root
* element of the page's DOM "document" object.
*
* @param {any} obj - The value to be checked.
*
* @returns {boolean} -
* Boolean true or false depending on whether the "obj" parameter value is
* either an Element or a Document (HTMLDocument) object.
*/
this.isContainerElement = function(obj) {
if (typeof Element !== "undefined"
&& typeof HTMLDocument !== "undefined") {
return obj instanceof Element || obj instanceof HTMLDocument;
}
if (!obj) {
return false;
}
if (obj.nodeType === 1 && obj.style) {
return true;
}
return !!(obj.nodeType === 9 && obj.documentElement);
}
/**
* Checks whether a value is an Element object. If the Element is not
* supported, checks whether the value:
* - is a non-empty object;
* - has a nodeType "number" value of 1, indicating that it is an Element
* node; and
* - has the inline "style" property.
*
* @param {any} obj - The value to be checked.
*
* @returns {boolean} -
* Boolean true or false depending on whether the "obj" parameter value is
* an Element object.
*/
this.isElement = function(obj) {
if (typeof Element !== "undefined") {
return obj instanceof Element;
}
return !!(obj && obj.nodeType === 1 && obj.style);
}
/**
* Using the getElementsByClassName() method, tries to fetch a list of
* Element objects containing the target CSS class name(s) from within the
* child hierarchy of the "container" parameter Document or Element object.
* This functionality is the most modern and computionally the fastest out
* of all the list-retrieval methods in the parent function.
*
* @returns {HTMLCollection<Element> | undefined} -
* - If the getElementsByClassName() method is supported by the Element
* class or Document interface, returns a lively-updated HTMLCollection
* containing every Element object with the target CSS class name(s) under
* the "container" parameter value.
* - Returns undefined if the getElementsByClassName() method is not
* supported by the Element class or Document interface.
*/
this.byClassName = function() {
if (container.getElementsByClassName) {
return container.getElementsByClassName(className);
}
return undefined;
}
/**
* Using the querySelectorAll() method, tries to fetch a list of Element
* objects containing the target CSS class name(s) from within the child
* hierarchy of the "container" parameter Document or Element object. To be
* a valid CSS class selector, this method must escape any special,
* reserved CSS characters in the parent function's "className" parameter
* string argument with backslashes (\\), and any sequences of one or more
* whitespace characters separating CSS class names from one another must
* be replaced with a period (.) character.
*
* @returns {HTMLCollection<Element> | undefined} -
* - If the getElementsByClassName() method is supported by the Element
* class or Document interface, returns a lively-updated HTMLCollection
* containing every Element object containing the target CSS class name(s)
* under the "container" parameter value.
* - Returns undefined if the getElementsByClassName() method is not
* supported by the Element class or Document interface.
*/
this.byQuerySelector = function() {
if (!container.querySelectorAll) {
return undefined;
}
className = className.replace(
/([_!\"#\$%&\'\(\)\*\+-\.\/\\:;<=>\?@\[\,\]\^`\{\|\}~])/g,
function(match, specialChar) {
return '\\' + specialChar;
}
);
className = "." + className.replace(/[\s\uFEFF\xA0]+/g, ".");
return container.querySelectorAll(className);
}
/**
* Gets all of the Element objects from under the "container" parameter
* value's child hierarchy using the getElementsByTagName() method and adds
* the ones which contains the target CSS class name(s) to an Array.
*
* @throws -
* A ReferenceError exception if the containsCSSClass() function, which is
* used to check whether an Element contains the target CSS class names, is
* not currently loaded.
*
* @returns {Array<Element> | undefined} -
* - An Array containing any Element objects with the target CSS class
* name(s).
* - undefined if the getElementsByTagName() method is not supported by
* the Element class or the Document interface for the "container"
* parameter argument object.
*/
this.byTagNameBackup = function() {
if (!container.getElementsByTagName) {
return undefined;
}
if (typeof containsCSSClass !== "function") {
throw new ReferenceError("containsCSSClass() function "
+ "must be loaded in order to use the elementsByClass() "
+ "function.");
}
var elementList = container.getElementsByTagName("*");
var results = [], index, element;
for (index = 0; index < elementList.length; index++) {
element = elementList[index];
if (this.isElement(element)
&& containsCSSClass(element, className)) {
results.push(element);
}
}
return results;
}
/**
* Tries the various methods defined in the parent function for getting a
* list of Element objects with the target CSS class name(s) from the child
* hierarchy of the "container" parameter's argument object.
*
* @returns {HTMLCollection<Element> | NodeList<Element> | Array<Element> |
* null} -
* If the "getLive" parameter has a Boolean value passed to it, this method
* will try to return:
* - a lively-updated HTMLCollection of Element objects, if true; or
* - a static NodeList or Array of Element objects, if false.
*
* If the "getLive" parameter is undefined or not a Boolean value, this
* method may return either a lively-updated or a static list of Element
* objects with the target CSS class name(s). In this case, the method
* prioritizes more modern and computationally faster JavaScript methods
* over legacy and slower ones. More specifically, checked in the following
* order:
* - A live HTMLCollection of Element objects is returned if the Element
* class's or Document interface's getElementsByClassName() method is
* supported.
* - A static NodeList of Element objects is returned if the Element
* class's or Document interface's querySelectorAll() method is
* supported.
* - A static Array of Element objects is returned if the Element class's
* or Document interface's getElementsByTagName() method is supported and
* the external polyfill containsCSSClass() function is loaded.
*
* Returns null if none of the JavaScript methods used for retrieving a
* list of the target Element objects and relied on by the called methods
* are supported.
*/
this.tryMethods = function() {
if (typeof getLive === "boolean") {
return getLive ? this.liveMethods() : this.staticMethods();
}
return this.defaultMethods();
}
/**
* Tries any methods defined in the parent function for getting a
* lively-updated list of Element objects which contain the target CSS
* class name(s). Currently, this method only supports the Element class's
* and Document interface's getElementsByClassName() method for returning
* an Element HTMLCollection, which is always live. Implementing additional
* logic for fetching and updating a live list using JavaScript native
* methods can be very complex and computationally expensive.
*
* @returns {HTMLCollection<Element> | null} -
* - A lively-updated HTMLCollection containing Elements with the target
* CSS class name(s).
* - null if no additional JavaScript methods for returning a
* lively-updated list data structure of Element objects with the target
* CSS class names are supported.
*/
this.liveMethods = function() {
var result = this.byClassName();
return result === undefined ? null : result;
}
/**
* Tries any methods defined in the parent function for retrieving a static
* list of Element objects with the target CSS class name(s). Currently,
* this method relies on the Element class's and Document interface's:
* - querySelectorAll() method for returning a static NodeList; or
* - getElementsByTagName() method for getting all child Elements of the
* "container" parameter's argument object, searching through, and
* returning an Array of the target Element objects.
*
* @returns {NodeList<Element> | Array<Element> | null} -
* - A static NodeList or Array of the Element objects with the target CSS
* class name(s) in the child hierarchy of the "container" parameter's
* Element or Document argument object.
* - null if no JavaScript methods are supported for finding a static list
* of any target Element objects.
*/
this.staticMethods = function() {
var result = this.byQuerySelector();
if (result !== undefined) {
return result;
}
result = this.byTagNameBackup();
return result === undefined ? null : result;
}
/**
* Executes the methods of the parent function for retrieving a list data
* structure of Element objects with the target CSS class names in the
* child hierarchy of the "container" parameter's Element or Document
* value. Methods are executed in order of how modern the JavaScript
* functions which they use are and how quickly they perform. Either a
* lively-updated or a static NodeList of matching Element objects may be
* returned by this method.
*
* @returns {HTMLCollection<Element> | NodeList<Element> | Array<Element> |
* null} -
* A list data structure of one of the following types, containing any
* Element objects with the target CSS class name(s) from the child
* hierarchy of the "container" parameter's Element or Document value:
* - A lively-updated HTMLCollection if the Element class's or Document
* interface's getElementsByClassName() is supported.
* - A static NodeList if the Element class's or Document interface's
* querySelectorAll() method is supported.
* - An Array if the Element class's or Document interface's
* getElementsByTagName() method is supported and the containsCSSClass()
* external polyfill function is loaded.
* - null if none of the above methods are supported.
*/
this.defaultMethods = function() {
var result = this.byClassName();
if (result !== undefined) {
return result;
}
result = this.byQuerySelector();
if (result !== undefined) {
return result;
}
result = this.byTagNameBackup();
if (result !== undefined) {
return result;
}
return null;
}
/* Main area for method calling and execution */
this.checkParameter();
return this.tryMethods();
} |
JavaScript | function checkParams() {
checkNodeParam();
checkOptionsParam();
} | function checkParams() {
checkNodeParam();
checkOptionsParam();
} |
JavaScript | function isNode(obj) {
if (typeof Node !== "undefined") {
return obj instanceof Node;
}
return !!(obj && obj.appendChild);
} | function isNode(obj) {
if (typeof Node !== "undefined") {
return obj instanceof Node;
}
return !!(obj && obj.appendChild);
} |
JavaScript | function checkNodeParam() {
if (!isNode(node)) {
throw new TypeError("The value passed to the \"node\" parameter "
+ "must be a Node object.");
}
} | function checkNodeParam() {
if (!isNode(node)) {
throw new TypeError("The value passed to the \"node\" parameter "
+ "must be a Node object.");
}
} |
JavaScript | function checkOptionsParam() {
if (typeof options === "undefined") {
options = { composed: false };
return;
}
if (options && typeof options === "object") {
if (typeof options.composed === "boolean") {
return;
}
throw new ReferenceError("The object passed to the \"options\" "
+ "parameter must contain the Boolean-value property named "
+ "\"composed\".");
}
throw new TypeError("Value passed to \"options\" parameter must be "
+ "an object with a Boolean-value property named \"composed\".");
} | function checkOptionsParam() {
if (typeof options === "undefined") {
options = { composed: false };
return;
}
if (options && typeof options === "object") {
if (typeof options.composed === "boolean") {
return;
}
throw new ReferenceError("The object passed to the \"options\" "
+ "parameter must contain the Boolean-value property named "
+ "\"composed\".");
}
throw new TypeError("Value passed to \"options\" parameter must be "
+ "an object with a Boolean-value property named \"composed\".");
} |
JavaScript | function tryMethods() {
if (overridden) {
return upwardsTraversal(node);
}
if (node.getRootNode) {
return node.getRootNode(options);
}
return upwardsTraversal(node);
} | function tryMethods() {
if (overridden) {
return upwardsTraversal(node);
}
if (node.getRootNode) {
return node.getRootNode(options);
}
return upwardsTraversal(node);
} |
JavaScript | function upwardsTraversal(startNode) {
var currentNode = startNode;
while (currentNode.parentNode) {
currentNode = currentNode.parentNode;
}
if (typeof ShadowRoot !== "undefined"
&& currentNode instanceof ShadowRoot
&& options.composed && currentNode.host) {
return upwardsTraversal(currentNode.host);
}
return currentNode;
} | function upwardsTraversal(startNode) {
var currentNode = startNode;
while (currentNode.parentNode) {
currentNode = currentNode.parentNode;
}
if (typeof ShadowRoot !== "undefined"
&& currentNode instanceof ShadowRoot
&& options.composed && currentNode.host) {
return upwardsTraversal(currentNode.host);
}
return currentNode;
} |
JavaScript | function updateResults(reservation, oldResults, reservationState) {
const results = [...oldResults];
const modifiedIndex = results.findIndex((result => result.id === reservation.id));
// return results as is if modified reservation was not found
if (modifiedIndex === -1) {
return results;
}
const resource = results[modifiedIndex].resource;
const updatedReservation = {
...results[modifiedIndex],
...reservation,
state: reservationState || reservation.state,
resource
};
results[modifiedIndex] = updatedReservation;
return results;
} | function updateResults(reservation, oldResults, reservationState) {
const results = [...oldResults];
const modifiedIndex = results.findIndex((result => result.id === reservation.id));
// return results as is if modified reservation was not found
if (modifiedIndex === -1) {
return results;
}
const resource = results[modifiedIndex].resource;
const updatedReservation = {
...results[modifiedIndex],
...reservation,
state: reservationState || reservation.state,
resource
};
results[modifiedIndex] = updatedReservation;
return results;
} |
JavaScript | onShowOnlyFiltersChange(filters) {
this.setState({
showOnlyFilters: filters,
});
} | onShowOnlyFiltersChange(filters) {
this.setState({
showOnlyFilters: filters,
});
} |
JavaScript | handleEditClick(reservation) {
const { history, actions } = this.props;
const normalizedReservation = Object.assign(
{}, reservation, { resource: reservation.resource.id }
);
// clear old selected reservations before selecting new reservation to edit
actions.clearReservations();
// fetch resource before changing page to make sure reservation page has
// all needed info to function
this.handleFetchResource(reservation.resource.id, reservation.begin);
actions.editReservation({ reservation: normalizedReservation });
const nextUrl = `${getEditReservationUrl(normalizedReservation)}&path=manage-reservations`;
history.push(nextUrl);
} | handleEditClick(reservation) {
const { history, actions } = this.props;
const normalizedReservation = Object.assign(
{}, reservation, { resource: reservation.resource.id }
);
// clear old selected reservations before selecting new reservation to edit
actions.clearReservations();
// fetch resource before changing page to make sure reservation page has
// all needed info to function
this.handleFetchResource(reservation.resource.id, reservation.begin);
actions.editReservation({ reservation: normalizedReservation });
const nextUrl = `${getEditReservationUrl(normalizedReservation)}&path=manage-reservations`;
history.push(nextUrl);
} |
JavaScript | handleEditReservation(reservation, status) {
const { actions } = this.props;
switch (status) {
case constants.RESERVATION_STATE.CANCELLED:
actions.selectReservationToCancel(reservation);
actions.openReservationCancelModal(reservation);
break;
case constants.RESERVATION_STATE.CONFIRMED:
actions.confirmPreliminaryReservation(reservation);
break;
case constants.RESERVATION_STATE.DENIED:
actions.denyPreliminaryReservation(reservation);
break;
default:
break;
}
} | handleEditReservation(reservation, status) {
const { actions } = this.props;
switch (status) {
case constants.RESERVATION_STATE.CANCELLED:
actions.selectReservationToCancel(reservation);
actions.openReservationCancelModal(reservation);
break;
case constants.RESERVATION_STATE.CONFIRMED:
actions.confirmPreliminaryReservation(reservation);
break;
case constants.RESERVATION_STATE.DENIED:
actions.denyPreliminaryReservation(reservation);
break;
default:
break;
}
} |
JavaScript | function isStaffForResource(resource) {
if (resource.userPermissions) {
const perms = resource.userPermissions;
if (perms.isAdmin || perms.isManager || perms.isViewer) {
return true;
}
}
return false;
} | function isStaffForResource(resource) {
if (resource.userPermissions) {
const perms = resource.userPermissions;
if (perms.isAdmin || perms.isManager || perms.isViewer) {
return true;
}
}
return false;
} |
JavaScript | function cookieBotAddListener() {
if (SETTINGS.TRACKING) {
window.addEventListener('CookiebotOnDialogDisplay', cookieBotImageOverride);
}
} | function cookieBotAddListener() {
if (SETTINGS.TRACKING) {
window.addEventListener('CookiebotOnDialogDisplay', cookieBotImageOverride);
}
} |
JavaScript | function cookieBotRemoveListener() {
if (SETTINGS.TRACKING) {
window.removeEventListener('CookiebotOnDialogDisplay', cookieBotImageOverride);
}
} | function cookieBotRemoveListener() {
if (SETTINGS.TRACKING) {
window.removeEventListener('CookiebotOnDialogDisplay', cookieBotImageOverride);
}
} |
JavaScript | renderField(
name, fieldName, type, label, controlProps = {}, help = null, info = null, altCheckbox = false
) {
const { t } = this.props;
if (!includes(this.props.fields, name)) {
return null;
}
const isRequired = includes(this.requiredFields, name);
return (
<Field
altCheckbox={altCheckbox}
component={ReduxFormField}
controlProps={controlProps}
help={help}
info={info}
label={`${label}${isRequired ? '*' : ''}`}
labelErrorPrefix={t('common.checkError')}
name={name}
props={{ fieldName }}
type={type}
/>
);
} | renderField(
name, fieldName, type, label, controlProps = {}, help = null, info = null, altCheckbox = false
) {
const { t } = this.props;
if (!includes(this.props.fields, name)) {
return null;
}
const isRequired = includes(this.requiredFields, name);
return (
<Field
altCheckbox={altCheckbox}
component={ReduxFormField}
controlProps={controlProps}
help={help}
info={info}
label={`${label}${isRequired ? '*' : ''}`}
labelErrorPrefix={t('common.checkError')}
name={name}
props={{ fieldName }}
type={type}
/>
);
} |
JavaScript | function renderEarliestResDay(daysInAdvance, t) {
if (!daysInAdvance) {
return null;
}
// create a date (today + daysInAdvace) and use it to create written "days in advance" text.
const date = moment().add(daysInAdvance, 'days');
return (
<p className="reservable-after-text">
<img alt="" className="app-ResourceHeader__info-icon" src={iconCalendar} />
<strong>{t('ReservationInfo.reservationEarliestDays', { time: moment(date).toNow(true) })}</strong>
</p>
);
} | function renderEarliestResDay(daysInAdvance, t) {
if (!daysInAdvance) {
return null;
}
// create a date (today + daysInAdvace) and use it to create written "days in advance" text.
const date = moment().add(daysInAdvance, 'days');
return (
<p className="reservable-after-text">
<img alt="" className="app-ResourceHeader__info-icon" src={iconCalendar} />
<strong>{t('ReservationInfo.reservationEarliestDays', { time: moment(date).toNow(true) })}</strong>
</p>
);
} |
JavaScript | function isPaymentUrlExpired(timestamp) {
const createdAt = moment(timestamp);
const expiresAt = createdAt.add(maxPaymentUrlAge, 'minutes');
const minutesLeft = expiresAt.diff(moment(), 'minutes');
if (minutesLeft < 0) {
return true;
}
return false;
} | function isPaymentUrlExpired(timestamp) {
const createdAt = moment(timestamp);
const expiresAt = createdAt.add(maxPaymentUrlAge, 'minutes');
const minutesLeft = expiresAt.diff(moment(), 'minutes');
if (minutesLeft < 0) {
return true;
}
return false;
} |
JavaScript | function deletePersistedPaymentUrl() {
if (!enablePersistPaymentUrl) {
return undefined;
}
try {
return localStorage.removeItem(persistedPaymentUrlKey);
} catch (err) {
return undefined;
}
} | function deletePersistedPaymentUrl() {
if (!enablePersistPaymentUrl) {
return undefined;
}
try {
return localStorage.removeItem(persistedPaymentUrlKey);
} catch (err) {
return undefined;
}
} |
JavaScript | function isValidDateString(dateString) {
if (dateString.length < 8 || dateString.length > 10) {
return false;
}
// eslint-disable-next-line
const regex = /\d{1,2}[.]\d{1,2}[.]\d{4}/;
if (regex.test(dateString) && moment(dateString, 'L').isValid()) {
return true;
}
return false;
} | function isValidDateString(dateString) {
if (dateString.length < 8 || dateString.length > 10) {
return false;
}
// eslint-disable-next-line
const regex = /\d{1,2}[.]\d{1,2}[.]\d{4}/;
if (regex.test(dateString) && moment(dateString, 'L').isValid()) {
return true;
}
return false;
} |
JavaScript | function onFavoriteFilterChange(filterValue, filters, onSearchChange) {
if (filterValue) {
onFilterChange('is_favorite_resource', false, filters, onSearchChange);
} else {
onFilterChange('is_favorite_resource', 'no', filters, onSearchChange);
}
} | function onFavoriteFilterChange(filterValue, filters, onSearchChange) {
if (filterValue) {
onFilterChange('is_favorite_resource', false, filters, onSearchChange);
} else {
onFilterChange('is_favorite_resource', 'no', filters, onSearchChange);
}
} |
JavaScript | componentDidMount() {
const {
location,
reservationCreated,
reservationEdited,
reservationToEdit,
selected,
history,
isLoggedIn,
loginExpiresAt
} = this.props;
if (
isEmpty(reservationCreated)
&& isEmpty(reservationEdited)
&& isEmpty(reservationToEdit)
&& isEmpty(selected)
) {
const query = queryString.parse(location.search);
if (!query.id && query.resource) {
history.replace(`/resources/${query.resource}`);
} else if ('path' in query && query.path === 'manage-reservations') {
history.replace('/manage-reservations');
} else {
history.replace('/my-reservations');
}
} else {
// handle price ops only when reservation info exists
const isEditing = !isEmpty(reservationToEdit);
const { mandatoryProducts, extraProducts } = this.state;
this.handleCheckOrderPrice(
this.props.resource, selected, mandatoryProducts, extraProducts, isEditing
);
}
if (
this.state.view === 'information'
&& (!isEmpty(reservationCreated) || !isEmpty(reservationEdited))
) {
this.handleRedirect();
} else {
this.fetchResource();
window.scrollTo(0, 0);
}
// ensure user has enough time to complete reservation
this.handleSigninRefresh(isLoggedIn, loginExpiresAt, 20);
} | componentDidMount() {
const {
location,
reservationCreated,
reservationEdited,
reservationToEdit,
selected,
history,
isLoggedIn,
loginExpiresAt
} = this.props;
if (
isEmpty(reservationCreated)
&& isEmpty(reservationEdited)
&& isEmpty(reservationToEdit)
&& isEmpty(selected)
) {
const query = queryString.parse(location.search);
if (!query.id && query.resource) {
history.replace(`/resources/${query.resource}`);
} else if ('path' in query && query.path === 'manage-reservations') {
history.replace('/manage-reservations');
} else {
history.replace('/my-reservations');
}
} else {
// handle price ops only when reservation info exists
const isEditing = !isEmpty(reservationToEdit);
const { mandatoryProducts, extraProducts } = this.state;
this.handleCheckOrderPrice(
this.props.resource, selected, mandatoryProducts, extraProducts, isEditing
);
}
if (
this.state.view === 'information'
&& (!isEmpty(reservationCreated) || !isEmpty(reservationEdited))
) {
this.handleRedirect();
} else {
this.fetchResource();
window.scrollTo(0, 0);
}
// ensure user has enough time to complete reservation
this.handleSigninRefresh(isLoggedIn, loginExpiresAt, 20);
} |
JavaScript | handleSigninRefresh(isLoggedIn, loginExpiresAt, minMinutesLeft = 20) {
// dont handle if user is not currently logged in
if (isLoggedIn && loginExpiresAt) {
const expiresAt = moment.unix(loginExpiresAt);
const minutesLeft = expiresAt.diff(moment(), 'minutes');
if (minutesLeft < minMinutesLeft) {
userManager.signinSilent();
}
}
} | handleSigninRefresh(isLoggedIn, loginExpiresAt, minMinutesLeft = 20) {
// dont handle if user is not currently logged in
if (isLoggedIn && loginExpiresAt) {
const expiresAt = moment.unix(loginExpiresAt);
const minutesLeft = expiresAt.diff(moment(), 'minutes');
if (minutesLeft < minMinutesLeft) {
userManager.signinSilent();
}
}
} |
JavaScript | async function fetchAnnouncement() {
const apiUrl = buildAPIUrl('announcements');
const response = await fetch(apiUrl, {
method: 'GET',
headers: getHeadersCreator(),
});
if (!response.ok) {
throw new Error('announcement_fetch_error');
}
const data = await response.json();
return data;
} | async function fetchAnnouncement() {
const apiUrl = buildAPIUrl('announcements');
const response = await fetch(apiUrl, {
method: 'GET',
headers: getHeadersCreator(),
});
if (!response.ok) {
throw new Error('announcement_fetch_error');
}
const data = await response.json();
return data;
} |
JavaScript | function parseReservationData(reservation) {
const trimmedValues = mapValues(reservation, (value) => {
if (typeof (value) === 'string') {
return value.trim();
}
return value;
});
const parsed = pickBy(trimmedValues, value => value || value === 0 || typeof (value) === 'boolean');
return JSON.stringify(decamelizeKeys(parsed));
} | function parseReservationData(reservation) {
const trimmedValues = mapValues(reservation, (value) => {
if (typeof (value) === 'string') {
return value.trim();
}
return value;
});
const parsed = pickBy(trimmedValues, value => value || value === 0 || typeof (value) === 'boolean');
return JSON.stringify(decamelizeKeys(parsed));
} |
JavaScript | function hasPayment(order) {
if (order) {
return 'price' in order && (Number(order.price) > 0);
}
return false;
} | function hasPayment(order) {
if (order) {
return 'price' in order && (Number(order.price) > 0);
}
return false;
} |
JavaScript | async function checkOrderPrice(begin, end, orderLines, state, customerGroup = '') {
const apiUrl = buildAPIUrl('order/check_price');
const payload = {
begin,
end,
order_lines: orderLines,
};
if (customerGroup) {
payload.customer_group = customerGroup;
}
const response = await fetch(apiUrl, {
method: 'POST',
headers: getHeadersCreator()(state),
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error('order_price_fetch_error');
}
const data = await response.json();
return data;
} | async function checkOrderPrice(begin, end, orderLines, state, customerGroup = '') {
const apiUrl = buildAPIUrl('order/check_price');
const payload = {
begin,
end,
order_lines: orderLines,
};
if (customerGroup) {
payload.customer_group = customerGroup;
}
const response = await fetch(apiUrl, {
method: 'POST',
headers: getHeadersCreator()(state),
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error('order_price_fetch_error');
}
const data = await response.json();
return data;
} |
JavaScript | function isManuallyConfirmedWithOrderAllowed(reservation) {
const { needManualConfirmation, state } = reservation;
if (needManualConfirmation && hasOrder(reservation)) {
const states = constants.RESERVATION_STATE;
if (state === states.REQUESTED || state === states.READY_FOR_PAYMENT) {
return true;
}
}
return false;
} | function isManuallyConfirmedWithOrderAllowed(reservation) {
const { needManualConfirmation, state } = reservation;
if (needManualConfirmation && hasOrder(reservation)) {
const states = constants.RESERVATION_STATE;
if (state === states.REQUESTED || state === states.READY_FOR_PAYMENT) {
return true;
}
}
return false;
} |
JavaScript | function handleSigninRefresh(isLoggedIn, loginExpiresAt, minMinutesLeft = 20) {
// dont handle if user is not currently logged in
if (isLoggedIn && loginExpiresAt) {
const expiresAt = moment.unix(loginExpiresAt);
const minutesLeft = expiresAt.diff(moment(), 'minutes');
if (minutesLeft < minMinutesLeft) {
// may not work in localhost
userManager.signinSilent();
}
}
} | function handleSigninRefresh(isLoggedIn, loginExpiresAt, minMinutesLeft = 20) {
// dont handle if user is not currently logged in
if (isLoggedIn && loginExpiresAt) {
const expiresAt = moment.unix(loginExpiresAt);
const minutesLeft = expiresAt.diff(moment(), 'minutes');
if (minutesLeft < minMinutesLeft) {
// may not work in localhost
userManager.signinSilent();
}
}
} |
JavaScript | function MandatoryProduct({ filteredtimeSlotPrices, order, t }) {
const totalPrice = order.price;
const {
type, period, amount: basePrice, tax_percentage: vat
} = order.product.price;
const vatText = t('ReservationProducts.price.includesVat', { vat: getRoundedVat(vat) });
return (
<React.Fragment>
{filteredtimeSlotPrices.length > 0 ? (
<ProductTimeSlotPrices
orderLine={order}
timeSlotPrices={filteredtimeSlotPrices}
/>
) : (
<p>
{`${t('ReservationProducts.table.heading.price')}: ${basePrice} €${type !== 'fixed'
? ` / ${getPrettifiedPeriodUnits(period)}` : ''}`}
</p>
)}
<p>{`${t('ReservationProducts.table.heading.total')}: ${totalPrice} € ${vatText}`}</p>
</React.Fragment>
);
} | function MandatoryProduct({ filteredtimeSlotPrices, order, t }) {
const totalPrice = order.price;
const {
type, period, amount: basePrice, tax_percentage: vat
} = order.product.price;
const vatText = t('ReservationProducts.price.includesVat', { vat: getRoundedVat(vat) });
return (
<React.Fragment>
{filteredtimeSlotPrices.length > 0 ? (
<ProductTimeSlotPrices
orderLine={order}
timeSlotPrices={filteredtimeSlotPrices}
/>
) : (
<p>
{`${t('ReservationProducts.table.heading.price')}: ${basePrice} €${type !== 'fixed'
? ` / ${getPrettifiedPeriodUnits(period)}` : ''}`}
</p>
)}
<p>{`${t('ReservationProducts.table.heading.total')}: ${totalPrice} € ${vatText}`}</p>
</React.Fragment>
);
} |
JavaScript | function ExtraProduct({
filteredtimeSlotPrices, order, t, handleChange
}) {
const { amount: unitPrice, tax_percentage: vat } = order.product.price;
const { quantity, price: totalPrice } = order;
const maxQuantity = order.product.max_quantity;
const vatText = t('ReservationProducts.price.includesVat', { vat: getRoundedVat(vat) });
return (
<React.Fragment>
{filteredtimeSlotPrices.length > 0 ? (
<ProductTimeSlotPrices
orderLine={order}
timeSlotPrices={filteredtimeSlotPrices}
/>
) : (
<p>
{`${t('ReservationProducts.table.heading.unitPrice')}: ${unitPrice} €`}
</p>
)}
<div className="extra-mobile-quantity-input">
<QuantityInput
handleAdd={() => handleChange(quantity + 1, order)}
handleReduce={() => handleChange(quantity - 1, order)}
maxQuantity={maxQuantity}
mobile
quantity={quantity}
/>
</div>
<p className="extra-mobile-total">
{`${t('ReservationProducts.table.heading.total')}: ${totalPrice} € ${vatText}`}
</p>
</React.Fragment>
);
} | function ExtraProduct({
filteredtimeSlotPrices, order, t, handleChange
}) {
const { amount: unitPrice, tax_percentage: vat } = order.product.price;
const { quantity, price: totalPrice } = order;
const maxQuantity = order.product.max_quantity;
const vatText = t('ReservationProducts.price.includesVat', { vat: getRoundedVat(vat) });
return (
<React.Fragment>
{filteredtimeSlotPrices.length > 0 ? (
<ProductTimeSlotPrices
orderLine={order}
timeSlotPrices={filteredtimeSlotPrices}
/>
) : (
<p>
{`${t('ReservationProducts.table.heading.unitPrice')}: ${unitPrice} €`}
</p>
)}
<div className="extra-mobile-quantity-input">
<QuantityInput
handleAdd={() => handleChange(quantity + 1, order)}
handleReduce={() => handleChange(quantity - 1, order)}
maxQuantity={maxQuantity}
mobile
quantity={quantity}
/>
</div>
<p className="extra-mobile-total">
{`${t('ReservationProducts.table.heading.total')}: ${totalPrice} € ${vatText}`}
</p>
</React.Fragment>
);
} |
JavaScript | render() {
const github = this.issues.map(issue => {
if (issue.state === 'unavailable'){
return html`
<div class='issue'>
<div class="name">
<span class='property' @click=${()=> this.openLink(`${issue.attributes.path}`)} title='Open repository'>
${this.config.show_github_icon && html`<ha-icon icon="${issue.attributes.icon}"></ha-icon>` || ''}
<span class='issue-name'>${issue.attributes.friendly_name + ' unavailable'}</span>
</span>
</div>
</div>
`
}
return html`
<div class='issue'>
<div class="name">
<span class='property' @click=${() => this.openLink(`${issue.attributes.path}`)} title='Open repository'>
${this.config.show_github_icon && html`<ha-icon icon="${issue.attributes.icon}"></ha-icon>` || ''}
<span class='issue-name'>${issue.attributes.name}</span>
</span>
</div>
<div></div>
<div class="links">
<div class='property'>
<span @click=${() => this.openLink(`${issue.attributes.path}/issues`)} title='Open issues'>
<ha-icon icon="mdi:alert-circle-outline"></ha-icon>
<span>${issue.attributes.open_issues}</span>
</span>
<span
class='${this.config.show_extended ? '' : 'hidden'}'
@click=${() => this.openLink(`${issue.attributes.path}/releases`)}
title='Open releases'
>
<ha-icon icon="mdi:tag-outline"></ha-icon>
</span>
</div>
<div class='property'>
<span @click=${() => this.openLink(`${issue.attributes.path}/pulls`)} title='Open pull requests'>
<ha-icon icon="mdi:source-pull"></ha-icon>
<span>${issue.attributes.open_pull_requests}</span>
</span>
<span
class='${this.config.show_extended ? '' : 'hidden'}'
@click=${() => this.openLink(`${issue.attributes.path}/network/members`)}
title='Open forks'
>
<ha-icon icon="mdi:source-fork"></ha-icon>
</span>
</div>
<div class='property'>
<span @click=${() => this.openLink(`${issue.attributes.path}/stargazers`)} title='Open stargazers'>
<ha-icon icon="mdi:star"></ha-icon>
<span>${issue.attributes.stargazers}</span>
</span>
<span
class='${this.config.show_extended ? '' : 'hidden'}'
@click=${() => this.openLink(`${issue.attributes.path}/commits`)}
title='Open commits'
>
<ha-icon icon="mdi:clock-outline"></ha-icon>
</span>
</div>
</div>
</div>
`
});
return html`
<ha-card class='github-card'>
<style>${GithubCard.styles}</style>
<div class='header'>
${this.config.title}
</div>
<div class='github-card__body'>
${github}
</div>
</ha-card>
`;
} | render() {
const github = this.issues.map(issue => {
if (issue.state === 'unavailable'){
return html`
<div class='issue'>
<div class="name">
<span class='property' @click=${()=> this.openLink(`${issue.attributes.path}`)} title='Open repository'>
${this.config.show_github_icon && html`<ha-icon icon="${issue.attributes.icon}"></ha-icon>` || ''}
<span class='issue-name'>${issue.attributes.friendly_name + ' unavailable'}</span>
</span>
</div>
</div>
`
}
return html`
<div class='issue'>
<div class="name">
<span class='property' @click=${() => this.openLink(`${issue.attributes.path}`)} title='Open repository'>
${this.config.show_github_icon && html`<ha-icon icon="${issue.attributes.icon}"></ha-icon>` || ''}
<span class='issue-name'>${issue.attributes.name}</span>
</span>
</div>
<div></div>
<div class="links">
<div class='property'>
<span @click=${() => this.openLink(`${issue.attributes.path}/issues`)} title='Open issues'>
<ha-icon icon="mdi:alert-circle-outline"></ha-icon>
<span>${issue.attributes.open_issues}</span>
</span>
<span
class='${this.config.show_extended ? '' : 'hidden'}'
@click=${() => this.openLink(`${issue.attributes.path}/releases`)}
title='Open releases'
>
<ha-icon icon="mdi:tag-outline"></ha-icon>
</span>
</div>
<div class='property'>
<span @click=${() => this.openLink(`${issue.attributes.path}/pulls`)} title='Open pull requests'>
<ha-icon icon="mdi:source-pull"></ha-icon>
<span>${issue.attributes.open_pull_requests}</span>
</span>
<span
class='${this.config.show_extended ? '' : 'hidden'}'
@click=${() => this.openLink(`${issue.attributes.path}/network/members`)}
title='Open forks'
>
<ha-icon icon="mdi:source-fork"></ha-icon>
</span>
</div>
<div class='property'>
<span @click=${() => this.openLink(`${issue.attributes.path}/stargazers`)} title='Open stargazers'>
<ha-icon icon="mdi:star"></ha-icon>
<span>${issue.attributes.stargazers}</span>
</span>
<span
class='${this.config.show_extended ? '' : 'hidden'}'
@click=${() => this.openLink(`${issue.attributes.path}/commits`)}
title='Open commits'
>
<ha-icon icon="mdi:clock-outline"></ha-icon>
</span>
</div>
</div>
</div>
`
});
return html`
<ha-card class='github-card'>
<style>${GithubCard.styles}</style>
<div class='header'>
${this.config.title}
</div>
<div class='github-card__body'>
${github}
</div>
</ha-card>
`;
} |
JavaScript | function parent(str, { strict = false } = {}) {
if (isWin && str.includes('/'))
str = str.split('\\').join('/');
// special case for strings ending in enclosure containing path separator
if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/';
// preserves full path in case of trailing path separator
str += 'a';
do {str = path__default.dirname(str);}
while (isglob(str, {strict}) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str));
// remove escape chars and return result
return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1');
} | function parent(str, { strict = false } = {}) {
if (isWin && str.includes('/'))
str = str.split('\\').join('/');
// special case for strings ending in enclosure containing path separator
if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/';
// preserves full path in case of trailing path separator
str += 'a';
do {str = path__default.dirname(str);}
while (isglob(str, {strict}) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str));
// remove escape chars and return result
return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1');
} |
JavaScript | function consumeName(source, offset) {
// Let result initially be an empty string.
// Repeatedly consume the next input code point from the stream:
for (; offset < source.length; offset++) {
var code = source.charCodeAt(offset);
// name code point
if (isName$1(code)) {
// Append the code point to result.
continue;
}
// the stream starts with a valid escape
if (isValidEscape$1(code, getCharCode(source, offset + 1))) {
// Consume an escaped code point. Append the returned code point to result.
offset = consumeEscaped(source, offset) - 1;
continue;
}
// anything else
// Reconsume the current input code point. Return result.
break;
}
return offset;
} | function consumeName(source, offset) {
// Let result initially be an empty string.
// Repeatedly consume the next input code point from the stream:
for (; offset < source.length; offset++) {
var code = source.charCodeAt(offset);
// name code point
if (isName$1(code)) {
// Append the code point to result.
continue;
}
// the stream starts with a valid escape
if (isValidEscape$1(code, getCharCode(source, offset + 1))) {
// Consume an escaped code point. Append the returned code point to result.
offset = consumeEscaped(source, offset) - 1;
continue;
}
// anything else
// Reconsume the current input code point. Return result.
break;
}
return offset;
} |
JavaScript | function decodeSourceMap(map) {
if (typeof map === 'string') {
map = JSON.parse(map);
}
let { mappings } = map;
if (typeof mappings === 'string') {
mappings = decode$1(mappings);
}
else {
// Clone the Line so that we can sort it. We don't want to mutate an array
// that we don't own directly.
mappings = mappings.map(cloneSegmentLine);
}
// Sort each Line's segments. There's no guarantee that segments are sorted for us,
// and even Chrome's implementation sorts:
// https://cs.chromium.org/chromium/src/third_party/devtools-frontend/src/front_end/sdk/SourceMap.js?l=507-508&rcl=109232bcf479c8f4ef8ead3cf56c49eb25f8c2f0
mappings.forEach(sortSegments);
return defaults({ mappings }, map);
} | function decodeSourceMap(map) {
if (typeof map === 'string') {
map = JSON.parse(map);
}
let { mappings } = map;
if (typeof mappings === 'string') {
mappings = decode$1(mappings);
}
else {
// Clone the Line so that we can sort it. We don't want to mutate an array
// that we don't own directly.
mappings = mappings.map(cloneSegmentLine);
}
// Sort each Line's segments. There's no guarantee that segments are sorted for us,
// and even Chrome's implementation sorts:
// https://cs.chromium.org/chromium/src/third_party/devtools-frontend/src/front_end/sdk/SourceMap.js?l=507-508&rcl=109232bcf479c8f4ef8ead3cf56c49eb25f8c2f0
mappings.forEach(sortSegments);
return defaults({ mappings }, map);
} |
JavaScript | function uniqInStr(str) {
let uniq = String(Math.random()).slice(2);
while (str.indexOf(uniq) > -1) {
/* istanbul ignore next */
uniq += uniq;
}
return uniq;
} | function uniqInStr(str) {
let uniq = String(Math.random()).slice(2);
while (str.indexOf(uniq) > -1) {
/* istanbul ignore next */
uniq += uniq;
}
return uniq;
} |
JavaScript | function stripPathFilename(path) {
path = normalizePath(path);
const index = path.lastIndexOf('/');
return path.slice(0, index + 1);
} | function stripPathFilename(path) {
path = normalizePath(path);
const index = path.lastIndexOf('/');
return path.slice(0, index + 1);
} |
JavaScript | function resolve$1(input, base) {
// The base is always treated as a directory, if it's not empty.
// https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
// https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
if (base && !base.endsWith('/'))
base += '/';
return resolve(input, base);
} | function resolve$1(input, base) {
// The base is always treated as a directory, if it's not empty.
// https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
// https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
if (base && !base.endsWith('/'))
base += '/';
return resolve(input, base);
} |
JavaScript | put(key) {
const { array, indexes } = this;
// The key may or may not be present. If it is present, it's a number.
let index = indexes[key];
// If it's not yet present, we need to insert it and track the index in the
// indexes.
if (index === undefined) {
index = indexes[key] = array.length;
array.push(key);
}
return index;
} | put(key) {
const { array, indexes } = this;
// The key may or may not be present. If it is present, it's a number.
let index = indexes[key];
// If it's not yet present, we need to insert it and track the index in the
// indexes.
if (index === undefined) {
index = indexes[key] = array.length;
array.push(key);
}
return index;
} |
JavaScript | traceMappings() {
const mappings = [];
const names = new FastStringArray();
const sources = new FastStringArray();
const sourcesContent = [];
const { mappings: rootMappings, names: rootNames } = this.map;
for (let i = 0; i < rootMappings.length; i++) {
const segments = rootMappings[i];
const tracedSegments = [];
for (let j = 0; j < segments.length; j++) {
const segment = segments[j];
// 1-length segments only move the current generated column, there's no
// source information to gather from it.
if (segment.length === 1)
continue;
const source = this.sources[segment[1]];
const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
if (!traced)
continue;
// So we traced a segment down into its original source file. Now push a
// new segment pointing to this location.
const { column, line, name } = traced;
const { content, filename } = traced.source;
// Store the source location, and ensure we keep sourcesContent up to
// date with the sources array.
const sourceIndex = sources.put(filename);
sourcesContent[sourceIndex] = content;
// This looks like unnecessary duplication, but it noticeably increases
// performance. If we were to push the nameIndex onto length-4 array, v8
// would internally allocate 22 slots! That's 68 wasted bytes! Array
// literals have the same capacity as their length, saving memory.
if (name) {
tracedSegments.push([segment[0], sourceIndex, line, column, names.put(name)]);
}
else {
tracedSegments.push([segment[0], sourceIndex, line, column]);
}
}
mappings.push(tracedSegments);
}
// TODO: Make all sources relative to the sourceRoot.
return defaults({
mappings,
names: names.array,
sources: sources.array,
sourcesContent,
}, this.map);
} | traceMappings() {
const mappings = [];
const names = new FastStringArray();
const sources = new FastStringArray();
const sourcesContent = [];
const { mappings: rootMappings, names: rootNames } = this.map;
for (let i = 0; i < rootMappings.length; i++) {
const segments = rootMappings[i];
const tracedSegments = [];
for (let j = 0; j < segments.length; j++) {
const segment = segments[j];
// 1-length segments only move the current generated column, there's no
// source information to gather from it.
if (segment.length === 1)
continue;
const source = this.sources[segment[1]];
const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
if (!traced)
continue;
// So we traced a segment down into its original source file. Now push a
// new segment pointing to this location.
const { column, line, name } = traced;
const { content, filename } = traced.source;
// Store the source location, and ensure we keep sourcesContent up to
// date with the sources array.
const sourceIndex = sources.put(filename);
sourcesContent[sourceIndex] = content;
// This looks like unnecessary duplication, but it noticeably increases
// performance. If we were to push the nameIndex onto length-4 array, v8
// would internally allocate 22 slots! That's 68 wasted bytes! Array
// literals have the same capacity as their length, saving memory.
if (name) {
tracedSegments.push([segment[0], sourceIndex, line, column, names.put(name)]);
}
else {
tracedSegments.push([segment[0], sourceIndex, line, column]);
}
}
mappings.push(tracedSegments);
}
// TODO: Make all sources relative to the sourceRoot.
return defaults({
mappings,
names: names.array,
sources: sources.array,
sourcesContent,
}, this.map);
} |
JavaScript | traceSegment(line, column, name) {
const { mappings, names } = this.map;
// It's common for parent sourcemaps to have pointers to lines that have no
// mapping (like a "//# sourceMappingURL=") at the end of the child file.
if (line >= mappings.length)
return null;
const segments = mappings[line];
if (segments.length === 0)
return null;
let index = binarySearch(segments, column, segmentComparator$1);
if (index === -1)
return null; // we come before any mapped segment
// If we can't find a segment that lines up to this column, we use the
// segment before.
if (index < 0) {
index = ~index - 1;
}
const segment = segments[index];
// 1-length segments only move the current generated column, there's no
// source information to gather from it.
if (segment.length === 1)
return null;
const source = this.sources[segment[1]];
// So now we can recurse down, until we hit the original source file.
return source.traceSegment(segment[2], segment[3],
// A child map's recorded name for this segment takes precedence over the
// parent's mapped name. Imagine a mangler changing the name over, etc.
segment.length === 5 ? names[segment[4]] : name);
} | traceSegment(line, column, name) {
const { mappings, names } = this.map;
// It's common for parent sourcemaps to have pointers to lines that have no
// mapping (like a "//# sourceMappingURL=") at the end of the child file.
if (line >= mappings.length)
return null;
const segments = mappings[line];
if (segments.length === 0)
return null;
let index = binarySearch(segments, column, segmentComparator$1);
if (index === -1)
return null; // we come before any mapped segment
// If we can't find a segment that lines up to this column, we use the
// segment before.
if (index < 0) {
index = ~index - 1;
}
const segment = segments[index];
// 1-length segments only move the current generated column, there's no
// source information to gather from it.
if (segment.length === 1)
return null;
const source = this.sources[segment[1]];
// So now we can recurse down, until we hit the original source file.
return source.traceSegment(segment[2], segment[3],
// A child map's recorded name for this segment takes precedence over the
// parent's mapped name. Imagine a mangler changing the name over, etc.
segment.length === 5 ? names[segment[4]] : name);
} |
JavaScript | function stripFilename(path) {
if (!path)
return '';
const index = path.lastIndexOf('/');
return path.slice(0, index + 1);
} | function stripFilename(path) {
if (!path)
return '';
const index = path.lastIndexOf('/');
return path.slice(0, index + 1);
} |
JavaScript | function buildSourceMapTree(input, loader, relativeRoot) {
const maps = asArray(input).map(decodeSourceMap);
const map = maps.pop();
for (let i = 0; i < maps.length; i++) {
if (maps[i].sources.length !== 1) {
throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
'Did you specify these with the most recent transformation maps first?');
}
}
const { sourceRoot, sources, sourcesContent } = map;
const children = sources.map((sourceFile, i) => {
// Each source file is loaded relative to the sourcemap's own sourceRoot,
// which is itself relative to the sourcemap's parent.
const uri = resolve$1(sourceFile || '', resolve$1(sourceRoot || '', stripFilename(relativeRoot)));
// Use the provided loader callback to retrieve the file's sourcemap.
// TODO: We should eventually support async loading of sourcemap files.
const sourceMap = loader(uri);
// If there is no sourcemap, then it is an unmodified source file.
if (!sourceMap) {
// The source file's actual contents must be included in the sourcemap
// (done when generating the sourcemap) for it to be included as a
// sourceContent in the output sourcemap.
const sourceContent = sourcesContent ? sourcesContent[i] : null;
return new OriginalSource(uri, sourceContent);
}
// Else, it's a real sourcemap, and we need to recurse into it to load its
// source files.
return buildSourceMapTree(decodeSourceMap(sourceMap), loader, uri);
});
let tree = new SourceMapTree(map, children);
for (let i = maps.length - 1; i >= 0; i--) {
tree = new SourceMapTree(maps[i], [tree]);
}
return tree;
} | function buildSourceMapTree(input, loader, relativeRoot) {
const maps = asArray(input).map(decodeSourceMap);
const map = maps.pop();
for (let i = 0; i < maps.length; i++) {
if (maps[i].sources.length !== 1) {
throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
'Did you specify these with the most recent transformation maps first?');
}
}
const { sourceRoot, sources, sourcesContent } = map;
const children = sources.map((sourceFile, i) => {
// Each source file is loaded relative to the sourcemap's own sourceRoot,
// which is itself relative to the sourcemap's parent.
const uri = resolve$1(sourceFile || '', resolve$1(sourceRoot || '', stripFilename(relativeRoot)));
// Use the provided loader callback to retrieve the file's sourcemap.
// TODO: We should eventually support async loading of sourcemap files.
const sourceMap = loader(uri);
// If there is no sourcemap, then it is an unmodified source file.
if (!sourceMap) {
// The source file's actual contents must be included in the sourcemap
// (done when generating the sourcemap) for it to be included as a
// sourceContent in the output sourcemap.
const sourceContent = sourcesContent ? sourcesContent[i] : null;
return new OriginalSource(uri, sourceContent);
}
// Else, it's a real sourcemap, and we need to recurse into it to load its
// source files.
return buildSourceMapTree(decodeSourceMap(sourceMap), loader, uri);
});
let tree = new SourceMapTree(map, children);
for (let i = maps.length - 1; i >= 0; i--) {
tree = new SourceMapTree(maps[i], [tree]);
}
return tree;
} |
JavaScript | function parse_attached_sourcemap(processed, tag_name) {
const r_in = '[#@]\\s*sourceMappingURL\\s*=\\s*(\\S*)';
const regex = (tag_name == 'script')
? new RegExp('(?://' + r_in + ')|(?:/\\*' + r_in + '\\s*\\*/)$')
: new RegExp('/\\*' + r_in + '\\s*\\*/$');
function log_warning(message) {
// code_start: help to find preprocessor
const code_start = processed.code.length < 100 ? processed.code : (processed.code.slice(0, 100) + ' [...]');
console.warn(`warning: ${message}. processed.code = ${JSON.stringify(code_start)}`);
}
processed.code = processed.code.replace(regex, (_, match1, match2) => {
const map_url = (tag_name == 'script') ? (match1 || match2) : match1;
const map_data = (map_url.match(/data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(\S*)/) || [])[1];
if (map_data) {
// sourceMappingURL is data URL
if (processed.map) {
log_warning('Not implemented. ' +
'Found sourcemap in both processed.code and processed.map. ' +
'Please update your preprocessor to return only one sourcemap.');
// ignore attached sourcemap
return '';
}
processed.map = b64dec(map_data); // use attached sourcemap
return ''; // remove from processed.code
}
// sourceMappingURL is path or URL
if (!processed.map) {
log_warning(`Found sourcemap path ${JSON.stringify(map_url)} in processed.code, but no sourcemap data. ` +
'Please update your preprocessor to return sourcemap data directly.');
}
// ignore sourcemap path
return ''; // remove from processed.code
});
} | function parse_attached_sourcemap(processed, tag_name) {
const r_in = '[#@]\\s*sourceMappingURL\\s*=\\s*(\\S*)';
const regex = (tag_name == 'script')
? new RegExp('(?://' + r_in + ')|(?:/\\*' + r_in + '\\s*\\*/)$')
: new RegExp('/\\*' + r_in + '\\s*\\*/$');
function log_warning(message) {
// code_start: help to find preprocessor
const code_start = processed.code.length < 100 ? processed.code : (processed.code.slice(0, 100) + ' [...]');
console.warn(`warning: ${message}. processed.code = ${JSON.stringify(code_start)}`);
}
processed.code = processed.code.replace(regex, (_, match1, match2) => {
const map_url = (tag_name == 'script') ? (match1 || match2) : match1;
const map_data = (map_url.match(/data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(\S*)/) || [])[1];
if (map_data) {
// sourceMappingURL is data URL
if (processed.map) {
log_warning('Not implemented. ' +
'Found sourcemap in both processed.code and processed.map. ' +
'Please update your preprocessor to return only one sourcemap.');
// ignore attached sourcemap
return '';
}
processed.map = b64dec(map_data); // use attached sourcemap
return ''; // remove from processed.code
}
// sourceMappingURL is path or URL
if (!processed.map) {
log_warning(`Found sourcemap path ${JSON.stringify(map_url)} in processed.code, but no sourcemap data. ` +
'Please update your preprocessor to return sourcemap data directly.');
}
// ignore sourcemap path
return ''; // remove from processed.code
});
} |
JavaScript | function decoded_sourcemap_from_generator(generator) {
let previous_generated_line = 1;
const converted_mappings = [[]];
let result_line;
let result_segment;
let mapping;
const source_idx = generator._sources.toArray()
.reduce((acc, val, idx) => (acc[val] = idx, acc), {});
const name_idx = generator._names.toArray()
.reduce((acc, val, idx) => (acc[val] = idx, acc), {});
const mappings = generator._mappings.toArray();
result_line = converted_mappings[0];
for (let i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
if (mapping.generatedLine > previous_generated_line) {
while (mapping.generatedLine > previous_generated_line) {
converted_mappings.push([]);
previous_generated_line++;
}
result_line = converted_mappings[mapping.generatedLine - 1]; // line is one-based
}
else if (i > 0) {
const previous_mapping = mappings[i - 1];
if (
// sorted by selectivity
mapping.generatedColumn === previous_mapping.generatedColumn &&
mapping.originalColumn === previous_mapping.originalColumn &&
mapping.name === previous_mapping.name &&
mapping.generatedLine === previous_mapping.generatedLine &&
mapping.originalLine === previous_mapping.originalLine &&
mapping.source === previous_mapping.source) {
continue;
}
}
result_line.push([mapping.generatedColumn]);
result_segment = result_line[result_line.length - 1];
if (mapping.source != null) {
result_segment.push(...[
source_idx[mapping.source],
mapping.originalLine - 1,
mapping.originalColumn
]);
if (mapping.name != null) {
result_segment.push(name_idx[mapping.name]);
}
}
}
const map = {
version: generator._version,
sources: generator._sources.toArray(),
names: generator._names.toArray(),
mappings: converted_mappings
};
if (generator._file != null) {
map.file = generator._file;
}
// not needed: map.sourcesContent and map.sourceRoot
return map;
} | function decoded_sourcemap_from_generator(generator) {
let previous_generated_line = 1;
const converted_mappings = [[]];
let result_line;
let result_segment;
let mapping;
const source_idx = generator._sources.toArray()
.reduce((acc, val, idx) => (acc[val] = idx, acc), {});
const name_idx = generator._names.toArray()
.reduce((acc, val, idx) => (acc[val] = idx, acc), {});
const mappings = generator._mappings.toArray();
result_line = converted_mappings[0];
for (let i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
if (mapping.generatedLine > previous_generated_line) {
while (mapping.generatedLine > previous_generated_line) {
converted_mappings.push([]);
previous_generated_line++;
}
result_line = converted_mappings[mapping.generatedLine - 1]; // line is one-based
}
else if (i > 0) {
const previous_mapping = mappings[i - 1];
if (
// sorted by selectivity
mapping.generatedColumn === previous_mapping.generatedColumn &&
mapping.originalColumn === previous_mapping.originalColumn &&
mapping.name === previous_mapping.name &&
mapping.generatedLine === previous_mapping.generatedLine &&
mapping.originalLine === previous_mapping.originalLine &&
mapping.source === previous_mapping.source) {
continue;
}
}
result_line.push([mapping.generatedColumn]);
result_segment = result_line[result_line.length - 1];
if (mapping.source != null) {
result_segment.push(...[
source_idx[mapping.source],
mapping.originalLine - 1,
mapping.originalColumn
]);
if (mapping.name != null) {
result_segment.push(name_idx[mapping.name]);
}
}
}
const map = {
version: generator._version,
sources: generator._sources.toArray(),
names: generator._names.toArray(),
mappings: converted_mappings
};
if (generator._file != null) {
map.file = generator._file;
}
// not needed: map.sourcesContent and map.sourceRoot
return map;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.