<commit_before>
var multer = require('multer'),
pg = require('pg'),
mkdirp = require('mkdirp'),
fs = require('fs'),
query = require('pg-query'),
escape = require('pg-escape'),
config = require('../../app/config');

		//configuration
		query.connectionParameters = process.env.DATABASE_URL;

		module.exports = Project = {
		// projcts and song
		getAll: function(req, res) {
			'use strict';
			console.log("DEBUG: GET ALL PROJECTS ORDER BY id");

			var sql = escape("SELECT * FROM Project ORDER BY id");
			query(sql, function(err, rows, result) {
				if(err) {
					console.error(err);
					res.send("Error " + err);
				} else {
					res.send(rows);
					console.log(rows);
				}
			});
		},
		get: function(req, res) {
			console.log("DEBUG: GET PROJECT (with songs) id: " + req.params.id);
			var param = req.params.id,
			resultObj = {};

				// is param a number or a string?
				if(+param === +param) {
					//getting all info from project table
					var sql2 = escape("SELECT * from Project where id ="
						+ req.params.id + "");

					query(sql2, function(err2, rows2, result2) {
						if(err2) {
							console.error("err2: " + err2);
							res.send(err2);
						} else {
							resultObj = rows2[0];
							// getting all songs for the project
							var sql = escape("SELECT * from Song where projectid ="
								+ req.params.id + " ORDER BY id");

							query(sql, function(err, rows, result) {
								if(err) {
									console.error("Err: " + err);
									res.send("Error " + err);
								} else {
									resultObj['songs'] = rows;

									// getting influences
									Project.selectFromDB(req.params.id, "projectinfluence", function(err, rows) {
										if(err) {
											console.log("could not get influences: " + err);
											res.send(err);
										}	else {
											console.log("getInfluences");
											resultObj['influences'] = rows;
									  	// getting participation
									  	Project.selectFromDB(req.params.id, "projectparticipation", function(err, rows) {
												if(err) {
													console.log("could not get participation: " + err);
													res.send(err);
												}	else {
													resultObj['participation'] = rows;
											  	res.send(resultObj);

												}
											});
										}
									});
								}
							});
						}
					});
				} else {
					console.log("Could not find a project with id: " + param);
					res.status(404).json("Could not find a project with id: " + param);
				}
		},

		post: [ multer({
			//multer configuration:
				dest: './public/media/images/',

			}),
		function(req, res) {
			console.log("transloadit requst/response");
			console.log(req.transloadit);
			/*console.log(req.uploads);
			console.log(req.fields);*/
			if(req.body.id) {
				Project.put(req, res);
			} else {
				console.log("DEBUG: POST PROJECT");
				//Inserting in project
				if(req.files.file) {
					var projectName = config.capitalize(req.body.projectname),
						sql = escape("INSERT INTO project(projectname, email, about, imglarge, imgalt, imgthumb)"
								+ "VALUES('" + projectName + "', '"
								+ req.body.email + "', '"+ req.body.about + "', '" + req.transloadit.results.resize_to_125 + "', '"
								+ req.body.imgalt + "', '" + req.transloadit.results.resize_to_75 +"')" ),
						/*escape("INSERT INTO project(projectname, email, about, imglarge, imgalt)"
								+ "VALUES('" + projectName + "', '"
								+ req.body.email + "', '"+ req.body.about + "', '" + req.files.file.name + "', '"
								+ req.body.imgalt +"')" ),*/
						resultObj = {};
				} else {
					var projectName = config.capitalize(req.body.projectname),
						sql = escape("INSERT INTO project(projectname, email, about)"
								+ "VALUES('" + projectName + "', '"
								+ req.body.email + "', '"+ req.body.about + "')" ),
						resultObj = {};
				}

				query(sql,
					function(err, rows, result) {
						if(err) {
							console.error(err);
							res.send("Error 1 " + err);
						} else {
							query("SELECT * FROM Project WHERE projectname='" + projectName
								+ "'", function(err1, rows1, result1) {
									if(err1) {
										console.error("err1 message:");
										console.error(err1);
										console.log("\n");
										res.send("Error " + err1);
									}else{
										resultObj = rows1[0];
										console.log("The project: " + rows1[0].projectname + " was inserted successfully.");
				  								//Insert influences
				  								if(req.body.influence !== "") {
				  									var sql = escape("INSERT INTO projectinfluence"
				  										+ " VALUES(" + rows1[0].id + ", '" + (req.body.influence).toLowerCase() + "')" );

				  									console.log("Escaped query: " + sql);
				  									query(sql,
				  										function(err2, rows2, result2) {
				  											if(err2) {
				  												console.error(err2);
				  												res.send("Error 1 " + err2);
				  											} else {
				  												resultObj.influence = req.body.influence;

				  												console.log("Influences added to the database for " + req.body.influence);
														    			//Insert participation
																			if(req.body.participation !== "") {
																				var sql = escape("INSERT INTO projectparticipation"
																					+ " VALUES(" + rows1[0].id +", " + req.body.participator + ", '"
																						+ req.body.participatorRole + "')" );

																				query(sql,
																					function(err3, rows3, result3) {
																						if(err3) {
																							console.error(err3);
																							res.send("Error 1 " + err3);
																						} else {
																							resultObj.participator = req.body.participator;
																							resultObj.participatorRole = req.body.participatorRole;
																							res.status(201).send();
																							console.log("Participation added to the database for " + rows1[0].projectname);
																						}
																					});
																			} else {
																					res.status(201).send();
																			}
																		}
																	});
									}
								}
							});

						}
				});
			}

		}],
		put: function(req, res) {
			console.log("PUT PROJECT with id: " + req.body.id);
			var propertyNames,
				newValues,
				resultObj= {};

			// Update project table
			if(req.files.file) {
				propertyNames = ['projectname', 'email', 'about', 'imglarge', 'imgalt'];
				newValues = ["'" + req.body.projectname + "'", "'" + req.body.email + "'"
											, "'" + req.body.about + "'" , "'" + req.files.file.name + "'"
											, "'" + req.body.imgalt + "'"];
			} else {
				propertyNames = ['projectname', 'email', 'about',  'imgalt'];
				newValues = ["'" + req.body.projectname + "'", "'" + req.body.email + "'"
											, "'" + req.body.about + "'" , "'" + req.body.imgalt + "'"];
			}

			Project.updateDB(req.body.id, "project" , propertyNames, newValues, function(err, rows) {
				if(err) {
					console.log(err);
					res.send(err);
				} else {
					// Update projectinfluence table
					propertyNames = ['influence'];
					newValues = ["'" + req.body.influence + "'"];
					Project.updateDB(req.body.id, "projectinfluence" , propertyNames, newValues, function(err, rows) {
						if(err) {
							console.log(err);
							res.send(err);
						} else {
							// Update projectinfluence table
							propertyNames = ['userid', 'role'];
							newValues = ["'" + req.body.participator + "'", "'" + req.body.participatorRole + "'"];
							Project.updateDB(req.body.id, "projectparticipation" , propertyNames, newValues, function(err, rows) {
								if(err) {
									console.log(err);
									res.send(err);
								} else {
									res.status(200);
									console.log('update of projectname, email, about and influence OK');
								}
							});
						}
					});

				}
			});

		},
		delete: function(req, res) {
			// Delete projectinfluence table
			Project.deleteFromDB(req.params.id, "projectinfluence", function(err, rows) {
				if(err) {
					console.log(err);
					res.send(err);
				} else {
					// Delete projectparticipation table
					Project.deleteFromDB(req.params.id, "projectparticipation", function(err, rows) {
						if(err) {
							console.log(err);
							res.send(err);
						} else {
							// Delete project table
							Project.deleteFromDB(req.params.id, "project", function(err, rows) {
								if(err) {
									console.log(err);
									res.send(err);
								} else {
									res.status(200).json("Deleted projecet successfully");
									console.log('Deleted project ' + req.params.id
										+ " from project, projectinfluence and projectparticipation tables");

								}
							});
						}
					});

				}
			});
		},
		// config methods:
		selectFromDB: function(id, table, callback) {
			var sql = escape("SELECT * FROM " + table + " where projectid='"
				+ id +"'");

			query(sql, function(err, rows, results) {
				if(err) {
					callback(err);
				} else {
					callback(false, rows);
				}
			});
		},
		insertIntoDB: function(table, valuesArray, callback) {
			var sql = escape("INSERT INTO " + table + " VALUES(");

			valuesArray.forEach(function(currentValue, index, array) {
				if(index < (valuesArray.length -1)) {
					sql += currentValue + ",";
				} else {
					sql += currentValue + ")";
				}
			});
			console.log(table + " - ");
			console.log(sql);
			query(sql, function(err, rows, results) {
				if(err) {
					callback(err);
				} else {
					callback(false, rows);
				}
			});
		},
		updateDB: function(id, table, columnsArray, newValuesArray, callback) {
			var sql = escape("UPDATE " + table + " SET ");
			columnsArray.forEach(function(currentValue, index) {
				if(index < (columnsArray.length -1)) {
					sql += currentValue + "=" + newValuesArray[index] + ",";
				} else {
					sql += currentValue + "=" + newValuesArray[index];
					sql += " WHERE ";
					console.log(table);
					if(table == "project") {

						sql += "id =" + id;
					} else {
						sql += "projectid =" + id;
					}
				}
			});
			console.log("SQL: " + sql);

			query(sql, function(err, rows, results) {
				if(err) {
					callback(err);
				} else {
					callback(false, rows);
				}
			});
		},
		deleteFromDB: function(id, table, callback) {
			var sql = escape("DELETE FROM " + table + " WHERE ");

			if(table == "project") {
						sql += "id =" + id;
					} else {
						sql += "projectid =" + id;
					}

			//console.log("SQL: " + sql);

			query(sql, function(err, rows, results) {
				if(err) {
					callback(err);
				} else {
					callback(false, rows);
				}
			});
		},
};
<commit_msg>add body to req.body.transloadit<commit_after>
var multer = require('multer'),
pg = require('pg'),
mkdirp = require('mkdirp'),
fs = require('fs'),
query = require('pg-query'),
escape = require('pg-escape'),
config = require('../../app/config');

		//configuration
		query.connectionParameters = process.env.DATABASE_URL;

		module.exports = Project = {
		// projcts and song
		getAll: function(req, res) {
			'use strict';
			console.log("DEBUG: GET ALL PROJECTS ORDER BY id");

			var sql = escape("SELECT * FROM Project ORDER BY id");
			query(sql, function(err, rows, result) {
				if(err) {
					console.error(err);
					res.send("Error " + err);
				} else {
					res.send(rows);
					console.log(rows);
				}
			});
		},
		get: function(req, res) {
			console.log("DEBUG: GET PROJECT (with songs) id: " + req.params.id);
			var param = req.params.id,
			resultObj = {};

				// is param a number or a string?
				if(+param === +param) {
					//getting all info from project table
					var sql2 = escape("SELECT * from Project where id ="
						+ req.params.id + "");

					query(sql2, function(err2, rows2, result2) {
						if(err2) {
							console.error("err2: " + err2);
							res.send(err2);
						} else {
							resultObj = rows2[0];
							// getting all songs for the project
							var sql = escape("SELECT * from Song where projectid ="
								+ req.params.id + " ORDER BY id");

							query(sql, function(err, rows, result) {
								if(err) {
									console.error("Err: " + err);
									res.send("Error " + err);
								} else {
									resultObj['songs'] = rows;

									// getting influences
									Project.selectFromDB(req.params.id, "projectinfluence", function(err, rows) {
										if(err) {
											console.log("could not get influences: " + err);
											res.send(err);
										}	else {
											console.log("getInfluences");
											resultObj['influences'] = rows;
									  	// getting participation
									  	Project.selectFromDB(req.params.id, "projectparticipation", function(err, rows) {
												if(err) {
													console.log("could not get participation: " + err);
													res.send(err);
												}	else {
													resultObj['participation'] = rows;
											  	res.send(resultObj);

												}
											});
										}
									});
								}
							});
						}
					});
				} else {
					console.log("Could not find a project with id: " + param);
					res.status(404).json("Could not find a project with id: " + param);
				}
		},

		post: [ multer({
			//multer configuration:
				dest: './public/media/images/',

			}),
		function(req, res) {
			console.log("TRANSLOADIT requst/response");
			console.log(req.body.transloadit);
			/*console.log(req.uploads);
			console.log(req.fields);*/
			if(req.body.id) {
				Project.put(req, res);
			} else {
				console.log("DEBUG: POST PROJECT");
				//Inserting in project
				if(req.files.file) {
					var projectName = config.capitalize(req.body.projectname),
						sql = escape("INSERT INTO project(projectname, email, about, imglarge, imgalt, imgthumb)"
								+ "VALUES('" + projectName + "', '"
								+ req.body.email + "', '"+ req.body.about + "', '" + req.body.transloadit.results.resize_to_125 + "', '"
								+ req.body.imgalt + "', '" + req.body.transloadit.results.resize_to_75 +"')" ),
						/*escape("INSERT INTO project(projectname, email, about, imglarge, imgalt)"
								+ "VALUES('" + projectName + "', '"
								+ req.body.email + "', '"+ req.body.about + "', '" + req.files.file.name + "', '"
								+ req.body.imgalt +"')" ),*/
						resultObj = {};
				} else {
					var projectName = config.capitalize(req.body.projectname),
						sql = escape("INSERT INTO project(projectname, email, about)"
								+ "VALUES('" + projectName + "', '"
								+ req.body.email + "', '"+ req.body.about + "')" ),
						resultObj = {};
				}

				query(sql,
					function(err, rows, result) {
						if(err) {
							console.error(err);
							res.send("Error 1 " + err);
						} else {
							query("SELECT * FROM Project WHERE projectname='" + projectName
								+ "'", function(err1, rows1, result1) {
									if(err1) {
										console.error("err1 message:");
										console.error(err1);
										console.log("\n");
										res.send("Error " + err1);
									}else{
										resultObj = rows1[0];
										console.log("The project: " + rows1[0].projectname + " was inserted successfully.");
				  								//Insert influences
				  								if(req.body.influence !== "") {
				  									var sql = escape("INSERT INTO projectinfluence"
				  										+ " VALUES(" + rows1[0].id + ", '" + (req.body.influence).toLowerCase() + "')" );

				  									console.log("Escaped query: " + sql);
				  									query(sql,
				  										function(err2, rows2, result2) {
				  											if(err2) {
				  												console.error(err2);
				  												res.send("Error 1 " + err2);
				  											} else {
				  												resultObj.influence = req.body.influence;

				  												console.log("Influences added to the database for " + req.body.influence);
														    			//Insert participation
																			if(req.body.participation !== "") {
																				var sql = escape("INSERT INTO projectparticipation"
																					+ " VALUES(" + rows1[0].id +", " + req.body.participator + ", '"
																						+ req.body.participatorRole + "')" );

																				query(sql,
																					function(err3, rows3, result3) {
																						if(err3) {
																							console.error(err3);
																							res.send("Error 1 " + err3);
																						} else {
																							resultObj.participator = req.body.participator;
																							resultObj.participatorRole = req.body.participatorRole;
																							res.status(201).send();
																							console.log("Participation added to the database for " + rows1[0].projectname);
																						}
																					});
																			} else {
																					res.status(201).send();
																			}
																		}
																	});
									}
								}
							});

						}
				});
			}

		}],
		put: function(req, res) {
			console.log("PUT PROJECT with id: " + req.body.id);
			var propertyNames,
				newValues,
				resultObj= {};

			// Update project table
			if(req.files.file) {
				propertyNames = ['projectname', 'email', 'about', 'imglarge', 'imgalt'];
				newValues = ["'" + req.body.projectname + "'", "'" + req.body.email + "'"
											, "'" + req.body.about + "'" , "'" + req.files.file.name + "'"
											, "'" + req.body.imgalt + "'"];
			} else {
				propertyNames = ['projectname', 'email', 'about',  'imgalt'];
				newValues = ["'" + req.body.projectname + "'", "'" + req.body.email + "'"
											, "'" + req.body.about + "'" , "'" + req.body.imgalt + "'"];
			}

			Project.updateDB(req.body.id, "project" , propertyNames, newValues, function(err, rows) {
				if(err) {
					console.log(err);
					res.send(err);
				} else {
					// Update projectinfluence table
					propertyNames = ['influence'];
					newValues = ["'" + req.body.influence + "'"];
					Project.updateDB(req.body.id, "projectinfluence" , propertyNames, newValues, function(err, rows) {
						if(err) {
							console.log(err);
							res.send(err);
						} else {
							// Update projectinfluence table
							propertyNames = ['userid', 'role'];
							newValues = ["'" + req.body.participator + "'", "'" + req.body.participatorRole + "'"];
							Project.updateDB(req.body.id, "projectparticipation" , propertyNames, newValues, function(err, rows) {
								if(err) {
									console.log(err);
									res.send(err);
								} else {
									res.status(200);
									console.log('update of projectname, email, about and influence OK');
								}
							});
						}
					});

				}
			});

		},
		delete: function(req, res) {
			// Delete projectinfluence table
			Project.deleteFromDB(req.params.id, "projectinfluence", function(err, rows) {
				if(err) {
					console.log(err);
					res.send(err);
				} else {
					// Delete projectparticipation table
					Project.deleteFromDB(req.params.id, "projectparticipation", function(err, rows) {
						if(err) {
							console.log(err);
							res.send(err);
						} else {
							// Delete project table
							Project.deleteFromDB(req.params.id, "project", function(err, rows) {
								if(err) {
									console.log(err);
									res.send(err);
								} else {
									res.status(200).json("Deleted projecet successfully");
									console.log('Deleted project ' + req.params.id
										+ " from project, projectinfluence and projectparticipation tables");

								}
							});
						}
					});

				}
			});
		},
		// config methods:
		selectFromDB: function(id, table, callback) {
			var sql = escape("SELECT * FROM " + table + " where projectid='"
				+ id +"'");

			query(sql, function(err, rows, results) {
				if(err) {
					callback(err);
				} else {
					callback(false, rows);
				}
			});
		},
		insertIntoDB: function(table, valuesArray, callback) {
			var sql = escape("INSERT INTO " + table + " VALUES(");

			valuesArray.forEach(function(currentValue, index, array) {
				if(index < (valuesArray.length -1)) {
					sql += currentValue + ",";
				} else {
					sql += currentValue + ")";
				}
			});
			console.log(table + " - ");
			console.log(sql);
			query(sql, function(err, rows, results) {
				if(err) {
					callback(err);
				} else {
					callback(false, rows);
				}
			});
		},
		updateDB: function(id, table, columnsArray, newValuesArray, callback) {
			var sql = escape("UPDATE " + table + " SET ");
			columnsArray.forEach(function(currentValue, index) {
				if(index < (columnsArray.length -1)) {
					sql += currentValue + "=" + newValuesArray[index] + ",";
				} else {
					sql += currentValue + "=" + newValuesArray[index];
					sql += " WHERE ";
					console.log(table);
					if(table == "project") {

						sql += "id =" + id;
					} else {
						sql += "projectid =" + id;
					}
				}
			});
			console.log("SQL: " + sql);

			query(sql, function(err, rows, results) {
				if(err) {
					callback(err);
				} else {
					callback(false, rows);
				}
			});
		},
		deleteFromDB: function(id, table, callback) {
			var sql = escape("DELETE FROM " + table + " WHERE ");

			if(table == "project") {
						sql += "id =" + id;
					} else {
						sql += "projectid =" + id;
					}

			//console.log("SQL: " + sql);

			query(sql, function(err, rows, results) {
				if(err) {
					callback(err);
				} else {
					callback(false, rows);
				}
			});
		},
};
<|endoftext|>


<commit_before>define([
	"dcl/dcl",
	"dojo/hccss",
	"dojo/_base/lang",
	"dojo/dom-construct",
	"delite/register",
	"delite/Widget",
	"delite/Invalidating",
	"dojo/has!dojo-bidi?./Button/bidi/Button",
	"delite/themes/load!delite/themes/{{theme}}/common_css,./Button/themes/{{theme}}/Button_css" // common for duiInline
], function (dcl, has, lang, domConstruct, register, Widget, Invalidating, BidiButton) {

	var Button = dcl([Widget, Invalidating], {
		// summary:
		//		Non-templated BUTTON widget.
		//
		//		Buttons can display a label, an icon, or both.
		//		A name for the button should always be specified through innerHTML or the label attribute.
		//		It can be hidden via showLabel=false, but will always appear in high contrast mode.

		// label: String
		//		Text to display in button.
		label: "",

		// showLabel: Boolean
		//		Set this to true to hide the label text and display only the icon.
		//		(If showLabel=false then iconClass must be specified.)
		//		Especially useful for toolbars.
		//		If showLabel=true, the label will become the title (a.k.a. tooltip/hint) of the icon.
		//
		//		The exception case is for computers in high-contrast mode, where the label
		//		will still be displayed, since the icon doesn't appear.
		showLabel: true,

		// iconClass: String
		//		Class to apply to DOMNode in button to make it display an icon
		iconClass: "",

		// baseClass: String
		//		The name of the CSS class of this widget.
		baseClass: "d-button",

		preCreate: function () {
			this.addInvalidatingProperties("label", "showLabel", "title", "iconClass", "textDir");
		},

		postCreate: function () {
			// Get label from innerHTML, and then clear it since we are to put the label in a
			if (!this.label) {
				this.label = this.textContent.trim();
				this.innerHTML = "";
			}

			this.focusNode = this;
		},

		/*jshint maxcomplexity: 15*/
		refreshRendering: function (props) {
			// summary:
			//		Render or re-render the widget, based on property settings.
			//		Note that this will always create sub-nodes to contain the icon and the label,
			//		even though that's only really necessary when both are present.

			// Add or remove icon, or change its class
			if (props.iconClass) {
				if (this.iconClass && !has("highcontrast")) {
					this.iconNode = this.iconNode || domConstruct.create("span", null, this, "first");
					this.iconNode.className = "duiReset duiInline duiIcon " + this.iconClass;
				} else if (this.iconNode) {
					domConstruct.destroy(this.iconNode);
					delete this.iconNode;
				}
			}
			// Set or remove label
			var showLabel = this.label && (this.showLabel || has("highcontrast"));
			if (props.label || props.showLabel) {
				if (showLabel) {
					this.containerNode = this.containerNode ||
						domConstruct.create("span", {className: "duiReset duiInline duiButtonText"}, this);
					this.containerNode.textContent = this.label;
				} else if (this.containerNode) {
					domConstruct.destroy(this.containerNode);
					delete this.containerNode;
				}
			}

			// Set title.  If no label is shown and no title has been specified,
			// label is also set as title attribute of icon.
			if (props.title || props.label) {
				this.title = this.title || (!showLabel && this.label) || "";
			}
		}
	});

	return register("d-button", has("dojo-bidi") ? [HTMLButtonElement, Button, BidiButton] :
		[HTMLButtonElement, Button]);
});
<commit_msg>update css class name<commit_after>define([
	"dcl/dcl",
	"dojo/hccss",
	"dojo/_base/lang",
	"dojo/dom-construct",
	"delite/register",
	"delite/Widget",
	"delite/Invalidating",
	"dojo/has!dojo-bidi?./Button/bidi/Button",
	"delite/themes/load!delite/themes/{{theme}}/common_css,./Button/themes/{{theme}}/Button_css" // common for d-inline
], function (dcl, has, lang, domConstruct, register, Widget, Invalidating, BidiButton) {

	var Button = dcl([Widget, Invalidating], {
		// summary:
		//		Non-templated BUTTON widget.
		//
		//		Buttons can display a label, an icon, or both.
		//		A name for the button should always be specified through innerHTML or the label attribute.
		//		It can be hidden via showLabel=false, but will always appear in high contrast mode.

		// label: String
		//		Text to display in button.
		label: "",

		// showLabel: Boolean
		//		Set this to true to hide the label text and display only the icon.
		//		(If showLabel=false then iconClass must be specified.)
		//		Especially useful for toolbars.
		//		If showLabel=true, the label will become the title (a.k.a. tooltip/hint) of the icon.
		//
		//		The exception case is for computers in high-contrast mode, where the label
		//		will still be displayed, since the icon doesn't appear.
		showLabel: true,

		// iconClass: String
		//		Class to apply to DOMNode in button to make it display an icon
		iconClass: "",

		// baseClass: String
		//		The name of the CSS class of this widget.
		baseClass: "d-button",

		preCreate: function () {
			this.addInvalidatingProperties("label", "showLabel", "title", "iconClass", "textDir");
		},

		postCreate: function () {
			// Get label from innerHTML, and then clear it since we are to put the label in a
			if (!this.label) {
				this.label = this.textContent.trim();
				this.innerHTML = "";
			}

			this.focusNode = this;
		},

		/*jshint maxcomplexity: 15*/
		refreshRendering: function (props) {
			// summary:
			//		Render or re-render the widget, based on property settings.
			//		Note that this will always create sub-nodes to contain the icon and the label,
			//		even though that's only really necessary when both are present.

			// Add or remove icon, or change its class
			if (props.iconClass) {
				if (this.iconClass && !has("highcontrast")) {
					this.iconNode = this.iconNode || domConstruct.create("span", null, this, "first");
					this.iconNode.className = "d-reset d-inline d-icon " + this.iconClass;
				} else if (this.iconNode) {
					domConstruct.destroy(this.iconNode);
					delete this.iconNode;
				}
			}
			// Set or remove label
			var showLabel = this.label && (this.showLabel || has("highcontrast"));
			if (props.label || props.showLabel) {
				if (showLabel) {
					this.containerNode = this.containerNode ||
						domConstruct.create("span", {className: "d-reset d-inline duiButtonText"}, this);
					this.containerNode.textContent = this.label;
				} else if (this.containerNode) {
					domConstruct.destroy(this.containerNode);
					delete this.containerNode;
				}
			}

			// Set title.  If no label is shown and no title has been specified,
			// label is also set as title attribute of icon.
			if (props.title || props.label) {
				this.title = this.title || (!showLabel && this.label) || "";
			}
		}
	});

	return register("d-button", has("dojo-bidi") ? [HTMLButtonElement, Button, BidiButton] :
		[HTMLButtonElement, Button]);
});
<|endoftext|>


<commit_before>(function () {
    "use strict";

    function PapyrusScrollDirective() {
        return {
            restrict: "A",
            scope: {
                papyrusScroll: "&papyrusScroll",
                papyrusScrollThrottleMs: "=papyrusScrollThrottleMs",
                papyrusScrollPreloadViewPercentage: "=papyrusScrollPreloadViewPercentage"
            },
            controller: PapyrusScrollDirectiveController,
            link: function (scope, element, attrs, ctrl) {
                ctrl.initContainer(element);
            }
        };
    }

    function PapyrusScrollDirectiveController($scope, $timeout) {
        var vm = this;
        vm.initContainer = initContainer;

        function initContainer(container) {
            var $container = $(container);

            $(document).ready(function () {
                render($container);
            });

            $container.on("scroll", function () {
                render($container);
            });

            requestItems(1);
        }

        var  renderBackoff = null;

        function render(container) {
            if (!!renderBackoff) {
                $timeout.cancel(renderBackoff);
            }

            renderBackoff = $timeout(function() {
                var pending = getNrOfRequestItems(container);

                if (pending > 0) {
                    $scope.$apply(function () {
                        requestItems(pending);
                    });
                }
            }, getBackoffTimeout());
        }

        function requestItems(amount) {
            if (!!$scope.papyrusScroll) {
                $scope.papyrusScroll({ $amount: amount });
            }
        }

        function getNrOfRequestItems(container) {
            var items = container.find("[papyrus-scroll-item]");

            var containerHeight = container.height() || 0;
            var containerScrollTop = container.scrollTop() || 0;

            var itemHeight = (!items.length)
                ? 0
                : ($(items[0]).height() || 0);

            if (!itemHeight) {
                return 0;
            }

            var renderedHeight = items.length * itemHeight;
            var backgroundRenderedHeight = (renderedHeight - containerScrollTop) - containerHeight;

            var diff = backgroundRenderedHeight - (containerHeight * getPreloadPercentage());

            if (diff <= 0) {
                var nrOfItems = (Math.abs(diff) / itemHeight);

                return (isNaN(nrOfItems) || !isFinite(nrOfItems))
                    ? 0
                    : nrOfItems;
            }

            return 0;
        }

        function getBackoffTimeout() {
            return $scope.papyrusScrollThrottleMs || 50;
        }

        function getPreloadPercentage() {
             return ($scope.papyrusScrollPreloadViewPercentage || 75.0) / 100.0;
        }
    }

    PapyrusScrollDirectiveController.$inject = ["$scope", "$timeout"];

    angular.module("papyrus-scroll", [])
        .directive("papyrusScroll", PapyrusScrollDirective);
})();<commit_msg>added fix for preload<commit_after>(function () {
    "use strict";

    function PapyrusScrollDirective() {
        return {
            restrict: "A",
            scope: {
                papyrusScroll: "&papyrusScroll",
                papyrusScrollThrottleMs: "=papyrusScrollThrottleMs",
                papyrusScrollPreloadViewPercentage: "=papyrusScrollPreloadViewPercentage"
            },
            controller: PapyrusScrollDirectiveController,
            link: function (scope, element, attrs, ctrl) {
                ctrl.initContainer(element);
            }
        };
    }

    function PapyrusScrollDirectiveController($scope, $timeout) {
        var vm = this;
        vm.initContainer = initContainer;

        function initContainer(container) {
            var $container = $(container);

            requestItems(1);

            $(document).ready(function () {
                render($container);
            });

            $container.on("scroll", function () {
                render($container);
            });
        }

        var  renderBackoff = null;

        function render(container) {
            if (!!renderBackoff) {
                $timeout.cancel(renderBackoff);
            }

            renderBackoff = $timeout(function() {
                var pending = getNrOfRequestItems(container);

                if (pending > 0) {
                    $scope.$apply(function () {
                        requestItems(pending);
                    });
                }
            }, getBackoffTimeout());
        }

        function requestItems(amount) {
            if (!!$scope.papyrusScroll) {
                $scope.papyrusScroll({ $amount: amount });
            }
        }

        function getNrOfRequestItems(container) {
            var items = container.find("[papyrus-scroll-item]");

            var containerHeight = container.height() || 0;
            var containerScrollTop = container.scrollTop() || 0;

            var itemHeight = (!items.length)
                ? 0
                : ($(items[0]).height() || 0);

            if (!itemHeight) {
                return 0;
            }

            var renderedHeight = items.length * itemHeight;
            var backgroundRenderedHeight = (renderedHeight - containerScrollTop) - containerHeight;

            var diff = backgroundRenderedHeight - (containerHeight * getPreloadPercentage());

            if (diff <= 0) {
                var nrOfItems = (Math.abs(diff) / itemHeight);

                return (isNaN(nrOfItems) || !isFinite(nrOfItems))
                    ? 0
                    : nrOfItems;
            }

            return 0;
        }

        function getBackoffTimeout() {
            return $scope.papyrusScrollThrottleMs || 50;
        }

        function getPreloadPercentage() {
             return ($scope.papyrusScrollPreloadViewPercentage || 75.0) / 100.0;
        }
    }

    PapyrusScrollDirectiveController.$inject = ["$scope", "$timeout"];

    angular.module("papyrus-scroll", [])
        .directive("papyrusScroll", PapyrusScrollDirective);
})();<|endoftext|>


<commit_before>describe('Todos.Api', function() {

  beforeEach(function() {

    this.todoListId = new Guid();

    /*this.uncompletedTodoId = new Guid();
    this.completedTodoId = new Guid();*/

    this.createTodoListCommand = new Todos.CreateTodoList({
      targetId: this.todoListId,
      name: 'MyTodos',
    });

    /*this.todoListCreatedEvent = new Todos.TodoListCreated({
      sourceId: this.todoListId,
      name: 'MyTodos'
    });

    this.createUncompletedTodo = new Todos.CreateTodo({
      targetId: this.todoListId,
      id: this.uncompletedTodoId,
      title: 'My Todo',
      isCompleted: false,
      version: 2
    });

    this.uncompletedTodoCreatedEvent = new Todos.TodoCreated({
      sourceId: this.todoListId,
      id: this.uncompletedTodoId,
      title: 'My Todo',
      isCompleted: false
    });

    this.createCompletedTodo = new Todos.CreateTodo({
      targetId: this.todoListId,
      id: this.completedTodoId,
      title: 'My Todo',
      isCompleted: false,
      version: 2
    });

    this.completedTodoCreatedEvent = new Todos.TodoCreated({
      sourceId: this.todoListId,
      id: this.completedTodoId,
      title: 'My Todo',
      isCompleted: true
    });*/

  });

  it('receives a command for creating a todo list and sends it on the server-side command bus when valid', function() {

    Todos.App.test(Todos.TodosApi)
      .send(this.createTodoListCommand)
      .expect([this.createTodoListCommand]);
  });

  /*it('receives a command for creating a todo and sends it on the server-side command bus when valid', function() {

    Todos.App.test(Todos.TodosApi)
      .given([this.todoListCreatedEvent])
      .send(this.createUncompletedTodo)
      .expect([this.createUncompletedTodo]);
  });

  it('receives a command for completing a todo and sends it on the server-side command bus when valid', function() {

    let completeTodoCommand = new Todos.CompleteTodo({
      targetId: this.todoListId,
      todoId: this.uncompletedTodoId
    });

    Todos.App.test(Todos.TodosApi)
      .given([this.todoListCreatedEvent, this.uncompletedTodoCreatedEvent])
      .send(completeTodoCommand)
      .expect([completeTodoCommand]);
  });

  it('receives a command for completing a todo and sends it on the server-side command bus when todo is already completed and expects an error', function() {

    let completeTodoCommand = new Todos.CompleteTodo({
      targetId: this.todoListId,
      todoId: this.completedTodoId
    });

    Todos.App.test(Todos.TodosApi)
      .given([this.todoListCreatedEvent, this.completedTodoCreatedEvent])
      .send(completeTodoCommand)
      .expectToFailWith(new Todos.TodoCannotBeCompleted());
  });

  it('receives a command for reopening a todo and sends it on the server-side command bus when valid', function() {

    let reopenTodoCommand = new Todos.ReopenTodo({
      targetId: this.todoListId,
      todoId: this.completedTodoId
    });

    Todos.App.test(Todos.TodosApi)
      .given([this.todoListCreatedEvent, this.completedTodoCreatedEvent])
      .send(reopenTodoCommand)
      .expect([reopenTodoCommand]);
  });

  it('receives a command for reopening a todo and sends it on the server-side command bus when todo is already open and expects an error', function() {

    let reopenTodoCommand = new Todos.ReopenTodo({
      targetId: this.todoListId,
      todoId: this.uncompletedTodoId
    });

    Todos.App.test(Todos.TodosApi)
      .given([this.todoListCreatedEvent, this.uncompletedTodoCreatedEvent])
      .send(reopenTodoCommand)
      .expectToFailWith(new Todos.TodoCannotBeReopened());
  });*/

});
<commit_msg>Cleanup api bdd tests<commit_after>describe('Todos.Api', function() {

  beforeEach(function() {

    this.todoListId = new Guid();

    this.createTodoListCommand = new Todos.CreateTodoList({
      targetId: this.todoListId,
      name: 'MyTodos'
    });

    // TODO: Add other tests from repo history after API BDD testing API update

  });

  it('receives a command for creating a todo list and sends it on the server-side command bus when valid', function() {

    Todos.App.test(Todos.TodosApi)
      .send(this.createTodoListCommand)
      .expect([this.createTodoListCommand]);
  });

  // TODO: Add other tests from repo history after API BDD testing API update

});
<|endoftext|>


<commit_before>var PipeStream = require('pipestream');
var url = require('url');
var https = require('https');
var http = require('http');
var util = require('../../util');
var config = util.config;

module.exports = function(req, res, next) {
	PipeStream.wrap(req);
	PipeStream.wrap(res, true);

	var clientReq, clientRes, errorEmitted;
	var reqTransform, resTransform;
	req.on('dest', function(_req) {
		clientReq = _req.on('error', onReqError);
	}).on('error', onReqError);
	res.on('src', function(_res) {
		clientRes = _res.on('error', onResError);
	}).on('error', onResError);

	function onReqError(err) {
		onError(reqTransform, err);
	}

	function onResError(err) {
		onError(resTransform, err);
	}

	function onError(obj, err) {
		if (errorEmitted) {
			return;
		}
		errorEmitted = true;
		clientReq && clientReq.abort();
		res.destroy();
		if (obj && EventEmitter.listenerCount(obj, 'error') > 0) {
			obj.emit('error', err || new Error('Unknown'));
		}
	}

	var fullUrl = req.fullUrl = util.getFullUrl(req);
	if (req.headers.host == config.localUIHost) {
		var options = url.parse(fullUrl);
		options.host = '127.0.0.1';
		options.hostname = null;
		options.port = config.uiport;
		options.headers = req.headers;
		req.pipe(http.request(options, function(_res) {
			res.writeHead(_res.statusCode || 0, _res.headers);
			res.src(_res);
		}));
		return;
	}

	next();
};
<commit_msg>events<commit_after>var PipeStream = require('pipestream');
var url = require('url');
var https = require('https');
var http = require('http');
var util = require('../../util');
var config = util.config;

module.exports = function(req, res, next) {
	PipeStream.wrap(req);
	PipeStream.wrap(res, true);
	addErrorEvents(req, res);
	addDataEvents(req, res);

	var fullUrl = req.fullUrl = util.getFullUrl(req);
	if (req.headers.host == config.localUIHost) {
		var options = url.parse(fullUrl);
		options.host = '127.0.0.1';
		options.hostname = null;
		options.port = config.uiport;
		options.headers = req.headers;
		req.pipe(http.request(options, function(_res) {
			res.writeHead(_res.statusCode || 0, _res.headers);
			res.src(_res);
		}));
		return;
	}

	next();
};

function addErrorEvents(req, res) {
	var clientReq, clientRes, errorEmitted;
	var reqTransform, resTransform;
	req.on('dest', function(_req) {
		clientReq = _req.on('error', onReqError);
	}).on('error', onReqError);
	res.on('src', function(_res) {
		clientRes = _res.on('error', onResError);
	}).on('error', onResError);

	function onReqError(err) {
		onError(reqTransform, err);
	}

	function onResError(err) {
		onError(resTransform, err);
	}

	function onError(obj, err) {
		if (errorEmitted) {
			return;
		}
		errorEmitted = true;
		clientReq && clientReq.abort();
		res.destroy();
		if (obj && EventEmitter.listenerCount(obj, 'error') > 0) {
			obj.emit('error', err || new Error('Unknown'));
		}
	}
}

function addDataEvents(req, res) {

}

<|endoftext|>


<commit_before>Paloquiz.states.Highscores = function(game) {
    this.currentPage = 0;
    this.friendsScores = [];
    this.userPos = undefined;
    this.profileImagesData = [];
    this.numFriendsInPage = 0;
    this.maxPage = 0;

    this.scores = [];
    this.nameTextStyle;
    this.scoreTextStyle;
    this.positionTextStyle;
    this.nameUserTextStyle;
    this.scoreUserTextStyle;
    this.positionUserTextStyle;
    this.arrowRight;
    this.arrowLeft;
    this.backButton;
};

Paloquiz.states.Highscores.prototype = {

    PAGE_SIZE: 5,
    ENTRIES_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    ENTRY_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    POSITION_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    IMAGE_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    NAME_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    SCORE_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    IMAGE_SIZE: 0,

    init: function() {
        // Compute box sizes
        this.ENTRIES_BOX.x = this.game.width * .1;
        this.ENTRIES_BOX.y = this.game.height * .1;
        this.ENTRIES_BOX.width = this.game.width * .8;
        this.ENTRIES_BOX.height = this.game.height * .8;

        this.ENTRY_BOX.x = this.ENTRIES_BOX.x;
        this.ENTRY_BOX.y = this.ENTRIES_BOX.y;
        this.ENTRY_BOX.width = this.ENTRIES_BOX.width;
        this.ENTRY_BOX.height = this.ENTRIES_BOX.height / this.PAGE_SIZE;

        this.POSITION_BOX.x = this.ENTRY_BOX.x + this.ENTRY_BOX.width * .0;
        this.POSITION_BOX.y = this.ENTRY_BOX.y;
        this.POSITION_BOX.width = this.ENTRIES_BOX.width * .05;
        this.POSITION_BOX.height = this.ENTRY_BOX.height;

        this.IMAGE_BOX.x = this.ENTRY_BOX.x + this.ENTRY_BOX.width * .05;
        this.IMAGE_BOX.y = this.ENTRY_BOX.y;
        this.IMAGE_BOX.width = this.ENTRIES_BOX.width * .25;
        this.IMAGE_BOX.height = this.ENTRY_BOX.height;

        this.NAME_BOX.x = this.ENTRY_BOX.x + this.ENTRY_BOX.width * .30;
        this.NAME_BOX.y = this.ENTRY_BOX.y;
        this.NAME_BOX.width = this.ENTRIES_BOX.width * .45;
        this.NAME_BOX.height = this.ENTRY_BOX.height;

        this.SCORE_BOX.x = this.ENTRY_BOX.x + this.ENTRY_BOX.width * .78;
        this.SCORE_BOX.y = this.ENTRY_BOX.y;
        this.SCORE_BOX.width = this.ENTRIES_BOX.width * .22;
        this.SCORE_BOX.height = this.ENTRY_BOX.height;

        this.IMAGE_SIZE = .7 * Math.min(
            this.ENTRY_BOX.width * .25,
            this.ENTRY_BOX.height);

        // Font styles
        this.createFontStyles();
    },

    preload: function() {
        // Enable cross-origin image loading
        this.load.crossOrigin = 'anonymous';

        this.load.image('noface', 'assets/noface.png');
        this.load.image('arrow', 'assets/arrow.png');
        this.load.image('back', 'assets/back.png');
    },

    create: function() {
        // Set up background
        var background = this.add.image(this.game.world.centerX, this.game.world.centerY, 'background');
        background.anchor.setTo(0.5, 0.5);
        background.width = this.game.width;
        background.height = this.game.height;

        // Create game objects
        this.createHighscoreEntries();
        this.createUI();

        // Handler for loaded profile pictures
        this.load.onLoadComplete.add(this.loadComplete, this);

        // Go on only if logged in
        fbInit(function() {
                fbGetFriendsScores(function(friendsScores, userPos) {
                    this.friendsScores = friendsScores;
                    this.userPos = userPos;
                    this.maxPage = Math.floor(this.friendsScores.length / this.PAGE_SIZE);
                    this.loadScoresPage();
                }, this);
            },
            function() {
                // Exit if not logged in
                this.state.start('Main');
            });
    },

    shutdown: function() {
        // Remove handlers
        this.load.onLoadComplete.remove(this.loadComplete, this);
    },

    loadComplete: function() {
        for (var i = 0; i < this.numFriendsInPage; i++) {
            if (!this.profileImagesData[i].isSilhouette) {
                this.scores[i].img.loadTexture(i);
            }
            this.scores[i].img.width = this.IMAGE_SIZE;
            this.scores[i].img.height = this.IMAGE_SIZE;
            this.scores[i].img.anchor.setTo(.5, .5);
            this.scores[i].img.visible = true;
        }
    },

    loadScoresPage: function() {
        // Hide all entries
        this.scores.forEach(function(s) {
            s.img.loadTexture('noface');
            s.img.visible = false;
            s.pos.setStyle(this.positionTextStyle);
            s.pos.visible = false;
            s.name.setStyle(this.nameTextStyle);
            s.name.visible = false;
            s.score.setStyle(this.scoreTextStyle);
            s.score.visible = false;
        }, this);

        // Make sure page is in range
        if (this.currentPage < 0) {
            this.currentPage = 0;
        }
        if (this.currentPage > this.maxPage) {
            this.currentPage = this.maxPage;
        }

        // Hide arrows as needed
        this.arrowRight.visible = this.currentPage < this.maxPage;
        this.arrowLeft.visible = this.currentPage > 0;

        // Count friends in page
        var iFriendStart = this.PAGE_SIZE * this.currentPage;
        var iFriendEnd = Math.min(
            this.PAGE_SIZE * (this.currentPage + 1),
            this.friendsScores.length);
        this.numFriendsInPage = iFriendEnd - iFriendStart;
        this.profileImagesData = new Array(this.numFriendsInPage);

        // Function that starts the loader after every friend information is read
        var readFriends = 0;
        var friendInformationRead = function() {
            readFriends++;
            if (readFriends >= this.numFriendsInPage) {
                this.profileImagesData.forEach(function(img, i) {
                    this.load.image(i, img.url);
                }, this);
                this.load.start();
            }
        }
        friendInformationRead = friendInformationRead.bind(this);

        // Iterate through friends
        for (var iFriend = iFriendStart, iScore = 0; iFriend < iFriendEnd; iFriend++, iScore++) {
            // Copy index to use in closure
            var iFriendCpy = iFriend;
            var iScoreCpy = iScore;
            fbGetProfileDetails(this.friendsScores[iFriend].user.id, function(friend) {
                this.scores[iScoreCpy].pos.setText((iFriendCpy + 1) + '.');
                this.scores[iScoreCpy].name.setText(friend.first_name || friend.name);
                this.scores[iScoreCpy].score.setText(this.friendsScores[iFriendCpy].score);
                // Use special style for the user
                if (iFriendCpy == this.userPos) {
                    this.scores[iScoreCpy].pos.setStyle(this.positionUserTextStyle);
                    this.scores[iScoreCpy].name.setStyle(this.nameUserTextStyle);
                    this.scores[iScoreCpy].score.setStyle(this.scoreUserTextStyle);
                }
                this.scores[iScoreCpy].pos.visible = true;
                this.scores[iScoreCpy].name.visible = true;
                this.scores[iScoreCpy].score.visible = true;
                this.profileImagesData[iScoreCpy] = friend.image;
                friendInformationRead();
            }, this);
        }
    },

    createFontStyles: function() {
        var fontFace = 'Pixel Art';
        var textSize = Math.floor(this.ENTRY_BOX.height / 5) + 'px';
        var positionTextSize = textSize;
        var nameTextSize = textSize;
        var scoreTextSize = textSize;
        var normalColor = 'white';
        var userColor = 'red';
        // Normal
        this.positionTextStyle = {
            font: fontFace,
            fontSize: positionTextSize,
            fill: normalColor,
            align: 'right',
            boundsAlignH: 'right',
            boundsAlignV: 'middle'
        };
        this.nameTextStyle = {
            font: fontFace,
            fontSize: positionTextSize,
            fill: normalColor,
            align: 'left',
            boundsAlignH: 'left',
            boundsAlignV: 'middle'
        };
        this.scoreTextStyle = {
            font: fontFace,
            fontSize: scoreTextSize,
            fill: 'white',
            align: 'center',
            boundsAlignH: 'center',
            boundsAlignV: 'middle'
        };
        // User
        this.positionUserTextStyle = {
            font: fontFace,
            fontSize: positionTextSize,
            fill: userColor,
            align: 'right',
            boundsAlignH: 'right',
            boundsAlignV: 'middle'
        };
        this.nameUserTextStyle = {
            font: fontFace,
            fontSize: nameTextSize,
            fill: userColor,
            align: 'left',
            boundsAlignH: 'left',
            boundsAlignV: 'middle',
            wordWrap: true,
            wordWrapWidth: this.NAME_BOX.width
        };
        this.scoreUserTextStyle = {
            font: fontFace,
            fontSize: scoreTextSize,
            fill: userColor,
            align: 'center',
            boundsAlignH: 'center',
            boundsAlignV: 'middle'
        };
    },

    createHighscoreEntries: function() {
        for (var i = 0; i < this.PAGE_SIZE; i++) {
            var xOffset = 0;
            var yOffset = i * this.ENTRY_BOX.height;

            // Position
            var pos = this.add.text(0, 0, '', this.positionTextStyle);
            pos.setTextBounds(
                this.POSITION_BOX.x + xOffset,
                this.POSITION_BOX.y + yOffset,
                this.POSITION_BOX.width,
                this.POSITION_BOX.height);
            pos.visible = false;

            // Image
            var img = this.add.image(
                this.IMAGE_BOX.x + this.IMAGE_BOX.width / 2 + xOffset,
                this.IMAGE_BOX.y + this.IMAGE_BOX.height / 2 + yOffset,
                'noface');
            img.visible = false;

            // Name
            var name = this.add.text(0, 0, '', this.nameTextStyle);
            name.setTextBounds(
                this.NAME_BOX.x + xOffset,
                this.NAME_BOX.y + yOffset,
                this.NAME_BOX.width,
                this.NAME_BOX.height);
            name.visible = false;

            // Score
            var score = this.add.text(0, 0, '', this.scoreTextStyle);
            score.setTextBounds(
                this.SCORE_BOX.x + xOffset,
                this.SCORE_BOX.y + yOffset,
                this.SCORE_BOX.width,
                this.SCORE_BOX.height);
            score.visible = false;

            this.scores.push({
                pos: pos,
                img: img,
                name: name,
                score: score
            });
        }
    },

    createUI: function() {
        // Back button to go back to main state
        var backButton = this.add.button(0, 0, 'back',
            function() {
                this.state.start('Main');
            }, this, 0, 0, 0);
        var backButtonSize = .1 * Math.min(this.game.width, this.game.height);
        backButton.width = backButtonSize;
        backButton.height = backButtonSize;
        backButton.anchor.setTo(0, 0);
        backButton.x = backButton.width * .2;
        backButton.y = backButton.width * .2;

        // Arrows to navigate through pages
        this.arrowRight = this.add.button(
            this.game.width * .9, this.game.height * .9, 'arrow',
            function() {
                if (this.currentPage < this.maxPage) {
                    this.currentPage++;
                    this.loadScoresPage();
                }
            }, this, 0, 0, 0);
        this.arrowRight.anchor.setTo(1, 1);
        this.arrowRight.visible = false;

        this.arrowLeft = this.add.button(
            this.game.width * .1, this.game.height * .9, 'arrow',
            function() {
                if (this.currentPage > 0) {
                    this.currentPage--;
                    this.loadScoresPage();
                }
            }, this, 0, 0, 0);
        this.arrowLeft.scale.setTo(-1, 1);
        this.arrowLeft.anchor.setTo(1, 1);
        this.arrowLeft.visible = false;
    }

};<commit_msg>Added forgotten this<commit_after>Paloquiz.states.Highscores = function(game) {
    this.currentPage = 0;
    this.friendsScores = [];
    this.userPos = undefined;
    this.profileImagesData = [];
    this.numFriendsInPage = 0;
    this.maxPage = 0;

    this.scores = [];
    this.nameTextStyle;
    this.scoreTextStyle;
    this.positionTextStyle;
    this.nameUserTextStyle;
    this.scoreUserTextStyle;
    this.positionUserTextStyle;
    this.arrowRight;
    this.arrowLeft;
    this.backButton;
};

Paloquiz.states.Highscores.prototype = {

    PAGE_SIZE: 5,
    ENTRIES_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    ENTRY_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    POSITION_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    IMAGE_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    NAME_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    SCORE_BOX: {
        x: 0,
        y: 0,
        width: 0,
        height: 0
    },
    IMAGE_SIZE: 0,

    init: function() {
        // Compute box sizes
        this.ENTRIES_BOX.x = this.game.width * .1;
        this.ENTRIES_BOX.y = this.game.height * .1;
        this.ENTRIES_BOX.width = this.game.width * .8;
        this.ENTRIES_BOX.height = this.game.height * .8;

        this.ENTRY_BOX.x = this.ENTRIES_BOX.x;
        this.ENTRY_BOX.y = this.ENTRIES_BOX.y;
        this.ENTRY_BOX.width = this.ENTRIES_BOX.width;
        this.ENTRY_BOX.height = this.ENTRIES_BOX.height / this.PAGE_SIZE;

        this.POSITION_BOX.x = this.ENTRY_BOX.x + this.ENTRY_BOX.width * .0;
        this.POSITION_BOX.y = this.ENTRY_BOX.y;
        this.POSITION_BOX.width = this.ENTRIES_BOX.width * .05;
        this.POSITION_BOX.height = this.ENTRY_BOX.height;

        this.IMAGE_BOX.x = this.ENTRY_BOX.x + this.ENTRY_BOX.width * .05;
        this.IMAGE_BOX.y = this.ENTRY_BOX.y;
        this.IMAGE_BOX.width = this.ENTRIES_BOX.width * .25;
        this.IMAGE_BOX.height = this.ENTRY_BOX.height;

        this.NAME_BOX.x = this.ENTRY_BOX.x + this.ENTRY_BOX.width * .30;
        this.NAME_BOX.y = this.ENTRY_BOX.y;
        this.NAME_BOX.width = this.ENTRIES_BOX.width * .45;
        this.NAME_BOX.height = this.ENTRY_BOX.height;

        this.SCORE_BOX.x = this.ENTRY_BOX.x + this.ENTRY_BOX.width * .78;
        this.SCORE_BOX.y = this.ENTRY_BOX.y;
        this.SCORE_BOX.width = this.ENTRIES_BOX.width * .22;
        this.SCORE_BOX.height = this.ENTRY_BOX.height;

        this.IMAGE_SIZE = .7 * Math.min(
            this.ENTRY_BOX.width * .25,
            this.ENTRY_BOX.height);

        // Font styles
        this.createFontStyles();
    },

    preload: function() {
        // Enable cross-origin image loading
        this.load.crossOrigin = 'anonymous';

        this.load.image('noface', 'assets/noface.png');
        this.load.image('arrow', 'assets/arrow.png');
        this.load.image('back', 'assets/back.png');
    },

    create: function() {
        // Set up background
        var background = this.add.image(this.game.world.centerX, this.game.world.centerY, 'background');
        background.anchor.setTo(0.5, 0.5);
        background.width = this.game.width;
        background.height = this.game.height;

        // Create game objects
        this.createHighscoreEntries();
        this.createUI();

        // Handler for loaded profile pictures
        this.load.onLoadComplete.add(this.loadComplete, this);

        // Go on only if logged in
        fbInit(function() {
                fbGetFriendsScores(function(friendsScores, userPos) {
                    this.friendsScores = friendsScores;
                    this.userPos = userPos;
                    this.maxPage = Math.floor(this.friendsScores.length / this.PAGE_SIZE);
                    this.loadScoresPage();
                }, this);
            },
            function() {
                // Exit if not logged in
                this.state.start('Main');
            },
            this);
    },

    shutdown: function() {
        // Remove handlers
        this.load.onLoadComplete.remove(this.loadComplete, this);
    },

    loadComplete: function() {
        for (var i = 0; i < this.numFriendsInPage; i++) {
            if (!this.profileImagesData[i].isSilhouette) {
                this.scores[i].img.loadTexture(i);
            }
            this.scores[i].img.width = this.IMAGE_SIZE;
            this.scores[i].img.height = this.IMAGE_SIZE;
            this.scores[i].img.anchor.setTo(.5, .5);
            this.scores[i].img.visible = true;
        }
    },

    loadScoresPage: function() {
        // Hide all entries
        this.scores.forEach(function(s) {
            s.img.loadTexture('noface');
            s.img.visible = false;
            s.pos.setStyle(this.positionTextStyle);
            s.pos.visible = false;
            s.name.setStyle(this.nameTextStyle);
            s.name.visible = false;
            s.score.setStyle(this.scoreTextStyle);
            s.score.visible = false;
        }, this);

        // Make sure page is in range
        if (this.currentPage < 0) {
            this.currentPage = 0;
        }
        if (this.currentPage > this.maxPage) {
            this.currentPage = this.maxPage;
        }

        // Hide arrows as needed
        this.arrowRight.visible = this.currentPage < this.maxPage;
        this.arrowLeft.visible = this.currentPage > 0;

        // Count friends in page
        var iFriendStart = this.PAGE_SIZE * this.currentPage;
        var iFriendEnd = Math.min(
            this.PAGE_SIZE * (this.currentPage + 1),
            this.friendsScores.length);
        this.numFriendsInPage = iFriendEnd - iFriendStart;
        this.profileImagesData = new Array(this.numFriendsInPage);

        // Function that starts the loader after every friend information is read
        var readFriends = 0;
        var friendInformationRead = function() {
            readFriends++;
            if (readFriends >= this.numFriendsInPage) {
                this.profileImagesData.forEach(function(img, i) {
                    this.load.image(i, img.url);
                }, this);
                this.load.start();
            }
        }
        friendInformationRead = friendInformationRead.bind(this);

        // Iterate through friends
        for (var iFriend = iFriendStart, iScore = 0; iFriend < iFriendEnd; iFriend++, iScore++) {
            // Copy index to use in closure
            var iFriendCpy = iFriend;
            var iScoreCpy = iScore;
            fbGetProfileDetails(this.friendsScores[iFriend].user.id, function(friend) {
                this.scores[iScoreCpy].pos.setText((iFriendCpy + 1) + '.');
                this.scores[iScoreCpy].name.setText(friend.first_name || friend.name);
                this.scores[iScoreCpy].score.setText(this.friendsScores[iFriendCpy].score);
                // Use special style for the user
                if (iFriendCpy == this.userPos) {
                    this.scores[iScoreCpy].pos.setStyle(this.positionUserTextStyle);
                    this.scores[iScoreCpy].name.setStyle(this.nameUserTextStyle);
                    this.scores[iScoreCpy].score.setStyle(this.scoreUserTextStyle);
                }
                this.scores[iScoreCpy].pos.visible = true;
                this.scores[iScoreCpy].name.visible = true;
                this.scores[iScoreCpy].score.visible = true;
                this.profileImagesData[iScoreCpy] = friend.image;
                friendInformationRead();
            }, this);
        }
    },

    createFontStyles: function() {
        var fontFace = 'Pixel Art';
        var textSize = Math.floor(this.ENTRY_BOX.height / 5) + 'px';
        var positionTextSize = textSize;
        var nameTextSize = textSize;
        var scoreTextSize = textSize;
        var normalColor = 'white';
        var userColor = 'red';
        // Normal
        this.positionTextStyle = {
            font: fontFace,
            fontSize: positionTextSize,
            fill: normalColor,
            align: 'right',
            boundsAlignH: 'right',
            boundsAlignV: 'middle'
        };
        this.nameTextStyle = {
            font: fontFace,
            fontSize: positionTextSize,
            fill: normalColor,
            align: 'left',
            boundsAlignH: 'left',
            boundsAlignV: 'middle'
        };
        this.scoreTextStyle = {
            font: fontFace,
            fontSize: scoreTextSize,
            fill: 'white',
            align: 'center',
            boundsAlignH: 'center',
            boundsAlignV: 'middle'
        };
        // User
        this.positionUserTextStyle = {
            font: fontFace,
            fontSize: positionTextSize,
            fill: userColor,
            align: 'right',
            boundsAlignH: 'right',
            boundsAlignV: 'middle'
        };
        this.nameUserTextStyle = {
            font: fontFace,
            fontSize: nameTextSize,
            fill: userColor,
            align: 'left',
            boundsAlignH: 'left',
            boundsAlignV: 'middle',
            wordWrap: true,
            wordWrapWidth: this.NAME_BOX.width
        };
        this.scoreUserTextStyle = {
            font: fontFace,
            fontSize: scoreTextSize,
            fill: userColor,
            align: 'center',
            boundsAlignH: 'center',
            boundsAlignV: 'middle'
        };
    },

    createHighscoreEntries: function() {
        for (var i = 0; i < this.PAGE_SIZE; i++) {
            var xOffset = 0;
            var yOffset = i * this.ENTRY_BOX.height;

            // Position
            var pos = this.add.text(0, 0, '', this.positionTextStyle);
            pos.setTextBounds(
                this.POSITION_BOX.x + xOffset,
                this.POSITION_BOX.y + yOffset,
                this.POSITION_BOX.width,
                this.POSITION_BOX.height);
            pos.visible = false;

            // Image
            var img = this.add.image(
                this.IMAGE_BOX.x + this.IMAGE_BOX.width / 2 + xOffset,
                this.IMAGE_BOX.y + this.IMAGE_BOX.height / 2 + yOffset,
                'noface');
            img.visible = false;

            // Name
            var name = this.add.text(0, 0, '', this.nameTextStyle);
            name.setTextBounds(
                this.NAME_BOX.x + xOffset,
                this.NAME_BOX.y + yOffset,
                this.NAME_BOX.width,
                this.NAME_BOX.height);
            name.visible = false;

            // Score
            var score = this.add.text(0, 0, '', this.scoreTextStyle);
            score.setTextBounds(
                this.SCORE_BOX.x + xOffset,
                this.SCORE_BOX.y + yOffset,
                this.SCORE_BOX.width,
                this.SCORE_BOX.height);
            score.visible = false;

            this.scores.push({
                pos: pos,
                img: img,
                name: name,
                score: score
            });
        }
    },

    createUI: function() {
        // Back button to go back to main state
        var backButton = this.add.button(0, 0, 'back',
            function() {
                this.state.start('Main');
            }, this, 0, 0, 0);
        var backButtonSize = .1 * Math.min(this.game.width, this.game.height);
        backButton.width = backButtonSize;
        backButton.height = backButtonSize;
        backButton.anchor.setTo(0, 0);
        backButton.x = backButton.width * .2;
        backButton.y = backButton.width * .2;

        // Arrows to navigate through pages
        this.arrowRight = this.add.button(
            this.game.width * .9, this.game.height * .9, 'arrow',
            function() {
                if (this.currentPage < this.maxPage) {
                    this.currentPage++;
                    this.loadScoresPage();
                }
            }, this, 0, 0, 0);
        this.arrowRight.anchor.setTo(1, 1);
        this.arrowRight.visible = false;

        this.arrowLeft = this.add.button(
            this.game.width * .1, this.game.height * .9, 'arrow',
            function() {
                if (this.currentPage > 0) {
                    this.currentPage--;
                    this.loadScoresPage();
                }
            }, this, 0, 0, 0);
        this.arrowLeft.scale.setTo(-1, 1);
        this.arrowLeft.anchor.setTo(1, 1);
        this.arrowLeft.visible = false;
    }

};<|endoftext|>


<commit_before>// Description:
//   Gets the latest beers and their stats from the taphouse beerboard.
//
// Dependencies:
//   "tiny-rebel-web-scraper": "latest"
//
// Commands:
//   hubot what|which beers are on|available - gets the latest beer info from the board
//   hubot get me drunk - gets the strongest available beer
//
// Authors:
//   studioromeo
//   tomseldon
//

'use strict';

const tinyRebelWebScraper = require('tiny-rebel-web-scraper');

module.exports = function (robot) {
    const excuses = [
        'No beers here. Go to the City Arms instead.',
        'Sorry, dunno what\'s on, we\'re all drunk.',
        'ZZZzzz...wha..no, drank it all, try somewhere else...zzzZZZzzzZZZzzz...'
    ];

    robot.respond(/(what|which) beers are (on|available) ?(\(sorted by (.+)?\))?/i, function (message) {
        tinyRebelWebScraper.getAllDrinks('cardiff')
            .then((drinks) => {
                const sortField = message.match[4];
                const shouldSort = Boolean(sortField);

                if (shouldSort) {
                    drinks = sortDrinks(drinks, sortField);
                }

                const response = [
                    'Hey there!',
                    'The following drinks are available at Tiny Rebel (Cardiff):'
                ]
                    .concat(formatDrinks(drinks));

                message.send(response.join('\n'));
            })
            .catch((error) => {
                console.error(error);
                message.send(message.random(excuses));
            });
    });

    robot.respond(/get me drunk/i, function (message) {
        tinyRebelWebScraper.getAllDrinks('cardiff')
            .then((drinks) => {
                // Get the drink with the highest ABV level
                const drink = drinks.reduce((previous, current) => (previous.abv > current.abv) ? previous : current);

                const response = [
                    'Hey there!',
                    'The strongest drink on tap at Tiny Rebel (Cardiff) is:'
                ]
                    .concat(formatDrinks([drink]));

                message.send(response.join('\n'));
            })
            .catch((error) => {
                console.error(error);
                message.send(message.random(excuses));
            });
    });

    /**
     * Sort an array of drinks by the specified sort field.
     *
     * @param {Drink[]} drinks
     * @param {string} sortField
     *
     * @returns {Drink[]}
     */
    function sortDrinks (drinks, sortField) {
        return drinks.sort((a, b) => {
            if (a[sortField] < b[sortField]) {
                return -1;
            }

            if (a[sortField] > b[sortField]) {
                return 1;
            }

            return 0;
        });
    }

    /**
     * Takes an array of drinks (from the web scraper) and parses them into an array
     * of formatted strings, ready to be returned by the robot.
     *
     * @param {Drink[]} drinks
     *
     * @returns {String[]}
     */
    function formatDrinks (drinks) {
        const formattedDrinks = [];

        for (const drink of drinks) {
            let output = `(beer) ${drink.name} [${drink.style}] - ${drink.formattedAbv} -`;

            if (drink.quantity === 'half') {
                output = `${output} ½`;
            }

            output = `${output} ${drink.formattedPrice}`;

            formattedDrinks.push(output);
        }

        return formattedDrinks;
    }
};
<commit_msg>[FEATURE] Add brewery to beer info<commit_after>// Description:
//   Gets the latest beers and their stats from the taphouse beerboard.
//
// Dependencies:
//   "tiny-rebel-web-scraper": "latest"
//
// Commands:
//   hubot what|which beers are on|available - gets the latest beer info from the board
//   hubot get me drunk - gets the strongest available beer
//
// Authors:
//   studioromeo
//   tomseldon
//

'use strict';

const tinyRebelWebScraper = require('tiny-rebel-web-scraper');

module.exports = function (robot) {
    const excuses = [
        'No beers here. Go to the City Arms instead.',
        'Sorry, dunno what\'s on, we\'re all drunk.',
        'ZZZzzz...wha..no, drank it all, try somewhere else...zzzZZZzzzZZZzzz...'
    ];

    robot.respond(/(what|which) beers are (on|available) ?(\(sorted by (.+)?\))?/i, function (message) {
        tinyRebelWebScraper.getAllDrinks('cardiff')
            .then((drinks) => {
                const sortField = message.match[4];
                const shouldSort = Boolean(sortField);

                if (shouldSort) {
                    drinks = sortDrinks(drinks, sortField);
                }

                const response = [
                    'Hey there!',
                    'The following drinks are available at Tiny Rebel (Cardiff):'
                ]
                    .concat(formatDrinks(drinks));

                message.send(response.join('\n'));
            })
            .catch((error) => {
                console.error(error);
                message.send(message.random(excuses));
            });
    });

    robot.respond(/get me drunk/i, function (message) {
        tinyRebelWebScraper.getAllDrinks('cardiff')
            .then((drinks) => {
                // Get the drink with the highest ABV level
                const drink = drinks.reduce((previous, current) => (previous.abv > current.abv) ? previous : current);

                const response = [
                    'Hey there!',
                    'The strongest drink on tap at Tiny Rebel (Cardiff) is:'
                ]
                    .concat(formatDrinks([drink]));

                message.send(response.join('\n'));
            })
            .catch((error) => {
                console.error(error);
                message.send(message.random(excuses));
            });
    });

    /**
     * Sort an array of drinks by the specified sort field.
     *
     * @param {Drink[]} drinks
     * @param {string} sortField
     *
     * @returns {Drink[]}
     */
    function sortDrinks (drinks, sortField) {
        return drinks.sort((a, b) => {
            if (a[sortField] < b[sortField]) {
                return -1;
            }

            if (a[sortField] > b[sortField]) {
                return 1;
            }

            return 0;
        });
    }

    /**
     * Takes an array of drinks (from the web scraper) and parses them into an array
     * of formatted strings, ready to be returned by the robot.
     *
     * @param {Drink[]} drinks
     *
     * @returns {String[]}
     */
    function formatDrinks (drinks) {
        const formattedDrinks = [];

        for (const drink of drinks) {
            let output = `(beer) ${drink.name} [${drink.brewery}] - ${drink.style} - ${drink.formattedAbv} -`;

            if (drink.quantity === 'half') {
                output = `${output} ½`;
            }

            output = `${output} ${drink.formattedPrice}`;

            formattedDrinks.push(output);
        }

        return formattedDrinks;
    }
};
<|endoftext|>