<commit_before>var util = require( "util" );
var EventEmitter = require( "events" ).EventEmitter;

module.exports = CreateHandler;

function CreateHandler ( req, res, next ) {

    EventEmitter.call( this );

    this.req = req;
    this.res = res;
    this.next = next;

    this.on( "valid", this.create );
    this.on( "invalid", this._validationFailed );
    this.on( "error", this._error );
    this.on( "created", this._respond );

}

util.inherits( CreateHandler, EventEmitter );

CreateHandler.prototype._validationFailed = function( errors ) {
    this.res.status( 400 ).json( errors );
};

CreateHandler.prototype._error = function( error ) {
    this.next( error );
};

CreateHandler.prototype._respond = function( data ) {
    this.res.status( 201 ).json( data );
};

CreateHandler.prototype.validate = function() {
    "If validation fails emit 'invalid' and pass errors";
    "If validation passes emit 'valid' and pass in data";
    throw new Error( "Not implemented" );
};

CreateHandler.prototype.create = function( data ) {
    "If an error happens emit 'error' and pass error";
    "If successful emit 'created' with data to send in response";
    throw new Error( "Not implemented" );
};
<commit_msg>Some little changes<commit_after>var util = require( "util" );
var EventEmitter = require( "events" ).EventEmitter;

module.exports = CreateHandler;

function CreateHandler ( req, res, next ) {

    EventEmitter.call( this );

    this.req = req;
    this.res = res;
    this.next = next;

    this.on( "valid", this.create );
    this.on( "invalid", this._validationFailed );
    this.on( "error", this._error );
    this.on( "created", this._respond );

}

util.inherits( CreateHandler, EventEmitter );

CreateHandler.prototype._validationFailed = function( errors ) {
    this.res.status( 400 ).json( errors );
};

CreateHandler.prototype._error = function( error ) {
    this.next( error );
};

CreateHandler.prototype._respond = function( data ) {
    this.res.status( 201 ).json( data );
};

CreateHandler.prototype.validate = function() {
    "If validation fails emit 'invalid' and pass errors";
    "If validation passes emit 'valid' and pass in data";
    throw new Error( "Not implemented" );
};

CreateHandler.prototype.create = function( data ) {
    "If an error happens emit 'error' and pass error";
    "If successful emit 'created' with data to send in response";
    throw new Error( "Not implemented" );
};

CreateHandler.prototype.handle = function() {
    this.validate();
};
<|endoftext|>


<commit_before>//This page handles all resources page content

//encodes any apostrophes in a string into an escape character
function encodeApos (input)
{

  var encoded = input.replace(/'/g, "&apos");
  return encoded;
}

//decodes any apostrophe escapes back into apostrophes
function decodeApos(input)
{
  var decoded= input.replace(/&apos/g, "'");
  return decoded;
}

const auth = firebase.auth();

//authentication state change
auth.onAuthStateChanged(function(firebaseUser) {
	if(firebaseUser) {
		console.log(firebaseUser);
	} else {
		console.log('not logged in');
	}
});

//defines and appends the submit button for the resource modal
function makeModal(input, id)
{
  firebase.auth().signInAnonymously()
 .catch(function(error) {
  console.log(error)
 });
var inputClean = decodeApos(input);

	$('#modalHeading').html("");
	$('#myModal').modal('toggle');
	$('#modalHeading').append("
"+ inputClean +"
");
	console.log(inputClean);

	printReviews(inputClean);

    $("#modalSubmit").append("<input onclick='makeReview(\"" + id + "\")' type='submit' class='btn btn-success btn-send' value='Submit'>");

};

//Loads all resources on page load
window.onload = onLoad();

function onLoad(){
  allResources();

};

//clears filters for new input
function clearResources(){
	document.getElementById('myCounty').value="";
	document.getElementById('myPhase').value="";
	document.getElementById('myService').value="";
	allResources();
};
//Filters all resources
function allResources() {

	//Clears table of resources
	var tableRef = document.getElementById('table_body');
	while ( tableRef.rows.length > 0 )
	{
	 tableRef.deleteRow(0);
	}

	//Pull resources from Firebase database
	rootref.child("Resources").on("child_added", function(snap) {

		var id = snap.key;
		var stringID = id.toString();
		var county = snap.child("county").val();
		var address = snap.child("address").val();
		var name = snap.child("name").val();
		var phone = snap.child("phone").val();
		var contact = snap.child("contact").val();
		var restriction = snap.child("restriction").val();
		var notes = snap.child("notes").val();
		var url = snap.child("url").val();
		var nameCoded = encodeApos(name);

		var aggRate = calcAggregateRating(nameCoded);
		console.log("" + nameCoded + " " + aggRate + " v0.04");

		//Creates table with resources pulled from firebase
		$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							  "	" + restriction + "	" + url +
							  "	" + notes + "
");
		});
};

//Filters resources based on user input
function filterResources() {
		//Clears table of resources
		var tableRef = document.getElementById('table_body');
		while ( tableRef.rows.length > 0 )
		{
		 tableRef.deleteRow(0);
		}

//Grabs user input for filters
var serviceVal = document.getElementById("myService").value;
var phaseVal = document .getElementById("myPhase").value;
var countyVal = document.getElementById("myCounty").value;

//Pull resources from Firebase database
rootref.child("Resources").on("child_added", function(snap) {

	var id = snap.key;
	var stringID = id.toString();
	var county = snap.child("county").val();
	var address = snap.child("address").val();
	var name = snap.child("name").val();
	var phone = snap.child("phone").val();
	var contact = snap.child("contact").val();
	var restriction = snap.child("restriction").val();
	var notes = snap.child("notes").val();
	var url = snap.child("url").val();
	var phase = snap.child("phase").val();
	var service = snap.child("service").val();
	var nameCoded = encodeApos(name);

//creates table based on user inputs
if(countyVal == county && phaseVal == phase && serviceVal == service) {
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == county && phaseVal == false && serviceVal == false){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == county && phaseVal == phase && serviceVal == false){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == county && phaseVal == false && serviceVal == service){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == false && phaseVal == phase && serviceVal == false){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == false && phaseVal == phase && serviceVal == service){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}

else if (countyVal == false && phaseVal == false && serviceVal == service){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}

});
};

function printReviews(input)
{
  var resourceRef = rootref.child("Resources");
  var inputClean = decodeApos(input);

  resourceRef.orderByChild("name").equalTo(inputClean).on("child_added", function(snap)
  {
    snap.child("reviews").forEach(function(shot)
    {

      var user = shot.child("user").val();
      var rating = shot.child("rating").val();
      var rBody = shot.child("text").val();
      if (rating != 0)
      {
	$("#modal_body").append("
" + user + "	" + rating + "

" + rBody+ "
");
      }
    });
  },
  function(error)
  {
    $("#modal_body").append("
Sorry! No one has reviewed this content! Be the first!
")
  });
}

function makeReview(input)
{
  var rBody = document.getElementById("rMaker");
  var score = document.getElementById("rater");
  var userID = document.getElementById("username");
  var inputClean = decodeApos(input);
	var ref;

  rootref.child("Resources").child(input).child("reviews").push().set(
{
	user: "" + userID.value + "",
	rating: "" + score.value + "",
	text: "" + rBody.value + ""

}
);
		window.location.reload()
    auth.signOut();
};

function calcAggregateRating(input)
{
  var i = 0;
  var j = 0;
  var inputClean = decodeApos(input);
  var temp = 0;
  rootref.child("Resources").orderByChild("name").equalTo(inputClean).once("child_added", function(snap)
  {
    snap.child("reviews").forEach(function(shot)
    {
      temp = shot.child("rating").val();
      temp = parseInt(temp);
      j = j + temp;
      i = i+1;

    });
  });

  if (i <= 1)
  {
    return 0;
  }
  else
  {
    var aggRating = j/(i-1);
  }

}
<commit_msg>Update firebase-resources.js<commit_after>//This page handles all resources page content

//encodes any apostrophes in a string into an escape character
function encodeApos (input)
{

  var encoded = input.replace(/'/g, "&apos");
  return encoded;
}

//decodes any apostrophe escapes back into apostrophes
function decodeApos(input)
{
  var decoded= input.replace(/&apos/g, "'");
  return decoded;
}

const auth = firebase.auth();

//authentication state change
auth.onAuthStateChanged(function(firebaseUser) {
	if(firebaseUser) {
		console.log(firebaseUser);
	} else {
		console.log('not logged in');
	}
});

//defines and appends the submit button for the resource modal
function makeModal(input, id)
{
  firebase.auth().signInAnonymously()
 .catch(function(error) {
  console.log(error)
 });
var inputClean = decodeApos(input);

	$('#modalHeading').html("");
	$('#myModal').modal('toggle');
	$('#modalHeading').append("
"+ inputClean +"
");
	console.log(inputClean);

	printReviews(inputClean);

    $("#modalSubmit").append("<input onclick='makeReview(\"" + id + "\")' type='submit' class='btn btn-success btn-send' value='Submit'>");

};

//Loads all resources on page load
window.onload = onLoad();

function onLoad(){
  allResources();

};

//clears filters for new input
function clearResources(){
	document.getElementById('myCounty').value="";
	document.getElementById('myPhase').value="";
	document.getElementById('myService').value="";
	allResources();
};
//Filters all resources
function allResources() {

	//Clears table of resources
	var tableRef = document.getElementById('table_body');
	while ( tableRef.rows.length > 0 )
	{
	 tableRef.deleteRow(0);
	}

	//Pull resources from Firebase database
	rootref.child("Resources").on("child_added", function(snap) {

		var id = snap.key;
		var stringID = id.toString();
		var county = snap.child("county").val();
		var address = snap.child("address").val();
		var name = snap.child("name").val();
		var phone = snap.child("phone").val();
		var contact = snap.child("contact").val();
		var restriction = snap.child("restriction").val();
		var notes = snap.child("notes").val();
		var url = snap.child("url").val();
		var nameCoded = encodeApos(name);

		var aggRate = calcAggregateRating(nameCoded);
		console.log("" + nameCoded + " " + aggRate + " v0.04");

		//Creates table with resources pulled from firebase
		$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							  "	" + restriction + "	" + url +
							  "	" + notes + "
");
		});
};

//Filters resources based on user input
function filterResources() {
		//Clears table of resources
		var tableRef = document.getElementById('table_body');
		while ( tableRef.rows.length > 0 )
		{
		 tableRef.deleteRow(0);
		}

//Grabs user input for filters
var serviceVal = document.getElementById("myService").value;
var phaseVal = document .getElementById("myPhase").value;
var countyVal = document.getElementById("myCounty").value;

//Pull resources from Firebase database
rootref.child("Resources").on("child_added", function(snap) {

	var id = snap.key;
	var stringID = id.toString();
	var county = snap.child("county").val();
	var address = snap.child("address").val();
	var name = snap.child("name").val();
	var phone = snap.child("phone").val();
	var contact = snap.child("contact").val();
	var restriction = snap.child("restriction").val();
	var notes = snap.child("notes").val();
	var url = snap.child("url").val();
	var phase = snap.child("phase").val();
	var service = snap.child("service").val();
	var nameCoded = encodeApos(name);

//creates table based on user inputs
if(countyVal == county && phaseVal == phase && serviceVal == service) {
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == county && phaseVal == false && serviceVal == false){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == county && phaseVal == phase && serviceVal == false){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == county && phaseVal == false && serviceVal == service){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == false && phaseVal == phase && serviceVal == false){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}
else if (countyVal == false && phaseVal == phase && serviceVal == service){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}

else if (countyVal == false && phaseVal == false && serviceVal == service){
	$("#table_body").append("
"+ county +"	" + name + "	"+ address +"	"+ phone +"	" + contact +
							"	" + restriction + "	" + url +
							"	" + notes + "
");
}

});
};

function printReviews(input)
{
  var resourceRef = rootref.child("Resources");
  var inputClean = decodeApos(input);

  resourceRef.orderByChild("name").equalTo(inputClean).on("child_added", function(snap)
  {
    snap.child("reviews").forEach(function(shot)
    {

      var user = shot.child("user").val();
      var rating = shot.child("rating").val();
      var rBody = shot.child("text").val();
      if (rating != 0)
      {
	$("#modal_body").append("
" + user + "	" + rating + "

" + rBody+ "
");
      }
    });
  },
  function(error)
  {
    $("#modal_body").append("
Sorry! No one has reviewed this content! Be the first!
")
  });
}

function makeReview(input)
{
  var rBody = document.getElementById("rMaker");
  var score = document.getElementById("rater");
  var userID = document.getElementById("username");
  var inputClean = decodeApos(input);
	var ref;

  rootref.child("Resources").child(input).child("reviews").push().set(
{
	user: "" + userID.value + "",
	rating: "" + score.value + "",
	text: "" + rBody.value + ""

}
);
		window.location.reload()
    auth.signOut();
};

function calcAggregateRating(input)
{
  var i = 0;
  var j = 0;
  var inputClean = decodeApos(input);
  var temp = 0;
  rootref.child("Resources").orderByChild("name").equalTo(inputClean).once("child_added", function(snap)
  {
    snap.child("reviews").forEach(function(shot)
    {
      temp = shot.child("rating").val();
      temp = parseInt(temp);
      j = j + temp;
      i = i+1;

    });
  });

  if (i <= 1)
  {
    return 0;
  }
  else
  {
    var aggRating = j/(i-1);
    return aggRating;
  }

}
<|endoftext|>


<commit_before>/*
 * https://github.com/5orenso
 *
 * Copyright (c) 2014 Øistein Sørensen
 * Licensed under the MIT license.
 */
'use strict';
/**
 * @fileOverview Loading config, mouting routes and starting http server.
 * See {@tutorial getting-started}
 * @name The main server.
 */
var path = require('path'),
    commander = require('commander'),
    express = require('express'),
    bodyParser = require('body-parser'),
    compression = require('compression'),
    appPath = path.normalize(__dirname + '/../');

commander
    .option('-c, --config <file>', 'configuration file path', './config/config.js')
    .parse(process.argv);

var ConfigLoader = require(appPath + 'lib/config-loader');
var configLoader = new ConfigLoader();
var config = configLoader.load(commander.config);

if (config) {
    var Logger = require(appPath + 'lib/logger');
    var logger = new Logger({
        logLevel: config.logLevel
    });

    var app = express();
    app.use(bodyParser.json());
    app.use(compression({
        threshold: 512
    }));

    var webRouter = require('./routes/web');
    webRouter.setConfig(config, {});

    var apiRouter = require('./routes/api');
    apiRouter.setConfig(config, {});

    // Routes
    // * Add more routes here
    app.use('/api/', apiRouter);
    app.use('/', webRouter);

    // Start the server -------------------------------
    var server = app.listen(config.app.port, function () {
        var host = server.address().address;
        var port = server.address().port;
        logger.log('info', 'Something happens at http://' + host + ':' + port + '/');
    });
}
<commit_msg>Moved /ip to own router to show this can be done.<commit_after>/*
 * https://github.com/5orenso
 *
 * Copyright (c) 2014 Øistein Sørensen
 * Licensed under the MIT license.
 */
'use strict';
/**
 * @fileOverview Loading config, mouting routes and starting http server.
 * See {@tutorial getting-started}
 * @name The main server.
 */
var path = require('path'),
    commander = require('commander'),
    express = require('express'),
    bodyParser = require('body-parser'),
    compression = require('compression'),
    appPath = path.normalize(__dirname + '/../');

commander
    .option('-c, --config <file>', 'configuration file path', './config/config.js')
    .parse(process.argv);

var ConfigLoader = require(appPath + 'lib/config-loader');
var configLoader = new ConfigLoader();
var config = configLoader.load(commander.config);

if (config) {
    var Logger = require(appPath + 'lib/logger');
    var logger = new Logger({
        logLevel: config.logLevel
    });

    var app = express();
    app.use(bodyParser.json());
    app.use(compression({
        threshold: 512
    }));

    var apiRouter = require('./routes/api');
    apiRouter.setConfig(config, {});

    var ipRouter = require('./routes/ip');
    ipRouter.setConfig(config, {});

    var webRouter = require('./routes/web');
    webRouter.setConfig(config, {});

    // Routes
    // * Add more routes here
    app.use('/api/', apiRouter);
    app.use('/ip/', ipRouter);
    app.use('/', webRouter);

    // Start the server -------------------------------
    var server = app.listen(config.app.port, function () {
        var host = server.address().address;
        var port = server.address().port;
        logger.log('info', 'Something happens at http://' + host + ':' + port + '/');
    });
}
<|endoftext|>


<commit_before><<<<<<< HEAD
const { OUTPUT } = require('../const');
=======

>>>>>>> upstream/master
const Bot = require('slackbots');

class SlackBot extends Bot {
  constructor({ token, name }) {
    if (!token || !name) {
      throw Error('please set token and name of bot');
    }
    super({ token, name });

    this.awardPointsCallback = this.awardPointsCallback.bind(this);
    this.announcePlainString = this.announcePlainString.bind(this);
  }

  async awardPointsCallback(originalMessage, message) {
    const channel = await this.getChannelById(originalMessage.channel);
    await this.postMessageToChannel(channel.name, message, { as_user: true });
  }

  async announcePlainString(originalMessage, message) {
    const channel = await this.getChannelById(originalMessage.channel);

    await this.postMessageToChannel(channel.name, message, { as_user: true, link_names: 1 });
  }

  async getUserList() {
    const users = await this.getUsers();

    return users;
  }

  getName() {
    return this.name;
  }
}

module.exports = SlackBot;
<commit_msg>Fixed bug when merging<commit_after>const Bot = require('slackbots');

class SlackBot extends Bot {
  constructor({ token, name }) {
    if (!token || !name) {
      throw Error('please set token and name of bot');
    }
    super({ token, name });

    this.awardPointsCallback = this.awardPointsCallback.bind(this);
    this.announcePlainString = this.announcePlainString.bind(this);
  }

  async awardPointsCallback(originalMessage, message) {
    const channel = await this.getChannelById(originalMessage.channel);
    await this.postMessageToChannel(channel.name, message, { as_user: true });
  }

  async announcePlainString(originalMessage, message) {
    const channel = await this.getChannelById(originalMessage.channel);

    await this.postMessageToChannel(channel.name, message, { as_user: true, link_names: 1 });
  }

  async getUserList() {
    const users = await this.getUsers();

    return users;
  }

  getName() {
    return this.name;
  }
}

module.exports = SlackBot;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'DetailView',

  extends: 'foam.u2.View',

  requires: [
    'Property',
    'foam.u2.DetailPropertyView'
  ],

  exports: [ 'data$', 'data' ],

  properties: [
    {
      name: 'data',
      postSet: function(_, data) {
        if ( data.model_ !== this.model ) this.model = data.model_;
      }
    },
    {
      name: 'model',
      postSet: function(oldModel, model) {
        console.assert(Model.isInstance(model), 'Invalid model specified for ' + this.name_);
        if ( oldModel !== model )
          this.properties = model.getRuntimeProperties().filter(function(p) { return ! p.hidden; });
        if ( ( ! oldModel && ! this.hasOwnProperty('title') ) || this.title === oldModel.label ) this.title = model.label;
      }
    },
    {
      type: 'Boolean',
      name: 'showActions'
    },
    {
      name: 'properties'
    },
    {
      name: 'title',
      documentation: function() {/*

The display title for the $$DOC{ref:'foam.ui.View'}.

      */}
    },
    [ 'nodeName', 'div' ]
  ],

  templates: [
    function CSS() {/*
      .foam-u2-DetailView {
        background: #fdfdfd;
        border: solid 1px #dddddd;
        box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
        display: inline-block;
        margin: 5px;
      }
      .foam-u2-DetailView table {
        padding-bottom: 2px;
      }
      .foam-u2-DetailView-title {
        color: #333;
        float: left;
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 8px;
        padding: 2px;
      }
      .foam-u2-DetailView input {
        border: solid 1px #aacfe4;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        padding: 4px 2px;
      }
      .foam-u2-DetailView textarea {
        border: solid 1px #aacfe4;
        float: left;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        overflow: auto;
        padding: 4px 2px;
        width: 98%;
      }
      .foam-u2-DetailView select {
        border: solid 1px #aacfe4;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        padding: 4px 2px;
      }
    */}
  ],

  methods: [
    function init() {
      this.SUPER();

      this.Y.registerModel(this.DetailPropertyView, 'foam.u2.PropertyView');

      this.add(function(model, properties) {
        if ( ! model ) return 'Set model or data.';

        return this.actionBorder(
          this.E('table').cls('foam-u2-DetailView').
            start('tr').
              start('td').cls('foam-u2-DetailView-title').attrs({colspan: 2}).
                add(this.title$).
              end().
            end().
            add(properties));
      }.bind(this).on$(this.Y, this.model$, this.properties$));
    },
    function actionBorder(e) {
      if ( ! this.showActions || ! this.model.actions.length ) return e;

      return this.Y.E().add(e).start('div').add(this.model.actions).end();
    },
    function elementForFeature(fName) {
      var f = this.model_.getFeature(fName) || this.X.data.model_.getFeature(fName);
      return f ? f.toE(this.Y) : this.E('Unknown feature: ' + fName).style({color: 'red'});
    }
  ]
});
<commit_msg>U2: Improved and modernized DetailView CSS.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'DetailView',

  extends: 'foam.u2.View',

  requires: [
    'Property',
    'foam.u2.DetailPropertyView'
  ],

  exports: [ 'data$', 'data' ],

  properties: [
    {
      name: 'data',
      postSet: function(_, data) {
        if ( data.model_ !== this.model ) this.model = data.model_;
      }
    },
    {
      name: 'model',
      postSet: function(oldModel, model) {
        console.assert(Model.isInstance(model), 'Invalid model specified for ' + this.name_);
        if ( oldModel !== model )
          this.properties = model.getRuntimeProperties().filter(function(p) { return ! p.hidden; });
        if ( ( ! oldModel && ! this.hasOwnProperty('title') ) || this.title === oldModel.label ) this.title = model.label;
      }
    },
    {
      type: 'Boolean',
      name: 'showActions'
    },
    {
      name: 'properties'
    },
    {
      name: 'title',
      documentation: function() {/*

The display title for the $$DOC{ref:'foam.ui.View'}.

      */}
    },
    [ 'nodeName', 'div' ]
  ],

  templates: [
    function CSS() {/*
      $ {
        background: #fdfdfd;
        border: solid 1px #dddddd;
        box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
        display: inline-block;
        margin: 3px;
        padding: 3px;
      }
      $ table {
        padding-bottom: 2px;
      }
      $-title {
        color: #333;
        float: left;
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 8px;
        padding: 2px;
      }
      $ input {
        border: solid 1px #aacfe4;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        padding: 4px 2px;
      }
      $ textarea {
        border: solid 1px #aacfe4;
        float: left;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        overflow: auto;
        padding: 4px 2px;
        width: 98%;
      }
      $ select {
        border: solid 1px #aacfe4;
        font-size: 10px;
        margin: 2px 0 0px 2px;
        padding: 4px 2px;
      }
    */}
  ],

  methods: [
    function init() {
      this.SUPER();

      this.Y.registerModel(this.DetailPropertyView, 'foam.u2.PropertyView');

      this.add(function(model, properties) {
        if ( ! model ) return 'Set model or data.';

        return this.actionBorder(
          this.E('table').cls(this.myCls()).
            start('tr').
              start('td').cls(this.myCls('title')).attrs({colspan: 2}).
                add(this.title$).
              end().
            end().
            add(properties));
      }.bind(this).on$(this.Y, this.model$, this.properties$));
    },
    function actionBorder(e) {
      if ( ! this.showActions || ! this.model.actions.length ) return e;

      return this.Y.E().add(e).start('div').add(this.model.actions).end();
    },
    function elementForFeature(fName) {
      var f = this.model_.getFeature(fName) || this.X.data.model_.getFeature(fName);
      return f ? f.toE(this.Y) : this.E('Unknown feature: ' + fName).style({color: 'red'});
    }
  ]
});
<|endoftext|>


<commit_before>import express from 'express'
import path from 'path'
import {mergeAll} from 'ramda'
import {match} from 'react-router'
import compression from 'compression'
import appConfig from './config'
import crypto from 'crypto'
import Promise from 'bluebird'
import bodyParser from 'body-parser'
import DB from './db'
import CourseRoutes from './routes/course'
import ApiRoutes from './routes/api'
import errorLoggerRoutes from './routes/errorLogger'
import {appState} from './store/lukkariStore'
import {Routes} from './pages/routes'
import {renderFullPage} from './pages/initPage'
import Logger from './logger'

const fs = Promise.promisifyAll(require('fs'))

process.on('unhandledRejection', (reason, p) => {
  Logger.error('Unhandled Rejection at: Promise', p, 'reason:', reason)
})

const server = express()

server.use(compression({threshold: 512}))
server.use(bodyParser.json())
server.use(bodyParser.urlencoded({extended: true}))
server.disable('x-powered-by')
server.use('/course', CourseRoutes)
server.use('/api', ApiRoutes)

server.use('/favicon.png', express.static(`${__dirname}/img/favicon.png`))
server.use('/github.png', express.static(`${__dirname}/img/github.png`))
server.use('/spinner.gif', express.static(`${__dirname}/img/spinner.gif`))

const cssFilePath = path.resolve(`${__dirname}/../.generated/styles.css`)
const bundleJsFilePath = path.resolve(`${__dirname}/../.generated/bundle.js`)

if (process.env.NODE_ENV !== 'production') {
  server.use('/test/', express.static(path.resolve(`${__dirname}'/../test`)))
  server.use('/node_modules/', express.static(path.resolve(`${__dirname}'/../node_modules`)))
}

const checksumPromise = filePath =>
  fs
    .readFileAsync(filePath)
    .then(fileContent => crypto.createHash('md5')
      .update(fileContent)
      .digest('hex'))

const serveStaticResource = (filePath) => (req, res, next) =>
  checksumPromise(filePath)
    .then(checksum => {
      if (req.params.checksum === checksum) {
        const twoHoursInSeconds = 60 * 60 * 2
        res.setHeader('Cache-Control', `public, max-age=${twoHoursInSeconds}`)
        res.setHeader('ETag', checksum)
        res.sendFile(filePath)
      } else {
        res.status(404).send()
      }
    })
    .catch(next)

server.get('/static/:checksum/styles.css', serveStaticResource(cssFilePath))
server.get('/static/:checksum/bundle.js', serveStaticResource(bundleJsFilePath))

const buildInitialState = (displayName) => {
  switch (displayName) {
    case 'LukkariPage':
      return {
        selectedCourses: [],
        searchResults: [],
        currentDate: new Date(),
        isModalOpen: false,
        selectedIndex: -1,
        waitingAjax: false,
        departmentCourses: [],
        department: 'TITE'
      }
    case 'CatalogPage':
      return {
        selectedCourses: [],
        searchResults: [],
        currentDate: new Date(),
        isModalOpen: false,
        selectedIndex: -1,
        waitingAjax: false,
        departmentCourses: [],
        department: 'TITE'
      }
    case 'NotFoundPage':
      return {}
    default:
      return null
  }
}

const getNeedFunctionParams = (displayName, params, queryParams) => {
  switch (displayName) {
    case 'LukkariPage':
      return {
        courses: queryParams.courses
      }
    case 'CatalogPage':
      return {
        department: queryParams.department ? queryParams.department.toLowerCase() : 'tite'
      }
    default:
      return null
  }
}

const fetchComponentData = (components, pathParams, queryParams) => {
  const needs = components.reduce((prev, current) => {
    return current ? (current.needs || []).concat(prev) : prev
  }, [])
  const promises = needs.reduce((prev, currNeed) => {
    const param = getNeedFunctionParams(components[1].displayName, pathParams, queryParams)
    if (param) {
      const action = currNeed(param)
      appState.dispatch(action)
      return prev.concat(action.promise)
    } else {
      return prev
    }
  }, [])
  return Promise.all(promises)
}

server.get('/.well-known/acme-challenge/:content', (req, res) => res.send(appConfig.letsEncryptReponse))
server.use('/errors', errorLoggerRoutes)

server.get('*', (req, res) => {
  const urlPath = req.url
  match({routes: Routes, location: urlPath}, (error, redirectLocation, renderProps) => {
    if (error) {
      return res.status(500).send('Server error')
    } else if (redirectLocation) {
      return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
    } else if (renderProps === null) {
      return res.status(404).send('Not found')
    } else {
      return Promise
        .all([checksumPromise(cssFilePath), checksumPromise(bundleJsFilePath), fetchComponentData(renderProps.components, renderProps.params, renderProps.location.query)])
        .then(([cssChecksum, bundleJsChecksum]) => {
          const initialState = mergeAll([appState.currentState, buildInitialState(renderProps.components[1].displayName)])
          return Promise.resolve(renderFullPage(
            initialState,
            {cssChecksum, bundleJsChecksum},
            renderProps
          ))
            .then((page) => res.send(page))
        })
        .catch((err) => {
          res.status(500).send('Server error')
          Logger.error('Server error', err.stack)
        })
    }
  })
})

export const start = (port) => {
  const env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development'
  const reportPages = () => {
    Logger.info(`Page available at http://localhost:${port} in ${env}`)
  }
  return DB.isTableInitialized('course')
    .then((exists) => exists ? null : DB.initializeDb())
    .then(() => new Promise((resolve) => {
      server.listen(port, resolve)
    })).then(reportPages)
}
<commit_msg>Refactor initialState building<commit_after>import express from 'express'
import path from 'path'
import {mergeAll} from 'ramda'
import {match} from 'react-router'
import compression from 'compression'
import appConfig from './config'
import crypto from 'crypto'
import Promise from 'bluebird'
import bodyParser from 'body-parser'
import DB from './db'
import CourseRoutes from './routes/course'
import ApiRoutes from './routes/api'
import errorLoggerRoutes from './routes/errorLogger'
import {appState} from './store/lukkariStore'
import {Routes} from './pages/routes'
import {renderFullPage} from './pages/initPage'
import Logger from './logger'

const fs = Promise.promisifyAll(require('fs'))

process.on('unhandledRejection', (reason, p) => {
  Logger.error('Unhandled Rejection at: Promise', p, 'reason:', reason)
})

const server = express()

server.use(compression({threshold: 512}))
server.use(bodyParser.json())
server.use(bodyParser.urlencoded({extended: true}))
server.disable('x-powered-by')
server.use('/course', CourseRoutes)
server.use('/api', ApiRoutes)

server.use('/favicon.png', express.static(`${__dirname}/img/favicon.png`))
server.use('/github.png', express.static(`${__dirname}/img/github.png`))
server.use('/spinner.gif', express.static(`${__dirname}/img/spinner.gif`))

const cssFilePath = path.resolve(`${__dirname}/../.generated/styles.css`)
const bundleJsFilePath = path.resolve(`${__dirname}/../.generated/bundle.js`)

if (process.env.NODE_ENV !== 'production') {
  server.use('/test/', express.static(path.resolve(`${__dirname}'/../test`)))
  server.use('/node_modules/', express.static(path.resolve(`${__dirname}'/../node_modules`)))
}

const checksumPromise = filePath =>
  fs
    .readFileAsync(filePath)
    .then(fileContent => crypto.createHash('md5')
      .update(fileContent)
      .digest('hex'))

const serveStaticResource = (filePath) => (req, res, next) =>
  checksumPromise(filePath)
    .then(checksum => {
      if (req.params.checksum === checksum) {
        const twoHoursInSeconds = 60 * 60 * 2
        res.setHeader('Cache-Control', `public, max-age=${twoHoursInSeconds}`)
        res.setHeader('ETag', checksum)
        res.sendFile(filePath)
      } else {
        res.status(404).send()
      }
    })
    .catch(next)

server.get('/static/:checksum/styles.css', serveStaticResource(cssFilePath))
server.get('/static/:checksum/bundle.js', serveStaticResource(bundleJsFilePath))

const buildInitialState = (displayName) => {
  const pageState = () => {
    switch (displayName) {
      case 'LukkariPage':
        return {}
      case 'CatalogPage':
        return {}
      case 'NotFoundPage':
        return {}
      default:
        return null
    }
  }

  return {
    ...pageState, ...{
      selectedCourses: [],
      searchResults: [],
      currentDate: new Date(),
      isModalOpen: false,
      selectedIndex: -1,
      waitingAjax: false,
      departmentCourses: [],
      department: 'TITE'
    }
  }
}

const getNeedFunctionParams = (displayName, params, queryParams) => {
  switch (displayName) {
    case 'LukkariPage':
      return {
        courses: queryParams.courses
      }
    case 'CatalogPage':
      return {
        department: queryParams.department ? queryParams.department.toLowerCase() : 'tite'
      }
    default:
      return null
  }
}

const fetchComponentData = (components, pathParams, queryParams) => {
  const needs = components.reduce((prev, current) => {
    return current ? (current.needs || []).concat(prev) : prev
  }, [])
  const promises = needs.reduce((prev, currNeed) => {
    const param = getNeedFunctionParams(components[1].displayName, pathParams, queryParams)
    if (param) {
      const action = currNeed(param)
      appState.dispatch(action)
      return prev.concat(action.promise)
    } else {
      return prev
    }
  }, [])
  return Promise.all(promises)
}

server.get('/.well-known/acme-challenge/:content', (req, res) => res.send(appConfig.letsEncryptReponse))
server.use('/errors', errorLoggerRoutes)

server.get('*', (req, res) => {
  const urlPath = req.url
  match({routes: Routes, location: urlPath}, (error, redirectLocation, renderProps) => {
    if (error) {
      return res.status(500).send('Server error')
    } else if (redirectLocation) {
      return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
    } else if (renderProps === null) {
      return res.status(404).send('Not found')
    } else {
      return Promise
        .all([checksumPromise(cssFilePath), checksumPromise(bundleJsFilePath), fetchComponentData(renderProps.components, renderProps.params, renderProps.location.query)])
        .then(([cssChecksum, bundleJsChecksum]) => {
          const initialState = mergeAll([appState.currentState, buildInitialState(renderProps.components[1].displayName)])
          return Promise.resolve(renderFullPage(
            initialState,
            {cssChecksum, bundleJsChecksum},
            renderProps
          ))
            .then((page) => res.send(page))
        })
        .catch((err) => {
          res.status(500).send('Server error')
          Logger.error('Server error', err.stack)
        })
    }
  })
})

export const start = (port) => {
  const env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development'
  const reportPages = () => {
    Logger.info(`Page available at http://localhost:${port} in ${env}`)
  }
  return DB.isTableInitialized('course')
    .then((exists) => exists ? null : DB.initializeDb())
    .then(() => new Promise((resolve) => {
      server.listen(port, resolve)
    })).then(reportPages)
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Request helper
 */
module.exports = {
  isTwilio: function isTwilio(req) {
    return !!req.body.MessageSid;
  },
  isSlack: function isSlack(req) {
    return !!req.body.slackId;
  },
  isFacebook: function isFacebook(req) {
    return !!req.body.facebookId;
  },
  isFront: function isFront(req) {
    // TODO: Should be in a config constant
    return !!req.get('x-front-signature');
  },
  isCustomerIo: function isCustomerIo(req) {
    const platform = req.query.platform || req.body.platform;
    // TODO: Should be in a config constant
    return platform === 'customerio';
  },
};
<commit_msg>added request helper function to check if this request is a Twilio statusCallback with valid smsStatus (delivered)<commit_after>'use strict';

/**
 * Request helper
 */
module.exports = {
  isTwilio: function isTwilio(req) {
    return !!req.body.MessageSid;
  },
  isSlack: function isSlack(req) {
    return !!req.body.slackId;
  },
  isFacebook: function isFacebook(req) {
    return !!req.body.facebookId;
  },
  isFront: function isFront(req) {
    // TODO: Should be in a config constant
    return !!req.get('x-front-signature');
  },
  isCustomerIo: function isCustomerIo(req) {
    const platform = req.query.platform || req.body.platform;
    // TODO: Should be in a config constant
    return platform === 'customerio';
  },
  isStatusCallback: function isStatusCallback(req) {
    const messageStatus = req.body.MessageStatus;

    /**
     * Twilio has received confirmation of message delivery from the upstream carrier,
     * and, where available, the destination handset.
     * @see https://www.twilio.com/docs/api/messaging/message#message-status-values
     */
    return messageStatus === 'delivered';
  },
};
<|endoftext|>


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

Object.defineProperty(exports, '__esModule', { value: true });

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var Server = _interopDefault(require('upnpserver'));

let serverObj = null;

function startServer (directoriesArray, callback){
    let msg = "";
    if (serverObj !== null) {
        stopServer().then((msg) => {
            callback(null, msg);
        }).catch((msg) => {
            callback(null, msg);
        });
        return ;
    }
    directoriesArray = directoriesArray.filter((elem) => {
        return {
            path: elem.path,
            mountPoint: '/' + elem.name,
        }
    });
    console.log(directoriesArray);
    serverObj = new Server({ "name": "DLNA-Broadcaster" }, directoriesArray);

    serverObj.start();

    msg = "Server successfully started";
    callback(null, msg);
}

function stopServer (){
    return new Promise((fullfill, reject) => {
        if (serverObj === null) {
            fullfill("Server not started");
            return;
        }

        serverObj.stop((err, stopped) => {
            if (stopped) {
                serverObj = null;
                fullfill("Server successfully stopped");
            } else {
                reject("Unable to stop the server");
            }
        });

    });
}

exports.startServer = startServer;
exports.stopServer = stopServer;

}());
//# sourceMappingURL=server.js.map<commit_msg>Delete server.js<commit_after><|endoftext|>


<commit_before>var Raspi = require("raspi-io");
var five = require("johnny-five");
var pitft = require("pitft");
var sleep = require('sleep');
//var pitftTouch = require('pitft-touch');

var WriteVolumeAddress=0x4B;
var ReadStrokeAddress=08;
var volumeLevel=31;
var isStarted=false;

var fb = pitft("/dev/fb1"); // Returns a framebuffer in direct mode.  See the clock.js example for double buffering mode

var xMax = fb.size().width;
console.log(xMax);
var yMax = fb.size().height;
console.log(yMax);

// Clear the screen buffer
fb.clear();
fb.color(1, 1, 1); // Set the color to whit
fb.font("fantasy", 12); // Use the "fantasy" font with size 12

fb.text(0,20,"This will never work.",false);

console.log("Starting Board");

var board = new five.Board({
  io: new Raspi()
});

/*
var touch = new DSTouch({
  address: UU
});
*/

board.on("ready", function() {

  //prepare buttons from TFT
  var buttonOne = new five.Button(0);
  var buttonTwo = new five.Button(3);
  var buttonThree = new five.Button(4);
  var buttonFour = new five.Button(2);

  //prepare imu
  var imu = new five.IMU({
    controller: "MPU6050"
  });

  //prepare gps
  var gps = new five.GPS({
    breakout: "ADAFRUIT_ULTIMATE_GPS",
    pins: ['P1-8', 'P1-10']
  });

  //create a function that reads the Volume.
  function readVolume(){
    return defaultVolumeLevel;
  }

  //create a cunction that writes Volume
  function writeVolume(address,volume){
    return board.io.i2cWrite(address,volume)
    //sample writeVolume(WriteVolumeAddress,defaultVolumeLevel);
  }

  //create a function that read's stroke rate.
  function readStrokeRate(address){
    return board.io.i2cRead(address,4,true);
    //sample readStrokeRate(ReadStrokeAddress);
  }

  //default volume
  writeVolume(WriteVolumeAddress,volumeLevel);

  buttonOne.on("press", function() {
    writeVolume(WriteVolumeAddress,VolumeLevel+1);
    VolumeLevel = VolumeLevel+1
    console.log( "Increased Volume" );
  });

  buttonTwo.on("press", function() {
    writeVolume(WriteVolumeAddress,VolumeLevel-1);
    VolumeLevel = VolumeLevel-1
    console.log( "Decreased Volume" );
  });

  buttonThree.on("press", function() {
    if (isStarted == false){
      //startSomething();
      console.log("Started");
    }else{
      //stopSomething();
      console.log("Stopped");
    }
  });

  buttonThree.on("hold", function() {
    //resetTimer();
    isStarted = false;
    console.log( "Reset" );
  });

  buttonFour.on("press", function() {
    console.log( "IDK fam" );
    //doSumting();
  });

  /*
  touch.on("change", function() {
    console.log(this.x, this.y);
  });
  */

  gps.on("change", function() {
    console.log("GPS Data");
    console.log("  Speed   : ", gps.speed);
    console.log("  Course  : ", gps.course);
    console.log("  latitude   : ", gps.latitude);
    console.log("  longitude  : ", gps.longitude);
    console.log("  altitude   : ", gps.altitude);
    console.log("MPU6050 Roll Data");
    console.log("  pitch   : ", imu.gyro.pitch);
    console.log("MPU6050 Starting Acceleration");
    console.log("  Acceleration   : ", imu.accelerometer.acceleration);
    console.log("MPU6050 Temp");
    console.log("  fahrenheit   : ", imu.thermometer.fahrenheit);
    console.log("Volume");
    console.log("  Volume   : ",volumeLevel);
    console.log("Stroke Rate");
    console.log("  Stroke Rate   : ",readStrokeRate(ReadStrokeAddress));
    console.log("--------------------------------------");
  });
});
<commit_msg>added bad touch.<commit_after>var Raspi = require("raspi-io");
var five = require("johnny-five");
var pitft = require("pitft");
var sleep = require('sleep');
//var pitftTouch = require('pitft-touch');

var WriteVolumeAddress=0x4B;
var ReadStrokeAddress=08;
var volumeLevel=31;
var isStarted=false;

var fb = pitft("/dev/fb1"); // Returns a framebuffer in direct mode.  See the clock.js example for double buffering mode

var touchscreen = require("pitft-touch");

var touchCount = 0;

touchscreen("/dev/input/touchscreen", function(err, data) {
    if (err) {
        throw err;
    }

    // Stop after 10 touches
    if (touchCount++ == 10) {
        data.stop = true;
    }

    console.log(data);
});

var xMax = fb.size().width;
console.log(xMax);
var yMax = fb.size().height;
console.log(yMax);

// Clear the screen buffer
fb.clear();
fb.color(1, 1, 1); // Set the color to whit
fb.font("fantasy", 12); // Use the "fantasy" font with size 12

fb.text(0,20,"This will never work.",false);

console.log("Starting Board");

var board = new five.Board({
  io: new Raspi()
});

/*
var touch = new DSTouch({
  address: UU
});
*/

board.on("ready", function() {

  //prepare buttons from TFT
  var buttonOne = new five.Button(0);
  var buttonTwo = new five.Button(3);
  var buttonThree = new five.Button(4);
  var buttonFour = new five.Button(2);

  //prepare imu
  var imu = new five.IMU({
    controller: "MPU6050"
  });

  //prepare gps
  var gps = new five.GPS({
    breakout: "ADAFRUIT_ULTIMATE_GPS",
    pins: ['P1-8', 'P1-10']
  });

  //create a function that reads the Volume.
  function readVolume(){
    return defaultVolumeLevel;
  }

  //create a cunction that writes Volume
  function writeVolume(address,volume){
    return board.io.i2cWrite(address,volume)
    //sample writeVolume(WriteVolumeAddress,defaultVolumeLevel);
  }

  //create a function that read's stroke rate.
  function readStrokeRate(address){
    return board.io.i2cRead(address,4,true);
    //sample readStrokeRate(ReadStrokeAddress);
  }

  //default volume
  writeVolume(WriteVolumeAddress,volumeLevel);

  buttonOne.on("press", function() {
    writeVolume(WriteVolumeAddress,VolumeLevel+1);
    VolumeLevel = VolumeLevel+1
    console.log( "Increased Volume" );
  });

  buttonTwo.on("press", function() {
    writeVolume(WriteVolumeAddress,VolumeLevel-1);
    VolumeLevel = VolumeLevel-1
    console.log( "Decreased Volume" );
  });

  buttonThree.on("press", function() {
    if (isStarted == false){
      //startSomething();
      console.log("Started");
    }else{
      //stopSomething();
      console.log("Stopped");
    }
  });

  buttonThree.on("hold", function() {
    //resetTimer();
    isStarted = false;
    console.log( "Reset" );
  });

  buttonFour.on("press", function() {
    console.log( "IDK fam" );
    //doSumting();
  });

  /*
  touch.on("change", function() {
    console.log(this.x, this.y);
  });
  */

  gps.on("change", function() {
    console.log("GPS Data");
    console.log("  Speed   : ", gps.speed);
    console.log("  Course  : ", gps.course);
    console.log("  latitude   : ", gps.latitude);
    console.log("  longitude  : ", gps.longitude);
    console.log("  altitude   : ", gps.altitude);
    console.log("MPU6050 Roll Data");
    console.log("  pitch   : ", imu.gyro.pitch);
    console.log("MPU6050 Starting Acceleration");
    console.log("  Acceleration   : ", imu.accelerometer.acceleration);
    console.log("MPU6050 Temp");
    console.log("  fahrenheit   : ", imu.thermometer.fahrenheit);
    console.log("Volume");
    console.log("  Volume   : ",volumeLevel);
    console.log("Stroke Rate");
    console.log("  Stroke Rate   : ",readStrokeRate(ReadStrokeAddress));
    console.log("--------------------------------------");
  });
});
<|endoftext|>


<commit_before>import express from 'express';
import session from 'express-session';
import connectMongo from 'connect-mongo';
import passport from 'passport';
import bodyParser from 'body-parser';
import config from './config';
import language from './components/language';
import loadContentConfig from './components/content';
import loadQueryParams from './components/load-query-params';
import loadConfigElements from './components/load-config';
import loadUser from './components/load-user';
import templateConfig from './components/template-config';
import appRouteConfig from './router/appRoutes.js';
import apiRouteConfig from './router/apiRoutes.js';
import authRouteConfig from './router/authRoutes.js';
import memberRouteConfig from './router/membershipRoutes.js';
import { getLogger, getChildLogger } from './components/log-factory';
import dbConfig from './components/db/config';
import runDataImport from './components/db/data-import';
import configureAuth from './components/authentication';
import { print } from './components/custom-utils';

const app = express();
const MongoStore = connectMongo(session); // mongodb session store

global.Logger = getLogger({
    name: 'scholarship-site'
});

const dbLogger = getChildLogger({
    baseLogger: Logger,
    additionalFields: {
        module: 'db-config'
    }
});

dbConfig()
    .then((db) => {
        if (!db) {
            dbLogger.error(null, 'Got null or undefinded for the db connection from the db config');
            return;
        }

        // Now that we know the db is connected, continue setting up the app
        // TODO: Use secure cookies in production along with setting 'trust proxy' to 1 on the app
         app.use(session({
            secret: config.session.secret,
            resave: false, // don't save the session if unmodified
            saveUninitialized: false, // don't create session until something stored
            store: new MongoStore({
                db,
                touchAfter: 24 * 3600
            })
        }));
        app.use(passport.initialize());
        app.use(passport.session());
        app.use(express.static('public'));
        app.use(bodyParser.urlencoded({
            extended: true
        }));
        app.use(bodyParser.json());
        app.use(language);

        configureAuth({
            passport,
            db
        });
        authRouteConfig({
            app,
            passport,
            db,
            baseLogger: Logger
        });

        loadQueryParams(app);
        loadConfigElements(app);
        loadContentConfig(app);
        loadUser(app);
        templateConfig(app);
        appRouteConfig({
            app,
            db
        });
        apiRouteConfig({
            app,
            db,
            baseLogger: Logger
        });
        memberRouteConfig({
            app,
            db,
            baseLogger: Logger
        });

        if (config.db.shouldRunDataImport) {
            runDataImport({
                spreadsheetPath: 'app/files/database_may_28.csv',
                baseLogger: Logger,
                collections: {
                    provinces: db.collection('provinces'),
                    universities: db.collection('universities'),
                    programs: db.collection('programs')
                }
            });
        }

        app.listen(3000, () => Logger.info('App listening on port 3000'));
    })
    .catch(e => {
        dbLogger.error(e, 'Error connecting to database');
    });
<commit_msg>Added a comment about the session store initialization<commit_after>import express from 'express';
import session from 'express-session';
import connectMongo from 'connect-mongo';
import passport from 'passport';
import bodyParser from 'body-parser';
import config from './config';
import language from './components/language';
import loadContentConfig from './components/content';
import loadQueryParams from './components/load-query-params';
import loadConfigElements from './components/load-config';
import loadUser from './components/load-user';
import templateConfig from './components/template-config';
import appRouteConfig from './router/appRoutes.js';
import apiRouteConfig from './router/apiRoutes.js';
import authRouteConfig from './router/authRoutes.js';
import memberRouteConfig from './router/membershipRoutes.js';
import { getLogger, getChildLogger } from './components/log-factory';
import dbConfig from './components/db/config';
import runDataImport from './components/db/data-import';
import configureAuth from './components/authentication';
import { print } from './components/custom-utils';

const app = express();
const MongoStore = connectMongo(session); // mongodb session store

global.Logger = getLogger({
    name: 'scholarship-site'
});

const dbLogger = getChildLogger({
    baseLogger: Logger,
    additionalFields: {
        module: 'db-config'
    }
});

dbConfig()
    .then((db) => {
        if (!db) {
            dbLogger.error(null, 'Got null or undefinded for the db connection from the db config');
            return;
        }

        // Now that we know the db is connected, continue setting up the app
        // TODO: Use secure cookies in production along with setting 'trust proxy' to 1 on the app
         app.use(session({
            secret: config.session.secret,
            resave: false, // don't save the session if unmodified
            saveUninitialized: false, // don't create session until something stored
            store: new MongoStore({
                db,
                touchAfter: 24 * 3600 // Only update the session every 24 hours unless a modification to the session is made
            })
        }));
        app.use(passport.initialize());
        app.use(passport.session());
        app.use(express.static('public'));
        app.use(bodyParser.urlencoded({
            extended: true
        }));
        app.use(bodyParser.json());
        app.use(language);

        configureAuth({
            passport,
            db
        });
        authRouteConfig({
            app,
            passport,
            db,
            baseLogger: Logger
        });

        loadQueryParams(app);
        loadConfigElements(app);
        loadContentConfig(app);
        loadUser(app);
        templateConfig(app);
        appRouteConfig({
            app,
            db
        });
        apiRouteConfig({
            app,
            db,
            baseLogger: Logger
        });
        memberRouteConfig({
            app,
            db,
            baseLogger: Logger
        });

        if (config.db.shouldRunDataImport) {
            runDataImport({
                spreadsheetPath: 'app/files/database_may_28.csv',
                baseLogger: Logger,
                collections: {
                    provinces: db.collection('provinces'),
                    universities: db.collection('universities'),
                    programs: db.collection('programs')
                }
            });
        }

        app.listen(3000, () => Logger.info('App listening on port 3000'));
    })
    .catch(e => {
        dbLogger.error(e, 'Error connecting to database');
    });
<|endoftext|>


<commit_before>var Raspi = require("raspi-io");
var five = require("johnny-five");
var pitft = require("pitft");
var sleep = require('sleep');

var fb = pitft("/dev/fb1"); // Returns a framebuffer in direct mode.  See the clock.js example for double buffering mode

// Clear the screen buffer
fb.clear();

var xMax = fb.size().width;
var yMax = fb.size().height;

fb.color(1, 1, 1); // Set the color to white

fb.font("fantasy", 12); // Use the "fantasy" font with size 12
fb.text(0, 20, "HI", false); // Draw the text non-centered, rotated _a_ degrees

var board = new five.Board({
  io: new Raspi()
});

board.on("ready", function() {
  var gps = new five.GPS({
    breakout: "ADAFRUIT_ULTIMATE_GPS",
    pins: ['P1-8', 'P1-10']
  });

  // If latitude, longitude, course or speed change log it

  gps.on("change", function() {
    console.log("position");
    console.log("  latitude   : ", this.latitude);
    fb.font("fantasy", 12); // Use the "fantasy" font with size 12
    fb.text(20, 20, this.latitude, false); // Draw the text non-centered, rotated _a_ degrees
    console.log("  longitude  : ", this.longitude);
    fb.font("fantasy", 12); // Use the "fantasy" font with size 12
    fb.text(0, 20, this.longitude, false); // Draw the text non-centered, rotated _a_ degrees
    console.log("--------------------------------------");
    sleep.sleep(5)
    fb.clear();

  });
});
<commit_msg>test.<commit_after>var Raspi = require("raspi-io");
var five = require("johnny-five");
var pitft = require("pitft");
var sleep = require('sleep');

var fb = pitft("/dev/fb1"); // Returns a framebuffer in direct mode.  See the clock.js example for double buffering mode

// Clear the screen buffer
fb.clear();

var xMax = fb.size().width;
var yMax = fb.size().height;

fb.color(1, 1, 1); // Set the color to white

fb.font("fantasy", 12); // Use the "fantasy" font with size 12
fb.text(0, 20, "HI", false); // Draw the text non-centered, rotated _a_ degrees
sleep.sleep(5);

console.log("Starting Board");

var board = new five.Board({
  io: new Raspi()
  console.log("instantiated rpi");
});

board.on("ready", function() {
  console.log("this might work");

  var gps = new five.GPS({
    breakout: "ADAFRUIT_ULTIMATE_GPS",
    pins: ['P1-8', 'P1-10']
  });

  console.log("kk about todo shit");

  // If latitude, longitude, course or speed change log it

  gps.on("change", function() {
    fb.clear();
    console.log("position");
    console.log("  latitude   : ", this.latitude);
    fb.font("fantasy", 12); // Use the "fantasy" font with size 12
    fb.text(20, 20, this.latitude, false); // Draw the text non-centered, rotated _a_ degrees
    console.log("  longitude  : ", this.longitude);
    fb.font("fantasy", 12); // Use the "fantasy" font with size 12
    fb.text(0, 20, this.longitude, false); // Draw the text non-centered, rotated _a_ degrees
    console.log("--------------------------------------");
    sleep.sleep(5)
    fb.clear();

  });
});
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(document).ready(function () {
    $('.dataTable').dataTable();
});

<commit_msg>Update base.js<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(document).ready(function () {

    /**
     * DATATABLES - dataTable default builder constructor
     */
    $('.dataTable').dataTable();

    /**
     * MODAL - myModal default constructor
     *
     * Changes default for the modal plugin's 'keyboard' option to false
     */
    $.fn.modal.Constructor.DEFAULTS.keyboard = false;

    /**
     * This event is fired when the modal has loaded content using the remote option
     */
    $('#myModal').on('loaded.bs.modal', function (e) {

        /**
         * Insert close button for modal view
         */
        $('.modal-content').prepend('<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>');

        /**
         *
         */
        $('form').submit(function (event) {

            /**
             * stop form from submitting normally
             */
            event.preventDefault();
            var formData = new FormData($(this)[0]);
            var formAction = $(this).attr('action');
            $.ajax({
                url: formAction,
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false
            }).done(function (data) {
                console.log(data);
            });

            /**
             * myModal hide
             */
            $('#myModal').modal('hide');

            /**
             * Page reload
             */
            location.reload();
        });
    });

    /**
     * Remove data on hidden bs modal
     */
    $('#myModal').on('hidden.bs.modal', function (e) {
        $(this).removeData('bs.modal');
    });

    /**
     * TABS - myTabs default constructor
     *
     * Used to enable link to tab
     */
    $('#myTabs a:first').tab('show');
    var url = document.location.toString();
    if (url.match('#')) {
        var tabId = url.split('#')[1];
        $('#myTabs a[href=#' + tabId + ']').tab('show');
    }

    /**
     * Change hash for page-reload
     */
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
        window.location.hash = e.target.hash;
    });
});

<|endoftext|>


<commit_before>require('dotenv').config({ silent: true });
const async = require('async');

const config = require('../../lib/app/config');
const DeviceModel = require('../../lib/models/device');

function seedDevices(users, deviceTypes, callback) {
  async.parallel({
    sensor: function seedSensor (cb) {
      DeviceModel.create({
        name: 'Test Sensor Device',
        description: 'A test sensor device',
        deviceType: deviceTypes.sensor.model._id,
        owner: users.user.model._id,
        address64: '1234567812345678',
      }, cb);
    },
    actuator: function seedActuator (cb) {
      DeviceModel.create({
        name: 'Test Actuator Device',
        description: 'A test actuator device',
        deviceType: deviceTypes.actuator.model._id,
        owner: users.user.model._id,
        address64: '123456781234567a',
      }, cb);
    },
  }, function (err, results) {
    if (err) {
      throw new Error(err);
    }

    callback(err, {
      sensor: {
        model: results.sensor.toObject(),
      },
      actuator: {
        model: results.actuator.toObject(),
      }
    });
  });
}

module.exports = seedDevices;
<commit_msg>utils: updating seeds to reflect schema<commit_after>require('dotenv').config({ silent: true });
const async = require('async');

const config = require('../../lib/app/config');
const DeviceModel = require('../../lib/models/device');

function seedDevices(users, deviceTypes, callback) {
  async.parallel({
    sensor: function seedSensor (cb) {
      DeviceModel.create({
        name: 'Test Sensor Device',
        description: 'A test sensor device',
        deviceType: deviceTypes.sensor.model._id,
        owner: users.user.model._id,
        visibility: 'public',
        address: '1234567812345678',
      }, cb);
    },
    sensor2: function seedSensor2 (cb) {
      DeviceModel.create({
        name: 'Private Test Sensor Device',
        description: 'A test sensor device',
        deviceType: deviceTypes.sensor.model._id,
        owner: users.user.model._id,
        visibility: 'private',
        address: '123456781234567c',
      }, cb);
    },
    actuator: function seedActuator (cb) {
      DeviceModel.create({
        name: 'Test Actuator Device',
        description: 'A test actuator device',
        deviceType: deviceTypes.actuator.model._id,
        owner: users.user.model._id,
        visibility: 'private',
        address: '123456781234567a',
      }, cb);
    },
  }, function (err, results) {
    if (err) {
      throw new Error(err);
    }

    callback(err, {
      sensor: {
        model: results.sensor.toObject(),
      },
      sensor2: {
        model: results.sensor2.toObject(),
      },
      actuator: {
        model: results.actuator.toObject(),
      }
    });
  });
}

module.exports = seedDevices;
<|endoftext|>


<commit_before>/* Consistent asynchronous page loading */

var current_url = window.location.pathname;

/* This is a work around for the back button being broken in Opera
 * http://www.opera.com/support/kb/view/827/
 */
history.navigationMode = 'compatible';

function to_absolute(url) {
    if (url.match(/https?\:\/\//)) {
        return url;
    } else if (url.substr(0, 1) == "/") {
        return window.location.protocol + '//' + window.location.host + url;
    } else if (url.indexOf('?') != -1) {
        if (current_url.lastIndexOf('?') != -1) {
            return current_url.substring(0, current_url.lastIndexOf('?')) + url;
        }
        return current_url + url;
    } else {
        return current_url + url;
    }
}

function display_loading_screen(){
    $('body').append('

')
    $('#loading').height($('html').height())
    display_spinner()
}

/* reposition the spinner when the page is scrolled - on iPhone only */
function display_spinner(){
    offset = window.innerHeight / 2
    if (navigator.userAgent.match(/iPhone/i) ||
        navigator.userAgent.match(/iPod/i) ||
        navigator.userAgent.match(/iPad/i)) {
        offset += window.pageYOffset
    }
    $('#loading').css('background-position', '50% ' + offset + 'px')
}

$(window).scroll(display_spinner)

function clear_loading_screen(){
    $('#loading').remove();
}

// Callback method that swaps in the asynchronously loaded bits to the page, and fades it in
function async_load_callback(data, textStatus, xhr) {
    $('body').html(data.body);
    $('title').html(data.title);
    $(document).trigger('molly-page-change', [current_url])
    capture_outbound();
}

function ajax_failure() {
    $('#loading')
        .html('
Error loading page - please try again.
')
        .css({'font-size': '20px', 'font-weight': 'bold'})
        .fadeTo('fast', 0.9, function() {
            setTimeout(function() {
                clear_loading_screen();
            }, 1200);
        });
}

function async_load(url, query, meth) {

    /* Don't attempt AJAX for offsite links */
    if (to_absolute(url).substr(0, base.length) != base) {
        return true;
    }

    display_loading_screen()

    query['format'] = 'fragment';
    $.ajax({
            'url': to_absolute(url),
            'data': query,
            'type': meth,
            'dataType': 'json',
            'success': function(data, textStatus, xhr) {
                current_url = data.uri;
                // Detect if history API is available - http://diveintohtml5.org/detect.html#history
                if (!!(window.history && history.pushState)) {
                    history.pushState(null, null, to_absolute(current_url))
                } else {
                    window.location.hash = current_url;
                }
                return async_load_callback(data, textStatus, xhr);
            },
            'error': ajax_failure
        });
    return false;
}

function capture_outbound()  {
    // Intercept all forms
    $('form:not(.has-ajax-handler)').unbind('submit')
    $('form:not(.has-ajax-handler)').submit(function(evt) {
            var serial = $(this).serializeArray();
            var datamap = {}
            var i = 0;
            for (i = 0; i < serial.length; i++) {
                datamap[serial[i].name] = serial[i].value;
            }
            return async_load($(this).attr('action'), datamap, $(this).attr('method'));
        });

    // Intercept all links with an href
    $('a[href]:not(.has-ajax-handler)').unbind('click')
    $('a[href]:not(.has-ajax-handler)').click(function(evt) {
            return async_load($(this).attr('href'), {}, 'GET');
        });
}

$(window).load(function() {
    function check_hash_change(){
        if (window.location.hash && window.location.hash.substr(1) != current_url) {
            async_load(window.location.hash.substr(1), {}, "GET");
        }
        if (typeof(window.opera)!='undefined'){
            setTimeout(check_hash_change, 100);
        }
    }
    check_hash_change();
    $(document).trigger('molly-page-change', [current_url])
    capture_outbound();

    if (!!(window.history && history.pushState)) {
      window.addEventListener('popstate', function(e, state){
        if (current_url != window.location.pathname) {
          async_load(window.location.href, {}, 'GET');
        }
      }, false)
    }
});

<commit_msg>Remember to add redirect code in Js<commit_after>/* Consistent asynchronous page loading */

var current_url = window.location.pathname;

/* This is a work around for the back button being broken in Opera
 * http://www.opera.com/support/kb/view/827/
 */
history.navigationMode = 'compatible';

function to_absolute(url) {
    if (url.match(/https?\:\/\//)) {
        return url;
    } else if (url.substr(0, 1) == "/") {
        return window.location.protocol + '//' + window.location.host + url;
    } else if (url.indexOf('?') != -1) {
        if (current_url.lastIndexOf('?') != -1) {
            return current_url.substring(0, current_url.lastIndexOf('?')) + url;
        }
        return current_url + url;
    } else {
        return current_url + url;
    }
}

function display_loading_screen(){
    $('body').append('

')
    $('#loading').height($('html').height())
    display_spinner()
}

/* reposition the spinner when the page is scrolled - on iPhone only */
function display_spinner(){
    offset = window.innerHeight / 2
    if (navigator.userAgent.match(/iPhone/i) ||
        navigator.userAgent.match(/iPod/i) ||
        navigator.userAgent.match(/iPad/i)) {
        offset += window.pageYOffset
    }
    $('#loading').css('background-position', '50% ' + offset + 'px')
}

$(window).scroll(display_spinner)

function clear_loading_screen(){
    $('#loading').remove();
}

// Callback method that swaps in the asynchronously loaded bits to the page, and fades it in
function async_load_callback(data, textStatus, xhr) {
    $('body').html(data.body);
    $('title').html(data.title);
    $(document).trigger('molly-page-change', [current_url])
    capture_outbound();
}

function ajax_failure() {
    $('#loading')
        .html('
Error loading page - please try again.
')
        .css({'font-size': '20px', 'font-weight': 'bold'})
        .fadeTo('fast', 0.9, function() {
            setTimeout(function() {
                clear_loading_screen();
            }, 1200);
        });
}

function async_load(url, query, meth) {

    /* Don't attempt AJAX for offsite links */
    if (to_absolute(url).substr(0, base.length) != base) {
        return true;
    }

    display_loading_screen()

    query['format'] = 'fragment';
    $.ajax({
            'url': to_absolute(url),
            'data': query,
            'type': meth,
            'dataType': 'json',
            'success': function(data, textStatus, xhr) {
                if (data.redirect) {
                    window.location = data.redirect;
                    return true;
                }
                current_url = data.uri;
                // Detect if history API is available - http://diveintohtml5.org/detect.html#history
                if (!!(window.history && history.pushState)) {
                    history.pushState(null, null, to_absolute(current_url))
                } else {
                    window.location.hash = current_url;
                }
                return async_load_callback(data, textStatus, xhr);
            },
            'error': ajax_failure
        });
    return false;
}

function capture_outbound()  {
    // Intercept all forms
    $('form:not(.has-ajax-handler)').unbind('submit')
    $('form:not(.has-ajax-handler)').submit(function(evt) {
            var serial = $(this).serializeArray();
            var datamap = {}
            var i = 0;
            for (i = 0; i < serial.length; i++) {
                datamap[serial[i].name] = serial[i].value;
            }
            return async_load($(this).attr('action'), datamap, $(this).attr('method'));
        });

    // Intercept all links with an href
    $('a[href]:not(.has-ajax-handler)').unbind('click')
    $('a[href]:not(.has-ajax-handler)').click(function(evt) {
            return async_load($(this).attr('href'), {}, 'GET');
        });
}

$(window).load(function() {
    function check_hash_change(){
        if (window.location.hash && window.location.hash.substr(1) != current_url) {
            async_load(window.location.hash.substr(1), {}, "GET");
        }
        if (typeof(window.opera)!='undefined'){
            setTimeout(check_hash_change, 100);
        }
    }
    check_hash_change();
    $(document).trigger('molly-page-change', [current_url])
    capture_outbound();

    if (!!(window.history && history.pushState)) {
      window.addEventListener('popstate', function(e, state){
        if (current_url != window.location.pathname) {
          async_load(window.location.href, {}, 'GET');
        }
      }, false)
    }
});

<|endoftext|>


<commit_before>(function() {
	var controls = {
			'up': document.createElement('img'),
			'right': document.createElement('img'),
			'down': document.createElement('img'),
			'left': document.createElement('img')
		},
		arrow = document.createElement('canvas'),
		controlSize = 100,
		controlThird = controlSize / 3,
		controlTwoThird = controlThird * 2,
		controlHalf = controlSize / 2,
		ctx,
		c;

	if (!arrow.getContext) {
		throw 'This browser does not support the use of canvas';
	}

	arrow.width = arrow.height = controlSize;
	ctx = arrow.getContext('2d');

	ctx.fillStyle = '#888';

	for (c in controls) {
		ctx.strokeRect(0, 0, controlSize, controlSize);
		ctx.moveTo(controlThird, controlThird);
		ctx.lineTo(controlTwoThird, controlThird);
		ctx.lineTo(controlHalf, controlTwoThird);
		ctx.fill();
		controls[c].src = arrow.toDataURL("image/png").replace("image/png", "image/octet-stream");
	}

	var ad = function(parent) {
		if (parent.tagName != 'CANVAS') {
			throw 'The parent element must be a canvas tag';
		}

		this.parent = parent;
		this.ctx = this.parent.getContext('2d');
		_init.apply(this, [4, 4]);
	};

	var _init = function(gridWidth, nbColors) {
		var colors = _generateColors.apply(this, [nbColors]),
			grid = _generateGrid.apply(this, [gridWidth, nbColors]);

		_displayGrid.apply(this, [grid, colors]);
	};

	var _randomInt = function(maxExcluded) {
		return 0 | Math.random() * maxExcluded;
	};

	/**
	 * Generate an array of colors. A color is an array of 3 integer(0, 255).
	 * The first color is randomly generated, the last one is the opposite of
	 * the first one. The others are calculated with a lerp computation.
	 */
	var _generateColors = function(nb) {
		var colors = [],
			c = 1,
			last = nb - 1,
			percentColor,
			_generateRandomColor,
			_lerp;

		_generateRandomColor = function() {
			return [
				_randomInt(256),
				_randomInt(256),
				_randomInt(256)
			]
		};

		_lerp = function(val1, val2, ratio) {
			return 0 | (Math.min(val1, val2) + Math.abs(val1 - val2) * ratio);
		};

		colors[0] = _generateRandomColor();
		colors[last] = [
			(colors[0][0] + 128) % 256,
			(colors[0][1] + 128) % 256,
			(colors[0][2] + 128) % 256
		];

		for (; c < last; c++) {
			percentColor = c / last;
			colors[c] = [
				_lerp(colors[0][0], colors[last][0], percentColor),
				_lerp(colors[0][2], colors[last][1], percentColor),
				_lerp(colors[0][1], colors[last][2], percentColor)
			];
		}

		return colors;
	};

	/**
	 * Generate the grid from a width (the grid is a square) and a number of
	 * colors.
	 * The returned grid is a 2 dimensions array containing, for each cell, an
	 * integer corresponding to the cell's color index (0, nbColors - 1)
	 */
	var _generateGrid = function(width, nbColors) {
		var grid = [],
			x = 0,
			y;

		for (; x < width; x++) {
			grid[x] = [];
			for (y = 0; y < width; y++) {
				grid[x][y] = _randomInt(nbColors);
			}
		}

		return grid;
	};

	/**
	 * Display the grid in the canvas
	 */
	var _displayGrid = function(grid, colors) {
		var canvasWidth = this.ctx.canvas.clientWidth,
			canvasHeight = this.ctx.canvas.clientHeight,
			gridWidth = grid[0].length,
			cellSize = canvasWidth / (gridWidth + 2),
			x = 0,
			y,
			color,
			_displayCell;

		_displayCell = function(grid, color, x, y) {
			color = colors[grid[x][y]];
			this.ctx.fillStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
			this.ctx.fillRect((x + 1) * cellSize, (y + 1) * cellSize, cellSize, cellSize);
		};

		for (; x < gridWidth; x++) {
			// control buttons
			this.ctx.drawImage(controls['up'], (x + 1) * cellSize, 0, cellSize, cellSize);
			this.ctx.drawImage(controls['right'], canvasWidth - cellSize, (x + 1) * cellSize, cellSize, cellSize);
			this.ctx.drawImage(controls['down'], (x + 1) * cellSize, canvasHeight - cellSize, cellSize, cellSize);
			this.ctx.drawImage(controls['left'], 0, (x + 1) * cellSize, cellSize, cellSize);

			for (y = 0; y < gridWidth; y++) {
				_displayCell.apply(this, [grid, color, x, y]);
			}
		}
	};

	window.Ad = ad;
})();
<commit_msg>for loop used in a more regular way<commit_after>(function() {
	var controls = {
			'up': document.createElement('img'),
			'right': document.createElement('img'),
			'down': document.createElement('img'),
			'left': document.createElement('img')
		},
		arrow = document.createElement('canvas'),
		controlSize = 100,
		controlThird = controlSize / 3,
		controlTwoThird = controlThird * 2,
		controlHalf = controlSize / 2,
		ctx,
		c;

	if (!arrow.getContext) {
		throw 'This browser does not support the use of canvas';
	}

	arrow.width = arrow.height = controlSize;
	ctx = arrow.getContext('2d');

	ctx.fillStyle = '#888';

	for (c in controls) {
		ctx.strokeRect(0, 0, controlSize, controlSize);
		ctx.moveTo(controlThird, controlThird);
		ctx.lineTo(controlTwoThird, controlThird);
		ctx.lineTo(controlHalf, controlTwoThird);
		ctx.fill();
		controls[c].src = arrow.toDataURL("image/png").replace("image/png", "image/octet-stream");
	}

	var ad = function(parent) {
		if (parent.tagName != 'CANVAS') {
			throw 'The parent element must be a canvas tag';
		}

		this.parent = parent;
		this.ctx = this.parent.getContext('2d');
		_init.apply(this, [4, 4]);
	};

	var _init = function(gridWidth, nbColors) {
		var colors = _generateColors.apply(this, [nbColors]),
			grid = _generateGrid.apply(this, [gridWidth, nbColors]);

		_displayGrid.apply(this, [grid, colors]);
	};

	var _randomInt = function(maxExcluded) {
		return 0 | Math.random() * maxExcluded;
	};

	/**
	 * Generate an array of colors. A color is an array of 3 integer(0, 255).
	 * The first color is randomly generated, the last one is the opposite of
	 * the first one. The others are calculated with a lerp computation.
	 */
	var _generateColors = function(nb) {
		var colors = [],
			c = 1,
			last = nb - 1,
			percentColor,
			_generateRandomColor,
			_lerp;

		_generateRandomColor = function() {
			return [
				_randomInt(256),
				_randomInt(256),
				_randomInt(256)
			]
		};

		_lerp = function(val1, val2, ratio) {
			return 0 | (Math.min(val1, val2) + Math.abs(val1 - val2) * ratio);
		};

		colors[0] = _generateRandomColor();
		colors[last] = [
			(colors[0][0] + 128) % 256,
			(colors[0][1] + 128) % 256,
			(colors[0][2] + 128) % 256
		];

		for (; c < last; c++) {
			percentColor = c / last;
			colors[c] = [
				_lerp(colors[0][0], colors[last][0], percentColor),
				_lerp(colors[0][2], colors[last][1], percentColor),
				_lerp(colors[0][1], colors[last][2], percentColor)
			];
		}

		return colors;
	};

	/**
	 * Generate the grid from a width (the grid is a square) and a number of
	 * colors.
	 * The returned grid is a 2 dimensions array containing, for each cell, an
	 * integer corresponding to the cell's color index (0, nbColors - 1)
	 */
	var _generateGrid = function(width, nbColors) {
		var grid = [],
			x = 0,
			y;

		for (; x < width; x++) {
			grid[x] = [];
			for (y = 0; y < width; y++) {
				grid[x][y] = _randomInt(nbColors);
			}
		}

		return grid;
	};

	/**
	 * Display the grid in the canvas
	 */
	var _displayGrid = function(grid, colors) {
		var canvasWidth = this.ctx.canvas.clientWidth,
			canvasHeight = this.ctx.canvas.clientHeight,
			gridWidth = grid[0].length,
			cellSize = canvasWidth / (gridWidth + 2),
			x, y,
			color,
			_displayCell;

		_displayCell = function(grid, color, x, y) {
			color = colors[grid[x][y]];
			this.ctx.fillStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
			this.ctx.fillRect((x + 1) * cellSize, (y + 1) * cellSize, cellSize, cellSize);
		};

		for (x = 0; x < gridWidth; x++) {
			// control buttons
			this.ctx.drawImage(controls['up'], (x + 1) * cellSize, 0, cellSize, cellSize);
			this.ctx.drawImage(controls['right'], canvasWidth - cellSize, (x + 1) * cellSize, cellSize, cellSize);
			this.ctx.drawImage(controls['down'], (x + 1) * cellSize, canvasHeight - cellSize, cellSize, cellSize);
			this.ctx.drawImage(controls['left'], 0, (x + 1) * cellSize, cellSize, cellSize);

			for (y = 0; y < gridWidth; y++) {
				_displayCell.apply(this, [grid, color, x, y]);
			}
		}
	};

	window.Ad = ad;
})();
<|endoftext|>


<commit_before>define.class("$server/composition",function(require, $ui$, screen, view) {
	this.render = function() {
		return [screen(
			view({
				flex:1,
				init:function(){
					console.log('here')
				},
				bgcolor:'red',
				hardrect:{
					color:function(){
						var len = min(pow(1.5-length(mesh.pos),8.),1.)
						if(mesh.depth>13.) return pal.pal5(0.1*colornoise+0.1*view.time)*len
						return mix('brown',pal.pal5(0.1*colornoise + mesh.pos.y+mesh.depth/14+0.1*view.time),mesh.depth/12)*sin(mesh.pos.y*PI)
					},
					mesh:define.struct({
						pos:vec2,
						path:float,
						depth:float
					}).array(),
					position:function(){

						// lets walk
						var path = mesh.path
						var pos = vec2(0,0)
						var scale = vec2(1,1)
						var dir = vec2(0,-0.8)
						var turbulence = 2.
						var depth = int(mesh.depth)
						for(var i = 0; i < 14; i++){
							if(i >= depth) break
							var right = mod(path, 2.)
						    if(right>0.){
						    	dir = math.rotate2d(dir, 25.*math.DEG+0.01*turbulence*sin(view.time))
						    }
						    else{
						    	dir = math.rotate2d(dir, -25.*math.DEG+0.01*turbulence*sin(view.time))
						    }
						    pos += (dir * scale)*1.9
						    scale = scale * vec2(0.85,0.85)
							path = floor(path / 2.)
						}
						colornoise = 0.
						if(depth > 13){
							var noise = noise.noise3d(vec3(pos.x*.25,pos.y*.25,0.5*view.time)) * turbulence
							colornoise = noise
							dir = math.rotate2d(dir, -140.*math.DEG*noise)
							//pos += dir
							scale *= vec2(1,4.)
							//pos.x += noise*0.2
						}
						// alright we found a pos and dir

						var p = (math.rotate2d((mesh.pos*vec2(1.,.5)+vec2(-.8,-.4))*scale, atan(dir.y,dir.x)) + pos)  * vec2(30,30) + vec2(300,400)
						return vec4(p, 0, 1) * view.totalmatrix * view.viewmatrix
					},
					update:function(){
						var mesh = this.mesh = this.mesh.struct.array()

						// first triangle
						function recur(path, depth){

							mesh.pushQuad(
								-1,-1, path, depth,
								1,-1, path, depth,
								-1,1, path, depth,
								1,1, path, depth
							)
							if(depth>13)return

							recur(path, depth+1)
							recur(path + Math.pow(2, depth), depth+1)
						}
						recur(0,0)

						10101101

					}
				}
			})
		)]
	}
})
<commit_msg>Final tree<commit_after>define.class("$server/composition",function(require, $ui$, screen, view) {
	this.render = function() {
		return [screen(
			view({
				flex:1,
				init:function(){
					console.log('here')
				},
				bgcolor:'red',
				hardrect:{
					color:function(){
						var len = min(pow(1.5-length(mesh.pos),8.),1.)
						if(mesh.depth>13.) return pal.pal5(0.1*colornoise+0.1*view.time)*len
						return mix('brown',pal.pal5(0.1*colornoise + mesh.pos.y+mesh.depth/14+0.1*view.time),mesh.depth/12)*sin(mesh.pos.y*PI)
					},
					mesh:define.struct({
						pos:vec2,
						path:float,
						depth:float
					}).array(),
					position:function(){

						// lets walk
						var path = mesh.path
						var pos = vec2(0,0)
						var scale = vec2(1,1)
						var dir = vec2(0,-0.8)
						var turbulence = 2.
						var depth = int(mesh.depth)
						for(var i = 0; i < 14; i++){
							if(i >= depth) break
							var right = mod(path, 2.)
						    if(right>0.){
						    	dir = math.rotate2d(dir, 25.*math.DEG+0.01*turbulence*sin(view.time))
						    }
						    else{
						    	dir = math.rotate2d(dir, -25.*math.DEG+0.01*turbulence*sin(view.time))
						    }
						    pos += (dir * scale)*1.9
						    scale = scale * vec2(0.85,0.85)
							path = floor(path / 2.)
						}
						colornoise = 0.
						var vscale = vec2(1.,.5)
						var vcen = vec2(-.8,-.4)
						if(depth > 13){
							var noise = noise.noise3d(vec3(pos.x*.3,pos.y*.3,0.5*view.time)) * turbulence
							colornoise = noise
							dir = math.rotate2d(dir, -50.*math.DEG*noise)
							//pos += dir
							scale *= vec2(1,4.)
							//pos.x += noise*0.2
							vscale = vec2(3.,.5)
							vcen = vec2(0.8,0.)
						}
						// alright we found a pos and dir

						var p = (math.rotate2d((mesh.pos*vscale+vcen)*scale, atan(dir.y,dir.x)) + pos)  * vec2(30,30) + vec2(300,400)
						return vec4(p, 0, 1) * view.totalmatrix * view.viewmatrix
					},
					update:function(){
						var mesh = this.mesh = this.mesh.struct.array()

						// first triangle
						function recur(path, depth){

							mesh.pushQuad(
								-1,-1, path, depth,
								1,-1, path, depth,
								-1,1, path, depth,
								1,1, path, depth
							)
							if(depth>13)return

							recur(path, depth+1)
							recur(path + Math.pow(2, depth), depth+1)
						}
						recur(0,0)

						10101101

					}
				}
			})
		)]
	}
})
<|endoftext|>