language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function gitHasChanges() { return git(`status --porcelain --untracked-files=all`) .then(result => { let {index, workingTree} = gitUtil.extractStatus(result); if (index) { if (isNonEmpty(index.modified) || isNonEmpty(index.added) || isNonEmpty(index.deleted) || isNonEmpty(index.renamed) || isNonEmpty(index.copied)) { return true; } } if (workingTree) { if (isNonEmpty(workingTree.modified) || isNonEmpty(workingTree.added) || isNonEmpty(workingTree.deleted)) { return true; } } return false; }); }
function gitHasChanges() { return git(`status --porcelain --untracked-files=all`) .then(result => { let {index, workingTree} = gitUtil.extractStatus(result); if (index) { if (isNonEmpty(index.modified) || isNonEmpty(index.added) || isNonEmpty(index.deleted) || isNonEmpty(index.renamed) || isNonEmpty(index.copied)) { return true; } } if (workingTree) { if (isNonEmpty(workingTree.modified) || isNonEmpty(workingTree.added) || isNonEmpty(workingTree.deleted)) { return true; } } return false; }); }
JavaScript
async function post(post) { if (!isValid(post)) return response_400("Invalid post data"); post.id = generateRandomId(); post.createdTime = new Date(); await POSTS.put(post.id, JSON.stringify(post)); return new Response("Success", { status: 200, statusText: "OK", headers: { ...cors_headers, "content-type": "text/plain" }, }); }
async function post(post) { if (!isValid(post)) return response_400("Invalid post data"); post.id = generateRandomId(); post.createdTime = new Date(); await POSTS.put(post.id, JSON.stringify(post)); return new Response("Success", { status: 200, statusText: "OK", headers: { ...cors_headers, "content-type": "text/plain" }, }); }
JavaScript
function isValid(post) { return typeof(post.title) === "string" && typeof(post.username) === "string" && typeof(post.content) === "string"; }
function isValid(post) { return typeof(post.title) === "string" && typeof(post.username) === "string" && typeof(post.content) === "string"; }
JavaScript
function generateRandomId(length = 10, characters = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") { let id = ""; for (let i = 0; i < length; i++) { id += characters[Math.floor(Math.random() * characters.length)]; } return id; }
function generateRandomId(length = 10, characters = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") { let id = ""; for (let i = 0; i < length; i++) { id += characters[Math.floor(Math.random() * characters.length)]; } return id; }
JavaScript
preInit({ agent, protocol, timeout, concurrency, connection }) { this.concurrency = concurrency > 0 ? concurrency : 1; this.connection = Connection.create(connection); if (agent) this.globalize(protocol, agent); }
preInit({ agent, protocol, timeout, concurrency, connection }) { this.concurrency = concurrency > 0 ? concurrency : 1; this.connection = Connection.create(connection); if (agent) this.globalize(protocol, agent); }
JavaScript
preDelete() { if ( global.FMS_API_CLIENT.AGENTS && global.FMS_API_CLIENT.AGENTS[this.global] ) { this.localize()[`${this.protocol}Agent`].destroy(); delete global.FMS_API_CLIENT.AGENTS[this.global]; } }
preDelete() { if ( global.FMS_API_CLIENT.AGENTS && global.FMS_API_CLIENT.AGENTS[this.global] ) { this.localize()[`${this.protocol}Agent`].destroy(); delete global.FMS_API_CLIENT.AGENTS[this.global]; } }
JavaScript
globalize(protocol, agent) { if (!this.global) this.global = uuidv4(); /** * @global */ global.FMS_API_CLIENT.AGENTS[this.global] = protocol === 'https' ? { httpsAgent: new https.Agent(this.agent) } : { httpAgent: new http.Agent(this.agent) }; return global.FMS_API_CLIENT.AGENTS[this.global]; }
globalize(protocol, agent) { if (!this.global) this.global = uuidv4(); /** * @global */ global.FMS_API_CLIENT.AGENTS[this.global] = protocol === 'https' ? { httpsAgent: new https.Agent(this.agent) } : { httpAgent: new http.Agent(this.agent) }; return global.FMS_API_CLIENT.AGENTS[this.global]; }
JavaScript
localize() { if (typeof global.FMS_API_CLIENT.AGENTS === 'undefined') global.FMS_API_CLIENT.AGENTS = []; if (global.FMS_API_CLIENT.AGENTS[this.global]) { return global.FMS_API_CLIENT.AGENTS[this.global]; } else { return this.globalize(this.protocol, this.agent); } }
localize() { if (typeof global.FMS_API_CLIENT.AGENTS === 'undefined') global.FMS_API_CLIENT.AGENTS = []; if (global.FMS_API_CLIENT.AGENTS[this.global]) { return global.FMS_API_CLIENT.AGENTS[this.global]; } else { return this.globalize(this.protocol, this.agent); } }
JavaScript
request(data, parameters = {}) { const id = uuidv4(); const interceptor = instance.interceptors.request.use( ({ httpAgent, httpsAgent, ...request }) => { instance.interceptors.request.eject(interceptor); return new Promise((resolve, reject) => this.push({ request: this.handleRequest(request, id), resolve, reject }) ); } ); const response = instance.interceptors.response.use( response => { instance.interceptors.response.eject(response); return this.handleResponse(response, id); }, error => { instance.interceptors.response.eject(response); return this.handleError(error, id); } ); return instance( Object.assign( data, this.timeout ? { timeout: this.timeout } : {}, _.isEmpty(this.proxy) ? {} : { proxy: this.proxy }, _.isEmpty(this.agent) ? {} : this.localize(), parameters.request || {} ) ); }
request(data, parameters = {}) { const id = uuidv4(); const interceptor = instance.interceptors.request.use( ({ httpAgent, httpsAgent, ...request }) => { instance.interceptors.request.eject(interceptor); return new Promise((resolve, reject) => this.push({ request: this.handleRequest(request, id), resolve, reject }) ); } ); const response = instance.interceptors.response.use( response => { instance.interceptors.response.eject(response); return this.handleResponse(response, id); }, error => { instance.interceptors.response.eject(response); return this.handleError(error, id); } ); return instance( Object.assign( data, this.timeout ? { timeout: this.timeout } : {}, _.isEmpty(this.proxy) ? {} : { proxy: this.proxy }, _.isEmpty(this.agent) ? {} : this.localize(), parameters.request || {} ) ); }
JavaScript
handleResponse(response, id) { const token = _.get(response, 'config.headers.Authorization'); if (token) { this.connection.deactivate(token, id); } if (typeof response.data !== 'object') { return Promise.reject({ message: 'The Data API is currently unavailable', code: '1630' }); } else { this.connection.extend(token); return response; } }
handleResponse(response, id) { const token = _.get(response, 'config.headers.Authorization'); if (token) { this.connection.deactivate(token, id); } if (typeof response.data !== 'object') { return Promise.reject({ message: 'The Data API is currently unavailable', code: '1630' }); } else { this.connection.extend(token); return response; } }
JavaScript
handleRequest(config, id) { config.id = id; return config.url.startsWith('http') ? omit(config, ['params.request', 'data.request']) : Promise.reject({ code: '1630', message: 'The Data API Requires https or http' }); }
handleRequest(config, id) { config.id = id; return config.url.startsWith('http') ? omit(config, ['params.request', 'data.request']) : Promise.reject({ code: '1630', message: 'The Data API Requires https or http' }); }
JavaScript
push({ request, resolve, reject }) { this.queue.push({ request: this.mutate(request, (value, key) => key.replace(/\./g, '{{dot}}') ), resolve }); this.shift(); this.watch(reject); }
push({ request, resolve, reject }) { this.queue.push({ request: this.mutate(request, (value, key) => key.replace(/\./g, '{{dot}}') ), resolve }); this.shift(); this.watch(reject); }
JavaScript
shift() { if (this.pending.length < this.concurrency) { this.pending.push(this.queue.shift()); } }
shift() { if (this.pending.length < this.concurrency) { this.pending.push(this.queue.shift()); } }
JavaScript
mutate(request, mutation) { const { transformRequest, transformResponse, adapter, validateStatus, ...value } = request; const modified = request.url.includes('/containers/') ? request : deepMapKeys(value, mutation); return { ...modified, transformRequest, transformResponse, adapter, validateStatus }; }
mutate(request, mutation) { const { transformRequest, transformResponse, adapter, validateStatus, ...value } = request; const modified = request.url.includes('/containers/') ? request : deepMapKeys(value, mutation); return { ...modified, transformRequest, transformResponse, adapter, validateStatus }; }
JavaScript
handleError(error, id) { const token = _.get(error, 'config.headers.Authorization'); if (token) { this.connection.deactivate(token, id); } this.connection.confirm(); if (error.code) { return Promise.reject({ code: error.code, message: error.message }); } else if ( error.response.status === 502 || typeof error.response.data !== 'object' ) { return Promise.reject({ message: 'The Data API is currently unavailable', code: '1630' }); } else { if (error.response.data.messages[0].code === '952') this.connection.clear(token); return Promise.reject(error.response.data.messages[0]); } }
handleError(error, id) { const token = _.get(error, 'config.headers.Authorization'); if (token) { this.connection.deactivate(token, id); } this.connection.confirm(); if (error.code) { return Promise.reject({ code: error.code, message: error.message }); } else if ( error.response.status === 502 || typeof error.response.data !== 'object' ) { return Promise.reject({ message: 'The Data API is currently unavailable', code: '1630' }); } else { if (error.response.data.messages[0].code === '952') this.connection.clear(token); return Promise.reject(error.response.data.messages[0]); } }
JavaScript
watch(reject) { if (!this.global) this.global = uuidv4(); if (!global.FMS_API_CLIENT.WATCHERS) global.FMS_API_CLIENT.WATCHERS = {}; if (!global.FMS_API_CLIENT.WATCHERS[this.global]) { const WATCHER = setTimeout( function watch() { this.connection.clear(); if ( this.queue.length > 0 && !this.connection.starting && this.connection.available() ) { this.shift(); } if ( this.pending.length > 0 && !this.connection.starting && this.connection.available() ) { this.resolve(); } if ( this.pending.length > 0 && !this.connection.available() && !this.connection.starting && this.connection.sessions.length < this.concurrency ) { this.connection .start(!_.isEmpty(this.agent) ? this.localize() : false) .catch(error => { this.pending = []; this.queue = []; reject(error); }); } if (this.queue.length === 0 && this.pending.length === 0) { clearTimeout(global.FMS_API_CLIENT.WATCHERS[this.global]); delete global.FMS_API_CLIENT.WATCHERS[this.global]; } else { setTimeout(watch.bind(this), this.delay); } }.bind(this), this.delay ); global.FMS_API_CLIENT.WATCHERS[this.global] = WATCHER; } }
watch(reject) { if (!this.global) this.global = uuidv4(); if (!global.FMS_API_CLIENT.WATCHERS) global.FMS_API_CLIENT.WATCHERS = {}; if (!global.FMS_API_CLIENT.WATCHERS[this.global]) { const WATCHER = setTimeout( function watch() { this.connection.clear(); if ( this.queue.length > 0 && !this.connection.starting && this.connection.available() ) { this.shift(); } if ( this.pending.length > 0 && !this.connection.starting && this.connection.available() ) { this.resolve(); } if ( this.pending.length > 0 && !this.connection.available() && !this.connection.starting && this.connection.sessions.length < this.concurrency ) { this.connection .start(!_.isEmpty(this.agent) ? this.localize() : false) .catch(error => { this.pending = []; this.queue = []; reject(error); }); } if (this.queue.length === 0 && this.pending.length === 0) { clearTimeout(global.FMS_API_CLIENT.WATCHERS[this.global]); delete global.FMS_API_CLIENT.WATCHERS[this.global]; } else { setTimeout(watch.bind(this), this.delay); } }.bind(this), this.delay ); global.FMS_API_CLIENT.WATCHERS[this.global] = WATCHER; } }
JavaScript
resolve() { const pending = this.pending.shift(); this.connection .authentication( Object.assign( this.mutate(pending.request, (value, key) => key.replace(/{{dot}}/g, '.') ), { id: pending.id } ), _.isEmpty(this.agent) ? {} : this.localize() ) .then(request => typeof pending.resolve === 'function' ? pending.resolve(request) : request ); }
resolve() { const pending = this.pending.shift(); this.connection .authentication( Object.assign( this.mutate(pending.request, (value, key) => key.replace(/{{dot}}/g, '.') ), { id: pending.id } ), _.isEmpty(this.agent) ? {} : this.localize() ) .then(request => typeof pending.resolve === 'function' ? pending.resolve(request) : request ); }
JavaScript
status() { const status = { data: { since: this.since, in: pretty(this.in), out: pretty(this.out) } }; return status; }
status() { const status = { data: { since: this.since, in: pretty(this.in), out: pretty(this.out) } }; return status; }
JavaScript
basic() { const auth = `Basic ${Buffer.from(`${this.user}:${this.password}`).toString( 'base64' )}`; return auth; }
basic() { const auth = `Basic ${Buffer.from(`${this.user}:${this.password}`).toString( 'base64' )}`; return auth; }
JavaScript
authentication({ headers, id, ...request }) { return new Promise((resolve, reject) => { const sessions = _.sortBy( this.sessions.filter(session => !session.expired()), ['active', 'used'], ['desc'] ); const session = sessions[0]; session.active = true; session.url = request.url; session.request = id; session.used = moment().format(); resolve({ ...request, headers: { ...headers, Authorization: `Bearer ${session.token}` } }); }); }
authentication({ headers, id, ...request }) { return new Promise((resolve, reject) => { const sessions = _.sortBy( this.sessions.filter(session => !session.expired()), ['active', 'used'], ['desc'] ); const session = sessions[0]; session.active = true; session.url = request.url; session.request = id; session.used = moment().format(); resolve({ ...request, headers: { ...headers, Authorization: `Bearer ${session.token}` } }); }); }
JavaScript
clear(header) { this.sessions = this.sessions.filter(session => typeof header === 'string' ? header.replace('Bearer ', '') !== session.token : !session.expired() ); }
clear(header) { this.sessions = this.sessions.filter(session => typeof header === 'string' ? header.replace('Bearer ', '') !== session.token : !session.expired() ); }
JavaScript
extend(header) { const token = header.replace('Bearer ', ''); const session = _.find(this.sessions, session => session.token === token); if (session) session.extend(); }
extend(header) { const token = header.replace('Bearer ', ''); const session = _.find(this.sessions, session => session.token === token); if (session) session.extend(); }
JavaScript
confirm() { this.sessions.forEach(session => { if (_.isEmpty(session.request)) { session.active = false; } }); }
confirm() { this.sessions.forEach(session => { if (_.isEmpty(session.request)) { session.active = false; } }); }
JavaScript
deactivate(header, id) { const token = header.replace('Bearer ', ''); const session = _.find( this.sessions, session => session.token === token || session.request === id ); if (session) session.deactivate(); }
deactivate(header, id) { const token = header.replace('Bearer ', ''); const session = _.find( this.sessions, session => session.token === token || session.request === id ); if (session) session.deactivate(); }
JavaScript
preInit(data) { const { agent, timeout, concurrency, threshold, usage, proxy, ...connection } = data; const protocol = data.server.startsWith('https') ? 'https' : 'http'; this.data = Data.create({ track: usage === undefined }); this.agent = Agent.create({ agent, proxy, timeout, threshold, concurrency, protocol, connection }); }
preInit(data) { const { agent, timeout, concurrency, threshold, usage, proxy, ...connection } = data; const protocol = data.server.startsWith('https') ? 'https' : 'http'; this.data = Data.create({ track: usage === undefined }); this.agent = Agent.create({ agent, proxy, timeout, threshold, concurrency, protocol, connection }); }
JavaScript
preDelete() { return new Promise((resolve, reject) => this.agent.connection .end() .then(response => resolve()) .catch(error => resolve(error)) ); }
preDelete() { return new Promise((resolve, reject) => this.agent.connection .end() .then(response => resolve()) .catch(error => resolve(error)) ); }
JavaScript
login() { return new Promise((resolve, reject) => this.agent.connection .start(!_.isEmpty(this.agent.agent) ? this.agent.localize() : false) .then(body => this.data.outgoing(body)) .then(body => this._save(resolve(body))) .catch(error => this._save(reject(error))) ); }
login() { return new Promise((resolve, reject) => this.agent.connection .start(!_.isEmpty(this.agent.agent) ? this.agent.localize() : false) .then(body => this.data.outgoing(body)) .then(body => this._save(resolve(body))) .catch(error => this._save(reject(error))) ); }
JavaScript
logout(id) { return new Promise((resolve, reject) => this.agent.connection .end(!_.isEmpty(this.agent.agent) ? this.agent.localize() : false, id) .then(body => this.data.outgoing(body)) .then(body => this._save(resolve(body))) .catch(error => this._save(reject(error))) ); }
logout(id) { return new Promise((resolve, reject) => this.agent.connection .end(!_.isEmpty(this.agent.agent) ? this.agent.localize() : false, id) .then(body => this.data.outgoing(body)) .then(body => this._save(resolve(body))) .catch(error => this._save(reject(error))) ); }
JavaScript
productInfo() { return new Promise((resolve, reject) => productInfo(this.agent.connection.server, this.agent.connection.version) .then(response => resolve(response)) .catch(error => this._save(reject(error))) ); }
productInfo() { return new Promise((resolve, reject) => productInfo(this.agent.connection.server, this.agent.connection.version) .then(response => resolve(response)) .catch(error => this._save(reject(error))) ); }
JavaScript
status() { return new Promise((resolve, reject) => resolve({ ...this.data.status(), queue: this.agent.queue.map(({ url }) => ({ url })), pending: this.agent.pending.map(({ url }) => ({ url })), sessions: this.agent.connection.sessions.map( ({ issued, expires, id }) => ({ issued, expires, id }) ) }) ); }
status() { return new Promise((resolve, reject) => resolve({ ...this.data.status(), queue: this.agent.queue.map(({ url }) => ({ url })), pending: this.agent.pending.map(({ url }) => ({ url })), sessions: this.agent.connection.sessions.map( ({ issued, expires, id }) => ({ issued, expires, id }) ) }) ); }
JavaScript
reset() { return new Promise((resolve, reject) => { const logouts = []; this.agent.queue = []; this.agent.pending = []; this.agent.connection.sessions.forEach(({ id }) => logouts.push(this.logout(id)) ); Promise.all(logouts) .then(results => { return this.save(); }) .then(client => resolve({ message: 'Client Reset' }) ) .catch(error => reject({ message: 'Client Reset Failed' })); }); }
reset() { return new Promise((resolve, reject) => { const logouts = []; this.agent.queue = []; this.agent.pending = []; this.agent.connection.sessions.forEach(({ id }) => logouts.push(this.logout(id)) ); Promise.all(logouts) .then(results => { return this.save(); }) .then(client => resolve({ message: 'Client Reset' }) ) .catch(error => reject({ message: 'Client Reset Failed' })); }); }
JavaScript
databases(credentials, version) { return new Promise((resolve, reject) => databases( this.agent.connection.server, credentials || this.agent.connection.credentials, this.agent.connection.version ) .then(response => resolve(response)) .catch(error => this._save(reject(error))) ); }
databases(credentials, version) { return new Promise((resolve, reject) => databases( this.agent.connection.server, credentials || this.agent.connection.credentials, this.agent.connection.version ) .then(response => resolve(response)) .catch(error => this._save(reject(error))) ); }
JavaScript
layouts(parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.layouts( this.agent.connection.server, this.agent.connection.database, this.agent.connection.version ), method: 'get' }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => resolve(body.response)) .catch(error => this._save(reject(error))) ); }
layouts(parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.layouts( this.agent.connection.server, this.agent.connection.database, this.agent.connection.version ), method: 'get' }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => resolve(body.response)) .catch(error => this._save(reject(error))) ); }
JavaScript
scripts(parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.scripts( this.agent.connection.server, this.agent.connection.database, this.agent.connection.version ), method: 'get' }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => resolve(body.response)) .catch(error => this._save(reject(error))) ); }
scripts(parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.scripts( this.agent.connection.server, this.agent.connection.database, this.agent.connection.version ), method: 'get' }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => resolve(body.response)) .catch(error => this._save(reject(error))) ); }
JavaScript
layout(layout, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.layout( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'get', params: toStrings(sanitizeParameters(parameters, ['recordId'])) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => resolve(body.response)) .catch(error => this._save(reject(error))) ); }
layout(layout, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.layout( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'get', params: toStrings(sanitizeParameters(parameters, ['recordId'])) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => resolve(body.response)) .catch(error => this._save(reject(error))) ); }
JavaScript
duplicate(layout, recordId, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.duplicate( this.agent.connection.server, this.agent.connection.database, layout, recordId, this.agent.connection.version ), method: 'post', headers: { 'Content-Type': 'application/json' }, data: sanitizeParameters(parameters, [ 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'request' ]) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
duplicate(layout, recordId, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.duplicate( this.agent.connection.server, this.agent.connection.database, layout, recordId, this.agent.connection.version ), method: 'post', headers: { 'Content-Type': 'application/json' }, data: sanitizeParameters(parameters, [ 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'request' ]) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
JavaScript
create(layout, data = {}, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.create( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'post', headers: { 'Content-Type': 'application/json' }, data: Object.assign( sanitizeParameters(parameters, [ 'portalData', 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'request' ]), this.data.incoming(setData(data)) ) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(response => resolve(parameters.merge ? Object.assign(data, response) : response) ) .catch(error => this._save(reject(error))) ); }
create(layout, data = {}, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.create( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'post', headers: { 'Content-Type': 'application/json' }, data: Object.assign( sanitizeParameters(parameters, [ 'portalData', 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'request' ]), this.data.incoming(setData(data)) ) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(response => resolve(parameters.merge ? Object.assign(data, response) : response) ) .catch(error => this._save(reject(error))) ); }
JavaScript
edit(layout, recordId, data, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.update( this.agent.connection.server, this.agent.connection.database, layout, recordId, this.agent.connection.version ), method: 'patch', headers: { 'Content-Type': 'application/json' }, data: Object.assign( sanitizeParameters(parameters, [ 'portalData', 'modId', 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'request' ]), this.data.incoming(setData(data)) ) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(body => resolve( parameters.merge ? Object.assign(data, { recordId: recordId }, body) : body ) ) .catch(error => this._save(reject(error))) ); }
edit(layout, recordId, data, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.update( this.agent.connection.server, this.agent.connection.database, layout, recordId, this.agent.connection.version ), method: 'patch', headers: { 'Content-Type': 'application/json' }, data: Object.assign( sanitizeParameters(parameters, [ 'portalData', 'modId', 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'request' ]), this.data.incoming(setData(data)) ) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(body => resolve( parameters.merge ? Object.assign(data, { recordId: recordId }, body) : body ) ) .catch(error => this._save(reject(error))) ); }
JavaScript
delete(layout, recordId, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.delete( this.agent.connection.server, this.agent.connection.database, layout, recordId, this.agent.connection.version ), method: 'delete', data: sanitizeParameters(parameters, [ 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'request' ]) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
delete(layout, recordId, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.delete( this.agent.connection.server, this.agent.connection.database, layout, recordId, this.agent.connection.version ), method: 'delete', data: sanitizeParameters(parameters, [ 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'request' ]) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
JavaScript
list(layout, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.list( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'get', headers: { 'Content-Type': 'application/json' }, params: toStrings( sanitizeParameters(namespace(parameters), [ '_limit', '_offset', '_sort', 'portal', 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'layout.response', '_offset.*', '_limit.*', 'request' ]) ) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
list(layout, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.list( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'get', headers: { 'Content-Type': 'application/json' }, params: toStrings( sanitizeParameters(namespace(parameters), [ '_limit', '_offset', '_sort', 'portal', 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'layout.response', '_offset.*', '_limit.*', 'request' ]) ) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
JavaScript
find(layout, query, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.find( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'post', headers: { 'Content-Type': 'application/json' }, data: Object.assign( { query: toStrings(toArray(query)) }, sanitizeParameters(parameters, [ 'limit', 'sort', 'offset', 'portal', 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'layout.response', 'offset.*', 'limit.*', 'request' ]) ) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(result => resolve(result)) .catch(error => { this._save(); return error.code === '401' ? resolve({ data: [], message: 'No records match the request' }) : reject(error); }) ); }
find(layout, query, parameters = {}) { return new Promise((resolve, reject) => this.agent .request( { url: urls.find( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'post', headers: { 'Content-Type': 'application/json' }, data: Object.assign( { query: toStrings(toArray(query)) }, sanitizeParameters(parameters, [ 'limit', 'sort', 'offset', 'portal', 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', 'layout.response', 'offset.*', 'limit.*', 'request' ]) ) }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(result => resolve(result)) .catch(error => { this._save(); return error.code === '401' ? resolve({ data: [], message: 'No records match the request' }) : reject(error); }) ); }
JavaScript
globals(data, parameters) { return new Promise((resolve, reject) => this.agent .request( { url: urls.globals( this.agent.connection.server, this.agent.connection.database, this.agent.connection.version ), method: 'patch', headers: { 'Content-Type': 'application/json' }, data: { globalFields: toStrings(data) } }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
globals(data, parameters) { return new Promise((resolve, reject) => this.agent .request( { url: urls.globals( this.agent.connection.server, this.agent.connection.database, this.agent.connection.version ), method: 'patch', headers: { 'Content-Type': 'application/json' }, data: { globalFields: toStrings(data) } }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
JavaScript
upload(file, layout, containerFieldName, recordId = 0, parameters = {}) { return new Promise((resolve, reject) => { let stream; const form = new FormData(); const resolveRecordId = () => recordId === 0 ? this.create(layout, {}).then(response => response.recordId) : Promise.resolve(recordId); if (typeof file === 'string') { stream = fs.createReadStream(file); stream.on('error', error => reject({ message: error.message, code: error.code }) ); } else if (!file || !file.name || !file.buffer) { reject({ message: 'A file object must have a name and buffer property', code: 117 }); } else { stream = intoStream(file.buffer); stream.name = file.name; } form.append('upload', stream); resolveRecordId() .then(resolvedId => this.agent .request( { url: urls.upload( this.agent.connection.server, this.agent.connection.database, layout, resolvedId, containerFieldName, parameters.fieldRepetition, this.agent.connection.version ), method: 'post', data: form, headers: { ...form.getHeaders() } }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(response => Object.assign(response, { recordId: resolvedId })) ) .then(response => resolve(response)) .catch(error => this._save(reject(error))); }); }
upload(file, layout, containerFieldName, recordId = 0, parameters = {}) { return new Promise((resolve, reject) => { let stream; const form = new FormData(); const resolveRecordId = () => recordId === 0 ? this.create(layout, {}).then(response => response.recordId) : Promise.resolve(recordId); if (typeof file === 'string') { stream = fs.createReadStream(file); stream.on('error', error => reject({ message: error.message, code: error.code }) ); } else if (!file || !file.name || !file.buffer) { reject({ message: 'A file object must have a name and buffer property', code: 117 }); } else { stream = intoStream(file.buffer); stream.name = file.name; } form.append('upload', stream); resolveRecordId() .then(resolvedId => this.agent .request( { url: urls.upload( this.agent.connection.server, this.agent.connection.database, layout, resolvedId, containerFieldName, parameters.fieldRepetition, this.agent.connection.version ), method: 'post', data: form, headers: { ...form.getHeaders() } }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => parseScriptResult(body)) .then(response => Object.assign(response, { recordId: resolvedId })) ) .then(response => resolve(response)) .catch(error => this._save(reject(error))); }); }
JavaScript
run(layout, scripts, parameters, request) { return new Promise((resolve, reject) => this.agent .request( { url: urls.list( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'get', headers: { 'Content-Type': 'application/json' }, params: sanitizeParameters( Object.assign( Array.isArray(scripts) ? { scripts } : isJSON(scripts) ? { scripts: [scripts] } : { script: scripts }, typeof scripts === 'string' && typeof parameters !== 'undefined' ? { 'script.param': parameters } : {}, namespace({ limit: 1 }) ), [ 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', '_limit' ] ) }, typeof scripts === 'string' && typeof parameters !== 'undefined' ? request : parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => pick(parseScriptResult(body), 'scriptResult')) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
run(layout, scripts, parameters, request) { return new Promise((resolve, reject) => this.agent .request( { url: urls.list( this.agent.connection.server, this.agent.connection.database, layout, this.agent.connection.version ), method: 'get', headers: { 'Content-Type': 'application/json' }, params: sanitizeParameters( Object.assign( Array.isArray(scripts) ? { scripts } : isJSON(scripts) ? { scripts: [scripts] } : { script: scripts }, typeof scripts === 'string' && typeof parameters !== 'undefined' ? { 'script.param': parameters } : {}, namespace({ limit: 1 }) ), [ 'script', 'script.param', 'script.prerequest', 'script.prerequest.param', 'script.presort', 'script.presort.param', '_limit' ] ) }, typeof scripts === 'string' && typeof parameters !== 'undefined' ? request : parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => pick(parseScriptResult(body), 'scriptResult')) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
JavaScript
script(layout, script, param = {}, parameters) { return new Promise((resolve, reject) => this.agent .request( { url: urls.script( this.agent.connection.server, this.agent.connection.database, layout, script, this.agent.connection.version ), method: 'get', headers: { 'Content-Type': 'application/json' }, params: !isEmpty(param) ? { 'script.param': isJSON(param) ? JSON.stringify(param) : param.toString() } : param }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => ({ ...body.response, scriptResult: isJSON(body.response.scriptResult) ? JSON.parse(body.response.scriptResult) : body.response.scriptResult })) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
script(layout, script, param = {}, parameters) { return new Promise((resolve, reject) => this.agent .request( { url: urls.script( this.agent.connection.server, this.agent.connection.database, layout, script, this.agent.connection.version ), method: 'get', headers: { 'Content-Type': 'application/json' }, params: !isEmpty(param) ? { 'script.param': isJSON(param) ? JSON.stringify(param) : param.toString() } : param }, parameters ) .then(response => response.data) .then(body => this.data.outgoing(body)) .then(body => this._save(body)) .then(body => ({ ...body.response, scriptResult: isJSON(body.response.scriptResult) ? JSON.parse(body.response.scriptResult) : body.response.scriptResult })) .then(result => resolve(result)) .catch(error => this._save(reject(error))) ); }
JavaScript
function checkAnswer(answer){ correct = myQuestions[currentQuestionIndex].correctAnswer; if (answer === correct && currentQuestionIndex !== finalQuestionIndex){ score++; alert("Correct!"); currentQuestionIndex++; generateQuestion(); //display in the results div that the answer is correct. } else if (answer !== correct && currentQuestionIndex !== finalQuestionIndex) { // If incorrect, subtract 10sec from timer seconds = seconds - timePenalty; alert("Incorrect!") currentQuestionIndex++; generateQuestion(); //display in the results div that the answer is wrong. } else{ openInitPG(); }; }
function checkAnswer(answer){ correct = myQuestions[currentQuestionIndex].correctAnswer; if (answer === correct && currentQuestionIndex !== finalQuestionIndex){ score++; alert("Correct!"); currentQuestionIndex++; generateQuestion(); //display in the results div that the answer is correct. } else if (answer !== correct && currentQuestionIndex !== finalQuestionIndex) { // If incorrect, subtract 10sec from timer seconds = seconds - timePenalty; alert("Incorrect!") currentQuestionIndex++; generateQuestion(); //display in the results div that the answer is wrong. } else{ openInitPG(); }; }
JavaScript
function generateScores(){ initialsContainer.innerHTML = ""; scoreContainer.innerHTML = ""; var highscores = JSON.parse(localStorage.getItem("savedHighscores")) || []; for (i=0; i<highscores.length; i++){ var newNameSpan = document.createElement("li"); var newScoreSpan = document.createElement("li"); newNameSpan.textContent = highscores[i].name; newScoreSpan.textContent = highscores[i].score; initialsContainer.appendChild(newNameSpan); scoreContainer.appendChild(newScoreSpan); } }
function generateScores(){ initialsContainer.innerHTML = ""; scoreContainer.innerHTML = ""; var highscores = JSON.parse(localStorage.getItem("savedHighscores")) || []; for (i=0; i<highscores.length; i++){ var newNameSpan = document.createElement("li"); var newScoreSpan = document.createElement("li"); newNameSpan.textContent = highscores[i].name; newScoreSpan.textContent = highscores[i].score; initialsContainer.appendChild(newNameSpan); scoreContainer.appendChild(newScoreSpan); } }
JavaScript
trim(ago, now = Date.now()) { const times = this.times; const path = this.line.path; const oldest = now-ago; while(times[0] < oldest) { times.shift(); path.shift(); } return this.length; }
trim(ago, now = Date.now()) { const times = this.times; const path = this.line.path; const oldest = now-ago; while(times[0] < oldest) { times.shift(); path.shift(); } return this.length; }
JavaScript
draw() { this.viewport(); // Flow FBO and view renders Object.assign(this.uniforms.render, this.state, { time: this.timer.time, previous: this.particles.buffers[1].color[0].bind(1), viewSize: this.viewSize, viewRes: this.viewRes, colorMap: ((this.colorMap.color && this.colorMap.color[0])? this.colorMap.color[0] : this.colorMap).bind(2), colorMapRes: this.colorMap.shape }); this.particles.render = this.flowShader; // Render to the flow FBO - after the logic render, so particles don't // respond to their own flow. this.flow.bind(); this.gl.lineWidth(Math.max(0, this.state.flowWidth)); this.particles.draw(this.uniforms.render, this.gl.LINES); /** * @todo Mipmaps for global flow sampling - not working at the moment. * @todo Instead of auto-generating mipmaps, should we re-render at each * scale, with different opacities and line widths? This would * mean the influence is spread out when drawing, instead of when * sampling. */ // this.flow.color[0].generateMipmap(); // Render to the view. if(this.buffers.length === 0) { // Render the particles directly to the screen this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); } else { // Multi-buffer passes this.buffers[0].bind(); } if(this.state.autoClearView) { this.clearView(); } if(this.state.autoFade) { this.drawFade(); } // Draw the particles this.particles.render = this.renderShader; this.gl.lineWidth(Math.max(0, this.state.lineWidth)); this.particles.draw(this.uniforms.render, this.gl.LINES); return this; }
draw() { this.viewport(); // Flow FBO and view renders Object.assign(this.uniforms.render, this.state, { time: this.timer.time, previous: this.particles.buffers[1].color[0].bind(1), viewSize: this.viewSize, viewRes: this.viewRes, colorMap: ((this.colorMap.color && this.colorMap.color[0])? this.colorMap.color[0] : this.colorMap).bind(2), colorMapRes: this.colorMap.shape }); this.particles.render = this.flowShader; // Render to the flow FBO - after the logic render, so particles don't // respond to their own flow. this.flow.bind(); this.gl.lineWidth(Math.max(0, this.state.flowWidth)); this.particles.draw(this.uniforms.render, this.gl.LINES); /** * @todo Mipmaps for global flow sampling - not working at the moment. * @todo Instead of auto-generating mipmaps, should we re-render at each * scale, with different opacities and line widths? This would * mean the influence is spread out when drawing, instead of when * sampling. */ // this.flow.color[0].generateMipmap(); // Render to the view. if(this.buffers.length === 0) { // Render the particles directly to the screen this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); } else { // Multi-buffer passes this.buffers[0].bind(); } if(this.state.autoClearView) { this.clearView(); } if(this.state.autoFade) { this.drawFade(); } // Draw the particles this.particles.render = this.renderShader; this.gl.lineWidth(Math.max(0, this.state.lineWidth)); this.particles.draw(this.uniforms.render, this.gl.LINES); return this; }
JavaScript
drawBuffer(index) { this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); if(this.state.autoClearView) { this.gl.clear(this.gl.COLOR_BUFFER_BIT); } return this.copyBuffer(index).stepBuffers(); }
drawBuffer(index) { this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); if(this.state.autoClearView) { this.gl.clear(this.gl.COLOR_BUFFER_BIT); } return this.copyBuffer(index).stepBuffers(); }
JavaScript
copyBuffer(index = 0) { if(index < this.buffers.length) { this.copyShader.bind(); Object.assign(this.copyShader.uniforms, { view: this.buffers[index].color[0].bind(0), viewRes: this.viewRes }); this.screen.render(); } return this; }
copyBuffer(index = 0) { if(index < this.buffers.length) { this.copyShader.bind(); Object.assign(this.copyShader.uniforms, { view: this.buffers[index].color[0].bind(0), viewRes: this.viewRes }); this.screen.render(); } return this; }
JavaScript
spawn(spawner = initSpawner) { this.particles.spawn(spawner); return this; }
spawn(spawner = initSpawner) { this.particles.spawn(spawner); return this; }
JavaScript
spawnShader(shader, update, ...rest) { this.timer.tick(); this.particles.logic = shader; // @todo Allow switching between the particles data and the targets. // Disabling blending here is important this.gl.disable(this.gl.BLEND); this.particles.step(Particles.applyUpdate({ ...this.state, time: this.timer.time, viewSize: this.viewSize, viewRes: this.viewRes }, update), ...rest); this.particles.logic = this.logicShader; this.gl.enable(this.gl.BLEND); this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA); return this; }
spawnShader(shader, update, ...rest) { this.timer.tick(); this.particles.logic = shader; // @todo Allow switching between the particles data and the targets. // Disabling blending here is important this.gl.disable(this.gl.BLEND); this.particles.step(Particles.applyUpdate({ ...this.state, time: this.timer.time, viewSize: this.viewSize, viewRes: this.viewRes }, update), ...rest); this.particles.logic = this.logicShader; this.gl.enable(this.gl.BLEND); this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA); return this; }
JavaScript
step(update, buffer) { if(buffer) { buffer.bind(); } else { step(this.buffers); this.buffers[0].bind(); } this.gl.viewport(0, 0, this.shape[0], this.shape[1]); this.logic.bind(); Particles.applyUpdate(Object.assign(this.logic.uniforms, { dataRes: this.shape, geomRes: this.geomShape, particles: this.buffers[1].color[0].bind(0) }), update); this.screen.render(); this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); }
step(update, buffer) { if(buffer) { buffer.bind(); } else { step(this.buffers); this.buffers[0].bind(); } this.gl.viewport(0, 0, this.shape[0], this.shape[1]); this.logic.bind(); Particles.applyUpdate(Object.assign(this.logic.uniforms, { dataRes: this.shape, geomRes: this.geomShape, particles: this.buffers[1].color[0].bind(0) }), update); this.screen.render(); this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); }
JavaScript
apply(f, out = this.outputs) { this.each((track, key, ...rest) => { const trackOut = (out[key] || (out[key] = {})); return apply(f(track, key, ...rest, trackOut), trackOut); }); return this; }
apply(f, out = this.outputs) { this.each((track, key, ...rest) => { const trackOut = (out[key] || (out[key] = {})); return apply(f(track, key, ...rest, trackOut), trackOut); }); return this; }
JavaScript
add(...frame) { const adding = makeFrame(...frame); const f = this.indexOf(adding); this.insertFrame(f, adding); return f; }
add(...frame) { const adding = makeFrame(...frame); const f = this.indexOf(adding); this.insertFrame(f, adding); return f; }
JavaScript
spliceSpan(duration, start = 0, ...adding) { const a = this.gapAt(start); const b = this.gapAt(start+duration); const i = Math.min(a, b); return this.splice(Math.ceil(i), Math.floor(Math.max(a, b)-i), ...adding); }
spliceSpan(duration, start = 0, ...adding) { const a = this.gapAt(start); const b = this.gapAt(start+duration); const i = Math.min(a, b); return this.splice(Math.ceil(i), Math.floor(Math.max(a, b)-i), ...adding); }
JavaScript
to(...frame) { this.add(...frame); return this; }
to(...frame) { this.add(...frame); return this; }
JavaScript
easeJoin(f, align) { let ease = null; if(f > 0) { const frame = this.frames[f]; ease = ((frame.ease && frame.ease.length)? frame.ease : [0, 1]); ease.splice(1, 0, joinCurve(this.frames[f-1].ease, align)); frame.ease = ease; } return ease; }
easeJoin(f, align) { let ease = null; if(f > 0) { const frame = this.frames[f]; ease = ((frame.ease && frame.ease.length)? frame.ease : [0, 1]); ease.splice(1, 0, joinCurve(this.frames[f-1].ease, align)); frame.ease = ease; } return ease; }
JavaScript
sample(dt = 1, method = 'frequencies') { this.analyser[method](step(this.orderLog[0])); orderLogRates(this.orderLog, dt); return this; }
sample(dt = 1, method = 'frequencies') { this.analyser[method](step(this.orderLog[0])); orderLogRates(this.orderLog, dt); return this; }
JavaScript
function processBundle(resolve, reject) { var bundle = this; // Apply particular options if global settings dictate source files should be referenced inside sourcemaps. var sourcemapOptions = {}; if (globalSettings.sourcemapOptions.type === 'External_ReferencedFiles') { sourcemapOptions.includeContent = false; sourcemapOptions.sourceRoot = globalSettings.sourcemapOptions.sourceRoot; } // Determine the output folder. Use a specified folder if one // is set, else use the generic output folder. var outputDirectory = (bundle.outputFolder || styleSettings.destPath); // Compile SASS into CSS then prefix and save. var stream = gulp.src(bundle.sourcePaths) .pipe(plumber()) .pipe(rename(function(path) { path.basename = (bundle.outputFileName || path.basename.replace(/\.main$/gi, '')); })) .pipe(sourcemaps.init()) .pipe(sass(styleSettings.sassSettings).on('error', sass.logError)) .pipe(prefix(styleSettings.autoPrefixSettings)) .pipe(sourcemaps.write('./', sourcemapOptions)) .pipe(gulp.dest(outputDirectory)); // Whenever the stream finishes, resolve or reject the deferred accordingly. stream.on('error', function() { console.log(chalk.bgRed.white(' FE Skeleton: Stylesheet Failed.')); reject(); }) .on('end', function() { console.log(chalk.bgGreen.white(' FE Skeleton: Stylesheet Completed - '+[].concat(bundle.sourcePaths).join(', '))); resolve(); }); }
function processBundle(resolve, reject) { var bundle = this; // Apply particular options if global settings dictate source files should be referenced inside sourcemaps. var sourcemapOptions = {}; if (globalSettings.sourcemapOptions.type === 'External_ReferencedFiles') { sourcemapOptions.includeContent = false; sourcemapOptions.sourceRoot = globalSettings.sourcemapOptions.sourceRoot; } // Determine the output folder. Use a specified folder if one // is set, else use the generic output folder. var outputDirectory = (bundle.outputFolder || styleSettings.destPath); // Compile SASS into CSS then prefix and save. var stream = gulp.src(bundle.sourcePaths) .pipe(plumber()) .pipe(rename(function(path) { path.basename = (bundle.outputFileName || path.basename.replace(/\.main$/gi, '')); })) .pipe(sourcemaps.init()) .pipe(sass(styleSettings.sassSettings).on('error', sass.logError)) .pipe(prefix(styleSettings.autoPrefixSettings)) .pipe(sourcemaps.write('./', sourcemapOptions)) .pipe(gulp.dest(outputDirectory)); // Whenever the stream finishes, resolve or reject the deferred accordingly. stream.on('error', function() { console.log(chalk.bgRed.white(' FE Skeleton: Stylesheet Failed.')); reject(); }) .on('end', function() { console.log(chalk.bgGreen.white(' FE Skeleton: Stylesheet Completed - '+[].concat(bundle.sourcePaths).join(', '))); resolve(); }); }
JavaScript
function makeAnalyser(...rest) { const a = analyser(...rest); const gain = a.gain = a.ctx.createGain(); const out = (a.splitter || a.analyser); a.source.disconnect(); a.source.connect(gain).connect(out); return a; }
function makeAnalyser(...rest) { const a = analyser(...rest); const gain = a.gain = a.ctx.createGain(); const out = (a.splitter || a.analyser); a.source.disconnect(); a.source.connect(gain).connect(out); return a; }
JavaScript
function runWebpack(taskOptions) { // Ensure there is an options object (incase none were supplied to this function). taskOptions = (taskOptions || {}); // Bind a shorter reference to the script settings from the global file. var scriptSettings = globalSettings.taskConfiguration.scripts; // If production argument was specified then add UglifyJS plugin into webpack. if(args.hasOwnProperty('is-production') && args['is-production'] === true) { scriptSettings.webpackSettings.plugins .push(new webpack.optimize.UglifyJsPlugin(scriptSettings.uglifySettings)); } // Asking webpack to watch will keep the process running until it's cancelled. if(taskOptions.watch) { scriptSettings.webpackSettings.watch = true; } // Open a stream, trigger webpack-stream compilation and push output to file system. return gulp.src(scriptSettings.sourcePaths) // Pass a named file stream to webpack, for multiple entry points .pipe(named((file) => file.relative.replace(/\.main\.js$/gi, ''))) .pipe(webpackStream(scriptSettings.webpackSettings)) .pipe(gulp.dest(scriptSettings.destPath)); }
function runWebpack(taskOptions) { // Ensure there is an options object (incase none were supplied to this function). taskOptions = (taskOptions || {}); // Bind a shorter reference to the script settings from the global file. var scriptSettings = globalSettings.taskConfiguration.scripts; // If production argument was specified then add UglifyJS plugin into webpack. if(args.hasOwnProperty('is-production') && args['is-production'] === true) { scriptSettings.webpackSettings.plugins .push(new webpack.optimize.UglifyJsPlugin(scriptSettings.uglifySettings)); } // Asking webpack to watch will keep the process running until it's cancelled. if(taskOptions.watch) { scriptSettings.webpackSettings.watch = true; } // Open a stream, trigger webpack-stream compilation and push output to file system. return gulp.src(scriptSettings.sourcePaths) // Pass a named file stream to webpack, for multiple entry points .pipe(named((file) => file.relative.replace(/\.main\.js$/gi, ''))) .pipe(webpackStream(scriptSettings.webpackSettings)) .pipe(gulp.dest(scriptSettings.destPath)); }
JavaScript
function firebaseConfig() { const config = { apiKey: "AIzaSyBpHwvxDeJ3W7c0YArgP1XSIiMmsCANo68", authDomain: "firstfbproyect.firebaseapp.com", projectId: "firstfbproyect", storageBucket: "firstfbproyect.appspot.com", messagingSenderId: "888798996437", appId: "1:888798996437:web:18e424580075bd453a3f5c", measurementId: "G-EJYHB67FYW" }; // Initialize Firebase const app = initializeApp(config); const analytics = getAnalytics(app); }
function firebaseConfig() { const config = { apiKey: "AIzaSyBpHwvxDeJ3W7c0YArgP1XSIiMmsCANo68", authDomain: "firstfbproyect.firebaseapp.com", projectId: "firstfbproyect", storageBucket: "firstfbproyect.appspot.com", messagingSenderId: "888798996437", appId: "1:888798996437:web:18e424580075bd453a3f5c", measurementId: "G-EJYHB67FYW" }; // Initialize Firebase const app = initializeApp(config); const analytics = getAnalytics(app); }
JavaScript
function merge(source, dependencies) { return function output() { const mergedFiles = mergeStream(source(), dependencies()) .pipe(project.analyzer); const bundleType = global.config.build.bundleType; let outputs = []; if (bundleType === 'both' || bundleType === 'bundled') { outputs.push(writeBundledOutput(polymer.forkStream(mergedFiles))); } if (bundleType === 'both' || bundleType === 'unbundled') { outputs.push(writeUnbundledOutput(polymer.forkStream(mergedFiles))); } return Promise.all(outputs); }; }
function merge(source, dependencies) { return function output() { const mergedFiles = mergeStream(source(), dependencies()) .pipe(project.analyzer); const bundleType = global.config.build.bundleType; let outputs = []; if (bundleType === 'both' || bundleType === 'bundled') { outputs.push(writeBundledOutput(polymer.forkStream(mergedFiles))); } if (bundleType === 'both' || bundleType === 'unbundled') { outputs.push(writeUnbundledOutput(polymer.forkStream(mergedFiles))); } return Promise.all(outputs); }; }
JavaScript
function writeBundledOutput(stream) { return new Promise(resolve => { stream.pipe(project.bundler) .pipe(gulp.dest(bundledPath)) .on('end', resolve); }); }
function writeBundledOutput(stream) { return new Promise(resolve => { stream.pipe(project.bundler) .pipe(gulp.dest(bundledPath)) .on('end', resolve); }); }
JavaScript
function writeBundledServiceWorker() { // On windows if we pass the path with back slashes the sw-precache node module is not going // to strip the build/bundled or build/unbundled because the path was passed in with back slash. return polymer.addServiceWorker({ project: project, buildRoot: bundledPath.replace('\\', '/'), swConfig: global.config.swPrecacheConfig, serviceWorkerPath: global.config.serviceWorkerPath, bundled: true }); }
function writeBundledServiceWorker() { // On windows if we pass the path with back slashes the sw-precache node module is not going // to strip the build/bundled or build/unbundled because the path was passed in with back slash. return polymer.addServiceWorker({ project: project, buildRoot: bundledPath.replace('\\', '/'), swConfig: global.config.swPrecacheConfig, serviceWorkerPath: global.config.serviceWorkerPath, bundled: true }); }
JavaScript
function writeUnbundledServiceWorker() { return polymer.addServiceWorker({ project: project, buildRoot: unbundledPath.replace('\\', '/'), swConfig: global.config.swPrecacheConfig, serviceWorkerPath: global.config.serviceWorkerPath }); }
function writeUnbundledServiceWorker() { return polymer.addServiceWorker({ project: project, buildRoot: unbundledPath.replace('\\', '/'), swConfig: global.config.swPrecacheConfig, serviceWorkerPath: global.config.serviceWorkerPath }); }
JavaScript
function writable(value, start = _internal__WEBPACK_IMPORTED_MODULE_0__["noop"]) { let stop; const subscribers = []; function set(new_value) { if (Object(_internal__WEBPACK_IMPORTED_MODULE_0__["safe_not_equal"])(value, new_value)) { value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (let i = 0; i < subscribers.length; i += 1) { const s = subscribers[i]; s[1](); subscriber_queue.push(s, value); } if (run_queue) { for (let i = 0; i < subscriber_queue.length; i += 2) { subscriber_queue[i][0](subscriber_queue[i + 1]); } subscriber_queue.length = 0; } } } } function update(fn) { set(fn(value)); } function subscribe(run, invalidate = _internal__WEBPACK_IMPORTED_MODULE_0__["noop"]) { const subscriber = [run, invalidate]; subscribers.push(subscriber); if (subscribers.length === 1) { stop = start(set) || _internal__WEBPACK_IMPORTED_MODULE_0__["noop"]; } run(value); return () => { const index = subscribers.indexOf(subscriber); if (index !== -1) { subscribers.splice(index, 1); } if (subscribers.length === 0) { stop(); stop = null; } }; } return { set, update, subscribe }; }
function writable(value, start = _internal__WEBPACK_IMPORTED_MODULE_0__["noop"]) { let stop; const subscribers = []; function set(new_value) { if (Object(_internal__WEBPACK_IMPORTED_MODULE_0__["safe_not_equal"])(value, new_value)) { value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (let i = 0; i < subscribers.length; i += 1) { const s = subscribers[i]; s[1](); subscriber_queue.push(s, value); } if (run_queue) { for (let i = 0; i < subscriber_queue.length; i += 2) { subscriber_queue[i][0](subscriber_queue[i + 1]); } subscriber_queue.length = 0; } } } } function update(fn) { set(fn(value)); } function subscribe(run, invalidate = _internal__WEBPACK_IMPORTED_MODULE_0__["noop"]) { const subscriber = [run, invalidate]; subscribers.push(subscriber); if (subscribers.length === 1) { stop = start(set) || _internal__WEBPACK_IMPORTED_MODULE_0__["noop"]; } run(value); return () => { const index = subscribers.indexOf(subscriber); if (index !== -1) { subscribers.splice(index, 1); } if (subscribers.length === 0) { stop(); stop = null; } }; } return { set, update, subscribe }; }
JavaScript
_sendIntentSuccess(intentObj, req, res) { let data = { result: intentObj.result() }; try { data.result = data.result.toJSON(); } catch (e) { } handleIntentSuccess(req, res, null, data, intentObj); }
_sendIntentSuccess(intentObj, req, res) { let data = { result: intentObj.result() }; try { data.result = data.result.toJSON(); } catch (e) { } handleIntentSuccess(req, res, null, data, intentObj); }
JavaScript
_requestUniqueId() { if (uniqueRequestId >= MAX_REQUEST_ID) { uniqueRequestId = 0; } return uniqueRequestId++; }
_requestUniqueId() { if (uniqueRequestId >= MAX_REQUEST_ID) { uniqueRequestId = 0; } return uniqueRequestId++; }
JavaScript
addHandler(actionObj, verb, url) { if (typeof this[actions][actionObj.name] === 'undefined') { this[actions][actionObj.name] = actionObj; } // check if it is a match. let match = actionObj.__getMatch(); if (match.length > 0) { for (let i = 0; i < match.length; i++) { this[actionPatterns].push({ match: match[i], action: actionObj.name }); } } if (typeof verb !== 'string') return true; // handled throught default handler verb = verb.toLowerCase(); url = path.normalize(this[config].basePath + '/' + url); url = url.replace(/\\/g, '/'); if (this.running) { registerActionPath.call(this, verb, url, actionObj.name); return this; } let item = { verb: verb, url: url, name: actionObj.name }; this[paths].push(item); return this; }
addHandler(actionObj, verb, url) { if (typeof this[actions][actionObj.name] === 'undefined') { this[actions][actionObj.name] = actionObj; } // check if it is a match. let match = actionObj.__getMatch(); if (match.length > 0) { for (let i = 0; i < match.length; i++) { this[actionPatterns].push({ match: match[i], action: actionObj.name }); } } if (typeof verb !== 'string') return true; // handled throught default handler verb = verb.toLowerCase(); url = path.normalize(this[config].basePath + '/' + url); url = url.replace(/\\/g, '/'); if (this.running) { registerActionPath.call(this, verb, url, actionObj.name); return this; } let item = { verb: verb, url: url, name: actionObj.name }; this[paths].push(item); return this; }
JavaScript
listen(done) { const app = express(); configureApp(app, this[config]); // Configure Helmet configureHelmet(app, this[config].helmet); // handle CORS registerCors(app, this[config].cors, this[config].corsIgnore); // Handle static assets registerStaticPaths(app, this[config].static); // Handle middleware registerMiddleware.call(this, app, this[config]); this[server] = app; let isDone = false; this[httpServer] = app.listen(this[config].port, this[config].ip, (e) => { if (e) return done(e); if (isDone) return; logger('info', 'Listening on port %s', this[config].port); this.running = true; if (this[defaultHandlerPath].length > 0) { registerDefaultAction.call(this, defaultHandlerVerb, this[defaultHandlerPath]); } for (let i = 0; i < this[paths].length; i++) { let item = this[paths][i]; registerActionPath.call(this, item.verb, item.url, item.name); } this[paths] = null; app.use(handleRequestNotFound.bind(this)); app.use(handleRequestError.bind(this)); isDone = true; done(); }); this[httpServer].on('error', (e) => { if (!isDone) { isDone = true; if (e.code === 'EADDRINUSE') { return done(thorin.error('TRANSPORT.PORT_IN_USE', `The port ${this[config].port} or ip ${this[config].ip} is already in use.`)); } return done(thorin.error(e)); } logger.warn('Thorin HTTP Transport encountered an error:', e); }); }
listen(done) { const app = express(); configureApp(app, this[config]); // Configure Helmet configureHelmet(app, this[config].helmet); // handle CORS registerCors(app, this[config].cors, this[config].corsIgnore); // Handle static assets registerStaticPaths(app, this[config].static); // Handle middleware registerMiddleware.call(this, app, this[config]); this[server] = app; let isDone = false; this[httpServer] = app.listen(this[config].port, this[config].ip, (e) => { if (e) return done(e); if (isDone) return; logger('info', 'Listening on port %s', this[config].port); this.running = true; if (this[defaultHandlerPath].length > 0) { registerDefaultAction.call(this, defaultHandlerVerb, this[defaultHandlerPath]); } for (let i = 0; i < this[paths].length; i++) { let item = this[paths][i]; registerActionPath.call(this, item.verb, item.url, item.name); } this[paths] = null; app.use(handleRequestNotFound.bind(this)); app.use(handleRequestError.bind(this)); isDone = true; done(); }); this[httpServer].on('error', (e) => { if (!isDone) { isDone = true; if (e.code === 'EADDRINUSE') { return done(thorin.error('TRANSPORT.PORT_IN_USE', `The port ${this[config].port} or ip ${this[config].ip} is already in use.`)); } return done(thorin.error(e)); } logger.warn('Thorin HTTP Transport encountered an error:', e); }); }
JavaScript
function configureApp(app, config) { app.set('query parser', 'simple'); app.set('x-powered-by', false); if (thorin.env === 'production') { app.set('env', 'production'); } app.set('views', undefined); app.set('view cache', false); if (config.trustProxy) { app.set('trust proxy', true); } }
function configureApp(app, config) { app.set('query parser', 'simple'); app.set('x-powered-by', false); if (thorin.env === 'production') { app.set('env', 'production'); } app.set('views', undefined); app.set('view cache', false); if (config.trustProxy) { app.set('trust proxy', true); } }
JavaScript
function registerMiddleware(app, config) { /* Check for basic auth */ if (config.authorization && typeof config.authorization.basic === 'object' && config.authorization.basic) { registerBasicAuth(app, config.authorization.basic); } // Check if we have favicon registerFavicon(app, config); /* Parse root middlewares. */ for (let i = 0; i < this[rootMiddleware].length; i++) { app.use(this[rootMiddleware][i]); } delete this[rootMiddleware]; /* Parse Form data */ app.use(bodyParser.urlencoded({ extended: false, limit: config.options.payloadLimit, parameterLimit: 500 })); /* Parse JSON in the body */ app.use(bodyParser.json({ limit: config.options.payloadLimit })); /* Parse raw text */ if (config.rawText) { app.use(bodyParser.text({ type: 'text/*', limit: config.options.payloadLimit })); } /* attach any middleware */ for (let i = 0; i < this[middleware].length; i++) { app.use(this[middleware][i]); } this[middleware] = []; }
function registerMiddleware(app, config) { /* Check for basic auth */ if (config.authorization && typeof config.authorization.basic === 'object' && config.authorization.basic) { registerBasicAuth(app, config.authorization.basic); } // Check if we have favicon registerFavicon(app, config); /* Parse root middlewares. */ for (let i = 0; i < this[rootMiddleware].length; i++) { app.use(this[rootMiddleware][i]); } delete this[rootMiddleware]; /* Parse Form data */ app.use(bodyParser.urlencoded({ extended: false, limit: config.options.payloadLimit, parameterLimit: 500 })); /* Parse JSON in the body */ app.use(bodyParser.json({ limit: config.options.payloadLimit })); /* Parse raw text */ if (config.rawText) { app.use(bodyParser.text({ type: 'text/*', limit: config.options.payloadLimit })); } /* attach any middleware */ for (let i = 0; i < this[middleware].length; i++) { app.use(this[middleware][i]); } this[middleware] = []; }
JavaScript
function handleRequestError(err, req, res, next) { // In order to make errors visible, we have to set CORS for em. let intentObj; if (req.intent) { intentObj = req.intent; delete req.intent; } setCors.call(this, req, res, req.method); let reqErr, reqData, statusCode = 400; if (err instanceof SyntaxError) { // any other error, we bubble up. reqErr = thorin.error(PARSE_ERROR_CODE, 'Invalid payload.', err); statusCode = 400; reqData = { error: reqErr.toJSON() }; } else if (err instanceof Error && err.name.indexOf('Thorin') === 0) { reqErr = err; statusCode = err.statusCode || 400; reqData = { error: reqErr.toJSON() }; } else if (typeof err === 'object' && err.type) { if (err.type === 'entity.too.large') { reqErr = thorin.error(PARSE_ERROR_CODE, 'Payload too large', err.statusCode); } else { reqErr = thorin.error(err.error); } reqData = { error: reqErr.toJSON() }; statusCode = reqErr && reqErr.statusCode || 400; } else { switch (err.status) { case 415: // encoding unsupported. reqErr = thorin.error(PARSE_ERROR_CODE, 'Encoding unsupported', err); break; case 400: // aborted reqErr = thorin.error(PARSE_ERROR_CODE, 'Request aborted', err); break; case 413: // payload large reqErr = thorin.error(PARSE_ERROR_CODE, 'Payload too large', err); break; default: reqErr = thorin.error(err); statusCode = 500; } reqData = { error: reqErr.toJSON() }; } try { res.status(statusCode); } catch (e) { } let logErr; // TODO: include the HTML 404 not found pages. if (req._hasDebug !== false) { let logMsg = '[ENDED', logLevel = 'trace'; if (req.uniqueId) { logMsg += ' ' + req.uniqueId; } logMsg += '] -'; if (req.action) logMsg += ' ' + req.action; logMsg += " (" + req.method.toUpperCase() + ' ' + req.originalUrl.substr(0, 64) + ') '; logMsg += '= ' + statusCode + ' '; if (statusCode === 404) { if (reqErr.code !== 'TRANSPORT.NOT_FOUND') { logMsg += '[' + reqErr.code + '] '; } logMsg += reqErr.message; } else if (statusCode < 500) { logMsg += '[' + reqErr.code + '] ' + reqErr.message; } else { logMsg += '[' + reqErr.code + ']'; logLevel = 'warn'; logErr = reqErr; } if (req.startAt) { let took = Date.now() - req.startAt; logMsg += " (" + took + "ms)"; } logger(logLevel, logMsg, logErr); } try { if (this[config].debug && logErr.source) { logger('warn', logErr.source.stack); } } catch (e) { } // Check if we have a buffer in our rawData if (err.rawData instanceof Buffer) { try { res.set({ 'Content-Type': 'application/octet-stream' }); } catch (e) { } try { res.end(err.rawData); } catch (e) { console.error('Thorin.transport.http: failed to send error buffer to response.'); console.debug(e); try { res.end(); } catch (e) { } } return; } if (typeof err.rawData === 'string') { try { res.type('html'); } catch (e) { } try { res.end(err.rawData); } catch (e) { console.error('Thorin.transport.http: failed to send error string to response.'); console.debug(e); try { res.end(); } catch (e) { } } return; } try { if (req.exposeType === false && reqData.type) { delete reqData.type; } try { reqData = this.parseIntentJson(reqData, null, req, intentObj); } catch (e) { } res.header('content-type', 'application/json; charset=utf-8'); reqData = JSON.stringify(reqData); res.end(reqData); } catch (e) { console.error('Thorin.transport.http: failed to finalize request with error: ', reqErr); console.error(e); try { res.end(reqErr.message); } catch (e) { try { res.end(); } catch (e) { } } } }
function handleRequestError(err, req, res, next) { // In order to make errors visible, we have to set CORS for em. let intentObj; if (req.intent) { intentObj = req.intent; delete req.intent; } setCors.call(this, req, res, req.method); let reqErr, reqData, statusCode = 400; if (err instanceof SyntaxError) { // any other error, we bubble up. reqErr = thorin.error(PARSE_ERROR_CODE, 'Invalid payload.', err); statusCode = 400; reqData = { error: reqErr.toJSON() }; } else if (err instanceof Error && err.name.indexOf('Thorin') === 0) { reqErr = err; statusCode = err.statusCode || 400; reqData = { error: reqErr.toJSON() }; } else if (typeof err === 'object' && err.type) { if (err.type === 'entity.too.large') { reqErr = thorin.error(PARSE_ERROR_CODE, 'Payload too large', err.statusCode); } else { reqErr = thorin.error(err.error); } reqData = { error: reqErr.toJSON() }; statusCode = reqErr && reqErr.statusCode || 400; } else { switch (err.status) { case 415: // encoding unsupported. reqErr = thorin.error(PARSE_ERROR_CODE, 'Encoding unsupported', err); break; case 400: // aborted reqErr = thorin.error(PARSE_ERROR_CODE, 'Request aborted', err); break; case 413: // payload large reqErr = thorin.error(PARSE_ERROR_CODE, 'Payload too large', err); break; default: reqErr = thorin.error(err); statusCode = 500; } reqData = { error: reqErr.toJSON() }; } try { res.status(statusCode); } catch (e) { } let logErr; // TODO: include the HTML 404 not found pages. if (req._hasDebug !== false) { let logMsg = '[ENDED', logLevel = 'trace'; if (req.uniqueId) { logMsg += ' ' + req.uniqueId; } logMsg += '] -'; if (req.action) logMsg += ' ' + req.action; logMsg += " (" + req.method.toUpperCase() + ' ' + req.originalUrl.substr(0, 64) + ') '; logMsg += '= ' + statusCode + ' '; if (statusCode === 404) { if (reqErr.code !== 'TRANSPORT.NOT_FOUND') { logMsg += '[' + reqErr.code + '] '; } logMsg += reqErr.message; } else if (statusCode < 500) { logMsg += '[' + reqErr.code + '] ' + reqErr.message; } else { logMsg += '[' + reqErr.code + ']'; logLevel = 'warn'; logErr = reqErr; } if (req.startAt) { let took = Date.now() - req.startAt; logMsg += " (" + took + "ms)"; } logger(logLevel, logMsg, logErr); } try { if (this[config].debug && logErr.source) { logger('warn', logErr.source.stack); } } catch (e) { } // Check if we have a buffer in our rawData if (err.rawData instanceof Buffer) { try { res.set({ 'Content-Type': 'application/octet-stream' }); } catch (e) { } try { res.end(err.rawData); } catch (e) { console.error('Thorin.transport.http: failed to send error buffer to response.'); console.debug(e); try { res.end(); } catch (e) { } } return; } if (typeof err.rawData === 'string') { try { res.type('html'); } catch (e) { } try { res.end(err.rawData); } catch (e) { console.error('Thorin.transport.http: failed to send error string to response.'); console.debug(e); try { res.end(); } catch (e) { } } return; } try { if (req.exposeType === false && reqData.type) { delete reqData.type; } try { reqData = this.parseIntentJson(reqData, null, req, intentObj); } catch (e) { } res.header('content-type', 'application/json; charset=utf-8'); reqData = JSON.stringify(reqData); res.end(reqData); } catch (e) { console.error('Thorin.transport.http: failed to finalize request with error: ', reqErr); console.error(e); try { res.end(reqErr.message); } catch (e) { try { res.end(); } catch (e) { } } } }
JavaScript
function registerCors(app, corsConfig, corsIgnore) { if (corsConfig === false) return; let domains = []; if (typeof corsConfig === 'string') { domains = corsConfig.split(' '); } else if (corsConfig instanceof Array) { domains = corsConfig; } app.use((req, res, next) => { let origin = req.headers['origin'] || req.headers['referer'] || null, shouldAddHeaders = false, rawOrigin = origin; if (typeof rawOrigin === 'string') { let qsIdx = rawOrigin.indexOf('?'); if (qsIdx !== -1) { rawOrigin = rawOrigin.substr(0, qsIdx); } } if (corsConfig === true) { shouldAddHeaders = true; } else if (domains.length > 0 && typeof origin === 'string') { origin = getRawOrigin(origin); for (let i = 0; i < domains.length; i++) { let domain = domains[i], isMatch = matchCorsOrigin(domain, origin, rawOrigin); if (isMatch) { shouldAddHeaders = true; break; } } } if (!shouldAddHeaders) return next(); // CHECK if we have corsIgnore in settings let ignoreHosts; if (typeof corsIgnore === 'string') { ignoreHosts = [corsIgnore]; } else if (corsIgnore instanceof Array) { ignoreHosts = corsIgnore; } if (ignoreHosts instanceof Array) { origin = getRawOrigin(origin); for (let i = 0; i < ignoreHosts.length; i++) { let domain = ignoreHosts[i], isMatch = matchCorsOrigin(domain, origin, rawOrigin); if (isMatch) return next; } } res.header('Access-Control-Allow-Origin', rawOrigin || '*'); res.header('Access-Control-Allow-Methods', CORS_METHODS); res.header('Access-Control-Allow-Credentials', 'true'); res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers'] || '*'); res.header('Access-Control-Max-Age', '600'); next(); }); }
function registerCors(app, corsConfig, corsIgnore) { if (corsConfig === false) return; let domains = []; if (typeof corsConfig === 'string') { domains = corsConfig.split(' '); } else if (corsConfig instanceof Array) { domains = corsConfig; } app.use((req, res, next) => { let origin = req.headers['origin'] || req.headers['referer'] || null, shouldAddHeaders = false, rawOrigin = origin; if (typeof rawOrigin === 'string') { let qsIdx = rawOrigin.indexOf('?'); if (qsIdx !== -1) { rawOrigin = rawOrigin.substr(0, qsIdx); } } if (corsConfig === true) { shouldAddHeaders = true; } else if (domains.length > 0 && typeof origin === 'string') { origin = getRawOrigin(origin); for (let i = 0; i < domains.length; i++) { let domain = domains[i], isMatch = matchCorsOrigin(domain, origin, rawOrigin); if (isMatch) { shouldAddHeaders = true; break; } } } if (!shouldAddHeaders) return next(); // CHECK if we have corsIgnore in settings let ignoreHosts; if (typeof corsIgnore === 'string') { ignoreHosts = [corsIgnore]; } else if (corsIgnore instanceof Array) { ignoreHosts = corsIgnore; } if (ignoreHosts instanceof Array) { origin = getRawOrigin(origin); for (let i = 0; i < ignoreHosts.length; i++) { let domain = ignoreHosts[i], isMatch = matchCorsOrigin(domain, origin, rawOrigin); if (isMatch) return next; } } res.header('Access-Control-Allow-Origin', rawOrigin || '*'); res.header('Access-Control-Allow-Methods', CORS_METHODS); res.header('Access-Control-Allow-Credentials', 'true'); res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers'] || '*'); res.header('Access-Control-Max-Age', '600'); next(); }); }
JavaScript
function parseRequestInput(source, target) { let keys = Object.keys(source); if (keys.length === 1) { // Check if we have our main key as the full JSON let tmp = keys[0], shouldParse = false; tmp = tmp.trim(); if (tmp.charAt(0) === '{') { for (let i = 0; i < Math.min(tmp.length, 100); i++) { if (tmp[i] === '"') { shouldParse = true; break; } } if (shouldParse) { try { source = JSON.parse(tmp); keys = Object.keys(source); } catch (e) { return; } } } } keys.forEach((name) => { if (name == null || typeof name === 'undefined') return; target[name] = source[name]; }); }
function parseRequestInput(source, target) { let keys = Object.keys(source); if (keys.length === 1) { // Check if we have our main key as the full JSON let tmp = keys[0], shouldParse = false; tmp = tmp.trim(); if (tmp.charAt(0) === '{') { for (let i = 0; i < Math.min(tmp.length, 100); i++) { if (tmp[i] === '"') { shouldParse = true; break; } } if (shouldParse) { try { source = JSON.parse(tmp); keys = Object.keys(source); } catch (e) { return; } } } } keys.forEach((name) => { if (name == null || typeof name === 'undefined') return; target[name] = source[name]; }); }
JavaScript
function handleIntentSuccess(req, res, next, data, intentObj) { let took = Date.now() - req.startAt, status = 200, isDone = false; /* IF we already have a status code, we just end the rqeuest right here. */ try { if (typeof res.statusCode !== 'number') { res.status(status); } if (res.headersSent) { isDone = true; } } catch (e) { } if (isDone) { try { res.end(); } catch (e) { } } else { // We're sending a string or HTML let contentType = res.get('content-type'); if (typeof data === 'string') { if (!contentType) { let isHtml = data.indexOf("DOCTYPE ") !== -1 || data.indexOf("<html") !== -1 || data.indexOf("</") !== -1 || data.indexOf("/>") !== -1; if (isHtml) { res.type('html'); } else { res.type('text'); } } res.end(data); } else if (data instanceof Buffer) { // we have a buffer, possibly a download occurring try { if (!contentType) { res.set({ 'Content-Type': 'application/octet-stream' }); } res.send(data); } catch (e) { console.error('Thorin.transport.http: failed to send buffer to response.'); console.debug(e); } } else if (typeof data === 'object' && data != null) { try { try { data.result = data.result.toJSON(); } catch (e) { } if (req.exposeType === false && data.type) { delete data.type; } try { data = this.parseIntentJson(null, data, req, intentObj); } catch (e) { } data = JSON.stringify(data); res.header('content-type', 'application/json'); res.end(data); } catch (e) { console.error('Thorin.transport.http: failed to handleIntentSuccess', e); try { res.end(); } catch (e) { } } } else { res.end(data); } } if (req._hasDebug !== false) { let logMsg = '[ENDED ' + req.uniqueId + "] - "; logMsg += req.action + ' '; logMsg += "(" + req.method.toUpperCase() + ' ' + req.originalUrl.substr(0, 64) + ') '; logMsg += '= ' + status + ' '; logMsg += '(' + took + 'ms)'; logger('trace', logMsg); } }
function handleIntentSuccess(req, res, next, data, intentObj) { let took = Date.now() - req.startAt, status = 200, isDone = false; /* IF we already have a status code, we just end the rqeuest right here. */ try { if (typeof res.statusCode !== 'number') { res.status(status); } if (res.headersSent) { isDone = true; } } catch (e) { } if (isDone) { try { res.end(); } catch (e) { } } else { // We're sending a string or HTML let contentType = res.get('content-type'); if (typeof data === 'string') { if (!contentType) { let isHtml = data.indexOf("DOCTYPE ") !== -1 || data.indexOf("<html") !== -1 || data.indexOf("</") !== -1 || data.indexOf("/>") !== -1; if (isHtml) { res.type('html'); } else { res.type('text'); } } res.end(data); } else if (data instanceof Buffer) { // we have a buffer, possibly a download occurring try { if (!contentType) { res.set({ 'Content-Type': 'application/octet-stream' }); } res.send(data); } catch (e) { console.error('Thorin.transport.http: failed to send buffer to response.'); console.debug(e); } } else if (typeof data === 'object' && data != null) { try { try { data.result = data.result.toJSON(); } catch (e) { } if (req.exposeType === false && data.type) { delete data.type; } try { data = this.parseIntentJson(null, data, req, intentObj); } catch (e) { } data = JSON.stringify(data); res.header('content-type', 'application/json'); res.end(data); } catch (e) { console.error('Thorin.transport.http: failed to handleIntentSuccess', e); try { res.end(); } catch (e) { } } } else { res.end(data); } } if (req._hasDebug !== false) { let logMsg = '[ENDED ' + req.uniqueId + "] - "; logMsg += req.action + ' '; logMsg += "(" + req.method.toUpperCase() + ' ' + req.originalUrl.substr(0, 64) + ') '; logMsg += '= ' + status + ' '; logMsg += '(' + took + 'ms)'; logger('trace', logMsg); } }
JavaScript
function handleIntentError(req, res, next, data, intentObj) { if (intentObj.hasRawResult()) { data.rawData = intentObj.result(); } req.intent = intentObj; return handleRequestError.call(this, data, req, res, next); }
function handleIntentError(req, res, next, data, intentObj) { if (intentObj.hasRawResult()) { data.rawData = intentObj.result(); } req.intent = intentObj; return handleRequestError.call(this, data, req, res, next); }
JavaScript
function registerActionPath(verb, url, actionName) { var app = this[server]; var reqHandler = handleIncomingRequest.bind(this, actionName, url); app[verb](url, reqHandler); // We have to insert the action handler right before the notfound handler. let requestLayer = app._router.stack.pop(); // last one added let wasInserted = false; for (let i = 0; i < app._router.stack.length; i++) { if (app._router.stack[i].name === 'bound handleRequestNotFound') { app._router.stack.splice(i, 0, requestLayer); wasInserted = true; break; } } if (!wasInserted) { app._router.stack.push(requestLayer); } }
function registerActionPath(verb, url, actionName) { var app = this[server]; var reqHandler = handleIncomingRequest.bind(this, actionName, url); app[verb](url, reqHandler); // We have to insert the action handler right before the notfound handler. let requestLayer = app._router.stack.pop(); // last one added let wasInserted = false; for (let i = 0; i < app._router.stack.length; i++) { if (app._router.stack[i].name === 'bound handleRequestNotFound') { app._router.stack.splice(i, 0, requestLayer); wasInserted = true; break; } } if (!wasInserted) { app._router.stack.push(requestLayer); } }
JavaScript
init(httpConfig) { this[config] = thorin.util.extend({ debug: true, port: 3000, basePath: '/', actionPath: '/dispatch', // this is the default frux listener for incoming frux actions. authorization: { "header": "Authorization", // By default, we will look into the "Authorization: Bearer" header "basic": null // if set to {user,password}, we will apply basic authorization for it. This can be used for fast prototyping of password protected apps. //"cookie": "tps" }, ip: '0.0.0.0', cors: false, // Cross origin requests. If set a string, we'll use the domain as the origin, or an array of domains. corsIgnore: null, // If specified, we will ignore these hosts in CORS requests. Array or string trustProxy: true, // be default, we trust the X-Forwarded-For header. static: path.normalize(thorin.root + '/public'), // static path options: { payloadLimit: 100000 // maximum amount of string to process with json }, ignoreHeaders: null, // An array of ignored HTTP Headers. hideType: false, // If set to true, hide the "type" field in the result object rawText: false, // If set to true, we will parse raw text/plain POST requests and place the text under intentObj.rawInput._text helmet: { // Default helmet configuration, for full config, see https://github.com/helmetjs/helmet frameguard: false, xssFilter: { setOnOldIE: true }, contentSecurityPolicy: { browserSniff: true, disableAndroid: false, setAllHeaders: false, directives: { objectSrc: ["'none'"], workerSrc: false // This is not set. } }, dnsPrefetchControl: { allow: false }, hsts: false, ieNoOpen: true, noCache: false, hpkp: false } }, httpConfig); if (typeof this[config].actionPath === 'string') { this[config].actionPath = [this[config].actionPath]; } thorin.config.set('transport.' + this.name, this[config]); // update the app with the full config this[app] = new ExpressApp(this[config], this._log.bind(this)); for (let i = 0; i < this[middleware].length; i++) { this[app]._addMiddleware(this[middleware][i]); } this[middleware] = []; }
init(httpConfig) { this[config] = thorin.util.extend({ debug: true, port: 3000, basePath: '/', actionPath: '/dispatch', // this is the default frux listener for incoming frux actions. authorization: { "header": "Authorization", // By default, we will look into the "Authorization: Bearer" header "basic": null // if set to {user,password}, we will apply basic authorization for it. This can be used for fast prototyping of password protected apps. //"cookie": "tps" }, ip: '0.0.0.0', cors: false, // Cross origin requests. If set a string, we'll use the domain as the origin, or an array of domains. corsIgnore: null, // If specified, we will ignore these hosts in CORS requests. Array or string trustProxy: true, // be default, we trust the X-Forwarded-For header. static: path.normalize(thorin.root + '/public'), // static path options: { payloadLimit: 100000 // maximum amount of string to process with json }, ignoreHeaders: null, // An array of ignored HTTP Headers. hideType: false, // If set to true, hide the "type" field in the result object rawText: false, // If set to true, we will parse raw text/plain POST requests and place the text under intentObj.rawInput._text helmet: { // Default helmet configuration, for full config, see https://github.com/helmetjs/helmet frameguard: false, xssFilter: { setOnOldIE: true }, contentSecurityPolicy: { browserSniff: true, disableAndroid: false, setAllHeaders: false, directives: { objectSrc: ["'none'"], workerSrc: false // This is not set. } }, dnsPrefetchControl: { allow: false }, hsts: false, ieNoOpen: true, noCache: false, hpkp: false } }, httpConfig); if (typeof this[config].actionPath === 'string') { this[config].actionPath = [this[config].actionPath]; } thorin.config.set('transport.' + this.name, this[config]); // update the app with the full config this[app] = new ExpressApp(this[config], this._log.bind(this)); for (let i = 0; i < this[middleware].length; i++) { this[app]._addMiddleware(this[middleware][i]); } this[middleware] = []; }
JavaScript
run(done) { this.app.listen((e) => { if (e) return done(e); thorin.dispatcher.registerTransport(this); done(); }); }
run(done) { this.app.listen((e) => { if (e) return done(e); thorin.dispatcher.registerTransport(this); done(); }); }
JavaScript
addMiddleware(fn) { if (!this[app]) { this[middleware].push(fn); return this; } if (this.app.running) { console.error('Thorin.transport.http: addMiddleware() must be called before the app is running.'); return this; } if (typeof fn !== 'function') { console.error('Thorin.transport.http: addMiddleware(fn) must be called with a function.'); return this; } this.app._addMiddleware(fn); }
addMiddleware(fn) { if (!this[app]) { this[middleware].push(fn); return this; } if (this.app.running) { console.error('Thorin.transport.http: addMiddleware() must be called before the app is running.'); return this; } if (typeof fn !== 'function') { console.error('Thorin.transport.http: addMiddleware(fn) must be called with a function.'); return this; } this.app._addMiddleware(fn); }
JavaScript
routeAction(actionObj) { this.app.addHandler(actionObj); for (let i = 0; i < actionObj.aliases.length; i++) { let alias = actionObj.aliases[i]; if (typeof alias.verb !== 'string') { continue; } this.app.addHandler(actionObj, alias.verb, alias.name); } }
routeAction(actionObj) { this.app.addHandler(actionObj); for (let i = 0; i < actionObj.aliases.length; i++) { let alias = actionObj.aliases[i]; if (typeof alias.verb !== 'string') { continue; } this.app.addHandler(actionObj, alias.verb, alias.name); } }
JavaScript
_log() { if (this[config].debug === false) return; let logObj = thorin.logger(this.name); logObj.log.apply(logObj, arguments); }
_log() { if (this[config].debug === false) return; let logObj = thorin.logger(this.name); logObj.log.apply(logObj, arguments); }
JavaScript
match(reg) { if (!(reg instanceof RegExp)) { console.warn(`Action ${this.name} requires a regex for match()`); return this; } this[match].push(reg); return this; }
match(reg) { if (!(reg instanceof RegExp)) { console.warn(`Action ${this.name} requires a regex for match()`); return this; } this[match].push(reg); return this; }
JavaScript
enableCors(originDomain, opt) { this.cors = { credentials: true }; if (typeof originDomain === 'string') { // remove any trailing / let corsDomain; if (originDomain.indexOf('://') !== -1) { let tmp = originDomain.split('//'); corsDomain = tmp[0] + '//'; tmp[1] = tmp[1].split('/')[0]; corsDomain += tmp[1]; } else { corsDomain = originDomain.split('/')[0]; } this.cors.domain = corsDomain; } if (typeof originDomain === 'object') opt = originDomain; if (typeof opt === 'object' && opt) { if (opt.credentials === false) { this.cors.credentials = false; } else { this.cors.credentials = true; } } return this; }
enableCors(originDomain, opt) { this.cors = { credentials: true }; if (typeof originDomain === 'string') { // remove any trailing / let corsDomain; if (originDomain.indexOf('://') !== -1) { let tmp = originDomain.split('//'); corsDomain = tmp[0] + '//'; tmp[1] = tmp[1].split('/')[0]; corsDomain += tmp[1]; } else { corsDomain = originDomain.split('/')[0]; } this.cors.domain = corsDomain; } if (typeof originDomain === 'object') opt = originDomain; if (typeof opt === 'object' && opt) { if (opt.credentials === false) { this.cors.credentials = false; } else { this.cors.credentials = true; } } return this; }
JavaScript
hasCors() { if (typeof this[cors] === 'undefined' || this[cors] === false) return false; if (typeof this[cors] !== 'object' || !this[cors]) return false; return true; }
hasCors() { if (typeof this[cors] === 'undefined' || this[cors] === false) return false; if (typeof this[cors] !== 'object' || !this[cors]) return false; return true; }
JavaScript
function researchedElecMiner() { Object.values(mineableList).forEach((mineable) => { mineable.elecMinersResearchDom.style.display = 'inline-block'; }); }
function researchedElecMiner() { Object.values(mineableList).forEach((mineable) => { mineable.elecMinersResearchDom.style.display = 'inline-block'; }); }
JavaScript
function createDictionaryofTopWords(threshold) { let topWords = {} for (let [key, value] of Object.entries(frequencyData)) { if (value.frequency > threshold) { // threshold for top words topWords[key] = value.frequency } } return topWords }
function createDictionaryofTopWords(threshold) { let topWords = {} for (let [key, value] of Object.entries(frequencyData)) { if (value.frequency > threshold) { // threshold for top words topWords[key] = value.frequency } } return topWords }
JavaScript
calculateInstanceSourceTargetPositions64xyLow(attribute, {startRow, endRow}) { const isFP64 = this.use64bitPositions(); attribute.constant = !isFP64; if (!isFP64) { attribute.value = new Float32Array(4); return; } const {data, getSourcePosition, getTargetPosition} = this.props; const {value, size} = attribute; let i = startRow * size; const {iterable, objectInfo} = createIterable(data, startRow, endRow); for (const object of iterable) { objectInfo.index++; const sourcePosition = getSourcePosition(object, objectInfo); const targetPosition = getTargetPosition(object, objectInfo); value[i++] = fp64LowPart(sourcePosition[0]); value[i++] = fp64LowPart(sourcePosition[1]); value[i++] = fp64LowPart(targetPosition[0]); value[i++] = fp64LowPart(targetPosition[1]); } }
calculateInstanceSourceTargetPositions64xyLow(attribute, {startRow, endRow}) { const isFP64 = this.use64bitPositions(); attribute.constant = !isFP64; if (!isFP64) { attribute.value = new Float32Array(4); return; } const {data, getSourcePosition, getTargetPosition} = this.props; const {value, size} = attribute; let i = startRow * size; const {iterable, objectInfo} = createIterable(data, startRow, endRow); for (const object of iterable) { objectInfo.index++; const sourcePosition = getSourcePosition(object, objectInfo); const targetPosition = getTargetPosition(object, objectInfo); value[i++] = fp64LowPart(sourcePosition[0]); value[i++] = fp64LowPart(sourcePosition[1]); value[i++] = fp64LowPart(targetPosition[0]); value[i++] = fp64LowPart(targetPosition[1]); } }
JavaScript
function extractCameraVectors({viewMatrix, viewMatrixInverse}) { // Read the translation from the inverse view matrix return { eye: [viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]], direction: [-viewMatrix[2], -viewMatrix[6], -viewMatrix[10]], up: [viewMatrix[1], viewMatrix[5], viewMatrix[9]], right: [viewMatrix[0], viewMatrix[4], viewMatrix[8]] }; }
function extractCameraVectors({viewMatrix, viewMatrixInverse}) { // Read the translation from the inverse view matrix return { eye: [viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]], direction: [-viewMatrix[2], -viewMatrix[6], -viewMatrix[10]], up: [viewMatrix[1], viewMatrix[5], viewMatrix[9]], right: [viewMatrix[0], viewMatrix[4], viewMatrix[8]] }; }
JavaScript
addIcon (aName, svgString) { const node = SvgIconNode.clone().setTitle(aName).setSvgString(svgString) this.addSubnode(node) return this }
addIcon (aName, svgString) { const node = SvgIconNode.clone().setTitle(aName).setSvgString(svgString) this.addSubnode(node) return this }
JavaScript
function dateChange(date, interval, units) { switch (interval) { case 'year': date.setFullYear(date.getFullYear() + units) break case 'quarter': date.setMonth(date.getMonth() + 3 * units) break case 'month': date.setMonth(date.getMonth() + units) break case 'week': date.setDate(date.getDate() + 7 * units) break case 'day': date.setDate(date.getDate() + units) break case 'hour': date.setTime(date.getTime() + units * 3600000) break case 'minute': date.setTime(date.getTime() + units * 60000) break case 'second': date.setTime(date.getTime() + units * 1000) break default: date = undefined break } return date }
function dateChange(date, interval, units) { switch (interval) { case 'year': date.setFullYear(date.getFullYear() + units) break case 'quarter': date.setMonth(date.getMonth() + 3 * units) break case 'month': date.setMonth(date.getMonth() + units) break case 'week': date.setDate(date.getDate() + 7 * units) break case 'day': date.setDate(date.getDate() + units) break case 'hour': date.setTime(date.getTime() + units * 3600000) break case 'minute': date.setTime(date.getTime() + units * 60000) break case 'second': date.setTime(date.getTime() + units * 1000) break default: date = undefined break } return date }
JavaScript
async function runSeed() { console.log('seeding...') try { await preSeed() await seed() } catch (err) { console.error(err) process.exitCode = 1 } finally { console.log('closing db connection') await db.close() console.log('db connection closed') } }
async function runSeed() { console.log('seeding...') try { await preSeed() await seed() } catch (err) { console.error(err) process.exitCode = 1 } finally { console.log('closing db connection') await db.close() console.log('db connection closed') } }
JavaScript
async init () { return new Promise(function(fulfill, reject) { // Enter session into DB var result = async function() { // TODO: Write your own function to insert the session into your // Database. The function should return an object which contains // the id of the created Database-entry. // e.g. let response = await restClient.insert("sessions", this._session); let response = {}; // Change this response.sessionid = 123; // Change this // Fulfill promise and return Database entry id of session fulfill(response.sessionid); }(); }); }
async init () { return new Promise(function(fulfill, reject) { // Enter session into DB var result = async function() { // TODO: Write your own function to insert the session into your // Database. The function should return an object which contains // the id of the created Database-entry. // e.g. let response = await restClient.insert("sessions", this._session); let response = {}; // Change this response.sessionid = 123; // Change this // Fulfill promise and return Database entry id of session fulfill(response.sessionid); }(); }); }
JavaScript
function cart_container(){ $.ajax({ url : "action.php", method : "POST", data : {get_cart_product:1}, success : function(data){ $("#cart_product").html(data); } }) cart_count(); }
function cart_container(){ $.ajax({ url : "action.php", method : "POST", data : {get_cart_product:1}, success : function(data){ $("#cart_product").html(data); } }) cart_count(); }
JavaScript
function render() { /* This array holds the relative URL to the image used * for that particular row of the game level. */ var rowImages = [ 'images/water-block.png', // Top row is water 'images/stone-block.png', // Row 1 of 3 of stone 'images/stone-block.png', // Row 2 of 3 of stone 'images/stone-block.png', // Row 3 of 3 of stone 'images/grass-block.png', // Row 1 of 2 of grass 'images/grass-block.png' // Row 2 of 2 of grass ], numRows = 6, numCols = 5, row, col; // Before drawing, clear existing canvas ctx.clearRect(0,0,canvas.width,canvas.height) /* Loop through the number of rows and columns we've defined above * and, using the rowImages array, draw the correct image for that * portion of the "grid" */ for (row = 0; row < numRows; row++) { for (col = 0; col < numCols; col++) { /* The drawImage function of the canvas' context element * requires 3 parameters: the image to draw, the x coordinate * to start drawing and the y coordinate to start drawing. * We're using our Resources helpers to refer to our images * so that we get the benefits of caching these images, since * we're using them over and over. */ ctx.drawImage( Resources.get(rowImages[row]), col * dimensions.colWidth, row * dimensions.rowHeight ); } } renderEntities(); }
function render() { /* This array holds the relative URL to the image used * for that particular row of the game level. */ var rowImages = [ 'images/water-block.png', // Top row is water 'images/stone-block.png', // Row 1 of 3 of stone 'images/stone-block.png', // Row 2 of 3 of stone 'images/stone-block.png', // Row 3 of 3 of stone 'images/grass-block.png', // Row 1 of 2 of grass 'images/grass-block.png' // Row 2 of 2 of grass ], numRows = 6, numCols = 5, row, col; // Before drawing, clear existing canvas ctx.clearRect(0,0,canvas.width,canvas.height) /* Loop through the number of rows and columns we've defined above * and, using the rowImages array, draw the correct image for that * portion of the "grid" */ for (row = 0; row < numRows; row++) { for (col = 0; col < numCols; col++) { /* The drawImage function of the canvas' context element * requires 3 parameters: the image to draw, the x coordinate * to start drawing and the y coordinate to start drawing. * We're using our Resources helpers to refer to our images * so that we get the benefits of caching these images, since * we're using them over and over. */ ctx.drawImage( Resources.get(rowImages[row]), col * dimensions.colWidth, row * dimensions.rowHeight ); } } renderEntities(); }
JavaScript
function renderEntities() { /* Loop through all of the objects within the allEnemies array and call * the render function you have defined. * Then check if a collision with the player has occurred */ player.render(); allEnemies.forEach(function(enemy) { enemy.render(); enemy.checkCollisions(player); }); if (collectible.shown) { collectible.render(); collectible.checkCollect(player); } }
function renderEntities() { /* Loop through all of the objects within the allEnemies array and call * the render function you have defined. * Then check if a collision with the player has occurred */ player.render(); allEnemies.forEach(function(enemy) { enemy.render(); enemy.checkCollisions(player); }); if (collectible.shown) { collectible.render(); collectible.checkCollect(player); } }