<commit_before>var validateHTTP = require("./validateHTTP.js"),
    restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    uuid = require('node-uuid'),
    neo4j = require('node-neo4j'),
    Promise = require('promise');
module.exports.creategroup = function(req, res, next) {
    if((validateHTTP.validateHTTP(req, res, next, 'users')) === true) {
        db = new neo4j('http://localhost:7474');
        console.log('NEW GROUP!');
        console.log('PUT: ' + req.params.groupname)
        console.log('FOR COMPETITION: ' + req.params.competition)
        var url = 'http://localhost:5984/groups/' + req.params.groupname;
        var competition = req.params.competition
        var groupname = req.params.groupname
        var description = req.params.description
        var groupid = 0;
        var userid = 0;
        validateHTTP.validateHTTP(req, res, next, 'users')
        var topres = res
        request.get(url, function(err, response, body) {
            if(err) {
                return next(new restify.InternalServerError('Error has occured'));
            }
            // if the document isnt found it will create it from sratch
            console.log('code' + response.statusCode)
            if(response.statusCode === 200) {
                return next(new restify.ConflictError('Group Already Created'));
            } else if(response.statusCode === 404) {
                db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                    if(err) throw err;
                    if(result.data.length == 0) {
                        return next(new restify.InternalServerError('no competition found'));
                    } else {
                        var competitionid = result.data[0]._id
                        console.log('Groupname = ' + groupname)
                        db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                            if(err) throw err;
                            console.log('Group data = ' + results.data)
                            if(results.data.length == 0) {
                                db.insertNode({
                                    name: groupname,
                                    description: description
                                }, ['Group', competition], function(err, node) {
                                    if(err) throw err;
                                    // Output node properties.
                                    console.log('New neo4j node created with Groupname  = ' + node.name);
                                    groupid = node._id
                                    console.log('group id = ' + groupid)
                                    console.log('starting insert relationship')
                                    db.insertRelationship(node._id, competitionid, 'COMPETING_IN', {
                                        description: 'competiting in this competition'
                                    }, function(err, relationship) {
                                        if(err) throw err;
                                        console.log('relationship made')
                                        // Output relationship id.
                                        console.log(relationship._id);
                                        // Output relationship start_node_id.
                                        console.log(relationship._start);
                                        // Output relationship end_node_id.
                                        console.log(relationship._end);
                                        db.cypherQuery(" MATCH (n:User) WHERE n.name ='" + req.authorization.basic.username + "' RETURN n", function(err, Results) {
                                            if(err) throw err;
                                            console.log('name = ' + Results.data[0])
                                            console.log('user = ' + Results.data[0]._id)
                                            userid = Results.data[0]._id
                                            console.log('userid =' + userid)
                                            console.log(groupid)
                                            db.insertRelationship(userid, groupid, 'IN_GROUP', {
                                                description: 'Created this group'
                                            }, function(err, relationship) {
                                                if(err) throw err;
                                                console.log('relationship made')
                                                // Output relationship id.
                                                console.log(relationship._id);
                                                // Output relationship start_node_id.
                                                console.log(relationship._start);
                                                // Output relationship end_node_id.
                                                console.log(relationship._end);
                                                var d = new Date(),
                                                    date = d.toUTCString();
                                                console.log(date);
                                                var doc = {
                                                    groupname: groupname,
                                                    description: description,
                                                    date_joined: date,
                                                    last_modified: date,
                                                    createdby: req.authorization.basic.username,
                                                    grouppoints: 0,
                                                    transactions: [],
                                                    usersjoined: [req.authorization.basic.username],
                                                    competition: competition,
                                                    groupnodeid: groupid
                                                };
                                                var docStr = JSON.stringify(doc);
                                                var params = {
                                                    uri: url,
                                                    body: JSON.stringify(doc)
                                                };
                                                request.put(params, function(err, response, body) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant create document'));
                                                    }
                                                    // document has been inserted into database
                                                    body = JSON.parse(body);
                                                    console.log('about to sent res')
                                                    topres.send({
                                                        Group: req.params
                                                    });
                                                    topres.end();
                                                });
                                            });
                                        });
                                    });
                                });
                            } else {
                                console.log(result.data[0])
                                return next(new restify.ConflictError('Group already created'));
                            }
                        })
                    }
                    console.log(result.data.length); // delivers an array of query results
                });
                //
            };
        });
        // if the document is found, that means the user is already created.
    }
};
module.exports.showgroup = function(req, res, next) {
    db = new neo4j('http://localhost:7474');
    console.log('GET');
    console.log('GET: ' + req.params.groupname);
    var url = 'http://localhost:5984/groups/' + req.params.groupname;
    validateHTTP.validateHTTP(req, res, next, "users")
    var topres = res
    request.get(url, function(err, response, body) {
        if(err) {
            return next(new restify.InternalServerError('Failed To Connect To Database'));
        }
        // if the document isnt found it will create it from sratch
        console.log('code' + response.statusCode)
        if(response.statusCode === 200) {
            body = JSON.parse(body);
            //res.header('ETag', body._rev);
            res.header('Last-Modified', body.last_modified);
            res.header('Accepts', 'GET');
            group = {
                id: body._id,
                groupname: body.groupname,
                description: body.description,
                last_modified: body.last_modified,
                points: body.grouppoints,
                transactions: body.transactions,
                owner: body.createdby,
                groupmemebers: body.usersjoined
            }
            console.log(group)
            console.log("Set Group data");
            res.send(group);
            console.log("sent group data");
            res.end();
        } else if(response.statusCode === 404) {
            return next(new restify.ConflictError('Group Already Created'));
        }
    });
};
module.exports.showcompetitiongroup = function(req, res, next) {
    //match (n:freshers)-[COMPETING_IN]->r return n,r
    db = new neo4j('http://localhost:7474');
    console.log('GET');
    console.log('GET COMPETITION GROUPS: ' + req.params.competition)
    var url = 'http://localhost:5984/groups/' + req.params.groupname;
    var competition = req.params.competition
    validateHTTP.validateHTTP(req, res, next)
    var topres = res
    db.cypherQuery("match (n:" + competition + ")-[COMPETING_IN]->r return labels(n),n,r", function(err, Results) {
        if(err) throw err;
        if(Results.data == 0) {
            return next(new restify.NotFoundError('Competition not found'));
        } else {
            res.send(Results.data);
            console.log("competition data sent");
            res.end();
        }
    });
};
module.exports.joinGroup = function(req, res, next) {
    var db = new neo4j('http://localhost:7474');
    console.log('PUT');
    console.log('JOIN GROUP: ' + req.params.username + ' ' + req.params.groupname)
    var url = 'http://localhost:5984/users/' + req.authorization.basic.username;
    var groupurl = 'http://localhost:5984/groups/' + req.params.groupname;
    var userid = 0,
        groupid = 0,
        groupname = req.params.groupname,
        username = req.authorization.basic.username;
    validateHTTP.validateHTTP(req, res, next, "users");
    var topres = res
    //check user exists
    request.get(url, function(err, response, body) {
        console.log("request started")
        // if user is not found will send 404 error
        if(response.statusCode == 404) {
            return next(new restify.BadRequestError('User Not Found'))
        };
        if(response.statusCode == 200) {
            body = JSON.parse(body);
            console.log('set user id')
            userid = body.nodeid;
            //check group exists
            db.cypherQuery("match n where n.name='" + groupname + "' return n", function(err, Results) {
                if(err) throw err;
                if(Results.data == 0) {
                    return next(new restify.NotFoundError('Group not found'));
                } else {
                    groupid = Results.data[0]._id
                    console.log("Group ID set");
                    var d = new Date(),
                        date = d.toUTCString();
                    console.log(date);
                    //make relationship
                    db.insertRelationship(userid, groupid, 'IN_GROUP', {
                        datejoined: date,
                    }, function(err, relationship) {
                        if(err) throw err;
                        console.log("set user");
                        res.send("relationship created @ " + date);
                        console.log("sent data");
                        res.end();
                    });
                }
            });
        };
    });
};
// rebuilding with promises and closures
module.exports.groups = (function(req, res, next) {

    console.log("top of closure")
    console.log();
    console.log(req.params);
    console.log();
    console.log(req.body);
    console.log();
    var url = "",
        competition = "",
        groupname = "",
        description = "",
        groupid = 0,
        userid = 0,
        competitionid = "";
    return {
        createGroup: function(req, res, next) {
            console.log("group create started")
            console.log("POST "  + req.params.groupname )
            url = 'http://localhost:5984/groups/' + req.params.groupname
            var competition = req.params.competition;
            var groupname = req.params.groupname;
            var description = req.params.description;
            console.log(competition + " Group :"  + groupname + " Description: " + description)
            var groupid = 0;
            var userid = 0;
            getRequest(url).
            catch(function(err) {
                console.log("get request error")
                return next(new restify.InternalServerError('Error has occured'));
            }).then(function(call) {
                if(response.statusCode === 200) {
                    return next(new restify.ConflictError('Group Already Created'));
                }
            }).then(db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                if(err) throw err;
                if(result.data.length == 0) {
                    return next(new restify.InternalServerError('no competition found'));
                }
                return competitionid = result.data[0]._id
            })).then(function(i1d) {
                db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                    if(err) throw err;
                    if(results.data.length == 0) {
                        return results.data
                    } else {
                        console.log(result.data[0])
                        return next(new restify.ConflictError('Group already created'));
                    }
                })
            }).then(function(data) {
                db.insertNode({
                    name: groupname,
                    description: description
                }, ['Group', competition], function(err, node) {
                    if(err) throw err;
                    // Output node properties.
                    console.log('New neo4j node created with Groupname  = ' + node.name);
                    groupid = node._id
                    console.log('group id = ' + groupid)
                    return node._id
                });
            }).then(function(nodeid) {
                db.insertRelationship(node._id, competitionid, 'COMPETING_IN', {
                    description: 'competiting in this competition'
                }, function(err, relationship) {
                    if(err) throw err;
                    console.log('relationship made')
                    // Output relationship id.
                    console.log(relationship._id);
                    // Output relationship start_node_id.
                    console.log(relationship._start);
                    // Output relationship end_node_id.
                    console.log(relationship._end);
                })
            }).then(function() {
                db.cypherQuery(" MATCH (n:User) WHERE n.name ='" + req.authorization.basic.username + "' RETURN n", function(err, Results) {
                    if(err) throw err;
                    console.log('name = ' + Results.data[0])
                    console.log('user = ' + Results.data[0]._id)
                    userid = Results.data[0]._id
                    console.log('userid =' + userid)
                    console.log(groupid)
                    return userid
                })
            }).then(function(id) {
                db.insertRelationship(userid, groupid, 'IN_GROUP', {
                    description: 'Created this group'
                }, function(err, relationship) {
                    if(err) throw err;
                    console.log('relationship made')
                    // Output relationship id.
                    console.log(relationship._id);
                    // Output relationship start_node_id.
                    console.log(relationship._start);
                    // Output relationship end_node_id.
                    console.log(relationship._end);
                })
            }).then(function() {
                var d = new Date(),
                    date = d.toUTCString();
                console.log(date);
                var doc = {
                    groupname: groupname,
                    description: description,
                    date_joined: date,
                    last_modified: date,
                    createdby: req.authorization.basic.username,
                    grouppoints: 0,
                    transactions: [],
                    usersjoined: [req.authorization.basic.username],
                    competition: competition,
                    groupnodeid: groupid
                };
                var docStr = JSON.stringify(doc);
                var params = {
                    uri: url,
                    body: JSON.stringify(doc)
                };
                return params
            }).then(function(params) {
                request.put(params, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant create document'));
                    }
                    // document has been inserted into database
                    body = JSON.parse(body);
                    console.log('about to sent res')
                    res.send({
                        Group: req.params
                    });
                    res.end();
                });
            })
        },
        getRequest: function(url) {
            // set up initial get request.
            return new Promise(function(resolve, reject) {
                request.get(url, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        putRequest: function(params) {
            return new Promise(function(resolve, reject) {
                request.put(params, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        nodequery: function(query) {
            return new Promise(function(resolve, reject) {})
        }
    }
})();
module.exports.delgroup = function(req, res, next) {
    // check group exists
    // check owner is correct
    // delete relationships
    // delete couchdb
    //
    // send back success.
}<commit_msg>more group req debug<commit_after>var validateHTTP = require("./validateHTTP.js"),
    restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    uuid = require('node-uuid'),
    neo4j = require('node-neo4j'),
    Promise = require('promise');
module.exports.creategroup = function(req, res, next) {
    if((validateHTTP.validateHTTP(req, res, next, 'users')) === true) {
        db = new neo4j('http://localhost:7474');
        console.log('NEW GROUP!');
        console.log('PUT: ' + req.params.groupname)
        console.log('FOR COMPETITION: ' + req.params.competition)
        var url = 'http://localhost:5984/groups/' + req.params.groupname;
        var competition = req.params.competition
        var groupname = req.params.groupname
        var description = req.params.description
        var groupid = 0;
        var userid = 0;
        validateHTTP.validateHTTP(req, res, next, 'users')
        var topres = res
        request.get(url, function(err, response, body) {
            if(err) {
                return next(new restify.InternalServerError('Error has occured'));
            }
            // if the document isnt found it will create it from sratch
            console.log('code' + response.statusCode)
            if(response.statusCode === 200) {
                return next(new restify.ConflictError('Group Already Created'));
            } else if(response.statusCode === 404) {
                db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                    if(err) throw err;
                    if(result.data.length == 0) {
                        return next(new restify.InternalServerError('no competition found'));
                    } else {
                        var competitionid = result.data[0]._id
                        console.log('Groupname = ' + groupname)
                        db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                            if(err) throw err;
                            console.log('Group data = ' + results.data)
                            if(results.data.length == 0) {
                                db.insertNode({
                                    name: groupname,
                                    description: description
                                }, ['Group', competition], function(err, node) {
                                    if(err) throw err;
                                    // Output node properties.
                                    console.log('New neo4j node created with Groupname  = ' + node.name);
                                    groupid = node._id
                                    console.log('group id = ' + groupid)
                                    console.log('starting insert relationship')
                                    db.insertRelationship(node._id, competitionid, 'COMPETING_IN', {
                                        description: 'competiting in this competition'
                                    }, function(err, relationship) {
                                        if(err) throw err;
                                        console.log('relationship made')
                                        // Output relationship id.
                                        console.log(relationship._id);
                                        // Output relationship start_node_id.
                                        console.log(relationship._start);
                                        // Output relationship end_node_id.
                                        console.log(relationship._end);
                                        db.cypherQuery(" MATCH (n:User) WHERE n.name ='" + req.authorization.basic.username + "' RETURN n", function(err, Results) {
                                            if(err) throw err;
                                            console.log('name = ' + Results.data[0])
                                            console.log('user = ' + Results.data[0]._id)
                                            userid = Results.data[0]._id
                                            console.log('userid =' + userid)
                                            console.log(groupid)
                                            db.insertRelationship(userid, groupid, 'IN_GROUP', {
                                                description: 'Created this group'
                                            }, function(err, relationship) {
                                                if(err) throw err;
                                                console.log('relationship made')
                                                // Output relationship id.
                                                console.log(relationship._id);
                                                // Output relationship start_node_id.
                                                console.log(relationship._start);
                                                // Output relationship end_node_id.
                                                console.log(relationship._end);
                                                var d = new Date(),
                                                    date = d.toUTCString();
                                                console.log(date);
                                                var doc = {
                                                    groupname: groupname,
                                                    description: description,
                                                    date_joined: date,
                                                    last_modified: date,
                                                    createdby: req.authorization.basic.username,
                                                    grouppoints: 0,
                                                    transactions: [],
                                                    usersjoined: [req.authorization.basic.username],
                                                    competition: competition,
                                                    groupnodeid: groupid
                                                };
                                                var docStr = JSON.stringify(doc);
                                                var params = {
                                                    uri: url,
                                                    body: JSON.stringify(doc)
                                                };
                                                request.put(params, function(err, response, body) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant create document'));
                                                    }
                                                    // document has been inserted into database
                                                    body = JSON.parse(body);
                                                    console.log('about to sent res')
                                                    topres.send({
                                                        Group: req.params
                                                    });
                                                    topres.end();
                                                });
                                            });
                                        });
                                    });
                                });
                            } else {
                                console.log(result.data[0])
                                return next(new restify.ConflictError('Group already created'));
                            }
                        })
                    }
                    console.log(result.data.length); // delivers an array of query results
                });
                //
            };
        });
        // if the document is found, that means the user is already created.
    }
};
module.exports.showgroup = function(req, res, next) {
    db = new neo4j('http://localhost:7474');
    console.log('GET');
    console.log('GET: ' + req.params.groupname);
    var url = 'http://localhost:5984/groups/' + req.params.groupname;
    validateHTTP.validateHTTP(req, res, next, "users")
    var topres = res
    request.get(url, function(err, response, body) {
        if(err) {
            return next(new restify.InternalServerError('Failed To Connect To Database'));
        }
        // if the document isnt found it will create it from sratch
        console.log('code' + response.statusCode)
        if(response.statusCode === 200) {
            body = JSON.parse(body);
            //res.header('ETag', body._rev);
            res.header('Last-Modified', body.last_modified);
            res.header('Accepts', 'GET');
            group = {
                id: body._id,
                groupname: body.groupname,
                description: body.description,
                last_modified: body.last_modified,
                points: body.grouppoints,
                transactions: body.transactions,
                owner: body.createdby,
                groupmemebers: body.usersjoined
            }
            console.log(group)
            console.log("Set Group data");
            res.send(group);
            console.log("sent group data");
            res.end();
        } else if(response.statusCode === 404) {
            return next(new restify.ConflictError('Group Already Created'));
        }
    });
};
module.exports.showcompetitiongroup = function(req, res, next) {
    //match (n:freshers)-[COMPETING_IN]->r return n,r
    db = new neo4j('http://localhost:7474');
    console.log('GET');
    console.log('GET COMPETITION GROUPS: ' + req.params.competition)
    var url = 'http://localhost:5984/groups/' + req.params.groupname;
    var competition = req.params.competition
    validateHTTP.validateHTTP(req, res, next)
    var topres = res
    db.cypherQuery("match (n:" + competition + ")-[COMPETING_IN]->r return labels(n),n,r", function(err, Results) {
        if(err) throw err;
        if(Results.data == 0) {
            return next(new restify.NotFoundError('Competition not found'));
        } else {
            res.send(Results.data);
            console.log("competition data sent");
            res.end();
        }
    });
};
module.exports.joinGroup = function(req, res, next) {
    var db = new neo4j('http://localhost:7474');
    console.log('PUT');
    console.log('JOIN GROUP: ' + req.params.username + ' ' + req.params.groupname)
    var url = 'http://localhost:5984/users/' + req.authorization.basic.username;
    var groupurl = 'http://localhost:5984/groups/' + req.params.groupname;
    var userid = 0,
        groupid = 0,
        groupname = req.params.groupname,
        username = req.authorization.basic.username;
    validateHTTP.validateHTTP(req, res, next, "users");
    var topres = res
    //check user exists
    request.get(url, function(err, response, body) {
        console.log("request started")
        // if user is not found will send 404 error
        if(response.statusCode == 404) {
            return next(new restify.BadRequestError('User Not Found'))
        };
        if(response.statusCode == 200) {
            body = JSON.parse(body);
            console.log('set user id')
            userid = body.nodeid;
            //check group exists
            db.cypherQuery("match n where n.name='" + groupname + "' return n", function(err, Results) {
                if(err) throw err;
                if(Results.data == 0) {
                    return next(new restify.NotFoundError('Group not found'));
                } else {
                    groupid = Results.data[0]._id
                    console.log("Group ID set");
                    var d = new Date(),
                        date = d.toUTCString();
                    console.log(date);
                    //make relationship
                    db.insertRelationship(userid, groupid, 'IN_GROUP', {
                        datejoined: date,
                    }, function(err, relationship) {
                        if(err) throw err;
                        console.log("set user");
                        res.send("relationship created @ " + date);
                        console.log("sent data");
                        res.end();
                    });
                }
            });
        };
    });
};
// rebuilding with promises and closures
module.exports.groups = (function() {
    var url = "",
        competition = "",
        groupname = "",
        description = "",
        groupid = 0,
        userid = 0,
        competitionid = "";
    return {
        createGroup: function(req, res, next) {
            console.log(req.params)
            console.log("group create started")
            console.log("POST "  + req.params.groupname )
            url = 'http://localhost:5984/groups/' + req.params.groupname
            var competition = req.params.competition;
            var groupname = req.params.groupname;
            var description = req.params.description;
            console.log(competition + " Group :"  + groupname + " Description: " + description)
            var groupid = 0;
            var userid = 0;
            getRequest(url).
            catch(function(err) {
                console.log("get request error")
                return next(new restify.InternalServerError('Error has occured'));
            }).then(function(call) {
                if(response.statusCode === 200) {
                    return next(new restify.ConflictError('Group Already Created'));
                }
            }).then(db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                if(err) throw err;
                if(result.data.length == 0) {
                    return next(new restify.InternalServerError('no competition found'));
                }
                return competitionid = result.data[0]._id
            })).then(function(i1d) {
                db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                    if(err) throw err;
                    if(results.data.length == 0) {
                        return results.data
                    } else {
                        console.log(result.data[0])
                        return next(new restify.ConflictError('Group already created'));
                    }
                })
            }).then(function(data) {
                db.insertNode({
                    name: groupname,
                    description: description
                }, ['Group', competition], function(err, node) {
                    if(err) throw err;
                    // Output node properties.
                    console.log('New neo4j node created with Groupname  = ' + node.name);
                    groupid = node._id
                    console.log('group id = ' + groupid)
                    return node._id
                });
            }).then(function(nodeid) {
                db.insertRelationship(node._id, competitionid, 'COMPETING_IN', {
                    description: 'competiting in this competition'
                }, function(err, relationship) {
                    if(err) throw err;
                    console.log('relationship made')
                    // Output relationship id.
                    console.log(relationship._id);
                    // Output relationship start_node_id.
                    console.log(relationship._start);
                    // Output relationship end_node_id.
                    console.log(relationship._end);
                })
            }).then(function() {
                db.cypherQuery(" MATCH (n:User) WHERE n.name ='" + req.authorization.basic.username + "' RETURN n", function(err, Results) {
                    if(err) throw err;
                    console.log('name = ' + Results.data[0])
                    console.log('user = ' + Results.data[0]._id)
                    userid = Results.data[0]._id
                    console.log('userid =' + userid)
                    console.log(groupid)
                    return userid
                })
            }).then(function(id) {
                db.insertRelationship(userid, groupid, 'IN_GROUP', {
                    description: 'Created this group'
                }, function(err, relationship) {
                    if(err) throw err;
                    console.log('relationship made')
                    // Output relationship id.
                    console.log(relationship._id);
                    // Output relationship start_node_id.
                    console.log(relationship._start);
                    // Output relationship end_node_id.
                    console.log(relationship._end);
                })
            }).then(function() {
                var d = new Date(),
                    date = d.toUTCString();
                console.log(date);
                var doc = {
                    groupname: groupname,
                    description: description,
                    date_joined: date,
                    last_modified: date,
                    createdby: req.authorization.basic.username,
                    grouppoints: 0,
                    transactions: [],
                    usersjoined: [req.authorization.basic.username],
                    competition: competition,
                    groupnodeid: groupid
                };
                var docStr = JSON.stringify(doc);
                var params = {
                    uri: url,
                    body: JSON.stringify(doc)
                };
                return params
            }).then(function(params) {
                request.put(params, function(err, response, body) {
                    if(err) {
                        return next(new restify.InternalServerError('Cant create document'));
                    }
                    // document has been inserted into database
                    body = JSON.parse(body);
                    console.log('about to sent res')
                    res.send({
                        Group: req.params
                    });
                    res.end();
                });
            })
        },
        getRequest: function(url) {
            // set up initial get request.
            return new Promise(function(resolve, reject) {
                request.get(url, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        putRequest: function(params) {
            return new Promise(function(resolve, reject) {
                request.put(params, function(err, response, body) {
                    if(err) reject(err);
                    // if the document isnt found it will create it from sratch
                    console.log('code' + response.statusCode)
                    resolve({
                        response: response,
                        body: body
                    })
                })
            });
        },
        nodequery: function(query) {
            return new Promise(function(resolve, reject) {})
        }
    }
})();
module.exports.delgroup = function(req, res, next) {
    // check group exists
    // check owner is correct
    // delete relationships
    // delete couchdb
    //
    // send back success.
}<|endoftext|>


<commit_before>var graphSteak=function(sampledata,flame,timestep,meatType,maxTemps){
var graph=(function(){
var setup=function(div,data,flame,timestep,meatType,maxTemps)
	{

var dy=.1;
var n = boundaries[meatType].length*2+1, // number of layers

    m = data.length; // number of samples per layer

	var getState=function(temp)
	{

		for(var i=0;i<boundaries[meatType].length;i++)
		{
			if(temp>=boundaries[meatType][i])return i;
		}
		return 6;

	};
		var dat=[]
		for(var i =0;i<data.length;i++)
		{
			var moves = [];
			for (var x = 0; x < n; x++) moves.push(0);
			var state=getState(data[i][0]);
			var offset=0;

			for(var j=0;j<data[0].length;j++)
			{

				var nextState=getState(data[i][j]);

				if(state==nextState){moves[Math.abs(offset-nextState)]+=1}
				else{

					if(Math.abs(offset-state)>Math.abs(offset-nextState)){offset=boundaries[meatType].length*2;}

					moves[Math.abs(offset-nextState)]+=1;

					state=nextState;
					}

			}

			dat.push(moves);
		}
		maxTemps=maxTemps.splice(0,maxTemps.length-2);
			var maxs = [];
			for (var x = 0; x < 7; x++) maxs.push(0);
			var state=getState(maxTemps[0]);

			for(var j=0;j<maxTemps.length;j++)
			{

				var nextState=getState(maxTemps[j]);

				if(state==nextState){maxs[nextState]+=1}
				else{

					maxs[nextState]+=1;

					state=nextState;
					}

			}

		maxs.reverse();
		console.log(maxs);

    stack = d3.layout.stack(),
    layers = stack(d3.range(n).map(function(d,i) { return bumpLayer(i,dat); })),
    yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
    yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });

var margin = {top: 50, right: 10, bottom: 100, left: 50},
    width = 960 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .domain(d3.range(m))
    .rangeRoundBands([0, width], .08);

var xscaled = d3.scale.linear()
    .domain([0,m/timestep])
    .range([width/30, width]);

var y = d3.scale.linear()
    .domain([0, yStackMax])
    .range([height, 0]);
var yscaled = d3.scale.linear()
    .domain([0, yStackMax*dy])
    .range([height,0]);

var xAxis = d3.svg.axis()
    .scale(xscaled)
    .tickSize(0)
    .tickPadding(30)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(yscaled)
    .tickSize(0)
    .tickPadding(6)
    .orient("left");
var make_y_axis=function() {
    return d3.svg.axis()
        .scale(yscaled)
        .orient("left")

}
var svg = d3.select("body").append("svg")
	.attr("class","mysteak")
	.attr("id", "mysteak")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var svg3= d3.select(".span3").append("svg")
	.attr("class","containers")
    .attr("width", width + margin.left + margin.right)
    .attr("height", 180)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + 130 + ")");
		var legend = svg3.selectAll('g')

        .data(tempScale[meatType])

        .enter()
      .append('g')
        .attr('class', 'legend')
		.style('fill', "black");

    legend.append('rect')
        .attr('x', -30)
        .attr('y', function(d, i){ return -125+i *  15;})
        .attr('width', 8)
        .attr('height', 8)

        .style('fill', function(d) { return color[meatType](d['position'])

        });

    legend.append('text')
        .attr('x', -18)
        .attr('y', function(d, i){ return (-125+i *  15+8);})
        .text(function(d){ return d['info']; });

var ttip = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

var layer = svg.selectAll(".layer")
    .data(layers)
  .enter().append("g")
    .attr("class", "layer")

    .style("fill", function(d, i) { return color[meatType](i); });

var rect = layer.selectAll("rect")
    .data(function(d) { return d; })
  .enter().append("rect")
    .attr("x", function(d) { return x(d.x); })
    .attr("y", height)
    .attr("width", x.rangeBand())
    .attr("height", 0)
	.on("mouseover", function() {
		var rects = d3.select(this);
		var loc=null;
		for(var i=n-1;i>=0;i--)
		{
			if(color[meatType](i)==rects.style("fill")){loc=i;}
		}

		var leg=d3.selectAll('.legend')[0][boundaries[meatType].length-loc];

		$(leg).css("fill","red");

	})
.on("mousemove",function(){

	var Offset = document.getElementById("graphSteak").offsetTop;
	var pos=parseInt(data[0].length-(event.pageY-Offset-margin.top)/(height/yStackMax)+1);
var line=parseInt((event.pageX-margin.left)/(x.rangeBand()+1)-5.0);
//$(d3.select('.mylabel')[0][0]).text( meatType+ " temperature is "+ data[line][pos].toFixed(2)+ "\xB0C");
	//$(d3.select('.mylabel')[0][0]).text("Steak temperature is "+ pos+ "\xB0C");
	$("line").remove();
	var myLine = d3.selectAll("svg").filter(function(d,i){return i==2;}).append("svg:line")
    .attr("x1", margin.left)
    .attr("y1", event.pageY-Offset)
    .attr("x2", width*31/30)
    .attr("y2", event.pageY-Offset)
    .style("stroke", "grey");
	var ttip=d3.select('.tooltip');
	   ttip.html(data[line][pos].toFixed(2)+ "\xB0C")
	   			.style("opacity", 1)
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY) + "px");
})

.on("mouseout", function() {
		var rects = d3.select(this);
		var loc=null;
		for(var i=n-1;i>=0;i--)
		{

			if(color[meatType](i)==rects.style("fill")){loc=i;}
		}
		var leg=d3.selectAll('.legend')[0][boundaries[meatType].length-loc];

		$(leg).css("fill","black");

	});
var imgstop = svg.selectAll("image").data(flame);
            imgstop.enter()
            .append("svg:image")
			.attr("xlink:href", function(d){return d[1]==0? "flamedown.png":"flame.png"})
			.attr("width", Math.min(x.rangeBand(),30))
            .attr("height", Math.min(x.rangeBand(),30))
			.attr("x", function(d){return (d[0]+2)*(x.rangeBand()+1)})
            .attr("y", function(d){return -Math.min(x.rangeBand(),30)+(height+Math.min(x.rangeBand(),30))*d[1]})

var linktext = svg.selectAll("g.linklabelholder").data(flame);
    linktext.enter().append("g").attr("class", "linklabelholder")
     .append("text")
     .attr("class", "linklabel")
     .attr("dx", function(d){return (d[0]+2)*(x.rangeBand()+1)})
     .attr("dy", function(d){return -Math.min(x.rangeBand(),30)/1.2+(height+2*Math.min(x.rangeBand(),30))*d[1]})
     .attr("text-anchor", "right")
		.style("font-size", "8px")
     .text(function(d) { return d[2].toFixed(0)});

rect.transition()
    .delay(function(d, i) { return i * 10; })
    .attr("y", function(d) { return y(d.y0 + d.y); })
    .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(0,0)")
    .call(yAxis);
svg.append("text")
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height+60)
    .text("Time (seconds)");
svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("x", -height/3)
    .attr("y",-30)
 	.attr("transform", "rotate(-90)")
    .text(meatType+" Thickness (cm)");

svg.append("text")
    .attr("class", "y label1")
    .attr("text-anchor", "end")
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("Side 1");
svg.append("text")
    .attr("class", "y label2")
    .attr("text-anchor", "end")
    .attr("y", 13)
    .attr("x",-height+margin.bottom/3)
    .attr("transform", "rotate(-90)")
    .text("Side 2");
var svgContainer = d3.select(".span6").append("svg")
                                   .attr("width", '50%')
                                    .attr("height", '200px')
									.append("g")
    .attr("transform", "translate(" + 20 + "," + 130 + ")");
		var legend = svgContainer.selectAll('g')

        .data(tempScale[meatType])

        .enter()
      .append('g')
        .attr('class', 'legend')
		.style('fill', "black");

    legend.append('rect')
        .attr('x', function(d,i){return i*30-20})
        .attr('y', function(d, i){ return -125;})
        .attr('width', 8)
        .attr('height', 8)

        .style('fill', function(d) { return color[meatType](d['position'])

        });

    legend.append('text')
	.data(maxs)
        .attr('x', function(d,i){return i*30-12})
        .attr('y', function(d, i){ return (-125+8);})
		.style('font-size','6pt')
        .text(function(d){ return (100*d/m).toFixed(0) +"%"; });
var texts=svgContainer.selectAll("text")
.data([0])
 .enter().append("text")
 .attr("text-anchor", "left")
    .attr("x", '-10%')
    .attr("y", -130)
.text("Final Protein State Reached");
//Draw the Rectangle
var rectangle = svgContainer.selectAll("rect")
    .data([0,0,0,0,0,0,0].concat(maxTemps.reverse()))
  .enter().append("rect")
           .attr("x", '-10%')
           .attr("y", function(d,i){return-130+ 20+i*1})
           .attr("width", '50%')
           .attr("height", '1px')
		   .style('fill', function(d,i) {
			   return color[meatType](getState(d))});
/*
 svg.append("g")
        .attr("class", "grid")
        .call(make_y_axis()
            .tickSize(-width, 0, 0)
            .tickFormat("")

        )
	*/
var timeout = setTimeout(function() {
  d3.select("input[value=\"grouped\"]").property("checked", true).each(change);
}, 2000);

function change() {
  clearTimeout(timeout);
  if (this.value === "grouped") transitionGrouped();
  else transitionStacked();
}

function transitionGrouped() {
  y.domain([0, yGroupMax]);

  rect.transition()
      .duration(500)
      .delay(function(d, i) { return i * 10; })
      .attr("x", function(d, i, j) { return x(d.x) + x.rangeBand() / n * j; })
      .attr("width", x.rangeBand() / n)
    .transition()
      .attr("y", function(d) { return y(d.y); })
      .attr("height", function(d) { return height - y(d.y); });
}

function transitionStacked() {
  y.domain([0, yStackMax]);

  rect.transition()
      .duration(500)
      .delay(function(d, i) { return i * 10; })
      .attr("y", function(d) { return y(d.y0 + d.y); })
      .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
    .transition()
      .attr("x", function(d) { return x(d.x); })
      .attr("width", x.rangeBand());
}

function bumpLayer(layer,data) {

  var a = [], i;
  for (i = 0; i < m; ++i) {

	  a[i] = 1 * data[i][layer];

  }
  return a.map(function(d, i) { return {x: i, y: Math.max(0, d)}; });
}
	}
	    return {setup: setup};
	}
	());

	$(document).ready(function(){
    $('.graph').each(function(){
        graph.setup($(this),sampledata,flame,timestep,meatType,maxTemps);});
});
}
<commit_msg>Can now have two mini graphs need to save data and add dropdown<commit_after>var graphSteak=function(sampledata,flame,timestep,meatType,maxTemps){
var graph=(function(){
var setup=function(div,data,flame,timestep,meatType,maxTemps)
	{

var dy=.1;
var n = boundaries[meatType].length*2+1, // number of layers

    m = data.length; // number of samples per layer

	var getState=function(temp)
	{

		for(var i=0;i<boundaries[meatType].length;i++)
		{
			if(temp>=boundaries[meatType][i])return i;
		}
		return 6;

	};
		var dat=[]
		for(var i =0;i<data.length;i++)
		{
			var moves = [];
			for (var x = 0; x < n; x++) moves.push(0);
			var state=getState(data[i][0]);
			var offset=0;

			for(var j=0;j<data[0].length;j++)
			{

				var nextState=getState(data[i][j]);

				if(state==nextState){moves[Math.abs(offset-nextState)]+=1}
				else{

					if(Math.abs(offset-state)>Math.abs(offset-nextState)){offset=boundaries[meatType].length*2;}

					moves[Math.abs(offset-nextState)]+=1;

					state=nextState;
					}

			}

			dat.push(moves);
		}
		maxTemps=maxTemps.splice(0,maxTemps.length-2);
			var maxs = [];
			for (var x = 0; x < 7; x++) maxs.push(0);
			var state=getState(maxTemps[0]);

			for(var j=0;j<maxTemps.length;j++)
			{

				var nextState=getState(maxTemps[j]);

				if(state==nextState){maxs[nextState]+=1}
				else{

					maxs[nextState]+=1;

					state=nextState;
					}

			}

		maxs.reverse();
		console.log(maxs);

    stack = d3.layout.stack(),
    layers = stack(d3.range(n).map(function(d,i) { return bumpLayer(i,dat); })),
    yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
    yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });

var margin = {top: 50, right: 10, bottom: 100, left: 50},
    width = 960 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .domain(d3.range(m))
    .rangeRoundBands([0, width], .08);

var xscaled = d3.scale.linear()
    .domain([0,m/timestep])
    .range([width/30, width]);

var y = d3.scale.linear()
    .domain([0, yStackMax])
    .range([height, 0]);
var yscaled = d3.scale.linear()
    .domain([0, yStackMax*dy])
    .range([height,0]);

var xAxis = d3.svg.axis()
    .scale(xscaled)
    .tickSize(0)
    .tickPadding(30)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(yscaled)
    .tickSize(0)
    .tickPadding(6)
    .orient("left");
var make_y_axis=function() {
    return d3.svg.axis()
        .scale(yscaled)
        .orient("left")

}
var svg = d3.select("body").append("svg")
	.attr("class","mysteak")
	.attr("id", "mysteak")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var svg3= d3.select(".span3").append("svg")
	.attr("class","containers")
    .attr("width", width + margin.left + margin.right)
    .attr("height", 180)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + 130 + ")");
		var legend = svg3.selectAll('g')

        .data(tempScale[meatType])

        .enter()
      .append('g')
        .attr('class', 'legend')
		.style('fill', "black");

    legend.append('rect')
        .attr('x', -30)
        .attr('y', function(d, i){ return -125+i *  15;})
        .attr('width', 8)
        .attr('height', 8)

        .style('fill', function(d) { return color[meatType](d['position'])

        });

    legend.append('text')
        .attr('x', -18)
        .attr('y', function(d, i){ return (-125+i *  15+8);})
        .text(function(d){ return d['info']; });
var drawFinished=function(myMeatType,myMaxs,myMaxTemps)
	{
		var svgContainer = d3.select(".span6").append("svg")
                                   .attr("width", '50%')
                                    .attr("height", '200px')
									.append("g")
    .attr("transform", "translate(" + 20 + "," + 130 + ")");
		var legend = svgContainer.selectAll('g')

        .data(tempScale[myMeatType])

        .enter()
      .append('g')
        .attr('class', 'legend')
		.style('fill', "black");

    legend.append('rect')
        .attr('x', function(d,i){return i*30-20})
        .attr('y', function(d, i){ return -125;})
        .attr('width', 8)
        .attr('height', 8)

        .style('fill', function(d) { return color[myMeatType](d['position'])

        });

    legend.append('text')
	.data(myMaxs)
        .attr('x', function(d,i){return i*30-12})
        .attr('y', function(d, i){ return (-125+8);})
		.style('font-size','6pt')
        .text(function(d){ return (100*d/m).toFixed(0) +"%"; });
var texts=svgContainer.selectAll("text")
.data([0])
 .enter().append("text")
 .attr("text-anchor", "left")
    .attr("x", '-10%')
    .attr("y", -130)
.text("Final Protein State Reached");
//Draw the Rectangle
var rectangle = svgContainer.selectAll("rect")
    .data([0,0,0,0,0,0,0].concat(myMaxTemps.reverse()))
  .enter().append("rect")
           .attr("x", '-10%')
           .attr("y", function(d,i){return-130+ 20+i*1})
           .attr("width", '50%')
           .attr("height", '1px')
		   .style('fill', function(d,i) {
			   return color[myMeatType](getState(d))});
	}
var ttip = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

var layer = svg.selectAll(".layer")
    .data(layers)
  .enter().append("g")
    .attr("class", "layer")

    .style("fill", function(d, i) { return color[meatType](i); });

var rect = layer.selectAll("rect")
    .data(function(d) { return d; })
  .enter().append("rect")
    .attr("x", function(d) { return x(d.x); })
    .attr("y", height)
    .attr("width", x.rangeBand())
    .attr("height", 0)
	.on("mouseover", function() {
		var rects = d3.select(this);
		var loc=null;
		for(var i=n-1;i>=0;i--)
		{
			if(color[meatType](i)==rects.style("fill")){loc=i;}
		}

		var leg=d3.selectAll('.legend')[0][boundaries[meatType].length-loc];

		$(leg).css("fill","red");

	})
.on("mousemove",function(){

	var Offset = document.getElementById("graphSteak").offsetTop;
	var pos=parseInt(data[0].length-(event.pageY-Offset-margin.top)/(height/yStackMax)+1);
var line=parseInt((event.pageX-margin.left)/(x.rangeBand()+1)-5.0);
//$(d3.select('.mylabel')[0][0]).text( meatType+ " temperature is "+ data[line][pos].toFixed(2)+ "\xB0C");
	//$(d3.select('.mylabel')[0][0]).text("Steak temperature is "+ pos+ "\xB0C");
	$("line").remove();
	var myLine = d3.selectAll("svg").filter(function(d,i){return i==2;}).append("svg:line")
    .attr("x1", margin.left)
    .attr("y1", event.pageY-Offset)
    .attr("x2", width*31/30)
    .attr("y2", event.pageY-Offset)
    .style("stroke", "grey");
	var ttip=d3.select('.tooltip');
	   ttip.html(data[line][pos].toFixed(2)+ "\xB0C")
	   			.style("opacity", 1)
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY) + "px");
})

.on("mouseout", function() {
		var rects = d3.select(this);
		var loc=null;
		for(var i=n-1;i>=0;i--)
		{

			if(color[meatType](i)==rects.style("fill")){loc=i;}
		}
		var leg=d3.selectAll('.legend')[0][boundaries[meatType].length-loc];

		$(leg).css("fill","black");

	});
var imgstop = svg.selectAll("image").data(flame);
            imgstop.enter()
            .append("svg:image")
			.attr("xlink:href", function(d){return d[1]==0? "flamedown.png":"flame.png"})
			.attr("width", Math.min(x.rangeBand(),30))
            .attr("height", Math.min(x.rangeBand(),30))
			.attr("x", function(d){return (d[0]+2)*(x.rangeBand()+1)})
            .attr("y", function(d){return -Math.min(x.rangeBand(),30)+(height+Math.min(x.rangeBand(),30))*d[1]})

var linktext = svg.selectAll("g.linklabelholder").data(flame);
    linktext.enter().append("g").attr("class", "linklabelholder")
     .append("text")
     .attr("class", "linklabel")
     .attr("dx", function(d){return (d[0]+2)*(x.rangeBand()+1)})
     .attr("dy", function(d){return -Math.min(x.rangeBand(),30)/1.2+(height+2*Math.min(x.rangeBand(),30))*d[1]})
     .attr("text-anchor", "right")
		.style("font-size", "8px")
     .text(function(d) { return d[2].toFixed(0)});

rect.transition()
    .delay(function(d, i) { return i * 10; })
    .attr("y", function(d) { return y(d.y0 + d.y); })
    .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(0,0)")
    .call(yAxis);
svg.append("text")
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height+60)
    .text("Time (seconds)");
svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("x", -height/3)
    .attr("y",-30)
 	.attr("transform", "rotate(-90)")
    .text(meatType+" Thickness (cm)");

svg.append("text")
    .attr("class", "y label1")
    .attr("text-anchor", "end")
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("Side 1");
svg.append("text")
    .attr("class", "y label2")
    .attr("text-anchor", "end")
    .attr("y", 13)
    .attr("x",-height+margin.bottom/3)
    .attr("transform", "rotate(-90)")
    .text("Side 2");
drawFinished(meatType,maxs,maxTemps);
drawFinished(meatType,maxs,maxTemps);
/*
 svg.append("g")
        .attr("class", "grid")
        .call(make_y_axis()
            .tickSize(-width, 0, 0)
            .tickFormat("")

        )
	*/
var timeout = setTimeout(function() {
  d3.select("input[value=\"grouped\"]").property("checked", true).each(change);
}, 2000);

function change() {
  clearTimeout(timeout);
  if (this.value === "grouped") transitionGrouped();
  else transitionStacked();
}

function transitionGrouped() {
  y.domain([0, yGroupMax]);

  rect.transition()
      .duration(500)
      .delay(function(d, i) { return i * 10; })
      .attr("x", function(d, i, j) { return x(d.x) + x.rangeBand() / n * j; })
      .attr("width", x.rangeBand() / n)
    .transition()
      .attr("y", function(d) { return y(d.y); })
      .attr("height", function(d) { return height - y(d.y); });
}

function transitionStacked() {
  y.domain([0, yStackMax]);

  rect.transition()
      .duration(500)
      .delay(function(d, i) { return i * 10; })
      .attr("y", function(d) { return y(d.y0 + d.y); })
      .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
    .transition()
      .attr("x", function(d) { return x(d.x); })
      .attr("width", x.rangeBand());
}

function bumpLayer(layer,data) {

  var a = [], i;
  for (i = 0; i < m; ++i) {

	  a[i] = 1 * data[i][layer];

  }
  return a.map(function(d, i) { return {x: i, y: Math.max(0, d)}; });
}

	}
	    return {setup: setup};
	}
	());

	$(document).ready(function(){
    $('.graph').each(function(){
        graph.setup($(this),sampledata,flame,timestep,meatType,maxTemps);});
});
}
<|endoftext|>


<commit_before>module.exports = {
  color: '#038505'  //GREEN
  //color: '#1657b8'  //BLUE
  //color: '#ac8601'  //ORANGE
  //color: '#980c8e'  //PURPLE
  //color: '#bf4912'    //RED
};
<commit_msg>updates color to blue<commit_after>module.exports = {
  //color: '#038505'  //GREEN
  color: '#1657b8'  //BLUE
  //color: '#ac8601'  //ORANGE
  //color: '#980c8e'  //PURPLE
  //color: '#bf4912'    //RED
};
<|endoftext|>


<commit_before>(function() {
  module('gpub.spec.processorTest');

  var sgfOne = '(;GM[1]GN[Zed];B[aa];W[bb]C[So good!];B[cc])';
  var sgfTwo = '(;GM[1]GN[Zed];B[aa];W[bb]C[Still Cool!];B[cc])';
  var sgfThree = '(;GM[1];B[aa];W[bb]C[Still Cool!];B[cc])';

  // test('Process one SGF', function() {
    // var spec =  gpub.spec.create([
      // sgfOne
    // ], {
      // bookPurpose: gpub.bookPurpose.GAME_COMMENTARY,
      // boardRegion: glift.enums.boardRegions.AUTO
    // });

    // deepEqual(spec.sgfCollection.length, 2);
    // deepEqual(spec.sgfCollection[0].alias, 'Zed:0');
  // });

  // test('Process three SGFs', function() {
    // var spec =  gpub.spec.create([
      // sgfOne,
      // sgfTwo,
      // sgfThree,
    // ], {
      // bookPurpose: gpub.bookPurpose.GAME_COMMENTARY,
      // boardRegion: glift.enums.boardRegions.AUTO
    // });

    // deepEqual(spec.sgfCollection.length, 6);
    // deepEqual(spec.sgfCollection[0].alias, 'Zed:0');
    // deepEqual(spec.sgfCollection[2].alias, 'Zed:1');
    // deepEqual(spec.sgfCollection[4].alias, 'sgf:2');
  // });

  // test('Process Two SGFs!', function() {
    // var sgfOne
    // deepEqual(1, 1, '1 should equal 1');
  // });
})();
<commit_msg>Re-enable some processor tests I missed.<commit_after>(function() {
  module('gpub.spec.processorTest');

  var sgfOne = '(;GM[1]GN[Zed];B[aa];W[bb]C[So good!];B[cc])';
  var sgfTwo = '(;GM[1]GN[Zed];B[aa];W[bb]C[Still Cool!];B[cc])';
  var sgfThree = '(;GM[1];B[aa];W[bb]C[Still Cool!];B[cc])';

  test('Process one SGF', function() {
    var spec = gpub.spec.create(new gpub.Options({
      sgfs: [sgfOne],
    }));

    var proc = gpub.spec.process(spec);

    var id = 'Zed-1'
    deepEqual(proc.rootGrouping.positions[0].id, id);
    deepEqual(proc.rootGrouping.positions[0].alias, id);
    deepEqual(proc.rootGrouping.generated[id].positions.length, 2);
    deepEqual(proc.rootGrouping.generated[id].positions[0].alias, id);
  });

  test('Process three SGFs', function() {
    var spec =  gpub.spec.create(new gpub.Options({
      sgfs: [
        sgfOne,
        sgfTwo,
        sgfThree,
      ]
    }));

    var proc = gpub.spec.process(spec);

    deepEqual(proc.rootGrouping.positions.length, 3);

    proc.rootGrouping.positions.forEach(function(p) {
      var id = p.id;
      ok(proc.rootGrouping.generated[id], 'should have generated for id: ' + id);
      var gen = proc.rootGrouping.generated[id];
      deepEqual(gen.positions.length, 2);
      for (var i = 0; i < gen.positions.length; i++) {
        var genp = gen.positions[i];
        genp.alias = gen.alias;
        genp.id = gen.alias + '-' + i;
      };
      deepEqual(gen.labels['MAINLINE'].length, 2);
      deepEqual(gen.labels['VARIATION'].length, 0);
    });
  });

})();
<|endoftext|>


<commit_before>import jwt from 'jsonwebtoken';
import moment from 'moment';
import config from '../config';
import calendarList from './calendar/list';
import calendarGet from './calendar/get';
import calendarDelta from './calendar/delta';
import contactLists from './contacts/list';

const calendarCreate = require('./calendar/create');

const calendarPatch = require('./calendar/patch');
const calendarDayBefore = require('./calendar/dayBeforeEvents');

const contactCreate = require('./contacts/create');
const calendarWatch = require('./calendar/watch');
const calendarWatchStop = require('./calendar/watch/stop');

const { sendMessage: sms } = require('./utilities/sms');
const { getSyncToken, setSyncToken } = require('./utilities/token');
const { get, upsert } = require('../data/database');

async function listEvents(options) {
  const finalOptions = Object.assign(
    {
      calendarId: 'rarebeauty@soho.sg',
    },
    options,
  );
  try {
    // console.log(`finalOptions=${JSON.stringify(finalOptions)}`);
    const events = await calendarList(finalOptions);
    return events;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function getEvent(options) {
  const finalOptions = Object.assign(
    {
      calendarId: 'rarebeauty@soho.sg',
    },
    options,
  );
  try {
    const event = await calendarGet(finalOptions);
    return event;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function listDeltaEvents(options) {
  const finalOptions = Object.assign(
    {
      calendarId: 'rarebeauty@soho.sg',
    },
    options,
  );
  try {
    const response = await calendarDelta(finalOptions);
    return response;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function createEvent(options) {
  // node index --action=calendarCreate --name=Raymond Ho --mobile=12345678 --start=20170730T1130 --duration=105 --services=ELFS,HLW
  try {
    const event = await calendarCreate(
      Object.assign({}, options, {
        calendarId: 'rarebeauty@soho.sg',
      }),
    );
    // console.log(event);
    return event;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function patchEvent(options) {
  // node index --action=calendarPatch --eventId=XXX --mobile=11111111 --services=ELFS,HLW
  try {
    const event = await calendarPatch(
      Object.assign({}, options, {
        calendarId: 'rarebeauty@soho.sg',
      }),
    );
    // console.log(event);
    return event;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function remindCustomers(options) {
  try {
    const events = await calendarDayBefore(
      Object.assign({}, options, {
        calendarId: 'rarebeauty@soho.sg',
      }),
    );
    const remindedEvents = [];
    if (events.length === 0) {
      // console.log('No reminder events found.');
    } else {
      // console.log(`Upcoming events for ${events.length}`);

      events.forEach(async event => {
        // console.log(event);
        if (
          event.extendedProperties &&
          event.extendedProperties.shared &&
          (event.extendedProperties.shared.reminded === 'false' ||
            event.extendedProperties.shared.reminded === false)
        ) {
          remindedEvents[remindedEvents.length] = event;
          try {
            const name = event.summary;
            const mobile =
              (event.extendedProperties &&
                event.extendedProperties.shared &&
                event.extendedProperties.shared.mobile) ||
              -1;
            const startDate = moment(event.start.dateTime).format('DD-MMM');
            const startTime = moment(event.start.dateTime).format('hh:mm a');
            const message = `Hi ${name},\n\nGentle reminder for your appt on ${startDate} at ${startTime}.\n\nAny cancellation/changes:\nPlease reply, 1 day prior to this appt, to REPLY_MOBILE`;

            console.error(`message=${message}`);

            await sms(Object.assign({}, options, { mobile, message }));

            await calendarPatch({
              eventId: event.id,
              calendarId: 'rarebeauty@soho.sg',
              reminded: true,
            });
          } catch (err) {
            console.error(err);
          }
        }
      });
    }
    return remindedEvents;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function listContacts() {
  try {
    const contacts = await contactLists();
    return contacts;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function createContact(options) {
  try {
    const contact = await contactCreate(options);
    // console.log(contact);
    return contact;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function watchCalendar(options) {
  const finalOptions = Object.assign({}, options, {
    calendarId: 'rarebeauty@soho.sg',
    address: 'https://rarebeauty.soho.sg/events/calendar',
    id: 'anythingintheworld',
  });
  try {
    const response = await calendarWatch(finalOptions);
    // console.log(response);
    await upsert('config:watch', {
      resourceId: response.resourceId,
    });
    return response;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function stopWatchCalendar(options) {
  const response = await get('config:watch');
  // console.log(response);
  const finalOptions = Object.assign({}, options, {
    calendarId: 'rarebeauty@soho.sg',
    resourceId: response.value.resourceId,
  });
  try {
    const watchStopResponse = await calendarWatchStop(finalOptions);
    // console.log('stopped');
    return watchStopResponse;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function generateJWT(options) {
  return jwt.sign(
    {
      data: {
        username: options.username || 'baduser',
      },
    },
    config.auth.jwt.secret,
    {
      expiresIn: '365d',
    },
  );
}

async function listCustomerAppointments(options) {
  return listEvents(
    Object.assign(
      {
        maxResults: 3,
      },
      options,
    ),
  );
}

async function remindCustomersTouchUp(options) {
  const { startDT } = options;

  const lastDayForTwoWeeksReminderStartOfDayDT = moment(startDT)
    .add(3, 'days')
    .startOf('day');

  const forTwoWeeksReminderStartOfDayDT = moment(startDT)
    .subtract(10, 'days')
    .startOf('day');

  const forTwoWeeksReminderEndOfDayDT = moment(
    forTwoWeeksReminderStartOfDayDT,
  ).endOf('day');

  const events = await listEvents(
    Object.assign(options, {
      startDT: forTwoWeeksReminderStartOfDayDT.toISOString(),
      endDT: forTwoWeeksReminderEndOfDayDT.toISOString(),
    }),
  );

  const remindedEvents = [];

  if (events.length === 0) {
    // console.log('No reminder events found.');
  } else {
    // console.log(`Upcoming events for tomorrow ${events.length}`);
    events.forEach(async event => {
      // console.log(event);
      // console.log(`services=${JSON.stringify(event.extendedProperties.shared.services, null, 2)}`);

      if (
        event.extendedProperties &&
        event.extendedProperties.shared &&
        (event.extendedProperties.shared.touchUpReminded === 'false' ||
          event.extendedProperties.shared.touchUpReminded === false ||
          event.extendedProperties.shared.touchUpReminded === undefined)
      ) {
        const services = event.extendedProperties.shared.services.split(',');

        // this is full set services which are eligible for touch up
        if (
          services.indexOf('service:1') === -1 &&
          services.indexOf('service:2') === -1
        ) {
          return;
        }

        remindedEvents[remindedEvents.length] = event;

        try {
          const name = event.summary;
          const mobile =
            (event.extendedProperties &&
              event.extendedProperties.shared &&
              event.extendedProperties.shared.mobile) ||
            -1;
          const message = `Hi ${name},\n\nGentle Reminder.\n\nIf you need lashes touch up, your last eligible day is on ${lastDayForTwoWeeksReminderStartOfDayDT.format(
            'DD-MMM-YYYY',
          )}\n\nReply to REPLY_MOBILE to reserve your slot early.`;

          console.error(`message=${message}`);

          await sms(Object.assign({}, options, { mobile, message }));

          await calendarPatch({
            eventId: event.id,
            calendarId: 'rarebeauty@soho.sg',
            touchUpReminded: true,
          });
        } catch (err) {
          console.error(err);
        }
      }
    });
  }

  return remindedEvents;
}

const functions = {
  listEvents,
  listDeltaEvents,
  createEvent,
  patchEvent,
  remindCustomers,
  listContacts,
  createContact,
  watchCalendar,
  stopWatchCalendar,
  getSyncToken,
  setSyncToken,
  getEvent,
  generateJWT,
  listCustomerAppointments,
  remindCustomersTouchUp,
};

export default functions;
<commit_msg>try it again with 14 days concept<commit_after>import jwt from 'jsonwebtoken';
import moment from 'moment';
import config from '../config';
import calendarList from './calendar/list';
import calendarGet from './calendar/get';
import calendarDelta from './calendar/delta';
import contactLists from './contacts/list';

const calendarCreate = require('./calendar/create');

const calendarPatch = require('./calendar/patch');
const calendarDayBefore = require('./calendar/dayBeforeEvents');

const contactCreate = require('./contacts/create');
const calendarWatch = require('./calendar/watch');
const calendarWatchStop = require('./calendar/watch/stop');

const { sendMessage: sms } = require('./utilities/sms');
const { getSyncToken, setSyncToken } = require('./utilities/token');
const { get, upsert } = require('../data/database');

async function listEvents(options) {
  const finalOptions = Object.assign(
    {
      calendarId: 'rarebeauty@soho.sg',
    },
    options,
  );
  try {
    // console.log(`finalOptions=${JSON.stringify(finalOptions)}`);
    const events = await calendarList(finalOptions);
    return events;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function getEvent(options) {
  const finalOptions = Object.assign(
    {
      calendarId: 'rarebeauty@soho.sg',
    },
    options,
  );
  try {
    const event = await calendarGet(finalOptions);
    return event;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function listDeltaEvents(options) {
  const finalOptions = Object.assign(
    {
      calendarId: 'rarebeauty@soho.sg',
    },
    options,
  );
  try {
    const response = await calendarDelta(finalOptions);
    return response;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function createEvent(options) {
  // node index --action=calendarCreate --name=Raymond Ho --mobile=12345678 --start=20170730T1130 --duration=105 --services=ELFS,HLW
  try {
    const event = await calendarCreate(
      Object.assign({}, options, {
        calendarId: 'rarebeauty@soho.sg',
      }),
    );
    // console.log(event);
    return event;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function patchEvent(options) {
  // node index --action=calendarPatch --eventId=XXX --mobile=11111111 --services=ELFS,HLW
  try {
    const event = await calendarPatch(
      Object.assign({}, options, {
        calendarId: 'rarebeauty@soho.sg',
      }),
    );
    // console.log(event);
    return event;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function remindCustomers(options) {
  try {
    const events = await calendarDayBefore(
      Object.assign({}, options, {
        calendarId: 'rarebeauty@soho.sg',
      }),
    );
    const remindedEvents = [];
    if (events.length === 0) {
      // console.log('No reminder events found.');
    } else {
      // console.log(`Upcoming events for ${events.length}`);

      events.forEach(async event => {
        // console.log(event);
        if (
          event.extendedProperties &&
          event.extendedProperties.shared &&
          (event.extendedProperties.shared.reminded === 'false' ||
            event.extendedProperties.shared.reminded === false)
        ) {
          remindedEvents[remindedEvents.length] = event;
          try {
            const name = event.summary;
            const mobile =
              (event.extendedProperties &&
                event.extendedProperties.shared &&
                event.extendedProperties.shared.mobile) ||
              -1;
            const startDate = moment(event.start.dateTime).format('DD-MMM');
            const startTime = moment(event.start.dateTime).format('hh:mm a');
            const message = `Hi ${name},\n\nGentle reminder for your appt on ${startDate} at ${startTime}.\n\nAny cancellation/changes:\nPlease reply, 1 day prior to this appt, to REPLY_MOBILE`;

            console.error(`message=${message}`);

            await sms(Object.assign({}, options, { mobile, message }));

            await calendarPatch({
              eventId: event.id,
              calendarId: 'rarebeauty@soho.sg',
              reminded: true,
            });
          } catch (err) {
            console.error(err);
          }
        }
      });
    }
    return remindedEvents;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function listContacts() {
  try {
    const contacts = await contactLists();
    return contacts;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function createContact(options) {
  try {
    const contact = await contactCreate(options);
    // console.log(contact);
    return contact;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function watchCalendar(options) {
  const finalOptions = Object.assign({}, options, {
    calendarId: 'rarebeauty@soho.sg',
    address: 'https://rarebeauty.soho.sg/events/calendar',
    id: 'anythingintheworld',
  });
  try {
    const response = await calendarWatch(finalOptions);
    // console.log(response);
    await upsert('config:watch', {
      resourceId: response.resourceId,
    });
    return response;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function stopWatchCalendar(options) {
  const response = await get('config:watch');
  // console.log(response);
  const finalOptions = Object.assign({}, options, {
    calendarId: 'rarebeauty@soho.sg',
    resourceId: response.value.resourceId,
  });
  try {
    const watchStopResponse = await calendarWatchStop(finalOptions);
    // console.log('stopped');
    return watchStopResponse;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

async function generateJWT(options) {
  return jwt.sign(
    {
      data: {
        username: options.username || 'baduser',
      },
    },
    config.auth.jwt.secret,
    {
      expiresIn: '365d',
    },
  );
}

async function listCustomerAppointments(options) {
  return listEvents(
    Object.assign(
      {
        maxResults: 3,
      },
      options,
    ),
  );
}

async function remindCustomersTouchUp(options) {
  const { startDT } = options;

  const lastDayForTwoWeeksReminderStartOfDayDT = moment(startDT)
    .add(3, 'days')
    .startOf('day');

  const forTwoWeeksReminderStartOfDayDT = moment(startDT)
    .subtract(10, 'days')
    .startOf('day');

  const forTwoWeeksReminderEndOfDayDT = moment(
    forTwoWeeksReminderStartOfDayDT,
  ).endOf('day');

  const events = await listEvents(
    Object.assign(options, {
      startDT: forTwoWeeksReminderStartOfDayDT.toISOString(),
      endDT: forTwoWeeksReminderEndOfDayDT.toISOString(),
    }),
  );

  const remindedEvents = [];

  if (events.length === 0) {
    // console.log('No reminder events found.');
  } else {
    // console.log(`Upcoming events for tomorrow ${events.length}`);
    events.forEach(async event => {
      // console.log(event);
      // console.log(`services=${JSON.stringify(event.extendedProperties.shared.services, null, 2)}`);

      if (
        event.extendedProperties &&
        event.extendedProperties.shared &&
        (event.extendedProperties.shared.touchUpReminded === 'false' ||
          event.extendedProperties.shared.touchUpReminded === false ||
          event.extendedProperties.shared.touchUpReminded === undefined)
      ) {
        const services = event.extendedProperties.shared.services.split(',');

        // this is full set services which are eligible for touch up
        if (
          services.indexOf('service:1') === -1 &&
          services.indexOf('service:2') === -1
        ) {
          return;
        }

        remindedEvents[remindedEvents.length] = event;

        try {
          const name = event.summary;
          const mobile =
            (event.extendedProperties &&
              event.extendedProperties.shared &&
              event.extendedProperties.shared.mobile) ||
            -1;
          const message = `Hi ${name},\n\nGentle Reminder.\n\nIf you need lashes touch up, your last eligible day is ${lastDayForTwoWeeksReminderStartOfDayDT.format(
            'DD-MMM',
          )}\n\nReply to REPLY_MOBILE to reserve your slot early.`;

          console.error(`message=${message}`);

          await sms(Object.assign({}, options, { mobile, message }));

          await calendarPatch({
            eventId: event.id,
            calendarId: 'rarebeauty@soho.sg',
            touchUpReminded: true,
          });
        } catch (err) {
          console.error(err);
        }
      }
    });
  }

  return remindedEvents;
}

const functions = {
  listEvents,
  listDeltaEvents,
  createEvent,
  patchEvent,
  remindCustomers,
  listContacts,
  createContact,
  watchCalendar,
  stopWatchCalendar,
  getSyncToken,
  setSyncToken,
  getEvent,
  generateJWT,
  listCustomerAppointments,
  remindCustomersTouchUp,
};

export default functions;
<|endoftext|>


<commit_before>const Twit = require('twit')
const config = require('../config')

const bot = new Twit(config.twitterKeys)

const quote = require('positivity-api')

const db = require('../helpers/db')

// sentiment deps
const unified = require('unified')
const sentiment = require('retext-sentiment')
const english = require('retext-english')

// event is passed in from calling bot.js function
const sentimentBot = event => {
  // console.log('====================')
  // console.log(event)
  // console.log('====================')
  const processor = unified()
    .use(english)
    .use(sentiment)
  const tree = processor.parse(event.text)

  processor.run(tree, event.text)

  console.log('====================}')
  console.log(`POLARITY=${tree.data.polarity}`)
  console.log(`VALENCE=${tree.data.valence}`)
  console.log(`TWEET TEXT=${event.text}`)
  console.log('====================')

  const polarity = tree.data.polarity
  const valence = tree.data.valence

  // Don't do anything if it's the bot tweet
  if (event.user.screen_name == '_100DaysOfCode') return

  // if polarity is negative and polarity is <= -2
  if (valence == 'negative' && polarity <= -2) {
    // get a random quote
    const phrase = quote.random()
    const screen_name = event.user.screen_name
    const tweetId = event.id_str

    // Check key isn't in db already, key being the screen_name
    db.get(screen_name, (err, value) => {
      if (value !== undefined) {
        console.log('ALREADY IN DB USER ', screen_name)
      } else {
        // Put a user name and that they have been encouraged
        db.put(screen_name, 'encourage', err => {
          // some kind of I/O error
          if (err) return console.log('Ooops!', err)

          console.log('LOGGED USER: ', screen_name)

          // tweet a random encouragement phrase
          bot.post(
            'statuses/update',
            {
              status: `@${screen_name} ${phrase}`,
              in_reply_to_status_id: tweetId
            },
            (err, data, response) => {
              if (err) {
                console.log(err)
              } else {
                console.log(`${data.text} tweeted!`)
              }
            }
          )
        })
      }
    })
  }
}

module.exports = sentimentBot
<commit_msg>update<commit_after>const Twit = require('twit')
const config = require('../config')

const bot = new Twit(config.twitterKeys)

const quote = require('positivity-api')

const db = require('../helpers/db')

// sentiment deps
const unified = require('unified')
const sentiment = require('retext-sentiment')
const english = require('retext-english')

// event is passed in from calling bot.js function
const sentimentBot = event => {
  // console.log('====================')
  // console.log(event)
  // console.log('====================')
  const processor = unified()
    .use(english)
    .use(sentiment)
  const tree = processor.parse(event.text)

  processor.run(tree, event.text)

  console.log('====================}')
  console.log(`POLARITY=${tree.data.polarity}`)
  console.log(`VALENCE=${tree.data.valence}`)
  console.log(`TWEET TEXT=${event.text}`)
  console.log('====================')

  const polarity = tree.data.polarity
  const valence = tree.data.valence

  // Don't do anything if it's the bot tweet
  if (event.user.screen_name == '_100DaysOfCode') return

  // if polarity is negative and polarity is <= -2
  if (valence == 'negative' && polarity <= -2) {
    // get a random quote
    const phrase = quote.random()
    const screen_name = event.user.screen_name
    const tweetId = event.id_str

    // Check key isn't in db already, key being the screen_name
    db.get(screen_name, (err, value) => {
      if (typeof value !== 'undefined') {
        console.log('ALREADY IN DB USER ', screen_name)
      } else {
        // Put a user name and that they have been encouraged
        db.put(screen_name, 'encourage', err => {
          // some kind of I/O error
          if (err) return console.log('Ooops!', err)

          console.log('LOGGED USER: ', screen_name)

          // tweet a random encouragement phrase
          bot.post(
            'statuses/update',
            {
              status: `@${screen_name} ${phrase}`,
              in_reply_to_status_id: tweetId
            },
            (err, data, response) => {
              if (err) {
                console.log(err)
              } else {
                console.log(`${data.text} tweeted!`)
              }
            }
          )
        })
      }
    })
  }
}

module.exports = sentimentBot
<|endoftext|>