<commit_before>import request   from './request';
import userStore from '../user/user.store';
import files     from './files';
import MD5       from 'MD5';

// public API ---------------------------------------------------------------------

let scitran = {
    verifyUser,
    createProject,
    createSubject,
    createSession,
    createModality,
    createAcquisition,
	upload
};

export default scitran;

// implementations ----------------------------------------------------------------

/**
 * Verify User
 *
 * Checks if the currently logged in users
 * in in the scitran system and returns a
 * user object.
 */
function verifyUser (callback) {
    request.get('users/self', callback);
}

/**
 * Create Project
 *
 * Takes a group name and a project name and
 * generates a request to make a project in scitran.
 */
function createProject (groupName, projectName, callback) {
    console.log('create project: ' + projectName);
    let body = {name: projectName};
    request.post('groups/' + groupName + '/projects', {body: body}, callback);
}

/**
 * Create Subject
 *
 */
function createSubject (projectId, subjectName, callback) {
    console.log('create subject: ' + subjectName);
    let body = {label: subjectName};
    request.post('projects/' + projectId + '/sessions', {body: body}, callback);
}

/**
 * Create Session
 *
 */
function createSession (sessionName, callback) {
    console.log('create session: ' + sessionName);
    callback();
}

/**
 * Create Modality
 *
 */
function createModality (sessionId, modalityName, callback) {
    console.log('create modality: ' + modalityName);
    let body = {label: modalityName};
    request.post('sessions/' + sessionId + '/acquisitions', {body: body}, callback);
}

/**
 * Create Acquisition
 *
 */
function createAcquisition (acquisitionName, callback) {
    console.log('create acquisition: ' + acquisitionName);
    callback();
}

function uploadFile (level, id, file) {
    files.read(file, function (contents) {
        let url = level + '/' + id + '/file/' + file.name;
        request.put(url, {
            headers: {
                'Content-Type': 'application/octet-stream',
                'Content-MD5': MD5(contents)
            },
            body: contents
        }, function (err, res) {
            console.log(err);
            console.log(res);
        });
    });
}

/**
 * Upload
 *
 * Takes an entire bids filelist and upload recurses
 * through and uploads all the files.
 *
 * TODO
 *    - Check if we should call filelist filetree for
 *    consistency
 *    - Determine how to upload in between scitran levels
 */
function upload (filelist) {
    let groupName = 'SquishyRoles';
    scitran.createProject(groupName, filelist[0].name, function (err, res) {
        let projectId = res.body._id;
        uploadSubjects(filelist[0].children, projectId);
    });
}

function uploadSubjects (subjects, projectId) {
    for (let subject of subjects) {
        if (subject.children && subject.children.length > 0) {
            scitran.createSubject(projectId, subject.name, function (err, res) {
                let subjectId = res.body._id;
                uploadSessions(subject.children, subjectId);
            });
        } else {
            uploadFile('projects', projectId, subject);
        }
    }
}

function uploadSessions (sessions, subjectId) {
    for (let session of sessions) {
        if (session.children && session.children.length > 0) {
            scitran.createSession(session.name, function () {
                uploadModalities(session.children, subjectId);
            });
        } else {
            console.log('upload subject file: ' + session.name);
        }
    }
}

function uploadModalities (modalities, subjectId) {
    for (let modality of modalities) {
        if (modality.children && modality.children.length > 0) {
            scitran.createModality(subjectId, modality.name, function () {
                uploadAquisitions(modality.children);
            });
        } else {
            console.log('upload session file: ' + modality.name)
        }
    }
}

function uploadAquisitions (acquisitions) {
    for (let acquisition of acquisitions) {
        console.log('upload acquisition: ' + acquisition.name);
    }
}<commit_msg>added comments outlining optional string fields<commit_after>import request   from './request';
import userStore from '../user/user.store';
import files     from './files';
import MD5       from 'MD5';

// public API ---------------------------------------------------------------------

let scitran = {
    verifyUser,
    createProject,
    createSubject,
    createSession,
    createModality,
    createAcquisition,
	upload
};

export default scitran;

// implementations ----------------------------------------------------------------

/**
 * Verify User
 *
 * Checks if the currently logged in users
 * in in the scitran system and returns a
 * user object.
 */
function verifyUser (callback) {
    request.get('users/self', callback);
}

/**
 * Create Project
 *
 * Takes a group name and a project name and
 * generates a request to make a project in scitran.
 */
function createProject (groupName, projectName, callback) {
    console.log('create project: ' + projectName);
    let body = {name: projectName};
    request.post('groups/' + groupName + '/projects', {body: body}, callback);
}

/**
 * Create Subject
 *
 */
function createSubject (projectId, subjectName, callback) {
    console.log('create subject: ' + subjectName);
    let body = {label: subjectName};
    // body can have subject_code field equal to arbitrary string
    request.post('projects/' + projectId + '/sessions', {body: body}, callback);
}

/**
 * Create Session
 *
 */
function createSession (sessionName, callback) {
    console.log('create session: ' + sessionName);
    callback();
}

/**
 * Create Modality
 *
 */
function createModality (sessionId, modalityName, callback) {
    console.log('create modality: ' + modalityName);
    let body = {label: modalityName};
    // body can have datatype field equal to an arbitrary string
    request.post('sessions/' + sessionId + '/acquisitions', {body: body}, callback);
}

/**
 * Create Acquisition
 *
 */
function createAcquisition (acquisitionName, callback) {
    console.log('create acquisition: ' + acquisitionName);
    callback();
}

function uploadFile (level, id, file) {
    files.read(file, function (contents) {
        let url = level + '/' + id + '/file/' + file.name;
        request.put(url, {
            headers: {
                'Content-Type': 'application/octet-stream',
                'Content-MD5': MD5(contents)
            },
            body: contents
        }, function (err, res) {
            console.log(err);
            console.log(res);
        });
    });
}

/**
 * Upload
 *
 * Takes an entire bids filelist and upload recurses
 * through and uploads all the files.
 *
 * TODO
 *    - Check if we should call filelist filetree for
 *    consistency
 *    - Determine how to upload in between scitran levels
 */
function upload (filelist) {
    let groupName = 'SquishyRoles';
    scitran.createProject(groupName, filelist[0].name, function (err, res) {
        let projectId = res.body._id;
        uploadSubjects(filelist[0].children, projectId);
    });
}

function uploadSubjects (subjects, projectId) {
    for (let subject of subjects) {
        if (subject.children && subject.children.length > 0) {
            scitran.createSubject(projectId, subject.name, function (err, res) {
                let subjectId = res.body._id;
                uploadSessions(subject.children, subjectId);
            });
        } else {
            uploadFile('projects', projectId, subject);
        }
    }
}

function uploadSessions (sessions, subjectId) {
    for (let session of sessions) {
        if (session.children && session.children.length > 0) {
            scitran.createSession(session.name, function () {
                uploadModalities(session.children, subjectId);
            });
        } else {
            console.log('upload subject file: ' + session.name);
        }
    }
}

function uploadModalities (modalities, subjectId) {
    for (let modality of modalities) {
        if (modality.children && modality.children.length > 0) {
            scitran.createModality(subjectId, modality.name, function () {
                uploadAquisitions(modality.children);
            });
        } else {
            console.log('upload session file: ' + modality.name)
        }
    }
}

function uploadAquisitions (acquisitions) {
    for (let acquisition of acquisitions) {
        console.log('upload acquisition: ' + acquisition.name);
    }
}<|endoftext|>


<commit_before>// Import express and request modules
var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var Mopidy = require('mopidy');

// Get Environment Apps
var clientId = process.env.SLACKID;
var clientSecret = process.env.SLACKSECRET;

var mopidyurl = process.env.MOPIDYURL || '192.168.99.100';
var mopidyport = process.env.MOPIDYPORT || '6680';

// Instantiates Mopidy Websockets
var mopidy = new Mopidy({ webSocketUrl: `ws://${mopidyurl}:${mopidyport}/mopidy/ws/` });

// Instantiates Express and assigns our app variable to it
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Start app in PORT
const PORT=4390;
app.listen(PORT, function () {
  //Callback triggered when server is successfully listening. Hurray!
  console.log("Slacktunes listening on port " + PORT);
});

// This route handles GET requests to our root ngrok address and responds with the same "Ngrok is working message" we used before
app.get('/', function(req, res) {
  res.send('Ngrok is working! Path Hit: ' + req.url);
});

// This route handles get request to a /oauth endpoint. We'll use this endpoint for handling the logic of the Slack oAuth process behind our app.
app.get('/oauth', function(req, res) {
  // When a user authorizes an app, a code query parameter is passed on the oAuth endpoint. If that code is not there, we respond with an error message
  if (!req.query.code) {
    res.status(500);
    res.send({"Error": "Looks like we're not getting code."});
    console.log("Looks like we're not getting code.");
  } else {
    // If it's there...

    // We'll do a GET call to Slack's `oauth.access` endpoint, passing our app's client ID, client secret, and the code we just got as query parameters.
    request({
      url: 'https://slack.com/api/oauth.access', //URL to hit
      qs: {code: req.query.code, client_id: clientId, client_secret: clientSecret}, //Query string data
      method: 'GET', //Specify the method

    }, function (error, response, body) {
      if (error) {
        console.log(error);
      } else {
        res.json(body);

      }
    })
  }
});

///////////////////////////
// Slack Commands /////////
///////////////////////////

var returnSearchResult = function(searchResult){
  let tracks = searchResult[1].tracks.slice(0,5);
  options = Array();
  for (let track of tracks){
    options.push({"text": `${track.name} – ${track.album.name} (${track.date})`,
    "value": track.uri});
  }
  return {
    "text": "Encontré estas cancones",
    "response_type": "ephemeral",
    "attachments": [
      {
        "text": "Escoge cual te gustaría agregar al playlist",
        "fallback": "If you could read this message, you'd be choosing something fun to do right now.",
        "color": "#3AA3E3",
        "attachment_type": "default",
        "callback_id": "addSong",
        "actions": [
          {
            "name": "searchresults",
            "text": "Escoge una canción...",
            "type": "select",
            "options": options
          }
        ]
      }
    ]
  }
}

var getSongName = function(tracks){
  let track = tracks[0].track;
  return track.name
}

app.post('/command', function(req, res) {
  console.log('Resolving command...', req.body.text);

  let command = req.body.text.split(" ")[0];
  let query = req.body.text.split(" ").slice(1).join(" ");

  switch (command){

    case "add":
      mopidy.library.search({'any': [query]})
                    .then(returnSearchResult)
                    .then((msg) => {
                      res.send(msg)
                    });
      break;

    case "skip":
      let nowPlaying = null;
      mopidy.playback.getCurrentTrack()
                           .then((track)=>{
                             nowPlaying=track;
                           })
      mopidy.playback.next()
            .then(()=>{
                        let msg = {
                            "text": `"${nowPlaying.name}" was skipped by @${req.body.user_name}`,
                            "mrkdwn": false,
                            "response_type": "in_channel",
                        }
              res.send(msg);
            });
      break;

    case "list":
      res.send("Playlist");
      break;

  }

});

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

  let body = JSON.parse(req.body.payload);
  let actions = body.actions;
  let callback = body.callback_id;

  switch (callback){
    case "addSong":
      let songuri = actions[0].selected_options[0].value;
      mopidy.tracklist.add(null, null, songuri, null)
                      .then(getSongName)
                      .done((songName)=>{
                        res.send(`Se agregó ${songName}`)
                      })

      mopidy.playback.getCurrentTrack()
                           .then((track)=>{
                             if (!track){
                               mopidy.playback.play()
                             }
                           })
      break;
  }
});
<commit_msg>List command working<commit_after>// Import express and request modules
var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var Mopidy = require('mopidy');

// Get Environment Apps
var clientId = process.env.SLACKID;
var clientSecret = process.env.SLACKSECRET;

var mopidyurl = process.env.MOPIDYURL || '192.168.99.100';
var mopidyport = process.env.MOPIDYPORT || '6680';

// Instantiates Mopidy Websockets
var mopidy = new Mopidy({ webSocketUrl: `ws://${mopidyurl}:${mopidyport}/mopidy/ws/` });

// Instantiates Express and assigns our app variable to it
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Start app in PORT
const PORT=4390;
app.listen(PORT, function () {
  //Callback triggered when server is successfully listening. Hurray!
  console.log("Slacktunes listening on port " + PORT);
});

// This route handles GET requests to our root ngrok address and responds with the same "Ngrok is working message" we used before
app.get('/', function(req, res) {
  res.send('Ngrok is working! Path Hit: ' + req.url);
});

// This route handles get request to a /oauth endpoint. We'll use this endpoint for handling the logic of the Slack oAuth process behind our app.
app.get('/oauth', function(req, res) {
  // When a user authorizes an app, a code query parameter is passed on the oAuth endpoint. If that code is not there, we respond with an error message
  if (!req.query.code) {
    res.status(500);
    res.send({"Error": "Looks like we're not getting code."});
    console.log("Looks like we're not getting code.");
  } else {
    // If it's there...

    // We'll do a GET call to Slack's `oauth.access` endpoint, passing our app's client ID, client secret, and the code we just got as query parameters.
    request({
      url: 'https://slack.com/api/oauth.access', //URL to hit
      qs: {code: req.query.code, client_id: clientId, client_secret: clientSecret}, //Query string data
      method: 'GET', //Specify the method

    }, function (error, response, body) {
      if (error) {
        console.log(error);
      } else {
        res.json(body);

      }
    })
  }
});

///////////////////////////
// Slack Commands /////////
///////////////////////////

var returnSearchResult = function(searchResult){
  let tracks = searchResult[1].tracks.slice(0,5);
  options = Array();
  for (let track of tracks){
    options.push({"text": `${track.name} – ${track.album.name} (${track.date})`,
    "value": track.uri});
  }
  return {
    "text": "Encontré estas cancones",
    "response_type": "ephemeral",
    "attachments": [
      {
        "text": "Escoge cual te gustaría agregar al playlist",
        "fallback": "If you could read this message, you'd be choosing something fun to do right now.",
        "color": "#3AA3E3",
        "attachment_type": "default",
        "callback_id": "addSong",
        "actions": [
          {
            "name": "searchresults",
            "text": "Escoge una canción...",
            "type": "select",
            "options": options
          }
        ]
      }
    ]
  }
}

var getSongName = function(tracks){
  let track = tracks[0].track;
  return track.name
}

var getQueue = function(tracks){
  return mopidy.tracklist.index()
                    .then((index)=>{
                          let tracklist = Array();
                        for (let tltrack of tracks.slice(index)){
                          let track = tltrack.track;
                         tracklist.push(`${track.name} – ${track.album.name} (${track.date})`);
                      }
                    return tracklist.join("\n");
                  });
}

app.post('/command', function(req, res) {
  console.log('Resolving command...', req.body.text);

  let command = req.body.text.split(" ")[0];
  let query = req.body.text.split(" ").slice(1).join(" ");

  switch (command){

    case "add":
      mopidy.library.search({'any': [query]})
                    .then(returnSearchResult)
                    .then((msg) => {
                      res.send(msg)
                    });
      break;

    case "skip":
      let nowPlaying = null;

      mopidy.playback.getCurrentTrack()
                           .then((track)=>{
                             nowPlaying=track;
                           });

      mopidy.playback.next()
            .then(()=>{
                        let msg = {
                            "text": `"${nowPlaying.name}" was skipped by @${req.body.user_name}`,
                            "mrkdwn": false,
                            "response_type": "in_channel",
                        }
              res.send(msg);
            });

      break;

    case "list":
      mopidy.tracklist.getTlTracks()
                      .then(getQueue)
                      .done((msg)=>{
                        res.send(msg)
                      });

      break;

  }

});

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

  let body = JSON.parse(req.body.payload);
  let actions = body.actions;
  let callback = body.callback_id;

  switch (callback){
    case "addSong":
      let songuri = actions[0].selected_options[0].value;
      mopidy.tracklist.add(null, null, songuri, null)
                      .then(getSongName)
                      .done((songName)=>{
                        res.send(`Se agregó ${songName}`)
                      })

      mopidy.playback.getCurrentTrack()
                           .then((track)=>{
                             if (!track){
                               mopidy.playback.play()
                             }
                           })
      break;
  }
});
<|endoftext|>


<commit_before>import request   from './request';
import uploads   from './upload';
import userStore from '../user/user.store';

// public API ---------------------------------------------------------------------

// let scitran = {
//     verifyUser,
//     createProject,
//     createSubject,
//     createSession,
//     createModality,
// 	upload,
// };

export default  {

// implementations ----------------------------------------------------------------

    /**
     * Verify User
     *
     * Checks if the currently logged in users
     * in in the scitran system and returns a
     * user object.
     */
    verifyUser (callback) {
        request.get('users/self', callback);
    },

    /**
     * Create Project
     *
     * Takes a group name and a project name and
     * generates a request to make a project in scitran.
     */
    createProject (groupName, projectName, callback) {
        let body = {name: projectName};
        request.post('groups/' + groupName + '/projects', {body: body}, callback);
    },

    /**
     * Create Subject
     *
     */
    createSubject (projectId, subjectName, callback) {
        let body = {label: subjectName, subject_code: 'subject'};
        request.post('projects/' + projectId + '/sessions', {body: body}, callback);
    },

    /**
     * Create Session
     *
     */
    createSession (projectId, sessionName, callback) {
        let body = {label: sessionName, subject_code: 'session'};
        request.post('projects/' + projectId + '/sessions', {body: body}, callback);
    },

    /**
     * Create Modality
     *
     */
    createModality (sessionId, modalityName, callback) {
        let body = {label: modalityName, datatype: 'modality'};
        request.post('sessions/' + sessionId + '/acquisitions', {body: body}, callback);
    },

    /**
     * Upload File
     *
     * Pushed upload details into an upload queue.
     */
    uploadFile (level, id, file, tag) {
        let url = level + '/' + id + '/file/' + file.name;
        uploads.add({url: url, file: file, tag: tag, progress: this.progress});
    },

    /**
     * Upload
     *
     * Takes an entire bids file tree and upload recurses
     * through and uploads all the files.
     */
    upload (fileTree, count, progress) {
        let self = this;
        self.completed = 0;
        self.count = count;
        self.progress = function () {
            self.completed++;
            progress({total: self.count, completed: self.completed});
        }
        let groupName = 'SquishyRoles';
        self.createProject(groupName, fileTree[0].name, function (err, res) {
            let projectId = res.body._id;
            self.progress();
            self.uploadSubjects(fileTree[0].children, projectId);
        });
    },

    uploadSubjects (subjects, projectId) {
        let self = this;
        for (let subject of subjects) {
            if (subject.children && subject.children.length > 0) {
                self.createSubject(projectId, subject.name, function (err, res) {
                    self.progress();
                    let subjectId = res.body._id;
                    self.uploadSessions(subject.children, projectId, subjectId);
                });
            } else {
                self.uploadFile('projects', projectId, subject, 'project');
            }
        }
    },

    uploadSessions (sessions, projectId, subjectId) {
        let self = this;
        for (let session of sessions) {
            if (session.children && session.children.length > 0) {
                self.createSession(projectId, session.name, function () {
                    self.progress();
                    self.uploadModalities(session.children, subjectId);
                });
            } else {
                self.uploadFile('sessions', subjectId, session, 'subject');
            }
        }
    },

    uploadModalities (modalities, subjectId) {
        let self = this;
        for (let modality of modalities) {
            if (modality.children && modality.children.length > 0) {
                self.createModality(subjectId, modality.name, function (err, res) {
                    self.progress();
                    let modalityId = res.body._id;
                    self.uploadAquisitions(modality.children, modalityId);
                });
            } else {
                self.uploadFile('sessions', subjectId, modality, 'session');
            }
        }
    },

    uploadAquisitions (acquisitions, modalityId) {
        for (let acquisition of acquisitions) {
            this.uploadFile('acquisitions', modalityId, acquisition, 'modality');
        }
    }

};<commit_msg>added global comment about library<commit_after>import request   from './request';
import uploads   from './upload';
import userStore from '../user/user.store';

/**
 * Scitran
 *
 * A library for interactions with the
 * scitran service.
 */
export default  {

    /**
     * Verify User
     *
     * Checks if the currently logged in users
     * in in the scitran system and returns a
     * user object.
     */
    verifyUser (callback) {
        request.get('users/self', callback);
    },

    /**
     * Create Project
     *
     * Takes a group name and a project name and
     * generates a request to make a project in scitran.
     */
    createProject (groupName, projectName, callback) {
        let body = {name: projectName};
        request.post('groups/' + groupName + '/projects', {body: body}, callback);
    },

    /**
     * Create Subject
     *
     */
    createSubject (projectId, subjectName, callback) {
        let body = {label: subjectName, subject_code: 'subject'};
        request.post('projects/' + projectId + '/sessions', {body: body}, callback);
    },

    /**
     * Create Session
     *
     */
    createSession (projectId, sessionName, callback) {
        let body = {label: sessionName, subject_code: 'session'};
        request.post('projects/' + projectId + '/sessions', {body: body}, callback);
    },

    /**
     * Create Modality
     *
     */
    createModality (sessionId, modalityName, callback) {
        let body = {label: modalityName, datatype: 'modality'};
        request.post('sessions/' + sessionId + '/acquisitions', {body: body}, callback);
    },

    /**
     * Upload File
     *
     * Pushed upload details into an upload queue.
     */
    uploadFile (level, id, file, tag) {
        let url = level + '/' + id + '/file/' + file.name;
        uploads.add({url: url, file: file, tag: tag, progress: this.progress});
    },

    /**
     * Upload
     *
     * Takes an entire bids file tree and upload recurses
     * through and uploads all the files.
     */
    upload (fileTree, count, progress) {
        let self = this;
        self.completed = 0;
        self.count = count;
        self.progress = function () {
            self.completed++;
            progress({total: self.count, completed: self.completed});
        }
        let groupName = 'SquishyRoles';
        self.createProject(groupName, fileTree[0].name, function (err, res) {
            let projectId = res.body._id;
            self.progress();
            self.uploadSubjects(fileTree[0].children, projectId);
        });
    },

    uploadSubjects (subjects, projectId) {
        let self = this;
        for (let subject of subjects) {
            if (subject.children && subject.children.length > 0) {
                self.createSubject(projectId, subject.name, function (err, res) {
                    self.progress();
                    let subjectId = res.body._id;
                    self.uploadSessions(subject.children, projectId, subjectId);
                });
            } else {
                self.uploadFile('projects', projectId, subject, 'project');
            }
        }
    },

    uploadSessions (sessions, projectId, subjectId) {
        let self = this;
        for (let session of sessions) {
            if (session.children && session.children.length > 0) {
                self.createSession(projectId, session.name, function () {
                    self.progress();
                    self.uploadModalities(session.children, subjectId);
                });
            } else {
                self.uploadFile('sessions', subjectId, session, 'subject');
            }
        }
    },

    uploadModalities (modalities, subjectId) {
        let self = this;
        for (let modality of modalities) {
            if (modality.children && modality.children.length > 0) {
                self.createModality(subjectId, modality.name, function (err, res) {
                    self.progress();
                    let modalityId = res.body._id;
                    self.uploadAquisitions(modality.children, modalityId);
                });
            } else {
                self.uploadFile('sessions', subjectId, modality, 'session');
            }
        }
    },

    uploadAquisitions (acquisitions, modalityId) {
        for (let acquisition of acquisitions) {
            this.uploadFile('acquisitions', modalityId, acquisition, 'modality');
        }
    }

};<|endoftext|>


<commit_before>// sensors
import {AppbaseList} from './sensors/AppbaseList';
import {AppbaseSlider} from './sensors/AppbaseSlider';
import {AppbaseSearch} from './sensors/AppbaseSearch';
import {AppbaseDistanceSensor} from './sensors/AppbaseDistanceSensor';
import {AppbaseInputField} from './sensors/AppbaseInputField';
import {AppbaseButtonGroup} from './sensors/AppbaseButtonGroup';
import {AppbaseAppbaseGoogleSearch} from './sensors/AppbaseGoogleSearch';
// middleware
import {AppbaseReactiveMap} from './middleware/AppbaseReactiveMap';

module.exports = {
	AppbaseReactiveMap: AppbaseReactiveMap,
	AppbaseList: AppbaseList,
	AppbaseSlider: AppbaseSlider,
	AppbaseSearch: AppbaseSearch,
	AppbaseDistanceSensor: AppbaseDistanceSensor,
	AppbaseInputField: AppbaseInputField,
	AppbaseButtonGroup: AppbaseButtonGroup,
	AppbaseAppbaseGoogleSearch: AppbaseGoogleSearch
};
<commit_msg>Fix namespace AppbaseGoogleSearch<commit_after>// sensors
import {AppbaseList} from './sensors/AppbaseList';
import {AppbaseSlider} from './sensors/AppbaseSlider';
import {AppbaseSearch} from './sensors/AppbaseSearch';
import {AppbaseDistanceSensor} from './sensors/AppbaseDistanceSensor';
import {AppbaseInputField} from './sensors/AppbaseInputField';
import {AppbaseButtonGroup} from './sensors/AppbaseButtonGroup';
import {AppbaseGoogleSearch} from './sensors/AppbaseGoogleSearch';
// middleware
import {AppbaseReactiveMap} from './middleware/AppbaseReactiveMap';

module.exports = {
	AppbaseReactiveMap: AppbaseReactiveMap,
	AppbaseList: AppbaseList,
	AppbaseSlider: AppbaseSlider,
	AppbaseSearch: AppbaseSearch,
	AppbaseDistanceSensor: AppbaseDistanceSensor,
	AppbaseInputField: AppbaseInputField,
	AppbaseButtonGroup: AppbaseButtonGroup,
	AppbaseGoogleSearch: AppbaseGoogleSearch
};
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {

        $routeProvider.when('/', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl'
        });

        $routeProvider.when('/view1', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl'
        });

        $routeProvider.when('/view2', {
            templateUrl: 'view2/view2.html',
            controller: 'View2Ctrl'
        });

        //$routeProvider.otherwise({redirectTo: '/view1'});
}]);

var render_slides = function(callback){
    var slider = new Slider($('.slider')[0]);

    $('.image-container').on('change', function(e, value) {
        callback(value)
    })
}
<commit_msg>fix bug slider<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {

        $routeProvider.when('/', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl'
        });

        $routeProvider.when('/view1', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl'
        });

        $routeProvider.when('/view2', {
            templateUrl: 'view2/view2.html',
            controller: 'View2Ctrl'
        });

        //$routeProvider.otherwise({redirectTo: '/view1'});
}]);

var render_slides = function(callback){
    window.slider = new Slider($('.slider')[0]);

    $('.image-container').on('change', function(e, value) {
        callback(value)
    })
}
<|endoftext|>


<commit_before>angular.module('ControlPanel', [
    'ui.router',
    'ng-token-auth',
    'LocalStorageModule',
    'ui.bootstrap',
    'ui.bootstrap.showErrors',
    'validation.match',
    'datatables',
    'ngFileUpload',
    'angular.vertilize',

]);

var app = angular.module('ControlPanel');

app.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
  $stateProvider
        .state('login', {
          url: '/login?accountConfirmed',
          params: {
            passwordResetEmailSent: {
              value: false,
            },
            passwordReset: {
              value: false,
            },
            hiddenParam: 'YES',
          },
          templateUrl: 'control-panel/views/auth/login.html',
          controller: 'AuthCtrl',
          data: {
            requireLogin: false,
          },
        })
        .state('reset-password', {
          url: '/reset-password',
          templateUrl: 'control-panel/views/auth/reset-password.html',
          controller: 'AuthCtrl',
          data: {
            requireLogin: false,
          },
        })
        .state('change-password', {
          url: '/change-password',
          templateUrl: 'control-panel/views/auth/change-password.html',
          controller: 'AuthCtrl',
          data: {
            requireLogin: false,
          },
        })
        .state('dashboard', {
          templateUrl: 'control-panel/views/dashboard/common.html',
          abstract: true,
        })
        .state('dashboard.overview', {
          url: '/dashboard',
          templateUrl: 'control-panel/views/dashboard/overview.html',
          controller: 'DashboardCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.register', {
          url: '/register',
          templateUrl: 'control-panel/views/dashboard/register.html',
          controller: 'RegisterCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.profile', {
          url: '/profile',
          templateUrl: 'control-panel/views/dashboard/profile.html',
          controller: 'ProfileCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.listHubs', {
          url: '/hubs',
          templateUrl: 'control-panel/views/dashboard/listHubs.html',
          controller: 'ListHubsCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.viewHub', {
          url: '/hubs/:hubId',
          templateUrl: 'control-panel/views/dashboard/viewHub.html',
          controller: 'ViewHubCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.printer', {
          url: '/hubs/:hubId/printers/:printerId',
          templateUrl: 'control-panel/views/dashboard/printer.html',
          controller: 'PrinterCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.users', {
          url: '/users',
          templateUrl: 'control-panel/views/dashboard/users.html',
          controller: 'UsersCtrl',
          data: {
            requireLogin: true,
          },
        });

  $urlRouterProvider.otherwise('dashboard');
});

app.config(function($authProvider) {
  $authProvider.configure({
    apiUrl: 'https://dev.api.stratusprint.com/v1',
    // passwordResetSuccessUrl: 'https://dev.stratusprint.com/#/change-password',
    // confirmationSuccessUrl: 'https://dev.stratusprint.com/#/login?accountConfirmed=true',
  });
});

app.run(function($rootScope, $state, user, auth) {
  $rootScope.user = user;
  $rootScope.auth = auth;
});
<commit_msg>Remove of extra , in app.js<commit_after>angular.module('ControlPanel', [
    'ui.router',
    'ng-token-auth',
    'LocalStorageModule',
    'ui.bootstrap',
    'ui.bootstrap.showErrors',
    'validation.match',
    'datatables',
    'ngFileUpload',
    'angular.vertilize',
]);

var app = angular.module('ControlPanel');

app.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
  $stateProvider
        .state('login', {
          url: '/login?accountConfirmed',
          params: {
            passwordResetEmailSent: {
              value: false,
            },
            passwordReset: {
              value: false,
            },
            hiddenParam: 'YES',
          },
          templateUrl: 'control-panel/views/auth/login.html',
          controller: 'AuthCtrl',
          data: {
            requireLogin: false,
          },
        })
        .state('reset-password', {
          url: '/reset-password',
          templateUrl: 'control-panel/views/auth/reset-password.html',
          controller: 'AuthCtrl',
          data: {
            requireLogin: false,
          },
        })
        .state('change-password', {
          url: '/change-password',
          templateUrl: 'control-panel/views/auth/change-password.html',
          controller: 'AuthCtrl',
          data: {
            requireLogin: false,
          },
        })
        .state('dashboard', {
          templateUrl: 'control-panel/views/dashboard/common.html',
          abstract: true,
        })
        .state('dashboard.overview', {
          url: '/dashboard',
          templateUrl: 'control-panel/views/dashboard/overview.html',
          controller: 'DashboardCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.register', {
          url: '/register',
          templateUrl: 'control-panel/views/dashboard/register.html',
          controller: 'RegisterCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.profile', {
          url: '/profile',
          templateUrl: 'control-panel/views/dashboard/profile.html',
          controller: 'ProfileCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.listHubs', {
          url: '/hubs',
          templateUrl: 'control-panel/views/dashboard/listHubs.html',
          controller: 'ListHubsCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.viewHub', {
          url: '/hubs/:hubId',
          templateUrl: 'control-panel/views/dashboard/viewHub.html',
          controller: 'ViewHubCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.printer', {
          url: '/hubs/:hubId/printers/:printerId',
          templateUrl: 'control-panel/views/dashboard/printer.html',
          controller: 'PrinterCtrl',
          data: {
            requireLogin: true,
          },
        })
        .state('dashboard.users', {
          url: '/users',
          templateUrl: 'control-panel/views/dashboard/users.html',
          controller: 'UsersCtrl',
          data: {
            requireLogin: true,
          },
        });

  $urlRouterProvider.otherwise('dashboard');
});

app.config(function($authProvider) {
  $authProvider.configure({
    apiUrl: 'https://dev.api.stratusprint.com/v1',
    // passwordResetSuccessUrl: 'https://dev.stratusprint.com/#/change-password',
    // confirmationSuccessUrl: 'https://dev.stratusprint.com/#/login?accountConfirmed=true',
  });
});

app.run(function($rootScope, $state, user, auth) {
  $rootScope.user = user;
  $rootScope.auth = auth;
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mailin = require('mailin');
var fs = require('fs');
var nodemailer = require('nodemailer');
var ses = require('nodemailer-ses-transport');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/cha');

var User = require('./types/user');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log('Now connected to database');
});

var routes = require('./routes/index');
var users = require('./routes/users');

var accessKey = fs.readFileSync('/home/ubuntu/accessKey.txt').toString().trim();
var secretKey = fs.readFileSync('/home/ubuntu/secretKey.txt').toString().trim();

console.log(accessKey);
console.log(secretKey);

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport(ses({
        accessKeyId: accessKey,
        secretAccessKey: secretKey,
        region: 'us-west-2'
    })
);

// NB! No need to recreate the transporter object. You can use
// the same transporter object for all e-mails

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

mailin.start({
  port: 25,
  disableWebhook: true // Disable the webhook posting.
});

/* Access simplesmtp server instance. */
mailin.on('authorizeUser', function(connection, username, password, done) {
  /*
  if (username == "johnsmith" && password == "mysecret") {
    done(null, true);
  } else {
    done(new Error("Unauthorized!"), false);
  }
  */

  //TODO
});

/* Event emitted when a connection with the Mailin smtp server is initiated. */
mailin.on('startMessage', function (connection) {
  /* connection = {
      from: 'sender@somedomain.com',
      to: 'someaddress@yourdomain.com',
      id: 't84h5ugf',
      authentication: { username: null, authenticated: false, status: 'NORMAL' }
  }
  }; */
  console.log(connection);
});

/* Event emitted after a message was received and parsed. */
mailin.on('message', function (connection, data, content) {
  console.log(data);
  console.log(data.text.length);
  console.log(data.from[0].address);
  console.log(data.to[0].address);
  console.log(data.text);

  User.find({ internalEmail : data.to[0].address }, function(err, recipient) {
    var mailOptions;
    if(err) {
      //Send email not found error
      console.log("Error : ");
      console.log(err);
      console.log("Recipient : ");
      console.log(recipient);
      mailOptions = {
        from: 'postmaster@gocha.io',
        to: data.from[0].address,
        subject: "Address Error",
        html: "Terribly sorry, but that email doesn't exist.

Regards,
The Management"
      };
    } else if(data.text.length > 141){
      //Send email too long error
      console.log("Email length too long");
      mailOptions = {
        from: 'postmaster@gocha.io',
        to: data.from[0].address,
        subject: "Length Error",
        html: "Character count for your email was too long.  Current count is: " + data.text.length + "

Regards,
The Management"
      };
    } else {
      //Check if sender exists
      User.find({ externalEmail : data.from[0].address }, function(err, sender) {
        if(err || !sender.length){
          //User does not exist, so we need to make an email for them
          var newUser = new User({
            externalEmail: data.from[0].address
          });
          newUser.generateEmail(function(res, success){
            if(!success){
              console.log("Failed to generate email");
              //possibly send email saying all emails have been taken
            } else {
              console.log("Added new user");
              newUser.save(function(err){
                if(err) {
                  console.log("Unable to save new user");
                  throw err;
                } else {
                  console.log("New user saved");
                  //Now, we can pass along the message
                  mailOptions = {
                    from: newUser.internalEmail,
                    to: recipient.externalEmail,
                    subject: data.subject,
                    text: data.text
                  }
                }
              });
            }
          })
        } else {
          //Sender already exists, pass along the message just fine
          console.log("Sender : ");
          console.log(sender);
          console.log("Recipient : ");
        console.log(recipient);
          mailOptions = {
            from: sender[0].internalEmail,
            to: recipient[0].externalEmail,
            subject: data.subject,
            text: data.text
          };
        }
      });
    }

    //MailOptions have been set, transmit the message
    transporter.sendMail(mailOptions, function(error, info){
      if(error){
          console.log(mailOptions);
          console.log(error);
      } else {
          console.log('Message sent: ' + info.response);
      }
    });
  });
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

/*
var testUser = new User({
  externalEmail : 'vanhooser@ou.edu',
  internalEmail : 'gloriousLeader@gocha.io'
});

testUser.save(function(err){
  if(err) {
    throw err;
  } else {
    console.log("Added test user");
  }
});
*/

module.exports = app;

app.listen(80);<commit_msg>Forgot to pass back email<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mailin = require('mailin');
var fs = require('fs');
var nodemailer = require('nodemailer');
var ses = require('nodemailer-ses-transport');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/cha');

var User = require('./types/user');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log('Now connected to database');
});

var routes = require('./routes/index');
var users = require('./routes/users');

var accessKey = fs.readFileSync('/home/ubuntu/accessKey.txt').toString().trim();
var secretKey = fs.readFileSync('/home/ubuntu/secretKey.txt').toString().trim();

console.log(accessKey);
console.log(secretKey);

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport(ses({
        accessKeyId: accessKey,
        secretAccessKey: secretKey,
        region: 'us-west-2'
    })
);

// NB! No need to recreate the transporter object. You can use
// the same transporter object for all e-mails

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

mailin.start({
  port: 25,
  disableWebhook: true // Disable the webhook posting.
});

/* Access simplesmtp server instance. */
mailin.on('authorizeUser', function(connection, username, password, done) {
  /*
  if (username == "johnsmith" && password == "mysecret") {
    done(null, true);
  } else {
    done(new Error("Unauthorized!"), false);
  }
  */

  //TODO
});

/* Event emitted when a connection with the Mailin smtp server is initiated. */
mailin.on('startMessage', function (connection) {
  /* connection = {
      from: 'sender@somedomain.com',
      to: 'someaddress@yourdomain.com',
      id: 't84h5ugf',
      authentication: { username: null, authenticated: false, status: 'NORMAL' }
  }
  }; */
  console.log(connection);
});

/* Event emitted after a message was received and parsed. */
mailin.on('message', function (connection, data, content) {
  console.log(data);
  console.log(data.text.length);
  console.log(data.from[0].address);
  console.log(data.to[0].address);
  console.log(data.text);

  User.find({ internalEmail : data.to[0].address }, function(err, recipient) {
    var mailOptions;
    if(err) {
      //Send email not found error
      console.log("Error : ");
      console.log(err);
      console.log("Recipient : ");
      console.log(recipient);
      mailOptions = {
        from: 'postmaster@gocha.io',
        to: data.from[0].address,
        subject: "Address Error",
        html: "Terribly sorry, but that email doesn't exist.

Regards,
The Management"
      };
    } else if(data.text.length > 141){
      //Send email too long error
      console.log("Email length too long");
      mailOptions = {
        from: 'postmaster@gocha.io',
        to: data.from[0].address,
        subject: "Length Error",
        html: "Character count for your email was too long.  Current count is: " + data.text.length + "

Regards,
The Management"
      };
    } else {
      //Check if sender exists
      User.find({ externalEmail : data.from[0].address }, function(err, sender) {
        if(err || !sender.length){
          //User does not exist, so we need to make an email for them
          var newUser = new User({
            externalEmail: data.from[0].address
          });
          newUser.generateEmail(function(res, success){
            if(!success){
              console.log("Failed to generate email");
              //possibly send email saying all emails have been taken
            } else {
              console.log("Added new user");
              newUser.save(function(err){
                if(err) {
                  console.log("Unable to save new user");
                  throw err;
                } else {
                  console.log("New user saved");
                  //Now, we can pass along the message
                  mailOptions = {
                    from: res,
                    to: recipient.externalEmail,
                    subject: data.subject,
                    text: data.text
                  }
                }
              });
            }
          })
        } else {
          //Sender already exists, pass along the message just fine
          console.log("Sender : ");
          console.log(sender);
          console.log("Recipient : ");
        console.log(recipient);
          mailOptions = {
            from: sender[0].internalEmail,
            to: recipient[0].externalEmail,
            subject: data.subject,
            text: data.text
          };
        }
      });
    }

    //MailOptions have been set, transmit the message
    transporter.sendMail(mailOptions, function(error, info){
      if(error){
          console.log(mailOptions);
          console.log(error);
      } else {
          console.log('Message sent: ' + info.response);
      }
    });
  });
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

/*
var testUser = new User({
  externalEmail : 'vanhooser@ou.edu',
  internalEmail : 'gloriousLeader@gocha.io'
});

testUser.save(function(err){
  if(err) {
    throw err;
  } else {
    console.log("Added test user");
  }
});
*/

module.exports = app;

app.listen(80);<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');

const redis = require('redis');
const redisClient = redis.createClient();
const session = require('express-session');
const RedisStore = require('connect-redis')(session);

const logger = require('morgan');
const errorHandler = require('./lib/error_handler');

const index = require('./routes/index');
const commentsRouter = require('./routes/comments');
const coursesRouter = require('./routes/courses');
const gamesRouter = require('./routes/games');
const gameResultRouter = require('./routes/game_result');
const usersRouter = require('./routes/users');
const userStatsRouter = require('./routes/user_stats');
const friendsRouter = require('./routes/friends');

mongoose.Promise = require('bluebird');

const mongoDbOptions = {
  useMongoClient: true,
}

if (process.env.NODE_ENV === 'test')
  mongoose.connect(process.env.DB_SERVER, mongoDbOptions);

if (process.env.NODE_ENV !== 'test')
  mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/gff-dev', mongoDbOptions);

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

const sessionOptions = {
  secret: '1337',
  store: new RedisStore({
    client: redisClient,
  }),
  name: 'GolfForeFriends',
  saveUninitialized: true,
  resave: true,
  cookie: {
    maxAge: 86400 * 365
  },
};

if (app.get('env') === 'production')
  sessionOptions.cookie.secure = true;

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session(sessionOptions));
app.use(cors());

app.use(require('node-sass-middleware')({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true,
  sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/courses', coursesRouter);
app.use('/games', gamesRouter);
app.use('/games/result', gameResultRouter);
app.use('/games/comments', commentsRouter);
app.use('/users', usersRouter);
app.use('/users/stats', userStatsRouter);
app.use('/friends', friendsRouter);

app.use(function(req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(errorHandler);

module.exports = app;
<commit_msg>RedisClient uses REDIS_URL.<commit_after>'use strict';

const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');

const redis = require('redis');
// const redisClient = redis.createClient();
const redisClient = redis.createClient(process.env.REDIS_URL);
const session = require('express-session');
const RedisStore = require('connect-redis')(session);

const logger = require('morgan');
const errorHandler = require('./lib/error_handler');

const index = require('./routes/index');
const commentsRouter = require('./routes/comments');
const coursesRouter = require('./routes/courses');
const gamesRouter = require('./routes/games');
const gameResultRouter = require('./routes/game_result');
const usersRouter = require('./routes/users');
const userStatsRouter = require('./routes/user_stats');
const friendsRouter = require('./routes/friends');

mongoose.Promise = require('bluebird');

const mongoDbOptions = {
  useMongoClient: true,
}

if (process.env.NODE_ENV === 'test')
  mongoose.connect(process.env.DB_SERVER, mongoDbOptions);

if (process.env.NODE_ENV !== 'test')
  mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/gff-dev', mongoDbOptions);

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

const sessionOptions = {
  secret: '1337',
  store: new RedisStore({
    client: redisClient,
  }),
  name: 'GolfForeFriends',
  saveUninitialized: true,
  resave: true,
  cookie: {
    maxAge: 86400 * 365
  },
};

if (app.get('env') === 'production')
  sessionOptions.cookie.secure = true;

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session(sessionOptions));
app.use(cors());

app.use(require('node-sass-middleware')({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true,
  sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/courses', coursesRouter);
app.use('/games', gamesRouter);
app.use('/games/result', gameResultRouter);
app.use('/games/comments', commentsRouter);
app.use('/users', usersRouter);
app.use('/users/stats', userStatsRouter);
app.use('/friends', friendsRouter);

app.use(function(req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(errorHandler);

module.exports = app;
<|endoftext|>


<commit_before>(function() {
  var app = angular.module('notely', [
    'ui.router'
  ]);

  function config($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/notes');

    $stateProvider

      .state('notes', {
        url: '/notes',
        template: '
Notely

{{ message }}
',
        controller: function($scope) {
          $scope.message = "Welcome to Notely!";
        }
      });
  }

  config['$inject'] = ['$stateProvider', '$urlRouterProvider'];
  app.config(config);
})();
<commit_msg>Rename app variable and change inject syntax.<commit_after>(function() {
  var notelyApp = angular.module('notely', [
    'ui.router'
  ]);

  function config($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/notes');

    $stateProvider

      .state('notes', {
        url: '/notes',
        template: '
Notely

{{ message }}
',
        controller: function($scope) {
          $scope.message = "Welcome to Notely!";
        }
      });
  }

  config.$inject = ['$stateProvider', '$urlRouterProvider'];
  notelyApp.config(config);
})();
<|endoftext|>


<commit_before>angular.module('app', ['ngCookies'])
    .controller('overwatchDataController', ['$cookies', '$cookieStore', '$scope','$http', function($cookies,$cookieStore,$scope,$http) {

        $scope.playerCount = 0;

        $scope.team = {
            'players': []
        };
        $scope.savedPlayers = $cookies.getObject("savedPlayers");

        $scope.showSuggested = false;

        $scope.compositions = [];   //[arco-1341, cRc-1211, ...]
        $scope.suggestedComp;
        $scope.roles = [];          //[tank, tank, dps, ...]
        $scope.tankCount = 2;
        $scope.dpsCount = 2;
        $scope.supportCount = 2;

        $scope.loading = false;
        $scope.loadingCount = 0;
        function loadingOn() {
            $scope.loadingCount += 1;
            $scope.loading=true
            console.log($scope.loadingCount);
        }
        function loadingOff() {
            $scope.loadingCount -= 1;
            if ($scope.loadingCount==0) {
                $scope.loading=false
            }
            console.log($scope.loadingCount);
        }

        $scope.add6Players = function() {
            $scope.addPlayer("arco#1341");
            $scope.addPlayer("cRc#1211");
            $scope.addPlayer("Murdock#11667");
            $scope.addPlayer("CrotalusX#1265");
            $scope.addPlayer("Dragnier#1375");
            $scope.addPlayer("Hexcyclone#1148");
        }

        $scope.removePlayer = function(battleTag) {
            for (player in $scope.team.players) {
                if ($scope.team.players[player].battleTag==battleTag) {
                    delete $scope.team.players[player];
                    $scope.team.players = $scope.team.players.filter(function (item) { return item != undefined });
                    $scope.playerCount -= 1;
                    return;
                }
            }
        }

        $scope.addPlayer = function(battleTag) {
            loadingOn();
            // get api data
            $http({
                method: 'GET',
                url: "https://owapi.net/api/v3/u/"+battleTag.replace("#", "-")+"/heroes"
            }).then(function successCallback(response) {
                // this callback will be called asynchronously
                // when the response is available

                // error if team already has 6 players
                if ($scope.playerCount == 6) {
                    loadingOff();
                    alert("6 players already on team");
                    return;
                }
                // get hero data; error if none
                let heroes = {};
                if (response.data.eu) {
                    heroes = response.data.eu.heroes;
                } else if (response.data.kr) {
                    heroes = response.data.kr.heroes;
                } else if (response.data.us) {
                    heroes = response.data.us.heroes;
                } else {
                    loadingOff();
                    alert("no such player found ["+battleTag+"]");
                    return;
                }

                // check if player already on team
                for (player in $scope.team.players) {
                    if ($scope.team.players[player].battleTag==battleTag) {
                        loadingOff();
                        alert("player ["+battleTag+"] already on team");
                        return;
                    }
                }

                // save player for easy reuse
                if ($scope.savedPlayers == null) {
                    $scope.savedPlayers = [];
                }
                var flag = true;
                for (player in $scope.savedPlayers) {
                    if ($scope.savedPlayers[player]==battleTag) {
                        flag=false;
                    }
                }
                if (flag==true) {
                    var now = new Date(), exp = new Date(now.getFullYear()+10, now.getMonth(), now.getDate());
                    $scope.savedPlayers.push(battleTag);
                    $cookies.putObject("savedPlayers", $scope.savedPlayers, {'expires': exp});
                }

                // get all heroes (with win percentages) played more than two hours
                var heroesSortedByWin = [];
                for (hero in heroes.playtime.competitive) {
                    if (heroes.playtime.competitive[hero] >= 2) {
                        for (heroStats in heroes.stats.competitive) {
                            if (hero==heroStats) {
                                heroesSortedByWin.push({"name":hero, "win_percentage":(heroes.stats.competitive[hero].general_stats.win_percentage).slice(0,-1), "color":getColor(1-(heroes.stats.competitive[hero].general_stats.win_percentage).slice(0,-1)/100)});
                            }
                        }
                    }
                }
                // alert if player has no heroes with >= 2 hours
                if (heroesSortedByWin.length == 0) {
                    alert("player has no heros with >2 hours play time");
                }
                // sort array
                heroesSortedByWin.sort(function(a, b) {
                    return parseFloat(b.win_percentage) - parseFloat(a.win_percentage);
                });

                // get top 3
                //heroesSortedByWin = heroesSortedByWin.slice(0,3);

                // push to scope
                $scope.playerCount++;
                var player = {};
                player[battleTag]=heroesSortedByWin;
                $scope.team.players.push({name: battleTag.substring(0, battleTag.lastIndexOf("#")), battleTag:battleTag, heroes:heroesSortedByWin});
                // if 6 players on team, generate team comps
                if ($scope.playerCount == 6) {
                    $scope.genTeamComp();
                }
                loadingOff();
            }, function errorCallback(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                //FIXME: get failed error code / remove. line below is for add6 testing function
                loadingOff();
                $scope.addPlayer(battleTag);
            });

        };

        // populates scope.roles with requested role selection
        var genRolesArray = function () {
            $scope.roles = [];
            var i;
            for (i = 0; i < $scope.tankCount; i++) {
                $scope.roles.push("tank");
            }
            for (i = 0; i < $scope.dpsCount; i++) {
                $scope.roles.push("dps");
            }
            for (i = 0; i < $scope.supportCount; i++) {
                $scope.roles.push("support");
            }
        }

        var permutator = function(inputArr) {
            var results = [];
            function permute(arr, memo) {
                var cur, memo = memo || [];
                for (var i = 0; i < arr.length; i++) {
                    cur = arr.splice(i, 1);
                    if (arr.length === 0) {
                        results.push(memo.concat(cur));
                    }
                    permute(arr.slice(), memo.concat(cur));
                    arr.splice(i, 0, cur[0]);
                }
                return results;
            }
            return permute(inputArr);
        }

        var genPlayersBestHeroForRole = function (player, role, used) {
            for (hero in player.heroes) {
                let r = genRole(player.heroes[hero].name);
                if (role==r.role && used.indexOf(player.heroes[hero].name)==-1) {
                    return {name:player.heroes[hero].name, win_percentage:player.heroes[hero].win_percentage};
                }
            }
            return {name:"n/a", win_percentage:0};
        }

        //$scope.genTC = function() { genTeamComp(); }

        $scope.genTeamComp = function () {
            loadingOn();
            $scope.compositions = [];
            genRolesArray();
            let playerPermutations = permutator($scope.team.players);
            let rolePermutations = permutator($scope.roles);
            for (playerCombo in playerPermutations) {
                for (roleCombo in rolePermutations) {
                    var comp = {};
                    var used = [];
                    comp.team = [];
                    var score = 0;
                    var i;
                    for (i=0; i<6; i++) {
                        let hero = genPlayersBestHeroForRole(playerPermutations[playerCombo][i], rolePermutations[roleCombo][i], used);
                        used.push(hero.name);
                        score = parseFloat(score) + parseFloat(hero.win_percentage);
                        comp.team.push({player:playerPermutations[playerCombo][i].name, hero:hero.name});
                    }
                    comp.score = score;
                    $scope.compositions.push(comp);
                }
            }
            $scope.compositions.sort(function(a, b) {
                return parseFloat(b.score) - parseFloat(a.score);
            });
            console.log($scope.compositions[0]);
            $scope.suggestedComp = $scope.compositions[0];
            $scope.showSuggested = true;
            loadingOff();
        }

        var getColor = function (value){
            //value from 0 to 1
            var hue=((1-value)*120).toString(10);
            return ["hsl(",hue,",100%,50%)"].join("");
        }

        var genRole = function(character) {
            switch(character) {
                case "ana":
                case "lucio":
                case "mercy":
                case "symmetra":
                case "zenyatta":
                    return {"role":"support", "special":"n/a"};
                    break;
                case "genji":
                case "hanzo":
                case "reaper":
                case "tracer":
                    return {"role":"dps", "special":"flanker"};
                    break;
                case "mei":
                case "torbjorn":
                    return {"role":"dps", "special":"off-tank"};
                    break;
                case "mccree":
                case "soldier76":
                case "widowmaker":
                    return {"role":"dps", "special":"hitscan"};
                    break;
                case "junkrat":
                case "bastion":
                case "pharah":
                    return {"role":"dps", "special":"n/a"};
                    break;
                case "dva":
                case "reinhardt":
                case "roadhog":
                case "winston":
                case "zarya":
                    return {"role":"tank", "special":"n/a"};
                    break;
            }
        }

}]);
<commit_msg>api changed. accomadated.<commit_after>angular.module('app', ['ngCookies'])
    .controller('overwatchDataController', ['$cookies', '$cookieStore', '$scope','$http', function($cookies,$cookieStore,$scope,$http) {

        $scope.playerCount = 0;

        $scope.team = {
            'players': []
        };
        $scope.savedPlayers = $cookies.getObject("savedPlayers");

        $scope.showSuggested = false;

        $scope.compositions = [];   //[arco-1341, cRc-1211, ...]
        $scope.suggestedComp;
        $scope.roles = [];          //[tank, tank, dps, ...]
        $scope.tankCount = 2;
        $scope.dpsCount = 2;
        $scope.supportCount = 2;

        $scope.loading = false;
        $scope.loadingCount = 0;
        function loadingOn() {
            $scope.loadingCount += 1;
            $scope.loading=true
            console.log($scope.loadingCount);
        }
        function loadingOff() {
            $scope.loadingCount -= 1;
            if ($scope.loadingCount==0) {
                $scope.loading=false
            }
            console.log($scope.loadingCount);
        }

        $scope.add6Players = function() {
            $scope.addPlayer("arco#1341");
            $scope.addPlayer("cRc#1211");
            $scope.addPlayer("Murdock#11667");
            $scope.addPlayer("CrotalusX#1265");
            $scope.addPlayer("Dragnier#1375");
            $scope.addPlayer("Hexcyclone#1148");
        }

        $scope.removePlayer = function(battleTag) {
            for (player in $scope.team.players) {
                if ($scope.team.players[player].battleTag==battleTag) {
                    delete $scope.team.players[player];
                    $scope.team.players = $scope.team.players.filter(function (item) { return item != undefined });
                    $scope.playerCount -= 1;
                    return;
                }
            }
        }

        $scope.addPlayer = function(battleTag) {
            loadingOn();
            // get api data
            $http({
                method: 'GET',
                url: "https://owapi.net/api/v3/u/"+battleTag.replace("#", "-")+"/heroes"
            }).then(function successCallback(response) {
                // this callback will be called asynchronously
                // when the response is available

                // error if team already has 6 players
                if ($scope.playerCount == 6) {
                    loadingOff();
                    alert("6 players already on team");
                    return;
                }
                // get hero data; error if none
                let heroes = {};
                if (response.data.eu) {
                    heroes = response.data.eu.heroes;
                } else if (response.data.kr) {
                    heroes = response.data.kr.heroes;
                } else if (response.data.us) {
                    heroes = response.data.us.heroes;
                } else {
                    loadingOff();
                    alert("no such player found ["+battleTag+"]");
                    return;
                }

                // check if player already on team
                for (player in $scope.team.players) {
                    if ($scope.team.players[player].battleTag==battleTag) {
                        loadingOff();
                        alert("player ["+battleTag+"] already on team");
                        return;
                    }
                }

                // save player for easy reuse
                if ($scope.savedPlayers == null) {
                    $scope.savedPlayers = [];
                }
                var flag = true;
                for (player in $scope.savedPlayers) {
                    if ($scope.savedPlayers[player]==battleTag) {
                        flag=false;
                    }
                }
                if (flag==true) {
                    var now = new Date(), exp = new Date(now.getFullYear()+10, now.getMonth(), now.getDate());
                    $scope.savedPlayers.push(battleTag);
                    $cookies.putObject("savedPlayers", $scope.savedPlayers, {'expires': exp});
                }

                // get all heroes (with win percentages) played more than two hours
                var heroesSortedByWin = [];
                for (hero in heroes.playtime.competitive) {
                    if (heroes.playtime.competitive[hero] >= 2) {
                        for (heroStats in heroes.stats.competitive) {
                            if (hero==heroStats) {
                                console.log(heroes.stats.competitive[hero]);
                                heroesSortedByWin.push({"name":hero, "win_percentage":Math.round((heroes.stats.competitive[hero].general_stats.win_percentage*100)), "color":getColor(1-(heroes.stats.competitive[hero].general_stats.win_percentage))});
                            }
                        }
                    }
                }
                // alert if player has no heroes with >= 2 hours
                if (heroesSortedByWin.length == 0) {
                    alert("player has no heros with >2 hours play time");
                }
                // sort array
                heroesSortedByWin.sort(function(a, b) {
                    return parseFloat(b.win_percentage) - parseFloat(a.win_percentage);
                });

                // get top 3
                //heroesSortedByWin = heroesSortedByWin.slice(0,3);

                // push to scope
                $scope.playerCount++;
                var player = {};
                player[battleTag]=heroesSortedByWin;
                $scope.team.players.push({name: battleTag.substring(0, battleTag.lastIndexOf("#")), battleTag:battleTag, heroes:heroesSortedByWin});
                // if 6 players on team, generate team comps
                if ($scope.playerCount == 6) {
                    $scope.genTeamComp();
                }
                loadingOff();
            }, function errorCallback(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                //FIXME: get failed error code / remove. line below is for add6 testing function
                loadingOff();
                $scope.addPlayer(battleTag);
            });

        };

        // populates scope.roles with requested role selection
        var genRolesArray = function () {
            $scope.roles = [];
            var i;
            for (i = 0; i < $scope.tankCount; i++) {
                $scope.roles.push("tank");
            }
            for (i = 0; i < $scope.dpsCount; i++) {
                $scope.roles.push("dps");
            }
            for (i = 0; i < $scope.supportCount; i++) {
                $scope.roles.push("support");
            }
        }

        var permutator = function(inputArr) {
            var results = [];
            function permute(arr, memo) {
                var cur, memo = memo || [];
                for (var i = 0; i < arr.length; i++) {
                    cur = arr.splice(i, 1);
                    if (arr.length === 0) {
                        results.push(memo.concat(cur));
                    }
                    permute(arr.slice(), memo.concat(cur));
                    arr.splice(i, 0, cur[0]);
                }
                return results;
            }
            return permute(inputArr);
        }

        var genPlayersBestHeroForRole = function (player, role, used) {
            for (hero in player.heroes) {
                let r = genRole(player.heroes[hero].name);
                if (role==r.role && used.indexOf(player.heroes[hero].name)==-1) {
                    return {name:player.heroes[hero].name, win_percentage:player.heroes[hero].win_percentage};
                }
            }
            return {name:"n/a", win_percentage:0};
        }

        //$scope.genTC = function() { genTeamComp(); }

        $scope.genTeamComp = function () {
            loadingOn();
            $scope.compositions = [];
            genRolesArray();
            let playerPermutations = permutator($scope.team.players);
            let rolePermutations = permutator($scope.roles);
            for (playerCombo in playerPermutations) {
                for (roleCombo in rolePermutations) {
                    var comp = {};
                    var used = [];
                    comp.team = [];
                    var score = 0;
                    var i;
                    for (i=0; i<6; i++) {
                        let hero = genPlayersBestHeroForRole(playerPermutations[playerCombo][i], rolePermutations[roleCombo][i], used);
                        used.push(hero.name);
                        score = parseFloat(score) + parseFloat(hero.win_percentage);
                        comp.team.push({player:playerPermutations[playerCombo][i].name, hero:hero.name});
                    }
                    comp.score = score;
                    $scope.compositions.push(comp);
                }
            }
            $scope.compositions.sort(function(a, b) {
                return parseFloat(b.score) - parseFloat(a.score);
            });
            console.log($scope.compositions[0]);
            $scope.suggestedComp = $scope.compositions[0];
            $scope.showSuggested = true;
            loadingOff();
        }

        var getColor = function (value){
            //value from 0 to 1
            var hue=((1-value)*120).toString(10);
            return ["hsl(",hue,",100%,50%)"].join("");
        }

        var genRole = function(character) {
            switch(character) {
                case "ana":
                case "lucio":
                case "mercy":
                case "symmetra":
                case "zenyatta":
                    return {"role":"support", "special":"n/a"};
                    break;
                case "genji":
                case "hanzo":
                case "reaper":
                case "tracer":
                    return {"role":"dps", "special":"flanker"};
                    break;
                case "mei":
                case "torbjorn":
                    return {"role":"dps", "special":"off-tank"};
                    break;
                case "mccree":
                case "soldier76":
                case "widowmaker":
                    return {"role":"dps", "special":"hitscan"};
                    break;
                case "junkrat":
                case "bastion":
                case "pharah":
                    return {"role":"dps", "special":"n/a"};
                    break;
                case "dva":
                case "reinhardt":
                case "roadhog":
                case "winston":
                case "zarya":
                    return {"role":"tank", "special":"n/a"};
                    break;
            }
        }

}]);
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc overview
 * @name DoToo
 * @description
 * # DoToo is a 'To Do' app
 *
 * Main module of the application.
 */
var DoToo = angular.module('DoToo', []);
<commit_msg>make jshint happy<commit_after>'use strict';

/**
 * @ngdoc overview
 * @name DoToo
 * @description
 * # DoToo is a 'To Do' app
 *
 * Main module of the application.
 */
window.DoToo = angular.module('DoToo', []);
<|endoftext|>