<commit_before>/////////////////////////////////////////////////////
//get requests///////////////////////////////////////
/////////////////////////////////////////////////////

//landing page
app.get('/', function(req, res){
	res.render('landing.jade');
});

//login
app.get('/login', function(req, res) {
	var loginError = null;

	if(req.query.loginError == 1)
		loginError = 'Whooops!  Bad user / pass combo, try again plz:';

	res.render('login.jade', {loginMessage: loginError})
});

//register
app.get('/register', function(req, res){
	var registerError = null;

	if(req.query.registerError == 1)
		registerError = 'There is already a user registered at that address.  Did you forget your password?';
	if(req.query.registerError == 2)
		registerError = "Passwords don't match - try again!"

	res.render('register.jade', {registerMessage: registerError});
});

//set up a new user profile
app.get('/setupNewUser', function(req, res){

	res.render('chooseClass.jade', {});

});

//logout
app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

//show a page of search results
app.get('/searchResults', function(req, res){

	res.render('searchResults.jade', {	searchResults: searchBuffer[req.user['_id']],
										page: req.query.page,
										nPages: Math.ceil(searchBuffer[req.user['_id']].length/10),
										hasContacted: req.user.hasContacted} );
});

//user profile page
app.get('/userProfile', function(req, res){

	res.render('userProfile.jade', {user: req.user, disciplines: disciplines, languages: languages});

});

//show the first 10 user matches, with links to subsequnt batches of 10
app.get('/userMatches', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
	    	collection.find( {scientist: req.user.developer, language : {$in: req.user.language}, discipline : {$in: req.user.discipline}} ).toArray(function(err, matches){
	    		matchBuffer[req.user['_id']] = matches;
	    		res.render('userMatches.jade', {match: matches,
	    										page: req.query.page,
	    										nPages: Math.ceil(matchBuffer[req.user['_id']].length/10),
	    										hasContacted: req.user.hasContacted});
	    	});
	    });
	});
});

//search page
app.get('/userSearch', function(req, res){

	res.render('userSearch.jade', {languages: languages, disciplines: disciplines});

});

//view another user's profile
app.get('/viewProfile', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
	    	collection.findOne( {uName: req.query.userID}, function(err, user){
	    		res.render('readonlyProfile.jade', {user: user});
	    	});
		});
	});
});

//show the page to contact a user
app.get('/contactUser', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
	    	collection.findOne( {uName: req.query.username}, function(err, user){
	    		res.render('contactUser.jade', {user: user});
	    	});
		});
	});
});

////////////////////////////////////////////////////////
//post requests/////////////////////////////////////////
////////////////////////////////////////////////////////

//validate login attempt
app.post('/login', passport.authenticate('local', { successRedirect: '/userMatches?page=0', failureRedirect: '/login/?loginError=1'}) );

//register a new user
app.post('/regUser', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

		    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
		    	if(err) return res.render('error.jade');
		    	//make sure the password was entered the same way twice
		    	if(req.body.pass != req.body.repass) return res.redirect('/register/?registerError=2');

				//reject new account if email is already taken
		    	collection.find({email: req.body.email}).toArray(function(err, accounts){
		    		if(accounts.length != 0) return res.redirect('/register/?registerError=1');

			        // hash the password along with our new salt:
			        bcrypt.hash(req.body.pass, salt, function(err, hash) {
			        	if(err) return res.render('error.jade');

		        		//register new user in the db:
						collection.insert({'email': req.body.email, 'Pass': hash}, {safe: true}, function(err,res) {});

						//log the new user in:
						collection.findOne({email: req.body.email}, function(err, user){
							if(err) return res.render('error.jade');

							req.login(user, function(err) {
							  if (err) return res.render('error.jade');
							  return res.redirect('/setupNewUser');
							});
						});
			        });
		    	});
		    });
		});
	});
});

//register user and go to setup page
app.post('/newUser', function(req, res){

	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user
			collection.findOne({ email: req.user.email }, function(err, user){

		    	if (err || !user) return res.render('error.jade');

                //update the local user object
                req.user.scientist = !!req.body.scientist;
                req.user.developer = !req.body.scientist;
                req.user.hasContacted = [];

                //write the new data to the DB and carry on to user setup
		    	collection.update(	{email : user.email},
		    						{$set:{ scientist: !!req.body.scientist,
		    								developer: !req.body.scientist,
		    								hasContacted : []

		    							}
		    						},
		    						function(){
										  return res.render('setupUser.jade', {user: req.user, disciplines: disciplines, languages: languages});
		    						});
			});
		});
	});
});

//update a user's profile
app.post('/recordUpdate', function(req, res){

	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user
			collection.findOne({ email: req.user.email }, function(err, user){

		    	if (err || !user) return res.render('error.jade');

		    	//register the username if present - only on profile creation
		    	if(req.body.uName){

			    	//update the local user object
			    	req.user.discipline = req.body.discipline;
			    	req.user.language = req.body.language
			    	req.user.uName = req.body.uName;

		    		//insist all fields have at least one option selected
		    		if(!req.body.discipline){
		    			return res.render('setupUser.jade', {user: req.user, disciplines:disciplines, languages:languages, disciplineError: 'Please choose at least one discipline'})
		    		}

			    	//update the DB and carry on to main user pages
			    	collection.update(	{email : user.email},
			    						{$set:{	discipline : req.body.discipline,
			    								language : req.body.language,
			    								uName : req.body.uName}
			    						},
			    						function(){
											return res.redirect('/userMatches?page=0');
			    						});
			    } else{ //no uName, just a regular update - but in this case email can change
			    	//update the local user object
			    	req.user.discipline = req.body.discipline;
			    	req.user.language = req.body.language;
			    	req.user.email = req.body.email;

			    	//update the DB and carry on to main user pages
			    	collection.update(	{uName : user.uName},
			    						{$set:{	discipline : req.body.discipline,
			    								language : req.body.language,
			    								email : req.body.email}
			    						},
			    						function(){
											return res.redirect('/userMatches?page=0');
			    						});
			    }
			});
		});
	});
});

//go to the password recovery page
app.post('/forgotPass', function(req, res){

	res.render('recoverPassword.jade');

});

//password recovery - generate a random password, hash it, update the db, and mail it to the user
app.post('/emailNewPassword', function(req, res){

	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user
			collection.findOne({ uName: req.body.username }, function(err, user){
				var newPass;

		    	if (err) return res.render('error.jade');
		    	if (!user)
		    		return res.render('error.jade');

		    	//generate a new password, bunch of random characters
		    	newPass = (Math.random() + 1).toString(36);

			    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
			    	if(err) return res.render('error.jade');

				        // hash the password along with our new salt:
				        bcrypt.hash(newPass, salt, function(err, hash) {
				        	if(err) return res.render('error.jade');

				        	//update db
				        	collection.update({uName : user.uName}, {$set:{Pass : hash}}, function(){});

				        });
			    });

				mail({
				    from: "Fred Foo <foo@blurdybloop.com>", // sender address
				    to: "herpderp, mills.wj@gmail.com", // list of receivers
				    subject: "Hello", // Subject line
				    text: newPass // body
				});

				res.redirect('/')
			});
		});
	});
});

//go to the change password form
app.post('/changePasswordForm', function(req, res){

	return res.render('changePassword.jade');

});

//validate and register the new password
app.post('/updatePassword', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
		    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
		    	if(err) return res.render('error.jade');
		    	//make sure the password was entered the same way twice
		    	if(req.body.pass != req.body.repass) return res.render('changePassword.jade');

		        // hash the password along with our new salt:
		        bcrypt.hash(req.body.pass, salt, function(err, hash) {
		        	if(err) return res.render('error.jade');

	        		//register new password in the db:
	        		collection.update({uName : req.user.uName}, {$set:{Pass : hash}}, function(){
	        			return res.redirect('/userMatches?page=0');
	        		});
		        });
		    });
		});
	});
});

//delete the profile of the currently logged in user
app.post('/deleteProfile', function(req, res){

	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user
			collection.findOne({ uName: req.user.uName }, function(err, user){

		    	if (err || !user) return res.render('error.jade');

		    	//logout
		    	req.logout();

		    	//dump user from DB and return to landing page:
		    	collection.remove({uName : user.uName}, true, function(){
		    		return res.redirect('/');
		    	});
			});
		});
	});
});

//run a search using the given parameters
app.post('/search', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
			var scientist = (req.body.profession == 'scientist') ? true : false;

	    	collection.find( {	scientist: scientist,
	    						//for checkbox groups, blank === match anything
	    						language : {$in: (req.body.language ? req.body.language : languages)},
	    						discipline : {$in: (req.body.discipline ? req.body.discipline : disciplines)}
	    					} ).toArray(function(err, matches){
	    							searchBuffer[req.user['_id']] = matches;
	    							return res.redirect('/searchResults?page=0');
	    						});
		});
	});
});

//send an email to the user indicated by _id, and the initiating user
app.post('/sendEmail', function(req, res){
	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user to get their email - this way email is never exposed in the browser
			collection.findOne({ uName: req.body.uName }, function(err, user){

				//send the mail
				mail({
				    from: "Interdisciplinary Programming <noreply@interdisciplinaryprogramming.com>", // sender address
				    to: user.email + ', ' + req.user.email, // list of receivers
				    subject: req.body.subject, // Subject line
				    text: req.body.body // body
				});

				//make a note in the initiating user's database that they've now contacted this user
				collection.findOne({uName: req.user.uName}, function(err, user){
			    	collection.update(	{uName : user.uName},
			    						{$addToSet:{hasContacted : req.body.uName} },
			    						function(){
											return res.redirect('/userMatches?page=0');
			    						});
				});
			});
		});
	});
});<commit_msg>profile registration validation<commit_after>/////////////////////////////////////////////////////
//get requests///////////////////////////////////////
/////////////////////////////////////////////////////

//landing page
app.get('/', function(req, res){
	res.render('landing.jade');
});

//login
app.get('/login', function(req, res) {
	var loginError = null;

	if(req.query.loginError == 1)
		loginError = 'Whooops!  Bad user / pass combo, try again plz:';

	res.render('login.jade', {loginMessage: loginError})
});

//register
app.get('/register', function(req, res){
	var registerError = null;

	if(req.query.registerError == 1)
		registerError = 'There is already a user registered at that address.  Did you forget your password?';
	if(req.query.registerError == 2)
		registerError = "Passwords don't match - try again!"

	res.render('register.jade', {registerMessage: registerError});
});

//set up a new user profile
app.get('/setupNewUser', function(req, res){

	res.render('chooseClass.jade', {});

});

//logout
app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

//show a page of search results
app.get('/searchResults', function(req, res){

	res.render('searchResults.jade', {	searchResults: searchBuffer[req.user['_id']],
										page: req.query.page,
										nPages: Math.ceil(searchBuffer[req.user['_id']].length/10),
										hasContacted: req.user.hasContacted} );
});

//user profile page
app.get('/userProfile', function(req, res){

	res.render('userProfile.jade', {user: req.user, disciplines: disciplines, languages: languages});

});

//show the first 10 user matches, with links to subsequnt batches of 10
app.get('/userMatches', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
	    	collection.find( {scientist: req.user.developer, language : {$in: req.user.language}, discipline : {$in: req.user.discipline}} ).toArray(function(err, matches){
	    		matchBuffer[req.user['_id']] = matches;
	    		res.render('userMatches.jade', {match: matches,
	    										page: req.query.page,
	    										nPages: Math.ceil(matchBuffer[req.user['_id']].length/10),
	    										hasContacted: req.user.hasContacted});
	    	});
	    });
	});
});

//search page
app.get('/userSearch', function(req, res){

	res.render('userSearch.jade', {languages: languages, disciplines: disciplines});

});

//view another user's profile
app.get('/viewProfile', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
	    	collection.findOne( {uName: req.query.userID}, function(err, user){
	    		res.render('readonlyProfile.jade', {user: user});
	    	});
		});
	});
});

//show the page to contact a user
app.get('/contactUser', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
	    	collection.findOne( {uName: req.query.username}, function(err, user){
	    		res.render('contactUser.jade', {user: user});
	    	});
		});
	});
});

////////////////////////////////////////////////////////
//post requests/////////////////////////////////////////
////////////////////////////////////////////////////////

//validate login attempt
app.post('/login', passport.authenticate('local', { successRedirect: '/userMatches?page=0', failureRedirect: '/login/?loginError=1'}) );

//register a new user
app.post('/regUser', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

		    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
		    	if(err) return res.render('error.jade');
		    	//make sure the password was entered the same way twice
		    	if(req.body.pass != req.body.repass) return res.redirect('/register/?registerError=2');

				//reject new account if email is already taken
		    	collection.find({email: req.body.email}).toArray(function(err, accounts){
		    		if(accounts.length != 0) return res.redirect('/register/?registerError=1');

			        // hash the password along with our new salt:
			        bcrypt.hash(req.body.pass, salt, function(err, hash) {
			        	if(err) return res.render('error.jade');

		        		//register new user in the db:
						collection.insert({'email': req.body.email, 'Pass': hash}, {safe: true}, function(err,res) {});

						//log the new user in:
						collection.findOne({email: req.body.email}, function(err, user){
							if(err) return res.render('error.jade');

							req.login(user, function(err) {
							  if (err) return res.render('error.jade');
							  return res.redirect('/setupNewUser');
							});
						});
			        });
		    	});
		    });
		});
	});
});

//register user and go to setup page
app.post('/newUser', function(req, res){

	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user
			collection.findOne({ email: req.user.email }, function(err, user){

		    	if (err || !user) return res.render('error.jade');

                //update the local user object
                req.user.scientist = !!req.body.scientist;
                req.user.developer = !req.body.scientist;
                req.user.hasContacted = [];

                //write the new data to the DB and carry on to user setup
		    	collection.update(	{email : user.email},
		    						{$set:{ scientist: !!req.body.scientist,
		    								developer: !req.body.scientist,
		    								hasContacted : []

		    							}
		    						},
		    						function(){
										  return res.render('setupUser.jade', {user: req.user, disciplines: disciplines, languages: languages});
		    						});
			});
		});
	});
});

//update a user's profile
app.post('/recordUpdate', function(req, res){

	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user
			collection.findOne({ email: req.user.email }, function(err, user){

		    	if (err || !user) return res.render('error.jade');

		    	//register the username if present - only on profile creation
		    	if(req.body.uName){

			    	//update the local user object
			    	req.user.discipline = req.body.discipline;
			    	req.user.language = req.body.language
			    	req.user.uName = req.body.uName;

		    		//insist all fields have at least one option selected
		    		if(!req.body.discipline){
		    			return res.render('setupUser.jade', {user: req.user, disciplines:disciplines, languages:languages, disciplineError: 'Please choose at least one discipline'})
		    		}
		    		if(!req.body.language){
		    			return res.render('setupUser.jade', {user: req.user, disciplines:disciplines, languages:languages, languageError: 'Please choose at least one language'})
		    		}

			    	//update the DB and carry on to main user pages
			    	collection.update(	{email : user.email},
			    						{$set:{	discipline : req.body.discipline,
			    								language : req.body.language,
			    								uName : req.body.uName}
			    						},
			    						function(){
											return res.redirect('/userMatches?page=0');
			    						});
			    } else{ //no uName, just a regular update - but in this case email can change
			    	//update the local user object
			    	req.user.discipline = req.body.discipline;
			    	req.user.language = req.body.language;
			    	req.user.email = req.body.email;

		    		//insist all fields have at least one option selected
		    		if(!req.body.discipline){
		    			return res.render('setupUser.jade', {user: req.user, disciplines:disciplines, languages:languages, disciplineError: 'Please choose at least one discipline'})
		    		}
		    		if(!req.body.language){
		    			return res.render('setupUser.jade', {user: req.user, disciplines:disciplines, languages:languages, languageError: 'Please choose at least one language'})
		    		}

			    	//update the DB and carry on to main user pages
			    	collection.update(	{uName : user.uName},
			    						{$set:{	discipline : req.body.discipline,
			    								language : req.body.language,
			    								email : req.body.email}
			    						},
			    						function(){
											return res.redirect('/userMatches?page=0');
			    						});
			    }
			});
		});
	});
});

//go to the password recovery page
app.post('/forgotPass', function(req, res){

	res.render('recoverPassword.jade');

});

//password recovery - generate a random password, hash it, update the db, and mail it to the user
app.post('/emailNewPassword', function(req, res){

	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user
			collection.findOne({ uName: req.body.username }, function(err, user){
				var newPass;

		    	if (err) return res.render('error.jade');
		    	if (!user)
		    		return res.render('error.jade');

		    	//generate a new password, bunch of random characters
		    	newPass = (Math.random() + 1).toString(36);

			    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
			    	if(err) return res.render('error.jade');

				        // hash the password along with our new salt:
				        bcrypt.hash(newPass, salt, function(err, hash) {
				        	if(err) return res.render('error.jade');

				        	//update db
				        	collection.update({uName : user.uName}, {$set:{Pass : hash}}, function(){});

				        });
			    });

				mail({
				    from: "Fred Foo <foo@blurdybloop.com>", // sender address
				    to: "herpderp, mills.wj@gmail.com", // list of receivers
				    subject: "Hello", // Subject line
				    text: newPass // body
				});

				res.redirect('/')
			});
		});
	});
});

//go to the change password form
app.post('/changePasswordForm', function(req, res){

	return res.render('changePassword.jade');

});

//validate and register the new password
app.post('/updatePassword', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
		    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
		    	if(err) return res.render('error.jade');
		    	//make sure the password was entered the same way twice
		    	if(req.body.pass != req.body.repass) return res.render('changePassword.jade');

		        // hash the password along with our new salt:
		        bcrypt.hash(req.body.pass, salt, function(err, hash) {
		        	if(err) return res.render('error.jade');

	        		//register new password in the db:
	        		collection.update({uName : req.user.uName}, {$set:{Pass : hash}}, function(){
	        			return res.redirect('/userMatches?page=0');
	        		});
		        });
		    });
		});
	});
});

//delete the profile of the currently logged in user
app.post('/deleteProfile', function(req, res){

	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user
			collection.findOne({ uName: req.user.uName }, function(err, user){

		    	if (err || !user) return res.render('error.jade');

		    	//logout
		    	req.logout();

		    	//dump user from DB and return to landing page:
		    	collection.remove({uName : user.uName}, true, function(){
		    		return res.redirect('/');
		    	});
			});
		});
	});
});

//run a search using the given parameters
app.post('/search', function(req, res){

	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {
			var scientist = (req.body.profession == 'scientist') ? true : false;

	    	collection.find( {	scientist: scientist,
	    						//for checkbox groups, blank === match anything
	    						language : {$in: (req.body.language ? req.body.language : languages)},
	    						discipline : {$in: (req.body.discipline ? req.body.discipline : disciplines)}
	    					} ).toArray(function(err, matches){
	    							searchBuffer[req.user['_id']] = matches;
	    							return res.redirect('/searchResults?page=0');
	    						});
		});
	});
});

//send an email to the user indicated by _id, and the initiating user
app.post('/sendEmail', function(req, res){
	//open link to the database
	mongo.Db.connect(mongoUri, function(err, db) {
		db.collection('Users', function(er, collection) {

			//find the user to get their email - this way email is never exposed in the browser
			collection.findOne({ uName: req.body.uName }, function(err, user){

				//send the mail
				mail({
				    from: "Interdisciplinary Programming <noreply@interdisciplinaryprogramming.com>", // sender address
				    to: user.email + ', ' + req.user.email, // list of receivers
				    subject: req.body.subject, // Subject line
				    text: req.body.body // body
				});

				//make a note in the initiating user's database that they've now contacted this user
				collection.findOne({uName: req.user.uName}, function(err, user){
			    	collection.update(	{uName : user.uName},
			    						{$addToSet:{hasContacted : req.body.uName} },
			    						function(){
											return res.redirect('/userMatches?page=0');
			    						});
				});
			});
		});
	});
});<|endoftext|>


<commit_before>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

app.get('/MSCbuilder', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/MSCbuilder.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);
	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		odbManipulationFile = '',
		i, j,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /Filter/Current " + req.body.loadTarget]);
		return res.redirect('/Filter');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /Filter/Filters/" + req.body.deleteTarget]);
		return res.redirect('/Filter');
	}

	//register a new filter - build file and run with execFile for most robust execution (spawn seems to create a race condition, consider removing).
	odbManipulationFile += 'odbedit -c "rm /Filter/Filters/' + req.body.filterName + '"\n';
	odbManipulationFile += 'odbedit -c "mkdir /Filter/Filters/' + req.body.filterName + '"\n';
	for(i=0; i<filter.length; i++){
		odbManipulationFile += 'odbedit -c "create string /Filter/Filters/' + req.body.filterName + '/orCondition'+i+'[' + filter[i].length + ']"\n';
		for(j=0; j<filter[i].length; j++){
			odbManipulationFile += 'odbedit -c "set /Filter/Filters/' + req.body.filterName + '/orCondition'+i + '['+j+'] ' + filter[i][j] + '"\n';
		}
	}

	fs.writeFile('odbManipulation.sh', odbManipulationFile, function(){
		fs.chmod('./odbManipulation.sh', '777', function(){
			execFile('./odbManipulation.sh', function(error, stdout, stderr){
				console.log('Writing ' + req.body.filterName + ' filter to ODB, process [error, stdout, stderr]:');
				console.log([error, stdout, stderr]);

				if(req.body.applyFilter == 'on'){
					spawn('odbedit', ['-c', "set /Filter/Current " + req.body.filterName]);
				}
			});
		});
	});

	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
});

app.post('/buildMSC', function(req, res){

	function configGRIFFINclover(index, suppressors){
		var names = [],
			MSC = [],
			masterChan = (index<9) ? 0 : 1,
			firstCollectorChan = ((index-1)%8)*2, //ie, collector channel of first (of 2) GRIF16s used for this clover.
			collectorChan,
			ADC,
			name, address,
			crystalPrefix = 'GRG' + ((index<10) ? '0'+index : index),
			color = ['B', 'G', 'R', 'W'],
			crystalSuffix = ['N00A', 'N00B'],
			vetoPrefix = 'GRS' + ((index<10) ? '0'+index : index),
			i,j,k;

		if(suppressors){
			//HPGe
			/*
			for(i=0; i<crystalSuffix.length; i++){
				for(j=0; j<color.length; j++){
					name = crystalPrefix + color[j] + crystalSuffix[i];

					collectorChan = firstCollectorChan + i;
					ADC = j;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}
			*/
			//BGO
			for(j=0; j<color.length; j++){
				for(i=0; i<5; i++){
					name = vetoPrefix + color[j] + 'N0' + i + 'X';

					collectorChan = firstCollectorChan + ((j<2) ? 0 : 1);
					ADC = 5 + (j%2)*5+i;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}

		} else{
			//HPGE

			//BGO

		}

		return [names, MSC];
	}

	var test = configGRIFFINclover(1, true),
		i;

	for(i=0; i<test[0].length; i++){
		console.log(test[0][i] + ': ' + test[1][i].toString(16));
	}

	return res.redirect('/DAQ');

});

<commit_msg>building canonical MSC table builder<commit_after>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

app.get('/MSCbuilder', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/MSCbuilder.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);
	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		odbManipulationFile = '',
		i, j,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /Filter/Current " + req.body.loadTarget]);
		return res.redirect('/Filter');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /Filter/Filters/" + req.body.deleteTarget]);
		return res.redirect('/Filter');
	}

	//register a new filter - build file and run with execFile for most robust execution (spawn seems to create a race condition, consider removing).
	odbManipulationFile += 'odbedit -c "rm /Filter/Filters/' + req.body.filterName + '"\n';
	odbManipulationFile += 'odbedit -c "mkdir /Filter/Filters/' + req.body.filterName + '"\n';
	for(i=0; i<filter.length; i++){
		odbManipulationFile += 'odbedit -c "create string /Filter/Filters/' + req.body.filterName + '/orCondition'+i+'[' + filter[i].length + ']"\n';
		for(j=0; j<filter[i].length; j++){
			odbManipulationFile += 'odbedit -c "set /Filter/Filters/' + req.body.filterName + '/orCondition'+i + '['+j+'] ' + filter[i][j] + '"\n';
		}
	}

	fs.writeFile('odbManipulation.sh', odbManipulationFile, function(){
		fs.chmod('./odbManipulation.sh', '777', function(){
			execFile('./odbManipulation.sh', function(error, stdout, stderr){
				console.log('Writing ' + req.body.filterName + ' filter to ODB, process [error, stdout, stderr]:');
				console.log([error, stdout, stderr]);

				if(req.body.applyFilter == 'on'){
					spawn('odbedit', ['-c', "set /Filter/Current " + req.body.filterName]);
				}
			});
		});
	});

	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
});

app.post('/buildMSC', function(req, res){

	function configGRIFFINclover(index, suppressors){
		var names = [],
			MSC = [],
			masterChan = (index<9) ? 0 : 1,
			firstCollectorChan = ((index-1)%8)*2, //ie, collector channel of first (of 2) GRIF16s used for this clover.
			collectorChan,
			ADC,
			name, address,
			crystalPrefix = 'GRG' + ((index<10) ? '0'+index : index),
			color = ['B', 'G', 'R', 'W'],
			crystalSuffix = ['N00A', 'N00B'],
			vetoPrefix = 'GRS' + ((index<10) ? '0'+index : index),
			i,j,k;

		if(suppressors){
			//HPGe
			for(i=0; i<crystalSuffix.length; i++){
				for(j=0; j<color.length; j++){
					name = crystalPrefix + color[j] + crystalSuffix[i];

					collectorChan = firstCollectorChan + i;
					ADC = j;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}

			//BGO
			for(j=0; j<color.length; j++){
				for(i=0; i<5; i++){
					name = vetoPrefix + color[j] + 'N0' + i + 'X';

					collectorChan = firstCollectorChan + ((j<2) ? 0 : 1);
					ADC = 5 + (j%2)*5+i;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}

		} else{
			for(i=0; i<crystalSuffix.length; i++){
				for(j=0; j<color.length; j++){
					name = crystalPrefix + color[j] + crystalSuffix[i];

					collectorChan = firstCollectorChan;
					ADC = j + 4*i;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}
		}

		return [names, MSC];
	}

	var test = configGRIFFINclover(1, true),
		i;

	for(i=0; i<test[0].length; i++){
		console.log(test[0][i] + ': ' + test[1][i].toString(16));
	}

	return res.redirect('/DAQ');

});

<|endoftext|>


<commit_before>var db = require('./database.js');
var con = db.connection;
var settings = db.system_settings;
var moment = require('moment');
var middleware = require('./roles.js');
var admin = require('./admin.js');

module.exports = function(app) {

	app.get('/', function(req, res) {
		//session.startSession(req, res);
		// req.session.put('info', 'myInfo', function(req,res){
		console.log(req.body.idtoken);
		res.render('login.html');
		// });
	});

	app.get('/teacher', middleware.isTeacher, function(req, res) {
		var uid_teacher = req.user.local.uid_teacher;
		con.query('select teachers.uid_teacher, teachers.prefix, teachers.name as teacherName, offerings.name as offeringName, offerings.uid_offering, offerings.description, offerings.max_size, offerings.recurring from teachers inner join offerings ON teachers.uid_teacher=offerings.uid_teacher where teachers.uid_teacher = ?;', [uid_teacher], function(err, resultsTeacher) {
			if (!err && resultsTeacher !== undefined && resultsTeacher.length != 0) {
				res.render('teacher.html', {
					data: resultsTeacher,
					teacherName: resultsTeacher[0].prefix + " " + resultsTeacher[0].teacherName,
				});
			} else {
				con.query('select * from teachers where uid_teacher = ?;', [uid_teacher], function(err, resultsTeacher) {
					console.log(resultsTeacher);
					 res.render('teacher.html', {
					 	teacherName: resultsTeacher[0].prefix + " " + resultsTeacher[0].teacherName,
					 });
				});
			}
		});
	});

	app.get('/editOffering/:id', middleware.isTeacher, function(req, res) {
		var offering_uid = req.params.id;
		var teacher_uid = req.user.local.uid_teacher;
		con.query('select * from offerings where uid_offering = ?;', [offering_uid], function(err, offeringInfo) {
			if (!err) {
				con.query('select opp_block_day.uid_day, opp_block_day.day, calendar.uid_offering as "set" from opp_block_day left join calendar on opp_block_day.uid_day=calendar.uid_day and calendar.uid_offering = ? order by opp_block_day.day;', [offering_uid], function(err, dayResults) {
					if (!err) {
						for (var i = 0; i < dayResults.length; i++) {
							console.log(settings.hours_close_teacher.value_int);
							if (moment(dayResults[i].day).add(settings.hours_close_teacher.value_int,'hours').isBefore()){
								dayResults[i]['canEdit'] = false;

							}else{
								dayResults[i]['canEdit'] = true;
							}

							dayResults[i].day = moment(dayResults[i].day).format('MM-DD');
							dayResults[i].set = dayResults[i].set == offering_uid ? 1 : 0;
						}
						res.render('offeringEdit.html', {
							data: offeringInfo,
							offeringIdUpdate: offering_uid,
							offeringId: offering_uid,
							dayData: dayResults
						});
					}
				});
			} else {
				res.send("not valid offering id!");
			}
		});
	});

	app.get('/delete/:id', middleware.isTeacher, function(req, res) {
		var offering_uid = req.params.id;
		var teacher_uid = req.user.local.uid_teacher;
		con.query('delete from calendar where uid_offering = ?;', [offering_uid], function(err,result) {
			con.query('delete from offerings where uid_offering = ?', [offering_uid], function(err) {
				if (err) {
					console.log(err);
				} else {
					console.log(teacher_uid);
					res.redirect("/teacher/");
				}
			});
		});
	});

	app.post('/updateOffering/:offering_id', middleware.isTeacher, function(req, res) {
		var offering_id = req.params.offering_id;
		var name = req.body.name;
		var description = req.body.description;
		var max_size = parseInt(req.body.max_size);
		var teacherId = req.user.local.uid_teacher;
		var recurring = req.body.recurring == 'on' ? 1 : 0;

		var days = req.body.days;

			con.query('delete from calendar where uid_offering = ?;', [offering_id], function(err,result) {});

		if (!Array.isArray(days)){days = [days];}
		for (var i = 0; i < days.length; i++) {if(days[i] != undefined){days[i] = parseInt(days[i])}else{days = []}}

		if (recurring == 1) {
			con.query('UPDATE offerings SET recurring = 0  WHERE recurring = 1 and  uid_teacher = ? and uid_offering !=? ;', [uid_teacher[0].uid_teacher, offering_id], function(err) {
				if (err) {
					console.log(err);
				}
			});
		}

		con.query('UPDATE offerings SET name = ?, description = ?, max_size = ?, recurring = ? WHERE uid_offering = ?;', [name, description, max_size, recurring, offering_id], function(err) {
			if (err) {
				console.log(err);
			} else {
				res.redirect("/teacher/" + teacherId);
			}
		});
		for (var d = 0; d < days.length; d++) {
				con.query('insert into calendar (uid_day, uid_offering) values (?,?);', [days[d], offering_id], function(err,result) {
					if (err){
						console.log(err);
					}
			});
		}

	});
	//UPDATE offerings SET name=?, description = ?, max_size = ?, recurring = ?, WHERE uid_offering=?;
	//
	app.get('/add', middleware.isTeacher, function(req, res) {
		var teacher_uid = req.user.local.uid_teacher;
		con.query('INSERT into offerings (name, max_size, uid_teacher, recurring, description) values ("", 0, ?, 0, "");', [teacher_uid], function(err) {
			if (!err) {
				con.query('select * from offerings where uid_offering = last_insert_id();', function(err, offeringInfo) {
					res.redirect('/editOffering/'+offeringInfo[0].uid_offering);
				});
			} else {
				res.send("not valid offering id!");
			}
		});
	});

	app.get('/attendance/:offering', middleware.isTeacher, function(req, res) {
		var offering = req.params.offering;

		var uid_day = 1;//theres a function for this somewhere
		con.query('select * from choices inner join students on choices.uid_student = students.uid_student and uid_offering = ? and uid_day = ?', [offering, uid_day], function(err, students) {
			console.log(students);
			res.render('attendance.html',{students: students, uid_offering: offering});
		});

	});

	app.post('/updateAttendance/:offering', middleware.isTeacher, function(req,res){
		console.log(req.params.offering);
		res.end(JSON.stringify(req.body.students));
		var students = req.body.students;
		for (var i = 0; i <students.length;i++ ){
			con.query('update students set arrived = 1 where uid_student = ?',[students[i]], function(err){
				console.log(err);
			});

		}

	});

	//CSV Post
	app.post('/studentcsvinput', middleware.isAdmin, function(req,res) {
		if (res != undefined){
			admin.createStudentCSV(req.body.Rad);
			res.redirect('/admin');
		}
	});

	app.post('/teachercsvinput', middleware.isAdmin, function(req, res) {
		if (res != undefined){
			admin.createTeacherCSV(req.body.Radical);
			res.redirect('/admin');
		}
	});

	app.get('/csvinput', middleware.isAdmin, function(req,res) {
		res.render('clientcsv.html', {
		});
	});

	app.get('/Day/:id', function(req, res) {
		var day_uid = req.params.id;
			con.query('select * from offerings;', function(err, resultsDay) {
				var link=resultsDay[0].uid_teacher;
				//console.log(link);
				con.query('select name from teachers where uid_teacher=?;',[link], function(err, resultName){

				//console.log(resultsDay);

				res.render('Day.html', {
				data:resultsDay,
				Teacher:resultName.name

				});
			});

		});
	});

	app.get('/Offeringstudents/:id', function(req, res){
		var teacher_uid = req.params.id;
		//console.log(teacher_uid);
		con.query('select uid_offering from offerings where uid_teacher=?;',[teacher_uid], function(err, resultsO){
			var off=resultsO[0].uid_offering;
			//console.log(off);
			con.query('select uid_student from choices where uid_offering=?;', [off], function(err, resultsS){

				var stud=resultsS[0].uid_student;

				con.query('select lastname from students where uid_student=?;',[stud], function(err, resultsZ){
				con.query('select name from teachers where uid_teacher=?;', [teacher_uid], function(err, resultsN){
				console.log(resultsN);
				res.render('Offeringstudents.html',{
				name:resultsN[0].name,
				data:resultsZ
				});
			});
			});
		});
	});
	});

	app.get('/Admin', function(req, res){
		con.query('select * from opp_block_day;', function(err, resultsAdmin){
				console.log(resultsAdmin);
				res.render('Admin.html',{

				data:resultsAdmin
				});

		});
	});

	//need to join those uid students with student names
	app.get('/Mopblock', function(req, res){
		con.query('select * from absent;', function(err, resultsMopblock){
				console.log(resultsMopblock);
				res.render('Mopblock.html',{
				data:resultsMopblock
			});

		});
	});
	//need to access stuff from choices table idk how
}
<commit_msg>johnny's fault<commit_after>var db = require('./database.js');
var con = db.connection;
var settings = db.system_settings;
var moment = require('moment');
var middleware = require('./roles.js');
var admin = require('./admin.js');

module.exports = function(app) {

	app.get('/', function(req, res) {
		//session.startSession(req, res);
		// req.session.put('info', 'myInfo', function(req,res){
		console.log(req.body.idtoken);
		res.render('login.html');
		// });
	});

	app.get('/teacher', middleware.isTeacher, function(req, res) {
		var uid_teacher = req.user.local.uid_teacher;
		con.query('select teachers.uid_teacher, teachers.teacher_firstname as teacherName, offerings.name as offeringName, offerings.uid_offering, offerings.description, offerings.max_size, offerings.recurring from teachers inner join offerings ON teachers.uid_teacher=offerings.uid_teacher where teachers.uid_teacher = ?;', [uid_teacher], function(err, resultsTeacher) {
			if (!err && resultsTeacher !== undefined && resultsTeacher.length != 0) {
				res.render('teacher.html', {
					data: resultsTeacher,
					teacherName: resultsTeacher[0].teacherName,
				});
			} else {
				con.query('select * from teachers where uid_teacher = ?;', [uid_teacher], function(err, resultsTeacher) {
					console.log(resultsTeacher);
					 res.render('teacher.html', {
					 	teacherName: resultsTeacher[0].prefix + " " + resultsTeacher[0].teacherName,
					 });
				});
			}
		});
	});

	app.get('/editOffering/:id', middleware.isTeacher, function(req, res) {
		var offering_uid = req.params.id;
		var teacher_uid = req.user.local.uid_teacher;
		con.query('select * from offerings where uid_offering = ?;', [offering_uid], function(err, offeringInfo) {
			if (!err) {
				con.query('select opp_block_day.uid_day, opp_block_day.day, calendar.uid_offering as "set" from opp_block_day left join calendar on opp_block_day.uid_day=calendar.uid_day and calendar.uid_offering = ? order by opp_block_day.day;', [offering_uid], function(err, dayResults) {
					if (!err) {
						for (var i = 0; i < dayResults.length; i++) {
							console.log(settings.hours_close_teacher.value_int);
							if (moment(dayResults[i].day).add(settings.hours_close_teacher.value_int,'hours').isBefore()){
								dayResults[i]['canEdit'] = false;

							}else{
								dayResults[i]['canEdit'] = true;
							}

							dayResults[i].day = moment(dayResults[i].day).format('MM-DD');
							dayResults[i].set = dayResults[i].set == offering_uid ? 1 : 0;
						}
						res.render('offeringEdit.html', {
							data: offeringInfo,
							offeringIdUpdate: offering_uid,
							offeringId: offering_uid,
							dayData: dayResults
						});
					}
				});
			} else {
				res.send("not valid offering id!");
			}
		});
	});

	app.get('/delete/:id', middleware.isTeacher, function(req, res) {
		var offering_uid = req.params.id;
		var teacher_uid = req.user.local.uid_teacher;
		con.query('delete from calendar where uid_offering = ?;', [offering_uid], function(err,result) {
			con.query('delete from offerings where uid_offering = ?', [offering_uid], function(err) {
				if (err) {
					console.log(err);
				} else {
					console.log(teacher_uid);
					res.redirect("/teacher/");
				}
			});
		});
	});

	app.post('/updateOffering/:offering_id', middleware.isTeacher, function(req, res) {
		var offering_id = req.params.offering_id;
		var name = req.body.name;
		var description = req.body.description;
		var max_size = parseInt(req.body.max_size);
		var teacherId = req.user.local.uid_teacher;
		var recurring = req.body.recurring == 'on' ? 1 : 0;

		var days = req.body.days;

			con.query('delete from calendar where uid_offering = ?;', [offering_id], function(err,result) {});

		if (!Array.isArray(days)){days = [days];}
		for (var i = 0; i < days.length; i++) {if(days[i] != undefined){days[i] = parseInt(days[i])}else{days = []}}

		if (recurring == 1) {
			con.query('UPDATE offerings SET recurring = 0  WHERE recurring = 1 and  uid_teacher = ? and uid_offering !=? ;', [uid_teacher[0].uid_teacher, offering_id], function(err) {
				if (err) {
					console.log(err);
				}
			});
		}

		con.query('UPDATE offerings SET name = ?, description = ?, max_size = ?, recurring = ? WHERE uid_offering = ?;', [name, description, max_size, recurring, offering_id], function(err) {
			if (err) {
				console.log(err);
			} else {
				res.redirect("/teacher/" + teacherId);
			}
		});
		for (var d = 0; d < days.length; d++) {
				con.query('insert into calendar (uid_day, uid_offering) values (?,?);', [days[d], offering_id], function(err,result) {
					if (err){
						console.log(err);
					}
			});
		}

	});
	//UPDATE offerings SET name=?, description = ?, max_size = ?, recurring = ?, WHERE uid_offering=?;
	//
	app.get('/add', middleware.isTeacher, function(req, res) {
		var teacher_uid = req.user.local.uid_teacher;
		con.query('INSERT into offerings (name, max_size, uid_teacher, recurring, description) values ("", 0, ?, 0, "");', [teacher_uid], function(err) {
			if (!err) {
				con.query('select * from offerings where uid_offering = last_insert_id();', function(err, offeringInfo) {
					res.redirect('/editOffering/'+offeringInfo[0].uid_offering);
				});
			} else {
				res.send("not valid offering id!");
			}
		});
	});

	app.get('/attendance/:offering', middleware.isTeacher, function(req, res) {
		var offering = req.params.offering;

		var uid_day = 1;//theres a function for this somewhere
		con.query('select * from choices inner join students on choices.uid_student = students.uid_student and uid_offering = ? and uid_day = ?', [offering, uid_day], function(err, students) {
			console.log(students);
			res.render('attendance.html',{students: students, uid_offering: offering});
		});

	});

	app.post('/updateAttendance/:offering', middleware.isTeacher, function(req,res){
		console.log(req.params.offering);
		res.end(JSON.stringify(req.body.students));
		var students = req.body.students;
		for (var i = 0; i <students.length;i++ ){
			con.query('update students set arrived = 1 where uid_student = ?',[students[i]], function(err){
				console.log(err);
			});

		}

	});

	//CSV Post
	app.post('/studentcsvinput', middleware.isAdmin, function(req,res) {
		if (res != undefined){
			admin.createStudentCSV(req.body.Rad);
			res.redirect('/admin');
		}
	});

	app.post('/teachercsvinput', middleware.isAdmin, function(req, res) {
		if (res != undefined){
			admin.createTeacherCSV(req.body.Radical);
			res.redirect('/admin');
		}
	});

	app.get('/csvinput', middleware.isAdmin, function(req,res) {
		res.render('clientcsv.html', {
		});
	});

	app.get('/Day/:id', function(req, res) {
		var day_uid = req.params.id;
			con.query('select * from offerings;', function(err, resultsDay) {
				var link=resultsDay[0].uid_teacher;
				//console.log(link);
				con.query('select name from teachers where uid_teacher=?;',[link], function(err, resultName){

				//console.log(resultsDay);

				res.render('Day.html', {
				data:resultsDay,
				Teacher:resultName.name

				});
			});

		});
	});

	app.get('/Offeringstudents/:id', function(req, res){
		var teacher_uid = req.params.id;
		//console.log(teacher_uid);
		con.query('select uid_offering from offerings where uid_teacher=?;',[teacher_uid], function(err, resultsO){
			var off=resultsO[0].uid_offering;
			//console.log(off);
			con.query('select uid_student from choices where uid_offering=?;', [off], function(err, resultsS){

				var stud=resultsS[0].uid_student;

				con.query('select lastname from students where uid_student=?;',[stud], function(err, resultsZ){
				con.query('select name from teachers where uid_teacher=?;', [teacher_uid], function(err, resultsN){
				console.log(resultsN);
				res.render('Offeringstudents.html',{
				name:resultsN[0].name,
				data:resultsZ
				});
			});
			});
		});
	});
	});

	app.get('/Admin', function(req, res){
		con.query('select * from opp_block_day;', function(err, resultsAdmin){
				console.log(resultsAdmin);
				res.render('Admin.html',{

				data:resultsAdmin
				});

		});
	});

	//need to join those uid students with student names
	app.get('/Mopblock', function(req, res){
		con.query('select * from absent;', function(err, resultsMopblock){
				console.log(resultsMopblock);
				res.render('Mopblock.html',{
				data:resultsMopblock
			});

		});
	});
	//need to access stuff from choices table idk how
}
<|endoftext|>


<commit_before>var rss = require('rss-to-json');
var Comment = require('./models/comment.js');

function isLoggedIn(req, res, next) {
    if(req.isAuthenticated()) {
        return next();
    }
    res.redirect('/');
};

module.exports = function(app, passport) {
    app.get('*', function(req, res, next) {
	        res.locals.user = req.user || null;
		next();
    });

    app.use(function(req, res, next) {
     res.setHeader('Access-Control-Allow-Origin', '*');
     res.setHeader('Access-Control-Allow-Credentials', 'true');
     res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
     res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
    //and remove cacheing so we get the most recent comments
     res.setHeader('Cache-Control', 'no-cache');
     next();
    });

    app.get('/', function(req, res) {
      rss.load("http://www.io-tech.fi/feed/", function(err, feed) {
        Comment.find({}, 'author date comment id').sort('-date').limit(10).exec(function(err, comments) {
          if(err) {
            return console.log(err);
          } else {
            res.render('index', {title: 'Jeva ohsiha', json: feed, comments: comments});
          }
        })
	   });
    });

    app.get('/delete', isLoggedIn, function(req, res) {
      Comment.findOne({_id: req.query.id}).remove(function(err) {
        if(err) {
          return console.log(err);
        } else {
          res.redirect('/');
        }
      });
    });

    app.post('/comment', isLoggedIn, function(req, res) {
      var newComment = new Comment();
      newComment.author = req.user.google.name;
      newComment.comment = req.body.comment;
      newComment.save(function(err) {
        if (err) {
          return console.log(err);
        } else {
          res.redirect('/');
        }
      });
    });

    app.get('/comments', function(req, res) {
      Comment.find({}, 'author date comment id').sort('-date').limit(10).exec(function(err, comments) {
        if(err) {
          return console.log(err);
        } else {
          console.log('comments loaded');
          res.json(comments);
        }
      });
    });

    app.get('/json', function(req, res) {
        rss.load("http://www.io-tech.fi/feed/", function(err, feed) {
	   console.log('json loaded');
	   res.json(feed);
	   });
     });
    app.get('/auth/google', passport.authenticate('google', {scope : ['profile', 'email'] }));

    app.get('/auth/google/callback',
            passport.authenticate('google', {
	        successRedirect : '/',
		failureRedirect : '/'
	    }));
     app.get('/logout', function(req, res) {
         req.logout();
	 res.redirect('/');
     });
};
<commit_msg>fixed comment post<commit_after>var rss = require('rss-to-json');
var Comment = require('./models/comment.js');

function isLoggedIn(req, res, next) {
    if(req.isAuthenticated()) {
        return next();
    }
    res.redirect('/');
};

module.exports = function(app, passport) {
    app.get('*', function(req, res, next) {
	        res.locals.user = req.user || null;
		next();
    });

    app.use(function(req, res, next) {
     res.setHeader('Access-Control-Allow-Origin', '*');
     res.setHeader('Access-Control-Allow-Credentials', 'true');
     res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
     res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
    //and remove cacheing so we get the most recent comments
     res.setHeader('Cache-Control', 'no-cache');
     next();
    });

    app.get('/', function(req, res) {
      rss.load("http://www.io-tech.fi/feed/", function(err, feed) {
        Comment.find({}, 'author date comment id').sort('-date').limit(10).exec(function(err, comments) {
          if(err) {
            return console.log(err);
          } else {
            res.render('index', {title: 'Jeva ohsiha', json: feed, comments: comments});
          }
        })
	   });
    });

    app.get('/delete', isLoggedIn, function(req, res) {
      Comment.findOne({_id: req.query.id}).remove(function(err) {
        if(err) {
          return console.log(err);
        } else {
          res.redirect('/');
        }
      });
    });

    app.post('/comments', function(req, res) {
      var newComment = new Comment();
      newComment.author = req.body.author;
      newComment.comment = req.body.comment;
      newComment.save(function(err) {
        if (err) {
          return console.log(err);
        } else {
          res.redirect('/');
        }
      });
    });

    app.get('/comments', function(req, res) {
      Comment.find({}, 'author date comment id').sort('-date').limit(10).exec(function(err, comments) {
        if(err) {
          return console.log(err);
        } else {
          console.log('comments loaded');
          res.json(comments);
        }
      });
    });

    app.get('/json', function(req, res) {
        rss.load("http://www.io-tech.fi/feed/", function(err, feed) {
	   console.log('json loaded');
	   res.json(feed);
	   });
     });
    app.get('/auth/google', passport.authenticate('google', {scope : ['profile', 'email'] }));

    app.get('/auth/google/callback',
            passport.authenticate('google', {
	        successRedirect : '/',
		failureRedirect : '/'
	    }));
     app.get('/logout', function(req, res) {
         req.logout();
	 res.redirect('/');
     });
};
<|endoftext|>


<commit_before>/**
 *  @file routes.js
 */
const express = require('express'),
  storage = require('node-persist')

const categorize = require('./middlewares').categorize,
  validateGroup = require('./middlewares').validateGroup,
  handlers = require('./middlewares').handlers

exports.init = (bot) => {
  storage.initSync()

  const router = express.Router()

  const url = '/bot/:id/:name'

  handlers = handlers.map(handle => handle(bot))

  // handle group messages
  router.post.apply(router, [url, categorize, validateGroup].concat(handlers))

  // handle user messages
  router.post.apply(router, [url].concat(handlers))

  return router
}
<commit_msg>Fix assigning to constant<commit_after>/**
 *  @file routes.js
 */
const express = require('express'),
  storage = require('node-persist')

const categorize = require('./middlewares').categorize,
  validateGroup = require('./middlewares').validateGroup

let handlers = require('./middlewares').handlers

exports.init = (bot) => {
  storage.initSync()

  const router = express.Router()

  const url = '/bot/:id/:name'

  handlers = handlers.map(handle => handle(bot))

  // handle group messages
  router.post.apply(router, [url, categorize, validateGroup].concat(handlers))

  // handle user messages
  router.post.apply(router, [url].concat(handlers))

  return router
}
<|endoftext|>


<commit_before>const PanelsActionCreator = require('../actions/panels-action-creator');

const TARGET_PANELS = [
  // [stripId, panelId],
  ['0', '0'],
  ['1', '1'],
  ['2', '2'],
  ['1', '2'],
  ['0', '3'],
  ['2', '5'],
  ['0', '0']
];

const TARGET_PANEL_INTENSITY = 100;
const PANEL_OFF_INTENSITY = 0;

export default class MoleGameLogic {
  // These are automatically added to the sculpture store
  static trackedProperties = {
    targetPanelIndex: 0
  };

  constructor(store) {
    this.store = store;
  }

  get data() {
    return this.store.data.get('mole');
  }

  start() {
    this._enableCurrentTargetPanel();
  }

  handleActionPayload(payload) {
    switch (payload.actionType) {
      case PanelsActionCreator.PANEL_PRESSED:
        this._actionPanelPressed(payload);
        break;
      default:
        // Do nothing for unrecognized actions
        break;
    }
  }

  _actionPanelPressed(payload) {
    let {stripId, panelId, pressed} = payload;

    const targetPanelIndex = this.data.get("targetPanelIndex");
    const [targetStripId, targetPanelId] = this._getTargetPanel(targetPanelIndex);

    if (stripId === targetStripId && panelId === targetPanelId && pressed) {
      this.data.set("targetPanelIndex", targetPanelIndex + 1);
      this._enableCurrentTargetPanel();
    }
  }

  _enableCurrentTargetPanel() {
    const targetPanelIndex = this.data.get("targetPanelIndex");
    if (targetPanelIndex > 0) {
      this._disablePanelIndex(targetPanelIndex - 1);
    }

    if (targetPanelIndex >= TARGET_PANELS.length) {
      this.data.set("targetPanelIndex", 0);
      this._enableCurrentTargetPanel();

      //TODO: end animation
      this.store.lock();
      setTimeout(() => {
        this.store.restoreStatus();
        this.store.publishChanges();
      }, 2000);
      return;
    }

    const [targetStripId, targetPanelId] = this._getTargetPanel(targetPanelIndex);
    this._enablePanel(targetStripId, targetPanelId);
  }

  _enablePanel(stripId, panelId) {
    this.store.data.get('lights').setIntensity(stripId, panelId, TARGET_PANEL_INTENSITY);
  }

  _disablePanelIndex(index) {
    const [stripId, panelId] = this._getTargetPanel(index);
    this._disablePanel(stripId, panelId);
  }

  _disablePanel(stripId, panelId) {
    this.store.data.get('lights').setIntensity(stripId, panelId, PANEL_OFF_INTENSITY);
  }

  _getTargetPanel(index) {
    return TARGET_PANELS[index];
  }
}
<commit_msg>Stopped ending up on the same panel for debugging ease<commit_after>const PanelsActionCreator = require('../actions/panels-action-creator');

const TARGET_PANELS = [
  // [stripId, panelId],
  ['0', '0'],
  ['1', '1'],
  ['2', '2'],
  ['1', '2'],
  ['0', '3'],
  ['2', '5']
];

const TARGET_PANEL_INTENSITY = 100;
const PANEL_OFF_INTENSITY = 0;

export default class MoleGameLogic {
  // These are automatically added to the sculpture store
  static trackedProperties = {
    targetPanelIndex: 0
  };

  constructor(store) {
    this.store = store;
  }

  get data() {
    return this.store.data.get('mole');
  }

  start() {
    this._enableCurrentTargetPanel();
  }

  handleActionPayload(payload) {
    switch (payload.actionType) {
      case PanelsActionCreator.PANEL_PRESSED:
        this._actionPanelPressed(payload);
        break;
      default:
        // Do nothing for unrecognized actions
        break;
    }
  }

  _actionPanelPressed(payload) {
    let {stripId, panelId, pressed} = payload;

    const targetPanelIndex = this.data.get("targetPanelIndex");
    const [targetStripId, targetPanelId] = this._getTargetPanel(targetPanelIndex);

    if (stripId === targetStripId && panelId === targetPanelId && pressed) {
      this.data.set("targetPanelIndex", targetPanelIndex + 1);
      this._enableCurrentTargetPanel();
    }
  }

  _enableCurrentTargetPanel() {
    const targetPanelIndex = this.data.get("targetPanelIndex");
    if (targetPanelIndex > 0) {
      this._disablePanelIndex(targetPanelIndex - 1);
    }

    if (targetPanelIndex >= TARGET_PANELS.length) {
      this.data.set("targetPanelIndex", 0);
      this._enableCurrentTargetPanel();

      //TODO: end animation
      this.store.lock();
      setTimeout(() => {
        this.store.restoreStatus();
        this.store.publishChanges();
      }, 2000);
      return;
    }

    const [targetStripId, targetPanelId] = this._getTargetPanel(targetPanelIndex);
    this._enablePanel(targetStripId, targetPanelId);
  }

  _enablePanel(stripId, panelId) {
    this.store.data.get('lights').setIntensity(stripId, panelId, TARGET_PANEL_INTENSITY);
  }

  _disablePanelIndex(index) {
    const [stripId, panelId] = this._getTargetPanel(index);
    this._disablePanel(stripId, panelId);
  }

  _disablePanel(stripId, panelId) {
    this.store.data.get('lights').setIntensity(stripId, panelId, PANEL_OFF_INTENSITY);
  }

  _getTargetPanel(index) {
    return TARGET_PANELS[index];
  }
}
<|endoftext|>


<commit_before>import { pt, LinearGradient, Color, Rectangle } from "lively.graphics";
import { Morph, StyleSheet } from "lively.morphic";
import { signal, disconnect, connect } from "lively.bindings";
import { obj, arr } from "lively.lang/index.js";

// var b = new Button({label: "test", extent: pt(22,18)}).openInWorld()
// b.scale = 10
// import { Icon } from "./icons.js";
// b.label = [Icon.textAttribute("plus")]
// b.padding = Rectangle.inset(2,4,2,5); b.fit()
// b.relayout()
// b.fit()

export class Button extends Morph {

  static get styleSheet() {
    return new StyleSheet('Button Style', {
      ".Button": {borderWidth: 1, borderRadius: 5, extent: pt(100, 20)},
      ".Button.activeStyle": {
        borderColor: Color.gray,
        fill: new LinearGradient({
          stops: [{offset: 0, color: Color.white}, {offset: 1, color: new Color.rgb(236, 240, 241)}]
        }),
        nativeCursor: "pointer"
      },
      ".Button.triggerStyle": {
        borderColor: Color.gray,
        fill: Color.rgb(161, 161, 161),
        nativeCursor: "pointer"
      },
      ".Button.inactiveStyle": {
        borderColor: Color.gray,
        opacity: .5,
        fill: new LinearGradient({
          stops: [{offset: 0, color: Color.white}, {offset: 1, color: new Color.rgb(236, 240, 241)}]
        }),
        nativeCursor: "not-allowed"
      },
      ".Button.activeStyle [name=label]": {fontSize: 12, fontColor: Color.almostBlack},
      ".Button.triggerStyle [name=label]": {fontSize: 12, fontColor: Color.almostBlack},
      ".Button.inactiveStyle [name=label]": {fontSize: 12, fontColor: Color.almostBlack.withA(0.5)}
    });
  }

  static get properties() {
    return {
      fill: {defaultValue: Color.white},
      padding:      {isStyleProp: true, defaultValue: Rectangle.inset(4,2)},
      draggable:    {defaultValue: false},

      fontSize: {
        type: "Number",
        min: 0,
        isStyleProps: true,
        defaultValue: 12,
        after: ['labelMorph', 'iconMorph'],
        set(s) {
          this.setProperty('fontSize', s);
          this.labelMorph.fontSize = s;
          this.iconMorph && (this.iconMorph.fontSize = s);
        }
      },

      fontColor: {
        isStyleProps: true,
        defaultValue: Color.black,
        after: ['labelMorph', 'iconMorph'],
        set(c) {
          this.setProperty('fontColor', c);
          this.labelMorph.fontColor = c;
          this.iconMorph && (this.iconMorph.fontColor = c);
        }
      },

      activeMode: {
        after: ["labelMorph"],
        type: 'Enum',
        values: ['active', 'inactive', 'triggered'],
        get() {
           return this._buttonMode || 'active'
        },
        set(m) {
           switch(m) {
             case "active":
               this.activate();
               break;
             case "inactive":
               this.deactivate();
               break;
             case "triggered":
               this.perform();
               break;
           }
           this._buttonMode = m;
        }
      },
      iconMorph: {
        after: ['submorphs'],
        initialize() {
          this.iconMorph = this.addMorph({
            type: "label", name: "icon",
            value: ""
          });
        },
        get() { return this.getSubmorphNamed('icon') },
        set(iconMorph) {
          var existing = this.iconMorph;
          if (existing) {
            disconnect(this.iconMorph, "extent", this, "relayout");
            existing.remove();
          }
          if (!iconMorph) return;
          iconMorph.name = "icon";
          iconMorph.reactsToPointer = false;
          this.addMorphAt(iconMorph, 0);
          connect(this.iconMorph, 'extent', this, 'relayout');
        }
      },
      // button label
      labelMorph: {
        after: ["submorphs"],
        initialize() {
          this.labelMorph = this.addMorph({
            type: "label", name: "label",
            value: "no label yet"
          });
        },
        get() { return this.getSubmorphNamed("label"); },
        set(labelMorph) {
          var existing = this.labelMorph;
          if (existing) {
            disconnect(this.labelMorph, "extent", this, "relayout");
            existing.remove();
          }
          labelMorph.name = "label";
          labelMorph.reactsToPointer = false;
          this.addMorphAt(labelMorph, 0);
          connect(this.labelMorph, 'extent', this, 'relayout');
        }
      },

      icon: {
        after: ['labelMorph', 'iconMorph'],
        isStyleProp: true,
        type: "Icon", // "" -> no icon, else a valid font awesome icon code
        initialize() {
          this.icon = "";
        },
        set(codeOrIconMorph) {
          this.setProperty('icon', codeOrIconMorph);
          if (!this.iconMorph) {
            this.iconMorph = this.addMorph({
              type: "label",
              name: "icon",
              value: ""
            });
          }
          if (codeOrIconMorph && codeOrIconMorph.isMorph) {
            this.iconMorph = codeOrIconMorph;
          } else {
            this.iconMorph.value = codeOrIconMorph || "";
          }
        }
      },

      iconPosition: {
        defaultValue: "left",
        type: "Enum",
        values: ["left", "right", "bottom", "top"]
      },

      label: {
        after: ["labelMorph"],
        isStyleProp: true,
        type: "RichText", // this includes an attributes Array
        set(stringOrAttributesOrMorph) {
          if (stringOrAttributesOrMorph.isMorph) {
            this.setProperty('label', stringOrAttributesOrMorph.value)
            this.labelMorph = stringOrAttributesOrMorph;
          } else {
            this.setProperty('label', stringOrAttributesOrMorph)
            this.labelMorph.value = stringOrAttributesOrMorph;
          }
        }
      },

      labelWithTextAttributes: {
        after: ["labelMorph"], derived: true,
        get() { return this.labelMorph.textAndAttributes; },
        set(val) { this.labelMorph.textAndAttributes = val; }
      }
    }
  }

  constructor(props) {
    super(props);
    this.activeMode = 'active';
    this.relayout();
    connect(this, 'extent', this, 'relayout');
    connect(this, 'iconPosition', this, 'relayout');
    connect(this, 'padding', this, 'relayout');
    connect(this, 'fontSize', this, 'relayout');
    connect(this, 'fontFamily', this, 'relayout');
  }

  get isButton() { return true }

  relayout() {
    var label = this.labelMorph,
        icon = this.iconMorph;
    if (!label) return;
    var padding = this.padding,
        padT = padding.top(),
        padB = padding.bottom(),
        padL = padding.left(),
        padR = padding.right(),
        minHeight = label.height + padT + padB,
        minWidth = label.width + padL + padR;
    if (minHeight > this.height) this.height = minHeight;
    if (minWidth > this.width) this.width = minWidth;
    let innerPadding = this.innerBounds().insetByRect(padding);
    label.center = innerPadding.center();
    if (!icon || !this.iconMorph.value) return this;
    switch (this.iconPosition) {
      case 'left':
        label.rightCenter = innerPadding.rightCenter();
        icon.rightCenter = label.leftCenter;
        return this;
      case 'right':
        label.leftCenter = innerPadding.leftCenter();
        icon.leftCenter = label.rightCenter;
        return this;
      case 'top':
        label.bottomCenter = innerPadding.bottomCenter();
        icon.bottomCenter = label.topCenter;
        return this;
      case 'bottom':
        label.topCenter = innerPadding.topCenter();
        icon.topCenter = label.bottomCenter;
        return this;
    }
    return this;
  }

  fit() {
    var padding = this.padding, label = this.labelMorph;
    label.fit();
    this.extent = padding.bottomLeft().addPt(padding.bottomRight()).addPt(label.extent);
    this.relayout();
    return this;
  }

  get isActive() {
    return this.activeMode == 'active'
  }

  activate() {
    let classes = arr.withoutAll(this.styleClasses, ['inactiveStyle', 'triggerStyle'])
    this.styleClasses = [...classes, 'activeStyle'];
  }

  deactivate() {
    let classes = arr.withoutAll(this.styleClasses, ['activeStyle', 'triggerStyle'])
    this.styleClasses = [...classes, 'inactiveStyle'];
  }

  perform() {
    let classes = arr.withoutAll(this.styleClasses, ['inactiveStyle', 'activeStyle'])
    this.styleClasses = [...classes, 'triggerStyle'];
  }

  enable() { this.activeMode = "active"; }

  disable() { this.activeMode = "inactive"; }

  trigger() {
    try {
      signal(this, "fire");
      typeof this.action == "function" && this.action();
    } catch (err) {
      var w = this.world();
      if (w) w.logError(err);
      else console.error(err);
    }
  }

  onMouseDown(evt) {
    if (this.isActive && this.innerBoundsContainsPoint(evt.positionIn(this)))
      this.activeMode = 'triggered'
  }

  onMouseUp(evt) {
    if (evt.isClickTarget(this) && this.activeMode == 'triggered') {
      this.activeMode = 'active';
      this.trigger();
    }
  }

  onHoverOut(evt) {
    // When leaving the button without mouse up, reset appearance
    if (this.activeMode == 'triggered' && evt.isClickTarget(this))
      this.activeMode = 'active';
  }

  onHoverIn(evt) {
    if (this.isActive && evt.isClickTarget(this))
      this.activeMode = 'triggered';
  }

}
<commit_msg>button: change label menu item<commit_after>import { pt, LinearGradient, Color, Rectangle } from "lively.graphics";
import { Morph, StyleSheet } from "lively.morphic";
import { signal, disconnect, connect } from "lively.bindings";
import { obj, arr } from "lively.lang/index.js";

// var b = new Button({label: "test", extent: pt(22,18)}).openInWorld()
// b.scale = 10
// import { Icon } from "./icons.js";
// b.label = [Icon.textAttribute("plus")]
// b.padding = Rectangle.inset(2,4,2,5); b.fit()
// b.relayout()
// b.fit()

export class Button extends Morph {

  static get styleSheet() {
    return new StyleSheet('Button Style', {
      ".Button": {borderWidth: 1, borderRadius: 5, extent: pt(100, 20)},
      ".Button.activeStyle": {
        borderColor: Color.gray,
        fill: new LinearGradient({
          stops: [{offset: 0, color: Color.white}, {offset: 1, color: new Color.rgb(236, 240, 241)}]
        }),
        nativeCursor: "pointer"
      },
      ".Button.triggerStyle": {
        borderColor: Color.gray,
        fill: Color.rgb(161, 161, 161),
        nativeCursor: "pointer"
      },
      ".Button.inactiveStyle": {
        borderColor: Color.gray,
        opacity: .5,
        fill: new LinearGradient({
          stops: [{offset: 0, color: Color.white}, {offset: 1, color: new Color.rgb(236, 240, 241)}]
        }),
        nativeCursor: "not-allowed"
      },
      ".Button.activeStyle [name=label]": {fontSize: 12, fontColor: Color.almostBlack},
      ".Button.triggerStyle [name=label]": {fontSize: 12, fontColor: Color.almostBlack},
      ".Button.inactiveStyle [name=label]": {fontSize: 12, fontColor: Color.almostBlack.withA(0.5)}
    });
  }

  static get properties() {
    return {
      fill: {defaultValue: Color.white},
      padding:      {isStyleProp: true, defaultValue: Rectangle.inset(4,2)},
      draggable:    {defaultValue: false},

      fontSize: {
        type: "Number",
        min: 0,
        isStyleProps: true,
        defaultValue: 12,
        after: ['labelMorph', 'iconMorph'],
        set(s) {
          this.setProperty('fontSize', s);
          this.labelMorph.fontSize = s;
          this.iconMorph && (this.iconMorph.fontSize = s);
        }
      },

      fontColor: {
        isStyleProps: true,
        defaultValue: Color.black,
        after: ['labelMorph', 'iconMorph'],
        set(c) {
          this.setProperty('fontColor', c);
          this.labelMorph.fontColor = c;
          this.iconMorph && (this.iconMorph.fontColor = c);
        }
      },

      activeMode: {
        after: ["labelMorph"],
        type: 'Enum',
        values: ['active', 'inactive', 'triggered'],
        get() {
           return this._buttonMode || 'active'
        },
        set(m) {
           switch(m) {
             case "active":
               this.activate();
               break;
             case "inactive":
               this.deactivate();
               break;
             case "triggered":
               this.perform();
               break;
           }
           this._buttonMode = m;
        }
      },
      iconMorph: {
        after: ['submorphs'],
        initialize() {
          this.iconMorph = this.addMorph({
            type: "label", name: "icon",
            value: ""
          });
        },
        get() { return this.getSubmorphNamed('icon') },
        set(iconMorph) {
          var existing = this.iconMorph;
          if (existing) {
            disconnect(this.iconMorph, "extent", this, "relayout");
            existing.remove();
          }
          if (!iconMorph) return;
          iconMorph.name = "icon";
          iconMorph.reactsToPointer = false;
          this.addMorphAt(iconMorph, 0);
          connect(this.iconMorph, 'extent', this, 'relayout');
        }
      },
      // button label
      labelMorph: {
        after: ["submorphs"],
        initialize() {
          this.labelMorph = this.addMorph({
            type: "label", name: "label",
            value: "no label yet"
          });
        },
        get() { return this.getSubmorphNamed("label"); },
        set(labelMorph) {
          var existing = this.labelMorph;
          if (existing) {
            disconnect(this.labelMorph, "extent", this, "relayout");
            existing.remove();
          }
          labelMorph.name = "label";
          labelMorph.reactsToPointer = false;
          this.addMorphAt(labelMorph, 0);
          connect(this.labelMorph, 'extent', this, 'relayout');
        }
      },

      icon: {
        after: ['labelMorph', 'iconMorph'],
        isStyleProp: true,
        type: "Icon", // "" -> no icon, else a valid font awesome icon code
        initialize() {
          this.icon = "";
        },
        set(codeOrIconMorph) {
          this.setProperty('icon', codeOrIconMorph);
          if (!this.iconMorph) {
            this.iconMorph = this.addMorph({
              type: "label",
              name: "icon",
              value: ""
            });
          }
          if (codeOrIconMorph && codeOrIconMorph.isMorph) {
            this.iconMorph = codeOrIconMorph;
          } else {
            this.iconMorph.value = codeOrIconMorph || "";
          }
        }
      },

      iconPosition: {
        defaultValue: "left",
        type: "Enum",
        values: ["left", "right", "bottom", "top"]
      },

      label: {
        after: ["labelMorph"],
        isStyleProp: true,
        type: "RichText", // this includes an attributes Array
        set(stringOrAttributesOrMorph) {
          if (stringOrAttributesOrMorph.isMorph) {
            this.setProperty('label', stringOrAttributesOrMorph.value)
            this.labelMorph = stringOrAttributesOrMorph;
          } else {
            this.setProperty('label', stringOrAttributesOrMorph)
            this.labelMorph.value = stringOrAttributesOrMorph;
          }
        }
      },

      labelWithTextAttributes: {
        after: ["labelMorph"], derived: true,
        get() { return this.labelMorph.textAndAttributes; },
        set(val) { this.labelMorph.textAndAttributes = val; }
      }
    }
  }

  constructor(props) {
    super(props);
    this.activeMode = 'active';
    this.relayout();
    connect(this, 'extent', this, 'relayout');
    connect(this, 'iconPosition', this, 'relayout');
    connect(this, 'padding', this, 'relayout');
    connect(this, 'fontSize', this, 'relayout');
    connect(this, 'fontFamily', this, 'relayout');
  }

  get isButton() { return true }

  relayout() {
    var label = this.labelMorph,
        icon = this.iconMorph;
    if (!label) return;
    var padding = this.padding,
        padT = padding.top(),
        padB = padding.bottom(),
        padL = padding.left(),
        padR = padding.right(),
        minHeight = label.height + padT + padB,
        minWidth = label.width + padL + padR;
    if (minHeight > this.height) this.height = minHeight;
    if (minWidth > this.width) this.width = minWidth;
    let innerPadding = this.innerBounds().insetByRect(padding);
    label.center = innerPadding.center();
    if (!icon || !this.iconMorph.value) return this;
    switch (this.iconPosition) {
      case 'left':
        label.rightCenter = innerPadding.rightCenter();
        icon.rightCenter = label.leftCenter;
        return this;
      case 'right':
        label.leftCenter = innerPadding.leftCenter();
        icon.leftCenter = label.rightCenter;
        return this;
      case 'top':
        label.bottomCenter = innerPadding.bottomCenter();
        icon.bottomCenter = label.topCenter;
        return this;
      case 'bottom':
        label.topCenter = innerPadding.topCenter();
        icon.topCenter = label.bottomCenter;
        return this;
    }
    return this;
  }

  fit() {
    var padding = this.padding, label = this.labelMorph;
    label.fit();
    this.extent = padding.bottomLeft().addPt(padding.bottomRight()).addPt(label.extent);
    this.relayout();
    return this;
  }

  get isActive() {
    return this.activeMode == 'active'
  }

  activate() {
    let classes = arr.withoutAll(this.styleClasses, ['inactiveStyle', 'triggerStyle'])
    this.styleClasses = [...classes, 'activeStyle'];
  }

  deactivate() {
    let classes = arr.withoutAll(this.styleClasses, ['activeStyle', 'triggerStyle'])
    this.styleClasses = [...classes, 'inactiveStyle'];
  }

  perform() {
    let classes = arr.withoutAll(this.styleClasses, ['inactiveStyle', 'activeStyle'])
    this.styleClasses = [...classes, 'triggerStyle'];
  }

  enable() { this.activeMode = "active"; }

  disable() { this.activeMode = "inactive"; }

  trigger() {
    try {
      signal(this, "fire");
      typeof this.action == "function" && this.action();
    } catch (err) {
      var w = this.world();
      if (w) w.logError(err);
      else console.error(err);
    }
  }

  onMouseDown(evt) {
    if (this.isActive && this.innerBoundsContainsPoint(evt.positionIn(this)))
      this.activeMode = 'triggered'
  }

  onMouseUp(evt) {
    if (evt.isClickTarget(this) && this.activeMode == 'triggered') {
      this.activeMode = 'active';
      this.trigger();
    }
  }

  onHoverOut(evt) {
    // When leaving the button without mouse up, reset appearance
    if (this.activeMode == 'triggered' && evt.isClickTarget(this))
      this.activeMode = 'active';
  }

  onHoverIn(evt) {
    if (this.isActive && evt.isClickTarget(this))
      this.activeMode = 'triggered';
  }

  async interactivelyChangeLabel() {
    let newLabel = await this.world().prompt("edit button label", {
      input: this.labelMorph.textString,
      historyId: "lively.morphic-button-edit-label-hist"
    });
    if (typeof newLabel === "string")
      this.label = newLabel;
  }

  menuItems() {
    let items = super.menuItems();

    items.unshift({isDivider: true});
    items.unshift(["change label", () => this.interactivelyChangeLabel()]);

    return items;
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redex/LICENSE

export function create(config, logger, context) {

   function getEventType(service, status) {
      if (!service.status) { // no status i.e. app restarted
         return 'initial';
      } else if (service.status !== status) { // status changed
         return 'changed';
      } else { // status unchanged
         if (service.statusCount === config.debounceCount) {
            return 'debounced';
         } else if (service.statusCount < config.debounceCount) {
            return 'debouncing';
         } else {
            return 'unchanged';
         }
      }
   }

   function setServiceStatus(service, status, eventType, message) {
      service.message = message;
      if (eventType === 'initial') {
         assert(!service.status, 'initial');
         service.status = status;
         service.alertedStatus = service.status;
         service.statusCount = config.debounceCount;
         service.debounceCount = service.debounceCount || config.debounceCount;
      } else if (eventType === 'changed') {
         assert(service.status != status, 'status changed');
         service.statusCount = 0;
         service.status = status;
      } else {
         assert(service.status == status, 'status unchanged', service.statusCount);
         service.statusCount += 1;
      }
   }

   function isAlertableEvent(service, eventType) {
      if (eventType === 'debounced') {
         return true;
      } else if (eventType === 'changed' && service.debounceCount === 0) {
         return true;
      } else {
         return false;
      }
   }

   const those = {
      async pub() {
         return null;
      },
      async start() {
         logger.info('started');
      },
      async end() {
      },
      async processStatus(service, status, message) {
         logger.debug('processStatus', service.name, status, message);
         let eventType = getEventType(service, status);
         service.debug[eventType] = { status: status, time: new Date() };
         setServiceStatus(service, status, eventType, message);
         if (!isAlertableEvent(service, eventType)) {
            logger.debug('not alertable event:', service.name, eventType, service.status);
         } else if (service.alertedStatus === service.status) {
            logger.debug('equal alertedStatus:', service.name, eventType, service.status);
         } else {
            logger.info('send alert:', service.name, eventType, service.status, service.alertedStatus);
            service.alertedStatus = service.status;
            try {
               await context.components.reporter.sendAlert(service.status + ' ' + service.name, message);
            } catch (err) {
               logger.error(err, 'sendAlert', service.name, service.status);
            }
         }
      }
   };
   return those;
}
<commit_msg>update commit script<commit_after>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redex/LICENSE

export function create(config, logger, context) {

   function getEventType(service, status) {
      if (!service.status) { // no status i.e. app restarted
         return 'initial';
      } else if (service.status !== status) { // status changed
         return 'changed';
      } else { // status unchanged
         if (service.statusCount === config.debounceCount) {
            return 'debounced';
         } else if (service.statusCount < config.debounceCount) {
            return 'debouncing';
         } else {
            return 'unchanged';
         }
      }
   }

   function setServiceStatus(service, status, eventType, message) {
      service.message = message;
      if (eventType === 'initial') {
         assert(!service.status, 'initial');
         service.status = status;
         service.alertedStatus = service.status;
         service.statusCount = config.debounceCount;
         service.debounceCount = service.debounceCount || config.debounceCount;
      } else if (eventType === 'changed') {
         assert(service.status != status, 'status changed');
         service.statusCount = 0;
         service.status = status;
      } else {
         assert(service.status == status, 'status unchanged', service.statusCount);
         service.statusCount += 1;
      }
   }

   function isAlertableEvent(service, eventType) {
      if (eventType === 'debounced') {
         return true;
      } else if (eventType === 'changed' && service.debounceCount === 0) {
         return true;
      } else {
         return false;
      }
   }

   const those = {
      async pub() {
         return null;
      },
      async start() {
         logger.info('started');
      },
      async end() {
      },
      async processStatus(service, status, message) {
         logger.debug('processStatus', service.name, status, message);
         let eventType = getEventType(service, status);
         service.debug.events = service.debug.events || {};
         service.debug.events[eventType] = { status: status, time: new Date() };
         service.debug.status = service.debug.status || {};
         service.debug.status[status] = { time: new Date() };
         setServiceStatus(service, status, eventType, message);
         if (!isAlertableEvent(service, eventType)) {
            logger.debug('not alertable event:', service.name, eventType, service.status);
         } else if (service.alertedStatus === service.status) {
            logger.debug('equal alertedStatus:', service.name, eventType, service.status);
         } else {
            logger.info('send alert:', service.name, eventType, service.status, service.alertedStatus);
            service.alertedStatus = service.status;
            try {
               await context.components.reporter.sendAlert(service.status + ' ' + service.name, message);
            } catch (err) {
               logger.error(err, 'sendAlert', service.name, service.status);
            }
         }
      }
   };
   return those;
}
<|endoftext|>


<commit_before>const SteamUser = require('../index.js');

SteamUser.formatCurrency = function(amount, currency) {
	amount = amount.toFixed(2);

	if (!SteamUser.CurrencyData[currency]) {
		return amount;
	}

	var data = SteamUser.CurrencyData[currency];

	if (data.whole) {
		amount = amount.replace('.00', '');
	}

	if (data.commas) {
		amount = amount.replace('.', ',');
	}

	return (data.prepend || '') + amount + (data.append || '');
};

/**
 * Same as emit() except the second argument (the first provided to the callback function) is a SteamID and will be appended to the event name with a hash.
 * @private
 */
SteamUser.prototype._emitIdEvent = function() {
	this.emit.apply(this, arguments);
	arguments[0] += '#' + arguments[1].getSteamID64();
	this.emit.apply(this, arguments);
};
<commit_msg>Replace var with let in utility.js<commit_after>const SteamUser = require('../index.js');

SteamUser.formatCurrency = function(amount, currency) {
	amount = amount.toFixed(2);

	if (!SteamUser.CurrencyData[currency]) {
		return amount;
	}

	let data = SteamUser.CurrencyData[currency];

	if (data.whole) {
		amount = amount.replace('.00', '');
	}

	if (data.commas) {
		amount = amount.replace('.', ',');
	}

	return (data.prepend || '') + amount + (data.append || '');
};

/**
 * Same as emit() except the second argument (the first provided to the callback function) is a SteamID and will be appended to the event name with a hash.
 * @private
 */
SteamUser.prototype._emitIdEvent = function() {
	this.emit.apply(this, arguments);
	arguments[0] += '#' + arguments[1].getSteamID64();
	this.emit.apply(this, arguments);
};
<|endoftext|>