language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function dateComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Date comparator provided is not supported.\n Use only ' + legalComparators);
}
}
} | function dateComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Date comparator provided is not supported.\n Use only ' + legalComparators);
}
}
} |
JavaScript | function numberComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators);
}
}
} | function numberComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators);
}
}
} |
JavaScript | function angleBetweenClockHands(date) {
const h = (date.getUTCHours() > 12) ? date.getUTCHours() - 12 : date.getUTCHours();
const m = date.getUTCMinutes();
const hL = 0.5 * (60 * h + m);
const mL = 6 * m;
const f = hL - mL;
const j = (f > 180) ? (360 - f) : f;
const n = (j < 0) ? -j : j;
return n * (Math.PI / 180);
} | function angleBetweenClockHands(date) {
const h = (date.getUTCHours() > 12) ? date.getUTCHours() - 12 : date.getUTCHours();
const m = date.getUTCMinutes();
const hL = 0.5 * (60 * h + m);
const mL = 6 * m;
const f = hL - mL;
const j = (f > 180) ? (360 - f) : f;
const n = (j < 0) ? -j : j;
return n * (Math.PI / 180);
} |
JavaScript | async _connect () {
this.wrapperKey = await this._getWrapperKey()
this.websocket = await this._getWebsocket()
return this.init()
} | async _connect () {
this.wrapperKey = await this._getWrapperKey()
this.websocket = await this._getWebsocket()
return this.init()
} |
JavaScript | _onCloseWebsocket (event) {
this.websocketConnected = false
this.onCloseWebsocket(event)
// Don't attempt reconnection if user closes socket
if (this.websocketClosing) return
if (this.reconnect.attempts === 0) {
return
}
if (this.reconnect.attempts !== -1 && this.nextAttemptId > this.reconnect.attempts) {
return
}
setTimeout(async () => {
this.websocket = await this._getWebsocket()
}, this.reconnect.delay)
} | _onCloseWebsocket (event) {
this.websocketConnected = false
this.onCloseWebsocket(event)
// Don't attempt reconnection if user closes socket
if (this.websocketClosing) return
if (this.reconnect.attempts === 0) {
return
}
if (this.reconnect.attempts !== -1 && this.nextAttemptId > this.reconnect.attempts) {
return
}
setTimeout(async () => {
this.websocket = await this._getWebsocket()
}, this.reconnect.delay)
} |
JavaScript | function promptUser() {
return inquirer.prompt([
{
type: "input",
name: "title",
message: "What is the title of your project?"
},
{
type: "list",
message: "What license does your project allow?",
name: "license",
choices: [
"ISC",
"MIT",
"0BSD",
"Unlicense",
]
},
{
type: "editor",
name: "description",
message: "Please give a good description of your project?"
},
{
type: "input",
name: "installation",
message: "What are the installation instructions?"
},
{
type: "input",
name: "usage",
message: "Describe your developed app's usage?"
},
{
type: "input",
name: "contributors",
message: "Who were the contributors on this project?",
},
{
type: "input",
name: "username",
message: "What is your GitHub Username?",
},
{
type: "input",
message: "What is your preferred method of communication?",
name: "contact",
default: "email",
},
{
type: "input",
name: "email",
message: "Input your preferred email address?",
},
{
type: "input",
name: "tests",
message: "Enter any test instructions now."
},
{
type: "input",
name: "credits",
message: "enter any url credits used in development of app separated by a space please."
},
])
} | function promptUser() {
return inquirer.prompt([
{
type: "input",
name: "title",
message: "What is the title of your project?"
},
{
type: "list",
message: "What license does your project allow?",
name: "license",
choices: [
"ISC",
"MIT",
"0BSD",
"Unlicense",
]
},
{
type: "editor",
name: "description",
message: "Please give a good description of your project?"
},
{
type: "input",
name: "installation",
message: "What are the installation instructions?"
},
{
type: "input",
name: "usage",
message: "Describe your developed app's usage?"
},
{
type: "input",
name: "contributors",
message: "Who were the contributors on this project?",
},
{
type: "input",
name: "username",
message: "What is your GitHub Username?",
},
{
type: "input",
message: "What is your preferred method of communication?",
name: "contact",
default: "email",
},
{
type: "input",
name: "email",
message: "Input your preferred email address?",
},
{
type: "input",
name: "tests",
message: "Enter any test instructions now."
},
{
type: "input",
name: "credits",
message: "enter any url credits used in development of app separated by a space please."
},
])
} |
JavaScript | function generateMarkdown(data) {
return `
[](https://www.npmjs.com/package/inquirer-emoji)
<img src="https://badge.fury.io/js/inquirer.svg" alt="npm">
# ${data.title}
# Licence
>
* select the license badge to view licence aggreements:
[](https://opensource.org/licenses/${data.license})
### :octocat:
### node js :package:
# Table of Contents
<!-- toc -->
* [Description](#description)
* [Installation](#installation)
* [Usage](#usage)
* [Contributors](#contributors)
* [GitHub Information](#github-information)
* [Questions](#questions)
* [Credits](#credits)
<!-- toc stop -->
# **Description**
> ${data.description}
## **Installation**
* ${data.installation}
## **Usage**
* ${data.usage}
### **Contributors**
* ${data.contributors}
## **GitHub Information**
# '''' https://github.com/${data.username} ''''
Picture of Developer:
<img src="https://avatars0.githubusercontent.com/${data.username}" width="250px" >
## *Questions*
> questions or comments contact me by ${data.contact} :
#### ${data.email}
## Test Example
${data.tests}:
<img src="./utils/screenshot.jpg" width="500px" >
* Link to video for test demonstration
https://drive.google.com/file/d/1rUZHHpgqWhH1ulRpuMnLxKdz-tA4BneW/view
### Credits
* ${data.credits}
`;
} | function generateMarkdown(data) {
return `
[](https://www.npmjs.com/package/inquirer-emoji)
<img src="https://badge.fury.io/js/inquirer.svg" alt="npm">
# ${data.title}
# Licence
>
* select the license badge to view licence aggreements:
[](https://opensource.org/licenses/${data.license})
### :octocat:
### node js :package:
# Table of Contents
<!-- toc -->
* [Description](#description)
* [Installation](#installation)
* [Usage](#usage)
* [Contributors](#contributors)
* [GitHub Information](#github-information)
* [Questions](#questions)
* [Credits](#credits)
<!-- toc stop -->
# **Description**
> ${data.description}
## **Installation**
* ${data.installation}
## **Usage**
* ${data.usage}
### **Contributors**
* ${data.contributors}
## **GitHub Information**
# '''' https://github.com/${data.username} ''''
Picture of Developer:
<img src="https://avatars0.githubusercontent.com/${data.username}" width="250px" >
## *Questions*
> questions or comments contact me by ${data.contact} :
#### ${data.email}
## Test Example
${data.tests}:
<img src="./utils/screenshot.jpg" width="500px" >
* Link to video for test demonstration
https://drive.google.com/file/d/1rUZHHpgqWhH1ulRpuMnLxKdz-tA4BneW/view
### Credits
* ${data.credits}
`;
} |
JavaScript | on(event, fn) {
let handlers = this.handlers[event];
if (!handlers) {
handlers = this.handlers[event] = [];
}
handlers.push(fn);
// Return an event descriptor
return {
name: event,
callback: fn,
un: (e, fn) => this.un(e, fn)
};
} | on(event, fn) {
let handlers = this.handlers[event];
if (!handlers) {
handlers = this.handlers[event] = [];
}
handlers.push(fn);
// Return an event descriptor
return {
name: event,
callback: fn,
un: (e, fn) => this.un(e, fn)
};
} |
JavaScript | un(event, fn) {
const handlers = this.handlers[event];
if (handlers) {
if (fn) {
for (let i = handlers.length - 1; i >= 0; i--) {
if (handlers[i] === fn) {
handlers.splice(i, 1);
}
}
} else {
handlers.length = 0;
}
}
} | un(event, fn) {
const handlers = this.handlers[event];
if (handlers) {
if (fn) {
for (let i = handlers.length - 1; i >= 0; i--) {
if (handlers[i] === fn) {
handlers.splice(i, 1);
}
}
} else {
handlers.length = 0;
}
}
} |
JavaScript | once(event, handler) {
const fn = (...args) => {
/* eslint-disable no-invalid-this */
handler.apply(this, args);
/* eslint-enable no-invalid-this */
setTimeout(() => this.un(event, fn), 0);
};
return this.on(event, fn);
} | once(event, handler) {
const fn = (...args) => {
/* eslint-disable no-invalid-this */
handler.apply(this, args);
/* eslint-enable no-invalid-this */
setTimeout(() => this.un(event, fn), 0);
};
return this.on(event, fn);
} |
JavaScript | fireEvent(event, ...args) {
if (this._isDisabledEventEmission(event)) {
return;
}
const handlers = this.handlers[event];
handlers && handlers.forEach(fn => fn(...args));
} | fireEvent(event, ...args) {
if (this._isDisabledEventEmission(event)) {
return;
}
const handlers = this.handlers[event];
handlers && handlers.forEach(fn => fn(...args));
} |
JavaScript | createAnillos (){
//Anillos
//Geometrías
var anillo1Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo1Geometry.translate(-34,-10,-6.3);
anillo1Geometry.rotateX(1.54);
var anillo2Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo2Geometry.translate(0.9,-10,-6.3);
anillo2Geometry.rotateX(1.58);
var anillo3Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo3Geometry.translate(33,-10,-6.3);
anillo3Geometry.rotateX(1.54);
var anillo4Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo4Geometry.translate(16,10,-6.3);
anillo4Geometry.rotateX(1.58);
var anillo5Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo5Geometry.translate(-17,10,-6.3);
anillo5Geometry.rotateX(1.58);
//Materiales
var anilloMaterial = new THREE.MeshStandardMaterial({color: 0x804000});
//Mesh
this.anillo1 = new THREE.Mesh(anillo1Geometry, anilloMaterial);
this.anillo2 = new THREE.Mesh(anillo2Geometry, anilloMaterial);
this.anillo3 = new THREE.Mesh(anillo3Geometry, anilloMaterial);
this.anillo4 = new THREE.Mesh(anillo4Geometry, anilloMaterial);
this.anillo5 = new THREE.Mesh(anillo5Geometry, anilloMaterial);
//Añadirlos a la escena
this.add(this.anillo1);
this.add(this.anillo2);
this.add(this.anillo3);
this.add(this.anillo4);
this.add(this.anillo5);
} | createAnillos (){
//Anillos
//Geometrías
var anillo1Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo1Geometry.translate(-34,-10,-6.3);
anillo1Geometry.rotateX(1.54);
var anillo2Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo2Geometry.translate(0.9,-10,-6.3);
anillo2Geometry.rotateX(1.58);
var anillo3Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo3Geometry.translate(33,-10,-6.3);
anillo3Geometry.rotateX(1.54);
var anillo4Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo4Geometry.translate(16,10,-6.3);
anillo4Geometry.rotateX(1.58);
var anillo5Geometry = new THREE.TorusGeometry(5,1.7,10,25);
anillo5Geometry.translate(-17,10,-6.3);
anillo5Geometry.rotateX(1.58);
//Materiales
var anilloMaterial = new THREE.MeshStandardMaterial({color: 0x804000});
//Mesh
this.anillo1 = new THREE.Mesh(anillo1Geometry, anilloMaterial);
this.anillo2 = new THREE.Mesh(anillo2Geometry, anilloMaterial);
this.anillo3 = new THREE.Mesh(anillo3Geometry, anilloMaterial);
this.anillo4 = new THREE.Mesh(anillo4Geometry, anilloMaterial);
this.anillo5 = new THREE.Mesh(anillo5Geometry, anilloMaterial);
//Añadirlos a la escena
this.add(this.anillo1);
this.add(this.anillo2);
this.add(this.anillo3);
this.add(this.anillo4);
this.add(this.anillo5);
} |
JavaScript | createGround () {
// La geometría es una caja con poca altura y 5 agujeros
var cilindro1 = new THREE.CylinderGeometry(5,5,12,20);
var cilindro2 = new THREE.CylinderGeometry(5,5,12,20);
var cilindro3 = new THREE.CylinderGeometry(5,5,12,20);
var cilindro4 = new THREE.CylinderGeometry(5,5,12,20);
var cilindro5 = new THREE.CylinderGeometry(5,5,12,20);
var geometryGround = new THREE.BoxGeometry (100,12,50);
cilindro1.translate(-35,0.2,-11);
cilindro2.translate(-1,0.2,-11);
cilindro3.translate(33,0.2,-11);
cilindro4.translate(-18,0.2,11);
cilindro5.translate(17,0.2,11);
var geometryGroundBSP = new ThreeBSP(geometryGround);
var cilindroBSP1 = new ThreeBSP(cilindro1);
var cilindroBSP2 = new ThreeBSP(cilindro2);
var cilindroBSP3 = new ThreeBSP(cilindro3);
var cilindroBSP4 = new ThreeBSP(cilindro4);
var cilindroBSP5 = new ThreeBSP(cilindro5);
//Se sustrae los cilindros
var finalGeometryGround = geometryGroundBSP.subtract(cilindroBSP1);
var finalGeometryGround2 = finalGeometryGround.subtract(cilindroBSP2);
var finalGeometryGround3 = finalGeometryGround2.subtract(cilindroBSP3);
var finalGeometryGround4 = finalGeometryGround3.subtract(cilindroBSP4);
var finalGeometryGround5 = finalGeometryGround4.subtract(cilindroBSP5);
//Se crea el material con una textura de madera
var materialGround = new THREE.MeshBasicMaterial ( { color: 0xd3f5dc, map: new THREE.TextureLoader().load('./imgs/wood.jpg') } );
materialGround.transparency = true;
materialGround.opacity = 0.5;
//Se hace mesh
this.ground = finalGeometryGround5.toMesh(materialGround);
this.ground.geometry.computeFaceNormals();
this.ground.geometry.computeVertexNormals();
this.ground.position.y = -0.1;
//se añade a la escena
this.add (this.ground);
} | createGround () {
// La geometría es una caja con poca altura y 5 agujeros
var cilindro1 = new THREE.CylinderGeometry(5,5,12,20);
var cilindro2 = new THREE.CylinderGeometry(5,5,12,20);
var cilindro3 = new THREE.CylinderGeometry(5,5,12,20);
var cilindro4 = new THREE.CylinderGeometry(5,5,12,20);
var cilindro5 = new THREE.CylinderGeometry(5,5,12,20);
var geometryGround = new THREE.BoxGeometry (100,12,50);
cilindro1.translate(-35,0.2,-11);
cilindro2.translate(-1,0.2,-11);
cilindro3.translate(33,0.2,-11);
cilindro4.translate(-18,0.2,11);
cilindro5.translate(17,0.2,11);
var geometryGroundBSP = new ThreeBSP(geometryGround);
var cilindroBSP1 = new ThreeBSP(cilindro1);
var cilindroBSP2 = new ThreeBSP(cilindro2);
var cilindroBSP3 = new ThreeBSP(cilindro3);
var cilindroBSP4 = new ThreeBSP(cilindro4);
var cilindroBSP5 = new ThreeBSP(cilindro5);
//Se sustrae los cilindros
var finalGeometryGround = geometryGroundBSP.subtract(cilindroBSP1);
var finalGeometryGround2 = finalGeometryGround.subtract(cilindroBSP2);
var finalGeometryGround3 = finalGeometryGround2.subtract(cilindroBSP3);
var finalGeometryGround4 = finalGeometryGround3.subtract(cilindroBSP4);
var finalGeometryGround5 = finalGeometryGround4.subtract(cilindroBSP5);
//Se crea el material con una textura de madera
var materialGround = new THREE.MeshBasicMaterial ( { color: 0xd3f5dc, map: new THREE.TextureLoader().load('./imgs/wood.jpg') } );
materialGround.transparency = true;
materialGround.opacity = 0.5;
//Se hace mesh
this.ground = finalGeometryGround5.toMesh(materialGround);
this.ground.geometry.computeFaceNormals();
this.ground.geometry.computeVertexNormals();
this.ground.position.y = -0.1;
//se añade a la escena
this.add (this.ground);
} |
JavaScript | createFondoNubes(){
var fondoGeometry = new THREE.BoxGeometry(190,150,1);
var fondoTexture = new THREE.TextureLoader().load('./imgs/stone.jpg')
var fondoMaterial = new THREE.MeshLambertMaterial({map:fondoTexture});
var fondoMesh1 = new THREE.Mesh(fondoGeometry,fondoMaterial);
var fondoMesh2 = new THREE.Mesh(fondoGeometry,fondoMaterial);
var fondoMesh3 = new THREE.Mesh(fondoGeometry,fondoMaterial);
fondoMesh1.position.set(0,25,-80);
this.add(fondoMesh1);
fondoMesh2.rotation.y = 80;
fondoMesh2.position.set(-105,25,15);
this.add(fondoMesh2);
fondoMesh3.rotation.y = -80;
fondoMesh3.position.set(105,25,15);
this.add(fondoMesh3);
} | createFondoNubes(){
var fondoGeometry = new THREE.BoxGeometry(190,150,1);
var fondoTexture = new THREE.TextureLoader().load('./imgs/stone.jpg')
var fondoMaterial = new THREE.MeshLambertMaterial({map:fondoTexture});
var fondoMesh1 = new THREE.Mesh(fondoGeometry,fondoMaterial);
var fondoMesh2 = new THREE.Mesh(fondoGeometry,fondoMaterial);
var fondoMesh3 = new THREE.Mesh(fondoGeometry,fondoMaterial);
fondoMesh1.position.set(0,25,-80);
this.add(fondoMesh1);
fondoMesh2.rotation.y = 80;
fondoMesh2.position.set(-105,25,15);
this.add(fondoMesh2);
fondoMesh3.rotation.y = -80;
fondoMesh3.position.set(105,25,15);
this.add(fondoMesh3);
} |
JavaScript | createFondoHierba(){
var fondoGeometry = new THREE.BoxGeometry(300,280,1);
var fondoTexture = new THREE.TextureLoader().load('./imgs/hierba.jpg')
var fondoMaterial = new THREE.MeshLambertMaterial({map:fondoTexture});
var fondoMesh1 = new THREE.Mesh(fondoGeometry,fondoMaterial);
fondoMesh1.rotation.x = -7.9;
fondoMesh1.position.set(0,-5,0);
this.add(fondoMesh1);
} | createFondoHierba(){
var fondoGeometry = new THREE.BoxGeometry(300,280,1);
var fondoTexture = new THREE.TextureLoader().load('./imgs/hierba.jpg')
var fondoMaterial = new THREE.MeshLambertMaterial({map:fondoTexture});
var fondoMesh1 = new THREE.Mesh(fondoGeometry,fondoMaterial);
fondoMesh1.rotation.x = -7.9;
fondoMesh1.position.set(0,-5,0);
this.add(fondoMesh1);
} |
JavaScript | format(err, withStatus = false) {
let formattedError;
let status;
// Handle mongoose validation errors
if (err.name === 'ValidationError') {
const errors = Object.values(err.errors);
const message = `Invalid field${errors.length > 1 ? 's' : ''}.`;
const fields = errors.reduce(
(obj, error) => insertValueAtPath(error.kind, error.path.split('.'), obj),
{},
);
status = 400;
formattedError = { message, fields };
}
// Handle mongoose duplication errors
if (err.name === 'MongoError') {
const { code } = err;
const keys = Object.keys(err.keyValue);
const message = `Invalid field${keys.length > 1 ? 's' : ''}.`;
let fields;
if (code === 11000) {
fields = keys.reduce((obj, key) => insertValueAtPath('duplicate', key.split('.'), obj), {});
}
status = 400;
formattedError = { message, fields };
}
// Handle internally created errors
if (err.name === 'ApplicationError') {
status = err.statusCode || 500;
formattedError = { message: err.message };
}
// Last line of defense
if (!formattedError) {
status = 500;
formattedError = { message: 'An unknown error occurred.' };
}
if (withStatus) return { formattedError, status };
return formattedError;
} | format(err, withStatus = false) {
let formattedError;
let status;
// Handle mongoose validation errors
if (err.name === 'ValidationError') {
const errors = Object.values(err.errors);
const message = `Invalid field${errors.length > 1 ? 's' : ''}.`;
const fields = errors.reduce(
(obj, error) => insertValueAtPath(error.kind, error.path.split('.'), obj),
{},
);
status = 400;
formattedError = { message, fields };
}
// Handle mongoose duplication errors
if (err.name === 'MongoError') {
const { code } = err;
const keys = Object.keys(err.keyValue);
const message = `Invalid field${keys.length > 1 ? 's' : ''}.`;
let fields;
if (code === 11000) {
fields = keys.reduce((obj, key) => insertValueAtPath('duplicate', key.split('.'), obj), {});
}
status = 400;
formattedError = { message, fields };
}
// Handle internally created errors
if (err.name === 'ApplicationError') {
status = err.statusCode || 500;
formattedError = { message: err.message };
}
// Last line of defense
if (!formattedError) {
status = 500;
formattedError = { message: 'An unknown error occurred.' };
}
if (withStatus) return { formattedError, status };
return formattedError;
} |
JavaScript | async clearDatabase() {
await Author.deleteMany();
await Message.deleteMany();
await Room.deleteMany();
} | async clearDatabase() {
await Author.deleteMany();
await Message.deleteMany();
await Room.deleteMany();
} |
JavaScript | initRouteParams() {
return {
req: {},
res: {
json(data) {
return data;
},
},
next() {},
};
} | initRouteParams() {
return {
req: {},
res: {
json(data) {
return data;
},
},
next() {},
};
} |
JavaScript | async createMessage(req, res, next) {
let payload = {};
try {
const { roomId, authorId, text } = req.body;
const savedMessage = await messageRepository.createMessage({ roomId, authorId, text });
res.status(201);
res.location(`${req.baseUrl}/${savedMessage._id}`);
payload = { message: savedMessage };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async createMessage(req, res, next) {
let payload = {};
try {
const { roomId, authorId, text } = req.body;
const savedMessage = await messageRepository.createMessage({ roomId, authorId, text });
res.status(201);
res.location(`${req.baseUrl}/${savedMessage._id}`);
payload = { message: savedMessage };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async updateMessageById(req, res, next) {
let payload = {};
try {
const { messageId } = req.params;
const { text } = req.body;
const updatedMessage = await messageRepository.updateMessageById(messageId, {
text,
});
if (!updatedMessage)
throw new ApplicationError({ message: 'Message not found.', statusCode: 404 });
res.status(200);
payload = { message: updatedMessage };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async updateMessageById(req, res, next) {
let payload = {};
try {
const { messageId } = req.params;
const { text } = req.body;
const updatedMessage = await messageRepository.updateMessageById(messageId, {
text,
});
if (!updatedMessage)
throw new ApplicationError({ message: 'Message not found.', statusCode: 404 });
res.status(200);
payload = { message: updatedMessage };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async archiveMessageById(req, res, next) {
let payload = {};
try {
const { messageId } = req.params;
const archivedMessage = await messageRepository.archiveMessageById(messageId);
if (!archivedMessage)
throw new ApplicationError({ message: 'Message not found.', statusCode: 404 });
res.status(200);
payload = { message: archivedMessage };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async archiveMessageById(req, res, next) {
let payload = {};
try {
const { messageId } = req.params;
const archivedMessage = await messageRepository.archiveMessageById(messageId);
if (!archivedMessage)
throw new ApplicationError({ message: 'Message not found.', statusCode: 404 });
res.status(200);
payload = { message: archivedMessage };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async deleteMessageById(req, res, next) {
let payload = {};
try {
const { messageId } = req.params;
const deletedMessage = await messageRepository.deleteMessageById(messageId);
res.status(200);
if (!deletedMessage)
throw new ApplicationError({ message: 'Message not found.', statusCode: 404 });
payload = {
message: deletedMessage,
};
} catch (err) {
return next(err);
}
return res.json(payload);
} | async deleteMessageById(req, res, next) {
let payload = {};
try {
const { messageId } = req.params;
const deletedMessage = await messageRepository.deleteMessageById(messageId);
res.status(200);
if (!deletedMessage)
throw new ApplicationError({ message: 'Message not found.', statusCode: 404 });
payload = {
message: deletedMessage,
};
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async createMessage({ roomId, authorId, text }) {
const newMessage = new Message({ roomId, authorId, text });
const savedMessage = await newMessage.save();
const leanMessage = savedMessage.toObject();
return leanMessage;
} | async createMessage({ roomId, authorId, text }) {
const newMessage = new Message({ roomId, authorId, text });
const savedMessage = await newMessage.save();
const leanMessage = savedMessage.toObject();
return leanMessage;
} |
JavaScript | async updateMessageById(id, { text = '' }) {
const updates = { text };
const updatedMessage = await Message.findByIdAndUpdate(id, updates, {
new: true,
runValidators: true,
})
.lean()
.exec();
return updatedMessage;
} | async updateMessageById(id, { text = '' }) {
const updates = { text };
const updatedMessage = await Message.findByIdAndUpdate(id, updates, {
new: true,
runValidators: true,
})
.lean()
.exec();
return updatedMessage;
} |
JavaScript | async updateMessageById({ id, updateValues: { text } }, cb) {
const socket = this;
try {
const updatedMessage = await messageRepository.updateMessageById(id, { text });
if (!updatedMessage) throw new ApplicationError({ message: 'Message not found.' });
// Broadcast to Authors currently listening to the associated Room
socket.to(updatedMessage.roomId).emit(MESSAGE_UPDATED, { message: updatedMessage });
// Send Message back to sender
cb({ message: updatedMessage });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async updateMessageById({ id, updateValues: { text } }, cb) {
const socket = this;
try {
const updatedMessage = await messageRepository.updateMessageById(id, { text });
if (!updatedMessage) throw new ApplicationError({ message: 'Message not found.' });
// Broadcast to Authors currently listening to the associated Room
socket.to(updatedMessage.roomId).emit(MESSAGE_UPDATED, { message: updatedMessage });
// Send Message back to sender
cb({ message: updatedMessage });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | async archiveMessageById({ id }, cb) {
const socket = this;
try {
const archivedMessage = await messageRepository.archiveMessageById(id);
if (!archivedMessage) throw new ApplicationError({ message: 'Message not found.' });
// Broadcast to Authors currently listening to the associated Room
socket.to(archivedMessage.roomId).emit(MESSAGE_ARCHIVED, { message: archivedMessage });
// Send Message back to sender
cb({ message: archivedMessage });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async archiveMessageById({ id }, cb) {
const socket = this;
try {
const archivedMessage = await messageRepository.archiveMessageById(id);
if (!archivedMessage) throw new ApplicationError({ message: 'Message not found.' });
// Broadcast to Authors currently listening to the associated Room
socket.to(archivedMessage.roomId).emit(MESSAGE_ARCHIVED, { message: archivedMessage });
// Send Message back to sender
cb({ message: archivedMessage });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | async deleteMessageById({ id }, cb) {
const socket = this;
try {
const deletedMessage = await messageRepository.deleteMessageById(id);
if (!deletedMessage) throw new ApplicationError({ message: 'Message not found.' });
// Broadcast to Authors currently listening to the associated Room
socket.to(deletedMessage.roomId).emit(MESSAGE_DELETED, { message: deletedMessage });
// Send Message back to sender
cb({ message: deletedMessage });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async deleteMessageById({ id }, cb) {
const socket = this;
try {
const deletedMessage = await messageRepository.deleteMessageById(id);
if (!deletedMessage) throw new ApplicationError({ message: 'Message not found.' });
// Broadcast to Authors currently listening to the associated Room
socket.to(deletedMessage.roomId).emit(MESSAGE_DELETED, { message: deletedMessage });
// Send Message back to sender
cb({ message: deletedMessage });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | async mochaGlobalSetup() {
this.mongoServer = new MongoMemoryServer();
const mongoUri = await this.mongoServer.getUri();
await db.connect(mongoUri);
} | async mochaGlobalSetup() {
this.mongoServer = new MongoMemoryServer();
const mongoUri = await this.mongoServer.getUri();
await db.connect(mongoUri);
} |
JavaScript | async updateRoomById({ id, updateValues: { name, authors } }, cb) {
const socket = this;
try {
const updatedRoom = await roomRepository.updateRoomById(id, { name, authors });
if (!updatedRoom) throw new ApplicationError({ message: 'Room not found.' });
// Broadcast to Authors currently listening to this Room
socket.to(updatedRoom._id).emit(ROOM_UPDATED, { room: updatedRoom });
// Send Room back to sender
cb({ room: updatedRoom });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async updateRoomById({ id, updateValues: { name, authors } }, cb) {
const socket = this;
try {
const updatedRoom = await roomRepository.updateRoomById(id, { name, authors });
if (!updatedRoom) throw new ApplicationError({ message: 'Room not found.' });
// Broadcast to Authors currently listening to this Room
socket.to(updatedRoom._id).emit(ROOM_UPDATED, { room: updatedRoom });
// Send Room back to sender
cb({ room: updatedRoom });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | async archiveRoomById({ id }, cb) {
const socket = this;
try {
const archivedRoom = await roomRepository.archiveRoomById(id);
if (!archivedRoom) throw new ApplicationError({ message: 'Room not found.' });
await messageRepository.archiveAllMessages({ roomId: id });
// Broadcast to Authors currently listening to this Room
socket.to(archivedRoom._id).emit(ROOM_ARCHIVED, { room: archivedRoom });
// Send Room back to sender
cb({ room: archivedRoom });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async archiveRoomById({ id }, cb) {
const socket = this;
try {
const archivedRoom = await roomRepository.archiveRoomById(id);
if (!archivedRoom) throw new ApplicationError({ message: 'Room not found.' });
await messageRepository.archiveAllMessages({ roomId: id });
// Broadcast to Authors currently listening to this Room
socket.to(archivedRoom._id).emit(ROOM_ARCHIVED, { room: archivedRoom });
// Send Room back to sender
cb({ room: archivedRoom });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | async deleteRoomById({ id }, cb) {
const socket = this;
try {
const deletedRoom = await roomRepository.deleteRoomById(id);
if (!deletedRoom) throw new ApplicationError({ message: 'Room not found.' });
await messageRepository.deleteAllMessages({ roomId: id });
// Broadcast to Authors currently listening to this Room
socket.to(deletedRoom._id).emit(ROOM_DELETED, { room: deletedRoom });
// Send Room back to sender
cb({ room: deletedRoom });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async deleteRoomById({ id }, cb) {
const socket = this;
try {
const deletedRoom = await roomRepository.deleteRoomById(id);
if (!deletedRoom) throw new ApplicationError({ message: 'Room not found.' });
await messageRepository.deleteAllMessages({ roomId: id });
// Broadcast to Authors currently listening to this Room
socket.to(deletedRoom._id).emit(ROOM_DELETED, { room: deletedRoom });
// Send Room back to sender
cb({ room: deletedRoom });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | async createAuthor(req, res, next) {
let payload = {};
try {
const { _id, firstName, lastName } = req.body;
const author = await authorRepository.createAuthor({ _id, firstName, lastName });
res.status(201);
res.location(`${req.baseUrl}/${author._id}`);
payload = { author };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async createAuthor(req, res, next) {
let payload = {};
try {
const { _id, firstName, lastName } = req.body;
const author = await authorRepository.createAuthor({ _id, firstName, lastName });
res.status(201);
res.location(`${req.baseUrl}/${author._id}`);
payload = { author };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async updateAuthorById(req, res, next) {
let payload = {};
try {
const { authorId } = req.params;
const { firstName, lastName } = req.body;
const updatedAuthor = await authorRepository.updateAuthorById(authorId, {
firstName,
lastName,
});
if (!updatedAuthor)
throw new ApplicationError({ message: 'Author not found.', statusCode: 404 });
res.status(200);
payload = { author: updatedAuthor };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async updateAuthorById(req, res, next) {
let payload = {};
try {
const { authorId } = req.params;
const { firstName, lastName } = req.body;
const updatedAuthor = await authorRepository.updateAuthorById(authorId, {
firstName,
lastName,
});
if (!updatedAuthor)
throw new ApplicationError({ message: 'Author not found.', statusCode: 404 });
res.status(200);
payload = { author: updatedAuthor };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async archiveAuthorById(req, res, next) {
let payload = {};
try {
const { authorId } = req.params;
const archivedAuthor = await authorRepository.archiveAuthorById(authorId);
if (!archivedAuthor)
throw new ApplicationError({ message: 'Author not found.', statusCode: 404 });
// Archive Messages and Rooms associated with this Author
await messageRepository.archiveAllMessages({ authorId });
await roomRepository.archiveAllRooms({ authorId });
res.status(200);
payload = { author: archivedAuthor };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async archiveAuthorById(req, res, next) {
let payload = {};
try {
const { authorId } = req.params;
const archivedAuthor = await authorRepository.archiveAuthorById(authorId);
if (!archivedAuthor)
throw new ApplicationError({ message: 'Author not found.', statusCode: 404 });
// Archive Messages and Rooms associated with this Author
await messageRepository.archiveAllMessages({ authorId });
await roomRepository.archiveAllRooms({ authorId });
res.status(200);
payload = { author: archivedAuthor };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async deleteAuthorById(req, res, next) {
let payload = {};
try {
const { authorId } = req.params;
const deletedAuthor = await authorRepository.deleteAuthorById(authorId);
if (!deletedAuthor)
throw new ApplicationError({ message: 'Author not found.', statusCode: 404 });
// Delete Messages and Rooms associated with this Author
await messageRepository.deleteAllMessages({ authorId });
await roomRepository.deleteAllRooms({ authorId });
res.status(200);
payload = {
author: deletedAuthor,
};
} catch (err) {
return next(err);
}
return res.json(payload);
} | async deleteAuthorById(req, res, next) {
let payload = {};
try {
const { authorId } = req.params;
const deletedAuthor = await authorRepository.deleteAuthorById(authorId);
if (!deletedAuthor)
throw new ApplicationError({ message: 'Author not found.', statusCode: 404 });
// Delete Messages and Rooms associated with this Author
await messageRepository.deleteAllMessages({ authorId });
await roomRepository.deleteAllRooms({ authorId });
res.status(200);
payload = {
author: deletedAuthor,
};
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async createAuthor({ _id, firstName, lastName }) {
const newAuthor = new Author({ _id, firstName, lastName });
const savedAuthor = await newAuthor.save();
const leanAuthor = savedAuthor.toObject();
return leanAuthor;
} | async createAuthor({ _id, firstName, lastName }) {
const newAuthor = new Author({ _id, firstName, lastName });
const savedAuthor = await newAuthor.save();
const leanAuthor = savedAuthor.toObject();
return leanAuthor;
} |
JavaScript | async updateAuthorById(id, { firstName = '', lastName = '' }) {
const updates = { firstName, lastName };
const updatedAuthor = await Author.findByIdAndUpdate(id, updates, {
new: true,
runValidators: true,
})
.lean()
.exec();
return updatedAuthor;
} | async updateAuthorById(id, { firstName = '', lastName = '' }) {
const updates = { firstName, lastName };
const updatedAuthor = await Author.findByIdAndUpdate(id, updates, {
new: true,
runValidators: true,
})
.lean()
.exec();
return updatedAuthor;
} |
JavaScript | async updateAuthorById({ id, updateValues: { firstName, lastName } }, cb) {
const socket = this;
try {
const updatedAuthor = await authorRepository.updateAuthorById(id, { firstName, lastName });
if (!updatedAuthor) throw new ApplicationError({ message: 'Author not found.' });
const rooms = await roomRepository.getAllRooms({
authorId: updatedAuthor._id,
onlyActive: 0,
limit: 0,
});
// Broadcast to Authors currently listening to the associated rooms
socket.to(...rooms.map((room) => room._id)).emit(AUTHOR_UPDATED, { author: updatedAuthor });
// Send Author back to sender
cb({ author: updatedAuthor });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async updateAuthorById({ id, updateValues: { firstName, lastName } }, cb) {
const socket = this;
try {
const updatedAuthor = await authorRepository.updateAuthorById(id, { firstName, lastName });
if (!updatedAuthor) throw new ApplicationError({ message: 'Author not found.' });
const rooms = await roomRepository.getAllRooms({
authorId: updatedAuthor._id,
onlyActive: 0,
limit: 0,
});
// Broadcast to Authors currently listening to the associated rooms
socket.to(...rooms.map((room) => room._id)).emit(AUTHOR_UPDATED, { author: updatedAuthor });
// Send Author back to sender
cb({ author: updatedAuthor });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | async archiveAuthorById({ id }, cb) {
const socket = this;
try {
const archivedAuthor = await authorRepository.archiveAuthorById(id);
if (!archivedAuthor) throw new ApplicationError({ message: 'Author not found.' });
const rooms = await roomRepository.getAllRooms({
authorId: archivedAuthor._id,
onlyActive: 0,
limit: 0,
});
await messageRepository.archiveAllMessages({ authorId: id });
await roomRepository.archiveAllRooms({ authorId: id });
// Broadcast to Authors currently listening to the associated rooms; client will manage
// archive Messages/Rooms
socket.to(...rooms.map((room) => room._id)).emit(AUTHOR_ARCHIVED, { author: archivedAuthor });
// Send Author back to sender
cb({ author: archivedAuthor });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async archiveAuthorById({ id }, cb) {
const socket = this;
try {
const archivedAuthor = await authorRepository.archiveAuthorById(id);
if (!archivedAuthor) throw new ApplicationError({ message: 'Author not found.' });
const rooms = await roomRepository.getAllRooms({
authorId: archivedAuthor._id,
onlyActive: 0,
limit: 0,
});
await messageRepository.archiveAllMessages({ authorId: id });
await roomRepository.archiveAllRooms({ authorId: id });
// Broadcast to Authors currently listening to the associated rooms; client will manage
// archive Messages/Rooms
socket.to(...rooms.map((room) => room._id)).emit(AUTHOR_ARCHIVED, { author: archivedAuthor });
// Send Author back to sender
cb({ author: archivedAuthor });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | async deleteAuthorById({ id }, cb) {
const socket = this;
try {
const deletedAuthor = await authorRepository.deleteAuthorById(id);
if (!deletedAuthor) throw new ApplicationError({ message: 'Author not found.' });
const rooms = await roomRepository.getAllRooms({
authorId: deletedAuthor._id,
onlyActive: 0,
limit: 0,
});
await messageRepository.deleteAllMessages({ authorId: id });
await roomRepository.deleteAllRooms({ authorId: id });
// Broadcast to Authors currently listening to the associated rooms; client will manage
// delete Messages/Rooms
socket.to(...rooms.map((room) => room._id)).emit(AUTHOR_DELETED, { author: deletedAuthor });
// Send Author back to sender
cb({ author: deletedAuthor });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} | async deleteAuthorById({ id }, cb) {
const socket = this;
try {
const deletedAuthor = await authorRepository.deleteAuthorById(id);
if (!deletedAuthor) throw new ApplicationError({ message: 'Author not found.' });
const rooms = await roomRepository.getAllRooms({
authorId: deletedAuthor._id,
onlyActive: 0,
limit: 0,
});
await messageRepository.deleteAllMessages({ authorId: id });
await roomRepository.deleteAllRooms({ authorId: id });
// Broadcast to Authors currently listening to the associated rooms; client will manage
// delete Messages/Rooms
socket.to(...rooms.map((room) => room._id)).emit(AUTHOR_DELETED, { author: deletedAuthor });
// Send Author back to sender
cb({ author: deletedAuthor });
} catch (err) {
cb({ error: errorUtils.format(err) });
}
} |
JavaScript | connect(uri) {
return new Promise((resolve, reject) => {
mongoose
.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })
.then(() => {
console.log('Connected to Database.');
resolve();
})
.catch((err) => {
console.error(err);
reject(err);
});
});
} | connect(uri) {
return new Promise((resolve, reject) => {
mongoose
.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })
.then(() => {
console.log('Connected to Database.');
resolve();
})
.catch((err) => {
console.error(err);
reject(err);
});
});
} |
JavaScript | async createRoom(req, res, next) {
let payload = {};
try {
const { name, authors } = req.body;
const room = await roomRepository.createRoom({ name, authors });
res.status(201);
res.location(`${req.baseUrl}/${room._id}`);
payload = { room };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async createRoom(req, res, next) {
let payload = {};
try {
const { name, authors } = req.body;
const room = await roomRepository.createRoom({ name, authors });
res.status(201);
res.location(`${req.baseUrl}/${room._id}`);
payload = { room };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async updateRoomById(req, res, next) {
let payload = {};
try {
const { roomId } = req.params;
const { name, authors } = req.body;
const updatedRoom = await roomRepository.updateRoomById(roomId, { name, authors });
if (!updatedRoom) throw new ApplicationError({ message: 'Room not found.', statusCode: 404 });
res.status(200);
payload = { room: updatedRoom };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async updateRoomById(req, res, next) {
let payload = {};
try {
const { roomId } = req.params;
const { name, authors } = req.body;
const updatedRoom = await roomRepository.updateRoomById(roomId, { name, authors });
if (!updatedRoom) throw new ApplicationError({ message: 'Room not found.', statusCode: 404 });
res.status(200);
payload = { room: updatedRoom };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async archiveRoomById(req, res, next) {
let payload = {};
try {
const { roomId } = req.params;
const archivedRoom = await roomRepository.archiveRoomById(roomId);
if (!archivedRoom)
throw new ApplicationError({ message: 'Room not found.', statusCode: 404 });
// Archive Messages associated with this Room
await messageRepository.archiveAllMessages({ roomId });
res.status(200);
payload = { room: archivedRoom };
} catch (err) {
return next(err);
}
return res.json(payload);
} | async archiveRoomById(req, res, next) {
let payload = {};
try {
const { roomId } = req.params;
const archivedRoom = await roomRepository.archiveRoomById(roomId);
if (!archivedRoom)
throw new ApplicationError({ message: 'Room not found.', statusCode: 404 });
// Archive Messages associated with this Room
await messageRepository.archiveAllMessages({ roomId });
res.status(200);
payload = { room: archivedRoom };
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async deleteRoomById(req, res, next) {
let payload = {};
try {
const { roomId } = req.params;
const deletedRoom = await roomRepository.deleteRoomById(roomId);
if (!deletedRoom) throw new ApplicationError({ message: 'Room not found.', statusCode: 404 });
// Delete Messages associated with this Room
await messageRepository.deleteAllMessages({ roomId });
res.status(200);
payload = {
room: deletedRoom,
};
} catch (err) {
return next(err);
}
return res.json(payload);
} | async deleteRoomById(req, res, next) {
let payload = {};
try {
const { roomId } = req.params;
const deletedRoom = await roomRepository.deleteRoomById(roomId);
if (!deletedRoom) throw new ApplicationError({ message: 'Room not found.', statusCode: 404 });
// Delete Messages associated with this Room
await messageRepository.deleteAllMessages({ roomId });
res.status(200);
payload = {
room: deletedRoom,
};
} catch (err) {
return next(err);
}
return res.json(payload);
} |
JavaScript | async createRoom({ name, authors = [] }) {
const newRoom = new Room({ name, authors: authors.map(({ _id }) => ({ author: _id })) });
const savedRoom = await newRoom.save();
const populatedRoom = await Room.populate(savedRoom, { path: 'authors.author' });
const leanRoom = populatedRoom.toObject();
const { authors: roomAuthors } = leanRoom;
leanRoom.authors = flattenAuthors(roomAuthors);
return leanRoom;
} | async createRoom({ name, authors = [] }) {
const newRoom = new Room({ name, authors: authors.map(({ _id }) => ({ author: _id })) });
const savedRoom = await newRoom.save();
const populatedRoom = await Room.populate(savedRoom, { path: 'authors.author' });
const leanRoom = populatedRoom.toObject();
const { authors: roomAuthors } = leanRoom;
leanRoom.authors = flattenAuthors(roomAuthors);
return leanRoom;
} |
JavaScript | async updateRoomById(id, { name = '', authors = [] }) {
const updates = {
name,
authors: authors.map(({ _id, isActive }) => ({ author: _id, isActive })),
};
const updatedRoom = await Room.findByIdAndUpdate(id, updates, {
new: true,
runValidators: true,
})
.populate('authors.author')
.lean()
.exec();
if (!updatedRoom) return null;
const { authors: roomAuthors } = updatedRoom;
updatedRoom.authors = flattenAuthors(roomAuthors);
return updatedRoom;
} | async updateRoomById(id, { name = '', authors = [] }) {
const updates = {
name,
authors: authors.map(({ _id, isActive }) => ({ author: _id, isActive })),
};
const updatedRoom = await Room.findByIdAndUpdate(id, updates, {
new: true,
runValidators: true,
})
.populate('authors.author')
.lean()
.exec();
if (!updatedRoom) return null;
const { authors: roomAuthors } = updatedRoom;
updatedRoom.authors = flattenAuthors(roomAuthors);
return updatedRoom;
} |
JavaScript | function selectBoxUpdate() {
let selectedValue = document.getElementById('neighborhoods-select').value;
if (selectedValue === 'All') {
console.log('All Selected');
let showProject = document.getElementsByClassName('Project');
let showCertificate = document.getElementsByClassName('Certificate');
let showEducation = document.getElementsByClassName('Education');
for (var i = 0; i < showProject.length; i++) {
showProject[i].style.display = 'inline-block';
}
for (var i = 0; i < showCertificate.length; i++) {
showCertificate[i].style.display = 'inline-block';
}
for (var i = 0; i < showEducation.length; i++) {
showEducation[i].style.display = 'inline-block';
}
} else if (selectedValue === 'Project') {
console.log('Project Selected!');
let showProject = document.getElementsByClassName('Project');
let hideCertification = document.getElementsByClassName('Certificate');
let hideEducation = document.getElementsByClassName('Education');
for (var i = 0; i < showProject.length; i++) {
showProject[i].style.display = 'inline-block';
}
for (var i = 0; i < hideCertification.length; i++) {
hideCertification[i].style.display = 'none';
}
for (var i = 0; i < hideEducation.length; i++) {
hideEducation[i].style.display = 'none';
}
// Hide Certification, Education Class and Show Project Class
} else if (selectedValue === 'Certificate') {
console.log('Certification Selected!');
let showCertificate = document.getElementsByClassName('Certificate');
let hideProject = document.getElementsByClassName('Project');
let hideEducation = document.getElementsByClassName('Education');
for (var i = 0; i < showCertificate.length; i++) {
showCertificate[i].style.display = 'inline-block';
}
for (var i = 0; i < hideProject.length; i++) {
hideProject[i].style.display = 'none';
}
for (var i = 0; i < hideEducation.length; i++) {
hideEducation[i].style.display = 'none';
}
// Hide Project, Education Class and Show Certification Class
} else if (selectedValue === 'Education') {
// Hide Project, Certification and Show Education Class
console.log('Education Selected!');
let showEducation = document.getElementsByClassName('Education');
let hideProject = document.getElementsByClassName('Project');
let hideCertificate = document.getElementsByClassName('Certificate');
for (var i = 0; i < showEducation.length; i++) {
showEducation[i].style.display = 'inline-block';
}
for (var i = 0; i < hideProject.length; i++) {
hideProject[i].style.display = 'none';
}
for (var i = 0; i < hideCertificate.length; i++) {
hideCertificate[i].style.display = 'none';
}
}
} | function selectBoxUpdate() {
let selectedValue = document.getElementById('neighborhoods-select').value;
if (selectedValue === 'All') {
console.log('All Selected');
let showProject = document.getElementsByClassName('Project');
let showCertificate = document.getElementsByClassName('Certificate');
let showEducation = document.getElementsByClassName('Education');
for (var i = 0; i < showProject.length; i++) {
showProject[i].style.display = 'inline-block';
}
for (var i = 0; i < showCertificate.length; i++) {
showCertificate[i].style.display = 'inline-block';
}
for (var i = 0; i < showEducation.length; i++) {
showEducation[i].style.display = 'inline-block';
}
} else if (selectedValue === 'Project') {
console.log('Project Selected!');
let showProject = document.getElementsByClassName('Project');
let hideCertification = document.getElementsByClassName('Certificate');
let hideEducation = document.getElementsByClassName('Education');
for (var i = 0; i < showProject.length; i++) {
showProject[i].style.display = 'inline-block';
}
for (var i = 0; i < hideCertification.length; i++) {
hideCertification[i].style.display = 'none';
}
for (var i = 0; i < hideEducation.length; i++) {
hideEducation[i].style.display = 'none';
}
// Hide Certification, Education Class and Show Project Class
} else if (selectedValue === 'Certificate') {
console.log('Certification Selected!');
let showCertificate = document.getElementsByClassName('Certificate');
let hideProject = document.getElementsByClassName('Project');
let hideEducation = document.getElementsByClassName('Education');
for (var i = 0; i < showCertificate.length; i++) {
showCertificate[i].style.display = 'inline-block';
}
for (var i = 0; i < hideProject.length; i++) {
hideProject[i].style.display = 'none';
}
for (var i = 0; i < hideEducation.length; i++) {
hideEducation[i].style.display = 'none';
}
// Hide Project, Education Class and Show Certification Class
} else if (selectedValue === 'Education') {
// Hide Project, Certification and Show Education Class
console.log('Education Selected!');
let showEducation = document.getElementsByClassName('Education');
let hideProject = document.getElementsByClassName('Project');
let hideCertificate = document.getElementsByClassName('Certificate');
for (var i = 0; i < showEducation.length; i++) {
showEducation[i].style.display = 'inline-block';
}
for (var i = 0; i < hideProject.length; i++) {
hideProject[i].style.display = 'none';
}
for (var i = 0; i < hideCertificate.length; i++) {
hideCertificate[i].style.display = 'none';
}
}
} |
JavaScript | function validateForm() {
let projectName = document.getElementById('searchForm').projectName.value;
let sumLang = document.getElementById('searchForm').sumLang.value;
let pjdate1 = document.getElementById('searchForm').pjdate1.value;
let pjdate2 = document.getElementById('searchForm').pjdate2.value;
let projectExplanation = document.getElementById('searchForm').projectExplanation.value;
let projectUrl = document.getElementById('searchForm').projectUrl.value;
// let githuburl = document.getElementById('searchForm').githuburl.value;
// let imgData = document.getElementById('searchForm').projectImg.value;
let portType = document.getElementById('searchForm').portType.value;
if (projectName, sumLang, pjdate1, pjdate2, projectExplanation, projectUrl, portType === "") {
alert('Some Fields are Empty!');
return false;
}
} | function validateForm() {
let projectName = document.getElementById('searchForm').projectName.value;
let sumLang = document.getElementById('searchForm').sumLang.value;
let pjdate1 = document.getElementById('searchForm').pjdate1.value;
let pjdate2 = document.getElementById('searchForm').pjdate2.value;
let projectExplanation = document.getElementById('searchForm').projectExplanation.value;
let projectUrl = document.getElementById('searchForm').projectUrl.value;
// let githuburl = document.getElementById('searchForm').githuburl.value;
// let imgData = document.getElementById('searchForm').projectImg.value;
let portType = document.getElementById('searchForm').portType.value;
if (projectName, sumLang, pjdate1, pjdate2, projectExplanation, projectUrl, portType === "") {
alert('Some Fields are Empty!');
return false;
}
} |
JavaScript | commitSwitch_(pos) {
this.updateInViewport_(pos, this.oldPos_);
this.doLayout_(pos);
this.preloadNext_(pos, Math.sign(pos - this.oldPos_));
this.oldPos_ = pos;
this.pos_ = pos;
this.controls_.setControlsState();
} | commitSwitch_(pos) {
this.updateInViewport_(pos, this.oldPos_);
this.doLayout_(pos);
this.preloadNext_(pos, Math.sign(pos - this.oldPos_));
this.oldPos_ = pos;
this.pos_ = pos;
this.controls_.setControlsState();
} |
JavaScript | function platformPostfix() {
if (/^win/.test(process.platform)) {
return process.arch == 'x64' ? 'win64' : 'win32';
} else if (/^darwin/.test(process.platform)) {
return 'osx64';
}
// This might not be ideal, but we don't have anything else and there is always a chance that it will work
return process.arch == 'x64' ? 'linux64' : 'linux32';
} | function platformPostfix() {
if (/^win/.test(process.platform)) {
return process.arch == 'x64' ? 'win64' : 'win32';
} else if (/^darwin/.test(process.platform)) {
return 'osx64';
}
// This might not be ideal, but we don't have anything else and there is always a chance that it will work
return process.arch == 'x64' ? 'linux64' : 'linux32';
} |
JavaScript | function maybeFinish() {
if (to !== null) clearTimeout(to);
to = setTimeout(function() {
var alldone = true;
var names = Object.keys(files);
for (var i=0; i<names.length; i++) {
if (!files[names[i]]["done"]) {
alldone = false;
break;
}
}
if (alldone && !returned) {
returned = true;
callback(null);
}
}, 1000);
} | function maybeFinish() {
if (to !== null) clearTimeout(to);
to = setTimeout(function() {
var alldone = true;
var names = Object.keys(files);
for (var i=0; i<names.length; i++) {
if (!files[names[i]]["done"]) {
alldone = false;
break;
}
}
if (alldone && !returned) {
returned = true;
callback(null);
}
}, 1000);
} |
JavaScript | function iterateMap(map, onEach) {
for (const pair of map) {
onEach(pair);
}
} | function iterateMap(map, onEach) {
for (const pair of map) {
onEach(pair);
}
} |
JavaScript | add(prop, referencedTable //undefined means self
) {
this.map.set(prop, referencedTable);
return this;
} | add(prop, referencedTable //undefined means self
) {
this.map.set(prop, referencedTable);
return this;
} |
JavaScript | function delay(millis) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => setTimeout(resolve, millis));
});
} | function delay(millis) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => setTimeout(resolve, millis));
});
} |
JavaScript | function exceptNullValues(value) {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value !== 'object') {
return value;
}
if (Array.isArray(value)) {
return value.map(element => {
if (element === undefined || element === null) {
return undefined;
}
return exceptNullValues(element);
});
}
let obj = {};
for (const fieldName in value) {
const fieldValue = value[fieldName];
if (fieldValue !== undefined && fieldValue !== null) {
obj[fieldName] = exceptNullValues(fieldValue);
}
}
return obj;
} | function exceptNullValues(value) {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value !== 'object') {
return value;
}
if (Array.isArray(value)) {
return value.map(element => {
if (element === undefined || element === null) {
return undefined;
}
return exceptNullValues(element);
});
}
let obj = {};
for (const fieldName in value) {
const fieldValue = value[fieldName];
if (fieldValue !== undefined && fieldValue !== null) {
obj[fieldName] = exceptNullValues(fieldValue);
}
}
return obj;
} |
JavaScript | function compareNodeNames(fromEl, toEl) {
var fromNodeName = fromEl.nodeName;
var toNodeName = toEl.nodeName;
var fromCodeStart, toCodeStart;
if (fromNodeName === toNodeName) {
return true;
}
fromCodeStart = fromNodeName.charCodeAt(0);
toCodeStart = toNodeName.charCodeAt(0);
// If the target element is a virtual DOM node or SVG node then we may
// need to normalize the tag name before comparing. Normal HTML elements that are
// in the "http://www.w3.org/1999/xhtml"
// are converted to upper case
if (fromCodeStart <= 90 && toCodeStart >= 97) { // from is upper and to is lower
return fromNodeName === toNodeName.toUpperCase();
} else if (toCodeStart <= 90 && fromCodeStart >= 97) { // to is upper and from is lower
return toNodeName === fromNodeName.toUpperCase();
} else {
return false;
}
} | function compareNodeNames(fromEl, toEl) {
var fromNodeName = fromEl.nodeName;
var toNodeName = toEl.nodeName;
var fromCodeStart, toCodeStart;
if (fromNodeName === toNodeName) {
return true;
}
fromCodeStart = fromNodeName.charCodeAt(0);
toCodeStart = toNodeName.charCodeAt(0);
// If the target element is a virtual DOM node or SVG node then we may
// need to normalize the tag name before comparing. Normal HTML elements that are
// in the "http://www.w3.org/1999/xhtml"
// are converted to upper case
if (fromCodeStart <= 90 && toCodeStart >= 97) { // from is upper and to is lower
return fromNodeName === toNodeName.toUpperCase();
} else if (toCodeStart <= 90 && fromCodeStart >= 97) { // to is upper and from is lower
return toNodeName === fromNodeName.toUpperCase();
} else {
return false;
}
} |
JavaScript | function moveChildren(fromEl, toEl) {
var curChild = fromEl.firstChild;
while (curChild) {
var nextChild = curChild.nextSibling;
toEl.appendChild(curChild);
curChild = nextChild;
}
return toEl;
} | function moveChildren(fromEl, toEl) {
var curChild = fromEl.firstChild;
while (curChild) {
var nextChild = curChild.nextSibling;
toEl.appendChild(curChild);
curChild = nextChild;
}
return toEl;
} |
JavaScript | function removeNode(node, parentNode, skipKeyedNodes) {
if (onBeforeNodeDiscarded(node) === false) {
return;
}
if (parentNode) {
parentNode.removeChild(node);
}
onNodeDiscarded(node);
walkDiscardedChildNodes(node, skipKeyedNodes);
} | function removeNode(node, parentNode, skipKeyedNodes) {
if (onBeforeNodeDiscarded(node) === false) {
return;
}
if (parentNode) {
parentNode.removeChild(node);
}
onNodeDiscarded(node);
walkDiscardedChildNodes(node, skipKeyedNodes);
} |
JavaScript | move(dx,dy){
if(game.is_paused){
return false;
}
var player = this.players[this.current_player_id];
//if this move is in the list of possible moves
if(this.possible_moves.findIndex((move) => move.x == dx && move.y == dy) != -1){
player.y += dy;
player.x += dx;
this.nextPlayer();
this.renderer.render();
}
} | move(dx,dy){
if(game.is_paused){
return false;
}
var player = this.players[this.current_player_id];
//if this move is in the list of possible moves
if(this.possible_moves.findIndex((move) => move.x == dx && move.y == dy) != -1){
player.y += dy;
player.x += dx;
this.nextPlayer();
this.renderer.render();
}
} |
JavaScript | place(orientation,x,y,value){
if(game.is_paused){
return false;
}
//If we are placing a new preview wall, we need to remove the last preview wall
if(value == -1) {
this.clearPreviews();
}
//Check if we can place a wall here
if(this.canPlace(orientation,x,y,value)){
//Place the 2 walls
this.setWall(orientation,x,y,value)
//Place the intersection
this.setIntersection(x,y,value)
//If the wall placed is not a preview, switch players and remove a wall from the current player
if(value == 1){
this.players[this.current_player_id].walls -= 1
this.nextPlayer();
}
this.renderer.render();
}
} | place(orientation,x,y,value){
if(game.is_paused){
return false;
}
//If we are placing a new preview wall, we need to remove the last preview wall
if(value == -1) {
this.clearPreviews();
}
//Check if we can place a wall here
if(this.canPlace(orientation,x,y,value)){
//Place the 2 walls
this.setWall(orientation,x,y,value)
//Place the intersection
this.setIntersection(x,y,value)
//If the wall placed is not a preview, switch players and remove a wall from the current player
if(value == 1){
this.players[this.current_player_id].walls -= 1
this.nextPlayer();
}
this.renderer.render();
}
} |
JavaScript | clearPreviews() {
for(var i=0; i < this.vertical_walls.length; i ++){
for(var j=0; j < this.vertical_walls[i].length; j ++){
if(this.vertical_walls[i][j] == -1) this.vertical_walls[i][j] = 0;
}
}
for(var i=0; i < this.horizontal_walls.length; i ++){
for(var j=0; j < this.horizontal_walls[i].length; j ++){
if(this.horizontal_walls[i][j] == -1) this.horizontal_walls[i][j] = 0;
}
}
for(var i=0; i < this.intersections.length; i ++){
for(var j=0; j < this.intersections[i].length; j ++){
if(this.intersections[i][j] == -1) this.intersections[i][j] = 0;
}
}
} | clearPreviews() {
for(var i=0; i < this.vertical_walls.length; i ++){
for(var j=0; j < this.vertical_walls[i].length; j ++){
if(this.vertical_walls[i][j] == -1) this.vertical_walls[i][j] = 0;
}
}
for(var i=0; i < this.horizontal_walls.length; i ++){
for(var j=0; j < this.horizontal_walls[i].length; j ++){
if(this.horizontal_walls[i][j] == -1) this.horizontal_walls[i][j] = 0;
}
}
for(var i=0; i < this.intersections.length; i ++){
for(var j=0; j < this.intersections[i].length; j ++){
if(this.intersections[i][j] == -1) this.intersections[i][j] = 0;
}
}
} |
JavaScript | canMove(x,y,dx,dy){
//Different possible responses
const edge_error = {
possible: false,
reason: "edge"
}
const wall_error = {
possible: false,
reason: "wall"
}
const possible = {
possible: true
}
//Check if this action will hit the edge of the board
if(x + dx >= this.size || x + dx < 0 || y + dy >= this.size || y + dy < 0){
return edge_error;
}
//Check if this action will hit a wall
if(dx > 0){
for(var dist = 0; dist < dx; dist++){
if(this.vertical_walls[y][x+dist] == 1){
return wall_error;
}
}
}
else if(dx < 0){
for(var dist = dx; dist < 0; dist++){
if(this.vertical_walls[y][x+dist] == 1){
return wall_error;
}
}
}
if(dy > 0){
for(var dist = 0; dist <= dy-1; dist++){
if(this.horizontal_walls[y+dist][x] == 1){
return wall_error;
}
}
}
else if(dy < 0){
for(var dist = dy; dist < 0; dist++){
if(this.horizontal_walls[dist+y][x] == 1){
return wall_error;
}
}
}
return possible;
} | canMove(x,y,dx,dy){
//Different possible responses
const edge_error = {
possible: false,
reason: "edge"
}
const wall_error = {
possible: false,
reason: "wall"
}
const possible = {
possible: true
}
//Check if this action will hit the edge of the board
if(x + dx >= this.size || x + dx < 0 || y + dy >= this.size || y + dy < 0){
return edge_error;
}
//Check if this action will hit a wall
if(dx > 0){
for(var dist = 0; dist < dx; dist++){
if(this.vertical_walls[y][x+dist] == 1){
return wall_error;
}
}
}
else if(dx < 0){
for(var dist = dx; dist < 0; dist++){
if(this.vertical_walls[y][x+dist] == 1){
return wall_error;
}
}
}
if(dy > 0){
for(var dist = 0; dist <= dy-1; dist++){
if(this.horizontal_walls[y+dist][x] == 1){
return wall_error;
}
}
}
else if(dy < 0){
for(var dist = dy; dist < 0; dist++){
if(this.horizontal_walls[dist+y][x] == 1){
return wall_error;
}
}
}
return possible;
} |
JavaScript | canPlace(orientation,x,y,value){
//If the current player doesn't have any walls left
if(this.players[this.current_player_id].walls == 0){
return false
}
//Detect if the wall goes out of the map
if (orientation == "h" && (y < 0 || y > this.size - 2 || x > this.size-2 || x < 0)) {
return false;
}
else if (orientation == "v" && (y < 0 || y > this.size - 2 )) {
return false;
}
//Check if the wall will intersect with another wall or another intersection
if(orientation == 'v' && (this.vertical_walls[y+1][x] == 1 || this.vertical_walls[y][x] == 1 || this.intersections[y][x] == 1)){
return false;
}
else if(orientation == "h" && (this.horizontal_walls[y][x+1] == 1 || this.horizontal_walls[y][x] == 1 || this.intersections[y][x] == 1)){
return false;
}
//Check if all players could win if this wall was placed
//Backup all the walls
if(value == 1) {
var old_vertical_walls = new Array(this.size);
var old_horizontal_walls = new Array(this.size - 1);
for(var i = 0; i < this.size; i++){
old_vertical_walls[i] = this.vertical_walls[i].slice(0);
}
for(var i = 0; i < this.size - 1; i++){
old_horizontal_walls[i] = this.horizontal_walls[i].slice(0);
}
//Temporarly place the wall
this.setWall(orientation,x,y,1);
//Check if all player can win
var result = true;
for(var i = 0; i < this.players.length; i++){
if(!this.canWin(this.players[i])){
result = false;
}
}
//Restore the walls
for(var i = 0; i < this.size; i++){
this.vertical_walls[i] = old_vertical_walls[i].slice(0);
}
for(var i = 0; i < this.size - 1; i++){
this.horizontal_walls[i] = old_horizontal_walls[i].slice(0);
}
return result;
}else {
return true;
}
} | canPlace(orientation,x,y,value){
//If the current player doesn't have any walls left
if(this.players[this.current_player_id].walls == 0){
return false
}
//Detect if the wall goes out of the map
if (orientation == "h" && (y < 0 || y > this.size - 2 || x > this.size-2 || x < 0)) {
return false;
}
else if (orientation == "v" && (y < 0 || y > this.size - 2 )) {
return false;
}
//Check if the wall will intersect with another wall or another intersection
if(orientation == 'v' && (this.vertical_walls[y+1][x] == 1 || this.vertical_walls[y][x] == 1 || this.intersections[y][x] == 1)){
return false;
}
else if(orientation == "h" && (this.horizontal_walls[y][x+1] == 1 || this.horizontal_walls[y][x] == 1 || this.intersections[y][x] == 1)){
return false;
}
//Check if all players could win if this wall was placed
//Backup all the walls
if(value == 1) {
var old_vertical_walls = new Array(this.size);
var old_horizontal_walls = new Array(this.size - 1);
for(var i = 0; i < this.size; i++){
old_vertical_walls[i] = this.vertical_walls[i].slice(0);
}
for(var i = 0; i < this.size - 1; i++){
old_horizontal_walls[i] = this.horizontal_walls[i].slice(0);
}
//Temporarly place the wall
this.setWall(orientation,x,y,1);
//Check if all player can win
var result = true;
for(var i = 0; i < this.players.length; i++){
if(!this.canWin(this.players[i])){
result = false;
}
}
//Restore the walls
for(var i = 0; i < this.size; i++){
this.vertical_walls[i] = old_vertical_walls[i].slice(0);
}
for(var i = 0; i < this.size - 1; i++){
this.horizontal_walls[i] = old_horizontal_walls[i].slice(0);
}
return result;
}else {
return true;
}
} |
JavaScript | canWin(player){
//Create an array containing ann the squares of the board
var visited = new Array(this.size);
for(var i = 0; i < this.size; i++){
visited[i] = new Array(this.size);
for(var j = 0; j < this.size; j++){
visited[i][j] = false;
}
}
//Array containing all the cases that needs to be processed
var queue = [];
//initialization, we visit the case where the player currently is
queue.push([player.x,player.y]);
visited[player.y][player.x] = true;
var n,px,py;
//For each squares in the queue, put in the queue all the squares where you can go from here that haven't been visited
//This algorithm will check evry possible paths, and when he finds a way to win, he returns that the player can win
//If after trying all the possibilities, he can't win, return false
while(queue.length > 0){
//Remove first element
n = queue.pop(0);
px = n[0];
py = n[1];
//We found a way to win
if(py == player.targetY){
return true;
}
//Get all the adjacent squares where the player can move
if(this.canMove(px,py,1,0).possible){
if(!visited[py][px+1]){
queue.push([px+1,py]);
visited[py][px+1] = true;
}
}
if(this.canMove(px,py,-1,0).possible){
if(!visited[py][px-1] ){
queue.push([px-1,py]);
visited[py][px-1] = true;
}
}
if(this.canMove(px,py,0,1).possible){
if(!visited[py+1][px]){
queue.push([px,py+1]);
visited[py+1][px] = true;
}
}
if(this.canMove(px,py,0,-1).possible){
if(!visited[py-1][px]){
queue.push([px,py-1]);
visited[py-1][px] = true;
}
}
}
return false;
} | canWin(player){
//Create an array containing ann the squares of the board
var visited = new Array(this.size);
for(var i = 0; i < this.size; i++){
visited[i] = new Array(this.size);
for(var j = 0; j < this.size; j++){
visited[i][j] = false;
}
}
//Array containing all the cases that needs to be processed
var queue = [];
//initialization, we visit the case where the player currently is
queue.push([player.x,player.y]);
visited[player.y][player.x] = true;
var n,px,py;
//For each squares in the queue, put in the queue all the squares where you can go from here that haven't been visited
//This algorithm will check evry possible paths, and when he finds a way to win, he returns that the player can win
//If after trying all the possibilities, he can't win, return false
while(queue.length > 0){
//Remove first element
n = queue.pop(0);
px = n[0];
py = n[1];
//We found a way to win
if(py == player.targetY){
return true;
}
//Get all the adjacent squares where the player can move
if(this.canMove(px,py,1,0).possible){
if(!visited[py][px+1]){
queue.push([px+1,py]);
visited[py][px+1] = true;
}
}
if(this.canMove(px,py,-1,0).possible){
if(!visited[py][px-1] ){
queue.push([px-1,py]);
visited[py][px-1] = true;
}
}
if(this.canMove(px,py,0,1).possible){
if(!visited[py+1][px]){
queue.push([px,py+1]);
visited[py+1][px] = true;
}
}
if(this.canMove(px,py,0,-1).possible){
if(!visited[py-1][px]){
queue.push([px,py-1]);
visited[py-1][px] = true;
}
}
}
return false;
} |
JavaScript | drawControls() {
if(this.game.control_mode == "move") {
for(var i = 0; i < this.game.possible_moves.length; i++){
var player = this.game.players[this.game.current_player_id];
var color = this.colorToHTML(player.color,0.7);
this.drawPawn(player.x + this.game.possible_moves[i].x, player.y + this.game.possible_moves[i].y, color, false);
}
}
} | drawControls() {
if(this.game.control_mode == "move") {
for(var i = 0; i < this.game.possible_moves.length; i++){
var player = this.game.players[this.game.current_player_id];
var color = this.colorToHTML(player.color,0.7);
this.drawPawn(player.x + this.game.possible_moves[i].x, player.y + this.game.possible_moves[i].y, color, false);
}
}
} |
JavaScript | drawPlayers() {
for(var i = 0; i < this.game.players.length; i++){
var border = (i == this.game.current_player_id);
var player = this.game.players[i];
var color = this.colorToHTML(player.color,1);
this.drawPawn(this.game.players[i].x, this.game.players[i].y, color, border, player.walls + "I");
}
} | drawPlayers() {
for(var i = 0; i < this.game.players.length; i++){
var border = (i == this.game.current_player_id);
var player = this.game.players[i];
var color = this.colorToHTML(player.color,1);
this.drawPawn(this.game.players[i].x, this.game.players[i].y, color, border, player.walls + "I");
}
} |
JavaScript | drawWalls() {
//horizontal walls
for(var y = 0; y < this.game.size-1; y++){
for(var x = 0; x < this.game.size; x++){
//Draw the wall only if there is a real wall, or if the wall is a ghost wall and the current control mode is wall placement
if(this.game.horizontal_walls[y][x] == 1 || (this.game.horizontal_walls[y][x] == -1 && this.game.control_mode == "wall")){
//Change the wall color according to if it is a ghost wall or a real one
if(this.game.horizontal_walls[y][x] == 1) {
this.ctx.strokeStyle = this.wall;
}
if(this.game.horizontal_walls[y][x] == -1) {
this.ctx.strokeStyle = this.wall_preview;
}
//Draw the wall
this.ctx.beginPath();
this.ctx.moveTo(this.case_width * (x + 1 ) - this.wall_width / 2, this.case_height * (y + 1 ));
this.ctx.lineTo(this.case_width * x + this.wall_width / 2, this.case_height * (y + 1 ));
this.ctx.lineWidth = this.wall_width;
this.ctx.stroke();
}
}
}
//Same thing for vertical walls
for(var y = 0; y < this.game.size; y++){
for(var x = 0; x < this.game.size-1; x++){
if(this.game.vertical_walls[y][x] == 1 || (this.game.vertical_walls[y][x] == -1 && this.game.control_mode == "wall")){
if(this.game.vertical_walls[y][x] == 1) {
this.ctx.strokeStyle = this.wall;
}
if(this.game.vertical_walls[y][x] == -1) {
this.ctx.strokeStyle = this.wall_preview;
}
this.ctx.beginPath()
this.ctx.moveTo(this.case_width * ( x + 1 ), this.case_height * y + this.wall_width / 2);
this.ctx.lineTo(this.case_width * ( x + 1 ), this.case_height * ( y + 1 ) - this.wall_width / 2);
this.ctx.lineWidth = this.wall_width;
this.ctx.stroke();
}
}
}
//Same thing for intersections
for(var y = 0; y < this.game.size-1; y++){
for(var x = 0; x < this.game.size-1; x++){
if(this.game.intersections[y][x] == 1 || (this.game.intersections[y][x] == -1 && this.game.control_mode == "wall")){
if(this.game.intersections[y][x] == 1) {
this.ctx.strokeStyle = this.wall;
}
else if(this.game.intersections[y][x] == -1) {
this.ctx.strokeStyle = this.wall_preview;
}
this.ctx.beginPath();
this.ctx.moveTo(this.case_width * ( x + 1 ), this.case_height * (y + 1) + this.wall_width / 2);
this.ctx.lineTo(this.case_width * ( x + 1 ), this.case_height * (y + 1) - this.wall_width / 2);
this.ctx.lineWidth = this.wall_width + 1;
this.ctx.stroke();
}
}
}
} | drawWalls() {
//horizontal walls
for(var y = 0; y < this.game.size-1; y++){
for(var x = 0; x < this.game.size; x++){
//Draw the wall only if there is a real wall, or if the wall is a ghost wall and the current control mode is wall placement
if(this.game.horizontal_walls[y][x] == 1 || (this.game.horizontal_walls[y][x] == -1 && this.game.control_mode == "wall")){
//Change the wall color according to if it is a ghost wall or a real one
if(this.game.horizontal_walls[y][x] == 1) {
this.ctx.strokeStyle = this.wall;
}
if(this.game.horizontal_walls[y][x] == -1) {
this.ctx.strokeStyle = this.wall_preview;
}
//Draw the wall
this.ctx.beginPath();
this.ctx.moveTo(this.case_width * (x + 1 ) - this.wall_width / 2, this.case_height * (y + 1 ));
this.ctx.lineTo(this.case_width * x + this.wall_width / 2, this.case_height * (y + 1 ));
this.ctx.lineWidth = this.wall_width;
this.ctx.stroke();
}
}
}
//Same thing for vertical walls
for(var y = 0; y < this.game.size; y++){
for(var x = 0; x < this.game.size-1; x++){
if(this.game.vertical_walls[y][x] == 1 || (this.game.vertical_walls[y][x] == -1 && this.game.control_mode == "wall")){
if(this.game.vertical_walls[y][x] == 1) {
this.ctx.strokeStyle = this.wall;
}
if(this.game.vertical_walls[y][x] == -1) {
this.ctx.strokeStyle = this.wall_preview;
}
this.ctx.beginPath()
this.ctx.moveTo(this.case_width * ( x + 1 ), this.case_height * y + this.wall_width / 2);
this.ctx.lineTo(this.case_width * ( x + 1 ), this.case_height * ( y + 1 ) - this.wall_width / 2);
this.ctx.lineWidth = this.wall_width;
this.ctx.stroke();
}
}
}
//Same thing for intersections
for(var y = 0; y < this.game.size-1; y++){
for(var x = 0; x < this.game.size-1; x++){
if(this.game.intersections[y][x] == 1 || (this.game.intersections[y][x] == -1 && this.game.control_mode == "wall")){
if(this.game.intersections[y][x] == 1) {
this.ctx.strokeStyle = this.wall;
}
else if(this.game.intersections[y][x] == -1) {
this.ctx.strokeStyle = this.wall_preview;
}
this.ctx.beginPath();
this.ctx.moveTo(this.case_width * ( x + 1 ), this.case_height * (y + 1) + this.wall_width / 2);
this.ctx.lineTo(this.case_width * ( x + 1 ), this.case_height * (y + 1) - this.wall_width / 2);
this.ctx.lineWidth = this.wall_width + 1;
this.ctx.stroke();
}
}
}
} |
JavaScript | function EditImageController(
$scope,
imageFormats,
validationRules,
settings
) {
var ctrl = this;
settings.getSettings().then(getConfiguredFormats);
ctrl.diskFormats = [];
ctrl.validationRules = validationRules;
ctrl.imageProtectedOptions = [
{ label: gettext('Yes'), value: true },
{ label: gettext('No'), value: false }
];
ctrl.imageVisibilityOptions = [
{ label: gettext('Public'), value: 'public'},
{ label: gettext('Private'), value: 'private' }
];
ctrl.setFormats = setFormats;
ctrl.allowPublicizeImage = { rules: [['image', 'image:publicize_image']]};
$scope.imagePromise.then(init);
///////////////////////////
function getConfiguredFormats(response) {
var settingsFormats = response.OPENSTACK_IMAGE_FORMATS;
var dupe = angular.copy(imageFormats);
angular.forEach(dupe, function stripUnknown(name, key) {
if (settingsFormats.indexOf(key) === -1) {
delete dupe[key];
}
});
ctrl.imageFormats = dupe;
}
function init(response) {
ctrl.image = response.data;
ctrl.image.kernel = ctrl.image.properties.kernel_id;
ctrl.image.ramdisk = ctrl.image.properties.ramdisk_id;
ctrl.image.architecture = ctrl.image.properties.architecture;
ctrl.image.visibility = ctrl.image.is_public ? 'public' : 'private';
ctrl.image_format = ctrl.image.disk_format;
if (ctrl.image.container_format === 'docker') {
ctrl.image_format = 'docker';
ctrl.image.disk_format = 'raw';
}
setFormats();
}
function setFormats() {
ctrl.image.container_format = 'bare';
if (['aki', 'ami', 'ari'].indexOf(ctrl.image_format) > -1) {
ctrl.image.container_format = ctrl.image_format;
}
ctrl.image.disk_format = ctrl.image_format;
if (ctrl.image_format === 'docker') {
ctrl.image.container_format = 'docker';
ctrl.image.disk_format = 'raw';
}
}
} // end of controller | function EditImageController(
$scope,
imageFormats,
validationRules,
settings
) {
var ctrl = this;
settings.getSettings().then(getConfiguredFormats);
ctrl.diskFormats = [];
ctrl.validationRules = validationRules;
ctrl.imageProtectedOptions = [
{ label: gettext('Yes'), value: true },
{ label: gettext('No'), value: false }
];
ctrl.imageVisibilityOptions = [
{ label: gettext('Public'), value: 'public'},
{ label: gettext('Private'), value: 'private' }
];
ctrl.setFormats = setFormats;
ctrl.allowPublicizeImage = { rules: [['image', 'image:publicize_image']]};
$scope.imagePromise.then(init);
///////////////////////////
function getConfiguredFormats(response) {
var settingsFormats = response.OPENSTACK_IMAGE_FORMATS;
var dupe = angular.copy(imageFormats);
angular.forEach(dupe, function stripUnknown(name, key) {
if (settingsFormats.indexOf(key) === -1) {
delete dupe[key];
}
});
ctrl.imageFormats = dupe;
}
function init(response) {
ctrl.image = response.data;
ctrl.image.kernel = ctrl.image.properties.kernel_id;
ctrl.image.ramdisk = ctrl.image.properties.ramdisk_id;
ctrl.image.architecture = ctrl.image.properties.architecture;
ctrl.image.visibility = ctrl.image.is_public ? 'public' : 'private';
ctrl.image_format = ctrl.image.disk_format;
if (ctrl.image.container_format === 'docker') {
ctrl.image_format = 'docker';
ctrl.image.disk_format = 'raw';
}
setFormats();
}
function setFormats() {
ctrl.image.container_format = 'bare';
if (['aki', 'ami', 'ari'].indexOf(ctrl.image_format) > -1) {
ctrl.image.container_format = ctrl.image_format;
}
ctrl.image.disk_format = ctrl.image_format;
if (ctrl.image_format === 'docker') {
ctrl.image.container_format = 'docker';
ctrl.image.disk_format = 'raw';
}
}
} // end of controller |
JavaScript | function updateProjectQuota(quota, projectId) {
var url = '/api/cinder/quota-sets/' + projectId;
return apiService.patch(url, quota)
.error(function() {
toastService.add('error', gettext('Unable to update project quota data.'));
});
} | function updateProjectQuota(quota, projectId) {
var url = '/api/cinder/quota-sets/' + projectId;
return apiService.patch(url, quota)
.error(function() {
toastService.add('error', gettext('Unable to update project quota data.'));
});
} |
JavaScript | function trunksService(neutron, userSession, detailRoute, $location) {
return {
getDetailsPath: getDetailsPath,
getTrunksPromise: getTrunksPromise,
getTrunkPromise: getTrunkPromise
};
/*
* @ngdoc function
* @name getDetailsPath
* @param item {Object} - The trunk object
* @description
* Given a Trunk object, returns the relative path to the details
* view.
*/
function getDetailsPath(item) {
return detailRoute + 'OS::Neutron::Trunk/' + item.id;
}
/*
* @ngdoc function
* @name getTrunksPromise
* @description
* Given filter/query parameters, returns a promise for the matching
* trunks. This is used in displaying lists of Trunks.
*/
function getTrunksPromise(params) {
return userSession.get().then(getTrunksForProject);
function getTrunksForProject(userSession) {
params.project_id = userSession.project_id;
return neutron.getTrunks(params);
}
}
/*
* @ngdoc function
* @name getTrunkPromise
* @description
* Given an id, returns a promise for the trunk data.
*/
function getTrunkPromise(identifier) {
return neutron.getTrunk(identifier).then(getTrunkSuccess, getTrunkError);
function getTrunkSuccess(trunk) {
return trunk;
}
function getTrunkError(trunk) {
$location.url('project/trunks');
return trunk;
}
}
} | function trunksService(neutron, userSession, detailRoute, $location) {
return {
getDetailsPath: getDetailsPath,
getTrunksPromise: getTrunksPromise,
getTrunkPromise: getTrunkPromise
};
/*
* @ngdoc function
* @name getDetailsPath
* @param item {Object} - The trunk object
* @description
* Given a Trunk object, returns the relative path to the details
* view.
*/
function getDetailsPath(item) {
return detailRoute + 'OS::Neutron::Trunk/' + item.id;
}
/*
* @ngdoc function
* @name getTrunksPromise
* @description
* Given filter/query parameters, returns a promise for the matching
* trunks. This is used in displaying lists of Trunks.
*/
function getTrunksPromise(params) {
return userSession.get().then(getTrunksForProject);
function getTrunksForProject(userSession) {
params.project_id = userSession.project_id;
return neutron.getTrunks(params);
}
}
/*
* @ngdoc function
* @name getTrunkPromise
* @description
* Given an id, returns a promise for the trunk data.
*/
function getTrunkPromise(identifier) {
return neutron.getTrunk(identifier).then(getTrunkSuccess, getTrunkError);
function getTrunkSuccess(trunk) {
return trunk;
}
function getTrunkError(trunk) {
$location.url('project/trunks');
return trunk;
}
}
} |
JavaScript | applyTo2d(options) {
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.grayscaleFilter.applyTo2d(options);
} | applyTo2d(options) {
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.grayscaleFilter.applyTo2d(options);
} |
JavaScript | applyTo2d(options) {
this.blendFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.hueRotationFilter.applyTo(options);
this.saturationFilter.applyTo2d(options);
} | applyTo2d(options) {
this.blendFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.hueRotationFilter.applyTo(options);
this.saturationFilter.applyTo2d(options);
} |
JavaScript | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height, '#a0a0a0');
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData, softLight);
this.blendFilter.applyTo2d(options);
this.grayscaleFilter.applyTo2d(options);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
} | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height, '#a0a0a0');
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData, softLight);
this.blendFilter.applyTo2d(options);
this.grayscaleFilter.applyTo2d(options);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
} |
JavaScript | fire(...args) {
const context = this.graphics;
return this.graphics.fire.apply(context, args);
} | fire(...args) {
const context = this.graphics;
return this.graphics.fire.apply(context, args);
} |
JavaScript | calculatePixelSize() {
const canvas = this.getCanvas();
const canvasWidth = canvas.getWidth();
const canvasHeight = canvas.getHeight();
const wrapperWidth = canvas.wrapperEl.offsetWidth;
const wrapperHeight = canvas.wrapperEl.offsetHeight;
const hPixelSize = canvasWidth / wrapperWidth;
const vPixelSize = canvasHeight / wrapperHeight;
return Math.max(hPixelSize, vPixelSize);
} | calculatePixelSize() {
const canvas = this.getCanvas();
const canvasWidth = canvas.getWidth();
const canvasHeight = canvas.getHeight();
const wrapperWidth = canvas.wrapperEl.offsetWidth;
const wrapperHeight = canvas.wrapperEl.offsetHeight;
const hPixelSize = canvasWidth / wrapperWidth;
const vPixelSize = canvasHeight / wrapperHeight;
return Math.max(hPixelSize, vPixelSize);
} |
JavaScript | _onFabricMouseUp() {
const cropzone = this._cropzone;
const listeners = this._listeners;
const canvas = this.getCanvas();
canvas.setActiveObject(cropzone);
canvas.off({
'mouse:move': listeners.mousemove,
'mouse:up': listeners.mouseup
});
} | _onFabricMouseUp() {
const cropzone = this._cropzone;
const listeners = this._listeners;
const canvas = this.getCanvas();
canvas.setActiveObject(cropzone);
canvas.off({
'mouse:move': listeners.mousemove,
'mouse:up': listeners.mouseup
});
} |
JavaScript | updateCropzoneRect(aspectRatio, fixAspect, initialSizeInPercent) {
if (!this._isCropzoneSet()) {
this.setCropzoneRect(aspectRatio || 1, fixAspect, initialSizeInPercent);
} else {
this._renderCropzoneRect(aspectRatio, fixAspect, ar => this._updateCurrentCropzoneRect(ar, fixAspect));
}
} | updateCropzoneRect(aspectRatio, fixAspect, initialSizeInPercent) {
if (!this._isCropzoneSet()) {
this.setCropzoneRect(aspectRatio || 1, fixAspect, initialSizeInPercent);
} else {
this._renderCropzoneRect(aspectRatio, fixAspect, ar => this._updateCurrentCropzoneRect(ar, fixAspect));
}
} |
JavaScript | _renderCropzoneRect(aspectRatio, fixAspect, dimensionFactory) {
const canvas = this.getCanvas();
const cropzone = this._cropzone;
this._fixedAspectRatio = fixAspect ? aspectRatio : null;
canvas.discardActiveObject();
canvas.selection = false;
canvas.remove(cropzone);
cropzone.set(dimensionFactory(aspectRatio));
canvas.add(cropzone);
canvas.selection = true;
canvas.setActiveObject(cropzone);
} | _renderCropzoneRect(aspectRatio, fixAspect, dimensionFactory) {
const canvas = this.getCanvas();
const cropzone = this._cropzone;
this._fixedAspectRatio = fixAspect ? aspectRatio : null;
canvas.discardActiveObject();
canvas.selection = false;
canvas.remove(cropzone);
cropzone.set(dimensionFactory(aspectRatio));
canvas.add(cropzone);
canvas.selection = true;
canvas.setActiveObject(cropzone);
} |
JavaScript | _updateCurrentCropzoneRect(aspectRatio, fixAspect) {
const canvas = this.getCanvas();
const cr = this.getCropzoneRect();
const currentAspect = cr.width / cr.height;
aspectRatio = aspectRatio || currentAspect;
const maxSize = Math.max(cr.width, cr.height);
const widthRatio = maxSize / canvas.getWidth();
const heightRatio = maxSize / canvas.getHeight();
const newRatioIsPortraitButOldIsLandscape = aspectRatio < 1 && currentAspect >= 1;
const newRatioIsLandscapeButOldIsPortrait = aspectRatio >= 1 && currentAspect < 1;
const scale = (newRatioIsPortraitButOldIsLandscape || newRatioIsLandscapeButOldIsPortrait)
? Math.max(widthRatio, heightRatio, 1)
: 1;
return this._ensureNewCropzoneRectIsinBoundary(aspectRatio, fixAspect, maxSize, scale);
} | _updateCurrentCropzoneRect(aspectRatio, fixAspect) {
const canvas = this.getCanvas();
const cr = this.getCropzoneRect();
const currentAspect = cr.width / cr.height;
aspectRatio = aspectRatio || currentAspect;
const maxSize = Math.max(cr.width, cr.height);
const widthRatio = maxSize / canvas.getWidth();
const heightRatio = maxSize / canvas.getHeight();
const newRatioIsPortraitButOldIsLandscape = aspectRatio < 1 && currentAspect >= 1;
const newRatioIsLandscapeButOldIsPortrait = aspectRatio >= 1 && currentAspect < 1;
const scale = (newRatioIsPortraitButOldIsLandscape || newRatioIsLandscapeButOldIsPortrait)
? Math.max(widthRatio, heightRatio, 1)
: 1;
return this._ensureNewCropzoneRectIsinBoundary(aspectRatio, fixAspect, maxSize, scale);
} |
JavaScript | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const overlayLayer = this.createTopLayer(width, height, '#b77d21');
const colorDodgeLayer = this.createTopLayer(width, height, '#382c34');
const overlayLayerImageData = overlayLayer.getImageData(0, 0, width, height);
const colorDodgeLayerImageData = colorDodgeLayer.getImageData(0, 0, width, height);
blend(options.imageData, overlayLayerImageData, overlay);
blend(options.imageData, colorDodgeLayerImageData, colorDodge);
} | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const overlayLayer = this.createTopLayer(width, height, '#b77d21');
const colorDodgeLayer = this.createTopLayer(width, height, '#382c34');
const overlayLayerImageData = overlayLayer.getImageData(0, 0, width, height);
const colorDodgeLayerImageData = colorDodgeLayer.getImageData(0, 0, width, height);
blend(options.imageData, overlayLayerImageData, overlay);
blend(options.imageData, colorDodgeLayerImageData, colorDodge);
} |
JavaScript | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height);
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData,
(bottomPixel, topPixel) => 255 - (255 - topPixel) * (255 - bottomPixel) / 255);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
} | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height);
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData,
(bottomPixel, topPixel) => 255 - (255 - topPixel) * (255 - bottomPixel) / 255);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
} |
JavaScript | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const colorDodgeLayer = this.createTopLayer(width, height, '#22253f');
const colorDodgeLayerImageData = colorDodgeLayer.getImageData(0, 0, width, height);
blend(options.imageData, colorDodgeLayerImageData, colorDodge);
this.blendFilter.applyTo2d(options);
} | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const colorDodgeLayer = this.createTopLayer(width, height, '#22253f');
const colorDodgeLayerImageData = colorDodgeLayer.getImageData(0, 0, width, height);
blend(options.imageData, colorDodgeLayerImageData, colorDodge);
this.blendFilter.applyTo2d(options);
} |
JavaScript | _setGridStyle(gridStyle, {applyStraightenGridStyle}) {
if (applyStraightenGridStyle) {
this._graphics.setStraightenGridStyle(gridStyle);
}
} | _setGridStyle(gridStyle, {applyStraightenGridStyle}) {
if (applyStraightenGridStyle) {
this._graphics.setStraightenGridStyle(gridStyle);
}
} |
JavaScript | applyTo2d(options) {
this.blendFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.hueRotationFilter.applyTo(options);
this.contrastFilter.applyTo2d(options);
} | applyTo2d(options) {
this.blendFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.hueRotationFilter.applyTo(options);
this.contrastFilter.applyTo2d(options);
} |
JavaScript | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height);
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData, multiply);
this.contrastFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height);
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData, multiply);
this.contrastFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} |
JavaScript | start() {
const canvas = this.getCanvas();
this._isSelected = false;
canvas.defaultCursor = 'crosshair';
canvas.selection = false;
this.graphics.getComponent(componentNames.LOCK).start();
} | start() {
const canvas = this.getCanvas();
this._isSelected = false;
canvas.defaultCursor = 'crosshair';
canvas.selection = false;
this.graphics.getComponent(componentNames.LOCK).start();
} |
JavaScript | end() {
const canvas = this.getCanvas();
this._isSelected = false;
canvas.defaultCursor = 'default';
canvas.selection = true;
this.graphics.getComponent(componentNames.LOCK).end();
} | end() {
const canvas = this.getCanvas();
this._isSelected = false;
canvas.defaultCursor = 'default';
canvas.selection = true;
this.graphics.getComponent(componentNames.LOCK).end();
} |
JavaScript | registerUniformScalingPaths(uniformScaling) {
snippet.forEach(uniformScaling, (isUniformScaling, type) => {
this._uniformScalingPathMap[type] = isUniformScaling;
}, this);
} | registerUniformScalingPaths(uniformScaling) {
snippet.forEach(uniformScaling, (isUniformScaling, type) => {
this._uniformScalingPathMap[type] = isUniformScaling;
}, this);
} |
JavaScript | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height);
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData, overlay);
this.brightnessFilter.applyTo2d(options);
} | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height);
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData, overlay);
this.brightnessFilter.applyTo2d(options);
} |
JavaScript | applyTo2d(options) {
this.blendFilter.applyTo2d(options);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} | applyTo2d(options) {
this.blendFilter.applyTo2d(options);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} |
JavaScript | applyTo2d(options) {
this.blendFilter.applyTo2d(options);
this.contrastFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} | applyTo2d(options) {
this.blendFilter.applyTo2d(options);
this.contrastFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} |
JavaScript | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height);
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData, softLight);
} | applyTo2d(options) {
const width = options.sourceWidth;
const height = options.sourceHeight;
const topLayer = this.createTopLayer(width, height);
const topLayerImageData = topLayer.getImageData(0, 0, width, height);
blend(options.imageData, topLayerImageData, softLight);
} |
JavaScript | applyTo2d(options) {
this.hueRotationFilter.applyTo(options);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} | applyTo2d(options) {
this.hueRotationFilter.applyTo(options);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} |
JavaScript | applyTo2d(options) {
this.darkenBlendFilter.applyTo2d(options);
this.lightenBlendFilter.applyTo2d(options);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} | applyTo2d(options) {
this.darkenBlendFilter.applyTo2d(options);
this.lightenBlendFilter.applyTo2d(options);
this.contrastFilter.applyTo2d(options);
this.brightnessFilter.applyTo2d(options);
this.saturationFilter.applyTo2d(options);
} |
JavaScript | function QMModel(db, tableName, fields) {
this.filterConditions = {};
this.sorters = [];
this.limiters = null;
this._meta = {
db: db,
tableName: tableName,
fields: fields,
};
} | function QMModel(db, tableName, fields) {
this.filterConditions = {};
this.sorters = [];
this.limiters = null;
this._meta = {
db: db,
tableName: tableName,
fields: fields,
};
} |
JavaScript | function QMObject(model) {
this._meta = {
model: model,
};
this.id = null;
//Functions for single object
//save
this.save = function(forceInsert) {
if (typeof forceInsert === 'undefined') { forceInsert = false; }
var updateFields = {};
for (var newValue in this) {
if (newValue !== 'save' && newValue !== '_meta') {
updateFields[newValue] = this[newValue];
}
}
if (this.id && !forceInsert) {
model.filter({id: this.id}).update(updateFields);
} else {
model.insert(updateFields);
}
}
} | function QMObject(model) {
this._meta = {
model: model,
};
this.id = null;
//Functions for single object
//save
this.save = function(forceInsert) {
if (typeof forceInsert === 'undefined') { forceInsert = false; }
var updateFields = {};
for (var newValue in this) {
if (newValue !== 'save' && newValue !== '_meta') {
updateFields[newValue] = this[newValue];
}
}
if (this.id && !forceInsert) {
model.filter({id: this.id}).update(updateFields);
} else {
model.insert(updateFields);
}
}
} |
JavaScript | function QMField(type, label, params) {
this.items = [];
var fieldName;
this.type = type;
this.params = params;
} | function QMField(type, label, params) {
this.items = [];
var fieldName;
this.type = type;
this.params = params;
} |
JavaScript | function ee_init(ee_textbox){
/*Add the required icons*/
/*EasyEditor is using icons from css.gg<https://css.gg | https://github.com/astrit/css.gg> */
var icons = ['format-left', 'format-center', 'format-right', 'format-color',
'format-bold', 'format-italic', 'format-underline', 'layout-list',
'link', 'image', 'code-slash', 'quote-o', 'smile-mouth-open', 'info'];
$('head').append("<link href='https://css.gg/css?=" + icons.join('|') + "' rel='stylesheet'>");
/*Define frame's IDs.*/
var ee_text_id = 'ee-t-'+ee_textbox.attr("id");
var ee_frame_id = 'ee-f-'+ee_textbox.attr("id");
/*Define frame body.*/
var ee_frame_body = "<div class='ee-frame' id='"+ee_frame_id+"'><ul>";
ee_frame_body += "<li title='Bold' id='ee-bold' class='no-right-padding'><i class='gg-format-bold'></i></li>";
ee_frame_body += "<li title='Italic' id='ee-italic' class='no-right-padding'><i class='gg-format-italic'></i></li>";
ee_frame_body += "<li title='Underline' id='ee-underline' class='right-space'><i class='gg-format-underline'></i></li>";
ee_frame_body += "<li title='Align Left' id='ee-left' class='adjust-button'><i class='gg-format-left'></i></li>";
ee_frame_body += "<li title='Align Center' id='ee-center' class='adjust-button'><i class='gg-format-center'></i></li>";
ee_frame_body += "<li title='Align Right' id='ee-right' class='right-space adjust-button'><i class='gg-format-right'></i></li>";
ee_frame_body += "<li title='Font' id='ee-font' class='right-space adjust-font-button'><i class='gg-format-color'></i></li>";
ee_frame_body += "<li title='Link' id='ee-link' class='adjust-font-button'><i class='gg-link'></i></li>";
ee_frame_body += "<li title='Image' id='ee-image' class='small-right-space top-space'><i class='gg-image'></i></li>";
ee_frame_body += "<li title='List Item' id='ee-list' class='right-space adjust-font-button'><i class='gg-layout-list'></i></li>";
ee_frame_body += "<li title='Code' id='ee-code' class='no-right-padding'><i class='gg-code-slash'></i></li>";
ee_frame_body += "<li title='Quote' id='ee-quote' class='top-space'><i class='gg-quote-o'></i></li>";
ee_frame_body += "<li title='Emoji' id='ee-emoji' class='no-top-space'><i class='gg-smile-mouth-open'></i></li>";
ee_frame_body += "<li title='About' id='ee-about' class='no-top-space about-button'><i class='gg-info'></i></li>";
ee_frame_body += "</ul></div>";
ee_frame_body += "<div class='ee-preview' id='"+ee_text_id+"' title='Preview Window'></div>";
/*Validate the textarea height and width.*/
if (ee_textbox.height() < 300)
ee_textbox.height(300);
if (ee_textbox.width() < 500)
ee_textbox.width(500);
/*Add the frame to textarea.*/
ee_textbox.addClass('ee-textbox');
ee_textbox.before(ee_frame_body);
$('#'+ee_frame_id).width(ee_textbox.width());
$('#'+ee_text_id).width(ee_textbox.width());
$('#'+ee_text_id).height((ee_textbox.height() / 2));
ee_textbox.height((ee_textbox.height() / 2));
} | function ee_init(ee_textbox){
/*Add the required icons*/
/*EasyEditor is using icons from css.gg<https://css.gg | https://github.com/astrit/css.gg> */
var icons = ['format-left', 'format-center', 'format-right', 'format-color',
'format-bold', 'format-italic', 'format-underline', 'layout-list',
'link', 'image', 'code-slash', 'quote-o', 'smile-mouth-open', 'info'];
$('head').append("<link href='https://css.gg/css?=" + icons.join('|') + "' rel='stylesheet'>");
/*Define frame's IDs.*/
var ee_text_id = 'ee-t-'+ee_textbox.attr("id");
var ee_frame_id = 'ee-f-'+ee_textbox.attr("id");
/*Define frame body.*/
var ee_frame_body = "<div class='ee-frame' id='"+ee_frame_id+"'><ul>";
ee_frame_body += "<li title='Bold' id='ee-bold' class='no-right-padding'><i class='gg-format-bold'></i></li>";
ee_frame_body += "<li title='Italic' id='ee-italic' class='no-right-padding'><i class='gg-format-italic'></i></li>";
ee_frame_body += "<li title='Underline' id='ee-underline' class='right-space'><i class='gg-format-underline'></i></li>";
ee_frame_body += "<li title='Align Left' id='ee-left' class='adjust-button'><i class='gg-format-left'></i></li>";
ee_frame_body += "<li title='Align Center' id='ee-center' class='adjust-button'><i class='gg-format-center'></i></li>";
ee_frame_body += "<li title='Align Right' id='ee-right' class='right-space adjust-button'><i class='gg-format-right'></i></li>";
ee_frame_body += "<li title='Font' id='ee-font' class='right-space adjust-font-button'><i class='gg-format-color'></i></li>";
ee_frame_body += "<li title='Link' id='ee-link' class='adjust-font-button'><i class='gg-link'></i></li>";
ee_frame_body += "<li title='Image' id='ee-image' class='small-right-space top-space'><i class='gg-image'></i></li>";
ee_frame_body += "<li title='List Item' id='ee-list' class='right-space adjust-font-button'><i class='gg-layout-list'></i></li>";
ee_frame_body += "<li title='Code' id='ee-code' class='no-right-padding'><i class='gg-code-slash'></i></li>";
ee_frame_body += "<li title='Quote' id='ee-quote' class='top-space'><i class='gg-quote-o'></i></li>";
ee_frame_body += "<li title='Emoji' id='ee-emoji' class='no-top-space'><i class='gg-smile-mouth-open'></i></li>";
ee_frame_body += "<li title='About' id='ee-about' class='no-top-space about-button'><i class='gg-info'></i></li>";
ee_frame_body += "</ul></div>";
ee_frame_body += "<div class='ee-preview' id='"+ee_text_id+"' title='Preview Window'></div>";
/*Validate the textarea height and width.*/
if (ee_textbox.height() < 300)
ee_textbox.height(300);
if (ee_textbox.width() < 500)
ee_textbox.width(500);
/*Add the frame to textarea.*/
ee_textbox.addClass('ee-textbox');
ee_textbox.before(ee_frame_body);
$('#'+ee_frame_id).width(ee_textbox.width());
$('#'+ee_text_id).width(ee_textbox.width());
$('#'+ee_text_id).height((ee_textbox.height() / 2));
ee_textbox.height((ee_textbox.height() / 2));
} |
JavaScript | function ee_font_panel(ee_button){
//different font properties
var fonts = ['Tahoma', 'Calibri', 'Times New Roman', 'Arial', 'Aharoni',
'Bodoni MT', 'Dotum', 'MS Outlook', 'Consolas', 'Gill Sans MT',
'Vladimir Script', 'Gigi', 'Elephant', 'Fira Code', 'Magneto'];
var colors = ['Black', 'Red', 'Blue',
'Green', 'Yellow', 'Orange',
'Brown', 'Pink', 'Gray',
'SkyBlue', 'LimeGreen', 'SlateGray'];
var sizes = [10, 11, 12, 14, 16, 18, 22, 24, 28, 32, 40, 60];
var fpanel_fonts = '';
var fpanel_colors = '';
var fpanel_sizes = '';
fonts.forEach(function(font){
fpanel_fonts = fpanel_fonts + "<option>" + font + "</option>";
});
colors.forEach(function(color){
fpanel_colors = fpanel_colors + "<option>" + color + "</option>";
});
sizes.forEach(function(size){
fpanel_sizes = fpanel_sizes + "<option>" + size + "pt</option>";
});
/*Define font panel body.*/
var ee_fpanel_body = "\
<div class='ee-fpanel'>\
<select id='ee-font-family' title='Font Family'>\
" + fpanel_fonts + "\
</select>\
<select id='ee-font-size' title='Font Size'>\
" + fpanel_sizes + "\
</select>\
<select id='ee-font-color' title='Font Color'>\
" + fpanel_colors + "\
</select>\
<button id='ee-font-ok'>Apply</button>\
</div>\
";
$(ee_button).after(ee_fpanel_body);
} | function ee_font_panel(ee_button){
//different font properties
var fonts = ['Tahoma', 'Calibri', 'Times New Roman', 'Arial', 'Aharoni',
'Bodoni MT', 'Dotum', 'MS Outlook', 'Consolas', 'Gill Sans MT',
'Vladimir Script', 'Gigi', 'Elephant', 'Fira Code', 'Magneto'];
var colors = ['Black', 'Red', 'Blue',
'Green', 'Yellow', 'Orange',
'Brown', 'Pink', 'Gray',
'SkyBlue', 'LimeGreen', 'SlateGray'];
var sizes = [10, 11, 12, 14, 16, 18, 22, 24, 28, 32, 40, 60];
var fpanel_fonts = '';
var fpanel_colors = '';
var fpanel_sizes = '';
fonts.forEach(function(font){
fpanel_fonts = fpanel_fonts + "<option>" + font + "</option>";
});
colors.forEach(function(color){
fpanel_colors = fpanel_colors + "<option>" + color + "</option>";
});
sizes.forEach(function(size){
fpanel_sizes = fpanel_sizes + "<option>" + size + "pt</option>";
});
/*Define font panel body.*/
var ee_fpanel_body = "\
<div class='ee-fpanel'>\
<select id='ee-font-family' title='Font Family'>\
" + fpanel_fonts + "\
</select>\
<select id='ee-font-size' title='Font Size'>\
" + fpanel_sizes + "\
</select>\
<select id='ee-font-color' title='Font Color'>\
" + fpanel_colors + "\
</select>\
<button id='ee-font-ok'>Apply</button>\
</div>\
";
$(ee_button).after(ee_fpanel_body);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.