language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
async function calculateTtl (ttl = 0, relative = true) { if (ttl === 0) return 0 if (ttl < 0) throw new Error('ttl must be greater than 0') if (relative) { const { height } = await this.api.getCurrentKeyBlock() return +(height) + ttl } return ttl }
async function calculateTtl (ttl = 0, relative = true) { if (ttl === 0) return 0 if (ttl < 0) throw new Error('ttl must be greater than 0') if (relative) { const { height } = await this.api.getCurrentKeyBlock() return +(height) + ttl } return ttl }
JavaScript
async function prepareTxParams (txType, { senderId, nonce: n, ttl: t, fee: f, gas, absoluteTtl }) { const nonce = await this.getAccountNonce(senderId, n) const ttl = await (calculateTtl.bind(this)(t, !absoluteTtl)) const fee = calculateFee(f, txType, { showWarning: this.showWarning, gas, params: R.merge(R.last(arguments), { nonce, ttl }) }) return { fee, ttl, nonce } }
async function prepareTxParams (txType, { senderId, nonce: n, ttl: t, fee: f, gas, absoluteTtl }) { const nonce = await this.getAccountNonce(senderId, n) const ttl = await (calculateTtl.bind(this)(t, !absoluteTtl)) const fee = calculateFee(f, txType, { showWarning: this.showWarning, gas, params: R.merge(R.last(arguments), { nonce, ttl }) }) return { fee, ttl, nonce } }
JavaScript
async function listEvents() { try { const response = await fetch(`/api/location`); return response.json(); } catch (error) { console.log(error); } }
async function listEvents() { try { const response = await fetch(`/api/location`); return response.json(); } catch (error) { console.log(error); } }
JavaScript
function openCatalougeItem(item) { if (parseInt(item.datasetId) !== 0) { router.push('/DetailedDataset/' + item.datasetId).then(() => window.scrollTo(0, 0)); } else if (parseInt(item.coordinationId) !== 0) { router.push('/DetailedCoordination/' + item.coordinationId).then(() => window.scrollTo(0, 0)); } return; }
function openCatalougeItem(item) { if (parseInt(item.datasetId) !== 0) { router.push('/DetailedDataset/' + item.datasetId).then(() => window.scrollTo(0, 0)); } else if (parseInt(item.coordinationId) !== 0) { router.push('/DetailedCoordination/' + item.coordinationId).then(() => window.scrollTo(0, 0)); } return; }
JavaScript
function fixDate(fixingDate) { const dd = fixingDate.getDate() < 10 ? `0${fixingDate.getDate()}` : fixingDate.getDate(); let mm = fixingDate.getMonth() < 10 ? `0${fixingDate.getMonth()}` : fixingDate.getMonth(); // month is from 0-11 in javascript but 1-12 in html mm = parseInt(mm) + 1; const yyyy = fixingDate.getFullYear(); return `${yyyy}-${mm}-${dd}`; }
function fixDate(fixingDate) { const dd = fixingDate.getDate() < 10 ? `0${fixingDate.getDate()}` : fixingDate.getDate(); let mm = fixingDate.getMonth() < 10 ? `0${fixingDate.getMonth()}` : fixingDate.getMonth(); // month is from 0-11 in javascript but 1-12 in html mm = parseInt(mm) + 1; const yyyy = fixingDate.getFullYear(); return `${yyyy}-${mm}-${dd}`; }
JavaScript
function checkRequiredVariables() { if (title !== '' && description !== '' && selectedCategory !== '') { if (wantToRequestCoordination === '2' && selectedCoordination !== '' && joinCoordinationReason !== '') { return true; } if (wantToRequestCoordination !== '2') { return true; } } return false; }
function checkRequiredVariables() { if (title !== '' && description !== '' && selectedCategory !== '') { if (wantToRequestCoordination === '2' && selectedCoordination !== '' && joinCoordinationReason !== '') { return true; } if (wantToRequestCoordination !== '2') { return true; } } return false; }
JavaScript
function submitApplicationToJoinCoordination(id) { const d = { reason: joinCoordinationReason, coordinationId: selectedCoordination, datasetId: id, }; PostApi(`${host}/api/applications`, d, successfullySentApplication); }
function submitApplicationToJoinCoordination(id) { const d = { reason: joinCoordinationReason, coordinationId: selectedCoordination, datasetId: id, }; PostApi(`${host}/api/applications`, d, successfullySentApplication); }
JavaScript
function clearStates() { setTitle(''); setDescription(''); setPublished('1'); setDistTitle(['']); setDistUri(['']); setDistFileFormat([0]); setDistribution(0); setSelectedTags(''); setNewTags([]); setAccessLevel('1'); setSelectedCategory(''); }
function clearStates() { setTitle(''); setDescription(''); setPublished('1'); setDistTitle(['']); setDistUri(['']); setDistFileFormat([0]); setDistribution(0); setSelectedTags(''); setNewTags([]); setAccessLevel('1'); setSelectedCategory(''); }
JavaScript
function fixDate(date) { let notificationDate = new Date(date); let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; let result = notificationDate.toLocaleDateString('no', options); return result.substr(0, 1).toUpperCase() + result.substr(1); }
function fixDate(date) { let notificationDate = new Date(date); let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; let result = notificationDate.toLocaleDateString('no', options); return result.substr(0, 1).toUpperCase() + result.substr(1); }
JavaScript
function importPostReq(id) { if (id == null) { setInvalid(true); } else { setOpen(true); setImportUrl(''); } }
function importPostReq(id) { if (id == null) { setInvalid(true); } else { setOpen(true); setImportUrl(''); } }
JavaScript
function mapResponseToPublishers(res, type) { if (JSON.stringify(res) === '{}') return []; let pubs = res .map((entry) => { let count; switch (type) { case 'datasets': count = entry.datasetsCount; break; case 'coordinations': count = entry.coordinationsCount; break; case 'both': default: count = entry.datasetsCount + entry.coordinationsCount; } return { name: entry.name.split(' ')[0], id: entry.id, count: count, }; }) .filter((entry) => entry.count > 0); return pubs; }
function mapResponseToPublishers(res, type) { if (JSON.stringify(res) === '{}') return []; let pubs = res .map((entry) => { let count; switch (type) { case 'datasets': count = entry.datasetsCount; break; case 'coordinations': count = entry.coordinationsCount; break; case 'both': default: count = entry.datasetsCount + entry.coordinationsCount; } return { name: entry.name.split(' ')[0], id: entry.id, count: count, }; }) .filter((entry) => entry.count > 0); return pubs; }
JavaScript
searchWithXml(xml, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/search?${queryString.stringify({ format })}`, xml, cb, CONTENT_TYPES.xml ); }
searchWithXml(xml, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/search?${queryString.stringify({ format })}`, xml, cb, CONTENT_TYPES.xml ); }
JavaScript
createStoredSearch(xml, cb = undefined) { return this._request( 'PUT', `/data/search/saved/xs${Date.now()}`, xml, cb, CONTENT_TYPES.xml ); }
createStoredSearch(xml, cb = undefined) { return this._request( 'PUT', `/data/search/saved/xs${Date.now()}`, xml, cb, CONTENT_TYPES.xml ); }
JavaScript
updateStoredSearch(id, xml, cb = undefined) { return this._request( 'PUT', `/data/search/saved/${id}`, xml, cb, CONTENT_TYPES.xml ); }
updateStoredSearch(id, xml, cb = undefined) { return this._request( 'PUT', `/data/search/saved/${id}`, xml, cb, CONTENT_TYPES.xml ); }
JavaScript
shareAssessor( originalProjectId, sharedProjectId, subjectIdOrLabel, experimentIdOrLabel, assessorIdOrLabel, newLabel = undefined, primary = false, cb = undefined ) { const options = queryString.stringify({ label: newLabel, primary }); return this._request( 'PUT', `/data/projects/${originalProjectId}/subjects/${subjectIdOrLabel}/experiments/${experimentIdOrLabel}/assessors/${assessorIdOrLabel}/projects/${sharedProjectId}?${options}`, undefined, cb ); }
shareAssessor( originalProjectId, sharedProjectId, subjectIdOrLabel, experimentIdOrLabel, assessorIdOrLabel, newLabel = undefined, primary = false, cb = undefined ) { const options = queryString.stringify({ label: newLabel, primary }); return this._request( 'PUT', `/data/projects/${originalProjectId}/subjects/${subjectIdOrLabel}/experiments/${experimentIdOrLabel}/assessors/${assessorIdOrLabel}/projects/${sharedProjectId}?${options}`, undefined, cb ); }
JavaScript
refreshCatalog(resources, cb = undefined) { if (!resources) { throw new IllegalArgumentsError('resources are required'); } return this._request( 'PUT', '/xapi/archive/catalogs/refresh', Array.isArray(resources) ? resources : [resources], cb ); }
refreshCatalog(resources, cb = undefined) { if (!resources) { throw new IllegalArgumentsError('resources are required'); } return this._request( 'PUT', '/xapi/archive/catalogs/refresh', Array.isArray(resources) ? resources : [resources], cb ); }
JavaScript
refreshCatalogWithSpecificOperation(operations, resources, cb = undefined) { operations = Array.isArray(operations) ? operations : [operations]; if (operations.find((operation) => !Archive.RefreshOperations[operation])) { throw new IllegalArgumentsError( `There is an operation that is not supported in the requested operations: ${operations}` ); } return this._request( 'PUT', `/xapi/archive/catalogs/refresh/${operations.join(',')}`, Array.isArray(resources) ? resources : [resources], cb ); }
refreshCatalogWithSpecificOperation(operations, resources, cb = undefined) { operations = Array.isArray(operations) ? operations : [operations]; if (operations.find((operation) => !Archive.RefreshOperations[operation])) { throw new IllegalArgumentsError( `There is an operation that is not supported in the requested operations: ${operations}` ); } return this._request( 'PUT', `/xapi/archive/catalogs/refresh/${operations.join(',')}`, Array.isArray(resources) ? resources : [resources], cb ); }
JavaScript
download(resources, cb = undefined) { if (!resources) { throw new IllegalArgumentsError('resources are required'); } return this._request('POST', '/xapi/archive/download', resources, cb); }
download(resources, cb = undefined) { if (!resources) { throw new IllegalArgumentsError('resources are required'); } return this._request('POST', '/xapi/archive/download', resources, cb); }
JavaScript
downloadWithSize(resources, cb = undefined) { if (!resources) { throw new IllegalArgumentsError('resources are required'); } return this._request( 'POST', '/xapi/archive/downloadwithsize', resources, cb ); }
downloadWithSize(resources, cb = undefined) { if (!resources) { throw new IllegalArgumentsError('resources are required'); } return this._request( 'POST', '/xapi/archive/downloadwithsize', resources, cb ); }
JavaScript
isScriptEnabled(projectId, cb = undefined) { if (!projectId) { throw new IllegalArgumentsError('project id is required'); } return this._request( 'GET', `/xapi/anonymize/projects/${projectId}/enabled`, undefined, cb ); }
isScriptEnabled(projectId, cb = undefined) { if (!projectId) { throw new IllegalArgumentsError('project id is required'); } return this._request( 'GET', `/xapi/anonymize/projects/${projectId}/enabled`, undefined, cb ); }
JavaScript
createWorkflowWithRawXml(xml, cb = undefined) { return this._request( 'PUT', `/data/workflows?inbody=true`, xml, cb, CONTENT_TYPES.xml ); }
createWorkflowWithRawXml(xml, cb = undefined) { return this._request( 'PUT', `/data/workflows?inbody=true`, xml, cb, CONTENT_TYPES.xml ); }
JavaScript
createWorkflow(json, cb = undefined) { if (typeof json !== 'object') { throw new IllegalArgumentsError(`a map of workflow entry is not valid`); } return this._request( 'PUT', `/data/workflows?${queryString.stringify(json)}`, undefined, cb ); }
createWorkflow(json, cb = undefined) { if (typeof json !== 'object') { throw new IllegalArgumentsError(`a map of workflow entry is not valid`); } return this._request( 'PUT', `/data/workflows?${queryString.stringify(json)}`, undefined, cb ); }
JavaScript
updateWorkflowStatus(workflowId, status, cb = undefined) { return this._request( 'PUT', `/data/workflows/${workflowId}?wrk:workflowData/status=${status}`, undefined, cb ); }
updateWorkflowStatus(workflowId, status, cb = undefined) { return this._request( 'PUT', `/data/workflows/${workflowId}?wrk:workflowData/status=${status}`, undefined, cb ); }
JavaScript
__getURL(path) { let url = path; if (path.indexOf('//') === -1) { url = this.jsXnat.basePath + path; } const newCacheBuster = 'timestamp=' + new Date().getTime(); return url.replace(/(timestamp=\d+)/, newCacheBuster); }
__getURL(path) { let url = path; if (path.indexOf('//') === -1) { url = this.jsXnat.basePath + path; } const newCacheBuster = 'timestamp=' + new Date().getTime(); return url.replace(/(timestamp=\d+)/, newCacheBuster); }
JavaScript
async __getRequestHeaders(requiredAuthMethod) { const headers = {}; headers.Authorization = await this.jsXnat.getAuthorizationHeader( requiredAuthMethod ); return headers; }
async __getRequestHeaders(requiredAuthMethod) { const headers = {}; headers.Authorization = await this.jsXnat.getAuthorizationHeader( requiredAuthMethod ); return headers; }
JavaScript
updateDicomScpReceiverDefinitionWithId( id, dicomScpDefinition, cb = undefined ) { return this._request('PUT', `/xapi/dicomscp/${id}`, dicomScpDefinition, cb); }
updateDicomScpReceiverDefinitionWithId( id, dicomScpDefinition, cb = undefined ) { return this._request('PUT', `/xapi/dicomscp/${id}`, dicomScpDefinition, cb); }
JavaScript
createSimpleProject( id, secondaryId = undefined, name = undefined, cb = undefined ) { return this.createProject( { _attrs: { ID: id, secondary_ID: secondaryId ? secondaryId : id, }, name: name ? name : id, }, cb ); }
createSimpleProject( id, secondaryId = undefined, name = undefined, cb = undefined ) { return this.createProject( { _attrs: { ID: id, secondary_ID: secondaryId ? secondaryId : id, }, name: name ? name : id, }, cb ); }
JavaScript
createProject(json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`project data is required`); } const { _attrs: { ID, secondary_ID }, name, } = json; if (!ID) { throw new IllegalArgumentsError(`ID is required`); } if (!secondary_ID) { throw new IllegalArgumentsError(`secondary_ID is required`); } if (!name) { throw new IllegalArgumentsError(`name is required`); } return this.createProjectWithRawXml( new XmlParser().convertFromJsonToXml('Project', json), cb ); }
createProject(json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`project data is required`); } const { _attrs: { ID, secondary_ID }, name, } = json; if (!ID) { throw new IllegalArgumentsError(`ID is required`); } if (!secondary_ID) { throw new IllegalArgumentsError(`secondary_ID is required`); } if (!name) { throw new IllegalArgumentsError(`name is required`); } return this.createProjectWithRawXml( new XmlParser().convertFromJsonToXml('Project', json), cb ); }
JavaScript
updateProject(id, json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`project data is required`); } return this.updateProjectWithRawXml( id, new XmlParser().convertFromJsonToXml('Project', json), cb ); }
updateProject(id, json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`project data is required`); } return this.updateProjectWithRawXml( id, new XmlParser().convertFromJsonToXml('Project', json), cb ); }
JavaScript
updateProjectWithRawXml(id, xml, cb = undefined) { return this._request( 'PUT', `/data/projects/${id}`, xml, cb, CONTENT_TYPES.xml ); }
updateProjectWithRawXml(id, xml, cb = undefined) { return this._request( 'PUT', `/data/projects/${id}`, xml, cb, CONTENT_TYPES.xml ); }
JavaScript
acceptOrDeclineProjectAccessRequest(id, action, cb = undefined) { if (!ProjectCommon.ProjectAccessRequestActions[action]) { throw new IllegalArgumentsError(`action is invalid: ${action}`); } return this._request( 'PUT', `/data/pars/${id}?${action}=true`, undefined, cb ); }
acceptOrDeclineProjectAccessRequest(id, action, cb = undefined) { if (!ProjectCommon.ProjectAccessRequestActions[action]) { throw new IllegalArgumentsError(`action is invalid: ${action}`); } return this._request( 'PUT', `/data/pars/${id}?${action}=true`, undefined, cb ); }
JavaScript
storeConfigForTool(id, toolId, filePath, contents, cb = undefined) { return this._request( 'PUT', `/data/projects/${id}/config/${toolId}/${filePath}?inbody=true`, contents, cb ); }
storeConfigForTool(id, toolId, filePath, contents, cb = undefined) { return this._request( 'PUT', `/data/projects/${id}/config/${toolId}/${filePath}?inbody=true`, contents, cb ); }
JavaScript
createFolder( projectId, resourceLabel, format = undefined, tags = [], content = undefined, cb = undefined ) { return Resource.createResource(this).createFolder( `/data/projects/${projectId}`, resourceLabel, format, tags, content, cb ); }
createFolder( projectId, resourceLabel, format = undefined, tags = [], content = undefined, cb = undefined ) { return Resource.createResource(this).createFolder( `/data/projects/${projectId}`, resourceLabel, format, tags, content, cb ); }
JavaScript
deleteFolder(projectId, resourceIdOrLabel, safe = false, cb = undefined) { return Resource.createResource(this).deleteFolder( `/data/projects/${projectId}`, resourceIdOrLabel, safe, cb ); }
deleteFolder(projectId, resourceIdOrLabel, safe = false, cb = undefined) { return Resource.createResource(this).deleteFolder( `/data/projects/${projectId}`, resourceIdOrLabel, safe, cb ); }
JavaScript
createSimpleSubject(projectId, subjectLabel, cb = undefined) { if (subjectLabel === undefined) { throw new IllegalArgumentsError(`subject label is required`); } return this.createSubject( projectId, subjectLabel, { _attrs: { project: projectId, label: subjectLabel, }, }, cb ); }
createSimpleSubject(projectId, subjectLabel, cb = undefined) { if (subjectLabel === undefined) { throw new IllegalArgumentsError(`subject label is required`); } return this.createSubject( projectId, subjectLabel, { _attrs: { project: projectId, label: subjectLabel, }, }, cb ); }
JavaScript
createSubject(projectId, subjectLabel, json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`subject data is required`); } if (!json._attrs) { json._attrs = {}; } json._attrs.project = projectId; json._attrs.label = subjectLabel; return this.createSubjectWithRawXml( projectId, subjectLabel, new XmlParser().convertFromJsonToXml('Subject', json), cb ); }
createSubject(projectId, subjectLabel, json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`subject data is required`); } if (!json._attrs) { json._attrs = {}; } json._attrs.project = projectId; json._attrs.label = subjectLabel; return this.createSubjectWithRawXml( projectId, subjectLabel, new XmlParser().convertFromJsonToXml('Subject', json), cb ); }
JavaScript
updateSubjectBySubjectLabel(projectId, subjectLabel, json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`subject data is required`); } return this.updateSubjectWithRawXml( { projectId, subjectLabel }, new XmlParser().convertFromJsonToXml('Project', json), cb ); }
updateSubjectBySubjectLabel(projectId, subjectLabel, json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`subject data is required`); } return this.updateSubjectWithRawXml( { projectId, subjectLabel }, new XmlParser().convertFromJsonToXml('Project', json), cb ); }
JavaScript
updateSubject(subjectId, json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`subject data is required`); } return this.updateSubjectWithRawXml( { subjectId }, new XmlParser().convertFromJsonToXml('Project', json), cb ); }
updateSubject(subjectId, json, cb = undefined) { if (!json) { throw new IllegalArgumentsError(`subject data is required`); } return this.updateSubjectWithRawXml( { subjectId }, new XmlParser().convertFromJsonToXml('Project', json), cb ); }
JavaScript
shareSubject( originalProjectId, sharedProjectId, subjectIdOrLabel, newLabel = undefined, primary = false, format = RESPONSE_FORMAT.json, cb = undefined ) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } const options = queryString.stringify({ label: newLabel, primary, format }); return this._request( 'PUT', `/data/projects/${originalProjectId}/subjects/${subjectIdOrLabel}/projects/${sharedProjectId}?${options}`, undefined, cb ); }
shareSubject( originalProjectId, sharedProjectId, subjectIdOrLabel, newLabel = undefined, primary = false, format = RESPONSE_FORMAT.json, cb = undefined ) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } const options = queryString.stringify({ label: newLabel, primary, format }); return this._request( 'PUT', `/data/projects/${originalProjectId}/subjects/${subjectIdOrLabel}/projects/${sharedProjectId}?${options}`, undefined, cb ); }
JavaScript
createFolder( projectId, subjectIdOrLabel, resourceLabel, format = undefined, tags = [], content = undefined, cb = undefined ) { return Resource.createResource(this).createFolder( `/data/projects/${projectId}/subjects/${subjectIdOrLabel}`, resourceLabel, format, tags, content, cb ); }
createFolder( projectId, subjectIdOrLabel, resourceLabel, format = undefined, tags = [], content = undefined, cb = undefined ) { return Resource.createResource(this).createFolder( `/data/projects/${projectId}/subjects/${subjectIdOrLabel}`, resourceLabel, format, tags, content, cb ); }
JavaScript
deleteFolder( projectId, subjectIdOrLabel, resourceIdOrLabel, safe = false, cb = undefined ) { return Resource.createResource(this).deleteFolder( `/data/projects/${projectId}/subjects/${subjectIdOrLabel}`, resourceIdOrLabel, safe, cb ); }
deleteFolder( projectId, subjectIdOrLabel, resourceIdOrLabel, safe = false, cb = undefined ) { return Resource.createResource(this).deleteFolder( `/data/projects/${projectId}/subjects/${subjectIdOrLabel}`, resourceIdOrLabel, safe, cb ); }
JavaScript
shareExperiment( originalProjectId, sharedProjectId, subjectIdOrLabel, experimentIdOrLabel, newLabel = undefined, primary = false, cb = undefined ) { const options = queryString.stringify({ label: newLabel, primary }); return this._request( 'PUT', `/data/projects/${originalProjectId}/subjects/${subjectIdOrLabel}/experiments/${experimentIdOrLabel}/projects/${sharedProjectId}?${options}`, undefined, cb ); }
shareExperiment( originalProjectId, sharedProjectId, subjectIdOrLabel, experimentIdOrLabel, newLabel = undefined, primary = false, cb = undefined ) { const options = queryString.stringify({ label: newLabel, primary }); return this._request( 'PUT', `/data/projects/${originalProjectId}/subjects/${subjectIdOrLabel}/experiments/${experimentIdOrLabel}/projects/${sharedProjectId}?${options}`, undefined, cb ); }
JavaScript
deleteExperiment( projectId, subjectIdOrLabel, experimentIdOrLabel, removeFiles = false, cb = undefined ) { return this._request( 'DELETE', `/data/projects/${projectId}/subjects/${subjectIdOrLabel}/experiments/${experimentIdOrLabel}`, { removeFiles }, cb ); }
deleteExperiment( projectId, subjectIdOrLabel, experimentIdOrLabel, removeFiles = false, cb = undefined ) { return this._request( 'DELETE', `/data/projects/${projectId}/subjects/${subjectIdOrLabel}/experiments/${experimentIdOrLabel}`, { removeFiles }, cb ); }
JavaScript
unshareExperiment( projectId, subjectIdOrLabel, experimentIdOrLabel, cb = undefined ) { return this.deleteSubject( projectId, subjectIdOrLabel, experimentIdOrLabel, false, cb ); }
unshareExperiment( projectId, subjectIdOrLabel, experimentIdOrLabel, cb = undefined ) { return this.deleteSubject( projectId, subjectIdOrLabel, experimentIdOrLabel, false, cb ); }
JavaScript
async issueToken(cb = undefined) { const res = await this._request( 'GET', `/data/services/tokens/issue`, undefined, cb, CONTENT_TYPES.json, AUTH_METHODS.password ); if (typeof res === 'object') { return res; } else { return JSON.parse(res); } }
async issueToken(cb = undefined) { const res = await this._request( 'GET', `/data/services/tokens/issue`, undefined, cb, CONTENT_TYPES.json, AUTH_METHODS.password ); if (typeof res === 'object') { return res; } else { return JSON.parse(res); } }
JavaScript
issueTokenForUser(username, cb = undefined) { if (!username) { throw new IllegalArgumentsError('username is required'); } return this._request( 'GET', `/data/services/tokens/issue/user/${username}`, undefined, cb ); }
issueTokenForUser(username, cb = undefined) { if (!username) { throw new IllegalArgumentsError('username is required'); } return this._request( 'GET', `/data/services/tokens/issue/user/${username}`, undefined, cb ); }
JavaScript
checkUploadStatus(uploadId, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request('GET', `/data/status/${uploadId}`, undefined, cb); }
checkUploadStatus(uploadId, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request('GET', `/data/status/${uploadId}`, undefined, cb); }
JavaScript
resetUploadStatus(uploadId, cb = undefined) { return this._request( 'GET', `/servlet/AjaxServlet?remote-class=org.nrg.xnat.ajax.UploadProgress&remote-method=start&ID=${uploadId}`, undefined, cb ); }
resetUploadStatus(uploadId, cb = undefined) { return this._request( 'GET', `/servlet/AjaxServlet?remote-class=org.nrg.xnat.ajax.UploadProgress&remote-method=start&ID=${uploadId}`, undefined, cb ); }
JavaScript
createFolder( path, resourceLabel, format = undefined, tags = [], content = undefined, cb = undefined ) { if (!resourceLabel) { throw new IllegalArgumentsError('resource label is required'); } if (tags && !Array.isArray(tags)) { tags = tags.split(','); } const options = queryString.stringify({ format, tags: tags ? tags.join(',') : undefined, content, }); return this._request( 'PUT', `${path}/resources/${resourceLabel}?${options}`, undefined, cb ); }
createFolder( path, resourceLabel, format = undefined, tags = [], content = undefined, cb = undefined ) { if (!resourceLabel) { throw new IllegalArgumentsError('resource label is required'); } if (tags && !Array.isArray(tags)) { tags = tags.split(','); } const options = queryString.stringify({ format, tags: tags ? tags.join(',') : undefined, content, }); return this._request( 'PUT', `${path}/resources/${resourceLabel}?${options}`, undefined, cb ); }
JavaScript
async deleteFolder(path, resourceIdOrLabel, safe = false, cb = undefined) { if (!resourceIdOrLabel) { throw new IllegalArgumentsError('resource id or label is required'); } if (safe) { log('#@$#%3454354325432543253255343'); const { ResultSet: { Result: res }, } = await this.getFolders(path); const found = res.find( (item) => item.label === resourceIdOrLabel || item.xnat_abstractresource_id === resourceIdOrLabel ); if (found && found.file_count > 0) { throw new UnsafeError('the specified folder contains files'); } } return this._request( 'DELETE', `${path}/resources/${resourceIdOrLabel}`, undefined, cb ); }
async deleteFolder(path, resourceIdOrLabel, safe = false, cb = undefined) { if (!resourceIdOrLabel) { throw new IllegalArgumentsError('resource id or label is required'); } if (safe) { log('#@$#%3454354325432543253255343'); const { ResultSet: { Result: res }, } = await this.getFolders(path); const found = res.find( (item) => item.label === resourceIdOrLabel || item.xnat_abstractresource_id === resourceIdOrLabel ); if (found && found.file_count > 0) { throw new UnsafeError('the specified folder contains files'); } } return this._request( 'DELETE', `${path}/resources/${resourceIdOrLabel}`, undefined, cb ); }
JavaScript
__getDump(src, fields = [], format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'GET', `/data/services/dicomdump`, { src, field: fields === undefined || Array.isArray(fields) ? fields : fields.split(','), format, }, cb ); }
__getDump(src, fields = [], format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'GET', `/data/services/dicomdump`, { src, field: fields === undefined || Array.isArray(fields) ? fields : fields.split(','), format, }, cb ); }
JavaScript
moveSessionToProject( src, projectId, async = false, format = RESPONSE_FORMAT.json, cb = undefined ) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/services/prearchive/move?${queryString.stringify({ format, })}`, { src, newProject: projectId, async }, cb, CONTENT_TYPES.form ); }
moveSessionToProject( src, projectId, async = false, format = RESPONSE_FORMAT.json, cb = undefined ) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/services/prearchive/move?${queryString.stringify({ format, })}`, { src, newProject: projectId, async }, cb, CONTENT_TYPES.form ); }
JavaScript
rebuildSession(src, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/services/prearchive/rebuild?${queryString.stringify({ format, })}`, { src }, cb, CONTENT_TYPES.form ); }
rebuildSession(src, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/services/prearchive/rebuild?${queryString.stringify({ format, })}`, { src }, cb, CONTENT_TYPES.form ); }
JavaScript
deleteSession(src, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/services/prearchive/delete`, { src }, cb, CONTENT_TYPES.form ); }
deleteSession(src, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/services/prearchive/delete`, { src }, cb, CONTENT_TYPES.form ); }
JavaScript
archive( src, overwrite = Prearchive.OverwriteOptions.none, quarantine = false, triggerPipelines = true, dest = '', cb = undefined ) { return this._request( 'POST', `/data/services/archive`, { src, overwrite, quarantine, triggerPipelines, dest }, cb, CONTENT_TYPES.form ); }
archive( src, overwrite = Prearchive.OverwriteOptions.none, quarantine = false, triggerPipelines = true, dest = '', cb = undefined ) { return this._request( 'POST', `/data/services/archive`, { src, overwrite, quarantine, triggerPipelines, dest }, cb, CONTENT_TYPES.form ); }
JavaScript
validateArchive(src, format, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/services/validate-archive?${queryString.stringify({ format })}`, { src }, cb, CONTENT_TYPES.form ); }
validateArchive(src, format, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'POST', `/data/services/validate-archive?${queryString.stringify({ format })}`, { src }, cb, CONTENT_TYPES.form ); }
JavaScript
deleteScan(src, scanId, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'DELETE', `/data${src}/scans/${scanId}`, { format }, cb, CONTENT_TYPES.json ); }
deleteScan(src, scanId, format = RESPONSE_FORMAT.json, cb = undefined) { if (!RESPONSE_FORMAT[format]) { format = RESPONSE_FORMAT.json; } return this._request( 'DELETE', `/data${src}/scans/${scanId}`, { format }, cb, CONTENT_TYPES.json ); }
JavaScript
function addToDashboard(set){ api.put("/sets/" + localStorage.getItem("userId") + "/" + set.setId).then(response =>{ console.log("added set " + set.setId + " to users dashboard"); }).catch(e=>{ alert(`Something went wrong while adding set to dashboard: \n${handleError(e)}`); }) }
function addToDashboard(set){ api.put("/sets/" + localStorage.getItem("userId") + "/" + set.setId).then(response =>{ console.log("added set " + set.setId + " to users dashboard"); }).catch(e=>{ alert(`Something went wrong while adding set to dashboard: \n${handleError(e)}`); }) }
JavaScript
function addToDashboard(set) { api .put("/sets/" + localStorage.getItem("userId") + "/" + set.setId) .then((response) => { console.log("added set " + set.setId + " to users dashboard"); }) .catch((e) => { alert( `Something went wrong while adding set to dashboard: \n${handleError( e )}` ); }); }
function addToDashboard(set) { api .put("/sets/" + localStorage.getItem("userId") + "/" + set.setId) .then((response) => { console.log("added set " + set.setId + " to users dashboard"); }) .catch((e) => { alert( `Something went wrong while adding set to dashboard: \n${handleError( e )}` ); }); }
JavaScript
goToDashboard(){ let gameId = this.state.gameId; let userId = 0; if(this.state.timerPlayer){ userId = this.state.players[0].userId; }else{ userId = this.state.players[1].userId; } //clear intervals clearInterval(this.state.timerInterval); clearInterval(this.state.timerUploadInterval); clearInterval(this.state.readyCheck); clearInterval(this.state.statusDownloadInterval); //check if other player left already and behave accordingly api.get("/games/" + gameId).then((response)=>{ if(response.data.players.length < 2){ api.delete(`/games/${gameId}`).then((result)=>{ this.props.history.push("/dashboard"); }).catch((e) => { alert(`Something went wrong while removing game: \n${handleError(e)}`); }); }else{ api.put("/games/" + gameId + "/" + userId + "/remover").then((result)=>{ this.props.history.push("/dashboard"); }).catch(e=>{ alert(`Something went wrong while leaving the game. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); } }).catch((e) => { alert(`Something went wrong while leaving the game. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }
goToDashboard(){ let gameId = this.state.gameId; let userId = 0; if(this.state.timerPlayer){ userId = this.state.players[0].userId; }else{ userId = this.state.players[1].userId; } //clear intervals clearInterval(this.state.timerInterval); clearInterval(this.state.timerUploadInterval); clearInterval(this.state.readyCheck); clearInterval(this.state.statusDownloadInterval); //check if other player left already and behave accordingly api.get("/games/" + gameId).then((response)=>{ if(response.data.players.length < 2){ api.delete(`/games/${gameId}`).then((result)=>{ this.props.history.push("/dashboard"); }).catch((e) => { alert(`Something went wrong while removing game: \n${handleError(e)}`); }); }else{ api.put("/games/" + gameId + "/" + userId + "/remover").then((result)=>{ this.props.history.push("/dashboard"); }).catch(e=>{ alert(`Something went wrong while leaving the game. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); } }).catch((e) => { alert(`Something went wrong while leaving the game. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }
JavaScript
createUploadAndDownloadTimer(){ clearInterval(this.state.statusDownloadInterval); //create timerUpload interval. person with timerUpload, uploads the timer to backend, the download player fetches the timer to sync his timer. if(this.state.timerPlayer){ let uploadInterval = setInterval(() => { //update status in backend let requestBody={gameId:this.state.gameId, status: this.state.currentStatus} api.put('/games', requestBody).then((result) => { }).catch((e) => { alert(`Something went wrong during status upload interval. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }, 1000); //save the interval so it can be cleared later this.setState({timerUploadInterval: uploadInterval});} }
createUploadAndDownloadTimer(){ clearInterval(this.state.statusDownloadInterval); //create timerUpload interval. person with timerUpload, uploads the timer to backend, the download player fetches the timer to sync his timer. if(this.state.timerPlayer){ let uploadInterval = setInterval(() => { //update status in backend let requestBody={gameId:this.state.gameId, status: this.state.currentStatus} api.put('/games', requestBody).then((result) => { }).catch((e) => { alert(`Something went wrong during status upload interval. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }, 1000); //save the interval so it can be cleared later this.setState({timerUploadInterval: uploadInterval});} }
JavaScript
endGame(){ let results = "" let player = 1; if(this.state.timerPlayer){ if(this.state.points2 > this.state.points1){ results = "the game has ended. You lost. You will be redirected to Dashboard now."; }else{ results = "the game has ended. Congratulations! You won. You will be redirected to Dashboard now."; } }else{ player = 2; if(this.state.points2 > this.state.points1){ results = "the game has ended. Congratulations! You won. You will be redirected to Dashboard now."; }else{ results = "the game has ended. You lost. You will be redirected to Dashboard now."; } } //clear intervals clearInterval(this.state.timerInterval); clearInterval(this.state.timerUploadInterval); clearInterval(this.state.readyCheck); clearInterval(this.state.statusDownloadInterval); this.props.history.push("/results/" + this.state.gameId); }
endGame(){ let results = "" let player = 1; if(this.state.timerPlayer){ if(this.state.points2 > this.state.points1){ results = "the game has ended. You lost. You will be redirected to Dashboard now."; }else{ results = "the game has ended. Congratulations! You won. You will be redirected to Dashboard now."; } }else{ player = 2; if(this.state.points2 > this.state.points1){ results = "the game has ended. Congratulations! You won. You will be redirected to Dashboard now."; }else{ results = "the game has ended. You lost. You will be redirected to Dashboard now."; } } //clear intervals clearInterval(this.state.timerInterval); clearInterval(this.state.timerUploadInterval); clearInterval(this.state.readyCheck); clearInterval(this.state.statusDownloadInterval); this.props.history.push("/results/" + this.state.gameId); }
JavaScript
submitReady(ready){ if(ready){ }else{ } let gameId=this.state.gameId; let requestBody = null; //check if player1 or player2. if(this.state.timerPlayer){ requestBody = { "gameId": gameId, "player1Ready": ready, }; }else{ requestBody = { "gameId": gameId, "player2Ready": ready, }; } api.put(`/games`, requestBody).then(result => {} ).catch(e=>{ alert(`Something went wrong while making yourself ready. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }
submitReady(ready){ if(ready){ }else{ } let gameId=this.state.gameId; let requestBody = null; //check if player1 or player2. if(this.state.timerPlayer){ requestBody = { "gameId": gameId, "player1Ready": ready, }; }else{ requestBody = { "gameId": gameId, "player2Ready": ready, }; } api.put(`/games`, requestBody).then(result => {} ).catch(e=>{ alert(`Something went wrong while making yourself ready. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }
JavaScript
checkIfOpponentReady(){ let readyCheck = setInterval(()=>{ api.get(`/games/${this.state.gameId}`).then(result => { let opponentReady = false; if(this.state.timerPlayer){ opponentReady=result.data.player2Ready} else{ opponentReady=result.data.player1Ready } if(opponentReady == true){ clearInterval(this.state.backupTimerInterval); clearInterval(this.state.timerUploadInterval); //unready yourself so that the next check can go through successfully with both players unready, then ready once answered or timer = 0. //setTimeout important for server delay. //if game started if(this.state.gameStarted){ //toggle between showing answer screen & card currently in play if(this.state.showAnswerTransition){ this.setState({showAnswerTransition: false}); //after showing answer and timer went from 5 to 0, next card starts this.nextCard(); }else{ this.setState({showAnswerTransition: true}); //after card was played, show answer screen. this.showAnswer(); } } else{ //or start game if not started yet this.startGame(); this.setState({gameStarted:true}); } //clear the interval so it doesn't check anymore clearInterval(this.state.readyCheck); setTimeout(()=> {this.submitReady(false);}, 1000) ; } } ).catch(e=>{ alert(`Something went wrong while updating the chat. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }, 1000) this.setState({readyCheck:readyCheck}); }
checkIfOpponentReady(){ let readyCheck = setInterval(()=>{ api.get(`/games/${this.state.gameId}`).then(result => { let opponentReady = false; if(this.state.timerPlayer){ opponentReady=result.data.player2Ready} else{ opponentReady=result.data.player1Ready } if(opponentReady == true){ clearInterval(this.state.backupTimerInterval); clearInterval(this.state.timerUploadInterval); //unready yourself so that the next check can go through successfully with both players unready, then ready once answered or timer = 0. //setTimeout important for server delay. //if game started if(this.state.gameStarted){ //toggle between showing answer screen & card currently in play if(this.state.showAnswerTransition){ this.setState({showAnswerTransition: false}); //after showing answer and timer went from 5 to 0, next card starts this.nextCard(); }else{ this.setState({showAnswerTransition: true}); //after card was played, show answer screen. this.showAnswer(); } } else{ //or start game if not started yet this.startGame(); this.setState({gameStarted:true}); } //clear the interval so it doesn't check anymore clearInterval(this.state.readyCheck); setTimeout(()=> {this.submitReady(false);}, 1000) ; } } ).catch(e=>{ alert(`Something went wrong while updating the chat. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }, 1000) this.setState({readyCheck:readyCheck}); }
JavaScript
function CardList({flashcards}) { return ( <div> {flashcards.map(flashcard => { return <Card flashcard = {flashcard} key={flashcard.id} /> })} </div> ) }
function CardList({flashcards}) { return ( <div> {flashcards.map(flashcard => { return <Card flashcard = {flashcard} key={flashcard.id} /> })} </div> ) }
JavaScript
function logout(){ api.put("/users/logout/" + localStorage.getItem("userId")).then(result=>{ //after logout console.log("user "+localStorage.getItem("userId") + " logged out!"); localStorage.clear(); props.history.push("/main"); }).catch(e=>{ alert(`Something went wrong while logging out user: \n${handleError(e)}`); }); }
function logout(){ api.put("/users/logout/" + localStorage.getItem("userId")).then(result=>{ //after logout console.log("user "+localStorage.getItem("userId") + " logged out!"); localStorage.clear(); props.history.push("/main"); }).catch(e=>{ alert(`Something went wrong while logging out user: \n${handleError(e)}`); }); }
JavaScript
goToDashboard(){ let gameId=this.state.gameId; let userId = 0; if(this.state.timerPlayer){ userId = this.state.players[0].userId; }else{ userId = this.state.players[1].userId; } //check if other player left already and behave accordingly api.get("/games/" + gameId).then((response)=>{ if(response.data.players.length < 2){ api.delete(`/games/${gameId}`).then((result)=>{ console.log("closed game"); this.props.history.push("/dashboard"); }).catch((e) => { alert(`Something went wrong while removing game: \n${handleError(e)}`); }); }else{ api.put("/games/" + gameId + "/" + userId + "/remover").then((result)=>{ console.log("removed player from game"); this.props.history.push("/dashboard"); }).catch(e=>{ alert(`Something went wrong while leaving the game. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); } }).catch((e) => { alert(`Something went wrong while leaving the game. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }
goToDashboard(){ let gameId=this.state.gameId; let userId = 0; if(this.state.timerPlayer){ userId = this.state.players[0].userId; }else{ userId = this.state.players[1].userId; } //check if other player left already and behave accordingly api.get("/games/" + gameId).then((response)=>{ if(response.data.players.length < 2){ api.delete(`/games/${gameId}`).then((result)=>{ console.log("closed game"); this.props.history.push("/dashboard"); }).catch((e) => { alert(`Something went wrong while removing game: \n${handleError(e)}`); }); }else{ api.put("/games/" + gameId + "/" + userId + "/remover").then((result)=>{ console.log("removed player from game"); this.props.history.push("/dashboard"); }).catch(e=>{ alert(`Something went wrong while leaving the game. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); } }).catch((e) => { alert(`Something went wrong while leaving the game. Maybe the host left the game?: \n${handleError(e)}`); this.props.history.push("/dashboard"); }); }
JavaScript
deleteSet(index){ if (window.confirm('Are you sure you want to delete this set?')) { // delete it! const updatedList = []; const updatedOwnSetList = []; for(var i = 0; i < this.state.setList.length; i++){ updatedList.push(this.state.setList[i]) if(this.state.ownSetList.includes(this.state.setList[i])){ updatedOwnSetList.push(this.state.setList[i]); } } let set = updatedList[index]; updatedList.splice(index, 1); updatedOwnSetList.splice(this.state.ownSetList.indexOf(this.state.setList[index]),1); this.setState({setList: updatedList, ownSetList: updatedOwnSetList}); api.delete('/sets/' + set.setId).then(result => {console.log("deleted set");} ).catch(e=>{ alert(`Something went wrong while deleting user set: \n${handleError(e)}`); }); } else { // Do nothing! console.log('Set was not removed'); } }
deleteSet(index){ if (window.confirm('Are you sure you want to delete this set?')) { // delete it! const updatedList = []; const updatedOwnSetList = []; for(var i = 0; i < this.state.setList.length; i++){ updatedList.push(this.state.setList[i]) if(this.state.ownSetList.includes(this.state.setList[i])){ updatedOwnSetList.push(this.state.setList[i]); } } let set = updatedList[index]; updatedList.splice(index, 1); updatedOwnSetList.splice(this.state.ownSetList.indexOf(this.state.setList[index]),1); this.setState({setList: updatedList, ownSetList: updatedOwnSetList}); api.delete('/sets/' + set.setId).then(result => {console.log("deleted set");} ).catch(e=>{ alert(`Something went wrong while deleting user set: \n${handleError(e)}`); }); } else { // Do nothing! console.log('Set was not removed'); } }
JavaScript
function addToDashboard(set){ api.put("/sets/" + localStorage.getItem("userId") + "/" + set.setId).then(response =>{ console.log("added set " + set.setId + " to users dashboard"); }).catch(e=>{ alert(`Something went wrong while adding set to dashboard: \n${handleError(e)}`); }) }
function addToDashboard(set){ api.put("/sets/" + localStorage.getItem("userId") + "/" + set.setId).then(response =>{ console.log("added set " + set.setId + " to users dashboard"); }).catch(e=>{ alert(`Something went wrong while adding set to dashboard: \n${handleError(e)}`); }) }
JavaScript
checkStarChange_right() { const flashcards_starred = []; var index = this.state.flashcards_starred.indexOf( this.state.currentFlashcard ); if (this.state.studyStarred) { for (var i = 0; i < this.state.flashcards_starred.length; i++) { if ( this.state.markedCards.includes(this.state.flashcards_starred[i].cardId) ) { flashcards_starred.push(this.state.flashcards_starred[i]); } } if (flashcards_starred.length == this.state.flashcards_starred.length) { index++; } if (flashcards_starred == 1) { this.setState({ rightButtonDisabled: true }); } this.setState({ currentFlashcard: flashcards_starred[index], flashcards_starred: flashcards_starred, }); if (index == 0) { this.setState({ leftButtonDisabled: true }); } } }
checkStarChange_right() { const flashcards_starred = []; var index = this.state.flashcards_starred.indexOf( this.state.currentFlashcard ); if (this.state.studyStarred) { for (var i = 0; i < this.state.flashcards_starred.length; i++) { if ( this.state.markedCards.includes(this.state.flashcards_starred[i].cardId) ) { flashcards_starred.push(this.state.flashcards_starred[i]); } } if (flashcards_starred.length == this.state.flashcards_starred.length) { index++; } if (flashcards_starred == 1) { this.setState({ rightButtonDisabled: true }); } this.setState({ currentFlashcard: flashcards_starred[index], flashcards_starred: flashcards_starred, }); if (index == 0) { this.setState({ leftButtonDisabled: true }); } } }
JavaScript
checkStarChange_left() { const flashcards_starred = []; var index = this.state.flashcards_starred.indexOf( this.state.currentFlashcard ); if (this.state.studyStarred) { for (var i = 0; i < this.state.flashcards_starred.length; i++) { if ( this.state.markedCards.includes(this.state.flashcards_starred[i].cardId) ) { flashcards_starred.push(this.state.flashcards_starred[i]); } } if (flashcards_starred.length == 1) { this.setState({ rightButtonDisabled: true }); } this.setState({ currentFlashcard: flashcards_starred[index - 1], flashcards_starred: flashcards_starred, }); if (index == 0) { this.setState({ leftButtonDisabled: true }); } } }
checkStarChange_left() { const flashcards_starred = []; var index = this.state.flashcards_starred.indexOf( this.state.currentFlashcard ); if (this.state.studyStarred) { for (var i = 0; i < this.state.flashcards_starred.length; i++) { if ( this.state.markedCards.includes(this.state.flashcards_starred[i].cardId) ) { flashcards_starred.push(this.state.flashcards_starred[i]); } } if (flashcards_starred.length == 1) { this.setState({ rightButtonDisabled: true }); } this.setState({ currentFlashcard: flashcards_starred[index - 1], flashcards_starred: flashcards_starred, }); if (index == 0) { this.setState({ leftButtonDisabled: true }); } } }
JavaScript
switchAnswerQuestion() { const len = this.state.all_flashcards.length; const reversed = []; const reversed_starred = []; for (var i = 0; i < len; i++) { var rem = this.state.all_flashcards[i]; var rem_question = rem.question; rem.question = rem.answer; rem.answer = rem_question; reversed.push(rem); if (this.state.markedCards.includes(rem.cardId)) { reversed_starred.push(rem); } } this.setState({ all_flashcards: reversed }); this.setState({ flashcards_starred: reversed_starred }); }
switchAnswerQuestion() { const len = this.state.all_flashcards.length; const reversed = []; const reversed_starred = []; for (var i = 0; i < len; i++) { var rem = this.state.all_flashcards[i]; var rem_question = rem.question; rem.question = rem.answer; rem.answer = rem_question; reversed.push(rem); if (this.state.markedCards.includes(rem.cardId)) { reversed_starred.push(rem); } } this.setState({ all_flashcards: reversed }); this.setState({ flashcards_starred: reversed_starred }); }
JavaScript
shuffleCards() { if (!this.state.cardsShuffled) { this.setState({ flashcards_starred_rem: this.state.flashcards_starred }); this.setState({ all_flashcards_rem: this.state.all_flashcards }); const shuffled = []; const shuffled_starred = []; for (var i = 0; i < this.state.all_flashcards.length; i++) { shuffled.push(this.state.all_flashcards[i]); } for (var i = 0; i < this.state.flashcards_starred.length; i++) { shuffled_starred.push(this.state.flashcards_starred[i]); } for (var i = shuffled.length - 1; i > 0; i--) { const k = Math.floor(Math.random() * shuffled.length); const rem = shuffled[i]; shuffled[i] = shuffled[k]; shuffled[k] = rem; } for (var i = shuffled_starred.length - 1; i > 0; i--) { const k = Math.floor(Math.random() * shuffled_starred.length); const rem = shuffled_starred[i]; shuffled_starred[i] = shuffled_starred[k]; shuffled_starred[k] = rem; } //depending on if only starred are shown or not the shown Flashcard is changed to index 0 of the shuffled sets. if (this.state.studyStarred) { this.setState({ currentFlashcard: shuffled_starred[0] }); } else { this.setState({ currentFlashcard: shuffled[0] }); } this.setState({ all_flashcards: shuffled, flashcards_starred: shuffled_starred, }); this.setState({ rightButtonDisabled: false, leftButtonDisabled: true }); //check if the arrow buttons are disabled or not. Left should always be here, as we start from index 0. if (shuffled_starred.length == 1 && this.state.studyStarred) { this.setState({ rightButtonDisabled: true }); } if (this.state.all_flashcards.length == 1 && !this.state.studyStarred) { this.setState({ rightButtonDisabled: true }); } } else { this.unshuffleCards(); } }
shuffleCards() { if (!this.state.cardsShuffled) { this.setState({ flashcards_starred_rem: this.state.flashcards_starred }); this.setState({ all_flashcards_rem: this.state.all_flashcards }); const shuffled = []; const shuffled_starred = []; for (var i = 0; i < this.state.all_flashcards.length; i++) { shuffled.push(this.state.all_flashcards[i]); } for (var i = 0; i < this.state.flashcards_starred.length; i++) { shuffled_starred.push(this.state.flashcards_starred[i]); } for (var i = shuffled.length - 1; i > 0; i--) { const k = Math.floor(Math.random() * shuffled.length); const rem = shuffled[i]; shuffled[i] = shuffled[k]; shuffled[k] = rem; } for (var i = shuffled_starred.length - 1; i > 0; i--) { const k = Math.floor(Math.random() * shuffled_starred.length); const rem = shuffled_starred[i]; shuffled_starred[i] = shuffled_starred[k]; shuffled_starred[k] = rem; } //depending on if only starred are shown or not the shown Flashcard is changed to index 0 of the shuffled sets. if (this.state.studyStarred) { this.setState({ currentFlashcard: shuffled_starred[0] }); } else { this.setState({ currentFlashcard: shuffled[0] }); } this.setState({ all_flashcards: shuffled, flashcards_starred: shuffled_starred, }); this.setState({ rightButtonDisabled: false, leftButtonDisabled: true }); //check if the arrow buttons are disabled or not. Left should always be here, as we start from index 0. if (shuffled_starred.length == 1 && this.state.studyStarred) { this.setState({ rightButtonDisabled: true }); } if (this.state.all_flashcards.length == 1 && !this.state.studyStarred) { this.setState({ rightButtonDisabled: true }); } } else { this.unshuffleCards(); } }
JavaScript
unshuffleCards() { const flashcards_starred = []; for (var i = 0; i < this.state.flashcards_starred_rem.length; i++) { if ( this.state.markedCards.includes(this.state.flashcards_starred_rem[i].cardId) ) { flashcards_starred.push(this.state.flashcards_starred_rem[i]); } } if (this.state.studyStarred) { this.setState({ currentFlashcard: flashcards_starred[0] }); } else { this.setState({ currentFlashcard: this.state.all_flashcards_rem[0] }); } this.setState({ rightButtonDisabled: false, leftButtonDisabled: true, all_flashcards: this.state.all_flashcards_rem, flashcards_starred: flashcards_starred, }); if (flashcards_starred.length == 1 && this.state.studyStarred) { this.setState({ rightButtonDisabled: true }); } if (this.state.all_flashcards.length == 1 && !this.state.studyStarred) { this.setState({ rightButtonDisabled: true }); } }
unshuffleCards() { const flashcards_starred = []; for (var i = 0; i < this.state.flashcards_starred_rem.length; i++) { if ( this.state.markedCards.includes(this.state.flashcards_starred_rem[i].cardId) ) { flashcards_starred.push(this.state.flashcards_starred_rem[i]); } } if (this.state.studyStarred) { this.setState({ currentFlashcard: flashcards_starred[0] }); } else { this.setState({ currentFlashcard: this.state.all_flashcards_rem[0] }); } this.setState({ rightButtonDisabled: false, leftButtonDisabled: true, all_flashcards: this.state.all_flashcards_rem, flashcards_starred: flashcards_starred, }); if (flashcards_starred.length == 1 && this.state.studyStarred) { this.setState({ rightButtonDisabled: true }); } if (this.state.all_flashcards.length == 1 && !this.state.studyStarred) { this.setState({ rightButtonDisabled: true }); } }
JavaScript
function GameCard({flashcard,submitReadyAndCheckOponent, showAnswerTransition, points, previousAnswer, buttonDisabled}) { var starred = false; const [state, setText] = useState(null); //console.log("TEXT FOR GAME ID", flashcard.cardId); let handleChange=(event)=>{ setText(event.target.value); } if(showAnswerTransition){ return( <div className = "cardGameContainer"> <div className= "answerTransition"> <div className='correctAnswer'> The answer was: "{previousAnswer}" </div> <div className='score'> You got {points} points this round. </div> </div> </div> ); } else{ return( <div className = "cardGameContainer"> <div className= "cardGame"> <div className='front'> {flashcard.question} </div> </div> <textArea className="answerGame" placeholder = "Your answer..." onChange={handleChange}> {state} </textArea> <Button disabled={buttonDisabled} className="submit" onClick={()=>{ setText(""); if(flashcard.answer == state){ submitReadyAndCheckOponent(); }}}>Submit </Button> </div> );} }
function GameCard({flashcard,submitReadyAndCheckOponent, showAnswerTransition, points, previousAnswer, buttonDisabled}) { var starred = false; const [state, setText] = useState(null); //console.log("TEXT FOR GAME ID", flashcard.cardId); let handleChange=(event)=>{ setText(event.target.value); } if(showAnswerTransition){ return( <div className = "cardGameContainer"> <div className= "answerTransition"> <div className='correctAnswer'> The answer was: "{previousAnswer}" </div> <div className='score'> You got {points} points this round. </div> </div> </div> ); } else{ return( <div className = "cardGameContainer"> <div className= "cardGame"> <div className='front'> {flashcard.question} </div> </div> <textArea className="answerGame" placeholder = "Your answer..." onChange={handleChange}> {state} </textArea> <Button disabled={buttonDisabled} className="submit" onClick={()=>{ setText(""); if(flashcard.answer == state){ submitReadyAndCheckOponent(); }}}>Submit </Button> </div> );} }
JavaScript
function CardRender({flashcard, set_length, current_place, markedCards}) { var starred = false; const [flip, setFlip] = useState(false); const [star_active, setStar] = useState(starred); if(markedCards.includes(flashcard.cardId)){ starred = true; console.log(flashcard.cardId); } const starState = starred ? StarActive : Star; //stars the card and pushes its id into the markedCards array. (which is a reference to the state in LearnPage.js) //if it is de-starred, then its id is deleted from the array function pressStar(){ setStar(!star_active); if(!starred){ markedCards.push(flashcard.cardId);} else{ markedCards.splice(markedCards.indexOf(flashcard.cardId),1); } } return( <div className = "cardContainer"> <div className = "cardAdjust"> <div className={`card ${flip ? 'flip' : ''}`} onClick={() => {setFlip(!flip);}} > <div className = "id-front"> {current_place + 1} / {set_length} </div> <div className = "id-back"> {current_place + 1} / {set_length} </div> <div className='front'> {flashcard.question} </div> <div className='back'> {flashcard.answer} </div> </div> <div className={`star-container ${flip ? 'flip-star' : ''}`}> <button class = "star-front" onClick = {() => {pressStar();}} > <img class = "star-front-image" src = {starState} /> </button> <button class = "star-back" onClick = {() => pressStar()} > <img class = "star-back-image" src = {starState} /> </button> </div> </div> </div> ); }
function CardRender({flashcard, set_length, current_place, markedCards}) { var starred = false; const [flip, setFlip] = useState(false); const [star_active, setStar] = useState(starred); if(markedCards.includes(flashcard.cardId)){ starred = true; console.log(flashcard.cardId); } const starState = starred ? StarActive : Star; //stars the card and pushes its id into the markedCards array. (which is a reference to the state in LearnPage.js) //if it is de-starred, then its id is deleted from the array function pressStar(){ setStar(!star_active); if(!starred){ markedCards.push(flashcard.cardId);} else{ markedCards.splice(markedCards.indexOf(flashcard.cardId),1); } } return( <div className = "cardContainer"> <div className = "cardAdjust"> <div className={`card ${flip ? 'flip' : ''}`} onClick={() => {setFlip(!flip);}} > <div className = "id-front"> {current_place + 1} / {set_length} </div> <div className = "id-back"> {current_place + 1} / {set_length} </div> <div className='front'> {flashcard.question} </div> <div className='back'> {flashcard.answer} </div> </div> <div className={`star-container ${flip ? 'flip-star' : ''}`}> <button class = "star-front" onClick = {() => {pressStar();}} > <img class = "star-front-image" src = {starState} /> </button> <button class = "star-back" onClick = {() => pressStar()} > <img class = "star-back-image" src = {starState} /> </button> </div> </div> </div> ); }
JavaScript
function pressStar(){ setStar(!star_active); if(!starred){ markedCards.push(flashcard.cardId);} else{ markedCards.splice(markedCards.indexOf(flashcard.cardId),1); } }
function pressStar(){ setStar(!star_active); if(!starred){ markedCards.push(flashcard.cardId);} else{ markedCards.splice(markedCards.indexOf(flashcard.cardId),1); } }
JavaScript
function updateSet() { const requestBody = JSON.stringify({ title: set.title, setId: set.setId, explain: set.explain, userId: Number(localStorage.getItem("userId")), cards: quizes, photo: set.photo, liked: 0, setStatus: "PUBLIC", setCategory: "ENGLISH", }); api .put("/sets", requestBody) .then((result) => { console.log(result); history.push("/dashboard"); }) .catch((e) => { alert( `Something went wrong while creating user set: \n${handleError(e)}` ); }); }
function updateSet() { const requestBody = JSON.stringify({ title: set.title, setId: set.setId, explain: set.explain, userId: Number(localStorage.getItem("userId")), cards: quizes, photo: set.photo, liked: 0, setStatus: "PUBLIC", setCategory: "ENGLISH", }); api .put("/sets", requestBody) .then((result) => { console.log(result); history.push("/dashboard"); }) .catch((e) => { alert( `Something went wrong while creating user set: \n${handleError(e)}` ); }); }
JavaScript
render() { const container = this._make('div', [this.CSS.baseClass, this.CSS.wrapper]); const title = this._make('div', [this.CSS.input, this.CSS.title], { contentEditable: true, innerHTML: this.data.title }); const message = this._make('div', [this.CSS.input, this.CSS.message], { contentEditable: true, innerHTML: this.data.message }); title.dataset.placeholder = this.titlePlaceholder; message.dataset.placeholder = this.messagePlaceholder; container.appendChild(title); container.appendChild(message); return container; }
render() { const container = this._make('div', [this.CSS.baseClass, this.CSS.wrapper]); const title = this._make('div', [this.CSS.input, this.CSS.title], { contentEditable: true, innerHTML: this.data.title }); const message = this._make('div', [this.CSS.input, this.CSS.message], { contentEditable: true, innerHTML: this.data.message }); title.dataset.placeholder = this.titlePlaceholder; message.dataset.placeholder = this.messagePlaceholder; container.appendChild(title); container.appendChild(message); return container; }
JavaScript
save(successElement) { const title = successElement.querySelector(`.${this.CSS.title}`); const message = successElement.querySelector(`.${this.CSS.message}`); return Object.assign(this.data, { title: title.innerHTML, message: message.innerHTML }); }
save(successElement) { const title = successElement.querySelector(`.${this.CSS.title}`); const message = successElement.querySelector(`.${this.CSS.message}`); return Object.assign(this.data, { title: title.innerHTML, message: message.innerHTML }); }
JavaScript
static get sanitize() { return { title: {}, message: {} }; }
static get sanitize() { return { title: {}, message: {} }; }
JavaScript
function stupidWorkaroundToCreateContextMenu() { var CONTEXT_ID = 'page-settings'; chrome.contextMenus.removeAll(); chrome.contextMenus.create({ id: CONTEXT_ID, title: chrome.i18n.getMessage('context_menu'), contexts: ['page'], targetUrlPatterns: ['*://*/*'] }); }
function stupidWorkaroundToCreateContextMenu() { var CONTEXT_ID = 'page-settings'; chrome.contextMenus.removeAll(); chrome.contextMenus.create({ id: CONTEXT_ID, title: chrome.i18n.getMessage('context_menu'), contexts: ['page'], targetUrlPatterns: ['*://*/*'] }); }
JavaScript
function createTables( mysql_conn ) { //The following variables are SQL statements for creating the tables //for our database. //Project Name is enum //Section name ?? let waypointsTbl = { name: 'Waypoints', query: SQL`CREATE TABLE Waypoints( WaypointID INT NOT NULL AUTO_INCREMENT, Latitude FLOAT, Longitude FLOAT, Northing FLOAT, Easting FLOAT, UTMZone1 INT, UTMZone2 INT, Datum VARCHAR(20), Projection VARCHAR(5), Feildbook VARCHAR(50), FeildbookPage INT, Formation VARCHAR(20), SiteOrLocationName VARCHAR(100), DateCollected DATETIME, Elevation INT, ProjectName VARCHAR(20), Measured BOOLEAN, SectionName VARCHAR(20), Comments TEXT, PRIMARY KEY( WaypointID ) );` } let macrostructuresTbl = { name: 'Macrostructures', query: SQL`CREATE TABLE Macrostructures( MacrostructureID INT NOT NULL AUTO_INCREMENT, MacrostructureType INT, MegastructureType INT, SectionHeight INT, Northing FLOAT, Easting FLOAT, Datum varchar(10), WaypointID INT NOT NULL, Comments TEXT, PRIMARY KEY( MacrostructureID ), FOREIGN KEY( WaypointID ) REFERENCES Waypoints(WaypointID) );` } let mesostructuresTbl = { name: 'Mesostructures', query: SQL`CREATE TABLE Mesostructures( MesostructureID INT NOT NULL AUTO_INCREMENT, SampleID varchar(20), SampleSize varchar(20), FieldDescription varchar(50), RockDescription varchar(2000), MesostructureDesc INT, MacrostructureID INT NOT NULL, LaminaThickness FLOAT, SynopticRelief FLOAT, Wavelength FLOAT, AmplitudeOrHeight INT, MesostructureTexture INT, MesostructureGrains INT, MesostructureTexture2 INT, Analyst INT, LaminaShape INT, LaminaInheritance INT, MesoClotShape INT, MesoClotSize INT, PRIMARY KEY (MesostructureID), FOREIGN KEY (MacrostructureID ) REFERENCES Macrostructures( MacrostructureID ) );` } let thinSectionsTbl = { name: 'ThinSections', query: SQL`CREATE TABLE ThinSections( TSID INT NOT NULL AUTO_INCREMENT, SampleID VARCHAR(20) NOT NULL, Subsample VARCHAR(10), MesostructureID INT NOT NULL, TSDescription TEXT, PrimaryTexture INT, SecondaryTexture INT, Cement1 INT, Porosity1 INT, Cement2 INT, Porosity2 INT, PorosityPercentEst INT, CementFill BOOLEAN, Mineralogy1 INT, Mineralogy2 INT, ClasticGrains1 INT, ClasticGrains2 INT, PRIMARY KEY (TSID), FOREIGN KEY (MesostructureID) REFERENCES Mesostructures(MesostructureID) ); ` } // TODO: Relative file paths. let photoLinksTbl = { name: 'PhotoLinks', query: SQL`CREATE TABLE PhotoLinks( PhotoID INT NOT NULL AUTO_INCREMENT, OutcropPhoto BOOLEAN, Photomicrograph BOOLEAN, CLImage BOOLEAN, OtherImage BOOLEAN, TSOverview BOOLEAN, OtherDocument BOOLEAN, WaypointID INT, MacrostructureID INT, MesostructureID INT, TSID INT, PhotoLinkRelative TEXT, PRIMARY KEY (PhotoID), FOREIGN KEY (MacrostructureID) REFERENCES Macrostructures(MacrostructureID), FOREIGN KEY (MesostructureID) REFERENCES Mesostructures(MesostructureID), FOREIGN KEY (TSDescID) REFERENCES ThinSections(TSDescID), FOREIGN KEY (WaypointID) REFERENCES Waypoints(waypointID) );` } // no relation let microbilitesTbl = { name: 'Microbialites', query: SQL`CREATE TABLE Microbialites( Northing FLOAT, Easting FLOAT, SampleID varchar(20) NOT NULL, MacrostructureType INT, MesostructureDesc INT, LaminaShape INT, LaminaInheritance INT, PRIMARY KEY( SampleID ) );` } // no relation let samplesForARCTbl = { name: 'SamplesForARC', query: SQL`CREATE TABLE SamplesForARC( SampleID VARCHAR(20) NOT NULL, Datum VARCHAR(20), UTMZone1 INT, UTMZone2 CHAR(1), Easting FLOAT, Northing FLOAT, DateCollected DATETIME, MacrostructureType INT, MacrostructureDesc INT, PRIMARY KEY (SampleID) ); ` } // no relation let thrombolitesOnlyTbl = { name: 'ThrombolitesOnly', query: SQL`CREATE TABLE ThrombolitesOnly( Northing FLOAT, Easting FLOAT, SampleID VARCHAR(20), MesostructureDesc INT, PRIMARY KEY (SampleID) ); ` } var tables = [waypointsTbl, macrostructuresTbl, mesostructuresTbl, thinSectionsTbl, photoLinksTbl, microbilitesTbl, samplesForARCTbl, thrombolitesOnlyTbl]; //where the queries are made. for( let table of tables ) { let queryPromise = sendQuery(mysql_conn, table.query.sql ); queryPromise.then( () => { console.log("Added table " + table.name); }, queryPromiseReject ); } }
function createTables( mysql_conn ) { //The following variables are SQL statements for creating the tables //for our database. //Project Name is enum //Section name ?? let waypointsTbl = { name: 'Waypoints', query: SQL`CREATE TABLE Waypoints( WaypointID INT NOT NULL AUTO_INCREMENT, Latitude FLOAT, Longitude FLOAT, Northing FLOAT, Easting FLOAT, UTMZone1 INT, UTMZone2 INT, Datum VARCHAR(20), Projection VARCHAR(5), Feildbook VARCHAR(50), FeildbookPage INT, Formation VARCHAR(20), SiteOrLocationName VARCHAR(100), DateCollected DATETIME, Elevation INT, ProjectName VARCHAR(20), Measured BOOLEAN, SectionName VARCHAR(20), Comments TEXT, PRIMARY KEY( WaypointID ) );` } let macrostructuresTbl = { name: 'Macrostructures', query: SQL`CREATE TABLE Macrostructures( MacrostructureID INT NOT NULL AUTO_INCREMENT, MacrostructureType INT, MegastructureType INT, SectionHeight INT, Northing FLOAT, Easting FLOAT, Datum varchar(10), WaypointID INT NOT NULL, Comments TEXT, PRIMARY KEY( MacrostructureID ), FOREIGN KEY( WaypointID ) REFERENCES Waypoints(WaypointID) );` } let mesostructuresTbl = { name: 'Mesostructures', query: SQL`CREATE TABLE Mesostructures( MesostructureID INT NOT NULL AUTO_INCREMENT, SampleID varchar(20), SampleSize varchar(20), FieldDescription varchar(50), RockDescription varchar(2000), MesostructureDesc INT, MacrostructureID INT NOT NULL, LaminaThickness FLOAT, SynopticRelief FLOAT, Wavelength FLOAT, AmplitudeOrHeight INT, MesostructureTexture INT, MesostructureGrains INT, MesostructureTexture2 INT, Analyst INT, LaminaShape INT, LaminaInheritance INT, MesoClotShape INT, MesoClotSize INT, PRIMARY KEY (MesostructureID), FOREIGN KEY (MacrostructureID ) REFERENCES Macrostructures( MacrostructureID ) );` } let thinSectionsTbl = { name: 'ThinSections', query: SQL`CREATE TABLE ThinSections( TSID INT NOT NULL AUTO_INCREMENT, SampleID VARCHAR(20) NOT NULL, Subsample VARCHAR(10), MesostructureID INT NOT NULL, TSDescription TEXT, PrimaryTexture INT, SecondaryTexture INT, Cement1 INT, Porosity1 INT, Cement2 INT, Porosity2 INT, PorosityPercentEst INT, CementFill BOOLEAN, Mineralogy1 INT, Mineralogy2 INT, ClasticGrains1 INT, ClasticGrains2 INT, PRIMARY KEY (TSID), FOREIGN KEY (MesostructureID) REFERENCES Mesostructures(MesostructureID) ); ` } // TODO: Relative file paths. let photoLinksTbl = { name: 'PhotoLinks', query: SQL`CREATE TABLE PhotoLinks( PhotoID INT NOT NULL AUTO_INCREMENT, OutcropPhoto BOOLEAN, Photomicrograph BOOLEAN, CLImage BOOLEAN, OtherImage BOOLEAN, TSOverview BOOLEAN, OtherDocument BOOLEAN, WaypointID INT, MacrostructureID INT, MesostructureID INT, TSID INT, PhotoLinkRelative TEXT, PRIMARY KEY (PhotoID), FOREIGN KEY (MacrostructureID) REFERENCES Macrostructures(MacrostructureID), FOREIGN KEY (MesostructureID) REFERENCES Mesostructures(MesostructureID), FOREIGN KEY (TSDescID) REFERENCES ThinSections(TSDescID), FOREIGN KEY (WaypointID) REFERENCES Waypoints(waypointID) );` } // no relation let microbilitesTbl = { name: 'Microbialites', query: SQL`CREATE TABLE Microbialites( Northing FLOAT, Easting FLOAT, SampleID varchar(20) NOT NULL, MacrostructureType INT, MesostructureDesc INT, LaminaShape INT, LaminaInheritance INT, PRIMARY KEY( SampleID ) );` } // no relation let samplesForARCTbl = { name: 'SamplesForARC', query: SQL`CREATE TABLE SamplesForARC( SampleID VARCHAR(20) NOT NULL, Datum VARCHAR(20), UTMZone1 INT, UTMZone2 CHAR(1), Easting FLOAT, Northing FLOAT, DateCollected DATETIME, MacrostructureType INT, MacrostructureDesc INT, PRIMARY KEY (SampleID) ); ` } // no relation let thrombolitesOnlyTbl = { name: 'ThrombolitesOnly', query: SQL`CREATE TABLE ThrombolitesOnly( Northing FLOAT, Easting FLOAT, SampleID VARCHAR(20), MesostructureDesc INT, PRIMARY KEY (SampleID) ); ` } var tables = [waypointsTbl, macrostructuresTbl, mesostructuresTbl, thinSectionsTbl, photoLinksTbl, microbilitesTbl, samplesForARCTbl, thrombolitesOnlyTbl]; //where the queries are made. for( let table of tables ) { let queryPromise = sendQuery(mysql_conn, table.query.sql ); queryPromise.then( () => { console.log("Added table " + table.name); }, queryPromiseReject ); } }
JavaScript
function restoreFromCSV( mysql_conn ) { function deleteData() { //get the name of the tables. let queryString = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'geodb';" let queryPromise = sendQuery( mysql_conn, queryString ); queryPromise.then( function( tableNames ) { //for each table delete the contents of that table. for( let i = 0; i < tableNames.length; i++) { let tableName = tableNames[i].TABLE_NAME; let queryString = "DELETE FROM " + tableName + ";"; let deleteQueryPromise = sendQuery(mysql_conn, queryString); deleteQueryPromise.then( restoreData(tableName), queryPromiseReject ); } }, queryPromiseReject ); } function restoreData(tableName) { let queryString = "LOAD DATA LOCAL INFILE './../csv/" + tableName + ".txt' INTO TABLE " + tableName + " FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES; " ; sendQuery(mysql_conn, queryString); } rl.question("Are you sure you want to restore geodb? (yes / no)\n", function (answer) { if(answer === 'yes') { console.log("\n\n=====RESTORING DATABASE====="); deleteData(); //console.log("\n ======DATABASE RESTORED======\n") ; } else { console.log("Not restoring geodb"); } rl.close(); }); }
function restoreFromCSV( mysql_conn ) { function deleteData() { //get the name of the tables. let queryString = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'geodb';" let queryPromise = sendQuery( mysql_conn, queryString ); queryPromise.then( function( tableNames ) { //for each table delete the contents of that table. for( let i = 0; i < tableNames.length; i++) { let tableName = tableNames[i].TABLE_NAME; let queryString = "DELETE FROM " + tableName + ";"; let deleteQueryPromise = sendQuery(mysql_conn, queryString); deleteQueryPromise.then( restoreData(tableName), queryPromiseReject ); } }, queryPromiseReject ); } function restoreData(tableName) { let queryString = "LOAD DATA LOCAL INFILE './../csv/" + tableName + ".txt' INTO TABLE " + tableName + " FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES; " ; sendQuery(mysql_conn, queryString); } rl.question("Are you sure you want to restore geodb? (yes / no)\n", function (answer) { if(answer === 'yes') { console.log("\n\n=====RESTORING DATABASE====="); deleteData(); //console.log("\n ======DATABASE RESTORED======\n") ; } else { console.log("Not restoring geodb"); } rl.close(); }); }
JavaScript
addCity(city) { this.cities.push({ cityId: city.formatted_address, photos: city.photos }); const currentCityBox = document.createElement('div'); currentCityBox.classList.add('box'); currentCityBox.id = city.formatted_address; const btnClosing = document.createElement('img'); btnClosing.classList.add('closeBtn'); btnClosing.id = `${city.formatted_address}-closeBtn`; btnClosing.src = './res/img/close.png'; currentCityBox.appendChild(btnClosing); this.rootContainer.appendChild(currentCityBox); return city.formatted_address; }
addCity(city) { this.cities.push({ cityId: city.formatted_address, photos: city.photos }); const currentCityBox = document.createElement('div'); currentCityBox.classList.add('box'); currentCityBox.id = city.formatted_address; const btnClosing = document.createElement('img'); btnClosing.classList.add('closeBtn'); btnClosing.id = `${city.formatted_address}-closeBtn`; btnClosing.src = './res/img/close.png'; currentCityBox.appendChild(btnClosing); this.rootContainer.appendChild(currentCityBox); return city.formatted_address; }
JavaScript
populate(cityId) { Rx.Observable .fromPromise(this.getCityWeather(cityId)) .pluck('list') .map((weatherFor5Days) => Helpers.getFullCityWeatherPerDay(weatherFor5Days)) .map((weatherFor5Days) => Helpers.getCityWeatherPerDay(weatherFor5Days)) .map((weatherFor5Days) => ({ cityId, weatherFor5Days })) .forEach((fiveDaysWeather) => { var weatherFor5Days = fiveDaysWeather['weatherFor5Days']; this.addLegend(cityId); this.addForecast(cityId, weatherFor5Days); if (this.useGooglePhotoSearch) { Helpers.setBackgroundImage(cityId); } else { var currentPhotos = this.cities.filter(function(city) { if (city.cityId === cityId) { return city.photos; } }); if (currentPhotos.length > 0) { var photos = currentPhotos[0].photos; var randPhoto = photos[Math.floor(Math.random() * photos.length)]; var photoUrl = randPhoto.getUrl({ 'maxWidth': 620, 'maxHeight': 150 }); Helpers.setDefaultBackgroundImage( cityId, photoUrl ); } } }) }
populate(cityId) { Rx.Observable .fromPromise(this.getCityWeather(cityId)) .pluck('list') .map((weatherFor5Days) => Helpers.getFullCityWeatherPerDay(weatherFor5Days)) .map((weatherFor5Days) => Helpers.getCityWeatherPerDay(weatherFor5Days)) .map((weatherFor5Days) => ({ cityId, weatherFor5Days })) .forEach((fiveDaysWeather) => { var weatherFor5Days = fiveDaysWeather['weatherFor5Days']; this.addLegend(cityId); this.addForecast(cityId, weatherFor5Days); if (this.useGooglePhotoSearch) { Helpers.setBackgroundImage(cityId); } else { var currentPhotos = this.cities.filter(function(city) { if (city.cityId === cityId) { return city.photos; } }); if (currentPhotos.length > 0) { var photos = currentPhotos[0].photos; var randPhoto = photos[Math.floor(Math.random() * photos.length)]; var photoUrl = randPhoto.getUrl({ 'maxWidth': 620, 'maxHeight': 150 }); Helpers.setDefaultBackgroundImage( cityId, photoUrl ); } } }) }
JavaScript
addLegend(cityId) { const currentCityEl = document.getElementById(cityId); const currentLegendEl = document.createElement('div'); currentLegendEl.classList.add('legend'); currentLegendEl.innerText = cityId; currentLegendEl.id = `${cityId}-legend`; currentCityEl.appendChild(currentLegendEl); }
addLegend(cityId) { const currentCityEl = document.getElementById(cityId); const currentLegendEl = document.createElement('div'); currentLegendEl.classList.add('legend'); currentLegendEl.innerText = cityId; currentLegendEl.id = `${cityId}-legend`; currentCityEl.appendChild(currentLegendEl); }
JavaScript
addForecast(cityId, weatherFor5Days) { const currentForecast = document.createElement('div'); currentForecast.classList.add('forecast'); weatherFor5Days.forEach((currentDay, index) => { var cityTag = cityId + '_day' + index; this.addDay(currentDay, cityTag, currentForecast); }) }
addForecast(cityId, weatherFor5Days) { const currentForecast = document.createElement('div'); currentForecast.classList.add('forecast'); weatherFor5Days.forEach((currentDay, index) => { var cityTag = cityId + '_day' + index; this.addDay(currentDay, cityTag, currentForecast); }) }
JavaScript
function post() { let selector = document.getElementById("select-ecu"); let ecu = selector.options[selector.selectedIndex].value; if(ecu == "null") { alert("Please select a valid ECU."); return; } let data = { dbc: extractData(), ecu: ecu } fetch("upload", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(data) }).then(response => { if(!response.ok) { alert("Failed to compile DBC file"); throw "Failed to compile DBC file"; } return response.blob() }) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement("a"); a.style.display = "none"; a.href = url; a.download = "file.dbc"; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); }); }
function post() { let selector = document.getElementById("select-ecu"); let ecu = selector.options[selector.selectedIndex].value; if(ecu == "null") { alert("Please select a valid ECU."); return; } let data = { dbc: extractData(), ecu: ecu } fetch("upload", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(data) }).then(response => { if(!response.ok) { alert("Failed to compile DBC file"); throw "Failed to compile DBC file"; } return response.blob() }) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement("a"); a.style.display = "none"; a.href = url; a.download = "file.dbc"; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); }); }
JavaScript
function addDeleteButton(container) { let deleteButton = document.createElement("button"); deleteButton.classList.add("delete"); deleteButton.innerHTML = "Delete"; deleteButton.onclick = () => { container.remove(); } container.appendChild(deleteButton); }
function addDeleteButton(container) { let deleteButton = document.createElement("button"); deleteButton.classList.add("delete"); deleteButton.innerHTML = "Delete"; deleteButton.onclick = () => { container.remove(); } container.appendChild(deleteButton); }
JavaScript
async function loadSelectedFile() { let selector = document.getElementById("select-dbc"); let url = selector.options[selector.selectedIndex].value; if(url == "null") { alert("Please select a valid DBC file to load."); return; } let response = await fetch("/parse", { method: "POST", body: url }); let data = await response.json(); let parentContainer = document.getElementById("fields"); parentContainer.innerHTML = ""; importFields(data.dbc.file, "file", parentContainer); document.getElementById("select-ecu").selectedIndex = ecus.indexOf(data.ecu) + 1; }
async function loadSelectedFile() { let selector = document.getElementById("select-dbc"); let url = selector.options[selector.selectedIndex].value; if(url == "null") { alert("Please select a valid DBC file to load."); return; } let response = await fetch("/parse", { method: "POST", body: url }); let data = await response.json(); let parentContainer = document.getElementById("fields"); parentContainer.innerHTML = ""; importFields(data.dbc.file, "file", parentContainer); document.getElementById("select-ecu").selectedIndex = ecus.indexOf(data.ecu) + 1; }
JavaScript
updateSliderDraw(draw) { this.setState({ draw: draw }); }
updateSliderDraw(draw) { this.setState({ draw: draw }); }
JavaScript
handleDocumentClickEvent(clickEvent) { if(this.state.draw) { const target = clickEvent.target; if (this.sliderElement.contains) { // If click outside slider close it if (!this.sliderElement.contains(target)) { this.updateSliderDraw(false); } else { // If a link tag is clicked, close the slider // TODO : Replace with a close event which is propagated down if(target.tagName.toLowerCase() === 'a' && target.href) { this.updateSliderDraw(false); } } } } }
handleDocumentClickEvent(clickEvent) { if(this.state.draw) { const target = clickEvent.target; if (this.sliderElement.contains) { // If click outside slider close it if (!this.sliderElement.contains(target)) { this.updateSliderDraw(false); } else { // If a link tag is clicked, close the slider // TODO : Replace with a close event which is propagated down if(target.tagName.toLowerCase() === 'a' && target.href) { this.updateSliderDraw(false); } } } } }
JavaScript
render() { const isDrawn = this.state.draw; const {isSubSlider, headerHeight, windowWidth, windowHeight} = this.props; const drawnClass = isDrawn ? 'vertical-slider--drawn' : ''; const sliderLevelClass = isSubSlider ? 'vertical-slider--sub': 'vertical-slider--main'; // Get slider width which is a particular fraction of window width upto a given max width const width = Math.min(Math.floor(windowWidth * this.props.sliderWidthFraction), this.props.sliderWidthMax); const childStyles = { transform: `translateX(${isDrawn ? '0' : `-${width}px`})`, height: `${windowHeight - headerHeight}px`, width: `${width}px`, top: isSubSlider ? 0: `${headerHeight}px` , left: 0, position: isSubSlider ? 'absolute' : 'fixed' }; return ( <div ref={(ref)=> this.sliderElement = ref} className={`vertical-slider ${drawnClass} ${sliderLevelClass}`}> {isSubSlider ? this.getSubMenuBar(isDrawn): this.getTopBar(isDrawn)} <div aria-hidden={!isDrawn} style={childStyles} className="vertical-slider--children"> {this.getSliderChild(isSubSlider, this.props.children)} </div> </div> ); }
render() { const isDrawn = this.state.draw; const {isSubSlider, headerHeight, windowWidth, windowHeight} = this.props; const drawnClass = isDrawn ? 'vertical-slider--drawn' : ''; const sliderLevelClass = isSubSlider ? 'vertical-slider--sub': 'vertical-slider--main'; // Get slider width which is a particular fraction of window width upto a given max width const width = Math.min(Math.floor(windowWidth * this.props.sliderWidthFraction), this.props.sliderWidthMax); const childStyles = { transform: `translateX(${isDrawn ? '0' : `-${width}px`})`, height: `${windowHeight - headerHeight}px`, width: `${width}px`, top: isSubSlider ? 0: `${headerHeight}px` , left: 0, position: isSubSlider ? 'absolute' : 'fixed' }; return ( <div ref={(ref)=> this.sliderElement = ref} className={`vertical-slider ${drawnClass} ${sliderLevelClass}`}> {isSubSlider ? this.getSubMenuBar(isDrawn): this.getTopBar(isDrawn)} <div aria-hidden={!isDrawn} style={childStyles} className="vertical-slider--children"> {this.getSliderChild(isSubSlider, this.props.children)} </div> </div> ); }
JavaScript
function addPropsToChildren(children, props) { var addIndex = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return _react2.default.Children.map(children, function (child, index) { var finalProps = addIndex ? _ObjectHelper2.default.assignProperties({}, props, { index: index }) : props; return _react2.default.cloneElement(child, finalProps); }); }
function addPropsToChildren(children, props) { var addIndex = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return _react2.default.Children.map(children, function (child, index) { var finalProps = addIndex ? _ObjectHelper2.default.assignProperties({}, props, { index: index }) : props; return _react2.default.cloneElement(child, finalProps); }); }
JavaScript
function assignProperties(target) { for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } if (Object.assign) { Object.assign.apply(Object, [target].concat(sources)); return target; } for (var index = 0; index < sources.length; index++) { var source = sources[index]; if (source != null) { for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } } return target; }
function assignProperties(target) { for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } if (Object.assign) { Object.assign.apply(Object, [target].concat(sources)); return target; } for (var index = 0; index < sources.length; index++) { var source = sources[index]; if (source != null) { for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } } return target; }
JavaScript
function organizeDesktopChildren(children) { var newChildren = []; children.forEach(function (child, index) { if (child.type === _NavigationList2.default) { newChildren.push(_ReactHelper2.default.getMainNav(child)); } else { newChildren.push(_react2.default.cloneElement(child, { key: index })); } }); return newChildren; }
function organizeDesktopChildren(children) { var newChildren = []; children.forEach(function (child, index) { if (child.type === _NavigationList2.default) { newChildren.push(_ReactHelper2.default.getMainNav(child)); } else { newChildren.push(_react2.default.cloneElement(child, { key: index })); } }); return newChildren; }
JavaScript
function debounce(func, wait, immediate) { var timeout, args, context, timestamp, result; if (null == wait) wait = 100; function later() { var last = nowTS() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); context = args = null; } } } var debounced = function debounced() { context = this; args = arguments; timestamp = nowTS(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; debounced.clear = function () { if (timeout) { clearTimeout(timeout); timeout = null; } }; return debounced; }
function debounce(func, wait, immediate) { var timeout, args, context, timestamp, result; if (null == wait) wait = 100; function later() { var last = nowTS() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); context = args = null; } } } var debounced = function debounced() { context = this; args = arguments; timestamp = nowTS(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; debounced.clear = function () { if (timeout) { clearTimeout(timeout); timeout = null; } }; return debounced; }
JavaScript
handleKeyNavigation(listHelper, keyEvent) { const keyCode = keyEvent.which; let handledEvent = false; if (listHelper.canHandleEvent(keyCode)) { const newActiveIndex = this.activeElementSyncIndex + listHelper.getChange(keyCode); if (newActiveIndex >= -1 && newActiveIndex < this.props.children.length) { this.setState({ activeIndex: newActiveIndex }); // prevent default so that the default behaviour like down key // shifting the page down does not happens keyEvent.preventDefault(); } // If no child element is active, this means call any close event handler, if defined. if(newActiveIndex === -1 && this.props.handleCloseEvent) { this.props.handleCloseEvent(); } handledEvent = true; } return handledEvent; }
handleKeyNavigation(listHelper, keyEvent) { const keyCode = keyEvent.which; let handledEvent = false; if (listHelper.canHandleEvent(keyCode)) { const newActiveIndex = this.activeElementSyncIndex + listHelper.getChange(keyCode); if (newActiveIndex >= -1 && newActiveIndex < this.props.children.length) { this.setState({ activeIndex: newActiveIndex }); // prevent default so that the default behaviour like down key // shifting the page down does not happens keyEvent.preventDefault(); } // If no child element is active, this means call any close event handler, if defined. if(newActiveIndex === -1 && this.props.handleCloseEvent) { this.props.handleCloseEvent(); } handledEvent = true; } return handledEvent; }
JavaScript
isCurrentLevelEvent(keyEvent) { // Bubbling can only occur for menus which have sub menus and it can // only happen from titleElement of sub menu return this.subMenuElement === undefined || this.subMenuElement.titleElement === keyEvent.target; }
isCurrentLevelEvent(keyEvent) { // Bubbling can only occur for menus which have sub menus and it can // only happen from titleElement of sub menu return this.subMenuElement === undefined || this.subMenuElement.titleElement === keyEvent.target; }