language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function mergeExclusive(...objects) {
return objects.reduce((acc, obj) => {
const keys = new Set(Object.keys(acc));
const overlap = !!Object.keys(obj).find((okey) => keys.has(okey));
if (overlap) {
throw new Error('Cannot merge objects: keys are non-exclusive');
}
return { ...acc, ...obj };
}, {});
} | function mergeExclusive(...objects) {
return objects.reduce((acc, obj) => {
const keys = new Set(Object.keys(acc));
const overlap = !!Object.keys(obj).find((okey) => keys.has(okey));
if (overlap) {
throw new Error('Cannot merge objects: keys are non-exclusive');
}
return { ...acc, ...obj };
}, {});
} |
JavaScript | async initialize() {
if (!this.initializeCheck) {
this.initializeCheck = new Promise((resolve, reject) =>
this.addTask('dicom', [], [], [])
.then((result) => {
if (result.webWorker) {
this.webWorker = result.webWorker;
resolve();
} else {
reject(new Error('Could not initialize webworker'));
}
})
.catch(reject)
);
}
return this.initializeCheck;
} | async initialize() {
if (!this.initializeCheck) {
this.initializeCheck = new Promise((resolve, reject) =>
this.addTask('dicom', [], [], [])
.then((result) => {
if (result.webWorker) {
this.webWorker = result.webWorker;
resolve();
} else {
reject(new Error('Could not initialize webworker'));
}
})
.catch(reject)
);
}
return this.initializeCheck;
} |
JavaScript | async buildVolumeList(volumeID) {
const result = await this.addTask(
'dicom',
['buildVolumeList', 'output.json', volumeID],
[{ path: 'output.json', type: IOTypes.Text }],
[]
);
return JSON.parse(result.outputs[0].data);
} | async buildVolumeList(volumeID) {
const result = await this.addTask(
'dicom',
['buildVolumeList', 'output.json', volumeID],
[{ path: 'output.json', type: IOTypes.Text }],
[]
);
return JSON.parse(result.outputs[0].data);
} |
JavaScript | function useOrientationLabels(viewRef) {
const rightAxes = ref([]);
const upAxes = ref([]);
const top = computed(() => signedAxesToLabels(upAxes.value));
const right = computed(() => signedAxesToLabels(rightAxes.value));
const bottom = computed(() =>
signedAxesToLabels(upAxes.value.map((a) => -a))
);
const left = computed(() =>
signedAxesToLabels(rightAxes.value.map((a) => -a))
);
function updateAxes() {
const view = unref(viewRef);
if (view) {
const camera = view.getCamera();
const vup = camera.getViewUp();
const vdir = camera.getDirectionOfProjection();
const vright = [0, 0, 0];
// assumption: vright and vdir are not equal
// (which should be the case for the camera)
vec3.cross(vright, vdir, vup);
rightAxes.value = sortAndOrientAxes(vright);
upAxes.value = sortAndOrientAxes(vup);
}
}
useSubscription(viewRef, (view) => view.getCamera().onModified(updateAxes));
updateAxes();
return { top, right, bottom, left };
} | function useOrientationLabels(viewRef) {
const rightAxes = ref([]);
const upAxes = ref([]);
const top = computed(() => signedAxesToLabels(upAxes.value));
const right = computed(() => signedAxesToLabels(rightAxes.value));
const bottom = computed(() =>
signedAxesToLabels(upAxes.value.map((a) => -a))
);
const left = computed(() =>
signedAxesToLabels(rightAxes.value.map((a) => -a))
);
function updateAxes() {
const view = unref(viewRef);
if (view) {
const camera = view.getCamera();
const vup = camera.getViewUp();
const vdir = camera.getDirectionOfProjection();
const vright = [0, 0, 0];
// assumption: vright and vdir are not equal
// (which should be the case for the camera)
vec3.cross(vright, vdir, vup);
rightAxes.value = sortAndOrientAxes(vright);
upAxes.value = sortAndOrientAxes(vup);
}
}
useSubscription(viewRef, (view) => view.getCamera().onModified(updateAxes));
updateAxes();
return { top, right, bottom, left };
} |
JavaScript | function findClosestFrameVec(mat3x3, axis) {
let closestIndex = 0;
let closestSign = 1;
let closest = -Infinity;
let vector = [];
for (let idx = 0; idx < 3; idx += 1) {
const indexDir = vec3.fromValues(
mat3x3[idx * 3 + 0],
mat3x3[idx * 3 + 1],
mat3x3[idx * 3 + 2]
);
const cosine = vec3.dot(indexDir, axis);
const sign = Math.sign(cosine);
const howClose = Math.abs(cosine);
if (howClose > closest) {
closest = howClose;
closestIndex = idx;
closestSign = sign;
vector = indexDir;
}
}
return {
howClose: closest,
vectorIndex: closestIndex,
sign: closestSign,
vector,
};
} | function findClosestFrameVec(mat3x3, axis) {
let closestIndex = 0;
let closestSign = 1;
let closest = -Infinity;
let vector = [];
for (let idx = 0; idx < 3; idx += 1) {
const indexDir = vec3.fromValues(
mat3x3[idx * 3 + 0],
mat3x3[idx * 3 + 1],
mat3x3[idx * 3 + 2]
);
const cosine = vec3.dot(indexDir, axis);
const sign = Math.sign(cosine);
const howClose = Math.abs(cosine);
if (howClose > closest) {
closest = howClose;
closestIndex = idx;
closestSign = sign;
vector = indexDir;
}
}
return {
howClose: closest,
vectorIndex: closestIndex,
sign: closestSign,
vector,
};
} |
JavaScript | function apply2DCameraPlacement(
view,
imageParams,
viewUp,
orientation,
axis,
frame
) {
function updateCamera() {
// get world bounds center
const { bounds } = imageParams.value;
const center = [
(bounds[0] + bounds[1]) / 2,
(bounds[2] + bounds[3]) / 2,
(bounds[4] + bounds[5]) / 2,
];
const position = [...center];
position[axis.value] += orientation.value;
const dop = [0, 0, 0];
dop[axis.value] = -orientation.value;
const vup = [...viewUp.value];
if (unref(frame) === 'image') {
const { direction } = imageParams.value;
vec3.transformMat3(dop, dop, direction);
vec3.transformMat3(vup, vup, direction);
}
const camera = view.value.getCamera();
camera.setFocalPoint(...center);
camera.setPosition(...position);
camera.setDirectionOfProjection(...dop);
camera.setViewUp(...vup);
view.value.getRenderer().resetCamera();
view.value.set({ axis: axis.value }, true); // set the corresponding axis
}
watch([imageParams, viewUp, orientation, axis], updateCamera, {
immediate: true,
});
} | function apply2DCameraPlacement(
view,
imageParams,
viewUp,
orientation,
axis,
frame
) {
function updateCamera() {
// get world bounds center
const { bounds } = imageParams.value;
const center = [
(bounds[0] + bounds[1]) / 2,
(bounds[2] + bounds[3]) / 2,
(bounds[4] + bounds[5]) / 2,
];
const position = [...center];
position[axis.value] += orientation.value;
const dop = [0, 0, 0];
dop[axis.value] = -orientation.value;
const vup = [...viewUp.value];
if (unref(frame) === 'image') {
const { direction } = imageParams.value;
vec3.transformMat3(dop, dop, direction);
vec3.transformMat3(vup, vup, direction);
}
const camera = view.value.getCamera();
camera.setFocalPoint(...center);
camera.setPosition(...position);
camera.setDirectionOfProjection(...dop);
camera.setViewUp(...vup);
view.value.getRenderer().resetCamera();
view.value.set({ axis: axis.value }, true); // set the corresponding axis
}
watch([imageParams, viewUp, orientation, axis], updateCamera, {
immediate: true,
});
} |
JavaScript | function watchColorBy(colorByRef, sceneSourcesRef, viewRef) {
const pxm = useProxyManager();
function updateColorBy() {
const view = unref(viewRef);
const colorBy = unref(colorByRef);
const sources = unref(sceneSourcesRef);
if (view) {
sources.forEach((source, idx) => {
const colorSrc = colorBy[idx];
const rep = pxm.getRepresentation(source, view);
if (rep && colorSrc) {
const { array, location } = colorSrc;
rep.setColorBy(array, location);
}
});
}
}
watchEffect(updateColorBy);
} | function watchColorBy(colorByRef, sceneSourcesRef, viewRef) {
const pxm = useProxyManager();
function updateColorBy() {
const view = unref(viewRef);
const colorBy = unref(colorByRef);
const sources = unref(sceneSourcesRef);
if (view) {
sources.forEach((source, idx) => {
const colorSrc = colorBy[idx];
const rep = pxm.getRepresentation(source, view);
if (rep && colorSrc) {
const { array, location } = colorSrc;
rep.setColorBy(array, location);
}
});
}
}
watchEffect(updateColorBy);
} |
JavaScript | function multiComputed(fn) {
const obj = computed(fn);
const a = Object.keys(obj.value).reduce(
(acc, key) => ({
...acc,
[key]: computed(() => obj.value[key]),
}),
{}
);
return a;
} | function multiComputed(fn) {
const obj = computed(fn);
const a = Object.keys(obj.value).reduce(
(acc, key) => ({
...acc,
[key]: computed(() => obj.value[key]),
}),
{}
);
return a;
} |
JavaScript | function genSynPatientKey(patient) {
const pid = patient.PatientID.trim();
const name = patient.PatientName.trim();
const bdate = patient.PatientBirthDate.trim();
const sex = patient.PatientSex.trim();
// we only care about making a unique key here. The
// data doesn't actually matter.
return [pid, name, bdate, sex].map((s) => s.replace('|', '_')).join('|');
} | function genSynPatientKey(patient) {
const pid = patient.PatientID.trim();
const name = patient.PatientName.trim();
const bdate = patient.PatientBirthDate.trim();
const sex = patient.PatientSex.trim();
// we only care about making a unique key here. The
// data doesn't actually matter.
return [pid, name, bdate, sex].map((s) => s.replace('|', '_')).join('|');
} |
JavaScript | async buildVolume({ state, commit }, volumeID) {
const { dicomIO } = dependencies;
if (volumeID in state.volumeCache) {
return state.volumeCache[volumeID];
}
if (!(volumeID in state.volumeIndex)) {
throw new Error(`Cannot find given volume key: ${volumeID}`);
}
const itkImage = await dicomIO.buildVolume(volumeID);
const vtkImage = vtkITKHelper.convertItkToVtkImage(itkImage);
commit('cacheVolume', {
volumeKey: volumeID,
image: vtkImage,
});
return vtkImage;
} | async buildVolume({ state, commit }, volumeID) {
const { dicomIO } = dependencies;
if (volumeID in state.volumeCache) {
return state.volumeCache[volumeID];
}
if (!(volumeID in state.volumeIndex)) {
throw new Error(`Cannot find given volume key: ${volumeID}`);
}
const itkImage = await dicomIO.buildVolume(volumeID);
const vtkImage = vtkITKHelper.convertItkToVtkImage(itkImage);
commit('cacheVolume', {
volumeKey: volumeID,
image: vtkImage,
});
return vtkImage;
} |
JavaScript | function useViewContainer(viewRef) {
const container = ref(null);
useSubscription(viewRef, (view) =>
view.onModified(() => {
container.value = view.getContainer();
})
);
watch(
viewRef,
(view) => {
container.value = view?.getContainer?.() ?? null;
},
{ immediate: true }
);
return { container };
} | function useViewContainer(viewRef) {
const container = ref(null);
useSubscription(viewRef, (view) =>
view.onModified(() => {
container.value = view.getContainer();
})
);
watch(
viewRef,
(view) => {
container.value = view?.getContainer?.() ?? null;
},
{ immediate: true }
);
return { container };
} |
JavaScript | function createVizPipeline(steps, proxyManager) {
const pipeline = {};
steps.forEach((step, i) => {
if (i === 0 && step.type === 'dataset') {
const source = proxyManager.createProxy('Sources', 'TrivialProducer');
source.setInputData(step.dataset);
pipeline[i] = source;
pipeline.source = source;
} else if (i > 0 && step.type === 'filter') {
const { id, proxyGroup, proxyName } = step;
const filter = proxyManager.createProxy(proxyGroup, proxyName, {
inputProxy: pipeline[i - 1],
});
pipeline[i] = filter;
pipeline[id] = filter;
}
});
pipeline.length = steps.length;
// eslint-disable-next-line prefer-destructuring
pipeline.first = pipeline[0];
pipeline.last = pipeline[pipeline.length - 1];
return pipeline;
} | function createVizPipeline(steps, proxyManager) {
const pipeline = {};
steps.forEach((step, i) => {
if (i === 0 && step.type === 'dataset') {
const source = proxyManager.createProxy('Sources', 'TrivialProducer');
source.setInputData(step.dataset);
pipeline[i] = source;
pipeline.source = source;
} else if (i > 0 && step.type === 'filter') {
const { id, proxyGroup, proxyName } = step;
const filter = proxyManager.createProxy(proxyGroup, proxyName, {
inputProxy: pipeline[i - 1],
});
pipeline[i] = filter;
pipeline[id] = filter;
}
});
pipeline.length = steps.length;
// eslint-disable-next-line prefer-destructuring
pipeline.first = pipeline[0];
pipeline.last = pipeline[pipeline.length - 1];
return pipeline;
} |
JavaScript | async resetSlicing({ commit, state }) {
// pick middle of extent
const { extent } = state.imageParams;
const center = [
Math.round((extent[0] + extent[1]) / 2),
Math.round((extent[2] + extent[3]) / 2),
Math.round((extent[4] + extent[5]) / 2),
];
await commit('setSlices', {
x: center[0],
y: center[1],
z: center[2],
});
} | async resetSlicing({ commit, state }) {
// pick middle of extent
const { extent } = state.imageParams;
const center = [
Math.round((extent[0] + extent[1]) / 2),
Math.round((extent[2] + extent[3]) / 2),
Math.round((extent[4] + extent[5]) / 2),
];
await commit('setSlices', {
x: center[0],
y: center[1],
z: center[2],
});
} |
JavaScript | async selectBaseImage({ state, commit, dispatch }, id) {
let baseImageId = NO_SELECTION;
if (
id in state.data.index &&
(state.data.index[id].type === DataTypes.Image ||
state.data.index[id].type === DataTypes.Dicom)
) {
baseImageId = id;
}
// special case: load dicom image
if (baseImageId !== NO_SELECTION) {
const dataInfo = state.data.index[baseImageId];
if (!(baseImageId in state.data.vtkCache)) {
switch (dataInfo.type) {
case DataTypes.Dicom: {
const { volumeKey } = dataInfo;
const image = await dispatch('dicom/buildVolume', volumeKey);
commit('cacheDicomImage', { volumeKey, image });
break;
}
default:
throw new Error(
`selectBaseImage: Item ${baseImageId} has no vtk data`
);
}
}
}
commit('setBaseImage', baseImageId);
} | async selectBaseImage({ state, commit, dispatch }, id) {
let baseImageId = NO_SELECTION;
if (
id in state.data.index &&
(state.data.index[id].type === DataTypes.Image ||
state.data.index[id].type === DataTypes.Dicom)
) {
baseImageId = id;
}
// special case: load dicom image
if (baseImageId !== NO_SELECTION) {
const dataInfo = state.data.index[baseImageId];
if (!(baseImageId in state.data.vtkCache)) {
switch (dataInfo.type) {
case DataTypes.Dicom: {
const { volumeKey } = dataInfo;
const image = await dispatch('dicom/buildVolume', volumeKey);
commit('cacheDicomImage', { volumeKey, image });
break;
}
default:
throw new Error(
`selectBaseImage: Item ${baseImageId} has no vtk data`
);
}
}
}
commit('setBaseImage', baseImageId);
} |
JavaScript | function typedArrayReplacer(ta) {
if (ArrayBuffer.isView(ta) && !(ta instanceof DataView)) {
return Array.from(ta);
}
return ta;
} | function typedArrayReplacer(ta) {
if (ArrayBuffer.isView(ta) && !(ta instanceof DataView)) {
return Array.from(ta);
}
return ta;
} |
JavaScript | function samplePiecewiseLinear(points, shift = 0, samples = 256) {
// set endpoints to 0 and 1 if needed
const filledPoints = [...points];
if (points[0][0] > 0) filledPoints.unshift([0, 0]);
if (points[points.length - 1][0] < 1) filledPoints.push([1, 1]);
const sampledPoints = [];
let pi = 0;
let p1 = filledPoints[0]; // left
let p2 = filledPoints[1]; // right
let slope = (p2[1] - p1[1]) / (p2[0] - p1[0]);
for (let i = 0; i < samples; i += 1) {
const sx = i / (samples - 1) - shift; // sample x
if (i < samples - 1 && sx <= 1) {
while (sx > p2[0] && pi < filledPoints.length - 2) {
pi += 1;
// extraneous work if this loop goes over more than once,
// which only happens if sx > 0 on first iteration (aka shift < 0)
p1 = filledPoints[pi];
p2 = filledPoints[pi + 1];
slope = (p2[1] - p1[1]) / (p2[0] - p1[0]);
}
sampledPoints.push(slope * (sx - p1[0]) + p1[1]);
if (sampledPoints[sampledPoints.length - 1] > 1) {
debugger;
}
} else {
sampledPoints.push(0);
}
}
return sampledPoints;
} | function samplePiecewiseLinear(points, shift = 0, samples = 256) {
// set endpoints to 0 and 1 if needed
const filledPoints = [...points];
if (points[0][0] > 0) filledPoints.unshift([0, 0]);
if (points[points.length - 1][0] < 1) filledPoints.push([1, 1]);
const sampledPoints = [];
let pi = 0;
let p1 = filledPoints[0]; // left
let p2 = filledPoints[1]; // right
let slope = (p2[1] - p1[1]) / (p2[0] - p1[0]);
for (let i = 0; i < samples; i += 1) {
const sx = i / (samples - 1) - shift; // sample x
if (i < samples - 1 && sx <= 1) {
while (sx > p2[0] && pi < filledPoints.length - 2) {
pi += 1;
// extraneous work if this loop goes over more than once,
// which only happens if sx > 0 on first iteration (aka shift < 0)
p1 = filledPoints[pi];
p2 = filledPoints[pi + 1];
slope = (p2[1] - p1[1]) / (p2[0] - p1[0]);
}
sampledPoints.push(slope * (sx - p1[0]) + p1[1]);
if (sampledPoints[sampledPoints.length - 1] > 1) {
debugger;
}
} else {
sampledPoints.push(0);
}
}
return sampledPoints;
} |
JavaScript | function isValidResponse(response, types) {
const rtype = response?.type;
if (!types.includes(rtype)) {
return false;
}
switch (rtype) {
case 'rpc.result':
return 'result' in response;
case 'rpc.error':
return 'error' in response;
case 'rpc.deferred':
return 'id' in response;
case 'deferred.response':
return 'id' in response && 'rpcResponse' in response;
default:
return false;
}
} | function isValidResponse(response, types) {
const rtype = response?.type;
if (!types.includes(rtype)) {
return false;
}
switch (rtype) {
case 'rpc.result':
return 'result' in response;
case 'rpc.error':
return 'error' in response;
case 'rpc.deferred':
return 'id' in response;
case 'deferred.response':
return 'id' in response && 'rpcResponse' in response;
default:
return false;
}
} |
JavaScript | function throttle(durationSelector, config) {
if (config === void 0) {
config = defaultThrottleConfig;
}
return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
} | function throttle(durationSelector, config) {
if (config === void 0) {
config = defaultThrottleConfig;
}
return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
} |
JavaScript | function NgRedux(ngZone) {
var _this = this;
this.ngZone = ngZone;
this._store = null;
this._store$ = null;
/**
* Get the current state of the application
* @returns {RootState} the application state
*/
this.getState = function () {
return _this._store.getState();
};
/**
* Subscribe to the Redux store changes
*
* @param {() => void} listener callback to invoke when the state is updated
* @returns a function to unsubscribe
*/
this.subscribe = function (listener) {
return _this._store.subscribe(listener);
};
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param nextReducer The reducer for the store to use instead.
*/
this.replaceReducer = function (nextReducer) {
return _this._store.replaceReducer(nextReducer);
};
/**
* Dispatch an action to Redux
*/
this.dispatch = function (action) {
invariant_1.invariant(!!_this._store, 'Dispatch failed: did you forget to configure your store? ' +
'https://github.com/angular-redux/ng2-redux/blob/master/' +
'README.md#quick-start');
// Some apps dispatch actions from outside the angular zone; e.g. as
// part of a 3rd-party callback, etc. When this happens, we need to
// execute the dispatch in-zone or Angular2's UI won't update.
return _this.ngZone.run(function () { return _this._store.dispatch(action); });
};
NgRedux.instance = this;
this._store$ = new BehaviorSubject_1.BehaviorSubject(null)
.filter(function (n) { return n !== null; })
.switchMap(function (n) {
return Observable_1.Observable.from(n);
});
} | function NgRedux(ngZone) {
var _this = this;
this.ngZone = ngZone;
this._store = null;
this._store$ = null;
/**
* Get the current state of the application
* @returns {RootState} the application state
*/
this.getState = function () {
return _this._store.getState();
};
/**
* Subscribe to the Redux store changes
*
* @param {() => void} listener callback to invoke when the state is updated
* @returns a function to unsubscribe
*/
this.subscribe = function (listener) {
return _this._store.subscribe(listener);
};
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param nextReducer The reducer for the store to use instead.
*/
this.replaceReducer = function (nextReducer) {
return _this._store.replaceReducer(nextReducer);
};
/**
* Dispatch an action to Redux
*/
this.dispatch = function (action) {
invariant_1.invariant(!!_this._store, 'Dispatch failed: did you forget to configure your store? ' +
'https://github.com/angular-redux/ng2-redux/blob/master/' +
'README.md#quick-start');
// Some apps dispatch actions from outside the angular zone; e.g. as
// part of a 3rd-party callback, etc. When this happens, we need to
// execute the dispatch in-zone or Angular2's UI won't update.
return _this.ngZone.run(function () { return _this._store.dispatch(action); });
};
NgRedux.instance = this;
this._store$ = new BehaviorSubject_1.BehaviorSubject(null)
.filter(function (n) { return n !== null; })
.switchMap(function (n) {
return Observable_1.Observable.from(n);
});
} |
JavaScript | function combineLatest() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i] = arguments[_i];
}
return combineLatest_1.combineLatest.apply(void 0, observables)(this);
} | function combineLatest() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i] = arguments[_i];
}
return combineLatest_1.combineLatest.apply(void 0, observables)(this);
} |
JavaScript | function failureForKind(kind, isInUnion, options) {
switch (kind) {
case 0 /* String */:
case 1 /* FalseStringLiteral */:
return options.allowString ? undefined : 2 /* String */;
case 2 /* Number */:
case 3 /* FalseNumberLiteral */:
return options.allowNumber ? undefined : 3 /* Number */;
case 8 /* Enum */:
return 6 /* Enum */;
case 6 /* Null */:
return isInUnion && !options.allowNullUnion ? 4 /* Null */ : undefined;
case 7 /* Undefined */:
return isInUnion && !options.allowUndefinedUnion ? 5 /* Undefined */ : undefined;
default:
return undefined;
}
} | function failureForKind(kind, isInUnion, options) {
switch (kind) {
case 0 /* String */:
case 1 /* FalseStringLiteral */:
return options.allowString ? undefined : 2 /* String */;
case 2 /* Number */:
case 3 /* FalseNumberLiteral */:
return options.allowNumber ? undefined : 3 /* Number */;
case 8 /* Enum */:
return 6 /* Enum */;
case 6 /* Null */:
return isInUnion && !options.allowNullUnion ? 4 /* Null */ : undefined;
case 7 /* Undefined */:
return isInUnion && !options.allowUndefinedUnion ? 5 /* Undefined */ : undefined;
default:
return undefined;
}
} |
JavaScript | function Inc() {
this.active = false;
this.delay = 300;
this.interval = 100;
this.slave = null;
this.start_timer = null;
this.run_timer = null;
this.sign = null;
this.inc = null;
this.kind = null;
this.init = function () {
var self = this;
window.addEventListener('mouseup', function () {
self.up();
}, false);
};
this.down = function (slave, sign, kind, inc) {
this.slave = slave;
this.sign = sign;
this.kind = kind;
this.inc = inc;
var self = this;
this.start_timer = window.setTimeout(function () {
self.run();
}, this.delay);
this.active = true;
};
this.up = function () {
if (this.active) {
window.clearTimeout(this.start_timer);
if (this.run_timer) {
window.clearInterval(this.run_timer);
this.run_timer = null;
}
this.slave.incCB(this.sign, this.kind, this.inc);
this.cf = null;
this.active = false;
}
};
this.upS = function () {
if (this.active) {
window.clearTimeout(this.start_timer);
if (this.run_timer) {
window.clearInterval(this.run_timer);
this.run_timer = null;
}
this.cf = null;
this.active = false;
}
};
this.run = function () {
var self = this;
this.run_timer = window.setInterval(function () {
self.slave.incCB(self.sign, self.kind, self.inc);
}, 100);
};
} | function Inc() {
this.active = false;
this.delay = 300;
this.interval = 100;
this.slave = null;
this.start_timer = null;
this.run_timer = null;
this.sign = null;
this.inc = null;
this.kind = null;
this.init = function () {
var self = this;
window.addEventListener('mouseup', function () {
self.up();
}, false);
};
this.down = function (slave, sign, kind, inc) {
this.slave = slave;
this.sign = sign;
this.kind = kind;
this.inc = inc;
var self = this;
this.start_timer = window.setTimeout(function () {
self.run();
}, this.delay);
this.active = true;
};
this.up = function () {
if (this.active) {
window.clearTimeout(this.start_timer);
if (this.run_timer) {
window.clearInterval(this.run_timer);
this.run_timer = null;
}
this.slave.incCB(this.sign, this.kind, this.inc);
this.cf = null;
this.active = false;
}
};
this.upS = function () {
if (this.active) {
window.clearTimeout(this.start_timer);
if (this.run_timer) {
window.clearInterval(this.run_timer);
this.run_timer = null;
}
this.cf = null;
this.active = false;
}
};
this.run = function () {
var self = this;
this.run_timer = window.setInterval(function () {
self.slave.incCB(self.sign, self.kind, self.inc);
}, 100);
};
} |
JavaScript | function stripTags(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
return doc.body.textContent || '';
} | function stripTags(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
return doc.body.textContent || '';
} |
JavaScript | function filterByConcept(quizAttempt, concept = null) {
// Filter by concept, if applicable
let questionAttempts;
if (concept !== null) {
questionAttempts = quizAttempt.questionAttempts.filter(
questionAttempt => questionAttempt.question.concept === concept
);
} else {
questionAttempts = quizAttempt.questionAttempts;
}
return questionAttempts;
} | function filterByConcept(quizAttempt, concept = null) {
// Filter by concept, if applicable
let questionAttempts;
if (concept !== null) {
questionAttempts = quizAttempt.questionAttempts.filter(
questionAttempt => questionAttempt.question.concept === concept
);
} else {
questionAttempts = quizAttempt.questionAttempts;
}
return questionAttempts;
} |
JavaScript | function predictedScore(quizAttempt, concept = null) {
if (
!quizAttempt ||
!quizAttempt.questionAttempts ||
quizAttempt.questionAttempts.length === 0 ||
!quizAttempt.conceptConfidences ||
quizAttempt.conceptConfidences.length === 0
) {
return 0;
}
const questionAttempts = filterByConcept(quizAttempt, concept);
// Avoid divide by zero
const questionCount = questionAttempts.length;
if (questionCount === 0) {
return 0;
}
// Predicted score is the percentage of questions that the student predicted they would get correct (in the pre-quiz confidence assessment)
let predictedCount = 0;
// Calculate predicted count, based on entire quiz or specific concept
if (concept !== null) {
const conceptConfidence = quizAttempt.conceptConfidences.find(c => c.concept === concept);
if (conceptConfidence === undefined) {
return 0;
}
predictedCount += conceptConfidence.confidence;
} else {
quizAttempt.conceptConfidences.forEach(c => (predictedCount += c.confidence));
}
return predictedCount / questionCount;
} | function predictedScore(quizAttempt, concept = null) {
if (
!quizAttempt ||
!quizAttempt.questionAttempts ||
quizAttempt.questionAttempts.length === 0 ||
!quizAttempt.conceptConfidences ||
quizAttempt.conceptConfidences.length === 0
) {
return 0;
}
const questionAttempts = filterByConcept(quizAttempt, concept);
// Avoid divide by zero
const questionCount = questionAttempts.length;
if (questionCount === 0) {
return 0;
}
// Predicted score is the percentage of questions that the student predicted they would get correct (in the pre-quiz confidence assessment)
let predictedCount = 0;
// Calculate predicted count, based on entire quiz or specific concept
if (concept !== null) {
const conceptConfidence = quizAttempt.conceptConfidences.find(c => c.concept === concept);
if (conceptConfidence === undefined) {
return 0;
}
predictedCount += conceptConfidence.confidence;
} else {
quizAttempt.conceptConfidences.forEach(c => (predictedCount += c.confidence));
}
return predictedCount / questionCount;
} |
JavaScript | function wadayanoScore(quizAttempt, concept = null) {
if (!quizAttempt || !quizAttempt.questionAttempts || quizAttempt.questionAttempts.length === 0) {
return 0;
}
const questionAttempts = filterByConcept(quizAttempt, concept);
// Avoid divide by zero
const questionCount = questionAttempts.length;
if (questionCount === 0) {
return 0;
}
// wadayano score is the percentage of questions where the student accurately assessed their confidence (confident and correct are either both true, or both false)
const accurateConfidenceCount = questionAttempts.filter(q => q.isConfident === q.isCorrect)
.length;
return accurateConfidenceCount / questionCount;
} | function wadayanoScore(quizAttempt, concept = null) {
if (!quizAttempt || !quizAttempt.questionAttempts || quizAttempt.questionAttempts.length === 0) {
return 0;
}
const questionAttempts = filterByConcept(quizAttempt, concept);
// Avoid divide by zero
const questionCount = questionAttempts.length;
if (questionCount === 0) {
return 0;
}
// wadayano score is the percentage of questions where the student accurately assessed their confidence (confident and correct are either both true, or both false)
const accurateConfidenceCount = questionAttempts.filter(q => q.isConfident === q.isCorrect)
.length;
return accurateConfidenceCount / questionCount;
} |
JavaScript | function stringCompare(a, b, caseSensitive = false) {
if (!caseSensitive) {
a = a.toLowerCase();
b = b.toLowerCase();
}
// eslint-disable-next-line no-nested-ternary
return a < b ? -1 : a > b ? 1 : 0;
} | function stringCompare(a, b, caseSensitive = false) {
if (!caseSensitive) {
a = a.toLowerCase();
b = b.toLowerCase();
}
// eslint-disable-next-line no-nested-ternary
return a < b ? -1 : a > b ? 1 : 0;
} |
JavaScript | function createRandomGenerator(seed) {
const a = 5486230734; // some big numbers
const b = 6908969830;
const m = 9853205067;
let x = seed;
// returns a random value 0 <= num < 1
return function(seed = x) {
// seed is optional. If supplied sets a new seed
x = (seed * a + b) % m;
return x / m;
};
} | function createRandomGenerator(seed) {
const a = 5486230734; // some big numbers
const b = 6908969830;
const m = 9853205067;
let x = seed;
// returns a random value 0 <= num < 1
return function(seed = x) {
// seed is optional. If supplied sets a new seed
x = (seed * a + b) % m;
return x / m;
};
} |
JavaScript | function stringTo32BitHash(str) {
let v = 0;
for (let i = 0; i < str.length; i += 1) {
v += str.charCodeAt(i) << i % 24;
}
return v % 0xffffffff;
} | function stringTo32BitHash(str) {
let v = 0;
for (let i = 0; i < str.length; i += 1) {
v += str.charCodeAt(i) << i % 24;
}
return v % 0xffffffff;
} |
JavaScript | function shuffleArray(seed, arr) {
const rArr = [];
const random = createRandomGenerator(stringTo32BitHash(seed));
while (arr.length > 1) {
rArr.push(arr.splice(Math.floor(random() * arr.length), 1)[0]);
}
rArr.push(arr[0]);
return rArr;
} | function shuffleArray(seed, arr) {
const rArr = [];
const random = createRandomGenerator(stringTo32BitHash(seed));
while (arr.length > 1) {
rArr.push(arr.splice(Math.floor(random() * arr.length), 1)[0]);
}
rArr.push(arr[0]);
return rArr;
} |
JavaScript | function allowAccess(allowInstructor, allowStudent) {
const loggedIn = !!localStorage.getItem(AUTH_TOKEN);
if (!loggedIn) {
// If not logged in, deny
return false;
}
const currentRole = localStorage.getItem(AUTH_ROLE);
// Determine access based on current role and what this check is valid for
if (allowInstructor && currentRole === AUTH_ROLE_INSTRUCTOR) {
return true;
}
if (allowStudent && currentRole === AUTH_ROLE_STUDENT) {
return true;
}
// If role matched neither instructor nor student, or this route allows neither, deny
return false;
} | function allowAccess(allowInstructor, allowStudent) {
const loggedIn = !!localStorage.getItem(AUTH_TOKEN);
if (!loggedIn) {
// If not logged in, deny
return false;
}
const currentRole = localStorage.getItem(AUTH_ROLE);
// Determine access based on current role and what this check is valid for
if (allowInstructor && currentRole === AUTH_ROLE_INSTRUCTOR) {
return true;
}
if (allowStudent && currentRole === AUTH_ROLE_STUDENT) {
return true;
}
// If role matched neither instructor nor student, or this route allows neither, deny
return false;
} |
JavaScript | function AuthRoute({ children, instructor, student, ...rest }) {
const valid = allowAccess(instructor, student);
return (
<Route
{...rest}
render={({ location }) =>
valid ? children : <Redirect to={{ pathname: '/login', state: { from: location } }} />
}
/>
);
} | function AuthRoute({ children, instructor, student, ...rest }) {
const valid = allowAccess(instructor, student);
return (
<Route
{...rest}
render={({ location }) =>
valid ? children : <Redirect to={{ pathname: '/login', state: { from: location } }} />
}
/>
);
} |
JavaScript | function parseSurveyText(text) {
// Add an extra new line at the end so that last question gets popped off
text += '\n';
const lines = text.split('\n');
const questions = [];
let newQuestion = { options: [] };
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line === '' && newQuestion.prompt) {
questions.push(newQuestion);
newQuestion = { options: [] };
} else if (!newQuestion.prompt) {
newQuestion.prompt = line;
newQuestion.index = questions.length + 1;
} else if (line !== '') {
newQuestion.options.push({ index: newQuestion.options.length + 1, text: line });
}
}
// console.log(questions);
return { questions };
} | function parseSurveyText(text) {
// Add an extra new line at the end so that last question gets popped off
text += '\n';
const lines = text.split('\n');
const questions = [];
let newQuestion = { options: [] };
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line === '' && newQuestion.prompt) {
questions.push(newQuestion);
newQuestion = { options: [] };
} else if (!newQuestion.prompt) {
newQuestion.prompt = line;
newQuestion.index = questions.length + 1;
} else if (line !== '') {
newQuestion.options.push({ index: newQuestion.options.length + 1, text: line });
}
}
// console.log(questions);
return { questions };
} |
JavaScript | function stringifySurvey(survey) {
if (!survey) {
return '';
}
let text = '';
try {
survey.questions.forEach(question => {
text += `${question.prompt}\n`;
text += question.options.map(opt => opt.text).join('\n');
text += '\n\n';
});
} catch (error) {
alert('Error parsing survey');
}
return text.trim();
} | function stringifySurvey(survey) {
if (!survey) {
return '';
}
let text = '';
try {
survey.questions.forEach(question => {
text += `${question.prompt}\n`;
text += question.options.map(opt => opt.text).join('\n');
text += '\n\n';
});
} catch (error) {
alert('Error parsing survey');
}
return text.trim();
} |
JavaScript | async function instructorCourseCheck(context, courseId) {
// Perform instructor check first
const userInfo = instructorCheck(context);
// Check that the logged-in instructor is part of the given course
const course = await context.db.query.course({
where: { id: courseId }
}, `{ instructors { id, email } }`);
if (course.instructors.filter(i => i.id === userInfo.userId).length === 0) {
throw new Error('You don’t have permission to access this course.');
}
return userInfo;
} | async function instructorCourseCheck(context, courseId) {
// Perform instructor check first
const userInfo = instructorCheck(context);
// Check that the logged-in instructor is part of the given course
const course = await context.db.query.course({
where: { id: courseId }
}, `{ instructors { id, email } }`);
if (course.instructors.filter(i => i.id === userInfo.userId).length === 0) {
throw new Error('You don’t have permission to access this course.');
}
return userInfo;
} |
JavaScript | function correctShortAnswers(root, args, context, info) {
const { userId, isInstructor } = getUserInfo(context);
// If it’s not an instructor, always return false
if (!isInstructor) {
throw Error('Student role can not access correctShortAnswers');
}
// Otherwise, return the actual value
return root.correctShortAnswers;
} | function correctShortAnswers(root, args, context, info) {
const { userId, isInstructor } = getUserInfo(context);
// If it’s not an instructor, always return false
if (!isInstructor) {
throw Error('Student role can not access correctShortAnswers');
}
// Otherwise, return the actual value
return root.correctShortAnswers;
} |
JavaScript | function scrollToQuestionId(questionId) {
const questionElement = document.getElementById(`container${questionId}`);
if (questionElement !== null) {
questionElement.scrollIntoView(true);
// Scroll up to account for sticky question navbar, if not at bottom of page already
// https://stackoverflow.com/a/44422472/702643
if (window.innerHeight + Math.ceil(window.pageYOffset) < document.body.offsetHeight) {
const headerHeight = document.getElementById('question-navbar').offsetHeight;
window.scrollTo(0, window.scrollY - headerHeight);
}
}
} | function scrollToQuestionId(questionId) {
const questionElement = document.getElementById(`container${questionId}`);
if (questionElement !== null) {
questionElement.scrollIntoView(true);
// Scroll up to account for sticky question navbar, if not at bottom of page already
// https://stackoverflow.com/a/44422472/702643
if (window.innerHeight + Math.ceil(window.pageYOffset) < document.body.offsetHeight) {
const headerHeight = document.getElementById('question-navbar').offsetHeight;
window.scrollTo(0, window.scrollY - headerHeight);
}
}
} |
JavaScript | function toggleMenu(e) {
e.preventDefault();
// Toggle the class on both the "navbar-burger" and the "navbar-menu"
e.target.classList.toggle('is-active');
document.getElementById('header-main-menu').classList.toggle('is-active');
} | function toggleMenu(e) {
e.preventDefault();
// Toggle the class on both the "navbar-burger" and the "navbar-menu"
e.target.classList.toggle('is-active');
document.getElementById('header-main-menu').classList.toggle('is-active');
} |
JavaScript | async function removeInstructorFromCourse(root, args, context, info) {
// Lower-case email
const email = args.email.toLowerCase();
try {
// It could be a pending invite that should be canceled
const invitesCanceled = await context.db.mutation.deleteManyPendingCourseInvites({
where: {
course: { id: args.courseId },
email: email
},
}, `{ count }`);
console.log(JSON.stringify(invitesCanceled));
if (invitesCanceled.count > 0) {
return 'Invite canceled';
}
// Prevent a user from removing the last instructor of a course
const course = await context.db.query.course({
where: { id: args.courseId }
}, `{ instructors { id } }`);
if (course.instructors.length === 1) {
return `${email} is the only instructor in this course, and cannot be removed. To transfer ownership of a course, invite another instructor and have them remove you from the course.`;
}
// Otherwise, try to remove the instructor from the course
await context.db.mutation.updateCourse({
where: { id: args.courseId },
data: { instructors: { disconnect: { email } } }
});
return 'Instructor removed';
} catch (error) {
return 'Instructor was not in the course.';
}
} | async function removeInstructorFromCourse(root, args, context, info) {
// Lower-case email
const email = args.email.toLowerCase();
try {
// It could be a pending invite that should be canceled
const invitesCanceled = await context.db.mutation.deleteManyPendingCourseInvites({
where: {
course: { id: args.courseId },
email: email
},
}, `{ count }`);
console.log(JSON.stringify(invitesCanceled));
if (invitesCanceled.count > 0) {
return 'Invite canceled';
}
// Prevent a user from removing the last instructor of a course
const course = await context.db.query.course({
where: { id: args.courseId }
}, `{ instructors { id } }`);
if (course.instructors.length === 1) {
return `${email} is the only instructor in this course, and cannot be removed. To transfer ownership of a course, invite another instructor and have them remove you from the course.`;
}
// Otherwise, try to remove the instructor from the course
await context.db.mutation.updateCourse({
where: { id: args.courseId },
data: { instructors: { disconnect: { email } } }
});
return 'Instructor removed';
} catch (error) {
return 'Instructor was not in the course.';
}
} |
JavaScript | async function startOrResumeQuizAttempt(root, args, context, info) {
// Check for valid student login
const studentId = getUserInfo(context).userId;
const quizId = args.quizId;
// Check that student has access to the course that owns this quiz (LTI launch would automatically enroll, but practice launches shouldn't)
const studentInCourse = await context.db.query.students({
where: {
id: studentId,
courses_some: { quizzes_some: {id: quizId } }
}
}, `{ id }`);
if (studentInCourse.length === 0) {
throw Error('Student not enrolled in course that this quiz belongs to');
}
// Since the quiz attempt is unique on the combination of two fields (quizId and studentId), prisma's built-in upsert won't work
// Find existing uncompleted attempt(s) for this student and quiz
const existingAttempts = await context.db.query.quizAttempts({
where: {
quiz: { id: quizId },
student: { id: studentId },
completed: null
}
}, `{ id }`);
// If there's an existing attempt, return it
if (existingAttempts.length > 0) {
console.log('Returning existing quiz attempt');
return context.db.query.quizAttempt({ where: { id: existingAttempts[0].id } }, info);
} else {
// Otherwise create a new attempt and return it
// This will only be practice launches. LTI launches are handled in lti.js
// If it’s a graded quiz, block starting the attempt (since it must be LTI-launched first)
const quiz = await context.db.query.quiz({
where: { id: quizId }
}, `{ id, type }`);
if (quiz.type === 'GRADED') {
throw Error('This is a graded quiz, and must be launched from your LMS.');
}
return context.db.mutation.createQuizAttempt({
data: {
quiz: { connect: { id: quizId } },
student: { connect: { id: studentId } }
}
}, info);
console.log('Created new quiz attempt');
}
} | async function startOrResumeQuizAttempt(root, args, context, info) {
// Check for valid student login
const studentId = getUserInfo(context).userId;
const quizId = args.quizId;
// Check that student has access to the course that owns this quiz (LTI launch would automatically enroll, but practice launches shouldn't)
const studentInCourse = await context.db.query.students({
where: {
id: studentId,
courses_some: { quizzes_some: {id: quizId } }
}
}, `{ id }`);
if (studentInCourse.length === 0) {
throw Error('Student not enrolled in course that this quiz belongs to');
}
// Since the quiz attempt is unique on the combination of two fields (quizId and studentId), prisma's built-in upsert won't work
// Find existing uncompleted attempt(s) for this student and quiz
const existingAttempts = await context.db.query.quizAttempts({
where: {
quiz: { id: quizId },
student: { id: studentId },
completed: null
}
}, `{ id }`);
// If there's an existing attempt, return it
if (existingAttempts.length > 0) {
console.log('Returning existing quiz attempt');
return context.db.query.quizAttempt({ where: { id: existingAttempts[0].id } }, info);
} else {
// Otherwise create a new attempt and return it
// This will only be practice launches. LTI launches are handled in lti.js
// If it’s a graded quiz, block starting the attempt (since it must be LTI-launched first)
const quiz = await context.db.query.quiz({
where: { id: quizId }
}, `{ id, type }`);
if (quiz.type === 'GRADED') {
throw Error('This is a graded quiz, and must be launched from your LMS.');
}
return context.db.mutation.createQuizAttempt({
data: {
quiz: { connect: { id: quizId } },
student: { connect: { id: studentId } }
}
}, info);
console.log('Created new quiz attempt');
}
} |
JavaScript | async function inviteInstructor(email) {
// Send invite mutation
const result = await inviteInstructorMutation({
variables: {
courseId,
email,
},
});
// Show error, or success string from mutation
if (result.errors && result.errors.length > 0) {
ButterToast.raise({
content: <ToastTemplate content={result.errors[0].message} className="is-danger" />,
timeout: 3000,
});
} else {
ButterToast.raise({
content: (
<ToastTemplate content={result.data.sendInstructorCourseInvite} className="is-success" />
),
sticky: true,
});
}
refetch();
} | async function inviteInstructor(email) {
// Send invite mutation
const result = await inviteInstructorMutation({
variables: {
courseId,
email,
},
});
// Show error, or success string from mutation
if (result.errors && result.errors.length > 0) {
ButterToast.raise({
content: <ToastTemplate content={result.errors[0].message} className="is-danger" />,
timeout: 3000,
});
} else {
ButterToast.raise({
content: (
<ToastTemplate content={result.data.sendInstructorCourseInvite} className="is-success" />
),
sticky: true,
});
}
refetch();
} |
JavaScript | function inviteInstructorPrompt() {
const email = window.prompt(
'Other instructors will have all course permissions, including managing quizzes, deleting the course, and inviting/removing any instructors.\nEnter the email address of the instructor whom you would like to invite to this course:'
);
if (!email || email.trim() === '') {
return;
}
// Send the invite
inviteInstructor(email.trim());
} | function inviteInstructorPrompt() {
const email = window.prompt(
'Other instructors will have all course permissions, including managing quizzes, deleting the course, and inviting/removing any instructors.\nEnter the email address of the instructor whom you would like to invite to this course:'
);
if (!email || email.trim() === '') {
return;
}
// Send the invite
inviteInstructor(email.trim());
} |
JavaScript | async function removeInstructor(email) {
if (!window.confirm(`Are you sure you want to remove ${email} from this course?`)) {
return;
}
// Send remove mutation
const result = await removeInstructorMutation({
variables: {
courseId,
email: email.trim(),
},
});
// Show error, or success string from mutation
if (result.errors && result.errors.length > 0) {
ButterToast.raise({
content: <ToastTemplate content={result.errors[0].message} className="is-danger" />,
timeout: 12000,
});
} else {
ButterToast.raise({
content: (
<ToastTemplate content={result.data.removeInstructorFromCourse} className="is-success" />
),
});
}
refetch();
} | async function removeInstructor(email) {
if (!window.confirm(`Are you sure you want to remove ${email} from this course?`)) {
return;
}
// Send remove mutation
const result = await removeInstructorMutation({
variables: {
courseId,
email: email.trim(),
},
});
// Show error, or success string from mutation
if (result.errors && result.errors.length > 0) {
ButterToast.raise({
content: <ToastTemplate content={result.errors[0].message} className="is-danger" />,
timeout: 12000,
});
} else {
ButterToast.raise({
content: (
<ToastTemplate content={result.data.removeInstructorFromCourse} className="is-success" />
),
});
}
refetch();
} |
JavaScript | async function requestPasswordReset() {
const emailInput = window.prompt(
'Enter the email address connected with your wadayano instructor account. If you are a student, simply launch wadayano from your learning management system.'
);
if (!emailInput || emailInput.trim() === '') {
return;
}
const result = await instructorRequestPasswordResetMutation({
variables: { email: emailInput.trim() },
});
if (result.errors && result.errors.length > 0) {
ButterToast.raise({
content: <ToastTemplate content={result.errors[0].message} className="is-danger" />,
timeout: 12000,
});
} else if (result.data.instructorRequestPasswordReset === true) {
ButterToast.raise({
content: (
<ToastTemplate
content={`An email was sent to ${emailInput} with further instructions.`}
className="is-success"
/>
),
sticky: true,
});
} else {
ButterToast.raise({
content: (
<ToastTemplate
content={`No account was found for ${emailInput}, or there was an unexpected error sending the password reset email.`}
className="is-danger"
/>
),
timeout: 12000,
});
}
} | async function requestPasswordReset() {
const emailInput = window.prompt(
'Enter the email address connected with your wadayano instructor account. If you are a student, simply launch wadayano from your learning management system.'
);
if (!emailInput || emailInput.trim() === '') {
return;
}
const result = await instructorRequestPasswordResetMutation({
variables: { email: emailInput.trim() },
});
if (result.errors && result.errors.length > 0) {
ButterToast.raise({
content: <ToastTemplate content={result.errors[0].message} className="is-danger" />,
timeout: 12000,
});
} else if (result.data.instructorRequestPasswordReset === true) {
ButterToast.raise({
content: (
<ToastTemplate
content={`An email was sent to ${emailInput} with further instructions.`}
className="is-success"
/>
),
sticky: true,
});
} else {
ButterToast.raise({
content: (
<ToastTemplate
content={`No account was found for ${emailInput}, or there was an unexpected error sending the password reset email.`}
className="is-danger"
/>
),
timeout: 12000,
});
}
} |
JavaScript | conceptQuestionCounts(props, propName, componentName) {
if (!(props[propName] instanceof Map)) {
return new Error(
`Invalid prop \`${propName}\` supplied to` +
` \`${componentName}\`. Validation failed: must be a Map.`
);
}
return null;
} | conceptQuestionCounts(props, propName, componentName) {
if (!(props[propName] instanceof Map)) {
return new Error(
`Invalid prop \`${propName}\` supplied to` +
` \`${componentName}\`. Validation failed: must be a Map.`
);
}
return null;
} |
JavaScript | async function _upsertStudentOnLaunch(db, ltiUserId, name, email) {
const student = await db.mutation.upsertStudent({
where: { ltiUserId },
create: { ltiUserId, name, email },
update: { name, email }
}, `{ id }`);
return student.id;
} | async function _upsertStudentOnLaunch(db, ltiUserId, name, email) {
const student = await db.mutation.upsertStudent({
where: { ltiUserId },
create: { ltiUserId, name, email },
update: { name, email }
}, `{ id }`);
return student.id;
} |
JavaScript | function serializeBinary(binFileName, jsFileName) {
const binContent = fs.readFileSync(binFileName, 'binary');
const binLength = binContent.length;
const arrayStr1 = [];
for (let i = 0; i < 256; i++) {
arrayStr1.push(String.fromCharCode(i));
}
const arrayConv = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f',
];
const fd = fs.openSync(jsFileName, 'a');
fs.writeSync(fd, '"');
for (let i = 0, i_finish = (binLength - 1) | 0; i <= i_finish; i++) {
const c = binContent.charCodeAt(i);
let exit = 0;
if (c >= 32) {
if (c >= 127) {
if (c >= 128) {
fs.writeSync(fd, '\\x');
fs.writeSync(fd, arrayConv[c >>> 4]);
fs.writeSync(fd, arrayConv[c & 15]);
} else {
exit = 1;
}
} else if (c !== 92) {
if (c === /* "\"" */ 34) {
fs.writeSync(fd, '\\');
fs.writeSync(fd, arrayStr1[c]);
} else {
fs.writeSync(fd, arrayStr1[c]);
}
} else {
fs.writeSync(fd, '\\\\');
}
} else if (c >= 14) {
exit = 1;
} else {
switch (c) {
case 0:
if (
i === ((binLength - 1) | 0) ||
binContent.charCodeAt((i + 1) | 0) < /* "0" */ 48 ||
binContent.charCodeAt((i + 1) | 0) > /* "9" */ 57
) {
fs.writeSync(fd, '\\0');
} else {
exit = 1;
}
break;
case 8:
fs.writeSync(fd, '\\b');
break;
case 9:
fs.writeSync(fd, '\\t');
break;
case 10:
fs.writeSync(fd, '\\n');
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 11:
exit = 1;
break;
case 12:
fs.writeSync(fd, '\\f');
break;
case 13:
fs.writeSync(fd, '\\r');
break;
}
}
if (exit === 1) {
fs.writeSync(fd, '\\x');
fs.writeSync(fd, arrayConv[c >>> 4]);
fs.writeSync(fd, arrayConv[c & 15]);
}
}
fs.writeSync(fd, '"');
fs.closeSync(fd);
return /* () */ 0;
} | function serializeBinary(binFileName, jsFileName) {
const binContent = fs.readFileSync(binFileName, 'binary');
const binLength = binContent.length;
const arrayStr1 = [];
for (let i = 0; i < 256; i++) {
arrayStr1.push(String.fromCharCode(i));
}
const arrayConv = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f',
];
const fd = fs.openSync(jsFileName, 'a');
fs.writeSync(fd, '"');
for (let i = 0, i_finish = (binLength - 1) | 0; i <= i_finish; i++) {
const c = binContent.charCodeAt(i);
let exit = 0;
if (c >= 32) {
if (c >= 127) {
if (c >= 128) {
fs.writeSync(fd, '\\x');
fs.writeSync(fd, arrayConv[c >>> 4]);
fs.writeSync(fd, arrayConv[c & 15]);
} else {
exit = 1;
}
} else if (c !== 92) {
if (c === /* "\"" */ 34) {
fs.writeSync(fd, '\\');
fs.writeSync(fd, arrayStr1[c]);
} else {
fs.writeSync(fd, arrayStr1[c]);
}
} else {
fs.writeSync(fd, '\\\\');
}
} else if (c >= 14) {
exit = 1;
} else {
switch (c) {
case 0:
if (
i === ((binLength - 1) | 0) ||
binContent.charCodeAt((i + 1) | 0) < /* "0" */ 48 ||
binContent.charCodeAt((i + 1) | 0) > /* "9" */ 57
) {
fs.writeSync(fd, '\\0');
} else {
exit = 1;
}
break;
case 8:
fs.writeSync(fd, '\\b');
break;
case 9:
fs.writeSync(fd, '\\t');
break;
case 10:
fs.writeSync(fd, '\\n');
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 11:
exit = 1;
break;
case 12:
fs.writeSync(fd, '\\f');
break;
case 13:
fs.writeSync(fd, '\\r');
break;
}
}
if (exit === 1) {
fs.writeSync(fd, '\\x');
fs.writeSync(fd, arrayConv[c >>> 4]);
fs.writeSync(fd, arrayConv[c & 15]);
}
}
fs.writeSync(fd, '"');
fs.closeSync(fd);
return /* () */ 0;
} |
JavaScript | function fetchInitialRecordCount(){
var countQueryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query: "logstream:\"-1234\""
}
};
client.searchCount(countQueryInfo, function(count) {
if (count["status"] === "success"){
initialRecordCount = count["message"];
if(initialRecordCount >= 0){
setInterval(fetchCurrentRecordCount, 5000);
}
}
return initialRecordCount;
}, function(error) {
console.log("error occured: " + error);
});
} | function fetchInitialRecordCount(){
var countQueryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query: "logstream:\"-1234\""
}
};
client.searchCount(countQueryInfo, function(count) {
if (count["status"] === "success"){
initialRecordCount = count["message"];
if(initialRecordCount >= 0){
setInterval(fetchCurrentRecordCount, 5000);
}
}
return initialRecordCount;
}, function(error) {
console.log("error occured: " + error);
});
} |
JavaScript | function fetchCurrentRecordCount() {
var countQueryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query: "logstream:\"-1234\""
}
};
client.searchCount(countQueryInfo, function(count) {
currentRecordCount = count["message"];
var logCountDifference = currentRecordCount - initialRecordCount;
if(logCountDifference > 0){
fetchRecords(logCountDifference);
}
}, function(error) {
console.log("error occured: " + error);
});
} | function fetchCurrentRecordCount() {
var countQueryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query: "logstream:\"-1234\""
}
};
client.searchCount(countQueryInfo, function(count) {
currentRecordCount = count["message"];
var logCountDifference = currentRecordCount - initialRecordCount;
if(logCountDifference > 0){
fetchRecords(logCountDifference);
}
}, function(error) {
console.log("error occured: " + error);
});
} |
JavaScript | function fetchRecords(logCountDifference){
initialRecordCount = currentRecordCount;
logLineArray.length = 0;
var queryInfo;
queryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query:"logstream:\"-1234\"",
start: "0",
count: ""+logCountDifference,
sortBy : [
{
field : "_timestamp",
sortType : "DESC",
reversed : "true"
}
]
}
};
var lineItem = {time : 'Fri, 20 May 2016 12:30:21 GMT ',
className : 'fooClass',
content: 'fooContent',
trace : 'fooTrace'};
client.search(queryInfo, function (data) {
var obj = JSON.parse(data["message"]);
if (data["status"] === "success") {
for (var i = 0; i < obj.length; i++) {
var tempDay = new Date(parseInt(obj[i].values._eventTimeStamp)).toUTCString();
var lineItem = {
time: tempDay,
className: obj[i].values._class,
content: obj[i].values._content,
trace: obj[i].values._trace,
appname :obj[i].values._appName,
tenantId :obj[i].values.logstream,
};
writeToLogViewer(lineItem);
}
}
}, function (error) {
console.log("error occurred: " + error);
});
} | function fetchRecords(logCountDifference){
initialRecordCount = currentRecordCount;
logLineArray.length = 0;
var queryInfo;
queryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query:"logstream:\"-1234\"",
start: "0",
count: ""+logCountDifference,
sortBy : [
{
field : "_timestamp",
sortType : "DESC",
reversed : "true"
}
]
}
};
var lineItem = {time : 'Fri, 20 May 2016 12:30:21 GMT ',
className : 'fooClass',
content: 'fooContent',
trace : 'fooTrace'};
client.search(queryInfo, function (data) {
var obj = JSON.parse(data["message"]);
if (data["status"] === "success") {
for (var i = 0; i < obj.length; i++) {
var tempDay = new Date(parseInt(obj[i].values._eventTimeStamp)).toUTCString();
var lineItem = {
time: tempDay,
className: obj[i].values._class,
content: obj[i].values._content,
trace: obj[i].values._trace,
appname :obj[i].values._appName,
tenantId :obj[i].values.logstream,
};
writeToLogViewer(lineItem);
}
}
}, function (error) {
console.log("error occurred: " + error);
});
} |
JavaScript | function initSelect2(data, element, path) {
/* Initialize select2 selection box for html element*/
var $select = $(element).select2({
placeholder: "Value",
data: data,
multiple: true,
dropdownAutoWidth: true,
containerCssClass: 'custom-env-class-for-demo select',
width: '350px',
tags: true,
selectOnBlur: true,
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
}
});
/* Display values based on selected value in dropdown */
$select.on("select2:select", function(e) {
e.params.data.text = e.params.data.id;
$select.val(e.params.data.id).trigger('change');
if (e.params.data.isNew != undefined && e.params.data.isNew) {
$select.empty();
$select.select2("val", "Invalid Selection");
} else if (e.params.data.isNextLevel) {
$select.empty();
$select.trigger('change');
$select = initSelect2(e.params.data.data, element, "");
$select.select2('open');
} else {
var highlighted = $(e.target).data('select2').$dropdown.find('.select2-results__option--highlighted');
if (highlighted) {
var data = highlighted.data('data');
var id = data.id;
/* Display selected value in selection box */
if (id != 0) {
var selection = data.text;
if (path.indexOf("database:") >= 0) {
if (id.toLowerCase() === selection.toLowerCase()) {
path += ("/" + selection);
} else {
path += ("/" + selection + "/" + id);
}
$select.attr("data-placeholder", path);
}
$select.select2("val", id);
} else {
$select.select2("val", $(this).val());
}
}
}
});
$(".select2-search__field").on('input', function(e) {
if ($(this).val() == "database:") {
var dbs;
jagg.post("../blocks/database/list/ajax/list.jag", {
action: "getAllDatabasesInfo"
}, function(result) {
dbs = JSON.parse(result);
$select.trigger('change');
$select = initSelect2(dbs, element, "database:");
$select.select2('open');
});
}
});
$select.on("change", function(e) {
var text = e.target.value;
if (text.length > 45) {
var truncatedText = jQuery.trim(text).substring(0, 42).slice(0, -1) + "...";
$('.select2-selection__choice').text(truncatedText);
}
});
//noinspection JSAnnotator
return $select;
} | function initSelect2(data, element, path) {
/* Initialize select2 selection box for html element*/
var $select = $(element).select2({
placeholder: "Value",
data: data,
multiple: true,
dropdownAutoWidth: true,
containerCssClass: 'custom-env-class-for-demo select',
width: '350px',
tags: true,
selectOnBlur: true,
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
}
});
/* Display values based on selected value in dropdown */
$select.on("select2:select", function(e) {
e.params.data.text = e.params.data.id;
$select.val(e.params.data.id).trigger('change');
if (e.params.data.isNew != undefined && e.params.data.isNew) {
$select.empty();
$select.select2("val", "Invalid Selection");
} else if (e.params.data.isNextLevel) {
$select.empty();
$select.trigger('change');
$select = initSelect2(e.params.data.data, element, "");
$select.select2('open');
} else {
var highlighted = $(e.target).data('select2').$dropdown.find('.select2-results__option--highlighted');
if (highlighted) {
var data = highlighted.data('data');
var id = data.id;
/* Display selected value in selection box */
if (id != 0) {
var selection = data.text;
if (path.indexOf("database:") >= 0) {
if (id.toLowerCase() === selection.toLowerCase()) {
path += ("/" + selection);
} else {
path += ("/" + selection + "/" + id);
}
$select.attr("data-placeholder", path);
}
$select.select2("val", id);
} else {
$select.select2("val", $(this).val());
}
}
}
});
$(".select2-search__field").on('input', function(e) {
if ($(this).val() == "database:") {
var dbs;
jagg.post("../blocks/database/list/ajax/list.jag", {
action: "getAllDatabasesInfo"
}, function(result) {
dbs = JSON.parse(result);
$select.trigger('change');
$select = initSelect2(dbs, element, "database:");
$select.select2('open');
});
}
});
$select.on("change", function(e) {
var text = e.target.value;
if (text.length > 45) {
var truncatedText = jQuery.trim(text).substring(0, 42).slice(0, -1) + "...";
$('.select2-selection__choice').text(truncatedText);
}
});
//noinspection JSAnnotator
return $select;
} |
JavaScript | function populateDatatable() {
usersDatatable = $('.datatable table').dataTable({
responsive: true,
"orderCellsTop": true,
'ajax': {
"type" : "POST",
"url" : '../blocks/database/add/ajax/add.jag',
"data" : function( d ) {
d.action = "getDatabaseUsersForDataTable";
d.dbName = dbName;
}
},
"columns": [
{ "data": "username", "width": "10%"},
{ "data": "attachuser" , "width": "5%","sClass" : "dt-body-center"},
{ "data": "trash", "orderable": false, "width": "3%", "sClass" : "dt-body-center" }
],
"fnDrawCallback": function( oSettings ) {
// onclick event of checkbox switch
$('.switch input[type=checkbox]').on("click",function(){
var isChecked = $(this).is(":checked");
var currentId = $(this).attr("id");
var currentElement = $("#"+ currentId);
//getting the user name from checkbox id, removing 'chkbx_'
var userName = currentId.substr(7);
$('#modal-title').html('Select User Privilege for User: <i>' + userName + '</i>');
if(isChecked){
attachUserWithPermissions(userName);
}else {
detachUserAndDropTemplate(userName);
currentElement.removeAttr("checked");
}
});
// on click event of delete
$('.delete_user').on("click",function(){
var currentId = $(this).attr("id");
//getting the user name from id, removing 'delete_'
var userName = currentId.substr(7);
jagg.popMessage({type:'confirm',title:'Delete User',content:'Are you sure you want to delete the user ' + userName + ' ?', okCallback:function(){deleteUser(userName);}, cancelCallback:function(){}});
});
} // end of call back function
}); // end of datatable
} | function populateDatatable() {
usersDatatable = $('.datatable table').dataTable({
responsive: true,
"orderCellsTop": true,
'ajax': {
"type" : "POST",
"url" : '../blocks/database/add/ajax/add.jag',
"data" : function( d ) {
d.action = "getDatabaseUsersForDataTable";
d.dbName = dbName;
}
},
"columns": [
{ "data": "username", "width": "10%"},
{ "data": "attachuser" , "width": "5%","sClass" : "dt-body-center"},
{ "data": "trash", "orderable": false, "width": "3%", "sClass" : "dt-body-center" }
],
"fnDrawCallback": function( oSettings ) {
// onclick event of checkbox switch
$('.switch input[type=checkbox]').on("click",function(){
var isChecked = $(this).is(":checked");
var currentId = $(this).attr("id");
var currentElement = $("#"+ currentId);
//getting the user name from checkbox id, removing 'chkbx_'
var userName = currentId.substr(7);
$('#modal-title').html('Select User Privilege for User: <i>' + userName + '</i>');
if(isChecked){
attachUserWithPermissions(userName);
}else {
detachUserAndDropTemplate(userName);
currentElement.removeAttr("checked");
}
});
// on click event of delete
$('.delete_user').on("click",function(){
var currentId = $(this).attr("id");
//getting the user name from id, removing 'delete_'
var userName = currentId.substr(7);
jagg.popMessage({type:'confirm',title:'Delete User',content:'Are you sure you want to delete the user ' + userName + ' ?', okCallback:function(){deleteUser(userName);}, cancelCallback:function(){}});
});
} // end of call back function
}); // end of datatable
} |
JavaScript | function detachUserAndDropTemplate(userName){
// detach user from database
jagg.post("../blocks/database/add/ajax/add.jag", {
action:"detachUser",
databaseName:dbName,
username:userName
}, function (result) {
if(result) {
usersDatatable.api().ajax.reload();
jagg.message({content:'User ' + userName +' detached from database ' + dbName , type:'success', id:'userdetach'});
}
},function (jqXHR, textStatus, errorThrown) {
jagg.message({content:'Error occured while detaching the user from database' , type:'error', id:'userdetach'});
});
} | function detachUserAndDropTemplate(userName){
// detach user from database
jagg.post("../blocks/database/add/ajax/add.jag", {
action:"detachUser",
databaseName:dbName,
username:userName
}, function (result) {
if(result) {
usersDatatable.api().ajax.reload();
jagg.message({content:'User ' + userName +' detached from database ' + dbName , type:'success', id:'userdetach'});
}
},function (jqXHR, textStatus, errorThrown) {
jagg.message({content:'Error occured while detaching the user from database' , type:'error', id:'userdetach'});
});
} |
JavaScript | function attachUserWithPermissions(userName) {
if(userName) {
jagg.post("../blocks/database/add/ajax/add.jag", {
action:"attachUserWithPermissions",
databaseName:dbName,
userName:userName
},function (result) {
if(result){
usersDatatable.api().ajax.reload();
}
},function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status != 0){
jagg.message({type:'error',content:'User ' + userName + ' attaching failed for database ' + dbName, id:'attach_user'});
}
});
}
} | function attachUserWithPermissions(userName) {
if(userName) {
jagg.post("../blocks/database/add/ajax/add.jag", {
action:"attachUserWithPermissions",
databaseName:dbName,
userName:userName
},function (result) {
if(result){
usersDatatable.api().ajax.reload();
}
},function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status != 0){
jagg.message({type:'error',content:'User ' + userName + ' attaching failed for database ' + dbName, id:'attach_user'});
}
});
}
} |
JavaScript | function priviledgeCheckboxValidation() {
var checkboxes=document.getElementsByName('chkbx_priviledge');
var atLeastOneChecked=false;
for(var i=0,l=checkboxes.length;i<l;i++)
{
if(checkboxes[i].checked)
{
atLeastOneChecked=true;
break;
}
}
return atLeastOneChecked;
} | function priviledgeCheckboxValidation() {
var checkboxes=document.getElementsByName('chkbx_priviledge');
var atLeastOneChecked=false;
for(var i=0,l=checkboxes.length;i<l;i++)
{
if(checkboxes[i].checked)
{
atLeastOneChecked=true;
break;
}
}
return atLeastOneChecked;
} |
JavaScript | function editUserPriviledges(userName, permissionsJson) {
jagg.post("../blocks/resources/database/add/ajax/add.jag", {
action:"editUserPermissions",
applicationKey:applicationKey,
databaseName:dbName,
rssInstanceName:environment,
userName:userName,
permissions:permissionsJson
},function (result) {
usersDatatable.api().ajax.reload();
},function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status != 0){
jagg.message({type:'error',content:'User ' + userName + ' attaching failed for database ' + dbName, id:'attach_user'});
}
});
} | function editUserPriviledges(userName, permissionsJson) {
jagg.post("../blocks/resources/database/add/ajax/add.jag", {
action:"editUserPermissions",
applicationKey:applicationKey,
databaseName:dbName,
rssInstanceName:environment,
userName:userName,
permissions:permissionsJson
},function (result) {
usersDatatable.api().ajax.reload();
},function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status != 0){
jagg.message({type:'error',content:'User ' + userName + ' attaching failed for database ' + dbName, id:'attach_user'});
}
});
} |
JavaScript | function markExistingPriviledges(userName) {
//clear all checked boxes
$('#priviledges_modal input:checkbox').prop('checked', false);
var priviledgesString = $('#priviledges_' + userName).html();
var priviledgeArray = priviledgesString.split(", ");
for(var i in priviledgeArray) {
var privText = priviledgeArray[i];
$('#' + priviledgeEnum[privText]).prop('checked',true);
}
} | function markExistingPriviledges(userName) {
//clear all checked boxes
$('#priviledges_modal input:checkbox').prop('checked', false);
var priviledgesString = $('#priviledges_' + userName).html();
var priviledgeArray = priviledgesString.split(", ");
for(var i in priviledgeArray) {
var privText = priviledgeArray[i];
$('#' + priviledgeEnum[privText]).prop('checked',true);
}
} |
JavaScript | function displayApplicationInactiveMessage() {
jagg.message({
modalStatus: true,
type: 'warning',
timeout: 15000,
content: "<b>This application has been stopped due to inactivity for more than 24 hours</b></br>" +
"This is a limitation of free accounts in App Cloud.</br> To restart, click the <b>Start</b>. button.</br>" +
"Click the Support menu to contact us if you need any help."
});
} | function displayApplicationInactiveMessage() {
jagg.message({
modalStatus: true,
type: 'warning',
timeout: 15000,
content: "<b>This application has been stopped due to inactivity for more than 24 hours</b></br>" +
"This is a limitation of free accounts in App Cloud.</br> To restart, click the <b>Start</b>. button.</br>" +
"Click the Support menu to contact us if you need any help."
});
} |
JavaScript | function validateIconImage(filename, fileSize) {
var ext = getFileExtension(filename);
var extStatus = false;
var fileSizeStatus = true;
switch (ext.toLowerCase()) {
case 'jpg':
case 'jpeg':
case 'gif':
case 'bmp':
case 'png':
extStatus = true;
break;
default:
jagg.message({content: "Invalid image selected for Application Icon - Select a valid image", type: 'error', id:'notification'});
break;
}
if((fileSize/1024) > 51200 && extStatus == true) {
fileSizeStatus = false;
jagg.message({content: "Image file should be less than 5MB", type: 'error', id:'notification'});
}
if(extStatus == true && fileSizeStatus == true) {
return true;
}
return false;
} | function validateIconImage(filename, fileSize) {
var ext = getFileExtension(filename);
var extStatus = false;
var fileSizeStatus = true;
switch (ext.toLowerCase()) {
case 'jpg':
case 'jpeg':
case 'gif':
case 'bmp':
case 'png':
extStatus = true;
break;
default:
jagg.message({content: "Invalid image selected for Application Icon - Select a valid image", type: 'error', id:'notification'});
break;
}
if((fileSize/1024) > 51200 && extStatus == true) {
fileSizeStatus = false;
jagg.message({content: "Image file should be less than 5MB", type: 'error', id:'notification'});
}
if(extStatus == true && fileSizeStatus == true) {
return true;
}
return false;
} |
JavaScript | async function callAll(itemPath, options){
const size = await getFolderSize.strict(itemPath, options)
tap.equal(await getFolderSize.loose(itemPath, options), size, 'loose method should return same size as strict');
tap.strictSame(
await getFolderSize(itemPath, options),
{
errors: null,
size: size,
},
'default method should return no errors and same size as strict',
);
return size;
} | async function callAll(itemPath, options){
const size = await getFolderSize.strict(itemPath, options)
tap.equal(await getFolderSize.loose(itemPath, options), size, 'loose method should return same size as strict');
tap.strictSame(
await getFolderSize(itemPath, options),
{
errors: null,
size: size,
},
'default method should return no errors and same size as strict',
);
return size;
} |
JavaScript | function() {
return () => {
this.func();
};
} | function() {
return () => {
this.func();
};
} |
JavaScript | function outputUpdate(vol)
{
document.querySelector('#volume').value = vol;
activeElement.style.fontSize = vol + "vw"; // Unit vw is used to keep the font-size property "responsive"
} | function outputUpdate(vol)
{
document.querySelector('#volume').value = vol;
activeElement.style.fontSize = vol + "vw"; // Unit vw is used to keep the font-size property "responsive"
} |
JavaScript | function start() {
client.query(`SELECT SUM(quantity) as sum FROM product;`, function (err, result) {
if (err) {
console.error('pg error', err.stack);
return;
}
const row = result.rows[0];
const sum = row.sum || 0;
redisClient.set('sum', sum, function (err) {
if (err) {
console.error('redis error', err.stack);
} else {
console.log('set success', sum);
}
});
});
} | function start() {
client.query(`SELECT SUM(quantity) as sum FROM product;`, function (err, result) {
if (err) {
console.error('pg error', err.stack);
return;
}
const row = result.rows[0];
const sum = row.sum || 0;
redisClient.set('sum', sum, function (err) {
if (err) {
console.error('redis error', err.stack);
} else {
console.log('set success', sum);
}
});
});
} |
JavaScript | function processCSV(input, courseID, pUsers, modalID, callback)
{
//fetch groups in the course
let pGroups = apiGroups.getGroups(courseID); //groups may differ between input onchange events
//prepare to read csv file
let reader = new FileReader();
reader.readAsText(input.files[0]);
reader.onload = function(e) {
groupsUploadUI.loadingMsg(modalID);
Promise.all([
pGroups.catch(function(e) { groupsUploadUI.errorMsg(modalID, e.message);}),
pUsers.catch(function(e) { groupsUploadUI.errorMsg(modalID, e.message);})
]).then(function(values) {
//process csv lines after the groups and users are fetched
let lmsGroups = values[0];
let lmsUsers = values[1];
let lines = csvHandler.read(e.target.result);
if (lines && lines.length > 0) {
//get groups and members IDs
let groups = findGroupMembers(lines, lmsGroups, lmsUsers);
if (groups && groups.members) {
//send requests to add or edit group members
let requests = callback(groups.members);
if (requests.length > 0) {
Promise.all(requests.map((p) => p.catch(e => new Error(e.responseText))))
.then(function(values) {
let errors = values.filter(values => values instanceof Error);
if (errors.length === 0) {
if (groups.error) {
throw new Error(groups.error.message);
} else {
location.reload(); //everything ok, reload the page
}
} else {
throw new Error(getRequestsErrorMessage(errors));
}
}).catch(function(e) {
//there were some errors, but some requests might have been processed
groupsUploadUI.errorMsg(modalID, e.message);
$('#' + modalID + 'CloseCSV').click(function() {
location.reload();
});
});
} else {
throw new Error('None of the groups or of the users in the CSV file could be found in the course');
}
}
}
}).catch(function(e) {
groupsUploadUI.errorMsg(modalID, e.message);
});
};
} | function processCSV(input, courseID, pUsers, modalID, callback)
{
//fetch groups in the course
let pGroups = apiGroups.getGroups(courseID); //groups may differ between input onchange events
//prepare to read csv file
let reader = new FileReader();
reader.readAsText(input.files[0]);
reader.onload = function(e) {
groupsUploadUI.loadingMsg(modalID);
Promise.all([
pGroups.catch(function(e) { groupsUploadUI.errorMsg(modalID, e.message);}),
pUsers.catch(function(e) { groupsUploadUI.errorMsg(modalID, e.message);})
]).then(function(values) {
//process csv lines after the groups and users are fetched
let lmsGroups = values[0];
let lmsUsers = values[1];
let lines = csvHandler.read(e.target.result);
if (lines && lines.length > 0) {
//get groups and members IDs
let groups = findGroupMembers(lines, lmsGroups, lmsUsers);
if (groups && groups.members) {
//send requests to add or edit group members
let requests = callback(groups.members);
if (requests.length > 0) {
Promise.all(requests.map((p) => p.catch(e => new Error(e.responseText))))
.then(function(values) {
let errors = values.filter(values => values instanceof Error);
if (errors.length === 0) {
if (groups.error) {
throw new Error(groups.error.message);
} else {
location.reload(); //everything ok, reload the page
}
} else {
throw new Error(getRequestsErrorMessage(errors));
}
}).catch(function(e) {
//there were some errors, but some requests might have been processed
groupsUploadUI.errorMsg(modalID, e.message);
$('#' + modalID + 'CloseCSV').click(function() {
location.reload();
});
});
} else {
throw new Error('None of the groups or of the users in the CSV file could be found in the course');
}
}
}
}).catch(function(e) {
groupsUploadUI.errorMsg(modalID, e.message);
});
};
} |
JavaScript | function editMembers(members)
{
let requests = [];
for (let [groupID, userIDs] of Object.entries(members)) {
if(groupID > 0 && userIDs.length > 0) {
requests.push(apiGroups.editGroupMembers(groupID, userIDs));
}
}
return requests;
} | function editMembers(members)
{
let requests = [];
for (let [groupID, userIDs] of Object.entries(members)) {
if(groupID > 0 && userIDs.length > 0) {
requests.push(apiGroups.editGroupMembers(groupID, userIDs));
}
}
return requests;
} |
JavaScript | function addMembers(members)
{
let requests = [];
for(let [groupID, userIDs] of Object.entries(members)) {
if(groupID > 0) {
userIDs.forEach(function(userID) {
requests.push(apiGroups.addGroupMember(groupID, userID));
});
}
}
return requests;
} | function addMembers(members)
{
let requests = [];
for(let [groupID, userIDs] of Object.entries(members)) {
if(groupID > 0) {
userIDs.forEach(function(userID) {
requests.push(apiGroups.addGroupMember(groupID, userID));
});
}
}
return requests;
} |
JavaScript | function findGroupMembers(lines, lmsGroups, lmsUsers)
{
let members = {};
let userErrors = [];
let groupErrors = [];
lines.forEach(function(line) {
if (line && line['groep'] != '' && typeof line['groep'] != 'undefined' && line['email'] != '' && typeof line['email'] != 'undefined') {
//find group id
let group = findGroup(line['groep'], lmsGroups);
if (group && group.id) {
if (!members[group.id]) {
members[group.id] = [];
}
//find user id
let user = findUser(line['email'], lmsUsers);
if (user && user.id) {
members[group.id].push(user.id);
} else {
if (userErrors.indexOf(line['email']) === -1) {
userErrors.push(line['email']);
}
}
} else {
if (groupErrors.indexOf(line['groep']) === -1) {
groupErrors.push(line['groep']);
}
}
}
});
//prepare error messages
let error = null;
if (groupErrors.length > 0 || userErrors.length > 0) {
let message = '';
if (groupErrors.length > 0) {
message += 'Groups not found: ' + groupErrors.join(', ') + '\n';
}
if (userErrors.length > 0) {
message += 'Users not found: ' + userErrors.join(', ');
}
error = new Error(message);
}
return { members: members, error: error };
} | function findGroupMembers(lines, lmsGroups, lmsUsers)
{
let members = {};
let userErrors = [];
let groupErrors = [];
lines.forEach(function(line) {
if (line && line['groep'] != '' && typeof line['groep'] != 'undefined' && line['email'] != '' && typeof line['email'] != 'undefined') {
//find group id
let group = findGroup(line['groep'], lmsGroups);
if (group && group.id) {
if (!members[group.id]) {
members[group.id] = [];
}
//find user id
let user = findUser(line['email'], lmsUsers);
if (user && user.id) {
members[group.id].push(user.id);
} else {
if (userErrors.indexOf(line['email']) === -1) {
userErrors.push(line['email']);
}
}
} else {
if (groupErrors.indexOf(line['groep']) === -1) {
groupErrors.push(line['groep']);
}
}
}
});
//prepare error messages
let error = null;
if (groupErrors.length > 0 || userErrors.length > 0) {
let message = '';
if (groupErrors.length > 0) {
message += 'Groups not found: ' + groupErrors.join(', ') + '\n';
}
if (userErrors.length > 0) {
message += 'Users not found: ' + userErrors.join(', ');
}
error = new Error(message);
}
return { members: members, error: error };
} |
JavaScript | function affich_prop (lettre) {
var mot_prop = document.getElementById('propos').value;
var lg = mot_prop.length;
if(lg<longueur) {
document.getElementById('propos').value += lettre;
}
document.getElementById('propos').focus();
} | function affich_prop (lettre) {
var mot_prop = document.getElementById('propos').value;
var lg = mot_prop.length;
if(lg<longueur) {
document.getElementById('propos').value += lettre;
}
document.getElementById('propos').focus();
} |
JavaScript | function Listing (contact, date, desc, loc, money, photo, title, type) {
this.contact = contact;
this.date = date;
this.desc = desc;
this.loc = loc;
this.money = money;
this.photo = photo;
this.title = title;
this.type = type;
} | function Listing (contact, date, desc, loc, money, photo, title, type) {
this.contact = contact;
this.date = date;
this.desc = desc;
this.loc = loc;
this.money = money;
this.photo = photo;
this.title = title;
this.type = type;
} |
JavaScript | function scanmain()
{
// Check if browser has proper support for WebAssembly
if ( !BlinkIDSDK.isBrowserSupported() )
{
initialMessageEl.innerText = "This browser is not supported!";
return;
}
// 1. It's possible to obtain a free trial license key on microblink.com
let licenseKey = "sRwAAAYJbG9jYWxob3N0r/lOPk4/w35CpJlWKzU9YHIiwa8JO/OCocwaxylMkWvKHrWXh18xYPoAweHAy4ThamUzV7aXC4qLPheqIE01+rGUOxh9UMVxnyVJ8VN9QI9MEuhdippTO/vs8kEeAAoqsc3iu4Hb8KNduzp6mdSbaC38eyp1bfl+tVQRXxRD775waHVYLvUEeUolgzrybVOEjgrKA6wtzWlJXwKOUmk4tUZJUwauaAyB9LtgsVW9OD4Q1aPPIjdag1n/a4LBzFq0qo7NaZlcpHMu1vCybBSuSmRBDyruzIOEdaV5BwV1b0FQNXsyE7vgg0K4eyG+Ar+OJLANGG9etiwJnX03ycJMZk28";
if ( window.location.hostname === "blinkid.github.io" )
{
licenseKey = "sRwAAAYRYmxpbmtpZC5naXRodWIuaW+qBF9hPYYlTvZbRmaEOIXm3ZY6JuUWueHrbZMr5CHB/8yqAUMlydNc2fUb3CQKa2SB9kYOZ2CLBHwofUG5I1UN/2vw4tLkKF60VWtmsfUQQbkJ6oS6ehDtHFqX8Ba4p4B966tOtu42Bid2OdiqaH+clImmjl5logKfgQd6K2YKWREyYFCrsU5kIUd70Yx6Ou0XSSyudIDugLlDnQ257+Ko2mg7af0215dXpDQYljKd5rLZchG0Y2EuGDhMxvOP8QeboLCq/4cqM5i0Ezm0F39kVl9uI7LMOzuoP1LmfLOhgc3W38ixUCOt3NSqDbZKooU7fgRZ3JfW8/C65eOHCOhqpSo=";
}
// 2. Create instance of SDK load settings with your license key
const loadSettings = new BlinkIDSDK.WasmSDKLoadSettings( licenseKey );
/* [TEMPORARY FIX]
* Use basic WebAssembly builds since most performant option requires server setup and unpkg.com, which is used
* for examples, doesn't support COOP and COEP headers.
*
* For more information see "Integration" section in the official documentation.
*/
loadSettings.wasmType = "BASIC";
// [OPTIONAL] Change default settings
// Show or hide hello message in browser console when WASM is successfully loaded
loadSettings.allowHelloMessage = true;
// In order to provide better UX, display progress bar while loading the SDK
loadSettings.loadProgressCallback = ( progress ) => ( progressEl.value = progress );
// Set absolute location of the engine, i.e. WASM and support JS files
loadSettings.engineLocation = "https://unpkg.com/@microblink/[email protected]/resources/";
// 3. Load SDK
BlinkIDSDK.loadWasmModule( loadSettings ).then
(
( sdk ) =>
{
document.getElementById( "screen-initial" )?.classList.add( "hidden" );
document.getElementById( "wizard-card" )?.classList.remove( "hidden" );
document.getElementById( "btn-cin" )?.addEventListener( "click", ( ev ) =>
{
ev.preventDefault();
startScan( sdk );
});
},
( error ) =>
{
initialMessageEl.innerText = "Failed to load SDK!";
console.error( "Failed to load SDK!", error );
}
);
} | function scanmain()
{
// Check if browser has proper support for WebAssembly
if ( !BlinkIDSDK.isBrowserSupported() )
{
initialMessageEl.innerText = "This browser is not supported!";
return;
}
// 1. It's possible to obtain a free trial license key on microblink.com
let licenseKey = "sRwAAAYJbG9jYWxob3N0r/lOPk4/w35CpJlWKzU9YHIiwa8JO/OCocwaxylMkWvKHrWXh18xYPoAweHAy4ThamUzV7aXC4qLPheqIE01+rGUOxh9UMVxnyVJ8VN9QI9MEuhdippTO/vs8kEeAAoqsc3iu4Hb8KNduzp6mdSbaC38eyp1bfl+tVQRXxRD775waHVYLvUEeUolgzrybVOEjgrKA6wtzWlJXwKOUmk4tUZJUwauaAyB9LtgsVW9OD4Q1aPPIjdag1n/a4LBzFq0qo7NaZlcpHMu1vCybBSuSmRBDyruzIOEdaV5BwV1b0FQNXsyE7vgg0K4eyG+Ar+OJLANGG9etiwJnX03ycJMZk28";
if ( window.location.hostname === "blinkid.github.io" )
{
licenseKey = "sRwAAAYRYmxpbmtpZC5naXRodWIuaW+qBF9hPYYlTvZbRmaEOIXm3ZY6JuUWueHrbZMr5CHB/8yqAUMlydNc2fUb3CQKa2SB9kYOZ2CLBHwofUG5I1UN/2vw4tLkKF60VWtmsfUQQbkJ6oS6ehDtHFqX8Ba4p4B966tOtu42Bid2OdiqaH+clImmjl5logKfgQd6K2YKWREyYFCrsU5kIUd70Yx6Ou0XSSyudIDugLlDnQ257+Ko2mg7af0215dXpDQYljKd5rLZchG0Y2EuGDhMxvOP8QeboLCq/4cqM5i0Ezm0F39kVl9uI7LMOzuoP1LmfLOhgc3W38ixUCOt3NSqDbZKooU7fgRZ3JfW8/C65eOHCOhqpSo=";
}
// 2. Create instance of SDK load settings with your license key
const loadSettings = new BlinkIDSDK.WasmSDKLoadSettings( licenseKey );
/* [TEMPORARY FIX]
* Use basic WebAssembly builds since most performant option requires server setup and unpkg.com, which is used
* for examples, doesn't support COOP and COEP headers.
*
* For more information see "Integration" section in the official documentation.
*/
loadSettings.wasmType = "BASIC";
// [OPTIONAL] Change default settings
// Show or hide hello message in browser console when WASM is successfully loaded
loadSettings.allowHelloMessage = true;
// In order to provide better UX, display progress bar while loading the SDK
loadSettings.loadProgressCallback = ( progress ) => ( progressEl.value = progress );
// Set absolute location of the engine, i.e. WASM and support JS files
loadSettings.engineLocation = "https://unpkg.com/@microblink/[email protected]/resources/";
// 3. Load SDK
BlinkIDSDK.loadWasmModule( loadSettings ).then
(
( sdk ) =>
{
document.getElementById( "screen-initial" )?.classList.add( "hidden" );
document.getElementById( "wizard-card" )?.classList.remove( "hidden" );
document.getElementById( "btn-cin" )?.addEventListener( "click", ( ev ) =>
{
ev.preventDefault();
startScan( sdk );
});
},
( error ) =>
{
initialMessageEl.innerText = "Failed to load SDK!";
console.error( "Failed to load SDK!", error );
}
);
} |
JavaScript | async function startScan( sdk )
{
$('#form').addClass('d-none');
$('#screen-scanning').removeClass('d-none');
// 1. Create a recognizer objects which will be used to recognize single image or stream of images.
//
// Generic ID Recognizer - scan various ID documents
// ID Barcode Recognizer - scan barcodes from various ID documents
const genericIDRecognizer = await BlinkIDSDK.createBlinkIdRecognizer( sdk );
const idBarcodeRecognizer = await BlinkIDSDK.createIdBarcodeRecognizer( sdk );
// [OPTIONAL] Create a callbacks object that will receive recognition events, such as detected object location etc.
const callbacks = {
onQuadDetection: ( quad ) => drawQuad( quad ),
onDetectionFailed: () => updateScanFeedback( "Detection failed", true )
}
// 2. Create a RecognizerRunner object which orchestrates the recognition with one or more
// recognizer objects.
const recognizerRunner = await BlinkIDSDK.createRecognizerRunner
(
// SDK instance to use
sdk,
// List of recognizer objects that will be associated with created RecognizerRunner object
[ genericIDRecognizer, idBarcodeRecognizer ],
// [OPTIONAL] Should recognition pipeline stop as soon as first recognizer in chain finished recognition
false,
// [OPTIONAL] Callbacks object that will receive recognition events
callbacks
);
// 3. Create a VideoRecognizer object and attach it to HTMLVideoElement that will be used for displaying the camera feed
const videoRecognizer = await BlinkIDSDK.VideoRecognizer.createVideoRecognizerFromCameraStream
(
cameraFeed,
recognizerRunner
);
// 4. Start the recognition and await for the results
const processResult = await videoRecognizer.recognize();
// 5. If recognition was successful, obtain the result and display it
if ( processResult !== BlinkIDSDK.RecognizerResultState.Empty )
{
const genericIDResults = await genericIDRecognizer.getResult();
if ( genericIDResults.state !== BlinkIDSDK.RecognizerResultState.Empty )
{
console.log( "BlinkIDGeneric results", genericIDResults );
const firstName = genericIDResults.firstName || genericIDResults.mrz.secondaryID;
const lastName = genericIDResults.lastName || genericIDResults.mrz.primaryID;
const cin = genericIDResults.documentNumber ;
const sex = genericIDResults.sex ;
const dateOfBirth = {
year: genericIDResults.dateOfBirth.year || genericIDResults.mrz.dateOfBirth.year,
month: genericIDResults.dateOfBirth.month || genericIDResults.mrz.dateOfBirth.month,
day: genericIDResults.dateOfBirth.day || genericIDResults.mrz.dateOfBirth.day
}
// alert( );
firstname_ = ` ${ firstName }` ;
lastname_ = `${ lastName }` ;
cin_ = `${ cin }` ;
dateOfBirth_ =` ${ dateOfBirth.year }/${ dateOfBirth.month }/${ dateOfBirth.day } ` ;
// dateOfBirth_ =` ${ dateOfBirth.day }/${ dateOfBirth.month }/${ dateOfBirth.year } ` ;
dateOfBirth_ = new Date( dateOfBirth_);
}
}
else
{
alert( "Could not extract information!" );
}
// 7. Release all resources allocated on the WebAssembly heap and associated with camera stream
// Release browser resources associated with the camera stream
videoRecognizer?.releaseVideoFeed();
// Release memory on WebAssembly heap used by the RecognizerRunner
recognizerRunner?.delete();
// Release memory on WebAssembly heap used by the recognizer
genericIDRecognizer?.delete();
idBarcodeRecognizer?.delete();
// Clear any leftovers drawn to canvas
clearDrawCanvas();
// Hide scanning screen and show scan button again
$('#screen-scanning').addClass('d-none');
$('#form').removeClass('d-none');
$('#cin').val( cin_ ).removeAttr('disabled' );
$('#nom').val( firstname_ ).removeAttr('disabled' );
$('#prenom').val( lastname_ ).removeAttr('disabled' );
$('#dateN').val( dateOfBirth_ ).removeAttr('disabled' );
$('#sexe').val( sex_ ) ;
console.log( firstname_ +" " + lastname_ + ' '+ dateOfBirth_ + ' '+ cin_+ ' '+ sex_);
} | async function startScan( sdk )
{
$('#form').addClass('d-none');
$('#screen-scanning').removeClass('d-none');
// 1. Create a recognizer objects which will be used to recognize single image or stream of images.
//
// Generic ID Recognizer - scan various ID documents
// ID Barcode Recognizer - scan barcodes from various ID documents
const genericIDRecognizer = await BlinkIDSDK.createBlinkIdRecognizer( sdk );
const idBarcodeRecognizer = await BlinkIDSDK.createIdBarcodeRecognizer( sdk );
// [OPTIONAL] Create a callbacks object that will receive recognition events, such as detected object location etc.
const callbacks = {
onQuadDetection: ( quad ) => drawQuad( quad ),
onDetectionFailed: () => updateScanFeedback( "Detection failed", true )
}
// 2. Create a RecognizerRunner object which orchestrates the recognition with one or more
// recognizer objects.
const recognizerRunner = await BlinkIDSDK.createRecognizerRunner
(
// SDK instance to use
sdk,
// List of recognizer objects that will be associated with created RecognizerRunner object
[ genericIDRecognizer, idBarcodeRecognizer ],
// [OPTIONAL] Should recognition pipeline stop as soon as first recognizer in chain finished recognition
false,
// [OPTIONAL] Callbacks object that will receive recognition events
callbacks
);
// 3. Create a VideoRecognizer object and attach it to HTMLVideoElement that will be used for displaying the camera feed
const videoRecognizer = await BlinkIDSDK.VideoRecognizer.createVideoRecognizerFromCameraStream
(
cameraFeed,
recognizerRunner
);
// 4. Start the recognition and await for the results
const processResult = await videoRecognizer.recognize();
// 5. If recognition was successful, obtain the result and display it
if ( processResult !== BlinkIDSDK.RecognizerResultState.Empty )
{
const genericIDResults = await genericIDRecognizer.getResult();
if ( genericIDResults.state !== BlinkIDSDK.RecognizerResultState.Empty )
{
console.log( "BlinkIDGeneric results", genericIDResults );
const firstName = genericIDResults.firstName || genericIDResults.mrz.secondaryID;
const lastName = genericIDResults.lastName || genericIDResults.mrz.primaryID;
const cin = genericIDResults.documentNumber ;
const sex = genericIDResults.sex ;
const dateOfBirth = {
year: genericIDResults.dateOfBirth.year || genericIDResults.mrz.dateOfBirth.year,
month: genericIDResults.dateOfBirth.month || genericIDResults.mrz.dateOfBirth.month,
day: genericIDResults.dateOfBirth.day || genericIDResults.mrz.dateOfBirth.day
}
// alert( );
firstname_ = ` ${ firstName }` ;
lastname_ = `${ lastName }` ;
cin_ = `${ cin }` ;
dateOfBirth_ =` ${ dateOfBirth.year }/${ dateOfBirth.month }/${ dateOfBirth.day } ` ;
// dateOfBirth_ =` ${ dateOfBirth.day }/${ dateOfBirth.month }/${ dateOfBirth.year } ` ;
dateOfBirth_ = new Date( dateOfBirth_);
}
}
else
{
alert( "Could not extract information!" );
}
// 7. Release all resources allocated on the WebAssembly heap and associated with camera stream
// Release browser resources associated with the camera stream
videoRecognizer?.releaseVideoFeed();
// Release memory on WebAssembly heap used by the RecognizerRunner
recognizerRunner?.delete();
// Release memory on WebAssembly heap used by the recognizer
genericIDRecognizer?.delete();
idBarcodeRecognizer?.delete();
// Clear any leftovers drawn to canvas
clearDrawCanvas();
// Hide scanning screen and show scan button again
$('#screen-scanning').addClass('d-none');
$('#form').removeClass('d-none');
$('#cin').val( cin_ ).removeAttr('disabled' );
$('#nom').val( firstname_ ).removeAttr('disabled' );
$('#prenom').val( lastname_ ).removeAttr('disabled' );
$('#dateN').val( dateOfBirth_ ).removeAttr('disabled' );
$('#sexe').val( sex_ ) ;
console.log( firstname_ +" " + lastname_ + ' '+ dateOfBirth_ + ' '+ cin_+ ' '+ sex_);
} |
JavaScript | function drawQuad( quad )
{
clearDrawCanvas();
// Based on detection status, show appropriate color and message
setupColor( quad );
setupMessage( quad );
applyTransform( quad.transformMatrix );
drawContext.beginPath();
drawContext.moveTo( quad.topLeft .x, quad.topLeft .y );
drawContext.lineTo( quad.topRight .x, quad.topRight .y );
drawContext.lineTo( quad.bottomRight.x, quad.bottomRight.y );
drawContext.lineTo( quad.bottomLeft .x, quad.bottomLeft .y );
drawContext.closePath();
drawContext.stroke();
} | function drawQuad( quad )
{
clearDrawCanvas();
// Based on detection status, show appropriate color and message
setupColor( quad );
setupMessage( quad );
applyTransform( quad.transformMatrix );
drawContext.beginPath();
drawContext.moveTo( quad.topLeft .x, quad.topLeft .y );
drawContext.lineTo( quad.topRight .x, quad.topRight .y );
drawContext.lineTo( quad.bottomRight.x, quad.bottomRight.y );
drawContext.lineTo( quad.bottomLeft .x, quad.bottomLeft .y );
drawContext.closePath();
drawContext.stroke();
} |
JavaScript | function updateScanFeedback( message, force )
{
if ( scanFeedbackLock && !force )
{
return;
}
scanFeedbackLock = true;
scanFeedback.innerText = message;
window.setTimeout( () => scanFeedbackLock = false, 5000 );
} | function updateScanFeedback( message, force )
{
if ( scanFeedbackLock && !force )
{
return;
}
scanFeedbackLock = true;
scanFeedback.innerText = message;
window.setTimeout( () => scanFeedbackLock = false, 5000 );
} |
JavaScript | initialize() {
// If the client stub promise is already initialized, return immediately.
if (this.documentUnderstandingServiceStub) {
return this.documentUnderstandingServiceStub;
}
// Put together the "service stub" for
// google.cloud.documentai.v1beta2.DocumentUnderstandingService.
this.documentUnderstandingServiceStub = this._gaxGrpc.createStub(this._opts.fallback
? this._protos.lookupService('google.cloud.documentai.v1beta2.DocumentUnderstandingService')
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
this._protos.google.cloud.documentai.v1beta2
.DocumentUnderstandingService, this._opts);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const documentUnderstandingServiceStubMethods = [
'batchProcessDocuments',
'processDocument',
];
for (const methodName of documentUnderstandingServiceStubMethods) {
const callPromise = this.documentUnderstandingServiceStub.then(stub => (...args) => {
if (this._terminated) {
return Promise.reject('The client has already been closed.');
}
const func = stub[methodName];
return func.apply(stub, args);
}, (err) => () => {
throw err;
});
const descriptor = this.descriptors.longrunning[methodName] || undefined;
const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor);
this.innerApiCalls[methodName] = apiCall;
}
return this.documentUnderstandingServiceStub;
} | initialize() {
// If the client stub promise is already initialized, return immediately.
if (this.documentUnderstandingServiceStub) {
return this.documentUnderstandingServiceStub;
}
// Put together the "service stub" for
// google.cloud.documentai.v1beta2.DocumentUnderstandingService.
this.documentUnderstandingServiceStub = this._gaxGrpc.createStub(this._opts.fallback
? this._protos.lookupService('google.cloud.documentai.v1beta2.DocumentUnderstandingService')
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
this._protos.google.cloud.documentai.v1beta2
.DocumentUnderstandingService, this._opts);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const documentUnderstandingServiceStubMethods = [
'batchProcessDocuments',
'processDocument',
];
for (const methodName of documentUnderstandingServiceStubMethods) {
const callPromise = this.documentUnderstandingServiceStub.then(stub => (...args) => {
if (this._terminated) {
return Promise.reject('The client has already been closed.');
}
const func = stub[methodName];
return func.apply(stub, args);
}, (err) => () => {
throw err;
});
const descriptor = this.descriptors.longrunning[methodName] || undefined;
const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor);
this.innerApiCalls[methodName] = apiCall;
}
return this.documentUnderstandingServiceStub;
} |
JavaScript | async checkBatchProcessDocumentsProgress(name) {
const request = new google_gax_1.operationsProtos.google.longrunning.GetOperationRequest({ name });
const [operation] = await this.operationsClient.getOperation(request);
const decodeOperation = new gax.Operation(operation, this.descriptors.longrunning.batchProcessDocuments, gax.createDefaultBackoffSettings());
return decodeOperation;
} | async checkBatchProcessDocumentsProgress(name) {
const request = new google_gax_1.operationsProtos.google.longrunning.GetOperationRequest({ name });
const [operation] = await this.operationsClient.getOperation(request);
const decodeOperation = new gax.Operation(operation, this.descriptors.longrunning.batchProcessDocuments, gax.createDefaultBackoffSettings());
return decodeOperation;
} |
JavaScript | close() {
this.initialize();
if (!this._terminated) {
return this.documentUnderstandingServiceStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
} | close() {
this.initialize();
if (!this._terminated) {
return this.documentUnderstandingServiceStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
} |
JavaScript | initialize() {
// If the client stub promise is already initialized, return immediately.
if (this.documentProcessorServiceStub) {
return this.documentProcessorServiceStub;
}
// Put together the "service stub" for
// google.cloud.documentai.v1.DocumentProcessorService.
this.documentProcessorServiceStub = this._gaxGrpc.createStub(this._opts.fallback
? this._protos.lookupService('google.cloud.documentai.v1.DocumentProcessorService')
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
this._protos.google.cloud.documentai.v1
.DocumentProcessorService, this._opts);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const documentProcessorServiceStubMethods = [
'processDocument',
'batchProcessDocuments',
'reviewDocument',
];
for (const methodName of documentProcessorServiceStubMethods) {
const callPromise = this.documentProcessorServiceStub.then(stub => (...args) => {
if (this._terminated) {
return Promise.reject('The client has already been closed.');
}
const func = stub[methodName];
return func.apply(stub, args);
}, (err) => () => {
throw err;
});
const descriptor = this.descriptors.longrunning[methodName] || undefined;
const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor);
this.innerApiCalls[methodName] = apiCall;
}
return this.documentProcessorServiceStub;
} | initialize() {
// If the client stub promise is already initialized, return immediately.
if (this.documentProcessorServiceStub) {
return this.documentProcessorServiceStub;
}
// Put together the "service stub" for
// google.cloud.documentai.v1.DocumentProcessorService.
this.documentProcessorServiceStub = this._gaxGrpc.createStub(this._opts.fallback
? this._protos.lookupService('google.cloud.documentai.v1.DocumentProcessorService')
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
this._protos.google.cloud.documentai.v1
.DocumentProcessorService, this._opts);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
const documentProcessorServiceStubMethods = [
'processDocument',
'batchProcessDocuments',
'reviewDocument',
];
for (const methodName of documentProcessorServiceStubMethods) {
const callPromise = this.documentProcessorServiceStub.then(stub => (...args) => {
if (this._terminated) {
return Promise.reject('The client has already been closed.');
}
const func = stub[methodName];
return func.apply(stub, args);
}, (err) => () => {
throw err;
});
const descriptor = this.descriptors.longrunning[methodName] || undefined;
const apiCall = this._gaxModule.createApiCall(callPromise, this._defaults[methodName], descriptor);
this.innerApiCalls[methodName] = apiCall;
}
return this.documentProcessorServiceStub;
} |
JavaScript | processDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this.innerApiCalls.processDocument(request, options, callback);
} | processDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this.innerApiCalls.processDocument(request, options, callback);
} |
JavaScript | batchProcessDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this.innerApiCalls.batchProcessDocuments(request, options, callback);
} | batchProcessDocuments(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
name: request.name || '',
});
this.initialize();
return this.innerApiCalls.batchProcessDocuments(request, options, callback);
} |
JavaScript | reviewDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
human_review_config: request.humanReviewConfig || '',
});
this.initialize();
return this.innerApiCalls.reviewDocument(request, options, callback);
} | reviewDocument(request, optionsOrCallback, callback) {
request = request || {};
let options;
if (typeof optionsOrCallback === 'function' && callback === undefined) {
callback = optionsOrCallback;
options = {};
}
else {
options = optionsOrCallback;
}
options = options || {};
options.otherArgs = options.otherArgs || {};
options.otherArgs.headers = options.otherArgs.headers || {};
options.otherArgs.headers['x-goog-request-params'] =
gax.routingHeader.fromParams({
human_review_config: request.humanReviewConfig || '',
});
this.initialize();
return this.innerApiCalls.reviewDocument(request, options, callback);
} |
JavaScript | async checkReviewDocumentProgress(name) {
const request = new google_gax_1.operationsProtos.google.longrunning.GetOperationRequest({ name });
const [operation] = await this.operationsClient.getOperation(request);
const decodeOperation = new gax.Operation(operation, this.descriptors.longrunning.reviewDocument, gax.createDefaultBackoffSettings());
return decodeOperation;
} | async checkReviewDocumentProgress(name) {
const request = new google_gax_1.operationsProtos.google.longrunning.GetOperationRequest({ name });
const [operation] = await this.operationsClient.getOperation(request);
const decodeOperation = new gax.Operation(operation, this.descriptors.longrunning.reviewDocument, gax.createDefaultBackoffSettings());
return decodeOperation;
} |
JavaScript | humanReviewConfigPath(project, location, processor) {
return this.pathTemplates.humanReviewConfigPathTemplate.render({
project: project,
location: location,
processor: processor,
});
} | humanReviewConfigPath(project, location, processor) {
return this.pathTemplates.humanReviewConfigPathTemplate.render({
project: project,
location: location,
processor: processor,
});
} |
JavaScript | processorPath(project, location, processor) {
return this.pathTemplates.processorPathTemplate.render({
project: project,
location: location,
processor: processor,
});
} | processorPath(project, location, processor) {
return this.pathTemplates.processorPathTemplate.render({
project: project,
location: location,
processor: processor,
});
} |
JavaScript | close() {
this.initialize();
if (!this._terminated) {
return this.documentProcessorServiceStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
} | close() {
this.initialize();
if (!this._terminated) {
return this.documentProcessorServiceStub.then(stub => {
this._terminated = true;
stub.close();
});
}
return Promise.resolve();
} |
JavaScript | function filemain()
{
// Check if browser has proper support for WebAssembly
if ( !BlinkIDSDK.isBrowserSupported() )
{
// initialMessageEl.innerText = "This browser is not supported!";
return;
}
// 1. It's possible to obtain a free trial license key on microblink.com
let licenseKey = "sRwAAAYJbG9jYWxob3N0r/lOPk4/w35CpJlWK6UdzadwYSEZlshDSzAKA3GGbItdpzvAeanNv5uBeJuOSOT5YeqqTP+Ejn1DNw1m5u9X69/+7Myj+lu+lw7Hk2t8IU7Qqm6arDYxmLU4CzaFsR886TPcWZBB94J+cTSeWHFUnHYhs51hV6wGv9SMHXJtvJ4V6N2O4sD4OiOGe4hGZpCgQffPa20LBGmgvrvPslgRhy5/S54q7AMnMh7Gc1BmuFqximeVSnUr4fWpr4yF37Zu26zt6cLXNsPOPhVGjhw8LL/ywPO4tGuzfyvndktOKSf9fTM8HzsWi1sN+KPc/lbQBmIUjUtnHcw2RXSrfGb+5DlMFQ==";
if ( window.location.hostname === "blinkid.github.io" )
{
licenseKey = "sRwAAAYRYmxpbmtpZC5naXRodWIuaW+qBF9hPYYlTvZbRmaEqKVLrSgV5IXSbLI6wc/Iop4Gf5BlxzAR09YQNbwIX6IZq/u2e9ZUdxjggYLvLu+Ref0XclHnjIXRpwAzv2hu7nQVwtK7xt0eeGzu1fgZ0Q7JJv6sn+erIXpNWHOplqKF5RLeJ053PkSCpzkRFSM+3Bi0s4zvZVuQdPuFUAuXWdbqBRiKVhf/MWQNskNr4cRUPY3PHCRHcI2Ykmg24uR30HWS/X1bNKw6hKfsqOQ0lYhkE10tYUSbfK364Cn+VdGCbxenna0p7AgVMF+vZOuDSBKCGI4nOo5kh18A293+wXU9CFIP7YQRhrZhDdYpC29ZuOUYbK1R";
}
// 2. Create instance of SDK load settings with your license key
const loadSettings = new BlinkIDSDK.WasmSDKLoadSettings( licenseKey );
// [OPTIONAL] Change default settings
// Show or hide hello message in browser console when WASM is successfully loaded
loadSettings.allowHelloMessage = true;
// In order to provide better UX, display progress bar while loading the SDK
// loadSettings.loadProgressCallback = ( progress ) => ( progressEl.value = progress );
// Set absolute location of the engine, i.e. WASM and support JS files
loadSettings.engineLocation = "https://blinkid.github.io/blinkid-in-browser/resources";
// 3. Load SDK
BlinkIDSDK.loadWasmModule( loadSettings ).then
(
( sdk ) =>
{
document.getElementById( "image-file" )?.addEventListener( "change", ( ev ) =>
{
ev.preventDefault();
if ( inputImageFile.value ) {
startScan( sdk, inputImageFile.files );
}
});
},
( error ) =>
{
// initialMessageEl.innerText = "Failed to load SDK!";
console.log( "Failed to load SDK!", error );
}
);
} | function filemain()
{
// Check if browser has proper support for WebAssembly
if ( !BlinkIDSDK.isBrowserSupported() )
{
// initialMessageEl.innerText = "This browser is not supported!";
return;
}
// 1. It's possible to obtain a free trial license key on microblink.com
let licenseKey = "sRwAAAYJbG9jYWxob3N0r/lOPk4/w35CpJlWK6UdzadwYSEZlshDSzAKA3GGbItdpzvAeanNv5uBeJuOSOT5YeqqTP+Ejn1DNw1m5u9X69/+7Myj+lu+lw7Hk2t8IU7Qqm6arDYxmLU4CzaFsR886TPcWZBB94J+cTSeWHFUnHYhs51hV6wGv9SMHXJtvJ4V6N2O4sD4OiOGe4hGZpCgQffPa20LBGmgvrvPslgRhy5/S54q7AMnMh7Gc1BmuFqximeVSnUr4fWpr4yF37Zu26zt6cLXNsPOPhVGjhw8LL/ywPO4tGuzfyvndktOKSf9fTM8HzsWi1sN+KPc/lbQBmIUjUtnHcw2RXSrfGb+5DlMFQ==";
if ( window.location.hostname === "blinkid.github.io" )
{
licenseKey = "sRwAAAYRYmxpbmtpZC5naXRodWIuaW+qBF9hPYYlTvZbRmaEqKVLrSgV5IXSbLI6wc/Iop4Gf5BlxzAR09YQNbwIX6IZq/u2e9ZUdxjggYLvLu+Ref0XclHnjIXRpwAzv2hu7nQVwtK7xt0eeGzu1fgZ0Q7JJv6sn+erIXpNWHOplqKF5RLeJ053PkSCpzkRFSM+3Bi0s4zvZVuQdPuFUAuXWdbqBRiKVhf/MWQNskNr4cRUPY3PHCRHcI2Ykmg24uR30HWS/X1bNKw6hKfsqOQ0lYhkE10tYUSbfK364Cn+VdGCbxenna0p7AgVMF+vZOuDSBKCGI4nOo5kh18A293+wXU9CFIP7YQRhrZhDdYpC29ZuOUYbK1R";
}
// 2. Create instance of SDK load settings with your license key
const loadSettings = new BlinkIDSDK.WasmSDKLoadSettings( licenseKey );
// [OPTIONAL] Change default settings
// Show or hide hello message in browser console when WASM is successfully loaded
loadSettings.allowHelloMessage = true;
// In order to provide better UX, display progress bar while loading the SDK
// loadSettings.loadProgressCallback = ( progress ) => ( progressEl.value = progress );
// Set absolute location of the engine, i.e. WASM and support JS files
loadSettings.engineLocation = "https://blinkid.github.io/blinkid-in-browser/resources";
// 3. Load SDK
BlinkIDSDK.loadWasmModule( loadSettings ).then
(
( sdk ) =>
{
document.getElementById( "image-file" )?.addEventListener( "change", ( ev ) =>
{
ev.preventDefault();
if ( inputImageFile.value ) {
startScan( sdk, inputImageFile.files );
}
});
},
( error ) =>
{
// initialMessageEl.innerText = "Failed to load SDK!";
console.log( "Failed to load SDK!", error );
}
);
} |
JavaScript | function updateActorAccessUi(containerNode) {
//Update the permissions checkbox & UI
var menuItem = containerNode.data('menu_item');
if (actorSelectorWidget.selectedActor !== null) {
var hasAccess = actorCanAccessMenu(menuItem, actorSelectorWidget.selectedActor);
var hasCustomPermissions = actorHasCustomPermissions(menuItem, actorSelectorWidget.selectedActor);
var isOverrideActive = !hasAccess && getFieldValue(menuItem, 'restrict_access_to_items', false);
//Check if the parent menu has the "hide all submenus if this is hidden" override in effect.
var currentChild = containerNode, parentNode, parentItem;
do {
parentNode = getParentMenuNode(currentChild);
parentItem = parentNode.data('menu_item');
if (
parentItem
&& getFieldValue(parentItem, 'restrict_access_to_items', false)
&& !actorCanAccessMenu(parentItem, actorSelectorWidget.selectedActor)
) {
hasAccess = false;
isOverrideActive = true;
break;
}
currentChild = parentNode;
} while (parentNode.length > 0);
var checkbox = containerNode.find('.ws_actor_access_checkbox');
checkbox.prop('checked', hasAccess);
//Display the checkbox differently if some items of this menu are hidden and some are visible,
//or if their permissions don't match this menu's permissions.
var submenuItems = getSubmenuItemNodes(containerNode);
if ((submenuItems.length === 0) || isOverrideActive) {
//Either this menu doesn't contain any items, or their permissions don't matter because they're overridden.
checkbox.prop('indeterminate', false);
} else {
var differentPermissions = false;
submenuItems.each(function() {
var item = $(this).data('menu_item');
if ( !item ) { //Skip placeholder items created by drag & drop operations.
return true;
}
var hasSubmenuAccess = actorCanAccessMenu(item, actorSelectorWidget.selectedActor);
if (hasSubmenuAccess !== hasAccess) {
differentPermissions = true;
return false;
}
return true;
});
checkbox.prop('indeterminate', differentPermissions);
}
containerNode.toggleClass('ws_is_hidden_for_actor', !hasAccess);
containerNode.toggleClass('ws_has_custom_permissions_for_actor', hasCustomPermissions);
setMenuFlag(containerNode, 'custom_actor_permissions', hasCustomPermissions);
setMenuFlag(containerNode, 'hidden_from_others', false);
} else {
containerNode.removeClass('ws_is_hidden_for_actor ws_has_custom_permissions_for_actor');
setMenuFlag(containerNode, 'custom_actor_permissions', false);
var currentUserActor = 'user:' + wsEditorData.currentUserLogin;
var otherActors = _(wsEditorData.actors).keys().without(currentUserActor, 'special:super_admin').value(),
hiddenFromCurrentUser = ! actorCanAccessMenu(menuItem, currentUserActor),
hiddenFromOthers = ! _.some(otherActors, _.curry(actorCanAccessMenu, 2)(menuItem));
setMenuFlag(
containerNode,
'hidden_from_others',
hiddenFromOthers,
hiddenFromCurrentUser ? 'Hidden from everyone' : 'Hidden from everyone except you'
);
}
//Update the "hidden" flag.
setMenuFlag(containerNode, 'hidden', itemHasHiddenFlag(menuItem, actorSelectorWidget.selectedActor));
} | function updateActorAccessUi(containerNode) {
//Update the permissions checkbox & UI
var menuItem = containerNode.data('menu_item');
if (actorSelectorWidget.selectedActor !== null) {
var hasAccess = actorCanAccessMenu(menuItem, actorSelectorWidget.selectedActor);
var hasCustomPermissions = actorHasCustomPermissions(menuItem, actorSelectorWidget.selectedActor);
var isOverrideActive = !hasAccess && getFieldValue(menuItem, 'restrict_access_to_items', false);
//Check if the parent menu has the "hide all submenus if this is hidden" override in effect.
var currentChild = containerNode, parentNode, parentItem;
do {
parentNode = getParentMenuNode(currentChild);
parentItem = parentNode.data('menu_item');
if (
parentItem
&& getFieldValue(parentItem, 'restrict_access_to_items', false)
&& !actorCanAccessMenu(parentItem, actorSelectorWidget.selectedActor)
) {
hasAccess = false;
isOverrideActive = true;
break;
}
currentChild = parentNode;
} while (parentNode.length > 0);
var checkbox = containerNode.find('.ws_actor_access_checkbox');
checkbox.prop('checked', hasAccess);
//Display the checkbox differently if some items of this menu are hidden and some are visible,
//or if their permissions don't match this menu's permissions.
var submenuItems = getSubmenuItemNodes(containerNode);
if ((submenuItems.length === 0) || isOverrideActive) {
//Either this menu doesn't contain any items, or their permissions don't matter because they're overridden.
checkbox.prop('indeterminate', false);
} else {
var differentPermissions = false;
submenuItems.each(function() {
var item = $(this).data('menu_item');
if ( !item ) { //Skip placeholder items created by drag & drop operations.
return true;
}
var hasSubmenuAccess = actorCanAccessMenu(item, actorSelectorWidget.selectedActor);
if (hasSubmenuAccess !== hasAccess) {
differentPermissions = true;
return false;
}
return true;
});
checkbox.prop('indeterminate', differentPermissions);
}
containerNode.toggleClass('ws_is_hidden_for_actor', !hasAccess);
containerNode.toggleClass('ws_has_custom_permissions_for_actor', hasCustomPermissions);
setMenuFlag(containerNode, 'custom_actor_permissions', hasCustomPermissions);
setMenuFlag(containerNode, 'hidden_from_others', false);
} else {
containerNode.removeClass('ws_is_hidden_for_actor ws_has_custom_permissions_for_actor');
setMenuFlag(containerNode, 'custom_actor_permissions', false);
var currentUserActor = 'user:' + wsEditorData.currentUserLogin;
var otherActors = _(wsEditorData.actors).keys().without(currentUserActor, 'special:super_admin').value(),
hiddenFromCurrentUser = ! actorCanAccessMenu(menuItem, currentUserActor),
hiddenFromOthers = ! _.some(otherActors, _.curry(actorCanAccessMenu, 2)(menuItem));
setMenuFlag(
containerNode,
'hidden_from_others',
hiddenFromOthers,
hiddenFromCurrentUser ? 'Hidden from everyone' : 'Hidden from everyone except you'
);
}
//Update the "hidden" flag.
setMenuFlag(containerNode, 'hidden', itemHasHiddenFlag(menuItem, actorSelectorWidget.selectedActor));
} |
JavaScript | function updateItemEditor(containerNode) {
var menuItem = containerNode.data('menu_item');
//Apply flags based on the item's state.
var flags = ['hidden', 'unused', 'custom'];
for (var i = 0; i < flags.length; i++) {
setMenuFlag(containerNode, flags[i], getFieldValue(menuItem, flags[i], false));
}
//Update the permissions checkbox & other actor-specific UI
updateActorAccessUi(containerNode);
//Update all input fields with the current values.
containerNode.find('.ws_edit_field').each(function(index, field) {
field = $(field);
var fieldName = field.data('field_name');
var input = field.find('.ws_field_value').first();
var hasADefaultValue = itemTemplates.hasDefaultValue(menuItem.template_id, fieldName);
var defaultValue = getDefaultValue(menuItem, fieldName, null, containerNode);
var isDefault = hasADefaultValue && ((typeof menuItem[fieldName] === 'undefined') || (menuItem[fieldName] === null));
if (fieldName === 'access_level') {
isDefault = (getFieldValue(menuItem, 'extra_capability', '') === '')
&& isEmptyObject(menuItem.grant_access)
&& (!getFieldValue(menuItem, 'restrict_access_to_items', false));
} else if (fieldName === 'required_capability_read_only') {
isDefault = true;
hasADefaultValue = true;
}
field.toggleClass('ws_has_no_default', !hasADefaultValue);
field.toggleClass('ws_input_default', isDefault);
var displayValue = isDefault ? defaultValue : menuItem[fieldName];
if (knownMenuFields[fieldName].display !== null) {
displayValue = knownMenuFields[fieldName].display(menuItem, displayValue, input, containerNode);
}
setInputValue(input, displayValue);
if (typeof (knownMenuFields[fieldName].visible) === 'function') {
var isFieldVisible = knownMenuFields[fieldName].visible(menuItem, fieldName);
if (isFieldVisible) {
field.css('display', '');
} else {
field.css('display', 'none');
}
}
});
} | function updateItemEditor(containerNode) {
var menuItem = containerNode.data('menu_item');
//Apply flags based on the item's state.
var flags = ['hidden', 'unused', 'custom'];
for (var i = 0; i < flags.length; i++) {
setMenuFlag(containerNode, flags[i], getFieldValue(menuItem, flags[i], false));
}
//Update the permissions checkbox & other actor-specific UI
updateActorAccessUi(containerNode);
//Update all input fields with the current values.
containerNode.find('.ws_edit_field').each(function(index, field) {
field = $(field);
var fieldName = field.data('field_name');
var input = field.find('.ws_field_value').first();
var hasADefaultValue = itemTemplates.hasDefaultValue(menuItem.template_id, fieldName);
var defaultValue = getDefaultValue(menuItem, fieldName, null, containerNode);
var isDefault = hasADefaultValue && ((typeof menuItem[fieldName] === 'undefined') || (menuItem[fieldName] === null));
if (fieldName === 'access_level') {
isDefault = (getFieldValue(menuItem, 'extra_capability', '') === '')
&& isEmptyObject(menuItem.grant_access)
&& (!getFieldValue(menuItem, 'restrict_access_to_items', false));
} else if (fieldName === 'required_capability_read_only') {
isDefault = true;
hasADefaultValue = true;
}
field.toggleClass('ws_has_no_default', !hasADefaultValue);
field.toggleClass('ws_input_default', isDefault);
var displayValue = isDefault ? defaultValue : menuItem[fieldName];
if (knownMenuFields[fieldName].display !== null) {
displayValue = knownMenuFields[fieldName].display(menuItem, displayValue, input, containerNode);
}
setInputValue(input, displayValue);
if (typeof (knownMenuFields[fieldName].visible) === 'function') {
var isFieldVisible = knownMenuFields[fieldName].visible(menuItem, fieldName);
if (isFieldVisible) {
field.css('display', '');
} else {
field.css('display', 'none');
}
}
});
} |
JavaScript | function encodeMenuAsJSON(tree){
if (typeof tree === 'undefined' || !tree) {
tree = readMenuTreeState();
}
tree.format = {
name: wsEditorData.menuFormatName,
version: wsEditorData.menuFormatVersion
};
//Compress the admin menu.
tree = compressMenu(tree);
return $.toJSON(tree);
} | function encodeMenuAsJSON(tree){
if (typeof tree === 'undefined' || !tree) {
tree = readMenuTreeState();
}
tree.format = {
name: wsEditorData.menuFormatName,
version: wsEditorData.menuFormatVersion
};
//Compress the admin menu.
tree = compressMenu(tree);
return $.toJSON(tree);
} |
JavaScript | function readItemState(itemDiv, position){
position = (typeof position === 'undefined') ? 0 : position;
itemDiv = $(itemDiv);
var item = $.extend(true, {}, wsEditorData.blankMenuItem, itemDiv.data('menu_item'), readAllFields(itemDiv));
item.defaults = itemDiv.data('menu_item').defaults;
//Save the position data
item.position = position;
item.defaults.position = position; //The real default value will later overwrite this
item.separator = itemDiv.hasClass('ws_menu_separator');
item.custom = menuHasFlag(itemDiv, 'custom');
//Gather the menu's sub-items, if any
item.items = [];
var subMenuId = itemDiv.data('submenu_id');
if (subMenuId) {
var itemPosition = 0;
$('#' + subMenuId).find('.ws_item').each(function () {
var sub_item = readItemState(this, itemPosition++);
item.items.push(sub_item);
});
}
return item;
} | function readItemState(itemDiv, position){
position = (typeof position === 'undefined') ? 0 : position;
itemDiv = $(itemDiv);
var item = $.extend(true, {}, wsEditorData.blankMenuItem, itemDiv.data('menu_item'), readAllFields(itemDiv));
item.defaults = itemDiv.data('menu_item').defaults;
//Save the position data
item.position = position;
item.defaults.position = position; //The real default value will later overwrite this
item.separator = itemDiv.hasClass('ws_menu_separator');
item.custom = menuHasFlag(itemDiv, 'custom');
//Gather the menu's sub-items, if any
item.items = [];
var subMenuId = itemDiv.data('submenu_id');
if (subMenuId) {
var itemPosition = 0;
$('#' + subMenuId).find('.ws_item').each(function () {
var sub_item = readItemState(this, itemPosition++);
item.items.push(sub_item);
});
}
return item;
} |
JavaScript | function toggleItemHiddenFlag(selection, isHidden) {
var menuItem = selection.data('menu_item');
//By default, invert the current state.
if (typeof isHidden === 'undefined') {
isHidden = !itemHasHiddenFlag(menuItem, actorSelectorWidget.selectedActor);
}
//Mark the menu as hidden/visible
if (actorSelectorWidget.selectedActor === null) {
//For ALL roles and users.
menuItem.hidden = isHidden;
menuItem.hidden_from_actor = {};
} else {
//Just for the current role.
if (isHidden) {
menuItem.hidden_from_actor[actorSelectorWidget.selectedActor] = true;
} else {
if (actorSelectorWidget.selectedActor.indexOf('user:') === 0) {
//User-specific exception. Lets you can hide a menu from all admins but leave it visible to yourself.
menuItem.hidden_from_actor[actorSelectorWidget.selectedActor] = false;
} else {
delete menuItem.hidden_from_actor[actorSelectorWidget.selectedActor];
}
}
//When the user un-hides a menu that was globally hidden via the "hidden" flag, we must remove
//that flag but also make sure the menu stays hidden from other roles.
if (!isHidden && menuItem.hidden) {
menuItem.hidden = false;
$.each(wsEditorData.actors, function(otherActor) {
if (otherActor !== actorSelectorWidget.selectedActor) {
menuItem.hidden_from_actor[otherActor] = true;
}
});
}
}
setMenuFlag(selection, 'hidden', isHidden);
//Also mark all of it's submenus as hidden/visible
var submenuId = selection.data('submenu_id');
if (submenuId) {
$('#' + submenuId + ' .ws_item').each(function(){
toggleItemHiddenFlag($(this), isHidden);
});
}
} | function toggleItemHiddenFlag(selection, isHidden) {
var menuItem = selection.data('menu_item');
//By default, invert the current state.
if (typeof isHidden === 'undefined') {
isHidden = !itemHasHiddenFlag(menuItem, actorSelectorWidget.selectedActor);
}
//Mark the menu as hidden/visible
if (actorSelectorWidget.selectedActor === null) {
//For ALL roles and users.
menuItem.hidden = isHidden;
menuItem.hidden_from_actor = {};
} else {
//Just for the current role.
if (isHidden) {
menuItem.hidden_from_actor[actorSelectorWidget.selectedActor] = true;
} else {
if (actorSelectorWidget.selectedActor.indexOf('user:') === 0) {
//User-specific exception. Lets you can hide a menu from all admins but leave it visible to yourself.
menuItem.hidden_from_actor[actorSelectorWidget.selectedActor] = false;
} else {
delete menuItem.hidden_from_actor[actorSelectorWidget.selectedActor];
}
}
//When the user un-hides a menu that was globally hidden via the "hidden" flag, we must remove
//that flag but also make sure the menu stays hidden from other roles.
if (!isHidden && menuItem.hidden) {
menuItem.hidden = false;
$.each(wsEditorData.actors, function(otherActor) {
if (otherActor !== actorSelectorWidget.selectedActor) {
menuItem.hidden_from_actor[otherActor] = true;
}
});
}
}
setMenuFlag(selection, 'hidden', isHidden);
//Also mark all of it's submenus as hidden/visible
var submenuId = selection.data('submenu_id');
if (submenuId) {
$('#' + submenuId + ' .ws_item').each(function(){
toggleItemHiddenFlag($(this), isHidden);
});
}
} |
JavaScript | function denyAccessForAllExcept(menuItem, actor) {
//grant_access comes from PHP, which JSON-encodes empty assoc. arrays as arrays.
//However, we want it to be a dictionary.
if (!$.isPlainObject(menuItem.grant_access)) {
menuItem.grant_access = {};
}
$.each(wsEditorData.actors, function(otherActor) {
//If the input actor is more or equally specific...
if ((actor === null) || (AmeActorManager.compareActorSpecificity(actor, otherActor) >= 0)) {
menuItem.grant_access[otherActor] = false;
}
});
if (actor !== null) {
menuItem.grant_access[actor] = true;
}
return menuItem;
} | function denyAccessForAllExcept(menuItem, actor) {
//grant_access comes from PHP, which JSON-encodes empty assoc. arrays as arrays.
//However, we want it to be a dictionary.
if (!$.isPlainObject(menuItem.grant_access)) {
menuItem.grant_access = {};
}
$.each(wsEditorData.actors, function(otherActor) {
//If the input actor is more or equally specific...
if ((actor === null) || (AmeActorManager.compareActorSpecificity(actor, otherActor) >= 0)) {
menuItem.grant_access[otherActor] = false;
}
});
if (actor !== null) {
menuItem.grant_access[actor] = true;
}
return menuItem;
} |
JavaScript | function selectItem(container) {
if (container.hasClass('ws_active')) {
//The menu item is already selected.
return;
}
//Highlight the active item and un-highlight the previous one
container.addClass('ws_active');
container.siblings('.ws_active').removeClass('ws_active');
if (container.hasClass('ws_menu')) {
//Show/hide the appropriate submenu
if ( currentVisibleSubmenu ){
currentVisibleSubmenu.hide();
}
currentVisibleSubmenu = $('#' + container.data('submenu_id')).show();
updateSubmenuBoxHeight(container);
currentVisibleSubmenu.closest('.ws_main_container')
.find('.ws_toolbar .ws_delete_menu_button')
.toggleClass('ws_button_disabled', !canDeleteItem(getSelectedSubmenuItem()));
}
//Make the "delete" button appear disabled if you can't delete this item.
container.closest('.ws_main_container')
.find('.ws_toolbar .ws_delete_menu_button')
.toggleClass('ws_button_disabled', !canDeleteItem(container));
} | function selectItem(container) {
if (container.hasClass('ws_active')) {
//The menu item is already selected.
return;
}
//Highlight the active item and un-highlight the previous one
container.addClass('ws_active');
container.siblings('.ws_active').removeClass('ws_active');
if (container.hasClass('ws_menu')) {
//Show/hide the appropriate submenu
if ( currentVisibleSubmenu ){
currentVisibleSubmenu.hide();
}
currentVisibleSubmenu = $('#' + container.data('submenu_id')).show();
updateSubmenuBoxHeight(container);
currentVisibleSubmenu.closest('.ws_main_container')
.find('.ws_toolbar .ws_delete_menu_button')
.toggleClass('ws_button_disabled', !canDeleteItem(getSelectedSubmenuItem()));
}
//Make the "delete" button appear disabled if you can't delete this item.
container.closest('.ws_main_container')
.find('.ws_toolbar .ws_delete_menu_button')
.toggleClass('ws_button_disabled', !canDeleteItem(container));
} |
JavaScript | function fieldValueChange(){
/* jshint validthis:true */
var input = $(this);
var field = input.parents('.ws_edit_field').first();
var fieldName = field.data('field_name');
if ((fieldName === 'access_level') || (fieldName === 'embedded_page_id')) {
//These fields are read-only and can never be directly edited by the user.
//Ignore spurious change events.
return;
}
var containerNode = field.parents('.ws_container').first();
var menuItem = containerNode.data('menu_item');
var oldValue = menuItem[fieldName];
var value = getInputValue(input);
var defaultValue = getDefaultValue(menuItem, fieldName, null, containerNode);
var hasADefaultValue = (defaultValue !== null);
//Some fields/templates have no default values.
field.toggleClass('ws_has_no_default', !hasADefaultValue);
if (!hasADefaultValue) {
field.removeClass('ws_input_default');
}
if (field.hasClass('ws_input_default') && (value == defaultValue)) {
value = null; //null = use default.
}
//Ignore changes where the new value is the same as the old one.
if (value === oldValue) {
return;
}
//Update the item.
if (knownMenuFields[fieldName].write !== null) {
knownMenuFields[fieldName].write(menuItem, value, input, containerNode);
} else {
menuItem[fieldName] = value;
}
updateItemEditor(containerNode);
updateParentAccessUi(containerNode);
containerNode.trigger('adminMenuEditor:fieldChange', [menuItem, fieldName]);
} | function fieldValueChange(){
/* jshint validthis:true */
var input = $(this);
var field = input.parents('.ws_edit_field').first();
var fieldName = field.data('field_name');
if ((fieldName === 'access_level') || (fieldName === 'embedded_page_id')) {
//These fields are read-only and can never be directly edited by the user.
//Ignore spurious change events.
return;
}
var containerNode = field.parents('.ws_container').first();
var menuItem = containerNode.data('menu_item');
var oldValue = menuItem[fieldName];
var value = getInputValue(input);
var defaultValue = getDefaultValue(menuItem, fieldName, null, containerNode);
var hasADefaultValue = (defaultValue !== null);
//Some fields/templates have no default values.
field.toggleClass('ws_has_no_default', !hasADefaultValue);
if (!hasADefaultValue) {
field.removeClass('ws_input_default');
}
if (field.hasClass('ws_input_default') && (value == defaultValue)) {
value = null; //null = use default.
}
//Ignore changes where the new value is the same as the old one.
if (value === oldValue) {
return;
}
//Update the item.
if (knownMenuFields[fieldName].write !== null) {
knownMenuFields[fieldName].write(menuItem, value, input, containerNode);
} else {
menuItem[fieldName] = value;
}
updateItemEditor(containerNode);
updateParentAccessUi(containerNode);
containerNode.trigger('adminMenuEditor:fieldChange', [menuItem, fieldName]);
} |
JavaScript | function tryDeleteItem(selection) {
var menuItem = selection.data('menu_item');
var shouldDelete = false;
if (canDeleteItem(selection)) {
//Custom and duplicate items can be deleted normally.
shouldDelete = confirm('Delete this menu?');
} else {
//Non-custom items can not be deleted, but they can be hidden. Ask the user if they want to do that.
menuDeletionDialog.find('#ws-ame-menu-type-desc').text(
getDefaultValue(menuItem, 'is_plugin_page') ? 'an item added by another plugin' : 'a built-in menu item'
);
menuDeletionDialog.data('selected_menu', selection);
//Different versions get slightly different options because only the Pro version has
//role-specific permissions.
$('#ws_hide_menu_except_current_user').toggleClass('hidden', !wsEditorData.wsMenuEditorPro);
$('#ws_hide_menu_except_administrator').toggleClass('hidden', wsEditorData.wsMenuEditorPro);
menuDeletionDialog.dialog('open');
//Select "Cancel" as the default button.
menuDeletionDialog.find('#ws_cancel_menu_deletion').focus();
}
if (shouldDelete) {
//Delete this menu's submenu first, if any.
var submenuId = selection.data('submenu_id');
if (submenuId) {
$('#' + submenuId).remove();
}
var parentSubmenu = selection.closest('.ws_submenu');
//Delete the menu.
selection.remove();
if (parentSubmenu) {
//Refresh permissions UI for this menu's parent (if any).
updateParentAccessUi(parentSubmenu);
}
}
} | function tryDeleteItem(selection) {
var menuItem = selection.data('menu_item');
var shouldDelete = false;
if (canDeleteItem(selection)) {
//Custom and duplicate items can be deleted normally.
shouldDelete = confirm('Delete this menu?');
} else {
//Non-custom items can not be deleted, but they can be hidden. Ask the user if they want to do that.
menuDeletionDialog.find('#ws-ame-menu-type-desc').text(
getDefaultValue(menuItem, 'is_plugin_page') ? 'an item added by another plugin' : 'a built-in menu item'
);
menuDeletionDialog.data('selected_menu', selection);
//Different versions get slightly different options because only the Pro version has
//role-specific permissions.
$('#ws_hide_menu_except_current_user').toggleClass('hidden', !wsEditorData.wsMenuEditorPro);
$('#ws_hide_menu_except_administrator').toggleClass('hidden', wsEditorData.wsMenuEditorPro);
menuDeletionDialog.dialog('open');
//Select "Cancel" as the default button.
menuDeletionDialog.find('#ws_cancel_menu_deletion').focus();
}
if (shouldDelete) {
//Delete this menu's submenu first, if any.
var submenuId = selection.data('submenu_id');
if (submenuId) {
$('#' + submenuId).remove();
}
var parentSubmenu = selection.closest('.ws_submenu');
//Delete the menu.
selection.remove();
if (parentSubmenu) {
//Refresh permissions UI for this menu's parent (if any).
updateParentAccessUi(parentSubmenu);
}
}
} |
JavaScript | function main() {
$(".menu").click(function() {
$(this).children(".menu div").toggle();
});
} | function main() {
$(".menu").click(function() {
$(this).children(".menu div").toggle();
});
} |
JavaScript | function selectColor(l) {
let picked_colors = [], remain_colors = colors;
for (let i = 0; i < l; i++) {
let num = Math.floor(Math.random() * remain_colors.length);
let color = remain_colors[num];
picked_colors.push(color);
remain_colors = remain_colors.filter(item => item !== color)
}
return picked_colors
} | function selectColor(l) {
let picked_colors = [], remain_colors = colors;
for (let i = 0; i < l; i++) {
let num = Math.floor(Math.random() * remain_colors.length);
let color = remain_colors[num];
picked_colors.push(color);
remain_colors = remain_colors.filter(item => item !== color)
}
return picked_colors
} |
JavaScript | static fetchRestaurantById(id, callback) {
// fetch all restaurants with proper error handling.
const url = `${DBHelper.DATABASE_URL}/restaurants/${id}`
DBHelper._dbPromise.then(db => {
db.transaction('restaurants')
.objectStore('restaurants')
.get(parseInt(id))
.then(data => {
if (data !== 0)
callback(null, data);
})
.catch(err => {
const error = (`Get from idb failed. Returned status of ${err}`);
callback(error, null);
})
.then(() => {
fetch(url)
.then(response => response.json())
.then(data => {
DBHelper._dbPromise.then(db => {
let tx = db.transaction('restaurants', 'readwrite');
let store = tx.objectStore('restaurants');
store.put(data);
});
})
.catch(err => {
const error = (`Request failed. Returned status of ${err}`);
console.log(error);
})
})
});
} | static fetchRestaurantById(id, callback) {
// fetch all restaurants with proper error handling.
const url = `${DBHelper.DATABASE_URL}/restaurants/${id}`
DBHelper._dbPromise.then(db => {
db.transaction('restaurants')
.objectStore('restaurants')
.get(parseInt(id))
.then(data => {
if (data !== 0)
callback(null, data);
})
.catch(err => {
const error = (`Get from idb failed. Returned status of ${err}`);
callback(error, null);
})
.then(() => {
fetch(url)
.then(response => response.json())
.then(data => {
DBHelper._dbPromise.then(db => {
let tx = db.transaction('restaurants', 'readwrite');
let store = tx.objectStore('restaurants');
store.put(data);
});
})
.catch(err => {
const error = (`Request failed. Returned status of ${err}`);
console.log(error);
})
})
});
} |
JavaScript | static fetchReviewsByRestaurantId(id, callback) {
// fetch all reviews of a restaurant with proper error handling.
const url = `${DBHelper.DATABASE_URL}/reviews?restaurant_id=${id}`
fetch(url)
.then(response => response.json())
.then(data => {
DBHelper._dbPromise.then(db => {
let tx = db.transaction('reviews', 'readwrite');
let store = tx.objectStore('reviews');
data.forEach(review => {
store.put(review);
});
});
})
.catch(err => {
const error = (`Request failed. Returned status of ${err}`)
console.log(error);
})
.then(() => {
DBHelper._dbPromise.then(db => {
db.transaction('reviews')
.objectStore('reviews')
.index('restaurant')
.getAll(parseInt(id))
.then(data => {
// Get reviews from localStorage and add to array data response
const offlineReviews = JSON.parse(localStorage.getItem('reviews'));
if (offlineReviews) {
for (const key in offlineReviews) {
if (offlineReviews.hasOwnProperty(key)) {
data.push(offlineReviews[key]);
}
}
}
callback(null, data);
})
.catch(err => {
const error = (`Get from idb failed. Returned status of ${err}`)
callback(error, null);
});
});
});
} | static fetchReviewsByRestaurantId(id, callback) {
// fetch all reviews of a restaurant with proper error handling.
const url = `${DBHelper.DATABASE_URL}/reviews?restaurant_id=${id}`
fetch(url)
.then(response => response.json())
.then(data => {
DBHelper._dbPromise.then(db => {
let tx = db.transaction('reviews', 'readwrite');
let store = tx.objectStore('reviews');
data.forEach(review => {
store.put(review);
});
});
})
.catch(err => {
const error = (`Request failed. Returned status of ${err}`)
console.log(error);
})
.then(() => {
DBHelper._dbPromise.then(db => {
db.transaction('reviews')
.objectStore('reviews')
.index('restaurant')
.getAll(parseInt(id))
.then(data => {
// Get reviews from localStorage and add to array data response
const offlineReviews = JSON.parse(localStorage.getItem('reviews'));
if (offlineReviews) {
for (const key in offlineReviews) {
if (offlineReviews.hasOwnProperty(key)) {
data.push(offlineReviews[key]);
}
}
}
callback(null, data);
})
.catch(err => {
const error = (`Get from idb failed. Returned status of ${err}`)
callback(error, null);
});
});
});
} |
JavaScript | static saveOfflineDataOnAPI() {
const offlineReviews = JSON.parse(localStorage.getItem('reviews'));
if (offlineReviews) {
for (const key in offlineReviews) {
if (offlineReviews.hasOwnProperty(key)) {
const url = `${DBHelper.DATABASE_URL}/reviews`;
return fetch(url, {
method: 'POST',
body: JSON.stringify(offlineReviews[key]),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
DBHelper._dbPromise.then(db => {
db.transaction('reviews', 'readwrite')
.objectStore('reviews')
.put(data)
});
localStorage.removeItem('reviews');
return true;
})
.catch(err => {
console.log('Can´t save offline data on api.');
return;
});
}
}
}
} | static saveOfflineDataOnAPI() {
const offlineReviews = JSON.parse(localStorage.getItem('reviews'));
if (offlineReviews) {
for (const key in offlineReviews) {
if (offlineReviews.hasOwnProperty(key)) {
const url = `${DBHelper.DATABASE_URL}/reviews`;
return fetch(url, {
method: 'POST',
body: JSON.stringify(offlineReviews[key]),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
DBHelper._dbPromise.then(db => {
db.transaction('reviews', 'readwrite')
.objectStore('reviews')
.put(data)
});
localStorage.removeItem('reviews');
return true;
})
.catch(err => {
console.log('Can´t save offline data on api.');
return;
});
}
}
}
} |
JavaScript | function expectWarning(nameOrMap, expected, code) {
if (typeof nameOrMap === 'string') {
expectWarningByName(nameOrMap, expected, code);
} else {
expectWarningByMap(nameOrMap);
}
} | function expectWarning(nameOrMap, expected, code) {
if (typeof nameOrMap === 'string') {
expectWarningByName(nameOrMap, expected, code);
} else {
expectWarningByMap(nameOrMap);
}
} |
Subsets and Splits